diff --git a/github_code/affaan-m__ECC/scripts/hooks/observe-runner.js b/github_code/affaan-m__ECC/scripts/hooks/observe-runner.js new file mode 100644 index 0000000000000000000000000000000000000000..c046d75f0dd11e3b6039e296eeace1ba24366cc7 --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/hooks/observe-runner.js @@ -0,0 +1,199 @@ +#!/usr/bin/env node +'use strict'; + +const fs = require('fs'); +const path = require('path'); +const { spawnSync } = require('child_process'); + +const OBSERVE_RELATIVE_PATH = path.join('skills', 'continuous-learning-v2', 'hooks', 'observe.sh'); +const DEFAULT_TIMEOUT_MS = 9000; + +function getPluginRoot(options = {}) { + if (options.pluginRoot && String(options.pluginRoot).trim()) { + return String(options.pluginRoot).trim(); + } + if (process.env.CLAUDE_PLUGIN_ROOT && process.env.CLAUDE_PLUGIN_ROOT.trim()) { + return process.env.CLAUDE_PLUGIN_ROOT.trim(); + } + if (process.env.ECC_PLUGIN_ROOT && process.env.ECC_PLUGIN_ROOT.trim()) { + return process.env.ECC_PLUGIN_ROOT.trim(); + } + return path.resolve(__dirname, '..', '..'); +} + +function resolveTarget(rootDir, relPath) { + const resolvedRoot = path.resolve(rootDir); + const resolvedTarget = path.resolve(rootDir, relPath); + if ( + resolvedTarget !== resolvedRoot && + !resolvedTarget.startsWith(resolvedRoot + path.sep) + ) { + throw new Error(`Path traversal rejected: ${relPath}`); + } + return resolvedTarget; +} + +function toShellPath(filePath) { + const normalized = String(filePath || ''); + if (process.platform !== 'win32') { + return normalized; + } + + return normalized + .replace(/^([A-Za-z]):[\\/]/, (_, driveLetter) => `/${driveLetter.toLowerCase()}/`) + .replace(/\\/g, '/'); +} + +function findShellBinary() { + const candidates = []; + if (process.env.BASH && process.env.BASH.trim()) { + candidates.push(process.env.BASH.trim()); + } + + if (process.platform === 'win32') { + candidates.push('bash.exe', 'bash', 'sh'); + } else { + candidates.push('bash', 'sh'); + } + + for (const candidate of candidates) { + const probe = spawnSync(candidate, ['-c', ':'], { + stdio: 'ignore', + windowsHide: true + }); + // Require the probe to actually succeed, not just spawn: Windows' + // System32\bash.exe (WSL launcher) spawns even with no distro installed but + // exits non-zero, so `!probe.error` alone would treat it as a usable shell. + if (!probe.error && probe.status === 0) { + return candidate; + } + } + + return null; +} + +function getPhaseFromHookId(hookId) { + const prefix = String(hookId || process.env.ECC_HOOK_ID || '').split(':')[0]; + return prefix === 'pre' || prefix === 'post' ? prefix : null; +} + +function getTimeoutMs() { + const parsed = Number.parseInt(process.env.ECC_OBSERVE_RUNNER_TIMEOUT_MS || '', 10); + return Number.isFinite(parsed) && parsed > 0 ? parsed : DEFAULT_TIMEOUT_MS; +} + +function combineStderr(stderr, message) { + const prefix = typeof stderr === 'string' && stderr.length > 0 + ? stderr.endsWith('\n') ? stderr : `${stderr}\n` + : ''; + return `${prefix}${message}\n`; +} + +function run(raw, options = {}) { + const input = typeof raw === 'string' ? raw : String(raw ?? ''); + const phase = getPhaseFromHookId(options.hookId); + if (!phase) { + return { + stderr: '[Hook] observe runner received an unsupported hook id; skipping observation', + exitCode: 0 + }; + } + + const pluginRoot = getPluginRoot(options); + let observePath; + try { + observePath = resolveTarget(pluginRoot, OBSERVE_RELATIVE_PATH); + } catch (error) { + return { + stderr: `[Hook] observe runner path resolution failed: ${error.message}`, + exitCode: 0 + }; + } + + if (!fs.existsSync(observePath)) { + return { + stderr: `[Hook] observe script not found: ${observePath}`, + exitCode: 0 + }; + } + + const shell = findShellBinary(); + if (!shell) { + return { + stderr: '[Hook] shell runtime unavailable; skipping continuous-learning observation', + exitCode: 0 + }; + } + + const result = spawnSync(shell, [toShellPath(observePath), phase], { + input, + encoding: 'utf8', + env: { + ...process.env, + CLAUDE_PLUGIN_ROOT: pluginRoot, + ECC_PLUGIN_ROOT: pluginRoot + }, + cwd: process.cwd(), + timeout: getTimeoutMs(), + windowsHide: true + }); + + const output = { + exitCode: Number.isInteger(result.status) ? result.status : 0 + }; + + if (typeof result.stdout === 'string' && result.stdout.length > 0) { + output.stdout = result.stdout; + } + if (typeof result.stderr === 'string' && result.stderr.length > 0) { + output.stderr = result.stderr; + } + + if (result.error || result.signal || result.status === null) { + const reason = result.error + ? result.error.message + : result.signal + ? `terminated by signal ${result.signal}` + : 'missing exit status'; + output.stderr = combineStderr(output.stderr, `[Hook] observe runner failed: ${reason}`); + output.exitCode = 0; + } + + return output; +} + +function emitHookResult(raw, output) { + if (output && typeof output === 'object') { + if (output.stderr) { + process.stderr.write(String(output.stderr).endsWith('\n') ? String(output.stderr) : `${output.stderr}\n`); + } + if (Object.prototype.hasOwnProperty.call(output, 'stdout')) { + process.stdout.write(String(output.stdout ?? '')); + } else if (!Number.isInteger(output.exitCode) || output.exitCode === 0) { + process.stdout.write(raw); + } + return Number.isInteger(output.exitCode) ? output.exitCode : 0; + } + + process.stdout.write(raw); + return 0; +} + +if (require.main === module) { + let raw = ''; + try { + raw = fs.readFileSync(0, 'utf8'); + } catch (_error) { + raw = ''; + } + const output = run(raw, { hookId: process.argv[2] || process.env.ECC_HOOK_ID }); + process.exit(emitHookResult(raw, output)); +} + +module.exports = { + OBSERVE_RELATIVE_PATH, + findShellBinary, + getPhaseFromHookId, + run, + toShellPath +}; diff --git a/github_code/affaan-m__ECC/scripts/hooks/plan-canvas-pending.js b/github_code/affaan-m__ECC/scripts/hooks/plan-canvas-pending.js new file mode 100644 index 0000000000000000000000000000000000000000..9ba2a92072a9fb8031eb581c50ba64b70ebe7c6e --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/hooks/plan-canvas-pending.js @@ -0,0 +1,226 @@ +#!/usr/bin/env node +/** + * Plan Canvas undelivered-feedback guard (Stop) + * + * Cross-platform (Windows, macOS, Linux) + * + * Browser feedback only reaches an agent while that agent is parked inside + * `ecc-plan-canvas await`. The moment a turn ends, nothing is listening, so + * messages the human sends land in sessions.json and stay there: the canvas + * looks alive, the agent never hears a word. + * + * This hook closes that gap. On Stop it drains any undelivered feedback for + * the current project and blocks the stop, handing the messages to the agent + * as its next input, so a canvas message is delivered even when no `await` + * was running. + * + * Scope: sessions whose artifact lives under the hook's cwd, so parallel + * agents in other repos cannot swallow a message meant for this one. Set + * ECC_PLAN_CANVAS_STOP_SCOPE=all to consider every open session. + * + * Never blocks on failure: any error, unreachable server, or undrainable + * queue exits 0 with stdin passed through. + */ + +'use strict'; + +const fs = require('fs'); +const http = require('http'); +const os = require('os'); +const path = require('path'); + +// Loopback only, and short: a Stop hook must not stall the turn if the canvas +// server is wedged. Falling back to the state file keeps delivery working. +const SERVER_TIMEOUT_MS = 1000; +const MAX_ITEMS_REPORTED = 20; + +function stateDir() { + const override = process.env.ECC_PLAN_CANVAS_STATE_DIR; + if (override && override.trim()) return path.resolve(override.trim()); + return path.join(os.homedir(), '.claude', 'plan-canvas'); +} + +function readState() { + try { + const parsed = JSON.parse(fs.readFileSync(path.join(stateDir(), 'sessions.json'), 'utf8')); + return parsed && typeof parsed === 'object' && parsed.sessions ? parsed : null; + } catch { + return null; + } +} + +function readServerPort() { + try { + const info = JSON.parse(fs.readFileSync(path.join(stateDir(), 'server.json'), 'utf8')); + return Number.isInteger(info.port) ? info.port : null; + } catch { + return null; + } +} + +function isInside(dir, file) { + if (!dir) return true; + const base = path.resolve(dir); + const target = path.resolve(file); + return target === base || target.startsWith(base + path.sep); +} + +/** + * Sessions holding feedback the agent has never seen, oldest activity first. + */ +function pendingSessions(state, cwd, env = process.env) { + const scopeAll = String(env.ECC_PLAN_CANVAS_STOP_SCOPE || '').trim().toLowerCase() === 'all'; + return Object.values((state && state.sessions) || {}) + .filter(session => session && session.status !== 'ended') + .filter(session => Array.isArray(session.pendingFeedback) && session.pendingFeedback.length > 0) + .filter(session => (scopeAll ? true : isInside(cwd, session.file))) + .sort((a, b) => String(a.updatedAt || '').localeCompare(String(b.updatedAt || ''))); +} + +/** + * Ask the running server to hand over the batch. The server owns sessions.json + * while it is up, so this is the only race-free way to drain. timeoutMs=0 + * makes /api/await return immediately instead of long polling. + */ +function drainViaServer(port, key) { + return new Promise(resolve => { + const req = http.request( + { + host: '127.0.0.1', + port, + method: 'GET', + path: `/api/await?key=${encodeURIComponent(key)}&timeoutMs=0`, + agent: false + }, + res => { + let data = ''; + res.on('data', chunk => { + data += chunk; + }); + res.on('end', () => { + try { + const parsed = JSON.parse(data.trim() || '{}'); + resolve(parsed.status === 'feedback' && Array.isArray(parsed.items) ? parsed : null); + } catch { + resolve(null); + } + }); + } + ); + req.setTimeout(SERVER_TIMEOUT_MS, () => { + req.destroy(); + resolve(null); + }); + req.on('error', () => resolve(null)); + req.end(); + }); +} + +/** + * Drain straight from disk. Only safe when no server is listening, which is + * exactly when this path runs: with the server down nothing else mutates the + * file, and leaving the items queued would re-block on every future Stop. + */ +function drainViaFile(key) { + const file = path.join(stateDir(), 'sessions.json'); + try { + const state = JSON.parse(fs.readFileSync(file, 'utf8')); + const session = state.sessions && state.sessions[key]; + if (!session || !Array.isArray(session.pendingFeedback) || session.pendingFeedback.length === 0) { + return null; + } + const items = session.pendingFeedback; + const sessionEnded = session.status === 'ended'; + session.pendingFeedback = []; + if (!sessionEnded) session.status = 'open'; + session.updatedAt = new Date().toISOString(); + const tmp = `${file}.tmp`; + fs.writeFileSync(tmp, JSON.stringify(state, null, 2)); + fs.renameSync(tmp, file); + return { status: 'feedback', items, sessionEnded }; + } catch { + return null; + } +} + +function describeItem(item) { + if (!item || typeof item !== 'object') return null; + if (item.kind === 'verdict') { + const label = item.verdict === 'approve' ? 'APPROVED the plan' : 'REQUESTED CHANGES'; + return item.text ? `${label}: ${item.text}` : label; + } + if (item.kind === 'annotation') { + const anchor = item.anchor || {}; + const where = anchor.snippet || anchor.selector || 'the artifact'; + return item.text ? `on "${where}": ${item.text}` : null; + } + return item.text || null; +} + +function buildReason(delivered) { + const lines = [ + 'Plan Canvas: the human sent feedback in the browser that was never delivered to you.', + 'Handle it now instead of ending the turn.', + '' + ]; + for (const entry of delivered) { + lines.push(`Artifact: ${entry.file}`); + for (const text of entry.messages.slice(0, MAX_ITEMS_REPORTED)) lines.push(` - ${text}`); + const extra = entry.messages.length - MAX_ITEMS_REPORTED; + if (extra > 0) lines.push(` - (+${extra} more)`); + if (entry.sessionEnded) { + lines.push(' The user ended this review after sending. Address the feedback and report back in'); + lines.push(' your normal reply; do not reopen the canvas.'); + } else { + lines.push(' Reply IN THE CANVAS so the human sees it, and keep listening, with one command:'); + lines.push(` ecc-plan-canvas await ${JSON.stringify(entry.file)} --reply ""`); + } + lines.push(''); + } + lines.push('Run that await in the background so the next message reaches you without another Stop.'); + return lines.join('\n'); +} + +async function collectDeliveries(sessions, port) { + const delivered = []; + for (const session of sessions) { + const result = port ? await drainViaServer(port, session.key) : drainViaFile(session.key); + // A failed drain is deliberately not reported: blocking on feedback that + // is still queued would re-fire on every subsequent Stop. + if (!result) continue; + const messages = result.items.map(describeItem).filter(Boolean); + if (messages.length === 0) continue; + delivered.push({ file: session.file, messages, sessionEnded: Boolean(result.sessionEnded) }); + } + return delivered; +} + +async function run(rawInput) { + const passThrough = { stdout: rawInput || '', exitCode: 0 }; + let payload = {}; + try { + payload = JSON.parse(rawInput || '{}'); + } catch { + return passThrough; + } + + // The harness sets this once it has already resumed the agent from a Stop + // hook. Blocking again from here is how a hook wedges a session. + if (payload.stop_hook_active) return passThrough; + + const state = readState(); + if (!state) return passThrough; + + const sessions = pendingSessions(state, payload.cwd || process.cwd()); + if (sessions.length === 0) return passThrough; + + const delivered = await collectDeliveries(sessions, readServerPort()); + if (delivered.length === 0) return passThrough; + + return { + stdout: JSON.stringify({ decision: 'block', reason: buildReason(delivered) }), + exitCode: 0 + }; +} + +module.exports = { run, pendingSessions, describeItem, buildReason, drainViaFile }; diff --git a/github_code/affaan-m__ECC/scripts/hooks/plan-canvas-sessions.js b/github_code/affaan-m__ECC/scripts/hooks/plan-canvas-sessions.js new file mode 100644 index 0000000000000000000000000000000000000000..4e0799f870b6924ec69c10bfd82cf3298b4e84bc --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/hooks/plan-canvas-sessions.js @@ -0,0 +1,68 @@ +#!/usr/bin/env node +/** + * Plan Canvas open-session surfacing (SessionStart) + * + * Cross-platform (Windows, macOS, Linux) + * + * If a Plan Canvas review is still open from a previous agent session, + * surface it at session start so a fresh session can resume the loop with + * `plan-canvas await ` instead of leaving the human talking to an + * empty chair in the browser. + * + * Never blocks: exits 0 on every error, prints nothing when there is + * nothing to resume. + */ + +'use strict'; + +const fs = require('fs'); +const path = require('path'); +const os = require('os'); + +function stateDir() { + const override = process.env.ECC_PLAN_CANVAS_STATE_DIR; + if (override && override.trim()) return path.resolve(override.trim()); + return path.join(os.homedir(), '.claude', 'plan-canvas'); +} + +function openSessions() { + try { + const parsed = JSON.parse(fs.readFileSync(path.join(stateDir(), 'sessions.json'), 'utf8')); + return Object.values(parsed.sessions || {}).filter(session => session.status !== 'ended'); + } catch { + return []; + } +} + +function buildContext(sessions) { + const lines = [ + '[PlanCanvas] Open browser review sessions from a previous run:' + ]; + for (const session of sessions.slice(0, 5)) { + const pending = session.pendingFeedback && session.pendingFeedback.length; + lines.push(` - ${session.file}${pending ? ` (${pending} undelivered feedback item${pending === 1 ? '' : 's'})` : ''}`); + } + lines.push( + 'Resume with `node scripts/plan-canvas.js await ` (plan-canvas skill), or `end ` if the review is obsolete.' + ); + return lines.join('\n'); +} + +function run() { + const sessions = openSessions(); + if (sessions.length > 0) { + process.stdout.write(`${buildContext(sessions)}\n`); + } + return 0; +} + +if (require.main === module) { + try { + process.exit(run()); + } catch (error) { + process.stderr.write(`[PlanCanvas] WARNING: ${error.message}\n`); + process.exit(0); + } +} + +module.exports = { run, openSessions, buildContext }; diff --git a/github_code/affaan-m__ECC/scripts/hooks/plugin-hook-bootstrap.js b/github_code/affaan-m__ECC/scripts/hooks/plugin-hook-bootstrap.js new file mode 100644 index 0000000000000000000000000000000000000000..8d573ffedaa0f55de122a704737d3db0aa23f68d --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/hooks/plugin-hook-bootstrap.js @@ -0,0 +1,328 @@ +#!/usr/bin/env node +'use strict'; + +const fs = require('fs'); +const path = require('path'); +const { spawnSync } = require('child_process'); +const { ensureAgentDataHomeEnv } = require('../lib/agent-data-home'); + +const SHELL_PROBE_TIMEOUT_MS = 2000; + +function readStdinRaw() { + try { + return fs.readFileSync(0, 'utf8'); + } catch (_error) { + return ''; + } +} + +function writeStderr(stderr) { + if ((typeof stderr === 'string' || Buffer.isBuffer(stderr)) && stderr.length > 0) { + process.stderr.write(stderr); + } +} + +function toBuffer(value) { + if (Buffer.isBuffer(value)) return value; + return typeof value === 'string' ? Buffer.from(value, 'utf8') : Buffer.alloc(0); +} + +function withComparisonInput(result, comparisonInput) { + return { ...result, comparisonInput }; +} + +function isRawPassthrough(raw, stdout) { + const rawBytes = toBuffer(raw); + const stdoutBytes = toBuffer(stdout); + if (rawBytes.length === 0 || stdoutBytes.length === 0) return false; + return ( + stdoutBytes.length <= rawBytes.length && + rawBytes.subarray(0, stdoutBytes.length).equals(stdoutBytes) + ); +} + +function passthrough(result) { + const stdout = + typeof result?.stdout === 'string' || Buffer.isBuffer(result?.stdout) + ? result.stdout + : Buffer.alloc(0); + if (stdout.length > 0) { + // Most ECC hook scripts follow a `run(rawInput) -> rawInput` passthrough + // pattern: they do their work, then return the original input so the hook + // chain's tool result is preserved. The harness then writes the verbatim + // raw input (tool_input + tool_response, often 1-275 KB) into the session + // transcript as a hook_success attachment -- ~89% of every ECC session's + // transcript is this bloat. Detect the passthrough and emit empty stdout + // instead; the harness falls back to the tool_use's original result, the + // same path #2240 established for bash-hook-dispatcher. + // + // IMPORTANT: a strict `stdout === raw` check misses child processes whose + // synchronous `process.stdout.write()` is truncated before exit. Pipe + // capacity varies by platform and Node version (observed at 8, 16, and + // 64 KiB), so classify any non-empty byte-exact prefix of the raw hook + // event as passthrough instead of assuming one buffer size. + const raw = result?.comparisonInput; + const looksLikePassthrough = isRawPassthrough(raw, stdout); + if (looksLikePassthrough) { + writeStderr( + '[Hook] bootstrap: hook returned raw input as stdout; emitting empty to avoid transcript bloat\n' + ); + return; + } + process.stdout.write(stdout); + return; + } + + if (!Number.isInteger(result?.status) || result.status === 0) { + writeStderr('[Hook] bootstrap: hook produced no output; emitting empty stdout\n'); + } +} + +function normalizePluginRootForPlatform(rootDir, platform = process.platform) { + if (platform !== 'win32' || typeof rootDir !== 'string') { + return rootDir; + } + + const match = rootDir.match(/^\/([a-zA-Z])(?:\/(.*))?$/); + if (!match) { + return rootDir; + } + + const [, driveLetter, rest = ''] = match; + return `${driveLetter.toUpperCase()}:/${rest}`; +} + +function resolveTarget(rootDir, relPath) { + const resolvedRoot = path.resolve(rootDir); + const resolvedTarget = path.resolve(rootDir, relPath); + if ( + resolvedTarget !== resolvedRoot && + !resolvedTarget.startsWith(resolvedRoot + path.sep) + ) { + throw new Error(`Path traversal rejected: ${relPath}`); + } + return resolvedTarget; +} + +let _cachedShell = undefined; +let _cachedBash = undefined; + +function isPowerShellBin(bin) { + const base = path.basename(bin).toLowerCase(); + return base === 'pwsh.exe' || base === 'pwsh' || base === 'powershell.exe' || base === 'powershell'; +} + +function findShellBinary() { + if (_cachedShell !== undefined) return _cachedShell; + + const candidates = []; + + // Explicit override always wins — check before any platform probing. + // Warning: setting BASH to a bash binary on Windows bypasses the PowerShell + // preference and may reintroduce bash.exe zombie accumulation. + if (process.env.BASH && process.env.BASH.trim()) { + candidates.push(process.env.BASH.trim()); + } + + if (process.platform === 'win32') { + // Prefer PowerShell on Windows — it is native and does not leave zombie + // bash.exe / conhost.exe processes the way MSYS2/Git Bash does. + // Note: PowerShell is only suitable for .ps1 scripts; callers that need + // to run .sh scripts (e.g. observe-runner.js) must not use this function. + candidates.push('pwsh.exe', 'powershell.exe', 'bash.exe', 'bash'); + } else { + candidates.push('bash', 'sh'); + } + + const psProbeArgs = ['-NoProfile', '-NonInteractive', '-Command', 'exit 0']; + const shProbeArgs = ['-c', ':']; + + for (const candidate of candidates) { + const probe = spawnSync(candidate, isPowerShellBin(candidate) ? psProbeArgs : shProbeArgs, { + stdio: 'ignore', + windowsHide: true, + timeout: SHELL_PROBE_TIMEOUT_MS, + }); + // A candidate is only usable if it both spawns AND exits cleanly. The + // Windows System32 bash.exe WSL launcher spawns without error but exits + // non-zero when no distro is installed, so !probe.error alone is not enough. + if (!probe.error && probe.status === 0) { + _cachedShell = candidate; + return _cachedShell; + } + } + + _cachedShell = null; + return null; +} + +function findBashBinary() { + if (_cachedBash !== undefined) return _cachedBash; + + const candidates = []; + if (process.env.BASH && process.env.BASH.trim() && !isPowerShellBin(process.env.BASH.trim())) { + candidates.push(process.env.BASH.trim()); + } + candidates.push('bash.exe', 'bash'); + + for (const candidate of candidates) { + const probe = spawnSync(candidate, ['-c', ':'], { + stdio: 'ignore', + windowsHide: true, + timeout: SHELL_PROBE_TIMEOUT_MS, + }); + // Require a clean exit, not just a successful spawn: the Windows System32 + // bash.exe WSL stub spawns fine but exits non-zero with no distro installed. + if (!probe.error && probe.status === 0) { + _cachedBash = candidate; + return _cachedBash; + } + } + + _cachedBash = null; + return null; +} + +function spawnNode(rootDir, relPath, raw, args) { + ensureAgentDataHomeEnv(); + const hookEnv = { + ...process.env, + CLAUDE_PLUGIN_ROOT: rootDir, + ECC_PLUGIN_ROOT: rootDir, + }; + const result = spawnSync(process.execPath, [resolveTarget(rootDir, relPath), ...args], { + input: raw, + env: hookEnv, + cwd: process.cwd(), + timeout: 30000, + windowsHide: true, + }); + return withComparisonInput(result, Buffer.from(raw, 'utf8')); +} + +// spawnShell is not used by any hook in the shipped hooks.json configuration +// (all hooks use 'node' mode). It is provided for third-party plugins that +// register shell-backed hooks. Plugins should supply .ps1 scripts on Windows +// and .sh scripts on Unix; mixing them will produce a skip with a stderr warning. +function spawnShell(rootDir, relPath, raw, args) { + const shell = findShellBinary(); + if (!shell) { + return { + status: 0, + stdout: '', + stderr: '[Hook] shell runtime unavailable; skipping shell-backed hook\n', + }; + } + + ensureAgentDataHomeEnv(); + const hookEnv = { + ...process.env, + CLAUDE_PLUGIN_ROOT: rootDir, + ECC_PLUGIN_ROOT: rootDir, + }; + const scriptPath = resolveTarget(rootDir, relPath); + const isPs = isPowerShellBin(shell); + + // PowerShell cannot interpret bash scripts — fall back to a bash candidate + // rather than silently failing the hook. + if (isPs && scriptPath.endsWith('.sh')) { + const bash = findBashBinary(); + if (!bash) { + return { + status: 0, + stdout: '', + stderr: '[Hook] .sh script requested but no bash binary found on Windows; skipping\n', + }; + } + const bashResult = spawnSync(bash, [scriptPath, ...args], { + input: raw, + env: hookEnv, + cwd: process.cwd(), + timeout: 30000, + windowsHide: true, + }); + return withComparisonInput(bashResult, Buffer.from(raw, 'utf8')); + } + + const shellArgs = isPs + // -ExecutionPolicy Bypass: default Windows policy (Restricted) blocks -File + // execution of .ps1 scripts; Bypass scopes only to this child process. + ? ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-File', scriptPath, ...args] + : [scriptPath, ...args]; + + const result = spawnSync(shell, shellArgs, { + input: raw, + env: hookEnv, + cwd: process.cwd(), + timeout: 30000, + windowsHide: true, + }); + return withComparisonInput(result, Buffer.from(raw, 'utf8')); +} + +function main() { + const [, , mode, relPath, ...args] = process.argv; + const raw = readStdinRaw(); + const rootDir = normalizePluginRootForPlatform( + process.env.CLAUDE_PLUGIN_ROOT || process.env.ECC_PLUGIN_ROOT + ); + + if (!mode || !relPath || !rootDir) { + writeStderr( + '[Hook] bootstrap: missing required args (mode/relPath/rootDir); emitting empty stdout\n' + ); + process.exitCode = 0; + return; + } + + let result; + try { + if (mode === 'node') { + result = spawnNode(rootDir, relPath, raw, args); + } else if (mode === 'shell') { + result = spawnShell(rootDir, relPath, raw, args); + } else { + writeStderr(`[Hook] unknown bootstrap mode: ${mode}; emitting empty stdout\n`); + process.exitCode = 0; + return; + } + } catch (error) { + writeStderr(`[Hook] bootstrap resolution failed: ${error.message}; emitting empty stdout\n`); + process.exitCode = 0; + return; + } + + passthrough(result); + writeStderr(result.stderr); + + if (result.error || result.signal || result.status === null) { + const reason = result.error + ? result.error.message + : result.signal + ? `terminated by signal ${result.signal}` + : 'missing exit status'; + writeStderr(`[Hook] bootstrap execution failed: ${reason}\n`); + process.exitCode = 0; + return; + } + + process.exitCode = Number.isInteger(result.status) ? result.status : 0; +} + +// Run when invoked as a hook entry. Production hooks load this via +// `node -e "...; process.argv.splice(1,0,s); require(s)"`; on Node 21+ that +// leaves require.main undefined (not this module), which previously skipped +// main() and made every plugin hook a silent no-op. Guard on both the +// direct-entry case and that eval-bootstrap case. When imported for its +// exports (tests), require.main is a real, different module, so main() stays +// dormant. +if (require.main === module || require.main === undefined) { + main(); +} + +module.exports = { + isRawPassthrough, + main, + normalizePluginRootForPlatform, + withComparisonInput, +}; diff --git a/github_code/affaan-m__ECC/scripts/hooks/post-bash-build-complete.js b/github_code/affaan-m__ECC/scripts/hooks/post-bash-build-complete.js new file mode 100644 index 0000000000000000000000000000000000000000..b7a8275ce8e6dff8c2b1dc5363591e0d66b5a073 --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/hooks/post-bash-build-complete.js @@ -0,0 +1,49 @@ +#!/usr/bin/env node +'use strict'; + +const MAX_STDIN = 1024 * 1024; +let raw = ''; + +function run(rawInput) { + try { + const input = typeof rawInput === 'string' ? JSON.parse(rawInput) : rawInput; + const cmd = String(input.tool_input?.command || ''); + if (/(npm run build|pnpm build|yarn build)/.test(cmd)) { + return { + stdout: typeof rawInput === 'string' ? rawInput : JSON.stringify(rawInput), + stderr: '[Hook] Build completed - async analysis running in background', + exitCode: 0, + }; + } + } catch { + // ignore parse errors and pass through + } + + return typeof rawInput === 'string' ? rawInput : JSON.stringify(rawInput); +} + +if (require.main === module) { + process.stdin.setEncoding('utf8'); + process.stdin.on('data', chunk => { + if (raw.length < MAX_STDIN) { + const remaining = MAX_STDIN - raw.length; + raw += chunk.substring(0, remaining); + } + }); + + process.stdin.on('end', () => { + const result = run(raw); + if (result && typeof result === 'object') { + if (result.stderr) { + process.stderr.write(`${result.stderr}\n`); + } + process.stdout.write(String(result.stdout || '')); + process.exitCode = Number.isInteger(result.exitCode) ? result.exitCode : 0; + return; + } + + process.stdout.write(String(result)); + }); +} + +module.exports = { run }; diff --git a/github_code/affaan-m__ECC/scripts/hooks/post-bash-command-log.js b/github_code/affaan-m__ECC/scripts/hooks/post-bash-command-log.js new file mode 100644 index 0000000000000000000000000000000000000000..bdea239dfdf3f3deb23600a142e3003117e9c4de --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/hooks/post-bash-command-log.js @@ -0,0 +1,80 @@ +#!/usr/bin/env node +'use strict'; + +const fs = require('fs'); +const os = require('os'); +const path = require('path'); + +const MAX_STDIN = 1024 * 1024; +let raw = ''; + +const MODE_CONFIG = { + audit: { + fileName: 'bash-commands.log', + format: command => `[${new Date().toISOString()}] ${command}`, + }, + cost: { + fileName: 'cost-tracker.log', + format: command => `[${new Date().toISOString()}] tool=Bash command=${command}`, + }, +}; + +function sanitizeCommand(command) { + return String(command || '') + .replace(/\n/g, ' ') + .replace(/--token[= ][^ ]*/g, '--token=') + .replace(/Authorization:[: ]*[^ ]*[: ]*[^ ]*/gi, 'Authorization:') + .replace(/\bAKIA[A-Z0-9]{16}\b/g, '') + .replace(/\bASIA[A-Z0-9]{16}\b/g, '') + .replace(/password[= ][^ ]*/gi, 'password=') + .replace(/\bghp_[A-Za-z0-9_]+\b/g, '') + .replace(/\bgho_[A-Za-z0-9_]+\b/g, '') + .replace(/\bghs_[A-Za-z0-9_]+\b/g, '') + .replace(/\bgithub_pat_[A-Za-z0-9_]+\b/g, ''); +} + +function appendLine(filePath, line) { + fs.mkdirSync(path.dirname(filePath), { recursive: true }); + fs.appendFileSync(filePath, `${line}\n`, 'utf8'); +} + +function run(rawInput, mode = 'audit') { + const config = MODE_CONFIG[mode]; + + try { + if (config) { + const input = String(rawInput || '').trim() ? JSON.parse(String(rawInput)) : {}; + const command = sanitizeCommand(input.tool_input?.command || '?'); + appendLine(path.join(os.homedir(), '.claude', config.fileName), config.format(command)); + } + } catch { + // Logging must never block the calling hook. + } + + return typeof rawInput === 'string' ? rawInput : JSON.stringify(rawInput); +} + +function main() { + const mode = process.argv[2]; + + process.stdin.setEncoding('utf8'); + process.stdin.on('data', chunk => { + if (raw.length < MAX_STDIN) { + const remaining = MAX_STDIN - raw.length; + raw += chunk.substring(0, remaining); + } + }); + + process.stdin.on('end', () => { + process.stdout.write(run(raw, mode)); + }); +} + +if (require.main === module) { + main(); +} + +module.exports = { + run, + sanitizeCommand, +}; diff --git a/github_code/affaan-m__ECC/scripts/hooks/post-bash-dispatcher.js b/github_code/affaan-m__ECC/scripts/hooks/post-bash-dispatcher.js new file mode 100644 index 0000000000000000000000000000000000000000..43ec128c58b829ed52d36aa70889fe60a5b9dde3 --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/hooks/post-bash-dispatcher.js @@ -0,0 +1,24 @@ +#!/usr/bin/env node +'use strict'; + +const { runPostBash } = require('./bash-hook-dispatcher'); + +let raw = ''; +const MAX_STDIN = 1024 * 1024; + +process.stdin.setEncoding('utf8'); +process.stdin.on('data', chunk => { + if (raw.length < MAX_STDIN) { + const remaining = MAX_STDIN - raw.length; + raw += chunk.substring(0, remaining); + } +}); + +process.stdin.on('end', () => { + const result = runPostBash(raw); + if (result.stderr) { + process.stderr.write(result.stderr); + } + process.stdout.write(result.output); + process.exitCode = result.exitCode; +}); diff --git a/github_code/affaan-m__ECC/scripts/hooks/post-bash-pr-created.js b/github_code/affaan-m__ECC/scripts/hooks/post-bash-pr-created.js new file mode 100644 index 0000000000000000000000000000000000000000..b18dad53933fb9c71c090e80e3dbe5102a9b05d5 --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/hooks/post-bash-pr-created.js @@ -0,0 +1,60 @@ +#!/usr/bin/env node +'use strict'; + +const MAX_STDIN = 1024 * 1024; +let raw = ''; + +function run(rawInput) { + try { + const input = typeof rawInput === 'string' ? JSON.parse(rawInput) : rawInput; + const cmd = String(input.tool_input?.command || ''); + + if (/\bgh\s+pr\s+create\b/.test(cmd)) { + const out = String(input.tool_output?.output || ''); + const match = out.match(/https:\/\/github\.com\/[^/]+\/[^/]+\/pull\/\d+/); + if (match) { + const prUrl = match[0]; + const repo = prUrl.replace(/https:\/\/github\.com\/([^/]+\/[^/]+)\/pull\/\d+/, '$1'); + const prNum = prUrl.replace(/.+\/pull\/(\d+)/, '$1'); + return { + stdout: typeof rawInput === 'string' ? rawInput : JSON.stringify(rawInput), + stderr: [ + `[Hook] PR created: ${prUrl}`, + `[Hook] To review: gh pr review ${prNum} --repo ${repo}`, + ].join('\n'), + exitCode: 0, + }; + } + } + } catch { + // ignore parse errors and pass through + } + + return typeof rawInput === 'string' ? rawInput : JSON.stringify(rawInput); +} + +if (require.main === module) { + process.stdin.setEncoding('utf8'); + process.stdin.on('data', chunk => { + if (raw.length < MAX_STDIN) { + const remaining = MAX_STDIN - raw.length; + raw += chunk.substring(0, remaining); + } + }); + + process.stdin.on('end', () => { + const result = run(raw); + if (result && typeof result === 'object') { + if (result.stderr) { + process.stderr.write(`${result.stderr}\n`); + } + process.stdout.write(String(result.stdout || '')); + process.exit(Number.isInteger(result.exitCode) ? result.exitCode : 0); + return; + } + + process.stdout.write(String(result)); + }); +} + +module.exports = { run }; diff --git a/github_code/affaan-m__ECC/scripts/hooks/post-edit-accumulator.js b/github_code/affaan-m__ECC/scripts/hooks/post-edit-accumulator.js new file mode 100644 index 0000000000000000000000000000000000000000..c626b2dd80a57f4beb4b296d450da670d7f74346 --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/hooks/post-edit-accumulator.js @@ -0,0 +1,78 @@ +#!/usr/bin/env node +/** + * PostToolUse Hook: Accumulate edited JS/TS file paths for batch processing + * + * Cross-platform (Windows, macOS, Linux) + * + * Records each edited JS/TS path to a session-scoped temp file (one path per + * line). stop-format-typecheck.js reads this list at Stop time and runs format + * + typecheck once across all edited files, eliminating per-edit latency. + * + * appendFileSync is used so concurrent hook processes write atomically + * without overwriting each other. Deduplication is deferred to the Stop hook. + */ + +'use strict'; + +const crypto = require('crypto'); +const fs = require('fs'); +const os = require('os'); +const path = require('path'); + +const MAX_STDIN = 1024 * 1024; + +function getAccumFile() { + const raw = + process.env.CLAUDE_SESSION_ID || + crypto.createHash('sha1').update(process.cwd()).digest('hex').slice(0, 12); + // Strip path separators and traversal sequences so the value is safe to embed + // directly in a filename regardless of what CLAUDE_SESSION_ID contains. + const sessionId = raw.replace(/[^a-zA-Z0-9_-]/g, '_').slice(0, 64); + return path.join(os.tmpdir(), `ecc-edited-${sessionId}.txt`); +} + +/** + * @param {string} rawInput - Raw JSON string from stdin + * @returns {string} The original input (pass-through) + */ +const JS_TS_EXT = /\.(ts|tsx|js|jsx)$/; + +function appendPath(filePath) { + if (filePath && JS_TS_EXT.test(filePath)) { + fs.appendFileSync(getAccumFile(), filePath + '\n', 'utf8'); + } +} + +/** + * @param {string} rawInput - Raw JSON string from stdin + * @returns {string} The original input (pass-through) + */ +function run(rawInput) { + try { + const input = JSON.parse(rawInput); + // Edit / Write: single file_path + appendPath(input.tool_input?.file_path); + // MultiEdit: array of edits, each with its own file_path + const edits = input.tool_input?.edits; + if (Array.isArray(edits)) { + for (const edit of edits) appendPath(edit?.file_path); + } + } catch { + // Invalid input — pass through + } + return rawInput; +} + +if (require.main === module) { + let data = ''; + process.stdin.setEncoding('utf8'); + process.stdin.on('data', chunk => { + if (data.length < MAX_STDIN) data += chunk.substring(0, MAX_STDIN - data.length); + }); + process.stdin.on('end', () => { + process.stdout.write(run(data)); + process.exit(0); + }); +} + +module.exports = { run }; diff --git a/github_code/affaan-m__ECC/scripts/hooks/post-edit-console-warn.js b/github_code/affaan-m__ECC/scripts/hooks/post-edit-console-warn.js new file mode 100644 index 0000000000000000000000000000000000000000..f2ce096c291fbdccea66e89798c85c0b2a0c71af --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/hooks/post-edit-console-warn.js @@ -0,0 +1,75 @@ +#!/usr/bin/env node +/** + * PostToolUse Hook: Warn about console.log statements after edits + * + * Cross-platform (Windows, macOS, Linux) + * + * Runs after Edit tool use. If the edited JS/TS file contains console.log + * statements, warns with line numbers to help remove debug statements + * before committing. + */ + +const { readFile } = require('../lib/utils'); + +const MAX_DIRECT_STDIN_BYTES = 16 * 1024 * 1024; +function run(data) { + const warnings = []; + try { + const input = JSON.parse(data); + const filePath = input.tool_input?.file_path; + + if (filePath && /\.(ts|tsx|js|jsx)$/.test(filePath)) { + const content = readFile(filePath); + if (content) { + const matches = content + .split('\n') + .map((line, index) => ({ line, index })) + .filter(item => /console\.log/.test(item.line)) + .map(item => `${item.index + 1}: ${item.line.trim()}`); + + if (matches.length > 0) { + warnings.push(`[Hook] WARNING: console.log found in ${filePath}`); + warnings.push(...matches.slice(0, 5)); + warnings.push('[Hook] Remove console.log before committing'); + } + } + } + } catch { + // Invalid input — pass through + } + + return { + stdout: data, + stderr: warnings.join('\n'), + exitCode: 0, + }; +} + +if (require.main === module) { + let data = ''; + let stdinBytes = 0; + let oversized = false; + process.stdin.setEncoding('utf8'); + process.stdin.on('data', chunk => { + if (oversized) return; + stdinBytes += Buffer.byteLength(chunk, 'utf8'); + if (stdinBytes > MAX_DIRECT_STDIN_BYTES) { + data = ''; + oversized = true; + return; + } + data += chunk; + }); + process.stdin.on('end', () => { + if (oversized) { + process.exitCode = 0; + return; + } + const result = run(data); + if (result.stderr) process.stderr.write(`${result.stderr}\n`); + process.stdout.write(result.stdout); + process.exitCode = result.exitCode; + }); +} + +module.exports = { run }; diff --git a/github_code/affaan-m__ECC/scripts/hooks/post-edit-format.js b/github_code/affaan-m__ECC/scripts/hooks/post-edit-format.js new file mode 100644 index 0000000000000000000000000000000000000000..d79409841d6be6408c9b6c11e5c71a00a0665f7c --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/hooks/post-edit-format.js @@ -0,0 +1,118 @@ +#!/usr/bin/env node +/** + * PostToolUse Hook: Auto-format JS/TS files after edits + * + * Cross-platform (Windows, macOS, Linux) + * + * Runs after Edit tool use. If the edited file is a JS/TS file, + * auto-detects the project formatter (Biome or Prettier) by looking + * for config files, then formats accordingly. + * + * For Biome, uses `check --write` (format + lint in one pass) to + * avoid a redundant second invocation from quality-gate.js. + * + * Prefers the local node_modules/.bin binary over npx to skip + * package-resolution overhead (~200-500ms savings per invocation). + * + * Fails silently if no formatter is found or installed. + */ + +const { execFileSync, spawnSync } = require('child_process'); +const path = require('path'); + +// Shell metacharacters that cmd.exe interprets as command separators/operators +const UNSAFE_PATH_CHARS = /[&|<>^%!;`()$]/; + +const { findProjectRoot, detectFormatter, resolveFormatterBin } = require('../lib/resolve-formatter'); + +const MAX_DIRECT_STDIN_BYTES = 16 * 1024 * 1024; + +/** + * Core logic — exported so run-with-flags.js can call directly + * without spawning a child process. + * + * @param {string} rawInput - Raw JSON string from stdin + * @returns {string} The original input (pass-through) + */ +function run(rawInput) { + try { + const input = JSON.parse(rawInput); + const filePath = input.tool_input?.file_path; + + if (filePath && /\.(ts|tsx|js|jsx)$/.test(filePath)) { + try { + const resolvedFilePath = path.resolve(filePath); + const projectRoot = findProjectRoot(path.dirname(resolvedFilePath)); + const formatter = detectFormatter(projectRoot); + if (!formatter) return rawInput; + + const resolved = resolveFormatterBin(projectRoot, formatter); + if (!resolved) return rawInput; + + // Biome: `check --write` = format + lint in one pass + // Prettier: `--write` = format only + const args = formatter === 'biome' ? [...resolved.prefix, 'check', '--write', resolvedFilePath] : [...resolved.prefix, '--write', resolvedFilePath]; + + if (process.platform === 'win32' && resolved.bin.endsWith('.cmd')) { + // Windows: .cmd files require shell to execute. Guard against + // command injection by rejecting paths with shell metacharacters. + if (UNSAFE_PATH_CHARS.test(resolvedFilePath)) { + throw new Error('File path contains unsafe shell characters'); + } + const result = spawnSync(resolved.bin, args, { + cwd: projectRoot, + shell: true, + stdio: 'pipe', + timeout: 15000 + }); + if (result.error) throw result.error; + if (typeof result.status === 'number' && result.status !== 0) { + throw new Error(result.stderr?.toString() || `Formatter exited with status ${result.status}`); + } + } else { + execFileSync(resolved.bin, args, { + cwd: projectRoot, + stdio: ['pipe', 'pipe', 'pipe'], + timeout: 15000 + }); + } + } catch { + // Formatter not installed, file missing, or failed — non-blocking + } + } + } catch { + // Invalid input — pass through + } + + return rawInput; +} + +// ── stdin entry point (backwards-compatible) ──────────────────── +if (require.main === module) { + let data = ''; + let stdinBytes = 0; + let oversized = false; + process.stdin.setEncoding('utf8'); + + process.stdin.on('data', chunk => { + if (oversized) return; + stdinBytes += Buffer.byteLength(chunk, 'utf8'); + if (stdinBytes > MAX_DIRECT_STDIN_BYTES) { + data = ''; + oversized = true; + return; + } + data += chunk; + }); + + process.stdin.on('end', () => { + if (oversized) { + process.exit(0); + return; + } + data = run(data); + process.stdout.write(data, () => process.exit(0)); + }); +} + +module.exports = { run }; diff --git a/github_code/affaan-m__ECC/scripts/hooks/post-edit-typecheck.js b/github_code/affaan-m__ECC/scripts/hooks/post-edit-typecheck.js new file mode 100644 index 0000000000000000000000000000000000000000..28640c0acaeabc4617b0b12b057a86852f227f4a --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/hooks/post-edit-typecheck.js @@ -0,0 +1,105 @@ +#!/usr/bin/env node +/** + * PostToolUse Hook: TypeScript check after editing .ts/.tsx files + * + * Cross-platform (Windows, macOS, Linux) + * + * Runs after Edit tool use on TypeScript files. Walks up from the file's + * directory to find the nearest tsconfig.json, then runs tsc --noEmit + * and reports only errors related to the edited file. + */ + +const { execFileSync } = require("child_process"); +const fs = require("fs"); +const path = require("path"); + +const MAX_DIRECT_STDIN_BYTES = 16 * 1024 * 1024; +let data = ""; +let stdinBytes = 0; +let oversized = false; +process.stdin.setEncoding("utf8"); + +process.stdin.on("data", (chunk) => { + if (oversized) return; + stdinBytes += Buffer.byteLength(chunk, "utf8"); + if (stdinBytes > MAX_DIRECT_STDIN_BYTES) { + data = ""; + oversized = true; + return; + } + data += chunk; +}); + +process.stdin.on("end", () => { + if (oversized) { + process.exit(0); + return; + } + try { + const input = JSON.parse(data); + const filePath = input.tool_input?.file_path; + + if (filePath && /\.(ts|tsx)$/.test(filePath)) { + const resolvedPath = path.resolve(filePath); + if (!fs.existsSync(resolvedPath)) { + process.stdout.write(data, () => process.exit(0)); + return; + } + // Find nearest tsconfig.json by walking up (max 20 levels to prevent infinite loop) + let dir = path.dirname(resolvedPath); + const root = path.parse(dir).root; + let depth = 0; + + while (dir !== root && depth < 20) { + if (fs.existsSync(path.join(dir, "tsconfig.json"))) { + break; + } + dir = path.dirname(dir); + depth++; + } + + if (fs.existsSync(path.join(dir, "tsconfig.json"))) { + try { + // Use npx.cmd on Windows to avoid shell: true which enables command injection + const npxBin = process.platform === "win32" ? "npx.cmd" : "npx"; + execFileSync(npxBin, ["tsc", "--noEmit", "--pretty", "false"], { + cwd: dir, + encoding: "utf8", + stdio: ["pipe", "pipe", "pipe"], + timeout: 30000, + }); + } catch (err) { + // tsc exits non-zero when there are errors — filter to edited file + const output = (err.stdout || "") + (err.stderr || ""); + // Compute paths that uniquely identify the edited file. + // tsc output uses paths relative to its cwd (the tsconfig dir), + // so check for the relative path, absolute path, and original path. + // Avoid bare basename matching — it causes false positives when + // multiple files share the same name (e.g., src/utils.ts vs tests/utils.ts). + const relPath = path.relative(dir, resolvedPath); + const candidates = new Set([filePath, resolvedPath, relPath]); + const relevantLines = output + .split("\n") + .filter((line) => { + for (const candidate of candidates) { + if (line.includes(candidate)) return true; + } + return false; + }) + .slice(0, 10); + + if (relevantLines.length > 0) { + console.error( + "[Hook] TypeScript errors in " + path.basename(filePath) + ":", + ); + relevantLines.forEach((line) => console.error(line)); + } + } + } + } + } catch { + // Invalid input — pass through + } + + process.stdout.write(data, () => process.exit(0)); +}); diff --git a/github_code/affaan-m__ECC/scripts/hooks/posttooluse-dispatcher.js b/github_code/affaan-m__ECC/scripts/hooks/posttooluse-dispatcher.js new file mode 100644 index 0000000000000000000000000000000000000000..fcffeb40086bd9327f6360348a0a093290739b0a --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/hooks/posttooluse-dispatcher.js @@ -0,0 +1,290 @@ +#!/usr/bin/env node +/** + * Consolidates PostToolUse hooks into one synchronous and one asynchronous + * entrypoint while preserving each hook's ID, matcher, profile, and output. + */ + +'use strict'; + +const path = require('path'); +const { StringDecoder } = require('string_decoder'); +const { isHookEnabled } = require('../lib/hook-flags'); +const { runPostBash } = require('./bash-hook-dispatcher'); +const { run: runQualityGate } = require('./quality-gate'); +const { run: runDesignQualityCheck } = require('./design-quality-check'); +const { run: runPostEditAccumulator } = require('./post-edit-accumulator'); +const { run: runConsoleWarn } = require('./post-edit-console-warn'); +const { run: runGovernanceCapture } = require('./governance-capture'); +const { run: runSessionActivityTracker } = require('./session-activity-tracker'); +const { run: runObserve } = require('./observe-runner'); +const { run: runMetricsBridge } = require('./ecc-metrics-bridge'); +const { run: runContextMonitor } = require('./ecc-context-monitor'); +const { run: runSkillRunTracker } = require('./skill-run-tracker'); + +const MAX_STDIN = 1024 * 1024; + +const SYNC_HOOKS = [ + { id: 'post:edit:design-quality-check', matcher: 'Edit|Write|MultiEdit', profiles: 'standard,strict', script: 'scripts/hooks/design-quality-check.js', run: runDesignQualityCheck }, + { id: 'post:edit:accumulator', matcher: 'Edit|Write|MultiEdit', profiles: 'standard,strict', script: 'scripts/hooks/post-edit-accumulator.js', run: runPostEditAccumulator }, + { id: 'post:edit:console-warn', matcher: 'Edit', profiles: 'standard,strict', script: 'scripts/hooks/post-edit-console-warn.js', run: runConsoleWarn }, + { id: 'post:governance-capture', matcher: 'Bash|PowerShell|Write|Edit|MultiEdit', profiles: 'standard,strict', script: 'scripts/hooks/governance-capture.js', run: runGovernanceCapture }, + { id: 'post:session-activity-tracker', matcher: '*', profiles: 'standard,strict', script: 'scripts/hooks/session-activity-tracker.js', run: runSessionActivityTracker }, + { id: 'post:ecc-metrics-bridge', matcher: '*', profiles: 'minimal,standard,strict', script: 'scripts/hooks/ecc-metrics-bridge.js', run: runMetricsBridge }, + { id: 'post:ecc-context-monitor', matcher: '*', profiles: 'standard,strict', script: 'scripts/hooks/ecc-context-monitor.js', run: runContextMonitor } +]; + +const ASYNC_HOOKS = [ + { + id: 'post:bash:dispatcher', + matcher: 'Bash', + // main ran this phase unconditionally; sub-hooks gate themselves internally + profiles: 'minimal,standard,strict', + script: 'scripts/hooks/post-bash-dispatcher.js', + run(raw) { + const result = runPostBash(raw); + return { stdout: result.output, stderr: result.stderr, exitCode: result.exitCode }; + } + }, + { id: 'post:quality-gate', matcher: 'Edit|Write|MultiEdit', profiles: 'standard,strict', script: 'scripts/hooks/quality-gate.js', run: runQualityGate }, + { id: 'post:observe:continuous-learning', matcher: '*', profiles: 'standard,strict', script: 'scripts/hooks/observe-runner.js', run: runObserve }, + { id: 'post:skill:track', matcher: 'Skill', profiles: 'standard,strict', script: 'scripts/hooks/skill-run-tracker.js', run: runSkillRunTracker } +]; + +function getPluginRoot(env = process.env) { + return env.CLAUDE_PLUGIN_ROOT || env.ECC_PLUGIN_ROOT || path.resolve(__dirname, '..', '..'); +} + +function matchesTool(matcher, toolName) { + const normalizedToolName = String(toolName || '').toLowerCase(); + return ( + matcher === '*' || + String(matcher || '') + .split('|') + .map(value => value.trim()) + .filter(Boolean) + .some(value => value.toLowerCase() === normalizedToolName) + ); +} + +function isEnabled(hook, env) { + return isHookEnabled(hook.id, { + env, + profiles: hook.profiles, + }); +} + +function extractToolName(raw) { + try { + return String(JSON.parse(raw)?.tool_name || ''); + } catch { + return ''; + } +} + +function buildDryRunPreview(hook, raw) { + let target = ''; + try { + const input = JSON.parse(raw)?.tool_input || {}; + target = String(input.file_path || input.path || input.command || ''); + } catch { + target = ''; + } + const suffix = target ? ` target=${target}` : ''; + return `[DryRun] Hook "${hook.id}" would execute: ${hook.script} (enabled=true, profiles=${hook.profiles})${suffix}\n`; +} + +function normalizeResult(raw, output) { + if (typeof output === 'string' || Buffer.isBuffer(output)) { + const stdout = String(output); + return { stdout: stdout !== raw ? stdout : '', stderr: '', exitCode: 0 }; + } + if (!output || typeof output !== 'object') { + return { stdout: '', stderr: '', exitCode: 0 }; + } + + let stdout = ''; + if (Object.prototype.hasOwnProperty.call(output, 'stdout')) { + stdout = String(output.stdout ?? ''); + } else if (Object.prototype.hasOwnProperty.call(output, 'output')) { + stdout = String(output.output ?? ''); + } else if (Object.prototype.hasOwnProperty.call(output, 'additionalContext')) { + stdout = JSON.stringify({ + hookSpecificOutput: { + hookEventName: 'PostToolUse', + additionalContext: String(output.additionalContext ?? '') + } + }); + } + + return { + stdout: stdout !== raw ? stdout : '', + stderr: typeof output.stderr === 'string' ? output.stderr : '', + exitCode: Number.isInteger(output.exitCode) ? output.exitCode : 0 + }; +} + +function appendLine(current, next) { + if (!next) return current; + return current + (String(next).endsWith('\n') ? String(next) : `${next}\n`); +} + +function parseAdditionalContext(stdout) { + try { + const parsed = JSON.parse(stdout); + const output = parsed?.hookSpecificOutput; + if (output?.hookEventName !== 'PostToolUse') return null; + return typeof output.additionalContext === 'string' ? output.additionalContext : null; + } catch { + return null; + } +} + +function mergeHookStdout(outputs) { + if (outputs.length === 0) return { stdout: '', warning: '' }; + if (outputs.length === 1) return { stdout: outputs[0].stdout, warning: '' }; + + const contexts = outputs.map(output => parseAdditionalContext(output.stdout)); + if (contexts.every(context => context !== null)) { + return { + stdout: JSON.stringify({ + hookSpecificOutput: { + hookEventName: 'PostToolUse', + additionalContext: contexts.join('\n') + } + }), + warning: '' + }; + } + + const kept = outputs[outputs.length - 1]; + const dropped = outputs + .slice(0, -1) + .map(output => output.id) + .join(', '); + return { + stdout: kept.stdout, + warning: `[Hook] stdout from ${dropped} dropped in favor of ${kept.id}; raw stdout cannot be merged` + }; +} + +function runHooks(raw, hooks, options = {}) { + const env = options.env || process.env; + const toolName = options.toolName ?? extractToolName(raw); + const pluginRoot = getPluginRoot(env); + const outputs = []; + let stderr = ''; + let exitCode = 0; + + for (const hook of hooks) { + if (!matchesTool(hook.matcher, toolName) || !isEnabled(hook, env)) continue; + if (env.ECC_DRY_RUN === '1') { + stderr += buildDryRunPreview(hook, raw); + continue; + } + + try { + const result = normalizeResult( + raw, + hook.run(raw, { + hookId: hook.id, + pluginRoot, + scriptPath: path.join(pluginRoot, hook.script || ''), + truncated: options.truncated === true, + maxStdin: MAX_STDIN + }) + ); + if (result.stdout) outputs.push({ id: hook.id, stdout: result.stdout }); + stderr = appendLine(stderr, result.stderr); + if (result.exitCode !== 0) { + if (exitCode === 0) exitCode = result.exitCode; + stderr = appendLine(stderr, `[Hook] ${hook.id} exited with code ${result.exitCode}; continuing`); + } + } catch (error) { + stderr = appendLine(stderr, `[Hook] ${hook.id} failed: ${error.message}`); + } + } + + const merged = mergeHookStdout(outputs); + if (merged.warning) stderr = appendLine(stderr, merged.warning); + return { stdout: merged.stdout, stderr, exitCode }; +} + +function readStdinRaw() { + return new Promise(resolve => { + const decoder = new StringDecoder('utf8'); + let raw = ''; + let bytesRead = 0; + let truncated = false; + let settled = false; + process.stdin.on('data', chunk => { + const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk); + const remaining = Math.max(0, MAX_STDIN - bytesRead); + const accepted = buffer.subarray(0, remaining); + if (accepted.length > 0) { + raw += decoder.write(accepted); + bytesRead += accepted.length; + } + if (buffer.length > accepted.length) truncated = true; + }); + const finish = () => { + if (settled) return; + settled = true; + if (!truncated) raw += decoder.end(); + resolve({ raw, truncated }); + }; + process.stdin.once('end', finish); + process.stdin.once('error', finish); + }); +} + +function resolveMainStdout(raw, result, options = {}) { + if (result.stdout) return result.stdout; + if (options.truncated || result.exitCode !== 0 || !options.passthrough) return ''; + return raw; +} + +async function main() { + const mode = process.argv[2] === 'async' ? 'async' : 'sync'; + const { raw, truncated } = await readStdinRaw(); + const dispatcherId = `post:dispatcher:${mode}`; + const dispatcherEnabled = isEnabled( + { + id: dispatcherId, + profiles: 'minimal,standard,strict' + }, + process.env + ); + const hooks = dispatcherEnabled ? (mode === 'async' ? ASYNC_HOOKS : SYNC_HOOKS) : []; + const result = runHooks(raw, hooks, { truncated }); + if (truncated) { + process.stderr.write(`[Hook] stdin exceeded ${MAX_STDIN} bytes for PostToolUse ${mode}; suppressing pass-through\n`); + } + if (result.stderr) process.stderr.write(result.stderr); + const stdout = resolveMainStdout(raw, result, { + passthrough: process.env.ECC_POSTTOOLUSE_PASSTHROUGH === '1', + truncated + }); + if (stdout) process.stdout.write(stdout); + process.exitCode = result.exitCode; +} + +function cli() { + main().catch(error => { + process.stderr.write(`[Hook] PostToolUse dispatcher failed: ${error.message}\n`); + process.exitCode = 0; + }); +} + +if (require.main === module) cli(); + +module.exports = { + ASYNC_HOOKS, + SYNC_HOOKS, + cli, + matchesTool, + main, + mergeHookStdout, + normalizeResult, + resolveMainStdout, + runHooks +}; diff --git a/github_code/affaan-m__ECC/scripts/hooks/pre-bash-commit-quality.js b/github_code/affaan-m__ECC/scripts/hooks/pre-bash-commit-quality.js new file mode 100644 index 0000000000000000000000000000000000000000..5780c1d5b7aeb5e2b3373ec6934a7dd7a9baab36 --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/hooks/pre-bash-commit-quality.js @@ -0,0 +1,484 @@ +#!/usr/bin/env node +/** + * PreToolUse Hook: Pre-commit Quality Check + * + * Runs quality checks before git commit commands: + * - Detects staged files + * - Runs linter on staged files (if available) + * - Checks for common issues (console.log, TODO, etc.) + * - Validates commit message format (if provided) + * + * Cross-platform (Windows, macOS, Linux) + * + * Exit codes: + * 0 - Success (allow commit) + * 2 - Block commit (quality issues found) + */ + +const { spawnSync } = require('child_process'); +const path = require('path'); +const fs = require('fs'); + +const MAX_STDIN = 1024 * 1024; // 1MB limit + +/** + * Detect staged files for commit + * @returns {string[]} Array of staged file paths + */ +function getStagedFiles() { + const result = spawnSync('git', ['diff', '--cached', '--name-only', '--diff-filter=ACMR'], { + encoding: 'utf8', + stdio: ['pipe', 'pipe', 'pipe'] + }); + if (result.status !== 0) { + return []; + } + return result.stdout.trim().split('\n').filter(f => f.length > 0); +} + +function getStagedFileContent(filePath) { + const result = spawnSync('git', ['show', `:${filePath}`], { + encoding: 'utf8', + stdio: ['pipe', 'pipe', 'pipe'] + }); + if (result.status !== 0) { + return null; + } + return result.stdout; +} + +/** + * Check if a file should be quality-checked + * @param {string} filePath + * @returns {boolean} + */ +function shouldCheckFile(filePath) { + const checkableExtensions = ['.js', '.jsx', '.ts', '.tsx', '.py', '.go', '.rs']; + return checkableExtensions.some(ext => filePath.endsWith(ext)); +} + +/** + * Decide whether a captured api-key value is an OBVIOUS non-secret placeholder so + * the heuristic generic api-key rule does not emit a false positive. Deliberately + * narrow: only suppresses whole-value env references / interpolations / angle-bracket + * tokens and a short explicit whitelist of placeholder + env-var NAME tokens. It must + * NOT suppress arbitrary high-entropy data (uppercase-hex, base32, digit-only, mixed + * tokens), since the generic rule is the only net catching non-prefixed secrets and a + * false-negative there is the safety-critical failure this hook exists to prevent. + * @param {string} value + * @returns {boolean} + */ +function isPlaceholderSecret(value) { + const v = (value || '').trim(); + if (v.length === 0) return true; // empty value + if (/^process\.env\.[A-Za-z0-9_]+$/.test(v)) return true; // entire value is a process.env.NAME reference + if (/^\$\{[^}]*\}$/.test(v)) return true; // entire value is a ${...} interpolation + if (/^<[^<>]*>$/.test(v)) return true; // entire value is a token + // Short explicit whitelist of placeholder + env-var NAME tokens (whole-value match only). + // No general all-caps clause: real all-caps/hex/base32/digit secrets must still flag. + if (/^(REPLACE_ME|CHANGE_?ME|YOUR[_-]?API[_-]?KEY|YOUR[_-]?KEY[_-]?HERE|API[_-]?KEY|SECRET|TOKEN|KEY|TODO|TBD|FIXME|XXX+)$/i.test(v)) return true; + return false; +} + +/** + * Find issues in file content + * @param {string} filePath + * @returns {object[]} Array of issues found + */ +function findFileIssues(filePath) { + const issues = []; + + try { + const content = getStagedFileContent(filePath); + if (content === null || content === undefined) { + return issues; + } + const lines = content.split('\n'); + + lines.forEach((line, index) => { + const lineNum = index + 1; + + // Check for console.log + if (line.includes('console.log') && !line.trim().startsWith('//') && !line.trim().startsWith('*')) { + issues.push({ + type: 'console.log', + message: `console.log found at line ${lineNum}`, + line: lineNum, + severity: 'warning' + }); + } + + // Check for debugger statements + if (/\bdebugger\b/.test(line) && !line.trim().startsWith('//')) { + issues.push({ + type: 'debugger', + message: `debugger statement at line ${lineNum}`, + line: lineNum, + severity: 'error' + }); + } + + // Check for TODO/FIXME without issue reference + const todoMatch = line.match(/\/\/\s*(TODO|FIXME):?\s*(.+)/); + if (todoMatch && !todoMatch[2].match(/#\d+|issue/i)) { + issues.push({ + type: 'todo', + message: `TODO/FIXME without issue reference at line ${lineNum}: "${todoMatch[2].trim()}"`, + line: lineNum, + severity: 'info' + }); + } + + // Check for hardcoded secrets (basic patterns) + const secretPatterns = [ + { pattern: /sk-ant-[a-zA-Z0-9_-]{20,}/, name: 'Anthropic API key' }, + { pattern: /sk-[a-zA-Z0-9]{20,}/, name: 'OpenAI API key' }, + { pattern: /ghp_[a-zA-Z0-9]{36}/, name: 'GitHub PAT' }, + { pattern: /AKIA[A-Z0-9]{16}/, name: 'AWS Access Key' }, + // Capture the quoted value so obvious non-secret placeholders can be excluded + { pattern: /api[_-]?key\s*[=:]\s*['"]([^'"]+)['"]/i, name: 'API key', valueGroup: 1 }, + // Unquoted form (API_KEY=..., api_key: ... without quotes). Scoped to a + // single alnum/underscore/hyphen token of 12+ chars containing at least + // one digit — real secrets are near-always alphanumeric, whereas bare + // identifiers/expressions common in this hook's checkable languages + // (config.apiKey, getApiKey(), process.env.API_KEY) are pure-alpha or + // contain '.'/'(' that fall outside the character class, so they don't + // match. Kept deliberately narrow to avoid flagging ordinary code. + { pattern: /api[_-]?key\s*[=:]\s*(?!['"])((?=[A-Za-z0-9_-]*\d)[A-Za-z0-9_-]{12,})/i, name: 'API key', valueGroup: 1 } + ]; + + for (const { pattern, name, valueGroup } of secretPatterns) { + const secretMatch = line.match(pattern); + if (secretMatch && !(valueGroup && isPlaceholderSecret(secretMatch[valueGroup]))) { + issues.push({ + type: 'secret', + message: `Potential ${name} exposed at line ${lineNum}`, + line: lineNum, + severity: 'error' + }); + } + } + }); + } catch { + // File not readable, skip + } + + return issues; +} + +/** + * Validate commit message format + * @param {string} command + * @returns {object|null} Validation result or null if no message to validate + */ +function validateCommitMessage(command) { + // Extract commit message from command (quote-aware: when quoted, capture to the + // matching closing quote, consuming escaped chars (\") so an embedded escaped + // quote does not truncate the subject, and allowing the OTHER quote char inside + // the body; when unquoted, capture the full remaining tail, not just the first token) + const messageMatch = command.match(/(?:-m|--message)[=\s]+(?:"((?:\\.|[^"\\])*)"|'((?:\\.|[^'\\])*)'|([^"']+?)\s*$)/); + if (!messageMatch) return null; + + const message = messageMatch[1] ?? messageMatch[2] ?? messageMatch[3]; + const issues = []; + + // Check conventional commit format + const conventionalCommit = /^(feat|fix|docs|style|refactor|test|chore|build|ci|perf|revert)(\(.+\))?:\s*.+/; + if (!conventionalCommit.test(message)) { + issues.push({ + type: 'format', + message: 'Commit message does not follow conventional commit format', + suggestion: 'Use format: type(scope): description (e.g., "feat(auth): add login flow")' + }); + } + + // Check message length + if (message.length > 72) { + issues.push({ + type: 'length', + message: `Commit message too long (${message.length} chars, max 72)`, + suggestion: 'Keep the first line under 72 characters' + }); + } + + // Check for lowercase first letter (conventional) + if (conventionalCommit.test(message)) { + const afterColon = message.split(':')[1]; + if (afterColon && /^[A-Z]/.test(afterColon.trim())) { + issues.push({ + type: 'capitalization', + message: 'Subject should start with lowercase after type', + suggestion: 'Use lowercase for the first letter of the subject' + }); + } + } + + // Check for trailing period + if (message.endsWith('.')) { + issues.push({ + type: 'punctuation', + message: 'Commit message should not end with a period', + suggestion: 'Remove the trailing period' + }); + } + + return { message, issues }; +} + +function getPathEnv() { + const pathKey = Object.keys(process.env).find(key => key.toLowerCase() === 'path') || 'PATH'; + return process.env[pathKey] || ''; +} + +function isPathLike(command) { + return command.includes(path.sep) || (process.platform === 'win32' && /[\\/]/.test(command)); +} + +function getExecutableCandidates(command) { + if (process.platform !== 'win32' || path.extname(command)) { + return [command]; + } + + const pathExt = process.env.PATHEXT || '.COM;.EXE;.BAT;.CMD'; + return [command, ...pathExt.split(';').filter(Boolean).map(ext => `${command}${ext.toLowerCase()}`)]; +} + +function resolveCommand(command) { + if (isPathLike(command)) { + return getExecutableCandidates(command).find(candidate => fs.existsSync(candidate)) || null; + } + + for (const dir of getPathEnv().split(path.delimiter).filter(Boolean)) { + for (const candidate of getExecutableCandidates(path.join(dir, command))) { + if (fs.existsSync(candidate)) { + return candidate; + } + } + } + + return null; +} + +function runLinterCommand(command, args) { + const useShell = process.platform === 'win32' && /\.(?:cmd|bat)$/i.test(command); + return spawnSync(command, args, { + encoding: 'utf8', + stdio: ['pipe', 'pipe', 'pipe'], + timeout: 30000, + shell: useShell + }); +} + +function commandOutput(result) { + return result.stdout || result.stderr || result.error?.message || ''; +} + +/** + * Run linter on staged files + * @param {string[]} files + * @returns {object} Lint results + */ +function runLinter(files) { + const jsFiles = files.filter(f => /\.(js|jsx|ts|tsx)$/.test(f)); + const pyFiles = files.filter(f => f.endsWith('.py')); + const goFiles = files.filter(f => f.endsWith('.go')); + + const results = { + eslint: null, + pylint: null, + golint: null + }; + + // Run ESLint if available + if (jsFiles.length > 0) { + const eslintBin = process.platform === 'win32' ? 'eslint.cmd' : 'eslint'; + const eslintPath = path.join(process.cwd(), 'node_modules', '.bin', eslintBin); + if (fs.existsSync(eslintPath)) { + const result = runLinterCommand(eslintPath, ['--format', 'compact', ...jsFiles]); + results.eslint = { + success: result.status === 0, + output: commandOutput(result) + }; + } + } + + // Run Pylint if available + if (pyFiles.length > 0) { + try { + const pylintPath = resolveCommand('pylint'); + if (!pylintPath) { + results.pylint = null; + } else { + const result = runLinterCommand(pylintPath, ['--output-format=text', ...pyFiles]); + results.pylint = { + success: result.status === 0, + output: commandOutput(result) + }; + } + } catch { + // Pylint not available + } + } + + // Run golint if available + if (goFiles.length > 0) { + try { + const golintPath = resolveCommand('golint'); + if (!golintPath) { + results.golint = null; + } else { + const result = runLinterCommand(golintPath, goFiles); + results.golint = { + success: !result.stdout || result.stdout.trim() === '', + output: commandOutput(result) + }; + } + } catch { + // golint not available + } + } + + return results; +} + +/** + * Core logic — exported for direct invocation + * @param {string} rawInput - Raw JSON string from stdin + * @returns {{output:string, exitCode:number}} Pass-through output and exit code + */ +function evaluate(rawInput) { + try { + const input = JSON.parse(rawInput); + const command = input.tool_input?.command || ''; + + // Only run for git commit commands + if (!command.includes('git commit')) { + return { output: rawInput, exitCode: 0 }; + } + + // Check if this is an amend (skip checks for amends to avoid blocking) + if (command.includes('--amend')) { + return { output: rawInput, exitCode: 0 }; + } + + // Get staged files + const stagedFiles = getStagedFiles(); + + if (stagedFiles.length === 0) { + console.error('[Hook] No staged files found. Use "git add" to stage files first.'); + return { output: rawInput, exitCode: 0 }; + } + + console.error(`[Hook] Checking ${stagedFiles.length} staged file(s)...`); + + // Check each staged file + const filesToCheck = stagedFiles.filter(shouldCheckFile); + let totalIssues = 0; + let errorCount = 0; + let warningCount = 0; + let infoCount = 0; + + for (const file of filesToCheck) { + const fileIssues = findFileIssues(file); + if (fileIssues.length > 0) { + console.error(`\n[FILE] ${file}`); + for (const issue of fileIssues) { + const label = issue.severity === 'error' ? 'ERROR' : issue.severity === 'warning' ? 'WARNING' : 'INFO'; + console.error(` ${label} Line ${issue.line}: ${issue.message}`); + totalIssues++; + if (issue.severity === 'error') errorCount++; + if (issue.severity === 'warning') warningCount++; + if (issue.severity === 'info') infoCount++; + } + } + } + + // Validate commit message if provided + const messageValidation = validateCommitMessage(command); + if (messageValidation && messageValidation.issues.length > 0) { + console.error('\nCommit Message Issues:'); + for (const issue of messageValidation.issues) { + console.error(` WARNING ${issue.message}`); + if (issue.suggestion) { + console.error(` TIP ${issue.suggestion}`); + } + totalIssues++; + warningCount++; + } + } + + // Run linter + const lintResults = runLinter(filesToCheck); + + if (lintResults.eslint && !lintResults.eslint.success) { + console.error('\nESLint Issues:'); + console.error(lintResults.eslint.output); + totalIssues++; + errorCount++; + } + + if (lintResults.pylint && !lintResults.pylint.success) { + console.error('\nPylint Issues:'); + console.error(lintResults.pylint.output); + totalIssues++; + errorCount++; + } + + if (lintResults.golint && !lintResults.golint.success) { + console.error('\ngolint Issues:'); + console.error(lintResults.golint.output); + totalIssues++; + errorCount++; + } + + // Summary + if (totalIssues > 0) { + console.error(`\nSummary: ${totalIssues} issue(s) found (${errorCount} error(s), ${warningCount} warning(s), ${infoCount} info)`); + + if (errorCount > 0) { + console.error('\n[Hook] ERROR: Commit blocked due to critical issues. Fix them before committing.'); + return { output: rawInput, exitCode: 2 }; + } else { + console.error('\n[Hook] WARNING: Warnings found. Consider fixing them, but commit is allowed.'); + console.error('[Hook] To bypass these checks, use: git commit --no-verify'); + } + } else { + console.error('\n[Hook] PASS: All checks passed!'); + } + + } catch (error) { + console.error(`[Hook] Error: ${error.message}`); + // Non-blocking on error + } + + return { output: rawInput, exitCode: 0 }; +} + +function run(rawInput) { + const result = evaluate(rawInput); + return { + stdout: result.output, + exitCode: result.exitCode, + }; +} + +// ── stdin entry point ──────────────────────────────────────────── +if (require.main === module) { + let data = ''; + process.stdin.setEncoding('utf8'); + + process.stdin.on('data', chunk => { + if (data.length < MAX_STDIN) { + const remaining = MAX_STDIN - data.length; + data += chunk.substring(0, remaining); + } + }); + + process.stdin.on('end', () => { + const result = evaluate(data); + process.stdout.write(result.output); + process.exit(result.exitCode); + }); +} + +module.exports = { run, evaluate, validateCommitMessage, findFileIssues, isPlaceholderSecret }; diff --git a/github_code/affaan-m__ECC/scripts/hooks/pre-bash-dev-server-block.js b/github_code/affaan-m__ECC/scripts/hooks/pre-bash-dev-server-block.js new file mode 100644 index 0000000000000000000000000000000000000000..06eb64020ca9afdcfd933bcca7bfc8e442729229 --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/hooks/pre-bash-dev-server-block.js @@ -0,0 +1,229 @@ +#!/usr/bin/env node +'use strict'; + +const MAX_STDIN = 1024 * 1024; +const path = require('path'); +const { splitShellSegments } = require('../lib/shell-split'); +const { + extractCommandSubstitutions, + extractSubshellGroups +} = require('../lib/shell-substitution'); + +const DEV_COMMAND_WORDS = new Set([ + 'npm', + 'pnpm', + 'yarn', + 'bun', + 'npx', + 'tmux' +]); +const SKIPPABLE_PREFIX_WORDS = new Set(['env', 'command', 'builtin', 'exec', 'noglob', 'sudo', 'nohup']); +const PREFIX_OPTION_VALUE_WORDS = { + env: new Set(['-u', '-C', '-S', '--unset', '--chdir', '--split-string']), + sudo: new Set([ + '-u', + '-g', + '-h', + '-p', + '-r', + '-t', + '-C', + '--user', + '--group', + '--host', + '--prompt', + '--role', + '--type', + '--close-from' + ]) +}; + +function readToken(input, startIndex) { + let index = startIndex; + while (index < input.length && /\s/.test(input[index])) index += 1; + if (index >= input.length) return null; + + let token = ''; + let quote = null; + + while (index < input.length) { + const ch = input[index]; + + if (quote) { + if (ch === quote) { + quote = null; + index += 1; + continue; + } + + if (ch === '\\' && quote === '"' && index + 1 < input.length) { + token += input[index + 1]; + index += 2; + continue; + } + + token += ch; + index += 1; + continue; + } + + if (ch === '"' || ch === "'") { + quote = ch; + index += 1; + continue; + } + + if (/\s/.test(ch)) break; + + if (ch === '\\' && index + 1 < input.length) { + token += input[index + 1]; + index += 2; + continue; + } + + token += ch; + index += 1; + } + + return { token, end: index }; +} + +function shouldSkipOptionValue(wrapper, optionToken) { + if (!wrapper || !optionToken || optionToken.includes('=')) return false; + const optionSet = PREFIX_OPTION_VALUE_WORDS[wrapper]; + return Boolean(optionSet && optionSet.has(optionToken)); +} + +function isOptionToken(token) { + return token.startsWith('-') && token.length > 1; +} + +function normalizeCommandWord(token) { + if (!token) return ''; + const base = path.basename(token).toLowerCase(); + return base.replace(/\.(cmd|exe|bat)$/i, ''); +} + +function getLeadingCommandWord(segment) { + let index = 0; + let activeWrapper = null; + let skipNextValue = false; + + while (index < segment.length) { + const parsed = readToken(segment, index); + if (!parsed) return null; + index = parsed.end; + + const token = parsed.token; + if (!token) continue; + + if (skipNextValue) { + skipNextValue = false; + continue; + } + + if (token === '--') { + activeWrapper = null; + continue; + } + + if (token === '{' || token === '}') continue; + + if (/^[A-Za-z_][A-Za-z0-9_]*=.*/.test(token)) continue; + + const normalizedToken = normalizeCommandWord(token); + + if (SKIPPABLE_PREFIX_WORDS.has(normalizedToken)) { + activeWrapper = normalizedToken; + continue; + } + + if (activeWrapper && isOptionToken(token)) { + if (shouldSkipOptionValue(activeWrapper, token)) { + skipNextValue = true; + } + continue; + } + + return normalizedToken; + } + + return null; +} + +let raw = ''; +process.stdin.setEncoding('utf8'); +process.stdin.on('data', chunk => { + if (raw.length < MAX_STDIN) { + const remaining = MAX_STDIN - raw.length; + raw += chunk.substring(0, remaining); + } +}); + +const TMUX_LAUNCHER = /^\s*tmux\s+(new|new-session|new-window|split-window)\b/; +// Trailing (?![\w-]) rather than \b: \b treats a hyphen as a word boundary, so +// `dev\b` matches the `dev` prefix of distinct scripts like `dev-setup` / +// `dev-docs` / `dev-build` and wrongly blocks them. The lookahead still matches +// the dev server (`dev`, `dev;`, `dev:ssr`, ...) but not a `dev-` script. +const DEV_PATTERN = /\b(npm\s+run\s+dev|pnpm(?:\s+run)?\s+dev|yarn(?:\s+run)?\s+dev|bun(?:\s+run)?\s+dev)(?![\w-])/; + +/** + * Collect every command-line segment we should evaluate. Returns the top-level + * segments first, then segments harvested from `$(...)` / backtick command + * substitutions and plain `(...)` subshell groups, recursively. + * + * Without this expansion the leading-command and dev-pattern check below only + * sees the outermost command, so wrappers like `$(npm run dev)` and + * `(npm run dev)` (which still spawn a dev server) sneak past. + */ +function collectCheckSegments(cmd) { + const segments = [...splitShellSegments(cmd)]; + const queue = [cmd]; + const seen = new Set(); + + while (queue.length) { + const current = queue.shift(); + if (seen.has(current)) continue; + seen.add(current); + + for (const body of extractCommandSubstitutions(current)) { + for (const seg of splitShellSegments(body)) segments.push(seg); + queue.push(body); + } + for (const body of extractSubshellGroups(current)) { + for (const seg of splitShellSegments(body)) segments.push(seg); + queue.push(body); + } + } + + return segments; +} + +function isBlockedDevSegment(segment) { + const commandWord = getLeadingCommandWord(segment); + if (!commandWord || !DEV_COMMAND_WORDS.has(commandWord)) return false; + return DEV_PATTERN.test(segment) && !TMUX_LAUNCHER.test(segment); +} + +process.stdin.on('end', () => { + try { + const input = JSON.parse(raw); + const cmd = String(input.tool_input?.command || ''); + + if (process.platform !== 'win32') { + const segments = collectCheckSegments(cmd); + const hasBlockedDev = segments.some(isBlockedDevSegment); + + if (hasBlockedDev) { + console.error('[Hook] BLOCKED: Dev server must run in tmux for log access'); + console.error('[Hook] Use: tmux new-session -d -s dev "npm run dev"'); + console.error('[Hook] Then: tmux attach -t dev'); + process.exit(2); + } + } + } catch { + // ignore parse errors and pass through + } + + process.stdout.write(raw); +}); diff --git a/github_code/affaan-m__ECC/scripts/hooks/pre-bash-dispatcher.js b/github_code/affaan-m__ECC/scripts/hooks/pre-bash-dispatcher.js new file mode 100644 index 0000000000000000000000000000000000000000..b9ccad7d6f50ee3065e0c8c108eef350e5794f71 --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/hooks/pre-bash-dispatcher.js @@ -0,0 +1,24 @@ +#!/usr/bin/env node +'use strict'; + +const { runPreBash } = require('./bash-hook-dispatcher'); + +let raw = ''; +const MAX_STDIN = 1024 * 1024; + +process.stdin.setEncoding('utf8'); +process.stdin.on('data', chunk => { + if (raw.length < MAX_STDIN) { + const remaining = MAX_STDIN - raw.length; + raw += chunk.substring(0, remaining); + } +}); + +process.stdin.on('end', () => { + const result = runPreBash(raw); + if (result.stderr) { + process.stderr.write(result.stderr); + } + process.stdout.write(result.output); + process.exitCode = result.exitCode; +}); diff --git a/github_code/affaan-m__ECC/scripts/hooks/pre-bash-git-push-reminder.js b/github_code/affaan-m__ECC/scripts/hooks/pre-bash-git-push-reminder.js new file mode 100644 index 0000000000000000000000000000000000000000..52ae376aa5a230bcf9ef4872a5fc83a2af22f271 --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/hooks/pre-bash-git-push-reminder.js @@ -0,0 +1,56 @@ +#!/usr/bin/env node +'use strict'; + +const MAX_STDIN = 1024 * 1024; +const { buildPreToolUseAdditionalContext } = require('./pretooluse-visible-output'); +let raw = ''; + +function run(rawInput) { + try { + const input = typeof rawInput === 'string' ? JSON.parse(rawInput) : rawInput; + const cmd = String(input.tool_input?.command || ''); + if (/\bgit\s+push\b/.test(cmd)) { + return { + additionalContext: [ + '[Hook] Review changes before push...', + '[Hook] Continuing with push (remove this hook to add interactive review)', + ], + exitCode: 0, + }; + } + } catch { + // ignore parse errors and pass through + } + + return typeof rawInput === 'string' ? rawInput : JSON.stringify(rawInput); +} + +if (require.main === module) { + process.stdin.setEncoding('utf8'); + process.stdin.on('data', chunk => { + if (raw.length < MAX_STDIN) { + const remaining = MAX_STDIN - raw.length; + raw += chunk.substring(0, remaining); + } + }); + + process.stdin.on('end', () => { + const result = run(raw); + if (result && typeof result === 'object') { + if (result.stderr) { + process.stderr.write(`${result.stderr}\n`); + } + if (Object.prototype.hasOwnProperty.call(result, 'additionalContext')) { + process.stdout.write(buildPreToolUseAdditionalContext(result.additionalContext)); + } else { + process.stdout.write(String(result.stdout || '')); + } + process.exitCode = Number.isInteger(result.exitCode) ? result.exitCode : 0; + return; + } + + process.stdout.write(String(result)); + }); +} + +module.exports = { run }; diff --git a/github_code/affaan-m__ECC/scripts/hooks/pre-bash-tmux-reminder.js b/github_code/affaan-m__ECC/scripts/hooks/pre-bash-tmux-reminder.js new file mode 100644 index 0000000000000000000000000000000000000000..e00c16df8e5061e9a24d625130c0a77cca3b5eb9 --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/hooks/pre-bash-tmux-reminder.js @@ -0,0 +1,61 @@ +#!/usr/bin/env node +'use strict'; + +const MAX_STDIN = 1024 * 1024; +const { buildPreToolUseAdditionalContext } = require('./pretooluse-visible-output'); +let raw = ''; + +function run(rawInput) { + try { + const input = typeof rawInput === 'string' ? JSON.parse(rawInput) : rawInput; + const cmd = String(input.tool_input?.command || ''); + + if ( + process.platform !== 'win32' && + !process.env.TMUX && + /(npm (install|test)|pnpm (install|test)|yarn (install|test)|bun (install|test)|cargo build|make\b|docker\b|pytest|vitest|playwright)/.test(cmd) + ) { + return { + additionalContext: [ + '[Hook] Consider running in tmux for session persistence', + '[Hook] tmux new -s dev | tmux attach -t dev', + ], + exitCode: 0, + }; + } + } catch { + // ignore parse errors and pass through + } + + return typeof rawInput === 'string' ? rawInput : JSON.stringify(rawInput); +} + +if (require.main === module) { + process.stdin.setEncoding('utf8'); + process.stdin.on('data', chunk => { + if (raw.length < MAX_STDIN) { + const remaining = MAX_STDIN - raw.length; + raw += chunk.substring(0, remaining); + } + }); + + process.stdin.on('end', () => { + const result = run(raw); + if (result && typeof result === 'object') { + if (result.stderr) { + process.stderr.write(`${result.stderr}\n`); + } + if (Object.prototype.hasOwnProperty.call(result, 'additionalContext')) { + process.stdout.write(buildPreToolUseAdditionalContext(result.additionalContext)); + } else { + process.stdout.write(String(result.stdout || '')); + } + process.exitCode = Number.isInteger(result.exitCode) ? result.exitCode : 0; + return; + } + + process.stdout.write(String(result)); + }); +} + +module.exports = { run }; diff --git a/github_code/affaan-m__ECC/scripts/hooks/pre-compact.js b/github_code/affaan-m__ECC/scripts/hooks/pre-compact.js new file mode 100644 index 0000000000000000000000000000000000000000..2002ac3df2d3dac309d7ecbeaa814aba2f2fc3c3 --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/hooks/pre-compact.js @@ -0,0 +1,178 @@ +#!/usr/bin/env node +/** + * PreCompact Hook - Save LLM-generated summary before context compaction + * + * Cross-platform (Windows, macOS, Linux) + * + * Runs before Claude compacts context. Generates a rich LLM summary of the + * current session and writes it to the active session .tmp file so that the + * next session start gets a high-quality summary even after lossy compaction. + * + * Falls back to a plain log entry when transcript_path is unavailable or the + * LLM call fails. + */ + +const path = require('path'); +const fs = require('fs'); +const { getSessionsDir, getDateTimeString, getTimeString, findFiles, ensureDir, appendFile, readFile, writeFile, getProjectName, log } = require('../lib/utils'); +const { generateSessionSummary } = require('../lib/llm-summary'); + +const SUMMARY_START_MARKER = ''; +const SUMMARY_END_MARKER = ''; + +function escapeRegExp(value) { + return String(value).replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +} + +/** + * Canonicalize a path (resolve symlinks); fall back to the input on failure. + * Mirrors session-start.js#normalizePath so worktree comparisons agree. + */ +function normalizePath(p) { + try { + return fs.realpathSync(p); + } catch { + return p; + } +} + +/** + * Pick the session file that belongs to the CURRENT worktree. + * + * The sessions dir is shared across every project/worktree, so the newest + * `*-session.tmp` is frequently a DIFFERENT project's session. Matching by + * mtime (`sessions[0]`) therefore writes the compaction summary into the wrong + * project. Match on the `**Worktree:**` header (written by session-end.js) + * against cwd, mirroring session-start.js#selectMatchingSession: + * 1. exact worktree (cwd) match — newest wins + * 2. truly legacy sessions with NO Worktree header: same **Project:** name + * 3. otherwise null — do NOT annotate a foreign worktree's session + * A present-but-blank Worktree header counts as non-legacy (never a project + * fallback), so a foreign session is not matched by name. + * + * @param {Array<{path: string}>} sessions - newest-first session list + * @param {string} cwd + * @param {string} currentProject + * @param {(p: string) => (string|null)} [readFn] + * @returns {string|null} path of the chosen session, or null if none match + */ +function selectActiveSessionPath(sessions, cwd, currentProject, readFn = readFile) { + if (!sessions || sessions.length === 0) return null; + const normalizedCwd = normalizePath(cwd); + let projectMatch = null; + + for (const session of sessions) { + const content = readFn(session.path); + if (!content) continue; + + // (.*) not (.+): an explicit but empty header (`**Worktree:**` / `**Worktree:**\n`) + // must still register as present (hasWorktreeHeader) so it does not fall back + // to project-name matching against a foreign session. + const worktreeMatch = content.match(/\*\*Worktree:\*\*\s*(.*)$/m); + const hasWorktreeHeader = Boolean(worktreeMatch); + const sessionWorktree = worktreeMatch ? worktreeMatch[1].trim() : ''; + + if (sessionWorktree && normalizePath(sessionWorktree) === normalizedCwd) { + return session.path; + } + + // Project-name fallback only for truly legacy sessions with NO Worktree + // header at all — a present-but-blank header is not treated as legacy. + if (!projectMatch && currentProject && !hasWorktreeHeader) { + const projectFieldMatch = content.match(/\*\*Project:\*\*\s*(.+)$/m); + const sessionProject = projectFieldMatch ? projectFieldMatch[1].trim() : ''; + if (sessionProject && sessionProject === currentProject) { + projectMatch = session.path; + } + } + } + + return projectMatch; +} + +const MAX_STDIN = 1024 * 1024; +let stdinData = ''; + +if (require.main === module) { + process.stdin.setEncoding('utf8'); + + process.stdin.on('data', chunk => { + if (stdinData.length < MAX_STDIN) { + stdinData += chunk.substring(0, MAX_STDIN - stdinData.length); + } + }); + + process.stdin.on('end', () => { + main().catch(err => { + log(`[PreCompact] Error: ${err.message}`); + process.exit(0); + }); + }); +} + +async function main() { + let transcriptPath = null; + try { + const input = JSON.parse(stdinData); + if (input && typeof input.transcript_path === 'string' && input.transcript_path.length > 0) { + transcriptPath = input.transcript_path; + } + } catch { + // stdin not JSON or missing — proceed without transcript + } + + const sessionsDir = getSessionsDir(); + const compactionLog = path.join(sessionsDir, 'compaction-log.txt'); + + ensureDir(sessionsDir); + + const timestamp = getDateTimeString(); + appendFile(compactionLog, `[${timestamp}] Context compaction triggered\n`); + + const sessions = findFiles(sessionsDir, '*-session.tmp'); + if (sessions.length === 0) { + log('[PreCompact] No active session file found'); + process.exit(0); + } + + // Select the session for THIS worktree, not merely the newest across all + // projects (the sessions dir is shared). Skip when none matches rather than + // writing the summary into a foreign project's session file. + const activeSession = selectActiveSessionPath(sessions, process.cwd(), getProjectName()); + if (!activeSession) { + log('[PreCompact] No session matches the current worktree; skipping annotation'); + process.exit(0); + } + const timeStr = getTimeString(); + + if (!transcriptPath || !fs.existsSync(transcriptPath)) { + appendFile(activeSession, `\n---\n**[Compaction occurred at ${timeStr}]** - Context was summarized\n`); + log('[PreCompact] No transcript available; logged compaction event only'); + process.exit(0); + } + + // Generate LLM summary right before compaction — most critical timing + log('[PreCompact] Generating LLM summary before compaction...'); + const llmSummary = generateSessionSummary(transcriptPath); + + if (!llmSummary) { + appendFile(activeSession, `\n---\n**[Compaction occurred at ${timeStr}]** - Context was summarized\n`); + log('[PreCompact] LLM summary unavailable; logged compaction event only'); + process.exit(0); + } + + const existing = readFile(activeSession); + if (existing && existing.includes(SUMMARY_START_MARKER) && existing.includes(SUMMARY_END_MARKER)) { + const newBlock = `${SUMMARY_START_MARKER}\n${llmSummary}\n\n${SUMMARY_END_MARKER}`; + const updated = existing.replace(new RegExp(`${escapeRegExp(SUMMARY_START_MARKER)}[\\s\\S]*?${escapeRegExp(SUMMARY_END_MARKER)}`), () => newBlock); + writeFile(activeSession, updated); + log('[PreCompact] LLM summary written to session file before compaction'); + } else { + appendFile(activeSession, `\n---\n**[Compaction at ${timeStr}]**\n\n${llmSummary}\n`); + log('[PreCompact] LLM summary appended (no summary markers found)'); + } + + process.exit(0); +} + +module.exports = { selectActiveSessionPath, normalizePath }; diff --git a/github_code/affaan-m__ECC/scripts/hooks/pre-write-doc-warn.js b/github_code/affaan-m__ECC/scripts/hooks/pre-write-doc-warn.js new file mode 100644 index 0000000000000000000000000000000000000000..856b515974ffa3fe67ce2c2f14f2057287415e02 --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/hooks/pre-write-doc-warn.js @@ -0,0 +1,10 @@ +#!/usr/bin/env node +/** + * Backward-compatible doc warning hook entrypoint. + * Kept for consumers that still reference pre-write-doc-warn.js directly. + */ + +'use strict'; + +// doc-file-warning.js guards its stdin entrypoint behind require.main; call main() explicitly. +require('./doc-file-warning.js').main(); diff --git a/github_code/affaan-m__ECC/scripts/hooks/pretooluse-visible-output.js b/github_code/affaan-m__ECC/scripts/hooks/pretooluse-visible-output.js new file mode 100644 index 0000000000000000000000000000000000000000..dc48119099f6206e6011174a62ad9912d7af9a25 --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/hooks/pretooluse-visible-output.js @@ -0,0 +1,41 @@ +#!/usr/bin/env node +'use strict'; + +function normalizeAdditionalContext(value) { + if (Array.isArray(value)) { + return value + .map(item => String(item || '').trim()) + .filter(Boolean) + .join('\n'); + } + + return String(value || '').trim(); +} + +function combineAdditionalContext(current, next) { + const currentText = normalizeAdditionalContext(current); + const nextText = normalizeAdditionalContext(next); + + if (!currentText) return nextText; + if (!nextText) return currentText; + + return `${currentText}\n${nextText}`; +} + +function buildPreToolUseAdditionalContext(value) { + const additionalContext = normalizeAdditionalContext(value); + if (!additionalContext) return ''; + + return JSON.stringify({ + hookSpecificOutput: { + hookEventName: 'PreToolUse', + additionalContext, + }, + }); +} + +module.exports = { + buildPreToolUseAdditionalContext, + combineAdditionalContext, + normalizeAdditionalContext, +}; diff --git a/github_code/affaan-m__ECC/scripts/hooks/quality-gate.js b/github_code/affaan-m__ECC/scripts/hooks/quality-gate.js new file mode 100644 index 0000000000000000000000000000000000000000..37373b87cd13111b4fadd1a15c101977d1cb6ecc --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/hooks/quality-gate.js @@ -0,0 +1,168 @@ +#!/usr/bin/env node +/** + * Quality Gate Hook + * + * Runs lightweight quality checks after file edits. + * - Targets one file when file_path is provided + * - Falls back to no-op when language/tooling is unavailable + * + * For JS/TS files with Biome, this hook is skipped because + * post-edit-format.js already runs `biome check --write`. + * This hook still handles .json/.md files for Biome, and all + * Prettier / Go / Python checks. + */ + +'use strict'; + +const fs = require('fs'); +const path = require('path'); +const { spawnSync } = require('child_process'); + +const { findProjectRoot, detectFormatter, resolveFormatterBin } = require('../lib/resolve-formatter'); + +const MAX_STDIN = 1024 * 1024; + +/** + * Execute a command synchronously, returning the spawnSync result. + * + * @param {string} command - Executable path or name + * @param {string[]} args - Arguments to pass + * @param {string} [cwd] - Working directory (defaults to process.cwd()) + * @returns {import('child_process').SpawnSyncReturns} + */ +function exec(command, args, cwd = process.cwd()) { + return spawnSync(command, args, { + cwd, + encoding: 'utf8', + env: process.env, + timeout: 15000 + }); +} + +/** + * Write a message to stderr for logging. + * + * @param {string} msg - Message to log + */ +function log(msg) { + process.stderr.write(`${msg}\n`); +} + +/** + * Run quality-gate checks for a single file based on its extension. + * Skips JS/TS files when Biome is configured (handled by post-edit-format). + * + * @param {string} filePath - Path to the edited file + */ +function maybeRunQualityGate(filePath) { + if (!filePath || !fs.existsSync(filePath)) { + return; + } + + // Resolve to absolute path so projectRoot-relative comparisons work + filePath = path.resolve(filePath); + + const ext = path.extname(filePath).toLowerCase(); + const fix = String(process.env.ECC_QUALITY_GATE_FIX || '').toLowerCase() === 'true'; + const strict = String(process.env.ECC_QUALITY_GATE_STRICT || '').toLowerCase() === 'true'; + + if (['.ts', '.tsx', '.js', '.jsx', '.json', '.md'].includes(ext)) { + const projectRoot = findProjectRoot(path.dirname(filePath)); + const formatter = detectFormatter(projectRoot); + + if (formatter === 'biome') { + // JS/TS already handled by post-edit-format via `biome check --write` + if (['.ts', '.tsx', '.js', '.jsx'].includes(ext)) { + return; + } + + // .json / .md — still need quality gate + const resolved = resolveFormatterBin(projectRoot, 'biome'); + if (!resolved) return; + const args = [...resolved.prefix, 'check', filePath]; + if (fix) args.push('--write'); + const result = exec(resolved.bin, args, projectRoot); + if (result.status !== 0 && strict) { + log(`[QualityGate] Biome check failed for ${filePath}`); + } + return; + } + + if (formatter === 'prettier') { + const resolved = resolveFormatterBin(projectRoot, 'prettier'); + if (!resolved) return; + const args = [...resolved.prefix, fix ? '--write' : '--check', filePath]; + const result = exec(resolved.bin, args, projectRoot); + if (result.status !== 0 && strict) { + log(`[QualityGate] Prettier check failed for ${filePath}`); + } + return; + } + + // No formatter configured — skip + return; + } + + if (ext === '.go') { + if (fix) { + const r = exec('gofmt', ['-w', filePath]); + if (r.status !== 0 && strict) { + log(`[QualityGate] gofmt failed for ${filePath}`); + } + } else if (strict) { + const r = exec('gofmt', ['-l', filePath]); + if (r.status !== 0) { + log(`[QualityGate] gofmt failed for ${filePath}`); + } else if (r.stdout && r.stdout.trim()) { + log(`[QualityGate] gofmt check failed for ${filePath}`); + } + } + return; + } + + if (ext === '.py') { + const args = ['format']; + if (!fix) args.push('--check'); + args.push(filePath); + const r = exec('ruff', args); + if (r.status !== 0 && strict) { + log(`[QualityGate] Ruff check failed for ${filePath}`); + } + } +} + +/** + * Core logic — exported so run-with-flags.js can call directly. + * + * @param {string} rawInput - Raw JSON string from stdin + * @returns {string} The original input (pass-through) + */ +function run(rawInput) { + try { + const input = JSON.parse(rawInput); + const filePath = String(input.tool_input?.file_path || ''); + maybeRunQualityGate(filePath); + } catch { + // Ignore parse errors. + } + return rawInput; +} + +// ── stdin entry point (backwards-compatible) ──────────────────── +if (require.main === module) { + let raw = ''; + process.stdin.setEncoding('utf8'); + process.stdin.on('data', chunk => { + if (raw.length < MAX_STDIN) { + const remaining = MAX_STDIN - raw.length; + raw += chunk.substring(0, remaining); + } + }); + + process.stdin.on('end', () => { + const result = run(raw); + process.stdout.write(result); + }); +} + +module.exports = { run }; diff --git a/github_code/affaan-m__ECC/scripts/hooks/run-with-flags-shell.sh b/github_code/affaan-m__ECC/scripts/hooks/run-with-flags-shell.sh new file mode 100644 index 0000000000000000000000000000000000000000..227b8fc7b06b0ba5e2fa4dce53b2b4ae0f6b1d14 --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/hooks/run-with-flags-shell.sh @@ -0,0 +1,36 @@ +#!/usr/bin/env bash +set -euo pipefail + +HOOK_ID="${1:-}" +REL_SCRIPT_PATH="${2:-}" +PROFILES_CSV="${3:-standard,strict}" +SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" +PLUGIN_ROOT="${CLAUDE_PLUGIN_ROOT:-$(cd "${SCRIPT_DIR}/../.." && pwd)}" + +# Preserve stdin for passthrough or script execution +INPUT="$(cat)" + +if [[ -z "$HOOK_ID" || -z "$REL_SCRIPT_PATH" ]]; then + printf '%s' "$INPUT" + exit 0 +fi + +# Ask Node helper if this hook is enabled +ENABLED="$(node "${PLUGIN_ROOT}/scripts/hooks/check-hook-enabled.js" "$HOOK_ID" "$PROFILES_CSV" 2>/dev/null || echo yes)" +if [[ "$ENABLED" != "yes" ]]; then + printf '%s' "$INPUT" + exit 0 +fi + +SCRIPT_PATH="${PLUGIN_ROOT}/${REL_SCRIPT_PATH}" +if [[ ! -f "$SCRIPT_PATH" ]]; then + echo "[Hook] Script not found for ${HOOK_ID}: ${SCRIPT_PATH}" >&2 + printf '%s' "$INPUT" + exit 0 +fi + +# Extract phase prefix from hook ID (e.g., "pre:observe" -> "pre", "post:observe" -> "post") +# This is needed by scripts like observe.sh that behave differently for PreToolUse vs PostToolUse +HOOK_PHASE="${HOOK_ID%%:*}" + +printf '%s' "$INPUT" | "$SCRIPT_PATH" "$HOOK_PHASE" diff --git a/github_code/affaan-m__ECC/scripts/hooks/run-with-flags.js b/github_code/affaan-m__ECC/scripts/hooks/run-with-flags.js new file mode 100644 index 0000000000000000000000000000000000000000..9f6de372212d5c3ba20502b5e05711431f1a0053 --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/hooks/run-with-flags.js @@ -0,0 +1,275 @@ +#!/usr/bin/env node +/** + * Executes a hook script only when enabled by ECC hook profile flags. + * + * Usage: + * node run-with-flags.js [profilesCsv] + */ + +'use strict'; + +const fs = require('fs'); +const path = require('path'); +const { spawnSync } = require('child_process'); +const { isHookEnabled, isDryRun } = require('../lib/hook-flags'); +const { buildPreToolUseAdditionalContext } = require('./pretooluse-visible-output'); + +const MAX_STDIN = 1024 * 1024; + +function readStdinRaw() { + return new Promise(resolve => { + let raw = ''; + let truncated = false; + process.stdin.setEncoding('utf8'); + process.stdin.on('data', chunk => { + if (raw.length < MAX_STDIN) { + const remaining = MAX_STDIN - raw.length; + raw += chunk.substring(0, remaining); + if (chunk.length > remaining) { + truncated = true; + } + } else { + truncated = true; + } + }); + process.stdin.on('end', () => resolve({ raw, truncated })); + process.stdin.on('error', () => resolve({ raw, truncated })); + }); +} + +function writeStderr(stderr) { + if (typeof stderr !== 'string' || stderr.length === 0) { + return; + } + + process.stderr.write(stderr.endsWith('\n') ? stderr : `${stderr}\n`); +} + +/** + * Exit only after stdout and any previously queued stderr have drained. + * `process.exit()` immediately after a stream write drops anything beyond + * the OS pipe buffer, which cut large hook output mid-payload and made the + * harness treat the hook as failed (#2222). + */ +function exitWithStdout(text, exitCode) { + process.exitCode = exitCode; + let pendingWrites = 1; + const exitWhenFlushed = () => { + pendingWrites -= 1; + if (pendingWrites === 0) { + process.exit(exitCode); + } + }; + + if (typeof text === 'string' && text.length > 0) { + pendingWrites += 1; + process.stdout.write(text, exitWhenFlushed); + } + process.stderr.write('', exitWhenFlushed); +} + +function resolveHookResult(raw, output) { + if (typeof output === 'string' || Buffer.isBuffer(output)) { + return { stdout: String(output), exitCode: 0 }; + } + + if (output && typeof output === 'object') { + writeStderr(output.stderr); + const exitCode = Number.isInteger(output.exitCode) ? output.exitCode : 0; + + if (Object.prototype.hasOwnProperty.call(output, 'additionalContext')) { + return { stdout: buildPreToolUseAdditionalContext(output.additionalContext), exitCode }; + } + if (Object.prototype.hasOwnProperty.call(output, 'stdout')) { + return { stdout: String(output.stdout ?? ''), exitCode }; + } + return { stdout: exitCode === 0 ? raw : '', exitCode }; + } + + return { stdout: raw, exitCode: 0 }; +} + +function resolveLegacySpawnStdout(raw, result) { + const stdout = typeof result.stdout === 'string' ? result.stdout : ''; + if (stdout) { + return stdout; + } + + if (Number.isInteger(result.status) && result.status === 0) { + return raw; + } + + return ''; +} + +function getPluginRoot() { + if (process.env.CLAUDE_PLUGIN_ROOT && process.env.CLAUDE_PLUGIN_ROOT.trim()) { + return process.env.CLAUDE_PLUGIN_ROOT; + } + return path.resolve(__dirname, '..', '..'); +} + +//Safely extract target context from hook stdin JSON for dry-run preview. + +function extractTargetContext(raw) { + const result = { tool: '', filePath: '', command: '' }; + if (!raw || typeof raw !== 'string') return result; + + try { + const payload = JSON.parse(raw); + if (payload && typeof payload === 'object') { + result.tool = String(payload.tool || ''); + const input = payload.tool_input; + if (input && typeof input === 'object') { + result.filePath = String(input.file_path || input.path || ''); + result.command = String(input.command || ''); + } + } + } catch { + // best-effort field extraction; ignore malformed input + } + return result; +} + +// Build the [DryRun] preview line for stderr. + +function buildDryRunPreview(hookId, relScriptPath, profilesCsv, raw) { + const ctx = extractTargetContext(raw); + const parts = [`[DryRun] Hook "${hookId}" would execute: ${relScriptPath}`, `(enabled=true, profiles=${profilesCsv || 'default'})`]; + + if (ctx.tool) { + parts.push(`tool=${ctx.tool}`); + } + if (ctx.filePath) { + parts.push(`target=${ctx.filePath}`); + } + if (ctx.command) { + parts.push(`command=${ctx.command}`); + } + + return parts.join(' ') + '\n'; +} + +async function main() { + const [, , hookId, relScriptPath, profilesCsv] = process.argv; + const { raw, truncated } = await readStdinRaw(); + + // Oversized payloads: never echo the truncated string — a JSON document + // cut mid-stream is treated by the harness as a hook failure, blocking the + // tool call (#2222). Empty stdout + exit 0 means "no opinion", so + // pass-through paths fail open. The hook itself still runs and receives + // the truncated flag (run() context / ECC_HOOK_INPUT_TRUNCATED), so + // security hooks like config-protection can still choose to block. + const sanitizeEcho = text => (truncated && text === raw ? '' : text); + if (truncated) { + process.stderr.write(`[Hook] stdin exceeded ${MAX_STDIN} bytes for ${hookId || 'unknown'}; suppressing pass-through (fail-open unless the hook blocks)\n`); + } + + if (!hookId || !relScriptPath) { + exitWithStdout(sanitizeEcho(raw), 0); + return; + } + + if (!isHookEnabled(hookId, { profiles: profilesCsv })) { + exitWithStdout(sanitizeEcho(raw), 0); + return; + } + + if (isDryRun()) { + const preview = buildDryRunPreview(hookId, relScriptPath, profilesCsv, raw); + process.stderr.write(preview); + exitWithStdout(sanitizeEcho(raw), 0); + return; + } + + const pluginRoot = getPluginRoot(); + const resolvedRoot = path.resolve(pluginRoot); + const scriptPath = path.resolve(pluginRoot, relScriptPath); + + // Prevent path traversal outside the plugin root + if (!scriptPath.startsWith(resolvedRoot + path.sep)) { + process.stderr.write(`[Hook] Path traversal rejected for ${hookId}: ${scriptPath}\n`); + exitWithStdout(sanitizeEcho(raw), 0); + return; + } + + if (!fs.existsSync(scriptPath)) { + process.stderr.write(`[Hook] Script not found for ${hookId}: ${scriptPath}\n`); + exitWithStdout(sanitizeEcho(raw), 0); + return; + } + + // Prefer direct require() when the hook exports a run(rawInput) function. + // This eliminates one Node.js process spawn (~50-100ms savings per hook). + // + // SAFETY: Only require() hooks that export run(). Legacy hooks execute + // side effects at module scope (stdin listeners, process.exit, main() calls) + // which would interfere with the parent process or cause double execution. + let hookModule; + const src = fs.readFileSync(scriptPath, 'utf8'); + const hasRunExport = /\bmodule\.exports\b/.test(src) && /\brun\b/.test(src); + + if (hasRunExport) { + try { + hookModule = require(scriptPath); + } catch (requireErr) { + process.stderr.write(`[Hook] require() failed for ${hookId}: ${requireErr.message}\n`); + // Fall through to legacy spawnSync path + } + } + + if (hookModule && typeof hookModule.run === 'function') { + try { + // Awaited so a hook may export `async run()`. Without this an async hook + // hands back a pending Promise, which resolveHookResult reads as "no + // opinion" and silently degrades to pass-through. Synchronous hooks are + // unaffected: awaiting a plain value just costs a microtask. + const output = await hookModule.run(raw, { + hookId, + pluginRoot, + scriptPath, + truncated, + maxStdin: MAX_STDIN + }); + const result = resolveHookResult(raw, output); + exitWithStdout(sanitizeEcho(result.stdout), result.exitCode); + } catch (runErr) { + process.stderr.write(`[Hook] run() error for ${hookId}: ${runErr.message}\n`); + exitWithStdout(sanitizeEcho(raw), 0); + } + return; + } + + // Legacy path: spawn a child Node process for hooks without run() export + const result = spawnSync(process.execPath, [scriptPath], { + input: raw, + encoding: 'utf8', + env: { + ...process.env, + CLAUDE_PLUGIN_ROOT: pluginRoot, + ECC_PLUGIN_ROOT: pluginRoot, + ECC_HOOK_ID: hookId, + ECC_HOOK_INPUT_TRUNCATED: truncated ? '1' : '0', + ECC_HOOK_INPUT_MAX_BYTES: String(MAX_STDIN) + }, + cwd: process.cwd(), + timeout: 30000 + }); + + const legacyStdout = sanitizeEcho(resolveLegacySpawnStdout(raw, result)); + if (result.stderr) process.stderr.write(result.stderr); + + if (result.error || result.signal || result.status === null) { + const failureDetail = result.error ? result.error.message : result.signal ? `terminated by signal ${result.signal}` : 'missing exit status'; + writeStderr(`[Hook] legacy hook execution failed for ${hookId}: ${failureDetail}`); + exitWithStdout(legacyStdout, 1); + return; + } + + exitWithStdout(legacyStdout, Number.isInteger(result.status) ? result.status : 0); +} + +main().catch(err => { + process.stderr.write(`[Hook] run-with-flags error: ${err.message}\n`); + process.exit(0); +}); diff --git a/github_code/affaan-m__ECC/scripts/hooks/session-activity-tracker.js b/github_code/affaan-m__ECC/scripts/hooks/session-activity-tracker.js new file mode 100644 index 0000000000000000000000000000000000000000..43e5b7afeafe4ccb4dc02fe57483b20e4a7ee463 --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/hooks/session-activity-tracker.js @@ -0,0 +1,639 @@ +#!/usr/bin/env node +/** + * Session Activity Tracker Hook + * + * PostToolUse hook that records sanitized per-tool activity to + * ~/.claude/metrics/tool-usage.jsonl for ECC2 metric sync. + */ + +'use strict'; + +const crypto = require('crypto'); +const path = require('path'); +const { spawnSync } = require('child_process'); +const { + appendFile, + getClaudeDir, + stripAnsi, +} = require('../lib/utils'); + +const MAX_STDIN = 1024 * 1024; +const METRICS_FILE_NAME = 'tool-usage.jsonl'; +const FILE_PATH_KEYS = new Set([ + 'file_path', + 'file_paths', + 'source_path', + 'destination_path', + 'old_file_path', + 'new_file_path', +]); + +function redactSecrets(value) { + return String(value || '') + .replace(/\n/g, ' ') + .replace(/--token[= ][^ ]*/g, '--token=') + .replace(/Authorization:[: ]*[^ ]*[: ]*[^ ]*/gi, 'Authorization:') + .replace(/\bAKIA[A-Z0-9]{16}\b/g, '') + .replace(/\bASIA[A-Z0-9]{16}\b/g, '') + .replace(/password[= ][^ ]*/gi, 'password=') + .replace(/\bghp_[A-Za-z0-9_]+\b/g, '') + .replace(/\bgho_[A-Za-z0-9_]+\b/g, '') + .replace(/\bghs_[A-Za-z0-9_]+\b/g, '') + .replace(/\bgithub_pat_[A-Za-z0-9_]+\b/g, ''); +} + +function truncateSummary(value, maxLength = 220) { + const normalized = stripAnsi(redactSecrets(value)).trim().replace(/\s+/g, ' '); + if (normalized.length <= maxLength) { + return normalized; + } + return `${normalized.slice(0, maxLength - 3)}...`; +} + +function sanitizeParamValue(value, depth = 0) { + if (depth >= 4) { + return '[Truncated]'; + } + + if (value === null || value === undefined) { + return value; + } + + if (typeof value === 'string') { + return truncateSummary(value, 160); + } + + if (typeof value === 'number' || typeof value === 'boolean') { + return value; + } + + if (Array.isArray(value)) { + return value.slice(0, 8).map(entry => sanitizeParamValue(entry, depth + 1)); + } + + if (typeof value === 'object') { + const output = {}; + for (const [key, nested] of Object.entries(value).slice(0, 20)) { + output[key] = sanitizeParamValue(nested, depth + 1); + } + return output; + } + + return truncateSummary(String(value), 160); +} + +function sanitizeInputParams(toolInput) { + if (!toolInput || typeof toolInput !== 'object' || Array.isArray(toolInput)) { + return '{}'; + } + + try { + return JSON.stringify(sanitizeParamValue(toolInput)); + } catch { + return '{}'; + } +} + +function pushPathCandidate(paths, value) { + const candidate = String(value || '').trim(); + if (!candidate) { + return; + } + if (/^(https?:\/\/|app:\/\/|plugin:\/\/|mcp:\/\/)/i.test(candidate)) { + return; + } + if (!paths.includes(candidate)) { + paths.push(candidate); + } +} + +function pushFileEvent(events, value, action, diffPreview, patchPreview) { + const candidate = String(value || '').trim(); + if (!candidate) { + return; + } + if (/^(https?:\/\/|app:\/\/|plugin:\/\/|mcp:\/\/)/i.test(candidate)) { + return; + } + const normalizedDiffPreview = typeof diffPreview === 'string' && diffPreview.trim() + ? diffPreview.trim() + : undefined; + const normalizedPatchPreview = typeof patchPreview === 'string' && patchPreview.trim() + ? patchPreview.trim() + : undefined; + if (!events.some(event => + event.path === candidate + && event.action === action + && (event.diff_preview || undefined) === normalizedDiffPreview + && (event.patch_preview || undefined) === normalizedPatchPreview + )) { + const event = { path: candidate, action }; + if (normalizedDiffPreview) { + event.diff_preview = normalizedDiffPreview; + } + if (normalizedPatchPreview) { + event.patch_preview = normalizedPatchPreview; + } + events.push(event); + } +} + +function sanitizeDiffText(value, maxLength = 96) { + if (typeof value !== 'string' || !value.trim()) { + return ''; + } + return truncateSummary(value, maxLength); +} + +function sanitizePatchLines(value, maxLines = 4, maxLineLength = 120) { + if (typeof value !== 'string' || !value.trim()) { + return []; + } + + return stripAnsi(redactSecrets(value)) + .split(/\r?\n/) + .map(line => line.trim()) + .filter(Boolean) + .slice(0, maxLines) + .map(line => line.length <= maxLineLength ? line : `${line.slice(0, maxLineLength - 3)}...`); +} + +function buildReplacementPreview(oldValue, newValue) { + const before = sanitizeDiffText(oldValue); + const after = sanitizeDiffText(newValue); + if (!before && !after) { + return undefined; + } + if (!before) { + return `-> ${after}`; + } + if (!after) { + return `${before} ->`; + } + return `${before} -> ${after}`; +} + +function buildCreationPreview(content) { + const normalized = sanitizeDiffText(content); + if (!normalized) { + return undefined; + } + return `+ ${normalized}`; +} + +function buildPatchPreviewFromReplacement(oldValue, newValue) { + const beforeLines = sanitizePatchLines(oldValue); + const afterLines = sanitizePatchLines(newValue); + if (beforeLines.length === 0 && afterLines.length === 0) { + return undefined; + } + + const lines = ['@@']; + for (const line of beforeLines) { + lines.push(`- ${line}`); + } + for (const line of afterLines) { + lines.push(`+ ${line}`); + } + return lines.join('\n'); +} + +function buildPatchPreviewFromContent(content, prefix) { + const lines = sanitizePatchLines(content); + if (lines.length === 0) { + return undefined; + } + return lines.map(line => `${prefix} ${line}`).join('\n'); +} + +function buildDiffPreviewFromPatchPreview(patchPreview) { + if (typeof patchPreview !== 'string' || !patchPreview.trim()) { + return undefined; + } + + const lines = patchPreview + .split(/\r?\n/) + .map(line => line.trim()) + .filter(Boolean); + const removed = lines.find(line => line.startsWith('- ') || line.startsWith('-')); + const added = lines.find(line => line.startsWith('+ ') || line.startsWith('+')); + + if (!removed && !added) { + return undefined; + } + + const before = removed ? removed.replace(/^- ?/, '') : ''; + const after = added ? added.replace(/^\+ ?/, '') : ''; + if (before && after) { + return `${before} -> ${after}`; + } + if (before) { + return `${before} ->`; + } + return `-> ${after}`; +} + +function inferDefaultFileAction(toolName) { + const normalized = String(toolName || '').trim().toLowerCase(); + if (normalized.includes('read')) { + return 'read'; + } + if (normalized.includes('write')) { + return 'create'; + } + if (normalized.includes('edit')) { + return 'modify'; + } + if (normalized.includes('delete') || normalized.includes('remove')) { + return 'delete'; + } + if (normalized.includes('move') || normalized.includes('rename')) { + return 'move'; + } + return 'touch'; +} + +function actionForFileKey(toolName, key) { + if (key === 'source_path' || key === 'old_file_path') { + return 'move'; + } + if (key === 'destination_path' || key === 'new_file_path') { + return 'move'; + } + return inferDefaultFileAction(toolName); +} + +function collectFilePaths(value, paths) { + if (!value) { + return; + } + + if (Array.isArray(value)) { + for (const entry of value) { + collectFilePaths(entry, paths); + } + return; + } + + if (typeof value === 'string') { + pushPathCandidate(paths, value); + return; + } + + if (typeof value !== 'object') { + return; + } + + for (const [key, nested] of Object.entries(value)) { + if (FILE_PATH_KEYS.has(key)) { + collectFilePaths(nested, paths); + continue; + } + + if (nested && (Array.isArray(nested) || typeof nested === 'object')) { + collectFilePaths(nested, paths); + } + } +} + +function extractFilePaths(toolInput) { + const paths = []; + if (!toolInput || typeof toolInput !== 'object') { + return paths; + } + collectFilePaths(toolInput, paths); + return paths; +} + +function fileEventDiffPreview(toolName, value, action) { + if (!value || typeof value !== 'object' || Array.isArray(value)) { + return undefined; + } + + if (typeof value.old_string === 'string' || typeof value.new_string === 'string') { + return buildReplacementPreview(value.old_string, value.new_string); + } + + if (action === 'create') { + return buildCreationPreview(value.content || value.file_text || value.text); + } + + return undefined; +} + +function fileEventPatchPreview(value, action) { + if (!value || typeof value !== 'object' || Array.isArray(value)) { + return undefined; + } + + if (typeof value.old_string === 'string' || typeof value.new_string === 'string') { + return buildPatchPreviewFromReplacement(value.old_string, value.new_string); + } + + if (action === 'create') { + return buildPatchPreviewFromContent(value.content || value.file_text || value.text, '+'); + } + + if (action === 'delete') { + return buildPatchPreviewFromContent(value.content || value.old_string || value.file_text, '-'); + } + + return undefined; +} + +function runGit(args, cwd) { + const result = spawnSync('git', args, { + cwd, + encoding: 'utf8', + timeout: 2500, + }); + + if (result.error || result.status !== 0) { + return null; + } + + return String(result.stdout || '').trim(); +} + +function gitRepoRoot(cwd) { + return runGit(['rev-parse', '--show-toplevel'], cwd); +} + +const MAX_RELEVANT_PATCH_LINES = 6; + +function candidateGitPaths(repoRoot, filePath) { + const resolvedRepoRoot = path.resolve(repoRoot); + const candidates = []; + const pushCandidate = value => { + const candidate = String(value || '').trim(); + if (!candidate || candidates.includes(candidate)) { + return; + } + candidates.push(candidate); + }; + + const absoluteCandidates = path.isAbsolute(filePath) + ? [path.resolve(filePath)] + : [ + path.resolve(resolvedRepoRoot, filePath), + path.resolve(process.cwd(), filePath), + ]; + + for (const absolute of absoluteCandidates) { + const relative = path.relative(resolvedRepoRoot, absolute); + if (!relative || relative.startsWith('..') || path.isAbsolute(relative)) { + continue; + } + + pushCandidate(relative); + pushCandidate(relative.split(path.sep).join('/')); + pushCandidate(absolute); + pushCandidate(absolute.split(path.sep).join('/')); + } + + return candidates; +} + +function patchPreviewFromGitDiff(repoRoot, pathCandidates) { + for (const candidate of pathCandidates) { + const patch = runGit( + ['diff', '--no-ext-diff', '--no-color', '--unified=1', '--', candidate], + repoRoot + ); + if (!patch) { + continue; + } + + const relevant = patch + .split(/\r?\n/) + .filter(line => + line.startsWith('@@') + || (line.startsWith('+') && !line.startsWith('+++')) + || (line.startsWith('-') && !line.startsWith('---')) + ) + .slice(0, MAX_RELEVANT_PATCH_LINES); + + if (relevant.length > 0) { + return relevant.join('\n'); + } + } + + return undefined; +} + +function trackedInGit(repoRoot, pathCandidates) { + return pathCandidates.some(candidate => + runGit(['ls-files', '--error-unmatch', '--', candidate], repoRoot) !== null + ); +} + +function enrichFileEventFromWorkingTree(toolName, event) { + if (!event || typeof event !== 'object' || !event.path) { + return event; + } + + const repoRoot = gitRepoRoot(process.cwd()); + if (!repoRoot) { + return event; + } + + const pathCandidates = candidateGitPaths(repoRoot, event.path); + if (pathCandidates.length === 0) { + return event; + } + + const tool = String(toolName || '').trim().toLowerCase(); + const tracked = trackedInGit(repoRoot, pathCandidates); + const patchPreview = patchPreviewFromGitDiff(repoRoot, pathCandidates) || event.patch_preview; + const diffPreview = buildDiffPreviewFromPatchPreview(patchPreview) || event.diff_preview; + + if (tool.includes('write')) { + return { + ...event, + action: tracked ? 'modify' : event.action, + diff_preview: diffPreview, + patch_preview: patchPreview, + }; + } + + if (tracked && patchPreview) { + return { + ...event, + diff_preview: diffPreview, + patch_preview: patchPreview, + }; + } + + return event; +} + +function collectFileEvents(toolName, value, events, key = null, parentValue = null) { + if (!value) { + return; + } + + if (Array.isArray(value)) { + for (const entry of value) { + collectFileEvents(toolName, entry, events, key, parentValue); + } + return; + } + + if (typeof value === 'string') { + if (key && FILE_PATH_KEYS.has(key)) { + const action = actionForFileKey(toolName, key); + pushFileEvent( + events, + value, + action, + fileEventDiffPreview(toolName, parentValue, action), + fileEventPatchPreview(parentValue, action) + ); + } + return; + } + + if (typeof value !== 'object') { + return; + } + + for (const [nestedKey, nested] of Object.entries(value)) { + if (FILE_PATH_KEYS.has(nestedKey)) { + collectFileEvents(toolName, nested, events, nestedKey, value); + continue; + } + + if (nested && (Array.isArray(nested) || typeof nested === 'object')) { + collectFileEvents(toolName, nested, events, null, nested); + } + } +} + +function extractFileEvents(toolName, toolInput) { + const events = []; + if (!toolInput || typeof toolInput !== 'object') { + return events; + } + collectFileEvents(toolName, toolInput, events); + return events; +} + +function summarizeInput(toolName, toolInput, filePaths) { + if (toolName === 'Bash') { + return truncateSummary(toolInput?.command || 'bash'); + } + + if (filePaths.length > 0) { + return truncateSummary(`${toolName} ${filePaths.join(', ')}`); + } + + if (toolInput && typeof toolInput === 'object') { + const shallow = {}; + for (const [key, value] of Object.entries(toolInput)) { + if (value === null || value === undefined) { + continue; + } + if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { + shallow[key] = value; + } + } + const serialized = Object.keys(shallow).length > 0 ? JSON.stringify(shallow) : toolName; + return truncateSummary(serialized); + } + + return truncateSummary(toolName); +} + +function summarizeOutput(toolOutput) { + if (toolOutput === null || toolOutput === undefined) { + return ''; + } + + if (typeof toolOutput === 'string') { + return truncateSummary(toolOutput); + } + + if (typeof toolOutput === 'object' && typeof toolOutput.output === 'string') { + return truncateSummary(toolOutput.output); + } + + return truncateSummary(JSON.stringify(toolOutput)); +} + +function buildActivityRow(input, env = process.env) { + const hookEvent = String(env.CLAUDE_HOOK_EVENT_NAME || '').trim(); + if (hookEvent && hookEvent !== 'PostToolUse') { + return null; + } + + const toolName = String(input?.tool_name || '').trim(); + const sessionId = String(env.ECC_SESSION_ID || env.CLAUDE_SESSION_ID || '').trim(); + if (!toolName || !sessionId) { + return null; + } + + const toolInput = input?.tool_input || {}; + const fileEvents = extractFileEvents(toolName, toolInput).map(event => + enrichFileEventFromWorkingTree(toolName, event) + ); + const filePaths = fileEvents.length > 0 + ? [...new Set(fileEvents.map(event => event.path))] + : extractFilePaths(toolInput); + + return { + id: `tool-${Date.now()}-${crypto.randomBytes(6).toString('hex')}`, + timestamp: new Date().toISOString(), + session_id: sessionId, + tool_name: toolName, + input_summary: summarizeInput(toolName, toolInput, filePaths), + input_params_json: sanitizeInputParams(toolInput), + output_summary: summarizeOutput(input?.tool_output), + duration_ms: 0, + file_paths: filePaths, + file_events: fileEvents, + }; +} + +function run(rawInput) { + try { + const input = rawInput.trim() ? JSON.parse(rawInput) : {}; + const row = buildActivityRow(input); + if (row) { + appendFile( + path.join(getClaudeDir(), 'metrics', METRICS_FILE_NAME), + `${JSON.stringify(row)}\n` + ); + } + } catch { + // Keep hook non-blocking. + } + + return rawInput; +} + +function main() { + let raw = ''; + process.stdin.setEncoding('utf8'); + process.stdin.on('data', chunk => { + if (raw.length < MAX_STDIN) { + const remaining = MAX_STDIN - raw.length; + raw += chunk.substring(0, remaining); + } + }); + process.stdin.on('end', () => { + process.stdout.write(run(raw)); + }); +} + +if (require.main === module) { + main(); +} + +module.exports = { + buildActivityRow, + extractFileEvents, + extractFilePaths, + summarizeInput, + summarizeOutput, + run, +}; diff --git a/github_code/affaan-m__ECC/scripts/hooks/session-end-marker.js b/github_code/affaan-m__ECC/scripts/hooks/session-end-marker.js new file mode 100644 index 0000000000000000000000000000000000000000..7b27a8eb32ff10cafce693acc175f575d4de710d --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/hooks/session-end-marker.js @@ -0,0 +1,67 @@ +#!/usr/bin/env node +'use strict'; + +/** + * Session end marker hook - performs lightweight observer cleanup and + * outputs stdin to stdout unchanged. Exports run() for in-process execution. + */ + +const { + resolveProjectContext, + removeSessionLease, + listSessionLeases, + stopObserverForContext, + resolveSessionId +} = require('../lib/observer-sessions'); + +function log(message) { + process.stderr.write(`[SessionEnd] ${message}\n`); +} + +function run(rawInput) { + const output = rawInput || ''; + const sessionId = resolveSessionId(); + + if (!sessionId) { + log('No CLAUDE_SESSION_ID available; skipping observer cleanup'); + return output; + } + + try { + const observerContext = resolveProjectContext(); + removeSessionLease(observerContext, sessionId); + const remainingLeases = listSessionLeases(observerContext); + + if (remainingLeases.length === 0) { + if (stopObserverForContext(observerContext)) { + log(`Stopped observer for project ${observerContext.projectId} after final session lease ended`); + } else { + log(`No running observer to stop for project ${observerContext.projectId}`); + } + } else { + log(`Retained observer for project ${observerContext.projectId}; ${remainingLeases.length} session lease(s) remain`); + } + } catch (err) { + log(`Observer cleanup skipped: ${err.message}`); + } + + return output; +} + +// Legacy CLI execution (when run directly) +if (require.main === module) { + const MAX_STDIN = 1024 * 1024; + let raw = ''; + process.stdin.setEncoding('utf8'); + process.stdin.on('data', chunk => { + if (raw.length < MAX_STDIN) { + const remaining = MAX_STDIN - raw.length; + raw += chunk.substring(0, remaining); + } + }); + process.stdin.on('end', () => { + process.stdout.write(run(raw)); + }); +} + +module.exports = { run }; diff --git a/github_code/affaan-m__ECC/scripts/hooks/session-end.js b/github_code/affaan-m__ECC/scripts/hooks/session-end.js new file mode 100644 index 0000000000000000000000000000000000000000..9709aa95a65ef10db1b18173565ca35fcc1ccb21 --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/hooks/session-end.js @@ -0,0 +1,355 @@ +#!/usr/bin/env node +/** + * Stop Hook (Session End) - Persist learnings during active sessions + * + * Cross-platform (Windows, macOS, Linux) + * + * Runs on Stop events (after each response). Extracts a meaningful summary + * from the session transcript (via stdin JSON transcript_path) and updates a + * session file for cross-session continuity. + */ + +const path = require('path'); +const fs = require('fs'); +const { getSessionsDir, getDateString, getTimeString, getSessionIdShort, sanitizeSessionId, getProjectName, ensureDir, readFile, writeFile, runCommand, stripAnsi, log } = require('../lib/utils'); +const { generateSessionSummary, getContextRemainingPct, getContextThreshold } = require('../lib/llm-summary'); + +const SUMMARY_START_MARKER = ''; +const SUMMARY_END_MARKER = ''; +const SESSION_SEPARATOR = '\n---\n'; + +/** + * Extract a meaningful summary from the session transcript. + * Reads the JSONL transcript and pulls out key information: + * - User messages (tasks requested) + * - Tools used + * - Files modified + */ +function extractSessionSummary(transcriptPath) { + const content = readFile(transcriptPath); + if (!content) return null; + + const lines = content.split('\n').filter(Boolean); + const userMessages = []; + const toolsUsed = new Set(); + const filesModified = new Set(); + let parseErrors = 0; + + for (const line of lines) { + try { + const entry = JSON.parse(line); + + // Collect user messages (first 200 chars each) + if (entry.type === 'user' || entry.role === 'user' || entry.message?.role === 'user') { + // Support both direct content and nested message.content (Claude Code JSONL format) + const rawContent = entry.message?.content ?? entry.content; + // Skip tool_result carrier turns — they are not user asks. + const isToolResult = Array.isArray(rawContent) && rawContent.some(c => c && c.type === 'tool_result'); + const text = typeof rawContent === 'string' ? rawContent : Array.isArray(rawContent) ? rawContent.map(c => (c && c.text) || '').join(' ') : ''; + const cleaned = stripAnsi(text).trim(); + // Skip harness noise: local command echoes, caveats, system reminders. + const isNoise = /^<(local-command-caveat|local-command-stdout|command-name|command-message|command-args|system-reminder|task-notification)/i.test(cleaned); + // `isMeta` is also used for genuine channel- and plugin-originated + // human prompts. Exclude known structured noise above instead of + // discarding every metadata-marked user turn. + if (cleaned && !isToolResult && !isNoise) { + userMessages.push(cleaned.slice(0, 200)); + } + } + + // Collect tool names and modified files (direct tool_use entries) + if (entry.type === 'tool_use' || entry.tool_name) { + const toolName = entry.tool_name || entry.name || ''; + if (toolName) toolsUsed.add(toolName); + + const filePath = entry.tool_input?.file_path || entry.input?.file_path || ''; + if (filePath && (toolName === 'Edit' || toolName === 'Write')) { + filesModified.add(filePath); + } + } + + // Extract tool uses from assistant message content blocks (Claude Code JSONL format) + if (entry.type === 'assistant' && Array.isArray(entry.message?.content)) { + for (const block of entry.message.content) { + if (block.type === 'tool_use') { + const toolName = block.name || ''; + if (toolName) toolsUsed.add(toolName); + + const filePath = block.input?.file_path || ''; + if (filePath && (toolName === 'Edit' || toolName === 'Write')) { + filesModified.add(filePath); + } + } + } + } + } catch { + parseErrors++; + } + } + + if (parseErrors > 0) { + log(`[SessionEnd] Skipped ${parseErrors}/${lines.length} unparseable transcript lines`); + } + + if (userMessages.length === 0) return null; + + return { + userMessages: userMessages.slice(-10), // Last 10 user messages + toolsUsed: Array.from(toolsUsed).slice(0, 20), + filesModified: Array.from(filesModified).slice(0, 30), + totalMessages: userMessages.length + }; +} + +// Read hook input from stdin (Claude Code provides transcript_path via stdin JSON) +const MAX_STDIN = 1024 * 1024; +let stdinData = ''; +process.stdin.setEncoding('utf8'); + +process.stdin.on('data', chunk => { + if (stdinData.length < MAX_STDIN) { + const remaining = MAX_STDIN - stdinData.length; + stdinData += chunk.substring(0, remaining); + } +}); + +process.stdin.on('end', () => { + runMain(); +}); + +function runMain() { + main().catch(err => { + console.error('[SessionEnd] Error:', err.message); + process.exit(0); + }); +} + +function getSessionMetadata() { + const branchResult = runCommand('git rev-parse --abbrev-ref HEAD'); + + return { + project: getProjectName() || 'unknown', + branch: branchResult.success ? branchResult.output : 'unknown', + worktree: process.cwd() + }; +} + +function extractHeaderField(header, label) { + const match = header.match(new RegExp(`\\*\\*${escapeRegExp(label)}:\\*\\*\\s*(.+)$`, 'm')); + return match ? match[1].trim() : null; +} + +function buildSessionHeader(today, currentTime, metadata, existingContent = '') { + const headingMatch = existingContent.match(/^#\s+.+$/m); + const heading = headingMatch ? headingMatch[0] : `# Session: ${today}`; + const date = extractHeaderField(existingContent, 'Date') || today; + const started = extractHeaderField(existingContent, 'Started') || currentTime; + + return [ + heading, + `**Date:** ${date}`, + `**Started:** ${started}`, + `**Last Updated:** ${currentTime}`, + `**Project:** ${metadata.project}`, + `**Branch:** ${metadata.branch}`, + `**Worktree:** ${metadata.worktree}`, + '' + ].join('\n'); +} + +function mergeSessionHeader(content, today, currentTime, metadata) { + const separatorIndex = content.indexOf(SESSION_SEPARATOR); + if (separatorIndex === -1) { + return null; + } + + const existingHeader = content.slice(0, separatorIndex); + const body = content.slice(separatorIndex + SESSION_SEPARATOR.length); + const nextHeader = buildSessionHeader(today, currentTime, metadata, existingHeader); + return `${nextHeader}${SESSION_SEPARATOR}${body}`; +} + +async function main() { + // Parse stdin JSON to get transcript_path; fall back to env var on missing, + // empty, or non-string values as well as on malformed JSON. + let transcriptPath = null; + try { + const input = JSON.parse(stdinData); + if (input && typeof input.transcript_path === 'string' && input.transcript_path.length > 0) { + transcriptPath = input.transcript_path; + } + } catch { + // Malformed stdin: fall through to the env-var fallback below. + } + if (!transcriptPath) { + const envTranscriptPath = process.env.CLAUDE_TRANSCRIPT_PATH; + if (typeof envTranscriptPath === 'string' && envTranscriptPath.length > 0) { + transcriptPath = envTranscriptPath; + } + } + + // ECC's LLM summary helper launches a one-shot Claude subprocess whose Stop + // hooks inherit this dedicated marker. Skip that known internal session + // before touching session state. Transcript cardinality is not a safe proxy: + // an ordinary user session may legitimately contain one prompt and no tools. + if (process.env.ECC_LLM_SUMMARY_SUBPROCESS === '1') { + log('[SessionEnd] Skipped ECC LLM summary subprocess'); + return; + } + + // Read known transcripts before resolving session metadata or touching the + // session directory. Missing, unreadable, or unparseable transcript data keeps + // the established fallback behavior because it cannot be classified reliably. + let summary = null; + let transcriptExists = false; + if (transcriptPath) { + transcriptExists = fs.existsSync(transcriptPath); + if (transcriptExists) { + summary = extractSessionSummary(transcriptPath); + } else { + log(`[SessionEnd] Transcript not found: ${transcriptPath}`); + } + } + + const sessionsDir = getSessionsDir(); + const today = getDateString(); + // Derive shortId from transcript_path UUID when available, using the SAME + // last-8-chars convention as getSessionIdShort(sessionId.slice(-8)). This keeps + // backward compatibility for normal sessions (the derived shortId matches what + // getSessionIdShort() would have produced from the same UUID), while making + // every session map to a unique filename based on its own transcript UUID. + // + // Without this, a parent session and any `claude -p ...` subprocess spawned by + // another Stop hook share the project-name fallback filename, and the subprocess + // overwrites the parent's summary. See issue #1494 for full repro details. + let shortId = null; + if (transcriptPath) { + const m = path.basename(transcriptPath).match(/([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\.jsonl$/i); + if (m) { + // Run through sanitizeSessionId() for byte-for-byte parity with + // getSessionIdShort(sessionId.slice(-8)). + shortId = sanitizeSessionId(m[1].slice(-8).toLowerCase()); + } + } + if (!shortId) { + shortId = getSessionIdShort(); + } + const sessionFile = path.join(sessionsDir, `${today}-${shortId}-session.tmp`); + const sessionMetadata = getSessionMetadata(); + + ensureDir(sessionsDir); + + const currentTime = getTimeString(); + + // Decide whether to call LLM for a richer summary. + // Triggers: context remaining < 20%, or every 50 user messages as a baseline. + let llmSummary = null; + if (transcriptPath && summary && transcriptExists) { + const contextPct = getContextRemainingPct(transcriptPath); + const isContextLow = contextPct !== null && contextPct < getContextThreshold(); + const interval = parseInt(process.env.ECC_LLM_SUMMARY_INTERVAL || '50', 10); + const safeInterval = Number.isFinite(interval) && interval > 0 ? interval : 50; + const isPeriodicTurn = summary.totalMessages > 0 && summary.totalMessages % safeInterval === 0; + if (isContextLow || isPeriodicTurn) { + log(`[SessionEnd] LLM summary triggered (context: ${contextPct ?? 'unknown'}%, messages: ${summary.totalMessages})`); + llmSummary = generateSessionSummary(transcriptPath); + if (llmSummary) { + log('[SessionEnd] LLM summary generated successfully'); + } else { + log('[SessionEnd] LLM summary failed; falling back to mechanical extraction'); + } + } + } + + if (fs.existsSync(sessionFile)) { + const existing = readFile(sessionFile); + let updatedContent = existing; + + if (existing) { + const merged = mergeSessionHeader(existing, today, currentTime, sessionMetadata); + if (merged) { + updatedContent = merged; + } else { + log(`[SessionEnd] Failed to normalize header in ${sessionFile}`); + } + } + + // If we have a new summary, update only the generated summary block. + // This keeps repeated Stop invocations idempotent and preserves + // user-authored sections in the same session file. + if (summary && updatedContent) { + const summaryBlock = llmSummary ? `${SUMMARY_START_MARKER}\n${llmSummary}\n${SUMMARY_END_MARKER}` : buildSummaryBlock(summary); + + // Use function replacers: summaryBlock embeds raw user-message text, and a + // string replacement argument interprets $-sequences ($&, $$, $`, $', $n). + // A $& in a user message would otherwise re-inject the entire matched block + // and corrupt the persisted summary. A function replacer is treated literally. + if (updatedContent.includes(SUMMARY_START_MARKER) && updatedContent.includes(SUMMARY_END_MARKER)) { + updatedContent = updatedContent.replace(new RegExp(`${escapeRegExp(SUMMARY_START_MARKER)}[\\s\\S]*?${escapeRegExp(SUMMARY_END_MARKER)}`), () => summaryBlock); + } else { + // Migration path for files created before summary markers existed. + updatedContent = updatedContent.replace( + /## (?:Session Summary|Current State)[\s\S]*?$/, + () => `${summaryBlock}\n\n### Notes for Next Session\n-\n\n### Context to Load\n\`\`\`\n[relevant files]\n\`\`\`\n` + ); + } + } + + if (updatedContent) { + writeFile(sessionFile, updatedContent); + } + + log(`[SessionEnd] Updated session file: ${sessionFile}`); + } else { + // Create new session file + const block = llmSummary ? `${SUMMARY_START_MARKER}\n${llmSummary}\n${SUMMARY_END_MARKER}` : summary ? buildSummaryBlock(summary) : null; + const summarySection = block + ? `${block}\n\n### Notes for Next Session\n-\n\n### Context to Load\n\`\`\`\n[relevant files]\n\`\`\`` + : `## Current State\n\n[Session context goes here]\n\n### Completed\n- [ ]\n\n### In Progress\n- [ ]\n\n### Notes for Next Session\n-\n\n### Context to Load\n\`\`\`\n[relevant files]\n\`\`\``; + + const template = `${buildSessionHeader(today, currentTime, sessionMetadata)}${SESSION_SEPARATOR}${summarySection} +`; + + writeFile(sessionFile, template); + log(`[SessionEnd] Created session file: ${sessionFile}`); + } + + process.exit(0); +} + +function buildSummarySection(summary) { + let section = '## Session Summary\n\n'; + + // Tasks (from user messages — collapse newlines and escape backticks to prevent markdown breaks) + section += '### Tasks\n'; + for (const msg of summary.userMessages) { + section += `- ${msg.replace(/\n/g, ' ').replace(/`/g, '\\`')}\n`; + } + section += '\n'; + + // Files modified + if (summary.filesModified.length > 0) { + section += '### Files Modified\n'; + for (const f of summary.filesModified) { + section += `- ${f}\n`; + } + section += '\n'; + } + + // Tools used + if (summary.toolsUsed.length > 0) { + section += `### Tools Used\n${summary.toolsUsed.join(', ')}\n\n`; + } + + section += `### Stats\n- Total user messages: ${summary.totalMessages}\n`; + + return section; +} + +function buildSummaryBlock(summary) { + return `${SUMMARY_START_MARKER}\n${buildSummarySection(summary).trim()}\n${SUMMARY_END_MARKER}`; +} + +function escapeRegExp(value) { + return String(value).replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +} diff --git a/github_code/affaan-m__ECC/scripts/hooks/session-start-bootstrap.js b/github_code/affaan-m__ECC/scripts/hooks/session-start-bootstrap.js new file mode 100644 index 0000000000000000000000000000000000000000..4da168bad72611821639d6c7106708e3722cf5fe --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/hooks/session-start-bootstrap.js @@ -0,0 +1,85 @@ +#!/usr/bin/env node +'use strict'; + +/** + * session-start-bootstrap.js + * + * Bootstrap loader for the ECC SessionStart hook. + * + * Problem this solves: the previous approach embedded this logic as an inline + * `node -e "..."` string inside hooks.json. Characters like `!` (used in + * `!org.isDirectory()`) can trigger bash history expansion or other shell + * interpretation issues depending on the environment, causing + * "SessionStart:startup hook error" to appear in the Claude Code CLI header. + * + * By extracting to a standalone file, the shell never sees the JavaScript + * source and the `!` characters are safe. Behaviour is otherwise identical. + * + * How it works: + * 1. Reads the raw JSON event from stdin (passed by Claude Code). + * 2. Resolves the ECC plugin root directory (via CLAUDE_PLUGIN_ROOT env var + * or a set of well-known fallback paths). + * 3. Delegates to `scripts/hooks/run-with-flags.js` with the `session:start` + * event, which applies hook-profile gating and then runs session-start.js. + * 4. Passes stdout/stderr through and forwards the child exit code. + * 5. If the plugin root cannot be found, emits a warning and passes stdin + * through unchanged so Claude Code can continue normally. + */ + +const fs = require('fs'); +const path = require('path'); +const { spawnSync } = require('child_process'); +const { resolveEccRoot } = require('../lib/resolve-ecc-root'); + +// Read the raw JSON event from stdin +const raw = fs.readFileSync(0, 'utf8'); + +// Path (relative to plugin root) to the hook runner +const rel = path.join('scripts', 'hooks', 'run-with-flags.js'); + +// Resolve the ECC plugin root via the shared resolver, probing for the runner +// so a valid root is one that actually contains run-with-flags.js. +const root = resolveEccRoot({ probe: rel }); +const script = path.join(root, rel); + +if (fs.existsSync(script)) { + const result = spawnSync( + process.execPath, + [script, 'session:start', 'scripts/hooks/session-start.js', 'minimal,standard,strict'], + { + input: raw, + encoding: 'utf8', + env: process.env, + cwd: process.cwd(), + timeout: 30000, + } + ); + + const stdout = typeof result.stdout === 'string' ? result.stdout : ''; + if (stdout) { + process.stdout.write(stdout); + } else { + process.stdout.write(raw); + } + + if (result.stderr) { + process.stderr.write(result.stderr); + } + + if (result.error || result.status === null || result.signal) { + const reason = result.error + ? result.error.message + : result.signal + ? 'signal ' + result.signal + : 'missing exit status'; + process.stderr.write('[SessionStart] ERROR: session-start hook failed: ' + reason + '\n'); + process.exit(1); + } + + process.exit(Number.isInteger(result.status) ? result.status : 0); +} + +process.stderr.write( + '[SessionStart] WARNING: could not resolve ECC plugin root; skipping session-start hook\n' +); +process.stdout.write(raw); diff --git a/github_code/affaan-m__ECC/scripts/hooks/session-start.js b/github_code/affaan-m__ECC/scripts/hooks/session-start.js new file mode 100644 index 0000000000000000000000000000000000000000..63854aff1c2efeaaa82fbf05886dadbd791a048e --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/hooks/session-start.js @@ -0,0 +1,798 @@ +#!/usr/bin/env node +/** + * SessionStart Hook - Load previous context on new session + * + * Cross-platform (Windows, macOS, Linux) + * + * Runs when a new Claude session starts. Loads the most recent session + * summary into Claude's context via stdout, and reports available + * sessions and learned skills. + */ + +const { + getSessionsDir, + getSessionSearchDirs, + getLearnedSkillsDir, + getProjectName, + findFiles, + ensureDir, + readFile, + stripAnsi, + log +} = require('../lib/utils'); +const { resolveProjectContext, writeSessionLease, resolveSessionId, getHomunculusDir } = require('../lib/observer-sessions'); +const { getPackageManager, getSelectionPrompt } = require('../lib/package-manager'); +const { listAliases } = require('../lib/session-aliases'); +const { detectProjectType } = require('../lib/project-detect'); +const { + isRelevanceRankingEnabled, + detectStackKeywords, + computeRelevanceBoost, +} = require('../lib/instinct-relevance'); +const path = require('path'); +const fs = require('fs'); + +const DEFAULT_INSTINCT_CONFIDENCE_THRESHOLD = 0.7; +const DEFAULT_MAX_INJECTED_INSTINCTS = 6; +const MAX_INJECTED_LEARNED_SKILLS = 6; +const MAX_LEARNED_SKILL_SUMMARY_CHARS = 220; +const DEFAULT_SESSION_START_CONTEXT_MAX_CHARS = 8000; +const DEFAULT_SESSION_RETENTION_DAYS = 30; +const SESSION_START_MODE_INVALID = 'invalid'; +const SESSION_START_MODE_SKIP = 'skip'; + +/** + * Resolve a filesystem path to its canonical (real) form. + * + * Handles symlinks and, on case-insensitive filesystems (macOS, Windows), + * normalizes casing so that path comparisons are reliable. + * Falls back to the original path if resolution fails (e.g. path no longer exists). + * + * @param {string} p - The path to normalize. + * @returns {string} The canonical path, or the original if resolution fails. + */ +function normalizePath(p) { + try { + return fs.realpathSync(p); + } catch { + return p; + } +} + +function dedupeRecentSessions(searchDirs) { + const recentSessionsByName = new Map(); + + for (const [dirIndex, dir] of searchDirs.entries()) { + const matches = findFiles(dir, '*-session.tmp', { maxAge: 7 }); + + for (const match of matches) { + const basename = path.basename(match.path); + const current = { + ...match, + basename, + dirIndex, + }; + const existing = recentSessionsByName.get(basename); + + if ( + !existing + || current.mtime > existing.mtime + || (current.mtime === existing.mtime && current.dirIndex < existing.dirIndex) + ) { + recentSessionsByName.set(basename, current); + } + } + } + + return Array.from(recentSessionsByName.values()) + .sort((left, right) => right.mtime - left.mtime || left.dirIndex - right.dirIndex); +} + +/** + * Resolve session retention days from the ECC_SESSION_RETENTION_DAYS env var. + * + * @returns {number|null} The retention window in days, or `null` when the + * user has explicitly opted out of pruning. Falsy/garbage values fall back + * to {@link DEFAULT_SESSION_RETENTION_DAYS}. + */ +function getSessionRetentionDays() { + const raw = process.env.ECC_SESSION_RETENTION_DAYS; + if (!raw) return DEFAULT_SESSION_RETENTION_DAYS; + + const normalized = String(raw).trim().toLowerCase(); + if (['0', 'off', 'false', 'disabled', 'never', 'none'].includes(normalized)) { + return null; + } + + const parsed = Number.parseInt(raw, 10); + return Number.isInteger(parsed) && parsed > 0 ? parsed : DEFAULT_SESSION_RETENTION_DAYS; +} + +function isSessionStartContextDisabled() { + const raw = String(process.env.ECC_SESSION_START_CONTEXT || '').trim().toLowerCase(); + return ['0', 'false', 'off', 'none', 'disabled'].includes(raw); +} + +function getSessionStartMaxContextChars() { + const raw = process.env.ECC_SESSION_START_MAX_CHARS; + if (!raw) return DEFAULT_SESSION_START_CONTEXT_MAX_CHARS; + + const parsed = Number.parseInt(raw, 10); + return Number.isInteger(parsed) && parsed >= 0 ? parsed : DEFAULT_SESSION_START_CONTEXT_MAX_CHARS; +} + +/** + * Resolve the minimum confidence an instinct needs to be injected at + * SessionStart. Overridable via `ECC_INSTINCT_CONFIDENCE_THRESHOLD` + * (a number in [0, 1]); falsy or out-of-range values fall back to + * {@link DEFAULT_INSTINCT_CONFIDENCE_THRESHOLD}. + * + * @returns {number} The confidence floor for injected instincts. + */ +function getInstinctConfidenceThreshold() { + const raw = process.env.ECC_INSTINCT_CONFIDENCE_THRESHOLD; + if (!raw) return DEFAULT_INSTINCT_CONFIDENCE_THRESHOLD; + + // Require a plain decimal (e.g. "0.7", "1", "0.95") so trailing junk + // ("0.7x") and non-decimal numeric syntax like "0x1" (hex) or "1e2" + // (exponent) are rejected whole rather than silently accepted by Number(). + const normalized = raw.trim(); + if (!/^\d+(\.\d+)?$/.test(normalized)) return DEFAULT_INSTINCT_CONFIDENCE_THRESHOLD; + + const parsed = Number(normalized); + return Number.isFinite(parsed) && parsed >= 0 && parsed <= 1 + ? parsed + : DEFAULT_INSTINCT_CONFIDENCE_THRESHOLD; +} + +/** + * Resolve the maximum number of instincts injected at SessionStart. + * Overridable via `ECC_MAX_INJECTED_INSTINCTS` (a positive integer); + * falsy or invalid values fall back to + * {@link DEFAULT_MAX_INJECTED_INSTINCTS}. + * + * @returns {number} The cap on injected instincts. + */ +function getMaxInjectedInstincts() { + const raw = process.env.ECC_MAX_INJECTED_INSTINCTS; + if (!raw) return DEFAULT_MAX_INJECTED_INSTINCTS; + + // Require a plain non-negative integer so "3.9", "6abc", "0x1" (hex), + // and "1e2" (exponent) are rejected whole and fall back to the default, + // rather than parseInt truncating or Number() accepting alternate syntax. + const normalized = raw.trim(); + if (!/^\d+$/.test(normalized)) return DEFAULT_MAX_INJECTED_INSTINCTS; + + const parsed = Number(normalized); + return Number.isInteger(parsed) && parsed > 0 ? parsed : DEFAULT_MAX_INJECTED_INSTINCTS; +} + +function getSessionStartMode(rawInput) { + const input = String(rawInput || ''); + if (!input.trim()) return null; + + let payload; + try { + payload = JSON.parse(input); + } catch { + log(`[SessionStart] Invalid stdin payload; skipping previous session summary injection. Length: ${input.length}`); + return SESSION_START_MODE_INVALID; + } + + const supportedModes = new Set(['startup', 'resume', 'clear', 'compact']); + const hookName = typeof payload.hookName === 'string' ? payload.hookName.trim() : ''; + if (hookName.startsWith('SessionStart:')) { + const mode = hookName.slice('SessionStart:'.length).trim().toLowerCase(); + return supportedModes.has(mode) ? mode : SESSION_START_MODE_SKIP; + } + + if (payload.hook_event_name === 'SessionStart') { + const mode = typeof payload.source === 'string' ? payload.source.trim().toLowerCase() : ''; + return supportedModes.has(mode) ? mode : SESSION_START_MODE_SKIP; + } + + return SESSION_START_MODE_SKIP; +} + +function limitSessionStartContext(additionalContext, maxChars = getSessionStartMaxContextChars()) { + const context = String(additionalContext || ''); + + if (context.length <= maxChars) { + return context; + } + + const marker = '\n\n[SessionStart truncated context. Set ECC_SESSION_START_MAX_CHARS to raise the cap or ECC_SESSION_START_CONTEXT=off to disable injected context.]'; + const prefixLength = Math.max(0, maxChars - marker.length); + log(`[SessionStart] Truncated additional context from ${context.length} to ${maxChars} chars`); + + return `${context.slice(0, prefixLength).trimEnd()}${marker}`.slice(0, maxChars); +} + +function pruneExpiredSessions(searchDirs, retentionDays) { + const uniqueDirs = Array.from(new Set(searchDirs.filter(dir => typeof dir === 'string' && dir.length > 0))); + let removed = 0; + + for (const dir of uniqueDirs) { + if (!fs.existsSync(dir)) continue; + + let entries; + try { + entries = fs.readdirSync(dir, { withFileTypes: true }); + } catch { + continue; + } + + for (const entry of entries) { + if (!entry.isFile() || !entry.name.endsWith('-session.tmp')) continue; + + const fullPath = path.join(dir, entry.name); + let stats; + try { + stats = fs.statSync(fullPath); + } catch { + continue; + } + + const ageInDays = (Date.now() - stats.mtimeMs) / (1000 * 60 * 60 * 24); + if (ageInDays <= retentionDays) continue; + + try { + fs.rmSync(fullPath, { force: true }); + removed += 1; + } catch (error) { + log(`[SessionStart] Warning: failed to prune expired session ${fullPath}: ${error.message}`); + } + } + } + + return removed; +} + +/** + * Select the best matching session for the current working directory. + * + * Session files written by session-end.js contain header fields like: + * **Project:** my-project + * **Worktree:** /path/to/project + * + * This function reads each session file once, caching its content, and + * returns both the selected session object and its already-read content + * to avoid duplicate I/O in the caller. + * + * Priority (highest to lowest): + * 1. Exact worktree (cwd) match — most recent + * 2. Same project name match for legacy sessions without Worktree metadata + * 3. No injection when sessions belong to a different worktree/project + * + * Sessions are already sorted newest-first, so the first match in each + * category wins. + * + * @param {Array} sessions - Deduplicated session list, sorted newest-first. + * @param {string} cwd - Current working directory (process.cwd()). + * @param {string} currentProject - Current project name from getProjectName(). + * @returns {{ session: Object, content: string, matchReason: string } | null} + * The best matching session with its cached content and match reason, + * or null if the sessions array is empty or all files are unreadable. + */ +function selectMatchingSession(sessions, cwd, currentProject) { + if (sessions.length === 0) return null; + + // Normalize cwd once outside the loop to avoid repeated syscalls + const normalizedCwd = normalizePath(cwd); + + let projectMatch = null; + let projectMatchContent = null; + let readableSessions = 0; + + for (const session of sessions) { + const content = readFile(session.path); + if (!content) continue; + readableSessions++; + + // Extract **Worktree:** field + const worktreeMatch = content.match(/\*\*Worktree:\*\*\s*(.+)$/m); + const sessionWorktree = worktreeMatch ? worktreeMatch[1].trim() : ''; + + // Exact worktree match — best possible, return immediately + // Normalize both paths to handle symlinks and case-insensitive filesystems + if (sessionWorktree && normalizePath(sessionWorktree) === normalizedCwd) { + return { session, content, matchReason: 'worktree' }; + } + + // Project name match is only safe for legacy session files written before + // Worktree metadata existed. A different explicit Worktree is not a match. + if (!projectMatch && currentProject && !sessionWorktree) { + const projectFieldMatch = content.match(/\*\*Project:\*\*\s*(.+)$/m); + const sessionProject = projectFieldMatch ? projectFieldMatch[1].trim() : ''; + if (sessionProject && sessionProject === currentProject) { + projectMatch = session; + projectMatchContent = content; + } + } + } + + if (projectMatch) { + return { session: projectMatch, content: projectMatchContent, matchReason: 'project' }; + } + + log(readableSessions > 0 + ? '[SessionStart] No worktree/project session match found' + : '[SessionStart] All session files were unreadable'); + return null; +} + +function parseInstinctFile(content) { + const instincts = []; + let current = null; + let inFrontmatter = false; + let contentLines = []; + + for (const line of String(content).split('\n')) { + if (line.trim() === '---') { + if (inFrontmatter) { + inFrontmatter = false; + } else { + if (current && current.id) { + current.content = contentLines.join('\n').trim(); + instincts.push(current); + } + current = {}; + contentLines = []; + inFrontmatter = true; + } + continue; + } + + if (inFrontmatter) { + const separatorIndex = line.indexOf(':'); + if (separatorIndex === -1) continue; + const key = line.slice(0, separatorIndex).trim(); + let value = line.slice(separatorIndex + 1).trim(); + if ((value.startsWith('"') && value.endsWith('"')) || (value.startsWith("'") && value.endsWith("'"))) { + value = value.slice(1, -1); + } + if (key === 'confidence') { + const parsed = Number.parseFloat(value); + current[key] = Number.isFinite(parsed) ? parsed : 0.5; + } else { + current[key] = value; + } + } else if (current) { + contentLines.push(line); + } + } + + if (current && current.id) { + current.content = contentLines.join('\n').trim(); + instincts.push(current); + } + + return instincts; +} + +function readInstinctsFromDir(directory, scope) { + if (!directory || !fs.existsSync(directory)) return []; + + const entries = fs.readdirSync(directory, { withFileTypes: true }) + .filter(entry => entry.isFile() && /\.(ya?ml|md)$/i.test(entry.name)) + .sort((left, right) => left.name.localeCompare(right.name)); + + const instincts = []; + for (const entry of entries) { + const filePath = path.join(directory, entry.name); + try { + const parsed = parseInstinctFile(fs.readFileSync(filePath, 'utf8')); + for (const instinct of parsed) { + instincts.push({ + ...instinct, + _scopeLabel: scope, + _sourceFile: filePath, + }); + } + } catch (error) { + log(`[SessionStart] Warning: failed to parse instinct file ${filePath}: ${error.message}`); + } + } + + return instincts; +} + +function extractInstinctAction(content) { + const actionMatch = String(content || '').match(/## Action\s*\n+([\s\S]+?)(?:\n## |\n---|$)/); + const actionBlock = (actionMatch ? actionMatch[1] : String(content || '')).trim(); + const firstLine = actionBlock + .split('\n') + .map(line => line.trim()) + .find(Boolean); + + return firstLine || ''; +} + +function summarizeActiveInstincts(observerContext) { + const homunculusDir = getHomunculusDir(); + const globalDirs = [ + { dir: path.join(homunculusDir, 'instincts', 'personal'), scope: 'global' }, + { dir: path.join(homunculusDir, 'instincts', 'inherited'), scope: 'global' }, + ]; + const projectDirs = observerContext.isGlobal ? [] : [ + { dir: path.join(observerContext.projectDir, 'instincts', 'personal'), scope: 'project' }, + { dir: path.join(observerContext.projectDir, 'instincts', 'inherited'), scope: 'project' }, + ]; + + const scopedInstincts = [ + ...projectDirs.flatMap(({ dir, scope }) => readInstinctsFromDir(dir, scope)), + ...globalDirs.flatMap(({ dir, scope }) => readInstinctsFromDir(dir, scope)), + ]; + + const confidenceThreshold = getInstinctConfidenceThreshold(); + const maxInjected = getMaxInjectedInstincts(); + + // Relevance ranking (issue #2371 part b): at SessionStart there is no user + // task yet, so relevance is location/stack based. Project-scoped and + // stack-matching instincts get a small additive boost over their confidence. + // Gated by ECC_INSTINCT_RELEVANCE_RANKING (default on); when off, or when no + // stack is detected and nothing is project-scoped, every boost is 0 and the + // ranking collapses to confidence-only (unchanged behaviour). + // Detect the stack from the real project source tree (projectRoot), not the + // homunculus state dir (projectDir). In a global session projectRoot is empty, + // so detectStackKeywords falls back to process.cwd(). + const relevanceEnabled = isRelevanceRankingEnabled(); + const stackKeywords = relevanceEnabled + ? detectStackKeywords(observerContext.projectRoot || undefined) + : new Set(); + + const deduped = new Map(); + for (const instinct of scopedInstincts) { + if (!instinct.id || instinct.confidence < confidenceThreshold) continue; + const existing = deduped.get(instinct.id); + if (!existing || (existing._scopeLabel !== 'project' && instinct._scopeLabel === 'project')) { + deduped.set(instinct.id, instinct); + } + } + + const ranked = Array.from(deduped.values()) + .map(instinct => ({ + ...instinct, + action: extractInstinctAction(instinct.content), + _relevance: relevanceEnabled ? computeRelevanceBoost(instinct, stackKeywords) : 0, + })) + .filter(instinct => instinct.action) + .sort((left, right) => { + // Primary: combined confidence + relevance. When relevance is off every + // _relevance is 0, so this reduces to the prior confidence-only ordering. + // Tie-breaks on a genuinely equal combined score: project scope first, + // then id (deterministic). + const leftScore = left.confidence + left._relevance; + const rightScore = right.confidence + right._relevance; + if (rightScore !== leftScore) return rightScore - leftScore; + if (left._scopeLabel !== right._scopeLabel) return left._scopeLabel === 'project' ? -1 : 1; + return String(left.id).localeCompare(String(right.id)); + }) + .slice(0, maxInjected); + + if (ranked.length === 0) { + return ''; + } + + log(`[SessionStart] Injecting ${ranked.length} instinct(s) into session context`); + + const lines = ranked.map(instinct => { + const scope = instinct._scopeLabel === 'project' ? 'project' : 'global'; + const confidence = `${Math.round(instinct.confidence * 100)}%`; + return `- [${scope} ${confidence}] ${instinct.action}`; + }); + + return `Active instincts:\n${lines.join('\n')}`; +} + +function stripMarkdownInline(value) { + return String(value || '') + .replace(/`([^`]+)`/g, '$1') + .replace(/\*\*([^*]+)\*\*/g, '$1') + .replace(/\*([^*]+)\*/g, '$1') + .replace(/\[([^\]]+)\]\([^)]+\)/g, '$1') + .trim(); +} + +function collapseWhitespace(value) { + return String(value || '').replace(/\s+/g, ' ').trim(); +} + +function truncateSummary(value, maxLength = MAX_LEARNED_SKILL_SUMMARY_CHARS) { + const normalized = collapseWhitespace(stripMarkdownInline(value)); + if (normalized.length <= maxLength) { + return normalized; + } + return `${normalized.slice(0, Math.max(0, maxLength - 3)).trimEnd()}...`; +} + +function extractMarkdownHeading(content) { + const match = String(content || '').match(/^#\s+(.+)$/m); + return match ? stripMarkdownInline(match[1]) : ''; +} + +function extractSection(content, headingPattern) { + const source = String(content || ''); + const match = source.match(new RegExp(`^##\\s+${headingPattern}\\s*\\n+([\\s\\S]+?)(?:\\n##\\s+|$)`, 'im')); + return match ? match[1].trim() : ''; +} + +function extractFirstParagraph(content) { + const withoutHeading = String(content || '').replace(/^#\s+.+$/m, '').trim(); + return withoutHeading + .split(/\n\s*\n/) + .map(paragraph => paragraph.trim()) + .find(Boolean) || ''; +} + +function summarizeLearnedSkillFile(filePath, learnedRoot) { + const content = readFile(filePath); + if (!content) return null; + + const isDirectorySkill = path.basename(filePath).toLowerCase() === 'skill.md'; + const slug = isDirectorySkill + ? path.basename(path.dirname(filePath)) + : path.basename(filePath, path.extname(filePath)); + const title = extractMarkdownHeading(content) || slug; + const summary = truncateSummary( + extractSection(content, 'When to Use') + || extractSection(content, 'Trigger') + || extractSection(content, 'Problem') + || extractFirstParagraph(content) + || title + ); + + if (!summary) return null; + + let mtime = 0; + try { + mtime = fs.statSync(filePath).mtimeMs; + } catch { + // Keep unreadable/deleted files out of recency priority without failing the hook. + } + + const relativePath = path.relative(learnedRoot, filePath); + return { + slug, + title: truncateSummary(title, 80), + summary, + relativePath, + mtime, + }; +} + +function collectLearnedSkillFiles(learnedDir) { + const flatMarkdownFiles = findFiles(learnedDir, '*.md'); + const directorySkillFiles = findFiles(learnedDir, 'SKILL.md', { recursive: true }); + const byPath = new Map(); + + for (const match of [...flatMarkdownFiles, ...directorySkillFiles]) { + byPath.set(match.path, match); + } + + return Array.from(byPath.values()) + .sort((left, right) => right.mtime - left.mtime || left.path.localeCompare(right.path)); +} + +function summarizeLearnedSkills(learnedDir, learnedSkillFiles = collectLearnedSkillFiles(learnedDir)) { + const summaries = learnedSkillFiles + .map(match => summarizeLearnedSkillFile(match.path, learnedDir)) + .filter(Boolean) + .slice(0, MAX_INJECTED_LEARNED_SKILLS); + + if (summaries.length === 0) { + return ''; + } + + log(`[SessionStart] Injecting ${summaries.length} learned skill(s) into session context`); + + const lines = summaries.map(skill => { + const titleSuffix = skill.title && skill.title !== skill.slug ? ` (${skill.title})` : ''; + return `- ${skill.slug}${titleSuffix}: ${skill.summary}`; + }); + + return [ + 'Available learned skills:', + 'Reference only; apply a learned skill only when it is relevant to the current user request.', + ...lines, + ].join('\n'); +} + +async function main() { + const sessionsDir = getSessionsDir(); + const sessionSearchDirs = getSessionSearchDirs(); + const learnedDir = getLearnedSkillsDir(); + const additionalContextParts = []; + const observerContext = resolveProjectContext(); + const maxContextChars = getSessionStartMaxContextChars(); + const explicitContextDisabled = isSessionStartContextDisabled(); + const shouldInjectContext = !explicitContextDisabled && maxContextChars !== 0; + const sessionStartMode = getSessionStartMode(fs.readFileSync(0, 'utf8')); + + // Ensure directories exist + ensureDir(sessionsDir); + ensureDir(learnedDir); + + const retentionDays = getSessionRetentionDays(); + if (retentionDays === null) { + log('[SessionStart] Pruning disabled via ECC_SESSION_RETENTION_DAYS'); + } else { + const prunedSessions = pruneExpiredSessions(sessionSearchDirs, retentionDays); + if (prunedSessions > 0) { + log(`[SessionStart] Pruned ${prunedSessions} expired session(s) older than ${retentionDays} day(s)`); + } + } + + const observerSessionId = resolveSessionId(); + if (observerSessionId) { + writeSessionLease(observerContext, observerSessionId, { + hook: 'SessionStart', + projectRoot: observerContext.projectRoot + }); + log(`[SessionStart] Registered observer lease for ${observerSessionId}`); + } else { + log('[SessionStart] No CLAUDE_SESSION_ID available; skipping observer lease registration'); + } + + if (explicitContextDisabled) { + log('[SessionStart] Additional context injection disabled by ECC_SESSION_START_CONTEXT'); + } else if (maxContextChars === 0) { + log('[SessionStart] Additional context injection disabled by ECC_SESSION_START_MAX_CHARS=0'); + } + + if (shouldInjectContext) { + const instinctSummary = summarizeActiveInstincts(observerContext); + if (instinctSummary) { + additionalContextParts.push(instinctSummary); + } + + if (sessionStartMode && sessionStartMode !== 'startup') { + const reason = sessionStartMode === SESSION_START_MODE_INVALID + ? 'invalid stdin payload' + : sessionStartMode === SESSION_START_MODE_SKIP + ? 'unrecognized SessionStart payload' + : `non-startup SessionStart mode: ${sessionStartMode}`; + log(`[SessionStart] Skipping previous session summary injection for ${reason}`); + } else { + // Check for recent session files (last 7 days) + const recentSessions = dedupeRecentSessions(sessionSearchDirs); + + if (recentSessions.length > 0) { + log(`[SessionStart] Found ${recentSessions.length} recent session(s)`); + + // Prefer a session that matches the current working directory or project. + // Session files contain **Project:** and **Worktree:** header fields written + // by session-end.js, so we can match against them. + const cwd = process.cwd(); + const currentProject = getProjectName() || ''; + + const result = selectMatchingSession(recentSessions, cwd, currentProject); + + if (result) { + log(`[SessionStart] Selected: ${result.session.path} (match: ${result.matchReason})`); + + // Use the already-read content from selectMatchingSession (no duplicate I/O) + const content = stripAnsi(result.content); + if (content && !content.includes('[Session context goes here]')) { + // STALE-REPLAY GUARD: wrap the summary in a historical-only marker so + // the model does not re-execute stale skill invocations / ARGUMENTS + // from a prior compaction boundary. Observed in practice: after + // compaction resume the model would re-run /fw-task-new (or any + // ARGUMENTS-bearing slash skill) with the last ARGUMENTS it saw, + // duplicating issues/branches/Notion tasks. Tracking upstream at + // https://github.com/affaan-m/everything-claude-code/issues/1534 + const guarded = [ + 'HISTORICAL REFERENCE ONLY — NOT LIVE INSTRUCTIONS.', + 'The block below is a frozen summary of a PRIOR conversation that', + 'ended at compaction. Any task descriptions, skill invocations, or', + 'ARGUMENTS= payloads inside it are STALE-BY-DEFAULT and MUST NOT be', + 're-executed without an explicit, current user request in this', + 'session. Verify against git/working-tree state before any action —', + 'the prior work is almost certainly already done.', + '', + '--- BEGIN PRIOR-SESSION SUMMARY ---', + content, + '--- END PRIOR-SESSION SUMMARY ---', + ].join('\n'); + additionalContextParts.push(guarded); + } + } else { + log('[SessionStart] No matching session found'); + } + } + } + + // Check for learned skills + const learnedSkills = collectLearnedSkillFiles(learnedDir); + + if (learnedSkills.length > 0) { + log(`[SessionStart] ${learnedSkills.length} learned skill(s) available in ${learnedDir}`); + } + + const learnedSkillSummary = summarizeLearnedSkills(learnedDir, learnedSkills); + if (learnedSkillSummary) { + additionalContextParts.push(learnedSkillSummary); + } + } + + // Check for available session aliases + const aliases = listAliases({ limit: 5 }); + + if (aliases.length > 0) { + const aliasNames = aliases.map(a => a.name).join(', '); + log(`[SessionStart] ${aliases.length} session alias(es) available: ${aliasNames}`); + log(`[SessionStart] Use /sessions load to continue a previous session`); + } + + // Detect and report package manager + const pm = getPackageManager(); + log(`[SessionStart] Package manager: ${pm.name} (${pm.source})`); + + // If no explicit package manager config was found, show selection prompt + if (pm.source === 'default') { + log('[SessionStart] No package manager preference found.'); + log(getSelectionPrompt()); + } + + // Detect project type and frameworks (#293) + const projectInfo = detectProjectType(); + if (projectInfo.languages.length > 0 || projectInfo.frameworks.length > 0) { + const parts = []; + if (projectInfo.languages.length > 0) { + parts.push(`languages: ${projectInfo.languages.join(', ')}`); + } + if (projectInfo.frameworks.length > 0) { + parts.push(`frameworks: ${projectInfo.frameworks.join(', ')}`); + } + log(`[SessionStart] Project detected — ${parts.join('; ')}`); + if (shouldInjectContext) { + additionalContextParts.push(`Project type: ${JSON.stringify(projectInfo)}`); + } + } else { + log('[SessionStart] No specific project type detected'); + } + + const additionalContext = shouldInjectContext + ? limitSessionStartContext(additionalContextParts.join('\n\n'), maxContextChars) + : ''; + await writeSessionStartPayload(additionalContext); +} + +function writeSessionStartPayload(additionalContext) { + return new Promise((resolve, reject) => { + let settled = false; + const payload = JSON.stringify({ + hookSpecificOutput: { + hookEventName: 'SessionStart', + additionalContext + } + }); + + const handleError = (err) => { + if (settled) return; + settled = true; + if (err) { + log(`[SessionStart] stdout write error: ${err.message}`); + } + reject(err || new Error('stdout stream error')); + }; + + process.stdout.once('error', handleError); + process.stdout.write(payload, (err) => { + process.stdout.removeListener('error', handleError); + if (settled) return; + settled = true; + if (err) { + log(`[SessionStart] stdout write error: ${err.message}`); + reject(err); + return; + } + resolve(); + }); + }); +} + +main().catch(err => { + console.error('[SessionStart] Error:', err.message); + process.exitCode = 0; // Don't block on errors +}); diff --git a/github_code/affaan-m__ECC/scripts/hooks/skill-run-tracker.js b/github_code/affaan-m__ECC/scripts/hooks/skill-run-tracker.js new file mode 100644 index 0000000000000000000000000000000000000000..eef54b859b735d5b76e045dd4147e43ec19e00b0 --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/hooks/skill-run-tracker.js @@ -0,0 +1,149 @@ +#!/usr/bin/env node +'use strict'; + +/** + * PostToolUse hook: record Skill tool invocations for skill-health telemetry. + * + * Wires the write side of the already-shipped JSONL tracker + * (scripts/lib/skill-evolution/tracker.js). Before this hook, + * recordSkillExecution() had zero production callers, so + * ~/.claude/state/skill-runs.jsonl was never written and + * `scripts/skills-health.js --dashboard` always reported 0 runs (#2463). + * + * Privacy: the dashboard aggregates skill/version/outcome only, so this hook + * never persists prompt text. `task_description` is synthesized from the skill + * id, and every persisted string is charset-restricted and length-bounded — a + * skill id is an identifier, not free text, so anything that does not look like + * one is dropped rather than written through. + * + * Best-effort: never blocks tool execution. Runs under the PostToolUse + * dispatcher, which owns stdin, pass-through, and exit codes. + * + * Cross-platform (Windows, macOS, Linux); CommonJS. + */ + +const { recordSkillExecution } = require('../lib/skill-evolution/tracker'); + +// Bounds for persisted identifiers. Long enough for any real skill id or +// semver-ish version, short enough that a stray blob cannot ride in. +const MAX_SKILL_ID = 128; +const MAX_SKILL_VERSION = 64; + +// Identifiers only: letters, digits, and the separators skill ids actually use. +// Anything else (whitespace, punctuation, newlines) means it is not an id. +const SKILL_ID_PATTERN = /^[A-Za-z0-9._:@/-]+$/; +const SKILL_VERSION_PATTERN = /^[A-Za-z0-9._+-]+$/; + +// Return `value` only if it is a bounded, identifier-shaped string. +function boundedIdentifier(value, maxLength, pattern) { + if (typeof value !== 'string') { + return null; + } + const trimmed = value.trim(); + if (trimmed.length === 0 || trimmed.length > maxLength) { + return null; + } + return pattern.test(trimmed) ? trimmed : null; +} + +function firstIdentifier(maxLength, pattern, ...values) { + for (const value of values) { + const identifier = boundedIdentifier(value, maxLength, pattern); + if (identifier) { + return identifier; + } + } + return null; +} + +// Extract the skill identifier from the Skill tool input across the field +// names Claude Code has used for it. The Skill tool is genuinely un-wired in +// this repo, so no single canonical field is guaranteed — probe the plausible +// ones and bail (record nothing) if none is present. +function extractSkillId(toolInput) { + if (typeof toolInput === 'string') { + return boundedIdentifier(toolInput, MAX_SKILL_ID, SKILL_ID_PATTERN); + } + if (!toolInput || typeof toolInput !== 'object') { + return null; + } + return firstIdentifier( + MAX_SKILL_ID, + SKILL_ID_PATTERN, + toolInput.skill_id, + toolInput.skillId, + toolInput.skill, + toolInput.name, + toolInput.command + ); +} + +// Best-effort outcome: a failed tool call is recorded as "failure", everything +// else as "success". Both PostToolUseFailure routing and an error-bearing +// tool response are treated as failure. +function deriveOutcome(payload) { + if (payload && payload.hook_event_name === 'PostToolUseFailure') { + return 'failure'; + } + + const response = (payload && (payload.tool_response ?? payload.tool_output)) || null; + if (response && typeof response === 'object') { + if (response.is_error === true || response.isError === true) { + return 'failure'; + } + if (typeof response.status === 'string' && /error|fail/i.test(response.status)) { + return 'failure'; + } + if (typeof response.error === 'string' && response.error.trim().length > 0) { + return 'failure'; + } + } + + return 'success'; +} + +function buildRecord(payload) { + const skillId = extractSkillId(payload.tool_input); + if (!skillId) { + return null; // cannot satisfy the tracker's required skill_id — skip + } + + const input = payload.tool_input && typeof payload.tool_input === 'object' + ? payload.tool_input + : {}; + + const skillVersion = firstIdentifier( + MAX_SKILL_VERSION, + SKILL_VERSION_PATTERN, + input.skill_version, + input.skillVersion, + input.version + ) || 'unknown'; + + return { + skill_id: skillId, + skill_version: skillVersion, + // Synthesized, not user content. The tracker requires a non-empty + // task_description; the dashboard never displays it as prose. + task_description: `Skill invocation: ${skillId}`, + outcome: deriveOutcome(payload), + }; +} + +function run(rawInput) { + try { + const payload = typeof rawInput === 'string' + ? (rawInput.trim() ? JSON.parse(rawInput) : {}) + : rawInput; + if (payload && typeof payload === 'object' && payload.tool_name === 'Skill') { + const record = buildRecord(payload); + if (record) { + recordSkillExecution(record); + } + } + } catch { + // Telemetry is best-effort; never block tool execution on a failure here. + } +} + +module.exports = { buildRecord, deriveOutcome, extractSkillId, run }; diff --git a/github_code/affaan-m__ECC/scripts/hooks/stop-format-typecheck.js b/github_code/affaan-m__ECC/scripts/hooks/stop-format-typecheck.js new file mode 100644 index 0000000000000000000000000000000000000000..8ae580db5f0f32631151a3343d7caff028c80e80 --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/hooks/stop-format-typecheck.js @@ -0,0 +1,251 @@ +#!/usr/bin/env node +/** + * Stop Hook: Batch format and typecheck all JS/TS files edited this response + * + * Cross-platform (Windows, macOS, Linux) + * + * Reads the accumulator written by post-edit-accumulator.js and processes all + * edited files in one pass: groups files by project root for a single formatter + * invocation per root, and groups .ts/.tsx files by tsconfig dir for a single + * tsc --noEmit per tsconfig. The accumulator is cleared on read so repeated + * Stop calls do not double-process files. + * + * Per-batch timeout is proportional to the number of batches so the total + * never exceeds the Stop hook budget (90 s reserved for overhead). + */ + +'use strict'; + +const crypto = require('crypto'); +const { execFileSync, spawnSync } = require('child_process'); +const fs = require('fs'); +const os = require('os'); +const path = require('path'); + +const { findProjectRoot, detectFormatter, resolveFormatterBin } = require('../lib/resolve-formatter'); + +const MAX_STDIN = 1024 * 1024; +// Total ms budget reserved for all batches (leaves headroom below the 300s Stop timeout) +const TOTAL_BUDGET_MS = 270_000; + +// Characters cmd.exe treats as separators/operators when shell: true is used. +// Includes spaces and parentheses to guard paths like "C:\Users\John Doe\...". +const UNSAFE_PATH_CHARS = /[&|<>^%!\s()]/; + +/** Parse the accumulator text into a deduplicated array of file paths. */ +function parseAccumulator(raw) { + return [...new Set(raw.split('\n').map(l => l.trim()).filter(Boolean))]; +} + +/** + * Is this file part of an installed plugin or marketplace clone? + * + * Those trees are third-party checkouts we merely read. Formatting them writes + * to code the user does not own, and when a repo's committed code has drifted + * from its own formatter config the rewrite is large: an unrelated bugfix ends + * up carrying hundreds of reformatted lines it never touched, which is enough + * to sink the contribution it was meant to support. + * + * Checks both a project-local install root and the user-level one, mirroring + * the lookup in scripts/harness-audit.js. + */ +function isPluginClonePath(filePath, cwd = process.cwd(), homeDir = os.homedir()) { + const resolved = path.resolve(filePath); + const roots = [path.join(cwd, '.claude', 'plugins')]; + if (homeDir) roots.push(path.join(homeDir, '.claude', 'plugins')); + + return roots.some(root => { + const rel = path.relative(root, resolved); + return rel !== '' && !rel.startsWith('..') && !path.isAbsolute(rel); + }); +} + +function getAccumFile() { + const raw = + process.env.CLAUDE_SESSION_ID || + crypto.createHash('sha1').update(process.cwd()).digest('hex').slice(0, 12); + const sessionId = raw.replace(/[^a-zA-Z0-9_-]/g, '_').slice(0, 64); + return path.join(os.tmpdir(), `ecc-edited-${sessionId}.txt`); +} + +function formatBatch(projectRoot, files, timeoutMs) { + const formatter = detectFormatter(projectRoot); + if (!formatter) return; + + const resolved = resolveFormatterBin(projectRoot, formatter); + if (!resolved) return; + + const existingFiles = files.filter(f => fs.existsSync(f)); + if (existingFiles.length === 0) return; + + const fileArgs = + formatter === 'biome' + ? [...resolved.prefix, 'check', '--write', ...existingFiles] + : [...resolved.prefix, '--write', ...existingFiles]; + + try { + if (process.platform === 'win32' && resolved.bin.endsWith('.cmd')) { + if (existingFiles.some(f => UNSAFE_PATH_CHARS.test(f))) { + process.stderr.write('[Hook] stop-format-typecheck: skipping batch — unsafe path chars\n'); + return; + } + const result = spawnSync(resolved.bin, fileArgs, { cwd: projectRoot, shell: true, stdio: 'pipe', timeout: timeoutMs }); + if (result.error) throw result.error; + } else { + execFileSync(resolved.bin, fileArgs, { cwd: projectRoot, stdio: ['pipe', 'pipe', 'pipe'], timeout: timeoutMs }); + } + } catch { + // Formatter not installed or failed — non-blocking + } +} + +function findTsConfigDir(filePath) { + let dir = path.dirname(filePath); + const fsRoot = path.parse(dir).root; + let depth = 0; + while (dir !== fsRoot && depth < 20) { + if (fs.existsSync(path.join(dir, 'tsconfig.json'))) return dir; + dir = path.dirname(dir); + depth++; + } + return null; +} + +function typecheckBatch(tsConfigDir, editedFiles, timeoutMs) { + const isWin = process.platform === 'win32'; + const npxBin = isWin ? 'npx.cmd' : 'npx'; + const args = ['tsc', '--noEmit', '--pretty', 'false']; + const opts = { cwd: tsConfigDir, encoding: 'utf8', stdio: ['pipe', 'pipe', 'pipe'], timeout: timeoutMs }; + + let stdout = ''; + let stderr = ''; + let failed = false; + + try { + if (isWin) { + // .cmd files require shell: true on Windows + const result = spawnSync(npxBin, args, { ...opts, shell: true }); + if (result.error) return; // timed out or not found — non-blocking + if (result.status !== 0) { + stdout = result.stdout || ''; + stderr = result.stderr || ''; + failed = true; + } + } else { + execFileSync(npxBin, args, opts); + } + } catch (err) { + stdout = err.stdout || ''; + stderr = err.stderr || ''; + failed = true; + } + + if (!failed) return; + + const lines = (stdout + stderr).split('\n'); + for (const filePath of editedFiles) { + const relPath = path.relative(tsConfigDir, filePath); + const candidates = new Set([filePath, relPath]); + const relevantLines = lines + .filter(line => { for (const c of candidates) { if (line.includes(c)) return true; } return false; }) + .slice(0, 10); + if (relevantLines.length > 0) { + process.stderr.write(`[Hook] TypeScript errors in ${path.basename(filePath)}:\n`); + relevantLines.forEach(line => process.stderr.write(line + '\n')); + } + } +} + +function main() { + const accumFile = getAccumFile(); + + let raw; + try { + raw = fs.readFileSync(accumFile, 'utf8'); + } catch { + return; // No accumulator — nothing edited this response + } + + try { fs.unlinkSync(accumFile); } catch { /* best-effort */ } + + const files = parseAccumulator(raw); + if (files.length === 0) return; + + const byProjectRoot = new Map(); + for (const filePath of files) { + if (!/\.(ts|tsx|js|jsx)$/.test(filePath)) continue; + if (isPluginClonePath(filePath)) continue; + const resolved = path.resolve(filePath); + if (!fs.existsSync(resolved)) continue; + const root = findProjectRoot(path.dirname(resolved)); + if (!byProjectRoot.has(root)) byProjectRoot.set(root, []); + byProjectRoot.get(root).push(resolved); + } + + const byTsConfigDir = new Map(); + for (const filePath of files) { + if (!/\.(ts|tsx)$/.test(filePath)) continue; + if (isPluginClonePath(filePath)) continue; + const resolved = path.resolve(filePath); + if (!fs.existsSync(resolved)) continue; + const tsDir = findTsConfigDir(resolved); + if (!tsDir) continue; + if (!byTsConfigDir.has(tsDir)) byTsConfigDir.set(tsDir, []); + byTsConfigDir.get(tsDir).push(resolved); + } + + // Distribute the budget evenly across all batches so the cumulative total + // stays within the Stop hook wall-clock limit even in large monorepos. + const totalBatches = byProjectRoot.size + byTsConfigDir.size; + const perBatchMs = totalBatches > 0 ? Math.floor(TOTAL_BUDGET_MS / totalBatches) : 60_000; + + for (const [root, batch] of byProjectRoot) formatBatch(root, batch, perBatchMs); + for (const [tsDir, batch] of byTsConfigDir) typecheckBatch(tsDir, batch, perBatchMs); +} + +/** + * Exported so run-with-flags.js uses require() instead of spawnSync, + * letting the 300s hooks.json timeout govern the full batch. + * + * @param {string} rawInput - Raw JSON string from stdin (Stop event payload) + * @returns {string} The original input (pass-through) + */ +function run(rawInput) { + try { + main(); + } catch (err) { + process.stderr.write(`[Hook] stop-format-typecheck error: ${err.message}\n`); + } + return rawInput; +} + +if (require.main === module) { + let stdinData = ''; + let truncated = false; + process.stdin.setEncoding('utf8'); + process.stdin.on('data', chunk => { + if (stdinData.length < MAX_STDIN) { + const remaining = MAX_STDIN - stdinData.length; + stdinData += chunk.substring(0, remaining); + if (chunk.length > remaining) truncated = true; + } else { + truncated = true; + } + }); + process.stdin.on('end', () => { + const output = run(stdinData); + // Never echo truncated stdin (invalid JSON would be reported as a Stop + // hook failure, #2090); flush stdout before exiting so large payloads + // are not cut at the pipe buffer. + if (truncated) { + process.stderr.write('[Hook] stop-format-typecheck: stdin exceeded 1MB; suppressing pass-through (fail-open)\n'); + process.exit(0); + } + if (!output) { + process.exit(0); + } + process.stdout.write(output, () => process.exit(0)); + }); +} + +module.exports = { run, parseAccumulator, isPluginClonePath }; diff --git a/github_code/affaan-m__ECC/scripts/hooks/suggest-compact.js b/github_code/affaan-m__ECC/scripts/hooks/suggest-compact.js new file mode 100644 index 0000000000000000000000000000000000000000..dc1a414f0968c87990bc6e7a02abefcc7c078017 --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/hooks/suggest-compact.js @@ -0,0 +1,276 @@ +#!/usr/bin/env node +/** + * Strategic Compact Suggester + * + * Cross-platform (Windows, macOS, Linux) + * + * Runs on PreToolUse or periodically to suggest manual compaction at logical intervals + * + * Why manual over auto-compact: + * - Auto-compact happens at arbitrary points, often mid-task + * - Strategic compacting preserves context through logical phases + * - Compact after exploration, before execution + * - Compact after completing a milestone, before starting next + * + * Two signals (#2155): + * - Tool-call count: first at COMPACT_THRESHOLD (default 50), then every 25. + * - Context size (primary): the latest assistant `usage` record from the + * session transcript, compared against a window-scaled token threshold + * (COMPACT_CONTEXT_THRESHOLD; default 160k on a 200k window, 250k on 1M), + * re-reminding after every COMPACT_CONTEXT_INTERVAL tokens of growth + * (default 60k). Tool count is a weak proxy for window pressure — a few + * large reads can fill the window in very few calls, and many tiny calls + * can cross 50 while the window is barely used. + */ + +const fs = require('fs'); +const path = require('path'); +const { + getTempDir, + writeFile, + readStdinJson, + log, + output +} = require('../lib/utils'); +const { + readLatestContextTokens, + resolveContextWindow, + resolveContextThreshold, + resolveContextInterval, + computeContextBucket, + formatWindowLabel +} = require('../lib/transcript-context'); + +const COUNTER_FILE_PREFIX = 'claude-tool-count-'; +const CONTEXT_BUCKET_FILE_PREFIX = 'claude-context-bucket-'; +const STATE_FILE_PREFIXES = [COUNTER_FILE_PREFIX, CONTEXT_BUCKET_FILE_PREFIX]; +const DEFAULT_COMPACT_STATE_TTL_DAYS = 14; + +function getCounterRetentionDays() { + const raw = process.env.COMPACT_STATE_TTL_DAYS; + if (!raw) return DEFAULT_COMPACT_STATE_TTL_DAYS; + const parsed = Number.parseInt(raw, 10); + return Number.isInteger(parsed) && parsed > 0 ? parsed : DEFAULT_COMPACT_STATE_TTL_DAYS; +} + +/** + * Sweep stale per-session state files from the temp dir. + * + * Each session writes `claude-tool-count-` (and, with the context + * signal, `claude-context-bucket-`) into the OS temp dir; nothing + * else removes them. Without a sweep these files accumulate one-per-session + * forever. This helper removes state files whose mtime is older than + * `retentionDays`, while preserving the active session's files (which are + * about to be re-written by the caller). + * + * The helper never throws; per the always-exit-0 hook contract any + * filesystem failure is swallowed and logged to stderr. + * + * @param {string} tempDir - The temp directory to sweep. + * @param {number} retentionDays - Files older than this many days are removed. + * @param {string[]} currentStateFiles - Absolute paths of the active session's + * state files; preserved unconditionally. + */ +function cleanupOldCounters(tempDir, retentionDays, currentStateFiles) { + let entries; + try { + entries = fs.readdirSync(tempDir, { withFileTypes: true }); + } catch (err) { + log(`[StrategicCompact] Skipping counter sweep; readdir failed: ${err.message}`); + return; + } + + const cutoffMs = Date.now() - retentionDays * 24 * 60 * 60 * 1000; + const currentBasenames = new Set(currentStateFiles.map(filePath => path.basename(filePath))); + + for (const entry of entries) { + if (!entry.isFile()) continue; + if (!STATE_FILE_PREFIXES.some(prefix => entry.name.startsWith(prefix))) continue; + if (currentBasenames.has(entry.name)) continue; + + const fullPath = path.join(tempDir, entry.name); + let stats; + try { + stats = fs.statSync(fullPath); + } catch { + continue; + } + + // Strict "older than" semantics per the docstring: a file whose mtime + // sits exactly on the cutoff boundary has age == retentionDays, which + // is not *older than* retentionDays, so preserve it. Use >= so only + // strictly older files (mtimeMs < cutoffMs) fall through to deletion. + if (stats.mtimeMs >= cutoffMs) continue; + + try { + fs.rmSync(fullPath, { force: true }); + } catch (err) { + log(`[StrategicCompact] Warning: failed to prune stale counter ${fullPath}: ${err.message}`); + } + } +} + +/** + * Increment and persist the per-session tool-call counter. + * Uses fd-based read+write to reduce (but not eliminate) the race window + * between concurrent hook invocations. + */ +function incrementToolCallCount(counterFile) { + let count = 1; + + try { + const fd = fs.openSync(counterFile, 'a+'); + try { + const buf = Buffer.alloc(64); + const bytesRead = fs.readSync(fd, buf, 0, 64, 0); + if (bytesRead > 0) { + const parsed = parseInt(buf.toString('utf8', 0, bytesRead).trim(), 10); + // Clamp to reasonable range — corrupted files could contain huge values + // that pass Number.isFinite() (e.g., parseInt('9'.repeat(30)) => 1e+29) + count = (Number.isFinite(parsed) && parsed > 0 && parsed <= 1000000) + ? parsed + 1 + : 1; + } + // Truncate and write new value + fs.ftruncateSync(fd, 0); + fs.writeSync(fd, String(count), 0); + } finally { + fs.closeSync(fd); + } + } catch { + // Fallback: just use writeFile if fd operations fail + writeFile(counterFile, String(count)); + } + + return count; +} + +/** + * Read the last context bucket this session already fired for (-1 when the + * suggestion has not fired yet or the state file is unreadable/corrupted). + */ +function readLastContextBucket(bucketFile) { + try { + const parsed = parseInt(fs.readFileSync(bucketFile, 'utf8').trim(), 10); + return Number.isInteger(parsed) && parsed >= 0 && parsed <= 1000000 ? parsed : -1; + } catch { + return -1; + } +} + +/** + * Build the context-size suggestion when the transcript shows the session has + * crossed into a new context bucket. Returns null when the signal is silent + * (no transcript, below threshold, disabled, or already fired for the bucket). + * + * Never throws — any transcript or state-file failure silently disables the + * signal so the hook keeps its always-exit-0 contract. + */ +function buildContextSuggestion(transcriptPath, bucketFile, env) { + try { + const usage = readLatestContextTokens(transcriptPath); + if (!usage) return null; + + const { windowTokens, inferred } = resolveContextWindow(usage.tokens, usage.model); + const threshold = resolveContextThreshold(env, windowTokens); + if (threshold <= 0) return null; // COMPACT_CONTEXT_THRESHOLD=0 disables + + const interval = resolveContextInterval(env); + const bucket = computeContextBucket(usage.tokens, threshold, interval); + if (bucket < 0) return null; + + const lastBucket = readLastContextBucket(bucketFile); + if (bucket <= lastBucket) return null; + + writeFile(bucketFile, String(bucket)); + + const approxTokens = `${Math.round(usage.tokens / 1000)}k`; + // Only quote a percentage when the window size was actually detected. + // Against an assumed 200k default the denominator is a guess, and a + // "97% of 200k window" line on a 1M session triggers needless compaction. + const scale = inferred + ? '' + : ` (${Math.round((usage.tokens / windowTokens) * 100)}% of ${formatWindowLabel(windowTokens)} window)`; + return `[StrategicCompact] Context ~${approxTokens} tokens${scale} - consider /compact at the next logical boundary`; + } catch (err) { + log(`[StrategicCompact] Context signal skipped: ${err.message}`); + return null; + } +} + +async function main() { + // Claude Code passes hook input via stdin JSON; session_id is the + // canonical field (legacy env var, then 'default', as fallbacks) and + // transcript_path points at the session transcript JSONL used by the + // context-size signal. + let input = {}; + try { + input = await readStdinJson({ timeoutMs: 1000 }); + } catch { + input = {}; + } + + const rawSessionId = (input && typeof input.session_id === 'string' && input.session_id) + ? input.session_id + : (process.env.CLAUDE_SESSION_ID || 'default'); + const sessionId = rawSessionId.replace(/[^a-zA-Z0-9_-]/g, '') || 'default'; + const transcriptPath = (input && typeof input.transcript_path === 'string') ? input.transcript_path : ''; + + const tempDir = getTempDir(); + const counterFile = path.join(tempDir, `${COUNTER_FILE_PREFIX}${sessionId}`); + const bucketFile = path.join(tempDir, `${CONTEXT_BUCKET_FILE_PREFIX}${sessionId}`); + + // Sweep stale state files (concern 1 of #2156). Cheap, swallows errors, + // skips the active session's files. See cleanupOldCounters for details. + cleanupOldCounters(tempDir, getCounterRetentionDays(), [counterFile, bucketFile]); + + const rawThreshold = parseInt(process.env.COMPACT_THRESHOLD || '50', 10); + const threshold = Number.isFinite(rawThreshold) && rawThreshold > 0 && rawThreshold <= 10000 + ? rawThreshold + : 50; + + const count = incrementToolCallCount(counterFile); + + const messages = []; + + // Primary signal (#2155): real context size from the transcript's latest + // usage record. Fires at a window-scaled token threshold and re-fires only + // after the context grows by another interval step. + const contextSuggestion = buildContextSuggestion(transcriptPath, bucketFile, process.env); + if (contextSuggestion) { + messages.push(contextSuggestion); + } + + // Secondary signal: tool-call count at threshold, then every 25 calls. + if (count === threshold) { + messages.push(`[StrategicCompact] ${threshold} tool calls reached - consider /compact if transitioning phases`); + } else if (count > threshold && (count - threshold) % 25 === 0) { + messages.push(`[StrategicCompact] ${count} tool calls - good checkpoint for /compact if context is stale`); + } + + // log() writes to stderr (debug log). Per the Claude Code hooks guide, + // non-blocking PreToolUse stderr (exit 0) is only written to the debug log; + // it does not reach the model. To inject a user-facing suggestion without + // blocking the tool call, emit structured JSON to stdout with + // hookSpecificOutput.additionalContext — the documented mechanism for + // PreToolUse hooks to add context to the next model turn. Hooks must emit + // at most one stdout JSON payload per run, so both signals share it. + if (messages.length > 0) { + for (const msg of messages) { + log(msg); + } + output({ + hookSpecificOutput: { + hookEventName: 'PreToolUse', + additionalContext: messages.join('\n') + } + }); + } + + process.exit(0); +} + +main().catch(err => { + console.error('[StrategicCompact] Error:', err.message); + process.exit(0); +}); diff --git a/github_code/affaan-m__ECC/scripts/install-apply.js b/github_code/affaan-m__ECC/scripts/install-apply.js new file mode 100644 index 0000000000000000000000000000000000000000..1435d2ff665b0595f490afd211fc0295b40d0842 --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/install-apply.js @@ -0,0 +1,236 @@ +#!/usr/bin/env node +/** + * Refactored ECC installer runtime. + * + * Keeps the legacy language-based install entrypoint intact while moving + * target-specific mutation logic into testable Node code. + */ + +const os = require('os'); +const { + SUPPORTED_INSTALL_TARGETS, + listLegacyCompatibilityLanguages, + listSupportedLocales, +} = require('./lib/install-manifests'); +const { + LEGACY_INSTALL_TARGETS, + normalizeInstallRequest, + parseInstallArgs, +} = require('./lib/install/request'); +const { getComputeSponsorCopy } = require('./lib/compute-sponsor'); +const { stripAnsi } = require('./lib/utils'); +const { describeMissingDependencyError } = require('./lib/missing-dependency'); + +function getHelpText() { + const languages = listLegacyCompatibilityLanguages(); + const locales = listSupportedLocales(); + + return ` +Usage: install.sh [--target <${LEGACY_INSTALL_TARGETS.join('|')}>] [--dry-run] [--json] [ ...] + install.sh [--target <${SUPPORTED_INSTALL_TARGETS.join('|')}>] [--dry-run] [--json] --profile [--with ]... [--without ]... + install.sh [--target <${SUPPORTED_INSTALL_TARGETS.join('|')}>] [--dry-run] [--json] --modules [--with ]... [--without ]... + install.sh [--target <${SUPPORTED_INSTALL_TARGETS.join('|')}>] [--dry-run] [--json] --skills + install.sh [--target claude|claude-project] [--dry-run] [--json] --locale + install.sh [--dry-run] [--json] --config + +Targets: + claude (default) - Install ECC into ~/.claude/ with managed rules under rules/ecc and flat skills under skills/ + claude-project - Install ECC into ./.claude/ (per-project) with managed rules under rules/ecc and flat skills under skills/ + cursor - Install rules, hooks, and bundled Cursor configs to ./.cursor/ + antigravity - Install rules, workflows, skills, and agents to ./.agents/ + codex - Install shared agents/config into ~/.codex/ + gemini - Install project-local Gemini config into ./.gemini/ + opencode - Install into OPENCODE_CONFIG_DIR, XDG_CONFIG_HOME/opencode, or ~/.config/opencode/ + codebuddy - Install commands, agents, skills, and flattened rules into ./.codebuddy/ + joycode - Install commands, agents, skills, and flattened rules into ./.joycode/ + qwen - Install commands, agents, skills, rules, and Qwen config into ~/.qwen/ + zed - Install project settings, commands, agents, skills, and flattened rules into ./.zed/ + hermes - Install shared rules/skills/commands into ~/.hermes/ + kimi - Install Kimi Code project instructions, skills, and MCP config into ./.kimi-code/ (ECC hooks not configured) + openclaw - Install shared rules/skills/commands into ~/.openclaw/ + adal - Install shared rules/skills/commands into ./.adal/ + +Options: + --profile Resolve and install a manifest profile + --modules Resolve and install explicit module IDs + --with Include a user-facing install component + --skills Install one or more skill directories by ID, e.g. continuous-learning-v2 + --without + Exclude a user-facing install component + --locale Install translated docs to ~/.claude/docs// (or ./.claude/docs// for claude-project) + (claude or claude-project target only; can be combined with --profile or --with) + --config Load install intent from ecc-install.json + --enable-hooks Confirm installing the automatic hook runtime (required + when the selected profile/modules materialize hooks) + --no-hooks Install everything except the automatic hook runtime + --dry-run Show the install plan without copying files + --json Emit machine-readable plan/result JSON + --help Show this help text + +Compute: + ${getComputeSponsorCopy()} + +Available languages: +${languages.map(language => ` - ${language}`).join('\n')} + +Available locales (--locale): +${locales.map(locale => ` - ${locale}`).join('\n')} +`; +} + +function showHelp(exitCode = 0) { + console.log(getHelpText()); + process.exit(exitCode); +} + +function printHumanPlan(plan, dryRun) { + console.log(`${dryRun ? 'Dry-run install plan' : 'Applying install plan'}:\n`); + console.log(`Mode: ${plan.mode}`); + console.log(`Target: ${plan.target}`); + console.log(`Adapter: ${plan.adapter.id}`); + console.log(`Install root: ${plan.installRoot}`); + console.log(`Install-state: ${plan.installStatePath}`); + if (plan.mode === 'legacy') { + console.log(`Languages: ${plan.languages.join(', ')}`); + } else { + if (plan.mode === 'legacy-compat') { + console.log(`Legacy languages: ${plan.legacyLanguages.join(', ')}`); + } + console.log(`Profile: ${plan.profileId || '(custom modules)'}`); + console.log(`Included components: ${plan.includedComponentIds.join(', ') || '(none)'}`); + console.log(`Excluded components: ${plan.excludedComponentIds.join(', ') || '(none)'}`); + console.log(`Requested modules: ${plan.requestedModuleIds.join(', ') || '(none)'}`); + console.log(`Selected modules: ${plan.selectedModuleIds.join(', ') || '(none)'}`); + if (plan.skippedModuleIds.length > 0) { + console.log(`Skipped modules: ${plan.skippedModuleIds.join(', ')}`); + } + if (plan.excludedModuleIds.length > 0) { + console.log(`Excluded modules: ${plan.excludedModuleIds.join(', ')}`); + } + } + console.log(`${dryRun ? 'Operations' : 'Applied operations'}: ${plan.operations.length}`); + if (Array.isArray(plan.skippedOperations) && plan.skippedOperations.length > 0) { + console.log(`Skipped operations: ${plan.skippedOperations.length}`); + } + + if (plan.warnings.length > 0) { + console.log('\nWarnings:'); + for (const warning of plan.warnings) { + console.log(`- ${warning}`); + } + } + + console.log(`\n${dryRun ? 'Planned' : 'Applied'} file operations:`); + for (const operation of plan.operations) { + console.log(`- ${operation.sourceRelativePath} -> ${operation.destinationPath}`); + } + + if (Array.isArray(plan.skippedOperations) && plan.skippedOperations.length > 0) { + console.log('\nSkipped file operations:'); + for (const operation of plan.skippedOperations) { + console.log(`- ${operation.sourceRelativePath} -> ${operation.destinationPath}`); + } + } + + if (!dryRun) { + console.log(`\nDone. Install-state written to ${plan.installStatePath}`); + } + + console.log('\nCompute: ' + getComputeSponsorCopy()); +} + +async function main() { + try { + const options = parseInstallArgs(process.argv); + + if (options.help) { + showHelp(0); + } + + const { + findDefaultInstallConfigPath, + loadInstallConfig, + } = require('./lib/install/config'); + const { + applyInstallPlan, + previewInstallPlan, + } = require('./lib/install-executor'); + const { createInstallPlanFromRequest } = require('./lib/install/runtime'); + const defaultConfigPath = options.configPath || options.languages.length > 0 + ? null + : findDefaultInstallConfigPath({ cwd: process.cwd() }); + const config = options.configPath + ? loadInstallConfig(options.configPath, { cwd: process.cwd() }) + : (defaultConfigPath ? loadInstallConfig(defaultConfigPath, { cwd: process.cwd() }) : null); + const request = normalizeInstallRequest({ + ...options, + config, + }); + const rawPlan = createInstallPlanFromRequest(request, { + projectRoot: process.cwd(), + homeDir: process.env.HOME || os.homedir(), + env: process.env, + claudeRulesDir: process.env.CLAUDE_RULES_DIR || null, + }); + + if (options.dryRun) { + const plan = previewInstallPlan(rawPlan); + if (options.json) { + console.log(JSON.stringify({ dryRun: true, plan }, null, 2)); + } else { + printHumanPlan(plan, true); + } + return; + } + + let result = applyInstallPlan(rawPlan); + const { projectCanonicalInstallState } = require('./lib/install-state-store-sync'); + const installStateProjection = await projectCanonicalInstallState(result.statePreview, { + homeDir: process.env.HOME || os.homedir(), + }); + result = { + ...result, + installStateProjection, + warnings: installStateProjection.warning + ? [...result.warnings, `Install health projection warning: ${installStateProjection.warning.message}`] + : result.warnings, + }; + if (options.json) { + console.log(JSON.stringify({ dryRun: false, result }, null, 2)); + } else { + printHumanPlan(result, false); + } + } catch (error) { + const missingDependencyMessage = describeMissingDependencyError(error); + process.stderr.write( + missingDependencyMessage + ? `Error: ${missingDependencyMessage}\n` + : `Error: ${error.message}${getHelpText()}` + ); + process.exit(1); + } +} + +function sanitizeTerminalText(value) { + return stripAnsi(String(value || '')).replace(/[^\x20-\x7E]/g, '?'); +} + +function runGuidedMain(guidedArgs) { + Promise.resolve() + .then(() => require('./install-guided').main(guidedArgs)) + .then(exitCode => { + process.exitCode = exitCode; + }) + .catch(error => { + process.stderr.write(`Error: ${sanitizeTerminalText(error?.message)}\n`); + process.exitCode = 1; + }); +} + +const cliArgs = process.argv.slice(2); +if (cliArgs.includes('--guided')) { + const guidedArgs = cliArgs.filter(argument => argument !== '--guided'); + runGuidedMain(guidedArgs); +} else { + main(); +} diff --git a/github_code/affaan-m__ECC/scripts/install-guided.js b/github_code/affaan-m__ECC/scripts/install-guided.js new file mode 100644 index 0000000000000000000000000000000000000000..4fa27525dfdb6485b9dd97d80e0d8280fe1e4ac4 --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/install-guided.js @@ -0,0 +1,346 @@ +#!/usr/bin/env node +'use strict'; + +const readline = require('readline/promises'); + +const { + getHarnessCapability, + listGuidedHarnesses, + normalizeHarnessSelection, +} = require('./lib/harness-capabilities'); +const { + VALID_CLAUDE_HOOKS, + VALID_CLAUDE_SCOPES, + VALID_PROFILES, + applyMultiHarnessPlan, + createMultiHarnessPlan, + normalizeGuidedInstallRequest, +} = require('./lib/multi-harness-setup'); +const { formatHookCapabilityDisclosure } = require('./lib/install/hook-consent'); +const { startTerminalSpinner } = require('./lib/terminal-spinner'); +const { showTerminalWelcome } = require('./lib/terminal-welcome'); +const { stripAnsi } = require('./lib/utils'); + +const ADVANCED_HARNESSES = 'Cursor, Antigravity, Gemini CLI, OpenCode, CodeBuddy, JoyCode, Qwen Code, Zed, Hermes, and OpenClaw'; + +function showHelp(output = process.stdout) { + output.write(` +ECC guided multi-harness install + +Usage: + ecc install --guided + ecc install --guided --harness claude --harness codex --harness kimi [options] + +Guided harnesses: + claude Native Claude Code plugin; choose user, project, or local scope and an ECC hook profile. + codex Native Codex plugin and Codex-owned hook review/trust. + kimi Managed project install under ./.kimi-code; ECC hooks are not configured. + +Options: + --harness Repeatable; accepts Claude, Codex, Kimi, or all + --all-harnesses Select all three guided harnesses + --claude-scope + --claude-hooks + --profile + Kimi managed-project content profile + --yes, -y Apply without confirmation + --dry-run Preflight and preview without changing files + --json Emit machine-readable output + --help, -h Show this help + +Advanced managed adapters remain available through explicit ecc install --target commands: + ${ADVANCED_HARNESSES} + +This command configures ECC. It does not install or authenticate provider CLIs. +`); +} + +function parseArgs(argv) { + let options = { + allHarnesses: false, + claudeHooks: undefined, + claudeScope: undefined, + dryRun: false, + harnesses: [], + help: false, + json: false, + profile: undefined, + yes: false, + }; + const valueFlags = new Map([ + ['--harness', 'harnesses'], + ['--claude-scope', 'claudeScope'], + ['--claude-hooks', 'claudeHooks'], + ['--profile', 'profile'], + ]); + + for (let index = 0; index < argv.length; index += 1) { + const argument = argv[index]; + if (valueFlags.has(argument)) { + const value = argv[index + 1]; + if (!value || value.startsWith('--')) { + throw new Error(`Missing value for ${argument}`); + } + if (value.length > 256) { + throw new Error(`Value for ${argument} is too long.`); + } + const key = valueFlags.get(argument); + options = key === 'harnesses' + ? { ...options, harnesses: [...options.harnesses, value] } + : { ...options, [key]: value }; + index += 1; + } else if (argument === '--all-harnesses') { + options = { ...options, allHarnesses: true }; + } else if (argument === '--yes' || argument === '-y') { + options = { ...options, yes: true }; + } else if (argument === '--dry-run') { + options = { ...options, dryRun: true }; + } else if (argument === '--json') { + options = { ...options, json: true }; + } else if (argument === '--help' || argument === '-h') { + options = { ...options, help: true }; + } else { + throw new Error('Unknown argument. Run guided install with --help to see valid options.'); + } + } + if (options.allHarnesses && options.harnesses.length > 0) { + throw new Error('--all-harnesses and --harness are mutually exclusive.'); + } + return options; +} + +function choicesText(values) { + return values.join('|'); +} + +async function askChoice(terminal, output, prompt, values, defaultValue) { + output.write(`\n${prompt}\n`); + values.forEach((value, index) => output.write(` ${index + 1}. ${value}\n`)); + while (true) { + const question = defaultValue + ? `Choose [Recommended: ${defaultValue}] (one option only): ` + : 'Choose one option: '; + const answer = (await terminal.question(question)).trim().toLowerCase(); + if (!answer && defaultValue) return defaultValue; + const numeric = /^\d+$/.test(answer) ? values[Number(answer) - 1] : undefined; + const selected = numeric || values.find(value => value === answer); + if (selected) return selected; + output.write(`Please choose ${choicesText(values)}.\n`); + } +} + +async function askHarnesses(terminal, output) { + const guided = listGuidedHarnesses(); + output.write('\nWhich coding agents should ECC configure?\n'); + guided.forEach((harness, index) => { + output.write(` ${index + 1}. ${harness.label} — ${harness.destination}\n`); + }); + output.write(' all. All three guided harnesses\n'); + output.write(`\nAdvanced adapters (use ecc install --target): ${ADVANCED_HARNESSES}.\n\n`); + while (true) { + const answer = await terminal.question('Choose one or more (for example 1,3 or all): '); + if (answer.length > 1024) { + output.write('Please choose Claude, Codex, Kimi, or all.\n'); + continue; + } + try { + return normalizeHarnessSelection(answer); + } catch (_error) { + output.write('Please choose Claude, Codex, Kimi, or all.\n'); + } + } +} + +async function collectInteractiveOptions(options, dependencies = {}) { + const terminal = dependencies.terminal; + const output = dependencies.output || process.stdout; + let harnesses = options.allHarnesses ? ['all'] : options.harnesses; + if (harnesses.length === 0) harnesses = await askHarnesses(terminal, output); + const normalizedHarnesses = normalizeHarnessSelection(harnesses); + const includesClaude = normalizedHarnesses.includes('claude'); + const includesKimi = normalizedHarnesses.includes('kimi'); + const claudeScope = includesClaude && !options.claudeScope + ? await askChoice(terminal, output, 'Where should Claude enable ecc@ecc?', [...VALID_CLAUDE_SCOPES], 'user') + : options.claudeScope; + const claudeHooks = includesClaude && !options.claudeHooks + ? await askChoice(terminal, output, 'How should ECC hooks run in Claude?', [...VALID_CLAUDE_HOOKS], 'standard') + : options.claudeHooks; + const profile = includesKimi && !options.profile + ? await askChoice(terminal, output, 'Which ECC content profile should Kimi receive?', [...VALID_PROFILES], 'core') + : options.profile; + return { + ...options, + harnesses: normalizedHarnesses, + claudeScope, + claudeHooks, + profile, + }; +} + +function selectedHarnessIds(options) { + if (options.allHarnesses) return normalizeHarnessSelection(['all']); + if (options.harnesses.length === 0) return []; + return normalizeHarnessSelection(options.harnesses); +} + +function validateExecutionMode(options, interactive) { + const harnesses = selectedHarnessIds(options); + if (!interactive && harnesses.length === 0) { + throw new Error('Non-interactive guided install requires at least one --harness.'); + } + const requiresExplicit = !interactive || options.json; + if (requiresExplicit && harnesses.includes('claude') && (!options.claudeScope || !options.claudeHooks)) { + throw new Error('Claude requires explicit --claude-scope and --claude-hooks choices in this mode.'); + } + if (requiresExplicit && harnesses.includes('kimi') && !options.profile) { + throw new Error('Kimi requires an explicit --profile choice in this mode.'); + } + if ((!interactive || options.json) && !options.yes && !options.dryRun) { + throw new Error('Non-interactive and JSON mutations require --yes.'); + } +} + +function printPlan(plan, output) { + output.write('\nECC guided install preview\n\n'); + output.write('Harness Channel Destination\n'); + for (const entry of plan.harnesses) { + const harness = getHarnessCapability(entry.id); + output.write(`${harness.label.padEnd(13)} ${entry.channel.padEnd(17)} ${harness.destination}\n`); + } + if (plan.request.harnesses.includes('kimi')) { + output.write('\nKimi note: ECC hooks are not configured; model, provider, and authentication settings are unchanged.\n'); + } + if (plan.request.harnesses.includes('claude') && plan.request.claudeHooks && plan.request.claudeHooks !== 'off') { + output.write( + `\nClaude hook profile '${plan.request.claudeHooks}' enables automation that can:\n` + + `${formatHookCapabilityDisclosure()}\n` + + "Choose '--claude-hooks off' to install without automatic hook behavior.\n" + ); + } +} + +async function confirmPlan(terminal, output) { + output.write('\n'); + const answer = await terminal.question('Apply ECC to these harnesses? [y/N]: '); + return /^y(es)?$/i.test(answer.trim()); +} + +function sanitizeTerminalText(value) { + return stripAnsi(String(value || '')).replace(/[^\x20-\x7E]/g, '?'); +} + +function buildRetryArguments(plan, retryHarnesses) { + const harnesses = [...retryHarnesses]; + const harnessArguments = harnesses.flatMap(id => ['--harness', id]); + const claudeArguments = harnesses.includes('claude') + ? ['--claude-scope', plan.request.claudeScope, '--claude-hooks', plan.request.claudeHooks] + : []; + const kimiArguments = harnesses.includes('kimi') + ? ['--profile', plan.request.profile] + : []; + return [...harnessArguments, ...claudeArguments, ...kimiArguments].join(' '); +} + +async function main(argv = process.argv.slice(2), injected = {}) { + const output = injected.output || process.stdout; + const errorOutput = injected.errorOutput || process.stderr; + const interactive = injected.interactive !== undefined + ? injected.interactive + : Boolean(process.stdin.isTTY && output.isTTY); + const createPlan = injected.createPlan || createMultiHarnessPlan; + const applyPlan = injected.applyPlan || applyMultiHarnessPlan; + const renderWelcome = injected.showWelcome || showTerminalWelcome; + const makeSpinner = injected.startSpinner || startTerminalSpinner; + let terminal = injected.terminal; + let ownsTerminal = false; + + try { + let options = parseArgs(argv); + if (options.help) { + showHelp(output); + return 0; + } + validateExecutionMode(options, interactive); + const needsChoices = selectedHarnessIds(options).length === 0 + || (selectedHarnessIds(options).includes('claude') && (!options.claudeScope || !options.claudeHooks)) + || (selectedHarnessIds(options).includes('kimi') && !options.profile); + if (interactive && needsChoices) { + if (!terminal) { + terminal = readline.createInterface({ input: process.stdin, output }); + ownsTerminal = true; + } + options = await collectInteractiveOptions(options, { output, terminal }); + } + const request = normalizeGuidedInstallRequest({ + ...options, + harnesses: options.allHarnesses ? ['all'] : options.harnesses, + }); + const plan = await createPlan(request); + + if (options.json && options.dryRun) { + output.write(`${JSON.stringify({ dryRun: true, plan }, null, 2)}\n`); + return 0; + } + if (!options.json) printPlan(plan, output); + if (options.dryRun) { + output.write('\nDry run complete. No changes were made.\n'); + return 0; + } + if (!options.yes) { + if (!terminal) { + terminal = readline.createInterface({ input: process.stdin, output }); + ownsTerminal = true; + } + if (!await confirmPlan(terminal, output)) { + output.write('\nECC install cancelled. No changes were made.\n'); + return 0; + } + } + + const spinner = interactive && !options.json + ? makeSpinner('Applying ECC to selected harnesses...') + : undefined; + let result; + try { + result = await applyPlan(plan); + } finally { + spinner?.stop(); + } + if (options.json) { + output.write(`${JSON.stringify({ dryRun: false, result }, null, 2)}\n`); + } else if (result.status === 'complete') { + output.write(`\nECC configured for ${result.completed.map(item => getHarnessCapability(item.id).label).join(', ')}.\n`); + renderWelcome({ action: 'installed', interactive, json: false, output }); + } else { + const retry = buildRetryArguments(plan, result.retryHarnesses); + errorOutput.write( + `ECC stopped at ${sanitizeTerminalText(result.failure.id)}: ` + + `${sanitizeTerminalText(result.failure.message)}\n` + + `Retry with: ecc-universal install --guided ${retry}\n` + ); + } + return result.status === 'complete' ? 0 : 1; + } catch (error) { + const payload = { error: { code: 'GUIDED_INSTALL_FAILED', message: error.message } }; + if (argv.includes('--json')) errorOutput.write(`${JSON.stringify(payload, null, 2)}\n`); + else errorOutput.write(`Error: ${sanitizeTerminalText(error.message)}\n`); + return 1; + } finally { + if (ownsTerminal) terminal?.close(); + } +} + +if (require.main === module) { + main().then(code => { + process.exitCode = code; + }); +} + +module.exports = { + collectInteractiveOptions, + main, + parseArgs, + printPlan, + showHelp, + validateExecutionMode, +}; diff --git a/github_code/affaan-m__ECC/scripts/install-plan.js b/github_code/affaan-m__ECC/scripts/install-plan.js new file mode 100644 index 0000000000000000000000000000000000000000..e2d5fc653819e6b6cda61cd9cb46a4b8f8877a92 --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/install-plan.js @@ -0,0 +1,277 @@ +#!/usr/bin/env node +/** + * Inspect selective-install profiles and module plans without mutating targets. + */ + +const { + listInstallComponents, + listInstallModules, + listInstallProfiles, + resolveInstallPlan, +} = require('./lib/install-manifests'); +const { + findDefaultInstallConfigPath, + loadInstallConfig, +} = require('./lib/install/config'); +const { normalizeInstallRequest } = require('./lib/install/request'); +const { describeMissingDependencyError } = require('./lib/missing-dependency'); + +function showHelp() { + console.log(` +Inspect ECC selective-install manifests + +Usage: + node scripts/install-plan.js --list-profiles + node scripts/install-plan.js --list-modules + node scripts/install-plan.js --list-components [--family ] [--target ] [--json] + node scripts/install-plan.js --profile [--with ]... [--without ]... [--target ] [--json] + node scripts/install-plan.js --modules [--with ]... [--without ]... [--target ] [--json] + node scripts/install-plan.js --skills [--target ] [--json] + node scripts/install-plan.js --config [--json] + +Options: + --list-profiles List available install profiles + --list-modules List install modules + --list-components List user-facing install components + --family Filter listed components by family + --profile Resolve an install profile + --modules Resolve explicit module IDs (comma-separated) + --with Include a user-facing install component + --skills Include one or more skill components by directory ID + --without + Exclude a user-facing install component + --config Load install intent from ecc-install.json + --target Filter plan for a specific target + --json Emit machine-readable JSON + --help Show this help text +`); +} + +function parseArgs(argv) { + const args = argv.slice(2); + const parsed = { + json: false, + help: false, + profileId: null, + moduleIds: [], + includeComponentIds: [], + excludeComponentIds: [], + configPath: null, + target: null, + family: null, + listProfiles: false, + listModules: false, + listComponents: false, + }; + + function normalizeSkillComponentIds(rawValue) { + return [...new Set(String(rawValue || '').split(',').map(value => value.trim()).filter(Boolean))] + .map(value => (value.startsWith('skill:') ? value : `skill:${value}`)); + } + + for (let index = 0; index < args.length; index += 1) { + const arg = args[index]; + if (arg === '--help' || arg === '-h') { + parsed.help = true; + } else if (arg === '--json') { + parsed.json = true; + } else if (arg === '--list-profiles') { + parsed.listProfiles = true; + } else if (arg === '--list-modules') { + parsed.listModules = true; + } else if (arg === '--list-components') { + parsed.listComponents = true; + } else if (arg === '--family') { + parsed.family = args[index + 1] || null; + index += 1; + } else if (arg === '--profile') { + parsed.profileId = args[index + 1] || null; + index += 1; + } else if (arg === '--modules') { + const raw = args[index + 1] || ''; + parsed.moduleIds = raw.split(',').map(value => value.trim()).filter(Boolean); + index += 1; + } else if (arg === '--with') { + const componentId = args[index + 1] || ''; + if (componentId.trim()) { + parsed.includeComponentIds.push(componentId.trim()); + } + index += 1; + } else if (arg === '--skill' || arg === '--skills') { + parsed.includeComponentIds.push(...normalizeSkillComponentIds(args[index + 1] || '')); + index += 1; + } else if (arg === '--without') { + const componentId = args[index + 1] || ''; + if (componentId.trim()) { + parsed.excludeComponentIds.push(componentId.trim()); + } + index += 1; + } else if (arg === '--config') { + parsed.configPath = args[index + 1] || null; + index += 1; + } else if (arg === '--target') { + parsed.target = args[index + 1] || null; + index += 1; + } else { + throw new Error(`Unknown argument: ${arg}`); + } + } + + return parsed; +} + +function printProfiles(profiles) { + console.log('Install profiles:\n'); + for (const profile of profiles) { + console.log(`- ${profile.id} (${profile.moduleCount} modules)`); + console.log(` ${profile.description}`); + } +} + +function printModules(modules) { + console.log('Install modules:\n'); + for (const module of modules) { + console.log(`- ${module.id} [${module.kind}]`); + console.log( + ` targets=${module.targets.join(', ')} default=${module.defaultInstall} cost=${module.cost} stability=${module.stability}` + ); + console.log(` ${module.description}`); + } +} + +function printComponents(components) { + console.log('Install components:\n'); + for (const component of components) { + console.log(`- ${component.id} [${component.family}]`); + console.log(` targets=${component.targets.join(', ')} modules=${component.moduleIds.join(', ')}`); + console.log(` ${component.description}`); + } +} + +function printPlan(plan) { + console.log('Install plan:\n'); + console.log( + 'Note: target filtering and operation output currently reflect scaffold-level adapter planning, not a byte-for-byte mirror of legacy install.sh copy paths.\n' + ); + console.log(`Profile: ${plan.profileId || '(custom modules)'}`); + console.log(`Target: ${plan.target || '(all targets)'}`); + console.log(`Included components: ${plan.includedComponentIds.join(', ') || '(none)'}`); + console.log(`Excluded components: ${plan.excludedComponentIds.join(', ') || '(none)'}`); + console.log(`Requested: ${plan.requestedModuleIds.join(', ')}`); + if (plan.targetAdapterId) { + console.log(`Adapter: ${plan.targetAdapterId}`); + console.log(`Target root: ${plan.targetRoot}`); + console.log(`Install-state: ${plan.installStatePath}`); + } + console.log(''); + console.log(`Selected modules (${plan.selectedModuleIds.length}):`); + for (const module of plan.selectedModules) { + console.log(`- ${module.id} [${module.kind}]`); + } + + if (plan.skippedModuleIds.length > 0) { + console.log(''); + console.log(`Skipped for target ${plan.target} (${plan.skippedModuleIds.length}):`); + for (const module of plan.skippedModules) { + console.log(`- ${module.id} [${module.kind}]`); + } + } + + if (plan.excludedModuleIds.length > 0) { + console.log(''); + console.log(`Excluded by selection (${plan.excludedModuleIds.length}):`); + for (const module of plan.excludedModules) { + console.log(`- ${module.id} [${module.kind}]`); + } + } + + if (plan.operations.length > 0) { + console.log(''); + console.log(`Operation plan (${plan.operations.length}):`); + for (const operation of plan.operations) { + console.log( + `- ${operation.moduleId}: ${operation.sourceRelativePath} -> ${operation.destinationPath} [${operation.strategy}]` + ); + } + } +} + +function main() { + try { + const options = parseArgs(process.argv); + + if (options.help) { + showHelp(); + process.exit(0); + } + + if (options.listProfiles) { + const profiles = listInstallProfiles(); + if (options.json) { + console.log(JSON.stringify({ profiles }, null, 2)); + } else { + printProfiles(profiles); + } + return; + } + + if (options.listModules) { + const modules = listInstallModules(); + if (options.json) { + console.log(JSON.stringify({ modules }, null, 2)); + } else { + printModules(modules); + } + return; + } + + if (options.listComponents) { + const components = listInstallComponents({ + family: options.family, + target: options.target, + }); + if (options.json) { + console.log(JSON.stringify({ components }, null, 2)); + } else { + printComponents(components); + } + return; + } + + const defaultConfigPath = options.configPath + ? null + : findDefaultInstallConfigPath({ cwd: process.cwd() }); + const config = options.configPath + ? loadInstallConfig(options.configPath, { cwd: process.cwd() }) + : (defaultConfigPath ? loadInstallConfig(defaultConfigPath, { cwd: process.cwd() }) : null); + + if (process.argv.length <= 2 && !config) { + showHelp(); + process.exit(0); + } + + const request = normalizeInstallRequest({ + ...options, + languages: [], + config, + }); + const plan = resolveInstallPlan({ + profileId: request.profileId, + moduleIds: request.moduleIds, + includeComponentIds: request.includeComponentIds, + excludeComponentIds: request.excludeComponentIds, + target: request.target, + }); + + if (options.json) { + console.log(JSON.stringify(plan, null, 2)); + } else { + printPlan(plan); + } + } catch (error) { + console.error(`Error: ${describeMissingDependencyError(error) || error.message}`); + process.exit(1); + } +} + +main(); diff --git a/github_code/affaan-m__ECC/scripts/ito.js b/github_code/affaan-m__ECC/scripts/ito.js new file mode 100644 index 0000000000000000000000000000000000000000..e981d85ee5b7bce339a67c005a46beb949dceca6 --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/ito.js @@ -0,0 +1,327 @@ +#!/usr/bin/env node + +"use strict"; + +const fs = require("fs"); +const path = require("path"); +const { spawnSync } = require("child_process"); +const { + createSafeItoInvocationEnvironment, + getInvocationCommand, +} = require("./lib/ito-environment"); + +const SUPPORTED_COMMANDS = Object.freeze(["login", "logout", "auth", "find", "status", "evals"]); +const CANONICAL_REPOSITORY = "https://github.com/Ito-Markets/ito-cloud-runtime.git"; +const CANONICAL_PACKAGE_PATH = "cli/ito-compute-cli"; +const CANONICAL_ENTRY_SEGMENTS = Object.freeze([ + ...CANONICAL_PACKAGE_PATH.split("/"), + "dist", + "bin", + "ito.js", +]); +const EXECUTABLE_OVERRIDE = "ECC_ITO_CLI_EXECUTABLE"; +const MAX_OUTPUT_BYTES = 10 * 1024 * 1024; +const NODE_QUALIFICATION_TIMEOUT_MS = 31 * 60 * 1000; + +function showHelp() { + process.stdout.write(` +ECC × Itô local CLI bridge + +Usage: + ecc ito login [--no-browser] + ecc ito logout + ecc ito auth + ecc ito find + ecc ito status + ecc ito evals --cluster --live-sixtytwo --nodes --config-dir + ecc ito --json + +The bridge invokes the separately installed canonical Itô CLI and returns its +real stdout, stderr, and exit code unchanged. "ecc ito login" delegates to the +canonical CLI's device authorization. It opens the Itô verification page by default +and persists its device token in macOS Keychain. Pass --no-browser to +suppress that handoff. ECC itself performs no browser automation and adds no +lock, workload, inference, or purchase path. +"ecc ito auth" is validation-only and never starts device login. +"ecc ito logout" asks the canonical CLI to revoke the current device credential +and remove its local copy only after remote revocation is confirmed. + +Important: + - "find" reads live inventory and submits an authenticated RFQ. + - Obtain explicit buyer authority and every hard constraint before invoking it. + - "status" reads live RFQ and procurement status. + - "evals" invokes only the canonical CLI's double-opt-in, pinned + sixtytwo-cli node-qualification adapter against explicit nodes. + - Node qualification cannot rent, launch, recover, repair, or purchase. + - Inventory and RFQs are not reservations; only a returned firm quote is firm. + +The canonical package is currently unpublished. Install it locally: + Canonical source: Ito-Markets/ito-cloud-runtime/${CANONICAL_PACKAGE_PATH} + git clone ${CANONICAL_REPOSITORY} + cd ito-cloud-runtime/${CANONICAL_PACKAGE_PATH} + npm ci + npm run check + +Then set ${EXECUTABLE_OVERRIDE} to the explicit absolute built entry: + /absolute/path/to/ito-cloud-runtime/${CANONICAL_PACKAGE_PATH}/dist/bin/ito.js + +For safety, ECC never discovers this credential-bearing client through PATH. + +The same package's MCP server exposes only: + ito_auth + ito_find + ito_status + +Configure the MCP command as "node" with this absolute argument: + /absolute/path/to/ito-cloud-runtime/${CANONICAL_PACKAGE_PATH}/dist/bin/ito-mcp.js + +Device login never inherits ITO_API_KEY. The auth, find, and status commands +forward ITO_API_KEY directly when configured; ITO_AUTH_MODE=legacy is not +required. The canonical client stores device credentials in macOS Keychain by +default; file-token fallback remains explicit and must use restrictive settings. +Never put a key or token in arguments, tracked files, or chat. + +Live node qualification requires ITO_ENABLE_SIXTYTWO_LIVE=1, +--live-sixtytwo, an explicit node list, and an existing absolute config +directory. It forwards only named SIXTYTWO_API_TOKEN/SIXTYTWO_TOKEN and SSH +agent state; ITO_API_KEY is intentionally excluded. The canonical CLI requires +sixtytwo-cli==0.3.33 and fails closed. +`); +} + +function requiredOptionValue(args, option) { + const indexes = args + .map((value, index) => (value === option ? index : -1)) + .filter((index) => index >= 0); + if (indexes.length !== 1) { + throw new Error(`${option} is required exactly once for live node qualification.`); + } + const value = args[indexes[0] + 1]; + if (!value?.trim() || value.startsWith("--")) { + throw new Error(`${option} requires a non-empty value for live node qualification.`); + } + return value; +} + +function validateNodeQualificationArgs(args, environment) { + if (environment.ITO_ENABLE_SIXTYTWO_LIVE !== "1") { + throw new Error( + "Live node qualification requires ITO_ENABLE_SIXTYTWO_LIVE=1 before any process is started." + ); + } + if (args.filter((value) => value === "--live-sixtytwo").length !== 1) { + throw new Error( + "Live node qualification requires --live-sixtytwo exactly once before any process is started." + ); + } + requiredOptionValue(args, "--cluster"); + const nodes = requiredOptionValue(args, "--nodes"); + if (!nodes.split(",").every((node) => node.trim().length > 0)) { + throw new Error("--nodes must explicitly list one or more non-empty nodes."); + } + const configDirectory = requiredOptionValue(args, "--config-dir"); + if (!path.isAbsolute(configDirectory)) { + throw new Error("--config-dir must be an existing absolute directory."); + } + try { + const resolved = fs.realpathSync.native(configDirectory); + if ( + !fs.statSync(resolved).isDirectory() + || !fs.statSync(path.join(resolved, "sixtytwo.yaml")).isFile() + ) { + throw new Error("invalid qualification configuration"); + } + } catch { + throw new Error( + "--config-dir must exist and contain a regular sixtytwo.yaml before any process is started." + ); + } +} + +function parseArgs(argv, environment = process.env) { + const args = [...argv]; + if ( + args.length === 0 + || args.includes("--help") + || args.includes("-h") + ) { + return Object.freeze({ help: true, invocationArgs: [] }); + } + + if (environment.ECC_DRY_RUN === "1" || args.includes("--dry-run")) { + throw new Error( + "Itô compute has no paper or dry-run success mode. No CLI operation was invoked." + ); + } + + const jsonIndexes = args + .map((value, index) => (value === "--json" ? index : -1)) + .filter((index) => index >= 0); + if (jsonIndexes.length > 1) { + throw new Error("--json may only be provided once"); + } + const withoutJson = args.filter((value) => value !== "--json"); + const command = withoutJson.shift(); + if (!SUPPORTED_COMMANDS.includes(command)) { + throw new Error( + `Unsupported Itô command "${command || "(missing)"}"; ECC permits only login, logout, auth, find, status, and evals.` + ); + } + if (command === "auth" && withoutJson.includes("--no-browser")) { + throw new Error("--no-browser is valid only for ecc ito login; auth is validation-only."); + } + if (command === "evals") { + validateNodeQualificationArgs(withoutJson, environment); + } + + return Object.freeze({ + help: false, + invocationArgs: Object.freeze([ + ...(jsonIndexes.length === 1 ? ["--json"] : []), + command, + ...withoutJson, + ]), + }); +} + +function resolveItoExecutable(environment = process.env) { + const configured = environment[EXECUTABLE_OVERRIDE]?.trim(); + if (!configured) { + throw new Error([ + "The canonical ito-compute-cli is unpublished and ECC will not resolve", + `a credential-bearing "ito" executable from PATH. Build it from`, + `${CANONICAL_REPOSITORY.replace(/\.git$/, "")}/${CANONICAL_PACKAGE_PATH},`, + "run npm ci and npm run check, then set", + `${EXECUTABLE_OVERRIDE} to the explicit absolute dist/bin/ito.js path.`, + ].join(" ")); + } + + if (!path.isAbsolute(configured)) { + throw new Error( + `${EXECUTABLE_OVERRIDE} must be an absolute path explicitly configured by the operator.` + ); + } + return assertUsableExecutable(configured); +} + +function assertUsableExecutable(candidate) { + let canonicalCandidate; + try { + canonicalCandidate = fs.realpathSync.native(candidate); + } catch { + throw new Error( + `${EXECUTABLE_OVERRIDE} does not point to a readable local Itô CLI file.` + ); + } + if (!isCanonicalItoEntry(canonicalCandidate)) { + throw new Error( + `${EXECUTABLE_OVERRIDE} must point to the canonical dist/bin/ito.js entry.` + ); + } + if (!isUsableExecutable(canonicalCandidate)) { + throw new Error( + `${EXECUTABLE_OVERRIDE} does not point to a readable local Itô CLI file.` + ); + } + return canonicalCandidate; +} + +function isCanonicalItoEntry(candidate) { + const pathSegments = path + .normalize(candidate) + .split(path.sep) + .filter(Boolean); + if (pathSegments.length < CANONICAL_ENTRY_SEGMENTS.length) return false; + const candidateTail = pathSegments.slice(-CANONICAL_ENTRY_SEGMENTS.length); + return candidateTail.every((segment, index) => { + const expected = CANONICAL_ENTRY_SEGMENTS[index]; + return process.platform === "win32" + ? segment.toLowerCase() === expected.toLowerCase() + : segment === expected; + }); +} + +function isUsableExecutable(candidate) { + try { + const info = fs.statSync(candidate); + if (!info.isFile()) return false; + fs.accessSync(candidate, fs.constants.R_OK); + return true; + } catch { + return false; + } +} + +function buildInvocation(executable, args) { + if (!isCanonicalItoEntry(executable)) { + throw new Error( + `Refusing to invoke an Itô CLI shim. Set ${EXECUTABLE_OVERRIDE} to the absolute dist/bin/ito.js path.` + ); + } + return Object.freeze({ + executable: process.execPath, + args: Object.freeze([executable, ...args]), + }); +} + +function invokeIto(executable, args, environment = process.env) { + const invocation = buildInvocation(executable, args); + const command = getInvocationCommand(args); + const isNodeQualification = command === "evals"; + const isDeviceLogin = command === "login"; + const result = spawnSync(invocation.executable, invocation.args, { + cwd: process.cwd(), + encoding: "utf8", + // Keep policy helpers immutable for callers, but give child-process + // instrumentation its own mutable copy (for example NODE_V8_COVERAGE). + env: { ...createSafeItoInvocationEnvironment(environment, args) }, + stdio: isDeviceLogin ? "inherit" : ["pipe", "pipe", "pipe"], + maxBuffer: MAX_OUTPUT_BYTES, + timeout: isNodeQualification ? NODE_QUALIFICATION_TIMEOUT_MS : undefined, + shell: false, + windowsHide: true, + }); + + if (result.stdout) process.stdout.write(result.stdout); + if (result.stderr) process.stderr.write(result.stderr); + if (result.error) { + throw new Error(`The local Itô CLI could not be started: ${result.error.message}`); + } + if (typeof result.status === "number") return result.status; + if (result.signal) { + throw new Error(`The local Itô CLI terminated by signal ${result.signal}.`); + } + return 1; +} + +function main(argv = process.argv.slice(2), environment = process.env) { + try { + const parsed = parseArgs(argv, environment); + if (parsed.help) { + showHelp(); + return 0; + } + const executable = resolveItoExecutable(environment); + return invokeIto(executable, parsed.invocationArgs, environment); + } catch (error) { + console.error(`Error: ${error.message}`); + return 1; + } +} + +if (require.main === module) { + process.exitCode = main(); +} + +module.exports = Object.freeze({ + CANONICAL_PACKAGE_PATH, + CANONICAL_REPOSITORY, + EXECUTABLE_OVERRIDE, + NODE_QUALIFICATION_TIMEOUT_MS, + SUPPORTED_COMMANDS, + buildInvocation, + invokeIto, + main, + parseArgs, + resolveItoExecutable, +}); diff --git a/github_code/affaan-m__ECC/scripts/lib/agent-compress.js b/github_code/affaan-m__ECC/scripts/lib/agent-compress.js new file mode 100644 index 0000000000000000000000000000000000000000..4772643fb4ac88d8d4139365bf9f01dd8a614d6e --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/agent-compress.js @@ -0,0 +1,249 @@ +'use strict'; + +const fs = require('fs'); +const path = require('path'); +const { normalizeAgentTools } = require('./agent-tools'); + +/** + * Parse YAML frontmatter from a markdown string. + * Returns { frontmatter: {}, body: string }. + */ +function parseFrontmatter(content) { + const match = content.match(/^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n([\s\S]*))?$/); + if (!match) { + return { frontmatter: {}, body: content }; + } + + const frontmatter = {}; + for (const line of match[1].split('\n')) { + const colonIdx = line.indexOf(':'); + if (colonIdx === -1) continue; + + const key = line.slice(0, colonIdx).trim(); + let value = line.slice(colonIdx + 1).trim(); + + // Handle JSON arrays (e.g. tools: ["Read", "Grep"]) + if (value.startsWith('[') && value.endsWith(']')) { + try { + value = JSON.parse(value); + } catch { + // keep as string + } + } + + // Strip surrounding quotes + if (typeof value === 'string' && value.startsWith('"') && value.endsWith('"')) { + value = value.slice(1, -1); + } + + if (key === 'tools') { + value = normalizeAgentTools(value); + } + + frontmatter[key] = value; + } + + return { frontmatter, body: match[2] || '' }; +} + +/** + * Extract the first meaningful paragraph from agent body as a summary. + * Skips headings, list items, code blocks, and table rows. + */ +function extractSummary(body, maxSentences = 1) { + const lines = body.split('\n'); + const paragraphs = []; + let current = []; + let inCodeBlock = false; + + for (const line of lines) { + const trimmed = line.trim(); + + // Track fenced code blocks + if (trimmed.startsWith('```')) { + inCodeBlock = !inCodeBlock; + continue; + } + if (inCodeBlock) continue; + + if (trimmed === '') { + if (current.length > 0) { + paragraphs.push(current.join(' ')); + current = []; + } + continue; + } + + // Skip headings, list items (bold, plain, asterisk), numbered lists, table rows + if ( + trimmed.startsWith('#') || + trimmed.startsWith('- ') || + trimmed.startsWith('* ') || + /^\d+\.\s/.test(trimmed) || + trimmed.startsWith('|') + ) { + if (current.length > 0) { + paragraphs.push(current.join(' ')); + current = []; + } + continue; + } + + current.push(trimmed); + } + if (current.length > 0) { + paragraphs.push(current.join(' ')); + } + + const firstParagraph = paragraphs.find(p => p.length > 0); + if (!firstParagraph) return ''; + + const sentences = firstParagraph.match(/[^.!?]+[.!?]+/g) || [firstParagraph]; + return sentences.slice(0, maxSentences).map(s => s.trim()).join(' ').trim(); +} + +/** + * Load and parse a single agent file. + */ +function loadAgent(filePath) { + const content = fs.readFileSync(filePath, 'utf8'); + const { frontmatter, body } = parseFrontmatter(content); + const fileName = path.basename(filePath, '.md'); + + return { + fileName, + name: frontmatter.name || fileName, + description: frontmatter.description || '', + tools: Array.isArray(frontmatter.tools) ? frontmatter.tools : [], + model: frontmatter.model || 'sonnet', + body, + byteSize: Buffer.byteLength(content, 'utf8'), + }; +} + +/** + * Load all agents from a directory. + */ +function loadAgents(agentsDir) { + if (!fs.existsSync(agentsDir)) return []; + + return fs.readdirSync(agentsDir) + .filter(f => f.endsWith('.md')) + .sort() + .map(f => loadAgent(path.join(agentsDir, f))); +} + +/** + * Compress an agent to catalog entry (metadata only). + */ +function compressToCatalog(agent) { + return { + name: agent.name, + description: agent.description, + tools: agent.tools, + model: agent.model, + }; +} + +/** + * Compress an agent to summary entry (metadata + first paragraph). + */ +function compressToSummary(agent) { + return { + ...compressToCatalog(agent), + summary: extractSummary(agent.body), + }; +} + +const allowedModes = ['catalog', 'summary', 'full']; + +/** + * Build a compressed catalog from a directory of agents. + * + * Modes: + * - 'catalog': name, description, tools, model only (~2-3k tokens for 27 agents) + * - 'summary': catalog + first paragraph summary (~4-5k tokens) + * - 'full': no compression, full body included + * + * Returns { agents: [], stats: { totalAgents, originalBytes, compressedBytes, compressedTokenEstimate, mode } } + */ +function buildAgentCatalog(agentsDir, options = {}) { + const mode = options.mode || 'catalog'; + + if (!allowedModes.includes(mode)) { + throw new Error(`Invalid mode "${mode}". Allowed modes: ${allowedModes.join(', ')}`); + } + + const filter = options.filter || null; + + let agents = loadAgents(agentsDir); + + if (typeof filter === 'function') { + agents = agents.filter(filter); + } + + const originalBytes = agents.reduce((sum, a) => sum + a.byteSize, 0); + + let compressed; + if (mode === 'catalog') { + compressed = agents.map(compressToCatalog); + } else if (mode === 'summary') { + compressed = agents.map(compressToSummary); + } else { + compressed = agents.map(a => ({ + name: a.name, + description: a.description, + tools: a.tools, + model: a.model, + body: a.body, + })); + } + + const compressedJson = JSON.stringify(compressed); + // Rough token estimate: ~4 chars per token for English text + const compressedTokenEstimate = Math.ceil(compressedJson.length / 4); + + return { + agents: compressed, + stats: { + totalAgents: agents.length, + originalBytes, + compressedBytes: Buffer.byteLength(compressedJson, 'utf8'), + compressedTokenEstimate, + mode, + }, + }; +} + +/** + * Lazy-load a single agent's full content by name. + * Returns null if not found. + */ +function lazyLoadAgent(agentsDir, agentName) { + // Validate agentName: only allow alphanumeric, hyphen, underscore + if (!/^[\w-]+$/.test(agentName)) { + return null; + } + + const filePath = path.resolve(agentsDir, `${agentName}.md`); + + // Verify the resolved path is still within agentsDir + const resolvedAgentsDir = path.resolve(agentsDir); + if (!filePath.startsWith(resolvedAgentsDir + path.sep)) { + return null; + } + + if (!fs.existsSync(filePath)) return null; + return loadAgent(filePath); +} + +module.exports = { + buildAgentCatalog, + compressToCatalog, + compressToSummary, + extractSummary, + lazyLoadAgent, + loadAgent, + loadAgents, + parseFrontmatter, +}; diff --git a/github_code/affaan-m__ECC/scripts/lib/agent-data-home.js b/github_code/affaan-m__ECC/scripts/lib/agent-data-home.js new file mode 100644 index 0000000000000000000000000000000000000000..7302bd572ca183aef2ae33160cc5c672d7365539 --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/agent-data-home.js @@ -0,0 +1,245 @@ +/** + * Resolve ECC agent data home (memory persistence root) across harnesses. + * + * Docstring policy: public entry points here are documented; small internal + * helpers (e.g. `expandHomePath`, `readProjectConfigAt`) are left undocumented on + * purpose, consistent with ECC script modules elsewhere. Automated PR reviewers + * (e.g. CodeRabbit) may still flag low JSDoc coverage against a high threshold on + * the diff—that check is informational for this repo, not a bar every helper in + * touched files must meet. Prefer clarity in code and tests over blanket JSDoc on + * private helpers unless maintainers adopt a project-wide coverage rule. + * + * @see https://github.com/affaan-m/ECC/issues/2065 + */ + +const fs = require('fs'); +const path = require('path'); +const { assertWithinTrustedRoot } = require('./path-safety'); + +const AGENT_DATA_HOME_ENV = 'ECC_AGENT_DATA_HOME'; +const DEFAULT_CLAUDE_DIR_NAME = '.claude'; +const DEFAULT_CURSOR_ECC_DIR_SEGMENTS = ['.cursor', 'ecc']; +const PROJECT_CONFIG_RELATIVE = path.join('.cursor', 'ecc-agent-data.json'); + +/** + * Home directory for tilde expansion and default agent-data paths. + * + * Intentionally mirrors `getHomeDir()` in `scripts/lib/utils.js` (HOME/USERPROFILE, + * then `os.homedir()`). Do not import `utils.getHomeDir` here: `utils.js` already + * requires this module (`resolveAgentDataHome`), which would create a circular + * dependency and risk divergent defaults for `~/.cursor/ecc` vs `~/.claude`. + * + * If consolidation is needed later, prefer one of: + * + * | Approach | Tradeoff | + * | --- | --- | + * | Shared `scripts/lib/home-dir.js` imported by both | Clean; breaks the cycle | + * | Keep duplicate + cross-reference comment (this file) | Zero require risk | + * | Move all resolution here; thin-wrap from `utils` | Larger refactor | + */ +function getHomeDirFromEnv() { + const explicitHome = process.env.HOME || process.env.USERPROFILE; + if (explicitHome && String(explicitHome).trim().length > 0) { + return path.resolve(explicitHome); + } + return require('os').homedir(); +} + +function expandHomePath(value, baseDir) { + if (!value || typeof value !== 'string') return null; + const trimmed = value.trim(); + if (!trimmed) return null; + if (trimmed.startsWith('~')) { + const remainder = trimmed.slice(1).replace(/^[/\\]+/, ''); + return remainder ? path.join(getHomeDirFromEnv(), remainder) : getHomeDirFromEnv(); + } + if (path.isAbsolute(trimmed)) { + return path.resolve(trimmed); + } + const base = baseDir && String(baseDir).trim() + ? path.resolve(baseDir) + : process.cwd(); + return path.resolve(base, trimmed); +} + +/** + * Project root for a config file under .cursor/ecc-agent-data.json. + */ +function resolveProjectRootFromConfigPath(configPath) { + const configDir = path.dirname(path.resolve(configPath)); + if (path.basename(configDir) === '.cursor') { + return path.dirname(configDir); + } + return configDir; +} + +/** + * True when the current process is a Cursor hook subprocess. + * Cursor documents CURSOR_VERSION and CURSOR_PROJECT_DIR for hook scripts. + */ +function isCursorHookRuntime() { + if (process.env.CURSOR_VERSION && String(process.env.CURSOR_VERSION).trim()) { + return true; + } + if (process.env.CURSOR_PROJECT_DIR && String(process.env.CURSOR_PROJECT_DIR).trim()) { + return true; + } + return false; +} + +function getDefaultCursorAgentDataHome() { + return path.join(getHomeDirFromEnv(), ...DEFAULT_CURSOR_ECC_DIR_SEGMENTS); +} + +function getDefaultClaudeAgentDataHome() { + return path.join(getHomeDirFromEnv(), DEFAULT_CLAUDE_DIR_NAME); +} + +function warnUnsafeProjectConfig() { + console.error( + '[ECC] Ignoring unsafe agent data project config: agentDataHome must stay ' + + 'within the default Cursor or Claude data directories. Use ' + + 'ECC_AGENT_DATA_HOME for an explicit trusted override.' + ); +} + +function isSafeProjectConfigSyntax(candidate) { + const trimmed = candidate.trim(); + const isUserAnchored = trimmed.startsWith('~') || path.isAbsolute(trimmed); + const hasParentTraversal = trimmed.split(/[/\\]+/).includes('..'); + return isUserAnchored && !hasParentTraversal; +} + +function resolveAllowedProjectConfigHome(candidate) { + const allowedRoots = [ + getDefaultCursorAgentDataHome(), + getDefaultClaudeAgentDataHome(), + ]; + + for (const allowedRoot of allowedRoots) { + try { + return assertWithinTrustedRoot( + candidate, + allowedRoot, + 'use project agent data home' + ); + } catch { + // Try the next explicitly allowed default root. + } + } + return null; +} + +function readProjectConfigAt(configPath) { + if (!configPath || typeof configPath !== 'string') return null; + if (!fs.existsSync(configPath)) return null; + + try { + const parsed = JSON.parse(fs.readFileSync(configPath, 'utf8')); + if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return null; + const candidate = parsed.agentDataHome || parsed.ECC_AGENT_DATA_HOME; + if (typeof candidate !== 'string' || !candidate.trim()) return null; + if (!isSafeProjectConfigSyntax(candidate)) { + warnUnsafeProjectConfig(); + return null; + } + const projectRoot = resolveProjectRootFromConfigPath(configPath); + const resolved = expandHomePath(candidate, projectRoot); + const allowedHome = resolveAllowedProjectConfigHome(resolved); + if (!allowedHome) { + warnUnsafeProjectConfig(); + return null; + } + return allowedHome; + } catch (error) { + console.error( + `[ECC] Failed to read or parse agent data config at ${configPath}: ${error.message}` + ); + return null; + } +} + +function readProjectConfig(projectDir) { + if (!projectDir || typeof projectDir !== 'string') return null; + return readProjectConfigAt(path.join(path.resolve(projectDir), PROJECT_CONFIG_RELATIVE)); +} + +function resolveProjectDir() { + const candidates = [ + process.env.CURSOR_PROJECT_DIR, + process.env.CLAUDE_PROJECT_DIR, + process.cwd(), + ]; + + for (const candidate of candidates) { + if (!candidate || typeof candidate !== 'string') continue; + const resolved = path.resolve(candidate); + if (fs.existsSync(path.join(resolved, '.cursor'))) { + return resolved; + } + } + + return process.cwd(); +} + +/** + * Resolve agent data home without mutating process.env. + */ +function resolveAgentDataHome(options = {}) { + const fromEnv = expandHomePath(process.env[AGENT_DATA_HOME_ENV]); + if (fromEnv) return fromEnv; + + const projectDir = options.projectDir || resolveProjectDir(); + const fromProject = readProjectConfig(projectDir); + if (fromProject) return fromProject; + + if (options.preferCursorDefault === true || isCursorHookRuntime()) { + return getDefaultCursorAgentDataHome(); + } + + return getDefaultClaudeAgentDataHome(); +} + +/** + * Set ECC_AGENT_DATA_HOME on the current process when unset (hook subprocess safety net). + * @returns {string} Resolved agent data home + */ +function ensureAgentDataHomeEnv(options = {}) { + const resolved = resolveAgentDataHome(options); + if (!expandHomePath(process.env[AGENT_DATA_HOME_ENV])) { + process.env[AGENT_DATA_HOME_ENV] = resolved; + } + return resolved; +} + +/** + * Build Cursor sessionStart hook output env payload. + */ +function getCursorSessionEnvPayload(options = {}) { + const agentDataHome = resolveAgentDataHome({ + ...options, + preferCursorDefault: true, + }); + + return { + ECC_AGENT_DATA_HOME: agentDataHome, + }; +} + +module.exports = { + AGENT_DATA_HOME_ENV, + DEFAULT_CLAUDE_DIR_NAME, + DEFAULT_CURSOR_ECC_DIR_SEGMENTS, + PROJECT_CONFIG_RELATIVE, + expandHomePath, + resolveProjectRootFromConfigPath, + isCursorHookRuntime, + getDefaultCursorAgentDataHome, + getDefaultClaudeAgentDataHome, + readProjectConfig, + readProjectConfigAt, + resolveProjectDir, + resolveAgentDataHome, + ensureAgentDataHomeEnv, + getCursorSessionEnvPayload, +}; diff --git a/github_code/affaan-m__ECC/scripts/lib/agent-proximity/distance.js b/github_code/affaan-m__ECC/scripts/lib/agent-proximity/distance.js new file mode 100644 index 0000000000000000000000000000000000000000..2cddcbb89c0925374fe3cbd19f967f6e55500a4f --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/agent-proximity/distance.js @@ -0,0 +1,330 @@ +'use strict'; + +/** + * Agent-space distance metric + collision avoidance (ECC 2.0, Layer 4 v0). + * + * Two agents editing the same codebase are like two aircraft sharing airspace: + * we want a continuous notion of "how close are they" so that, as they approach, + * we fire a TCAS-style protocol — first a Traffic Advisory (exchange intent), + * then a Resolution Advisory (one steers away) — *before* they collide at the + * git/merge layer. + * + * ── The state of an agent ────────────────────────────────────────────────── + * At time t, agent a has a working set + * W_a = { (f, R_f, w_f) } (1) + * where f is a file it has touched, R_f the set of line ranges it edited in f, + * and w_f ∈ (0,1] a recency weight (older edits decay). Optionally an agent + * declares an intent set I_a of files it is about to touch. + * + * ── Collision is multi-channel ───────────────────────────────────────────── + * Two agents can collide through several independent channels, so we model a + * per-channel collision probability r_i ∈ [0,1] and combine with a noisy-OR + * (probability of colliding through *at least one* channel): + * R(a,b) = 1 − Π_i (1 − ω_i · r_i) (2) + * with channel weights ω_i ∈ [0,1]. R is the agent-distance's dual: we report + * both the risk R ∈ [0,1] and a distance D = 1 − R. + * + * Channels (each defined below): + * r_overlap — same file / overlapping line ranges (imminent) + * r_dep — one agent's files depend on the other's (collision even when + * far apart in the tree: edit there breaks here) + * r_tree — proximity in the directory tree (a soft prior) + * + * ── Channel 1: edit overlap ──────────────────────────────────────────────── + * For each shared file f ∈ files(W_a) ∩ files(W_b), the overlap COEFFICIENT + * (Szymkiewicz–Simpson) over the edited line ranges: + * lineOverlap(f) = |R_f^a ∩ R_f^b| / min(|R_f^a|, |R_f^b|) + * (the right collision measure — high when one agent's edit sits inside the + * other's region even if that region is huge; =1 when either side is a whole-file + * edit). The channel risk is the recency-weighted max across shared files: + * r_overlap = max_{f∈S} w_f^a·w_f^b · lineOverlap(f). (3) + * Different files ⇒ no shared f ⇒ r_overlap = 0 (tree/dep channels take over). + * + * ── Channel 2: dependency coupling ───────────────────────────────────────── + * Build a directed dependency graph G=(V,E), V=files, edge f→g iff f imports g. + * Even if f and g are in distant subtrees, if f (agent a) depends on g (agent b) + * then b's edit to g can break a. Coupling decays with graph distance: + * coupling(f,g) = γ^{ d_G(f,g) − 1 } (γ∈(0,1)), 0 if unreachable. (4) + * A direct edge (d_G=1) ⇒ coupling=1. We take the recency-weighted max over + * cross pairs: + * r_dep = max_{f∈W_a, g∈W_b} w_f·w_g·max(coupling(f,g), coupling(g,f)). (5) + * + * ── Channel 3: tree proximity ────────────────────────────────────────────── + * For two paths split into segments with lowest-common-ancestor depth L: + * treeDistance(f,g) = ((depth_f − L) + (depth_g − L)) / (depth_f + depth_g) (6) + * (0 = same file, 1 = disjoint roots). r_tree = 1 − min cross-pair treeDist. + * Tree proximity alone rarely causes a collision, so ω_tree is small — it nudges + * the metric, it does not dominate it. + * + * ── TCAS protocol ────────────────────────────────────────────────────────── + * Two thresholds carve a protected zone: + * R < τ_TA → CLEAR + * τ_TA ≤ R < τ_RA → TRAFFIC ADVISORY: each agent transmits what it is + * doing/has done to the other (the scout handshake) + * R ≥ τ_RA → RESOLUTION ADVISORY: the lower-priority agent steers + * away; the higher-priority one holds course. + * Like TCAS coordinating climb/descend, the resolution is *coordinated* and + * deterministic so both agents never pick the same maneuver: priority(a) breaks + * the tie (right-of-way to the agent with more committed work / earlier start; + * stable agentId as the final tiebreak). See advise(). + * + * ── Vector-space view ────────────────────────────────────────────────────── + * embedAgent() places each agent at the recency-weighted centroid of its files' + * coordinates, where a file's coordinate is a low-dim hash of its path segments + * smoothed toward its dependency neighbours. Then ‖v_a − v_b‖ tracks R, which is + * what a 3D "where are the agents" visualization renders. See embed.js. + */ + +const DEFAULTS = { + channelWeights: { overlap: 1.0, dependency: 0.9, tree: 0.25 }, + depDecay: 0.5, // γ in (4) + recencyFloor: 0.15, // weight never decays below this so stale-but-relevant files still count + thresholds: { ta: 0.35, ra: 0.7 } // τ_TA, τ_RA +}; + +function clamp01(x) { + if (!Number.isFinite(x)) return 0; + return x < 0 ? 0 : x > 1 ? 1 : x; +} + +function normalizePath(p) { + return String(p || '') + .replace(/\\/g, '/') + .replace(/^\.\//, '') + .replace(/\/+$/, ''); +} + +function segments(p) { + return normalizePath(p).split('/').filter(Boolean); +} + +/** + * Tree distance ∈ [0,1] between two file paths — eq. (6). 0 = same file. + */ +function treeDistance(a, b) { + const sa = segments(a); + const sb = segments(b); + if (sa.length === 0 || sb.length === 0) return 1; + let lca = 0; + while (lca < sa.length && lca < sb.length && sa[lca] === sb[lca]) lca += 1; + const da = sa.length; + const db = sb.length; + if (da === db && lca === da) return 0; // identical path + return clamp01((da - lca + (db - lca)) / (da + db)); +} + +/** + * Line-range overlap as the overlap COEFFICIENT (Szymkiewicz–Simpson): + * |A ∩ B| / min(|A|, |B|). This is the right collision measure — if one agent's + * edit sits largely inside the other's region the score is high even when the + * other region is huge (Jaccard would dilute it by union size). Empty/absent + * ranges ⇒ whole-file edit ⇒ full overlap (1). Each range is [start,end] inclusive. + */ +function lineRangeOverlap(rangesA, rangesB) { + const a = Array.isArray(rangesA) ? rangesA : []; + const b = Array.isArray(rangesB) ? rangesB : []; + if (a.length === 0 || b.length === 0) return 1; // file-level edit ⇒ whole-file overlap + const covered = ranges => { + const set = new Set(); + for (const [s, e] of ranges) { + const lo = Math.min(s, e); + const hi = Math.max(s, e); + for (let i = lo; i <= hi; i += 1) set.add(i); + } + return set; + }; + const ca = covered(a); + const cb = covered(b); + if (ca.size === 0 || cb.size === 0) return 0; + let inter = 0; + for (const v of ca) if (cb.has(v)) inter += 1; + return inter / Math.min(ca.size, cb.size); +} + +function jaccard(setA, setB) { + if (setA.size === 0 && setB.size === 0) return 0; + let inter = 0; + for (const v of setA) if (setB.has(v)) inter += 1; + const union = setA.size + setB.size - inter; + return union === 0 ? 0 : inter / union; +} + +/** + * Channel 1 — edit overlap, eq. (3). + */ +function overlapRisk(a, b) { + const filesA = a.files || []; + const filesB = b.files || []; + const byPathB = new Map(filesB.map(f => [normalizePath(f.path), f])); + // Per shared file, the (line-precise) overlap — lineRangeOverlap returns 1 when + // either side lacks ranges (a whole-file edit). The risk is the max across + // shared files: even one fully-overlapping file is a collision, while the same + // file edited in disjoint line ranges scores low. No coarse file-set Jaccard + // floor (it would max out for any shared file and mask line-level disjointness). + let r = 0; + for (const fa of filesA) { + const fb = byPathB.get(normalizePath(fa.path)); + if (fb) { + const w = (fa.weight ?? 1) * (fb.weight ?? 1); + r = Math.max(r, w * lineRangeOverlap(fa.lines, fb.lines)); + } + } + return clamp01(r); +} + +/** + * Shortest-path distance in a directed dependency graph, treated as undirected + * for reachability (a depends-on edge couples both endpoints). BFS, capped. + */ +function graphDistance(graph, from, to, cap = 6) { + const start = normalizePath(from); + const goal = normalizePath(to); + if (start === goal) return 0; + const adj = graph && graph.adjacency ? graph.adjacency : graph || {}; + const seen = new Set([start]); + let frontier = [start]; + for (let depth = 1; depth <= cap; depth += 1) { + const next = []; + for (const node of frontier) { + const neighbours = adj[node] || []; + for (const nb of neighbours) { + const n = normalizePath(nb); + if (n === goal) return depth; + if (!seen.has(n)) { + seen.add(n); + next.push(n); + } + } + } + if (next.length === 0) break; + frontier = next; + } + return Infinity; +} + +/** + * Channel 2 — dependency coupling, eqs. (4)-(5). + */ +function dependencyRisk(a, b, graph, opts = {}) { + const decay = opts.depDecay ?? DEFAULTS.depDecay; + const filesA = a.files || []; + const filesB = b.files || []; + let r = 0; + for (const fa of filesA) { + for (const fb of filesB) { + // A depends-on edge couples both endpoints, so use the smaller of the two + // directed distances (importer→imported or imported→importer). + const d = Math.min(graphDistance(graph, fa.path, fb.path), graphDistance(graph, fb.path, fa.path)); + if (d === Infinity || d === 0) continue; + const coupling = Math.pow(decay, d - 1); // γ^{d-1} + const w = (fa.weight ?? 1) * (fb.weight ?? 1); + r = Math.max(r, w * coupling); + } + } + return clamp01(r); +} + +/** + * Channel 3 — tree proximity (soft prior), eq. (6). + */ +function treeRisk(a, b) { + const filesA = a.files || []; + const filesB = b.files || []; + let minDist = 1; + for (const fa of filesA) { + for (const fb of filesB) { + minDist = Math.min(minDist, treeDistance(fa.path, fb.path)); + } + } + return clamp01(1 - minDist); +} + +/** + * Collision risk R(a,b) ∈ [0,1] via the noisy-OR of channels, eq. (2). + * Returns the risk, its dual distance, and the per-channel breakdown. + */ +function collisionRisk(a, b, graph = {}, options = {}) { + const weights = { ...DEFAULTS.channelWeights, ...(options.channelWeights || {}) }; + const channels = { + overlap: overlapRisk(a, b), + dependency: dependencyRisk(a, b, graph, options), + tree: treeRisk(a, b) + }; + let product = 1; + for (const key of Object.keys(channels)) { + const w = clamp01(weights[key] ?? 0); + product *= 1 - w * channels[key]; + } + const risk = clamp01(1 - product); + return { risk, distance: clamp01(1 - risk), channels }; +} + +/** + * Right-of-way priority: the agent with more committed work and the earlier + * start holds course; the other steers. Higher number = higher priority. + */ +function agentPriority(agent) { + const progress = (agent.files || []).reduce((s, f) => s + (f.weight ?? 1), 0); + const startedAt = agent.startedAt ? Date.parse(agent.startedAt) || 0 : 0; + // Earlier start ⇒ larger right-of-way term (negative ms, so earlier = larger). + return { progress, ageMs: startedAt ? Date.now() - startedAt : 0 }; +} + +/** + * TCAS-style advisory between two agents given their collision risk. + * Returns { level: 'clear'|'advisory'|'resolution', risk, transmit, steer, hold }. + * - advisory: both should transmit intent to each other. + * - resolution: `steer` is the agentId that must move; `hold` holds course. + */ +function advise(a, b, graph = {}, options = {}) { + const thresholds = { ...DEFAULTS.thresholds, ...(options.thresholds || {}) }; + const { risk, channels, distance } = collisionRisk(a, b, graph, options); + + if (risk < thresholds.ta) { + return { level: 'clear', risk, distance, channels, transmit: false, steer: null, hold: null }; + } + + const pa = agentPriority(a); + const pb = agentPriority(b); + // Right-of-way: more progress wins; tie → earlier start (greater age) wins; + // final deterministic tiebreak on agentId so the maneuver is coordinated. + let aHasPriority; + if (pa.progress !== pb.progress) aHasPriority = pa.progress > pb.progress; + else if (pa.ageMs !== pb.ageMs) aHasPriority = pa.ageMs > pb.ageMs; + else aHasPriority = String(a.agentId) < String(b.agentId); + + const hold = aHasPriority ? a.agentId : b.agentId; + const steer = aHasPriority ? b.agentId : a.agentId; + + if (risk < thresholds.ra) { + // Traffic advisory: exchange intent, no one has to move yet. + return { level: 'advisory', risk, distance, channels, transmit: true, steer: null, hold: null }; + } + // Resolution advisory: the lower-priority agent steers away. + return { level: 'resolution', risk, distance, channels, transmit: true, steer, hold }; +} + +/** + * Closure rate: how fast two agents are converging, from two risk samples + * Δt apart (TCAS uses closure rate, not just separation, to decide urgency). + * Positive ⇒ approaching. Used to escalate before the protected zone is reached. + */ +function closureRate(prevRisk, currRisk, dtMs) { + const dt = Number(dtMs) > 0 ? Number(dtMs) : 1; + return (clamp01(currRisk) - clamp01(prevRisk)) / (dt / 1000); +} + +module.exports = { + DEFAULTS, + treeDistance, + lineRangeOverlap, + graphDistance, + overlapRisk, + dependencyRisk, + treeRisk, + collisionRisk, + agentPriority, + advise, + closureRate, + _internal: { normalizePath, segments, jaccard } +}; diff --git a/github_code/affaan-m__ECC/scripts/lib/agent-proximity/graph.js b/github_code/affaan-m__ECC/scripts/lib/agent-proximity/graph.js new file mode 100644 index 0000000000000000000000000000000000000000..98bc05a3d545e292fc740584f816f2c01b7e35a2 --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/agent-proximity/graph.js @@ -0,0 +1,140 @@ +'use strict'; + +/** + * Lightweight dependency-graph builder for the agent-proximity metric. + * + * Edge f → g iff f imports/requires g. This is the structure the dependency + * channel (distance.js, eqs. 4-5) walks: two agents far apart in the tree still + * collide if one edits a file the other imports. + * + * v0 scans JS/TS `require()` / `import ... from` / `import(...)` for relative + * specifiers and resolves them to repo-relative paths. It is intentionally + * static and dependency-free; richer languages and call-graph edges are future + * channels that slot into the same adjacency shape. + */ + +const fs = require('fs'); +const path = require('path'); + +const SOURCE_EXTENSIONS = ['.js', '.mjs', '.cjs', '.ts', '.tsx', '.jsx']; +const RESOLVE_EXTENSIONS = ['.js', '.mjs', '.cjs', '.ts', '.tsx', '.jsx', '.json']; + +function toRepoRel(repoRoot, absPath) { + return path.relative(repoRoot, absPath).split(path.sep).join('/'); +} + +// Match relative specifiers only (./ or ../). Bare specifiers are node_modules +// and never the target of an in-repo collision. +const SPEC_PATTERNS = [ + /require\(\s*['"](\.[^'"]+)['"]\s*\)/g, + /import\s+(?:[^'"]*?\s+from\s+)?['"](\.[^'"]+)['"]/g, + /import\(\s*['"](\.[^'"]+)['"]\s*\)/g, + /export\s+(?:\*|\{[^}]*\})\s+from\s+['"](\.[^'"]+)['"]/g +]; + +function extractRelativeSpecifiers(source) { + const specs = new Set(); + for (const re of SPEC_PATTERNS) { + re.lastIndex = 0; + let m; + while ((m = re.exec(source)) !== null) { + specs.add(m[1]); + } + } + return [...specs]; +} + +/** + * Resolve a relative specifier from `fromFile` to a repo-relative path, trying + * extension and /index resolution like Node/TS would. + */ +function resolveSpecifier(repoRoot, fromFile, spec) { + const baseDir = path.dirname(path.join(repoRoot, fromFile)); + const target = path.resolve(baseDir, spec); + const candidates = [target]; + for (const ext of RESOLVE_EXTENSIONS) candidates.push(target + ext); + for (const ext of RESOLVE_EXTENSIONS) candidates.push(path.join(target, 'index' + ext)); + for (const cand of candidates) { + try { + if (fs.existsSync(cand) && fs.statSync(cand).isFile()) { + return toRepoRel(repoRoot, cand); + } + } catch { + /* ignore unreadable candidate */ + } + } + return null; +} + +function isSourceFile(p) { + return SOURCE_EXTENSIONS.includes(path.extname(p)); +} + +/** + * Build a dependency graph from an explicit list of repo-relative files. + * Returns { adjacency: { file: [importedFile, ...] }, files: [...] }. + * + * @param {string} repoRoot + * @param {string[]} files repo-relative paths to scan + * @param {object} [deps] injectable fs for testing: { readFileSync, existsSync, statSync } + */ +function buildDependencyGraph(repoRoot, files, deps = {}) { + const read = deps.readFileSync || fs.readFileSync; + const adjacency = {}; + const scanned = []; + for (const rel of files || []) { + const normalized = String(rel).replace(/\\/g, '/'); + if (!isSourceFile(normalized)) continue; + scanned.push(normalized); + let source = ''; + try { + source = String(read(path.join(repoRoot, normalized), 'utf8')); + } catch { + adjacency[normalized] = adjacency[normalized] || []; + continue; + } + const edges = new Set(adjacency[normalized] || []); + for (const spec of extractRelativeSpecifiers(source)) { + const resolved = resolveSpecifier(repoRoot, normalized, spec); + if (resolved && resolved !== normalized) edges.add(resolved); + } + adjacency[normalized] = [...edges]; + } + return { adjacency, files: scanned }; +} + +/** + * Build a graph directly from an in-memory map of { file: sourceText }, for + * callers that already have file contents (and for tests). Specifiers are + * resolved against the provided file set rather than the filesystem. + */ +function buildDependencyGraphFromSources(sources = {}) { + const adjacency = {}; + const fileList = Object.keys(sources).map(f => f.replace(/\\/g, '/')); + const fileSet = new Set(fileList); + const tryResolve = (fromFile, spec) => { + const base = path.posix.dirname(fromFile); + const target = path.posix.normalize(path.posix.join(base, spec)); + const candidates = [target]; + for (const ext of RESOLVE_EXTENSIONS) candidates.push(target + ext); + for (const ext of RESOLVE_EXTENSIONS) candidates.push(path.posix.join(target, 'index' + ext)); + return candidates.find(c => fileSet.has(c)) || null; + }; + for (const file of fileList) { + const edges = new Set(); + for (const spec of extractRelativeSpecifiers(String(sources[file] || ''))) { + const resolved = tryResolve(file, spec); + if (resolved && resolved !== file) edges.add(resolved); + } + adjacency[file] = [...edges]; + } + return { adjacency, files: fileList }; +} + +module.exports = { + buildDependencyGraph, + buildDependencyGraphFromSources, + extractRelativeSpecifiers, + resolveSpecifier, + isSourceFile +}; diff --git a/github_code/affaan-m__ECC/scripts/lib/agent-proximity/index.js b/github_code/affaan-m__ECC/scripts/lib/agent-proximity/index.js new file mode 100644 index 0000000000000000000000000000000000000000..6815fe291d83ee5bf828f9115fef6ea1062f2e21 --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/agent-proximity/index.js @@ -0,0 +1,223 @@ +'use strict'; + +/** + * Agent-proximity orchestration: scan all agents in a codebase, compute the + * pairwise TCAS advisories that drive the steer/transmit triggers, and embed + * each agent in 3D space for the "where are the agents" visualization. + * + * This is the call the control pane / hook layer makes each tick: + * const scan = scanAirspace(agents, graph) + * for (const a of scan.advisories) fireTrigger(a) // transmit / steer + * renderViz(scan.positions, scan.advisories) // 3D crawl view + */ + +const crypto = require('crypto'); +const { advise, collisionRisk, DEFAULTS } = require('./distance'); +const { buildDependencyGraph, buildDependencyGraphFromSources } = require('./graph'); + +const { normalizePath, segments } = require('./distance')._internal; + +/** + * Deterministic hash of a string to a unit-ish vector in R^dims (components in + * roughly [-1, 1]). Used to place tree prefixes in space. + */ +function hashVec(str, dims) { + const digest = crypto.createHash('sha256').update(String(str)).digest(); + const v = new Array(dims).fill(0); + for (let d = 0; d < dims; d += 1) { + // Two bytes per dim → [-1, 1). + const hi = digest[(d * 2) % digest.length]; + const lo = digest[(d * 2 + 1) % digest.length]; + v[d] = ((hi << 8) | lo) / 32768 - 1; + } + return v; +} + +/** + * Coordinate of a file: a space-filling embedding of its path. Files that share + * a long directory prefix share most of their coordinate (deeper segments + * perturb less), so tree-close files are space-close — exactly what eq. (6) + * wants the visualization to show. + */ +function fileCoordinate(filePath, dims = 3) { + const segs = segments(filePath); + const v = new Array(dims).fill(0); + let prefix = ''; + for (let i = 0; i < segs.length; i += 1) { + prefix += '/' + segs[i]; + const h = hashVec(prefix, dims); + const scale = 1 / Math.pow(2, i); + for (let d = 0; d < dims; d += 1) v[d] += h[d] * scale; + } + return v; +} + +/** + * Pull a file's coordinate toward the coordinates of its dependency neighbours + * (one averaging step), so coupled files that are far in the tree are drawn + * closer in space — the dependency channel made visible. + */ +function smoothByDependency(coords, graph, alpha = 0.35) { + const adj = (graph && graph.adjacency) || {}; + const out = {}; + for (const file of Object.keys(coords)) { + const base = coords[file]; + const neighbours = (adj[file] || []).map(normalizePath).filter(n => coords[n]); + if (neighbours.length === 0) { + out[file] = base.slice(); + continue; + } + const dims = base.length; + const avg = new Array(dims).fill(0); + for (const n of neighbours) for (let d = 0; d < dims; d += 1) avg[d] += coords[n][d]; + for (let d = 0; d < dims; d += 1) avg[d] /= neighbours.length; + out[file] = base.map((x, d) => (1 - alpha) * x + alpha * avg[d]); + } + return out; +} + +function weightedCentroid(files, fileCoords, dims) { + const v = new Array(dims).fill(0); + let wsum = 0; + for (const f of files) { + const c = fileCoords[normalizePath(f.path)]; + if (!c) continue; + const w = f.weight ?? 1; + for (let d = 0; d < dims; d += 1) v[d] += c[d] * w; + wsum += w; + } + if (wsum > 0) for (let d = 0; d < dims; d += 1) v[d] /= wsum; + return v; +} + +/** + * Embed agents in R^dims for visualization. Returns one position per agent plus + * the file coordinates used, so a renderer can draw both the agents and the + * file-cloud they sit in. + */ +function embedAgents(agents, graph = {}, options = {}) { + const dims = options.dims || 3; + const fileCoords = {}; + for (const agent of agents) { + for (const f of agent.files || []) { + const p = normalizePath(f.path); + if (!fileCoords[p]) fileCoords[p] = fileCoordinate(p, dims); + } + } + const smoothed = smoothByDependency(fileCoords, graph, options.dependencyPull ?? 0.35); + const positions = agents.map(agent => ({ + agentId: agent.agentId, + position: weightedCentroid(agent.files || [], smoothed, dims), + fileCount: (agent.files || []).length + })); + return { dims, positions, fileCoordinates: smoothed }; +} + +/** + * Scan the whole airspace: pairwise advisories + 3D positions in one pass. + * + * @param {Array<{agentId,files,startedAt?,intent?}>} agents + * @param {object} graph dependency graph (adjacency) + * @param {object} [options] + * @returns {{ advisories, positions, links, generatedAt }} + */ +function scanAirspace(agents, graph = {}, options = {}) { + const list = Array.isArray(agents) ? agents.filter(a => a && a.agentId !== null && a.agentId !== undefined) : []; + const advisories = []; + const links = []; + for (let i = 0; i < list.length; i += 1) { + for (let j = i + 1; j < list.length; j += 1) { + const a = list[i]; + const b = list[j]; + const verdict = advise(a, b, graph, options); + links.push({ + a: a.agentId, + b: b.agentId, + risk: verdict.risk, + distance: verdict.distance, + level: verdict.level + }); + if (verdict.level !== 'clear') { + advisories.push({ a: a.agentId, b: b.agentId, ...verdict }); + } + } + } + advisories.sort((x, y) => y.risk - x.risk); + links.sort((x, y) => y.risk - x.risk); + const embedding = embedAgents(list, graph, options); + return { + advisories, + positions: embedding.positions, + fileCoordinates: embedding.fileCoordinates, + links, + counts: { + agents: list.length, + advisories: advisories.length, + resolutions: advisories.filter(a => a.level === 'resolution').length + } + }; +} + +function clamp01(x) { + return !Number.isFinite(x) ? 0 : x < 0 ? 0 : x > 1 ? 1 : x; +} +function pct(x) { + return Math.round(clamp01(x) * 100); +} + +/** + * Turn airspace advisories into the messages to inject between agent sessions — + * the concrete "transmit intent / steer away" actions. Transport-agnostic: each + * trigger is { to, from, type, risk, content }; a dispatcher delivers them. + */ +function buildProximityTriggers(advisories) { + const triggers = []; + for (const adv of advisories || []) { + if (adv.level === 'advisory') { + // Traffic Advisory: both agents exchange intent. + triggers.push({ + to: adv.a, + from: adv.b, + type: 'proximity_transmit', + risk: adv.risk, + content: `Proximity ${pct(adv.risk)}%: you and ${adv.b} are converging in code-space. Share what you're working on and check for overlap before continuing.` + }); + triggers.push({ + to: adv.b, + from: adv.a, + type: 'proximity_transmit', + risk: adv.risk, + content: `Proximity ${pct(adv.risk)}%: you and ${adv.a} are converging in code-space. Share what you're working on and check for overlap before continuing.` + }); + } else if (adv.level === 'resolution') { + // Resolution Advisory: the lower-priority agent steers; the other holds. + triggers.push({ + to: adv.steer, + from: adv.hold, + type: 'proximity_steer', + risk: adv.risk, + content: `Collision risk ${pct(adv.risk)}% with ${adv.hold}, which holds right-of-way. Steer away: move to a different file/area, or coordinate with ${adv.hold} before editing the shared region.` + }); + triggers.push({ + to: adv.hold, + from: adv.steer, + type: 'proximity_hold', + risk: adv.risk, + content: `Collision risk ${pct(adv.risk)}% with ${adv.steer}; you hold right-of-way. ${adv.steer} has been asked to steer away — continue, but expect a handoff if they can't.` + }); + } + } + return triggers; +} + +module.exports = { + DEFAULTS, + scanAirspace, + embedAgents, + fileCoordinate, + collisionRisk, + advise, + buildProximityTriggers, + buildDependencyGraph, + buildDependencyGraphFromSources +}; diff --git a/github_code/affaan-m__ECC/scripts/lib/agent-tools.js b/github_code/affaan-m__ECC/scripts/lib/agent-tools.js new file mode 100644 index 0000000000000000000000000000000000000000..8b810c8855676da906c9be2e0c07bdf677dba584 --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/agent-tools.js @@ -0,0 +1,97 @@ +'use strict'; + +function stripSurroundingQuotes(value) { + const trimmed = value.trim(); + const quote = trimmed[0]; + if ((quote === '"' || quote === "'") && trimmed.endsWith(quote)) { + return trimmed.slice(1, -1).trim(); + } + return trimmed; +} + +function splitTopLevelToolList(value) { + const items = []; + const delimiters = []; + let quote = null; + let escaped = false; + let itemStart = 0; + + for (let index = 0; index < value.length; index += 1) { + const character = value[index]; + + if (quote) { + if (escaped) { + escaped = false; + } else if (character === '\\') { + escaped = true; + } else if (character === quote) { + quote = null; + } + continue; + } + + if (character === '"' || character === "'") { + quote = character; + continue; + } + + if (character === '(' || character === '[' || character === '{') { + delimiters.push(character); + continue; + } + + const expectedOpener = { + ')': '(', + ']': '[', + '}': '{', + }[character]; + if (expectedOpener && delimiters.at(-1) === expectedOpener) { + delimiters.pop(); + continue; + } + + if (character === ',' && delimiters.length === 0) { + items.push(value.slice(itemStart, index)); + itemStart = index + 1; + } + } + + items.push(value.slice(itemStart)); + return items; +} + +/** + * Normalize Claude agent frontmatter tools to the array shape used internally. + * + * Claude Code expects tools to be a comma-separated scalar. Flow sequences are + * still accepted here so ECC can read legacy or harness-adapted agent files. + */ +function normalizeAgentTools(value) { + if (Array.isArray(value)) { + return value + .filter(item => typeof item === 'string') + .map(stripSurroundingQuotes) + .filter(Boolean); + } + + if (typeof value !== 'string') { + return []; + } + + const trimmed = value.trim(); + const listValue = trimmed.startsWith('[') && trimmed.endsWith(']') + ? trimmed.slice(1, -1) + : stripSurroundingQuotes(trimmed); + + if (!listValue.trim()) { + return []; + } + + return splitTopLevelToolList(listValue) + .map(stripSurroundingQuotes) + .filter(Boolean); +} + +module.exports = { + normalizeAgentTools, +}; diff --git a/github_code/affaan-m__ECC/scripts/lib/atomic-write.js b/github_code/affaan-m__ECC/scripts/lib/atomic-write.js new file mode 100644 index 0000000000000000000000000000000000000000..9e9e524fec2d68144cc0d758fde6f73197aec886 --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/atomic-write.js @@ -0,0 +1,52 @@ +'use strict'; + +const crypto = require('crypto'); +const fs = require('fs'); +const path = require('path'); + +function writeFileAtomic(filePath, content, options = {}) { + const resolvedPath = path.resolve(filePath); + const parentDir = path.dirname(resolvedPath); + const tempPath = path.join( + parentDir, + `.${path.basename(resolvedPath)}.${process.pid}.${crypto.randomBytes(8).toString('hex')}.tmp` + ); + const mode = options.mode || 0o600; + + if (options.validateParent) options.validateParent(); + fs.mkdirSync(parentDir, { recursive: true }); + + let descriptor; + try { + if (options.validateParent) options.validateParent(); + descriptor = fs.openSync(tempPath, 'wx', mode); + if (options.validateParent) options.validateParent(); + fs.writeFileSync(descriptor, content, { encoding: options.encoding || 'utf8' }); + fs.fsyncSync(descriptor); + fs.closeSync(descriptor); + descriptor = undefined; + if (options.validateParent) options.validateParent(); + if (options.beforeRename) options.beforeRename(); + fs.renameSync(tempPath, resolvedPath); + } catch (error) { + if (descriptor !== undefined) { + fs.closeSync(descriptor); + } + // If the parent was replaced, this pathname may now name somebody else's + // file. Leave the private staging file in its original directory. + let parentUnchanged = true; + try { + if (options.validateParent) options.validateParent(); + } catch (_error) { + parentUnchanged = false; + } + if (parentUnchanged) fs.rmSync(tempPath, { force: true }); + throw error; + } + + return resolvedPath; +} + +module.exports = { + writeFileAtomic, +}; diff --git a/github_code/affaan-m__ECC/scripts/lib/claude-commit-attribution.js b/github_code/affaan-m__ECC/scripts/lib/claude-commit-attribution.js new file mode 100644 index 0000000000000000000000000000000000000000..cac44d52af9690d7529fd090e562a11ec61af464 --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/claude-commit-attribution.js @@ -0,0 +1,43 @@ +'use strict'; + +// Claude Code appends a `Co-Authored-By` trailer to commits and PRs unless the +// user opts out, so ECC-managed installs default that off. +// +// Two settings control the trailer. `attribution: { commit, pr }` is the current +// one and wins when set; `includeCoAuthoredBy` is deprecated as of Claude Code +// 2.1.x but still honored, and is the only one older versions understand. We +// write the deprecated key because unknown keys fail settings validation, so +// writing `attribution` would break users on older Claude Code. Either key being +// present counts as a deliberate user choice that ECC must not overwrite. +const COAUTHOR_SETTING_KEY = 'includeCoAuthoredBy'; + +function hasExplicitCommitAttributionPreference(settings) { + if (!settings || typeof settings !== 'object') { + return false; + } + if (typeof settings[COAUTHOR_SETTING_KEY] === 'boolean') { + return true; + } + + const attribution = settings.attribution; + return Boolean(attribution) + && typeof attribution === 'object' + && !Array.isArray(attribution) + && (attribution.commit !== undefined || attribution.pr !== undefined); +} + +function withCommitAttributionDisabled(settings) { + if (hasExplicitCommitAttributionPreference(settings)) { + return settings; + } + return { + ...settings, + [COAUTHOR_SETTING_KEY]: false, + }; +} + +module.exports = { + COAUTHOR_SETTING_KEY, + hasExplicitCommitAttributionPreference, + withCommitAttributionDisabled, +}; diff --git a/github_code/affaan-m__ECC/scripts/lib/claude-dry-run-sandbox.js b/github_code/affaan-m__ECC/scripts/lib/claude-dry-run-sandbox.js new file mode 100644 index 0000000000000000000000000000000000000000..339b8b511d1c7d88e8a1bd5eb8c3e4ecf3adac4b --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/claude-dry-run-sandbox.js @@ -0,0 +1,182 @@ +'use strict'; + +const fs = require('fs'); +const os = require('os'); +const path = require('path'); + +const { realpathNearestExisting } = require('./path-safety'); + +function readSnapshotFile(filePath) { + try { + const stat = fs.statSync(filePath); + if (!stat.isFile()) { + const error = new Error(`Claude dry-run state is not a regular file: ${filePath}`); + error.code = 'INVALID_DRY_RUN_STATE'; + throw error; + } + return fs.readFileSync(filePath); + } catch (error) { + if (error.code === 'ENOENT') return null; + throw error; + } +} + +function claudeStateFilePath(paths, options) { + const hasCustomConfigDir = ( + options.configDir !== undefined + || Boolean(process.env.CLAUDE_CONFIG_DIR) + ); + return hasCustomConfigDir + ? path.join(paths.configDir, '.claude.json') + : path.join(paths.homeDir, '.claude.json'); +} + +function remapSnapshotPath(value, mappings) { + if (typeof value !== 'string' || !path.isAbsolute(value)) return value; + for (const mapping of mappings) { + const relative = path.relative(mapping.source, value); + if ( + relative === '' + || ( + relative !== '..' + && !relative.startsWith(`..${path.sep}`) + && !path.isAbsolute(relative) + ) + ) { + return relative === '' ? mapping.destination : path.join(mapping.destination, relative); + } + } + return value; +} + +function remapSnapshotValue(value, mappings) { + if (typeof value === 'string') return remapSnapshotPath(value, mappings); + if (Array.isArray(value)) { + return value.map(entry => remapSnapshotValue(entry, mappings)); + } + if (!value || typeof value !== 'object') return value; + return Object.fromEntries(Object.entries(value).map(([key, entry]) => [ + remapSnapshotPath(key, mappings), + remapSnapshotValue(entry, mappings), + ])); +} + +function copyJsonSnapshot(sourcePath, destinationPath, mappings) { + const content = readSnapshotFile(sourcePath); + if (content === null) return; + let snapshot = content; + try { + const parsed = JSON.parse(content.toString('utf8')); + snapshot = Buffer.from(`${JSON.stringify(remapSnapshotValue(parsed, mappings), null, 2)}\n`); + } catch { + // Preserve malformed input so Claude reports the same inventory error from isolation. + } + fs.mkdirSync(path.dirname(destinationPath), { recursive: true, mode: 0o700 }); + fs.writeFileSync(destinationPath, snapshot, { mode: 0o600 }); +} + +function createSnapshotMappings(entries) { + const mappings = []; + for (const entry of entries) { + const sources = new Set([ + path.resolve(entry.source), + realpathNearestExisting(entry.source), + ]); + for (const source of sources) { + mappings.push({ source, destination: entry.destination }); + } + } + return mappings.sort((left, right) => right.source.length - left.source.length); +} + +function createDryRunSandbox(paths, options, baseEnv) { + const root = fs.mkdtempSync(path.join(os.tmpdir(), 'ecc-claude-dry-run-')); + const homeDir = path.join(root, 'home'); + const configDir = path.join(root, 'config'); + const projectRoot = path.join(root, 'project'); + const tempDir = path.join(root, 'tmp'); + try { + fs.chmodSync(root, 0o700); + for (const directoryPath of [homeDir, configDir, projectRoot, tempDir]) { + fs.mkdirSync(directoryPath, { recursive: true, mode: 0o700 }); + } + const mappings = createSnapshotMappings([ + { source: paths.projectRoot, destination: projectRoot }, + { source: paths.configDir, destination: configDir }, + { source: paths.homeDir, destination: homeDir }, + ]); + const snapshots = [ + [claudeStateFilePath(paths, options), path.join(configDir, '.claude.json')], + [path.join(paths.configDir, 'settings.json'), path.join(configDir, 'settings.json')], + [path.join(paths.configDir, 'settings.local.json'), path.join(configDir, 'settings.local.json')], + [ + path.join(paths.configDir, 'plugins', 'installed_plugins.json'), + path.join(configDir, 'plugins', 'installed_plugins.json'), + ], + [ + path.join(paths.configDir, 'plugins', 'known_marketplaces.json'), + path.join(configDir, 'plugins', 'known_marketplaces.json'), + ], + [ + path.join(paths.projectRoot, '.claude', 'settings.json'), + path.join(projectRoot, '.claude', 'settings.json'), + ], + [ + path.join(paths.projectRoot, '.claude', 'settings.local.json'), + path.join(projectRoot, '.claude', 'settings.local.json'), + ], + ]; + for (const [sourcePath, destinationPath] of snapshots) { + copyJsonSnapshot(sourcePath, destinationPath, mappings); + } + return { + cwd: projectRoot, + env: { + ...baseEnv, + APPDATA: path.join(root, 'appdata'), + CLAUDE_CONFIG_DIR: configDir, + CLAUDE_PROJECT_DIR: projectRoot, + HOME: homeDir, + INIT_CWD: projectRoot, + LOCALAPPDATA: path.join(root, 'localappdata'), + OLDPWD: projectRoot, + PWD: projectRoot, + TEMP: tempDir, + TMP: tempDir, + TMPDIR: tempDir, + USERPROFILE: homeDir, + XDG_CACHE_HOME: path.join(root, 'xdg-cache'), + XDG_CONFIG_HOME: path.join(root, 'xdg-config'), + XDG_DATA_HOME: path.join(root, 'xdg-data'), + XDG_STATE_HOME: path.join(root, 'xdg-state'), + }, + root, + }; + } catch (error) { + fs.rmSync(root, { force: true, recursive: true }); + throw error; + } +} + +function createDryRunClaudeRunner(run, paths, options = {}) { + return (args, runOptions = {}) => { + const sandbox = createDryRunSandbox( + paths, + options, + runOptions.env || process.env + ); + try { + return run(args, { + ...runOptions, + cwd: sandbox.cwd, + env: sandbox.env, + }); + } finally { + fs.rmSync(sandbox.root, { force: true, recursive: true }); + } + }; +} + +module.exports = { + createDryRunClaudeRunner, +}; diff --git a/github_code/affaan-m__ECC/scripts/lib/claude-plugin-setup.js b/github_code/affaan-m__ECC/scripts/lib/claude-plugin-setup.js new file mode 100644 index 0000000000000000000000000000000000000000..0672b505e9fcb5722659f33f52484100b0854c12 --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/claude-plugin-setup.js @@ -0,0 +1,722 @@ +'use strict'; + +const fs = require('fs'); +const path = require('path'); +const { spawnSync } = require('child_process'); + +const { writeFileAtomic } = require('./atomic-write'); +const { + hasExplicitCommitAttributionPreference, + withCommitAttributionDisabled, +} = require('./claude-commit-attribution'); +const { createDryRunClaudeRunner } = require('./claude-dry-run-sandbox'); +const { normalizeGitHubGitOrigin } = require('./github-origin'); +const { + CURRENT_PLUGIN_ID, + LEGACY_PLUGIN_IDS, + findManagedClaudeInstalls, + findManualClaudePlugin, + resolveClaudePaths, +} = require('./install/inventory'); + +const OFFICIAL_MARKETPLACE_NAME = 'ecc'; +const OFFICIAL_MARKETPLACE_REPO = 'affaan-m/ecc'; +const OFFICIAL_MARKETPLACE_URL = 'https://github.com/affaan-m/ECC'; +const PROVIDER_COMMAND_TIMEOUT_MS = 120 * 1000; +const VALID_SCOPES = new Set(['user', 'project', 'local']); +const VALID_HOOK_MODES = new Set(['off', 'minimal', 'standard', 'strict']); + +class ClaudeSetupError extends Error { + constructor(code, message, details = {}) { + super(message); + this.name = 'ClaudeSetupError'; + this.code = code; + this.phase = details.phase || 'preflight'; + this.observedScopes = [...(details.observedScopes || [])]; + this.recovery = [...(details.recovery || [])]; + } + + toJSON() { + return { + error: { + code: this.code, + message: this.message, + phase: this.phase, + observedScopes: [...this.observedScopes], + recovery: [...this.recovery], + }, + }; + } +} + +function fail(code, message, details) { + throw new ClaudeSetupError(code, message, details); +} + +function normalizeGitHubRepository(value) { + if (typeof value !== 'string') return null; + const normalized = value.trim().replace(/\.git$/i, '').replace(/\/+$/, ''); + const match = normalized.match(/^([^/]+\/[^/]+)$/); + return match ? match[1].toLowerCase() : null; +} + +function normalizeMarketplaceRepository(marketplace) { + return marketplace?.source === 'github' + ? normalizeGitHubRepository(marketplace.repo) + : normalizeGitHubGitOrigin(marketplace?.url); +} + +function isOfficialMarketplace(marketplace) { + if (!marketplace || marketplace.name !== OFFICIAL_MARKETPLACE_NAME) return false; + return normalizeMarketplaceRepository(marketplace) === OFFICIAL_MARKETPLACE_REPO; +} + +function parseJsonArray(stdout, label) { + let parsed; + try { + parsed = JSON.parse(String(stdout || '')); + } catch (error) { + fail( + `INVALID_${label.toUpperCase()}_INVENTORY`, + `Claude ${label} inventory returned invalid JSON: ${error.message}` + ); + } + if (!Array.isArray(parsed)) { + fail( + `INVALID_${label.toUpperCase()}_INVENTORY`, + `Claude ${label} inventory is invalid: expected a JSON array` + ); + } + return parsed; +} + +function parsePluginList(stdout) { + const plugins = parseJsonArray(stdout, 'plugin'); + for (const plugin of plugins) { + const isRelevant = plugin && ( + plugin.id === CURRENT_PLUGIN_ID + || String(plugin.id || '').startsWith('ecc@') + || LEGACY_PLUGIN_IDS.has(plugin.id) + || String(plugin.id || '').startsWith('everything-claude-code@') + ); + if (!isRelevant) continue; + if ( + typeof plugin.id !== 'string' + || !VALID_SCOPES.has(plugin.scope) + || typeof plugin.enabled !== 'boolean' + ) { + fail( + 'INVALID_PLUGIN_INVENTORY', + 'Claude plugin inventory contains an invalid ECC plugin entry' + ); + } + } + return plugins; +} + +function parseMarketplaceList(stdout) { + const marketplaces = parseJsonArray(stdout, 'marketplace'); + for (const marketplace of marketplaces) { + if (!marketplace || marketplace.name !== OFFICIAL_MARKETPLACE_NAME) continue; + if ( + typeof marketplace.name !== 'string' + || typeof marketplace.source !== 'string' + || !['github', 'git'].includes(marketplace.source) + || !normalizeMarketplaceRepository(marketplace) + ) { + fail( + 'INVALID_MARKETPLACE_INVENTORY', + 'Claude marketplace inventory contains an invalid `ecc` entry' + ); + } + } + return marketplaces; +} + +const UNSAFE_WINDOWS_SHELL_CHARS = /[\r\n&|<>^%!]/; + +function quoteWindowsCommandToken(value) { + const token = String(value); + if (UNSAFE_WINDOWS_SHELL_CHARS.test(token)) { + throw new Error('Claude Code command contains characters that are unsafe for cmd.exe'); + } + if (token === '') return '""'; + if (!/[\s"]/.test(token)) return token; + return `"${token.replace(/"/g, '""')}"`; +} + +function buildWindowsCommandLine(command, args) { + return [command, ...args].map(quoteWindowsCommandToken).join(' '); +} + +function resolveWindowsCmdShim(command, env) { + if (typeof command !== 'string' || command.length === 0) return null; + if (/\.(cmd|bat)$/i.test(command)) return command; + if (path.extname(command)) return null; + + const isPathLike = path.isAbsolute(command) + || command.includes('/') + || command.includes('\\'); + if (isPathLike) { + const candidate = `${command}.cmd`; + return fs.existsSync(candidate) ? candidate : null; + } + + const lookup = spawnSync('where.exe', [`${command}.cmd`], { + env, + encoding: 'utf8', + windowsHide: true, + }); + if (lookup.error || lookup.status !== 0) return null; + return String(lookup.stdout || '') + .split(/\r?\n/) + .map(line => line.trim()) + .find(Boolean) || null; +} + +function assertGitAvailable(options = {}, dependencies = {}) { + const spawn = dependencies.spawnSync || spawnSync; + const result = spawn('git', ['--version'], { + cwd: options.cwd || process.cwd(), + env: options.env || process.env, + encoding: 'utf8', + timeout: 10 * 1000, + windowsHide: true, + }); + if (result.error?.code === 'ENOENT') { + fail( + 'GIT_NOT_FOUND', + 'Git is required for Claude marketplace setup but `git` is not on PATH. Install Git, ensure `git` is on PATH, then rerun ECC setup.', + { + phase: 'preflight', + recovery: [ + 'Install Git from https://git-scm.com/downloads and ensure `git` is on PATH.', + 'Rerun ECC setup.', + ], + } + ); + } + if (result.error || result.status !== 0) { + const detail = String(result.stderr || result.stdout || result.error?.message || '').trim(); + fail( + 'GIT_UNAVAILABLE', + `Git is required for Claude marketplace setup but could not run${detail ? `: ${detail}` : '.'}`, + { + phase: 'preflight', + recovery: ['Repair Git, ensure `git --version` succeeds, then rerun ECC setup.'], + } + ); + } +} + +function runClaude(args, options = {}, dependencies = {}) { + const command = options.command || 'claude'; + const spawn = dependencies.spawnSync || spawnSync; + const timeoutMs = options.timeoutMs ?? PROVIDER_COMMAND_TIMEOUT_MS; + const spawnOptions = { + cwd: options.cwd || process.cwd(), + env: options.env || process.env, + encoding: 'utf8', + maxBuffer: 10 * 1024 * 1024, + killSignal: 'SIGKILL', + timeout: timeoutMs, + windowsHide: true, + }; + let result = spawn(command, args, spawnOptions); + + if (process.platform === 'win32' && result.error) { + const shim = resolveWindowsCmdShim(command, spawnOptions.env); + if (shim) { + let commandLine; + try { + commandLine = buildWindowsCommandLine(shim, args); + } catch (error) { + fail( + 'CLAUDE_COMMAND_FAILED', + `Could not run Claude Code: ${error.message}`, + { phase: options.phase || 'provider' } + ); + } + result = spawn(commandLine, { + ...spawnOptions, + shell: true, + }); + } + } + + const timedOut = ( + result.error?.code === 'ETIMEDOUT' + || (result.error?.killed === true && result.error?.signal === spawnOptions.killSignal) + ); + if (timedOut) { + fail( + 'CLAUDE_COMMAND_FAILED', + `Claude Code command timed out after ${timeoutMs} ms`, + { phase: options.phase || 'provider' } + ); + } + if (result.error) { + if (result.error.code === 'ENOENT') { + fail( + 'CLAUDE_NOT_FOUND', + 'Claude Code is not installed or `claude` is not on PATH. Install Claude Code, then rerun ECC setup.', + { phase: options.phase || 'inventory' } + ); + } + fail( + 'CLAUDE_COMMAND_FAILED', + `Could not run Claude Code: ${result.error.message}`, + { phase: options.phase || 'provider' } + ); + } + if (result.status !== 0) { + const detail = String(result.stderr || result.stdout || '').trim(); + fail( + 'CLAUDE_COMMAND_FAILED', + `Claude Code command failed${detail ? `: ${detail}` : ''}`, + { phase: options.phase || 'provider' } + ); + } + return result; +} + +function readSettings(settingsPath) { + if (!fs.existsSync(settingsPath)) return {}; + let settings; + try { + settings = JSON.parse(fs.readFileSync(settingsPath, 'utf8')); + } catch (error) { + fail( + 'INVALID_CLAUDE_SETTINGS', + `Claude user settings are invalid at ${settingsPath}: ${error.message}`, + { phase: 'preflight' } + ); + } + if (!settings || typeof settings !== 'object' || Array.isArray(settings)) { + fail( + 'INVALID_CLAUDE_SETTINGS', + `Claude user settings are invalid at ${settingsPath}: expected a JSON object`, + { phase: 'preflight' } + ); + } + const pluginConfigs = settings.pluginConfigs; + if (pluginConfigs !== undefined && ( + !pluginConfigs + || typeof pluginConfigs !== 'object' + || Array.isArray(pluginConfigs) + )) { + fail( + 'INVALID_CLAUDE_SETTINGS', + `Claude user settings are invalid at ${settingsPath}: pluginConfigs must be an object`, + { phase: 'preflight' } + ); + } + const eccConfig = pluginConfigs?.[CURRENT_PLUGIN_ID]; + if (eccConfig !== undefined && ( + !eccConfig + || typeof eccConfig !== 'object' + || Array.isArray(eccConfig) + )) { + fail( + 'INVALID_CLAUDE_SETTINGS', + `Claude user settings are invalid at ${settingsPath}: ${CURRENT_PLUGIN_ID} config must be an object`, + { phase: 'preflight' } + ); + } + if (eccConfig?.options !== undefined && ( + !eccConfig.options + || typeof eccConfig.options !== 'object' + || Array.isArray(eccConfig.options) + )) { + fail( + 'INVALID_CLAUDE_SETTINGS', + `Claude user settings are invalid at ${settingsPath}: ${CURRENT_PLUGIN_ID} options must be an object`, + { phase: 'preflight' } + ); + } + return settings; +} + +function hookOptions(hooks) { + return { + hooks_enabled: hooks !== 'off', + hook_profile: hooks === 'off' ? 'standard' : hooks, + }; +} + +function readStoredHookOptions(settings) { + const options = settings.pluginConfigs?.[CURRENT_PLUGIN_ID]?.options || {}; + return { + hooks_enabled: options.hooks_enabled !== false, + hook_profile: VALID_HOOK_MODES.has(options.hook_profile) + && options.hook_profile !== 'off' + ? options.hook_profile + : 'standard', + }; +} + +function deriveHookMode(settings) { + const options = readStoredHookOptions(settings); + return options.hooks_enabled ? options.hook_profile : 'off'; +} + +function withClaudeCommitAttributionPreference(settings) { + return withCommitAttributionDisabled(settings); +} + +function needsClaudeCommitAttributionPreferenceWrite(settings) { + return !hasExplicitCommitAttributionPreference(settings); +} + +function writeClaudePluginOptions(settingsPath, hooks) { + const settings = readSettings(settingsPath); + const pluginConfigs = settings.pluginConfigs || {}; + const eccConfig = pluginConfigs[CURRENT_PLUGIN_ID] || {}; + const options = eccConfig.options || {}; + const nextOptions = hooks === undefined + ? { ...options } + : { + ...options, + ...hookOptions(hooks), + }; + const nextSettings = { + ...withClaudeCommitAttributionPreference(settings), + pluginConfigs: { + ...pluginConfigs, + [CURRENT_PLUGIN_ID]: { + ...eccConfig, + options: nextOptions, + }, + }, + }; + writeFileAtomic(settingsPath, `${JSON.stringify(nextSettings, null, 2)}\n`); + return settingsPath; +} + +function currentEccPlugins(plugins) { + return plugins.filter(plugin => plugin?.id === CURRENT_PLUGIN_ID); +} + +function assertNoConflictingEccPlugins(plugins) { + const legacy = plugins.find(plugin => ( + LEGACY_PLUGIN_IDS.has(plugin?.id) + || String(plugin?.id || '').startsWith('everything-claude-code@') + )); + if (legacy) { + fail( + 'LEGACY_PLUGIN_INSTALLED', + `Legacy plugin ${legacy.id} is installed. Uninstall it before setting up ${CURRENT_PLUGIN_ID}.`, + { + observedScopes: [legacy.scope], + recovery: [`claude plugin uninstall ${legacy.id} --scope ${legacy.scope} --keep-data`], + } + ); + } + + const conflictingEcc = plugins.find(plugin => ( + typeof plugin?.id === 'string' + && plugin.id.startsWith('ecc@') + && plugin.id !== CURRENT_PLUGIN_ID + )); + if (conflictingEcc) { + fail( + 'DUPLICATE_ECC_PLUGIN', + `${conflictingEcc.id} is already installed and would duplicate ECC surfaces. Uninstall it before setting up ${CURRENT_PLUGIN_ID}.`, + { + observedScopes: [conflictingEcc.scope], + recovery: [ + `claude plugin uninstall ${conflictingEcc.id} --scope ${conflictingEcc.scope} --keep-data`, + ], + } + ); + } +} + +function inspectPluginInventory(plugins, requestedScope) { + assertNoConflictingEccPlugins(plugins); + const installed = currentEccPlugins(plugins); + const observedScopes = installed.map(plugin => plugin.scope); + if (installed.length > 1 || new Set(observedScopes).size !== observedScopes.length) { + fail( + 'MULTIPLE_PLUGIN_SCOPES', + `${CURRENT_PLUGIN_ID} is installed in multiple scopes. Resolve the duplicate scopes before setup.`, + { observedScopes } + ); + } + + if (!requestedScope && installed.length === 0) { + fail( + 'SCOPE_REQUIRED', + 'A fresh install requires --scope user, project, or local.' + ); + } + + const scope = requestedScope || installed[0].scope; + if (!VALID_SCOPES.has(scope)) { + fail('INVALID_SCOPE', `Invalid plugin scope: ${scope}`); + } + if (installed.length === 1 && installed[0].scope !== scope) { + fail( + 'SCOPE_MOVE_REQUIRED', + `${CURRENT_PLUGIN_ID} is already installed at ${installed[0].scope} scope. Use the scope migration workflow to move it to ${scope}.`, + { + observedScopes, + recovery: [ + `ecc setup --mode claude-plugin --scope ${scope} --move-scope --yes`, + ], + } + ); + } + + return { + installed: installed[0] || null, + observedScopes, + scope, + }; +} + +function assertSafeLocalInventory(options) { + const manual = findManualClaudePlugin(options); + if (manual) { + fail( + 'MANUAL_PLUGIN_INSTALL', + `A manual ECC plugin layout exists at ${manual.manifestPath}. Remove or migrate the manual install before setup.` + ); + } + let managedInstalls; + try { + managedInstalls = findManagedClaudeInstalls(options); + } catch (error) { + fail('INVALID_MANAGED_STATE', error.message); + } + const overlap = managedInstalls.find(install => install.overlapsPlugin); + if (overlap) { + fail( + 'MANAGED_INSTALL_OVERLAP', + `Managed ECC content at ${overlap.statePath} overlaps the Claude plugin. Remove that managed overlap before setup.` + ); + } + return managedInstalls; +} + +function ensureOfficialMarketplace(options) { + const run = options.run || runClaude; + const existing = options.marketplaces.find(entry => entry?.name === OFFICIAL_MARKETPLACE_NAME); + if (existing && !isOfficialMarketplace(existing)) { + fail( + 'MARKETPLACE_COLLISION', + 'Refusing the `ecc` marketplace collision because it is not the official affaan-m/ECC source.' + ); + } + + if (existing) { + run( + ['plugin', 'marketplace', 'update', OFFICIAL_MARKETPLACE_NAME], + { cwd: options.projectRoot, phase: 'marketplace' } + ); + } else { + run( + [ + 'plugin', 'marketplace', 'add', + OFFICIAL_MARKETPLACE_URL, + '--scope', options.scope, + ], + { cwd: options.projectRoot, phase: 'marketplace' } + ); + } + + const verified = parseMarketplaceList( + run( + ['plugin', 'marketplace', 'list', '--json'], + { cwd: options.projectRoot, phase: 'marketplace-verification' } + ).stdout + ).find(entry => entry?.name === OFFICIAL_MARKETPLACE_NAME); + if (!verified || !isOfficialMarketplace(verified)) { + fail( + 'MARKETPLACE_VERIFICATION_FAILED', + 'Could not verify the official ECC marketplace after the marketplace change.', + { phase: 'marketplace-verification' } + ); + } + return verified; +} + +function verifyPluginAtScope(options) { + const run = options.run || runClaude; + const plugins = parsePluginList( + run( + ['plugin', 'list', '--json'], + { cwd: options.projectRoot, phase: options.phase || 'plugin-verification' } + ).stdout + ); + const installed = currentEccPlugins(plugins); + const valid = ( + installed.length === 1 + && installed[0].scope === options.scope + && installed[0].enabled === true + ); + if (!valid) { + fail( + 'PLUGIN_VERIFICATION_FAILED', + `Could not verify ${CURRENT_PLUGIN_ID} as enabled only at ${options.scope} scope.`, + { + phase: options.phase || 'plugin-verification', + observedScopes: installed.map(plugin => plugin.scope), + } + ); + } + return installed[0]; +} + +function ensurePluginAtScope(options) { + const run = options.run || runClaude; + const configuredHooks = options.hookConfiguration || hookOptions(options.hooks); + if (options.installed) { + run( + ['plugin', 'update', CURRENT_PLUGIN_ID, '--scope', options.scope], + { cwd: options.projectRoot, phase: 'plugin-update' } + ); + return 'updated'; + } + run( + [ + 'plugin', 'install', CURRENT_PLUGIN_ID, + '--scope', options.scope, + '--config', `hooks_enabled=${configuredHooks.hooks_enabled}`, + '--config', `hook_profile=${configuredHooks.hook_profile}`, + ], + { cwd: options.projectRoot, phase: 'plugin-install' } + ); + return 'installed'; +} + +function setupClaudePlugin(options = {}, dependencies = {}) { + const paths = resolveClaudePaths(options); + if (options.hooks !== undefined && !VALID_HOOK_MODES.has(options.hooks)) { + fail('INVALID_HOOK_MODE', `Invalid hook mode: ${options.hooks}`); + } + if (options.scope !== undefined && !VALID_SCOPES.has(options.scope)) { + fail('INVALID_SCOPE', `Invalid plugin scope: ${options.scope}`); + } + + const settingsPath = path.join(paths.configDir, 'settings.json'); + const initialSettings = readSettings(settingsPath); + assertSafeLocalInventory(paths); + assertGitAvailable( + { cwd: paths.projectRoot }, + { spawnSync: dependencies.spawnSync } + ); + + const providerRun = dependencies.runClaude || runClaude; + const run = options.dryRun + ? createDryRunClaudeRunner(providerRun, paths, options) + : providerRun; + const plugins = parsePluginList( + run( + ['plugin', 'list', '--json'], + { cwd: paths.projectRoot, phase: 'inventory' } + ).stdout + ); + const inventory = inspectPluginInventory(plugins, options.scope); + const hooks = options.hooks === undefined && inventory.installed + ? deriveHookMode(initialSettings) + : (options.hooks || 'standard'); + const marketplaces = parseMarketplaceList( + run( + ['plugin', 'marketplace', 'list', '--json'], + { cwd: paths.projectRoot, phase: 'marketplace-inventory' } + ).stdout + ); + const namedMarketplace = marketplaces.find(entry => ( + entry?.name === OFFICIAL_MARKETPLACE_NAME + )); + if (namedMarketplace && !isOfficialMarketplace(namedMarketplace)) { + fail( + 'MARKETPLACE_COLLISION', + 'Refusing the `ecc` marketplace collision because it is not the official affaan-m/ECC source.' + ); + } + + if (options.dryRun) { + return { + action: inventory.installed ? 'would-update' : 'would-install', + dryRun: true, + hooks, + marketplaceAction: namedMarketplace ? 'would-update' : 'would-add', + pluginId: CURRENT_PLUGIN_ID, + scope: inventory.scope, + }; + } + + ensureOfficialMarketplace({ + marketplaces, + projectRoot: paths.projectRoot, + run, + scope: inventory.scope, + spawnSync: dependencies.spawnSync, + }); + const action = ensurePluginAtScope({ + hooks, + installed: inventory.installed, + projectRoot: paths.projectRoot, + run, + scope: inventory.scope, + }); + verifyPluginAtScope({ + phase: 'plugin-verification', + projectRoot: paths.projectRoot, + run, + scope: inventory.scope, + }); + const hooksToPersist = options.hooks !== undefined || !inventory.installed + ? hooks + : undefined; + if ( + options.hooks !== undefined + || !inventory.installed + || needsClaudeCommitAttributionPreferenceWrite(initialSettings) + ) { + writeClaudePluginOptions(settingsPath, hooksToPersist); + } + + return { + action, + hooks, + pluginId: CURRENT_PLUGIN_ID, + restartRequired: true, + scope: inventory.scope, + settingsPath, + }; +} + +module.exports = { + ClaudeSetupError, + CURRENT_PLUGIN_ID, + OFFICIAL_MARKETPLACE_NAME, + OFFICIAL_MARKETPLACE_URL, + PROVIDER_COMMAND_TIMEOUT_MS, + VALID_HOOK_MODES, + VALID_SCOPES, + buildWindowsCommandLine, + assertNoConflictingEccPlugins, + assertSafeLocalInventory, + assertGitAvailable, + createDryRunClaudeRunner, + currentEccPlugins, + deriveHookMode, + ensureOfficialMarketplace, + ensurePluginAtScope, + hookOptions, + inspectPluginInventory, + isOfficialMarketplace, + parseMarketplaceList, + parsePluginList, + readStoredHookOptions, + readSettings, + runClaude, + setupClaudePlugin, + verifyPluginAtScope, + needsClaudeCommitAttributionPreferenceWrite, + withClaudeCommitAttributionPreference, + writeClaudePluginOptions, +}; diff --git a/github_code/affaan-m__ECC/scripts/lib/claude-scope-migration.js b/github_code/affaan-m__ECC/scripts/lib/claude-scope-migration.js new file mode 100644 index 0000000000000000000000000000000000000000..ddb85958be0b9e229d30b55acb5e11ab8f186f6a --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/claude-scope-migration.js @@ -0,0 +1,414 @@ +'use strict'; + +const path = require('path'); + +const { + ClaudeSetupError, + CURRENT_PLUGIN_ID, + OFFICIAL_MARKETPLACE_URL, + VALID_HOOK_MODES, + VALID_SCOPES, + assertNoConflictingEccPlugins, + assertSafeLocalInventory, + assertGitAvailable, + currentEccPlugins, + createDryRunClaudeRunner, + deriveHookMode, + ensureOfficialMarketplace, + ensurePluginAtScope, + hookOptions, + isOfficialMarketplace, + needsClaudeCommitAttributionPreferenceWrite, + parseMarketplaceList, + parsePluginList, + readSettings, + readStoredHookOptions, + runClaude, + writeClaudePluginOptions, +} = require('./claude-plugin-setup'); +const { resolveClaudePaths } = require('./install/inventory'); + +function migrationError(code, message, details = {}) { + return new ClaudeSetupError(code, message, details); +} + +function recoveryCommands(sourceScope, destinationScope) { + const commands = []; + if (sourceScope) { + commands.push( + `claude plugin uninstall ${CURRENT_PLUGIN_ID} --scope ${sourceScope} --keep-data` + ); + } + commands.push( + `ecc setup --mode claude-plugin --scope ${destinationScope} --move-scope --yes` + ); + return commands; +} + +function readPluginInventory(run, projectRoot, phase) { + return parsePluginList( + run( + ['plugin', 'list', '--json'], + { cwd: projectRoot, phase } + ).stdout + ); +} + +function assertMigrationInventory(plugins, destinationScope) { + assertNoConflictingEccPlugins(plugins); + const installed = currentEccPlugins(plugins); + const observedScopes = installed.map(plugin => plugin.scope); + const uniqueScopes = new Set(observedScopes); + + if (installed.length === 0) { + throw migrationError( + 'PLUGIN_NOT_INSTALLED', + `${CURRENT_PLUGIN_ID} is not installed, so there is no source scope to migrate.`, + { + observedScopes, + recovery: [ + `ecc setup --mode claude-plugin --scope ${destinationScope} --yes`, + ], + } + ); + } + if ( + installed.length > 2 + || uniqueScopes.size !== installed.length + || ( + installed.length === 2 + && !uniqueScopes.has(destinationScope) + ) + ) { + throw migrationError( + 'AMBIGUOUS_PLUGIN_SCOPES', + `Cannot safely migrate ${CURRENT_PLUGIN_ID} from ambiguous scopes: ${observedScopes.join(', ')}.`, + { observedScopes } + ); + } + + if (installed.length === 1 && installed[0].scope === destinationScope) { + if (installed[0].enabled !== true) { + throw migrationError( + 'DESTINATION_VERIFICATION_FAILED', + `${CURRENT_PLUGIN_ID} exists at ${destinationScope} scope but is not enabled.`, + { + phase: 'destination-verification', + observedScopes, + recovery: recoveryCommands(null, destinationScope), + } + ); + } + return { + destination: installed[0], + mode: 'already-migrated', + observedScopes, + sourceScope: null, + }; + } + if (installed.length === 1) { + return { + destination: null, + mode: 'migrate', + observedScopes, + sourceScope: installed[0].scope, + }; + } + + return { + destination: installed.find(plugin => plugin.scope === destinationScope), + mode: 'resume', + observedScopes, + sourceScope: installed.find(plugin => plugin.scope !== destinationScope).scope, + }; +} + +function validateExpectedScopes(plugins, expectedScopes, options = {}) { + assertNoConflictingEccPlugins(plugins); + const installed = currentEccPlugins(plugins); + const observedScopes = installed.map(plugin => plugin.scope); + const actual = [...observedScopes].sort(); + const expected = [...expectedScopes].sort(); + const destination = installed.find(plugin => plugin.scope === options.destinationScope); + const matches = ( + actual.length === expected.length + && actual.every((scope, index) => scope === expected[index]) + && destination?.enabled === true + ); + if (!matches) { + throw migrationError( + options.code, + options.message, + { + phase: options.phase, + observedScopes, + recovery: options.recovery || [], + } + ); + } + return installed; +} + +function plannedActions(migration, destinationScope, marketplaceAction, hookConfiguration) { + const actions = []; + if (migration.mode === 'migrate') { + actions.push(marketplaceAction); + actions.push([ + 'plugin', 'install', CURRENT_PLUGIN_ID, + '--scope', destinationScope, + '--config', `hooks_enabled=${hookConfiguration.hooks_enabled}`, + '--config', `hook_profile=${hookConfiguration.hook_profile}`, + ]); + } + actions.push(['plugin', 'list', '--json']); + actions.push(['plugin', 'list', '--json']); + actions.push([ + 'plugin', 'uninstall', CURRENT_PLUGIN_ID, + '--scope', migration.sourceScope, + '--keep-data', + ]); + actions.push(['plugin', 'list', '--json']); + return actions; +} + +function verifySourceAndDestination(run, paths, migration, destinationScope, phase) { + const expectedScopes = [migration.sourceScope, destinationScope]; + return validateExpectedScopes( + readPluginInventory(run, paths.projectRoot, phase), + expectedScopes, + { + code: phase === 'concurrency-check' + ? 'CONCURRENT_SCOPE_CHANGE' + : 'DESTINATION_VERIFICATION_FAILED', + destinationScope, + message: phase === 'concurrency-check' + ? 'Claude plugin scopes changed during migration; the source was not removed.' + : `Could not verify ${CURRENT_PLUGIN_ID} at the destination before source cleanup.`, + phase, + recovery: recoveryCommands(null, destinationScope), + } + ); +} + +function uninstallSource(run, paths, migration, destinationScope) { + const args = [ + 'plugin', 'uninstall', CURRENT_PLUGIN_ID, + '--scope', migration.sourceScope, + '--keep-data', + ]; + try { + run(args, { cwd: paths.projectRoot, phase: 'source-uninstall' }); + return []; + } catch { + let observedScopes = [migration.sourceScope, destinationScope]; + try { + const plugins = readPluginInventory( + run, + paths.projectRoot, + 'source-uninstall-verification' + ); + assertNoConflictingEccPlugins(plugins); + const installed = currentEccPlugins(plugins); + observedScopes = installed.map(plugin => plugin.scope); + if ( + installed.length === 1 + && installed[0].scope === destinationScope + && installed[0].enabled === true + ) { + return ['Claude reported an uninstall error, but destination-only state was verified.']; + } + } catch { + // Preserve the safest known two-scope state in the structured recovery. + } + throw migrationError( + 'SOURCE_UNINSTALL_FAILED', + `The destination is installed, but Claude could not remove the ${migration.sourceScope} source scope.`, + { + phase: 'source-uninstall', + observedScopes, + recovery: recoveryCommands(migration.sourceScope, destinationScope), + } + ); + } +} + +function verifyFinalState(run, paths, destinationScope) { + const plugins = readPluginInventory(run, paths.projectRoot, 'final-verification'); + return validateExpectedScopes(plugins, [destinationScope], { + code: 'FINAL_VERIFICATION_FAILED', + destinationScope, + message: `Could not verify destination-only ${CURRENT_PLUGIN_ID} state after source cleanup.`, + phase: 'final-verification', + recovery: recoveryCommands(null, destinationScope), + }); +} + +function migrateClaudePluginScope(options = {}, dependencies = {}) { + if (!VALID_SCOPES.has(options.scope)) { + throw migrationError( + 'INVALID_SCOPE', + 'Scope migration requires --scope user, project, or local.' + ); + } + if (options.hooks !== undefined && !VALID_HOOK_MODES.has(options.hooks)) { + throw migrationError('INVALID_HOOK_MODE', `Invalid hook mode: ${options.hooks}`); + } + + const paths = resolveClaudePaths(options); + const settingsPath = path.join(paths.configDir, 'settings.json'); + const settings = readSettings(settingsPath); + assertSafeLocalInventory(paths); + assertGitAvailable( + { cwd: paths.projectRoot }, + { spawnSync: dependencies.spawnSync } + ); + const providerRun = dependencies.runClaude || runClaude; + const run = options.dryRun + ? createDryRunClaudeRunner(providerRun, paths, options) + : providerRun; + const plugins = readPluginInventory(run, paths.projectRoot, 'inventory'); + const migration = assertMigrationInventory(plugins, options.scope); + const hooks = options.hooks === undefined + ? deriveHookMode(settings) + : options.hooks; + const hookConfiguration = options.hooks === undefined + ? readStoredHookOptions(settings) + : hookOptions(options.hooks); + const needsCommitAttributionPreference = needsClaudeCommitAttributionPreferenceWrite(settings); + + const marketplaces = parseMarketplaceList( + run( + ['plugin', 'marketplace', 'list', '--json'], + { cwd: paths.projectRoot, phase: 'marketplace-inventory' } + ).stdout + ); + const namedMarketplace = marketplaces.find(entry => entry?.name === 'ecc'); + if (namedMarketplace && !isOfficialMarketplace(namedMarketplace)) { + throw migrationError( + 'MARKETPLACE_COLLISION', + 'Refusing the `ecc` marketplace collision because it is not the official affaan-m/ECC source.', + { + phase: 'marketplace-inventory', + observedScopes: migration.observedScopes, + } + ); + } + + if (migration.mode === 'already-migrated') { + const result = { + action: 'already-migrated', + hooks, + pluginId: CURRENT_PLUGIN_ID, + sourceScope: null, + scope: options.scope, + }; + if (options.dryRun) { + return { + ...result, + dryRun: true, + preferencesUpdated: false, + plannedActions: [ + ...(options.hooks === undefined ? [] : [{ + action: 'write-hook-preferences', + ...hookConfiguration, + }]), + ...(needsCommitAttributionPreference ? [{ + action: 'write-commit-attribution-preference', + includeCoAuthoredBy: false, + }] : []), + ], + }; + } + if (options.hooks !== undefined || needsCommitAttributionPreference) { + writeClaudePluginOptions( + settingsPath, + options.hooks !== undefined ? options.hooks : undefined + ); + return { ...result, preferencesUpdated: true }; + } + return result; + } + + let marketplaceAction = null; + if (migration.mode === 'migrate') { + marketplaceAction = namedMarketplace + ? ['plugin', 'marketplace', 'update', 'ecc'] + : [ + 'plugin', 'marketplace', 'add', + OFFICIAL_MARKETPLACE_URL, + '--scope', options.scope, + ]; + } + + if (options.dryRun) { + return { + action: migration.mode === 'resume' ? 'would-resume' : 'would-migrate', + dryRun: true, + hooks, + plannedActions: plannedActions( + migration, + options.scope, + marketplaceAction, + hookConfiguration + ), + pluginId: CURRENT_PLUGIN_ID, + sourceScope: migration.sourceScope, + scope: options.scope, + }; + } + + if (migration.mode === 'migrate') { + ensureOfficialMarketplace({ + marketplaces, + projectRoot: paths.projectRoot, + run, + scope: options.scope, + spawnSync: dependencies.spawnSync, + }); + ensurePluginAtScope({ + hookConfiguration, + hooks, + installed: false, + projectRoot: paths.projectRoot, + run, + scope: options.scope, + }); + } + + verifySourceAndDestination( + run, + paths, + migration, + options.scope, + 'destination-verification' + ); + verifySourceAndDestination( + run, + paths, + migration, + options.scope, + 'concurrency-check' + ); + const warnings = uninstallSource(run, paths, migration, options.scope); + verifyFinalState(run, paths, options.scope); + + if (options.hooks !== undefined || needsCommitAttributionPreference) { + writeClaudePluginOptions( + settingsPath, + options.hooks !== undefined ? options.hooks : undefined + ); + } + + const result = { + action: migration.mode === 'resume' ? 'resumed' : 'migrated', + hooks, + pluginId: CURRENT_PLUGIN_ID, + sourceScope: migration.sourceScope, + scope: options.scope, + }; + return warnings.length > 0 ? { ...result, warnings } : result; +} + +module.exports = { + migrateClaudePluginScope, +}; diff --git a/github_code/affaan-m__ECC/scripts/lib/codex-legacy-sync.js b/github_code/affaan-m__ECC/scripts/lib/codex-legacy-sync.js new file mode 100644 index 0000000000000000000000000000000000000000..5eb92d1802493f4a06986c4e6d54a4b026f4a0e7 --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/codex-legacy-sync.js @@ -0,0 +1,648 @@ +'use strict'; + +const crypto = require('crypto'); +const fs = require('fs'); +const os = require('os'); +const path = require('path'); +const { execFileSync } = require('child_process'); + +const SCHEMA = 'ecc.codex-legacy-sync.v1'; +const BEGIN_MARKER = ''; +const END_MARKER = ''; + +function getStatePath(codexHome) { + return path.join(codexHome, 'ecc', 'legacy-sync-state.json'); +} + +function openRegularFileNoFollow(filePath, writable = false) { + const noFollow = fs.constants.O_NOFOLLOW || 0; + const flags = (writable ? fs.constants.O_RDWR : fs.constants.O_RDONLY) | noFollow; + let descriptor; + try { + descriptor = fs.openSync(filePath, flags); + } catch (error) { + if (error.code === 'ENOENT') { + try { + const unresolved = fs.lstatSync(filePath); + if (unresolved.isSymbolicLink() || !unresolved.isFile()) { + throw new Error(`Refusing to manage non-regular legacy sync path: ${filePath}`); + } + } catch (lstatError) { + if (lstatError.code === 'ENOENT') return null; + throw lstatError; + } + throw error; + } + if (error.code === 'ELOOP') { + throw new Error(`Refusing to manage non-regular legacy sync path: ${filePath}`); + } + throw error; + } + const descriptorStat = fs.fstatSync(descriptor, { bigint: true }); + let finalPathStat; + try { + finalPathStat = fs.lstatSync(filePath, { bigint: true }); + } catch (error) { + fs.closeSync(descriptor); + if (error.code === 'ENOENT') { + throw new Error(`Legacy sync path changed while opening: ${filePath}`); + } + throw error; + } + if ( + !descriptorStat.isFile() + || !finalPathStat.isFile() + || finalPathStat.isSymbolicLink() + || descriptorStat.dev !== finalPathStat.dev + || descriptorStat.ino !== finalPathStat.ino + || descriptorStat.nlink !== 1n + || finalPathStat.nlink !== 1n + ) { + fs.closeSync(descriptor); + throw new Error(`Refusing to manage non-regular legacy sync path: ${filePath}`); + } + return { descriptor, stat: fs.fstatSync(descriptor) }; +} + +function readRegularFileNoFollow(filePath, encoding = null) { + const opened = openRegularFileNoFollow(filePath); + if (!opened) return null; + try { + return { + content: fs.readFileSync(opened.descriptor, encoding || undefined), + mode: opened.stat.mode & 0o777, + }; + } finally { + fs.closeSync(opened.descriptor); + } +} + +function replaceOpenedRegularFile(opened, content, mode = null) { + const buffer = Buffer.isBuffer(content) ? content : Buffer.from(content); + fs.ftruncateSync(opened.descriptor, 0); + fs.writeSync(opened.descriptor, buffer, 0, buffer.length, 0); + if (mode) fs.fchmodSync(opened.descriptor, mode); + fs.fsyncSync(opened.descriptor); +} + +function createRegularFileNoFollow(filePath, content, mode = 0o600) { + const noFollow = fs.constants.O_NOFOLLOW || 0; + const flags = fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL | noFollow; + const descriptor = fs.openSync(filePath, flags, mode); + try { + const stat = fs.fstatSync(descriptor); + if (!stat.isFile()) { + throw new Error(`Refusing to create non-regular legacy sync path: ${filePath}`); + } + fs.writeFileSync(descriptor, content); + fs.fchmodSync(descriptor, mode); + fs.fsyncSync(descriptor); + } finally { + fs.closeSync(descriptor); + } +} + +function removeOpenedRegularFile(filePath, opened) { + const quarantineDir = fs.mkdtempSync(path.join(path.dirname(filePath), '.ecc-remove-')); + const quarantinePath = path.join(quarantineDir, path.basename(filePath)); + fs.renameSync(filePath, quarantinePath); + const quarantined = openRegularFileNoFollow(quarantinePath); + const openedStat = fs.fstatSync(opened.descriptor, { bigint: true }); + const quarantinedStat = fs.fstatSync(quarantined.descriptor, { bigint: true }); + fs.closeSync(quarantined.descriptor); + fs.closeSync(opened.descriptor); + opened.descriptor = null; + if (quarantinedStat.dev !== openedStat.dev || quarantinedStat.ino !== openedStat.ino) { + try { + fs.linkSync(quarantinePath, filePath); + fs.unlinkSync(quarantinePath); + fs.rmdirSync(quarantineDir); + } catch (_restoreError) { + throw new Error( + `Legacy sync path changed before removal; preserved replacement at ${quarantinePath}` + ); + } + throw new Error(`Legacy sync path changed before removal: ${filePath}`); + } + fs.unlinkSync(quarantinePath); + fs.rmdirSync(quarantineDir); +} + +function atomicWriteJson(filePath, value) { + fs.mkdirSync(path.dirname(filePath), { recursive: true, mode: 0o700 }); + const tempPath = `${filePath}.tmp-${process.pid}-${Date.now()}`; + fs.writeFileSync(tempPath, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600 }); + fs.renameSync(tempPath, filePath); +} + +function readState(statePath) { + const snapshot = readRegularFileNoFollow(statePath, 'utf8'); + if (!snapshot) throw new Error(`Legacy Codex sync state not found at ${statePath}`); + return parseState(snapshot.content, statePath); +} + +function readStateIfPresent(statePath) { + const snapshot = readRegularFileNoFollow(statePath, 'utf8'); + return snapshot ? parseState(snapshot.content, statePath) : null; +} + +function parseState(content, statePath) { + const state = JSON.parse(content); + if (state.schema !== SCHEMA || !Array.isArray(state.paths)) { + throw new Error(`Invalid legacy Codex sync state at ${statePath}`); + } + return state; +} + +function hasUnsafeManagedAncestor(filePath, codexHome) { + const relativePath = path.relative(codexHome, filePath); + if (relativePath === '' || relativePath.startsWith('..') || path.isAbsolute(relativePath)) { + return relativePath !== ''; + } + const segments = relativePath.split(path.sep).slice(0, -1); + let currentPath = codexHome; + for (const segment of [null, ...segments]) { + if (segment !== null) currentPath = path.join(currentPath, segment); + try { + const stat = fs.lstatSync(currentPath); + if (stat.isSymbolicLink() || !stat.isDirectory()) return true; + } catch (error) { + if (error.code === 'ENOENT') break; + throw error; + } + } + return false; +} + +function isWithinRoot(filePath, rootPath) { + const relativePath = path.relative(rootPath, filePath); + return relativePath === '' || (!relativePath.startsWith('..') && !path.isAbsolute(relativePath)); +} + +function getTrustedRoot(state, filePath) { + const roots = Array.isArray(state.trustedRoots) && state.trustedRoots.length > 0 + ? state.trustedRoots + : [state.codexHome]; + return roots + .map(rootPath => path.resolve(rootPath)) + .find(rootPath => isWithinRoot(filePath, rootPath)) || null; +} + +function snapshotLegacyPath(filePath) { + const snapshot = readRegularFileNoFollow(filePath); + const previousType = snapshot ? 'file' : 'missing'; + return { + path: filePath, + installedSha256: null, + previousType, + previousContentBase64: snapshot ? snapshot.content.toString('base64') : null, + previousMode: snapshot ? snapshot.mode : null, + }; +} + +function assertInstalledStateUnmodified(state) { + for (const entry of state.paths) { + const filePath = path.resolve(entry.path); + const trustedRoot = getTrustedRoot(state, filePath); + if (!trustedRoot || hasUnsafeManagedAncestor(filePath, trustedRoot)) { + throw new Error(`Refusing to reuse unsafe legacy Codex ownership path: ${filePath}`); + } + const snapshot = readRegularFileNoFollow(filePath); + if (!entry.installedSha256) { + if (snapshot) throw new Error(`Refusing to replace modified legacy Codex artifact: ${filePath}`); + continue; + } + const digest = snapshot + ? crypto.createHash('sha256').update(snapshot.content).digest('hex') + : null; + if (digest !== entry.installedSha256) { + throw new Error(`Refusing to replace modified legacy Codex artifact: ${filePath}`); + } + } +} + +function beginLegacySyncState(options) { + const codexHome = path.resolve(options.codexHome); + const statePath = getStatePath(codexHome); + const configPath = path.join(codexHome, 'config.toml'); + const agentsPath = path.join(codexHome, 'AGENTS.md'); + const installedHooksPath = options.installedHooksPath ? path.resolve(options.installedHooksPath) : null; + const priorState = readStateIfPresent(statePath); + if (priorState && priorState.status !== 'installed') { + throw new Error(`Legacy Codex sync state requires recovery before reinstall: ${statePath}`); + } + if (priorState) assertInstalledStateUnmodified(priorState); + const trustedRoots = [...new Set([ + codexHome, + ...(Array.isArray(priorState?.trustedRoots) ? priorState.trustedRoots : []), + ...(priorState?.installedHooksPath ? [priorState.installedHooksPath] : []), + ...(installedHooksPath ? [installedHooksPath] : []), + ].map(rootPath => path.resolve(rootPath)))]; + const state = priorState ? { + ...priorState, + status: 'applying', + updatedAt: new Date().toISOString(), + backupDir: options.backupDir ? path.resolve(options.backupDir) : priorState.backupDir, + installedHooksPath, + trustedRoots, + rollbackPreviousHooksPath: options.previousHooksPath || null, + rollbackPaths: priorState.paths.map(entry => snapshotLegacyPath(path.resolve(entry.path))), + previousInstalledState: priorState, + } : { + schema: SCHEMA, + status: 'applying', + createdAt: new Date().toISOString(), + codexHome, + backupDir: options.backupDir ? path.resolve(options.backupDir) : null, + previousHooksPath: options.previousHooksPath || null, + installedHooksPath, + trustedRoots, + before: {}, + paths: [], + rollbackPaths: [], + }; + + for (const [key, filePath] of [['config', configPath], ['agents', agentsPath]]) { + if (priorState) break; + const snapshot = readRegularFileNoFollow(filePath, 'utf8'); + state.before[key] = snapshot ? snapshot.content : null; + } + atomicWriteJson(statePath, state); + return statePath; +} + +function recordLegacySyncPath(options) { + const state = readState(options.statePath); + const filePath = path.resolve(options.filePath); + const trustedRoot = getTrustedRoot(state, filePath); + if (!trustedRoot) { + throw new Error(`Refusing to record a legacy sync path outside trusted roots: ${filePath}`); + } + if (hasUnsafeManagedAncestor(filePath, trustedRoot)) { + throw new Error(`Refusing to manage legacy sync path through symlinked ancestor: ${filePath}`); + } + if (!state.paths.some(entry => entry.path === filePath)) { + const snapshot = snapshotLegacyPath(filePath); + state.paths.push(snapshot); + state.rollbackPaths = [...(state.rollbackPaths || []), { ...snapshot }]; + atomicWriteJson(options.statePath, state); + } +} + +function rollbackLegacyCodexSync(options) { + const state = readState(options.statePath); + const restoredPaths = []; + const retainedPaths = []; + + const rollbackPaths = Array.isArray(state.rollbackPaths) ? state.rollbackPaths : state.paths; + for (const entry of [...rollbackPaths].reverse()) { + const filePath = path.resolve(entry.path); + const trustedRoot = getTrustedRoot(state, filePath); + if (!trustedRoot) { + retainedPaths.push(filePath); + continue; + } + if (hasUnsafeManagedAncestor(filePath, trustedRoot)) { + retainedPaths.push(filePath); + continue; + } + let opened = null; + try { + opened = openRegularFileNoFollow(filePath, true); + } catch (_error) { + retainedPaths.push(filePath); + continue; + } + if (entry.previousType === 'file' && typeof entry.previousContentBase64 === 'string') { + const previousContent = Buffer.from(entry.previousContentBase64, 'base64'); + const previousMode = entry.previousMode || 0o600; + fs.mkdirSync(path.dirname(filePath), { recursive: true, mode: 0o700 }); + if (opened) { + try { + replaceOpenedRegularFile(opened, previousContent, previousMode); + } finally { + if (opened.descriptor !== null) fs.closeSync(opened.descriptor); + } + } else { + createRegularFileNoFollow(filePath, previousContent, previousMode); + } + restoredPaths.push(filePath); + } else if (entry.previousType === 'missing' || entry.previousType === undefined) { + if (opened) { + try { + removeOpenedRegularFile(filePath, opened); + } finally { + if (opened.descriptor !== null) fs.closeSync(opened.descriptor); + } + } + restoredPaths.push(filePath); + } else { + if (opened && opened.descriptor !== null) fs.closeSync(opened.descriptor); + retainedPaths.push(filePath); + } + } + + if (state.installedHooksPath) { + const getHooks = options.getGlobalHooksPath || defaultGetHooksPath; + const setHooks = options.setGlobalHooksPath || defaultSetHooksPath; + const currentHooks = getHooks(); + if (currentHooks && path.resolve(currentHooks) === path.resolve(state.installedHooksPath)) { + setHooks(state.rollbackPreviousHooksPath ?? state.previousHooksPath ?? ''); + } else if (currentHooks && currentHooks !== (state.rollbackPreviousHooksPath ?? state.previousHooksPath)) { + retainedPaths.push(`git:core.hooksPath=${currentHooks}`); + } + } + + if (retainedPaths.length === 0) { + if (state.previousInstalledState) { + atomicWriteJson(options.statePath, state.previousInstalledState); + } else { + fs.rmSync(options.statePath, { force: true }); + } + } + return { + status: retainedPaths.length === 0 ? 'rolled-back' : 'partial', + statePath: options.statePath, + restoredPaths, + retainedPaths: [...new Set(retainedPaths)].sort(), + }; +} + +function finalizeLegacySyncState(options) { + const state = readState(options.statePath); + state.status = 'installed'; + state.installedAt = new Date().toISOString(); + delete state.rollbackPaths; + delete state.rollbackPreviousHooksPath; + delete state.previousInstalledState; + state.paths = state.paths.map(entry => { + const trustedRoot = getTrustedRoot(state, path.resolve(entry.path)); + let installedSha256 = null; + if (trustedRoot && !hasUnsafeManagedAncestor(entry.path, trustedRoot)) { + try { + const snapshot = readRegularFileNoFollow(entry.path); + installedSha256 = snapshot + ? crypto.createHash('sha256').update(snapshot.content).digest('hex') + : null; + } catch (_error) { + installedSha256 = null; + } + } + return { ...entry, installedSha256 }; + }); + atomicWriteJson(options.statePath, state); + return state; +} + +function stripMarkerBlock(content) { + const markers = []; + let fence = null; + let offset = 0; + for (const lineWithEnding of content.match(/.*(?:\r?\n|$)/g) || []) { + if (lineWithEnding === '') continue; + const line = lineWithEnding.replace(/\r?\n$/, ''); + const fenceMatch = line.match(/^\s*(`{3,}|~{3,})(.*)$/); + if (fenceMatch) { + const run = fenceMatch[1]; + const marker = run[0]; + if (!fence) { + fence = { marker, length: run.length }; + } else if ( + marker === fence.marker + && run.length >= fence.length + && fenceMatch[2].trim() === '' + ) { + fence = null; + } + } else if (!fence && (line === BEGIN_MARKER || line === END_MARKER)) { + markers.push({ marker: line, index: offset }); + } + offset += lineWithEnding.length; + } + const begins = markers.filter(match => match.marker === BEGIN_MARKER); + const ends = markers.filter(match => match.marker === END_MARKER); + if (begins.length !== 1 || ends.length !== 1 || ends[0].index < begins[0].index) { + return content; + } + const suffixStart = ends[0].index + END_MARKER.length; + const suffixWithLineEnding = content.slice(suffixStart).replace(/^\r?\n/, ''); + return `${content.slice(0, begins[0].index)}${suffixWithLineEnding}`; +} + +function defaultGetHooksPath() { + try { + return execFileSync('git', ['config', '--global', '--get', 'core.hooksPath'], { + encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], timeout: 5000, + }).trim(); + } catch (_error) { + return ''; + } +} + +function defaultSetHooksPath(value) { + const args = value + ? ['config', '--global', 'core.hooksPath', value] + : ['config', '--global', '--unset-all', 'core.hooksPath']; + try { + execFileSync('git', args, { stdio: 'ignore', timeout: 5000 }); + } catch (error) { + if (value || error.status !== 5) throw error; + } +} + +function listLegacyCandidates(codexHome) { + const candidates = []; + const promptsDir = path.join(codexHome, 'prompts'); + if (fs.existsSync(promptsDir)) { + for (const entry of fs.readdirSync(promptsDir)) { + if (entry.startsWith('ecc-') || entry.startsWith('ecc_') || entry.includes('ecc-rules-pack')) { + candidates.push(path.join(promptsDir, entry)); + } + } + } + for (const relativePath of [ + 'docs/CODEX-NAVIGATION-GUIDE.md', + 'docs/COMMAND-AGENT-MAP.md', + 'COMMANDS-QUICK-REF.md', + 'CONTRIBUTING.md', + '.github/PULL_REQUEST_TEMPLATE.md', + 'ecc-prompts-manifest.txt', + 'ecc-extension-prompts-manifest.txt', + ]) { + const candidate = path.join(codexHome, relativePath); + if (fs.existsSync(candidate)) candidates.push(candidate); + } + return candidates; +} + +function hasMarkerBlock(codexHome) { + const agentsPath = path.join(codexHome, 'AGENTS.md'); + try { + const snapshot = readRegularFileNoFollow(agentsPath, 'utf8'); + if (snapshot) { + const stripped = stripMarkerBlock(snapshot.content); + return stripped !== snapshot.content; + } + } catch (error) { + // Only ENOENT means "no AGENTS.md" → no marker. Any other error + // (EACCES, EMFILE, EISDIR, symlink-ELOOP, ...) is an indeterminate + // inspection result and must propagate so callers do not read it as + // "clean home". Throwing here is intentional per the repo coding + // guideline: "Always handle errors explicitly at every level and never + // silently swallow errors." + if (error && error.code === 'ENOENT') return false; + throw error; + } + return false; +} + +function resolveCodexHome(codexHome) { + return path.resolve(codexHome || process.env.CODEX_HOME || path.join(process.env.HOME || os.homedir(), '.codex')); +} + +function legacyCodexSyncStateExists(codexHome) { + const resolvedCodexHome = resolveCodexHome(codexHome); + return readStateIfPresent(getStatePath(resolvedCodexHome)) !== null; +} + +function detectLegacyCodexSync(codexHome) { + const resolvedCodexHome = resolveCodexHome(codexHome); + if (readStateIfPresent(getStatePath(resolvedCodexHome))) return true; + return hasMarkerBlock(resolvedCodexHome); +} + +function uninstallLegacyCodexSync(options = {}) { + const codexHome = path.resolve(options.codexHome || process.env.CODEX_HOME || path.join(process.env.HOME || os.homedir(), '.codex')); + const statePath = getStatePath(codexHome); + const dryRun = options.dryRun === true; + const retainedPaths = []; + const plannedRemovals = []; + const removedPaths = []; + const agentsPath = path.join(codexHome, 'AGENTS.md'); + const state = readStateIfPresent(statePath); + + if (!state) { + let openedAgents = null; + try { + openedAgents = openRegularFileNoFollow(agentsPath, !dryRun); + if (openedAgents) { + const content = fs.readFileSync(openedAgents.descriptor, 'utf8'); + const stripped = stripMarkerBlock(content); + if (stripped !== content) { + plannedRemovals.push(`${agentsPath}#ecc-marker-block`); + if (!dryRun) { + replaceOpenedRegularFile(openedAgents, stripped, openedAgents.stat.mode & 0o777); + removedPaths.push(agentsPath); + } + } + } + } catch (_error) { + if (_error.code !== 'ENOENT') retainedPaths.push(agentsPath); + } finally { + if (openedAgents) fs.closeSync(openedAgents.descriptor); + } + retainedPaths.push(...listLegacyCandidates(codexHome)); + const hasWork = plannedRemovals.length > 0 || removedPaths.length > 0; + const status = dryRun + ? (hasWork || retainedPaths.length > 0 ? 'planned' : 'not-found') + : (retainedPaths.length > 0 ? 'partial' : (hasWork ? 'uninstalled' : 'not-found')); + return { + status, + statePath: null, + plannedRemovals, + removedPaths, + retainedPaths: [...new Set(retainedPaths)].sort(), + warnings: retainedPaths.length > 0 + ? ['Legacy Codex artifacts without an ownership manifest were preserved for manual review.'] + : [], + }; + } + + for (const entry of state.paths) { + const filePath = path.resolve(entry.path); + const trustedRoot = getTrustedRoot(state, filePath); + if (!trustedRoot) { + retainedPaths.push(filePath); + continue; + } + if (hasUnsafeManagedAncestor(filePath, trustedRoot)) { + retainedPaths.push(filePath); + continue; + } + let opened = null; + try { + opened = openRegularFileNoFollow(filePath, !dryRun); + } catch (_error) { + retainedPaths.push(filePath); + continue; + } + if (!opened) continue; + const currentContent = fs.readFileSync(opened.descriptor); + const matches = entry.installedSha256 + ? crypto.createHash('sha256').update(currentContent).digest('hex') === entry.installedSha256 + : false; + if (!matches) { + if (opened.descriptor !== null) fs.closeSync(opened.descriptor); + retainedPaths.push(filePath); + continue; + } + plannedRemovals.push(filePath); + if (!dryRun) { + if (entry.previousType === 'file' && typeof entry.previousContentBase64 === 'string') { + replaceOpenedRegularFile( + opened, + Buffer.from(entry.previousContentBase64, 'base64'), + entry.previousMode || 0o600 + ); + } else if (entry.previousType === 'missing' || entry.previousType === undefined) { + removeOpenedRegularFile(filePath, opened); + } else { + if (opened.descriptor !== null) fs.closeSync(opened.descriptor); + retainedPaths.push(filePath); + continue; + } + removedPaths.push(filePath); + } + if (opened.descriptor !== null) fs.closeSync(opened.descriptor); + } + + if (state.installedHooksPath) { + const getHooks = options.getGlobalHooksPath || defaultGetHooksPath; + const setHooks = options.setGlobalHooksPath || defaultSetHooksPath; + const currentHooks = getHooks(); + if (path.resolve(currentHooks || '.') === path.resolve(state.installedHooksPath)) { + if (!dryRun) setHooks(state.previousHooksPath || ''); + } else if (currentHooks) { + retainedPaths.push(`git:core.hooksPath=${currentHooks}`); + } + } + + if (!dryRun && retainedPaths.length === 0) { + fs.rmSync(statePath, { force: true }); + } + return { + status: dryRun ? 'planned' : retainedPaths.length > 0 ? 'partial' : 'uninstalled', + statePath, + plannedRemovals: [...new Set(plannedRemovals)], + removedPaths, + retainedPaths: [...new Set(retainedPaths)].sort(), + warnings: retainedPaths.length > 0 + ? ['Modified or unverifiable legacy Codex artifacts were preserved.'] + : [], + }; +} + +module.exports = { + BEGIN_MARKER, + END_MARKER, + SCHEMA, + beginLegacySyncState, + detectLegacyCodexSync, + finalizeLegacySyncState, + getStatePath, + legacyCodexSyncStateExists, + recordLegacySyncPath, + rollbackLegacyCodexSync, + stripMarkerBlock, + uninstallLegacyCodexSync, +}; diff --git a/github_code/affaan-m__ECC/scripts/lib/codex-plugin-setup.js b/github_code/affaan-m__ECC/scripts/lib/codex-plugin-setup.js new file mode 100644 index 0000000000000000000000000000000000000000..2f7de4170dea1cc760cbbcb86289520eb4e395bb --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/codex-plugin-setup.js @@ -0,0 +1,478 @@ +'use strict'; + +const { execFile: nodeExecFile } = require('child_process'); +const path = require('path'); +const { normalizeGitHubGitOrigin } = require('./github-origin'); + +const CODEX_PLUGIN_ID = 'ecc@ecc'; +const OFFICIAL_MARKETPLACE_NAME = 'ecc'; +const OFFICIAL_MARKETPLACE_REPO = 'affaan-m/ECC'; +const NORMALIZED_OFFICIAL_MARKETPLACE_REPO = OFFICIAL_MARKETPLACE_REPO.toLowerCase(); +const MAX_OUTPUT_BYTES = 10 * 1024 * 1024; +const PROVIDER_COMMAND_TIMEOUT_MS = 120 * 1000; + +class CodexPluginSetupError extends Error { + constructor(code, message, details = {}) { + super(message); + this.name = 'CodexPluginSetupError'; + this.code = code; + this.phase = details.phase || 'inventory'; + this.argv = [...(details.argv || [])]; + } +} + +function fail(code, message, details) { + throw new CodexPluginSetupError(code, message, details); +} + +function parseJsonObject(stdout, inventoryName, phase = 'inventory') { + let parsed; + try { + parsed = JSON.parse(String(stdout || '')); + } catch (error) { + fail( + `INVALID_${inventoryName.toUpperCase()}_INVENTORY`, + `Codex ${inventoryName} inventory returned invalid JSON: ${error.message}`, + { phase } + ); + } + if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) { + fail( + `INVALID_${inventoryName.toUpperCase()}_INVENTORY`, + `Codex ${inventoryName} inventory is invalid: expected a JSON object`, + { phase } + ); + } + return parsed; +} + +function parseMarketplaceInventory(stdout, phase) { + const inventory = parseJsonObject(stdout, 'marketplace', phase); + if (!Array.isArray(inventory.marketplaces)) { + fail( + 'INVALID_MARKETPLACE_INVENTORY', + 'Codex marketplace inventory is invalid: expected `marketplaces` to be an array', + { phase } + ); + } + for (const marketplace of inventory.marketplaces) { + if ( + !marketplace + || typeof marketplace.name !== 'string' + || marketplace.name.length === 0 + || typeof marketplace.root !== 'string' + || marketplace.root.length === 0 + ) { + fail( + 'INVALID_MARKETPLACE_INVENTORY', + 'Codex marketplace inventory contains an invalid marketplace entry', + { phase } + ); + } + } + const eccEntries = inventory.marketplaces.filter( + marketplace => marketplace.name === OFFICIAL_MARKETPLACE_NAME + ); + if (eccEntries.length > 1) { + fail( + 'INVALID_MARKETPLACE_INVENTORY', + 'Codex marketplace inventory contains duplicate `ecc` entries', + { phase } + ); + } + return inventory.marketplaces; +} + +function assertPluginEntries(entries, field, phase) { + if (!Array.isArray(entries)) { + fail( + 'INVALID_PLUGIN_INVENTORY', + `Codex plugin inventory is invalid: expected \`${field}\` to be an array`, + { phase } + ); + } + for (const plugin of entries) { + if ( + !plugin + || typeof plugin.pluginId !== 'string' + || plugin.pluginId.length === 0 + ) { + fail( + 'INVALID_PLUGIN_INVENTORY', + `Codex plugin inventory contains an invalid \`${field}\` entry`, + { phase } + ); + } + if (plugin.installed !== undefined && typeof plugin.installed !== 'boolean') { + fail( + 'INVALID_PLUGIN_INVENTORY', + `Codex plugin inventory contains an invalid \`${field}\` install state`, + { phase } + ); + } + if (plugin.enabled !== undefined && typeof plugin.enabled !== 'boolean') { + fail( + 'INVALID_PLUGIN_INVENTORY', + `Codex plugin inventory contains an invalid \`${field}\` enabled state`, + { phase } + ); + } + } +} + +function parsePluginInventory(stdout, phase) { + const inventory = parseJsonObject(stdout, 'plugin', phase); + assertPluginEntries(inventory.installed, 'installed', phase); + assertPluginEntries(inventory.available, 'available', phase); + const eccEntries = inventory.installed.filter( + plugin => plugin.pluginId === CODEX_PLUGIN_ID + ); + if (eccEntries.length > 1) { + fail( + 'INVALID_PLUGIN_INVENTORY', + `Codex plugin inventory contains duplicate ${CODEX_PLUGIN_ID} entries`, + { phase } + ); + } + return { + installed: [...inventory.installed], + available: [...inventory.available], + }; +} + +function executeFile(execFile, command, args, options) { + return new Promise((resolve, reject) => { + execFile(command, args, options, (error, stdout, stderr) => { + if (error) { + if (error.stderr === undefined) error.stderr = stderr; + if (error.stdout === undefined) error.stdout = stdout; + reject(error); + return; + } + resolve({ stdout: String(stdout || ''), stderr: String(stderr || '') }); + }); + }); +} + +function isCommandTimeout(error, killSignal = 'SIGKILL') { + return error?.code === 'ETIMEDOUT' + || (error?.killed === true && error?.signal === killSignal); +} + +async function runCodexCommand(args, options = {}, dependencies = {}) { + const command = dependencies.command || options.command || 'codex'; + const execFile = dependencies.execFile || nodeExecFile; + const argv = [...args]; + const timeoutMs = options.timeoutMs ?? PROVIDER_COMMAND_TIMEOUT_MS; + const killSignal = 'SIGKILL'; + try { + return await executeFile(execFile, command, argv, { + cwd: options.cwd || process.cwd(), + encoding: 'utf8', + env: options.env || process.env, + maxBuffer: MAX_OUTPUT_BYTES, + killSignal, + shell: false, + timeout: timeoutMs, + windowsHide: true, + }); + } catch (error) { + if (isCommandTimeout(error, killSignal)) { + fail( + 'CODEX_COMMAND_TIMEOUT', + `Codex command timed out after ${timeoutMs} ms`, + { argv, phase: options.phase } + ); + } + if (error?.code === 'ENOENT') { + fail( + 'CODEX_NOT_FOUND', + 'Codex CLI is not installed or `codex` is not on PATH. Install Codex, then rerun ECC setup.', + { argv, phase: options.phase } + ); + } + const detail = String(error?.stderr || error?.stdout || error?.message || '').trim(); + fail( + 'CODEX_COMMAND_FAILED', + `Codex command failed${detail ? `: ${detail}` : ''}`, + { argv, phase: options.phase } + ); + } +} + +async function resolveMarketplaceRepository(marketplace, options = {}, dependencies = {}) { + const execFile = dependencies.execFile || nodeExecFile; + const timeoutMs = options.timeoutMs ?? PROVIDER_COMMAND_TIMEOUT_MS; + const killSignal = 'SIGKILL'; + let result; + try { + result = await executeFile( + execFile, + dependencies.gitCommand || 'git', + ['-C', marketplace.root, 'remote', 'get-url', 'origin'], + { + cwd: options.cwd || process.cwd(), + encoding: 'utf8', + env: options.env || process.env, + maxBuffer: MAX_OUTPUT_BYTES, + killSignal, + shell: false, + timeout: timeoutMs, + windowsHide: true, + } + ); + } catch (error) { + if (isCommandTimeout(error, killSignal)) { + fail( + 'MARKETPLACE_PROVENANCE_TIMEOUT', + `Git provenance verification timed out after ${timeoutMs} ms`, + { phase: options.phase || 'marketplace-provenance' } + ); + } + const detail = String(error?.stderr || error?.message || '').trim(); + fail( + 'MARKETPLACE_COLLISION', + `Refusing the existing \`ecc\` marketplace because its Git provenance could not be verified${detail ? `: ${detail}` : ''}.`, + { phase: options.phase || 'marketplace-provenance' } + ); + } + return String(result.stdout || '').trim(); +} + +async function assertOfficialMarketplace( + marketplace, + options, + dependencies, + phase = 'marketplace-provenance' +) { + if (!marketplace) return; + const resolveRepository = dependencies.resolveMarketplaceRepository + || (entry => resolveMarketplaceRepository( + entry, + { ...options, phase }, + dependencies + )); + let repository; + try { + repository = normalizeGitHubGitOrigin(await resolveRepository(marketplace)); + } catch (error) { + if (error instanceof CodexPluginSetupError) throw error; + const detail = String(error?.message || error || '').trim(); + fail( + 'MARKETPLACE_COLLISION', + `Refusing the existing \`ecc\` marketplace because its provenance could not be verified${detail ? `: ${detail}` : ''}.`, + { phase } + ); + } + if (repository !== NORMALIZED_OFFICIAL_MARKETPLACE_REPO) { + fail( + 'MARKETPLACE_COLLISION', + 'Refusing the existing `ecc` marketplace because it is not the official affaan-m/ECC source.', + { phase } + ); + } +} + +function normalizeMarketplaceRoot(value) { + if (typeof value !== 'string' || value.length === 0) return null; + const isWindowsPath = /^[a-z]:[\\/]/i.test(value) || /^\\\\/.test(value); + const normalized = isWindowsPath + ? path.win32.normalize(value) + : path.posix.normalize(value); + return isWindowsPath ? normalized.toLowerCase() : normalized; +} + +function parseMarketplaceUpgradeResult(stdout, marketplace) { + const phase = 'marketplace-upgrade'; + const argv = [ + 'plugin', 'marketplace', 'upgrade', OFFICIAL_MARKETPLACE_NAME, '--json', + ]; + let result; + try { + result = JSON.parse(String(stdout || '')); + } catch (error) { + fail( + 'INVALID_MARKETPLACE_UPGRADE_RESULT', + `Codex marketplace refresh returned invalid JSON: ${error.message}`, + { phase, argv } + ); + } + const validShape = ( + result + && typeof result === 'object' + && !Array.isArray(result) + && Array.isArray(result.selectedMarketplaces) + && result.selectedMarketplaces.every(name => typeof name === 'string') + && Array.isArray(result.upgradedRoots) + && result.upgradedRoots.every(root => typeof root === 'string' && root.length > 0) + && Array.isArray(result.errors) + ); + if (!validShape) { + fail( + 'INVALID_MARKETPLACE_UPGRADE_RESULT', + 'Codex marketplace refresh returned an invalid result.', + { phase, argv } + ); + } + const expectedRoot = normalizeMarketplaceRoot(marketplace.root); + const upgradedRoot = result.upgradedRoots.length === 1 + ? normalizeMarketplaceRoot(result.upgradedRoots[0]) + : null; + if ( + result.errors.length > 0 + || result.selectedMarketplaces.length !== 1 + || result.selectedMarketplaces[0] !== OFFICIAL_MARKETPLACE_NAME + || upgradedRoot !== expectedRoot + ) { + fail( + 'MARKETPLACE_REFRESH_FAILED', + 'Codex did not confirm that the official ECC marketplace was refreshed.', + { phase, argv } + ); + } + return result; +} + +function findEccMarketplace(marketplaces) { + return marketplaces.find( + marketplace => marketplace.name === OFFICIAL_MARKETPLACE_NAME + ) || null; +} + +function findInstalledEccPlugin(inventory) { + return inventory.installed.find( + plugin => plugin.pluginId === CODEX_PLUGIN_ID + ) || null; +} + +async function readMarketplaceInventory(run, phase) { + const result = await run( + ['plugin', 'marketplace', 'list', '--json'], + { phase } + ); + return parseMarketplaceInventory(result.stdout, phase); +} + +async function readPluginInventory(run, phase) { + const result = await run(['plugin', 'list', '--json'], { phase }); + return parsePluginInventory(result.stdout, phase); +} + +async function reconcileCodexPlugin(options = {}, dependencies = {}) { + const run = (args, details = {}) => runCodexCommand( + args, + { + command: options.command, + cwd: options.cwd, + env: options.env, + phase: details.phase, + }, + dependencies + ); + const marketplaces = await readMarketplaceInventory(run, 'marketplace-inventory'); + const plugins = await readPluginInventory(run, 'plugin-inventory'); + const marketplace = findEccMarketplace(marketplaces); + const installedPlugin = findInstalledEccPlugin(plugins); + await assertOfficialMarketplace(marketplace, options, dependencies); + const pluginReady = ( + installedPlugin?.installed === true + && installedPlugin.enabled === true + ); + const isReconciled = Boolean(marketplace && pluginReady); + + if (options.dryRun) { + return { + action: isReconciled + ? 'unchanged' + : (installedPlugin ? 'would-update' : 'would-install'), + dryRun: true, + marketplaceAction: marketplace + ? 'would-upgrade' + : 'would-add', + pluginId: CODEX_PLUGIN_ID, + restartRequired: !isReconciled, + }; + } + + const marketplaceArgs = marketplace + ? ['plugin', 'marketplace', 'upgrade', OFFICIAL_MARKETPLACE_NAME, '--json'] + : ['plugin', 'marketplace', 'add', OFFICIAL_MARKETPLACE_REPO, '--json']; + const marketplaceAction = marketplace ? 'upgraded' : 'added'; + const marketplaceResult = await run(marketplaceArgs, { + phase: marketplace ? 'marketplace-upgrade' : 'marketplace-add', + }); + if (marketplace) { + parseMarketplaceUpgradeResult(marketplaceResult.stdout, marketplace); + } + + const verifiedMarketplaces = await readMarketplaceInventory( + run, + 'marketplace-verification' + ); + if (!findEccMarketplace(verifiedMarketplaces)) { + fail( + 'MARKETPLACE_VERIFICATION_FAILED', + 'Could not verify the ECC marketplace after reconciliation.', + { phase: 'marketplace-verification' } + ); + } + await assertOfficialMarketplace( + findEccMarketplace(verifiedMarketplaces), + options, + dependencies, + 'marketplace-verification' + ); + + const pluginsAfterMarketplace = marketplace + ? await readPluginInventory(run, 'plugin-verification') + : plugins; + const pluginAfterMarketplace = findInstalledEccPlugin(pluginsAfterMarketplace); + const pluginReadyAfterMarketplace = ( + pluginAfterMarketplace?.installed === true + && pluginAfterMarketplace.enabled === true + ); + + if (!pluginReadyAfterMarketplace) { + await run( + ['plugin', 'add', CODEX_PLUGIN_ID, '--json'], + { phase: 'plugin-add' } + ); + } + + const verifiedPlugins = pluginReadyAfterMarketplace + ? pluginsAfterMarketplace + : await readPluginInventory(run, 'plugin-verification'); + const verifiedPlugin = findInstalledEccPlugin(verifiedPlugins); + if (!(verifiedPlugin?.installed === true && verifiedPlugin.enabled === true)) { + fail( + 'PLUGIN_VERIFICATION_FAILED', + `Could not verify ${CODEX_PLUGIN_ID} as installed and enabled after reconciliation.`, + { phase: 'plugin-verification' } + ); + } + + return { + action: installedPlugin ? 'updated' : 'installed', + marketplaceAction, + pluginId: CODEX_PLUGIN_ID, + restartRequired: marketplaceAction === 'upgraded' || !pluginReadyAfterMarketplace, + }; +} + +module.exports = { + CODEX_PLUGIN_ID, + CodexPluginSetupError, + OFFICIAL_MARKETPLACE_NAME, + OFFICIAL_MARKETPLACE_REPO, + PROVIDER_COMMAND_TIMEOUT_MS, + executeFile, + findEccMarketplace, + findInstalledEccPlugin, + normalizeGitHubGitOrigin, + parseMarketplaceInventory, + parseMarketplaceUpgradeResult, + parsePluginInventory, + reconcileCodexPlugin, + resolveMarketplaceRepository, + runCodexCommand, +}; diff --git a/github_code/affaan-m__ECC/scripts/lib/compute-sponsor.js b/github_code/affaan-m__ECC/scripts/lib/compute-sponsor.js new file mode 100644 index 0000000000000000000000000000000000000000..98b1951ba912b7acf3dc8c7ee7cf873a76c7eaed --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/compute-sponsor.js @@ -0,0 +1,19 @@ +'use strict'; + +const ITO_COMPUTE_URL = 'https://compute.itomarkets.com'; + +function getComputeSponsorCopy() { + return "Run or self-host any open-source model. Itô is ECC's preferred compute sponsor: " + + 'open its dashboard to sign in and rent or manage GPUs at ' + + ITO_COMPUTE_URL + + '. Any GPU provider works. This sponsorship link is passive: it does not invoke ' + + 'an RFQ, reserve capacity, provision compute, or configure serving. Separately, ' + + 'the opt-in "ecc ito find" bridge invokes the explicitly configured canonical ' + + 'Itô CLI and submits a live authenticated RFQ; it does not reserve capacity. ' + + 'Managed inference through Itô is not live yet.'; +} + +module.exports = Object.freeze({ + ITO_COMPUTE_URL, + getComputeSponsorCopy, +}); diff --git a/github_code/affaan-m__ECC/scripts/lib/control-pane/actions.js b/github_code/affaan-m__ECC/scripts/lib/control-pane/actions.js new file mode 100644 index 0000000000000000000000000000000000000000..af70e542f16a3ad1223063639d53361a520efd82 --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/control-pane/actions.js @@ -0,0 +1,133 @@ +'use strict'; + +const path = require('path'); + +const ACTION_DEFINITIONS = new Map([ + [ + 'sync-knowledge', + { + label: 'Sync Knowledge', + description: 'Import all configured ECC2 memory connectors into the context graph.', + args: ({ limit }) => [ + 'run', + '--quiet', + '--', + 'graph', + 'connector-sync', + '--all', + '--json', + '--limit', + String(limit), + ], + executable: true, + }, + ], + [ + 'recall-knowledge', + { + label: 'Recall Knowledge', + description: 'Run ECC2 context recall for the current operator query.', + args: ({ query, limit }) => [ + 'run', + '--quiet', + '--', + 'graph', + 'recall', + query || 'ECC control pane', + '--json', + '--limit', + String(limit), + ], + executable: true, + }, + ], + [ + 'graph-sync', + { + label: 'Backfill Graph', + description: 'Backfill the ECC2 graph from sessions, decisions, file activity, and messages.', + args: ({ limit }) => [ + 'run', + '--quiet', + '--', + 'graph', + 'sync', + '--all', + '--json', + '--limit', + String(limit), + ], + executable: true, + }, + ], + [ + 'open-dashboard', + { + label: 'Open TUI', + description: 'Launch the ECC2 terminal dashboard.', + args: () => ['run', '--quiet', '--', 'dashboard'], + executable: false, + }, + ], +]); + +function normalizeLimit(value, fallback = 25) { + const parsed = Number.parseInt(String(value ?? fallback), 10); + if (!Number.isFinite(parsed) || parsed < 1) return fallback; + return Math.min(parsed, 500); +} + +function shellQuote(value) { + const text = String(value); + if (text.length === 0) return "''"; + if (/^[A-Za-z0-9_./:=@%+-]+$/.test(text)) return text; + return `'${text.replace(/'/g, `'\\''`)}'`; +} + +function commandLineFor(action) { + return [ + `cd ${shellQuote(action.cwd)}`, + '&&', + shellQuote(action.command), + ...action.args.map(shellQuote), + ].join(' '); +} + +function buildControlPaneAction(actionId, options = {}) { + const definition = ACTION_DEFINITIONS.get(actionId); + if (!definition) { + throw new Error(`Unknown control-pane action: ${actionId}`); + } + + const repoRoot = path.resolve(options.repoRoot || process.cwd()); + const cwd = path.join(repoRoot, 'ecc2'); + const limit = normalizeLimit(options.limit); + const query = String(options.query || '').trim(); + const args = definition.args({ limit, query }); + const action = { + id: actionId, + label: definition.label, + description: definition.description, + command: 'cargo', + args, + cwd, + executable: definition.executable, + }; + + return { + ...action, + commandLine: commandLineFor(action), + }; +} + +function buildControlPaneActions(options = {}) { + return Array.from(ACTION_DEFINITIONS.keys()).map(actionId => + buildControlPaneAction(actionId, options) + ); +} + +module.exports = { + buildControlPaneAction, + buildControlPaneActions, + shellQuote, +}; diff --git a/github_code/affaan-m__ECC/scripts/lib/control-pane/message-sink.js b/github_code/affaan-m__ECC/scripts/lib/control-pane/message-sink.js new file mode 100644 index 0000000000000000000000000000000000000000..e03c856e189e565983f3c538eee727a96f40f1ac --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/control-pane/message-sink.js @@ -0,0 +1,70 @@ +'use strict'; + +/** + * Concrete message sink for proximity triggers: delivers a session-to-session + * message through the canonical writer, the `ecc-tui messages send` CLI. The CLI + * owns the ecc2 session DB (the `messages` table the control pane reads), so we + * shell out to it rather than writing the SQLite directly and racing the daemon. + * + * Best-effort: if the binary is not found / the command fails, the call throws, + * and the dispatcher counts it as skipped — proximity never blocks on delivery. + * The command runner and binary path are injectable for tests. + */ + +const fs = require('fs'); +const path = require('path'); +const { execFileSync } = require('child_process'); + +// Proximity trigger type → ecc-tui message kind (value_enum on `--kind`). +// A steer/hold is a collision warning; a transmit is a "what are you doing" query. +const KIND_BY_TYPE = { + proximity_steer: 'conflict', + proximity_hold: 'conflict', + proximity_transmit: 'query' +}; + +/** + * Resolve the ecc-tui binary: explicit override, env var, a built target in the + * repo, then the bare name (hope it's on PATH). + */ +function resolveEccBin(deps = {}) { + if (deps.binPath) return deps.binPath; + if (process.env.ECC_TUI_BIN && process.env.ECC_TUI_BIN.trim()) return process.env.ECC_TUI_BIN.trim(); + const repoRoot = deps.repoRoot || path.join(__dirname, '..', '..', '..'); + for (const rel of ['ecc2/target/release/ecc-tui', 'ecc2/target/debug/ecc-tui']) { + const candidate = path.join(repoRoot, rel); + try { + if (fs.existsSync(candidate)) return candidate; + } catch { + /* ignore */ + } + } + return 'ecc-tui'; +} + +/** + * Build the `messages send` argv for a proximity message. + */ +function buildSendArgs({ fromSession, toSession, content, msgType }) { + const kind = KIND_BY_TYPE[msgType] || 'query'; + return ['messages', 'send', '--from', String(fromSession), '--to', String(toSession), '--kind', kind, '--text', String(content)]; +} + +/** + * Create a `sendMessage({ fromSession, toSession, content, msgType })` sink that + * delivers via `ecc-tui messages send`. Inject `runCommand(bin, args)` for tests. + */ +function createEccMessageSink(deps = {}) { + const run = deps.runCommand || ((bin, args) => execFileSync(bin, args, { encoding: 'utf8', timeout: 5000, stdio: ['ignore', 'pipe', 'pipe'] })); + const bin = resolveEccBin(deps); + return function sendMessage(message) { + run(bin, buildSendArgs(message)); + }; +} + +module.exports = { + KIND_BY_TYPE, + resolveEccBin, + buildSendArgs, + createEccMessageSink +}; diff --git a/github_code/affaan-m__ECC/scripts/lib/control-pane/proximity-viz.js b/github_code/affaan-m__ECC/scripts/lib/control-pane/proximity-viz.js new file mode 100644 index 0000000000000000000000000000000000000000..2780e5bcc21474f0d50bcc8eeb6021079a7bfd7d --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/control-pane/proximity-viz.js @@ -0,0 +1,191 @@ +'use strict'; + +/** + * Self-contained 3D "agent airspace" visualization, served by the control pane. + * + * Renders each agent as a point in code-space (positions from the proximity + * embedding), sized by working-set size and colored by collision risk, with + * links between converging pairs (amber = transmit advisory, red = steer). The + * scene auto-rotates so you can read the cloud. Dependency-free: a hand-rolled + * 3D2D projection on a , no external scripts (CSP/offline friendly). + * + * This is the operator/Enterprise view of Layer 4: multi-agent observability: + * literally watch the swarm and watch one agent steer away from a collision. + */ + +function renderProximityVizHtml() { + return ` + + + + +ECC Agent Airspace + + + +
+

ECC - Agent Airspace

+ connecting... +
+
+
+ +
+
clear
+
traffic advisory (transmit)
+
resolution (steer)
+
+
+
+

Advisories

+
No advisories - airspace clear.
+
+
+ + +`; +} + +module.exports = { renderProximityVizHtml }; diff --git a/github_code/affaan-m__ECC/scripts/lib/control-pane/proximity.js b/github_code/affaan-m__ECC/scripts/lib/control-pane/proximity.js new file mode 100644 index 0000000000000000000000000000000000000000..7e451baf0a98fb407eaa7d9029714b3b94fbc957 --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/control-pane/proximity.js @@ -0,0 +1,262 @@ +'use strict'; + +/** + * Control-pane integration for the agent-space proximity metric. + * + * Turns live sessions into agent working sets (the files each session's worktree + * has changed), builds the dependency graph over those files, and runs the + * TCAS-style airspace scan — so the board can surface "two agents are converging" + * advisories and a 3D position per agent. See docs/design/agent-proximity.md. + */ + +const path = require('path'); +const { execFileSync } = require('child_process'); + +const { scanAirspace, buildProximityTriggers } = require('../agent-proximity'); +const { buildDependencyGraph } = require('../agent-proximity/graph'); + +/** + * Parse `git diff --unified=0` output into per-file NEW-side line ranges. Hunk + * headers look like `@@ -a,b +c,d @@`; we keep the +c,d (new) side so the overlap + * channel can tell that two agents touch the *same file* but *different line + * ranges* (different functions) and not flag a false collision. + * + * @param {string} diff + * @returns {Map>} + */ +function parseDiffRanges(diff) { + const byFile = new Map(); + let current = null; + for (const line of String(diff || '').split('\n')) { + const fileMatch = line.match(/^\+\+\+ b\/(.+)$/); + if (fileMatch) { + const name = fileMatch[1].trim(); + current = name === '/dev/null' ? null : name; + if (current && !byFile.has(current)) byFile.set(current, []); + continue; + } + const hunk = line.match(/^@@ -\d+(?:,\d+)? \+(\d+)(?:,(\d+))? @@/); + if (hunk && current) { + const start = parseInt(hunk[1], 10); + const count = hunk[2] === undefined ? 1 : parseInt(hunk[2], 10); + if (count > 0) byFile.get(current).push([start, start + count - 1]); + } + } + return byFile; +} + +function runGitDiff(worktreePath, base, extraArgs) { + return execFileSync('git', ['-C', worktreePath, 'diff', ...extraArgs, `${base}...HEAD`], { + encoding: 'utf8', + timeout: 5000, + maxBuffer: 8 * 1024 * 1024, + stdio: ['ignore', 'pipe', 'ignore'] + }); +} + +/** + * Default working-set source: a session's worktree diff against its base, with + * per-file changed line ranges. Returns [{ path, lines? }], or [] on failure so + * proximity degrades gracefully (never throws into the snapshot path). + */ +function defaultWorkingSetFor(session) { + const wt = session && session.worktree; + if (!wt || !wt.path) return []; + const base = wt.base || 'HEAD'; + try { + const ranges = parseDiffRanges(runGitDiff(wt.path, base, ['--unified=0'])); + return [...ranges.entries()].map(([path, lines]) => (lines.length > 0 ? { path, lines } : { path })); + } catch { + return []; + } +} + +/** + * Back-compat file-name-only source (no line ranges). + */ +function defaultChangedFilesFor(session) { + const wt = session && session.worktree; + if (!wt || !wt.path) return []; + const base = wt.base || 'HEAD'; + try { + return runGitDiff(wt.path, base, ['--name-only']) + .split('\n') + .map(s => s.trim()) + .filter(Boolean); + } catch { + return []; + } +} + +/** + * Map sessions to agent working sets. Only sessions with a worktree and at least + * one changed file participate (an agent with no edits cannot collide). + * Inject `workingSetFor` (returns [{path,lines?}]) or `changedFilesFor` + * (returns file-name strings) for tests. + */ +function sessionsToAgents(sessions, deps = {}) { + const workingSetFor = deps.workingSetFor || (deps.changedFilesFor ? session => deps.changedFilesFor(session).map(p => ({ path: p })) : defaultWorkingSetFor); + const agents = []; + for (const session of sessions || []) { + const files = workingSetFor(session).map(f => ({ weight: 1, ...f })); + if (files.length === 0) continue; + agents.push({ + agentId: session.id, + label: session.task || session.id, + startedAt: session.createdAt || null, + files + }); + } + return agents; +} + +/** + * Compute the proximity snapshot from the control-pane sessions. + * + * @param {Array} sessions normalized control-pane sessions + * @param {object} [options] { repoRoot, changedFilesFor, ...scanOptions } + * @returns {{ enabled, advisories, positions, links, counts }} + */ +function buildProximitySnapshot(sessions, options = {}) { + const repoRoot = path.resolve(options.repoRoot || path.join(__dirname, '..', '..', '..')); + const agents = sessionsToAgents(sessions, options); + + // Need at least two participating agents for a collision to be possible. + if (agents.length < 2) { + return { + enabled: true, + advisories: [], + positions: agents.map(a => ({ agentId: a.agentId, position: [0, 0, 0], fileCount: a.files.length })), + links: [], + counts: { agents: agents.length, advisories: 0, resolutions: 0 } + }; + } + + const touched = [...new Set(agents.flatMap(a => a.files.map(f => f.path)))]; + let graph = { adjacency: {}, files: [] }; + try { + graph = options.graph || buildDependencyGraph(repoRoot, touched, options.graphDeps || {}); + } catch { + graph = { adjacency: {}, files: [] }; + } + + const scan = scanAirspace(agents, graph, options); + const labels = new Map(agents.map(a => [a.agentId, a.label])); + const advisories = scan.advisories.map(adv => ({ + ...adv, + aLabel: labels.get(adv.a) || adv.a, + bLabel: labels.get(adv.b) || adv.b + })); + return { + enabled: true, + advisories, + triggers: buildProximityTriggers(scan.advisories), + positions: scan.positions, + links: scan.links, + counts: scan.counts + }; +} + +/** + * Deliver proximity triggers via an injected message sink. The sink is + * `sendMessage({ fromSession, toSession, content, msgType })` — e.g. a writer + * for the ECC `messages` table the control pane already reads. Best-effort: + * a failing send is skipped, never thrown. Returns the dispatched count. + */ +function dispatchProximityTriggers(triggers, deps = {}) { + const send = deps.sendMessage; + if (typeof send !== 'function') return { dispatched: 0, skipped: (triggers || []).length }; + let dispatched = 0; + let skipped = 0; + for (const t of triggers || []) { + try { + send({ fromSession: t.from, toSession: t.to, content: t.content, msgType: t.type }); + dispatched += 1; + } catch { + skipped += 1; + } + } + return { dispatched, skipped }; +} + +/** + * Stateful dispatcher with per-trigger cooldown, so a collision that persists + * across many ticks fires once and then stays quiet until it clears or the + * cooldown lapses — agents get steered, not spammed. Inject `sendMessage` + * (e.g. createEccMessageSink) and optionally `now`/`cooldownMs` for tests. + */ +function createProximityDispatcher(deps = {}) { + const send = deps.sendMessage; + const cooldownMs = Number.isFinite(deps.cooldownMs) ? deps.cooldownMs : 5 * 60 * 1000; + const now = typeof deps.now === 'function' ? deps.now : () => Date.now(); + const lastFired = new Map(); + const keyOf = t => `${t.to}<-${t.from}:${t.type}`; + + return { + dispatch(triggers) { + let dispatched = 0; + let suppressed = 0; + let skipped = 0; + for (const t of triggers || []) { + const key = keyOf(t); + const last = lastFired.get(key); + const ts = now(); + if (last !== undefined && ts - last < cooldownMs) { + suppressed += 1; + continue; + } + if (typeof send !== 'function') { + skipped += 1; + continue; + } + try { + send({ fromSession: t.from, toSession: t.to, content: t.content, msgType: t.type }); + lastFired.set(key, ts); + dispatched += 1; + } catch { + skipped += 1; + } + } + return { dispatched, suppressed, skipped }; + }, + reset() { + lastFired.clear(); + } + }; +} + +/** + * One proximity tick: build the snapshot, then dispatch its triggers (steer the + * agents). `buildSnapshot()` returns a control-pane snapshot with a `proximity` + * field; `dispatcher` is a createProximityDispatcher. `dryRun` reports what + * would fire without sending. Both are injected so the CLI stays a thin wrapper + * and the logic is unit-testable. + */ +async function runProximityTick(deps = {}) { + const snapshot = await deps.buildSnapshot(); + const prox = (snapshot && snapshot.proximity) || { advisories: [], triggers: [], counts: {} }; + const triggers = prox.triggers || []; + let result; + if (deps.dryRun || !deps.dispatcher) { + result = { dispatched: 0, suppressed: 0, skipped: triggers.length, dryRun: Boolean(deps.dryRun) }; + } else { + result = deps.dispatcher.dispatch(triggers); + } + return { + counts: prox.counts || {}, + advisories: prox.advisories || [], + triggers, + result + }; +} + +module.exports = { + buildProximitySnapshot, + sessionsToAgents, + defaultWorkingSetFor, + defaultChangedFilesFor, + parseDiffRanges, + dispatchProximityTriggers, + createProximityDispatcher, + runProximityTick +}; diff --git a/github_code/affaan-m__ECC/scripts/lib/control-pane/server.js b/github_code/affaan-m__ECC/scripts/lib/control-pane/server.js new file mode 100644 index 0000000000000000000000000000000000000000..bfe84715939adcd347bb143500ebda62ee5fe1aa --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/control-pane/server.js @@ -0,0 +1,371 @@ +'use strict'; + +const fs = require('fs'); +const http = require('http'); +const path = require('path'); +const { spawn } = require('child_process'); + +const { buildControlPaneAction } = require('./actions'); +const { buildControlPaneSnapshot, resolveControlPaneConfig } = require('./state'); +const { renderControlPaneHtml } = require('./ui'); +const { renderProximityVizHtml } = require('./proximity-viz'); +const { claimWorkItem, moveWorkItem } = require('./work-item-mutations'); + +// Run a single write against the local work-item store, then close it. Kept +// thin so the loopback-only server can mutate the JIT board without holding a +// long-lived handle. +async function withStateStore(stateDbPath, fn) { + const { createStateStore } = require('../state-store'); + const store = await createStateStore({ dbPath: stateDbPath }); + try { + return await fn(store); + } finally { + store.close(); + } +} + +// Host/Origin gating lives in scripts/lib/loopback-guard.js so every ECC +// loopback server shares one hardened implementation; re-exported below to +// keep this module's public API stable. +const { + buildAllowedHostnames, + isAllowedHostHeader, + isAllowedOrigin +} = require('../loopback-guard'); + +function usage() { + return [ + 'Usage:', + ' node scripts/control-pane.js [--host 127.0.0.1] [--port 8765] [--db ] [--state-db ] [--config ] [--query ]', + '', + 'Options:', + ' --state-db Read agent work items from an ECC state-store database', + ' --read-only Disable action execution endpoints', + ' --no-open Do not open a browser after the server starts', + ' --help Show this help' + ].join('\n'); +} + +function valueAfter(args, name) { + const index = args.indexOf(name); + return index >= 0 ? args[index + 1] : null; +} + +function pathValueAfter(args, name) { + const value = valueAfter(args, name); + if (value === null) return null; + if (!value || value.startsWith('-')) { + throw new Error(`Invalid ${name} value: expected a path`); + } + return value; +} + +function parseArgs(argv) { + const args = argv.slice(2); + const help = args.includes('--help') || args.includes('-h'); + const host = valueAfter(args, '--host') || '127.0.0.1'; + const portValue = valueAfter(args, '--port') || '8765'; + const port = Number.parseInt(portValue, 10); + if (!Number.isFinite(port) || port < 0 || port > 65535) { + throw new Error(`Invalid --port value: ${portValue}`); + } + + return { + help, + host, + port, + dbPath: valueAfter(args, '--db'), + stateDbPath: pathValueAfter(args, '--state-db'), + configPath: valueAfter(args, '--config'), + query: valueAfter(args, '--query') || '', + openBrowser: !args.includes('--no-open'), + allowActions: !args.includes('--read-only') + }; +} + +function sendJson(res, statusCode, payload) { + const body = JSON.stringify(payload, null, 2); + res.writeHead(statusCode, { + 'content-type': 'application/json; charset=utf-8', + 'cache-control': 'no-store' + }); + res.end(`${body}\n`); +} + +function sendText(res, statusCode, body, contentType = 'text/plain; charset=utf-8') { + res.writeHead(statusCode, { + 'content-type': contentType, + 'cache-control': 'no-store' + }); + res.end(body); +} + +async function readRequestJson(req) { + const chunks = []; + for await (const chunk of req) chunks.push(chunk); + if (chunks.length === 0) return {}; + const raw = Buffer.concat(chunks).toString('utf8').trim(); + if (!raw) return {}; + return JSON.parse(raw); +} + +function boundedOutput(value, limit = 20000) { + const text = String(value || ''); + if (text.length <= limit) return text; + return `${text.slice(0, limit)}\n[truncated ${text.length - limit} chars]`; +} + +function runAction(action, options = {}) { + const timeoutMs = options.timeoutMs || 120000; + return new Promise(resolve => { + const startedAt = new Date().toISOString(); + const child = spawn(action.command, action.args, { + cwd: action.cwd, + env: process.env, + stdio: ['ignore', 'pipe', 'pipe'] + }); + let stdout = ''; + let stderr = ''; + let settled = false; + const timeout = setTimeout(() => { + if (!settled) { + child.kill('SIGTERM'); + } + }, timeoutMs); + + child.stdout.on('data', chunk => { + stdout += chunk.toString('utf8'); + }); + child.stderr.on('data', chunk => { + stderr += chunk.toString('utf8'); + }); + child.on('error', error => { + settled = true; + clearTimeout(timeout); + resolve({ + ok: false, + action: action.id, + startedAt, + finishedAt: new Date().toISOString(), + code: null, + error: error.message, + stdout: boundedOutput(stdout), + stderr: boundedOutput(stderr) + }); + }); + child.on('close', (code, signal) => { + settled = true; + clearTimeout(timeout); + resolve({ + ok: code === 0, + action: action.id, + startedAt, + finishedAt: new Date().toISOString(), + code, + signal, + stdout: boundedOutput(stdout), + stderr: boundedOutput(stderr) + }); + }); + }); +} + +function createControlPaneServer(options = {}) { + const repoRoot = path.resolve(options.repoRoot || path.join(__dirname, '..', '..', '..')); + const host = options.host || '127.0.0.1'; + const port = options.port === null || options.port === undefined ? 8765 : options.port; + const allowActions = options.allowActions !== false; + const resolvedConfig = resolveControlPaneConfig({ + cwd: options.cwd || repoRoot, + configPath: options.configPath, + dbPath: options.dbPath, + stateDbPath: options.stateDbPath, + env: options.env || process.env + }); + const baseQuery = options.query || ''; + const allowedHostnames = buildAllowedHostnames(host); + + const server = http.createServer(async (req, res) => { + try { + if (!isAllowedHostHeader(req.headers.host, allowedHostnames)) { + sendJson(res, 421, { ok: false, error: 'Misdirected request' }); + return; + } + if (!isAllowedOrigin(req.headers.origin, allowedHostnames)) { + sendJson(res, 403, { ok: false, error: 'Forbidden origin' }); + return; + } + + const requestUrl = new URL(req.url, `http://${host}:${port || 0}`); + + if (req.method === 'GET' && requestUrl.pathname === '/') { + sendText(res, 200, renderControlPaneHtml(), 'text/html; charset=utf-8'); + return; + } + + if (req.method === 'GET' && requestUrl.pathname === '/assets/ecc-icon.svg') { + const iconPath = path.join(repoRoot, 'assets', 'ecc-icon.svg'); + if (!fs.existsSync(iconPath)) { + sendText(res, 404, 'not found'); + return; + } + sendText(res, 200, fs.readFileSync(iconPath, 'utf8'), 'image/svg+xml; charset=utf-8'); + return; + } + + if (req.method === 'GET' && requestUrl.pathname === '/api/health') { + sendJson(res, 200, { + ok: true, + repoRoot, + dbPath: resolvedConfig.dbPath, + stateDbPath: resolvedConfig.stateDbPath, + allowActions + }); + return; + } + + if (req.method === 'GET' && requestUrl.pathname === '/api/snapshot') { + const snapshot = await buildControlPaneSnapshot({ + repoRoot, + dbPath: resolvedConfig.dbPath, + stateDbPath: resolvedConfig.stateDbPath, + config: resolvedConfig, + query: requestUrl.searchParams.get('query') || baseQuery, + limit: requestUrl.searchParams.get('limit') || 12, + allowActions + }); + sendJson(res, 200, snapshot); + return; + } + + // 3D agent-airspace visualization (Layer 4 observability). + if (req.method === 'GET' && requestUrl.pathname === '/proximity') { + sendText(res, 200, renderProximityVizHtml(), 'text/html; charset=utf-8'); + return; + } + + if (req.method === 'GET' && requestUrl.pathname === '/api/proximity') { + const snapshot = await buildControlPaneSnapshot({ + repoRoot, + dbPath: resolvedConfig.dbPath, + stateDbPath: resolvedConfig.stateDbPath, + config: resolvedConfig, + allowActions, + includeProximity: true + }); + sendJson(res, 200, snapshot.proximity || { enabled: true, advisories: [], positions: [], links: [], counts: {} }); + return; + } + + const actionMatch = requestUrl.pathname.match(/^\/api\/actions\/([^/]+)$/); + if (req.method === 'POST' && actionMatch) { + if (!allowActions) { + sendJson(res, 403, { + ok: false, + error: 'Control-pane action execution is disabled by --read-only.' + }); + return; + } + + const body = await readRequestJson(req); + const action = buildControlPaneAction(decodeURIComponent(actionMatch[1]), { + repoRoot, + query: body.query || baseQuery, + limit: body.limit || 25 + }); + + if (!action.executable) { + sendJson(res, 400, { + ok: false, + action: action.id, + error: 'This action is copy-only and cannot be executed from the browser.', + commandLine: action.commandLine + }); + return; + } + + const result = await runAction(action); + sendJson(res, result.ok ? 200 : 500, { + ...result, + commandLine: action.commandLine + }); + return; + } + + // Interactive JIT board: claim / move a work item from the browser. + const claimMatch = requestUrl.pathname.match(/^\/api\/work-items\/([^/]+)\/claim$/); + const moveMatch = requestUrl.pathname.match(/^\/api\/work-items\/([^/]+)\/move$/); + if (req.method === 'POST' && (claimMatch || moveMatch)) { + if (!allowActions) { + sendJson(res, 403, { + ok: false, + error: 'Board edits are disabled by --read-only.' + }); + return; + } + const id = decodeURIComponent((claimMatch || moveMatch)[1]); + const body = await readRequestJson(req); + try { + const result = await withStateStore(resolvedConfig.stateDbPath, store => + claimMatch + ? claimWorkItem(store, { + id, + owner: body.owner, + assigneeKind: body.as || body.assigneeKind, + sessionId: body.sessionId + }) + : moveWorkItem(store, { id, lane: body.lane }) + ); + sendJson(res, 200, { ok: true, ...result }); + } catch (mutationError) { + sendJson(res, 400, { ok: false, error: mutationError.message }); + } + return; + } + + sendJson(res, 404, { ok: false, error: 'not found' }); + } catch (error) { + sendJson(res, 500, { + ok: false, + error: error.message + }); + } + }); + + return { + get url() { + const address = server.address(); + const actualPort = address && typeof address === 'object' ? address.port : port; + return `http://${host}:${actualPort}`; + }, + server, + config: resolvedConfig, + listen() { + return new Promise((resolve, reject) => { + server.once('error', reject); + server.listen(port, host, () => { + server.off('error', reject); + resolve(this); + }); + }); + }, + close() { + return new Promise((resolve, reject) => { + server.close(error => { + if (error) reject(error); + else resolve(); + }); + }); + } + }; +} + +module.exports = { + createControlPaneServer, + parseArgs, + runAction, + isAllowedHostHeader, + isAllowedOrigin, + buildAllowedHostnames, + usage +}; diff --git a/github_code/affaan-m__ECC/scripts/lib/control-pane/state.js b/github_code/affaan-m__ECC/scripts/lib/control-pane/state.js new file mode 100644 index 0000000000000000000000000000000000000000..9827443c5031f6ecd4bccfe16eb7f811f4fe1b5e --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/control-pane/state.js @@ -0,0 +1,680 @@ +'use strict'; + +const fs = require('fs'); +const os = require('os'); +const path = require('path'); + +const { buildControlPaneActions } = require('./actions'); + +const SNAPSHOT_SCHEMA_VERSION = 'ecc.control-pane.snapshot.v1'; +const DEFAULT_STATE_STORE_RELATIVE_PATH = path.join('.claude', 'ecc', 'state.db'); + +function homeDir(env = process.env) { + return env.HOME || env.USERPROFILE || os.homedir() || '.'; +} + +function defaultDbPath(env = process.env) { + return path.join(homeDir(env), '.claude', 'ecc2.db'); +} + +function defaultStateDbPath(env = process.env) { + return path.join(homeDir(env), DEFAULT_STATE_STORE_RELATIVE_PATH); +} + +function defaultConfigPaths(cwd = process.cwd(), env = process.env) { + const home = homeDir(env); + const paths = [path.join(home, 'Library', 'Application Support', 'ecc2', 'config.toml'), path.join(home, '.config', 'ecc2', 'config.toml'), path.join(home, '.claude', 'ecc2.toml')]; + + let current = path.resolve(cwd); + while (current && current !== path.dirname(current)) { + paths.push(path.join(current, '.claude', 'ecc2.toml')); + paths.push(path.join(current, 'ecc2.toml')); + current = path.dirname(current); + } + + return Array.from(new Set(paths)); +} + +function isPlainObject(value) { + return Boolean(value) && typeof value === 'object' && !Array.isArray(value); +} + +function deepMerge(base, override) { + const merged = { ...base }; + for (const [key, value] of Object.entries(override || {})) { + if (isPlainObject(value) && isPlainObject(merged[key])) { + merged[key] = deepMerge(merged[key], value); + } else { + merged[key] = value; + } + } + return merged; +} + +function toCamelCase(value) { + return String(value).replace(/_([a-z])/g, (_, char) => char.toUpperCase()); +} + +function normalizeObjectKeys(value) { + if (Array.isArray(value)) return value.map(normalizeObjectKeys); + if (!isPlainObject(value)) return value; + + return Object.fromEntries(Object.entries(value).map(([key, item]) => [toCamelCase(key), normalizeObjectKeys(item)])); +} + +function normalizeMemoryConnectors(connectors = {}) { + return Object.fromEntries( + Object.entries(connectors || {}) + .sort(([left], [right]) => left.localeCompare(right)) + .map(([name, connector]) => [name, normalizeObjectKeys(connector)]) + ); +} + +function normalizeConfig(rawConfig = {}, options = {}) { + const { memory_connectors: snakeMemoryConnectors, memoryConnectors, state_db_path: snakeStateDbPath, stateDbPath: camelStateDbPath, ...rest } = rawConfig; + const normalized = normalizeObjectKeys(rest); + const connectorConfig = memoryConnectors || snakeMemoryConnectors || normalized.memoryConnectors; + return { + dbPath: options.dbPath || normalized.dbPath || defaultDbPath(options.env), + stateDbPath: options.stateDbPath || camelStateDbPath || snakeStateDbPath || normalized.stateDbPath || defaultStateDbPath(options.env), + memoryConnectors: normalizeMemoryConnectors(connectorConfig) + }; +} + +function readTomlConfig(configPath) { + // @iarna/toml is required lazily so commands that never resolve a config + // file (e.g. `--help`, or a first run before any ecc2.toml exists) don't + // need it on the require path. + const toml = require('@iarna/toml'); + const raw = fs.readFileSync(configPath, 'utf8'); + return toml.parse(raw); +} + +function resolveControlPaneConfig(options = {}) { + const env = options.env || process.env; + const cwd = options.cwd || process.cwd(); + const configPaths = options.configPath ? [path.resolve(options.configPath)] : defaultConfigPaths(cwd, env); + let merged = {}; + + for (const configPath of configPaths) { + if (fs.existsSync(configPath)) { + merged = deepMerge(merged, readTomlConfig(configPath)); + } + } + + return { + ...normalizeConfig(merged, { + env, + dbPath: options.dbPath || env.ECC2_DB_PATH || null, + stateDbPath: options.stateDbPath || env.ECC_STATE_DB_PATH || null + }), + configPaths: configPaths.filter(configPath => fs.existsSync(configPath)) + }; +} + +async function openSqlDatabase(dbPath) { + if (!dbPath || !fs.existsSync(dbPath)) return null; + // sql.js is required lazily so commands that never open an existing + // ecc2.db (e.g. `--help`, or a first run before any db exists) don't need + // it on the require path. + const initSqlJs = require('sql.js'); + const SQL = await initSqlJs(); + const buffer = fs.readFileSync(dbPath); + return new SQL.Database(buffer); +} + +function execRows(db, sql, params = []) { + const stmt = db.prepare(sql); + try { + stmt.bind(params); + const rows = []; + while (stmt.step()) rows.push(stmt.getAsObject()); + return rows; + } finally { + stmt.free(); + } +} + +function tableExists(db, tableName) { + const rows = execRows(db, "SELECT name FROM sqlite_master WHERE type = 'table' AND name = ? LIMIT 1", [tableName]); + return rows.length > 0; +} + +function parseJson(value, fallback) { + if (typeof value !== 'string' || value.trim() === '') return fallback; + try { + return JSON.parse(value); + } catch { + return fallback; + } +} + +function toNumber(value, fallback = 0) { + const parsed = Number(value); + return Number.isFinite(parsed) ? parsed : fallback; +} + +function normalizeSession(row, unreadMessages) { + const id = String(row.id || ''); + return { + id, + task: String(row.task || ''), + project: String(row.project || ''), + taskGroup: String(row.task_group || ''), + agentType: String(row.agent_type || ''), + harness: String(row.harness || 'unknown'), + detectedHarnesses: parseJson(row.detected_harnesses_json, []), + workingDir: String(row.working_dir || '.'), + state: String(row.state || 'pending'), + pid: row.pid === null || row.pid === undefined ? null : toNumber(row.pid), + worktree: row.worktree_path + ? { + path: String(row.worktree_path), + branch: row.worktree_branch ? String(row.worktree_branch) : null, + base: row.worktree_base ? String(row.worktree_base) : null + } + : null, + metrics: { + inputTokens: toNumber(row.input_tokens), + outputTokens: toNumber(row.output_tokens), + tokensUsed: toNumber(row.tokens_used), + toolCalls: toNumber(row.tool_calls), + filesChanged: toNumber(row.files_changed), + durationSecs: toNumber(row.duration_secs), + costUsd: toNumber(row.cost_usd) + }, + unreadMessages: unreadMessages.get(id) || 0, + createdAt: String(row.created_at || ''), + updatedAt: String(row.updated_at || ''), + lastHeartbeatAt: String(row.last_heartbeat_at || '') + }; +} + +function readUnreadMessageCounts(db) { + if (!tableExists(db, 'messages')) return new Map(); + return new Map(execRows(db, 'SELECT to_session, COUNT(*) AS unread_count FROM messages WHERE read = 0 GROUP BY to_session').map(row => [String(row.to_session), toNumber(row.unread_count)])); +} + +function readSessions(db) { + if (!tableExists(db, 'sessions')) return []; + const unreadMessages = readUnreadMessageCounts(db); + return execRows( + db, + `SELECT * + FROM sessions + ORDER BY updated_at DESC, created_at DESC, id ASC + LIMIT 100` + ).map(row => normalizeSession(row, unreadMessages)); +} + +function summarizeSessions(sessions) { + const summary = { + totalSessions: sessions.length, + runningSessions: 0, + pendingSessions: 0, + idleSessions: 0, + failedSessions: 0, + stoppedSessions: 0, + completedSessions: 0, + unreadMessages: 0, + activeWorktrees: 0, + totalTokens: 0, + totalCostUsd: 0 + }; + + for (const session of sessions) { + if (session.state === 'running') summary.runningSessions += 1; + if (session.state === 'pending') summary.pendingSessions += 1; + if (session.state === 'idle') summary.idleSessions += 1; + if (session.state === 'failed') summary.failedSessions += 1; + if (session.state === 'stopped') summary.stoppedSessions += 1; + if (session.state === 'completed') summary.completedSessions += 1; + if (session.worktree) summary.activeWorktrees += 1; + summary.unreadMessages += session.unreadMessages; + summary.totalTokens += session.metrics.tokensUsed; + summary.totalCostUsd += session.metrics.costUsd; + } + + summary.totalCostUsd = Number(summary.totalCostUsd.toFixed(6)); + return summary; +} + +function readEntities(db) { + if (!tableExists(db, 'context_graph_entities')) return []; + return execRows( + db, + `SELECT * + FROM context_graph_entities + ORDER BY updated_at DESC, id DESC + LIMIT 500` + ).map(row => ({ + id: toNumber(row.id), + sessionId: row.session_id ? String(row.session_id) : null, + entityType: String(row.entity_type || ''), + name: String(row.name || ''), + path: row.path ? String(row.path) : null, + summary: String(row.summary || ''), + metadata: parseJson(row.metadata_json, {}), + createdAt: String(row.created_at || ''), + updatedAt: String(row.updated_at || '') + })); +} + +function readObservations(db) { + if (!tableExists(db, 'context_graph_observations')) return []; + return execRows( + db, + `SELECT * + FROM context_graph_observations + ORDER BY created_at DESC, id DESC + LIMIT 1000` + ).map(row => ({ + id: toNumber(row.id), + sessionId: row.session_id ? String(row.session_id) : null, + entityId: toNumber(row.entity_id), + observationType: String(row.observation_type || ''), + priority: toNumber(row.priority, 1), + pinned: toNumber(row.pinned) === 1, + summary: String(row.summary || ''), + details: parseJson(row.details_json, {}), + createdAt: String(row.created_at || '') + })); +} + +function readRelationCounts(db) { + if (!tableExists(db, 'context_graph_relations')) return new Map(); + const rows = execRows( + db, + `SELECT entity_id, SUM(relation_count) AS relation_count + FROM ( + SELECT from_entity_id AS entity_id, COUNT(*) AS relation_count + FROM context_graph_relations + GROUP BY from_entity_id + UNION ALL + SELECT to_entity_id AS entity_id, COUNT(*) AS relation_count + FROM context_graph_relations + GROUP BY to_entity_id + ) + GROUP BY entity_id` + ); + return new Map(rows.map(row => [toNumber(row.entity_id), toNumber(row.relation_count)])); +} + +function tokenize(value) { + return String(value || '') + .toLowerCase() + .split(/[^a-z0-9_.-]+/g) + .map(token => token.trim()) + .filter(token => token.length >= 2); +} + +function scoreEntity(entity, observations, relationCount, queryTerms) { + const observationText = observations.map(observation => observation.summary).join(' '); + const metadataText = Object.entries(entity.metadata || {}) + .map(([key, value]) => `${key} ${value}`) + .join(' '); + const haystacks = [ + { text: entity.name, weight: 12 }, + { text: entity.entityType, weight: 5 }, + { text: entity.path || '', weight: 6 }, + { text: entity.summary, weight: 8 }, + { text: metadataText, weight: 5 }, + { text: observationText, weight: 10 } + ].map(item => ({ ...item, text: item.text.toLowerCase() })); + const matchedTerms = []; + let score = 0; + + for (const term of queryTerms) { + let matched = false; + for (const haystack of haystacks) { + if (haystack.text.includes(term)) { + score += haystack.weight; + matched = true; + } + } + if (matched) matchedTerms.push(term); + } + + const maxPriority = observations.reduce((highest, observation) => Math.max(highest, observation.priority), 0); + const hasPinnedObservation = observations.some(observation => observation.pinned); + score += Math.min(relationCount, 8); + score += maxPriority * 3; + if (hasPinnedObservation) score += 8; + + return { + score, + matchedTerms, + observationCount: observations.length, + relationCount, + maxObservationPriority: maxPriority, + hasPinnedObservation + }; +} + +function recallKnowledgeEntries({ entities, observations, relationCounts, query, limit = 12 }) { + const queryTerms = Array.from(new Set(tokenize(query))); + const observationsByEntity = new Map(); + for (const observation of observations) { + const bucket = observationsByEntity.get(observation.entityId) || []; + bucket.push(observation); + observationsByEntity.set(observation.entityId, bucket); + } + + return entities + .map(entity => { + const entityObservations = observationsByEntity.get(entity.id) || []; + const score = + queryTerms.length > 0 + ? scoreEntity(entity, entityObservations, relationCounts.get(entity.id) || 0, queryTerms) + : { + score: entityObservations.some(observation => observation.pinned) ? 10 : 1, + matchedTerms: [], + observationCount: entityObservations.length, + relationCount: relationCounts.get(entity.id) || 0, + maxObservationPriority: entityObservations.reduce((highest, observation) => Math.max(highest, observation.priority), 0), + hasPinnedObservation: entityObservations.some(observation => observation.pinned) + }; + return { + entity, + ...score, + latestObservation: entityObservations[0] || null + }; + }) + .filter(entry => queryTerms.length === 0 || entry.matchedTerms.length > 0) + .sort((left, right) => { + if (right.score !== left.score) return right.score - left.score; + return String(right.entity.updatedAt).localeCompare(String(left.entity.updatedAt)); + }) + .slice(0, Math.max(1, Math.min(Number(limit) || 12, 50))); +} + +function readConnectorCheckpointRows(db) { + if (!tableExists(db, 'context_graph_connector_checkpoints')) return []; + return execRows( + db, + `SELECT connector_name, COUNT(*) AS synced_sources, MAX(updated_at) AS last_synced_at + FROM context_graph_connector_checkpoints + GROUP BY connector_name` + ); +} + +function connectorStatus(config, db) { + const checkpoints = new Map( + (db ? readConnectorCheckpointRows(db) : []).map(row => [ + String(row.connector_name), + { + syncedSources: toNumber(row.synced_sources), + lastSyncedAt: row.last_synced_at ? String(row.last_synced_at) : null + } + ]) + ); + + return Object.entries(config.memoryConnectors || {}) + .sort(([left], [right]) => left.localeCompare(right)) + .map(([name, connector]) => { + const checkpoint = checkpoints.get(name) || { syncedSources: 0, lastSyncedAt: null }; + return { + name, + kind: connector.kind || 'unknown', + path: connector.path || null, + recurse: Boolean(connector.recurse), + defaultEntityType: connector.defaultEntityType || null, + defaultObservationType: connector.defaultObservationType || null, + includeSafeValues: Boolean(connector.includeSafeValues), + syncedSources: checkpoint.syncedSources, + lastSyncedAt: checkpoint.lastSyncedAt + }; + }); +} + +function normalizeWorkItemStatus(status) { + const normalized = String(status || 'open') + .trim() + .toLowerCase(); + if (['done', 'closed', 'resolved', 'merged', 'cancelled'].includes(normalized)) return 'done'; + if (['blocked', 'needs-review', 'failed', 'stalled'].includes(normalized)) return 'blocked'; + if (['running', 'in-progress', 'active', 'working'].includes(normalized)) return 'running'; + return 'ready'; +} + +// Heuristics for whether a work item's owner is an autonomous agent or a human. +// Agent signals win when present so the board reflects who is *actively* on a card. +const AGENT_OWNER_RE = /(agent|claude|codex|hermes|gemini|opencode|qwen|joycode|codebuddy|\bbot\b|gpt|sonnet|opus|haiku|fable)/i; +const SESSION_ID_RE = /^(sid-|tx-|proj-|sess|session|run-|wt-)/i; + +/** + * Classify the assignment of a work item for agent+human JIT team workflows. + * Returns the assignee kind ('agent' | 'human' | 'unassigned') and the resolved + * assignee label, so the board can show who owns each card and which cards are + * waiting for a just-in-time pickup. + */ +function classifyAssignee({ owner, sessionId, metadata = {} }) { + const explicitKind = String(metadata.assigneeKind || metadata.ownerKind || '') + .trim() + .toLowerCase(); + if (explicitKind === 'agent' || explicitKind === 'human') { + return { assigneeKind: explicitKind, assignee: owner || sessionId || metadata.assignee || null }; + } + const ownerStr = owner ? String(owner) : ''; + if (sessionId || (ownerStr && (AGENT_OWNER_RE.test(ownerStr) || SESSION_ID_RE.test(ownerStr)))) { + return { assigneeKind: 'agent', assignee: ownerStr || String(sessionId) }; + } + if (ownerStr) { + return { assigneeKind: 'human', assignee: ownerStr }; + } + return { assigneeKind: 'unassigned', assignee: null }; +} + +function normalizeWorkItem(row) { + const parsedMetadata = parseJson(row.metadata, {}); + const metadata = isPlainObject(parsedMetadata) ? normalizeObjectKeys(parsedMetadata) : {}; + const kanbanState = normalizeWorkItemStatus(row.status); + const owner = row.owner ? String(row.owner) : null; + const sessionId = row.session_id ? String(row.session_id) : null; + const { assigneeKind, assignee } = classifyAssignee({ owner, sessionId, metadata }); + return { + id: String(row.id || ''), + source: String(row.source || ''), + sourceId: row.source_id ? String(row.source_id) : null, + title: String(row.title || ''), + status: String(row.status || 'open'), + kanbanState, + priority: row.priority ? String(row.priority) : null, + url: row.url ? String(row.url) : null, + owner, + assigneeKind, + assignee, + repoRoot: row.repo_root ? String(row.repo_root) : null, + sessionId, + branch: metadata.branch || metadata.headRefName || null, + mergeGate: metadata.mergeGate || metadata.mergeGateStatus || metadata.mergeStateStatus || null, + blocker: metadata.blocker || null, + acceptance: Array.isArray(metadata.acceptance) ? metadata.acceptance.map(String) : [], + metadata, + createdAt: String(row.created_at || ''), + updatedAt: String(row.updated_at || '') + }; +} + +function readWorkItems(db) { + if (!tableExists(db, 'work_items')) return []; + return execRows( + db, + `SELECT * + FROM work_items + ORDER BY updated_at DESC, id DESC + LIMIT 100` + ).map(normalizeWorkItem); +} + +function summarizeWorkItems(items) { + const summary = { + totalCount: items.length, + openCount: 0, + blockedCount: 0, + doneCount: 0, + kanban: { + ready: 0, + running: 0, + blocked: 0, + done: 0 + }, + // Agent + human JIT team-workflow view: who owns the open work, and which + // open cards are waiting for a just-in-time pickup. + assignment: { + agent: 0, + human: 0, + unassigned: 0 + }, + needsAssignment: [], + items + }; + + for (const item of items) { + const kanbanState = normalizeWorkItemStatus(item.kanbanState || item.status); + summary.kanban[kanbanState] += 1; + const isOpen = kanbanState !== 'done'; + if (kanbanState === 'done') { + summary.doneCount += 1; + } else { + summary.openCount += 1; + } + if (kanbanState === 'blocked') summary.blockedCount += 1; + + // Assignment is only meaningful for open work; done cards don't need an owner. + if (isOpen) { + const kind = item.assigneeKind || classifyAssignee(item).assigneeKind; + summary.assignment[kind] = (summary.assignment[kind] || 0) + 1; + if (kind === 'unassigned') { + summary.needsAssignment.push({ + id: item.id, + title: item.title, + kanbanState, + priority: item.priority || null, + url: item.url || null + }); + } + } + } + + // Surface the highest-priority unclaimed work first for JIT pickup. + const priorityRank = { critical: 0, high: 1, urgent: 1, medium: 2, normal: 2, low: 3 }; + summary.needsAssignment.sort((a, b) => { + const ra = priorityRank[String(a.priority || '').toLowerCase()] ?? 2; + const rb = priorityRank[String(b.priority || '').toLowerCase()] ?? 2; + return ra - rb; + }); + + return summary; +} + +async function readWorkItemsSnapshot(stateDbPath) { + let db = null; + try { + db = await openSqlDatabase(stateDbPath); + if (!db) return summarizeWorkItems([]); + return summarizeWorkItems(readWorkItems(db)); + } catch { + return summarizeWorkItems([]); + } finally { + if (db) db.close(); + } +} + +async function buildControlPaneSnapshot(options = {}) { + const repoRoot = path.resolve(options.repoRoot || path.join(__dirname, '..', '..', '..')); + const config = options.config + ? normalizeConfig(options.config, { + env: options.env || process.env, + dbPath: options.dbPath || options.config.dbPath || null, + stateDbPath: options.stateDbPath || options.config.stateDbPath || null + }) + : resolveControlPaneConfig(options); + const dbPath = options.dbPath || config.dbPath; + const stateDbPath = options.stateDbPath || config.stateDbPath; + const query = String(options.query || '').trim(); + const limit = Math.max(1, Math.min(Number.parseInt(String(options.limit || 12), 10) || 12, 50)); + const generatedAt = new Date().toISOString(); + const workItems = await readWorkItemsSnapshot(stateDbPath); + const base = { + schemaVersion: SNAPSHOT_SCHEMA_VERSION, + generatedAt, + repoRoot, + dbPath, + stateDbPath, + database: { + exists: Boolean(dbPath && fs.existsSync(dbPath)) + }, + stateDatabase: { + exists: Boolean(stateDbPath && fs.existsSync(stateDbPath)) + }, + config: { + configPaths: config.configPaths || [], + memoryConnectorCount: Object.keys(config.memoryConnectors || {}).length + }, + execution: { + allowActions: options.allowActions !== false + }, + summary: summarizeSessions([]), + sessions: [], + knowledge: { + query, + entityCount: 0, + observationCount: 0, + results: [] + }, + connectors: connectorStatus(config, null), + workItems, + actions: buildControlPaneActions({ repoRoot, query, limit }) + }; + + const db = await openSqlDatabase(dbPath); + if (!db) { + return base; + } + + try { + const sessions = readSessions(db); + const entities = readEntities(db); + const observations = readObservations(db); + const relationCounts = readRelationCounts(db); + // Proximity (agent-space collision avoidance) is opt-in: it shells `git diff` + // per worktree, so we only compute it when explicitly requested to keep the + // default snapshot fast. + let proximity = null; + if (options.includeProximity) { + const { buildProximitySnapshot } = require('./proximity'); + proximity = buildProximitySnapshot(sessions, { repoRoot, ...(options.proximityOptions || {}) }); + } + return { + ...base, + summary: summarizeSessions(sessions), + sessions, + knowledge: { + query, + entityCount: entities.length, + observationCount: observations.length, + results: recallKnowledgeEntries({ + entities, + observations, + relationCounts, + query, + limit + }) + }, + connectors: connectorStatus(config, db), + proximity + }; + } finally { + db.close(); + } +} + +module.exports = { + SNAPSHOT_SCHEMA_VERSION, + buildControlPaneSnapshot, + defaultConfigPaths, + defaultStateDbPath, + recallKnowledgeEntries, + resolveControlPaneConfig +}; diff --git a/github_code/affaan-m__ECC/scripts/lib/control-pane/ui.js b/github_code/affaan-m__ECC/scripts/lib/control-pane/ui.js new file mode 100644 index 0000000000000000000000000000000000000000..f7b0e069dac93565a16dce65810ef51fdf6881c6 --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/control-pane/ui.js @@ -0,0 +1,696 @@ +'use strict'; + +function renderControlPaneHtml() { + return ` + + + + + ECC Control Pane + + + +
+
+
+ +

ECC Control Pane

+
+
+ + + +
+
+
+
+
+
+
+

Sessions

+ +
+
+
+
+
+

Work Items

+ +
+
+
+
+
+
+
+

Knowledge

+ +
+
+
+
+
+

Connectors

+ +
+
+
+
+
+

Actions

+ local allowlist +
+
+
+ No action output yet. +
+
+
+
+
+ + + +`; +} + +module.exports = { + renderControlPaneHtml +}; diff --git a/github_code/affaan-m__ECC/scripts/lib/control-pane/work-item-mutations.js b/github_code/affaan-m__ECC/scripts/lib/control-pane/work-item-mutations.js new file mode 100644 index 0000000000000000000000000000000000000000..c82a26196432b1cc0a95aee023354fe285c9bbdd --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/control-pane/work-item-mutations.js @@ -0,0 +1,121 @@ +'use strict'; + +/** + * Shared work-item mutation helpers for the agent+human JIT board. + * + * Used by both the `work-items.js` CLI (`claim`) and the control-pane local + * server (interactive claim / move), so the two surfaces never diverge. + */ + +const DONE_STATUSES = new Set(['done', 'closed', 'resolved', 'merged', 'cancelled']); +const PRIORITY_RANK = { critical: 0, high: 1, urgent: 1, medium: 2, normal: 2, low: 3 }; + +// Kanban lanes the board renders, and the canonical status each maps to on a move. +const LANE_TO_STATUS = { + ready: 'open', + running: 'running', + blocked: 'blocked', + done: 'done' +}; +const VALID_LANES = new Set(Object.keys(LANE_TO_STATUS)); +const VALID_ASSIGNEE_KINDS = new Set(['agent', 'human']); + +function isOpenStatus(status) { + return !DONE_STATUSES.has( + String(status || '') + .trim() + .toLowerCase() + ); +} + +function priorityRank(priority) { + return PRIORITY_RANK[String(priority || '').toLowerCase()] ?? 2; +} + +/** + * Resolve which work item a claim targets: an explicit id, otherwise the + * highest-priority unassigned open item (the JIT pickup queue). + */ +function selectClaimTarget(store, { id } = {}) { + if (id) { + const item = store.getWorkItemById(id); + if (!item) { + throw new Error(`Work item not found: ${id}`); + } + return item; + } + const { items } = store.listWorkItems({ limit: 100 }); + return items.filter(item => !item.owner && isOpenStatus(item.status)).sort((a, b) => priorityRank(a.priority) - priorityRank(b.priority))[0] || null; +} + +/** + * Claim an unassigned work item for an agent or human. Sets the owner (and + * optional assigneeKind) and moves the card to running unless an explicit + * status is supplied. Returns { claimed, item } or { claimed: false, reason }. + */ +function claimWorkItem(store, { id, owner, assigneeKind, sessionId, status } = {}) { + if (!owner) { + throw new Error('claim requires an owner.'); + } + const kind = assigneeKind ? String(assigneeKind).toLowerCase() : null; + if (kind && !VALID_ASSIGNEE_KINDS.has(kind)) { + throw new Error("assigneeKind must be 'agent' or 'human'."); + } + const target = selectClaimTarget(store, { id }); + if (!target) { + return { claimed: false, reason: 'no-unassigned-open-items' }; + } + if (!isOpenStatus(target.status)) { + throw new Error(`Work item ${target.id} is already done; cannot claim.`); + } + const metadata = { ...(target.metadata || {}) }; + if (kind) { + metadata.assigneeKind = kind; + } + const item = store.upsertWorkItem({ + ...target, + owner, + sessionId: sessionId ?? target.sessionId ?? null, + status: status ?? 'running', + metadata, + updatedAt: new Date().toISOString() + }); + return { claimed: true, item }; +} + +/** + * Move a work item to a kanban lane (ready | running | blocked | done). + */ +function moveWorkItem(store, { id, lane } = {}) { + if (!id) { + throw new Error('move requires a work item id.'); + } + const laneKey = String(lane || '') + .trim() + .toLowerCase(); + if (!VALID_LANES.has(laneKey)) { + throw new Error(`Invalid lane '${lane}'. Expected one of ${[...VALID_LANES].join(', ')}.`); + } + const target = store.getWorkItemById(id); + if (!target) { + throw new Error(`Work item not found: ${id}`); + } + const item = store.upsertWorkItem({ + ...target, + status: LANE_TO_STATUS[laneKey], + updatedAt: new Date().toISOString() + }); + return { moved: true, item }; +} + +module.exports = { + DONE_STATUSES, + LANE_TO_STATUS, + VALID_LANES, + VALID_ASSIGNEE_KINDS, + isOpenStatus, + priorityRank, + selectClaimTarget, + claimWorkItem, + moveWorkItem +}; diff --git a/github_code/affaan-m__ECC/scripts/lib/cursor-agent-names.js b/github_code/affaan-m__ECC/scripts/lib/cursor-agent-names.js new file mode 100644 index 0000000000000000000000000000000000000000..945771e0e8246a82501b9fa0d3937831438692f8 --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/cursor-agent-names.js @@ -0,0 +1,26 @@ +'use strict'; + +const path = require('path'); + +function toCursorAgentFileName(fileName) { + if (!fileName || fileName.startsWith('ecc-')) { + return fileName; + } + + return `ecc-${fileName}`; +} + +function toCursorAgentRelativePath(relativePath) { + const segments = String(relativePath || '').split(/[\\/]+/).filter(Boolean); + if (segments.length === 0) { + return relativePath; + } + + const fileName = segments.pop(); + return path.join(...segments, toCursorAgentFileName(fileName)); +} + +module.exports = { + toCursorAgentFileName, + toCursorAgentRelativePath, +}; diff --git a/github_code/affaan-m__ECC/scripts/lib/ecc_dashboard_runtime.py b/github_code/affaan-m__ECC/scripts/lib/ecc_dashboard_runtime.py new file mode 100644 index 0000000000000000000000000000000000000000..549552466cd4f50bde51f0f33a877ae60c3a5396 --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/ecc_dashboard_runtime.py @@ -0,0 +1,70 @@ +#!/usr/bin/env python3 +""" +Runtime helpers for ecc_dashboard.py that do not depend on tkinter. +""" + +from __future__ import annotations + +import os +import platform +import subprocess +from typing import Optional, Tuple, Dict, List + + +def maximize_window(window) -> None: + """Maximize the dashboard window using the safest supported method.""" + try: + window.state('zoomed') + return + except Exception: + pass + + system_name = platform.system() + if system_name == 'Linux': + try: + window.attributes('-zoomed', True) + except Exception: + pass + elif system_name == 'Darwin': + try: + window.attributes('-fullscreen', True) + except Exception: + pass + + +def build_terminal_launch( + path: str, + *, + os_name: Optional[str] = None, + system_name: Optional[str] = None, +) -> Tuple[List[str], Dict[str, object]]: + """Return safe argv/kwargs for opening a terminal rooted at the requested path.""" + resolved_os_name = os_name or os.name + resolved_system_name = system_name or platform.system() + + if resolved_os_name == 'nt': + creationflags = getattr(subprocess, 'CREATE_NEW_CONSOLE', 0) + return ( + ['cmd.exe'], + { + 'cwd': path, + 'creationflags': creationflags, + }, + ) + + if resolved_system_name == 'Darwin': + return (['open', '-a', 'Terminal', path], {}) + + return ( + ['x-terminal-emulator', '-e', 'bash', '-lc', 'cd -- "$1"; exec bash', 'bash', path], + {}, + ) + + +def launch_terminal(path: str) -> None: + """Open a terminal at the given path after validating the target directory.""" + canonical = os.path.realpath(path) + if not os.path.isdir(canonical): + raise ValueError(f"Path is not a valid directory: {canonical!r}") + argv, kwargs = build_terminal_launch(canonical) + subprocess.Popen(argv, **kwargs) # noqa: S603 - list argv, no shell=True, path validated above diff --git a/github_code/affaan-m__ECC/scripts/lib/feedback-links.js b/github_code/affaan-m__ECC/scripts/lib/feedback-links.js new file mode 100644 index 0000000000000000000000000000000000000000..ba37b0fabef7a1bf605e741b104efdb10abc0417 --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/feedback-links.js @@ -0,0 +1,39 @@ +const REPOSITORY_ISSUES_URL = 'https://github.com/affaan-m/ECC/issues/new'; + +const FEEDBACK_ROUTES = Object.freeze({ + problem: `${REPOSITORY_ISSUES_URL}?template=install-problem.yml`, + feedback: `${REPOSITORY_ISSUES_URL}?template=quick-feedback.yml`, + feature: `${REPOSITORY_ISSUES_URL}?template=feature-request.yml`, +}); + +function getFeedbackPayload() { + return { + schemaVersion: 'ecc.feedback.v1', + privacy: 'public-github', + diagnosticsUploaded: false, + routes: { ...FEEDBACK_ROUTES }, + }; +} + +function problemReportLines() { + return [ + 'Report this problem (public GitHub issue):', + FEEDBACK_ROUTES.problem, + 'ECC does not upload diagnostics. Redact paths, repository names, prompts, and secrets before sharing output.', + ]; +} + +function exitFeedbackLines() { + return [ + 'Optional 20-second exit feedback (public GitHub issue):', + FEEDBACK_ROUTES.feedback, + 'ECC does not upload diagnostics or block uninstall.', + ]; +} + +module.exports = { + FEEDBACK_ROUTES, + exitFeedbackLines, + getFeedbackPayload, + problemReportLines, +}; diff --git a/github_code/affaan-m__ECC/scripts/lib/github-coordination.js b/github_code/affaan-m__ECC/scripts/lib/github-coordination.js new file mode 100644 index 0000000000000000000000000000000000000000..a388e79123436c3b4aa21e4af259f25d271ad56d --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/github-coordination.js @@ -0,0 +1,57 @@ +'use strict'; + +const policy = require('./github-coordination/policy'); +const parsing = require('./github-coordination/parsing'); +const ghApi = require('./github-coordination/gh-api'); +const state = require('./github-coordination/state'); +const actions = require('./github-coordination/actions'); +const store = require('./github-coordination/store'); + +module.exports = { + DEFAULT_CONFIG_FILE: policy.DEFAULT_CONFIG_FILE, + DEFAULT_CONFIG_PATH: policy.DEFAULT_CONFIG_PATH, + DEFAULT_POLICY: policy.DEFAULT_POLICY, + DEFAULT_SCHEMA_VERSION: policy.DEFAULT_SCHEMA_VERSION, + loadPolicy: policy.loadPolicy, + + extractCoordinationState: parsing.extractCoordinationState, + extractIssueReferences: parsing.extractIssueReferences, + extractTasks: parsing.extractTasks, + mergeIssueBody: parsing.mergeIssueBody, + renderCoordinationState: parsing.renderCoordinationState, + + commentIssue: ghApi.commentIssue, + editIssue: ghApi.editIssue, + getIssue: ghApi.getIssue, + listIssues: ghApi.listIssues, + normalizeIssueNumber: ghApi.normalizeIssueNumber, + normalizeLabels: ghApi.normalizeLabels, + normalizeRepo: ghApi.normalizeRepo, + runGh: ghApi.runGh, + runGhJson: ghApi.runGhJson, + + buildIssueComment: state.buildIssueComment, + buildIssueStateFromAction: state.buildIssueStateFromAction, + defaultCoordinationState: state.defaultCoordinationState, + desiredLabelsForState: state.desiredLabelsForState, + getCoordinationState: state.getCoordinationState, + mapStateToWorkItemStatus: state.mapStateToWorkItemStatus, + slugifySegment: state.slugifySegment, + summarizeStateForOutput: state.summarizeStateForOutput, + syncIssueLabels: state.syncIssueLabels, + verifyDependenciesClosed: state.verifyDependenciesClosed, + + applyClaim: actions.applyClaim, + applyDecompose: actions.applyDecompose, + applyPublish: actions.applyPublish, + applyReview: actions.applyReview, + applySync: actions.applySync, + applyUnblock: actions.applyUnblock, + applyValidate: actions.applyValidate, + formatCollection: actions.formatCollection, + formatSummary: actions.formatSummary, + + epicWorkItemId: store.epicWorkItemId, + openStore: store.openStore, + upsertCoordinationWorkItem: store.upsertCoordinationWorkItem, +}; diff --git a/github_code/affaan-m__ECC/scripts/lib/github-coordination/actions.js b/github_code/affaan-m__ECC/scripts/lib/github-coordination/actions.js new file mode 100644 index 0000000000000000000000000000000000000000..06cd0d3834fe0eb68ee2ae0662745d9e6fa816d0 --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/github-coordination/actions.js @@ -0,0 +1,385 @@ +'use strict'; + +const { loadPolicy } = require('./policy'); +const { mergeIssueBody, normalizeBodyForComparison } = require('./parsing'); +const { getIssue, listIssues, editIssue, commentIssue, normalizeLabels } = require('./gh-api'); +const { + assertIssueClaimable, + buildIssueComment, + buildIssueStateFromAction, + desiredLabelsForState, + getCoordinationState, + summarizeStateForOutput, + syncIssueLabels, + verifyDependenciesClosed, +} = require('./state'); +const { upsertCoordinationWorkItem } = require('./store'); +const { extractIssueReferences, extractTasks } = require('./parsing'); + +function assertValidRepo(repo) { + if (typeof repo !== 'string' || !repo.trim()) { + throw new Error(`invalid repo: expected non-empty string, got ${JSON.stringify(repo)}`); + } +} + +function assertValidIssueNumber(issueNumber) { + if (!Number.isFinite(issueNumber) || issueNumber <= 0 || !Number.isInteger(issueNumber)) { + throw new Error(`invalid issueNumber: expected positive integer, got ${JSON.stringify(issueNumber)}`); + } +} + +function staleCoordinationLabels(issue, nextLabels, policy) { + const epicLabel = policy.labels && policy.labels.epic; + return normalizeLabels(issue.labels).filter(l => + (l.startsWith('coordination:') || l === epicLabel) && !nextLabels.includes(l) + ); +} + +// applyClaim performs a read (getIssue) → check (assertIssueClaimable) → write +// (editIssue) sequence that is NOT atomic. Two concurrent callers can both read +// an unclaimed issue, pass the check, and both succeed — resulting in a +// double-claim. A code-review finding suggested fixing this via +// context.store.acquireLock(repo, issueNumber), but that API does not exist in +// store.js; adding a call to it would throw at runtime. Left as-is until a +// locking primitive is available — callers should prevent races via external +// serialization (e.g. a serialized job queue or GitHub branch-protection rule). +function applyClaim(repo, issueNumber, options = {}, context = {}) { + assertValidRepo(repo); + assertValidIssueNumber(issueNumber); + const policy = context.policy || loadPolicy(context.rootDir || process.cwd(), options.configPath); + const store = context.store || null; + const issue = getIssue(repo, issueNumber, options); + const currentState = getCoordinationState(issue, policy); + + assertIssueClaimable(issue, currentState); + + const nextState = buildIssueStateFromAction(issue, currentState, 'claim', { + owner: options.actor || options.owner || currentState.owner || issue.author?.login || null, + branch: options.branch || currentState.branch || null, + status: options.status || 'claimed', + validation: options.validation || currentState.validation || 'pending', + review: options.review || currentState.review || (policy.review.required ? 'requested' : 'not-requested'), + projectState: options.projectState || 'in-progress', + }, policy); + + const trackedIssue = { + ...issue, + labels: desiredLabelsForState(nextState, policy), + }; + const body = mergeIssueBody(issue, nextState, policy); + if (!options.dryRun) { + editIssue(repo, issueNumber, { + body, + addLabels: trackedIssue.labels, + removeLabels: staleCoordinationLabels(issue, trackedIssue.labels, policy), + }, options); + commentIssue(repo, issueNumber, buildIssueComment('claimed', repo, issueNumber, nextState), options); + upsertCoordinationWorkItem(store, repo, trackedIssue, nextState, 'claim', { ...context, policy }); + } + + return summarizeStateForOutput(repo, trackedIssue, nextState, 'claim', policy); +} + +function applySync(repo, options = {}, context = {}) { + assertValidRepo(repo); + const policy = context.policy || loadPolicy(context.rootDir || process.cwd(), options.configPath); + const store = context.store || null; + const issues = listIssues(repo, { ...options, state: options.state || 'all', limit: options.limit || 100 }); + const syncedAt = new Date().toISOString(); + const results = []; + + for (const issue of issues) { + const currentState = getCoordinationState(issue, policy); + const nextState = buildIssueStateFromAction(issue, currentState, 'sync', { + status: currentState.status, + validation: currentState.validation, + review: currentState.review, + projectState: currentState.project && currentState.project.state ? currentState.project.state : 'backlog', + }, policy); + + const trackedIssue = { + ...issue, + labels: desiredLabelsForState(nextState, policy), + }; + const body = mergeIssueBody(issue, nextState, policy); + const labelPlan = syncIssueLabels(repo, issue, nextState, policy, options); + + let snapshot = null; + if (!options.dryRun) { + if (normalizeBodyForComparison(body) !== normalizeBodyForComparison(issue.body)) { + editIssue(repo, issue.number, { body }, options); + } + snapshot = upsertCoordinationWorkItem(store, repo, trackedIssue, nextState, 'sync', { ...context, policy }); + } + results.push({ + ...summarizeStateForOutput(repo, trackedIssue, nextState, 'sync', policy), + syncedAt, + labelPlan, + snapshot: snapshot || null, + }); + } + + return { + repo, + syncedAt, + count: results.length, + items: results, + }; +} + +function applyValidate(repo, issueNumber, options = {}, context = {}, existingIssue = null) { + assertValidRepo(repo); + assertValidIssueNumber(issueNumber); + const policy = context.policy || loadPolicy(context.rootDir || process.cwd(), options.configPath); + const issue = existingIssue || getIssue(repo, issueNumber, options); + const state = getCoordinationState(issue, policy); + const dependencyNumbers = Array.isArray(state.dependencies) ? state.dependencies : []; + const closedDependencies = verifyDependenciesClosed(repo, dependencyNumbers, options); + const missingDependencies = dependencyNumbers.filter(number => !closedDependencies.includes(number)); + const validations = []; + + if (missingDependencies.length > 0) { + validations.push({ check: 'dependencies', ok: false, detail: missingDependencies.join(',') }); + } else { + validations.push({ check: 'dependencies', ok: true, detail: 'closed' }); + } + + const ok = validations.every(entry => entry.ok); + const nextState = buildIssueStateFromAction(issue, state, 'validate', { + status: ok ? 'validated' : state.status, + validation: ok ? 'passed' : 'failed', + projectState: ok ? 'ready' : (state.project && state.project.state) || 'backlog', + }, policy); + const trackedIssue = { + ...issue, + labels: desiredLabelsForState(nextState, policy), + }; + + if (!options.dryRun) { + const body = mergeIssueBody(issue, nextState, policy); + editIssue(repo, issueNumber, { + body, + addLabels: trackedIssue.labels, + removeLabels: staleCoordinationLabels(issue, trackedIssue.labels, policy), + }, options); + upsertCoordinationWorkItem(context.store || null, repo, trackedIssue, nextState, 'validate', { ...context, policy }); + } + + return { + ...summarizeStateForOutput(repo, trackedIssue, nextState, 'validate', policy), + ok, + validations, + missingDependencies, + }; +} + +function applyPublish(repo, issueNumber, options = {}, context = {}) { + assertValidRepo(repo); + assertValidIssueNumber(issueNumber); + const policy = context.policy || loadPolicy(context.rootDir || process.cwd(), options.configPath); + const issue = getIssue(repo, issueNumber, options); + const state = getCoordinationState(issue, policy); + const validation = applyValidate(repo, issueNumber, { ...options, dryRun: true }, context, issue); + + if (!validation.ok) { + throw new Error(`Issue #${issueNumber} is not ready to publish: ${validation.validations.map(entry => `${entry.check}=${entry.ok}`).join(', ')}`); + } + + if (policy.review && policy.review.required && state.review !== 'approved') { + throw new Error(`Issue #${issueNumber} cannot be published: review approval required (current: ${state.review})`); + } + + const nextState = buildIssueStateFromAction(issue, state, 'publish', { + status: 'published', + validation: 'passed', + review: state.review === 'changes-requested' ? state.review : 'approved', + projectState: 'done', + }, policy); + const trackedIssue = { + ...issue, + labels: desiredLabelsForState(nextState, policy), + }; + + if (!options.dryRun) { + const body = mergeIssueBody(issue, nextState, policy); + editIssue(repo, issueNumber, { + body, + addLabels: trackedIssue.labels, + removeLabels: staleCoordinationLabels(issue, trackedIssue.labels, policy), + }, options); + commentIssue(repo, issueNumber, buildIssueComment('published', repo, issueNumber, nextState, { + validation: 'passed', + }), options); + upsertCoordinationWorkItem(context.store || null, repo, trackedIssue, nextState, 'publish', { ...context, policy }); + } + + return summarizeStateForOutput(repo, trackedIssue, nextState, 'publish', policy); +} + +function applyReview(repo, issueNumber, options = {}, context = {}) { + assertValidRepo(repo); + assertValidIssueNumber(issueNumber); + const policy = context.policy || loadPolicy(context.rootDir || process.cwd(), options.configPath); + const issue = getIssue(repo, issueNumber, options); + const state = getCoordinationState(issue, policy); + const reviewState = options.review || 'approved'; + const nextState = buildIssueStateFromAction(issue, state, 'review', { + status: reviewState === 'approved' ? 'ready' : reviewState === 'requested' ? 'claimed' : 'blocked', + review: reviewState, + projectState: reviewState === 'approved' ? 'ready' : 'blocked', + }, policy); + const trackedIssue = { + ...issue, + labels: desiredLabelsForState(nextState, policy), + }; + + if (!options.dryRun) { + const body = mergeIssueBody(issue, nextState, policy); + editIssue(repo, issueNumber, { + body, + addLabels: trackedIssue.labels, + removeLabels: staleCoordinationLabels(issue, trackedIssue.labels, policy), + }, options); + commentIssue(repo, issueNumber, buildIssueComment('reviewed', repo, issueNumber, nextState, { + review: reviewState, + }), options); + upsertCoordinationWorkItem(context.store || null, repo, trackedIssue, nextState, 'review', { ...context, policy }); + } + + return summarizeStateForOutput(repo, trackedIssue, nextState, 'review', policy); +} + +function applyDecompose(repo, issueNumber, options = {}, context = {}) { + assertValidRepo(repo); + assertValidIssueNumber(issueNumber); + const policy = context.policy || loadPolicy(context.rootDir || process.cwd(), options.configPath); + const issue = getIssue(repo, issueNumber, options); + const state = getCoordinationState(issue, policy); + const tasks = extractTasks(issue.body); + const dependencies = extractIssueReferences(issue.body); + const nextState = buildIssueStateFromAction(issue, state, 'decompose', { + tasks, + dependencies, + status: tasks.some(task => !task.done) ? 'claimed' : state.status, + projectState: tasks.some(task => !task.done) ? 'in-progress' : (state.project && state.project.state) || 'backlog', + }, policy); + + const trackedIssue = { + ...issue, + labels: desiredLabelsForState(nextState, policy), + }; + + if (!options.dryRun) { + const body = mergeIssueBody(issue, nextState, policy); + editIssue(repo, issueNumber, { + body, + addLabels: trackedIssue.labels, + removeLabels: staleCoordinationLabels(issue, trackedIssue.labels, policy), + }, options); + commentIssue(repo, issueNumber, buildIssueComment('decomposed', repo, issueNumber, nextState, { + taskCount: String(tasks.length), + dependencyCount: String(dependencies.length), + }), options); + upsertCoordinationWorkItem(context.store || null, repo, trackedIssue, nextState, 'decompose', { ...context, policy }); + } + + return { + ...summarizeStateForOutput(repo, trackedIssue, nextState, 'decompose', policy), + tasks, + dependencyCount: dependencies.length, + }; +} + +function applyUnblock(repo, options = {}, context = {}) { + assertValidRepo(repo); + const policy = context.policy || loadPolicy(context.rootDir || process.cwd(), options.configPath); + const store = context.store || null; + const issues = listIssues(repo, { ...options, state: 'all', limit: options.limit || 100 }); + const results = []; + + for (const issue of issues) { + const state = getCoordinationState(issue, policy); + if (state.status !== 'blocked') { + continue; + } + + const dependencyNumbers = Array.isArray(state.dependencies) ? state.dependencies : []; + const closedDependencies = verifyDependenciesClosed(repo, dependencyNumbers, options, issues); + if (dependencyNumbers.length > 0 && closedDependencies.length !== dependencyNumbers.length) { + continue; + } + + const nextState = buildIssueStateFromAction(issue, state, 'unblock', { + status: 'ready', + projectState: 'ready', + validation: state.validation === 'failed' ? 'pending' : state.validation, + }, policy); + const trackedIssue = { + ...issue, + labels: desiredLabelsForState(nextState, policy), + }; + + if (!options.dryRun) { + const body = mergeIssueBody(issue, nextState, policy); + editIssue(repo, issue.number, { + body, + addLabels: trackedIssue.labels, + removeLabels: staleCoordinationLabels(issue, trackedIssue.labels, policy), + }, options); + commentIssue(repo, issue.number, buildIssueComment('unblocked', repo, issue.number, nextState, { + dependencies: dependencyNumbers.length > 0 ? dependencyNumbers.join(',') : 'none', + }), options); + upsertCoordinationWorkItem(store, repo, trackedIssue, nextState, 'unblock', { ...context, policy }); + } + + results.push(summarizeStateForOutput(repo, trackedIssue, nextState, 'unblock', policy)); + } + + return { + repo, + count: results.length, + items: results, + }; +} + +function formatSummary(payload) { + const lines = [ + `${payload.action || 'sync'} epic #${payload.issueNumber}: ${payload.issueTitle}`, + `Repo: ${payload.repo}`, + `Status: ${payload.status}`, + `Owner: ${payload.owner || '(unassigned)'}`, + `Branch: ${payload.branch || '(none)'}`, + `Validation: ${payload.validation || 'pending'}`, + `Review: ${payload.review || 'not-requested'}`, + ]; + if (payload.tasks && payload.tasks.length > 0) { + lines.push(`Tasks: ${payload.tasks.length}`); + } + if (payload.dependencies && payload.dependencies.length > 0) { + lines.push(`Dependencies: ${payload.dependencies.join(', ')}`); + } + return `${lines.join('\n')}\n`; +} + +function formatCollection(payload) { + const lines = [ + `Repo: ${payload.repo}`, + `Items: ${payload.count}`, + ]; + for (const item of payload.items || []) { + lines.push(`- #${item.issueNumber} ${item.status}: ${item.issueTitle}`); + } + return `${lines.join('\n')}\n`; +} + +module.exports = { + applyClaim, + applyDecompose, + applyPublish, + applyReview, + applySync, + applyUnblock, + applyValidate, + formatCollection, + formatSummary, +}; diff --git a/github_code/affaan-m__ECC/scripts/lib/github-coordination/gh-api.js b/github_code/affaan-m__ECC/scripts/lib/github-coordination/gh-api.js new file mode 100644 index 0000000000000000000000000000000000000000..d7669cdb75fe5d063c1bb95d39dfc1a4661daec7 --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/github-coordination/gh-api.js @@ -0,0 +1,175 @@ +'use strict'; + +const { spawnSync } = require('child_process'); + +function normalizeRepo(repo) { + const parts = String(repo || '').split('/').filter(Boolean); + if (parts.length !== 2) { + throw new Error(`Invalid repo format: "${repo}". Expected "owner/repo".`); + } + const [owner, name] = parts; + return { owner, name }; +} + +function normalizeIssueNumber(value) { + const parsed = Number.parseInt(String(value), 10); + if (!Number.isFinite(parsed) || parsed <= 0) { + throw new Error(`Invalid issue number: ${value}`); + } + return parsed; +} + +function normalizeLabelValue(label) { + if (typeof label === 'string') { + return label.trim(); + } + if (label && typeof label === 'object') { + return String(label.name || label.label || '').trim(); + } + return ''; +} + +function normalizeLabels(labels) { + return Array.from(new Set((Array.isArray(labels) ? labels : []).map(normalizeLabelValue).filter(Boolean))).sort(); +} + +function runCommand(command, args, options = {}) { + const result = spawnSync(command, args, { + cwd: options.cwd, + env: options.env || process.env, + encoding: 'utf8', + maxBuffer: 10 * 1024 * 1024, + }); + + if (result.error) { + throw new Error(`${command} ${args.join(' ')} failed: ${result.error.message}`); + } + + if (result.status !== 0) { + throw new Error(`${command} ${args.join(' ')} failed: ${(result.stderr || result.stdout || '').trim()}`); + } + + return result.stdout || ''; +} + +// ECC_GH_SHIM creates a trust boundary: when set, shimPath replaces the real +// `gh` binary and command/commandArgs execute an arbitrary script via +// process.execPath. This variable MUST only be set in trusted, isolated test +// environments (e.g., a test's own temp directory). Never set ECC_GH_SHIM in +// production — doing so allows arbitrary script execution under the caller's +// privileges. +function runGh(args, options = {}) { + const shimPath = process.env.ECC_GH_SHIM; + const command = shimPath ? process.execPath : 'gh'; + const commandArgs = shimPath ? [shimPath, ...args] : args; + const env = { ...process.env }; + + if (options.stripGithubToken) { + delete env.GITHUB_TOKEN; + } + + return runCommand(command, commandArgs, { cwd: options.cwd, env }); +} + +function runGhJson(args, options = {}) { + try { + return JSON.parse(runGh(args, options) || 'null'); + } catch (error) { + throw new Error(`gh ${args.join(' ')} returned invalid JSON: ${error.message}`); + } +} + +function getIssue(repo, issueNumber, options = {}) { + const { owner, name } = normalizeRepo(repo); + const json = runGhJson([ + 'issue', + 'view', + String(issueNumber), + '--repo', + `${owner}/${name}`, + '--json', + 'number,title,body,url,state,labels,author,updatedAt,assignees', + ], options); + + if (!json) { + throw new Error(`Unable to load issue #${issueNumber} from ${repo}`); + } + + return json; +} + +function listIssues(repo, options = {}) { + const { owner, name } = normalizeRepo(repo); + const limit = Number.isFinite(options.limit) ? options.limit : 100; + const state = options.state || 'all'; + return runGhJson([ + 'issue', + 'list', + '--repo', + `${owner}/${name}`, + '--state', + state, + '--limit', + String(limit), + '--json', + 'number,title,body,url,state,labels,author,updatedAt,assignees', + ], options) || []; +} + +function editIssue(repo, issueNumber, options = {}) { + const { owner, name } = normalizeRepo(repo); + const args = [ + 'issue', + 'edit', + String(issueNumber), + '--repo', + `${owner}/${name}`, + ]; + + if (options.body !== undefined) { + args.push('--body', options.body); + } + + for (const label of options.addLabels || []) { + args.push('--add-label', label); + } + + for (const label of options.removeLabels || []) { + args.push('--remove-label', label); + } + + if (options.title) { + args.push('--title', options.title); + } + + if (options.assignee) { + args.push('--add-assignee', options.assignee); + } + + return runGh(args, options); +} + +function commentIssue(repo, issueNumber, body, options = {}) { + const { owner, name } = normalizeRepo(repo); + return runGh([ + 'issue', + 'comment', + String(issueNumber), + '--repo', + `${owner}/${name}`, + '--body', + body, + ], options); +} + +module.exports = { + commentIssue, + editIssue, + getIssue, + listIssues, + normalizeIssueNumber, + normalizeLabels, + normalizeRepo, + runGh, + runGhJson, +}; diff --git a/github_code/affaan-m__ECC/scripts/lib/github-coordination/parsing.js b/github_code/affaan-m__ECC/scripts/lib/github-coordination/parsing.js new file mode 100644 index 0000000000000000000000000000000000000000..987067c16d173f988f8a7e171f65899e39e5b344 --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/github-coordination/parsing.js @@ -0,0 +1,129 @@ +'use strict'; + +const { DEFAULT_POLICY, DEFAULT_SCHEMA_VERSION, DEFAULT_SECTION_MARKER } = require('./policy'); + +function escapeRegExp(str) { + return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +} + +function normalizeBodyForComparison(body) { + return (body || '').replace(/"lastSyncAt"\s*:\s*[^,}\n]+/g, '"lastSyncAt": NORMALIZED'); +} + +function extractCoordinationState(body, policy = DEFAULT_POLICY) { + const marker = escapeRegExp(policy.sectionMarker || DEFAULT_SECTION_MARKER); + const regex = new RegExp(`\\s*` + '```json\\s*([\\s\\S]*?)\\s*```' + `\\s*`, 'm'); + const match = String(body || '').match(regex); + + if (!match) { + return null; + } + + try { + const parsed = JSON.parse(match[1]); + return parsed && typeof parsed === 'object' ? parsed : null; + } catch (error) { + throw new SyntaxError(`Malformed coordination JSON in body: ${error.message} — raw: ${match[1].slice(0, 120)}`); + } +} + +function extractIssueReferences(text) { + const refs = new Set(); + const source = String(text || ''); + for (const match of source.matchAll(/(?:^|[^\d])#(\d+)\b/g)) { + refs.add(Number.parseInt(match[1], 10)); + } + return Array.from(refs) + .filter(Number.isFinite) + .sort((a, b) => a - b); +} + +function extractTasks(body) { + const lines = String(body || '').split(/\r?\n/); + const tasks = []; + let inTasks = false; + + for (const rawLine of lines) { + const line = rawLine.trim(); + if (/^#{2,3}\s+tasks\b/i.test(line) || /^#{2,3}\s+task list\b/i.test(line)) { + inTasks = true; + continue; + } + if (inTasks && /^#{2,3}\s+\S/.test(line)) { + break; + } + if (inTasks) { + const taskMatch = line.match(/^- \[( |x)\]\s+(.+)$/i); + if (taskMatch) { + tasks.push({ + title: taskMatch[2].trim(), + done: taskMatch[1].toLowerCase() === 'x' + }); + } + } + } + + return tasks; +} + +function parseStringList(value) { + if (!value) { + return []; + } + return String(value) + .split(',') + .map(part => part.trim()) + .filter(Boolean); +} + +function renderCoordinationState(state, policy = DEFAULT_POLICY) { + const marker = policy.sectionMarker || DEFAULT_SECTION_MARKER; + const payload = { + schemaVersion: state.schemaVersion || policy.schemaVersion || DEFAULT_SCHEMA_VERSION, + kind: state.kind || 'epic', + status: state.status || 'available', + owner: state.owner || null, + branch: state.branch || null, + validation: state.validation || 'pending', + review: state.review || 'not-requested', + project: state.project || { state: 'backlog', fields: {} }, + dependencies: Array.isArray(state.dependencies) ? state.dependencies : [], + tasks: Array.isArray(state.tasks) ? state.tasks : [], + labels: Array.isArray(state.labels) ? state.labels : [], + lastAction: state.lastAction || 'sync', + lastActionAt: state.lastActionAt || new Date().toISOString(), + lastSyncAt: state.lastSyncAt || new Date().toISOString(), + notes: state.notes || null + }; + + return [``, '```json', JSON.stringify(payload, null, 2), '```', ``].join('\n'); +} + +function mergeIssueBody(issue, nextState, policy = DEFAULT_POLICY) { + const body = String(issue.body || ''); + const markerEscaped = escapeRegExp(policy.sectionMarker || DEFAULT_SECTION_MARKER); + const rendered = renderCoordinationState(nextState, policy); + const regex = new RegExp(`\\n?[\\s\\S]*?\\n?`, 'm'); + + if (regex.test(body)) { + return body.replace(regex, `\n${rendered}\n`).trim() + '\n'; + } + + const trimmed = body.trimEnd(); + if (!trimmed) { + return `${rendered}\n`; + } + + return `${trimmed}\n\n${rendered}\n`; +} + +module.exports = { + escapeRegExp, + extractCoordinationState, + extractIssueReferences, + extractTasks, + mergeIssueBody, + normalizeBodyForComparison, + parseStringList, + renderCoordinationState +}; diff --git a/github_code/affaan-m__ECC/scripts/lib/github-coordination/policy.js b/github_code/affaan-m__ECC/scripts/lib/github-coordination/policy.js new file mode 100644 index 0000000000000000000000000000000000000000..dc0b0d5499506b29eeafedf9428de3b3cb88d97e --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/github-coordination/policy.js @@ -0,0 +1,101 @@ +'use strict'; + +const fs = require('fs'); +const path = require('path'); + +const DEFAULT_CONFIG_FILE = 'github-native-coordination.json'; +const DEFAULT_CONFIG_PATH = path.join(__dirname, '..', '..', '..', 'config', DEFAULT_CONFIG_FILE); +const DEFAULT_SECTION_MARKER = 'ecc-coordination'; +const DEFAULT_SCHEMA_VERSION = 'ecc.github.coordination.v1'; +const DEFAULT_LABELS = Object.freeze({ + epic: 'epic', + available: 'coordination:available', + claimed: 'coordination:claimed', + ready: 'coordination:ready', + blocked: 'coordination:blocked', + validated: 'coordination:validated', + reviewRequested: 'coordination:review-requested', + reviewApproved: 'coordination:review-approved', + reviewChangesRequested: 'coordination:review-changes-requested', + published: 'coordination:published', + synced: 'coordination:synced', +}); +const DEFAULT_POLICY = Object.freeze({ + schemaVersion: DEFAULT_SCHEMA_VERSION, + sectionMarker: DEFAULT_SECTION_MARKER, + labels: DEFAULT_LABELS, + review: { + required: true, + defaultMode: 'required', + }, + validation: { + required: true, + }, + branchModel: { + epicOnly: true, + taskBranches: false, + }, + project: { + enabled: false, + fieldNames: { + status: 'Status', + owner: 'Owner', + branch: 'Branch', + validation: 'Validation', + review: 'Review', + }, + }, +}); + +function loadPolicy(rootDir = process.cwd(), configPath = null) { + const resolvedPath = configPath + ? path.resolve(configPath) + : path.join(rootDir, 'config', DEFAULT_CONFIG_FILE); + + if (!fs.existsSync(resolvedPath)) { + return { + ...DEFAULT_POLICY, + sourcePath: null, + }; + } + + let parsed; + try { + parsed = JSON.parse(fs.readFileSync(resolvedPath, 'utf8')); + } catch (error) { + throw new Error(`Failed to load policy from ${resolvedPath}: ${error.message}`); + } + if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) { + throw new Error(`Policy file ${resolvedPath} must contain a JSON object, got ${Array.isArray(parsed) ? 'array' : typeof parsed}`); + } + const labels = typeof parsed.labels === 'object' && parsed.labels !== null && !Array.isArray(parsed.labels) ? parsed.labels : {}; + const review = typeof parsed.review === 'object' && parsed.review !== null && !Array.isArray(parsed.review) ? parsed.review : {}; + const validation = typeof parsed.validation === 'object' && parsed.validation !== null && !Array.isArray(parsed.validation) ? parsed.validation : {}; + const branchModel = typeof parsed.branchModel === 'object' && parsed.branchModel !== null && !Array.isArray(parsed.branchModel) ? parsed.branchModel : {}; + const project = typeof parsed.project === 'object' && parsed.project !== null && !Array.isArray(parsed.project) ? parsed.project : {}; + const fieldNames = typeof project.fieldNames === 'object' && project.fieldNames !== null && !Array.isArray(project.fieldNames) ? project.fieldNames : {}; + return { + ...DEFAULT_POLICY, + ...parsed, + labels: { ...DEFAULT_LABELS, ...labels }, + review: { ...DEFAULT_POLICY.review, ...review }, + validation: { ...DEFAULT_POLICY.validation, ...validation }, + branchModel: { ...DEFAULT_POLICY.branchModel, ...branchModel }, + project: { + ...DEFAULT_POLICY.project, + ...project, + fieldNames: { ...DEFAULT_POLICY.project.fieldNames, ...fieldNames }, + }, + sourcePath: resolvedPath, + }; +} + +module.exports = { + DEFAULT_CONFIG_FILE, + DEFAULT_CONFIG_PATH, + DEFAULT_LABELS, + DEFAULT_POLICY, + DEFAULT_SCHEMA_VERSION, + DEFAULT_SECTION_MARKER, + loadPolicy, +}; diff --git a/github_code/affaan-m__ECC/scripts/lib/github-coordination/state.js b/github_code/affaan-m__ECC/scripts/lib/github-coordination/state.js new file mode 100644 index 0000000000000000000000000000000000000000..3f094dc1140e386c943cf6be4331cdcdf03efed2 --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/github-coordination/state.js @@ -0,0 +1,252 @@ +'use strict'; + +const { DEFAULT_POLICY, DEFAULT_SCHEMA_VERSION } = require('./policy'); +const { extractIssueReferences, extractTasks } = require('./parsing'); +const { normalizeLabels, listIssues, editIssue } = require('./gh-api'); + +function slugifySegment(value) { + return String(value || '') + .toLowerCase() + .replace(/[^a-z0-9]+/g, '-') + .replace(/^-+|-+$/g, '') || 'unknown'; +} + +function defaultCoordinationState(issue, policy = DEFAULT_POLICY) { + return { + schemaVersion: policy.schemaVersion || DEFAULT_SCHEMA_VERSION, + kind: 'epic', + status: 'available', + owner: issue && issue.author && issue.author.login ? issue.author.login : null, + branch: null, + validation: 'pending', + review: 'not-requested', + project: { + state: 'backlog', + fields: {}, + }, + dependencies: extractIssueReferences(issue && issue.body ? issue.body : ''), + tasks: extractTasks(issue && issue.body ? issue.body : ''), + labels: normalizeLabels(issue && issue.labels), + lastAction: 'sync', + lastActionAt: new Date().toISOString(), + lastSyncAt: new Date().toISOString(), + notes: null, + }; +} + +function getCoordinationState(issue, policy = DEFAULT_POLICY) { + const { extractCoordinationState } = require('./parsing'); // lazy to avoid circular init order + let existing; + try { + existing = extractCoordinationState(issue && issue.body, policy); + } catch (error) { + process.stderr.write(`[github-coordination] Warning: ${error.message} (issue #${issue && issue.number})\n`); + existing = null; + } + if (existing) { + return { + ...defaultCoordinationState(issue, policy), + ...existing, + project: { + ...defaultCoordinationState(issue, policy).project, + ...(existing.project || {}), + }, + tasks: Array.isArray(existing.tasks) ? existing.tasks : extractTasks(issue && issue.body ? issue.body : ''), + dependencies: Array.isArray(existing.dependencies) ? existing.dependencies : extractIssueReferences(issue && issue.body ? issue.body : ''), + labels: Array.isArray(existing.labels) ? existing.labels : normalizeLabels(issue && issue.labels), + }; + } + return defaultCoordinationState(issue, policy); +} + +function buildIssueStateFromAction(issue, currentState, action, options = {}, policy = DEFAULT_POLICY) { + const now = new Date().toISOString(); + const next = { + ...currentState, + schemaVersion: policy.schemaVersion || DEFAULT_SCHEMA_VERSION, + kind: 'epic', + lastAction: action, + lastActionAt: now, + lastSyncAt: now, + labels: normalizeLabels(issue.labels), + dependencies: Array.isArray(currentState.dependencies) ? currentState.dependencies : extractIssueReferences(issue.body), + tasks: Array.isArray(currentState.tasks) ? currentState.tasks : extractTasks(issue.body), + }; + + if (options.owner !== undefined) next.owner = options.owner; + if (options.branch !== undefined) next.branch = options.branch; + if (options.validation !== undefined) next.validation = options.validation; + if (options.review !== undefined) next.review = options.review; + if (options.status !== undefined) next.status = options.status; + if (options.projectState !== undefined) { + next.project = { ...(next.project || {}), state: options.projectState }; + } + if (options.notes !== undefined) next.notes = options.notes; + if (options.tasks !== undefined) next.tasks = options.tasks; + if (options.dependencies !== undefined) next.dependencies = options.dependencies; + + return next; +} + +function desiredLabelsForState(state, policy = DEFAULT_POLICY) { + const labels = []; + const known = policy.labels || DEFAULT_POLICY.labels; + + labels.push(known.epic); + labels.push(known.synced); + + if (state.status === 'available') labels.push(known.available); + if (state.status === 'claimed') labels.push(known.claimed); + if (state.status === 'ready') labels.push(known.ready); + if (state.status === 'blocked') labels.push(known.blocked); + if (state.validation === 'passed') labels.push(known.validated); + if (state.review === 'requested') labels.push(known.reviewRequested); + if (state.review === 'approved') labels.push(known.reviewApproved); + if (state.review === 'changes-requested') labels.push(known.reviewChangesRequested); + if (state.status === 'published') labels.push(known.published); + + return Array.from(new Set(labels.filter(Boolean))).sort(); +} + +function syncIssueLabels(repo, issue, state, policy = DEFAULT_POLICY, options = {}) { + const desired = new Set(desiredLabelsForState(state, policy)); + const current = new Set(normalizeLabels(issue.labels)); + const addLabels = Array.from(desired).filter(label => !current.has(label)); + const removeLabels = Array.from(current).filter(label => { + if (!label.startsWith('coordination:') && label !== (policy.labels && policy.labels.epic)) { + return false; + } + return !desired.has(label); + }); + + if (options.dryRun || (addLabels.length === 0 && removeLabels.length === 0)) { + return { addLabels, removeLabels }; + } + + if (addLabels.length > 0 || removeLabels.length > 0) { + editIssue(repo, issue.number, { ...options, addLabels, removeLabels }); + } + + return { addLabels, removeLabels }; +} + +function findIssueByNumber(issues, issueNumber) { + return issues.find(issue => Number(issue.number) === Number(issueNumber)) || null; +} + +function buildIssueComment(action, repo, issueNumber, state, extra = {}) { + const summary = [ + `ECC coordination ${action}`, + `Repo: ${repo}`, + `Issue: #${issueNumber}`, + `Status: ${state.status}`, + `Owner: ${state.owner || '(unassigned)'}`, + `Branch: ${state.branch || '(none)'}`, + `Validation: ${state.validation || 'pending'}`, + `Review: ${state.review || 'not-requested'}`, + ]; + + for (const [key, value] of Object.entries(extra)) { + summary.push(`${key}: ${value}`); + } + + summary.push('', 'This comment is part of the append-only coordination audit trail.'); + return summary.join('\n'); +} + +function mapStateToWorkItemStatus(state) { + switch (state) { + case 'blocked': + return 'blocked'; + case 'published': + return 'done'; + case 'validated': + case 'reviewing': + case 'claimed': + case 'ready': + return 'in-progress'; + case 'changes-requested': + return 'needs-review'; + case 'available': + default: + return 'open'; + } +} + +function summarizeProjectProjection(state, policy = DEFAULT_POLICY) { + return { + enabled: Boolean(policy.project && policy.project.enabled), + state: state.project && state.project.state ? state.project.state : 'backlog', + fields: { + ...(state.project && state.project.fields ? state.project.fields : {}), + }, + }; +} + +function summarizeStateForOutput(repo, issue, state, action, policy = DEFAULT_POLICY) { + return { + schemaVersion: state.schemaVersion || policy.schemaVersion || DEFAULT_SCHEMA_VERSION, + repo, + issueNumber: issue.number, + issueUrl: issue.url || null, + issueTitle: issue.title, + action, + status: state.status, + owner: state.owner || null, + branch: state.branch || null, + validation: state.validation || 'pending', + review: state.review || 'not-requested', + project: summarizeProjectProjection(state, policy), + dependencies: Array.isArray(state.dependencies) ? state.dependencies : [], + tasks: Array.isArray(state.tasks) ? state.tasks : [], + labels: normalizeLabels(issue.labels), + workItemId: `github-${slugifySegment(repo)}-epic-${issue.number}`, + lastActionAt: state.lastActionAt || null, + lastSyncAt: state.lastSyncAt || null, + }; +} + +function assertIssueClaimable(issue, state) { + if (String(issue.state || '').toLowerCase() !== 'open') { + throw new Error(`Issue #${issue.number} is not open`); + } + + if (state.status === 'claimed') { + throw new Error(`Issue #${issue.number} is already claimed by ${state.owner || 'unknown'}`); + } +} + +function verifyDependenciesClosed(repo, dependencyNumbers, options = {}, allIssues = null) { + if (!Array.isArray(dependencyNumbers) || dependencyNumbers.length === 0) { + return []; + } + + const issueList = allIssues || listIssues(repo, { ...options, state: 'all', limit: options.limit || 200 }); + const closed = []; + for (const dependencyNumber of dependencyNumbers) { + const issue = findIssueByNumber(issueList, dependencyNumber); + if (!issue) { + process.stderr.write(`[github-coordination] Warning: dependency issue #${dependencyNumber} not found in issue list (may be in a different repo or beyond limit)\n`); + } else if (String(issue.state || '').toLowerCase() === 'closed') { + closed.push(dependencyNumber); + } + } + + return closed; +} + +module.exports = { + assertIssueClaimable, + buildIssueComment, + buildIssueStateFromAction, + defaultCoordinationState, + desiredLabelsForState, + findIssueByNumber, + getCoordinationState, + mapStateToWorkItemStatus, + slugifySegment, + summarizeProjectProjection, + summarizeStateForOutput, + syncIssueLabels, + verifyDependenciesClosed, +}; diff --git a/github_code/affaan-m__ECC/scripts/lib/github-coordination/store.js b/github_code/affaan-m__ECC/scripts/lib/github-coordination/store.js new file mode 100644 index 0000000000000000000000000000000000000000..cc3371023449e3f9552380b78be3c2734759a507 --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/github-coordination/store.js @@ -0,0 +1,65 @@ +'use strict'; + +const os = require('os'); + +const { createStateStore } = require('../state-store'); +const { DEFAULT_SCHEMA_VERSION, DEFAULT_POLICY } = require('./policy'); +const { normalizeLabels } = require('./gh-api'); +const { slugifySegment, mapStateToWorkItemStatus, summarizeProjectProjection } = require('./state'); + +function epicWorkItemId(repo, issueNumber) { + return `github-${slugifySegment(repo)}-epic-${issueNumber}`; +} + +function upsertCoordinationWorkItem(store, repo, issue, state, action, options = {}) { + if (!store) { + return null; + } + + const now = new Date().toISOString(); + const metadata = { + schemaVersion: state.schemaVersion || DEFAULT_SCHEMA_VERSION, + repo, + issueNumber: issue.number, + issueUrl: issue.url || null, + issueTitle: issue.title || null, + labels: normalizeLabels(issue.labels), + coordination: state, + projectProjection: summarizeProjectProjection(state, options.policy || DEFAULT_POLICY), + action, + actionAt: now, + syncedBy: 'ecc-github-coordination', + }; + + return store.upsertWorkItem({ + id: epicWorkItemId(repo, issue.number), + source: 'github-epic', + sourceId: String(issue.number), + title: `Epic #${issue.number}: ${issue.title}`, + status: mapStateToWorkItemStatus(state.status), + priority: state.status === 'blocked' ? 'high' : 'normal', + url: issue.url || null, + owner: state.owner || (issue.author && issue.author.login) || null, + repoRoot: options.repoRoot || process.cwd(), + sessionId: options.sessionId || null, + metadata, + updatedAt: now, + }); +} + +async function openStore(options = {}) { + if (options.dbPath === false) { + return null; + } + + return createStateStore({ + dbPath: options.dbPath, + homeDir: options.homeDir || process.env.HOME || os.homedir(), + }); +} + +module.exports = { + epicWorkItemId, + openStore, + upsertCoordinationWorkItem, +}; diff --git a/github_code/affaan-m__ECC/scripts/lib/github-discussions.js b/github_code/affaan-m__ECC/scripts/lib/github-discussions.js new file mode 100644 index 0000000000000000000000000000000000000000..17767feaa4e28a6f1740999ff7f60d466dc1804b --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/github-discussions.js @@ -0,0 +1,159 @@ +'use strict'; + +const { spawnSync } = require('child_process'); + +const DEFAULT_DISCUSSION_FIRST = 100; +const MAINTAINER_ASSOCIATIONS = new Set(['OWNER', 'MEMBER', 'COLLABORATOR']); +const DISCUSSION_ENABLED_QUERY = 'query($owner: String!, $name: String!) { repository(owner: $owner, name: $name) { hasDiscussionsEnabled } }'; +const DISCUSSION_QUERY = 'query($owner: String!, $name: String!, $first: Int!) { repository(owner: $owner, name: $name) { hasDiscussionsEnabled discussions(first: $first, orderBy: {field: UPDATED_AT, direction: DESC}) { totalCount nodes { number title url updatedAt authorAssociation category { name isAnswerable } answer { url authorAssociation } comments(first: 20) { nodes { authorAssociation } } } } } }'; + +function splitRepo(repo) { + const [owner, name] = String(repo || '').split('/'); + if (!owner || !name) { + throw new Error(`Invalid repo: ${repo}`); + } + return { owner, name }; +} + +function runCommand(command, args, options = {}) { + const result = spawnSync(command, args, { + cwd: options.cwd, + env: options.env || process.env, + encoding: 'utf8', + maxBuffer: 10 * 1024 * 1024, + }); + + if (result.error) { + throw new Error(`${command} ${args.join(' ')} failed: ${result.error.message}`); + } + + if (result.status !== 0) { + throw new Error(`${command} ${args.join(' ')} failed: ${(result.stderr || result.stdout || '').trim()}`); + } + + return result.stdout || ''; +} + +function runGhJson(args, options = {}) { + const shimPath = process.env.ECC_GH_SHIM; + const command = shimPath ? process.execPath : 'gh'; + const commandArgs = shimPath ? [shimPath, ...args] : args; + const env = { ...process.env }; + + if (!options.useEnvGithubToken) { + delete env.GITHUB_TOKEN; + } + + const stdout = runCommand(command, commandArgs, { env }); + try { + return JSON.parse(stdout || 'null'); + } catch (error) { + throw new Error(`gh ${args.join(' ')} returned invalid JSON: ${error.message}`); + } +} + +function discussionNeedsMaintainerTouch(discussion) { + if (MAINTAINER_ASSOCIATIONS.has(discussion.authorAssociation)) { + return false; + } + + if ( + discussion.answer + && MAINTAINER_ASSOCIATIONS.has(discussion.answer.authorAssociation) + ) { + return false; + } + + const comments = discussion.comments && Array.isArray(discussion.comments.nodes) + ? discussion.comments.nodes + : []; + return !comments.some(comment => MAINTAINER_ASSOCIATIONS.has(comment.authorAssociation)); +} + +function discussionNeedsAcceptedAnswer(discussion) { + return Boolean( + discussion + && discussion.category + && discussion.category.isAnswerable + && !discussion.answer + ); +} + +function summarizeDiscussion(discussion) { + return { + number: discussion.number, + title: discussion.title, + url: discussion.url, + updatedAt: discussion.updatedAt, + category: discussion.category ? discussion.category.name : null, + }; +} + +function fetchDiscussionSummary(repo, options = {}) { + const { owner, name } = splitRepo(repo); + const first = Number.isFinite(options.first) ? options.first : DEFAULT_DISCUSSION_FIRST; + const enabledPayload = runGhJson([ + 'api', + 'graphql', + '-f', + `owner=${owner}`, + '-f', + `name=${name}`, + '-f', + `query=${DISCUSSION_ENABLED_QUERY}`, + ], options); + const enabledRepository = enabledPayload && enabledPayload.data && enabledPayload.data.repository; + + if (!enabledRepository || !enabledRepository.hasDiscussionsEnabled) { + return emptyDiscussionSummary(); + } + + const payload = runGhJson([ + 'api', + 'graphql', + '-f', + `owner=${owner}`, + '-f', + `name=${name}`, + '-F', + `first=${first}`, + '-f', + `query=${DISCUSSION_QUERY}`, + ], options); + const repository = payload && payload.data && payload.data.repository; + const discussions = repository && repository.discussions; + const nodes = discussions && Array.isArray(discussions.nodes) ? discussions.nodes : []; + const needingTouch = nodes.filter(discussionNeedsMaintainerTouch); + const missingAcceptedAnswer = nodes.filter(discussionNeedsAcceptedAnswer); + + return { + enabled: Boolean(repository && repository.hasDiscussionsEnabled), + totalCount: discussions && Number.isFinite(discussions.totalCount) ? discussions.totalCount : 0, + sampledCount: nodes.length, + needingMaintainerTouch: needingTouch.map(summarizeDiscussion), + answerableWithoutAcceptedAnswer: missingAcceptedAnswer.map(summarizeDiscussion), + }; +} + +function emptyDiscussionSummary() { + return { + enabled: false, + totalCount: 0, + sampledCount: 0, + needingMaintainerTouch: [], + answerableWithoutAcceptedAnswer: [], + }; +} + +module.exports = { + DEFAULT_DISCUSSION_FIRST, + DISCUSSION_ENABLED_QUERY, + DISCUSSION_QUERY, + MAINTAINER_ASSOCIATIONS, + discussionNeedsAcceptedAnswer, + discussionNeedsMaintainerTouch, + emptyDiscussionSummary, + fetchDiscussionSummary, + splitRepo, + summarizeDiscussion, +}; diff --git a/github_code/affaan-m__ECC/scripts/lib/github-origin.js b/github_code/affaan-m__ECC/scripts/lib/github-origin.js new file mode 100644 index 0000000000000000000000000000000000000000..ea59c0e48e9246823ac8b04ed6b7b1b66fc0b51a --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/github-origin.js @@ -0,0 +1,14 @@ +'use strict'; + +function normalizeGitHubGitOrigin(value) { + if (typeof value !== 'string') return null; + const normalized = value.trim().replace(/\.git$/i, '').replace(/\/+$/, ''); + const match = normalized.match( + /^(?:https:\/\/github\.com\/|ssh:\/\/git@github\.com\/|git@github\.com:)([^/]+\/[^/]+)$/i + ); + return match ? match[1].toLowerCase() : null; +} + +module.exports = { + normalizeGitHubGitOrigin, +}; diff --git a/github_code/affaan-m__ECC/scripts/lib/harness-adapter-compliance.js b/github_code/affaan-m__ECC/scripts/lib/harness-adapter-compliance.js new file mode 100644 index 0000000000000000000000000000000000000000..e1aafd75280a8e448ecd75f0d3be21e7046acbb3 --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/harness-adapter-compliance.js @@ -0,0 +1,487 @@ +'use strict'; + +const fs = require('fs'); +const path = require('path'); + +const MATRIX_BLOCK_START = ''; +const MATRIX_BLOCK_END = ''; + +const COMPLIANCE_STATES = Object.freeze({ + Native: 'ECC can install or verify the surface directly for this harness.', + 'Adapter-backed': 'ECC has a thin adapter, plugin, or package surface, but parity differs by harness.', + 'Instruction-backed': 'ECC can provide the guidance and files, but the harness does not expose the runtime hook/session surface ECC needs for enforcement.', + 'Reference-only': 'The tool is useful as a design pressure or external runtime, but ECC does not yet ship a direct installer or adapter for it.', +}); + +const REQUIRED_FIELDS = Object.freeze([ + 'id', + 'harness', + 'state', + 'supported_assets', + 'unsupported_surfaces', + 'install_or_onramp', + 'verification_commands', + 'risk_notes', + 'last_verified_at', + 'owner', + 'source_docs', +]); + +function freezeRecord(record) { + return Object.freeze({ + ...record, + supported_assets: Object.freeze(record.supported_assets.slice()), + unsupported_surfaces: Object.freeze(record.unsupported_surfaces.slice()), + install_or_onramp: Object.freeze(record.install_or_onramp.slice()), + verification_commands: Object.freeze(record.verification_commands.slice()), + risk_notes: Object.freeze(record.risk_notes.slice()), + source_docs: Object.freeze(record.source_docs.slice()), + }); +} + +const ADAPTER_RECORDS = Object.freeze([ + { + id: 'claude-code', + harness: 'Claude Code', + state: 'Native', + supported_assets: [ + 'Claude plugin assets', + 'skills', + 'commands', + 'hooks', + 'MCP config', + 'local rules', + 'statusline-oriented workflows', + ], + unsupported_surfaces: ['Claude-native hooks do not imply parity in other harnesses'], + install_or_onramp: [ + '`./install.sh --profile minimal --target claude`', + 'Claude plugin install', + ], + verification_commands: [ + '`npm run harness:audit -- --format json`', + '`node scripts/session-inspect.js --list-adapters`', + ], + risk_notes: ['Avoid loading every skill by default; keep hooks opt-in and inspectable.'], + last_verified_at: '2026-05-12', + owner: 'ECC maintainers', + source_docs: [ + '.claude-plugin/plugin.json', + 'docs/architecture/cross-harness.md', + 'scripts/lib/install-targets/claude-home.js', + ], + }, + { + id: 'codex', + harness: 'Codex', + state: 'Instruction-backed', + supported_assets: [ + '`AGENTS.md`', + 'Codex plugin metadata', + 'skills', + 'MCP reference config', + 'command patterns', + ], + unsupported_surfaces: ['Native hook enforcement and Claude slash-command semantics are not equivalent'], + install_or_onramp: [ + '`./install.sh --profile minimal --target codex`', + 'repo-local `AGENTS.md` review', + ], + verification_commands: ['`npm run harness:audit -- --format json`'], + risk_notes: ['Treat hooks as policy text unless a native Codex hook surface exists.'], + last_verified_at: '2026-05-12', + owner: 'ECC maintainers', + source_docs: [ + '.codex-plugin/plugin.json', + 'AGENTS.md', + 'scripts/lib/install-targets/codex-home.js', + ], + }, + { + id: 'opencode', + harness: 'OpenCode', + state: 'Adapter-backed', + supported_assets: [ + 'OpenCode package/plugin metadata', + 'shared skills', + 'MCP config', + 'event adapter patterns', + ], + unsupported_surfaces: ['Event names, plugin packaging, and command dispatch differ from Claude Code'], + install_or_onramp: ['OpenCode package or plugin surface from this repo'], + verification_commands: [ + '`node tests/scripts/build-opencode.test.js`', + '`npm run harness:audit -- --format json`', + ], + risk_notes: ['Keep hook logic in shared scripts and adapt only event shape at the edge.'], + last_verified_at: '2026-05-12', + owner: 'ECC maintainers', + source_docs: [ + '.opencode/package.json', + '.opencode/plugins/ecc-hooks.ts', + 'scripts/build-opencode.js', + ], + }, + { + id: 'pi', + harness: 'Pi', + state: 'Adapter-backed', + supported_assets: [ + 'Pi package manifest', + 'canonical ECC skills (skills/)', + 'canonical ECC commands as prompt templates (commands/)', + 'canonical ECC engineering rules (rules/common/) injected into the system prompt', + 'session lifecycle hook adapter', + '/ecc-doctor diagnostics command', + ], + unsupported_surfaces: [ + 'Subagents, chains, approval prompts, and persistent todos require companion Pi packages and are not part of this adapter', + 'Pi core has no MCP surface, though ECC MCP configs load verbatim through the community pi-mcp-adapter package, which ECC neither installs nor depends on', + ], + install_or_onramp: ['`pi install git:github.com/affaan-m/ECC`', '`pi install /path/to/ECC` from a local checkout'], + verification_commands: [ + '`node tests/pi/pi-package-manifest.test.js`', + '`node tests/pi/pi-extension-adapter.test.js`', + '`npm run harness:adapters -- --check`', + ], + risk_notes: [ + 'Pi extensions execute with full user permissions, and hooks run without a shell and resolve from the installed package rather than the user project', + 'Keep canonical skills and commands as the single source of truth, and never generate copies under .pi/', + ], + last_verified_at: '2026-08-10', + owner: 'ECC maintainers', + source_docs: [ + '.pi/extensions/index.ts', + '.pi/README.md', + 'package.json', + ], + }, + { + id: 'cursor', + harness: 'Cursor', + state: 'Adapter-backed', + supported_assets: [ + 'Cursor rules', + 'project-local skills', + 'hook adapter', + 'shared scripts', + ], + unsupported_surfaces: ['Cursor hook events and rule loading differ from Claude Code'], + install_or_onramp: ['`./install.sh --profile minimal --target cursor`'], + verification_commands: [ + '`node tests/lib/install-targets.test.js`', + '`npm run harness:audit -- --format json`', + ], + risk_notes: ['Cursor adapters must preserve existing project rules and avoid silent overwrite.'], + last_verified_at: '2026-05-12', + owner: 'ECC maintainers', + source_docs: [ + '.cursor/', + 'scripts/lib/install-targets/cursor-project.js', + 'tests/lib/install-targets.test.js', + ], + }, + { + id: 'gemini', + harness: 'Gemini', + state: 'Instruction-backed', + supported_assets: [ + 'Gemini project-local instructions', + 'shared skills', + 'rules', + 'compatibility docs', + ], + unsupported_surfaces: ['No full ECC hook parity; ecosystem ports must document drift from upstream ECC'], + install_or_onramp: ['`./install.sh --profile minimal --target gemini`'], + verification_commands: ['`node tests/lib/install-targets.test.js`'], + risk_notes: ['Treat Gemini ports as ecosystem adapters until validated end to end inside Gemini CLI.'], + last_verified_at: '2026-05-12', + owner: 'ECC maintainers', + source_docs: [ + '.gemini/', + 'scripts/lib/install-targets/gemini-project.js', + 'tests/lib/install-targets.test.js', + ], + }, + { + id: 'zed', + harness: 'Zed', + state: 'Adapter-backed', + supported_assets: [ + 'Zed project settings', + 'flattened project rules', + 'shared skills', + 'commands', + 'agents', + ], + unsupported_surfaces: ['Zed external agents and native Agent Panel permissions are not Claude hooks'], + install_or_onramp: ['`./install.sh --profile minimal --target zed`'], + verification_commands: [ + '`node tests/lib/install-targets.test.js`', + '`npm run harness:audit -- --format json`', + ], + risk_notes: ['Keep project settings conservative and do not copy BYOK/OpenRouter secrets into `.zed/`.'], + last_verified_at: '2026-05-17', + owner: 'ECC maintainers', + source_docs: [ + '.zed/settings.json', + 'scripts/lib/install-targets/zed-project.js', + 'docs/architecture/cross-harness.md', + 'tests/lib/install-targets.test.js', + ], + }, + { + id: 'dmux', + harness: 'dmux', + state: 'Adapter-backed', + supported_assets: [ + 'session snapshots', + 'tmux/worktree orchestration status', + 'handoff exports', + ], + unsupported_surfaces: ['dmux is an orchestration runtime, not an install target for skills/rules'], + install_or_onramp: [ + '`node scripts/session-inspect.js --list-adapters`', + 'dmux session target inspection', + ], + verification_commands: ['`node tests/lib/session-adapters.test.js`'], + risk_notes: ['Treat dmux events as session/runtime signals, not as a replacement for repo validation.'], + last_verified_at: '2026-05-12', + owner: 'ECC maintainers', + source_docs: [ + 'scripts/lib/session-adapters/dmux-tmux.js', + 'scripts/orchestration-status.js', + 'tests/lib/session-adapters.test.js', + ], + }, + { + id: 'orca', + harness: 'Orca', + state: 'Reference-only', + supported_assets: [ + 'worktree lifecycle', + 'review state', + 'notification', + 'provider-identity design pressure', + ], + unsupported_surfaces: ['No ECC installer or direct adapter today'], + install_or_onramp: ['Use as a comparison target for worktree/session state requirements'], + verification_commands: ['`npm run observability:ready`'], + risk_notes: ['Do not import product-specific assumptions; convert lessons into ECC event fields.'], + last_verified_at: '2026-05-12', + owner: 'ECC maintainers', + source_docs: ['docs/architecture/cross-harness.md'], + }, + { + id: 'superset', + harness: 'Superset', + state: 'Reference-only', + supported_assets: [ + 'workspace presets', + 'parallel-agent review loops', + 'worktree isolation design pressure', + ], + unsupported_surfaces: ['No ECC installer or direct adapter today'], + install_or_onramp: ['Use as a comparison target for workspace preset taxonomy'], + verification_commands: ['`npm run observability:ready`'], + risk_notes: ['Keep ECC portable; do not require a desktop workspace to get basic value.'], + last_verified_at: '2026-05-12', + owner: 'ECC maintainers', + source_docs: ['docs/architecture/cross-harness.md'], + }, + { + id: 'ghast', + harness: 'Ghast', + state: 'Reference-only', + supported_assets: [ + 'terminal-native pane grouping', + 'cwd grouping', + 'search', + 'notifications', + ], + unsupported_surfaces: ['No ECC installer or direct adapter today'], + install_or_onramp: ['Use as a comparison target for terminal-first session grouping'], + verification_commands: ['`node scripts/session-inspect.js --list-adapters`'], + risk_notes: ['Preserve terminal ergonomics before adding visual UI assumptions.'], + last_verified_at: '2026-05-12', + owner: 'ECC maintainers', + source_docs: ['docs/architecture/cross-harness.md'], + }, + { + id: 'terminal-only', + harness: 'Terminal-only', + state: 'Native', + supported_assets: [ + 'skills', + 'rules', + 'commands', + 'scripts', + 'harness audit', + 'observability readiness', + 'handoffs', + ], + unsupported_surfaces: ['No external UI, no automatic session control unless scripts are run explicitly'], + install_or_onramp: [ + 'Clone repo', + 'run commands directly', + 'use minimal profile for project installs', + ], + verification_commands: [ + '`npm run harness:audit -- --format json`', + '`npm run observability:ready`', + ], + risk_notes: ['This is the fallback contract; every higher-level adapter should degrade to it.'], + last_verified_at: '2026-05-12', + owner: 'ECC maintainers', + source_docs: [ + 'scripts/harness-audit.js', + 'scripts/observability-readiness.js', + 'docs/architecture/observability-readiness.md', + ], + }, +].map(freezeRecord)); + +function toTextList(value) { + return Array.isArray(value) ? value.join('; ') : String(value || ''); +} + +function escapeMarkdownCell(value) { + return toTextList(value).replace(/\|/g, '\\|').trim(); +} + +function renderMarkdownTable(records = ADAPTER_RECORDS) { + const lines = [ + '| Harness or runtime | State | Supported assets | Unsupported or different surfaces | Install or onramp | Verification command | Risk notes |', + '| --- | --- | --- | --- | --- | --- | --- |', + ]; + + for (const record of records) { + lines.push([ + record.harness, + record.state, + record.supported_assets, + record.unsupported_surfaces, + record.install_or_onramp, + record.verification_commands, + record.risk_notes, + ].map(escapeMarkdownCell).join(' | ').replace(/^/, '| ').replace(/$/, ' |')); + } + + return lines.join('\n'); +} + +function renderStateTable() { + const lines = [ + '| State | Meaning |', + '| --- | --- |', + ]; + + for (const [state, meaning] of Object.entries(COMPLIANCE_STATES)) { + lines.push(`| ${escapeMarkdownCell(state)} | ${escapeMarkdownCell(meaning)} |`); + } + + return lines.join('\n'); +} + +function validateAdapterRecords(records = ADAPTER_RECORDS) { + const errors = []; + const ids = new Set(); + + records.forEach((record, index) => { + const label = record?.id || `record[${index}]`; + + for (const field of REQUIRED_FIELDS) { + if (!Object.prototype.hasOwnProperty.call(record, field)) { + errors.push(`${label}: missing required field ${field}`); + } + } + + if (typeof record.id !== 'string' || !/^[a-z0-9-]+$/.test(record.id)) { + errors.push(`${label}: id must be a lowercase slug`); + } else if (ids.has(record.id)) { + errors.push(`${label}: duplicate id`); + } else { + ids.add(record.id); + } + + if (!Object.prototype.hasOwnProperty.call(COMPLIANCE_STATES, record.state)) { + errors.push(`${label}: unknown state ${record.state}`); + } + + for (const field of [ + 'supported_assets', + 'unsupported_surfaces', + 'install_or_onramp', + 'verification_commands', + 'risk_notes', + 'source_docs', + ]) { + if (!Array.isArray(record[field]) || record[field].length === 0) { + errors.push(`${label}: ${field} must be a non-empty array`); + continue; + } + + record[field].forEach((value, valueIndex) => { + if (typeof value !== 'string' || !value.trim()) { + errors.push(`${label}: ${field}[${valueIndex}] must be a non-empty string`); + } + }); + } + + if (typeof record.harness !== 'string' || !record.harness.trim()) { + errors.push(`${label}: harness must be a non-empty string`); + } + + if (typeof record.owner !== 'string' || !record.owner.trim()) { + errors.push(`${label}: owner must be a non-empty string`); + } + + if (typeof record.last_verified_at !== 'string' || !/^\d{4}-\d{2}-\d{2}$/.test(record.last_verified_at)) { + errors.push(`${label}: last_verified_at must be YYYY-MM-DD`); + } + }); + + return errors; +} + +function extractMatrixBlock(markdown) { + const normalized = String(markdown).replace(/\r\n/g, '\n'); + const start = normalized.indexOf(MATRIX_BLOCK_START); + const end = normalized.indexOf(MATRIX_BLOCK_END); + + if (start < 0 || end < 0 || end <= start) { + return null; + } + + return normalized.slice(start + MATRIX_BLOCK_START.length, end).trim(); +} + +function validateDocumentation(options = {}) { + const repoRoot = options.repoRoot || path.resolve(__dirname, '..', '..'); + const docPath = options.docPath || path.join(repoRoot, 'docs', 'architecture', 'harness-adapter-compliance.md'); + const errors = []; + const source = fs.readFileSync(docPath, 'utf8'); + const actual = extractMatrixBlock(source); + const expected = renderMarkdownTable(); + + if (actual === null) { + errors.push(`missing matrix block markers in ${path.relative(repoRoot, docPath)}`); + } else if (actual !== expected) { + errors.push(`matrix block in ${path.relative(repoRoot, docPath)} is not generated from adapter records`); + } + + return errors; +} + +module.exports = { + ADAPTER_RECORDS, + COMPLIANCE_STATES, + MATRIX_BLOCK_END, + MATRIX_BLOCK_START, + REQUIRED_FIELDS, + extractMatrixBlock, + renderMarkdownTable, + renderStateTable, + validateAdapterRecords, + validateDocumentation, +}; diff --git a/github_code/affaan-m__ECC/scripts/lib/harness-capabilities.js b/github_code/affaan-m__ECC/scripts/lib/harness-capabilities.js new file mode 100644 index 0000000000000000000000000000000000000000..c42f0488e70fd1ad57b7d5bf00073fea20ee36a1 --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/harness-capabilities.js @@ -0,0 +1,374 @@ +const path = require('path'); + +const { SUPPORTED_INSTALL_TARGETS } = require('./install-manifests'); +const { listInstallTargetAdapters } = require('./install-targets/registry'); + +function deepFreeze(value) { + if (!value || typeof value !== 'object' || Object.isFrozen(value)) { + return value; + } + + for (const child of Object.values(value)) { + deepFreeze(child); + } + + return Object.freeze(value); +} + +function scope(id, targetId, root) { + return { id, targetId, root }; +} + +function hooks(mode, eccConfigured, note) { + return { + mode, + eccConfigured, + note, + summary: note, + }; +} + +const HARNESS_CAPABILITIES = deepFreeze([ + { + id: 'claude', + label: 'Claude Code', + targetIds: ['claude', 'claude-project'], + channel: 'native-plugin', + installMode: 'native-plugin', + guidedReady: true, + availability: 'guided', + destination: 'Selected Claude plugin scope: ~/.claude or ./.claude', + scopes: [ + scope('user', 'claude', '~/.claude'), + scope('project', 'claude-project', './.claude'), + scope('local', 'claude-project', './.claude'), + ], + hooks: hooks( + 'profile-selection', + true, + 'ECC hooks are configured through the selected off, minimal, standard, or strict profile.' + ), + aliases: ['claude-code'], + }, + { + id: 'codex', + label: 'Codex', + targetIds: ['codex'], + channel: 'native-plugin', + installMode: 'native-plugin', + guidedReady: true, + availability: 'guided', + destination: '~/.codex through the Codex native plugin lifecycle', + scopes: [scope('native', 'codex', '~/.codex')], + hooks: hooks( + 'native-trust', + true, + 'ECC hooks use Codex native plugin discovery and remain subject to Codex review and trust.' + ), + aliases: ['openai-codex'], + }, + { + id: 'kimi', + label: 'Kimi Code', + targetIds: ['kimi'], + channel: 'managed-project', + installMode: 'managed-project', + guidedReady: true, + availability: 'guided', + destination: './.kimi-code', + scopes: [scope('project', 'kimi', './.kimi-code')], + hooks: hooks( + 'not-configured', + false, + 'ECC hooks are not configured for the Kimi managed-project install.' + ), + aliases: ['kimi-code'], + }, + { + id: 'cursor', + label: 'Cursor', + targetIds: ['cursor'], + channel: 'managed-project', + installMode: 'managed-project', + guidedReady: false, + availability: 'advanced', + destination: './.cursor', + scopes: [scope('project', 'cursor', './.cursor')], + hooks: hooks( + 'adapter-configured', + true, + 'ECC hooks use the Cursor project adapter and Cursor event configuration.' + ), + aliases: [], + }, + { + id: 'antigravity', + label: 'Antigravity', + targetIds: ['antigravity'], + channel: 'managed-project', + installMode: 'managed-project', + guidedReady: false, + availability: 'advanced', + destination: './.agents', + scopes: [scope('project', 'antigravity', './.agents')], + hooks: hooks('not-configured', false, 'ECC hooks are not configured by this adapter.'), + aliases: ['google-antigravity'], + }, + { + id: 'gemini', + label: 'Gemini CLI', + targetIds: ['gemini'], + channel: 'managed-project', + installMode: 'managed-project', + guidedReady: false, + availability: 'advanced', + destination: './.gemini', + scopes: [scope('project', 'gemini', './.gemini')], + hooks: hooks('not-configured', false, 'ECC hooks are not configured by this adapter.'), + aliases: ['gemini-cli'], + }, + { + id: 'opencode', + label: 'OpenCode', + targetIds: ['opencode'], + channel: 'managed-home', + installMode: 'managed-home', + guidedReady: false, + availability: 'advanced', + destination: '~/.config/opencode', + destinationResolution: 'OPENCODE_CONFIG_DIR, then XDG_CONFIG_HOME/opencode, then ~/.config/opencode', + scopes: [scope('home', 'opencode', '~/.config/opencode')], + hooks: hooks( + 'adapter-opt-in', + false, + 'ECC hook runtime support is available through the OpenCode adapter but is not installed by default.' + ), + aliases: ['open-code'], + }, + { + id: 'codebuddy', + label: 'CodeBuddy', + targetIds: ['codebuddy'], + channel: 'managed-project', + installMode: 'managed-project', + guidedReady: false, + availability: 'advanced', + destination: './.codebuddy', + scopes: [scope('project', 'codebuddy', './.codebuddy')], + hooks: hooks( + 'managed-files', + true, + 'ECC hook runtime files are installed through the CodeBuddy project adapter.' + ), + aliases: ['code-buddy'], + }, + { + id: 'joycode', + label: 'JoyCode', + targetIds: ['joycode'], + channel: 'managed-project', + installMode: 'managed-project', + guidedReady: false, + availability: 'advanced', + destination: './.joycode', + scopes: [scope('project', 'joycode', './.joycode')], + hooks: hooks('not-configured', false, 'ECC hooks are not configured by this adapter.'), + aliases: ['joy-code'], + }, + { + id: 'qwen', + label: 'Qwen Code', + targetIds: ['qwen'], + channel: 'managed-home', + installMode: 'managed-home', + guidedReady: false, + availability: 'advanced', + destination: '~/.qwen', + scopes: [scope('home', 'qwen', '~/.qwen')], + hooks: hooks('not-configured', false, 'ECC hooks are not configured by this adapter.'), + aliases: ['qwen-code'], + }, + { + id: 'zed', + label: 'Zed', + targetIds: ['zed'], + channel: 'managed-project', + installMode: 'managed-project', + guidedReady: false, + availability: 'advanced', + destination: './.zed', + scopes: [scope('project', 'zed', './.zed')], + hooks: hooks('not-configured', false, 'ECC hooks are not configured by this adapter.'), + aliases: [], + }, + { + id: 'adal', + label: 'AdaL CLI', + targetIds: ['adal'], + channel: 'managed-project', + installMode: 'managed-project', + guidedReady: false, + availability: 'advanced', + destination: './.adal', + scopes: [scope('project', 'adal', './.adal')], + hooks: hooks('not-configured', false, 'ECC hooks are not configured by this adapter.'), + aliases: ['adal-cli'], + }, + { + id: 'hermes', + label: 'Hermes', + targetIds: ['hermes'], + channel: 'managed-home', + installMode: 'managed-home', + guidedReady: false, + availability: 'advanced', + destination: '~/.hermes', + scopes: [scope('home', 'hermes', '~/.hermes')], + hooks: hooks('not-configured', false, 'ECC hooks are not configured by this adapter.'), + aliases: ['hermes-agent'], + }, + { + id: 'openclaw', + label: 'OpenClaw', + targetIds: ['openclaw'], + channel: 'managed-home', + installMode: 'managed-home', + guidedReady: false, + availability: 'advanced', + destination: '~/.openclaw', + scopes: [scope('home', 'openclaw', '~/.openclaw')], + hooks: hooks('not-configured', false, 'ECC hooks are not configured by this adapter.'), + aliases: ['open-claw'], + }, +]); + +const GUIDED_HARNESS_IDS = deepFreeze( + HARNESS_CAPABILITIES + .filter(harness => harness.guidedReady) + .map(harness => harness.id) +); + +function normalizeLookupToken(value) { + return String(value).trim().toLowerCase().replace(/[\s_]+/g, '-'); +} + +const LOOKUP = new Map(); +for (const harness of HARNESS_CAPABILITIES) { + const keys = [harness.id, harness.label, ...harness.targetIds, ...harness.aliases]; + for (const key of keys) { + LOOKUP.set(normalizeLookupToken(key), harness); + } +} + +function expectedRootForAdapter(adapter) { + const homeDir = path.resolve('/__ecc_catalog_home__'); + const projectRoot = path.resolve('/__ecc_catalog_project__'); + const absoluteRoot = adapter.resolveRoot({ homeDir, projectRoot, env: {} }); + const baseRoot = adapter.kind === 'home' ? homeDir : projectRoot; + const prefix = adapter.kind === 'home' ? '~/' : './'; + return `${prefix}${path.relative(baseRoot, absoluteRoot).replace(/\\/g, '/')}`; +} + +function validateCatalog() { + const adapters = listInstallTargetAdapters(); + const adapterByTarget = new Map(adapters.map(adapter => [adapter.target, adapter])); + const catalogTargetIds = HARNESS_CAPABILITIES.flatMap(harness => harness.targetIds); + + if (new Set(catalogTargetIds).size !== catalogTargetIds.length) { + throw new Error('Harness capability catalog contains duplicate install target ids'); + } + + const supported = [...SUPPORTED_INSTALL_TARGETS].sort(); + const registered = adapters.map(adapter => adapter.target).sort(); + const catalogued = [...catalogTargetIds].sort(); + if ( + JSON.stringify(catalogued) !== JSON.stringify(supported) + || JSON.stringify(catalogued) !== JSON.stringify(registered) + ) { + throw new Error('Harness capability catalog is out of sync with install targets'); + } + + for (const harness of HARNESS_CAPABILITIES) { + for (const declaredScope of harness.scopes) { + const adapter = adapterByTarget.get(declaredScope.targetId); + if (!adapter || expectedRootForAdapter(adapter) !== declaredScope.root) { + throw new Error( + `Harness capability root is out of sync for target ${declaredScope.targetId}` + ); + } + } + } +} + +validateCatalog(); + +function listHarnessCapabilities() { + return HARNESS_CAPABILITIES.slice(); +} + +function listGuidedHarnesses() { + return GUIDED_HARNESS_IDS.map(id => LOOKUP.get(id)); +} + +function getHarnessCapability(value) { + if (typeof value !== 'string' || value.trim() === '') { + return null; + } + + return LOOKUP.get(normalizeLookupToken(value)) || null; +} + +function tokenizeSelection(selection) { + const values = Array.isArray(selection) ? selection : [selection]; + return values.flatMap(value => ( + typeof value === 'string' ? value.split(',') : [] + )).map(value => value.trim()).filter(Boolean); +} + +function normalizeHarnessSelection(selection) { + const tokens = tokenizeSelection(selection); + if (tokens.length === 0 || tokens.every(token => normalizeLookupToken(token) === 'none')) { + throw new Error('At least one guided harness must be selected'); + } + + const allTokens = tokens.filter(token => ['all', '*'].includes(normalizeLookupToken(token))); + const explicitTokens = tokens.filter(token => !['all', '*'].includes(normalizeLookupToken(token))); + if (allTokens.length > 0 && explicitTokens.length > 0) { + throw new Error('The all/* harness selection cannot be combined with other selections'); + } + if (allTokens.length > 0) { + return GUIDED_HARNESS_IDS.slice(); + } + + const selected = new Set(); + for (const token of tokens) { + const normalizedToken = normalizeLookupToken(token); + const menuIndex = /^\d+$/.test(normalizedToken) ? Number(normalizedToken) - 1 : -1; + const harness = menuIndex >= 0 + ? listGuidedHarnesses()[menuIndex] || null + : getHarnessCapability(token); + + if (!harness) { + throw new Error(`Unknown guided harness selection: ${token}`); + } + if (!harness.guidedReady) { + throw new Error(`${harness.label} is an advanced harness and is not guided-ready`); + } + selected.add(harness.id); + } + + if (selected.size === 0) { + throw new Error('At least one guided harness must be selected'); + } + + return GUIDED_HARNESS_IDS.filter(id => selected.has(id)); +} + +module.exports = { + GUIDED_HARNESS_IDS, + HARNESS_CAPABILITIES, + getHarnessCapability, + listGuidedHarnesses, + listHarnessCapabilities, + normalizeHarnessSelection, +}; diff --git a/github_code/affaan-m__ECC/scripts/lib/hook-flags.js b/github_code/affaan-m__ECC/scripts/lib/hook-flags.js new file mode 100644 index 0000000000000000000000000000000000000000..69d3f25d6ba5d49acdebed943352674f87caa5c3 --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/hook-flags.js @@ -0,0 +1,153 @@ +#!/usr/bin/env node +/** + * Shared hook enable/disable controls. + * + * Controls: + * - ECC_HOOKS_ENABLED=true|false (default: true) + * - ECC_HOOK_PROFILE=minimal|standard|strict (default: standard) + * - ECC_DISABLED_HOOKS=comma,separated,hook,ids + * + * Claude plugin options are used when their corresponding ECC variable is + * absent. A managed install can provide ecc/setup.json as the final fallback. + */ + +'use strict'; + +const fs = require('fs'); +const path = require('path'); + +const VALID_PROFILES = new Set(['minimal', 'standard', 'strict']); + +function normalizeId(value) { + return String(value || '').trim().toLowerCase(); +} + +function parseBoolean(value, fallback = true) { + if (value === undefined || value === null || String(value).trim() === '') { + return fallback; + } + const normalized = String(value).trim().toLowerCase(); + if (['1', 'true', 'yes', 'on'].includes(normalized)) return true; + if (['0', 'false', 'no', 'off'].includes(normalized)) return false; + return fallback; +} + +function sanitizeDiagnostic(value) { + return String(value || '') + // eslint-disable-next-line no-control-regex + .replace(/\x1b(?:\[[0-9;?]*[A-Za-z]|\][^\x07\x1b]*(?:\x07|\x1b\\)|\([A-Z]|[A-Z])/g, '') + .replace(/[^\x20-\x7E]/g, '?'); +} + +function readManagedHookConfig(env = process.env) { + const pluginRoot = String( + env.CLAUDE_PLUGIN_ROOT || env.ECC_PLUGIN_ROOT || '' + ).trim(); + const configPath = String(env.ECC_HOOK_CONFIG || '').trim() + || (pluginRoot ? path.join(pluginRoot, 'ecc', 'setup.json') : ''); + if (!configPath || !fs.existsSync(configPath)) return {}; + + try { + const config = JSON.parse(fs.readFileSync(configPath, 'utf8')); + return config?.hooks + && typeof config.hooks === 'object' + && !Array.isArray(config.hooks) + ? config.hooks + : {}; + } catch (error) { + process.stderr.write(`${sanitizeDiagnostic( + `Warning: unable to read managed ECC hook config at ${configPath}: ${error.message}` + )}\n`); + return {}; + } +} + +function areHooksEnabled(env = process.env, managed = readManagedHookConfig(env)) { + const raw = env.ECC_HOOKS_ENABLED !== undefined + ? env.ECC_HOOKS_ENABLED + : ( + env.CLAUDE_PLUGIN_OPTION_HOOKS_ENABLED !== undefined + ? env.CLAUDE_PLUGIN_OPTION_HOOKS_ENABLED + : managed.enabled + ); + return parseBoolean(raw, true); +} + +function getHookProfile(env = process.env, managed = readManagedHookConfig(env)) { + const selected = env.ECC_HOOK_PROFILE !== undefined + ? env.ECC_HOOK_PROFILE + : ( + env.CLAUDE_PLUGIN_OPTION_HOOK_PROFILE !== undefined + ? env.CLAUDE_PLUGIN_OPTION_HOOK_PROFILE + : managed.profile + ); + const raw = String(selected ?? 'standard').trim().toLowerCase(); + return VALID_PROFILES.has(raw) ? raw : 'standard'; +} + +function getDisabledHookIds(env = process.env) { + const raw = String(env.ECC_DISABLED_HOOKS || ''); + if (!raw.trim()) return new Set(); + + return new Set( + raw + .split(',') + .map(v => normalizeId(v)) + .filter(Boolean) + ); +} + +function parseProfiles(rawProfiles, fallback = ['standard', 'strict']) { + if (!rawProfiles) return [...fallback]; + + if (Array.isArray(rawProfiles)) { + const parsed = rawProfiles + .map(v => String(v || '').trim().toLowerCase()) + .filter(v => VALID_PROFILES.has(v)); + return parsed.length > 0 ? parsed : [...fallback]; + } + + const parsed = String(rawProfiles) + .split(',') + .map(v => v.trim().toLowerCase()) + .filter(v => VALID_PROFILES.has(v)); + + return parsed.length > 0 ? parsed : [...fallback]; +} + +function isDryRun(env = process.env) { + return env.ECC_DRY_RUN === '1'; +} + +function isHookEnabled(hookId, options = {}) { + const env = options.env || process.env; + const managed = readManagedHookConfig(env); + if (!areHooksEnabled(env, managed)) { + return false; + } + + const id = normalizeId(hookId); + if (!id) return true; + + const disabled = getDisabledHookIds(env); + if (disabled.has(id)) { + return false; + } + + const profile = getHookProfile(env, managed); + const allowedProfiles = parseProfiles(options.profiles); + return allowedProfiles.includes(profile); +} + +module.exports = { + VALID_PROFILES, + normalizeId, + parseBoolean, + readManagedHookConfig, + areHooksEnabled, + getHookProfile, + getDisabledHookIds, + parseProfiles, + isHookEnabled, + isDryRun, +}; diff --git a/github_code/affaan-m__ECC/scripts/lib/inspection.js b/github_code/affaan-m__ECC/scripts/lib/inspection.js new file mode 100644 index 0000000000000000000000000000000000000000..e6f2cdf338c959da36547d13e4d8733480169f97 --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/inspection.js @@ -0,0 +1,212 @@ +'use strict'; + +const DEFAULT_FAILURE_THRESHOLD = 3; +const DEFAULT_WINDOW_SIZE = 50; + +const FAILURE_OUTCOMES = new Set(['failure', 'failed', 'error']); + +/** + * Normalize a failure reason string for grouping. + * Strips timestamps, UUIDs, file paths, and numeric suffixes. + */ +function normalizeFailureReason(reason) { + if (!reason || typeof reason !== 'string') { + return 'unknown'; + } + + return reason + .trim() + .toLowerCase() + // Strip ISO timestamps (note: already lowercased, so t/z not T/Z) + .replace(/\d{4}-\d{2}-\d{2}[t ]\d{2}:\d{2}:\d{2}[.\dz]*/g, '') + // Strip UUIDs (already lowercased) + .replace(/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/g, '') + // Strip file paths + .replace(/\/[\w./-]+/g, '') + // Collapse whitespace + .replace(/\s+/g, ' ') + .trim(); +} + +/** + * Group skill runs by skill ID and normalized failure reason. + * + * @param {Array} skillRuns - Array of skill run objects + * @returns {Map} + */ +function groupFailures(skillRuns) { + const groups = new Map(); + + for (const run of skillRuns) { + const outcome = String(run.outcome || '').toLowerCase(); + if (!FAILURE_OUTCOMES.has(outcome)) { + continue; + } + + const normalizedReason = normalizeFailureReason(run.failureReason); + const key = `${run.skillId}::${normalizedReason}`; + + if (!groups.has(key)) { + groups.set(key, { + skillId: run.skillId, + normalizedReason, + runs: [], + }); + } + + groups.get(key).runs.push(run); + } + + return groups; +} + +/** + * Detect recurring failure patterns from skill runs. + * + * @param {Array} skillRuns - Array of skill run objects (newest first) + * @param {Object} [options] + * @param {number} [options.threshold=3] - Minimum failure count to trigger pattern detection + * @returns {Array} Array of detected patterns sorted by count descending + */ +function detectPatterns(skillRuns, options = {}) { + const threshold = options.threshold ?? DEFAULT_FAILURE_THRESHOLD; + const groups = groupFailures(skillRuns); + const patterns = []; + + for (const [, group] of groups) { + if (group.runs.length < threshold) { + continue; + } + + const sortedRuns = [...group.runs].sort( + (a, b) => (b.createdAt || '').localeCompare(a.createdAt || '') + ); + + const firstSeen = sortedRuns[sortedRuns.length - 1].createdAt || null; + const lastSeen = sortedRuns[0].createdAt || null; + const sessionIds = [...new Set(sortedRuns.map(r => r.sessionId).filter(Boolean))]; + const versions = [...new Set(sortedRuns.map(r => r.skillVersion).filter(Boolean))]; + + // Collect unique raw failure reasons for this normalized group + const rawReasons = [...new Set(sortedRuns.map(r => r.failureReason).filter(Boolean))]; + + patterns.push({ + skillId: group.skillId, + normalizedReason: group.normalizedReason, + count: group.runs.length, + firstSeen, + lastSeen, + sessionIds, + versions, + rawReasons, + runIds: sortedRuns.map(r => r.id), + }); + } + + // Sort by count descending, then by lastSeen descending + return patterns.sort((a, b) => { + if (b.count !== a.count) return b.count - a.count; + return (b.lastSeen || '').localeCompare(a.lastSeen || ''); + }); +} + +/** + * Generate an inspection report from detected patterns. + * + * @param {Array} patterns - Output from detectPatterns() + * @param {Object} [options] + * @param {string} [options.generatedAt] - ISO timestamp for the report + * @returns {Object} Inspection report + */ +function generateReport(patterns, options = {}) { + const generatedAt = options.generatedAt || new Date().toISOString(); + + if (patterns.length === 0) { + return { + generatedAt, + status: 'clean', + patternCount: 0, + patterns: [], + summary: 'No recurring failure patterns detected.', + }; + } + + const totalFailures = patterns.reduce((sum, p) => sum + p.count, 0); + const affectedSkills = [...new Set(patterns.map(p => p.skillId))]; + + return { + generatedAt, + status: 'attention_needed', + patternCount: patterns.length, + totalFailures, + affectedSkills, + patterns: patterns.map(p => ({ + skillId: p.skillId, + normalizedReason: p.normalizedReason, + count: p.count, + firstSeen: p.firstSeen, + lastSeen: p.lastSeen, + sessionIds: p.sessionIds, + versions: p.versions, + rawReasons: p.rawReasons.slice(0, 5), + suggestedAction: suggestAction(p), + })), + summary: `Found ${patterns.length} recurring failure pattern(s) across ${affectedSkills.length} skill(s) (${totalFailures} total failures).`, + }; +} + +/** + * Suggest a remediation action based on pattern characteristics. + */ +function suggestAction(pattern) { + const reason = pattern.normalizedReason; + + if (reason.includes('timeout')) { + return 'Increase timeout or optimize skill execution time.'; + } + if (reason.includes('permission') || reason.includes('denied') || reason.includes('auth')) { + return 'Check tool permissions and authentication configuration.'; + } + if (reason.includes('not found') || reason.includes('missing')) { + return 'Verify required files/dependencies exist before skill execution.'; + } + if (reason.includes('parse') || reason.includes('syntax') || reason.includes('json')) { + return 'Review input/output format expectations and add validation.'; + } + if (pattern.versions.length > 1) { + return 'Failure spans multiple versions. Consider rollback to last stable version.'; + } + + return 'Investigate root cause and consider adding error handling.'; +} + +/** + * Run full inspection pipeline: query skill runs, detect patterns, generate report. + * + * @param {Object} store - State store instance with listRecentSessions, getSessionDetail + * @param {Object} [options] + * @param {number} [options.threshold] - Minimum failure count + * @param {number} [options.windowSize] - Number of recent skill runs to analyze + * @returns {Object} Inspection report + */ +function inspect(store, options = {}) { + const windowSize = options.windowSize ?? DEFAULT_WINDOW_SIZE; + const threshold = options.threshold ?? DEFAULT_FAILURE_THRESHOLD; + + const status = store.getStatus({ recentSkillRunLimit: windowSize }); + const skillRuns = status.skillRuns.recent || []; + + const patterns = detectPatterns(skillRuns, { threshold }); + return generateReport(patterns, { generatedAt: status.generatedAt }); +} + +module.exports = { + DEFAULT_FAILURE_THRESHOLD, + DEFAULT_WINDOW_SIZE, + detectPatterns, + generateReport, + groupFailures, + inspect, + normalizeFailureReason, + suggestAction, +}; diff --git a/github_code/affaan-m__ECC/scripts/lib/install-executor.js b/github_code/affaan-m__ECC/scripts/lib/install-executor.js new file mode 100644 index 0000000000000000000000000000000000000000..72eac5e8a9868ac1632121977c1281c026afe50b --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/install-executor.js @@ -0,0 +1,571 @@ +const fs = require('fs'); +const os = require('os'); +const path = require('path'); + +const { toCursorAgentRelativePath } = require('./cursor-agent-names'); +const { LEGACY_INSTALL_TARGETS, parseInstallArgs } = require('./install/request'); +const { + buildCopyFileOperation, + createManifestInstallPlan, + createStatePreview, + dedupeCopyFileOperations, + getManifestVersion, + getPackageVersion, + getRepoCommit, + getSourceRoot, + listFilesRecursive, + readJsonObject, +} = require('./install/plan'); +const { SUPPORTED_INSTALL_TARGETS, listLegacyCompatibilityLanguages, resolveLegacyCompatibilitySelection } = require('./install-manifests'); +const { getInstallTargetAdapter } = require('./install-targets/registry'); +const { resolveInvocationEnvironment } = require('./invocation-environment'); + +const LANGUAGE_NAME_PATTERN = /^[a-zA-Z0-9_-]+$/; +const CLAUDE_ECC_NAMESPACE = 'ecc'; + +function readDirectoryNames(dirPath) { + if (!fs.existsSync(dirPath)) { + return []; + } + + return fs + .readdirSync(dirPath, { withFileTypes: true }) + .filter(entry => entry.isDirectory()) + .map(entry => entry.name) + .sort(); +} + +function listAvailableLanguages(sourceRoot = getSourceRoot()) { + return [...new Set([...listLegacyCompatibilityLanguages(), ...readDirectoryNames(path.join(sourceRoot, 'rules')).filter(name => name !== 'common')])].sort(); +} + +function validateLegacyTarget(target) { + if (LEGACY_INSTALL_TARGETS.includes(target)) { + return; + } + // A target can be fully supported yet not installable via the bare-language + // positional syntax (which is legacy-only). Guide the user to the right mode + // instead of implying the target is unknown (#2282). + if (SUPPORTED_INSTALL_TARGETS.includes(target)) { + throw new Error( + `Target '${target}' is supported, but the bare-language install syntax only accepts ${LEGACY_INSTALL_TARGETS.join(', ')}. ` + + `Install '${target}' with a component selection instead, e.g. \`install.sh --target ${target} --profile full\` ` + + `(or --modules / --skills ).` + ); + } + throw new Error(`Unknown install target: ${target}. Expected one of ${SUPPORTED_INSTALL_TARGETS.join(', ')}`); +} + +function applyInstallPlan(plan, dependencies = {}) { + const { applyInstallPlan: applyPlan } = require('./install/apply'); + return applyPlan(plan, dependencies); +} + +function previewInstallPlan(plan) { + const { previewInstallPlan: previewPlan } = require('./install/apply'); + return previewPlan(plan); +} + +function addRecursiveCopyOperations(operations, options) { + const sourceDir = path.join(options.sourceRoot, options.sourceRelativeDir); + if (!fs.existsSync(sourceDir)) { + return 0; + } + + const relativeFiles = listFilesRecursive(sourceDir); + + for (const relativeFile of relativeFiles) { + const sourceRelativePath = path.join(options.sourceRelativeDir, relativeFile); + const sourcePath = path.join(options.sourceRoot, sourceRelativePath); + const destinationRelativePath = typeof options.destinationRelativePathTransform === 'function' ? options.destinationRelativePathTransform(relativeFile, sourceRelativePath) : relativeFile; + if (!destinationRelativePath) { + continue; + } + const destinationPath = path.join(options.destinationDir, destinationRelativePath); + operations.push( + buildCopyFileOperation({ + moduleId: options.moduleId, + sourcePath, + sourceRelativePath, + destinationPath, + strategy: options.strategy || 'preserve-relative-path', + contentTransform: options.contentTransform, + }) + ); + } + + return relativeFiles.length; +} + +function addFileCopyOperation(operations, options) { + const sourcePath = path.join(options.sourceRoot, options.sourceRelativePath); + if (!fs.existsSync(sourcePath)) { + return false; + } + + operations.push( + buildCopyFileOperation({ + moduleId: options.moduleId, + sourcePath, + sourceRelativePath: options.sourceRelativePath, + destinationPath: options.destinationPath, + strategy: options.strategy || 'preserve-relative-path' + }) + ); + + return true; +} + +function addCursorAgentDataScaffoldOperations(operations, options) { + const scaffoldRoot = path.join(options.sourceRoot, 'scaffolds', 'cursor'); + if (!fs.existsSync(scaffoldRoot)) { + return; + } + + addFileCopyOperation(operations, { + moduleId: options.moduleId, + sourceRoot: options.sourceRoot, + sourceRelativePath: path.join('scaffolds', 'cursor', 'ecc-agent-data.json'), + destinationPath: path.join(options.targetRoot, 'ecc-agent-data.json'), + strategy: 'preserve-relative-path' + }); + + addFileCopyOperation(operations, { + moduleId: options.moduleId, + sourceRoot: options.sourceRoot, + sourceRelativePath: path.join('scaffolds', 'cursor', 'rules', 'ecc-agent-data-home.mdc'), + destinationPath: path.join(options.targetRoot, 'rules', 'ecc-agent-data-home.mdc'), + strategy: 'preserve-relative-path' + }); + + addJsonMergeOperation(operations, { + moduleId: options.moduleId, + sourceRoot: options.sourceRoot, + sourceRelativePath: path.join('scaffolds', 'cursor', 'hooks.json'), + destinationPath: path.join(options.targetRoot, 'hooks.json') + }); + + const cursorSessionHookDeps = [path.join('scripts', 'hooks', 'cursor-session-env.js'), path.join('scripts', 'lib', 'agent-data-home.js'), path.join('scripts', 'lib', 'utils.js')]; + + for (const sourceRelativePath of cursorSessionHookDeps) { + addFileCopyOperation(operations, { + moduleId: options.moduleId, + sourceRoot: options.sourceRoot, + sourceRelativePath, + destinationPath: path.join(options.targetRoot, sourceRelativePath), + strategy: 'preserve-relative-path' + }); + } +} + +function addJsonMergeOperation(operations, options) { + const sourcePath = path.join(options.sourceRoot, options.sourceRelativePath); + if (!fs.existsSync(sourcePath)) { + return false; + } + + operations.push({ + kind: 'merge-json', + moduleId: options.moduleId, + sourceRelativePath: options.sourceRelativePath, + destinationPath: options.destinationPath, + strategy: 'merge-json', + ownership: 'managed', + scaffoldOnly: false, + mergePayload: readJsonObject(sourcePath, options.sourceRelativePath) + }); + + return true; +} + +function addMatchingRuleOperations(operations, options) { + const sourceDir = path.join(options.sourceRoot, options.sourceRelativeDir); + if (!fs.existsSync(sourceDir)) { + return 0; + } + + const files = fs + .readdirSync(sourceDir, { withFileTypes: true }) + .filter(entry => entry.isFile() && options.matcher(entry.name)) + .map(entry => entry.name) + .sort(); + + for (const fileName of files) { + const sourceRelativePath = path.join(options.sourceRelativeDir, fileName); + const sourcePath = path.join(options.sourceRoot, sourceRelativePath); + const destinationPath = path.join(options.destinationDir, options.rename ? options.rename(fileName) : fileName); + + operations.push( + buildCopyFileOperation({ + moduleId: options.moduleId, + sourcePath, + sourceRelativePath, + destinationPath, + strategy: options.strategy || 'flatten-copy' + }) + ); + } + + return files.length; +} + +function isDirectoryNonEmpty(dirPath) { + return fs.existsSync(dirPath) && fs.statSync(dirPath).isDirectory() && fs.readdirSync(dirPath).length > 0; +} + +function planClaudeStyleLegacyInstall(context, { adapterId, adapterRootInput, rulesDir: rulesDirOverride }) { + const adapter = getInstallTargetAdapter(adapterId); + const targetRoot = adapter.resolveRoot(adapterRootInput); + const rulesDir = rulesDirOverride || path.join(targetRoot, 'rules', CLAUDE_ECC_NAMESPACE); + const installStatePath = adapter.getInstallStatePath(adapterRootInput); + const operations = []; + const warnings = []; + + if (isDirectoryNonEmpty(rulesDir)) { + warnings.push(`Destination ${rulesDir}/ already exists and files may be overwritten`); + } + + addRecursiveCopyOperations(operations, { + moduleId: 'legacy-claude-rules', + sourceRoot: context.sourceRoot, + sourceRelativeDir: path.join('rules', 'common'), + destinationDir: path.join(rulesDir, 'common') + }); + + for (const language of context.languages) { + if (!LANGUAGE_NAME_PATTERN.test(language)) { + warnings.push(`Invalid language name '${language}'. Only alphanumeric, dash, and underscore are allowed`); + continue; + } + + const sourceDir = path.join(context.sourceRoot, 'rules', language); + if (!fs.existsSync(sourceDir)) { + warnings.push(`rules/${language}/ does not exist, skipping`); + continue; + } + + addRecursiveCopyOperations(operations, { + moduleId: 'legacy-claude-rules', + sourceRoot: context.sourceRoot, + sourceRelativeDir: path.join('rules', language), + destinationDir: path.join(rulesDir, language) + }); + } + + return { + mode: 'legacy', + sourceRoot: context.sourceRoot, + adapter, + target: adapterId, + targetRoot, + installRoot: rulesDir, + installStatePath, + operations, + warnings, + selectedModules: ['legacy-claude-rules'] + }; +} + +function planClaudeLegacyInstall(context) { + return planClaudeStyleLegacyInstall(context, { + adapterId: 'claude', + adapterRootInput: { homeDir: context.homeDir }, + rulesDir: context.claudeRulesDir || null + }); +} + +function planClaudeProjectLegacyInstall(context) { + return planClaudeStyleLegacyInstall(context, { + adapterId: 'claude-project', + adapterRootInput: { repoRoot: context.projectRoot }, + rulesDir: null + }); +} + +function planCursorLegacyInstall(context) { + const adapter = getInstallTargetAdapter('cursor'); + const targetRoot = adapter.resolveRoot({ repoRoot: context.projectRoot }); + const installStatePath = adapter.getInstallStatePath({ repoRoot: context.projectRoot }); + const operations = []; + const warnings = []; + + addMatchingRuleOperations(operations, { + moduleId: 'legacy-cursor-install', + sourceRoot: context.sourceRoot, + sourceRelativeDir: path.join('.cursor', 'rules'), + destinationDir: path.join(targetRoot, 'rules'), + matcher: fileName => /^common-.*\.md$/.test(fileName) + }); + + for (const language of context.languages) { + if (!LANGUAGE_NAME_PATTERN.test(language)) { + warnings.push(`Invalid language name '${language}'. Only alphanumeric, dash, and underscore are allowed`); + continue; + } + + const matches = addMatchingRuleOperations(operations, { + moduleId: 'legacy-cursor-install', + sourceRoot: context.sourceRoot, + sourceRelativeDir: path.join('.cursor', 'rules'), + destinationDir: path.join(targetRoot, 'rules'), + matcher: fileName => fileName.startsWith(`${language}-`) && fileName.endsWith('.md') + }); + + if (matches === 0) { + warnings.push(`No Cursor rules for '${language}' found, skipping`); + } + } + + addRecursiveCopyOperations(operations, { + moduleId: 'legacy-cursor-install', + sourceRoot: context.sourceRoot, + sourceRelativeDir: path.join('.cursor', 'agents'), + destinationDir: path.join(targetRoot, 'agents'), + destinationRelativePathTransform: toCursorAgentRelativePath + }); + addRecursiveCopyOperations(operations, { + moduleId: 'legacy-cursor-install', + sourceRoot: context.sourceRoot, + sourceRelativeDir: path.join('.cursor', 'skills'), + destinationDir: path.join(targetRoot, 'skills') + }); + addRecursiveCopyOperations(operations, { + moduleId: 'legacy-cursor-install', + sourceRoot: context.sourceRoot, + sourceRelativeDir: path.join('.cursor', 'commands'), + destinationDir: path.join(targetRoot, 'commands') + }); + addRecursiveCopyOperations(operations, { + moduleId: 'legacy-cursor-install', + sourceRoot: context.sourceRoot, + sourceRelativeDir: path.join('.cursor', 'hooks'), + destinationDir: path.join(targetRoot, 'hooks') + }); + + addFileCopyOperation(operations, { + moduleId: 'legacy-cursor-install', + sourceRoot: context.sourceRoot, + sourceRelativePath: path.join('.cursor', 'hooks.json'), + destinationPath: path.join(targetRoot, 'hooks.json') + }); + addJsonMergeOperation(operations, { + moduleId: 'legacy-cursor-install', + sourceRoot: context.sourceRoot, + sourceRelativePath: '.mcp.json', + destinationPath: path.join(targetRoot, 'mcp.json') + }); + + addCursorAgentDataScaffoldOperations(operations, { + moduleId: 'legacy-cursor-install', + sourceRoot: context.sourceRoot, + targetRoot + }); + + return { + mode: 'legacy', + adapter, + target: 'cursor', + targetRoot, + installRoot: targetRoot, + installStatePath, + operations, + warnings, + selectedModules: ['legacy-cursor-install'] + }; +} + +function planAntigravityLegacyInstall(context) { + const adapter = getInstallTargetAdapter('antigravity'); + const targetRoot = adapter.resolveRoot({ repoRoot: context.projectRoot }); + const installStatePath = adapter.getInstallStatePath({ repoRoot: context.projectRoot }); + const operations = []; + const warnings = []; + + if (isDirectoryNonEmpty(path.join(targetRoot, 'rules'))) { + warnings.push(`Destination ${path.join(targetRoot, 'rules')}/ already exists and files may be overwritten`); + } + + addMatchingRuleOperations(operations, { + moduleId: 'legacy-antigravity-install', + sourceRoot: context.sourceRoot, + sourceRelativeDir: path.join('rules', 'common'), + destinationDir: path.join(targetRoot, 'rules'), + matcher: fileName => fileName.endsWith('.md'), + rename: fileName => `common-${fileName}` + }); + + for (const language of context.languages) { + if (!LANGUAGE_NAME_PATTERN.test(language)) { + warnings.push(`Invalid language name '${language}'. Only alphanumeric, dash, and underscore are allowed`); + continue; + } + + const sourceDir = path.join(context.sourceRoot, 'rules', language); + if (!fs.existsSync(sourceDir)) { + warnings.push(`rules/${language}/ does not exist, skipping`); + continue; + } + + addMatchingRuleOperations(operations, { + moduleId: 'legacy-antigravity-install', + sourceRoot: context.sourceRoot, + sourceRelativeDir: path.join('rules', language), + destinationDir: path.join(targetRoot, 'rules'), + matcher: fileName => fileName.endsWith('.md'), + rename: fileName => `${language}-${fileName}` + }); + } + + addRecursiveCopyOperations(operations, { + moduleId: 'legacy-antigravity-install', + sourceRoot: context.sourceRoot, + sourceRelativeDir: 'commands', + destinationDir: path.join(targetRoot, 'workflows') + }); + addRecursiveCopyOperations(operations, { + moduleId: 'legacy-antigravity-install', + sourceRoot: context.sourceRoot, + sourceRelativeDir: 'agents', + destinationDir: path.join(targetRoot, 'agents'), + contentTransform: 'antigravity-agent-frontmatter' + }); + addRecursiveCopyOperations(operations, { + moduleId: 'legacy-antigravity-install', + sourceRoot: context.sourceRoot, + sourceRelativeDir: 'skills', + destinationDir: path.join(targetRoot, 'skills') + }); + + return { + mode: 'legacy', + adapter, + target: 'antigravity', + targetRoot, + installRoot: targetRoot, + installStatePath, + operations, + warnings, + selectedModules: ['legacy-antigravity-install'] + }; +} + +function createLegacyInstallPlan(options = {}) { + const sourceRoot = options.sourceRoot || getSourceRoot(); + const projectRoot = options.projectRoot || process.cwd(); + const homeDir = options.homeDir || process.env.HOME || os.homedir(); + const target = options.target || 'claude'; + + validateLegacyTarget(target); + + const context = { + sourceRoot, + projectRoot, + homeDir, + languages: Array.isArray(options.languages) ? options.languages : [], + claudeRulesDir: options.claudeRulesDir || process.env.CLAUDE_RULES_DIR || null + }; + + let plan; + if (target === 'claude') { + plan = planClaudeLegacyInstall(context); + } else if (target === 'claude-project') { + plan = planClaudeProjectLegacyInstall(context); + } else if (target === 'cursor') { + plan = planCursorLegacyInstall(context); + } else { + plan = planAntigravityLegacyInstall(context); + } + + const source = { + repoVersion: getPackageVersion(sourceRoot), + repoCommit: getRepoCommit(sourceRoot), + manifestVersion: getManifestVersion(sourceRoot) + }; + + const statePreview = createStatePreview({ + adapter: plan.adapter, + targetRoot: plan.targetRoot, + installStatePath: plan.installStatePath, + request: { + profile: null, + modules: [], + legacyLanguages: context.languages, + legacyMode: true + }, + resolution: { + selectedModules: plan.selectedModules, + skippedModules: [] + }, + operations: plan.operations, + source + }); + + return { + mode: 'legacy', + sourceRoot, + target: plan.target, + adapter: { + id: plan.adapter.id, + target: plan.adapter.target, + kind: plan.adapter.kind + }, + targetRoot: plan.targetRoot, + installRoot: plan.installRoot, + installStatePath: plan.installStatePath, + warnings: plan.warnings, + languages: context.languages, + operations: plan.operations, + statePreview + }; +} + +function createLegacyCompatInstallPlan(options = {}) { + const sourceRoot = options.sourceRoot || getSourceRoot(); + const projectRoot = options.projectRoot || process.cwd(); + const target = options.target || 'claude'; + const includeComponentIds = Array.isArray(options.includeComponentIds) ? [...options.includeComponentIds] : []; + const excludeComponentIds = Array.isArray(options.excludeComponentIds) ? [...options.excludeComponentIds] : []; + + validateLegacyTarget(target); + + const selection = resolveLegacyCompatibilitySelection({ + repoRoot: sourceRoot, + target, + legacyLanguages: options.legacyLanguages || [] + }); + + return createManifestInstallPlan({ + sourceRoot, + projectRoot, + homeDir: options.homeDir, + env: resolveInvocationEnvironment(options), + target, + profileId: null, + moduleIds: selection.moduleIds, + includeComponentIds, + excludeComponentIds, + legacyLanguages: selection.legacyLanguages, + ruleLanguages: selection.ruleLanguages, + legacyMode: true, + exemptValidationCodes: options.exemptValidationCodes || [], + requestProfileId: null, + requestModuleIds: [], + requestIncludeComponentIds: includeComponentIds, + requestExcludeComponentIds: excludeComponentIds, + mode: 'legacy-compat' + }); +} + +module.exports = { + SUPPORTED_INSTALL_TARGETS, + LEGACY_INSTALL_TARGETS, + applyInstallPlan, + previewInstallPlan, + createLegacyCompatInstallPlan, + createManifestInstallPlan, + createLegacyInstallPlan, + dedupeCopyFileOperations, + getSourceRoot, + listAvailableLanguages, + parseInstallArgs +}; diff --git a/github_code/affaan-m__ECC/scripts/lib/install-lifecycle.js b/github_code/affaan-m__ECC/scripts/lib/install-lifecycle.js new file mode 100644 index 0000000000000000000000000000000000000000..99ec19614fe0a3882dd840a706b67d5034f834f5 --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/install-lifecycle.js @@ -0,0 +1,2412 @@ +const crypto = require('crypto'); +const fs = require('fs'); +const { execFileSync } = require('child_process'); +const os = require('os'); +const path = require('path'); +const { isDeepStrictEqual } = require('util'); + +const { loadInstallManifests } = require('./install-manifests'); +const { readInstallState, validateInstallState } = require('./install-state'); +const { assertWithinTrustedRoot } = require('./path-safety'); +const { createInstallPlanFromRequest } = require('./install/runtime'); +const { getRecordedHookConsent } = require('./install/hook-consent'); +const { + prepareClaudeSkillMigration, +} = require('./install/claude-skill-migration'); +const { + getLegacyAntigravityLocation, + inspectLegacyAntigravityState, +} = require('./install/antigravity-legacy-migration'); +const { + getLegacyOpencodeLocation, + inspectLegacyOpencodeState, +} = require('./install/opencode-legacy-migration'); +const { + acquireSettingsLock, + assertClaudeSettingsPath, + getClaudeSettingsPath, + inspectManagedHooks, + materializeManagedHooks, + repairManagedHooks, + uninstallManagedHooks, + updateSettingsAtomic, + validateManagedHooks, +} = require('./install/claude-settings'); +const { adaptAntigravityAgent } = require('./install/antigravity-agent'); +const { buildInstallIndex, rewriteRelativeLinks } = require('./install/link-rewrite'); +const { getInstallTargetAdapter, listInstallTargetAdapters } = require('./install-targets/registry'); +const { resolveInvocationEnvironment } = require('./invocation-environment'); +const OPENCODE_BUILD_ARTIFACT = path.join('.opencode', 'dist'); +const OPENCODE_BUILD_SCRIPT = path.join('scripts', 'build-opencode.js'); +const OPENCODE_PLUGIN_NOT_BUILT_CODE = 'opencode-plugin-not-built'; + +const DEFAULT_REPO_ROOT = path.join(__dirname, '../..'); + +function readPackageVersion(repoRoot) { + try { + const packageJson = JSON.parse(fs.readFileSync(path.join(repoRoot, 'package.json'), 'utf8')); + return packageJson.version || null; + } catch (_error) { + return null; + } +} + +function normalizeTargets(targets) { + if (!Array.isArray(targets) || targets.length === 0) { + return listInstallTargetAdapters().map(adapter => adapter.target); + } + + const normalizedTargets = []; + for (const target of targets) { + const adapter = getInstallTargetAdapter(target); + if (!normalizedTargets.includes(adapter.target)) { + normalizedTargets.push(adapter.target); + } + } + + return normalizedTargets; +} + +function compareStringArrays(left, right) { + const leftValues = Array.isArray(left) ? left : []; + const rightValues = Array.isArray(right) ? right : []; + + if (leftValues.length !== rightValues.length) { + return false; + } + + return leftValues.every((value, index) => value === rightValues[index]); +} + +function buildRecordedManifestRequest(record) { + const state = record.state || {}; + const request = state.request || {}; + + return { + mode: 'manifest', + target: state.target && state.target.target ? state.target.target : record.adapter.target, + profileId: request.profile || null, + moduleIds: Array.isArray(request.modules) ? [...request.modules] : [], + includeComponentIds: Array.isArray(request.includeComponents) ? [...request.includeComponents] : [], + excludeComponentIds: Array.isArray(request.excludeComponents) ? [...request.excludeComponents] : [], + legacyLanguages: Array.isArray(request.legacyLanguages) ? [...request.legacyLanguages] : [], + hookConsent: getRecordedHookConsent(state), + }; +} + +function resolveRecordedManifestPlan(record, context, options = {}) { + return createInstallPlanFromRequest(buildRecordedManifestRequest(record), { + sourceRoot: context.repoRoot, + projectRoot: context.projectRoot, + homeDir: context.homeDir, + env: context.env, + exemptValidationCodes: options.exemptValidationCodes || [], + }); +} + +function hasOpencodeBuildError(issues) { + return Array.isArray(issues) && issues.some(issue => issue.code === OPENCODE_PLUGIN_NOT_BUILT_CODE); +} + +function getOpencodeBuildValidationIssues(context) { + return getInstallTargetAdapter('opencode').validate({ + homeDir: context.homeDir, + repoRoot: context.repoRoot, + env: context.env, + }); +} + +function buildOpencodePayload(repoRoot, buildRunner = execFileSync) { + buildRunner(process.execPath, [path.join(repoRoot, OPENCODE_BUILD_SCRIPT)], { + cwd: repoRoot, + encoding: 'utf8', + stdio: ['ignore', 'pipe', 'pipe'], + }); +} + +function formatBuildErrorMessage(error) { + const stderr = typeof error.stderr === 'string' ? error.stderr.trim() : ''; + const stdout = typeof error.stdout === 'string' ? error.stdout.trim() : ''; + return stderr || stdout || error.message || 'Failed to build OpenCode payload'; +} + +function getManagedOperations(state) { + return Array.isArray(state && state.operations) ? state.operations.filter(operation => operation.ownership === 'managed') : []; +} + +function createUnsafeRepairSourceError() { + return new Error( + 'Refusing unsafe repair source metadata: sources must stay within the repository.' + ); +} + +function assertSafeRepairSourcePath(sourcePath, repoRoot) { + try { + return assertWithinTrustedRoot(sourcePath, repoRoot, 'read repair source'); + } catch { + throw createUnsafeRepairSourceError(); + } +} + +function resolveOperationSourcePath(repoRoot, operation) { + if (operation.sourceRelativePath) { + if (typeof operation.sourceRelativePath !== 'string') { + throw createUnsafeRepairSourceError(); + } + + const sourceRelativePath = operation.sourceRelativePath; + const hasParentTraversal = sourceRelativePath + .split(/[/\\]+/) + .includes('..'); + const isAbsolute = path.isAbsolute(sourceRelativePath) + || path.win32.isAbsolute(sourceRelativePath); + if (isAbsolute || hasParentTraversal) { + throw createUnsafeRepairSourceError(); + } + + return assertSafeRepairSourcePath( + path.resolve(repoRoot, sourceRelativePath), + repoRoot + ); + } + + if (!operation.sourcePath) { + return null; + } + if ( + typeof operation.sourcePath !== 'string' + || !path.isAbsolute(operation.sourcePath) + ) { + throw createUnsafeRepairSourceError(); + } + return assertSafeRepairSourcePath(operation.sourcePath, repoRoot); +} + +function areFilesEqual(leftPath, rightPath) { + try { + return readFileNoFollow(leftPath).equals(readFileNoFollow(rightPath)); + } catch (_error) { + return false; + } +} + +function hasRecordedContentDigest(operation) { + return /^[a-f0-9]{64}$/i.test(String(operation && operation.contentSha256 || '')); +} + +function fileMatchesRecordedContent(filePath, operation) { + if (!hasRecordedContentDigest(operation)) { + return false; + } + + try { + return crypto.createHash('sha256') + .update(readFileNoFollow(filePath)) + .digest('hex') === operation.contentSha256.toLowerCase(); + } catch (_error) { + return false; + } +} + +function isMarkdownPath(filePath) { + return /\.(md|mdx|markdown)$/i.test(String(filePath || '')); +} + +function buildLinkIndexForOperations(operations, trustedRoot) { + const mappings = (operations || []) + .filter(operation => operation.kind === 'copy-file' && operation.sourceRelativePath) + .map(operation => ({ + sourceRel: operation.sourceRelativePath, + destRel: path.relative(trustedRoot, operation.destinationPath), + })); + return buildInstallIndex(mappings); +} + +function transformCopyFileContent(operation, content) { + if (!operation.contentTransform) { + return content; + } + if (operation.contentTransform === 'antigravity-agent-frontmatter') { + return adaptAntigravityAgent(content, operation.sourceRelativePath); + } + throw new Error(`Unknown install content transform: ${operation.contentTransform}`); +} + +function getExpectedCopyFileContent(operation, content, linkIndex) { + const transformed = transformCopyFileContent(operation, content); + if (!linkIndex || !operation.sourceRelativePath || !isMarkdownPath(operation.destinationPath)) { + return transformed; + } + return rewriteRelativeLinks(transformed, { + sourceRel: operation.sourceRelativePath, + index: linkIndex, + }); +} + +function isPlainObject(value) { + return Boolean(value) && typeof value === 'object' && !Array.isArray(value); +} + +function cloneJsonValue(value) { + if (value === undefined) { + return undefined; + } + + return JSON.parse(JSON.stringify(value)); +} + +function parseJsonLikeValue(value, label) { + if (value === undefined) { + return undefined; + } + + if (typeof value === 'string') { + try { + return JSON.parse(value); + } catch (error) { + throw new Error(`Invalid ${label}: ${error.message}`); + } + } + + if (value === null || Array.isArray(value) || isPlainObject(value) || typeof value === 'number' || typeof value === 'boolean') { + return cloneJsonValue(value); + } + + throw new Error(`Invalid ${label}: expected JSON-compatible data`); +} + +function getOperationTextContent(operation) { + const candidateKeys = ['renderedContent', 'content', 'managedContent', 'expectedContent', 'templateOutput']; + + for (const key of candidateKeys) { + if (typeof operation[key] === 'string') { + return operation[key]; + } + } + + return null; +} + +function getOperationJsonPayload(operation) { + const candidateKeys = ['mergePayload', 'managedPayload', 'payload', 'value', 'expectedValue']; + + for (const key of candidateKeys) { + if (operation[key] !== undefined) { + return parseJsonLikeValue(operation[key], `${operation.kind}.${key}`); + } + } + + return undefined; +} + +function getOperationPreviousContent(operation) { + const candidateKeys = ['previousContent', 'originalContent', 'backupContent']; + + for (const key of candidateKeys) { + if (typeof operation[key] === 'string') { + return operation[key]; + } + } + + return null; +} + +function getOperationPreviousJson(operation) { + const candidateKeys = ['previousValue', 'previousJson', 'originalValue']; + + for (const key of candidateKeys) { + if (operation[key] !== undefined) { + return parseJsonLikeValue(operation[key], `${operation.kind}.${key}`); + } + } + + return undefined; +} + +function formatJson(value) { + return `${JSON.stringify(value, null, 2)}\n`; +} + +function getManagedDestination( + destinationPath, + trustedRoot, + action, + { allowFinalSymlink = false } = {} +) { + if (!destinationPath || typeof destinationPath !== 'string') { + throw new Error(`Refusing to ${action}: missing destination path.`); + } + + const canonicalRoot = assertWithinTrustedRoot(trustedRoot, trustedRoot, action); + const resolvedDestination = path.resolve(destinationPath); + const canonicalParent = assertWithinTrustedRoot( + path.dirname(resolvedDestination), + canonicalRoot, + action + ); + const managedPath = path.join(canonicalParent, path.basename(resolvedDestination)); + let stat = null; + + try { + stat = fs.lstatSync(managedPath); + } catch (error) { + if (!error || (error.code !== 'ENOENT' && error.code !== 'ENOTDIR')) { + throw error; + } + } + + if (stat && stat.isSymbolicLink() && !allowFinalSymlink) { + const error = new Error( + `Refusing to ${action}: managed destination is a final symlink.` + ); + error.code = 'ECC_FINAL_DESTINATION_SYMLINK'; + throw error; + } + + return { + canonicalRoot, + exists: stat !== null, + isFinalSymlink: Boolean(stat && stat.isSymbolicLink()), + managedPath + }; +} + +function ensureContainedParentDir(destinationPath, trustedRoot, action) { + const initialDestination = getManagedDestination( + destinationPath, + trustedRoot, + action + ); + const { canonicalRoot, managedPath } = initialDestination; + const canonicalParent = path.dirname(managedPath); + const relativeParent = path.relative(canonicalRoot, canonicalParent); + const pathSegments = relativeParent + ? relativeParent.split(path.sep).filter(Boolean) + : []; + let currentPath = canonicalRoot; + + for (const segment of pathSegments) { + const validatedParent = assertWithinTrustedRoot(currentPath, canonicalRoot, action); + const nextPath = path.join(validatedParent, segment); + try { + fs.mkdirSync(nextPath); + } catch (error) { + if (!error || error.code !== 'EEXIST') { + throw error; + } + } + + const validatedNext = assertWithinTrustedRoot(nextPath, canonicalRoot, action); + const nextStat = fs.lstatSync(validatedNext); + if (!nextStat.isDirectory() || nextStat.isSymbolicLink()) { + throw new Error(`Refusing to ${action}: destination parent is not a trusted directory.`); + } + currentPath = validatedNext; + } + + return getManagedDestination(managedPath, canonicalRoot, action).managedPath; +} + +function prepareContainedWriteDestination(destinationPath, trustedRoot, action) { + return ensureContainedParentDir(destinationPath, trustedRoot, action); +} + +function getContainedExistingPath( + destinationPath, + trustedRoot, + action, + { allowFinalSymlink = false } = {} +) { + const initialDestination = getManagedDestination( + destinationPath, + trustedRoot, + action, + { allowFinalSymlink } + ); + const followsToExistingPath = fs.existsSync(initialDestination.managedPath); + if (!followsToExistingPath && !initialDestination.isFinalSymlink) { + return null; + } + + const finalDestination = getManagedDestination( + initialDestination.managedPath, + trustedRoot, + action, + { allowFinalSymlink } + ); + return finalDestination.exists ? finalDestination.managedPath : null; +} + +function hasSameFileIdentity(leftStat, rightStat) { + return leftStat.dev === rightStat.dev && leftStat.ino === rightStat.ino; +} + +function createChangedDestinationError(action) { + return new Error( + `Refusing to ${action}: managed destination changed during the write.` + ); +} + +function getStableParentStat(filePath, action) { + const parentStat = fs.lstatSync(path.dirname(filePath)); + if (!parentStat.isDirectory() || parentStat.isSymbolicLink()) { + throw createChangedDestinationError(action); + } + return parentStat; +} + +function assertPinnedWriteDestination( + filePath, + fileDescriptor, + expectedParentStat, + trustedRoot, + action +) { + const liveDestination = getManagedDestination(filePath, trustedRoot, action); + if (path.resolve(liveDestination.managedPath) !== path.resolve(filePath)) { + throw createChangedDestinationError(action); + } + + const liveParentStat = getStableParentStat(filePath, action); + if (!hasSameFileIdentity(expectedParentStat, liveParentStat)) { + throw createChangedDestinationError(action); + } + + const descriptorStat = fs.fstatSync(fileDescriptor); + const livePathStat = fs.lstatSync(liveDestination.managedPath); + if ( + !descriptorStat.isFile() + || !livePathStat.isFile() + || livePathStat.isSymbolicLink() + || !hasSameFileIdentity(descriptorStat, livePathStat) + ) { + throw createChangedDestinationError(action); + } +} + +function writeFileNoFollow(filePath, content, mode, trustedRoot, action) { + const expectedParentStat = getStableParentStat(filePath, action); + const flags = fs.constants.O_WRONLY + | fs.constants.O_CREAT + | (fs.constants.O_NOFOLLOW || 0); + const fileDescriptor = fs.openSync(filePath, flags, mode); + + try { + assertPinnedWriteDestination( + filePath, + fileDescriptor, + expectedParentStat, + trustedRoot, + action + ); + fs.ftruncateSync(fileDescriptor, 0); + fs.writeFileSync(fileDescriptor, content); + if (mode !== undefined) { + fs.fchmodSync(fileDescriptor, mode); + } + } finally { + fs.closeSync(fileDescriptor); + } +} + +function readFileWithMetadataNoFollow(filePath, encoding) { + const flags = fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW || 0); + const fileDescriptor = fs.openSync(filePath, flags); + + try { + const stat = fs.fstatSync(fileDescriptor); + if (!stat.isFile()) { + throw new Error(`Refusing to read non-file path: ${filePath}`); + } + return { + content: fs.readFileSync(fileDescriptor, encoding), + mode: stat.mode, + }; + } finally { + fs.closeSync(fileDescriptor); + } +} + +function readFileNoFollow(filePath, encoding) { + return readFileWithMetadataNoFollow(filePath, encoding).content; +} + +function readJsonNoFollow(filePath) { + return JSON.parse(readFileNoFollow(filePath, 'utf8')); +} + +function assertClaudeSettingsDestination(operation, trustedRoot, target = null) { + if (target && target !== 'claude' && target !== 'claude-project') { + throw new Error('Refusing to manage Claude hooks for a non-Claude target.'); + } + assertClaudeSettingsPath(operation.destinationPath, trustedRoot); +} + +function writeContainedFile(destinationPath, content, trustedRoot, action, mode) { + const preparedDestination = prepareContainedWriteDestination(destinationPath, trustedRoot, action); + const finalDestination = getManagedDestination( + preparedDestination, + trustedRoot, + action + ).managedPath; + writeFileNoFollow( + finalDestination, + content, + mode, + trustedRoot, + action + ); + return finalDestination; +} + +function copyContainedFile(sourcePath, destinationPath, trustedRoot, action) { + const source = readFileWithMetadataNoFollow(sourcePath); + return writeContainedFile( + destinationPath, + source.content, + trustedRoot, + action, + source.mode & 0o777 + ); +} + +function removeContainedPath(destinationPath, trustedRoot, action, options = {}) { + const existingDestination = getContainedExistingPath( + destinationPath, + trustedRoot, + action, + { allowFinalSymlink: true } + ); + if (!existingDestination) { + return null; + } + + const managedDestination = getManagedDestination( + existingDestination, + trustedRoot, + action, + { allowFinalSymlink: true } + ); + const finalDestination = managedDestination.managedPath; + const expectedStat = fs.lstatSync(finalDestination, { bigint: true }); + const quarantineDir = fs.mkdtempSync(path.join( + path.dirname(managedDestination.canonicalRoot), + '.ecc-remove-' + )); + const quarantinePath = path.join(quarantineDir, path.basename(finalDestination)); + + try { + fs.renameSync(finalDestination, quarantinePath); + } catch (error) { + fs.rmdirSync(quarantineDir); + throw error; + } + + const quarantinedStat = fs.lstatSync(quarantinePath, { bigint: true }); + if (!hasSameFileIdentity(expectedStat, quarantinedStat)) { + try { + fs.renameSync(quarantinePath, finalDestination); + fs.rmdirSync(quarantineDir); + } catch (_restoreError) { + throw new Error( + `Refusing to ${action}: managed destination changed before removal; replacement preserved at ${quarantinePath}.` + ); + } + throw createChangedDestinationError(action); + } + + if (quarantinedStat.isDirectory() && !options.recursive) { + fs.rmdirSync(quarantinePath); + } else { + fs.rmSync(quarantinePath, options); + } + fs.rmdirSync(quarantineDir); + return finalDestination; +} + +function deepMergeJson(baseValue, patchValue) { + if (!isPlainObject(baseValue) || !isPlainObject(patchValue)) { + return cloneJsonValue(patchValue); + } + + const merged = { ...baseValue }; + for (const [key, value] of Object.entries(patchValue)) { + if (isPlainObject(value) && isPlainObject(merged[key])) { + merged[key] = deepMergeJson(merged[key], value); + } else { + merged[key] = cloneJsonValue(value); + } + } + return merged; +} + +function jsonContainsSubset(actualValue, expectedValue) { + if (isPlainObject(expectedValue)) { + if (!isPlainObject(actualValue)) { + return false; + } + + return Object.entries(expectedValue).every(([key, value]) => Object.prototype.hasOwnProperty.call(actualValue, key) && jsonContainsSubset(actualValue[key], value)); + } + + if (Array.isArray(expectedValue)) { + if (!Array.isArray(actualValue) || actualValue.length !== expectedValue.length) { + return false; + } + + return expectedValue.every((item, index) => jsonContainsSubset(actualValue[index], item)); + } + + return actualValue === expectedValue; +} + +const JSON_REMOVE_SENTINEL = Symbol('json-remove'); + +function deepRemoveJsonSubset(currentValue, managedValue) { + if (isPlainObject(managedValue)) { + if (!isPlainObject(currentValue)) { + return currentValue; + } + + const nextValue = { ...currentValue }; + for (const [key, value] of Object.entries(managedValue)) { + if (!Object.prototype.hasOwnProperty.call(nextValue, key)) { + continue; + } + + if (isPlainObject(value)) { + const nestedValue = deepRemoveJsonSubset(nextValue[key], value); + if (nestedValue === JSON_REMOVE_SENTINEL) { + delete nextValue[key]; + } else { + nextValue[key] = nestedValue; + } + continue; + } + + if (Array.isArray(value)) { + if (Array.isArray(nextValue[key]) && jsonContainsSubset(nextValue[key], value)) { + delete nextValue[key]; + } + continue; + } + + if (nextValue[key] === value) { + delete nextValue[key]; + } + } + + return Object.keys(nextValue).length === 0 ? JSON_REMOVE_SENTINEL : nextValue; + } + + if (Array.isArray(managedValue)) { + return jsonContainsSubset(currentValue, managedValue) ? JSON_REMOVE_SENTINEL : currentValue; + } + + return currentValue === managedValue ? JSON_REMOVE_SENTINEL : currentValue; +} + +function hydrateRecordedOperations(repoRoot, operations, trustedRoot) { + return operations.map(operation => { + if (operation.kind === 'update-claude-settings') { + const sourcePath = resolveOperationSourcePath(repoRoot, operation); + if (!sourcePath || !fs.existsSync(sourcePath)) { + throw new Error( + `Missing source file for repair: ${sourcePath || operation.sourceRelativePath}` + ); + } + return { + ...operation, + sourcePath, + previousManagedHooks: operation.managedHooks, + managedHooks: materializeManagedHooks( + readJsonNoFollow(sourcePath), + trustedRoot + ), + }; + } + + if (operation.kind !== 'copy-file') { + return { ...operation }; + } + + return { + ...operation, + sourcePath: resolveOperationSourcePath(repoRoot, operation) + }; + }); +} + +function buildRecordedStatePreview(state, context, operations) { + return { + ...state, + operations: operations.map(operation => ({ ...operation })), + source: { + ...state.source, + repoVersion: context.packageVersion, + manifestVersion: context.manifestVersion + }, + lastValidatedAt: new Date().toISOString() + }; +} + +function shouldRepairFromRecordedOperations(state) { + return getManagedOperations(state).some(operation => operation.kind !== 'copy-file'); +} + +function executeRepairOperation( + repoRoot, + operation, + trustedRoot, + linkIndex = null, + target = null, + settingsLockHeld = false +) { + // Install-state is attacker-controllable; never write/delete outside the + // adapter-derived trusted root, regardless of what the state file claims + // (GHSA-hfpv-w6mp-5g95). + if (operation.kind === 'copy-file') { + const sourcePath = resolveOperationSourcePath(repoRoot, operation); + if (!sourcePath || !fs.existsSync(sourcePath)) { + throw new Error(`Missing source file for repair: ${sourcePath || operation.sourceRelativePath}`); + } + + if (operation.contentTransform || isMarkdownPath(operation.destinationPath)) { + const source = readFileWithMetadataNoFollow(sourcePath, 'utf8'); + writeContainedFile( + operation.destinationPath, + getExpectedCopyFileContent(operation, source.content, linkIndex), + trustedRoot, + 'repair', + source.mode & 0o777 + ); + } else { + copyContainedFile(sourcePath, operation.destinationPath, trustedRoot, 'repair'); + } + return operation.destinationPath; + } + + if (operation.kind === 'render-template') { + const renderedContent = getOperationTextContent(operation); + if (renderedContent === null) { + throw new Error(`Missing rendered content for repair: ${operation.destinationPath}`); + } + + writeContainedFile(operation.destinationPath, renderedContent, trustedRoot, 'repair'); + return operation.destinationPath; + } + + if (operation.kind === 'merge-json') { + const payload = getOperationJsonPayload(operation); + if (payload === undefined) { + throw new Error(`Missing merge payload for repair: ${operation.destinationPath}`); + } + + const existingDestination = getContainedExistingPath(operation.destinationPath, trustedRoot, 'repair'); + const currentValue = existingDestination + ? readJsonNoFollow( + getManagedDestination(existingDestination, trustedRoot, 'repair').managedPath + ) + : {}; + const mergedValue = deepMergeJson(currentValue, payload); + + writeContainedFile(operation.destinationPath, formatJson(mergedValue), trustedRoot, 'repair'); + return operation.destinationPath; + } + + if (operation.kind === 'update-claude-settings') { + assertClaudeSettingsDestination(operation, trustedRoot, target); + const managedHooks = validateManagedHooks(operation.managedHooks); + const previousManagedHooks = operation.previousManagedHooks + ? validateManagedHooks(operation.previousManagedHooks, 'previous managed hooks') + : null; + const existingDestination = getContainedExistingPath( + operation.destinationPath, + trustedRoot, + 'repair' + ); + const settingsPath = existingDestination + ? getManagedDestination(existingDestination, trustedRoot, 'repair').managedPath + : prepareContainedWriteDestination(operation.destinationPath, trustedRoot, 'repair'); + updateSettingsAtomic( + settingsPath, + currentSettings => repairManagedHooks(currentSettings, managedHooks, { + previousManagedHooks, + }), + { + lockHeld: settingsLockHeld, + beforeCommit() { + getManagedDestination(settingsPath, trustedRoot, 'repair'); + }, + } + ); + return operation.destinationPath; + } + + if (operation.kind === 'remove') { + const removedPath = removeContainedPath( + operation.destinationPath, + trustedRoot, + 'repair', + { recursive: true, force: true } + ); + return removedPath ? operation.destinationPath : null; + } + + throw new Error(`Unsupported repair operation kind: ${operation.kind}`); +} + +function executeUninstallOperation(operation, trustedRoot, options = {}) { + // Confine deletes to the trusted install root (GHSA-hfpv-w6mp-5g95). + if (operation.kind === 'copy-file') { + if (options.preserveDriftedCopies) { + const existingDestination = getContainedExistingPath( + operation.destinationPath, + trustedRoot, + 'uninstall', + { allowFinalSymlink: true } + ); + if (!existingDestination) { + return { + removedPaths: [], + cleanupTargets: [] + }; + } + if (fs.lstatSync(existingDestination).isSymbolicLink()) { + return { + removedPaths: [], + cleanupTargets: [], + retainedPaths: [operation.destinationPath] + }; + } + const recordedDigest = operation.contentSha256; + const currentDigest = /^[a-f0-9]{64}$/i.test(recordedDigest || '') + ? crypto.createHash('sha256') + .update(readFileNoFollow(existingDestination)) + .digest('hex') + : null; + if (!currentDigest || currentDigest !== recordedDigest.toLowerCase()) { + return { + removedPaths: [], + cleanupTargets: [], + retainedPaths: [operation.destinationPath] + }; + } + } + + const removedPath = removeContainedPath( + operation.destinationPath, + trustedRoot, + 'uninstall', + { force: true } + ); + if (!removedPath) { + return { + removedPaths: [], + cleanupTargets: [] + }; + } + + return { + removedPaths: [operation.destinationPath], + cleanupTargets: [removedPath] + }; + } + + if (operation.kind === 'render-template') { + const previousContent = getOperationPreviousContent(operation); + if (previousContent !== null) { + writeContainedFile(operation.destinationPath, previousContent, trustedRoot, 'uninstall'); + return { + removedPaths: [], + cleanupTargets: [] + }; + } + + const previousJson = getOperationPreviousJson(operation); + if (previousJson !== undefined) { + writeContainedFile(operation.destinationPath, formatJson(previousJson), trustedRoot, 'uninstall'); + return { + removedPaths: [], + cleanupTargets: [] + }; + } + + const removedPath = removeContainedPath( + operation.destinationPath, + trustedRoot, + 'uninstall', + { force: true } + ); + if (!removedPath) { + return { + removedPaths: [], + cleanupTargets: [] + }; + } + + return { + removedPaths: [operation.destinationPath], + cleanupTargets: [removedPath] + }; + } + + if (operation.kind === 'merge-json') { + const previousContent = getOperationPreviousContent(operation); + if (previousContent !== null) { + writeContainedFile(operation.destinationPath, previousContent, trustedRoot, 'uninstall'); + return { + removedPaths: [], + cleanupTargets: [] + }; + } + + const previousJson = getOperationPreviousJson(operation); + if (previousJson !== undefined) { + writeContainedFile(operation.destinationPath, formatJson(previousJson), trustedRoot, 'uninstall'); + return { + removedPaths: [], + cleanupTargets: [] + }; + } + + const existingDestination = getContainedExistingPath( + operation.destinationPath, + trustedRoot, + 'uninstall' + ); + if (!existingDestination) { + return { + removedPaths: [], + cleanupTargets: [] + }; + } + + const payload = getOperationJsonPayload(operation); + if (payload === undefined) { + throw new Error(`Missing merge payload for uninstall: ${operation.destinationPath}`); + } + + const currentValue = readJsonNoFollow( + getManagedDestination(existingDestination, trustedRoot, 'uninstall').managedPath + ); + const nextValue = deepRemoveJsonSubset(currentValue, payload); + if (nextValue === JSON_REMOVE_SENTINEL) { + const removedPath = removeContainedPath( + operation.destinationPath, + trustedRoot, + 'uninstall', + { force: true } + ); + return { + removedPaths: removedPath ? [operation.destinationPath] : [], + cleanupTargets: removedPath ? [removedPath] : [] + }; + } + + writeContainedFile(operation.destinationPath, formatJson(nextValue), trustedRoot, 'uninstall'); + return { + removedPaths: [], + cleanupTargets: [] + }; + } + + if (operation.kind === 'update-claude-settings') { + assertClaudeSettingsDestination(operation, trustedRoot, options.target); + const existingDestination = getContainedExistingPath( + operation.destinationPath, + trustedRoot, + 'uninstall' + ); + if (!existingDestination) { + return { + removedPaths: [], + cleanupTargets: [] + }; + } + + const settingsPath = getManagedDestination( + existingDestination, + trustedRoot, + 'uninstall' + ).managedPath; + const uninstalled = updateSettingsAtomic( + settingsPath, + currentSettings => uninstallManagedHooks(currentSettings, operation.managedHooks), + { + lockHeld: Boolean(options.settingsLockHeld), + beforeCommit() { + getManagedDestination(settingsPath, trustedRoot, 'uninstall'); + }, + } + ); + + return { + removedPaths: [], + cleanupTargets: [], + retainedPaths: uninstalled.retained.length > 0 + ? [operation.destinationPath] + : [] + }; + } + + if (operation.kind === 'remove') { + const previousContent = getOperationPreviousContent(operation); + if (previousContent !== null) { + writeContainedFile(operation.destinationPath, previousContent, trustedRoot, 'uninstall'); + return { + removedPaths: [], + cleanupTargets: [] + }; + } + + const previousJson = getOperationPreviousJson(operation); + if (previousJson !== undefined) { + writeContainedFile(operation.destinationPath, formatJson(previousJson), trustedRoot, 'uninstall'); + return { + removedPaths: [], + cleanupTargets: [] + }; + } + + return { + removedPaths: [], + cleanupTargets: [] + }; + } + + throw new Error(`Unsupported uninstall operation kind: ${operation.kind}`); +} + +function inspectManagedOperation(repoRoot, trustedRoot, operation, linkIndex = null, target = null) { + const destinationPath = operation.destinationPath; + if (!destinationPath) { + return { + status: 'invalid-destination', + operation + }; + } + + let managedDestination; + try { + managedDestination = getManagedDestination( + destinationPath, + trustedRoot, + 'inspect managed operation', + { allowFinalSymlink: operation.kind === 'remove' } + ); + } catch (error) { + return { + status: 'unsafe-destination', + operation, + destinationPath, + reason: error && error.code === 'ECC_FINAL_DESTINATION_SYMLINK' + ? 'final-symlink' + : 'outside-root' + }; + } + + const inspectedPath = managedDestination.managedPath; + + if (operation.kind === 'remove') { + if (managedDestination.exists) { + return { + status: 'drifted', + operation, + destinationPath + }; + } + + return { + status: 'ok', + operation, + destinationPath + }; + } + + let copySourcePath = null; + if (operation.kind === 'copy-file') { + try { + copySourcePath = resolveOperationSourcePath(repoRoot, operation); + } catch { + return { + status: 'unsafe-source', + operation, + destinationPath + }; + } + } + + if (!managedDestination.exists) { + return { + status: 'missing', + operation, + destinationPath + }; + } + + if (operation.kind === 'copy-file') { + if (!copySourcePath || !fs.existsSync(copySourcePath)) { + return { + status: 'missing-source', + operation, + destinationPath, + sourcePath: copySourcePath + }; + } + + let contentMatches; + try { + contentMatches = hasRecordedContentDigest(operation) + ? fileMatchesRecordedContent(inspectedPath, operation) + : operation.contentTransform || isMarkdownPath(operation.destinationPath) + ? readFileNoFollow(inspectedPath, 'utf8') === getExpectedCopyFileContent( + operation, + readFileNoFollow(copySourcePath, 'utf8'), + linkIndex + ) + : areFilesEqual(copySourcePath, inspectedPath); + } catch (_error) { + return { + status: 'unverified', + operation, + destinationPath, + sourcePath: copySourcePath + }; + } + + if (!contentMatches) { + return { + status: 'drifted', + operation, + destinationPath, + sourcePath: copySourcePath + }; + } + + return { + status: 'ok', + operation, + destinationPath, + sourcePath: copySourcePath + }; + } + + if (operation.kind === 'render-template') { + const renderedContent = getOperationTextContent(operation); + if (renderedContent === null) { + return { + status: 'unverified', + operation, + destinationPath + }; + } + + try { + if (readFileNoFollow(inspectedPath, 'utf8') !== renderedContent) { + return { + status: 'drifted', + operation, + destinationPath + }; + } + } catch { + return { + status: 'drifted', + operation, + destinationPath + }; + } + + return { + status: 'ok', + operation, + destinationPath + }; + } + + if (operation.kind === 'merge-json') { + const payload = getOperationJsonPayload(operation); + if (payload === undefined) { + return { + status: 'unverified', + operation, + destinationPath + }; + } + + try { + const currentValue = readJsonNoFollow(inspectedPath); + if (!jsonContainsSubset(currentValue, payload)) { + return { + status: 'drifted', + operation, + destinationPath + }; + } + } catch (_error) { + return { + status: 'drifted', + operation, + destinationPath + }; + } + + return { + status: 'ok', + operation, + destinationPath + }; + } + + if (operation.kind === 'update-claude-settings') { + try { + assertClaudeSettingsDestination(operation, trustedRoot, target); + } catch (_error) { + return { + status: 'unsafe-destination', + operation, + destinationPath, + reason: 'non-canonical-claude-settings' + }; + } + let managedHooks; + try { + managedHooks = validateManagedHooks(operation.managedHooks); + } catch (_error) { + return { + status: 'unverified', + operation, + destinationPath + }; + } + + try { + const inspection = inspectManagedHooks( + readJsonNoFollow(inspectedPath), + managedHooks + ); + return { + status: inspection.status, + operation, + destinationPath, + managedHookInspection: inspection + }; + } catch (error) { + return { + status: 'invalid-settings', + operation, + destinationPath, + error: `Failed to inspect Claude settings at ${destinationPath}: ${error.message}` + }; + } + } + + return { + status: 'unverified', + operation, + destinationPath + }; +} + +function summarizeManagedOperationHealth(repoRoot, trustedRoot, operations, target = null) { + const linkIndex = buildLinkIndexForOperations(operations, trustedRoot); + return operations.reduce( + (summary, operation) => { + const inspection = inspectManagedOperation( + repoRoot, + trustedRoot, + operation, + linkIndex, + target + ); + if (inspection.status === 'missing') { + summary.missing.push(inspection); + } else if (inspection.status === 'drifted') { + summary.drifted.push(inspection); + } else if (inspection.status === 'missing-source') { + summary.missingSource.push(inspection); + } else if (inspection.status === 'unsafe-source') { + summary.unsafeSource.push(inspection); + } else if (inspection.status === 'unsafe-destination') { + summary.unsafeDestination.push(inspection); + } else if (inspection.status === 'invalid-settings') { + summary.invalidSettings.push(inspection); + } else if (inspection.status === 'unverified' || inspection.status === 'invalid-destination') { + summary.unverified.push(inspection); + } + return summary; + }, + { + missing: [], + drifted: [], + missingSource: [], + unsafeSource: [], + unsafeDestination: [], + invalidSettings: [], + unverified: [] + } + ); +} + +function getUnsafeManagedDestinationError(operationHealth) { + const hasFinalSymlink = operationHealth.unsafeDestination.some( + inspection => inspection.reason === 'final-symlink' + ); + if (hasFinalSymlink) { + return 'Refusing unsafe managed destination: final symlink detected.'; + } + return 'Refusing unsafe managed destination outside adapter-derived install root.'; +} + +function getUnsafeOperationResult(record, operationHealth) { + const error = operationHealth.unsafeDestination.length > 0 + ? getUnsafeManagedDestinationError(operationHealth) + : operationHealth.unsafeSource.length > 0 + ? createUnsafeRepairSourceError().message + : operationHealth.invalidSettings.length > 0 + ? operationHealth.invalidSettings[0].error + : null; + if (!error) { + return null; + } + + return { + adapter: record.adapter, + status: 'error', + installStatePath: record.installStatePath, + repairedPaths: [], + plannedRepairs: [], + stateRefreshed: false, + error + }; +} + +function buildDiscoveryRecord(adapter, context, location = null, knownState = null) { + const installTargetInput = { + homeDir: context.homeDir, + projectRoot: context.projectRoot, + repoRoot: context.projectRoot, + env: context.env, + }; + const targetRoot = location + ? location.targetRoot + : adapter.resolveRoot(installTargetInput); + const installStatePath = location + ? location.installStatePath + : adapter.getInstallStatePath(installTargetInput); + const exists = fs.existsSync(installStatePath); + + if (!exists) { + return { + adapter: { + id: adapter.id, + target: adapter.target, + kind: adapter.kind + }, + targetRoot, + installStatePath, + exists: false, + state: null, + error: null, + legacy: Boolean(location), + legacyLayout: location?.legacyLayout || null + }; + } + + if (knownState) { + return { + adapter: { + id: adapter.id, + target: adapter.target, + kind: adapter.kind + }, + targetRoot, + installStatePath, + exists: true, + state: knownState, + error: null, + legacy: Boolean(location), + legacyLayout: location?.legacyLayout || null + }; + } + + try { + const state = readInstallState(installStatePath); + return { + adapter: { + id: adapter.id, + target: adapter.target, + kind: adapter.kind + }, + targetRoot, + installStatePath, + exists: true, + state, + error: null, + legacy: Boolean(location), + legacyLayout: location?.legacyLayout || null + }; + } catch (error) { + return { + adapter: { + id: adapter.id, + target: adapter.target, + kind: adapter.kind + }, + targetRoot, + installStatePath, + exists: true, + state: null, + error: error.message, + legacy: Boolean(location), + legacyLayout: location?.legacyLayout || null + }; + } +} + +function discoverInstalledStates(options = {}) { + const context = { + homeDir: options.homeDir || process.env.HOME || os.homedir(), + projectRoot: options.projectRoot || process.cwd(), + env: resolveInvocationEnvironment(options), + }; + const targets = normalizeTargets(options.targets); + + return targets.flatMap(target => { + const adapter = getInstallTargetAdapter(target); + const canonicalRecord = buildDiscoveryRecord(adapter, context); + if (adapter.target === 'opencode') { + const legacyLocation = getLegacyOpencodeLocation(context.homeDir); + const legacyInspection = inspectLegacyOpencodeState(legacyLocation); + if ( + path.resolve(legacyLocation.installStatePath) === path.resolve(canonicalRecord.installStatePath) + || legacyInspection.status === 'absent' + || legacyInspection.status === 'invalid' + ) { + return [canonicalRecord]; + } + if (legacyInspection.status === 'unreadable') { + return [canonicalRecord, { + adapter: { + id: adapter.id, + target: adapter.target, + kind: adapter.kind, + }, + targetRoot: legacyLocation.targetRoot, + installStatePath: legacyLocation.installStatePath, + exists: true, + state: null, + error: legacyInspection.error, + legacy: true, + legacyLayout: 'opencode', + }]; + } + return [ + canonicalRecord, + buildDiscoveryRecord(adapter, context, legacyLocation, legacyInspection.state), + ]; + } + + if (adapter.target !== 'antigravity') { + return [canonicalRecord]; + } + + const legacyLocation = { + ...getLegacyAntigravityLocation(context.projectRoot), + legacyLayout: 'antigravity', + }; + const legacyInspection = inspectLegacyAntigravityState(legacyLocation); + if ( + path.resolve(legacyLocation.installStatePath) === path.resolve(canonicalRecord.installStatePath) + || legacyInspection.status === 'absent' + || legacyInspection.status === 'invalid' + ) { + return [canonicalRecord]; + } + + if (legacyInspection.status === 'unreadable') { + return [canonicalRecord, { + adapter: { + id: adapter.id, + target: adapter.target, + kind: adapter.kind, + }, + targetRoot: legacyLocation.targetRoot, + installStatePath: legacyLocation.installStatePath, + exists: true, + state: null, + error: legacyInspection.error, + legacy: true, + legacyLayout: 'antigravity', + }]; + } + + return [ + canonicalRecord, + buildDiscoveryRecord(adapter, context, legacyLocation, legacyInspection.state), + ]; + }); +} + +function buildIssue(severity, code, message, extra = {}) { + return { + severity, + code, + message, + ...extra + }; +} + +function determineStatus(issues) { + if (issues.some(issue => issue.severity === 'error')) { + return 'error'; + } + + if (issues.some(issue => issue.severity === 'warning')) { + return 'warning'; + } + + return 'ok'; +} + +function analyzeRecord(record, context) { + const issues = []; + + if (record.legacyLayout === 'antigravity') { + issues.push(buildIssue( + 'warning', + 'legacy-antigravity-layout', + 'Legacy Antigravity install-state remains under .agent. Review and move any preserved modified or unmanaged files out of .agent, then rerun the Antigravity install to finish migration.' + )); + } + + if (record.legacyLayout === 'opencode') { + issues.push(buildIssue( + 'warning', + 'legacy-opencode-layout', + 'Legacy OpenCode install-state remains under ~/.opencode. Rerun the OpenCode install or repair command to migrate unchanged ECC-managed files to ~/.config/opencode; modified files are preserved for review.' + )); + } + + if (record.error) { + issues.push(buildIssue('error', 'invalid-install-state', record.error)); + return { + ...record, + status: determineStatus(issues), + issues + }; + } + + const state = record.state; + if (!state) { + return { + ...record, + status: 'missing', + issues + }; + } + + if (!fs.existsSync(state.target.root)) { + issues.push(buildIssue('error', 'missing-target-root', `Target root does not exist: ${state.target.root}`)); + } + + if (state.target.root !== record.targetRoot) { + issues.push( + buildIssue('warning', 'target-root-mismatch', `Recorded target root differs from current target root (${record.targetRoot})`, { + recordedTargetRoot: state.target.root, + currentTargetRoot: record.targetRoot + }) + ); + } + + if (state.target.installStatePath !== record.installStatePath) { + issues.push( + buildIssue('warning', 'install-state-path-mismatch', `Recorded install-state path differs from current path (${record.installStatePath})`, { + recordedInstallStatePath: state.target.installStatePath, + currentInstallStatePath: record.installStatePath + }) + ); + } + + const managedOperations = getManagedOperations(state); + const operationHealth = summarizeManagedOperationHealth( + context.repoRoot, + record.targetRoot, + managedOperations, + record.adapter.target + ); + const missingManagedOperations = operationHealth.missing; + + if (operationHealth.unsafeDestination.length > 0) { + issues.push( + buildIssue( + 'error', + 'unsafe-managed-destination', + `${operationHealth.unsafeDestination.length} managed operation(s) target an unsafe destination` + ) + ); + } + + if (operationHealth.unsafeSource.length > 0) { + issues.push( + buildIssue( + 'error', + 'unsafe-repair-source', + `${operationHealth.unsafeSource.length} managed operation(s) reference unsafe repair source metadata` + ) + ); + } + + if (operationHealth.invalidSettings.length > 0) { + issues.push( + buildIssue( + 'error', + 'invalid-claude-settings', + operationHealth.invalidSettings[0].error, + { paths: operationHealth.invalidSettings.map(entry => entry.destinationPath) } + ) + ); + } + + if (missingManagedOperations.length > 0) { + issues.push( + buildIssue('error', 'missing-managed-files', `${missingManagedOperations.length} managed file(s) are missing`, { + paths: missingManagedOperations.map(entry => entry.destinationPath) + }) + ); + } + + if (operationHealth.drifted.length > 0) { + issues.push( + buildIssue('warning', 'drifted-managed-files', `${operationHealth.drifted.length} managed file(s) differ from the source repo`, { + paths: operationHealth.drifted.map(entry => entry.destinationPath) + }) + ); + } + + if (operationHealth.missingSource.length > 0) { + issues.push( + buildIssue('error', 'missing-source-files', `${operationHealth.missingSource.length} source file(s) referenced by install-state are missing`, { + paths: operationHealth.missingSource.map(entry => entry.sourcePath).filter(Boolean) + }) + ); + } + + if (operationHealth.unverified.length > 0) { + issues.push( + buildIssue('warning', 'unverified-managed-operations', `${operationHealth.unverified.length} managed operation(s) could not be content-verified`, { + paths: operationHealth.unverified.map(entry => entry.destinationPath).filter(Boolean) + }) + ); + } + + if (state.source.manifestVersion !== context.manifestVersion) { + issues.push(buildIssue('warning', 'manifest-version-mismatch', `Recorded manifest version ${state.source.manifestVersion} differs from current manifest version ${context.manifestVersion}`)); + } + + if (context.packageVersion && state.source.repoVersion && state.source.repoVersion !== context.packageVersion) { + issues.push(buildIssue('warning', 'repo-version-mismatch', `Recorded repo version ${state.source.repoVersion} differs from current repo version ${context.packageVersion}`)); + } + + if (!state.request.legacyMode) { + try { + const desiredPlan = resolveRecordedManifestPlan(record, context); + + if (!compareStringArrays(desiredPlan.selectedModuleIds, state.resolution.selectedModules) || !compareStringArrays(desiredPlan.skippedModuleIds, state.resolution.skippedModules)) { + issues.push( + buildIssue('warning', 'resolution-drift', 'Current manifest resolution differs from recorded install-state', { + expectedSelectedModules: desiredPlan.selectedModuleIds, + recordedSelectedModules: state.resolution.selectedModules, + expectedSkippedModules: desiredPlan.skippedModuleIds, + recordedSkippedModules: state.resolution.skippedModules + }) + ); + } + } catch (error) { + issues.push(buildIssue('error', 'resolution-unavailable', error.message)); + } + } + + return { + ...record, + status: determineStatus(issues), + issues + }; +} + +function buildDoctorReport(options = {}) { + const repoRoot = options.repoRoot || DEFAULT_REPO_ROOT; + const manifests = loadInstallManifests({ repoRoot }); + const records = discoverInstalledStates({ + homeDir: options.homeDir, + projectRoot: options.projectRoot, + targets: options.targets, + env: resolveInvocationEnvironment(options), + }).filter(record => record.exists); + const context = { + repoRoot, + homeDir: options.homeDir || process.env.HOME || os.homedir(), + projectRoot: options.projectRoot || process.cwd(), + env: resolveInvocationEnvironment(options), + manifestVersion: manifests.modulesVersion, + packageVersion: readPackageVersion(repoRoot) + }; + const results = records.map(record => analyzeRecord(record, context)); + const summary = results.reduce( + (accumulator, result) => { + const errorCount = result.issues.filter(issue => issue.severity === 'error').length; + const warningCount = result.issues.filter(issue => issue.severity === 'warning').length; + + return { + checkedCount: accumulator.checkedCount + 1, + okCount: accumulator.okCount + (result.status === 'ok' ? 1 : 0), + errorCount: accumulator.errorCount + errorCount, + warningCount: accumulator.warningCount + warningCount + }; + }, + { + checkedCount: 0, + okCount: 0, + errorCount: 0, + warningCount: 0 + } + ); + + return { + generatedAt: new Date().toISOString(), + packageVersion: context.packageVersion, + manifestVersion: context.manifestVersion, + results, + summary + }; +} + +function createRepairPlanFromRecord(record, context, options = {}) { + const state = record.state; + if (!state) { + throw new Error('No install-state available for repair'); + } + + if ( + record.legacyLayout !== 'opencode' + && (state.request.legacyMode || shouldRepairFromRecordedOperations(state)) + ) { + const operations = hydrateRecordedOperations( + context.repoRoot, + getManagedOperations(state), + record.targetRoot + ); + const statePreview = buildRecordedStatePreview(state, context, operations); + + return { + mode: state.request.legacyMode ? 'legacy' : 'recorded', + target: record.adapter.target, + adapter: record.adapter, + targetRoot: state.target.root, + installRoot: state.target.root, + installStatePath: state.target.installStatePath, + warnings: [], + languages: Array.isArray(state.request.legacyLanguages) ? [...state.request.legacyLanguages] : [], + operations, + statePreview + }; + } + + const desiredPlan = resolveRecordedManifestPlan(record, context, options); + + return { + ...desiredPlan, + statePreview: { + ...desiredPlan.statePreview, + installedAt: state.installedAt, + lastValidatedAt: new Date().toISOString() + } + }; +} + +function buildAdapterDerivedStatePreview(statePreview, record) { + return { + ...statePreview, + target: { + ...statePreview.target, + id: record.adapter.id, + target: record.adapter.target, + kind: record.adapter.kind, + root: record.targetRoot, + installStatePath: record.installStatePath + } + }; +} + +function assertValidInstallStateForWrite(state, label) { + const validation = validateInstallState(state); + if (validation.valid) { + return; + } + + const details = validation.errors + .map(error => `${error.instancePath || '/'} ${error.message}`) + .join('; '); + throw new Error(`Invalid install-state (${label}): ${details}`); +} + +function writeRefreshedInstallState(record, statePreview) { + const trustedStatePreview = buildAdapterDerivedStatePreview(statePreview, record); + const stateWithCurrentDigests = { + ...trustedStatePreview, + operations: (trustedStatePreview.operations || []).map(operation => { + if (!operation.destinationPath) { + return { ...operation }; + } + try { + const contentSha256 = crypto.createHash('sha256') + .update(readFileNoFollow(operation.destinationPath)) + .digest('hex'); + return { ...operation, contentSha256 }; + } catch (_error) { + const { contentSha256: _staleDigest, ...operationWithoutDigest } = operation; + return operationWithoutDigest; + } + }), + }; + assertValidInstallStateForWrite(stateWithCurrentDigests, record.installStatePath); + return writeContainedFile( + record.installStatePath, + formatJson(stateWithCurrentDigests), + record.targetRoot, + 'repair' + ); +} + +function prepareRepairMigration(plan, record) { + const trustedPlan = { + ...plan, + adapter: record.adapter, + targetRoot: record.targetRoot, + installRoot: record.targetRoot, + installStatePath: record.installStatePath, + statePreview: buildAdapterDerivedStatePreview(plan.statePreview, record), + }; + const migration = prepareClaudeSkillMigration(trustedPlan); + return { + migration, + plan: { + ...trustedPlan, + operations: migration.finalState.operations, + statePreview: migration.finalState, + warnings: [ + ...(Array.isArray(plan.warnings) ? plan.warnings : []), + ...migration.warnings, + ], + }, + }; +} + +function repairInstalledStates(options = {}) { + const repoRoot = options.repoRoot || DEFAULT_REPO_ROOT; + const manifests = loadInstallManifests({ repoRoot }); + const context = { + repoRoot, + homeDir: options.homeDir || process.env.HOME || os.homedir(), + projectRoot: options.projectRoot || process.cwd(), + env: resolveInvocationEnvironment(options), + manifestVersion: manifests.modulesVersion, + packageVersion: readPackageVersion(repoRoot) + }; + const buildOpencodeRunner = typeof options.buildOpencodePayload === 'function' + ? options.buildOpencodePayload + : buildOpencodePayload; + const records = discoverInstalledStates({ + homeDir: context.homeDir, + projectRoot: context.projectRoot, + targets: options.targets, + env: context.env, + }).filter(record => ( + record.exists + && (!record.legacy || record.legacyLayout === 'opencode') + )); + + const results = records.map(record => { + if (record.error) { + return { + adapter: record.adapter, + status: 'error', + installStatePath: record.installStatePath, + repairedPaths: [], + plannedRepairs: [], + error: record.error + }; + } + + let releaseSettingsLock = null; + try { + const settingsPathToLock = !options.dryRun + && getManagedOperations(record.state || {}).some( + operation => operation.kind === 'update-claude-settings' + ) + ? getClaudeSettingsPath(record.targetRoot) + : null; + if (settingsPathToLock) { + releaseSettingsLock = acquireSettingsLock(settingsPathToLock); + } + const needsOpencodeBuild = record.adapter.target === 'opencode' + && hasOpencodeBuildError(getOpencodeBuildValidationIssues(context)); + const opencodeBuildRepairPath = path.join(context.repoRoot, OPENCODE_BUILD_ARTIFACT); + + if (record.legacyLayout === 'opencode') { + if (needsOpencodeBuild && !options.dryRun) { + try { + buildOpencodeRunner(context.repoRoot); + } catch (error) { + return { + adapter: record.adapter, + status: 'error', + installStatePath: record.installStatePath, + repairedPaths: [], + plannedRepairs: [], + error: formatBuildErrorMessage(error), + }; + } + } + + const canonicalPlan = createRepairPlanFromRecord(record, context, { + exemptValidationCodes: options.dryRun && needsOpencodeBuild + ? [OPENCODE_PLUGIN_NOT_BUILT_CODE] + : [], + }); + const plannedRepairs = [...new Set([ + ...(needsOpencodeBuild ? [opencodeBuildRepairPath] : []), + ...canonicalPlan.operations.map(operation => operation.destinationPath), + ...getManagedOperations(record.state).map(operation => operation.destinationPath), + record.installStatePath, + ])]; + + if (options.dryRun) { + return { + adapter: record.adapter, + status: 'planned', + installStatePath: canonicalPlan.installStatePath, + repairedPaths: [], + plannedRepairs, + stateRefreshed: false, + warnings: canonicalPlan.warnings, + error: null, + }; + } + + // Load lazily to avoid a module cycle during install-lifecycle startup. + const { applyInstallPlan } = require('./install/apply'); + const appliedPlan = applyInstallPlan(canonicalPlan); + return { + adapter: record.adapter, + status: 'repaired', + installStatePath: canonicalPlan.installStatePath, + repairedPaths: [ + ...(needsOpencodeBuild ? [opencodeBuildRepairPath] : []), + ...canonicalPlan.operations.map(operation => operation.destinationPath), + ], + plannedRepairs: [], + stateRefreshed: true, + warnings: appliedPlan.warnings, + error: null, + }; + } + + if (needsOpencodeBuild && options.dryRun) { + const rawPlan = createRepairPlanFromRecord(record, context, { + exemptValidationCodes: [OPENCODE_PLUGIN_NOT_BUILT_CODE], + }); + const { plan: desiredPlan } = prepareRepairMigration(rawPlan, record); + const operationHealth = summarizeManagedOperationHealth( + context.repoRoot, + record.targetRoot, + desiredPlan.operations, + record.adapter.target + ); + const unsafeOperationResult = getUnsafeOperationResult( + record, + operationHealth + ); + if (unsafeOperationResult) { + return unsafeOperationResult; + } + const repairOperations = [...operationHealth.missing.map(entry => ({ ...entry.operation })), ...operationHealth.drifted.map(entry => ({ ...entry.operation }))]; + const plannedRepairs = [opencodeBuildRepairPath, ...repairOperations.map(operation => operation.destinationPath)]; + + return { + adapter: record.adapter, + status: 'planned', + installStatePath: record.installStatePath, + repairedPaths: [], + plannedRepairs, + stateRefreshed: false, + warnings: desiredPlan.warnings, + error: null + }; + } + + if (needsOpencodeBuild) { + try { + buildOpencodeRunner(context.repoRoot); + } catch (error) { + return { + adapter: record.adapter, + status: 'error', + installStatePath: record.installStatePath, + repairedPaths: [], + plannedRepairs: [], + error: formatBuildErrorMessage(error) + }; + } + } + + const rawPlan = createRepairPlanFromRecord(record, context); + const { + migration, + plan: desiredPlan, + } = prepareRepairMigration(rawPlan, record); + const operationHealth = summarizeManagedOperationHealth( + context.repoRoot, + record.targetRoot, + desiredPlan.operations, + record.adapter.target + ); + + const unsafeOperationResult = getUnsafeOperationResult( + record, + operationHealth + ); + if (unsafeOperationResult) { + return unsafeOperationResult; + } + + if (operationHealth.missingSource.length > 0) { + return { + adapter: record.adapter, + status: 'error', + installStatePath: record.installStatePath, + repairedPaths: [], + plannedRepairs: [], + warnings: desiredPlan.warnings, + error: `Missing source file(s): ${operationHealth.missingSource.map(entry => entry.sourcePath).join(', ')}` + }; + } + + const repairOperations = [ + ...operationHealth.missing.map(entry => ({ ...entry.operation })), + ...operationHealth.drifted.map(entry => ({ ...entry.operation })), + ...desiredPlan.operations + .filter(operation => ( + operation.kind === 'update-claude-settings' + && operation.previousManagedHooks + && !isDeepStrictEqual(operation.previousManagedHooks, operation.managedHooks) + )) + .map(operation => ({ ...operation })), + ].filter((operation, index, items) => items.findIndex(candidate => ( + candidate.kind === operation.kind + && candidate.destinationPath === operation.destinationPath + )) === index); + const repairLinkIndex = buildLinkIndexForOperations(desiredPlan.operations, record.targetRoot); + const legacyMigrationPaths = migration.legacyOperationsToRemove.map( + operation => operation.destinationPath + ); + const plannedRepairs = [...new Set([ + ...(needsOpencodeBuild ? [opencodeBuildRepairPath] : []), + ...repairOperations.map(operation => operation.destinationPath), + ...legacyMigrationPaths, + ])]; + + if (options.dryRun) { + return { + adapter: record.adapter, + status: plannedRepairs.length > 0 ? 'planned' : 'ok', + installStatePath: record.installStatePath, + repairedPaths: [], + plannedRepairs, + stateRefreshed: plannedRepairs.length === 0, + warnings: desiredPlan.warnings, + error: null + }; + } + + const hasLegacyMigration = migration.legacyOperationsToRemove.length > 0; + const repairedPaths = needsOpencodeBuild ? [opencodeBuildRepairPath] : []; + if (migration.requiresBridgeState && (repairOperations.length > 0 || hasLegacyMigration)) { + writeRefreshedInstallState(record, migration.bridgeState); + } + + for (const operation of repairOperations) { + const repairedPath = executeRepairOperation( + context.repoRoot, + operation, + record.targetRoot, + repairLinkIndex, + record.adapter.target, + Boolean(releaseSettingsLock) + ); + if (repairedPath) { + repairedPaths.push(repairedPath); + } + } + if (hasLegacyMigration) { + for (const operation of migration.legacyOperationsToRemove) { + const removedPath = removeContainedPath( + operation.destinationPath, + record.targetRoot, + 'migrate managed Claude skill', + { force: true } + ); + if (removedPath) { + repairedPaths.push(removedPath); + } + } + } + const changedInstalledBytes = repairOperations.length > 0 + || needsOpencodeBuild + || hasLegacyMigration; + const statePreviewToWrite = changedInstalledBytes + ? desiredPlan.statePreview + : { + ...desiredPlan.statePreview, + installedAt: record.state.installedAt, + source: { ...record.state.source }, + }; + writeRefreshedInstallState(record, statePreviewToWrite); + + return { + adapter: record.adapter, + status: (repairOperations.length > 0 || needsOpencodeBuild || hasLegacyMigration) + ? 'repaired' + : 'ok', + installStatePath: record.installStatePath, + repairedPaths, + plannedRepairs: [], + stateRefreshed: true, + warnings: desiredPlan.warnings, + error: null + }; + } catch (error) { + return { + adapter: record.adapter, + status: 'error', + installStatePath: record.installStatePath, + repairedPaths: [], + plannedRepairs: [], + error: error.message + }; + } finally { + if (releaseSettingsLock) releaseSettingsLock(); + } + }); + + const summary = results.reduce( + (accumulator, result) => ({ + checkedCount: accumulator.checkedCount + 1, + repairedCount: accumulator.repairedCount + (result.status === 'repaired' ? 1 : 0), + plannedRepairCount: accumulator.plannedRepairCount + (result.status === 'planned' ? 1 : 0), + errorCount: accumulator.errorCount + (result.status === 'error' ? 1 : 0) + }), + { + checkedCount: 0, + repairedCount: 0, + plannedRepairCount: 0, + errorCount: 0 + } + ); + + return { + dryRun: Boolean(options.dryRun), + generatedAt: new Date().toISOString(), + results, + summary + }; +} + +function cleanupEmptyParentDirs(filePath, stopAt) { + const trustedStopAt = assertWithinTrustedRoot(stopAt, stopAt, 'clean up'); + const trustedFilePath = assertWithinTrustedRoot(filePath, trustedStopAt, 'clean up'); + let currentPath = path.dirname(trustedFilePath); + + while (currentPath) { + const relativePath = path.relative(trustedStopAt, currentPath); + const isContained = relativePath !== '..' + && !relativePath.startsWith(`..${path.sep}`) + && !path.isAbsolute(relativePath); + if (!isContained || relativePath === '') { + break; + } + + let validatedPath = assertWithinTrustedRoot(currentPath, trustedStopAt, 'clean up'); + if (!fs.existsSync(validatedPath)) { + currentPath = path.dirname(validatedPath); + continue; + } + + validatedPath = assertWithinTrustedRoot(validatedPath, trustedStopAt, 'clean up'); + const stat = fs.lstatSync(validatedPath); + if (!stat.isDirectory() || stat.isSymbolicLink()) { + break; + } + + validatedPath = assertWithinTrustedRoot(validatedPath, trustedStopAt, 'clean up'); + if (fs.readdirSync(validatedPath).length > 0) { + break; + } + + const finalPath = assertWithinTrustedRoot(validatedPath, trustedStopAt, 'clean up'); + const removedPath = removeContainedPath(finalPath, trustedStopAt, 'clean up'); + if (!removedPath) break; + currentPath = path.dirname(removedPath); + } +} + +function uninstallInstalledStates(options = {}) { + const records = discoverInstalledStates({ + homeDir: options.homeDir, + projectRoot: options.projectRoot, + targets: options.targets, + env: resolveInvocationEnvironment(options), + }).filter(record => record.exists); + + const results = records.map(record => { + if (record.error || !record.state) { + return { + adapter: record.adapter, + status: 'error', + installStatePath: record.installStatePath, + removedPaths: [], + plannedRemovals: [], + error: record.error || 'No valid install-state available' + }; + } + + const state = record.state; + const managedOperations = getManagedOperations(state); + if (record.legacyLayout === 'antigravity' && managedOperations.length > 0) { + return { + adapter: record.adapter, + status: 'partial', + installStatePath: record.installStatePath, + removedPaths: [], + plannedRemovals: [], + retainedPaths: managedOperations.map(operation => operation.destinationPath), + warning: 'Legacy Antigravity files were preserved because their provenance cannot be revalidated during uninstall. Rerun the Antigravity installer to migrate verified files, then review .agent manually.', + error: null + }; + } + const plannedRemovals = Array.from(new Set([ + ...managedOperations.map(operation => operation.destinationPath), + record.installStatePath + ])); + + if (options.dryRun) { + return { + adapter: record.adapter, + status: 'planned', + installStatePath: record.installStatePath, + removedPaths: [], + plannedRemovals, + error: null + }; + } + + let releaseSettingsLock = null; + try { + const removedPaths = []; + const cleanupTargets = []; + const retainedPaths = []; + const operations = getManagedOperations(state); + if (operations.some(operation => operation.kind === 'update-claude-settings')) { + releaseSettingsLock = acquireSettingsLock( + getClaudeSettingsPath(record.targetRoot) + ); + } + + for (const operation of operations) { + const outcome = executeUninstallOperation(operation, record.targetRoot, { + preserveDriftedCopies: true, + target: record.adapter.target, + settingsLockHeld: Boolean(releaseSettingsLock), + }); + removedPaths.push(...outcome.removedPaths); + cleanupTargets.push(...outcome.cleanupTargets); + retainedPaths.push(...(outcome.retainedPaths || [])); + } + + if (retainedPaths.length === 0) { + const removedStatePath = removeContainedPath( + record.installStatePath, + record.targetRoot, + 'uninstall', + { force: true } + ); + if (removedStatePath) { + removedPaths.push(record.installStatePath); + cleanupTargets.push(removedStatePath); + } + } + + for (const cleanupTarget of cleanupTargets) { + cleanupEmptyParentDirs(cleanupTarget, record.targetRoot); + } + + return { + adapter: record.adapter, + status: retainedPaths.length > 0 ? 'partial' : 'uninstalled', + installStatePath: record.installStatePath, + removedPaths, + retainedPaths: [...new Set(retainedPaths)].sort(), + plannedRemovals: [], + warning: retainedPaths.length > 0 + ? 'Modified or unverifiable managed files were preserved together with install-state for review.' + : null, + error: null + }; + } catch (error) { + return { + adapter: record.adapter, + status: 'error', + installStatePath: record.installStatePath, + removedPaths: [], + plannedRemovals, + error: error.message + }; + } finally { + if (releaseSettingsLock) releaseSettingsLock(); + } + }); + + const summary = results.reduce( + (accumulator, result) => ({ + checkedCount: accumulator.checkedCount + 1, + uninstalledCount: accumulator.uninstalledCount + (result.status === 'uninstalled' ? 1 : 0), + plannedRemovalCount: accumulator.plannedRemovalCount + (result.status === 'planned' ? 1 : 0), + partialCount: accumulator.partialCount + (result.status === 'partial' ? 1 : 0), + errorCount: accumulator.errorCount + (result.status === 'error' ? 1 : 0) + }), + { + checkedCount: 0, + uninstalledCount: 0, + plannedRemovalCount: 0, + partialCount: 0, + errorCount: 0 + } + ); + + return { + dryRun: Boolean(options.dryRun), + generatedAt: new Date().toISOString(), + results, + summary + }; +} + +module.exports = { + DEFAULT_REPO_ROOT, + buildDoctorReport, + discoverInstalledStates, + normalizeTargets, + repairInstalledStates, + uninstallInstalledStates +}; diff --git a/github_code/affaan-m__ECC/scripts/lib/install-manifests.js b/github_code/affaan-m__ECC/scripts/lib/install-manifests.js new file mode 100644 index 0000000000000000000000000000000000000000..bb16cc93c89bbda4c2c4f493baeab6188d6985eb --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/install-manifests.js @@ -0,0 +1,757 @@ +const fs = require('fs'); +const os = require('os'); +const path = require('path'); +const { getInstallTargetAdapter, planInstallTargetScaffold } = require('./install-targets/registry'); +const { resolveInvocationEnvironment } = require('./invocation-environment'); + +const DEFAULT_REPO_ROOT = path.join(__dirname, '../..'); +const SUPPORTED_INSTALL_TARGETS = ['claude', 'claude-project', 'cursor', 'antigravity', 'codex', 'gemini', 'opencode', 'codebuddy', 'joycode', 'qwen', 'zed', 'hermes', 'openclaw', 'kimi', 'adal']; +const COMPONENT_FAMILY_PREFIXES = { + baseline: 'baseline:', + language: 'lang:', + framework: 'framework:', + capability: 'capability:', + agent: 'agent:', + skill: 'skill:', + locale: 'locale:', +}; +const SUPPORTED_LOCALES = Object.freeze(['ja', 'zh-CN', 'ko-KR', 'pt-BR', 'ru', 'tr', 'vi-VN', 'zh-TW', 'de-DE', 'uk-UA']); +const LOCALE_ALIAS_TO_COMPONENT_ID = Object.freeze({ + 'ja': 'locale:ja', + 'ja-JP': 'locale:ja', + 'zh-CN': 'locale:zh-cn', + 'zh': 'locale:zh-cn', + 'ko-KR': 'locale:ko-kr', + 'ko': 'locale:ko-kr', + 'pt-BR': 'locale:pt-br', + 'pt': 'locale:pt-br', + 'ru': 'locale:ru', + 'tr': 'locale:tr', + 'vi-VN': 'locale:vi-vn', + 'vi': 'locale:vi-vn', + 'zh-TW': 'locale:zh-tw', + 'de-DE': 'locale:de-de', + 'de': 'locale:de-de', + 'uk-UA': 'locale:uk-ua', + 'uk': 'locale:uk-ua' +}); + +function listSupportedLocales() { + return [...SUPPORTED_LOCALES]; +} +const LEGACY_COMPAT_BASE_MODULE_IDS_BY_TARGET = Object.freeze({ + claude: [ + 'rules-core', + 'agents-core', + 'commands-core', + 'hooks-runtime', + 'platform-configs', + 'workflow-quality', + ], + 'claude-project': [ + 'rules-core', + 'agents-core', + 'commands-core', + 'hooks-runtime', + 'platform-configs', + 'workflow-quality', + ], + cursor: [ + 'rules-core', + 'agents-core', + 'commands-core', + 'hooks-runtime', + 'platform-configs', + 'workflow-quality', + ], + antigravity: [ + 'rules-core', + 'agents-core', + 'commands-core', + 'skill-unified-memory', + 'workflow-quality', + ], + zed: [ + 'rules-core', + 'agents-core', + 'commands-core', + 'platform-configs', + 'workflow-quality', + ], + hermes: [ + 'rules-core', + 'agents-core', + 'commands-core', + 'platform-configs', + 'workflow-quality', + ], + openclaw: [ + 'rules-core', + 'agents-core', + 'commands-core', + 'platform-configs', + 'workflow-quality', + ], + kimi: [ + 'rules-core', + 'agents-core', + 'commands-core', + 'platform-configs', + 'workflow-quality', + ], + adal: [ + 'rules-core', + 'agents-core', + 'commands-core', + 'platform-configs', + 'workflow-quality', + ], +}); +const LEGACY_LANGUAGE_ALIAS_TO_CANONICAL = Object.freeze({ + c: 'c', + cpp: 'cpp', + csharp: 'csharp', + fsharp: 'fsharp', + go: 'go', + golang: 'go', + arkts: 'arkts', + harmonyos: 'arkts', + java: 'java', + javascript: 'typescript', + kotlin: 'java', + perl: 'perl', + php: 'php', + python: 'python', + rails: 'ruby', + ruby: 'ruby', + rust: 'rust', + swift: 'swift', + typescript: 'typescript', +}); +const LEGACY_LANGUAGE_EXTRA_MODULE_IDS = Object.freeze({ + c: ['framework-language'], + cpp: ['framework-language'], + csharp: ['framework-language'], + fsharp: ['framework-language'], + go: ['framework-language'], + arkts: ['framework-language'], + java: ['framework-language'], + perl: [], + php: [], + python: ['framework-language'], + ruby: ['framework-language', 'security'], + rust: ['framework-language'], + swift: [], + typescript: ['framework-language'], +}); +const LEGACY_LANGUAGE_RULE_NAMESPACES = Object.freeze({ + c: 'cpp', + harmonyos: 'arkts', + javascript: 'typescript', + go: 'golang', + golang: 'golang', + rails: 'ruby', +}); +const TARGET_DEFAULT_PROFILE_IDS = Object.freeze({ + opencode: 'opencode', +}); +const TARGET_DEFAULT_EXCLUSIONS = Object.freeze({ + opencode: [ + { + moduleId: 'hooks-runtime', + reason: 'OpenCode defaults intentionally exclude hooks-runtime until users opt in.', + optInCommand: './install.sh --target opencode --modules hooks-runtime', + }, + ], +}); + +function readJson(filePath, label) { + try { + return JSON.parse(fs.readFileSync(filePath, 'utf8')); + } catch (error) { + throw new Error(`Failed to read ${label}: ${error.message}`); + } +} + +function dedupeStrings(values) { + return [...new Set((Array.isArray(values) ? values : []).map(value => String(value).trim()).filter(Boolean))]; +} + +function listSkillDirectoryIds(repoRoot) { + const skillsRoot = path.join(repoRoot, 'skills'); + if (!fs.existsSync(skillsRoot) || !fs.statSync(skillsRoot).isDirectory()) { + return []; + } + + return fs.readdirSync(skillsRoot, { withFileTypes: true }) + .filter(entry => entry.isDirectory()) + .map(entry => entry.name) + .sort(); +} + +function addSyntheticSkillComponents({ repoRoot, modules, components }) { + const moduleIds = new Set(modules.map(module => module.id)); + const componentIds = new Set(components.map(component => component.id)); + + for (const skillId of listSkillDirectoryIds(repoRoot)) { + const componentId = `skill:${skillId}`; + if (componentIds.has(componentId)) { + continue; + } + + const moduleId = `skill-${skillId}`; + if (!moduleIds.has(moduleId)) { + modules.push({ + id: moduleId, + kind: 'skills', + description: `Single-skill install surface for ${skillId}.`, + paths: [`skills/${skillId}`], + targets: SUPPORTED_INSTALL_TARGETS.slice(), + dependencies: [], + defaultInstall: false, + cost: 'light', + stability: 'stable', + synthetic: true, + }); + moduleIds.add(moduleId); + } + + components.push({ + id: componentId, + family: 'skill', + description: `Install only the ${skillId} skill directory.`, + modules: [moduleId], + synthetic: true, + }); + componentIds.add(componentId); + } +} + +function readOptionalStringOption(options, key) { + if ( + !Object.prototype.hasOwnProperty.call(options, key) + || options[key] === null + || options[key] === undefined + ) { + return null; + } + + if (typeof options[key] !== 'string' || options[key].trim() === '') { + throw new Error(`${key} must be a non-empty string when provided`); + } + + return options[key]; +} + +function readModuleTargetsOrThrow(module) { + const moduleId = module && module.id ? module.id : ''; + const targets = module && module.targets; + + if (!Array.isArray(targets)) { + throw new Error(`Install module ${moduleId} has invalid targets; expected an array of supported target ids`); + } + + const normalizedTargets = targets.map(target => ( + typeof target === 'string' ? target.trim() : '' + )); + + if (normalizedTargets.some(target => target.length === 0)) { + throw new Error(`Install module ${moduleId} has invalid targets; expected an array of supported target ids`); + } + + const unsupportedTargets = normalizedTargets.filter(target => !SUPPORTED_INSTALL_TARGETS.includes(target)); + if (unsupportedTargets.length > 0) { + throw new Error( + `Install module ${moduleId} has unsupported targets: ${unsupportedTargets.join(', ')}` + ); + } + + return normalizedTargets; +} + +function assertKnownModuleIds(moduleIds, manifests) { + const unknownModuleIds = dedupeStrings(moduleIds) + .filter(moduleId => !manifests.modulesById.has(moduleId)); + + if (unknownModuleIds.length === 1) { + throw new Error(`Unknown install module: ${unknownModuleIds[0]}`); + } + + if (unknownModuleIds.length > 1) { + throw new Error(`Unknown install modules: ${unknownModuleIds.join(', ')}`); + } +} + +function intersectTargets(modules) { + if (!Array.isArray(modules) || modules.length === 0) { + return []; + } + + return SUPPORTED_INSTALL_TARGETS.filter(target => ( + modules.every(module => Array.isArray(module.targets) && module.targets.includes(target)) + )); +} + +function getManifestPaths(repoRoot = DEFAULT_REPO_ROOT) { + return { + modulesPath: path.join(repoRoot, 'manifests', 'install-modules.json'), + profilesPath: path.join(repoRoot, 'manifests', 'install-profiles.json'), + componentsPath: path.join(repoRoot, 'manifests', 'install-components.json'), + }; +} + +function loadInstallManifests(options = {}) { + const repoRoot = options.repoRoot || DEFAULT_REPO_ROOT; + const { modulesPath, profilesPath, componentsPath } = getManifestPaths(repoRoot); + + if (!fs.existsSync(modulesPath) || !fs.existsSync(profilesPath)) { + throw new Error(`Install manifests not found under ${repoRoot}`); + } + + const modulesData = readJson(modulesPath, 'install-modules.json'); + const profilesData = readJson(profilesPath, 'install-profiles.json'); + const componentsData = fs.existsSync(componentsPath) + ? readJson(componentsPath, 'install-components.json') + : { version: null, components: [] }; + const modules = Array.isArray(modulesData.modules) ? modulesData.modules.slice() : []; + const profiles = profilesData && typeof profilesData.profiles === 'object' + ? profilesData.profiles + : {}; + const components = Array.isArray(componentsData.components) ? componentsData.components.slice() : []; + + addSyntheticSkillComponents({ repoRoot, modules, components }); + + for (const module of modules) { + readModuleTargetsOrThrow(module); + } + + const modulesById = new Map(modules.map(module => [module.id, module])); + const componentsById = new Map(components.map(component => [component.id, component])); + + return { + repoRoot, + modulesPath, + profilesPath, + componentsPath, + modules, + profiles, + components, + modulesById, + componentsById, + modulesVersion: modulesData.version, + profilesVersion: profilesData.version, + componentsVersion: componentsData.version, + }; +} + +function listInstallProfiles(options = {}) { + const manifests = loadInstallManifests(options); + return Object.entries(manifests.profiles).map(([id, profile]) => ({ + id, + description: profile.description, + moduleCount: Array.isArray(profile.modules) ? profile.modules.length : 0, + })); +} + +function listInstallModules(options = {}) { + const manifests = loadInstallManifests(options); + return manifests.modules.map(module => ({ + id: module.id, + kind: module.kind, + description: module.description, + targets: module.targets, + defaultInstall: module.defaultInstall, + cost: module.cost, + stability: module.stability, + dependencyCount: Array.isArray(module.dependencies) ? module.dependencies.length : 0, + })); +} + +function listLegacyCompatibilityLanguages() { + return Object.keys(LEGACY_LANGUAGE_ALIAS_TO_CANONICAL).sort(); +} + +function validateInstallModuleIds(moduleIds, options = {}) { + const manifests = loadInstallManifests(options); + const normalizedModuleIds = dedupeStrings(moduleIds); + assertKnownModuleIds(normalizedModuleIds, manifests); + return normalizedModuleIds; +} + +function listInstallComponents(options = {}) { + const manifests = loadInstallManifests(options); + const family = options.family || null; + const target = options.target || null; + + if (family && !Object.hasOwn(COMPONENT_FAMILY_PREFIXES, family)) { + throw new Error( + `Unknown component family: ${family}. Expected one of ${Object.keys(COMPONENT_FAMILY_PREFIXES).join(', ')}` + ); + } + + if (target && !SUPPORTED_INSTALL_TARGETS.includes(target)) { + throw new Error( + `Unknown install target: ${target}. Expected one of ${SUPPORTED_INSTALL_TARGETS.join(', ')}` + ); + } + + return manifests.components + .filter(component => !family || component.family === family) + .map(component => { + const moduleIds = dedupeStrings(component.modules); + const modules = moduleIds + .map(moduleId => manifests.modulesById.get(moduleId)) + .filter(Boolean); + const targets = intersectTargets(modules); + + return { + id: component.id, + family: component.family, + description: component.description, + moduleIds, + moduleCount: moduleIds.length, + targets, + }; + }) + .filter(component => !target || component.targets.includes(target)); +} + +function getInstallComponent(componentId, options = {}) { + const manifests = loadInstallManifests(options); + const normalizedComponentId = String(componentId || '').trim(); + + if (!normalizedComponentId) { + throw new Error('An install component ID is required'); + } + + const component = manifests.componentsById.get(normalizedComponentId); + if (!component) { + throw new Error(`Unknown install component: ${normalizedComponentId}`); + } + + const moduleIds = dedupeStrings(component.modules); + const modules = moduleIds + .map(moduleId => manifests.modulesById.get(moduleId)) + .filter(Boolean) + .map(module => ({ + id: module.id, + kind: module.kind, + description: module.description, + targets: module.targets, + defaultInstall: module.defaultInstall, + cost: module.cost, + stability: module.stability, + dependencies: dedupeStrings(module.dependencies), + })); + + return { + id: component.id, + family: component.family, + description: component.description, + moduleIds, + moduleCount: moduleIds.length, + targets: intersectTargets(modules), + modules, + }; +} + +function expandComponentIdsToModuleIds(componentIds, manifests) { + const expandedModuleIds = []; + + for (const componentId of dedupeStrings(componentIds)) { + const component = manifests.componentsById.get(componentId); + if (!component) { + throw new Error(`Unknown install component: ${componentId}`); + } + expandedModuleIds.push(...component.modules); + } + + return dedupeStrings(expandedModuleIds); +} + +function getTargetDefaultProfileId(target, manifests) { + const profileId = target ? TARGET_DEFAULT_PROFILE_IDS[target] : null; + return profileId && manifests.profiles[profileId] ? profileId : null; +} + +function getTargetDefaultExclusions(target, manifests) { + const exclusions = target ? TARGET_DEFAULT_EXCLUSIONS[target] : null; + if (!Array.isArray(exclusions)) { + return []; + } + + return exclusions + .filter(exclusion => manifests.modulesById.has(exclusion.moduleId)) + .map(exclusion => ({ ...exclusion })); +} + +function resolveLegacyCompatibilitySelection(options = {}) { + const manifests = loadInstallManifests(options); + const target = options.target || null; + + if (target && !SUPPORTED_INSTALL_TARGETS.includes(target)) { + throw new Error( + `Unknown install target: ${target}. Expected one of ${SUPPORTED_INSTALL_TARGETS.join(', ')}` + ); + } + + const legacyLanguages = dedupeStrings(options.legacyLanguages) + .map(language => language.toLowerCase()); + const normalizedLegacyLanguages = dedupeStrings(legacyLanguages); + + if (normalizedLegacyLanguages.length === 0) { + throw new Error('No legacy languages were provided'); + } + + const unknownLegacyLanguages = normalizedLegacyLanguages + .filter(language => !Object.hasOwn(LEGACY_LANGUAGE_ALIAS_TO_CANONICAL, language)); + + if (unknownLegacyLanguages.length === 1) { + throw new Error( + `Unknown legacy language: ${unknownLegacyLanguages[0]}. Expected one of ${listLegacyCompatibilityLanguages().join(', ')}` + ); + } + + if (unknownLegacyLanguages.length > 1) { + throw new Error( + `Unknown legacy languages: ${unknownLegacyLanguages.join(', ')}. Expected one of ${listLegacyCompatibilityLanguages().join(', ')}` + ); + } + + const canonicalLegacyLanguages = normalizedLegacyLanguages + .map(language => LEGACY_LANGUAGE_ALIAS_TO_CANONICAL[language]); + const ruleLanguages = normalizedLegacyLanguages.map(language => ( + LEGACY_LANGUAGE_RULE_NAMESPACES[language] || language + )); + const baseModuleIds = LEGACY_COMPAT_BASE_MODULE_IDS_BY_TARGET[target || 'claude'] + || LEGACY_COMPAT_BASE_MODULE_IDS_BY_TARGET.claude; + const moduleIds = dedupeStrings([ + ...baseModuleIds, + ...(target === 'antigravity' + ? [] + : canonicalLegacyLanguages.flatMap(language => LEGACY_LANGUAGE_EXTRA_MODULE_IDS[language] || [])), + ]); + + assertKnownModuleIds(moduleIds, manifests); + + return { + legacyLanguages: normalizedLegacyLanguages, + canonicalLegacyLanguages, + ruleLanguages, + moduleIds, + }; +} + +function resolveInstallPlan(options = {}) { + const manifests = loadInstallManifests(options); + const requestedProfileId = options.profileId || null; + const explicitModuleIds = dedupeStrings(options.moduleIds); + const includedComponentIds = dedupeStrings(options.includeComponentIds); + const excludedComponentIds = dedupeStrings(options.excludeComponentIds); + const requestedModuleIds = []; + const target = options.target || null; + + if (target && !SUPPORTED_INSTALL_TARGETS.includes(target)) { + throw new Error( + `Unknown install target: ${target}. Expected one of ${SUPPORTED_INSTALL_TARGETS.join(', ')}` + ); + } + + const shouldUseTargetDefaultProfile = !requestedProfileId + && explicitModuleIds.length === 0 + && includedComponentIds.length === 0; + const targetDefaultProfileId = shouldUseTargetDefaultProfile + ? getTargetDefaultProfileId(target, manifests) + : null; + const profileId = requestedProfileId || targetDefaultProfileId; + const targetDefaultExclusions = targetDefaultProfileId + ? getTargetDefaultExclusions(target, manifests) + : []; + + if (profileId) { + const profile = manifests.profiles[profileId]; + if (!profile) { + throw new Error(`Unknown install profile: ${profileId}`); + } + requestedModuleIds.push(...profile.modules); + } + + requestedModuleIds.push(...explicitModuleIds); + requestedModuleIds.push(...expandComponentIdsToModuleIds(includedComponentIds, manifests)); + + const excludedModuleIds = expandComponentIdsToModuleIds(excludedComponentIds, manifests); + const excludedModuleOwners = new Map(); + for (const componentId of excludedComponentIds) { + const component = manifests.componentsById.get(componentId); + if (!component) { + throw new Error(`Unknown install component: ${componentId}`); + } + for (const moduleId of component.modules) { + const owners = excludedModuleOwners.get(moduleId) || []; + owners.push(componentId); + excludedModuleOwners.set(moduleId, owners); + } + } + for (const exclusion of targetDefaultExclusions) { + const owners = excludedModuleOwners.get(exclusion.moduleId) || []; + owners.push(`${target} default`); + excludedModuleOwners.set(exclusion.moduleId, owners); + } + + const validatedProjectRoot = readOptionalStringOption(options, 'projectRoot'); + const validatedHomeDir = readOptionalStringOption(options, 'homeDir'); + const targetPlanningInput = target + ? { + repoRoot: manifests.repoRoot, + projectRoot: validatedProjectRoot || manifests.repoRoot, + homeDir: validatedHomeDir || os.homedir(), + env: resolveInvocationEnvironment(options), + } + : null; + const targetAdapter = target ? getInstallTargetAdapter(target) : null; + + const effectiveRequestedIds = dedupeStrings( + requestedModuleIds.filter(moduleId => !excludedModuleOwners.has(moduleId)) + ); + + if (requestedModuleIds.length === 0) { + throw new Error('No install profile, module IDs, or included component IDs were provided'); + } + + if (effectiveRequestedIds.length === 0) { + throw new Error('Selection excludes every requested install module'); + } + + const selectedIds = new Set(); + const skippedTargetIds = new Set(); + const excludedIds = new Set([ + ...excludedModuleIds, + ...targetDefaultExclusions.map(exclusion => exclusion.moduleId), + ]); + const visitingIds = new Set(); + const resolvedIds = new Set(); + + function resolveModule(moduleId, dependencyOf, rootRequesterId) { + const module = manifests.modulesById.get(moduleId); + if (!module) { + throw new Error(`Unknown install module: ${moduleId}`); + } + + if (excludedModuleOwners.has(moduleId)) { + if (dependencyOf) { + const owners = excludedModuleOwners.get(moduleId) || []; + throw new Error( + `Module ${dependencyOf} depends on excluded module ${moduleId}${owners.length > 0 ? ` (excluded by ${owners.join(', ')})` : ''}` + ); + } + return; + } + + const supportsTarget = !target + || ( + readModuleTargetsOrThrow(module).includes(target) + && (!targetAdapter || targetAdapter.supportsModule(module, targetPlanningInput)) + ); + + if (!supportsTarget) { + if (dependencyOf) { + skippedTargetIds.add(rootRequesterId || dependencyOf); + return false; + } + skippedTargetIds.add(moduleId); + return false; + } + + if (resolvedIds.has(moduleId)) { + return true; + } + + if (visitingIds.has(moduleId)) { + throw new Error(`Circular install dependency detected at ${moduleId}`); + } + + visitingIds.add(moduleId); + for (const dependencyId of module.dependencies) { + const dependencyResolved = resolveModule( + dependencyId, + moduleId, + rootRequesterId || moduleId + ); + if (!dependencyResolved) { + visitingIds.delete(moduleId); + if (!dependencyOf) { + skippedTargetIds.add(moduleId); + } + return false; + } + } + visitingIds.delete(moduleId); + resolvedIds.add(moduleId); + selectedIds.add(moduleId); + return true; + } + + for (const moduleId of effectiveRequestedIds) { + resolveModule(moduleId, null, moduleId); + } + + const selectedModules = manifests.modules.filter(module => selectedIds.has(module.id)); + const skippedModules = manifests.modules.filter(module => skippedTargetIds.has(module.id)); + const excludedModules = manifests.modules.filter(module => excludedIds.has(module.id)); + const scaffoldPlan = target + ? planInstallTargetScaffold({ + target, + repoRoot: targetPlanningInput.repoRoot, + projectRoot: targetPlanningInput.projectRoot, + homeDir: targetPlanningInput.homeDir, + env: targetPlanningInput.env, + modules: selectedModules, + exemptValidationCodes: options.exemptValidationCodes || [], + }) + : null; + + return { + repoRoot: manifests.repoRoot, + profileId, + target, + requestedModuleIds: effectiveRequestedIds, + explicitModuleIds, + includedComponentIds, + excludedComponentIds, + targetDefaultProfileId, + targetDefaultExclusions, + warnings: targetDefaultExclusions.map(exclusion => ( + `${exclusion.moduleId} is intentionally excluded from the OpenCode default. ` + + `Opt in with: ${exclusion.optInCommand}` + )), + selectedModuleIds: selectedModules.map(module => module.id), + skippedModuleIds: skippedModules.map(module => module.id), + excludedModuleIds: excludedModules.map(module => module.id), + selectedModules, + skippedModules, + excludedModules, + targetAdapterId: scaffoldPlan ? scaffoldPlan.adapter.id : null, + homeDir: targetPlanningInput ? targetPlanningInput.homeDir : null, + targetRoot: scaffoldPlan ? scaffoldPlan.targetRoot : null, + installStatePath: scaffoldPlan ? scaffoldPlan.installStatePath : null, + operations: scaffoldPlan ? scaffoldPlan.operations : [], + }; +} + +module.exports = { + DEFAULT_REPO_ROOT, + SUPPORTED_INSTALL_TARGETS, + SUPPORTED_LOCALES, + LOCALE_ALIAS_TO_COMPONENT_ID, + getManifestPaths, + loadInstallManifests, + getInstallComponent, + listInstallComponents, + listLegacyCompatibilityLanguages, + listSupportedLocales, + listInstallModules, + listInstallProfiles, + resolveInstallPlan, + resolveLegacyCompatibilitySelection, + validateInstallModuleIds, +}; diff --git a/github_code/affaan-m__ECC/scripts/lib/install-state-store-sync.js b/github_code/affaan-m__ECC/scripts/lib/install-state-store-sync.js new file mode 100644 index 0000000000000000000000000000000000000000..fb31c6aa04712e85f95ef4ddd894d0599c58e228 --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/install-state-store-sync.js @@ -0,0 +1,62 @@ +'use strict'; + +const { + createStateStore, + projectInstallState, + reconcileCurrentInstallState, +} = require('./state-store'); + +function openFailure(error) { + const warning = { + code: 'projection-open-failed', + message: error.message, + }; + return { + status: 'warning', + warningCount: 1, + warnings: [warning], + warning, + }; +} + +async function withStateStore(options, operation) { + const openStore = options.createStore || createStateStore; + let store; + try { + store = await openStore({ + dbPath: options.dbPath, + homeDir: options.homeDir, + }); + return await operation(store); + } catch (error) { + return openFailure(error); + } finally { + if (store) { + try { + store.close(); + } catch (_error) { + // Projection is a derived cache. A close failure must not invalidate + // the canonical JSON install-state or a completed file operation. + } + } + } +} + +async function projectCanonicalInstallState(state, options = {}) { + return withStateStore(options, store => projectInstallState(store, state)); +} + +async function reconcileCanonicalInstallStates(options = {}) { + return withStateStore(options, store => reconcileCurrentInstallState(store, { + homeDir: options.homeDir, + projectRoot: options.projectRoot, + targets: options.targets, + env: options.env, + discoverInstalledStates: options.discoverInstalledStates, + })); +} + +module.exports = { + projectCanonicalInstallState, + reconcileCanonicalInstallStates, +}; diff --git a/github_code/affaan-m__ECC/scripts/lib/install-state.js b/github_code/affaan-m__ECC/scripts/lib/install-state.js new file mode 100644 index 0000000000000000000000000000000000000000..3b5b7fc231a65ae8099734eb5f4af85b7e71f51d --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/install-state.js @@ -0,0 +1,354 @@ +const fs = require('fs'); +const path = require('path'); +const { + CLAUDE_HOOKS_CONFIG_PATH, + getClaudeSettingsPath, + validateRecordedManagedHooks, +} = require('./install/claude-settings'); + +// Dependency-free, self-contained validation. The installer closure must not +// require any non-builtin package (enterprise supply-chain vetting: the vetted +// bytes must be the installed bytes). install-state is validated by the +// hand-rolled validator below, which enforces the same constraints as +// schemas/install-state.schema.json (ecc.install.v1). + +let cachedValidator = null; + +function cloneJsonValue(value) { + if (value === undefined) { + return undefined; + } + + return JSON.parse(JSON.stringify(value)); +} + +function readJson(filePath, label) { + try { + return JSON.parse(fs.readFileSync(filePath, 'utf8')); + } catch (error) { + throw new Error(`Failed to read ${label}: ${error.message}`); + } +} + +function getValidator() { + if (cachedValidator) { + return cachedValidator; + } + + cachedValidator = createFallbackValidator(); + return cachedValidator; +} + +function createFallbackValidator() { + const validate = state => { + const errors = []; + validate.errors = errors; + + function pushError(instancePath, message) { + errors.push({ + instancePath, + message, + }); + } + + function isNonEmptyString(value) { + return typeof value === 'string' && value.length > 0; + } + + function validateNoAdditionalProperties(value, instancePath, allowedKeys) { + for (const key of Object.keys(value)) { + if (!allowedKeys.includes(key)) { + pushError(`${instancePath}/${key}`, 'must NOT have additional properties'); + } + } + } + + function validateStringArray(value, instancePath) { + if (!Array.isArray(value)) { + pushError(instancePath, 'must be array'); + return; + } + + for (let index = 0; index < value.length; index += 1) { + if (!isNonEmptyString(value[index])) { + pushError(`${instancePath}/${index}`, 'must be non-empty string'); + } + } + } + + function validateOptionalString(value, instancePath) { + if (value !== undefined && value !== null && !isNonEmptyString(value)) { + pushError(instancePath, 'must be string or null'); + } + } + + if (!state || typeof state !== 'object' || Array.isArray(state)) { + pushError('/', 'must be object'); + return false; + } + + validateNoAdditionalProperties( + state, + '', + ['schemaVersion', 'installedAt', 'lastValidatedAt', 'target', 'request', 'resolution', 'source', 'operations'] + ); + + if (state.schemaVersion !== 'ecc.install.v1') { + pushError('/schemaVersion', 'must equal ecc.install.v1'); + } + + if (!isNonEmptyString(state.installedAt)) { + pushError('/installedAt', 'must be non-empty string'); + } + + if (state.lastValidatedAt !== undefined && !isNonEmptyString(state.lastValidatedAt)) { + pushError('/lastValidatedAt', 'must be non-empty string'); + } + + const target = state.target; + if (!target || typeof target !== 'object' || Array.isArray(target)) { + pushError('/target', 'must be object'); + } else { + validateNoAdditionalProperties(target, '/target', ['id', 'target', 'kind', 'root', 'installStatePath']); + if (!isNonEmptyString(target.id)) { + pushError('/target/id', 'must be non-empty string'); + } + validateOptionalString(target.target, '/target/target'); + if (target.kind !== undefined && !['home', 'project'].includes(target.kind)) { + pushError('/target/kind', 'must be equal to one of the allowed values'); + } + if (!isNonEmptyString(target.root)) { + pushError('/target/root', 'must be non-empty string'); + } + if (!isNonEmptyString(target.installStatePath)) { + pushError('/target/installStatePath', 'must be non-empty string'); + } + } + + const request = state.request; + if (!request || typeof request !== 'object' || Array.isArray(request)) { + pushError('/request', 'must be object'); + } else { + validateNoAdditionalProperties( + request, + '/request', + ['profile', 'modules', 'includeComponents', 'excludeComponents', 'legacyLanguages', 'legacyMode', 'hookConsent'] + ); + if (!(Object.prototype.hasOwnProperty.call(request, 'profile') && (request.profile === null || typeof request.profile === 'string'))) { + pushError('/request/profile', 'must be string or null'); + } + validateStringArray(request.modules, '/request/modules'); + validateStringArray(request.includeComponents, '/request/includeComponents'); + validateStringArray(request.excludeComponents, '/request/excludeComponents'); + validateStringArray(request.legacyLanguages, '/request/legacyLanguages'); + if (typeof request.legacyMode !== 'boolean') { + pushError('/request/legacyMode', 'must be boolean'); + } + if ( + request.hookConsent !== undefined + && request.hookConsent !== null + && request.hookConsent !== 'enabled' + && request.hookConsent !== 'declined' + ) { + pushError('/request/hookConsent', 'must be enabled, declined, or null'); + } + } + + const resolution = state.resolution; + if (!resolution || typeof resolution !== 'object' || Array.isArray(resolution)) { + pushError('/resolution', 'must be object'); + } else { + validateNoAdditionalProperties(resolution, '/resolution', ['selectedModules', 'skippedModules']); + validateStringArray(resolution.selectedModules, '/resolution/selectedModules'); + validateStringArray(resolution.skippedModules, '/resolution/skippedModules'); + } + + const source = state.source; + if (!source || typeof source !== 'object' || Array.isArray(source)) { + pushError('/source', 'must be object'); + } else { + validateNoAdditionalProperties(source, '/source', ['repoVersion', 'repoCommit', 'manifestVersion']); + validateOptionalString(source.repoVersion, '/source/repoVersion'); + validateOptionalString(source.repoCommit, '/source/repoCommit'); + if (!Number.isInteger(source.manifestVersion) || source.manifestVersion < 1) { + pushError('/source/manifestVersion', 'must be integer >= 1'); + } + } + + if (!Array.isArray(state.operations)) { + pushError('/operations', 'must be array'); + } else { + for (let index = 0; index < state.operations.length; index += 1) { + const operation = state.operations[index]; + const instancePath = `/operations/${index}`; + + if (!operation || typeof operation !== 'object' || Array.isArray(operation)) { + pushError(instancePath, 'must be object'); + continue; + } + + if (!isNonEmptyString(operation.kind)) { + pushError(`${instancePath}/kind`, 'must be non-empty string'); + } + if (!isNonEmptyString(operation.moduleId)) { + pushError(`${instancePath}/moduleId`, 'must be non-empty string'); + } + if (!isNonEmptyString(operation.sourceRelativePath)) { + pushError(`${instancePath}/sourceRelativePath`, 'must be non-empty string'); + } + if (!isNonEmptyString(operation.destinationPath)) { + pushError(`${instancePath}/destinationPath`, 'must be non-empty string'); + } + if (!isNonEmptyString(operation.strategy)) { + pushError(`${instancePath}/strategy`, 'must be non-empty string'); + } + if (!isNonEmptyString(operation.ownership)) { + pushError(`${instancePath}/ownership`, 'must be non-empty string'); + } + if (typeof operation.scaffoldOnly !== 'boolean') { + pushError(`${instancePath}/scaffoldOnly`, 'must be boolean'); + } + if ( + operation.contentSha256 !== undefined + && !/^[a-f0-9]{64}$/i.test(operation.contentSha256) + ) { + pushError(`${instancePath}/contentSha256`, 'must be a SHA-256 hex digest'); + } + if (operation.kind === 'update-claude-settings') { + if (!['claude', 'claude-project'].includes(state.target && state.target.target)) { + pushError(`${instancePath}/kind`, 'is only valid for Claude targets'); + } + if (operation.moduleId !== 'hooks-runtime') { + pushError(`${instancePath}/moduleId`, 'must equal hooks-runtime'); + } + if (String(operation.sourceRelativePath).replace(/\\/g, '/') !== CLAUDE_HOOKS_CONFIG_PATH) { + pushError(`${instancePath}/sourceRelativePath`, 'must equal hooks/hooks.json'); + } + if ( + isNonEmptyString(state.target && state.target.root) + && isNonEmptyString(operation.destinationPath) + ) { + const expectedDestination = path.resolve(getClaudeSettingsPath(state.target.root)); + const actualDestination = path.resolve(operation.destinationPath); + const pathsMatch = process.platform === 'win32' + ? expectedDestination.toLowerCase() === actualDestination.toLowerCase() + : expectedDestination === actualDestination; + if (!pathsMatch) { + pushError( + `${instancePath}/destinationPath`, + 'must equal the canonical Claude settings path' + ); + } + } + try { + validateRecordedManagedHooks(operation.managedHooks); + } catch (error) { + pushError(`${instancePath}/managedHooks`, error.message); + } + } + } + } + + return errors.length === 0; + }; + + validate.errors = []; + return validate; +} + +function formatValidationErrors(errors = []) { + return errors + .map(error => `${error.instancePath || '/'} ${error.message}`) + .join('; '); +} + +function validateInstallState(state) { + const validator = getValidator(); + const valid = validator(state); + return { + valid, + errors: validator.errors || [], + }; +} + +function assertValidInstallState(state, label) { + const result = validateInstallState(state); + if (!result.valid) { + throw new Error(`Invalid install-state${label ? ` (${label})` : ''}: ${formatValidationErrors(result.errors)}`); + } +} + +function createInstallState(options) { + const installedAt = options.installedAt || new Date().toISOString(); + const state = { + schemaVersion: 'ecc.install.v1', + installedAt, + target: { + id: options.adapter.id, + target: options.adapter.target || undefined, + kind: options.adapter.kind || undefined, + root: options.targetRoot, + installStatePath: options.installStatePath, + }, + request: { + profile: options.request.profile || null, + modules: Array.isArray(options.request.modules) ? [...options.request.modules] : [], + includeComponents: Array.isArray(options.request.includeComponents) + ? [...options.request.includeComponents] + : [], + excludeComponents: Array.isArray(options.request.excludeComponents) + ? [...options.request.excludeComponents] + : [], + legacyLanguages: Array.isArray(options.request.legacyLanguages) + ? [...options.request.legacyLanguages] + : [], + legacyMode: Boolean(options.request.legacyMode), + hookConsent: Object.prototype.hasOwnProperty.call(options.request, 'hookConsent') + ? options.request.hookConsent + : null, + }, + resolution: { + selectedModules: Array.isArray(options.resolution.selectedModules) + ? [...options.resolution.selectedModules] + : [], + skippedModules: Array.isArray(options.resolution.skippedModules) + ? [...options.resolution.skippedModules] + : [], + }, + source: { + repoVersion: options.source.repoVersion || null, + repoCommit: options.source.repoCommit || null, + manifestVersion: options.source.manifestVersion, + }, + operations: Array.isArray(options.operations) + ? options.operations.map(operation => cloneJsonValue(operation)) + : [], + }; + + if (options.lastValidatedAt) { + state.lastValidatedAt = options.lastValidatedAt; + } + + assertValidInstallState(state, 'create'); + return state; +} + +function readInstallState(filePath) { + const state = readJson(filePath, 'install-state'); + assertValidInstallState(state, filePath); + return state; +} + +function writeInstallState(filePath, state) { + assertValidInstallState(state, filePath); + fs.mkdirSync(path.dirname(filePath), { recursive: true }); + fs.writeFileSync(filePath, `${JSON.stringify(state, null, 2)}\n`); + return state; +} + +module.exports = { + createInstallState, + readInstallState, + validateInstallState, + writeInstallState, +}; diff --git a/github_code/affaan-m__ECC/scripts/lib/install-targets/adal-project.js b/github_code/affaan-m__ECC/scripts/lib/install-targets/adal-project.js new file mode 100644 index 0000000000000000000000000000000000000000..313f5437a69f8e0a4ac3689ab3564369e004f8a6 --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/install-targets/adal-project.js @@ -0,0 +1,10 @@ +const { createInstallTargetAdapter } = require('./helpers'); + +module.exports = createInstallTargetAdapter({ + id: 'adal-project', + target: 'adal', + kind: 'project', + rootSegments: ['.adal'], + installStatePathSegments: ['ecc-install-state.json'], + nativeRootRelativePath: '.adal', +}); diff --git a/github_code/affaan-m__ECC/scripts/lib/install-targets/antigravity-project.js b/github_code/affaan-m__ECC/scripts/lib/install-targets/antigravity-project.js new file mode 100644 index 0000000000000000000000000000000000000000..7861bbc2515f3a138b48b13b1297a48dc174bc67 --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/install-targets/antigravity-project.js @@ -0,0 +1,121 @@ +const path = require('path'); + +const { + createFlatRuleOperations, + createInstallTargetAdapter, + createManagedOperation, + createManagedScaffoldOperation, + normalizeRelativePath, +} = require('./helpers'); + +const SUPPORTED_SOURCE_PREFIXES = ['rules', 'commands', 'agents', 'skills']; + +function supportsAntigravitySourcePath(sourceRelativePath) { + const normalizedPath = normalizeRelativePath(sourceRelativePath); + return SUPPORTED_SOURCE_PREFIXES.some(prefix => ( + normalizedPath === prefix || normalizedPath.startsWith(`${prefix}/`) + )); +} + +module.exports = createInstallTargetAdapter({ + id: 'antigravity-project', + target: 'antigravity', + kind: 'project', + rootSegments: ['.agents'], + installStatePathSegments: ['ecc-install-state.json'], + supportsModule(module) { + const paths = Array.isArray(module && module.paths) ? module.paths : []; + return paths.length > 0; + }, + planOperations(input, adapter) { + const modules = Array.isArray(input.modules) + ? input.modules + : (input.module ? [input.module] : []); + const { + repoRoot, + projectRoot, + homeDir, + } = input; + const planningInput = { + repoRoot, + projectRoot, + homeDir, + }; + const targetRoot = adapter.resolveRoot(planningInput); + + return modules.flatMap(module => { + const paths = Array.isArray(module.paths) ? module.paths : []; + return paths + .filter(supportsAntigravitySourcePath) + .flatMap(sourceRelativePath => { + const normalizedSourcePath = normalizeRelativePath(sourceRelativePath); + + if ( + normalizedSourcePath === 'rules' + || normalizedSourcePath.startsWith('rules/') + ) { + return createFlatRuleOperations({ + moduleId: module.id, + repoRoot, + sourceRelativePath: normalizedSourcePath, + destinationDir: path.join(targetRoot, 'rules'), + }); + } + + if ( + normalizedSourcePath === 'commands' + || normalizedSourcePath.startsWith('commands/') + ) { + const commandRelativePath = normalizedSourcePath === 'commands' + ? '' + : normalizedSourcePath.slice('commands/'.length); + return [ + createManagedScaffoldOperation( + module.id, + normalizedSourcePath, + path.join(targetRoot, 'workflows', commandRelativePath), + 'preserve-relative-path' + ), + ]; + } + + if ( + normalizedSourcePath === 'agents' + || normalizedSourcePath.startsWith('agents/') + ) { + const agentRelativePath = normalizedSourcePath === 'agents' + ? '' + : normalizedSourcePath.slice('agents/'.length); + return [ + createManagedOperation({ + moduleId: module.id, + sourceRelativePath: normalizedSourcePath, + destinationPath: path.join(targetRoot, 'agents', agentRelativePath), + strategy: 'preserve-relative-path', + contentTransform: 'antigravity-agent-frontmatter', + }), + ]; + } + + if ( + normalizedSourcePath === 'skills' + || normalizedSourcePath.startsWith('skills/') + ) { + const skillRelativePath = normalizedSourcePath === 'skills' + ? '' + : normalizedSourcePath.slice('skills/'.length); + return [ + createManagedScaffoldOperation( + module.id, + normalizedSourcePath, + path.join(targetRoot, 'skills', skillRelativePath), + 'preserve-relative-path' + ), + ]; + } + + return []; + }); + }); + }, +}); diff --git a/github_code/affaan-m__ECC/scripts/lib/install-targets/claude-home.js b/github_code/affaan-m__ECC/scripts/lib/install-targets/claude-home.js new file mode 100644 index 0000000000000000000000000000000000000000..5cc426ac967d863dee26dfc0cc10c2320a5cc101 --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/install-targets/claude-home.js @@ -0,0 +1,98 @@ +const path = require('path'); + +const { + createInstallTargetAdapter, + createRemappedOperation, + isForeignPlatformPath, + normalizeRelativePath, + planClaudeHooksOperations, +} = require('./helpers'); + +const CLAUDE_ECC_NAMESPACE = 'ecc'; + +function getClaudeManagedDestinationPath(adapter, sourceRelativePath, input) { + const normalizedSourcePath = normalizeRelativePath(sourceRelativePath); + const targetRoot = adapter.resolveRoot(input); + + if (normalizedSourcePath === 'rules') { + return path.join(targetRoot, 'rules', CLAUDE_ECC_NAMESPACE); + } + + if (normalizedSourcePath.startsWith('rules/')) { + return path.join( + targetRoot, + 'rules', + CLAUDE_ECC_NAMESPACE, + normalizedSourcePath.slice('rules/'.length) + ); + } + + if (normalizedSourcePath === 'skills') { + return path.join(targetRoot, 'skills'); + } + + if (normalizedSourcePath.startsWith('skills/')) { + return path.join( + targetRoot, + 'skills', + normalizedSourcePath.slice('skills/'.length) + ); + } + + if (normalizedSourcePath === 'docs' || normalizedSourcePath.startsWith('docs/')) { + return path.join(targetRoot, normalizedSourcePath); + } + + return null; +} + +module.exports = createInstallTargetAdapter({ + id: 'claude-home', + target: 'claude', + kind: 'home', + rootSegments: ['.claude'], + installStatePathSegments: ['ecc', 'install-state.json'], + nativeRootRelativePath: '.claude-plugin', + planOperations(input, adapter) { + const modules = Array.isArray(input.modules) + ? input.modules + : (input.module ? [input.module] : []); + const planningInput = { + repoRoot: input.repoRoot, + projectRoot: input.projectRoot, + homeDir: input.homeDir, + }; + + return modules.flatMap(module => { + const paths = Array.isArray(module.paths) ? module.paths : []; + return paths + .filter(p => !isForeignPlatformPath(p, adapter.target)) + .flatMap(sourceRelativePath => { + if ( + module.id === 'hooks-runtime' + && normalizeRelativePath(sourceRelativePath) === 'hooks' + ) { + return planClaudeHooksOperations(adapter, module, planningInput); + } + + const managedDestinationPath = getClaudeManagedDestinationPath( + adapter, + sourceRelativePath, + planningInput + ); + + if (managedDestinationPath) { + return [createRemappedOperation( + adapter, + module.id, + sourceRelativePath, + managedDestinationPath, + { strategy: 'preserve-relative-path' } + )]; + } + + return [adapter.createScaffoldOperation(module.id, sourceRelativePath, planningInput)]; + }); + }); + }, +}); diff --git a/github_code/affaan-m__ECC/scripts/lib/install-targets/claude-project.js b/github_code/affaan-m__ECC/scripts/lib/install-targets/claude-project.js new file mode 100644 index 0000000000000000000000000000000000000000..a4fda3970b4b635535bf689660128610157452af --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/install-targets/claude-project.js @@ -0,0 +1,98 @@ +const path = require('path'); + +const { + createInstallTargetAdapter, + createRemappedOperation, + isForeignPlatformPath, + normalizeRelativePath, + planClaudeHooksOperations, +} = require('./helpers'); + +const CLAUDE_ECC_NAMESPACE = 'ecc'; + +function getClaudeManagedDestinationPath(adapter, sourceRelativePath, input) { + const normalizedSourcePath = normalizeRelativePath(sourceRelativePath); + const targetRoot = adapter.resolveRoot(input); + + if (normalizedSourcePath === 'rules') { + return path.join(targetRoot, 'rules', CLAUDE_ECC_NAMESPACE); + } + + if (normalizedSourcePath.startsWith('rules/')) { + return path.join( + targetRoot, + 'rules', + CLAUDE_ECC_NAMESPACE, + normalizedSourcePath.slice('rules/'.length) + ); + } + + if (normalizedSourcePath === 'skills') { + return path.join(targetRoot, 'skills'); + } + + if (normalizedSourcePath.startsWith('skills/')) { + return path.join( + targetRoot, + 'skills', + normalizedSourcePath.slice('skills/'.length) + ); + } + + if (normalizedSourcePath === 'docs' || normalizedSourcePath.startsWith('docs/')) { + return path.join(targetRoot, normalizedSourcePath); + } + + return null; +} + +module.exports = createInstallTargetAdapter({ + id: 'claude-project', + target: 'claude-project', + kind: 'project', + rootSegments: ['.claude'], + installStatePathSegments: ['ecc', 'install-state.json'], + nativeRootRelativePath: '.claude-plugin', + planOperations(input, adapter) { + const modules = Array.isArray(input.modules) + ? input.modules + : (input.module ? [input.module] : []); + const planningInput = { + repoRoot: input.repoRoot, + projectRoot: input.projectRoot, + homeDir: input.homeDir, + }; + + return modules.flatMap(module => { + const paths = Array.isArray(module.paths) ? module.paths : []; + return paths + .filter(p => !isForeignPlatformPath(p, 'claude')) + .flatMap(sourceRelativePath => { + if ( + module.id === 'hooks-runtime' + && normalizeRelativePath(sourceRelativePath) === 'hooks' + ) { + return planClaudeHooksOperations(adapter, module, planningInput); + } + + const managedDestinationPath = getClaudeManagedDestinationPath( + adapter, + sourceRelativePath, + planningInput + ); + + if (managedDestinationPath) { + return [createRemappedOperation( + adapter, + module.id, + sourceRelativePath, + managedDestinationPath, + { strategy: 'preserve-relative-path' } + )]; + } + + return [adapter.createScaffoldOperation(module.id, sourceRelativePath, planningInput)]; + }); + }); + }, +}); diff --git a/github_code/affaan-m__ECC/scripts/lib/install-targets/codebuddy-project.js b/github_code/affaan-m__ECC/scripts/lib/install-targets/codebuddy-project.js new file mode 100644 index 0000000000000000000000000000000000000000..100a133a47f6d67c68ee98a835f185d1df2eacc1 --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/install-targets/codebuddy-project.js @@ -0,0 +1,50 @@ +const path = require('path'); + +const { + createFlatRuleOperations, + createInstallTargetAdapter, + isForeignPlatformPath, +} = require('./helpers'); + +module.exports = createInstallTargetAdapter({ + id: 'codebuddy-project', + target: 'codebuddy', + kind: 'project', + rootSegments: ['.codebuddy'], + installStatePathSegments: ['ecc-install-state.json'], + nativeRootRelativePath: '.codebuddy', + planOperations(input, adapter) { + const modules = Array.isArray(input.modules) + ? input.modules + : (input.module ? [input.module] : []); + const { + repoRoot, + projectRoot, + homeDir, + } = input; + const planningInput = { + repoRoot, + projectRoot, + homeDir, + }; + const targetRoot = adapter.resolveRoot(planningInput); + + return modules.flatMap(module => { + const paths = Array.isArray(module.paths) ? module.paths : []; + return paths + .filter(p => !isForeignPlatformPath(p, adapter.target)) + .flatMap(sourceRelativePath => { + if (sourceRelativePath === 'rules') { + return createFlatRuleOperations({ + moduleId: module.id, + repoRoot, + sourceRelativePath, + destinationDir: path.join(targetRoot, 'rules'), + }); + } + + return [adapter.createScaffoldOperation(module.id, sourceRelativePath, planningInput)]; + }); + }); + }, +}); diff --git a/github_code/affaan-m__ECC/scripts/lib/install-targets/codex-home.js b/github_code/affaan-m__ECC/scripts/lib/install-targets/codex-home.js new file mode 100644 index 0000000000000000000000000000000000000000..ae29b41a1f52a93a09069992668c4a7deb9fded9 --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/install-targets/codex-home.js @@ -0,0 +1,10 @@ +const { createInstallTargetAdapter } = require('./helpers'); + +module.exports = createInstallTargetAdapter({ + id: 'codex-home', + target: 'codex', + kind: 'home', + rootSegments: ['.codex'], + installStatePathSegments: ['ecc-install-state.json'], + nativeRootRelativePath: '.codex', +}); diff --git a/github_code/affaan-m__ECC/scripts/lib/install-targets/cursor-project.js b/github_code/affaan-m__ECC/scripts/lib/install-targets/cursor-project.js new file mode 100644 index 0000000000000000000000000000000000000000..81e71aefd0b2cf25efc7394dce2cc5983fa8028d --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/install-targets/cursor-project.js @@ -0,0 +1,210 @@ +const fs = require('fs'); +const path = require('path'); + +const { toCursorAgentFileName } = require('../cursor-agent-names'); +const { + createFlatFileOperations, + createFlatRuleOperations, + createInstallTargetAdapter, + createManagedOperation, + isForeignPlatformPath, +} = require('./helpers'); + +function toCursorRuleFileName(fileName, sourceRelativeFile) { + if (path.basename(sourceRelativeFile).toLowerCase() === 'readme.md') { + return null; + } + + return fileName.endsWith('.md') + ? `${fileName.slice(0, -3)}.mdc` + : fileName; +} + +function readJsonObject(filePath, label) { + let parsed; + try { + parsed = JSON.parse(fs.readFileSync(filePath, 'utf8')); + } catch (error) { + throw new Error(`Failed to parse ${label} at ${filePath}: ${error.message}`); + } + + if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) { + throw new Error(`Invalid ${label} at ${filePath}: expected a JSON object`); + } + + return parsed; +} + +function createJsonMergeOperation({ moduleId, repoRoot, sourceRelativePath, destinationPath }) { + const sourcePath = path.join(repoRoot, sourceRelativePath); + if (!fs.existsSync(sourcePath) || !fs.statSync(sourcePath).isFile()) { + return null; + } + + return createManagedOperation({ + kind: 'merge-json', + moduleId, + sourceRelativePath, + destinationPath, + strategy: 'merge-json', + ownership: 'managed', + scaffoldOnly: false, + mergePayload: readJsonObject(sourcePath, sourceRelativePath), + }); +} + +module.exports = createInstallTargetAdapter({ + id: 'cursor-project', + target: 'cursor', + kind: 'project', + rootSegments: ['.cursor'], + installStatePathSegments: ['ecc-install-state.json'], + nativeRootRelativePath: '.cursor', + planOperations(input, adapter) { + const modules = Array.isArray(input.modules) + ? input.modules + : (input.module ? [input.module] : []); + const seenDestinationPaths = new Set(); + const { + repoRoot, + projectRoot, + homeDir, + } = input; + const planningInput = { + repoRoot, + projectRoot, + homeDir, + }; + const targetRoot = adapter.resolveRoot(planningInput); + const entries = modules.flatMap((module, moduleIndex) => { + const paths = Array.isArray(module.paths) ? module.paths : []; + return paths + .filter(p => !isForeignPlatformPath(p, adapter.target)) + .map((sourceRelativePath, pathIndex) => ({ + module, + sourceRelativePath, + moduleIndex, + pathIndex, + })); + }).sort((left, right) => { + const getPriority = value => { + if (value === '.cursor') { + return 0; + } + + if (value === 'rules') { + return 1; + } + + return 2; + }; + + const leftPriority = getPriority(left.sourceRelativePath); + const rightPriority = getPriority(right.sourceRelativePath); + if (leftPriority !== rightPriority) { + return leftPriority - rightPriority; + } + + if (left.moduleIndex !== right.moduleIndex) { + return left.moduleIndex - right.moduleIndex; + } + + return left.pathIndex - right.pathIndex; + }); + + function takeUniqueOperations(operations) { + return operations.filter(operation => { + if (!operation || !operation.destinationPath) { + return false; + } + + if (seenDestinationPaths.has(operation.destinationPath)) { + return false; + } + + seenDestinationPaths.add(operation.destinationPath); + return true; + }); + } + + return entries.flatMap(({ module, sourceRelativePath }) => { + const cursorMcpOperation = createJsonMergeOperation({ + moduleId: module.id, + repoRoot, + sourceRelativePath: '.mcp.json', + destinationPath: path.join(targetRoot, 'mcp.json'), + }); + + if (sourceRelativePath === 'AGENTS.md') { + // Cursor treats nested AGENTS.md files as directory context; do not + // install ECC's root project identity into a host project's .cursor/. + return []; + } + + if (sourceRelativePath === 'rules') { + return takeUniqueOperations(createFlatRuleOperations({ + moduleId: module.id, + repoRoot, + sourceRelativePath, + destinationDir: path.join(targetRoot, 'rules'), + destinationNameTransform: toCursorRuleFileName, + })); + } + + if (sourceRelativePath === 'agents') { + return takeUniqueOperations(createFlatFileOperations({ + moduleId: module.id, + repoRoot, + sourceRelativePath, + destinationDir: path.join(targetRoot, 'agents'), + destinationNameTransform: toCursorAgentFileName, + })); + } + + if (sourceRelativePath === '.cursor') { + const cursorRoot = path.join(repoRoot, '.cursor'); + if (!fs.existsSync(cursorRoot) || !fs.statSync(cursorRoot).isDirectory()) { + return []; + } + + const childOperations = fs.readdirSync(cursorRoot, { withFileTypes: true }) + .sort((left, right) => left.name.localeCompare(right.name)) + .filter(entry => entry.name !== 'rules') + .map(entry => createManagedOperation({ + moduleId: module.id, + sourceRelativePath: path.join('.cursor', entry.name), + destinationPath: path.join(targetRoot, entry.name), + strategy: 'preserve-relative-path', + })); + + const ruleOperations = createFlatRuleOperations({ + moduleId: module.id, + repoRoot, + sourceRelativePath: '.cursor/rules', + destinationDir: path.join(targetRoot, 'rules'), + destinationNameTransform: toCursorRuleFileName, + }); + + return takeUniqueOperations([ + ...childOperations, + ...(cursorMcpOperation ? [cursorMcpOperation] : []), + ...ruleOperations, + ]); + } + + if (sourceRelativePath === 'mcp-configs') { + const operations = [ + adapter.createScaffoldOperation(module.id, sourceRelativePath, planningInput), + ]; + if (cursorMcpOperation) { + operations.push(cursorMcpOperation); + } + return takeUniqueOperations(operations); + } + + return takeUniqueOperations([ + adapter.createScaffoldOperation(module.id, sourceRelativePath, planningInput), + ]); + }); + }, +}); diff --git a/github_code/affaan-m__ECC/scripts/lib/install-targets/gemini-project.js b/github_code/affaan-m__ECC/scripts/lib/install-targets/gemini-project.js new file mode 100644 index 0000000000000000000000000000000000000000..f87f8539d19f3b15fb8983de9cf2c9f835780d1e --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/install-targets/gemini-project.js @@ -0,0 +1,10 @@ +const { createInstallTargetAdapter } = require('./helpers'); + +module.exports = createInstallTargetAdapter({ + id: 'gemini-project', + target: 'gemini', + kind: 'project', + rootSegments: ['.gemini'], + installStatePathSegments: ['ecc-install-state.json'], + nativeRootRelativePath: '.gemini', +}); diff --git a/github_code/affaan-m__ECC/scripts/lib/install-targets/helpers.js b/github_code/affaan-m__ECC/scripts/lib/install-targets/helpers.js new file mode 100644 index 0000000000000000000000000000000000000000..dbb5b44e559d2a269237e66f3053085b63ef76dd --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/install-targets/helpers.js @@ -0,0 +1,417 @@ +const fs = require('fs'); +const os = require('os'); +const path = require('path'); +const { + CLAUDE_HOOKS_CONFIG_PATH, + getClaudeSettingsPath, +} = require('../install/claude-settings'); + +const PLATFORM_SOURCE_PATH_OWNERS = Object.freeze({ + '.claude-plugin': 'claude', + '.codex': 'codex', + '.cursor': 'cursor', + '.gemini': 'gemini', + '.hermes': 'hermes', + '.kimi': 'kimi', + '.kimi-code': 'kimi', + '.joycode': 'joycode', + '.opencode': 'opencode', + '.openclaw': 'openclaw', + '.codebuddy': 'codebuddy', + '.qwen': 'qwen', + '.zed': 'zed', + '.adal': 'adal', +}); + +function normalizeRelativePath(relativePath) { + return String(relativePath || '') + .replace(/\\/g, '/') + .replace(/^\.\/+/, '') + .replace(/\/+$/, ''); +} + +function isForeignPlatformPath(sourceRelativePath, adapterTarget) { + const normalizedPath = normalizeRelativePath(sourceRelativePath); + + for (const [prefix, ownerTarget] of Object.entries(PLATFORM_SOURCE_PATH_OWNERS)) { + if (normalizedPath === prefix || normalizedPath.startsWith(`${prefix}/`)) { + return ownerTarget !== adapterTarget; + } + } + + return false; +} + +function resolveBaseRoot(scope, input = {}) { + if (scope === 'home') { + return input.homeDir || os.homedir(); + } + + if (scope === 'project') { + const projectRoot = input.projectRoot || input.repoRoot; + if (!projectRoot) { + throw new Error('projectRoot or repoRoot is required for project install targets'); + } + return projectRoot; + } + + throw new Error(`Unsupported install target scope: ${scope}`); +} + +function buildValidationIssue(severity, code, message, extra = {}) { + return { + severity, + code, + message, + ...extra, + }; +} + +function listRelativeFiles(dirPath, prefix = '') { + if (!fs.existsSync(dirPath)) { + return []; + } + + const entries = fs.readdirSync(dirPath, { withFileTypes: true }).sort((left, right) => ( + left.name.localeCompare(right.name) + )); + const files = []; + + for (const entry of entries) { + const entryPrefix = prefix ? path.join(prefix, entry.name) : entry.name; + const absolutePath = path.join(dirPath, entry.name); + + if (entry.isDirectory()) { + files.push(...listRelativeFiles(absolutePath, entryPrefix)); + } else if (entry.isFile()) { + files.push(normalizeRelativePath(entryPrefix)); + } + } + + return files; +} + +function createManagedOperation({ + kind = 'copy-path', + moduleId, + sourceRelativePath, + destinationPath, + strategy = 'preserve-relative-path', + ownership = 'managed', + scaffoldOnly = true, + ...rest +}) { + return { + kind, + moduleId, + sourceRelativePath: normalizeRelativePath(sourceRelativePath), + destinationPath, + strategy, + ownership, + scaffoldOnly, + ...rest, + }; +} + +function defaultValidateAdapterInput(config, input = {}) { + if (config.kind === 'project' && !input.projectRoot && !input.repoRoot) { + return [ + buildValidationIssue( + 'error', + 'missing-project-root', + 'projectRoot or repoRoot is required for project install targets' + ), + ]; + } + + if (config.kind === 'home' && !input.homeDir && !os.homedir()) { + return [ + buildValidationIssue( + 'error', + 'missing-home-dir', + 'homeDir is required for home install targets' + ), + ]; + } + + return []; +} + +function createRemappedOperation(adapter, moduleId, sourceRelativePath, destinationPath, options = {}) { + return createManagedOperation({ + kind: options.kind || 'copy-path', + moduleId, + sourceRelativePath, + destinationPath, + strategy: options.strategy || 'preserve-relative-path', + ownership: options.ownership || 'managed', + scaffoldOnly: Object.hasOwn(options, 'scaffoldOnly') ? options.scaffoldOnly : true, + ...options.extra, + }); +} + +function planClaudeHooksOperations(adapter, module, input) { + const operations = [ + createRemappedOperation( + adapter, + module.id, + CLAUDE_HOOKS_CONFIG_PATH, + getClaudeSettingsPath(adapter.resolveRoot(input)), + { + kind: 'update-claude-settings', + strategy: 'merge-hook-ids', + } + ), + ]; + + if (!input.repoRoot) { + return operations; + } + + const sourceHooksRoot = path.join(input.repoRoot, 'hooks'); + if (!fs.existsSync(sourceHooksRoot)) { + return operations; + } + + return [ + ...operations, + ...fs.readdirSync(sourceHooksRoot, { withFileTypes: true }) + .filter(entry => entry.name !== 'hooks.json') + .sort((left, right) => left.name.localeCompare(right.name)) + .map(entry => adapter.createScaffoldOperation( + module.id, + path.join('hooks', entry.name), + input + )), + ]; +} + +function createNamespacedFlatRuleOperations(adapter, moduleId, sourceRelativePath, input = {}) { + const normalizedSourcePath = normalizeRelativePath(sourceRelativePath); + const sourceRoot = path.join(input.repoRoot || '', normalizedSourcePath); + + if (!input.repoRoot || !fs.existsSync(sourceRoot) || !fs.statSync(sourceRoot).isDirectory()) { + return []; + } + + const targetRulesDir = path.join(adapter.resolveRoot(input), 'rules'); + const operations = []; + const entries = fs.readdirSync(sourceRoot, { withFileTypes: true }).sort((left, right) => ( + left.name.localeCompare(right.name) + )); + + for (const entry of entries) { + const namespace = entry.name; + const entryPath = path.join(sourceRoot, entry.name); + + if (entry.isDirectory()) { + const relativeFiles = listRelativeFiles(entryPath); + for (const relativeFile of relativeFiles) { + const flattenedFileName = `${namespace}-${normalizeRelativePath(relativeFile).replace(/\//g, '-')}`; + const sourceRelativeFile = path.join(normalizedSourcePath, namespace, relativeFile); + operations.push(createManagedOperation({ + moduleId, + sourceRelativePath: sourceRelativeFile, + destinationPath: path.join(targetRulesDir, flattenedFileName), + strategy: 'flatten-copy', + })); + } + } else if (entry.isFile()) { + operations.push(createManagedOperation({ + moduleId, + sourceRelativePath: path.join(normalizedSourcePath, entry.name), + destinationPath: path.join(targetRulesDir, entry.name), + strategy: 'flatten-copy', + })); + } + } + + return operations; +} + +function createFlatFileOperations({ + moduleId, + repoRoot, + sourceRelativePath, + destinationDir, + destinationNameTransform, +}) { + const normalizedSourcePath = normalizeRelativePath(sourceRelativePath); + const sourceRoot = path.join(repoRoot || '', normalizedSourcePath); + + if (!repoRoot || !fs.existsSync(sourceRoot) || !fs.statSync(sourceRoot).isDirectory()) { + return []; + } + + const operations = []; + const entries = fs.readdirSync(sourceRoot, { withFileTypes: true }).sort((left, right) => ( + left.name.localeCompare(right.name) + )); + + for (const entry of entries) { + const namespace = entry.name; + const entryPath = path.join(sourceRoot, entry.name); + + if (entry.isDirectory()) { + const relativeFiles = listRelativeFiles(entryPath); + for (const relativeFile of relativeFiles) { + const defaultFileName = `${namespace}-${normalizeRelativePath(relativeFile).replace(/\//g, '-')}`; + const sourceRelativeFile = path.join(normalizedSourcePath, namespace, relativeFile); + const flattenedFileName = typeof destinationNameTransform === 'function' + ? destinationNameTransform(defaultFileName, sourceRelativeFile) + : defaultFileName; + if (!flattenedFileName) { + continue; + } + operations.push(createManagedOperation({ + moduleId, + sourceRelativePath: sourceRelativeFile, + destinationPath: path.join(destinationDir, flattenedFileName), + strategy: 'flatten-copy', + })); + } + } else if (entry.isFile()) { + const sourceRelativeFile = path.join(normalizedSourcePath, entry.name); + const destinationFileName = typeof destinationNameTransform === 'function' + ? destinationNameTransform(entry.name, sourceRelativeFile) + : entry.name; + if (!destinationFileName) { + continue; + } + operations.push(createManagedOperation({ + moduleId, + sourceRelativePath: sourceRelativeFile, + destinationPath: path.join(destinationDir, destinationFileName), + strategy: 'flatten-copy', + })); + } + } + + return operations; +} + +function createFlatRuleOperations(options) { + return createFlatFileOperations(options); +} + +function createInstallTargetAdapter(config) { + const adapter = { + id: config.id, + target: config.target, + kind: config.kind, + nativeRootRelativePath: config.nativeRootRelativePath || null, + supports(target) { + return target === config.target || target === config.id; + }, + resolveRoot(input = {}) { + const baseRoot = resolveBaseRoot(config.kind, input); + if (typeof config.resolveRoot === 'function') { + return config.resolveRoot(input, baseRoot); + } + return path.join(baseRoot, ...config.rootSegments); + }, + getInstallStatePath(input = {}) { + const root = adapter.resolveRoot(input); + return path.join(root, ...config.installStatePathSegments); + }, + resolveDestinationPath(sourceRelativePath, input = {}) { + const normalizedSourcePath = normalizeRelativePath(sourceRelativePath); + const targetRoot = adapter.resolveRoot(input); + + if ( + config.nativeRootRelativePath + && normalizedSourcePath === normalizeRelativePath(config.nativeRootRelativePath) + ) { + return targetRoot; + } + + return path.join(targetRoot, normalizedSourcePath); + }, + determineStrategy(sourceRelativePath) { + const normalizedSourcePath = normalizeRelativePath(sourceRelativePath); + + if ( + config.nativeRootRelativePath + && normalizedSourcePath === normalizeRelativePath(config.nativeRootRelativePath) + ) { + return 'sync-root-children'; + } + + return 'preserve-relative-path'; + }, + createScaffoldOperation(moduleId, sourceRelativePath, input = {}) { + const normalizedSourcePath = normalizeRelativePath(sourceRelativePath); + return createManagedOperation({ + moduleId, + sourceRelativePath: normalizedSourcePath, + destinationPath: adapter.resolveDestinationPath(normalizedSourcePath, input), + strategy: adapter.determineStrategy(normalizedSourcePath), + }); + }, + planOperations(input = {}) { + if (typeof config.planOperations === 'function') { + return config.planOperations(input, adapter); + } + + if (Array.isArray(input.modules)) { + return input.modules.flatMap(module => { + const paths = Array.isArray(module.paths) ? module.paths : []; + return paths + .filter(p => !isForeignPlatformPath(p, config.target)) + .map(sourceRelativePath => adapter.createScaffoldOperation( + module.id, + sourceRelativePath, + input + )); + }); + } + + const module = input.module || {}; + const paths = Array.isArray(module.paths) ? module.paths : []; + return paths + .filter(p => !isForeignPlatformPath(p, config.target)) + .map(sourceRelativePath => adapter.createScaffoldOperation( + module.id, + sourceRelativePath, + input + )); + }, + supportsModule(module, input = {}) { + if (typeof config.supportsModule === 'function') { + return config.supportsModule(module, input, adapter); + } + + return true; + }, + validate(input = {}) { + if (typeof config.validate === 'function') { + return config.validate(input, adapter); + } + + return defaultValidateAdapterInput(config, input); + }, + }; + + return Object.freeze(adapter); +} + +module.exports = { + buildValidationIssue, + createFlatFileOperations, + createFlatRuleOperations, + createInstallTargetAdapter, + createManagedOperation, + createManagedScaffoldOperation: (moduleId, sourceRelativePath, destinationPath, strategy) => ( + createManagedOperation({ + moduleId, + sourceRelativePath, + destinationPath, + strategy, + }) + ), + createNamespacedFlatRuleOperations, + createRemappedOperation, + isForeignPlatformPath, + normalizeRelativePath, + planClaudeHooksOperations, +}; diff --git a/github_code/affaan-m__ECC/scripts/lib/install-targets/hermes-home.js b/github_code/affaan-m__ECC/scripts/lib/install-targets/hermes-home.js new file mode 100644 index 0000000000000000000000000000000000000000..f87922d4b0ac83213c469d2bded5ebb92dd924d0 --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/install-targets/hermes-home.js @@ -0,0 +1,10 @@ +const { createInstallTargetAdapter } = require('./helpers'); + +module.exports = createInstallTargetAdapter({ + id: 'hermes-home', + target: 'hermes', + kind: 'home', + rootSegments: ['.hermes'], + installStatePathSegments: ['ecc-install-state.json'], + nativeRootRelativePath: '.hermes', +}); diff --git a/github_code/affaan-m__ECC/scripts/lib/install-targets/joycode-project.js b/github_code/affaan-m__ECC/scripts/lib/install-targets/joycode-project.js new file mode 100644 index 0000000000000000000000000000000000000000..8faf3515bf54a8ddb1625b5821f905b6258da539 --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/install-targets/joycode-project.js @@ -0,0 +1,50 @@ +const path = require('path'); + +const { + createFlatRuleOperations, + createInstallTargetAdapter, + isForeignPlatformPath, +} = require('./helpers'); + +module.exports = createInstallTargetAdapter({ + id: 'joycode-project', + target: 'joycode', + kind: 'project', + rootSegments: ['.joycode'], + installStatePathSegments: ['ecc-install-state.json'], + nativeRootRelativePath: '.joycode', + planOperations(input, adapter) { + const modules = Array.isArray(input.modules) + ? input.modules + : (input.module ? [input.module] : []); + const { + repoRoot, + projectRoot, + homeDir, + } = input; + const planningInput = { + repoRoot, + projectRoot, + homeDir, + }; + const targetRoot = adapter.resolveRoot(planningInput); + + return modules.flatMap(module => { + const paths = Array.isArray(module.paths) ? module.paths : []; + return paths + .filter(p => !isForeignPlatformPath(p, adapter.target)) + .flatMap(sourceRelativePath => { + if (sourceRelativePath === 'rules') { + return createFlatRuleOperations({ + moduleId: module.id, + repoRoot, + sourceRelativePath, + destinationDir: path.join(targetRoot, 'rules'), + }); + } + + return [adapter.createScaffoldOperation(module.id, sourceRelativePath, planningInput)]; + }); + }); + }, +}); diff --git a/github_code/affaan-m__ECC/scripts/lib/install-targets/kimi-project.js b/github_code/affaan-m__ECC/scripts/lib/install-targets/kimi-project.js new file mode 100644 index 0000000000000000000000000000000000000000..dd1bf11d8b9ed80ef1dc7807ade8b7842c944828 --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/install-targets/kimi-project.js @@ -0,0 +1,109 @@ +const fs = require('fs'); +const path = require('path'); + +const { + createInstallTargetAdapter, + createManagedOperation, + isForeignPlatformPath, +} = require('./helpers'); + +function readJsonObject(filePath, label) { + let parsed; + try { + parsed = JSON.parse(fs.readFileSync(filePath, 'utf8')); + } catch (error) { + throw new Error(`Failed to parse ${label} at ${filePath}: ${error.message}`); + } + + if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) { + throw new Error(`Invalid ${label} at ${filePath}: expected a JSON object`); + } + + return parsed; +} + +function createMcpMergeOperation(moduleId, repoRoot, targetRoot) { + if (!repoRoot) { + throw new Error('repoRoot is required to plan Kimi MCP configuration'); + } + + const sourceRelativePath = '.mcp.json'; + const sourcePath = path.join(repoRoot, sourceRelativePath); + if (!fs.existsSync(sourcePath) || !fs.statSync(sourcePath).isFile()) { + return null; + } + + return createManagedOperation({ + kind: 'merge-json', + moduleId, + sourceRelativePath, + destinationPath: path.join(targetRoot, 'mcp.json'), + strategy: 'merge-json', + scaffoldOnly: false, + mergePayload: readJsonObject(sourcePath, sourceRelativePath), + }); +} + +module.exports = createInstallTargetAdapter({ + id: 'kimi-project', + target: 'kimi', + kind: 'project', + rootSegments: ['.kimi-code'], + installStatePathSegments: ['ecc-install-state.json'], + nativeRootRelativePath: '.kimi-code', + planOperations(input, adapter) { + const modules = Array.isArray(input.modules) + ? input.modules + : (input.module ? [input.module] : []); + const planningInput = { + repoRoot: input.repoRoot, + projectRoot: input.projectRoot, + homeDir: input.homeDir, + }; + const targetRoot = adapter.resolveRoot(planningInput); + + return modules.flatMap(module => { + const paths = Array.isArray(module.paths) ? module.paths : []; + + return paths + .filter(sourceRelativePath => !isForeignPlatformPath(sourceRelativePath, adapter.target)) + .flatMap(sourceRelativePath => { + if (sourceRelativePath === '.kimi') { + // The repository's compatibility documentation still lives in + // .kimi/. Sync its children into the current native root without + // creating that obsolete directory in the destination project. + return [createManagedOperation({ + moduleId: module.id, + sourceRelativePath, + destinationPath: targetRoot, + strategy: 'sync-root-children', + })]; + } + + if (sourceRelativePath === '.agents') { + const skillsSourcePath = path.join(input.repoRoot || '', '.agents', 'skills'); + if (!input.repoRoot || !fs.existsSync(skillsSourcePath)) { + return []; + } + + return [createManagedOperation({ + moduleId: module.id, + sourceRelativePath: '.agents/skills', + destinationPath: path.join(targetRoot, 'skills'), + strategy: 'preserve-relative-path', + })]; + } + + if (sourceRelativePath === 'mcp-configs') { + const mcpMergeOperation = createMcpMergeOperation(module.id, input.repoRoot, targetRoot); + return [ + adapter.createScaffoldOperation(module.id, sourceRelativePath, planningInput), + ...(mcpMergeOperation ? [mcpMergeOperation] : []), + ]; + } + + return [adapter.createScaffoldOperation(module.id, sourceRelativePath, planningInput)]; + }); + }); + }, +}); diff --git a/github_code/affaan-m__ECC/scripts/lib/install-targets/openclaw-home.js b/github_code/affaan-m__ECC/scripts/lib/install-targets/openclaw-home.js new file mode 100644 index 0000000000000000000000000000000000000000..89dab46966ee17ed59a51e8408530a78df8d3415 --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/install-targets/openclaw-home.js @@ -0,0 +1,10 @@ +const { createInstallTargetAdapter } = require('./helpers'); + +module.exports = createInstallTargetAdapter({ + id: 'openclaw-home', + target: 'openclaw', + kind: 'home', + rootSegments: ['.openclaw'], + installStatePathSegments: ['ecc-install-state.json'], + nativeRootRelativePath: '.openclaw', +}); diff --git a/github_code/affaan-m__ECC/scripts/lib/install-targets/opencode-home.js b/github_code/affaan-m__ECC/scripts/lib/install-targets/opencode-home.js new file mode 100644 index 0000000000000000000000000000000000000000..d25fdf7da76e590b2f58d5cd3faeedfa3b027252 --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/install-targets/opencode-home.js @@ -0,0 +1,92 @@ +const fs = require('fs'); +const os = require('os'); +const path = require('path'); + +const { + buildValidationIssue, + createInstallTargetAdapter, +} = require('./helpers'); +const { resolveOpencodeConfigRoot } = require('../opencode-paths'); + +const COMPILED_PLUGIN_DIST_DIR = path.join('.opencode', 'dist'); +const REQUIRED_COMPILED_ARTEFACTS = Object.freeze([ + { relativePath: path.join(COMPILED_PLUGIN_DIST_DIR, 'index.js'), expectedType: 'file' }, + { relativePath: path.join(COMPILED_PLUGIN_DIST_DIR, 'plugins'), expectedType: 'directory' }, + { relativePath: path.join(COMPILED_PLUGIN_DIST_DIR, 'tools'), expectedType: 'directory' }, +]); +const BUILD_COMMAND_HINT = 'node scripts/build-opencode.js (or: npm run build:opencode)'; + +// Errors that mean "this artefact does not exist at the expected path / type". +// Anything else (EACCES, EIO, ...) is a genuine system fault we surface to the +// caller rather than masking as a missing artefact. +const MISSING_ARTEFACT_ERROR_CODES = new Set(['ENOENT', 'ENOTDIR']); + +function isExpectedType(absolutePath, expectedType) { + let stat; + try { + stat = fs.statSync(absolutePath); + } catch (error) { + if (error && MISSING_ARTEFACT_ERROR_CODES.has(error.code)) { + return false; + } + throw error; + } + return expectedType === 'file' ? stat.isFile() : stat.isDirectory(); +} + +function defaultValidateOpencodeHome(input = {}) { + if (!input.homeDir && !os.homedir()) { + return [ + buildValidationIssue( + 'error', + 'missing-home-dir', + 'homeDir is required for home install targets' + ), + ]; + } + + if (!input.repoRoot) { + return []; + } + + const missingPaths = REQUIRED_COMPILED_ARTEFACTS + .map(artefact => ({ + relativePath: artefact.relativePath, + absolutePath: path.join(input.repoRoot, artefact.relativePath), + expectedType: artefact.expectedType, + })) + .filter(entry => !isExpectedType(entry.absolutePath, entry.expectedType)); + + if (missingPaths.length > 0) { + const missingList = missingPaths.map(entry => entry.relativePath).join(', '); + return [ + buildValidationIssue( + 'error', + 'opencode-plugin-not-built', + 'OpenCode install requires the compiled plugin payload under ' + + `${COMPILED_PLUGIN_DIST_DIR}, but the following artefact(s) were ` + + `missing or had the wrong type: ${missingList}. Run ` + + `${BUILD_COMMAND_HINT} from the repo root before re-running the ` + + 'installer.', + { + missingPaths: missingPaths.map(entry => entry.absolutePath), + missingRelativePaths: missingPaths.map(entry => entry.relativePath), + expectedTypes: missingPaths.map(entry => entry.expectedType), + } + ), + ]; + } + + return []; +} + +module.exports = createInstallTargetAdapter({ + id: 'opencode-home', + target: 'opencode', + kind: 'home', + rootSegments: ['.config', 'opencode'], + resolveRoot: resolveOpencodeConfigRoot, + installStatePathSegments: ['ecc-install-state.json'], + nativeRootRelativePath: '.opencode', + validate: defaultValidateOpencodeHome, +}); diff --git a/github_code/affaan-m__ECC/scripts/lib/install-targets/qwen-home.js b/github_code/affaan-m__ECC/scripts/lib/install-targets/qwen-home.js new file mode 100644 index 0000000000000000000000000000000000000000..96981d7b06cd4a65cf31995a4125efa8b5099b64 --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/install-targets/qwen-home.js @@ -0,0 +1,10 @@ +const { createInstallTargetAdapter } = require('./helpers'); + +module.exports = createInstallTargetAdapter({ + id: 'qwen-home', + target: 'qwen', + kind: 'home', + rootSegments: ['.qwen'], + installStatePathSegments: ['ecc-install-state.json'], + nativeRootRelativePath: '.qwen', +}); diff --git a/github_code/affaan-m__ECC/scripts/lib/install-targets/registry.js b/github_code/affaan-m__ECC/scripts/lib/install-targets/registry.js new file mode 100644 index 0000000000000000000000000000000000000000..8dd7cf848810c1512dff72fdae4841563dea5d58 --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/install-targets/registry.js @@ -0,0 +1,91 @@ +const adalProject = require('./adal-project'); +const antigravityProject = require('./antigravity-project'); +const claudeHome = require('./claude-home'); +const claudeProject = require('./claude-project'); +const codebuddyProject = require('./codebuddy-project'); +const codexHome = require('./codex-home'); +const cursorProject = require('./cursor-project'); +const geminiProject = require('./gemini-project'); +const hermesHome = require('./hermes-home'); +const joycodeProject = require('./joycode-project'); +const kimiProject = require('./kimi-project'); +const openclawHome = require('./openclaw-home'); +const opencodeHome = require('./opencode-home'); +const qwenHome = require('./qwen-home'); +const zedProject = require('./zed-project'); +const { resolveInvocationEnvironment } = require('../invocation-environment'); + +const ADAPTERS = Object.freeze([ + claudeHome, + claudeProject, + cursorProject, + antigravityProject, + codexHome, + geminiProject, + hermesHome, + opencodeHome, + openclawHome, + codebuddyProject, + joycodeProject, + kimiProject, + qwenHome, + zedProject, + adalProject, +]); + +function listInstallTargetAdapters() { + return ADAPTERS.slice(); +} + +function getInstallTargetAdapter(targetOrAdapterId) { + const adapter = ADAPTERS.find(candidate => candidate.supports(targetOrAdapterId)); + + if (!adapter) { + throw new Error(`Unknown install target adapter: ${targetOrAdapterId}`); + } + + return adapter; +} + +function planInstallTargetScaffold(options = {}) { + const adapter = getInstallTargetAdapter(options.target); + const modules = Array.isArray(options.modules) ? options.modules : []; + const exemptValidationCodes = new Set(Array.isArray(options.exemptValidationCodes) ? options.exemptValidationCodes : []); + const planningInput = { + repoRoot: options.repoRoot, + projectRoot: options.projectRoot || options.repoRoot, + homeDir: options.homeDir, + env: resolveInvocationEnvironment(options), + }; + const validationIssues = adapter.validate(planningInput); + const blockingIssues = validationIssues.filter(issue => ( + issue.severity === 'error' && !exemptValidationCodes.has(issue.code) + )); + if (blockingIssues.length > 0) { + throw new Error(blockingIssues.map(issue => issue.message).join('; ')); + } + const targetRoot = adapter.resolveRoot(planningInput); + const installStatePath = adapter.getInstallStatePath(planningInput); + const operations = adapter.planOperations({ + ...planningInput, + modules, + }); + + return { + adapter: { + id: adapter.id, + target: adapter.target, + kind: adapter.kind, + }, + targetRoot, + installStatePath, + validationIssues, + operations, + }; +} + +module.exports = { + getInstallTargetAdapter, + listInstallTargetAdapters, + planInstallTargetScaffold, +}; diff --git a/github_code/affaan-m__ECC/scripts/lib/install-targets/zed-project.js b/github_code/affaan-m__ECC/scripts/lib/install-targets/zed-project.js new file mode 100644 index 0000000000000000000000000000000000000000..c0d8b9821d4e6e3285dcf141d3afd82f6698581c --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/install-targets/zed-project.js @@ -0,0 +1,50 @@ +const path = require('path'); + +const { + createFlatRuleOperations, + createInstallTargetAdapter, + isForeignPlatformPath, +} = require('./helpers'); + +module.exports = createInstallTargetAdapter({ + id: 'zed-project', + target: 'zed', + kind: 'project', + rootSegments: ['.zed'], + installStatePathSegments: ['ecc-install-state.json'], + nativeRootRelativePath: '.zed', + planOperations(input, adapter) { + const modules = Array.isArray(input.modules) + ? input.modules + : (input.module ? [input.module] : []); + const { + repoRoot, + projectRoot, + homeDir, + } = input; + const planningInput = { + repoRoot, + projectRoot, + homeDir, + }; + const targetRoot = adapter.resolveRoot(planningInput); + + return modules.flatMap(module => { + const paths = Array.isArray(module.paths) ? module.paths : []; + return paths + .filter(p => !isForeignPlatformPath(p, adapter.target)) + .flatMap(sourceRelativePath => { + if (sourceRelativePath === 'rules') { + return createFlatRuleOperations({ + moduleId: module.id, + repoRoot, + sourceRelativePath, + destinationDir: path.join(targetRoot, 'rules'), + }); + } + + return [adapter.createScaffoldOperation(module.id, sourceRelativePath, planningInput)]; + }); + }); + }, +}); diff --git a/github_code/affaan-m__ECC/scripts/lib/install/antigravity-agent.js b/github_code/affaan-m__ECC/scripts/lib/install/antigravity-agent.js new file mode 100644 index 0000000000000000000000000000000000000000..7e4f7a962a48cb8a1183568c9b8a4364b18cca86 --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/install/antigravity-agent.js @@ -0,0 +1,68 @@ +'use strict'; + +const TOOL_NAMES = Object.freeze({ + Read: 'view_file', + Write: 'write_to_file', + Edit: 'replace_file_content', + Grep: 'grep_search', + Glob: 'find_by_name', + Bash: 'run_command', + WebSearch: 'search_web', + WebFetch: 'read_url_content', +}); + +const MODEL_NAMES = Object.freeze({ + haiku: 'flash', + sonnet: 'pro', + opus: 'pro', +}); + +function splitFrontmatter(source, label) { + const match = String(source || '').match(/^---\r?\n([\s\S]*?)\r?\n---\r?\n/); + if (!match) { + throw new Error(`Cannot adapt Antigravity agent ${label}: missing YAML frontmatter`); + } + + // Keep YAML loading behind the transform boundary. Public help commands load + // the installer graph without executing a transform, including in hermetic + // packed-artifact checks where runtime dependencies are intentionally absent. + const frontmatter = require('js-yaml').load(match[1]); + if (!frontmatter || typeof frontmatter !== 'object' || Array.isArray(frontmatter)) { + throw new Error(`Cannot adapt Antigravity agent ${label}: frontmatter must be an object`); + } + + return { + frontmatter, + body: source.slice(match[0].length), + }; +} + +function normalizeToolNames(value) { + const names = Array.isArray(value) ? value : String(value || '').split(','); + return [...new Set(names + .map(name => String(name).trim()) + .filter(name => Object.hasOwn(TOOL_NAMES, name)) + .map(name => TOOL_NAMES[name]))]; +} + +function adaptAntigravityAgent(source, label = '') { + const { frontmatter, body } = splitFrontmatter(source, label); + const { color: _claudeColor, ...supportedFrontmatter } = frontmatter; + const adapted = { ...supportedFrontmatter }; + if (Object.hasOwn(frontmatter, 'tools')) { + adapted.tools = normalizeToolNames(frontmatter.tools); + } + if (Object.hasOwn(frontmatter, 'model')) { + adapted.model = Object.hasOwn(MODEL_NAMES, frontmatter.model) + ? MODEL_NAMES[frontmatter.model] + : frontmatter.model; + } + const serialized = require('js-yaml') + .dump(adapted, { lineWidth: -1, noRefs: true }) + .trimEnd(); + return `---\n${serialized}\n---\n${body}`; +} + +module.exports = { + adaptAntigravityAgent, +}; diff --git a/github_code/affaan-m__ECC/scripts/lib/install/antigravity-legacy-migration.js b/github_code/affaan-m__ECC/scripts/lib/install/antigravity-legacy-migration.js new file mode 100644 index 0000000000000000000000000000000000000000..4f5e1a055aef79914a57c12acacd365167aa9bea --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/install/antigravity-legacy-migration.js @@ -0,0 +1,413 @@ +'use strict'; + +const crypto = require('crypto'); +const fs = require('fs'); +const path = require('path'); + +const { readInstallState } = require('../install-state'); +const { assertWithinTrustedRoot } = require('../path-safety'); + +const ANTIGRAVITY_TARGET = 'antigravity'; +const CANONICAL_ROOT_NAME = '.agents'; +const LEGACY_ROOT_NAME = '.agent'; +const INSTALL_STATE_NAME = 'ecc-install-state.json'; + +function samePath(leftPath, rightPath) { + const left = path.resolve(leftPath); + const right = path.resolve(rightPath); + if (process.platform === 'win32') { + return left.toLowerCase() === right.toLowerCase(); + } + return left === right; +} + +function pathExists(filePath) { + try { + fs.lstatSync(filePath); + return true; + } catch (error) { + if (error && (error.code === 'ENOENT' || error.code === 'ENOTDIR')) { + return false; + } + throw error; + } +} + +function getLegacyAntigravityLocation(projectRoot) { + const targetRoot = path.join(path.resolve(projectRoot), LEGACY_ROOT_NAME); + return { + targetRoot, + installStatePath: path.join(targetRoot, INSTALL_STATE_NAME), + }; +} + +function getLegacyLocationForPlan(plan) { + if ( + !plan + || !plan.adapter + || plan.adapter.target !== ANTIGRAVITY_TARGET + || typeof plan.targetRoot !== 'string' + || path.basename(path.resolve(plan.targetRoot)) !== CANONICAL_ROOT_NAME + ) { + return null; + } + + return getLegacyAntigravityLocation(path.dirname(path.resolve(plan.targetRoot))); +} + +function inspectLegacyAntigravityState(location) { + if (!location) { + return { status: 'absent', state: null, error: null }; + } + try { + if (!pathExists(location.installStatePath)) { + return { status: 'absent', state: null, error: null }; + } + const rootStat = fs.lstatSync(location.targetRoot); + const stateStat = fs.lstatSync(location.installStatePath); + if ( + !rootStat.isDirectory() + || rootStat.isSymbolicLink() + || !stateStat.isFile() + || stateStat.isSymbolicLink() + ) { + return { status: 'invalid', state: null, error: null }; + } + const state = readInstallState(location.installStatePath); + const isAntigravity = state.target.target === ANTIGRAVITY_TARGET + || state.target.id === 'antigravity-project'; + if ( + !isAntigravity + || !samePath(state.target.root, location.targetRoot) + || !samePath(state.target.installStatePath, location.installStatePath) + || state.operations.some(operation => ( + operation.kind !== 'copy-file' + || operation.ownership !== 'managed' + )) + ) { + return { status: 'invalid', state: null, error: null }; + } + return { status: 'valid', state, error: null }; + } catch (error) { + return { + status: 'unreadable', + state: null, + error: `Unable to inspect legacy Antigravity install-state at ${location.installStatePath}: ${error.message}`, + }; + } +} + +function readValidLegacyAntigravityState(location) { + const inspection = inspectLegacyAntigravityState(location); + return inspection.status === 'valid' ? inspection.state : null; +} + +function sha256FileNoFollow(filePath) { + const flags = fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW || 0); + const descriptor = fs.openSync(filePath, flags); + try { + const stat = fs.fstatSync(descriptor); + if (!stat.isFile()) { + return null; + } + return { + digest: crypto.createHash('sha256').update(fs.readFileSync(descriptor)).digest('hex'), + stat, + }; + } finally { + fs.closeSync(descriptor); + } +} + +function getExpectedLegacyDestination(operation, legacyRoot) { + const sourceRelativePath = String(operation.sourceRelativePath || '') + .replace(/\\/g, '/') + .replace(/^\.\//, ''); + const parts = sourceRelativePath.split('/'); + if ( + path.posix.isAbsolute(sourceRelativePath) + || path.win32.isAbsolute(sourceRelativePath) + || parts.some(part => part === '' || part === '.' || part === '..') + ) { + return null; + } + + if (parts[0] === 'rules' && parts.length >= 2) { + const fileName = parts.length === 2 + ? parts[1] + : `${parts[1]}-${parts.slice(2).join('-')}`; + return path.join(legacyRoot, 'rules', fileName); + } + if (parts[0] === 'commands' && parts.length >= 2) { + return path.join(legacyRoot, 'workflows', ...parts.slice(1)); + } + if (parts[0] === 'agents' && parts.length >= 2) { + return path.join(legacyRoot, 'skills', ...parts.slice(1)); + } + if (parts[0] === '.agents' && parts.length >= 2) { + return path.join(legacyRoot, '.agents', ...parts.slice(1)); + } + if (sourceRelativePath === 'AGENTS.md') { + return path.join(legacyRoot, 'AGENTS.md'); + } + return null; +} + +function getVerifiedManagedFile(operation, legacyRoot, sourceRoot) { + if ( + !operation + || operation.ownership !== 'managed' + || operation.kind !== 'copy-file' + || typeof operation.destinationPath !== 'string' + || typeof sourceRoot !== 'string' + || !/^[a-f0-9]{64}$/i.test(operation.contentSha256 || '') + ) { + return null; + } + + let destinationPath; + let sourcePath; + try { + const expectedDestination = getExpectedLegacyDestination(operation, legacyRoot); + if (!expectedDestination || !samePath(operation.destinationPath, expectedDestination)) { + return null; + } + destinationPath = assertWithinTrustedRoot( + operation.destinationPath, + legacyRoot, + 'migrate legacy Antigravity install' + ); + sourcePath = assertWithinTrustedRoot( + path.join(sourceRoot, operation.sourceRelativePath), + sourceRoot, + 'verify legacy Antigravity source' + ); + } catch (_error) { + return null; + } + + if (!pathExists(destinationPath)) { + return { destinationPath, missing: true }; + } + + const stat = fs.lstatSync(destinationPath); + if (!stat.isFile() || stat.isSymbolicLink()) { + return null; + } + + const destination = sha256FileNoFollow(destinationPath); + if ( + !destination + || destination.digest !== operation.contentSha256.toLowerCase() + ) { + return null; + } + + if (!pathExists(sourcePath)) { + return { + destinationPath, + fileStat: destination.stat, + missing: false, + retainedReason: 'The current ECC source file is unavailable, so its provenance cannot be revalidated.', + }; + } + + const source = sha256FileNoFollow(sourcePath); + if (!source || destination.digest !== source.digest) { + return { + destinationPath, + fileStat: destination.stat, + missing: false, + retainedReason: 'The current ECC source differs from the recorded installed content, so the legacy file was preserved.', + }; + } + + return { destinationPath, fileStat: destination.stat, missing: false }; +} + +function cleanupResult(overrides = {}) { + return { + detected: false, + complete: false, + removedPaths: [], + retainedPaths: [], + warnings: [], + ...overrides, + }; +} + +function removeEmptyParents(startPath, legacyRoot) { + let currentPath = path.dirname(startPath); + while (!samePath(currentPath, legacyRoot)) { + let safePath; + try { + safePath = assertWithinTrustedRoot( + currentPath, + legacyRoot, + 'clean legacy Antigravity install' + ); + } catch (_error) { + return; + } + if (!pathExists(safePath)) { + currentPath = path.dirname(safePath); + continue; + } + const stat = fs.lstatSync(safePath); + if (!stat.isDirectory() || stat.isSymbolicLink() || fs.readdirSync(safePath).length > 0) { + return; + } + fs.rmdirSync(safePath); + currentPath = path.dirname(safePath); + } +} + +function listLegacyContent(legacyRoot, installStatePath) { + if (!pathExists(legacyRoot)) { + return []; + } + + const content = []; + const pending = [legacyRoot]; + while (pending.length > 0) { + const currentPath = pending.pop(); + for (const entry of fs.readdirSync(currentPath, { withFileTypes: true })) { + const entryPath = path.join(currentPath, entry.name); + if (samePath(entryPath, installStatePath)) { + continue; + } + if (entry.isDirectory() && !entry.isSymbolicLink()) { + pending.push(entryPath); + } else { + content.push(entryPath); + } + } + } + return content; +} + +function removeLegacyStateWhenEmpty(location) { + if (listLegacyContent(location.targetRoot, location.installStatePath).length > 0) { + return false; + } + + try { + fs.rmSync(location.installStatePath, { force: true }); + } catch (_error) { + return false; + } + try { + if (pathExists(location.targetRoot) && fs.readdirSync(location.targetRoot).length === 0) { + fs.rmdirSync(location.targetRoot); + } + } catch (_error) { + // Root cleanup is best effort after the legacy state is gone. + } + return true; +} + +function cleanupLegacyAntigravityInstall(plan) { + const location = getLegacyLocationForPlan(plan); + if (!location || typeof plan.sourceRoot !== 'string' || !pathExists(plan.installStatePath)) { + return cleanupResult(); + } + + try { + const canonicalState = readInstallState(plan.installStatePath); + const isCanonicalState = ( + canonicalState.target.target === ANTIGRAVITY_TARGET + || canonicalState.target.id === 'antigravity-project' + ) + && samePath(canonicalState.target.root, plan.targetRoot) + && samePath(canonicalState.target.installStatePath, plan.installStatePath); + if (!isCanonicalState) { + return cleanupResult(); + } + } catch (_error) { + return cleanupResult(); + } + + const legacyInspection = inspectLegacyAntigravityState(location); + if (legacyInspection.status === 'unreadable') { + return cleanupResult({ + detected: true, + retainedPaths: [location.targetRoot], + warnings: [legacyInspection.error], + }); + } + if (legacyInspection.status !== 'valid') { + return cleanupResult(); + } + const legacyState = legacyInspection.state; + + const removedPaths = []; + const filesToRemove = []; + const warnings = []; + for (const operation of legacyState.operations || []) { + const verified = getVerifiedManagedFile(operation, location.targetRoot, plan.sourceRoot); + if (!verified) { + continue; + } + if (verified.missing) { + continue; + } + if (verified.retainedReason) { + warnings.push(`${verified.destinationPath}: ${verified.retainedReason}`); + continue; + } + filesToRemove.push({ + destinationPath: verified.destinationPath, + fileStat: verified.fileStat, + }); + } + + for (const { destinationPath, fileStat } of filesToRemove) { + try { + const safeDestination = assertWithinTrustedRoot( + destinationPath, + location.targetRoot, + 'remove verified legacy Antigravity file' + ); + const currentStat = fs.lstatSync(safeDestination); + if ( + currentStat.isSymbolicLink() + || !currentStat.isFile() + || currentStat.dev !== fileStat.dev + || currentStat.ino !== fileStat.ino + ) { + continue; + } + fs.rmSync(safeDestination); + removedPaths.push(safeDestination); + removeEmptyParents(safeDestination, location.targetRoot); + } catch (_error) { + // Keep failed deletions tracked in legacy state so a later install can retry. + } + } + + let complete = false; + try { + complete = removeLegacyStateWhenEmpty(location); + } catch (_error) { + complete = false; + } + if (complete) { + removedPaths.push(location.installStatePath); + } + let retainedPaths = []; + if (!complete) { + try { + retainedPaths = listLegacyContent(location.targetRoot, location.installStatePath); + } catch (_error) { + retainedPaths = [location.targetRoot]; + } + } + return cleanupResult({ detected: true, complete, removedPaths, retainedPaths, warnings }); +} + +module.exports = { + cleanupLegacyAntigravityInstall, + getLegacyAntigravityLocation, + inspectLegacyAntigravityState, + readValidLegacyAntigravityState, +}; diff --git a/github_code/affaan-m__ECC/scripts/lib/install/apply.js b/github_code/affaan-m__ECC/scripts/lib/install/apply.js new file mode 100644 index 0000000000000000000000000000000000000000..fbab1293bb8dcdebb1df4a23556f06419bd290ec --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/install/apply.js @@ -0,0 +1,689 @@ +'use strict'; + +const crypto = require('crypto'); +const fs = require('fs'); +const path = require('path'); + +const { + hasExplicitCommitAttributionPreference, + withCommitAttributionDisabled, +} = require('../claude-commit-attribution'); +const { readInstallState, writeInstallState } = require('../install-state'); +const { assertHookConsentReady, planMaterializesHookRuntime } = require('./hook-consent'); +const { + getClaudeSettingsPath, + mergeManagedHooks, + readSettings, + runWithSettingsLock, + uninstallManagedHooks, + updateSettingsAtomic, + validateManagedHooks, + validateRecordedManagedHooks, +} = require('./claude-settings'); +const { filterMcpConfig, parseDisabledMcpServers } = require('../mcp-config'); +const { assertWithinTrustedRoot } = require('../path-safety'); +const { + assertSafeClaudeSkillOperation, + prepareClaudeSkillMigration, + removeLegacyClaudeSkillFiles, +} = require('./claude-skill-migration'); +const { cleanupLegacyAntigravityInstall } = require('./antigravity-legacy-migration'); +const { + assertNoNewUserOwnedFile, + prepareUserOwnedFileGuard, + preserveUnwrittenFiles, +} = require('./ownership-guard'); +const { cleanupLegacyOpencodeInstall } = require('./opencode-legacy-migration'); +const { buildInstallIndex, rewriteRelativeLinks } = require('./link-rewrite'); +const { adaptAntigravityAgent } = require('./antigravity-agent'); + +function isMarkdownPath(filePath) { + return /\.(md|mdx|markdown)$/i.test(String(filePath || '')); +} + +function transformInstallContent(operation, content) { + if (!operation.contentTransform) { + return content; + } + if (operation.contentTransform === 'antigravity-agent-frontmatter') { + return adaptAntigravityAgent(content, operation.sourceRelativePath); + } + throw new Error(`Unknown install content transform: ${operation.contentTransform}`); +} + +// Map every copy-file operation to { sourceRel, destRel } so relative links in +// namespaced markdown can be rewritten to the file's actual installed location +// (issue #2340). Returns null when the plan lacks the data needed to do so. +function buildLinkIndexForPlan(plan) { + if (!plan || !plan.targetRoot || !Array.isArray(plan.operations)) { + return null; + } + const mappings = []; + for (const operation of plan.operations) { + if (operation.kind === 'copy-file' && operation.sourceRelativePath) { + mappings.push({ + sourceRel: operation.sourceRelativePath, + destRel: path.relative(plan.targetRoot, operation.destinationPath), + }); + } + } + return buildInstallIndex(mappings); +} + +function readJsonObject(filePath, label) { + let parsed; + try { + parsed = JSON.parse(fs.readFileSync(filePath, 'utf8')); + } catch (error) { + const wrappedError = new Error(`Failed to parse ${label} at ${filePath}: ${error.message}`); + wrappedError.code = error.code; + throw wrappedError; + } + + if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) { + throw new Error(`Invalid ${label} at ${filePath}: expected a JSON object`); + } + + return parsed; +} + +function readOptionalJsonObject(filePath, label) { + try { + return readJsonObject(filePath, label); + } catch (error) { + if (error.code === 'ENOENT') { + return {}; + } + throw error; + } +} + +function readInstalledFileNoFollow(plan, operation) { + assertSafeInstallOperation(plan, operation); + assertSafeClaudeSkillOperation(plan, operation); + const flags = fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW || 0); + let descriptor; + try { + descriptor = fs.openSync(operation.destinationPath, flags); + } catch (error) { + if (error.code === 'ENOENT') { + return null; + } + throw error; + } + + try { + const openedStat = fs.fstatSync(descriptor, { bigint: true }); + const finalPathStat = fs.lstatSync(operation.destinationPath, { bigint: true }); + if (finalPathStat.isSymbolicLink() || !finalPathStat.isFile()) { + return null; + } + const identityMatches = openedStat.ino === finalPathStat.ino + && (!openedStat.dev || !finalPathStat.dev || openedStat.dev === finalPathStat.dev); + if (!openedStat.isFile() || !identityMatches) { + throw new Error( + `Refusing to hash changed install destination: ${operation.destinationPath}` + ); + } + // Revalidate the full path after opening. The descriptor pins the file so + // the digest and metadata refer to the same object. + assertSafeInstallOperation(plan, operation); + assertSafeClaudeSkillOperation(plan, operation); + return fs.readFileSync(descriptor); + } finally { + fs.closeSync(descriptor); + } +} + +function stateWithContentDigests(state, plan) { + const currentDestinations = new Set((plan.operations || []) + .filter(operation => operation.destinationPath) + .map(operation => { + const resolved = path.resolve(operation.destinationPath); + return process.platform === 'win32' ? resolved.toLowerCase() : resolved; + })); + return { + ...state, + operations: (state.operations || []).map(operation => { + if (!operation.destinationPath) { + return { ...operation }; + } + const resolved = path.resolve(operation.destinationPath); + const destinationKey = process.platform === 'win32' + ? resolved.toLowerCase() + : resolved; + if (!currentDestinations.has(destinationKey)) { + return { ...operation }; + } + const installedContent = readInstalledFileNoFollow(plan, operation); + if (installedContent === null) { + return { ...operation }; + } + return { + ...operation, + contentSha256: crypto.createHash('sha256') + .update(installedContent) + .digest('hex'), + }; + }), + }; +} + +function cloneJsonValue(value) { + if (value === undefined) { + return undefined; + } + + return JSON.parse(JSON.stringify(value)); +} + +function isPlainObject(value) { + return Boolean(value) && typeof value === 'object' && !Array.isArray(value); +} + +function deepMergeJson(baseValue, patchValue) { + if (!isPlainObject(baseValue) || !isPlainObject(patchValue)) { + return cloneJsonValue(patchValue); + } + + const merged = { ...baseValue }; + for (const [key, value] of Object.entries(patchValue)) { + if (isPlainObject(value) && isPlainObject(merged[key])) { + merged[key] = deepMergeJson(merged[key], value); + } else { + merged[key] = cloneJsonValue(value); + } + } + return merged; +} + +function formatJson(value) { + return `${JSON.stringify(value, null, 2)}\n`; +} + +function shouldSetClaudeCommitAttributionPreference(plan) { + if (!plan?.adapter || !['claude', 'claude-project'].includes(plan.adapter.target)) { + return false; + } + + return plan.operations.some(operation => { + if (typeof operation?.destinationPath !== 'string') { + return false; + } + const relativePath = path.relative(plan.targetRoot, operation.destinationPath); + return relativePath && !relativePath.startsWith(`docs${path.sep}`) && relativePath !== 'docs'; + }); +} + +function writeClaudeCommitAttributionPreference(settingsPath, options = {}) { + let settings; + try { + settings = readSettings(settingsPath); + } catch (_error) { + // Unreadable or malformed settings belong to the user; leave them untouched. + return false; + } + + if (hasExplicitCommitAttributionPreference(settings)) { + return false; + } + + let changed = false; + updateSettingsAtomic(settingsPath, latestSettings => { + if (hasExplicitCommitAttributionPreference(latestSettings)) { + return { settings: latestSettings }; + } + changed = true; + return { settings: withCommitAttributionDisabled(latestSettings) }; + }, options); + return changed; +} + +function isMcpConfigPath(filePath) { + const basename = path.basename(String(filePath || '')); + return basename === '.mcp.json' || basename === 'mcp.json'; +} + +function assertSafeInstallOperation(plan, operation) { + if (!operation || typeof operation.destinationPath !== 'string') { + throw new Error('Refusing to apply install operation: missing destination path.'); + } + + const targetRoot = plan && plan.targetRoot; + assertWithinTrustedRoot(operation.destinationPath, targetRoot, 'install ECC file'); + + const resolvedRoot = path.resolve(targetRoot); + const resolvedTarget = path.resolve(operation.destinationPath); + const relativePath = path.relative(resolvedRoot, resolvedTarget); + const segments = relativePath ? relativePath.split(path.sep) : []; + for (const segmentIndex of Array.from({ length: segments.length + 1 }, (_value, index) => index)) { + const currentPath = segmentIndex === 0 + ? resolvedRoot + : path.join(resolvedRoot, ...segments.slice(0, segmentIndex)); + try { + const stats = fs.lstatSync(currentPath); + if (stats.isSymbolicLink()) { + throw new Error( + `Refusing to install ECC file through symlinked path: '${currentPath}'.` + ); + } + } catch (error) { + if (error && error.code === 'ENOENT') { + break; + } + throw error; + } + } +} + +function readPreviousInstallState(plan) { + if (!fs.existsSync(plan.installStatePath)) { + return null; + } + return readInstallState(plan.installStatePath); +} + +function comparablePath(filePath) { + const resolved = path.resolve(filePath); + return process.platform === 'win32' ? resolved.toLowerCase() : resolved; +} + +function findPreviousManagedHooks(previousState, plan, operation) { + if ( + !previousState + || previousState.target.id !== plan.adapter.id + || comparablePath(previousState.target.root) !== comparablePath(plan.targetRoot) + || comparablePath(previousState.target.installStatePath) !== comparablePath(plan.installStatePath) + ) { + return null; + } + + const previousOperation = (previousState.operations || []).find(candidate => ( + candidate.kind === operation.kind + && comparablePath(candidate.destinationPath) === comparablePath(operation.destinationPath) + )); + if (!previousOperation || !previousOperation.managedHooks) { + return null; + } + + return validateRecordedManagedHooks( + previousOperation.managedHooks, + 'previous managed hooks' + ); +} + +function preflightClaudeSettingsOperations(plan) { + const settingsOperations = plan.operations.filter(operation => ( + operation.kind === 'update-claude-settings' + || operation.kind === 'remove-claude-settings-hooks' + )); + if (settingsOperations.length === 0) { + return new Map(); + } + + const previousState = readPreviousInstallState(plan); + return new Map(settingsOperations.map(operation => { + assertSafeInstallOperation(plan, operation); + const managedHooks = validateManagedHooks(operation.managedHooks); + const settings = readSettings(operation.destinationPath); + const previousManagedHooks = findPreviousManagedHooks(previousState, plan, operation); + if (operation.kind === 'remove-claude-settings-hooks') { + const removal = uninstallManagedHooks(settings, managedHooks); + if (removal.retained.length > 0) { + throw new Error( + `Refusing to disable modified Claude hooks in ${operation.destinationPath}; ` + + 'run the ECC uninstaller to review retained entries.' + ); + } + } else { + mergeManagedHooks(settings, managedHooks, { previousManagedHooks }); + } + return [operation, { managedHooks, previousManagedHooks }]; + })); +} + +function prepareHookConsentMigration(plan, migration) { + if (plan.hookConsent !== 'declined') { + return migration; + } + const previousState = readPreviousInstallState(plan); + if (!previousState) { + return migration; + } + + const removals = (previousState.operations || []) + .filter(operation => operation.kind === 'update-claude-settings') + .map(operation => ({ + ...operation, + kind: 'remove-claude-settings-hooks', + strategy: 'remove-hook-ids', + scaffoldOnly: false, + })); + if (removals.length === 0) { + return migration; + } + const removalDestinations = new Set(removals.map(operation => comparablePath( + operation.destinationPath + ))); + return { + ...migration, + // Disable hooks only after every ordinary install operation succeeds so a + // partial reinstall cannot silently revoke working hooks before failing. + appliedOperations: [...migration.appliedOperations, ...removals], + finalState: { + ...migration.finalState, + operations: migration.finalState.operations.filter(operation => !( + operation.kind === 'update-claude-settings' + && removalDestinations.has(comparablePath(operation.destinationPath)) + )), + }, + bridgeState: { + ...migration.bridgeState, + request: { + ...migration.bridgeState.request, + hookConsent: 'enabled', + }, + resolution: { + ...migration.bridgeState.resolution, + selectedModules: [...new Set([ + ...migration.bridgeState.resolution.selectedModules, + 'hooks-runtime', + ])], + }, + }, + requiresBridgeState: true, + }; +} + +function previewInstallPlan(plan) { + const migration = prepareHookConsentMigration( + plan, + prepareUserOwnedFileGuard(plan, prepareClaudeSkillMigration(plan)) + ); + const appliedPlan = { + ...plan, + operations: migration.appliedOperations, + }; + preflightClaudeSettingsOperations(appliedPlan); + const hookConsentWarnings = planMaterializesHookRuntime(plan) && plan.hookConsent !== 'enabled' + ? ['Applying this plan requires an explicit hook decision: --enable-hooks or --no-hooks.'] + : []; + return { + ...plan, + statePreview: migration.finalState, + plannedOperations: [...plan.operations], + operations: migration.appliedOperations, + skippedOperations: migration.skippedOperations, + warnings: [ + ...(Array.isArray(plan.warnings) ? plan.warnings : []), + ...migration.warnings, + ...hookConsentWarnings, + ], + applied: false, + }; +} + +function applyInstallPlan(plan, dependencies = {}) { + assertHookConsentReady(plan); + const isClaudeManualTarget = plan.adapter + && (plan.adapter.target === 'claude' || plan.adapter.target === 'claude-project'); + const settingsPathToLock = isClaudeManualTarget + ? getClaudeSettingsPath(plan.targetRoot) + : null; + if (settingsPathToLock) { + assertSafeInstallOperation(plan, { destinationPath: settingsPathToLock }); + } + return settingsPathToLock + ? runWithSettingsLock( + settingsPathToLock, + () => applyInstallPlanLocked(plan, dependencies, true) + ) + : applyInstallPlanLocked(plan, dependencies, false); +} + +function applyInstallPlanLocked(plan, dependencies = {}, settingsLockHeld = false) { + const persistInstallState = dependencies.writeInstallState || writeInstallState; + const beforeInstallStateRead = dependencies.beforeInstallStateRead; + const beforeOperationWrite = dependencies.beforeOperationWrite; + const beforeInstallStateWrite = dependencies.beforeInstallStateWrite; + if (typeof beforeInstallStateRead === 'function') { + beforeInstallStateRead({ plan }); + } + const migration = prepareHookConsentMigration( + plan, + prepareUserOwnedFileGuard(plan, prepareClaudeSkillMigration(plan)) + ); + const appliedPlan = { + ...plan, + operations: migration.appliedOperations, + }; + const preparedClaudeSettings = preflightClaudeSettingsOperations(appliedPlan); + const disabledServers = parseDisabledMcpServers(process.env.ECC_DISABLED_MCPS); + const linkIndex = buildLinkIndexForPlan(appliedPlan); + const hasLegacyMigration = migration.legacyOperationsToRemove.length > 0; + const hookRemovalCount = appliedPlan.operations.filter(operation => ( + operation.kind === 'remove-claude-settings-hooks' + )).length; + let completedHookRemovalCount = 0; + const writtenDestinations = new Set(); + if (migration.requiresBridgeState) { + // Own every operation that may be written during a flat-skill migration + // before the first copy. A later failure is retryable and uninstall can + // clean the entire partial install, including non-skill files. During + // legacy migration the bridge also retains the prior managed operations. + if (typeof beforeInstallStateWrite === 'function') { + beforeInstallStateWrite({ plan: appliedPlan, state: migration.bridgeState }); + } + persistInstallState(plan.installStatePath, migration.bridgeState); + } + + let finalState; + try { + for (const operation of appliedPlan.operations) { + assertSafeInstallOperation(appliedPlan, operation); + assertSafeClaudeSkillOperation(appliedPlan, operation); + fs.mkdirSync(path.dirname(operation.destinationPath), { recursive: true }); + // Recheck directories that were absent during the first validation. This + // narrows the symlink-swap window around mkdirSync, but path checks cannot + // eliminate a later TOCTOU race before the file write. + assertSafeInstallOperation(appliedPlan, operation); + assertSafeClaudeSkillOperation(appliedPlan, operation); + if (typeof beforeOperationWrite === 'function') { + beforeOperationWrite({ plan: appliedPlan, operation }); + } + assertNoNewUserOwnedFile(migration, operation); + + if ( + operation.kind === 'update-claude-settings' + || operation.kind === 'remove-claude-settings-hooks' + ) { + // Re-read at the write boundary so unrelated settings added after + // planning are preserved. A same-ID change still fails closed. + const prepared = preparedClaudeSettings.get(operation); + assertSafeInstallOperation(appliedPlan, operation); + updateSettingsAtomic(operation.destinationPath, latestSettings => { + const merged = operation.kind === 'remove-claude-settings-hooks' + ? uninstallManagedHooks(latestSettings, prepared.managedHooks) + : mergeManagedHooks(latestSettings, prepared.managedHooks, { + previousManagedHooks: prepared.previousManagedHooks, + }); + if ( + operation.kind === 'remove-claude-settings-hooks' + && merged.retained.length > 0 + ) { + throw new Error( + `Refusing to disable modified Claude hooks in ${operation.destinationPath}; ` + + 'run the ECC uninstaller to review retained entries.' + ); + } + return merged; + }, { + lockHeld: settingsLockHeld, + beforeCommit() { + assertSafeInstallOperation(appliedPlan, operation); + }, + }); + writtenDestinations.add(operation.destinationPath); + if (operation.kind === 'remove-claude-settings-hooks') { + completedHookRemovalCount += 1; + } + continue; + } + + if (operation.kind === 'merge-json') { + const payload = cloneJsonValue(operation.mergePayload); + if (payload === undefined) { + throw new Error(`Missing merge payload for ${operation.destinationPath}`); + } + + const filteredPayload = ( + isMcpConfigPath(operation.destinationPath) && disabledServers.length > 0 + ) + ? filterMcpConfig(payload, disabledServers).config + : payload; + + const currentValue = readOptionalJsonObject( + operation.destinationPath, + 'existing JSON config' + ); + const mergedValue = deepMergeJson(currentValue, filteredPayload); + fs.writeFileSync(operation.destinationPath, formatJson(mergedValue), 'utf8'); + writtenDestinations.add(operation.destinationPath); + continue; + } + + if (operation.kind === 'copy-file' && isMcpConfigPath(operation.destinationPath) && disabledServers.length > 0) { + const sourceConfig = readJsonObject(operation.sourcePath, 'MCP config'); + const filteredConfig = filterMcpConfig(sourceConfig, disabledServers).config; + fs.writeFileSync(operation.destinationPath, formatJson(filteredConfig), 'utf8'); + writtenDestinations.add(operation.destinationPath); + continue; + } + + // Declared transforms are part of the install contract and always apply. + // Markdown link rewriting is additive when the plan has a usable index. + const needsLinkRewrite = Boolean( + linkIndex + && operation.sourceRelativePath + && isMarkdownPath(operation.destinationPath) + ); + if (operation.kind === 'copy-file' && (operation.contentTransform || needsLinkRewrite)) { + const transformed = transformInstallContent( + operation, + fs.readFileSync(operation.sourcePath, 'utf8') + ); + const installedContent = needsLinkRewrite + ? rewriteRelativeLinks(transformed, { + sourceRel: operation.sourceRelativePath, + index: linkIndex, + }) + : transformed; + fs.writeFileSync(operation.destinationPath, installedContent, 'utf8'); + writtenDestinations.add(operation.destinationPath); + continue; + } + + fs.copyFileSync(operation.sourcePath, operation.destinationPath); + writtenDestinations.add(operation.destinationPath); + } + + if (hasLegacyMigration) { + removeLegacyClaudeSkillFiles(migration, plan.targetRoot); + } + + if (shouldSetClaudeCommitAttributionPreference(appliedPlan)) { + writeClaudeCommitAttributionPreference( + getClaudeSettingsPath(plan.targetRoot), + { lockHeld: settingsLockHeld } + ); + } + + finalState = stateWithContentDigests(migration.finalState, appliedPlan); + if (typeof beforeInstallStateWrite === 'function') { + beforeInstallStateWrite({ plan: appliedPlan, state: finalState }); + } + persistInstallState(plan.installStatePath, finalState); + } catch (error) { + if (migration.requiresBridgeState) { + try { + // The bridge was committed before any writes. Refresh it with hashes of + // files that now exist so uninstall can remove only bytes this attempt + // actually installed while preserving user changes. + persistInstallState( + plan.installStatePath, + stateWithContentDigests( + preserveUnwrittenFiles( + hookRemovalCount > 0 && completedHookRemovalCount === hookRemovalCount + ? migration.finalState + : migration.bridgeState, + migration, + writtenDestinations + ), + { + ...appliedPlan, + operations: appliedPlan.operations.filter(operation => ( + writtenDestinations.has(operation.destinationPath) + )), + } + ) + ); + } catch (checkpointError) { + throw new Error( + `${error.message} Install-state checkpoint also failed: ${checkpointError.message}`, + { cause: error } + ); + } + } + throw error; + } + let antigravityMigrationWarnings = []; + try { + const antigravityMigration = cleanupLegacyAntigravityInstall(appliedPlan); + if (antigravityMigration.detected && !antigravityMigration.complete) { + antigravityMigrationWarnings = [ + 'Legacy Antigravity migration is incomplete. ECC preserved modified, unverifiable, or unmanaged content under .agent; review and move anything you want to keep, then rerun the Antigravity install.', + ...(Array.isArray(antigravityMigration.warnings) ? antigravityMigration.warnings : []), + ]; + } + } catch (error) { + antigravityMigrationWarnings = [ + `Legacy Antigravity cleanup did not finish: ${error.message}. Content under .agent was preserved; remove it manually or rerun the Antigravity install.`, + ]; + } + + let opencodeMigrationWarnings = []; + try { + const opencodeMigration = cleanupLegacyOpencodeInstall(appliedPlan); + if (opencodeMigration.detected && !opencodeMigration.complete) { + opencodeMigrationWarnings = [ + 'Legacy OpenCode migration is incomplete. ECC preserved modified or unverifiable managed content under ~/.opencode; review it and rerun the OpenCode install.', + ...(Array.isArray(opencodeMigration.warnings) ? opencodeMigration.warnings : []), + ]; + } + } catch (error) { + opencodeMigrationWarnings = [ + `Legacy OpenCode cleanup did not finish: ${error.message}. Content under ~/.opencode was preserved; rerun the OpenCode install or review it manually.`, + ]; + } + + return { + ...plan, + statePreview: finalState, + plannedOperations: [...plan.operations], + operations: migration.appliedOperations, + skippedOperations: migration.skippedOperations, + warnings: [ + ...(Array.isArray(plan.warnings) ? plan.warnings : []), + ...migration.warnings, + ...antigravityMigrationWarnings, + ...opencodeMigrationWarnings, + ], + applied: true, + }; +} + +module.exports = { + applyInstallPlan, + assertSafeInstallOperation, + previewInstallPlan, +}; diff --git a/github_code/affaan-m__ECC/scripts/lib/install/claude-settings-lock.js b/github_code/affaan-m__ECC/scripts/lib/install/claude-settings-lock.js new file mode 100644 index 0000000000000000000000000000000000000000..ae413fa01b006a38b87c4cea999d2825a05cfc01 --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/install/claude-settings-lock.js @@ -0,0 +1,170 @@ +'use strict'; + +const crypto = require('crypto'); +const fs = require('fs'); +const path = require('path'); + +const INVALID_LOCK_STALE_MS = 5 * 60 * 1000; + +function sameFileIdentity(left, right) { + return left.dev === right.dev && left.ino === right.ino; +} + +function createSettingsLock(lockPath) { + const tempPath = `${lockPath}.create-${process.pid}-${crypto.randomBytes(8).toString('hex')}`; + let descriptor; + let ownedStats; + try { + descriptor = fs.openSync(tempPath, 'wx', 0o600); + fs.writeFileSync(descriptor, `${JSON.stringify({ + pid: process.pid, + startedAt: new Date().toISOString(), + token: crypto.randomBytes(16).toString('hex'), + })}\n`); + fs.fsyncSync(descriptor); + ownedStats = fs.fstatSync(descriptor, { bigint: true }); + fs.closeSync(descriptor); + descriptor = undefined; + fs.linkSync(tempPath, lockPath); + } catch (error) { + if (descriptor !== undefined) fs.closeSync(descriptor); + fs.rmSync(tempPath, { force: true }); + throw error; + } + fs.rmSync(tempPath, { force: true }); + + let released = false; + return () => { + if (released) return; + const quarantinePath = `${lockPath}.release-${process.pid}-${crypto.randomBytes(8).toString('hex')}`; + fs.renameSync(lockPath, quarantinePath); + const quarantinedStats = fs.lstatSync(quarantinePath, { bigint: true }); + if (!sameFileIdentity(quarantinedStats, ownedStats)) { + if (!fs.existsSync(lockPath)) fs.renameSync(quarantinePath, lockPath); + throw new Error(`Refusing to release a changed Claude settings lock: ${lockPath}`); + } + released = true; + fs.rmSync(quarantinePath, { force: true }); + }; +} + +function inspectSettingsLock(lockPath) { + const descriptor = fs.openSync(lockPath, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW || 0)); + try { + const stats = fs.fstatSync(descriptor, { bigint: true }); + const pathStats = fs.lstatSync(lockPath, { bigint: true }); + if ( + !stats.isFile() + || pathStats.isSymbolicLink() + || !pathStats.isFile() + || !sameFileIdentity(stats, pathStats) + ) { + return { metadata: null, stats }; + } + let metadata = null; + try { + metadata = JSON.parse(fs.readFileSync(descriptor, 'utf8')); + } catch (_error) { + // Invalid locks may be recovered only after the bounded lease below. + } + return { metadata, stats }; + } finally { + fs.closeSync(descriptor); + } +} + +function processIsAlive(pid) { + try { + process.kill(pid, 0); + return true; + } catch (error) { + return error.code !== 'ESRCH'; + } +} + +function recoverSettingsLock(lockPath) { + const recoveryPath = `${lockPath}.recover`; + try { + fs.mkdirSync(recoveryPath, { mode: 0o700 }); + } catch (error) { + if (error && error.code === 'EEXIST') return null; + throw error; + } + + const quarantinePath = `${lockPath}.stale-${process.pid}-${crypto.randomBytes(8).toString('hex')}`; + try { + let inspected; + try { + inspected = inspectSettingsLock(lockPath); + } catch (error) { + if (error && error.code === 'ENOENT') return createSettingsLock(lockPath); + throw error; + } + const validOwner = Number.isSafeInteger(inspected.metadata && inspected.metadata.pid) + && inspected.metadata.pid > 0; + const stale = validOwner + ? !processIsAlive(inspected.metadata.pid) + : Date.now() - Number(inspected.stats.mtimeMs) >= INVALID_LOCK_STALE_MS; + if (!stale) return null; + + fs.renameSync(lockPath, quarantinePath); + const quarantinedStats = fs.lstatSync(quarantinePath, { bigint: true }); + if (!sameFileIdentity(quarantinedStats, inspected.stats)) { + if (!fs.existsSync(lockPath)) fs.renameSync(quarantinePath, lockPath); + return null; + } + fs.rmSync(quarantinePath, { force: true }); + return createSettingsLock(lockPath); + } finally { + fs.rmSync(recoveryPath, { recursive: true, force: true }); + fs.rmSync(quarantinePath, { force: true }); + } +} + +function acquireSettingsLock(settingsPath) { + const lockPath = `${settingsPath}.ecc.lock`; + fs.mkdirSync(path.dirname(settingsPath), { recursive: true }); + try { + return createSettingsLock(lockPath); + } catch (error) { + if (!error || error.code !== 'EEXIST') { + throw error; + } + } + const recovered = recoverSettingsLock(lockPath); + if (recovered) return recovered; + throw new Error( + `Another ECC process is updating Claude settings: ${settingsPath}. ` + + `If no ECC process is active, inspect and remove ${lockPath}.` + ); +} + +function runWithSettingsLock(settingsPath, callback) { + const releaseLock = acquireSettingsLock(settingsPath); + let primaryError = null; + let result; + try { + result = callback(); + } catch (error) { + primaryError = error; + } + + let releaseError = null; + try { + releaseLock(); + } catch (error) { + releaseError = error; + } + + if (primaryError) { + if (releaseError) primaryError.releaseError = releaseError; + throw primaryError; + } + if (releaseError) throw releaseError; + return result; +} + +module.exports = { + acquireSettingsLock, + runWithSettingsLock, +}; diff --git a/github_code/affaan-m__ECC/scripts/lib/install/claude-settings.js b/github_code/affaan-m__ECC/scripts/lib/install/claude-settings.js new file mode 100644 index 0000000000000000000000000000000000000000..7075c5bd95fa31a0b9686da692bab6e64c80ba3c --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/install/claude-settings.js @@ -0,0 +1,699 @@ +'use strict'; + +const fs = require('fs'); +const path = require('path'); +const { isDeepStrictEqual } = require('util'); +const { writeFileAtomic } = require('../atomic-write'); +const { acquireSettingsLock, runWithSettingsLock } = require('./claude-settings-lock'); + +const CLAUDE_SETTINGS_FILENAME = 'settings.json'; +const CLAUDE_HOOKS_CONFIG_PATH = 'hooks/hooks.json'; +const PLUGIN_ROOT_PLACEHOLDER = '${CLAUDE_PLUGIN_ROOT}'; +const PLUGIN_ROOT_ENV_PROLOGUE = 'var e=process.env.CLAUDE_PLUGIN_ROOT;'; +const PLUGIN_ROOT_ENV_READ = /\bprocess\.env\.CLAUDE_PLUGIN_ROOT\b(?!\s*=)/; +const VALID_EVENTS = new Set([ + 'SessionStart', 'UserPromptSubmit', 'PreToolUse', 'PermissionRequest', + 'PostToolUse', 'PostToolUseFailure', 'Notification', 'SubagentStart', + 'Stop', 'SubagentStop', 'PreCompact', 'InstructionsLoaded', + 'TeammateIdle', 'TaskCompleted', 'ConfigChange', 'WorktreeCreate', + 'WorktreeRemove', 'SessionEnd', +]); +const EVENTS_WITHOUT_MATCHER = new Set([ + 'UserPromptSubmit', 'Notification', 'Stop', 'SubagentStop', +]); +const VALID_HOOK_TYPES = new Set(['command', 'http', 'prompt', 'agent']); + +function isJsonObject(value) { + if (!value || typeof value !== 'object' || Array.isArray(value)) { + return false; + } + const prototype = Object.getPrototypeOf(value); + return prototype === Object.prototype || prototype === null; +} + +function cloneValue(value) { + if (Array.isArray(value)) { + return value.map(cloneValue); + } + if (isJsonObject(value)) { + return Object.fromEntries( + Object.entries(value).map(([key, nestedValue]) => [key, cloneValue(nestedValue)]) + ); + } + return value; +} + +function isNonEmptyString(value) { + return typeof value === 'string' && value.trim() !== ''; +} + +function getClaudeSettingsPath(targetRoot) { + return path.join(targetRoot, CLAUDE_SETTINGS_FILENAME); +} + +function assertClaudeSettingsPath(destinationPath, trustedRoot) { + const resolvedDestination = path.resolve(destinationPath); + const resolvedExpected = path.resolve(getClaudeSettingsPath(trustedRoot)); + const pathsMatch = process.platform === 'win32' + ? resolvedDestination.toLowerCase() === resolvedExpected.toLowerCase() + : resolvedDestination === resolvedExpected; + if (!pathsMatch) { + throw new Error( + `Refusing to manage Claude hooks outside the canonical settings file: ${destinationPath}` + ); + } +} + +function validateHookHandler(hook, label) { + if (!isJsonObject(hook)) { + throw new Error(`Invalid managed hook handler at ${label}: expected a JSON object`); + } + if (!VALID_HOOK_TYPES.has(hook.type)) { + throw new Error(`Invalid managed hook handler at ${label}: unsupported type`); + } + if (hook.timeout !== undefined && (typeof hook.timeout !== 'number' || hook.timeout < 0)) { + throw new Error(`Invalid managed hook handler at ${label}: invalid timeout`); + } + + if (hook.type === 'command') { + const validCommand = isNonEmptyString(hook.command) + || (Array.isArray(hook.command) + && hook.command.length > 0 + && hook.command.every(isNonEmptyString)); + if (!validCommand) { + throw new Error(`Invalid managed hook handler at ${label}: invalid command`); + } + if (hook.async !== undefined && typeof hook.async !== 'boolean') { + throw new Error(`Invalid managed hook handler at ${label}: invalid async flag`); + } + return; + } + + if (hook.async !== undefined) { + throw new Error(`Invalid managed hook handler at ${label}: async requires command type`); + } + if (hook.type === 'http') { + if (!isNonEmptyString(hook.url)) { + throw new Error(`Invalid managed hook handler at ${label}: invalid url`); + } + if ( + hook.headers !== undefined + && (!isJsonObject(hook.headers) + || !Object.values(hook.headers).every(value => typeof value === 'string')) + ) { + throw new Error(`Invalid managed hook handler at ${label}: invalid headers`); + } + if ( + hook.allowedEnvVars !== undefined + && (!Array.isArray(hook.allowedEnvVars) + || !hook.allowedEnvVars.every(isNonEmptyString)) + ) { + throw new Error(`Invalid managed hook handler at ${label}: invalid allowedEnvVars`); + } + return; + } + if (!isNonEmptyString(hook.prompt)) { + throw new Error(`Invalid managed hook handler at ${label}: invalid prompt`); + } + if (hook.model !== undefined && !isNonEmptyString(hook.model)) { + throw new Error(`Invalid managed hook handler at ${label}: invalid model`); + } +} + +function validateManagedHooks(managedHooks, label = 'managed hooks') { + if (!isJsonObject(managedHooks)) { + throw new Error(`Invalid ${label}: expected a JSON object`); + } + if (Object.keys(managedHooks).length === 0) { + throw new Error(`Invalid ${label}: expected at least one hook event`); + } + + const seenIds = new Set(); + for (const [event, entries] of Object.entries(managedHooks)) { + if (!VALID_EVENTS.has(event)) { + throw new Error(`Invalid ${label}: unsupported hook event "${event}"`); + } + if (!Array.isArray(entries)) { + throw new Error(`Invalid ${label}.${event}: expected an array`); + } + if (entries.length === 0) { + throw new Error(`Invalid ${label}.${event}: expected at least one hook entry`); + } + + entries.forEach((entry, index) => { + if (!isJsonObject(entry)) { + throw new Error( + `Invalid managed hook entry at ${label}.${event}[${index}]: expected a JSON object` + ); + } + if (typeof entry.id !== 'string' || entry.id.trim() === '') { + throw new Error( + `Invalid managed hook entry at ${label}.${event}[${index}]: ` + + 'expected a non-empty unique id' + ); + } + if (seenIds.has(entry.id)) { + throw new Error(`Invalid ${label}: expected globally unique id "${entry.id}"`); + } + seenIds.add(entry.id); + if ( + !Object.prototype.hasOwnProperty.call(entry, 'matcher') + && !EVENTS_WITHOUT_MATCHER.has(event) + ) { + throw new Error( + `Invalid managed hook entry at ${label}.${event}[${index}]: missing matcher` + ); + } + if ( + Object.prototype.hasOwnProperty.call(entry, 'matcher') + && typeof entry.matcher !== 'string' + && !isJsonObject(entry.matcher) + ) { + throw new Error( + `Invalid managed hook entry at ${label}.${event}[${index}]: invalid matcher` + ); + } + if (!Array.isArray(entry.hooks) || entry.hooks.length === 0) { + throw new Error( + `Invalid managed hook entry at ${label}.${event}[${index}]: expected hooks` + ); + } + entry.hooks.forEach((hook, hookIndex) => { + validateHookHandler(hook, `${label}.${event}[${index}].hooks[${hookIndex}]`); + }); + }); + } + + return cloneValue(managedHooks); +} + +function validateRecordedManagedHooks(managedHooks, label = 'recorded managed hooks') { + if (!isJsonObject(managedHooks) || Object.keys(managedHooks).length === 0) { + throw new Error(`Invalid ${label}: expected a non-empty JSON object`); + } + for (const [event, entries] of Object.entries(managedHooks)) { + if (!isNonEmptyString(event) || !Array.isArray(entries) || entries.length === 0) { + throw new Error(`Invalid ${label}.${event}: expected a non-empty hook array`); + } + const seenIds = new Set(); + entries.forEach((entry, index) => { + if (!isJsonObject(entry) || !isNonEmptyString(entry.id) || !Array.isArray(entry.hooks)) { + throw new Error(`Invalid hook entry at ${label}.${event}[${index}]`); + } + if (seenIds.has(entry.id)) { + throw new Error( + `Invalid ${label}: expected unique id "${entry.id}" within event "${event}"` + ); + } + seenIds.add(entry.id); + }); + } + return cloneValue(managedHooks); +} + +function validateSettings(settings, label = 'Claude settings') { + if (!isJsonObject(settings)) { + throw new Error(`Invalid ${label}: expected a JSON object`); + } + + if (Object.prototype.hasOwnProperty.call(settings, 'hooks')) { + if (!isJsonObject(settings.hooks)) { + throw new Error(`Invalid ${label}: expected "hooks" to be a JSON object`); + } + for (const [event, entries] of Object.entries(settings.hooks)) { + if (!Array.isArray(entries)) { + throw new Error(`Invalid ${label}: expected hooks.${event} to be an array`); + } + } + } + + return cloneValue(settings); +} + +function replacePluginRootPlaceholders(value, pluginRoot) { + if (typeof pluginRoot !== 'string') { + throw new Error('Invalid Claude plugin root: expected a string'); + } + if (typeof value === 'string') { + return value.split(PLUGIN_ROOT_PLACEHOLDER).join(pluginRoot); + } + if (Array.isArray(value)) { + return value.map(item => replacePluginRootPlaceholders(item, pluginRoot)); + } + if (isJsonObject(value)) { + return Object.fromEntries( + Object.entries(value).map(([key, nestedValue]) => [ + key, + replacePluginRootPlaceholders(nestedValue, pluginRoot), + ]) + ); + } + return value; +} + +function resolveManagedHookCommands(managedHooks, targetRoot) { + const encodedRoot = Buffer.from(targetRoot, 'utf8').toString('base64'); + const rootExpression = `Buffer.from('${encodedRoot}','base64').toString('utf8')`; + const resolveCommand = command => { + // Leave invalid entries intact so managed-hook validation reports them. + if (typeof command !== 'string') { + return command; + } + const resolved = command + .split(PLUGIN_ROOT_ENV_PROLOGUE) + .join(`var e=${rootExpression};`); + if (PLUGIN_ROOT_ENV_READ.test(resolved)) { + throw new Error( + 'Unable to resolve CLAUDE_PLUGIN_ROOT in a managed hook command; ' + + 'the hooks.json command prologue no longer matches the expected form' + ); + } + return resolved; + }; + return Object.fromEntries( + Object.entries(managedHooks).map(([event, entries]) => [ + event, + entries.map(entry => ({ + ...entry, + hooks: entry.hooks.map(hook => ({ + ...hook, + ...(typeof hook.command === 'string' || Array.isArray(hook.command) + ? { + command: Array.isArray(hook.command) + ? hook.command.map(resolveCommand) + : resolveCommand(hook.command), + } + : {}), + })), + })), + ]) + ); +} + +function materializeManagedHooks(hooksConfig, targetRoot) { + if (!isJsonObject(hooksConfig) || !isJsonObject(hooksConfig.hooks)) { + throw new Error('Invalid hooks config: expected a JSON object with a hooks object'); + } + if (!isNonEmptyString(targetRoot)) { + throw new Error('Invalid Claude target root: expected a non-empty string'); + } + return validateManagedHooks(resolveManagedHookCommands( + replacePluginRootPlaceholders(hooksConfig.hooks, targetRoot), + targetRoot + )); +} + +function parseSettings(rawSettings, label = 'Claude settings') { + let settings; + try { + settings = JSON.parse(rawSettings); + } catch (error) { + throw new Error(`Failed to parse ${label}: ${error.message}`, { cause: error }); + } + return validateSettings(settings, label); +} + +function readSettings(settingsPath, fileSystem = fs) { + const reader = fileSystem && fileSystem.fs ? fileSystem.fs : fileSystem; + let rawSettings; + try { + rawSettings = reader.readFileSync(settingsPath, 'utf8'); + } catch (error) { + if (error && error.code === 'ENOENT') { + return {}; + } + throw error; + } + return parseSettings(rawSettings, `Claude settings at ${settingsPath}`); +} + +function readSettingsSnapshot(settingsPath) { + const flags = fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW || 0); + let descriptor; + try { + descriptor = fs.openSync(settingsPath, flags); + } catch (error) { + if (error && error.code === 'ENOENT') { + return { exists: false, raw: null, settings: {}, mode: 0o600 }; + } + throw error; + } + + try { + const descriptorStat = fs.fstatSync(descriptor); + let pathStat; + try { + pathStat = fs.lstatSync(settingsPath); + } catch (error) { + if (error && error.code === 'ENOENT') { + error.code = 'ECC_SETTINGS_CHANGED'; + } + throw error; + } + if ( + !descriptorStat.isFile() + || !pathStat.isFile() + || pathStat.isSymbolicLink() + || descriptorStat.dev !== pathStat.dev + || descriptorStat.ino !== pathStat.ino + ) { + const error = new Error(`Refusing to read changed Claude settings at ${settingsPath}`); + error.code = 'ECC_SETTINGS_CHANGED'; + throw error; + } + const raw = fs.readFileSync(descriptor, 'utf8'); + return { + exists: true, + raw, + settings: parseSettings(raw, `Claude settings at ${settingsPath}`), + mode: descriptorStat.mode & 0o777, + dev: descriptorStat.dev, + ino: descriptorStat.ino, + }; + } finally { + fs.closeSync(descriptor); + } +} + +function assertSettingsSnapshotUnchanged(settingsPath, snapshot) { + let current; + try { + current = readSettingsSnapshot(settingsPath); + } catch (error) { + error.code = error.code || 'ECC_SETTINGS_CHANGED'; + throw error; + } + const unchanged = current.exists === snapshot.exists + && current.raw === snapshot.raw + && (!current.exists || (current.dev === snapshot.dev && current.ino === snapshot.ino)); + if (!unchanged) { + const error = new Error(`Claude settings changed during update: ${settingsPath}`); + error.code = 'ECC_SETTINGS_CHANGED'; + throw error; + } +} + +function updateSettingsAtomic(settingsPath, transform, options = {}) { + const update = () => { + const parentPath = path.dirname(path.resolve(settingsPath)); + const parentStats = fs.lstatSync(parentPath, { bigint: true }); + const validateParent = () => { + const current = fs.lstatSync(parentPath, { bigint: true }); + if ( + !current.isDirectory() || current.isSymbolicLink() + || current.dev !== parentStats.dev || current.ino !== parentStats.ino + ) { + const error = new Error(`Claude settings parent directory changed: ${parentPath}`); + error.code = 'ECC_SETTINGS_PARENT_CHANGED'; + throw error; + } + }; + const maxAttempts = options.maxAttempts || 3; + for (let attempt = 1; attempt <= maxAttempts; attempt += 1) { + try { + validateParent(); + const snapshot = readSettingsSnapshot(settingsPath); + const result = transform(snapshot.settings); + if (typeof options.beforeCommit === 'function') options.beforeCommit(); + assertSettingsSnapshotUnchanged(settingsPath, snapshot); + writeFileAtomic( + settingsPath, + `${JSON.stringify(result.settings, null, 2)}\n`, + { + encoding: 'utf8', + mode: snapshot.mode, + validateParent, + beforeRename() { + assertSettingsSnapshotUnchanged(settingsPath, snapshot); + }, + } + ); + return result; + } catch (error) { + if (error.code !== 'ECC_SETTINGS_CHANGED' || attempt === maxAttempts) { + throw error; + } + } + } + throw new Error(`Unable to update Claude settings at ${settingsPath}`); + }; + if (options.lockHeld) { + return update(); + } + return runWithSettingsLock(settingsPath, update); +} + +function reference(event, id) { + return { event, id }; +} + +function entriesMatchingId(entries, id) { + return entries + .map((entry, index) => ({ entry, index })) + .filter(candidate => isJsonObject(candidate.entry) && candidate.entry.id === id); +} + +function assertUnambiguousMatch(entries, event, id) { + const matches = entriesMatchingId(entries, id); + if (matches.length > 1) { + throw new Error( + `Claude settings contains multiple hooks for event "${event}" and id "${id}"` + ); + } + return matches[0] || null; +} + +function managedEntryFor(managedHooks, event, id) { + const entries = managedHooks && managedHooks[event]; + if (!Array.isArray(entries)) { + return null; + } + return entries.find(entry => entry.id === id) || null; +} + +function mergeManagedHooks(settings, managedHooks, options = {}) { + const validatedSettings = validateSettings(settings); + const desiredHooks = validateManagedHooks(managedHooks); + const previousHooks = options.previousManagedHooks === undefined + || options.previousManagedHooks === null + ? null + : validateRecordedManagedHooks(options.previousManagedHooks, 'previous managed hooks'); + const repair = options.mode === 'repair' || options.repair === true; + if (options.mode !== undefined && options.mode !== 'merge' && options.mode !== 'repair') { + throw new Error(`Unknown Claude settings merge mode: ${options.mode}`); + } + + let nextHooks = validatedSettings.hooks + ? cloneValue(validatedSettings.hooks) + : {}; + const added = []; + const updated = []; + const unchanged = []; + const removed = []; + + if (previousHooks) { + for (const [event, previousEntries] of Object.entries(previousHooks)) { + let eventEntries = nextHooks[event] ? cloneValue(nextHooks[event]) : []; + for (const previousEntry of previousEntries) { + if (managedEntryFor(desiredHooks, event, previousEntry.id)) continue; + const match = assertUnambiguousMatch(eventEntries, event, previousEntry.id); + if (!match) continue; + if (!isDeepStrictEqual(match.entry, previousEntry)) { + throw new Error( + `Refusing to remove Claude hook for event "${event}" and id ` + + `"${previousEntry.id}" because the previous managed entry has drifted` + ); + } + eventEntries = eventEntries.filter((_entry, index) => index !== match.index); + removed.push(reference(event, previousEntry.id)); + } + nextHooks = eventEntries.length > 0 + ? { ...nextHooks, [event]: eventEntries } + : withoutProperty(nextHooks, event); + } + } + + for (const [event, desiredEntries] of Object.entries(desiredHooks)) { + let eventEntries = nextHooks[event] ? cloneValue(nextHooks[event]) : []; + for (const desiredEntry of desiredEntries) { + const match = assertUnambiguousMatch(eventEntries, event, desiredEntry.id); + if (!match) { + eventEntries = [...eventEntries, cloneValue(desiredEntry)]; + added.push(reference(event, desiredEntry.id)); + continue; + } + if (isDeepStrictEqual(match.entry, desiredEntry)) { + unchanged.push(reference(event, desiredEntry.id)); + continue; + } + + const previousEntry = managedEntryFor(previousHooks, event, desiredEntry.id); + if (!repair && (!previousEntry || !isDeepStrictEqual(match.entry, previousEntry))) { + const driftReason = previousEntry ? ' because the previous managed entry has drifted' : ''; + throw new Error( + `Refusing to overwrite Claude hook for event "${event}" and id ` + + `"${desiredEntry.id}"${driftReason}` + ); + } + + eventEntries = eventEntries.map((entry, index) => ( + index === match.index ? cloneValue(desiredEntry) : entry + )); + updated.push(reference(event, desiredEntry.id)); + } + if (desiredEntries.length > 0) { + nextHooks = { ...nextHooks, [event]: eventEntries }; + } + } + + const nextSettings = Object.keys(nextHooks).length > 0 + ? { ...validatedSettings, hooks: nextHooks } + : validatedSettings; + return { + settings: nextSettings, + managedHooks: cloneValue(desiredHooks), + added, + updated, + unchanged, + removed, + }; +} + +function repairManagedHooks(settings, managedHooks, options = {}) { + return mergeManagedHooks(settings, managedHooks, { + ...options, + mode: 'repair', + }); +} + +function inspectManagedHooks(settings, managedHooks) { + const validatedSettings = validateSettings(settings); + const expectedHooks = validateManagedHooks(managedHooks); + const settingsHooks = validatedSettings.hooks || {}; + const managedSubset = {}; + const matched = []; + const missing = []; + const drifted = []; + + for (const [event, expectedEntries] of Object.entries(expectedHooks)) { + const actualEntries = settingsHooks[event] || []; + const foundEntries = []; + for (const expectedEntry of expectedEntries) { + const match = assertUnambiguousMatch(actualEntries, event, expectedEntry.id); + if (!match) { + missing.push(reference(event, expectedEntry.id)); + continue; + } + + foundEntries.push(cloneValue(match.entry)); + if (isDeepStrictEqual(match.entry, expectedEntry)) { + matched.push(reference(event, expectedEntry.id)); + } else { + drifted.push({ + ...reference(event, expectedEntry.id), + expected: cloneValue(expectedEntry), + actual: cloneValue(match.entry), + }); + } + } + if (foundEntries.length > 0) { + managedSubset[event] = foundEntries; + } + } + + const ok = missing.length === 0 && drifted.length === 0; + return { + status: ok ? 'ok' : (missing.length > 0 ? 'missing' : 'drifted'), + ok, + managedHooks: managedSubset, + matched, + missing, + drifted, + }; +} + +function withoutProperty(object, omittedKey) { + return Object.fromEntries( + Object.entries(object).filter(([key]) => key !== omittedKey) + ); +} + +function uninstallManagedHooks(settings, recordedManagedHooks) { + const validatedSettings = validateSettings(settings); + const recordedHooks = validateRecordedManagedHooks(recordedManagedHooks); + const currentHooks = validatedSettings.hooks || {}; + + for (const [event, recordedEntries] of Object.entries(recordedHooks)) { + const eventEntries = currentHooks[event] || []; + for (const recordedEntry of recordedEntries) { + assertUnambiguousMatch(eventEntries, event, recordedEntry.id); + } + } + + const removed = []; + const retained = []; + const missing = []; + let nextHooks = cloneValue(currentHooks); + + for (const [event, recordedEntries] of Object.entries(recordedHooks)) { + let eventEntries = nextHooks[event] || []; + for (const recordedEntry of recordedEntries) { + const match = assertUnambiguousMatch(eventEntries, event, recordedEntry.id); + if (!match) { + missing.push(reference(event, recordedEntry.id)); + continue; + } + if (!isDeepStrictEqual(match.entry, recordedEntry)) { + retained.push({ + ...reference(event, recordedEntry.id), + expected: cloneValue(recordedEntry), + actual: cloneValue(match.entry), + reason: 'modified', + }); + continue; + } + + eventEntries = eventEntries.filter((_entry, index) => index !== match.index); + removed.push(reference(event, recordedEntry.id)); + } + nextHooks = eventEntries.length > 0 + ? { ...nextHooks, [event]: eventEntries } + : withoutProperty(nextHooks, event); + } + + nextHooks = Object.fromEntries( + Object.entries(nextHooks).filter(([, entries]) => entries.length > 0) + ); + const settingsWithoutHooks = withoutProperty(validatedSettings, 'hooks'); + const nextSettings = Object.keys(nextHooks).length > 0 + ? { ...settingsWithoutHooks, hooks: nextHooks } + : settingsWithoutHooks; + + return { + settings: nextSettings, + removed, + retained, + missing, + }; +} + +module.exports = { + CLAUDE_HOOKS_CONFIG_PATH, + CLAUDE_SETTINGS_FILENAME, + acquireSettingsLock, + assertClaudeSettingsPath, + getClaudeSettingsPath, + inspectManagedHooks, + materializeManagedHooks, + mergeManagedHooks, + parseSettings, + readSettings, + repairManagedHooks, + replacePluginRootPlaceholders, + runWithSettingsLock, + updateSettingsAtomic, + uninstallManagedHooks, + validateManagedHooks, + validateRecordedManagedHooks, + validateSettings, +}; diff --git a/github_code/affaan-m__ECC/scripts/lib/install/claude-skill-migration.js b/github_code/affaan-m__ECC/scripts/lib/install/claude-skill-migration.js new file mode 100644 index 0000000000000000000000000000000000000000..adc9170b3032ab6115b1e1531ef2c6684b1c7a4f --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/install/claude-skill-migration.js @@ -0,0 +1,417 @@ +'use strict'; + +const fs = require('fs'); +const path = require('path'); + +const { readInstallState } = require('../install-state'); +const { assertWithinTrustedRoot } = require('../path-safety'); + +const CLAUDE_TARGETS = new Set(['claude', 'claude-project']); + +function pathExists(filePath) { + try { + fs.lstatSync(filePath); + return true; + } catch (error) { + if (error && error.code === 'ENOENT') { + return false; + } + throw error; + } +} + +function normalizeSourceRelativePath(sourceRelativePath) { + const slashNormalized = String(sourceRelativePath || '').replace(/\\/g, '/'); + const normalized = path.posix.normalize(slashNormalized).replace(/^\.\//, ''); + if ( + !normalized + || normalized === '.' + || normalized === '..' + || normalized.startsWith('../') + || path.posix.isAbsolute(normalized) + ) { + return null; + } + return normalized; +} + +function comparablePath(filePath) { + const resolvedPath = path.resolve(filePath); + return process.platform === 'win32' ? resolvedPath.toLowerCase() : resolvedPath; +} + +function samePath(leftPath, rightPath) { + return comparablePath(leftPath) === comparablePath(rightPath); +} + +function assertSafeSkillPath(targetPath, targetRoot, action) { + const resolvedRoot = path.resolve(targetRoot); + const resolvedTarget = path.resolve(targetPath); + const relativePath = path.relative(resolvedRoot, resolvedTarget); + if ( + relativePath === '' + || relativePath.startsWith('..') + || path.isAbsolute(relativePath) + ) { + throw new Error( + `Refusing to ${action} outside the install root: '${targetPath}' is not within '${targetRoot}'.` + ); + } + + let currentPath = resolvedRoot; + for (const segment of relativePath.split(path.sep)) { + currentPath = path.join(currentPath, segment); + let stats; + try { + stats = fs.lstatSync(currentPath); + } catch (error) { + if (error && error.code === 'ENOENT') { + break; + } + throw error; + } + if (stats.isSymbolicLink()) { + throw new Error( + `Refusing to ${action} through symlinked Claude skill path: '${currentPath}'.` + ); + } + } + + if (pathExists(targetRoot)) { + assertWithinTrustedRoot(targetPath, targetRoot, action); + } +} + +function describeClaudeSkillOperation(targetRoot, operation) { + if (!operation || operation.kind !== 'copy-file') { + return null; + } + + const sourceRelativePath = normalizeSourceRelativePath(operation.sourceRelativePath); + if (!sourceRelativePath) { + return null; + } + + const sourceParts = sourceRelativePath.split('/'); + if (sourceParts[0] !== 'skills' || sourceParts.length < 3 || !sourceParts[1]) { + return null; + } + + const skillName = sourceParts[1]; + const relativeParts = sourceParts.slice(2); + const flatSkillRoot = path.join(targetRoot, 'skills', skillName); + const legacySkillRoot = path.join(targetRoot, 'skills', 'ecc', skillName); + + return { + sourceKey: sourceRelativePath, + skillName, + flatSkillRoot, + flatDestinationPath: path.join(flatSkillRoot, ...relativeParts), + legacySkillRoot, + legacyDestinationPath: path.join(legacySkillRoot, ...relativeParts), + }; +} + +function assertSafeClaudeSkillOperation(plan, operation) { + const target = plan && plan.adapter && plan.adapter.target; + if (!CLAUDE_TARGETS.has(target)) { + return; + } + const descriptor = describeClaudeSkillOperation(plan.targetRoot, operation); + if (!descriptor || !samePath(operation.destinationPath, descriptor.flatDestinationPath)) { + return; + } + assertSafeSkillPath( + operation.destinationPath, + plan.targetRoot, + 'install Claude skill' + ); +} + +function isManagedOperation(operation) { + return operation && operation.ownership === 'managed'; +} + +function uniqueOperations(operations) { + const byDestination = new Map(); + for (const operation of operations) { + // A target path has one current owner. Later operations come from the + // newest plan and replace stale metadata for the same destination. + byDestination.set(comparablePath(operation.destinationPath), operation); + } + return [...byDestination.values()]; +} + +function buildState(statePreview, operations) { + return { + ...statePreview, + operations: uniqueOperations(operations).map(operation => ({ ...operation })), + }; +} + +function groupCurrentSkillOperations(plan) { + const groups = new Map(); + for (const operation of plan.operations) { + const descriptor = describeClaudeSkillOperation(plan.targetRoot, operation); + if (!descriptor || !samePath(operation.destinationPath, descriptor.flatDestinationPath)) { + continue; + } + + assertSafeSkillPath( + operation.destinationPath, + plan.targetRoot, + 'install Claude skill' + ); + + const current = groups.get(descriptor.flatSkillRoot) || []; + current.push({ operation, descriptor }); + groups.set(descriptor.flatSkillRoot, current); + } + return groups; +} + +function classifyPreviousOperations(plan, previousState) { + const flatByDestination = new Map(); + const legacyBySource = new Map(); + const legacyBySkillRoot = new Map(); + + for (const operation of (previousState && previousState.operations) || []) { + if (!isManagedOperation(operation)) { + continue; + } + const descriptor = describeClaudeSkillOperation(plan.targetRoot, operation); + if (!descriptor) { + continue; + } + + if (samePath(operation.destinationPath, descriptor.flatDestinationPath)) { + assertSafeSkillPath( + operation.destinationPath, + plan.targetRoot, + 'inspect managed Claude skill' + ); + flatByDestination.set(comparablePath(operation.destinationPath), operation); + continue; + } + + if (!samePath(operation.destinationPath, descriptor.legacyDestinationPath)) { + continue; + } + + assertSafeSkillPath( + operation.destinationPath, + plan.targetRoot, + 'migrate managed Claude skill' + ); + legacyBySource.set(descriptor.sourceKey, operation); + const current = legacyBySkillRoot.get(descriptor.legacySkillRoot) || []; + current.push({ operation, descriptor }); + legacyBySkillRoot.set(descriptor.legacySkillRoot, current); + } + + return { + flatByDestination, + legacyBySource, + legacyBySkillRoot, + }; +} + +function createConflictWarning(skillName, flatSkillRoot, retainsLegacy) { + const legacySuffix = retainsLegacy + ? ' The existing ECC-managed nested copy was retained and remains tracked for uninstall.' + : ''; + return `Skipped Claude skill '${skillName}' at ${flatSkillRoot}: the flat skill directory is user-owned because it is not recorded in ECC install-state.${legacySuffix}`; +} + +function createFileConflictWarning(destinationPath, retainsLegacy) { + const legacySuffix = retainsLegacy + ? ' The matching ECC-managed nested file was retained and remains tracked for uninstall.' + : ''; + return `Skipped user-owned Claude skill file ${destinationPath}: the existing file is not recorded in ECC install-state.${legacySuffix}`; +} + +function createDisabledMigration(plan, previousState) { + const finalState = buildState(plan.statePreview, [ + ...((previousState && previousState.operations) || []), + ...plan.statePreview.operations, + ]); + return { + enabled: false, + appliedOperations: [...plan.operations], + skippedOperations: [], + warnings: [], + bridgeState: finalState, + finalState, + legacyOperationsToRemove: [], + requiresBridgeState: plan.operations.length > 0, + }; +} + +function collectRetainedLegacyOperations(currentGroups, previous) { + const currentSourceKeys = new Set( + [...currentGroups.values()] + .flat() + .map(({ descriptor }) => descriptor.sourceKey) + ); + return ( + [...previous.legacyBySource.entries()] + .filter(([sourceKey]) => !currentSourceKeys.has(sourceKey)) + .map(([_sourceKey, operation]) => operation) + ); +} + +function classifySkillGroup(flatSkillRoot, entries, previous) { + const hasManagedFlatFile = entries.some(({ operation }) => ( + previous.flatByDestination.has(comparablePath(operation.destinationPath)) + )); + const legacyEntries = previous.legacyBySkillRoot.get( + entries[0].descriptor.legacySkillRoot + ) || []; + + if (pathExists(flatSkillRoot) && !hasManagedFlatFile) { + return { + skippedOperations: entries.map(({ operation }) => operation), + warnings: [createConflictWarning( + entries[0].descriptor.skillName, + flatSkillRoot, + legacyEntries.length > 0 + )], + retainedLegacyOperations: legacyEntries.map(({ operation }) => operation), + }; + } + + const conflicts = entries.filter(({ operation }) => ( + pathExists(operation.destinationPath) + && !previous.flatByDestination.has(comparablePath(operation.destinationPath)) + )); + return { + skippedOperations: conflicts.map(({ operation }) => operation), + warnings: conflicts.map(({ operation, descriptor }) => createFileConflictWarning( + operation.destinationPath, + previous.legacyBySource.has(descriptor.sourceKey) + )), + retainedLegacyOperations: conflicts + .map(({ descriptor }) => previous.legacyBySource.get(descriptor.sourceKey)) + .filter(Boolean), + }; +} + +function classifySkillConflicts(currentGroups, previous) { + const groupClassifications = [...currentGroups.entries()] + .map(([flatSkillRoot, entries]) => classifySkillGroup( + flatSkillRoot, + entries, + previous + )); + const skippedOperations = groupClassifications + .flatMap(classification => classification.skippedOperations); + return { + skippedOperations, + skippedDestinations: new Set( + skippedOperations.map(operation => comparablePath(operation.destinationPath)) + ), + warnings: groupClassifications.flatMap(classification => classification.warnings), + retainedLegacyOperations: new Set([ + ...collectRetainedLegacyOperations(currentGroups, previous), + ...groupClassifications.flatMap( + classification => classification.retainedLegacyOperations + ), + ]), + }; +} + +function buildMigrationStates(plan, previousState, previous, classification) { + const { skippedDestinations, retainedLegacyOperations } = classification; + const appliedOperations = plan.operations.filter(operation => ( + !skippedDestinations.has(comparablePath(operation.destinationPath)) + )); + const legacyOperations = [...previous.legacyBySource.values()]; + const legacyOperationsToRemove = legacyOperations.filter(operation => ( + !retainedLegacyOperations.has(operation) + )); + const removedLegacyDestinations = new Set( + legacyOperationsToRemove.map(operation => comparablePath(operation.destinationPath)) + ); + const finalOperations = [ + ...((previousState && previousState.operations) || []).filter(operation => ( + !removedLegacyDestinations.has(comparablePath(operation.destinationPath)) + )), + ...plan.statePreview.operations.filter(operation => ( + !skippedDestinations.has(comparablePath(operation.destinationPath)) + )), + ]; + const bridgeOperations = [ + ...((previousState && previousState.operations) || []), + ...appliedOperations, + ]; + + return { + appliedOperations, + bridgeState: buildState(plan.statePreview, bridgeOperations), + finalState: buildState(plan.statePreview, finalOperations), + legacyOperationsToRemove, + requiresBridgeState: appliedOperations.length > 0, + }; +} + +function prepareClaudeSkillMigration(plan) { + const previousState = pathExists(plan.installStatePath) + ? readInstallState(plan.installStatePath) + : null; + const target = plan && plan.adapter && plan.adapter.target; + if (!CLAUDE_TARGETS.has(target)) { + return createDisabledMigration(plan, previousState); + } + const currentGroups = groupCurrentSkillOperations(plan); + const previous = classifyPreviousOperations(plan, previousState); + const classification = classifySkillConflicts(currentGroups, previous); + const states = buildMigrationStates( + plan, + previousState, + previous, + classification + ); + + return { + enabled: true, + appliedOperations: states.appliedOperations, + skippedOperations: classification.skippedOperations, + warnings: classification.warnings, + bridgeState: states.bridgeState, + finalState: states.finalState, + legacyOperationsToRemove: states.legacyOperationsToRemove, + requiresBridgeState: states.requiresBridgeState, + }; +} + +function cleanupEmptyLegacyParents(filePath, targetRoot) { + const skillsRoot = path.join(targetRoot, 'skills'); + let currentPath = path.dirname(filePath); + + while (!samePath(currentPath, skillsRoot)) { + assertSafeSkillPath(currentPath, targetRoot, 'clean Claude skill migration'); + if (!pathExists(currentPath) || fs.readdirSync(currentPath).length > 0) { + return; + } + fs.rmdirSync(currentPath); + currentPath = path.dirname(currentPath); + } +} + +function removeLegacyClaudeSkillFiles(migration, targetRoot) { + for (const operation of migration.legacyOperationsToRemove) { + assertSafeSkillPath( + operation.destinationPath, + targetRoot, + 'migrate managed Claude skill' + ); + fs.rmSync(operation.destinationPath, { force: true }); + cleanupEmptyLegacyParents(operation.destinationPath, targetRoot); + } +} + +module.exports = { + assertSafeClaudeSkillOperation, + prepareClaudeSkillMigration, + removeLegacyClaudeSkillFiles, +}; diff --git a/github_code/affaan-m__ECC/scripts/lib/install/config.js b/github_code/affaan-m__ECC/scripts/lib/install/config.js new file mode 100644 index 0000000000000000000000000000000000000000..32c1b47a931023fdb135a74757ee0b265454e883 --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/install/config.js @@ -0,0 +1,91 @@ +'use strict'; + +const fs = require('fs'); +const path = require('path'); + +const DEFAULT_INSTALL_CONFIG = 'ecc-install.json'; +const CONFIG_SCHEMA_PATH = path.join(__dirname, '..', '..', '..', 'schemas', 'ecc-install-config.schema.json'); + +let cachedValidator = null; + +function readJson(filePath, label) { + try { + return JSON.parse(fs.readFileSync(filePath, 'utf8')); + } catch (error) { + throw new Error(`Invalid JSON in ${label}: ${error.message}`); + } +} + +function getValidator() { + if (cachedValidator) { + return cachedValidator; + } + + // ajv is required lazily so scripts that never load an install config (the + // common case, e.g. `--list-profiles`) don't need it on the require path. + const Ajv = require('ajv'); + const schema = readJson(CONFIG_SCHEMA_PATH, 'ecc-install-config.schema.json'); + const ajv = new Ajv({ allErrors: true }); + cachedValidator = ajv.compile(schema); + return cachedValidator; +} + +function dedupeStrings(values) { + return [...new Set((Array.isArray(values) ? values : []).map(value => String(value).trim()).filter(Boolean))]; +} + +function formatValidationErrors(errors = []) { + return errors.map(error => `${error.instancePath || '/'} ${error.message}`).join('; '); +} + +function resolveInstallConfigPath(configPath, options = {}) { + if (!configPath) { + throw new Error('An install config path is required'); + } + + const cwd = options.cwd || process.cwd(); + return path.isAbsolute(configPath) + ? configPath + : path.normalize(path.join(cwd, configPath)); +} + +function findDefaultInstallConfigPath(options = {}) { + const cwd = options.cwd || process.cwd(); + const candidatePath = path.join(cwd, DEFAULT_INSTALL_CONFIG); + return fs.existsSync(candidatePath) ? candidatePath : null; +} + +function loadInstallConfig(configPath, options = {}) { + const resolvedPath = resolveInstallConfigPath(configPath, options); + + if (!fs.existsSync(resolvedPath)) { + throw new Error(`Install config not found: ${resolvedPath}`); + } + + const raw = readJson(resolvedPath, path.basename(resolvedPath)); + const validator = getValidator(); + + if (!validator(raw)) { + throw new Error( + `Invalid install config ${resolvedPath}: ${formatValidationErrors(validator.errors)}` + ); + } + + return { + path: resolvedPath, + version: raw.version, + target: raw.target || null, + profileId: raw.profile || null, + moduleIds: dedupeStrings(raw.modules), + includeComponentIds: dedupeStrings(raw.include), + excludeComponentIds: dedupeStrings(raw.exclude), + options: raw.options && typeof raw.options === 'object' ? { ...raw.options } : {}, + }; +} + +module.exports = { + DEFAULT_INSTALL_CONFIG, + findDefaultInstallConfigPath, + loadInstallConfig, + resolveInstallConfigPath, +}; diff --git a/github_code/affaan-m__ECC/scripts/lib/install/hook-consent.js b/github_code/affaan-m__ECC/scripts/lib/install/hook-consent.js new file mode 100644 index 0000000000000000000000000000000000000000..883c121d70ab6aae6858e45db977f3afd8a518bf --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/install/hook-consent.js @@ -0,0 +1,202 @@ +'use strict'; + +/** + * Explicit consent gate for materializing the automatic hook runtime. + * + * The capability disclosure and held-materialization semantics were + * contributed in PR #2634 by Samarjeet Singh Tomar (@samartomar); this + * module integrates them with the single-decision consent model used by + * the guided installer. + */ + +const HOOK_CAPABILITY_GROUPS = Object.freeze([ + Object.freeze({ + id: 'automatic-source-writes', + description: 'Automatically format or otherwise modify project source files.', + }), + Object.freeze({ + id: 'command-rewrite-and-process-control', + description: 'Rewrite requested commands and start, replace, or terminate processes.', + }), + Object.freeze({ + id: 'transcript-derived-llm-egress', + description: 'Send transcript-derived conversation text to an external LLM.', + }), + Object.freeze({ + id: 'mcp-network-and-process-activity', + description: 'Probe MCP endpoints and launch, reconnect, or terminate MCP processes.', + }), + Object.freeze({ + id: 'automatic-permission-gates', + description: 'Automatically deny or alter Edit, Write, Bash, and configuration operations.', + }), + Object.freeze({ + id: 'session-observation-and-cost-records', + description: 'Persist session, observation, governance, notification, and cost records.', + }), +]); + +const HOOK_CONSENT_DECISIONS = Object.freeze(['enabled', 'declined']); +const HOOK_RUNTIME_MODULE_ID = 'hooks-runtime'; + +function normalizeOperationPath(value) { + return String(value || '').replace(/\\/g, '/').toLowerCase(); +} + +function isHookRuntimeOperation(operation = {}) { + if ( + operation.kind === 'update-claude-settings' + || operation.moduleId === HOOK_RUNTIME_MODULE_ID + ) { + return true; + } + + const source = normalizeOperationPath(operation.sourceRelativePath); + const destination = normalizeOperationPath(operation.destinationPath); + return ( + source === 'hooks' + || source.startsWith('hooks/') + || source === '.cursor/hooks' + || source.startsWith('.cursor/hooks/') + || source === '.cursor/hooks.json' + || destination.endsWith('/hooks/hooks.json') + || destination.endsWith('/.cursor/hooks.json') + || destination.includes('/.cursor/hooks/') + ); +} + +function planMaterializesHookRuntime(plan = {}) { + const operations = Array.isArray(plan.operations) ? plan.operations : []; + return operations.some(isHookRuntimeOperation); +} + +function formatHookCapabilityDisclosure(indent = ' ') { + return HOOK_CAPABILITY_GROUPS + .map((group, index) => `${indent}${index + 1}. ${group.description}`) + .join('\n'); +} + +function resolveHookConsentFlags({ enableHooks = false, noHooks = false } = {}) { + if (enableHooks && noHooks) { + throw new Error('--enable-hooks and --no-hooks are mutually exclusive'); + } + if (enableHooks) { + return 'enabled'; + } + if (noHooks) { + return 'declined'; + } + return null; +} + +function withoutHookRuntimeId(values) { + return (Array.isArray(values) ? values : []).filter(value => value !== HOOK_RUNTIME_MODULE_ID); +} + +function setStatePreviewHookConsent(statePreview, hookConsent) { + if (!statePreview || !statePreview.request) { + return statePreview; + } + + return { + ...statePreview, + request: { + ...statePreview.request, + hookConsent, + }, + }; +} + +function getRecordedHookConsent(state = {}) { + const explicitDecision = state.request && HOOK_CONSENT_DECISIONS.includes(state.request.hookConsent) + ? state.request.hookConsent + : null; + if (explicitDecision) { + return explicitDecision; + } + + if (Array.isArray(state.request && state.request.modules) && state.request.modules.includes(HOOK_RUNTIME_MODULE_ID)) { + return 'enabled'; + } + + if (Array.isArray(state.resolution && state.resolution.selectedModules) && state.resolution.selectedModules.includes(HOOK_RUNTIME_MODULE_ID)) { + return 'enabled'; + } + + if (planMaterializesHookRuntime(state)) { + return 'enabled'; + } + + return null; +} + +function stripHookRuntimeFromPlan(plan) { + const hadHookRuntimeModule = Array.isArray(plan.selectedModuleIds) + && plan.selectedModuleIds.includes('hooks-runtime'); + const operations = (Array.isArray(plan.operations) ? plan.operations : []) + .filter(operation => !isHookRuntimeOperation(operation)); + const statePreview = plan.statePreview + ? { + ...plan.statePreview, + operations: (Array.isArray(plan.statePreview.operations) ? plan.statePreview.operations : []) + .filter(operation => !isHookRuntimeOperation(operation)), + resolution: plan.statePreview.resolution + ? { + ...plan.statePreview.resolution, + selectedModules: withoutHookRuntimeId(plan.statePreview.resolution.selectedModules), + } + : plan.statePreview.resolution, + } + : plan.statePreview; + + return { + ...plan, + operations, + statePreview: setStatePreviewHookConsent(statePreview, 'declined'), + selectedModuleIds: withoutHookRuntimeId(plan.selectedModuleIds), + excludedModuleIds: hadHookRuntimeModule && Array.isArray(plan.excludedModuleIds) + ? [...new Set([...plan.excludedModuleIds, HOOK_RUNTIME_MODULE_ID])] + : plan.excludedModuleIds, + }; +} + +function withHookConsent(plan, hookConsent = null) { + if (hookConsent !== null && !HOOK_CONSENT_DECISIONS.includes(hookConsent)) { + throw new Error(`Unknown hook consent decision: ${hookConsent}`); + } + if (hookConsent === 'declined') { + return { ...stripHookRuntimeFromPlan(plan), hookConsent }; + } + return { + ...plan, + hookConsent, + statePreview: setStatePreviewHookConsent(plan.statePreview, hookConsent), + }; +} + +function assertHookConsentReady(plan = {}) { + if (!planMaterializesHookRuntime(plan)) { + return; + } + if (plan.hookConsent === 'enabled') { + return; + } + throw new Error( + 'This install would enable ECC\'s automatic hook runtime, which can:\n' + + `${formatHookCapabilityDisclosure()}\n` + + 'Confirm with --enable-hooks to install it, or --no-hooks to install ' + + 'everything else without the hook runtime. The guided installer ' + + '(ecc install --guided) collects this choice interactively.' + ); +} + +module.exports = { + HOOK_CAPABILITY_GROUPS, + assertHookConsentReady, + formatHookCapabilityDisclosure, + getRecordedHookConsent, + isHookRuntimeOperation, + planMaterializesHookRuntime, + resolveHookConsentFlags, + withHookConsent, +}; diff --git a/github_code/affaan-m__ECC/scripts/lib/install/inventory.js b/github_code/affaan-m__ECC/scripts/lib/install/inventory.js new file mode 100644 index 0000000000000000000000000000000000000000..eea35548788df01df64c88abc3cac3a65c7d9819 --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/install/inventory.js @@ -0,0 +1,148 @@ +'use strict'; + +const fs = require('fs'); +const os = require('os'); +const path = require('path'); +const { isWithinRoot, realpathNearestExisting } = require('../path-safety'); + +const CURRENT_PLUGIN_ID = 'ecc@ecc'; +const LEGACY_PLUGIN_IDS = new Set([ + 'everything-claude-code@everything-claude-code', + 'everything-claude-code@ecc', +]); + +function resolveClaudePaths(options = {}) { + const homeDir = options.homeDir + || process.env.HOME + || process.env.USERPROFILE + || os.homedir(); + const configDir = options.configDir + || process.env.CLAUDE_CONFIG_DIR + || path.join(homeDir, '.claude'); + const projectRoot = options.projectRoot || process.cwd(); + + return { + homeDir: path.resolve(homeDir), + configDir: path.resolve(configDir), + projectRoot: path.resolve(projectRoot), + }; +} + +function readJsonObject(filePath, label) { + let value; + try { + value = JSON.parse(fs.readFileSync(filePath, 'utf8')); + } catch (error) { + throw new Error(`${label} is invalid at ${filePath}: ${error.message}`); + } + if (!value || typeof value !== 'object' || Array.isArray(value)) { + throw new Error(`${label} is invalid at ${filePath}: expected a JSON object`); + } + return value; +} + +function findManualClaudePlugin(options = {}) { + const { configDir } = resolveClaudePaths(options); + const pluginsDir = path.join(configDir, 'plugins'); + const candidates = [ + ['ecc', '.claude-plugin', 'plugin.json'], + ['ecc', 'plugin.json'], + ['ecc@ecc', '.claude-plugin', 'plugin.json'], + ['ecc@ecc', 'plugin.json'], + ['everything-claude-code', '.claude-plugin', 'plugin.json'], + ['everything-claude-code', 'plugin.json'], + ]; + + for (const segments of candidates) { + const manifestPath = path.join(pluginsDir, ...segments); + if (fs.existsSync(manifestPath)) { + return { + manifestPath, + installPath: path.dirname(path.dirname(manifestPath)), + }; + } + } + return null; +} + +function validateManagedState(state, statePath, expectedRoot) { + const selectedModules = state?.resolution?.selectedModules; + const operations = state?.operations; + if ( + state?.schemaVersion !== 'ecc.install.v1' + || !state.target + || typeof state.target !== 'object' + || Array.isArray(state.target) + || !Array.isArray(selectedModules) + || !selectedModules.every(moduleId => typeof moduleId === 'string' && moduleId.length > 0) + || !Array.isArray(operations) + ) { + throw new Error(`Managed Claude install-state is invalid at ${statePath}`); + } + + for (const operation of operations) { + if ( + !operation + || typeof operation !== 'object' + || typeof operation.destinationPath !== 'string' + || !path.isAbsolute(operation.destinationPath) + || !isWithinRoot(operation.destinationPath, expectedRoot) + ) { + throw new Error(`Managed Claude install-state is invalid at ${statePath}`); + } + } + + return { selectedModules, operations }; +} + +function operationOverlapsPlugin(operation, expectedRoot) { + const canonicalRoot = realpathNearestExisting(expectedRoot); + const canonicalDestination = realpathNearestExisting(operation.destinationPath); + const relativePath = path.relative(canonicalRoot, canonicalDestination); + const firstSegment = relativePath.split(path.sep)[0]; + return ['agents', 'commands', 'hooks', 'skills'].includes(firstSegment); +} + +function findManagedClaudeInstalls(options = {}) { + const { configDir, projectRoot } = resolveClaudePaths(options); + const candidates = [ + { + statePath: path.join(configDir, 'ecc', 'install-state.json'), + expectedRoot: configDir, + }, + { + statePath: path.join(projectRoot, '.claude', 'ecc', 'install-state.json'), + expectedRoot: path.join(projectRoot, '.claude'), + }, + ]; + const findings = []; + + for (const candidate of candidates) { + if (!fs.existsSync(candidate.statePath)) continue; + const state = readJsonObject(candidate.statePath, 'Managed Claude install-state'); + const { selectedModules, operations } = validateManagedState( + state, + candidate.statePath, + candidate.expectedRoot + ); + const modulesOverlap = selectedModules.some(moduleId => moduleId !== 'rules-core'); + const operationsOverlap = operations.some(operation => ( + operationOverlapsPlugin(operation, candidate.expectedRoot) + )); + findings.push({ + statePath: candidate.statePath, + selectedModules: [...selectedModules], + overlapsPlugin: modulesOverlap || operationsOverlap, + }); + } + + return findings; +} + +module.exports = { + CURRENT_PLUGIN_ID, + LEGACY_PLUGIN_IDS, + findManagedClaudeInstalls, + findManualClaudePlugin, + resolveClaudePaths, +}; diff --git a/github_code/affaan-m__ECC/scripts/lib/install/link-rewrite.js b/github_code/affaan-m__ECC/scripts/lib/install/link-rewrite.js new file mode 100644 index 0000000000000000000000000000000000000000..2a06fcc104aa6c4f9239291bca7966be323b14e5 --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/install/link-rewrite.js @@ -0,0 +1,167 @@ +'use strict'; + +const path = require('path'); + +const posix = path.posix; + +// Matches inline markdown links and images: `](target)` / `](target "title")`. +// We deliberately scope to the inline form because that is what skill/rule docs +// use for cross-directory references. Reference-style and autolinks are left +// untouched (they are rare in these files and carry higher false-positive risk). +const INLINE_LINK_PATTERN = /(!?\]\()([^()\s]+)(\s+"[^"]*")?(\))/g; + +function toPosix(relativePath) { + return String(relativePath || '').replace(/\\/g, '/').replace(/^\.\//, ''); +} + +function stripTrailingSlash(value) { + return value.length > 1 ? value.replace(/\/+$/, '') : value; +} + +// Build file + directory lookup maps from the plan's own file placements. +// `fileMappings` is a list of { sourceRel, destRel } where both are paths +// relative to the repo root and the install root respectively. The directory +// map is derived by walking shared ancestors of each source/dest pair, which is +// exact for prefix-insertion namespacing (e.g. `rules/x` -> `rules/ecc/x`): +// the path suffix below the inserted segment is preserved, so ancestor `k` +// of the source maps to the dest with the matching number of trailing +// segments removed. +function buildInstallIndex(fileMappings) { + const byFile = new Map(); + const byDir = new Map(); + + for (const mapping of fileMappings || []) { + const sourceRel = toPosix(mapping.sourceRel); + const destRel = toPosix(mapping.destRel); + if (!sourceRel || !destRel) { + continue; + } + + byFile.set(sourceRel, destRel); + + const sourceParts = sourceRel.split('/'); + const destParts = destRel.split('/'); + // Map every source ancestor directory to its installed counterpart by + // removing the same count of trailing segments from the dest path. + for (let depth = 1; depth < sourceParts.length; depth += 1) { + const trailing = sourceParts.length - depth; + const destDepth = destParts.length - trailing; + if (destDepth < 1) { + continue; + } + const sourceDir = sourceParts.slice(0, depth).join('/'); + const destDir = destParts.slice(0, destDepth).join('/'); + // Only record real prefix-insertion mappings (suffix preserved). If a + // directory resolves to itself (no namespace change) we skip it so the + // rewriter leaves those links alone. + if (sourceDir !== destDir) { + byDir.set(sourceDir, destDir); + } + } + } + + return { byFile, byDir }; +} + +function isExternalOrAnchor(target) { + return ( + target === '' + || target.startsWith('#') + || target.startsWith('/') + || target.startsWith('mailto:') + || /^[a-zA-Z][a-zA-Z0-9+.-]*:/.test(target) // has a URL scheme (http:, https:, file:, ...) + ); +} + +// Resolve `target` (a relative link from `sourceDir`) to its repo-relative +// path, then return the install-relative path it should point to, or null when +// the target is not installed by this plan (leave such links untouched). +function resolveInstalledTarget(target, sourceDir, index) { + const hadTrailingSlash = target.endsWith('/'); + const resolved = stripTrailingSlash(toPosix(posix.normalize(posix.join(sourceDir, target)))); + + // Escapes the repo root (starts with `..`) -> not something we placed. + if (resolved === '' || resolved === '.' || resolved.startsWith('..')) { + return null; + } + + if (!hadTrailingSlash && index.byFile.has(resolved)) { + return { installed: index.byFile.get(resolved), trailingSlash: false }; + } + if (index.byDir.has(resolved)) { + return { installed: index.byDir.get(resolved), trailingSlash: hadTrailingSlash }; + } + return null; +} + +// Rewrite relative links in a markdown file so they resolve to installed target +// locations. The source file may itself install at the same relative path; links +// can still need changes when their targets move, such as rules -> rules/ecc. +// Pure: no IO. +function rewriteRelativeLinks(content, options) { + const { sourceRel, index } = options || {}; + const normalizedSource = toPosix(sourceRel); + const installedSource = index && index.byFile.get(normalizedSource); + + if (!installedSource) { + return content; + } + + const installedSourceDir = posix.dirname(installedSource); + const sourceDir = posix.dirname(normalizedSource); + const lines = String(content).split('\n'); + let inFence = false; + + for (let i = 0; i < lines.length; i += 1) { + const fenceToggle = /^\s*(```|~~~)/.test(lines[i]); + if (fenceToggle) { + inFence = !inFence; + continue; + } + if (inFence) { + continue; // never rewrite inside fenced code blocks + } + + lines[i] = lines[i].replace( + INLINE_LINK_PATTERN, + (match, open, target, title, close) => { + // Preserve any `#fragment` so anchors survive the rewrite. + const hashIdx = target.indexOf('#'); + const pathPart = hashIdx === -1 ? target : target.slice(0, hashIdx); + const fragment = hashIdx === -1 ? '' : target.slice(hashIdx); + + if (isExternalOrAnchor(pathPart)) { + return match; + } + + const resolution = resolveInstalledTarget(pathPart, sourceDir, index); + if (!resolution) { + return match; + } + + let rewritten = posix.relative(installedSourceDir, resolution.installed); + if (rewritten === '') { + rewritten = '.'; + } + if (resolution.trailingSlash && !rewritten.endsWith('/')) { + rewritten += '/'; + } + // If the recomputed link points to the same place as the original + // (e.g. an intra-namespace `./sibling.md` whose endpoints both shift by + // the same prefix), keep the original text verbatim - including any + // leading `./` - so the rewrite stays a strict no-op where it must. + if (posix.normalize(rewritten) === posix.normalize(pathPart)) { + return match; + } + return `${open}${rewritten}${fragment}${title || ''}${close}`; + } + ); + } + + return lines.join('\n'); +} + +module.exports = { + buildInstallIndex, + rewriteRelativeLinks, +}; diff --git a/github_code/affaan-m__ECC/scripts/lib/install/opencode-legacy-migration.js b/github_code/affaan-m__ECC/scripts/lib/install/opencode-legacy-migration.js new file mode 100644 index 0000000000000000000000000000000000000000..baf3472f135491e4d2d421f6b5e3ba68ecd560ec --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/install/opencode-legacy-migration.js @@ -0,0 +1,398 @@ +'use strict'; + +const crypto = require('crypto'); +const fs = require('fs'); +const path = require('path'); + +const { readInstallState } = require('../install-state'); +const { assertWithinTrustedRoot } = require('../path-safety'); + +const OPENCODE_TARGET = 'opencode'; +const INSTALL_STATE_NAME = 'ecc-install-state.json'; + +function samePath(leftPath, rightPath) { + const left = path.resolve(leftPath); + const right = path.resolve(rightPath); + return process.platform === 'win32' + ? left.toLowerCase() === right.toLowerCase() + : left === right; +} + +function pathExists(filePath) { + try { + fs.lstatSync(filePath); + return true; + } catch (error) { + if (error && (error.code === 'ENOENT' || error.code === 'ENOTDIR')) { + return false; + } + throw error; + } +} + +function getLegacyOpencodeLocation(homeDir) { + const targetRoot = path.join(path.resolve(homeDir), '.opencode'); + return { + targetRoot, + installStatePath: path.join(targetRoot, INSTALL_STATE_NAME), + legacyLayout: 'opencode', + }; +} + +function getLegacyLocationForPlan(plan) { + if ( + !plan + || plan.adapter?.target !== OPENCODE_TARGET + || typeof plan.targetRoot !== 'string' + ) { + return null; + } + if (typeof plan.homeDir === 'string' && plan.homeDir.trim() !== '') { + return getLegacyOpencodeLocation(plan.homeDir); + } + const canonicalRoot = path.resolve(plan.targetRoot); + if ( + path.basename(canonicalRoot) !== 'opencode' + || path.basename(path.dirname(canonicalRoot)) !== '.config' + ) { + return null; + } + return getLegacyOpencodeLocation(path.dirname(path.dirname(canonicalRoot))); +} + +function inspectLegacyOpencodeState(location) { + if (!location) { + return { status: 'absent', state: null, error: null }; + } + try { + if (!pathExists(location.installStatePath)) { + return { status: 'absent', state: null, error: null }; + } + const rootStat = fs.lstatSync(location.targetRoot); + const stateStat = fs.lstatSync(location.installStatePath); + if ( + !rootStat.isDirectory() + || rootStat.isSymbolicLink() + || !stateStat.isFile() + || stateStat.isSymbolicLink() + ) { + return { status: 'invalid', state: null, error: null }; + } + const state = readInstallState(location.installStatePath); + const isOpencode = state.target.target === OPENCODE_TARGET + || state.target.id === 'opencode-home'; + if ( + !isOpencode + || !samePath(state.target.root, location.targetRoot) + || !samePath(state.target.installStatePath, location.installStatePath) + ) { + return { status: 'invalid', state: null, error: null }; + } + return { status: 'valid', state, error: null }; + } catch (error) { + return { + status: 'unreadable', + state: null, + error: `Unable to inspect legacy OpenCode install-state at ${location.installStatePath}: ${error.message}`, + }; + } +} + +function hashFileNoFollow(filePath) { + const flags = fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW || 0); + const descriptor = fs.openSync(filePath, flags); + try { + const before = fs.fstatSync(descriptor, { bigint: true }); + if (!before.isFile()) { + throw new Error(`Refusing to read a non-file at ${filePath}`); + } + const content = fs.readFileSync(descriptor); + const after = fs.fstatSync(descriptor, { bigint: true }); + const finalPathStat = fs.lstatSync(filePath, { bigint: true }); + const unchanged = before.dev === after.dev + && before.ino === after.ino + && before.size === after.size + && before.mtimeMs === after.mtimeMs + && before.ctimeMs === after.ctimeMs + && after.dev === finalPathStat.dev + && after.ino === finalPathStat.ino + && after.size === finalPathStat.size + && after.mtimeMs === finalPathStat.mtimeMs + && after.ctimeMs === finalPathStat.ctimeMs; + if (finalPathStat.isSymbolicLink() || !finalPathStat.isFile() || !unchanged) { + throw new Error(`Refusing to read a file that changed during validation: ${filePath}`); + } + return { + digest: crypto.createHash('sha256').update(content).digest('hex'), + stat: after, + }; + } finally { + fs.closeSync(descriptor); + } +} + +function removeEmptyParents(startPath, legacyRoot) { + let currentPath = path.dirname(startPath); + while (!samePath(currentPath, legacyRoot)) { + const safePath = assertWithinTrustedRoot( + currentPath, + legacyRoot, + 'clean legacy OpenCode install' + ); + if (!pathExists(safePath)) { + currentPath = path.dirname(safePath); + continue; + } + const stat = fs.lstatSync(safePath); + if (!stat.isDirectory() || stat.isSymbolicLink() || fs.readdirSync(safePath).length > 0) { + return; + } + fs.rmdirSync(safePath); + currentPath = path.dirname(safePath); + } +} + +function verifyManagedLegacyFile(operation, location, sourceRoot) { + if (operation?.ownership !== 'managed' || operation?.kind !== 'copy-file') { + return { skipped: true }; + } + if ( + typeof operation.destinationPath !== 'string' + || typeof operation.sourceRelativePath !== 'string' + || !/^[a-f0-9]{64}$/i.test(operation.contentSha256 || '') + ) { + return { retainedPath: operation?.destinationPath || location.targetRoot }; + } + + let destinationPath; + let sourcePath; + try { + destinationPath = assertWithinTrustedRoot( + operation.destinationPath, + location.targetRoot, + 'migrate legacy OpenCode install' + ); + sourcePath = assertWithinTrustedRoot( + path.join(sourceRoot, operation.sourceRelativePath), + sourceRoot, + 'verify legacy OpenCode source' + ); + } catch (_error) { + return { retainedPath: operation.destinationPath }; + } + + let destination; + try { + destination = hashFileNoFollow(destinationPath); + } catch (error) { + if (error && (error.code === 'ENOENT' || error.code === 'ENOTDIR')) { + return { missing: true }; + } + return { retainedPath: destinationPath }; + } + if (destination.digest !== operation.contentSha256.toLowerCase()) { + return { retainedPath: destinationPath }; + } + let source; + try { + source = hashFileNoFollow(sourcePath); + } catch (_error) { + return { retainedPath: destinationPath }; + } + if (source.digest !== destination.digest) { + return { retainedPath: destinationPath }; + } + return { destinationPath, stat: destination.stat }; +} + +function pathExistsWith(fileSystem, filePath) { + try { + fileSystem.lstatSync(filePath); + return true; + } catch (error) { + if (error && (error.code === 'ENOENT' || error.code === 'ENOTDIR')) { + return false; + } + throw error; + } +} + +function restoreQuarantinedFileNoClobber(quarantinePath, safePath, fileSystem) { + try { + fileSystem.linkSync(quarantinePath, safePath); + } catch (error) { + error.retainedPath = quarantinePath; + throw error; + } + try { + fileSystem.rmSync(quarantinePath); + } catch (error) { + error.retainedPath = quarantinePath; + throw error; + } +} + +function removeVerifiedLegacyFile(entry, location, fileSystem = fs) { + const safePath = assertWithinTrustedRoot( + entry.destinationPath, + location.targetRoot, + 'remove verified legacy OpenCode file' + ); + const quarantineDir = fileSystem.mkdtempSync(path.join( + path.dirname(location.targetRoot), + '.ecc-opencode-remove-' + )); + const quarantinePath = path.join(quarantineDir, path.basename(safePath)); + try { + fileSystem.renameSync(safePath, quarantinePath); + const quarantinedStat = fileSystem.lstatSync(quarantinePath, { bigint: true }); + const identityMatches = !quarantinedStat.isSymbolicLink() + && quarantinedStat.isFile() + && quarantinedStat.dev === entry.stat.dev + && quarantinedStat.ino === entry.stat.ino; + if (!identityMatches) { + const identityError = new Error( + `Legacy OpenCode file changed during quarantine: ${safePath}` + ); + identityError.code = 'ESTALE'; + throw identityError; + } + fileSystem.rmSync(quarantinePath); + fileSystem.rmdirSync(quarantineDir); + return true; + } catch (error) { + let restoreError = null; + try { + if (pathExistsWith(fileSystem, quarantinePath)) { + restoreQuarantinedFileNoClobber(quarantinePath, safePath, fileSystem); + } + if ( + pathExistsWith(fileSystem, quarantineDir) + && fileSystem.readdirSync(quarantineDir).length === 0 + ) { + fileSystem.rmdirSync(quarantineDir); + } + } catch (recoveryError) { + restoreError = recoveryError; + } + if (restoreError) { + restoreError.cause = error; + throw restoreError; + } + throw error; + } +} + +function emptyCleanupResult() { + return { + detected: false, + complete: false, + removedPaths: [], + retainedPaths: [], + warnings: [], + }; +} + +function hasTrustedCanonicalState(plan) { + if (typeof plan.sourceRoot !== 'string' || !pathExists(plan.installStatePath)) { + return false; + } + try { + const canonicalState = readInstallState(plan.installStatePath); + return !( + (canonicalState.target.target !== OPENCODE_TARGET + && canonicalState.target.id !== 'opencode-home') + || !samePath(canonicalState.target.root, plan.targetRoot) + || !samePath(canonicalState.target.installStatePath, plan.installStatePath) + ); + } catch (_error) { + return false; + } +} + +function classifyLegacyOperations(inspection, location, sourceRoot) { + const removable = []; + const retainedPaths = []; + for (const operation of inspection.state.operations || []) { + const verified = verifyManagedLegacyFile(operation, location, sourceRoot); + if (verified.destinationPath) removable.push(verified); + else if (verified.retainedPath) retainedPaths.push(verified.retainedPath); + } + return { removable, retainedPaths }; +} + +function removeLegacyFiles(removable, location, retainedPaths) { + const removedPaths = []; + for (const entry of removable) { + try { + if (!removeVerifiedLegacyFile(entry, location)) { + retainedPaths.push(entry.destinationPath); + continue; + } + removedPaths.push(entry.destinationPath); + removeEmptyParents(entry.destinationPath, location.targetRoot); + } catch (error) { + retainedPaths.push(entry.destinationPath); + if (error.retainedPath) retainedPaths.push(error.retainedPath); + } + } + return removedPaths; +} + +function finalizeLegacyCleanup(location, retainedPaths, removedPaths) { + if (retainedPaths.length > 0) return false; + fs.rmSync(location.installStatePath, { force: true }); + removedPaths.push(location.installStatePath); + try { + if (pathExists(location.targetRoot) && fs.readdirSync(location.targetRoot).length === 0) { + fs.rmdirSync(location.targetRoot); + } + } catch (_error) { + // Removing an empty legacy root is best effort after ownership is cleared. + } + return true; +} + +function cleanupLegacyOpencodeInstall(plan) { + const location = getLegacyLocationForPlan(plan); + const emptyResult = emptyCleanupResult(); + if (!location || !hasTrustedCanonicalState(plan)) return emptyResult; + + const inspection = inspectLegacyOpencodeState(location); + if (inspection.status === 'unreadable') { + return { + ...emptyResult, + detected: true, + retainedPaths: [location.targetRoot], + warnings: [inspection.error], + }; + } + if (inspection.status !== 'valid') { + return emptyResult; + } + + const { removable, retainedPaths } = classifyLegacyOperations( + inspection, + location, + plan.sourceRoot + ); + const removedPaths = removeLegacyFiles(removable, location, retainedPaths); + const complete = finalizeLegacyCleanup(location, retainedPaths, removedPaths); + + return { + detected: true, + complete, + removedPaths, + retainedPaths: [...new Set(retainedPaths)].sort(), + warnings: complete + ? [] + : ['Modified, unsupported, or unverifiable managed files remain under ~/.opencode and were preserved.'], + }; +} + +module.exports = { + cleanupLegacyOpencodeInstall, + getLegacyOpencodeLocation, + inspectLegacyOpencodeState, + removeVerifiedLegacyFile, +}; diff --git a/github_code/affaan-m__ECC/scripts/lib/install/ownership-guard.js b/github_code/affaan-m__ECC/scripts/lib/install/ownership-guard.js new file mode 100644 index 0000000000000000000000000000000000000000..962c62e8835f0550ccdca05e499a16391f436491 --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/install/ownership-guard.js @@ -0,0 +1,159 @@ +'use strict'; + +const fs = require('fs'); +const path = require('path'); + +const { readInstallState } = require('../install-state'); + +function pathExists(filePath) { + try { + fs.lstatSync(filePath); + return true; + } catch (error) { + if (error && error.code === 'ENOENT') { + return false; + } + throw error; + } +} + +function comparablePath(filePath) { + const resolvedPath = path.resolve(filePath); + return process.platform === 'win32' ? resolvedPath.toLowerCase() : resolvedPath; +} + +/** + * #2964: the shared copy path used to write every copy-file operation + * unconditionally and record the destination as `ownership: 'managed'` even + * when the file already existed and was authored by the user. The visible + * symptom is a lost edit; the dangerous one is the install-state record, + * which makes a later uninstall delete the user's file. + * + * This guard generalises the Claude flat-skill migration conflict pattern to + * every adapter copy operation: when a destination exists and is NOT recorded + * as an ECC-managed operation in the previous install-state, the operation is + * skipped with a warning instead of overwriting and claiming ownership. + * + * All managed targets share this ownership boundary (#2964). + */ +function prepareUserOwnedFileGuard(plan, migration) { + const previousState = pathExists(plan.installStatePath) + ? readInstallState(plan.installStatePath) + : null; + if (previousState && ( + previousState.target.id !== plan.adapter.id + || comparablePath(previousState.target.root) !== comparablePath(plan.targetRoot) + || comparablePath(previousState.target.installStatePath) !== comparablePath(plan.installStatePath) + )) { + throw new Error(`Refusing install: install-state target does not match the current plan at ${plan.installStatePath}.`); + } + // Recorded files remain updateable by reinstall/repair. Preserve their prior + // digests if an attempt fails before writing them so uninstall detects drift. + const previousManagedOperations = new Map( + ((previousState && previousState.operations) || []) + .filter(operation => ( + operation + && operation.ownership === 'managed' + && operation.destinationPath + )) + .map(operation => [comparablePath(operation.destinationPath), operation]) + ); + const managedDestinations = new Set(previousManagedOperations.keys()); + + const appliedOperations = []; + const skippedOperations = []; + const warnings = []; + for (const operation of (migration && migration.appliedOperations) || []) { + if ( + operation + && operation.kind === 'copy-file' + && operation.destinationPath + && pathExists(operation.destinationPath) + && !managedDestinations.has(comparablePath(operation.destinationPath)) + ) { + skippedOperations.push(operation); + warnings.push( + `Skipped user-owned file ${operation.destinationPath}: the existing file is not recorded in ECC install-state.` + ); + continue; + } + appliedOperations.push(operation); + } + + if (skippedOperations.length === 0) { + return { ...migration, managedDestinations, previousManagedOperations }; + } + + const skippedDestinations = new Set( + skippedOperations.map(operation => comparablePath(operation.destinationPath)) + ); + const filterStateOperations = operations => (operations || []) + .filter(operation => !skippedDestinations.has(comparablePath(operation.destinationPath))); + + // Never leave a skipped destination inside the install-state: recording it + // would claim ownership of a file ECC did not create and make uninstall + // delete it (#2964). + const bridgeState = migration.bridgeState + ? { + ...migration.bridgeState, + operations: filterStateOperations(migration.bridgeState.operations), + } + : migration.bridgeState; + const finalState = migration.finalState + ? { + ...migration.finalState, + operations: filterStateOperations(migration.finalState.operations), + } + : migration.finalState; + + return { + ...migration, + managedDestinations, + previousManagedOperations, + appliedOperations, + skippedOperations: [ + ...((migration && migration.skippedOperations) || []), + ...skippedOperations, + ], + warnings: [...((migration && migration.warnings) || []), ...warnings], + bridgeState, + finalState, + // Only keep bridge persistence when operations actually remain; a fully + // skipped plan installs nothing and must not claim anything. + requiresBridgeState: Boolean(migration.requiresBridgeState) + && appliedOperations.length > 0, + }; +} + +function assertNoNewUserOwnedFile(migration, operation) { + if (operation.kind !== 'copy-file' + || migration.managedDestinations.has(comparablePath(operation.destinationPath)) + || !pathExists(operation.destinationPath)) { + return; + } + throw new Error(`Refusing install: a user-owned file appeared at ${operation.destinationPath} after planning. Rerun the installer to preserve it.`); +} + +function preserveUnwrittenFiles(state, migration, writtenDestinations) { + const writtenPaths = new Set([...writtenDestinations].map(comparablePath)); + return { + ...state, + operations: state.operations.filter(operation => ( + operation.kind !== 'copy-file' + || migration.managedDestinations.has(comparablePath(operation.destinationPath)) + || writtenPaths.has(comparablePath(operation.destinationPath)) + || !pathExists(operation.destinationPath) + )).map(operation => { + const destination = comparablePath(operation.destinationPath); + return operation.kind === 'copy-file' && !writtenPaths.has(destination) + ? migration.previousManagedOperations.get(destination) || operation + : operation; + }), + }; +} + +module.exports = { + assertNoNewUserOwnedFile, + prepareUserOwnedFileGuard, + preserveUnwrittenFiles, +}; diff --git a/github_code/affaan-m__ECC/scripts/lib/install/plan.js b/github_code/affaan-m__ECC/scripts/lib/install/plan.js new file mode 100644 index 0000000000000000000000000000000000000000..08173a6721e1514d7f1e893dd352680f65eed833 --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/install/plan.js @@ -0,0 +1,355 @@ +'use strict'; + +const fs = require('fs'); +const path = require('path'); +const { execFileSync } = require('child_process'); + +const { resolveInstallPlan } = require('../install-manifests'); +const { getInstallTargetAdapter } = require('../install-targets/registry'); +const { resolveInvocationEnvironment } = require('../invocation-environment'); +const { + materializeManagedHooks, +} = require('./claude-settings'); + +const EXCLUDED_GENERATED_SOURCE_SUFFIXES = ['/ecc-install-state.json', '/ecc/install-state.json']; +const IGNORED_DIRECTORY_NAMES = new Set([ + 'node_modules', + '.git', + '__pycache__', + '.pytest_cache', +]); +const IGNORED_FILE_EXTENSIONS = new Set(['.pyc', '.pyo', '.pyd']); + +function getSourceRoot() { + return path.join(__dirname, '../../..'); +} + +function getPackageVersion(sourceRoot) { + try { + const packageJson = JSON.parse(fs.readFileSync(path.join(sourceRoot, 'package.json'), 'utf8')); + return packageJson.version || null; + } catch (_error) { + return null; + } +} + +function getManifestVersion(sourceRoot) { + try { + const modulesManifest = JSON.parse(fs.readFileSync(path.join(sourceRoot, 'manifests', 'install-modules.json'), 'utf8')); + return modulesManifest.version || 1; + } catch (_error) { + return 1; + } +} + +function getRepoCommit(sourceRoot) { + try { + return execFileSync('git', ['rev-parse', 'HEAD'], { + cwd: sourceRoot, + encoding: 'utf8', + stdio: ['ignore', 'pipe', 'ignore'], + timeout: 5000 + }).trim(); + } catch (_error) { + return null; + } +} + +function listFilesRecursive(dirPath) { + if (!fs.existsSync(dirPath)) { + return []; + } + + const files = []; + const entries = fs.readdirSync(dirPath, { withFileTypes: true }); + + for (const entry of entries) { + const absolutePath = path.join(dirPath, entry.name); + if (entry.isDirectory()) { + if (IGNORED_DIRECTORY_NAMES.has(entry.name)) { + continue; + } + const childFiles = listFilesRecursive(absolutePath); + for (const childFile of childFiles) { + files.push(path.join(entry.name, childFile)); + } + } else if (entry.isFile()) { + if (IGNORED_FILE_EXTENSIONS.has(path.extname(entry.name).toLowerCase())) { + continue; + } + files.push(entry.name); + } + } + + return files.sort(); +} + +function isGeneratedRuntimeSourcePath(sourceRelativePath) { + const normalizedPath = String(sourceRelativePath || '').replace(/\\/g, '/'); + return EXCLUDED_GENERATED_SOURCE_SUFFIXES.some(suffix => normalizedPath.endsWith(suffix)); +} + +function createStatePreview(options) { + const { createInstallState } = require('../install-state'); + return createInstallState(options); +} + +function buildCopyFileOperation({ + moduleId, + sourcePath, + sourceRelativePath, + destinationPath, + strategy, + contentTransform, +}) { + return { + kind: 'copy-file', + moduleId, + sourcePath, + sourceRelativePath, + destinationPath, + strategy, + ownership: 'managed', + scaffoldOnly: false, + ...(contentTransform ? { contentTransform } : {}), + }; +} + +function readJsonObject(filePath, label) { + let parsed; + try { + parsed = JSON.parse(fs.readFileSync(filePath, 'utf8')); + } catch (error) { + throw new Error(`Failed to parse ${label} at ${filePath}: ${error.message}`); + } + + if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) { + throw new Error(`Invalid ${label} at ${filePath}: expected a JSON object`); + } + + return parsed; +} + +function materializeClaudeSettingsOperation(sourceRoot, operation) { + const sourcePath = path.join(sourceRoot, operation.sourceRelativePath); + if (!fs.existsSync(sourcePath)) { + return []; + } + + const hooksConfig = readJsonObject(sourcePath, operation.sourceRelativePath); + const managedHooks = materializeManagedHooks( + hooksConfig, + path.dirname(operation.destinationPath) + ); + + return [{ + ...operation, + sourcePath, + scaffoldOnly: false, + managedHooks, + }]; +} + +function materializeScaffoldOperation(sourceRoot, operation) { + if (operation.kind === 'update-claude-settings') { + return materializeClaudeSettingsOperation(sourceRoot, operation); + } + + if (operation.kind === 'merge-json') { + return [ + { + kind: 'merge-json', + moduleId: operation.moduleId, + sourceRelativePath: operation.sourceRelativePath, + destinationPath: operation.destinationPath, + strategy: operation.strategy || 'merge-json', + ownership: operation.ownership || 'managed', + scaffoldOnly: Object.hasOwn(operation, 'scaffoldOnly') ? operation.scaffoldOnly : false, + mergePayload: readJsonObject(path.join(sourceRoot, operation.sourceRelativePath), operation.sourceRelativePath) + } + ]; + } + + const sourcePath = path.join(sourceRoot, operation.sourceRelativePath); + if (!fs.existsSync(sourcePath)) { + return []; + } + + if (isGeneratedRuntimeSourcePath(operation.sourceRelativePath)) { + return []; + } + + const stat = fs.statSync(sourcePath); + if (stat.isFile()) { + return [ + buildCopyFileOperation({ + moduleId: operation.moduleId, + sourcePath, + sourceRelativePath: operation.sourceRelativePath, + destinationPath: operation.destinationPath, + strategy: operation.strategy, + contentTransform: operation.contentTransform, + }) + ]; + } + + const relativeFiles = listFilesRecursive(sourcePath).filter(relativeFile => { + const sourceRelativePath = path.join(operation.sourceRelativePath, relativeFile); + return !isGeneratedRuntimeSourcePath(sourceRelativePath); + }); + return relativeFiles.map(relativeFile => { + const sourceRelativePath = path.join(operation.sourceRelativePath, relativeFile); + return buildCopyFileOperation({ + moduleId: operation.moduleId, + sourcePath: path.join(sourcePath, relativeFile), + sourceRelativePath, + destinationPath: path.join(operation.destinationPath, relativeFile), + strategy: operation.strategy, + contentTransform: operation.contentTransform, + }); + }); +} + +function isSelectedAntigravityLegacyRule(operation, ruleLanguages) { + const normalizedSourcePath = String(operation.sourceRelativePath || '').replace(/\\/g, '/'); + if (!normalizedSourcePath.startsWith('rules/')) { + return true; + } + + const namespace = normalizedSourcePath.split('/')[1]; + return namespace === 'common' || ruleLanguages.includes(namespace); +} + +function dedupeCopyFileOperations(operations) { + // A `copy-file` operation fully overwrites its destination, so when several + // of them target the same path (e.g. a generic `commands/.md` shadowed + // by an OpenCode `.opencode/commands/.md` override) only the last one + // actually determines the installed content. Recording the shadowed earlier + // writes in install-state makes `doctor` report perpetual drift and drives + // `repair` to clobber the override with the generic source (issue #2414). + // Keep only the last `copy-file` per destination - matching the sequential + // apply order in applyInstallPlan - and leave every other operation kind + // (e.g. accumulating `merge-json` writes into a shared config) untouched and + // in order. + const lastCopyIndexByDestination = new Map(); + operations.forEach((operation, index) => { + if (operation.kind === 'copy-file' && operation.destinationPath) { + lastCopyIndexByDestination.set(operation.destinationPath, index); + } + }); + + return operations.filter((operation, index) => { + if (operation.kind !== 'copy-file' || !operation.destinationPath) { + return true; + } + return lastCopyIndexByDestination.get(operation.destinationPath) === index; + }); +} + +function createManifestInstallPlan(options = {}) { + const sourceRoot = options.sourceRoot || getSourceRoot(); + const projectRoot = options.projectRoot || process.cwd(); + const target = options.target || 'claude'; + const legacyLanguages = Array.isArray(options.legacyLanguages) ? [...options.legacyLanguages] : []; + const requestProfileId = Object.hasOwn(options, 'requestProfileId') ? options.requestProfileId : options.profileId || null; + const requestModuleIds = Object.hasOwn(options, 'requestModuleIds') ? [...options.requestModuleIds] : Array.isArray(options.moduleIds) ? [...options.moduleIds] : []; + const requestIncludeComponentIds = Object.hasOwn(options, 'requestIncludeComponentIds') + ? [...options.requestIncludeComponentIds] + : Array.isArray(options.includeComponentIds) + ? [...options.includeComponentIds] + : []; + const requestExcludeComponentIds = Object.hasOwn(options, 'requestExcludeComponentIds') + ? [...options.requestExcludeComponentIds] + : Array.isArray(options.excludeComponentIds) + ? [...options.excludeComponentIds] + : []; + const plan = resolveInstallPlan({ + repoRoot: sourceRoot, + projectRoot, + homeDir: options.homeDir, + env: resolveInvocationEnvironment(options), + profileId: options.profileId || null, + moduleIds: options.moduleIds || [], + includeComponentIds: options.includeComponentIds || [], + excludeComponentIds: options.excludeComponentIds || [], + target, + exemptValidationCodes: options.exemptValidationCodes || [], + }); + const adapter = getInstallTargetAdapter(target); + const materializedOperations = plan.operations.flatMap(operation => ( + materializeScaffoldOperation(sourceRoot, operation) + )); + const ruleLanguages = Array.isArray(options.ruleLanguages) ? [...options.ruleLanguages] : []; + const operations = dedupeCopyFileOperations( + options.legacyMode && target === 'antigravity' + ? materializedOperations.filter(operation => ( + isSelectedAntigravityLegacyRule(operation, ruleLanguages) + )) + : materializedOperations + ); + const source = { + repoVersion: getPackageVersion(sourceRoot), + repoCommit: getRepoCommit(sourceRoot), + manifestVersion: getManifestVersion(sourceRoot) + }; + const statePreview = createStatePreview({ + adapter, + targetRoot: plan.targetRoot, + installStatePath: plan.installStatePath, + request: { + profile: requestProfileId, + modules: requestModuleIds, + includeComponents: requestIncludeComponentIds, + excludeComponents: requestExcludeComponentIds, + legacyLanguages, + legacyMode: Boolean(options.legacyMode) + }, + resolution: { + selectedModules: plan.selectedModuleIds, + skippedModules: plan.skippedModuleIds + }, + operations, + source + }); + + return { + mode: options.mode || 'manifest', + sourceRoot, + target, + adapter: { + id: adapter.id, + target: adapter.target, + kind: adapter.kind + }, + homeDir: plan.homeDir, + targetRoot: plan.targetRoot, + installRoot: plan.targetRoot, + installStatePath: plan.installStatePath, + warnings: Array.isArray(options.warnings) ? [...options.warnings] : [], + languages: legacyLanguages, + legacyLanguages, + profileId: plan.profileId, + requestedModuleIds: plan.requestedModuleIds, + explicitModuleIds: plan.explicitModuleIds, + includedComponentIds: plan.includedComponentIds, + excludedComponentIds: plan.excludedComponentIds, + selectedModuleIds: plan.selectedModuleIds, + skippedModuleIds: plan.skippedModuleIds, + excludedModuleIds: plan.excludedModuleIds, + operations, + statePreview + }; +} + +module.exports = { + buildCopyFileOperation, + createManifestInstallPlan, + createStatePreview, + dedupeCopyFileOperations, + getManifestVersion, + getPackageVersion, + getRepoCommit, + getSourceRoot, + listFilesRecursive, + readJsonObject, +}; diff --git a/github_code/affaan-m__ECC/scripts/lib/install/request.js b/github_code/affaan-m__ECC/scripts/lib/install/request.js new file mode 100644 index 0000000000000000000000000000000000000000..f99f5aba1e1fe2b8bd6dfa0c499f22cacdefbf08 --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/install/request.js @@ -0,0 +1,169 @@ +'use strict'; + +const { validateInstallModuleIds, LOCALE_ALIAS_TO_COMPONENT_ID, listSupportedLocales } = require('../install-manifests'); +const { resolveHookConsentFlags } = require('./hook-consent'); + +const LEGACY_INSTALL_TARGETS = ['claude', 'claude-project', 'cursor', 'antigravity']; + +function dedupeStrings(values) { + return [...new Set((Array.isArray(values) ? values : []).map(value => String(value).trim()).filter(Boolean))]; +} + +function normalizeSkillComponentIds(rawValue) { + return dedupeStrings(String(rawValue || '').split(',')).map(value => ( + value.startsWith('skill:') ? value : `skill:${value}` + )); +} + +function parseInstallArgs(argv) { + const args = argv.slice(2); + const parsed = { + target: null, + dryRun: false, + json: false, + help: false, + configPath: null, + profileId: null, + moduleIds: [], + includeComponentIds: [], + excludeComponentIds: [], + languages: [], + locale: null, + enableHooks: false, + noHooks: false, + }; + + for (let index = 0; index < args.length; index += 1) { + const arg = args[index]; + + if (arg === '--target') { + parsed.target = args[index + 1] || null; + index += 1; + } else if (arg === '--config') { + parsed.configPath = args[index + 1] || null; + index += 1; + } else if (arg === '--profile') { + parsed.profileId = args[index + 1] || null; + index += 1; + } else if (arg === '--modules') { + const raw = args[index + 1] || ''; + parsed.moduleIds = dedupeStrings(raw.split(',')); + index += 1; + } else if (arg === '--with') { + const componentId = args[index + 1] || ''; + if (componentId.trim()) { + parsed.includeComponentIds.push(componentId.trim()); + } + index += 1; + } else if (arg === '--skill' || arg === '--skills') { + parsed.includeComponentIds.push(...normalizeSkillComponentIds(args[index + 1] || '')); + index += 1; + } else if (arg === '--without') { + const componentId = args[index + 1] || ''; + if (componentId.trim()) { + parsed.excludeComponentIds.push(componentId.trim()); + } + index += 1; + } else if (arg === '--locale') { + const locale = args[index + 1] || ''; + if (!locale || locale.startsWith('--')) { + throw new Error('Missing value for --locale'); + } + parsed.locale = locale; + index += 1; + } else if (arg === '--enable-hooks') { + parsed.enableHooks = true; + } else if (arg === '--no-hooks') { + parsed.noHooks = true; + } else if (arg === '--dry-run') { + parsed.dryRun = true; + } else if (arg === '--json') { + parsed.json = true; + } else if (arg === '--help' || arg === '-h') { + parsed.help = true; + } else if (arg.startsWith('--')) { + throw new Error(`Unknown argument: ${arg}`); + } else { + parsed.languages.push(arg); + } + } + + return parsed; +} + +function normalizeInstallRequest(options = {}) { + const config = options.config && typeof options.config === 'object' + ? options.config + : null; + const profileId = options.profileId || config?.profileId || null; + const target = options.target || config?.target || 'claude'; + const moduleIds = validateInstallModuleIds( + dedupeStrings([...(config?.moduleIds || []), ...(options.moduleIds || [])]) + ); + const locale = options.locale || config?.locale || null; + const localeComponentId = locale ? LOCALE_ALIAS_TO_COMPONENT_ID[locale] : null; + if (locale && !localeComponentId) { + throw new Error( + `Unsupported locale: "${locale}". Supported locales: ${listSupportedLocales().join(', ')}` + ); + } + if (locale && target !== 'claude' && target !== 'claude-project') { + throw new Error('--locale can only be used with --target claude or --target claude-project'); + } + const requestedIncludeComponentIds = dedupeStrings([ + ...(config?.includeComponentIds || []), + ...(options.includeComponentIds || []), + ]); + const includeComponentIds = dedupeStrings([ + ...requestedIncludeComponentIds, + ...(localeComponentId ? [localeComponentId] : []), + ]); + const excludeComponentIds = dedupeStrings([ + ...(config?.excludeComponentIds || []), + ...(options.excludeComponentIds || []), + ]); + const legacyLanguages = dedupeStrings(dedupeStrings([ + ...(Array.isArray(options.legacyLanguages) ? options.legacyLanguages : []), + ...(Array.isArray(options.languages) ? options.languages : []), + ]).map(language => language.toLowerCase())); + const hookConsent = resolveHookConsentFlags(options); + if (hookConsent === 'declined' && moduleIds.includes('hooks-runtime')) { + throw new Error('--no-hooks cannot be combined with an explicit hooks-runtime module selection'); + } + const hasManifestBaseSelection = Boolean(profileId) || moduleIds.length > 0 || includeComponentIds.length > 0; + const hasNonLocaleManifestSelection = Boolean(profileId) + || moduleIds.length > 0 + || requestedIncludeComponentIds.length > 0 + || excludeComponentIds.length > 0; + const usingManifestMode = hasManifestBaseSelection || excludeComponentIds.length > 0; + + if (hasNonLocaleManifestSelection && legacyLanguages.length > 0) { + throw new Error( + 'Legacy language arguments cannot be combined with --profile, --modules, --with, --without, or manifest config selections' + ); + } + + if (!options.help && !hasManifestBaseSelection && legacyLanguages.length === 0) { + throw new Error('No install profile, module IDs, included components, or legacy languages were provided'); + } + + return { + mode: legacyLanguages.length > 0 + ? 'legacy-compat' + : (usingManifestMode ? 'manifest' : 'legacy-compat'), + target, + profileId, + moduleIds, + includeComponentIds, + excludeComponentIds, + legacyLanguages, + hookConsent, + configPath: config?.path || options.configPath || null, + }; +} + +module.exports = { + LEGACY_INSTALL_TARGETS, + normalizeInstallRequest, + parseInstallArgs, +}; diff --git a/github_code/affaan-m__ECC/scripts/lib/install/runtime.js b/github_code/affaan-m__ECC/scripts/lib/install/runtime.js new file mode 100644 index 0000000000000000000000000000000000000000..eabb930b26a8f85f26768de2d65036cc7f1c7b46 --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/install/runtime.js @@ -0,0 +1,66 @@ +'use strict'; + +const { + createLegacyCompatInstallPlan, + createLegacyInstallPlan, + createManifestInstallPlan, +} = require('../install-executor'); +const { resolveInvocationEnvironment } = require('../invocation-environment'); +const { withHookConsent } = require('./hook-consent'); + +function createInstallPlanFromRequest(request, options = {}) { + if (!request || typeof request !== 'object') { + throw new Error('A normalized install request is required'); + } + + return withHookConsent(createRawInstallPlan(request, options), request.hookConsent || null); +} + +function createRawInstallPlan(request, options = {}) { + if (request.mode === 'manifest') { + return createManifestInstallPlan({ + target: request.target, + profileId: request.profileId, + moduleIds: request.moduleIds, + includeComponentIds: request.includeComponentIds, + excludeComponentIds: request.excludeComponentIds, + projectRoot: options.projectRoot, + homeDir: options.homeDir, + env: resolveInvocationEnvironment(options), + sourceRoot: options.sourceRoot, + exemptValidationCodes: options.exemptValidationCodes || [], + }); + } + + if (request.mode === 'legacy-compat') { + return createLegacyCompatInstallPlan({ + target: request.target, + legacyLanguages: request.legacyLanguages, + includeComponentIds: request.includeComponentIds, + excludeComponentIds: request.excludeComponentIds, + projectRoot: options.projectRoot, + homeDir: options.homeDir, + env: resolveInvocationEnvironment(options), + claudeRulesDir: options.claudeRulesDir, + sourceRoot: options.sourceRoot, + exemptValidationCodes: options.exemptValidationCodes || [], + }); + } + + if (request.mode === 'legacy') { + return createLegacyInstallPlan({ + target: request.target, + languages: request.languages, + projectRoot: options.projectRoot, + homeDir: options.homeDir, + claudeRulesDir: options.claudeRulesDir, + sourceRoot: options.sourceRoot, + }); + } + + throw new Error(`Unsupported install request mode: ${request.mode}`); +} + +module.exports = { + createInstallPlanFromRequest, +}; diff --git a/github_code/affaan-m__ECC/scripts/lib/instinct-relevance.js b/github_code/affaan-m__ECC/scripts/lib/instinct-relevance.js new file mode 100644 index 0000000000000000000000000000000000000000..81dde7e79581418025a9b8c194b1729bebfa8fb4 --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/instinct-relevance.js @@ -0,0 +1,173 @@ +/** + * Instinct relevance ranking for SessionStart. + * + * At SessionStart there is no user task yet, so "relevance" is location/stack + * relevance: instincts scoped to the current project, or whose domain/trigger + * matches the detected stack, get a small additive boost on top of their + * confidence when ranking which instincts to inject. The confidence >= + * threshold floor and the injection cap are enforced by the caller; this + * module only computes the additive boost and the stack keyword set. When + * nothing is project-scoped and no stack is detected, every boost is 0 and the + * ranking degrades to confidence-only (unchanged behaviour). + * + * Resolves part (b) of: + * https://github.com/affaan-m/everything-claude-code/issues/2371 + */ + +const fs = require('fs'); +const path = require('path'); +const { detectProjectType } = require('./project-detect'); + +// Additive ranking boosts. These are intentionally NOT env-configurable: part +// (b) of the issue asks for relevance ranking, not more tunable knobs (part (a) +// already made the injection count + confidence threshold configurable). The +// values are chosen so a project-scoped 0.7 instinct (0.7 + 0.25 = 0.95) can +// surface above an unrelated global 0.9, and a stack-matching 0.75 instinct +// (0.75 + 0.2 = 0.95) can surface above an unrelated 0.9. +const DEFAULT_PROJECT_SCOPE_BOOST = 0.25; +const DEFAULT_STACK_MATCH_BOOST = 0.2; + +/** + * Whether a file with any of the given extensions exists directly in the root + * (non-recursive, top-level only — kept cheap for a blocking SessionStart hook). + * @param {string} root - Project root directory. + * @param {string[]} extensions - Extensions to look for (e.g. ['.tf']). + * @returns {boolean} + */ +function hasFileWithExtension(root, extensions) { + try { + return fs.readdirSync(root, { withFileTypes: true }).some( + (entry) => entry.isFile() && extensions.includes(path.extname(entry.name)) + ); + } catch { + return false; + } +} + +/** + * Whether a named file exists directly in the root. + * @param {string} root - Project root directory. + * @param {string} name - File name relative to root. + * @returns {boolean} + */ +function fileExists(root, name) { + try { + return fs.existsSync(path.join(root, name)); + } catch { + return false; + } +} + +/** + * Resolve whether relevance ranking is enabled. Default on; opt out by setting + * `ECC_INSTINCT_RELEVANCE_RANKING` to `off`, `false`, `0`, or `no` + * (case-insensitive). Any other value (including unset) keeps ranking on. + * @returns {boolean} + */ +function isRelevanceRankingEnabled() { + const raw = process.env.ECC_INSTINCT_RELEVANCE_RANKING; + if (raw === undefined || raw === null || raw === '') return true; + const normalized = String(raw).trim().toLowerCase(); + return !['off', 'false', '0', 'no'].includes(normalized); +} + +/** + * Cheap, non-recursive stack-keyword detection for the project root. Reuses + * detectProjectType (languages + frameworks) and layers the extra IaC/data + * markers issue #2371 calls out that detectProjectType does not cover + * (`*.tf` / `*.tfvars` -> terraform, `dbt_project.yml` -> dbt). + * @param {string} [projectRoot] - Defaults to process.cwd(). + * @param {{languages?: string[], frameworks?: string[]}} [projectInfo] - + * Optional precomputed detectProjectType() result, to avoid a second pass. + * @returns {Set} Lowercase keyword set (may be empty). + */ +function detectStackKeywords(projectRoot, projectInfo) { + const root = projectRoot || process.cwd(); + const keywords = new Set(); + + let info = projectInfo; + if (!info) { + try { + info = detectProjectType(root); + } catch { + info = { languages: [], frameworks: [] }; + } + } + for (const language of info.languages || []) keywords.add(String(language).toLowerCase()); + for (const framework of info.frameworks || []) keywords.add(String(framework).toLowerCase()); + + if (hasFileWithExtension(root, ['.tf', '.tfvars'])) keywords.add('terraform'); + if (fileExists(root, 'dbt_project.yml')) keywords.add('dbt'); + + return keywords; +} + +/** + * Tokenize a free-text field into lowercase word tokens (split on + * non-alphanumerics). Token-set matching avoids substring false positives such + * as the keyword `go` matching the word `good`. + * @param {string} value + * @returns {string[]} + */ +function tokenize(value) { + return String(value || '') + .toLowerCase() + .split(/[^a-z0-9]+/) + .filter(Boolean); +} + +/** + * Whether an instinct's domain/trigger/stack fields intersect the stack + * keywords by whole-token match. + * @param {object} instinct - Parsed instinct (frontmatter fields as properties). + * @param {Set} stackKeywords + * @returns {boolean} + */ +function instinctMatchesStack(instinct, stackKeywords) { + if (!instinct || !stackKeywords || stackKeywords.size === 0) return false; + const tokens = new Set([ + ...tokenize(instinct.domain), + ...tokenize(instinct.trigger), + ...tokenize(instinct.stack), + ]); + for (const keyword of stackKeywords) { + if (tokens.has(keyword)) return true; + } + return false; +} + +/** + * Additive relevance boost for ranking. Deterministic and pure. A + * project-scoped instinct (location-relevant by construction) and a + * stack-matching instinct each contribute their boost; both can apply. + * @param {object} instinct - Must carry `_scopeLabel` ('project'|'global') and + * optional `domain`/`trigger`/`stack` fields. + * @param {Set} stackKeywords + * @param {{projectBoost?: number, stackBoost?: number}} [opts] + * @returns {number} + */ +function computeRelevanceBoost(instinct, stackKeywords, opts) { + const options = opts || {}; + const projectBoost = Number.isFinite(options.projectBoost) + ? options.projectBoost + : DEFAULT_PROJECT_SCOPE_BOOST; + const stackBoost = Number.isFinite(options.stackBoost) + ? options.stackBoost + : DEFAULT_STACK_MATCH_BOOST; + + let boost = 0; + if (instinct && instinct._scopeLabel === 'project') boost += projectBoost; + if (instinctMatchesStack(instinct, stackKeywords)) boost += stackBoost; + return boost; +} + +module.exports = { + DEFAULT_PROJECT_SCOPE_BOOST, + DEFAULT_STACK_MATCH_BOOST, + isRelevanceRankingEnabled, + detectStackKeywords, + instinctMatchesStack, + computeRelevanceBoost, + // Exported for testing. + tokenize, +}; diff --git a/github_code/affaan-m__ECC/scripts/lib/invocation-environment.js b/github_code/affaan-m__ECC/scripts/lib/invocation-environment.js new file mode 100644 index 0000000000000000000000000000000000000000..f36a092520200db863e2345e660974c0e2999da4 --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/invocation-environment.js @@ -0,0 +1,17 @@ +'use strict'; + +function resolveInvocationEnvironment(options = {}) { + if (Object.prototype.hasOwnProperty.call(options, 'env')) { + return { ...(options.env || {}) }; + } + + if (typeof options.homeDir === 'string' && options.homeDir.trim() !== '') { + return {}; + } + + return { ...process.env }; +} + +module.exports = { + resolveInvocationEnvironment, +}; diff --git a/github_code/affaan-m__ECC/scripts/lib/ito-environment.js b/github_code/affaan-m__ECC/scripts/lib/ito-environment.js new file mode 100644 index 0000000000000000000000000000000000000000..e9a6c909c466c759bc50e73e32e5f23e13f4474b --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/ito-environment.js @@ -0,0 +1,113 @@ +"use strict"; + +const SYSTEM_ENVIRONMENT_KEYS = Object.freeze([ + "CI", + "ComSpec", + "DISPLAY", + "FORCE_COLOR", + "HOME", + "LANG", + "LC_ALL", + "NO_COLOR", + "PATH", + "PATHEXT", + "SHELL", + "SystemRoot", + "TEMP", + "TERM", + "TMP", + "TMPDIR", + "USERPROFILE", + "WAYLAND_DISPLAY", + "WINDIR", + "XDG_RUNTIME_DIR", +]); + +const ITO_RUNTIME_ENVIRONMENT_KEYS = Object.freeze([ + "ITO_API_KEY", + "ITO_API_URL", + "ITO_INVENTORY_URL", + "ITO_AUTH_MODE", + "ITO_ALLOW_FILE_TOKEN", + "ITO_TOKEN_FILE", +]); + +const ITO_EVAL_ENVIRONMENT_KEYS = Object.freeze([ + "ITO_ENABLE_SIXTYTWO_LIVE", + "SIXTYTWO_API_TOKEN", + "SIXTYTWO_TOKEN", + "SSH_AUTH_SOCK", + "SSH_AGENT_PID", +]); + +const ECC_ITO_CONTROL_KEYS = Object.freeze([ + "ECC_DRY_RUN", + "ECC_ITO_CLI_EXECUTABLE", + "NODE_ENV", +]); +const ITO_RUNTIME_COMMANDS = new Set(["login", "logout", "auth", "find", "status"]); + +function copyDefined(source, target, key) { + if (typeof source[key] === "string") { + target[key] = source[key]; + } +} + +function createSafeItoEnvironment(source = process.env, options = {}) { + const safe = {}; + for (const key of SYSTEM_ENVIRONMENT_KEYS) { + copyDefined(source, safe, key); + } + for (const [key] of Object.entries(source)) { + if (key.startsWith("LC_")) copyDefined(source, safe, key); + } + + if (options.includeItoRuntime) { + for (const key of ITO_RUNTIME_ENVIRONMENT_KEYS) { + if (key === "ITO_API_KEY" && options.includeItoApiKey !== true) continue; + copyDefined(source, safe, key); + } + } + + if (options.includeItoEvals) { + for (const key of ITO_EVAL_ENVIRONMENT_KEYS) { + copyDefined(source, safe, key); + } + } + + if (options.includeControls) { + for (const key of ECC_ITO_CONTROL_KEYS) { + copyDefined(source, safe, key); + } + } + + return Object.freeze(safe); +} + +function getInvocationCommand(args = []) { + return args.filter((value) => value !== "--json")[0]; +} + +function createSafeItoInvocationEnvironment( + source = process.env, + args = [], + options = {}, +) { + const command = getInvocationCommand(args); + return createSafeItoEnvironment(source, { + includeControls: options.includeControls === true, + includeItoRuntime: ITO_RUNTIME_COMMANDS.has(command), + includeItoApiKey: ["auth", "find", "status"].includes(command), + includeItoEvals: command === "evals", + }); +} + +module.exports = Object.freeze({ + ECC_ITO_CONTROL_KEYS, + ITO_EVAL_ENVIRONMENT_KEYS, + ITO_RUNTIME_ENVIRONMENT_KEYS, + SYSTEM_ENVIRONMENT_KEYS, + createSafeItoEnvironment, + createSafeItoInvocationEnvironment, + getInvocationCommand, +}); diff --git a/github_code/affaan-m__ECC/scripts/lib/llm-summary.js b/github_code/affaan-m__ECC/scripts/lib/llm-summary.js new file mode 100644 index 0000000000000000000000000000000000000000..b53fabd899bdd5e5f7d5a43b64708b26a2242880 --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/llm-summary.js @@ -0,0 +1,177 @@ +#!/usr/bin/env node +/** + * LLM-powered session summary generator + * + * Uses `claude -p` (Claude Code CLI) to generate rich, contextual session + * summaries from JSONL transcripts. Requires no API key — reuses Claude Code's + * own authentication. + * + * Recursion guard: sets ECC_SKIP_LLM_SUMMARY=1 in subprocess env so any Stop + * hooks fired by the subprocess do NOT re-enter LLM summarization. + */ + +'use strict'; + +const { spawnSync } = require('child_process'); +const fs = require('fs'); + +const MAX_TRANSCRIPT_CHARS = 7000; +const MAX_TURNS = 25; +const LLM_TIMEOUT_MS = 90000; + +function getLLMModel() { + return process.env.ECC_LLM_SUMMARY_MODEL || 'haiku'; +} + +function getContextThreshold() { + const raw = parseInt(process.env.ECC_LLM_SUMMARY_CONTEXT_THRESHOLD || '20', 10); + return Number.isFinite(raw) && raw > 0 && raw <= 100 ? raw : 20; +} + +/** + * Extract the last MAX_TURNS user+assistant turns from a JSONL transcript. + * Returns null when the transcript is missing or has no parseable turns. + */ +function extractConversationText(transcriptPath) { + let content; + try { + content = fs.readFileSync(transcriptPath, 'utf8'); + } catch { + return null; + } + + const lines = content.split('\n').filter(Boolean); + const turns = []; + + for (const line of lines) { + try { + const entry = JSON.parse(line); + const isUser = entry.type === 'user' || entry.message?.role === 'user'; + const isAssistant = entry.type === 'assistant'; + + if (isUser) { + const rawContent = entry.message?.content ?? entry.content; + const text = + typeof rawContent === 'string' + ? rawContent + : Array.isArray(rawContent) + ? rawContent + .filter(c => c?.type === 'text') + .map(c => c.text) + .join(' ') + : ''; + const cleaned = text.replace(/\n+/g, ' ').trim(); + if (cleaned) { + turns.push({ role: 'User', text: cleaned.slice(0, 400) }); + } + } + + if (isAssistant && Array.isArray(entry.message?.content)) { + const textParts = entry.message.content + .filter(b => b?.type === 'text') + .map(b => b.text) + .join(' ') + .replace(/\n+/g, ' ') + .trim(); + if (textParts) { + turns.push({ role: 'Claude', text: textParts.slice(0, 600) }); + } + } + } catch { + // Skip unparseable lines + } + } + + if (turns.length === 0) return null; + + const recent = turns.slice(-MAX_TURNS); + const formatted = recent.map(t => `**${t.role}:** ${t.text}`).join('\n\n'); + return formatted.length > MAX_TRANSCRIPT_CHARS ? '...(前略)\n\n' + formatted.slice(-MAX_TRANSCRIPT_CHARS) : formatted; +} + +/** + * Read the context remaining percentage from a transcript's latest usage record. + * Returns null when unavailable. + */ +function getContextRemainingPct(transcriptPath) { + try { + const { readLatestContextTokens, resolveContextWindowTokens } = require('./transcript-context'); + const usage = readLatestContextTokens(transcriptPath); + if (!usage) return null; + const windowTokens = resolveContextWindowTokens(usage.tokens, usage.model); + return Math.round((1 - usage.tokens / windowTokens) * 100); + } catch { + return null; + } +} + +/** + * Generate a session summary using `claude -p`. + * Returns the summary string, or null on failure or when recursion guard is active. + */ +function generateSessionSummary(transcriptPath) { + if (process.env.ECC_SKIP_LLM_SUMMARY) return null; + + const conversation = extractConversationText(transcriptPath); + if (!conversation) return null; + + const prompt = [ + 'Below is a conversation log from a Claude Code coding session.', + 'Create a summary to help the next session quickly understand the context.', + '', + '## Prioritize including', + '- Design decisions and technology choices made this session', + '- Bugs and problems solved', + '- Files changed or created, with a brief description of changes', + '- Unfinished tasks and work to continue in the next session', + '- Important context the next session needs to know', + '', + '## Conversation log', + conversation, + '', + '## Output format (Markdown only, no preamble)', + '', + '## Session Summary', + '', + '### Tasks', + '(main tasks worked on this session)', + '', + '### Decisions Made', + '(design decisions and technology choices)', + '', + '### Files Modified', + '(files changed or created)', + '', + '### Unresolved Issues', + '(unfinished tasks and work to continue)', + '', + '### Next Session Context', + '(important context for the next session)' + ].join('\n'); + + try { + const result = spawnSync('claude', ['--model', getLLMModel(), '-p'], { + input: prompt, + encoding: 'utf8', + env: { + ...process.env, + CLAUDECODE: '', + ECC_SKIP_LLM_SUMMARY: '1', + ECC_LLM_SUMMARY_SUBPROCESS: '1' + }, + timeout: LLM_TIMEOUT_MS, + shell: process.platform === 'win32' + }); + + if (result.error || result.status !== 0) { + return null; + } + + const output = (result.stdout || '').trim(); + return output || null; + } catch { + return null; + } +} + +module.exports = { generateSessionSummary, extractConversationText, getContextRemainingPct, getContextThreshold, getLLMModel }; diff --git a/github_code/affaan-m__ECC/scripts/lib/loopback-guard.js b/github_code/affaan-m__ECC/scripts/lib/loopback-guard.js new file mode 100644 index 0000000000000000000000000000000000000000..c56366ea35131d8afd3ab5362ec1c6eb5d7f5ec0 --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/loopback-guard.js @@ -0,0 +1,57 @@ +'use strict'; + +/** + * Host/Origin gating for ECC's loopback HTTP servers (control pane, plan + * canvas). DNS rebinding can point an attacker-controlled hostname at + * 127.0.0.1, so every request must present a Host header from this + * allowlist before the server does any work. + */ + +const LOOPBACK_HOSTNAMES = new Set(['127.0.0.1', 'localhost', '[::1]', '::1']); + +// Extract the hostname portion of an HTTP Host header value, stripping any +// port. Returns null when the header is missing or malformed. +function parseHostHeader(value) { + if (!value || typeof value !== 'string') return null; + const trimmed = value.trim(); + if (!trimmed) return null; + const match = trimmed.match(/^(\[[^\]]+\]|[^:]+)(?::(\d+))?$/); + if (!match) return null; + if (match[2] !== undefined) { + const port = Number(match[2]); + if (!Number.isInteger(port) || port > 65535) return null; + } + return match[1].toLowerCase(); +} + +function buildAllowedHostnames(configuredHost) { + const set = new Set(LOOPBACK_HOSTNAMES); + if (configuredHost) set.add(String(configuredHost).toLowerCase()); + return set; +} + +function isAllowedHostHeader(hostHeader, allowedHostnames) { + const hostname = parseHostHeader(hostHeader); + if (!hostname) return false; + return allowedHostnames.has(hostname); +} + +// Origin is absent on same-origin navigations and CLI clients; when present +// it must resolve to an allowed hostname. +function isAllowedOrigin(originHeader, allowedHostnames) { + if (!originHeader || typeof originHeader !== 'string') return true; + try { + const url = new URL(originHeader); + return allowedHostnames.has(url.hostname.toLowerCase()); + } catch { + return false; + } +} + +module.exports = { + LOOPBACK_HOSTNAMES, + buildAllowedHostnames, + isAllowedHostHeader, + isAllowedOrigin, + parseHostHeader +}; diff --git a/github_code/affaan-m__ECC/scripts/lib/mcp-config.js b/github_code/affaan-m__ECC/scripts/lib/mcp-config.js new file mode 100644 index 0000000000000000000000000000000000000000..bce45de0737fc35030e8493fcb4d089fee5fc3b3 --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/mcp-config.js @@ -0,0 +1,56 @@ +'use strict'; + +function parseDisabledMcpServers(value) { + return [...new Set( + String(value || '') + .split(',') + .map((entry) => entry.trim()) + .filter(Boolean) + )]; +} + +function filterMcpConfig(config, disabledServerNames = []) { + if (!config || typeof config !== 'object' || Array.isArray(config)) { + throw new Error('MCP config must be a JSON object'); + } + + const servers = config.mcpServers; + if (!servers || typeof servers !== 'object' || Array.isArray(servers)) { + throw new Error('MCP config must include an mcpServers object'); + } + + const disabled = new Set(parseDisabledMcpServers(disabledServerNames)); + if (disabled.size === 0) { + return { + config: { + ...config, + mcpServers: { ...servers }, + }, + removed: [], + }; + } + + const nextServers = {}; + const removed = []; + + for (const [name, serverConfig] of Object.entries(servers)) { + if (disabled.has(name)) { + removed.push(name); + continue; + } + nextServers[name] = serverConfig; + } + + return { + config: { + ...config, + mcpServers: nextServers, + }, + removed, + }; +} + +module.exports = { + filterMcpConfig, + parseDisabledMcpServers, +}; diff --git a/github_code/affaan-m__ECC/scripts/lib/mcp-inventory/canonical-mcp.js b/github_code/affaan-m__ECC/scripts/lib/mcp-inventory/canonical-mcp.js new file mode 100644 index 0000000000000000000000000000000000000000..80d22552048397460a1d0308f751a2b94e44deaa --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/mcp-inventory/canonical-mcp.js @@ -0,0 +1,284 @@ +'use strict'; + +const MCP_SCHEMA_VERSION = 'ecc.mcp.v1'; + +// Env keys whose values are almost always secrets. Used only to flag a server +// as carrying credentials; values are NEVER copied into the canonical record. +const SECRET_KEY_PATTERN = /(token|secret|key|password|passwd|auth|credential|api[_-]?key|access[_-]?key|private)/i; + +const REDACTED = '***'; + +// Known secret value prefixes (provider API keys) plus a high-entropy fallback. +const SECRET_VALUE_PATTERNS = [ + /^sk-[A-Za-z0-9_-]{16,}$/i, // OpenAI / Anthropic (sk-ant-...) + /^ghp_[A-Za-z0-9]{16,}$/, // GitHub PAT (classic) + /^github_pat_[A-Za-z0-9_]{16,}$/, // GitHub PAT (fine-grained) + /^gh[oprs]_[A-Za-z0-9]{16,}$/, // other GitHub tokens + /^sm_[A-Za-z0-9_-]{16,}$/, // Supermemory + /^AIza[A-Za-z0-9_-]{16,}$/, // Google API key + /^xox[baprs]-[A-Za-z0-9-]{10,}$/, // Slack + /^(pb|sk|pk|rk)_(live|test)_[A-Za-z0-9]{12,}$/i // Stripe / PostBridge-style +]; + +// A CLI flag whose following value is a secret (e.g. --modelApiKey sk-...). +const SECRET_FLAG_PATTERN = /(^|[-_])(api[-_]?key|apikey|token|secret|password|passwd|auth|credential|access[-_]?key|private[-_]?key)$/i; + +function looksLikeSecretValue(value) { + if (typeof value !== 'string') { + return false; + } + + if (SECRET_VALUE_PATTERNS.some(pattern => pattern.test(value))) { + return true; + } + + // High-entropy fallback: a long opaque token (letters AND digits, no path or + // package separators) is almost certainly a credential, not a flag value. + return value.length >= 32 + && /^[A-Za-z0-9_+/=.-]+$/.test(value) + && /[A-Za-z]/.test(value) + && /[0-9]/.test(value) + && !value.includes('/') + && !value.includes('@'); +} + +// Redact secret values from a command arg vector: any token that looks like a +// credential, or any token that immediately follows a secret-named flag. The +// flag names themselves are preserved so the command shape stays legible. +function redactArgs(args) { + const list = Array.isArray(args) ? args : []; + const result = []; + + for (let index = 0; index < list.length; index += 1) { + const current = list[index]; + if (typeof current !== 'string') { + continue; + } + + // Inline form: --flag=secret + const inlineMatch = current.match(/^(--?[A-Za-z0-9_-]+)=(.+)$/); + if (inlineMatch && (SECRET_FLAG_PATTERN.test(inlineMatch[1].replace(/^--?/, '')) || looksLikeSecretValue(inlineMatch[2]))) { + result.push(`${inlineMatch[1]}=${REDACTED}`); + continue; + } + + const previous = index > 0 ? list[index - 1] : null; + const followsSecretFlag = typeof previous === 'string' + && /^--?[A-Za-z0-9_-]+$/.test(previous) + && SECRET_FLAG_PATTERN.test(previous.replace(/^--?/, '')); + + if (followsSecretFlag || looksLikeSecretValue(current)) { + result.push(REDACTED); + continue; + } + + result.push(current); + } + + return result; +} + +// Redact embedded credentials in a server URL (userinfo + token query params). +function redactUrl(url) { + if (typeof url !== 'string' || url.length === 0) { + return url; + } + + let safe = url.replace(/\/\/[^/@]+@/, `//${REDACTED}@`); + safe = safe.replace(/([?&](?:token|key|api[_-]?key|access[_-]?token|secret)=)[^&]+/gi, `$1${REDACTED}`); + return safe; +} + +function isObject(value) { + return Boolean(value) && typeof value === 'object' && !Array.isArray(value); +} + +function asNonEmptyString(value) { + return typeof value === 'string' && value.trim().length > 0 ? value.trim() : null; +} + +function asStringArray(value) { + if (!Array.isArray(value)) { + return []; + } + + return value.filter(item => typeof item === 'string'); +} + +// Normalize a transport label across harnesses: +// Claude: type "stdio" | "http" | "sse" +// OpenCode: type "local" (stdio) | "remote" (http/sse) +// Codex: no type; presence of url => http, else stdio +function normalizeTransport(rawType, { url } = {}) { + const type = typeof rawType === 'string' ? rawType.toLowerCase() : ''; + + if (type === 'http' || type === 'streamable-http' || type === 'streamable_http') { + return 'http'; + } + + if (type === 'sse') { + return 'sse'; + } + + if (type === 'stdio' || type === 'local') { + return 'stdio'; + } + + if (type === 'remote') { + return url ? 'http' : 'stdio'; + } + + return url ? 'http' : 'stdio'; +} + +// Extract env KEY names only (never values). Flags whether any key looks secret. +function summarizeEnv(env) { + if (!isObject(env)) { + return { envKeys: [], hasSecrets: false }; + } + + const envKeys = Object.keys(env).sort(); + const hasSecrets = envKeys.some(key => SECRET_KEY_PATTERN.test(key)); + return { envKeys, hasSecrets }; +} + +// A stable identity for de-duplication across harnesses. Two server configs +// with the same transport + command + args + url collapse to one logical +// server even if their names differ slightly. +function buildSignature({ transport, command, args, url }) { + if (transport === 'http' || transport === 'sse') { + return `${transport}:${url || ''}`; + } + + const argString = asStringArray(args).join(' '); + return `stdio:${[command, argString].filter(Boolean).join(' ')}`.trim(); +} + +// Normalize a single raw server entry (from any reader) to ecc.mcp.v1 shape. +// rawServer fields the readers already pre-split: name, type, command, args, +// url, env, enabled, source { harness, scope, configPath }. +function normalizeServerEntry(rawServer) { + const name = asNonEmptyString(rawServer.name) || 'unknown'; + const command = asNonEmptyString(rawServer.command); + const rawUrl = asNonEmptyString(rawServer.url); + const rawArgs = asStringArray(rawServer.args); + const transport = normalizeTransport(rawServer.type, { url: rawUrl }); + const { envKeys, hasSecrets } = summarizeEnv(rawServer.env); + + // Secrets can hide in args (e.g. --modelApiKey sk-...) and URLs, not just + // env. Redact before anything is stored or hashed into the signature. + const args = redactArgs(rawArgs); + const url = redactUrl(rawUrl); + const argsCarrySecret = rawArgs.length !== args.length + || rawArgs.some((value, index) => value !== args[index]); + const urlCarriesSecret = rawUrl !== url; + + const source = isObject(rawServer.source) ? rawServer.source : {}; + + return { + name, + transport, + command: transport === 'stdio' ? command : null, + args: transport === 'stdio' ? args : [], + url: transport === 'stdio' ? null : url, + envKeys, + hasSecrets: hasSecrets || argsCarrySecret || urlCarriesSecret, + enabled: rawServer.enabled === false ? false : true, + signature: buildSignature({ transport, command, args, url }), + sources: [{ + harness: asNonEmptyString(source.harness) || 'unknown', + scope: asNonEmptyString(source.scope) || 'user', + configPath: asNonEmptyString(source.configPath) || null + }] + }; +} + +// Merge many per-harness server records into a deduplicated inventory keyed by +// logical server name. Records that share a name are merged; their sources are +// concatenated and their signatures compared for drift. +function mergeServers(serverRecords) { + const byName = new Map(); + + for (const record of serverRecords) { + const existing = byName.get(record.name); + if (!existing) { + byName.set(record.name, { + ...record, + signatures: [record.signature], + sources: [...record.sources] + }); + continue; + } + + existing.sources.push(...record.sources); + existing.signatures.push(record.signature); + existing.hasSecrets = existing.hasSecrets || record.hasSecrets; + // Union of env keys observed across harnesses. + existing.envKeys = Array.from(new Set([...existing.envKeys, ...record.envKeys])).sort(); + } + + return Array.from(byName.values()).map(server => { + const uniqueSignatures = Array.from(new Set(server.signatures)); + const { signatures: _signatures, ...rest } = server; + return { + ...rest, + harnessCount: server.sources.length, + consistent: uniqueSignatures.length <= 1 + }; + }); +} + +function buildFragmentation(mergedServers) { + return mergedServers + .filter(server => server.harnessCount > 1) + .map(server => ({ + name: server.name, + harnessCount: server.harnessCount, + harnesses: server.sources.map(source => source.harness), + consistent: server.consistent + })) + .sort((a, b) => b.harnessCount - a.harnessCount || a.name.localeCompare(b.name)); +} + +function buildInventory(serverRecords) { + const merged = mergeServers(serverRecords).sort((a, b) => a.name.localeCompare(b.name)); + const fragmentation = buildFragmentation(merged); + const harnesses = new Set(); + let serversWithSecrets = 0; + + for (const server of merged) { + server.sources.forEach(source => harnesses.add(source.harness)); + if (server.hasSecrets) { + serversWithSecrets += 1; + } + } + + return { + schemaVersion: MCP_SCHEMA_VERSION, + servers: merged, + fragmentation, + aggregates: { + serverCount: merged.length, + harnessCount: harnesses.size, + duplicateServerCount: fragmentation.length, + inconsistentServerCount: fragmentation.filter(item => !item.consistent).length, + serversWithSecrets + } + }; +} + +module.exports = { + MCP_SCHEMA_VERSION, + SECRET_KEY_PATTERN, + REDACTED, + looksLikeSecretValue, + redactArgs, + redactUrl, + normalizeTransport, + summarizeEnv, + buildSignature, + normalizeServerEntry, + mergeServers, + buildFragmentation, + buildInventory +}; diff --git a/github_code/affaan-m__ECC/scripts/lib/mcp-inventory/collect.js b/github_code/affaan-m__ECC/scripts/lib/mcp-inventory/collect.js new file mode 100644 index 0000000000000000000000000000000000000000..9d14f002b001bee8be09f3b8668eb047400dcb9e --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/mcp-inventory/collect.js @@ -0,0 +1,47 @@ +'use strict'; + +const { normalizeServerEntry, buildInventory } = require('./canonical-mcp'); +const { readClaudeCodeMcp } = require('./readers/claude-code'); +const { readCodexMcp } = require('./readers/codex'); +const { readOpencodeMcp } = require('./readers/opencode'); + +const DEFAULT_READERS = Object.freeze({ + 'claude-code': readClaudeCodeMcp, + codex: readCodexMcp, + opencode: readOpencodeMcp +}); + +// Collect MCP server configs from every harness reader, normalize each raw +// entry to ecc.mcp.v1, then merge into a single deduplicated inventory with a +// fragmentation report. Secrets are stripped during normalization (only env +// key names survive), so the returned inventory is safe to print or persist. +function collectMcpInventory(options = {}) { + const readers = options.readers || DEFAULT_READERS; + const readerOptions = options.readerOptions || {}; + + const rawRecords = []; + for (const [harness, reader] of Object.entries(readers)) { + if (typeof reader !== 'function') { + continue; + } + + let entries; + try { + entries = reader(readerOptions[harness] || readerOptions.shared || {}); + } catch { + entries = []; + } + + if (Array.isArray(entries)) { + rawRecords.push(...entries); + } + } + + const normalized = rawRecords.map(normalizeServerEntry); + return buildInventory(normalized); +} + +module.exports = { + collectMcpInventory, + DEFAULT_READERS +}; diff --git a/github_code/affaan-m__ECC/scripts/lib/mcp-inventory/readers/claude-code.js b/github_code/affaan-m__ECC/scripts/lib/mcp-inventory/readers/claude-code.js new file mode 100644 index 0000000000000000000000000000000000000000..9d903ca66e15158a679bad1d821feec7608ab1bc --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/mcp-inventory/readers/claude-code.js @@ -0,0 +1,73 @@ +'use strict'; + +const fs = require('fs'); +const os = require('os'); +const path = require('path'); + +// Claude Code stores MCP servers under "mcpServers" in ~/.claude.json (user +// scope) and in project-local .mcp.json files (project scope). Each entry: +// { type: "stdio"|"http"|"sse", command, args[], env{}, url } +function mapClaudeServer(name, raw, source) { + if (!raw || typeof raw !== 'object') { + return null; + } + + return { + name, + type: typeof raw.type === 'string' ? raw.type : (raw.url ? 'http' : 'stdio'), + command: raw.command || null, + args: Array.isArray(raw.args) ? raw.args : [], + url: raw.url || null, + env: raw.env && typeof raw.env === 'object' ? raw.env : {}, + enabled: raw.disabled === true ? false : true, + source + }; +} + +function readMcpServersBlock(filePath, scope) { + if (!fs.existsSync(filePath) || !fs.statSync(filePath).isFile()) { + return []; + } + + let parsed; + try { + parsed = JSON.parse(fs.readFileSync(filePath, 'utf8')); + } catch { + return []; + } + + const block = parsed && typeof parsed.mcpServers === 'object' && parsed.mcpServers + ? parsed.mcpServers + : {}; + + return Object.entries(block) + .map(([name, raw]) => mapClaudeServer(name, raw, { + harness: 'claude-code', + scope, + configPath: filePath + })) + .filter(Boolean); +} + +function readClaudeCodeMcp(options = {}) { + const homeDir = options.homeDir || os.homedir(); + const userConfig = options.userConfigPath || path.join(homeDir, '.claude.json'); + const projectConfigPaths = Array.isArray(options.projectConfigPaths) + ? options.projectConfigPaths + : []; + + const records = [ + ...readMcpServersBlock(userConfig, 'user') + ]; + + for (const projectPath of projectConfigPaths) { + records.push(...readMcpServersBlock(projectPath, 'project')); + } + + return records; +} + +module.exports = { + readClaudeCodeMcp, + mapClaudeServer +}; diff --git a/github_code/affaan-m__ECC/scripts/lib/mcp-inventory/readers/codex.js b/github_code/affaan-m__ECC/scripts/lib/mcp-inventory/readers/codex.js new file mode 100644 index 0000000000000000000000000000000000000000..84c9d3dda9cef8dabf5b2e3f61fa9fc2b3489b94 --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/mcp-inventory/readers/codex.js @@ -0,0 +1,82 @@ +'use strict'; + +const fs = require('fs'); +const os = require('os'); +const path = require('path'); + +// Codex stores MCP servers in ~/.codex/config.toml as TOML tables: +// [mcp_servers.NAME] +// command = "npx" +// args = ["-y", "pkg"] +// url = "https://..." # http transport +// [mcp_servers.NAME.env] # secret values live here +// [mcp_servers.NAME.http_headers] +// We parse with @iarna/toml when available and fall back to a minimal +// section parser so the reader degrades gracefully without the dependency. +function loadTomlParser(parseTomlImpl) { + if (typeof parseTomlImpl === 'function') { + return parseTomlImpl; + } + + try { + return require('@iarna/toml').parse; + } catch { + return null; + } +} + +function mapCodexServer(name, raw, configPath) { + if (!raw || typeof raw !== 'object') { + return null; + } + + const type = raw.url ? 'http' : 'stdio'; + return { + name, + type, + command: typeof raw.command === 'string' ? raw.command : null, + args: Array.isArray(raw.args) ? raw.args : [], + url: typeof raw.url === 'string' ? raw.url : null, + env: raw.env && typeof raw.env === 'object' ? raw.env : {}, + enabled: raw.enabled === false ? false : true, + source: { + harness: 'codex', + scope: 'user', + configPath + } + }; +} + +function readCodexMcp(options = {}) { + const homeDir = options.homeDir || os.homedir(); + const configPath = options.configPath || path.join(homeDir, '.codex', 'config.toml'); + + if (!fs.existsSync(configPath) || !fs.statSync(configPath).isFile()) { + return []; + } + + const parseToml = loadTomlParser(options.parseTomlImpl); + if (!parseToml) { + return []; + } + + let parsed; + try { + parsed = parseToml(fs.readFileSync(configPath, 'utf8')); + } catch { + return []; + } + + const block = parsed && typeof parsed.mcp_servers === 'object' && parsed.mcp_servers + ? parsed.mcp_servers + : {}; + + return Object.entries(block) + .map(([name, raw]) => mapCodexServer(name, raw, configPath)) + .filter(Boolean); +} + +module.exports = { + readCodexMcp, + mapCodexServer +}; diff --git a/github_code/affaan-m__ECC/scripts/lib/mcp-inventory/readers/opencode.js b/github_code/affaan-m__ECC/scripts/lib/mcp-inventory/readers/opencode.js new file mode 100644 index 0000000000000000000000000000000000000000..c19cd1f87331c61a101066d17e8f4bf88a872479 --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/mcp-inventory/readers/opencode.js @@ -0,0 +1,79 @@ +'use strict'; + +const fs = require('fs'); +const os = require('os'); +const path = require('path'); +const { resolveOpencodeConfigRoot } = require('../../opencode-paths'); +const { resolveInvocationEnvironment } = require('../../invocation-environment'); + +// OpenCode stores MCP servers under "mcp" in its resolved configuration root. +// Shape differs from Claude/Codex: +// { type: "local"|"remote", command: ["npx","-y","pkg"], environment: {}, +// enabled: bool, url: "https://..." } +// command is an ARRAY (binary + args combined); environment (not env) holds +// secrets; type "local" => stdio, "remote" => http/sse. +function mapOpencodeServer(name, raw, configPath) { + if (!raw || typeof raw !== 'object') { + return null; + } + + const commandArray = Array.isArray(raw.command) ? raw.command.filter(item => typeof item === 'string') : []; + const [command, ...args] = commandArray; + + return { + name, + type: typeof raw.type === 'string' ? raw.type : (raw.url ? 'remote' : 'local'), + command: command || (typeof raw.command === 'string' ? raw.command : null), + args: command ? args : (Array.isArray(raw.args) ? raw.args : []), + url: typeof raw.url === 'string' ? raw.url : null, + env: raw.environment && typeof raw.environment === 'object' + ? raw.environment + : (raw.env && typeof raw.env === 'object' ? raw.env : {}), + enabled: raw.enabled === false ? false : true, + source: { + harness: 'opencode', + scope: 'user', + configPath + } + }; +} + +function readOpencodeMcp(options = {}) { + const homeDir = options.homeDir || os.homedir(); + const configRoot = resolveOpencodeConfigRoot({ + homeDir, + env: resolveInvocationEnvironment(options), + }); + const candidatePaths = options.configPath + ? [options.configPath] + : [ + path.join(configRoot, 'opencode.json'), + path.join(configRoot, 'config.json'), + path.join(homeDir, '.opencode.json') + ]; + + const configPath = candidatePaths.find(candidate => fs.existsSync(candidate) && fs.statSync(candidate).isFile()); + if (!configPath) { + return []; + } + + let parsed; + try { + parsed = JSON.parse(fs.readFileSync(configPath, 'utf8')); + } catch { + return []; + } + + const block = parsed && typeof parsed.mcp === 'object' && parsed.mcp + ? parsed.mcp + : (parsed && typeof parsed.mcpServers === 'object' && parsed.mcpServers ? parsed.mcpServers : {}); + + return Object.entries(block) + .map(([name, raw]) => mapOpencodeServer(name, raw, configPath)) + .filter(Boolean); +} + +module.exports = { + readOpencodeMcp, + mapOpencodeServer +}; diff --git a/github_code/affaan-m__ECC/scripts/lib/memory-vault-format.js b/github_code/affaan-m__ECC/scripts/lib/memory-vault-format.js new file mode 100644 index 0000000000000000000000000000000000000000..006f32e30ea2c05ad1b86fc70473f8723854f406 --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/memory-vault-format.js @@ -0,0 +1,309 @@ +'use strict'; + +const { TextDecoder } = require('util'); + +const MEMORY_SCHEMA_VERSION = 'ecc.memory.v1'; +const MEMORY_KINDS = Object.freeze([ + 'context', + 'decision', + 'fact', + 'handoff', + 'lesson', + 'note', + 'preference', + 'runbook', +]); +const MEMORY_SCOPES = Object.freeze(['project', 'team', 'user']); +const MEMORY_TRUST_STATES = Object.freeze(['unreviewed']); +const MEMORY_STATUSES = Object.freeze(['active', 'rejected', 'superseded']); + +const MAX_BODY_BYTES = 64 * 1024; +const MAX_DOCUMENT_BYTES = 128 * 1024; +const MAX_TITLE_CHARS = 200; +const MAX_TAGS = 32; +const MAX_LINKS = 64; +const MAX_TARGETS = 32; + +const MEMORY_ID_PATTERN = /^mem_[a-z0-9][a-z0-9_-]{2,127}$/; +const SLUG_PATTERN = /^[a-z0-9][a-z0-9._-]{0,63}$/; +const ISO_TIMESTAMP_PATTERN = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{3}Z$/; + +const FRONTMATTER_FIELDS = Object.freeze([ + ['schema', 'schema'], + ['id', 'id'], + ['title', 'title'], + ['kind', 'kind'], + ['scope', 'scope'], + ['trust', 'trust'], + ['status', 'status'], + ['source_harness', 'sourceHarness'], + ['target_harnesses', 'targetHarnesses'], + ['tags', 'tags'], + ['links', 'links'], + ['created_at', 'createdAt'], + ['updated_at', 'updatedAt'], +]); +const FRONTMATTER_KEYS = new Map(FRONTMATTER_FIELDS); +const FATAL_UTF8_DECODER = new TextDecoder('utf-8', { fatal: true }); + +const SECRET_PATTERNS = Object.freeze([ + { label: 'provider API key', pattern: /\bsk-[A-Za-z0-9_-]{16,}\b/i }, + { label: 'Stripe key', pattern: /\b(?:sk|rk)_live_[A-Za-z0-9]{16,}\b/ }, + { label: 'npm token', pattern: /\bnpm_[A-Za-z0-9]{20,}\b/ }, + { label: 'Hugging Face token', pattern: /\bhf_[A-Za-z0-9]{20,}\b/ }, + { label: 'GitHub token', pattern: /\bgh[pors]_[A-Za-z0-9]{16,}\b/ }, + { label: 'GitHub token', pattern: /\bgithub_pat_[A-Za-z0-9_]{16,}\b/ }, + { label: 'Google API key', pattern: /\bAIza[A-Za-z0-9_-]{16,}\b/ }, + { label: 'Slack token', pattern: /\bxox[baprs]-[A-Za-z0-9-]{10,}\b/ }, + { label: 'AWS access key', pattern: /\b(?:AKIA|ASIA)[A-Z0-9]{16}\b/ }, + { label: 'private key', pattern: /-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----/ }, +]); + +function hasUnsafeControlCharacters(value, allowBodyWhitespace = false) { + return Array.from(value).some(character => { + const codePoint = character.codePointAt(0); + const allowedWhitespace = allowBodyWhitespace + && (codePoint === 0x09 || codePoint === 0x0a || codePoint === 0x0d); + const isControl = (codePoint <= 0x1f && !allowedWhitespace) + || (codePoint >= 0x7f && codePoint <= 0x9f); + const isBidirectionalFormatting = ( + (codePoint >= 0x202a && codePoint <= 0x202e) + || (codePoint >= 0x2066 && codePoint <= 0x2069) + ); + return isControl || isBidirectionalFormatting; + }); +} + +function asNonEmptyString(value, label, maxChars = 10_000) { + if (typeof value !== 'string' || value.trim().length === 0) { + throw new Error(`${label} must be a non-empty string.`); + } + const normalized = value.trim(); + if (normalized.length > maxChars) { + throw new Error(`${label} is too long (maximum ${maxChars} characters).`); + } + if (hasUnsafeControlCharacters(normalized)) { + throw new Error(`${label} must not contain control or bidirectional formatting characters.`); + } + return normalized; +} + +function validateEnum(value, allowed, label) { + const normalized = asNonEmptyString(value, label, 64); + if (!allowed.includes(normalized)) { + throw new Error(`${label} must be one of: ${allowed.join(', ')}.`); + } + return normalized; +} + +function validateSlug(value, label) { + const normalized = asNonEmptyString(value, label, 64); + if (!SLUG_PATTERN.test(normalized)) { + throw new Error(`${label} must be a lowercase letters/numbers slug.`); + } + return normalized; +} + +function validateMemoryId(value) { + const normalized = asNonEmptyString(value, 'memory id', 132); + if (!MEMORY_ID_PATTERN.test(normalized)) { + throw new Error('memory id must match mem_ and cannot contain a path.'); + } + return normalized; +} + +function uniqueStrings(values, { label, limit, validator }) { + if (!Array.isArray(values)) { + throw new Error(`${label} must be an array.`); + } + if (values.length > limit) { + throw new Error(`${label} has too many values (maximum ${limit}).`); + } + return values.reduce((result, value) => { + const normalized = validator(value); + if (result.includes(normalized)) { + throw new Error(`${label} must not contain duplicate values.`); + } + return [...result, normalized]; + }, []); +} + +function validateTimestamp(value, label) { + const normalized = asNonEmptyString(value, label, 64); + const parsed = new Date(normalized); + if ( + !ISO_TIMESTAMP_PATTERN.test(normalized) + || Number.isNaN(parsed.getTime()) + || parsed.toISOString() !== normalized + ) { + throw new Error(`${label} must be an ISO-8601 timestamp.`); + } + return normalized; +} + +function normalizeBody(value) { + if (typeof value !== 'string') { + throw new Error('memory body must be a string.'); + } + if (hasUnsafeControlCharacters(value, true)) { + throw new Error('memory body must not contain unsafe control or bidirectional formatting characters.'); + } + const normalized = value.trim(); + if (normalized.length === 0) { + throw new Error('memory body must contain non-whitespace context.'); + } + if (Buffer.byteLength(normalized, 'utf8') > MAX_BODY_BYTES) { + throw new Error(`memory body is too large (maximum ${MAX_BODY_BYTES} bytes).`); + } + return normalized; +} + +function normalizeMemory(memory) { + if (!memory || typeof memory !== 'object' || Array.isArray(memory)) { + throw new Error('memory must be an object.'); + } + + const targetHarnesses = uniqueStrings(memory.targetHarnesses, { + label: 'target harnesses', + limit: MAX_TARGETS, + validator: value => validateSlug(value, 'target harness'), + }); + if (targetHarnesses.length === 0) { + throw new Error('target harnesses must contain at least one harness or "all".'); + } + + if (memory.schema !== MEMORY_SCHEMA_VERSION) { + throw new Error('Unsupported memory schema.'); + } + + return { + schema: memory.schema, + id: validateMemoryId(memory.id), + title: asNonEmptyString(memory.title, 'memory title', MAX_TITLE_CHARS), + kind: validateEnum(memory.kind, MEMORY_KINDS, 'memory kind'), + scope: validateEnum(memory.scope, MEMORY_SCOPES, 'memory scope'), + trust: validateEnum(memory.trust, MEMORY_TRUST_STATES, 'memory trust'), + status: validateEnum(memory.status, MEMORY_STATUSES, 'memory status'), + sourceHarness: validateSlug(memory.sourceHarness, 'source harness'), + targetHarnesses, + tags: uniqueStrings(memory.tags, { + label: 'tags', + limit: MAX_TAGS, + validator: value => validateSlug(value, 'tag'), + }), + links: uniqueStrings(memory.links, { + label: 'links', + limit: MAX_LINKS, + validator: validateMemoryId, + }), + createdAt: validateTimestamp(memory.createdAt, 'created_at'), + updatedAt: validateTimestamp(memory.updatedAt, 'updated_at'), + body: normalizeBody(memory.body), + }; +} + +function serializeMemoryDocument(memory) { + const normalized = normalizeMemory(memory); + const metadata = FRONTMATTER_FIELDS.map(([serializedKey, objectKey]) => ( + `${serializedKey}: ${JSON.stringify(normalized[objectKey])}` + )).join('\n'); + const body = normalized.body.length > 0 ? `\n\n${normalized.body}` : ''; + return `---\n${metadata}\n---${body}\n`; +} + +function decodeUtf8(buffer, label = 'text') { + try { + return FATAL_UTF8_DECODER.decode(buffer); + } catch { + throw new Error(`${label} must contain valid UTF-8 text.`); + } +} + +function parseFrontmatterLine(line, sourcePath, seen) { + const separator = line.indexOf(':'); + if (separator <= 0) { + throw new Error(`Invalid memory frontmatter line in ${sourcePath}.`); + } + const serializedKey = line.slice(0, separator).trim(); + const objectKey = FRONTMATTER_KEYS.get(serializedKey); + if (!objectKey) { + throw new Error(`Unknown memory frontmatter field in ${sourcePath}.`); + } + if (seen.has(objectKey)) { + throw new Error(`Duplicate memory frontmatter field in ${sourcePath}.`); + } + const rawValue = line.slice(separator + 1).trim(); + try { + return { objectKey, value: JSON.parse(rawValue) }; + } catch { + throw new Error(`Memory frontmatter field in ${sourcePath} must use a JSON value.`); + } +} + +function parseMemoryDocument(source, sourcePath = '') { + const openingMarker = typeof source === 'string' + ? /^---\r?\n/.exec(source) + : null; + if (!openingMarker) { + throw new Error(`Memory document ${sourcePath} must start with --- frontmatter.`); + } + if (Buffer.byteLength(source, 'utf8') > MAX_DOCUMENT_BYTES) { + throw new Error(`Memory document ${sourcePath} is too large.`); + } + + const frontmatterStart = openingMarker[0].length; + const remainder = source.slice(frontmatterStart); + const closingMarker = /\r?\n---(?=\r?\n|$)/.exec(remainder); + if (!closingMarker) { + throw new Error(`Memory document ${sourcePath} has no closing frontmatter marker.`); + } + + const frontmatterSource = remainder.slice(0, closingMarker.index); + const parsed = frontmatterSource.split(/\r?\n/).reduce((state, line) => { + const next = parseFrontmatterLine(line, sourcePath, state.seen); + return { + values: { ...state.values, [next.objectKey]: next.value }, + seen: new Set([...state.seen, next.objectKey]), + }; + }, { values: {}, seen: new Set() }); + + const missing = FRONTMATTER_FIELDS + .map(([, objectKey]) => objectKey) + .filter(objectKey => !parsed.seen.has(objectKey)); + if (missing.length > 0) { + throw new Error(`Memory document ${sourcePath} is missing fields: ${missing.join(', ')}.`); + } + + const afterMarker = remainder.slice(closingMarker.index + closingMarker[0].length); + const body = afterMarker.replace(/^\r?\n/, '').replace(/\r?\n$/, ''); + return normalizeMemory({ ...parsed.values, body }); +} + +function findPotentialSecrets(value) { + const text = typeof value === 'string' ? value : ''; + return SECRET_PATTERNS + .filter(item => item.pattern.test(text)) + .map(item => item.label) + .filter((label, index, labels) => labels.indexOf(label) === index); +} + +module.exports = { + MAX_BODY_BYTES, + MAX_DOCUMENT_BYTES, + MEMORY_KINDS, + MEMORY_SCHEMA_VERSION, + MEMORY_SCOPES, + MEMORY_STATUSES, + MEMORY_TRUST_STATES, + asNonEmptyString, + decodeUtf8, + findPotentialSecrets, + hasUnsafeControlCharacters, + normalizeMemory, + parseMemoryDocument, + serializeMemoryDocument, + uniqueStrings, + validateEnum, + validateMemoryId, + validateSlug, +}; diff --git a/github_code/affaan-m__ECC/scripts/lib/memory-vault.js b/github_code/affaan-m__ECC/scripts/lib/memory-vault.js new file mode 100644 index 0000000000000000000000000000000000000000..cdf0f40896098f35b3c06bff604309af3bdfb459 --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/memory-vault.js @@ -0,0 +1,793 @@ +'use strict'; + +const crypto = require('crypto'); +const fs = require('fs'); +const os = require('os'); +const path = require('path'); + +const { assertWithinTrustedRoot, realpathNearestExisting } = require('./path-safety'); +const { + MAX_BODY_BYTES, + MAX_DOCUMENT_BYTES, + MEMORY_KINDS, + MEMORY_SCHEMA_VERSION, + MEMORY_SCOPES, + MEMORY_STATUSES, + MEMORY_TRUST_STATES, + asNonEmptyString, + decodeUtf8, + findPotentialSecrets, + hasUnsafeControlCharacters, + normalizeMemory, + parseMemoryDocument, + serializeMemoryDocument, + uniqueStrings, + validateEnum, + validateMemoryId, + validateSlug, +} = require('./memory-vault-format'); + +const DEFAULT_RECALL_SCOPES = Object.freeze(['project', 'team']); + +const MAX_FILES = 5000; +const MAX_SCAN_BYTES = 16 * 1024 * 1024; +const MAX_DIAGNOSTICS = 100; +const MAX_QUERY_CHARS = 500; +const MAX_RESULTS = 100; +const PROJECT_MEMORY_GITIGNORE = '*\n!.gitignore\n'; + +const VAULT_ROOT_BOUNDARIES = Symbol('vaultRootBoundaries'); + +function findNearestProjectRoot(cwd) { + let current = path.resolve(cwd); + while (true) { + if (fs.existsSync(path.join(current, '.git'))) { + return current; + } + const parent = path.dirname(current); + if (parent === current) { + return path.resolve(cwd); + } + current = parent; + } +} + +function resolveOverride(value, cwd) { + return path.resolve(cwd, asNonEmptyString(value, 'memory root override', 4096)); +} + +function resolveVaultRoots(options = {}) { + const cwd = path.resolve(options.cwd || process.cwd()); + const env = options.env || process.env; + const homeDir = path.resolve( + options.homeDir || env.HOME || env.USERPROFILE || os.homedir() + ); + const projectRoot = findNearestProjectRoot(cwd); + const projectVault = env.ECC_MEMORY_PROJECT_ROOT + ? resolveOverride(env.ECC_MEMORY_PROJECT_ROOT, cwd) + : path.join(projectRoot, '.ecc', 'memory'); + const userVault = env.ECC_MEMORY_USER_ROOT + ? resolveOverride(env.ECC_MEMORY_USER_ROOT, cwd) + : path.join(homeDir, '.ecc', 'memory'); + + const roots = { + project: path.join(projectVault, 'project'), + team: path.join(projectVault, 'team'), + user: userVault, + }; + Object.defineProperty(roots, VAULT_ROOT_BOUNDARIES, { + value: Object.freeze({ + project: env.ECC_MEMORY_PROJECT_ROOT + ? realpathNearestExisting(projectVault) + : projectRoot, + team: env.ECC_MEMORY_PROJECT_ROOT + ? realpathNearestExisting(projectVault) + : projectRoot, + user: env.ECC_MEMORY_USER_ROOT + ? realpathNearestExisting(userVault) + : homeDir, + }), + enumerable: false, + configurable: false, + writable: false, + }); + return Object.freeze(roots); +} + +function assertMemoryRootSafe(roots, scope) { + if (!roots || typeof roots !== 'object' || Array.isArray(roots)) { + throw new Error('Memory roots must include a trusted boundary policy.'); + } + const root = roots[scope]; + if (typeof root !== 'string' || root.length === 0) { + throw new Error(`No memory root is configured for scope "${scope}".`); + } + const boundary = roots[VAULT_ROOT_BOUNDARIES]?.[scope]; + if (typeof boundary !== 'string' || boundary.length === 0) { + throw new Error(`No trusted boundary policy is configured for memory scope "${scope}".`); + } + assertWithinTrustedRoot(root, boundary, 'access memory through a symlink'); + if (fs.existsSync(root) && fs.lstatSync(root).isSymbolicLink()) { + throw new Error(`Refusing to access memory through symlink root: ${root}`); + } + return root; +} + +function assertMemoryDirectorySafe(directory, root) { + assertWithinTrustedRoot(directory, root, 'access memory directory'); + if (fs.existsSync(directory) && fs.lstatSync(directory).isSymbolicLink()) { + throw new Error(`Refusing to access memory through symlink directory: ${directory}`); + } + return directory; +} + +function sameFileIdentity(left, right) { + // The inode is the primary identity signal and must always match. + if (left.ino !== right.ino) { + return false; + } + // libuv 1.49.0 through 1.50.x resolve path-based stat() and lstat() on Windows + // through GetFileInformationByName, which leaves the volume serial unset, while + // fstat() on an open handle reports it. Comparing the two then never matches and + // every vault read and write is rejected. libuv 82cdfb75f fixed this in 1.51.0, + // so only Node 22.12-22.16 and 24.0-24.1 are affected, but the guard should not + // depend on the runtime's patch level. Compare dev only when both sides report + // one; POSIX always does, so the original strict behaviour is preserved there. + if (!left.dev || !right.dev) { + return true; + } + return left.dev === right.dev; +} + +function readRegularTextFile(filePath, options = {}) { + const label = options.label || 'file'; + const maxBytes = options.maxBytes || MAX_DOCUMENT_BYTES; + if (options.trustedRoot) { + assertWithinTrustedRoot(filePath, options.trustedRoot, `read ${label}`); + } + + const flags = fs.constants.O_RDONLY + | (fs.constants.O_NOFOLLOW || 0) + | (fs.constants.O_NONBLOCK || 0); + const descriptor = fs.openSync(filePath, flags); + try { + const opened = fs.fstatSync(descriptor, { bigint: true }); + if (!opened.isFile()) { + throw new Error(`${label} must be a regular, non-symlink file.`); + } + const after = fs.lstatSync(filePath, { bigint: true }); + if ( + after.isSymbolicLink() + || !after.isFile() + || !sameFileIdentity(after, opened) + ) { + throw new Error(`${label} must remain a regular, non-symlink file while it is opened.`); + } + if (options.trustedRoot) { + assertWithinTrustedRoot(filePath, options.trustedRoot, `read ${label}`); + } + if (opened.size > BigInt(maxBytes)) { + throw new Error(`${label} is too large (${opened.size} bytes).`); + } + + const chunks = []; + let total = 0; + while (total <= maxBytes) { + const buffer = Buffer.alloc(Math.min(64 * 1024, maxBytes + 1 - total)); + const bytesRead = fs.readSync(descriptor, buffer, 0, buffer.length, null); + if (bytesRead === 0) break; + chunks.push(buffer.subarray(0, bytesRead)); + total += bytesRead; + } + if (total > maxBytes) { + throw new Error(`${label} is too large (maximum ${maxBytes} bytes).`); + } + return decodeUtf8(Buffer.concat(chunks, total), label); + } finally { + fs.closeSync(descriptor); + } +} + +function writeCreateOnlyTextFile(filePath, content, trustedRoot) { + assertWithinTrustedRoot(filePath, trustedRoot, 'write memory'); + const temporaryPath = path.join( + path.dirname(filePath), + `.ecc-memory-${process.pid}-${crypto.randomUUID()}.tmp` + ); + const flags = fs.constants.O_WRONLY + | fs.constants.O_CREAT + | fs.constants.O_EXCL + | (fs.constants.O_NOFOLLOW || 0); + let descriptor; + let operationError; + let cleanupError; + try { + descriptor = fs.openSync(temporaryPath, flags, 0o600); + const opened = fs.fstatSync(descriptor, { bigint: true }); + const after = fs.lstatSync(temporaryPath, { bigint: true }); + assertWithinTrustedRoot(temporaryPath, trustedRoot, 'write memory'); + if ( + !opened.isFile() + || after.isSymbolicLink() + || !after.isFile() + || !sameFileIdentity(after, opened) + ) { + throw new Error('Memory destination changed while it was being created.'); + } + fs.writeFileSync(descriptor, content, 'utf8'); + fs.fsyncSync(descriptor); + fs.closeSync(descriptor); + descriptor = undefined; + assertWithinTrustedRoot(filePath, trustedRoot, 'write memory'); + fs.linkSync(temporaryPath, filePath); + } catch (error) { + operationError = error; + } finally { + if (descriptor !== undefined) { + try { + fs.closeSync(descriptor); + } catch (error) { + cleanupError = error; + } + } + try { + fs.unlinkSync(temporaryPath); + } catch (error) { + if (!error || error.code !== 'ENOENT') cleanupError = cleanupError || error; + } + } + if (operationError) throw operationError; + if (cleanupError) throw cleanupError; +} + +function ensureProjectScopeIgnored(roots, scope) { + if (scope !== 'project') return; + const root = roots.project; + const ignorePath = path.join(root, '.gitignore'); + try { + writeCreateOnlyTextFile(ignorePath, PROJECT_MEMORY_GITIGNORE, root); + } catch (error) { + if (!error || error.code !== 'EEXIST') throw error; + const existing = readRegularTextFile(ignorePath, { + label: 'project memory .gitignore', + maxBytes: MAX_DOCUMENT_BYTES, + trustedRoot: root, + }); + if (existing !== PROJECT_MEMORY_GITIGNORE) { + throw new Error( + 'Project memory .gitignore does not contain the required fail-closed rules.' + ); + } + } +} + +function normalizeScopes(scopes = MEMORY_SCOPES) { + const values = Array.isArray(scopes) ? scopes : [scopes]; + return uniqueStrings(values, { + label: 'scopes', + limit: MEMORY_SCOPES.length, + validator: value => validateEnum(value, MEMORY_SCOPES, 'memory scope'), + }); +} + +function initializeVault(options = {}) { + const roots = options.roots || resolveVaultRoots(options); + const scopes = normalizeScopes(options.scopes || DEFAULT_RECALL_SCOPES); + const directories = scopes.flatMap(scope => { + const root = assertMemoryRootSafe(roots, scope); + fs.mkdirSync(root, { recursive: true, mode: 0o700 }); + ensureProjectScopeIgnored(roots, scope); + return MEMORY_KINDS.map(kind => { + const directory = path.join(root, `${kind}s`); + assertMemoryDirectorySafe(directory, root); + fs.mkdirSync(directory, { recursive: true, mode: 0o700 }); + return directory; + }); + }); + return { scopes, roots, directories }; +} + +function defaultMemoryId(now = new Date()) { + const day = now.toISOString().slice(0, 10).replace(/-/g, ''); + const random = crypto.randomUUID().replace(/-/g, '').slice(0, 20); + return `mem_${day}_${random}`; +} + +function normalizeSaveInput(input, options) { + const now = options.now ? options.now() : new Date().toISOString(); + const id = input.id || ( + options.idFactory ? options.idFactory() : defaultMemoryId(new Date(now)) + ); + return normalizeMemory({ + schema: MEMORY_SCHEMA_VERSION, + id, + title: input.title, + kind: input.kind || 'note', + scope: input.scope || 'project', + trust: 'unreviewed', + status: 'active', + sourceHarness: input.sourceHarness || 'unknown', + targetHarnesses: input.targetHarnesses || ['all'], + tags: input.tags || [], + links: input.links || [], + createdAt: now, + updatedAt: now, + body: input.body || '', + }); +} + +function saveMemory(input, options = {}) { + const roots = options.roots || resolveVaultRoots(options); + const memory = normalizeSaveInput(input || {}, options); + const secretKinds = findPotentialSecrets(JSON.stringify(memory)); + if (secretKinds.length > 0) { + throw new Error(`Refusing to save memory containing a suspected secret (${secretKinds.join(', ')}).`); + } + + const root = assertMemoryRootSafe(roots, memory.scope); + fs.mkdirSync(root, { recursive: true, mode: 0o700 }); + ensureProjectScopeIgnored(roots, memory.scope); + const directory = path.join(root, `${memory.kind}s`); + assertMemoryDirectorySafe(directory, root); + fs.mkdirSync(directory, { recursive: true, mode: 0o700 }); + const destination = path.join(directory, `${memory.id}.md`); + + try { + writeCreateOnlyTextFile(destination, serializeMemoryDocument(memory), root); + } catch (error) { + if (error && error.code === 'EEXIST') { + throw new Error(`Memory ${memory.id} already exists; writes are create-only.`); + } + throw error; + } + return { memory, path: destination }; +} + +function walkMemoryRoot(root, maxEntries = MAX_FILES) { + if (!root || !fs.existsSync(root)) { + return { + paths: [], + skippedSymlinks: [], + skippedSymlinkCount: 0, + truncated: false, + visitedCount: 0, + }; + } + + const paths = []; + const skippedSymlinks = []; + let skippedSymlinkCount = 0; + let visitedCount = 0; + let truncated = false; + + const walk = (directory, depth) => { + if (depth > 8 || visitedCount >= maxEntries) { + truncated = true; + return; + } + const handle = fs.opendirSync(directory); + const entries = []; + try { + while (entries.length < maxEntries - visitedCount) { + const entry = handle.readSync(); + if (!entry) break; + entries.push(entry); + } + if (handle.readSync() !== null) truncated = true; + } finally { + handle.closeSync(); + } + entries.sort((left, right) => left.name.localeCompare(right.name)); + for (const entry of entries) { + if (visitedCount >= maxEntries) { + truncated = true; + break; + } + visitedCount += 1; + const entryPath = path.join(directory, entry.name); + if (entry.isSymbolicLink()) { + skippedSymlinkCount += 1; + if (skippedSymlinks.length < MAX_DIAGNOSTICS) { + skippedSymlinks.push(entryPath); + } + continue; + } + if (entry.isDirectory() && !entry.name.startsWith('.')) { + walk(entryPath, depth + 1); + continue; + } + const include = entry.isFile() + && entry.name.endsWith('.md') + && !entry.name.startsWith('.'); + if (include) paths.push(entryPath); + } + }; + + walk(root, 0); + return { + paths, + skippedSymlinks, + skippedSymlinkCount, + truncated, + visitedCount, + }; +} + +function vaultRelativePath(scope, root, filePath) { + const relative = path.relative(root, filePath).split(path.sep).join('/'); + return `${scope}:${relative}`; +} + +function assertMemoryMatchesLocation(memory, scope, root, filePath) { + const [kindDirectory] = path.relative(root, filePath).split(path.sep); + if (memory.scope !== scope || kindDirectory !== `${memory.kind}s`) { + const error = new Error('Memory metadata does not match its vault location.'); + error.code = 'ECC_MEMORY_LOCATION_MISMATCH'; + throw error; + } +} + +function publicMemoryFileError(error) { + if (error?.code === 'ECC_MEMORY_SECRET') { + return { code: 'suspected-secret', message: 'Memory document was quarantined.' }; + } + if (error?.code === 'ECC_MEMORY_LOCATION_MISMATCH') { + return { + code: 'location-mismatch', + message: 'Memory metadata does not match its vault location.', + }; + } + return { + code: 'invalid-document', + message: 'Memory document is invalid or unreadable.', + }; +} + +function readMemoryFiles(options = {}) { + const roots = options.roots || resolveVaultRoots(options); + const scopes = normalizeScopes(options.scopes || DEFAULT_RECALL_SCOPES); + const entries = []; + const invalidFiles = []; + const skippedSymlinks = []; + let invalidFileCount = 0; + let skippedSymlinkCount = 0; + let visitedCount = 0; + let scannedBytes = 0; + let truncated = false; + + for (const scope of scopes) { + if (visitedCount >= MAX_FILES || scannedBytes >= MAX_SCAN_BYTES) { + truncated = true; + break; + } + const root = assertMemoryRootSafe(roots, scope); + const walked = walkMemoryRoot(root, MAX_FILES - visitedCount); + visitedCount += walked.visitedCount; + truncated = truncated || walked.truncated; + skippedSymlinkCount += walked.skippedSymlinkCount; + for (const skippedPath of walked.skippedSymlinks) { + if (skippedSymlinks.length >= MAX_DIAGNOSTICS) break; + skippedSymlinks.push(vaultRelativePath(scope, root, skippedPath)); + } + + for (const filePath of walked.paths) { + if (scannedBytes >= MAX_SCAN_BYTES) { + truncated = true; + break; + } + try { + const source = readRegularTextFile(filePath, { + label: 'memory document', + maxBytes: MAX_DOCUMENT_BYTES, + trustedRoot: root, + }); + const sourceBytes = Buffer.byteLength(source, 'utf8'); + if (scannedBytes + sourceBytes > MAX_SCAN_BYTES) { + truncated = true; + break; + } + scannedBytes += sourceBytes; + const memory = parseMemoryDocument(source, filePath); + assertMemoryMatchesLocation(memory, scope, root, filePath); + if (findPotentialSecrets(JSON.stringify(memory)).length > 0) { + const error = new Error('Memory contains a suspected secret.'); + error.code = 'ECC_MEMORY_SECRET'; + throw error; + } + entries.push({ + memory, + path: vaultRelativePath(scope, root, filePath), + }); + } catch (error) { + invalidFileCount += 1; + if (invalidFiles.length < MAX_DIAGNOSTICS) { + invalidFiles.push({ + path: vaultRelativePath(scope, root, filePath), + ...publicMemoryFileError(error), + }); + } + } + } + } + + return { + entries, + invalidFiles, + invalidFileCount, + skippedSymlinks, + skippedSymlinkCount, + scannedBytes, + truncated, + diagnosticsTruncated: invalidFileCount > invalidFiles.length + || skippedSymlinkCount > skippedSymlinks.length, + }; +} + +function tokenize(value) { + return String(value || '').toLowerCase().match(/[\p{L}\p{N}_-]+/gu) || []; +} + +function countOccurrences(haystack, needle) { + if (!needle) return 0; + let count = 0; + let offset = 0; + while (count < 8) { + const index = haystack.indexOf(needle, offset); + if (index < 0) break; + count += 1; + offset = index + needle.length; + } + return count; +} + +function scoreMemory(memory, query) { + const normalizedQuery = query.toLowerCase(); + const tokens = Array.from(new Set(tokenize(query))); + const title = memory.title.toLowerCase(); + const body = memory.body.toLowerCase(); + const tags = memory.tags.map(tag => tag.toLowerCase()); + const metadata = [ + memory.kind, + memory.scope, + memory.sourceHarness, + ...memory.targetHarnesses, + ].join(' ').toLowerCase(); + + const phraseScore = normalizedQuery && title.includes(normalizedQuery) + ? 20 + : normalizedQuery && body.includes(normalizedQuery) ? 5 : 0; + return tokens.reduce((score, token) => ( + score + + (title.includes(token) ? 8 : 0) + + (tags.includes(token) ? 6 : 0) + + (metadata.includes(token) ? 3 : 0) + + Math.min(countOccurrences(body, token), 5) + ), phraseScore); +} + +function buildExcerpt(body, query, maxChars = 240) { + const normalized = String(body || '').replace(/\s+/g, ' ').trim(); + if (normalized.length <= maxChars) return normalized; + const tokens = tokenize(query); + const lower = normalized.toLowerCase(); + const matchIndex = tokens.reduce((best, token) => { + const index = lower.indexOf(token); + if (index < 0) return best; + return best < 0 ? index : Math.min(best, index); + }, -1); + const start = Math.max(0, (matchIndex < 0 ? 0 : matchIndex) - 60); + const prefix = start > 0 ? '…' : ''; + const suffix = start + maxChars < normalized.length ? '…' : ''; + return `${prefix}${normalized.slice(start, start + maxChars)}${suffix}`; +} + +function summarizeMemory(memory) { + return Object.fromEntries( + Object.entries(memory).filter(([key]) => key !== 'body') + ); +} + +function searchMemories(query, options = {}) { + const normalizedQuery = typeof query === 'string' ? query.trim() : ''; + if (normalizedQuery.length > MAX_QUERY_CHARS) { + throw new Error(`memory search query is too long (maximum ${MAX_QUERY_CHARS} characters).`); + } + if (hasUnsafeControlCharacters(normalizedQuery)) { + throw new Error('memory search query must not contain control characters.'); + } + + const kinds = options.kinds + ? uniqueStrings(options.kinds, { + label: 'kinds', + limit: MEMORY_KINDS.length, + validator: value => validateEnum(value, MEMORY_KINDS, 'memory kind'), + }) + : null; + const trust = options.trust + ? validateEnum(options.trust, MEMORY_TRUST_STATES, 'memory trust') + : null; + const targetHarness = options.targetHarness + ? validateSlug(options.targetHarness, 'target harness') + : null; + const limit = Math.max(1, Math.min(Number(options.limit) || 20, MAX_RESULTS)); + const loaded = readMemoryFiles({ ...options, scopes: options.scopes || options.scope }); + + const results = loaded.entries + .filter(({ memory }) => memory.status === 'active') + .filter(({ memory }) => !kinds || kinds.includes(memory.kind)) + .filter(({ memory }) => !trust || memory.trust === trust) + .filter(({ memory }) => ( + !targetHarness + || memory.targetHarnesses.includes('all') + || memory.targetHarnesses.includes(targetHarness) + )) + .map(entry => ({ + ...entry, + score: normalizedQuery ? scoreMemory(entry.memory, normalizedQuery) : 0, + excerpt: buildExcerpt(entry.memory.body, normalizedQuery), + })) + .filter(result => normalizedQuery.length === 0 || result.score > 0) + .sort((left, right) => ( + right.score - left.score + || right.memory.updatedAt.localeCompare(left.memory.updatedAt) + || left.memory.id.localeCompare(right.memory.id) + )) + .slice(0, limit) + .map(result => ({ + memory: summarizeMemory(result.memory), + score: result.score, + excerpt: result.excerpt, + })); + + return { + results, + diagnostics: { + invalidFiles: loaded.invalidFiles, + invalidFileCount: loaded.invalidFileCount, + skippedSymlinks: loaded.skippedSymlinks, + skippedSymlinkCount: loaded.skippedSymlinkCount, + scannedBytes: loaded.scannedBytes, + truncated: loaded.truncated, + diagnosticsTruncated: loaded.diagnosticsTruncated, + }, + }; +} + +function readMemoryById(id, options = {}) { + const memoryId = validateMemoryId(id); + const targetHarness = options.targetHarness + ? validateSlug(options.targetHarness, 'target harness') + : null; + const loaded = readMemoryFiles(options); + const matches = loaded.entries + .filter(entry => entry.memory.id === memoryId) + .filter(entry => ( + !targetHarness + || entry.memory.targetHarnesses.includes('all') + || entry.memory.targetHarnesses.includes(targetHarness) + )); + if (matches.length === 0) { + throw new Error(`Memory ${memoryId} was not found.`); + } + if (matches.length > 1) { + throw new Error(`Memory ${memoryId} is duplicated in ${matches.length} files.`); + } + const allBacklinks = loaded.entries + .filter(entry => entry.memory.links.includes(memoryId)) + .filter(entry => entry.memory.status === 'active') + .map(entry => entry.memory) + .filter(memory => ( + !targetHarness + || memory.targetHarnesses.includes('all') + || memory.targetHarnesses.includes(targetHarness) + )) + .sort((left, right) => left.id.localeCompare(right.id)); + const backlinks = allBacklinks + .slice(0, MAX_RESULTS) + .map(summarizeMemory); + return { + ...matches[0], + backlinks, + backlinksTruncated: allBacklinks.length > backlinks.length, + }; +} + +function doctorMemoryVault(options = {}) { + const loaded = readMemoryFiles(options); + const targetHarness = options.targetHarness + ? validateSlug(options.targetHarness, 'target harness') + : null; + const visibleEntries = loaded.entries.filter(entry => ( + !targetHarness + || entry.memory.targetHarnesses.includes('all') + || entry.memory.targetHarnesses.includes(targetHarness) + )); + const byId = new Map(); + for (const entry of visibleEntries) { + const paths = byId.get(entry.memory.id) || []; + paths.push(entry.path); + byId.set(entry.memory.id, paths); + } + const allDuplicateIds = Array.from(byId.entries()) + .filter(([, paths]) => paths.length > 1) + .map(([id, paths]) => ({ id, paths })) + .sort((left, right) => left.id.localeCompare(right.id)); + const duplicateIds = allDuplicateIds.slice(0, MAX_DIAGNOSTICS); + const knownIds = new Set(byId.keys()); + const allBrokenLinks = []; + let brokenLinkCount = 0; + for (const entry of visibleEntries) { + for (const targetId of entry.memory.links) { + if (!knownIds.has(targetId)) { + brokenLinkCount += 1; + if (allBrokenLinks.length < MAX_DIAGNOSTICS) { + allBrokenLinks.push({ + sourceId: entry.memory.id, + targetId, + path: entry.path, + }); + } + } + } + } + const brokenLinks = [...allBrokenLinks] + .sort((left, right) => left.sourceId.localeCompare(right.sourceId)); + const ok = loaded.invalidFileCount === 0 + && allDuplicateIds.length === 0 + && brokenLinkCount === 0 + && loaded.skippedSymlinkCount === 0 + && !loaded.truncated; + + return { + schemaVersion: 'ecc.memory.doctor.v1', + ok, + memoryCount: visibleEntries.length, + invalidFiles: loaded.invalidFiles, + invalidFileCount: loaded.invalidFileCount, + duplicateIds, + duplicateIdCount: allDuplicateIds.length, + brokenLinks, + brokenLinkCount, + skippedSymlinks: loaded.skippedSymlinks, + skippedSymlinkCount: loaded.skippedSymlinkCount, + scannedBytes: loaded.scannedBytes, + truncated: loaded.truncated, + diagnosticsTruncated: loaded.diagnosticsTruncated + || allDuplicateIds.length > duplicateIds.length + || brokenLinkCount > brokenLinks.length, + }; +} + +module.exports = { + DEFAULT_RECALL_SCOPES, + MAX_BODY_BYTES, + MAX_DIAGNOSTICS, + MAX_DOCUMENT_BYTES, + MAX_FILES, + MAX_QUERY_CHARS, + MAX_RESULTS, + MAX_SCAN_BYTES, + MEMORY_KINDS, + MEMORY_SCHEMA_VERSION, + MEMORY_SCOPES, + MEMORY_STATUSES, + MEMORY_TRUST_STATES, + defaultMemoryId, + decodeUtf8, + doctorMemoryVault, + findPotentialSecrets, + findNearestProjectRoot, + initializeVault, + normalizeMemory, + parseMemoryDocument, + readRegularTextFile, + readMemoryById, + readMemoryFiles, + resolveVaultRoots, + sameFileIdentity, + saveMemory, + scoreMemory, + searchMemories, + serializeMemoryDocument, + tokenize, +}; diff --git a/github_code/affaan-m__ECC/scripts/lib/missing-dependency.js b/github_code/affaan-m__ECC/scripts/lib/missing-dependency.js new file mode 100644 index 0000000000000000000000000000000000000000..d75334714e8ff56a5ea4ecfa24c1ff2380ab1d55 --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/missing-dependency.js @@ -0,0 +1,65 @@ +'use strict'; + +const fs = require('fs'); +const path = require('path'); + +// Runtime dependencies that can be missing when ECC is installed via the +// Claude Code plugin marketplace (a plain git clone, so `npm install` never +// runs), even though the code that needs them is fine. Versions are read +// straight from package.json's "dependencies" field instead of a second +// hardcoded copy, so this can't silently drift out of sync with what's +// actually declared there. +const TRACKED_DEPENDENCIES = ['ajv', 'sql.js', 'js-yaml', '@iarna/toml']; + +function loadRuntimeDependencyVersions() { + try { + const packageJsonPath = path.join(__dirname, '..', '..', 'package.json'); + const declared = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8')).dependencies || {}; + + const versions = {}; + for (const name of TRACKED_DEPENDENCIES) { + const declaredVersion = declared[name]; + if (declaredVersion) { + versions[name] = declaredVersion.replace(/^[\^~]/, ''); + } + } + return versions; + } catch { + // package.json isn't reachable from here for some reason. Fall back to + // an empty map rather than crash — describeMissingDependencyError() + // just won't be able to suggest a pinned version in that case. + return {}; + } +} + +const RUNTIME_DEPENDENCY_VERSIONS = loadRuntimeDependencyVersions(); + +function describeMissingDependencyError(error) { + if (!error || error.code !== 'MODULE_NOT_FOUND') { + return null; + } + + const match = /Cannot find module '([^']+)'/.exec(error.message || ''); + const moduleName = match && match[1]; + + if (!moduleName || !TRACKED_DEPENDENCIES.includes(moduleName)) { + return null; + } + + const pinnedVersion = RUNTIME_DEPENDENCY_VERSIONS[moduleName]; + const installCommand = pinnedVersion + ? `npm install --no-save ${moduleName}@${pinnedVersion}` + : `npm install --no-save ${moduleName}`; + + return ( + `Missing dependency '${moduleName}'. ECC's production dependencies aren't installed ` + + '(this happens when ECC was installed via the Claude Code plugin marketplace, which ' + + 'clones the repo but never runs npm install). Run "npm install" from the ECC repo ' + + `root, or install just this package with "${installCommand}".` + ); +} + +module.exports = { + RUNTIME_DEPENDENCY_VERSIONS, + describeMissingDependencyError, +}; diff --git a/github_code/affaan-m__ECC/scripts/lib/multi-harness-setup.js b/github_code/affaan-m__ECC/scripts/lib/multi-harness-setup.js new file mode 100644 index 0000000000000000000000000000000000000000..141eb42066720d3fb94459b369e9771dfdd18bcc --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/multi-harness-setup.js @@ -0,0 +1,530 @@ +'use strict'; + +const fs = require('fs'); +const crypto = require('crypto'); +const os = require('os'); +const path = require('path'); + +const { assertSafeInstallOperation } = require('./install/apply'); +const { assertWithinTrustedRoot, realpathNearestExisting } = require('./path-safety'); + +const VALID_CLAUDE_SCOPES = new Set(['user', 'project', 'local']); +const VALID_CLAUDE_HOOKS = new Set(['off', 'minimal', 'standard', 'strict']); +const VALID_PROFILES = new Set(['minimal', 'core', 'developer', 'security', 'research', 'full']); + +function catalogHelpers() { + return require('./harness-capabilities'); +} + +function normalizeGuidedInstallRequest(input = {}) { + const { normalizeHarnessSelection } = catalogHelpers(); + const harnesses = normalizeHarnessSelection(input.harnesses || []); + if (harnesses.length === 0) { + throw new Error('Choose at least one guided harness: Claude, Codex, or Kimi.'); + } + + const includesClaude = harnesses.includes('claude'); + const includesKimi = harnesses.includes('kimi'); + if (!includesClaude && (input.claudeScope !== undefined || input.claudeHooks !== undefined)) { + throw new Error('Claude scope and hook options require Claude to be selected.'); + } + if (!includesKimi && input.profile !== undefined) { + throw new Error('The managed install profile requires Kimi to be selected.'); + } + + const claudeScope = includesClaude ? (input.claudeScope || 'user') : undefined; + const claudeHooks = includesClaude ? (input.claudeHooks || 'standard') : undefined; + const profile = includesKimi ? (input.profile || 'core') : undefined; + if (claudeScope && !VALID_CLAUDE_SCOPES.has(claudeScope)) { + throw new Error(`Invalid Claude scope: ${claudeScope}`); + } + if (claudeHooks && !VALID_CLAUDE_HOOKS.has(claudeHooks)) { + throw new Error(`Invalid Claude hooks preference: ${claudeHooks}`); + } + if (profile && !VALID_PROFILES.has(profile)) { + throw new Error(`Invalid Kimi install profile: ${profile}`); + } + + return { + harnesses, + ...(claudeHooks ? { claudeHooks } : {}), + ...(claudeScope ? { claudeScope } : {}), + dryRun: Boolean(input.dryRun), + json: Boolean(input.json), + ...(profile ? { profile } : {}), + yes: Boolean(input.yes), + }; +} + +function canonicalPath(filePath) { + return realpathNearestExisting(filePath); +} + +function pathsMatch(left, right) { + return canonicalPath(left) === canonicalPath(right); +} + +function sameFileIdentity(left, right) { + return left.dev === right.dev + && left.ino === right.ino + && left.size === right.size + && left.mtimeMs === right.mtimeMs + && left.ctimeMs === right.ctimeMs; +} + +function readRegularFileSnapshot(filePath) { + const flags = fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW || 0); + let descriptor; + try { + descriptor = fs.openSync(filePath, flags); + } catch (error) { + if (error && (error.code === 'ENOENT' || error.code === 'ENOTDIR')) return null; + throw error; + } + + try { + const before = fs.fstatSync(descriptor); + if (!before.isFile()) { + throw new Error(`Refusing to read a non-file at ${filePath}.`); + } + const content = fs.readFileSync(descriptor); + const after = fs.fstatSync(descriptor); + const finalPathStat = fs.lstatSync(filePath); + if ( + finalPathStat.isSymbolicLink() + || !finalPathStat.isFile() + || !sameFileIdentity(before, after) + || !sameFileIdentity(after, finalPathStat) + ) { + throw new Error(`Refusing to read a file that changed during validation: ${filePath}.`); + } + return { content, stat: after }; + } finally { + fs.closeSync(descriptor); + } +} + +function fingerprintFile(filePath) { + const snapshot = readRegularFileSnapshot(filePath); + if (!snapshot) return { exists: false, sha256: null }; + return { + exists: true, + sha256: crypto.createHash('sha256').update(snapshot.content).digest('hex'), + }; +} + +function fingerprintInstallStateValue(state) { + const content = Buffer.from(`${JSON.stringify(state, null, 2)}\n`); + return { + exists: true, + sha256: crypto.createHash('sha256').update(content).digest('hex'), + }; +} + +function operationIdentityMatches(stateOperation, plannedOperation) { + return [ + 'kind', + 'moduleId', + 'sourceRelativePath', + 'strategy', + 'scaffoldOnly', + ].every(field => stateOperation[field] === plannedOperation[field]); +} + +function assertInstallStateUnchanged(plan, expectedFingerprint) { + const currentFingerprint = fingerprintFile(plan.installStatePath); + if ( + currentFingerprint.exists !== expectedFingerprint.exists + || currentFingerprint.sha256 !== expectedFingerprint.sha256 + ) { + throw new Error( + `Refusing to overwrite an unowned or changed install-state at ${plan.installStatePath}. ` + + 'Re-run the guided preview and review the existing state before retrying.' + ); + } +} + +function assertPriorInstallStateMatchesPlan(state, plan) { + const target = state.target || {}; + const adapter = plan.adapter || {}; + if ( + target.id !== adapter.id + || target.target !== adapter.target + || target.kind !== adapter.kind + ) { + throw new Error( + `Refusing to trust managed install-state at ${plan.installStatePath}: ` + + 'target identity does not match the current Kimi install plan.' + ); + } + if (!pathsMatch(target.root, plan.targetRoot)) { + throw new Error( + `Refusing to trust managed install-state at ${plan.installStatePath}: ` + + 'recorded root does not match the current install root.' + ); + } + if (!pathsMatch(target.installStatePath, plan.installStatePath)) { + throw new Error( + `Refusing to trust managed install-state at ${plan.installStatePath}: ` + + 'recorded install-state path does not match the current install-state path.' + ); + } +} + +function readOwnedDestinations(plan, dependencies) { + if (!plan.installStatePath) { + return { destinations: new Set(), stateFingerprint: { exists: false, sha256: null } }; + } + try { + assertSafeInstallOperation(plan, { destinationPath: plan.installStatePath }); + } catch (error) { + throw new Error(`Refusing to trust managed install-state path: ${error.message}`); + } + const initialFingerprint = fingerprintFile(plan.installStatePath); + if (!initialFingerprint.exists) { + return { destinations: new Set(), stateFingerprint: { exists: false, sha256: null } }; + } + const readState = dependencies.readInstallState || require('./install-state').readInstallState; + const state = readState(plan.installStatePath); + const validatedFingerprint = fingerprintFile(plan.installStatePath); + if ( + initialFingerprint.exists !== validatedFingerprint.exists + || initialFingerprint.sha256 !== validatedFingerprint.sha256 + ) { + throw new Error( + `Refusing to trust install-state that changed during validation: ${plan.installStatePath}.` + ); + } + assertPriorInstallStateMatchesPlan(state, plan); + const plannedByDestination = new Map(plan.operations.map(operation => [ + canonicalPath(operation.destinationPath), + operation, + ])); + const destinations = new Set(); + for (const operation of state.operations || []) { + if (operation.ownership !== 'managed') { + throw new Error( + `Refusing to trust non-managed ownership from install-state at ${plan.installStatePath}.` + ); + } + const destinationPath = operation.destinationPath; + assertWithinTrustedRoot(destinationPath, plan.targetRoot, 'trust install-state ownership'); + const canonicalDestination = canonicalPath(destinationPath); + const plannedOperation = plannedByDestination.get(canonicalDestination); + if (!plannedOperation) continue; + if (!operationIdentityMatches(operation, plannedOperation)) { + throw new Error( + `Refusing unverified ownership from install-state at ${plan.installStatePath}: ` + + `operation identity does not match the current plan for ${destinationPath}.` + ); + } + const currentFingerprint = fingerprintFile(destinationPath); + if ( + !currentFingerprint.exists + || !/^[a-f0-9]{64}$/i.test(operation.contentSha256 || '') + || currentFingerprint.sha256 !== operation.contentSha256.toLowerCase() + ) { + throw new Error( + `Refusing unverified ownership from install-state at ${plan.installStatePath}: ` + + `content digest does not match ${destinationPath}.` + ); + } + destinations.add(canonicalDestination); + } + return { destinations, stateFingerprint: validatedFingerprint }; +} + +function assertMergeDestination(destinationPath, existingSnapshot = null) { + const snapshot = existingSnapshot || readRegularFileSnapshot(destinationPath); + if (!snapshot) return null; + let current; + try { + current = JSON.parse(snapshot.content.toString('utf8')); + } catch (error) { + throw new Error(`Cannot merge ECC configuration into invalid JSON at ${destinationPath}: ${error.message}`); + } + if (!current || typeof current !== 'object' || Array.isArray(current)) { + throw new Error(`Cannot merge ECC configuration at ${destinationPath}: expected a JSON object.`); + } + return current; +} + +function isPlainObject(value) { + return Boolean(value) && typeof value === 'object' && !Array.isArray(value); +} + +function findJsonConflicts(current, patch, prefix = '') { + if (!isPlainObject(patch)) return []; + return Object.entries(patch).flatMap(([key, patchValue]) => { + if (!Object.prototype.hasOwnProperty.call(current, key)) return []; + const currentValue = current[key]; + const field = prefix ? `${prefix}.${key}` : key; + if (isPlainObject(currentValue) && isPlainObject(patchValue)) { + return findJsonConflicts(currentValue, patchValue, field); + } + return JSON.stringify(currentValue) === JSON.stringify(patchValue) ? [] : [field]; + }); +} + +function classifyManagedOperation(operation, ownedDestinations) { + const destinationPath = operation.destinationPath; + const destination = readRegularFileSnapshot(destinationPath); + if (!destination) return 'create'; + const canonicalDestination = canonicalPath(destinationPath); + if (operation.kind === 'merge-json') { + const current = assertMergeDestination(destinationPath, destination); + if (ownedDestinations.has(canonicalDestination)) return 'managed-json-update'; + const conflicts = findJsonConflicts(current, operation.mergePayload); + if (conflicts.length > 0) { + throw new Error( + `Refusing to overwrite unowned JSON fields at ${destinationPath}: ${conflicts.join(', ')}` + ); + } + return 'json-merge'; + } + if (ownedDestinations.has(canonicalDestination)) return 'managed-update'; + if ( + operation.kind === 'copy-file' + && typeof operation.sourcePath === 'string' + && readRegularFileSnapshot(operation.sourcePath)?.content.equals(destination.content) + ) { + return 'identical'; + } + throw new Error(`Refusing to replace unowned existing file: ${destinationPath}`); +} + +function writableRequirement(destinationPath) { + if (fs.existsSync(destinationPath)) { + const mode = fs.statSync(destinationPath).isDirectory() + ? fs.constants.W_OK | fs.constants.X_OK + : fs.constants.W_OK; + return { candidatePath: destinationPath, mode }; + } + + let candidatePath = path.dirname(destinationPath); + while (!fs.existsSync(candidatePath)) { + const parentPath = path.dirname(candidatePath); + if (parentPath === candidatePath) break; + candidatePath = parentPath; + } + return { + candidatePath, + mode: fs.constants.W_OK | fs.constants.X_OK, + }; +} + +function assertManagedDestinationsWritable(plan, dependencies) { + const accessSync = dependencies.accessSync || fs.accessSync; + const destinationPaths = [ + ...plan.operations.map(operation => operation.destinationPath), + ...(plan.installStatePath ? [plan.installStatePath] : []), + ]; + const requirements = new Map(); + + for (const destinationPath of destinationPaths) { + const requirement = writableRequirement(destinationPath); + const existingMode = requirements.get(requirement.candidatePath) || 0; + requirements.set(requirement.candidatePath, existingMode | requirement.mode); + } + + for (const [candidatePath, mode] of requirements) { + try { + accessSync(candidatePath, mode); + } catch (_error) { + const label = plan.target === 'kimi' ? 'Kimi' : 'Managed install'; + throw new Error( + `${label} destination is not writable by the current user: ${candidatePath}. ` + + 'Fix the project ownership or permissions, then retry.' + ); + } + } +} + +function preflightManagedPlan(plan, dependencies = {}) { + if (!plan || !Array.isArray(plan.operations)) { + throw new Error('A managed install plan with operations is required.'); + } + if (typeof plan.installStatePath !== 'string' || plan.installStatePath.length === 0) { + throw new Error('A managed install-state path is required before preflight.'); + } + const ownership = readOwnedDestinations(plan, dependencies); + const operations = plan.operations.map(operation => { + assertSafeInstallOperation(plan, operation); + return { + destinationPath: operation.destinationPath, + kind: operation.kind, + classification: classifyManagedOperation(operation, ownership.destinations), + }; + }); + assertManagedDestinationsWritable(plan, dependencies); + return { + plan, + operations, + ownershipSnapshot: { + destinations: [...ownership.destinations], + stateFingerprint: ownership.stateFingerprint, + }, + }; +} + +async function applyPreflightedManagedPlan(entry) { + const preview = entry.preview && entry.preview.ownershipSnapshot + ? entry.preview + : preflightManagedPlan(entry.preview.plan); + const ownedDestinations = new Set(preview.ownershipSnapshot.destinations); + let expectedStateFingerprint = preview.ownershipSnapshot.stateFingerprint; + // Several ordered JSON merges may share one destination. Preserve each + // operation's preview instead of collapsing that sequence to one path entry. + const expectedOperations = new Map(preview.plan.operations.map((operation, index) => [ + operation, preview.operations[index], + ])); + const writtenDestinations = new Set(); + const assertStateUnchanged = () => ( + assertInstallStateUnchanged(preview.plan, expectedStateFingerprint) + ); + const prepareInstallStateWrite = ({ state }) => { + assertStateUnchanged(); + expectedStateFingerprint = fingerprintInstallStateValue(state); + }; + const assertOperationUnchanged = operation => { + const destination = canonicalPath(operation.destinationPath); + const expected = expectedOperations.get(operation); + const currentClassification = classifyManagedOperation(operation, ownedDestinations); + const expectedClassification = operation.kind === 'merge-json' + && writtenDestinations.has(destination) + ? 'managed-json-update' + : expected && expected.classification; + if ( + !expected + || expected.kind !== operation.kind + || canonicalPath(expected.destinationPath) !== destination + || expectedClassification !== currentClassification + ) { + throw new Error( + `Refusing to write ${operation.destinationPath}: destination changed after Kimi preflight.` + ); + } + return destination; + }; + + const result = require('./install-executor').applyInstallPlan(preview.plan, { + beforeInstallStateRead() { + assertStateUnchanged(); + // Check the original preview before ownership filtering can skip a late + // collision. Guided setup must report the changed plan as a failure. + for (const operation of preview.plan.operations) { + assertOperationUnchanged(operation); + } + }, + beforeOperationWrite({ operation }) { + assertStateUnchanged(); + const destination = assertOperationUnchanged(operation); + ownedDestinations.add(destination); + writtenDestinations.add(destination); + }, + beforeInstallStateWrite: prepareInstallStateWrite, + }); + const { projectCanonicalInstallState } = require('./install-state-store-sync'); + const installStateProjection = await projectCanonicalInstallState(result.statePreview); + return { + ...result, + installStateProjection, + warnings: installStateProjection.warning + ? [...result.warnings, `Install health projection warning: ${installStateProjection.warning.message}`] + : result.warnings, + }; +} + +function defaultDependencies(options = {}) { + return { + previewClaude: request => require('../setup').reconcileClaudePlugin( + { dryRun: true, hooks: request.claudeHooks, scope: request.claudeScope } + ), + previewCodex: () => require('./codex-plugin-setup').reconcileCodexPlugin({ dryRun: true }), + createManagedPlan: request => require('./install/runtime').createInstallPlanFromRequest( + require('./install/request').normalizeInstallRequest({ + profileId: request.profile, + target: 'kimi', + }), + { + homeDir: options.homeDir || process.env.HOME || os.homedir(), + projectRoot: options.projectRoot || process.cwd(), + sourceRoot: options.sourceRoot, + } + ), + preflightManaged: preflightManagedPlan, + applyClaude: request => require('../setup').reconcileClaudePlugin( + { dryRun: false, hooks: request.claudeHooks, scope: request.claudeScope } + ), + applyCodex: () => require('./codex-plugin-setup').reconcileCodexPlugin({ dryRun: false }), + applyManaged: applyPreflightedManagedPlan, + }; +} + +async function createMultiHarnessPlan(request, injected = {}, options = {}) { + const dependencies = { ...defaultDependencies(options), ...injected }; + let entries = []; + for (const id of request.harnesses) { + if (id === 'claude') { + entries = [...entries, { id, channel: 'native-plugin', preview: await dependencies.previewClaude(request) }]; + } else if (id === 'codex') { + entries = [...entries, { id, channel: 'native-plugin', preview: await dependencies.previewCodex(request) }]; + } else if (id === 'kimi') { + const managedPlan = await dependencies.createManagedPlan(request); + entries = [...entries, { + id, + channel: 'managed-project', + preview: await dependencies.preflightManaged(managedPlan), + }]; + } else { + throw new Error(`Unsupported guided harness: ${id}`); + } + } + return { harnesses: entries, request }; +} + +async function applyMultiHarnessPlan(plan, injected = {}, options = {}) { + const dependencies = { ...defaultDependencies(options), ...injected }; + if (plan.request.dryRun) { + return { status: 'preview', completed: [], retryHarnesses: [...plan.request.harnesses] }; + } + + let completed = []; + for (let index = 0; index < plan.harnesses.length; index += 1) { + const entry = plan.harnesses[index]; + try { + let result; + if (entry.id === 'claude') result = await dependencies.applyClaude(plan.request, entry); + else if (entry.id === 'codex') result = await dependencies.applyCodex(plan.request, entry); + else if (entry.preview && entry.preview.plan) { + const latestPreview = dependencies.preflightManaged(entry.preview.plan); + result = await dependencies.applyManaged( + { ...entry, preview: latestPreview }, + plan.request + ); + } else { + result = await dependencies.applyManaged(entry, plan.request); + } + completed = [...completed, { id: entry.id, result }]; + } catch (error) { + return { + status: completed.length > 0 ? 'partial' : 'failed', + completed, + failure: { id: entry.id, message: error.message }, + retryHarnesses: plan.harnesses.slice(index).map(item => item.id), + }; + } + } + return { status: 'complete', completed, retryHarnesses: [] }; +} + +module.exports = { + VALID_CLAUDE_HOOKS, + VALID_CLAUDE_SCOPES, + VALID_PROFILES, + applyMultiHarnessPlan, + createMultiHarnessPlan, + normalizeGuidedInstallRequest, + preflightManagedPlan, + findJsonConflicts, +}; diff --git a/github_code/affaan-m__ECC/scripts/lib/nasiko-release.js b/github_code/affaan-m__ECC/scripts/lib/nasiko-release.js new file mode 100644 index 0000000000000000000000000000000000000000..6e5391768084e58409677f322c682d599371998d --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/nasiko-release.js @@ -0,0 +1,473 @@ +'use strict'; + +const crypto = require('crypto'); +const fs = require('fs'); +const https = require('https'); +const os = require('os'); +const path = require('path'); +const zlib = require('zlib'); + +const REGISTRY_ORIGIN = 'https://registry.nasiko.dev'; +const REPOSITORY = 'nasiko/nasiko'; +const SOURCE_URL = 'https://github.com/Nasiko-Labs/nasiko'; +const LICENSE = 'Apache-2.0'; +const METADATA_FILENAME = '.ecc-nasiko-install.json'; +const MAX_MANIFEST_BYTES = 1024 * 1024; +const MAX_ARCHIVE_BYTES = 100 * 1024 * 1024; +const MAX_BINARY_BYTES = 64 * 1024 * 1024; +const MAX_METADATA_BYTES = 64 * 1024; +const SHA256_PATTERN = /^sha256:[a-f0-9]{64}$/; + +const QUALIFIED_RELEASES = Object.freeze({ + 'v0.1.0': Object.freeze({ + 'linux/amd64': Object.freeze({ manifestDigest: 'sha256:0df748a40f3d714b6b6a3376a1d13a224c05bdb8d1628f31ace5a7bee8ceb9de', binaryDigest: 'sha256:94a2bcab2d3832257e0111480bb7c3dcac81d63a7ae9bac53206a92c0957ee0f' }), + 'linux/arm64': Object.freeze({ manifestDigest: 'sha256:655021a129c7df4621a80d16ea4eab38018530bfe9a20da646641d9f4ac5c249', binaryDigest: 'sha256:85f9fa5cfbed6c276fce6df2d71e9d0c66d7d8e8d46a40297464833d38db7a7e' }), + 'darwin/amd64': Object.freeze({ manifestDigest: 'sha256:b4188482621efd7da5a2ab630f653665ab5f80b9aceae448b6bb5fc93e003f06', binaryDigest: 'sha256:ed6232e0bb96a2dcfd86d3c25f86021091600d52f09250403a54528bfe8100a3' }), + 'darwin/arm64': Object.freeze({ manifestDigest: 'sha256:ce7e54fa19f989a5d125c4409b3587ca9503bb5a07bc5ff223c60e0fbad437f0', binaryDigest: 'sha256:3c60f862b04eea1b9a633593b39f1a443d9ca2123cf3edfd150d313e95f3894b' }), + 'windows/amd64': Object.freeze({ manifestDigest: 'sha256:0760fe1fc98e8fedb66796aaf891a1de9268af1338c5e88b949656fda5d9f045', binaryDigest: 'sha256:0f57672d24fc3c70e4cbbf22864e65b35b9978ddaae3793803841536e682929b' }), + }), +}); + +function normalizePlatform(platform = process.platform, architecture = process.arch) { + const osName = platform === 'win32' ? 'windows' : platform; + if (!['linux', 'darwin', 'windows'].includes(osName)) throw new Error(`Unsupported platform: ${platform}`); + const arch = architecture === 'x64' ? 'amd64' : architecture; + if (!['amd64', 'arm64'].includes(arch)) throw new Error(`Unsupported architecture: ${architecture}`); + if (osName === 'windows' && arch !== 'amd64') throw new Error(`Unsupported architecture for Windows: ${architecture}`); + return { os: osName, arch, binaryName: osName === 'windows' ? 'nasiko.exe' : 'nasiko' }; +} + +function getQualifiedRelease(version, platform = process.platform, architecture = process.arch) { + if (!/^v\d+\.\d+\.\d+$/.test(String(version || ''))) { + throw new Error('Nasiko installation requires a pinned version such as v0.1.0; latest is not allowed.'); + } + const normalized = normalizePlatform(platform, architecture); + const qualification = QUALIFIED_RELEASES[version]?.[`${normalized.os}/${normalized.arch}`]; + if (!qualification) throw new Error(`Nasiko ${version} is not qualified for ${normalized.os}/${normalized.arch}.`); + return { version, ...normalized, ...qualification, license: LICENSE, sourceUrl: SOURCE_URL }; +} + +function digestBytes(bytes) { + return `sha256:${crypto.createHash('sha256').update(bytes).digest('hex')}`; +} + +function assertDigest(bytes, expectedDigest, label) { + if (!SHA256_PATTERN.test(expectedDigest)) throw new Error(`${label} has an invalid expected digest.`); + const actual = digestBytes(bytes); + if (actual !== expectedDigest) throw new Error(`${label} digest mismatch: expected ${expectedDigest}, got ${actual}.`); +} + +function validateManifest(bytes) { + let manifest; + try { manifest = JSON.parse(bytes.toString('utf8')); } catch (_error) { throw new Error('Nasiko manifest is not valid JSON.'); } + if (manifest.schemaVersion !== 2 || !Array.isArray(manifest.layers) || manifest.layers.length !== 1) { + throw new Error('Nasiko manifest must contain exactly one OCI layer.'); + } + const layer = manifest.layers[0]; + if (layer.mediaType !== 'application/gzip' || !SHA256_PATTERN.test(layer.digest)) { + throw new Error('Nasiko manifest layer is not a qualified gzip artifact.'); + } + if (!Number.isSafeInteger(layer.size) || layer.size <= 0 || layer.size > MAX_ARCHIVE_BYTES) { + throw new Error('Nasiko manifest layer size is outside the allowed range.'); + } + return { digest: layer.digest, size: layer.size }; +} + +function readTarString(block, offset, length) { + return block.subarray(offset, offset + length).toString('utf8').replace(/\0.*$/, ''); +} + +function readTarOctal(block, offset, length) { + const field = block.subarray(offset, offset + length).toString('ascii'); + const match = /^ *([0-7]+)[ \0]*$/.exec(field); + if (!match) throw new Error('Unsafe Nasiko archive: invalid tar size field.'); + const size = Number.parseInt(match[1], 8); + if (!Number.isSafeInteger(size) || size < 0) { + throw new Error('Unsafe Nasiko archive: invalid tar size field.'); + } + return size; +} + +function extractQualifiedTarGzip(archiveBytes, expectedName) { + let tar; + try { tar = zlib.gunzipSync(archiveBytes, { maxOutputLength: MAX_BINARY_BYTES + 2048 }); } + catch (_error) { throw new Error('Nasiko archive is invalid or exceeds the decompressed size limit.'); } + let offset = 0; + let binary = null; + let terminated = false; + while (offset < tar.length) { + if (offset + 512 > tar.length) throw new Error('Unsafe Nasiko archive: truncated tar header.'); + const header = tar.subarray(offset, offset + 512); + if (header.every(byte => byte === 0)) { + const terminatorEnd = offset + 1024; + if ( + terminatorEnd > tar.length + || !tar.subarray(offset + 512, terminatorEnd).every(byte => byte === 0) + || !tar.subarray(terminatorEnd).every(byte => byte === 0) + ) { + throw new Error('Unsafe Nasiko archive: incomplete terminator or nonzero trailing data.'); + } + terminated = true; + break; + } + const name = readTarString(header, 0, 100); + const prefix = readTarString(header, 345, 155); + const type = String.fromCharCode(header[156] || 48); + const size = readTarOctal(header, 124, 12); + const start = offset + 512; + const end = start + size; + const paddedEnd = start + Math.ceil(size / 512) * 512; + if (!Number.isSafeInteger(end) || paddedEnd > tar.length) throw new Error('Nasiko archive is truncated.'); + const payload = tar.subarray(start, end); + if (!tar.subarray(end, paddedEnd).every(byte => byte === 0)) { + throw new Error('Unsafe Nasiko archive: nonzero tar padding.'); + } + const isBinary = !prefix && name === expectedName && (type === '0' || type === '\0'); + const isAppleDouble = !prefix && name === `._${expectedName}` && type === '0' && size <= 1024 * 1024; + const isPaxMetadata = !prefix && name === `PaxHeader/${expectedName}` && type === 'x' && size <= 64 * 1024 + && !/(?:^|\n)(?:path|linkpath)=/i.test(payload.toString('utf8')); + if (isBinary && !binary && size > 0 && size <= MAX_BINARY_BYTES) binary = Buffer.from(payload); + else if (!isAppleDouble && !isPaxMetadata) throw new Error('Unsafe Nasiko archive: expected exactly one bounded regular binary file.'); + offset = paddedEnd; + } + if (!terminated) throw new Error('Unsafe Nasiko archive: missing complete tar terminator.'); + if (!binary) throw new Error('Unsafe Nasiko archive: expected exactly one bounded regular binary file.'); + return binary; +} + +function fetchBytes(url, options = {}) { + const parsed = new URL(url); + if (parsed.origin !== REGISTRY_ORIGIN || parsed.protocol !== 'https:') return Promise.reject(new Error('Nasiko download origin is not allowed.')); + const maxBytes = options.maxBytes || MAX_ARCHIVE_BYTES; + return new Promise((resolve, reject) => { + const request = https.get(parsed, { headers: options.accept ? { Accept: options.accept } : {} }, response => { + if (response.statusCode >= 300 && response.statusCode < 400) { response.resume(); reject(new Error('Nasiko registry redirects are not allowed.')); return; } + if (response.statusCode !== 200) { response.resume(); reject(new Error(`Nasiko registry returned HTTP ${response.statusCode}.`)); return; } + const chunks = []; + let total = 0; + response.on('data', chunk => { + total += chunk.length; + if (total > maxBytes) request.destroy(new Error('Nasiko registry response exceeded the size limit.')); + else chunks.push(chunk); + }); + response.on('end', () => resolve(Buffer.concat(chunks))); + response.on('error', reject); + }); + request.setTimeout(options.timeoutMs || 15000, () => request.destroy(new Error('Nasiko registry request timed out.'))); + request.on('error', reject); + }); +} + +function defaultInstallDirectory(normalized, environment = process.env, homeDirectory = os.homedir()) { + if (normalized.os === 'windows') { + if (!environment.LOCALAPPDATA) throw new Error('LOCALAPPDATA is required on Windows.'); + return path.join(environment.LOCALAPPDATA, 'nasiko', 'bin'); + } + return path.join(homeDirectory, '.local', 'bin'); +} + +function validateInstallDirectory(directory) { + if (typeof directory !== 'string' || directory.includes('\0') || !path.isAbsolute(directory)) throw new Error('Nasiko install directory must be an absolute path.'); + if (/^(?:\\\\|\\\\\?\\|\\\\\.\\)/.test(directory)) throw new Error('Nasiko install directory must be on a local filesystem.'); + const resolved = path.resolve(directory); + if (resolved === path.parse(resolved).root) throw new Error('Nasiko cannot install directly into a filesystem root.'); + let ancestor = resolved; + while (!fs.existsSync(ancestor)) { + const parent = path.dirname(ancestor); + if (parent === ancestor) throw new Error('Nasiko install directory has no resolvable filesystem ancestor.'); + ancestor = parent; + } + const canonical = fs.realpathSync(ancestor); + return path.join(canonical, path.relative(ancestor, resolved)); +} + +function assertPrivateInstallDirectory(directory) { + const stats = fs.lstatSync(directory); + if (!stats.isDirectory() || stats.isSymbolicLink()) throw new Error('Nasiko install directory must be a real directory, not a symlink.'); + if (process.platform !== 'win32') { + if (typeof process.getuid === 'function' && stats.uid !== process.getuid()) throw new Error('Nasiko install directory must be owned by the current user.'); + if ((stats.mode & 0o022) !== 0) throw new Error('Nasiko install directory must not be group- or world-writable.'); + } +} + +function metadataPathFor(executable) { return path.join(path.dirname(executable), METADATA_FILENAME); } + +function readBoundedRegularFile(filePath, maximumBytes) { + const noFollow = fs.constants.O_NOFOLLOW; + const descriptor = fs.openSync(filePath, fs.constants.O_RDONLY | (noFollow || 0)); + try { + const stats = fs.fstatSync(descriptor); + if (!stats.isFile() || stats.size <= 0 || stats.size > maximumBytes) return null; + if (!noFollow) { + const pathStats = fs.lstatSync(filePath); + if (pathStats.isSymbolicLink() + || pathStats.dev !== stats.dev + || pathStats.ino !== stats.ino + || pathStats.birthtimeMs !== stats.birthtimeMs) { + const error = new Error('Nasiko managed files must not be symbolic links or reparse points.'); + error.code = 'ELOOP'; + throw error; + } + } + const bytes = Buffer.allocUnsafe(stats.size); + let total = 0; + while (total < bytes.length) { + const count = fs.readSync(descriptor, bytes, total, bytes.length - total, total); + if (count === 0) return null; + total += count; + } + if (fs.fstatSync(descriptor).size !== stats.size) return null; + return bytes; + } finally { fs.closeSync(descriptor); } +} + +function readMetadata(executable) { + try { + const bytes = readBoundedRegularFile(metadataPathFor(executable), MAX_METADATA_BYTES); + return bytes ? JSON.parse(bytes.toString('utf8')) : null; + } + catch (_error) { return null; } +} + +function inspectInstalledNasiko(executable, resolveRelease = getQualifiedRelease) { + if (!executable) return { installed: false, qualified: false, version: null, executable: null }; + let binary; + try { binary = readBoundedRegularFile(executable, MAX_BINARY_BYTES); } + catch (error) { + if (error.code === 'ENOENT') return { installed: false, qualified: false, version: null, executable }; + if (error.code === 'ELOOP') throw new Error('Nasiko executable must be a regular file, not a symlink.'); + throw error; + } + if (!binary) return { installed: true, qualified: false, version: null, executable, binaryDigest: null, metadataPath: metadataPathFor(executable) }; + const binaryDigest = digestBytes(binary); + const metadata = readMetadata(executable); + let release = null; + try { if (metadata) release = resolveRelease(metadata.version, metadata.platform, metadata.architecture); } catch (_error) { release = null; } + const qualified = Boolean(release + && metadata.installedPath === executable + && metadata.manifestDigest === release.manifestDigest + && metadata.binaryDigest === release.binaryDigest + && binaryDigest === release.binaryDigest + && metadata.license === release.license + && metadata.sourceUrl === release.sourceUrl); + return { installed: true, qualified, version: qualified ? metadata.version : null, executable, binaryDigest, metadataPath: metadataPathFor(executable) }; +} + +function writeMetadataExclusive(metadataPath, metadata) { + fs.writeFileSync(metadataPath, `${JSON.stringify(metadata, null, 2)}\n`, { mode: 0o600, flag: 'wx' }); +} + +function sameFileIdentity(left, right) { + return left.dev === right.dev && left.ino === right.ino; +} + +function processIsAlive(pid) { + try { + process.kill(pid, 0); + return true; + } catch (error) { + return error.code !== 'ESRCH'; + } +} + +function inspectLifecycleLock(lockPath, fileSystem) { + const descriptor = fileSystem.openSync(lockPath, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW || 0)); + try { + const descriptorStats = fileSystem.fstatSync(descriptor, { bigint: true }); + if (!descriptorStats.isFile() || descriptorStats.size <= 0n || descriptorStats.size > 4096n) return null; + const bytes = fileSystem.readFileSync(descriptor); + const pathStats = fileSystem.lstatSync(lockPath); + if (pathStats.isSymbolicLink() || !pathStats.isFile()) return null; + let metadata; + try { metadata = JSON.parse(bytes.toString('utf8')); } catch (_error) { return null; } + if ( + !Number.isSafeInteger(metadata.pid) + || metadata.pid <= 0 + || typeof metadata.startedAt !== 'string' + || !Number.isFinite(Date.parse(metadata.startedAt)) + ) return null; + return { metadata, stats: descriptorStats }; + } finally { fileSystem.closeSync(descriptor); } +} + +function removeLockIfOwned(lockPath, expectedStats, fileSystem) { + let descriptor; + try { + descriptor = fileSystem.openSync(lockPath, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW || 0)); + const current = fileSystem.fstatSync(descriptor, { bigint: true }); + const pathStats = fileSystem.lstatSync(lockPath); + if (!pathStats.isSymbolicLink() && pathStats.isFile() && current.isFile() && sameFileIdentity(current, expectedStats)) { + fileSystem.closeSync(descriptor); + descriptor = undefined; + fileSystem.rmSync(lockPath, { force: true }); + return true; + } + } catch (error) { + if (error.code !== 'ENOENT' && error.code !== 'ELOOP') throw error; + } finally { + if (descriptor !== undefined) fileSystem.closeSync(descriptor); + } + return false; +} + +function createLifecycleLock(lockPath, fileSystem) { + let descriptor; + try { + descriptor = fileSystem.openSync(lockPath, 'wx', 0o600); + fileSystem.writeFileSync(descriptor, `${JSON.stringify({ + pid: process.pid, + startedAt: new Date().toISOString(), + token: crypto.randomBytes(16).toString('hex'), + })}\n`); + fileSystem.fsyncSync(descriptor); + } + catch (error) { + if (descriptor !== undefined) { + const ownedStats = fileSystem.fstatSync(descriptor, { bigint: true }); + try { fileSystem.closeSync(descriptor); } finally { removeLockIfOwned(lockPath, ownedStats, fileSystem); } + } + throw error; + } + const ownedStats = fileSystem.fstatSync(descriptor, { bigint: true }); + let released = false; + return () => { + if (released) return; + released = true; + try { fileSystem.closeSync(descriptor); } finally { removeLockIfOwned(lockPath, ownedStats, fileSystem); } + }; +} + +function acquireLifecycleLock(installDirectory, fileSystem = fs, options = {}) { + const lockPath = path.join(installDirectory, '.ecc-nasiko-lifecycle.lock'); + try { + return createLifecycleLock(lockPath, fileSystem); + } catch (error) { + if (error.code !== 'EEXIST') throw error; + } + + let existing; + try { existing = inspectLifecycleLock(lockPath, fileSystem); } + catch (error) { + if (error.code === 'ENOENT') { + try { return createLifecycleLock(lockPath, fileSystem); } + catch (retryError) { + if (retryError.code === 'EEXIST') { + throw new Error(`Another Nasiko lifecycle operation won lock acquisition: ${lockPath}.`); + } + throw retryError; + } + } + throw error; + } + const isProcessAlive = options.isProcessAlive || processIsAlive; + if (!existing || isProcessAlive(existing.metadata.pid)) { + throw new Error(`Another Nasiko lifecycle operation is already in progress; inspect ${lockPath} before recovering a stale lock.`); + } + if (!removeLockIfOwned(lockPath, existing.stats, fileSystem)) { + throw new Error(`Nasiko lifecycle lock changed during stale-owner recovery: ${lockPath}.`); + } + try { + return createLifecycleLock(lockPath, fileSystem); + } catch (error) { + if (error.code === 'EEXIST') { + throw new Error(`Another Nasiko lifecycle operation won stale-lock recovery: ${lockPath}.`); + } + throw error; + } +} + +async function installNasiko(options = {}, dependencies = {}) { + const version = options.version || 'v0.1.0'; + const base = getQualifiedRelease(version, dependencies.platform || process.platform, dependencies.arch || process.arch); + const release = dependencies.releaseOverride ? { ...base, ...dependencies.releaseOverride } : base; + const installDirectory = validateInstallDirectory(options.installDir || defaultInstallDirectory(release, dependencies.environment || process.env, dependencies.homeDirectory || os.homedir())); + const destination = path.join(installDirectory, release.binaryName); + const plan = { dryRun: Boolean(options.dryRun), version, platform: release.os, architecture: release.arch, manifestDigest: release.manifestDigest, binaryDigest: release.binaryDigest, registryOrigin: REGISTRY_ORIGIN, destination, license: release.license, sourceUrl: release.sourceUrl }; + if (options.dryRun) return plan; + if (!options.yes) throw new Error('Nasiko installation requires explicit --yes consent.'); + fs.mkdirSync(installDirectory, { recursive: true, mode: 0o755 }); + assertPrivateInstallDirectory(installDirectory); + const releaseLock = acquireLifecycleLock(installDirectory); + const metadataPath = metadataPathFor(destination); + let destinationOwned = false; + let metadataOwned = false; + try { + const existing = inspectInstalledNasiko(destination); + if (existing.installed) { + if (existing.qualified && existing.version === version) return { ...plan, dryRun: false, installed: true, reused: true }; + throw new Error('An unqualified or incompatible Nasiko executable or receipt already exists at the destination.'); + } + const retrieve = dependencies.fetchBytes || fetchBytes; + const manifestBytes = await retrieve(`${REGISTRY_ORIGIN}/v2/${REPOSITORY}/manifests/${release.manifestDigest}`, { accept: 'application/vnd.oci.image.manifest.v1+json', maxBytes: MAX_MANIFEST_BYTES }); + assertDigest(manifestBytes, release.manifestDigest, 'Nasiko manifest'); + const layer = validateManifest(manifestBytes); + const archiveBytes = await retrieve(`${REGISTRY_ORIGIN}/v2/${REPOSITORY}/blobs/${layer.digest}`, { maxBytes: MAX_ARCHIVE_BYTES }); + if (archiveBytes.length !== layer.size) throw new Error('Nasiko archive size mismatch.'); + assertDigest(archiveBytes, layer.digest, 'Nasiko archive'); + const binary = (dependencies.extractBinary || extractQualifiedTarGzip)(archiveBytes, release.binaryName); + assertDigest(binary, release.binaryDigest, 'Nasiko binary'); + if (dependencies.beforePublish) dependencies.beforePublish(destination); + const descriptor = fs.openSync(destination, 'wx', 0o700); + destinationOwned = true; + try { + fs.writeFileSync(descriptor, binary); + fs.fsyncSync(descriptor); + if (fs.fstatSync(descriptor).size !== binary.length) throw new Error('Published Nasiko binary size mismatch.'); + } finally { fs.closeSync(descriptor); } + const metadata = { version, platform: release.os, architecture: release.arch, manifestDigest: release.manifestDigest, artifactDigest: layer.digest, binaryDigest: release.binaryDigest, installedPath: destination, license: release.license, sourceUrl: release.sourceUrl }; + (dependencies.writeMetadata || writeMetadataExclusive)(metadataPath, metadata); + metadataOwned = true; + return { ...plan, dryRun: false, installed: true, reused: false, artifactDigest: layer.digest }; + } catch (error) { + if (metadataOwned) fs.rmSync(metadataPath, { force: true }); + if (destinationOwned) fs.rmSync(destination, { force: true }); + throw error; + } finally { releaseLock(); } +} + +function uninstallNasiko(options = {}, dependencies = {}) { + const version = options.version || 'v0.1.0'; + const release = getQualifiedRelease(version, dependencies.platform || process.platform, dependencies.arch || process.arch); + const installDirectory = validateInstallDirectory(options.installDir || defaultInstallDirectory(release, dependencies.environment || process.env, dependencies.homeDirectory || os.homedir())); + const destination = path.join(installDirectory, release.binaryName); + const plan = { dryRun: Boolean(options.dryRun), version, destination }; + if (options.dryRun) return plan; + if (!options.yes) throw new Error('Nasiko uninstall requires explicit --yes consent.'); + if (!fs.existsSync(installDirectory)) return { ...plan, dryRun: false, removed: false }; + assertPrivateInstallDirectory(installDirectory); + const releaseLock = acquireLifecycleLock(installDirectory); + const metadataPath = metadataPathFor(destination); + const suffix = `${process.pid}-${crypto.randomBytes(6).toString('hex')}`; + const binaryTombstone = `${destination}.remove-${suffix}`; + const metadataTombstone = `${metadataPath}.remove-${suffix}`; + let binaryStaged = false; + let metadataStaged = false; + const rename = dependencies.rename || fs.renameSync; + const remove = dependencies.remove || (target => fs.rmSync(target)); + try { + const status = (dependencies.inspectInstalled || inspectInstalledNasiko)(destination); + if (!status.installed) return { ...plan, dryRun: false, removed: false }; + if (!status.qualified || status.version !== version) throw new Error('Refusing to remove an unqualified or modified Nasiko executable.'); + rename(destination, binaryTombstone); + binaryStaged = true; + rename(metadataPath, metadataTombstone); + metadataStaged = true; + const cleanupPending = []; + try { remove(metadataTombstone); } catch (_error) { cleanupPending.push(metadataTombstone); } + metadataStaged = false; + try { remove(binaryTombstone); } catch (_error) { cleanupPending.push(binaryTombstone); } + binaryStaged = false; + if (cleanupPending.length > 0) { + const cleanupError = new Error(`Nasiko uninstall is incomplete; retained staged file(s): ${cleanupPending.join(', ')}. Remove these files before reinstalling.`); + cleanupError.cleanupPending = cleanupPending; + throw cleanupError; + } + return { ...plan, dryRun: false, removed: true, cleanupPending: [] }; + } catch (error) { + if (metadataStaged && !fs.existsSync(metadataPath)) rename(metadataTombstone, metadataPath); + if (binaryStaged && !fs.existsSync(destination)) rename(binaryTombstone, destination); + throw error; + } finally { releaseLock(); } +} + +module.exports = { QUALIFIED_RELEASES, REGISTRY_ORIGIN, acquireLifecycleLock, digestBytes, extractQualifiedTarGzip, fetchBytes, getQualifiedRelease, inspectInstalledNasiko, installNasiko, normalizePlatform, uninstallNasiko, validateInstallDirectory }; diff --git a/github_code/affaan-m__ECC/scripts/lib/observer-sessions.js b/github_code/affaan-m__ECC/scripts/lib/observer-sessions.js new file mode 100644 index 0000000000000000000000000000000000000000..08296da3a4ade8c86ae2c3fdfd5b22937f34ab11 --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/observer-sessions.js @@ -0,0 +1,212 @@ +const fs = require('fs'); +const os = require('os'); +const path = require('path'); +const crypto = require('crypto'); +const { spawnSync } = require('child_process'); +const { ensureDir, sanitizeSessionId } = require('./utils'); + +function getHomunculusDir() { + const override = process.env.CLV2_HOMUNCULUS_DIR; + if (override) { + if (path.isAbsolute(override)) { + return override; + } + process.stderr.write(`[ecc] CLV2_HOMUNCULUS_DIR=${override} is not absolute; ignoring\n`); + } + + const xdgDataHome = process.env.XDG_DATA_HOME; + if (xdgDataHome) { + if (path.isAbsolute(xdgDataHome)) { + return path.join(xdgDataHome, 'ecc-homunculus'); + } + process.stderr.write(`[ecc] XDG_DATA_HOME=${xdgDataHome} is not absolute; ignoring\n`); + } + + return path.join(os.homedir(), '.local', 'share', 'ecc-homunculus'); +} + +function getProjectsDir() { + return path.join(getHomunculusDir(), 'projects'); +} + +function getProjectRegistryPath() { + return path.join(getHomunculusDir(), 'projects.json'); +} + +function readProjectRegistry() { + try { + return JSON.parse(fs.readFileSync(getProjectRegistryPath(), 'utf8')); + } catch { + return {}; + } +} + +function runGit(args, cwd) { + const result = spawnSync('git', args, { + cwd, + encoding: 'utf8', + stdio: ['ignore', 'pipe', 'ignore'] + }); + if (result.status !== 0) return ''; + return (result.stdout || '').trim(); +} + +function stripRemoteCredentials(remoteUrl) { + if (!remoteUrl) return ''; + return String(remoteUrl).replace(/:\/\/[^@]+@/, '://'); +} + +function normalizeRemoteUrl(remoteUrl) { + if (!remoteUrl) return ''; + const raw = String(remoteUrl); + const isNetwork = !raw.startsWith('file://') && (raw.includes('://') || /^[^@/:]+@[^:/]+:/.test(raw)); + let normalized = stripRemoteCredentials(raw) + .replace(/^[A-Za-z][A-Za-z0-9+.-]*:\/\//, '') + .replace(/^[^@/:]+@([^:/]+):/, '$1/') + .replace(/\.git\/?$/, '') + .replace(/\/+$/, ''); + + if (isNetwork) { + normalized = normalized.toLowerCase(); + } + + return normalized; +} + +function resolveProjectRoot(cwd = process.cwd()) { + const envRoot = process.env.CLAUDE_PROJECT_DIR; + if (envRoot && fs.existsSync(envRoot)) { + return path.resolve(envRoot); + } + + const gitRoot = runGit(['rev-parse', '--show-toplevel'], cwd); + if (gitRoot) return path.resolve(gitRoot); + + return ''; +} + +function computeProjectId(projectRoot) { + const remoteUrl = stripRemoteCredentials(runGit(['remote', 'get-url', 'origin'], projectRoot)); + const hashInput = normalizeRemoteUrl(remoteUrl) || remoteUrl || projectRoot; + return crypto.createHash('sha256').update(hashInput).digest('hex').slice(0, 12); +} + +function resolveProjectContext(cwd = process.cwd()) { + const projectRoot = resolveProjectRoot(cwd); + if (!projectRoot) { + const projectDir = getHomunculusDir(); + ensureDir(projectDir); + return { projectId: 'global', projectRoot: '', projectDir, isGlobal: true }; + } + + const registry = readProjectRegistry(); + const registryEntry = Object.values(registry).find(entry => entry && path.resolve(entry.root || '') === projectRoot); + const projectId = registryEntry?.id || computeProjectId(projectRoot); + const projectDir = path.join(getProjectsDir(), projectId); + ensureDir(projectDir); + + return { projectId, projectRoot, projectDir, isGlobal: false }; +} + +function getObserverPidFile(context) { + return path.join(context.projectDir, '.observer.pid'); +} + +function getObserverSignalCounterFile(context) { + return path.join(context.projectDir, '.observer-signal-counter'); +} + +function getObserverActivityFile(context) { + return path.join(context.projectDir, '.observer-last-activity'); +} + +function getSessionLeaseDir(context) { + return path.join(context.projectDir, '.observer-sessions'); +} + +function resolveSessionId(rawSessionId = process.env.CLAUDE_SESSION_ID) { + return sanitizeSessionId(rawSessionId || '') || ''; +} + +function getSessionLeaseFile(context, rawSessionId = process.env.CLAUDE_SESSION_ID) { + const sessionId = resolveSessionId(rawSessionId); + if (!sessionId) return ''; + return path.join(getSessionLeaseDir(context), `${sessionId}.json`); +} + +function writeSessionLease(context, rawSessionId = process.env.CLAUDE_SESSION_ID, extra = {}) { + const leaseFile = getSessionLeaseFile(context, rawSessionId); + if (!leaseFile) return ''; + + ensureDir(getSessionLeaseDir(context)); + const payload = { + sessionId: resolveSessionId(rawSessionId), + cwd: process.cwd(), + pid: process.pid, + updatedAt: new Date().toISOString(), + ...extra + }; + fs.writeFileSync(leaseFile, JSON.stringify(payload, null, 2) + '\n'); + return leaseFile; +} + +function removeSessionLease(context, rawSessionId = process.env.CLAUDE_SESSION_ID) { + const leaseFile = getSessionLeaseFile(context, rawSessionId); + if (!leaseFile) return false; + try { + fs.rmSync(leaseFile, { force: true }); + return true; + } catch { + return false; + } +} + +function listSessionLeases(context) { + const leaseDir = getSessionLeaseDir(context); + if (!fs.existsSync(leaseDir)) return []; + return fs.readdirSync(leaseDir) + .filter(name => name.endsWith('.json')) + .map(name => path.join(leaseDir, name)); +} + +function stopObserverForContext(context) { + const pidFile = getObserverPidFile(context); + if (!fs.existsSync(pidFile)) return false; + + const pid = (fs.readFileSync(pidFile, 'utf8') || '').trim(); + if (!/^[0-9]+$/.test(pid) || pid === '0' || pid === '1') { + fs.rmSync(pidFile, { force: true }); + return false; + } + + try { + process.kill(Number(pid), 0); + } catch { + fs.rmSync(pidFile, { force: true }); + return false; + } + + try { + process.kill(Number(pid), 'SIGTERM'); + } catch { + return false; + } + + fs.rmSync(pidFile, { force: true }); + fs.rmSync(getObserverSignalCounterFile(context), { force: true }); + return true; +} + +module.exports = { + getHomunculusDir, + normalizeRemoteUrl, + resolveProjectContext, + getObserverActivityFile, + getObserverPidFile, + getSessionLeaseDir, + writeSessionLease, + removeSessionLease, + listSessionLeases, + stopObserverForContext, + resolveSessionId +}; diff --git a/github_code/affaan-m__ECC/scripts/lib/opencode-paths.js b/github_code/affaan-m__ECC/scripts/lib/opencode-paths.js new file mode 100644 index 0000000000000000000000000000000000000000..0a5ef3f3df5bb66fd320fda824b2c8fb9516beb5 --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/opencode-paths.js @@ -0,0 +1,31 @@ +'use strict'; + +const os = require('os'); +const path = require('path'); +const { resolveInvocationEnvironment } = require('./invocation-environment'); + +function configuredDirectory(environment, name) { + const value = environment && environment[name]; + return typeof value === 'string' && value.trim() !== '' + ? path.resolve(value.trim()) + : null; +} + +function resolveOpencodeConfigRoot(options = {}) { + const environment = resolveInvocationEnvironment(options); + const explicitRoot = configuredDirectory(environment, 'OPENCODE_CONFIG_DIR'); + if (explicitRoot) { + return explicitRoot; + } + + const xdgConfigRoot = configuredDirectory(environment, 'XDG_CONFIG_HOME'); + if (xdgConfigRoot) { + return path.join(xdgConfigRoot, 'opencode'); + } + + return path.join(path.resolve(options.homeDir || os.homedir()), '.config', 'opencode'); +} + +module.exports = { + resolveOpencodeConfigRoot, +}; diff --git a/github_code/affaan-m__ECC/scripts/lib/orchestration-session.js b/github_code/affaan-m__ECC/scripts/lib/orchestration-session.js new file mode 100644 index 0000000000000000000000000000000000000000..9449020fcf7b7233edb581e77ff4bde5d749cf49 --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/orchestration-session.js @@ -0,0 +1,299 @@ +'use strict'; + +const fs = require('fs'); +const path = require('path'); +const { spawnSync } = require('child_process'); + +function stripCodeTicks(value) { + if (typeof value !== 'string') { + return value; + } + + const trimmed = value.trim(); + if (trimmed.startsWith('`') && trimmed.endsWith('`') && trimmed.length >= 2) { + return trimmed.slice(1, -1); + } + + return trimmed; +} + +function parseSection(content, heading) { + if (typeof content !== 'string' || content.length === 0) { + return ''; + } + + const lines = content.split('\n'); + const headingLines = new Set([`## ${heading}`, `**${heading}**`]); + const startIndex = lines.findIndex(line => headingLines.has(line.trim())); + + if (startIndex === -1) { + return ''; + } + + const collected = []; + for (let index = startIndex + 1; index < lines.length; index += 1) { + const line = lines[index]; + const trimmed = line.trim(); + if (trimmed.startsWith('## ') || (/^\*\*.+\*\*$/.test(trimmed) && !headingLines.has(trimmed))) { + break; + } + collected.push(line); + } + + return collected.join('\n').trim(); +} + +function parseBullets(section) { + if (!section) { + return []; + } + + return section + .split('\n') + .map(line => line.trim()) + .filter(line => line.startsWith('- ')) + .map(line => stripCodeTicks(line.replace(/^- /, '').trim())); +} + +function parseWorkerStatus(content) { + const status = { + state: null, + updated: null, + branch: null, + worktree: null, + taskFile: null, + handoffFile: null + }; + + if (typeof content !== 'string' || content.length === 0) { + return status; + } + + for (const line of content.split('\n')) { + const match = line.match(/^- ([A-Za-z ]+):\s*(.+)$/); + if (!match) { + continue; + } + + const key = match[1].trim().toLowerCase().replace(/\s+/g, ''); + const value = stripCodeTicks(match[2]); + + if (key === 'state') status.state = value; + if (key === 'updated') status.updated = value; + if (key === 'branch') status.branch = value; + if (key === 'worktree') status.worktree = value; + if (key === 'taskfile') status.taskFile = value; + if (key === 'handofffile') status.handoffFile = value; + } + + return status; +} + +function parseWorkerTask(content) { + return { + objective: parseSection(content, 'Objective'), + seedPaths: parseBullets(parseSection(content, 'Seeded Local Overlays')) + }; +} + +function parseWorkerHandoff(content) { + return { + summary: parseBullets(parseSection(content, 'Summary')), + validation: parseBullets(parseSection(content, 'Validation')), + remainingRisks: parseBullets(parseSection(content, 'Remaining Risks')) + }; +} + +function readTextIfExists(filePath) { + if (!filePath || !fs.existsSync(filePath)) { + return ''; + } + + return fs.readFileSync(filePath, 'utf8'); +} + +function listWorkerDirectories(coordinationDir) { + if (!coordinationDir || !fs.existsSync(coordinationDir)) { + return []; + } + + return fs.readdirSync(coordinationDir, { withFileTypes: true }) + .filter(entry => entry.isDirectory()) + .filter(entry => { + const workerDir = path.join(coordinationDir, entry.name); + return ['status.md', 'task.md', 'handoff.md'] + .some(filename => fs.existsSync(path.join(workerDir, filename))); + }) + .map(entry => entry.name) + .sort(); +} + +function loadWorkerSnapshots(coordinationDir) { + return listWorkerDirectories(coordinationDir).map(workerSlug => { + const workerDir = path.join(coordinationDir, workerSlug); + const statusPath = path.join(workerDir, 'status.md'); + const taskPath = path.join(workerDir, 'task.md'); + const handoffPath = path.join(workerDir, 'handoff.md'); + + const status = parseWorkerStatus(readTextIfExists(statusPath)); + const task = parseWorkerTask(readTextIfExists(taskPath)); + const handoff = parseWorkerHandoff(readTextIfExists(handoffPath)); + + return { + workerSlug, + workerDir, + status, + task, + handoff, + files: { + status: statusPath, + task: taskPath, + handoff: handoffPath + } + }; + }); +} + +function listTmuxPanes(sessionName, options = {}) { + const { spawnSyncImpl = spawnSync } = options; + const format = [ + '#{pane_id}', + '#{window_index}', + '#{pane_index}', + '#{pane_title}', + '#{pane_current_command}', + '#{pane_current_path}', + '#{pane_active}', + '#{pane_dead}', + '#{pane_pid}' + ].join('\t'); + + const result = spawnSyncImpl('tmux', ['list-panes', '-t', sessionName, '-F', format], { + encoding: 'utf8', + stdio: ['ignore', 'pipe', 'pipe'] + }); + + if (result.error) { + if (result.error.code === 'ENOENT') { + return []; + } + throw result.error; + } + + if (result.status !== 0) { + return []; + } + + return (result.stdout || '') + .split('\n') + .map(line => line.trim()) + .filter(Boolean) + .map(line => { + const [ + paneId, + windowIndex, + paneIndex, + title, + currentCommand, + currentPath, + active, + dead, + pid + ] = line.split('\t'); + + return { + paneId, + windowIndex: Number(windowIndex), + paneIndex: Number(paneIndex), + title, + currentCommand, + currentPath, + active: active === '1', + dead: dead === '1', + pid: pid ? Number(pid) : null + }; + }); +} + +function summarizeWorkerStates(workers) { + return workers.reduce((counts, worker) => { + const state = worker.status.state || 'unknown'; + counts[state] = (counts[state] || 0) + 1; + return counts; + }, {}); +} + +function buildSessionSnapshot({ sessionName, coordinationDir, panes }) { + const workerSnapshots = loadWorkerSnapshots(coordinationDir); + const paneMap = new Map(panes.map(pane => [pane.title, pane])); + + const workers = workerSnapshots.map(worker => ({ + ...worker, + pane: paneMap.get(worker.workerSlug) || null + })); + + return { + sessionName, + coordinationDir, + sessionActive: panes.length > 0, + paneCount: panes.length, + workerCount: workers.length, + workerStates: summarizeWorkerStates(workers), + panes, + workers + }; +} + +function resolveSnapshotTarget(targetPath, cwd = process.cwd()) { + const absoluteTarget = path.resolve(cwd, targetPath); + + if (fs.existsSync(absoluteTarget) && fs.statSync(absoluteTarget).isFile()) { + const config = JSON.parse(fs.readFileSync(absoluteTarget, 'utf8')); + const repoRoot = path.resolve(config.repoRoot || cwd); + const coordinationRoot = path.resolve( + config.coordinationRoot || path.join(repoRoot, '.orchestration') + ); + + return { + sessionName: config.sessionName, + coordinationDir: path.join(coordinationRoot, config.sessionName), + repoRoot, + targetType: 'plan' + }; + } + + return { + sessionName: targetPath, + coordinationDir: path.join(cwd, '.claude', 'orchestration', targetPath), + repoRoot: cwd, + targetType: 'session' + }; +} + +function collectSessionSnapshot(targetPath, cwd = process.cwd()) { + const target = resolveSnapshotTarget(targetPath, cwd); + const panes = listTmuxPanes(target.sessionName); + const snapshot = buildSessionSnapshot({ + sessionName: target.sessionName, + coordinationDir: target.coordinationDir, + panes + }); + + return { + ...snapshot, + repoRoot: target.repoRoot, + targetType: target.targetType + }; +} + +module.exports = { + buildSessionSnapshot, + collectSessionSnapshot, + listTmuxPanes, + loadWorkerSnapshots, + normalizeText: stripCodeTicks, + parseWorkerHandoff, + parseWorkerStatus, + parseWorkerTask, + resolveSnapshotTarget +}; diff --git a/github_code/affaan-m__ECC/scripts/lib/package-manager.d.ts b/github_code/affaan-m__ECC/scripts/lib/package-manager.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..90a9573fe56f7be60d9c5fada8a2b86fef98e2f3 --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/package-manager.d.ts @@ -0,0 +1,119 @@ +/** + * Package Manager Detection and Selection. + * Supports: npm, pnpm, yarn, bun. + */ + +/** Supported package manager names */ +export type PackageManagerName = 'npm' | 'pnpm' | 'yarn' | 'bun'; + +/** Configuration for a single package manager */ +export interface PackageManagerConfig { + name: PackageManagerName; + /** Lock file name (e.g., "package-lock.json", "pnpm-lock.yaml") */ + lockFile: string; + /** Install command (e.g., "npm install") */ + installCmd: string; + /** Run script command prefix (e.g., "npm run", "pnpm") */ + runCmd: string; + /** Execute binary command (e.g., "npx", "pnpm dlx") */ + execCmd: string; + /** Test command (e.g., "npm test") */ + testCmd: string; + /** Build command (e.g., "npm run build") */ + buildCmd: string; + /** Dev server command (e.g., "npm run dev") */ + devCmd: string; +} + +/** How the package manager was detected */ +export type DetectionSource = + | 'environment' + | 'project-config' + | 'package.json' + | 'lock-file' + | 'global-config' + | 'default'; + +/** Result from getPackageManager() */ +export interface PackageManagerResult { + name: PackageManagerName; + config: PackageManagerConfig; + source: DetectionSource; +} + +/** Map of all supported package managers keyed by name */ +export const PACKAGE_MANAGERS: Record; + +/** Priority order for lock file detection */ +export const DETECTION_PRIORITY: PackageManagerName[]; + +export interface GetPackageManagerOptions { + /** Project directory to detect from (default: process.cwd()) */ + projectDir?: string; +} + +/** + * Get the package manager to use for the current project. + * + * Detection priority: + * 1. CLAUDE_PACKAGE_MANAGER environment variable + * 2. Project-specific config (.claude/package-manager.json) + * 3. package.json `packageManager` field + * 4. Lock file detection + * 5. Global user preference (~/.claude/package-manager.json) + * 6. Default to npm (no child processes spawned) + */ +export function getPackageManager(options?: GetPackageManagerOptions): PackageManagerResult; + +/** + * Set the user's globally preferred package manager. + * Saves to ~/.claude/package-manager.json. + * @throws If pmName is not a known package manager or if save fails + */ +export function setPreferredPackageManager(pmName: PackageManagerName): { packageManager: string; setAt: string }; + +/** + * Set a project-specific preferred package manager. + * Saves to /.claude/package-manager.json. + * @throws If pmName is not a known package manager + */ +export function setProjectPackageManager(pmName: PackageManagerName, projectDir?: string): { packageManager: string; setAt: string }; + +/** + * Get package managers installed on the system. + * WARNING: Spawns child processes for each PM check. + * Do NOT call during session startup hooks. + */ +export function getAvailablePackageManagers(): PackageManagerName[]; + +/** Detect package manager from lock file in the given directory */ +export function detectFromLockFile(projectDir?: string): PackageManagerName | null; + +/** Detect package manager from package.json `packageManager` field */ +export function detectFromPackageJson(projectDir?: string): PackageManagerName | null; + +/** + * Get the full command string to run a script. + * @param script - Script name: "install", "test", "build", "dev", or custom + */ +export function getRunCommand(script: string, options?: GetPackageManagerOptions): string; + +/** + * Get the full command string to execute a package binary. + * @param binary - Binary name (e.g., "prettier", "eslint") + * @param args - Arguments to pass to the binary + */ +export function getExecCommand(binary: string, args?: string, options?: GetPackageManagerOptions): string; + +/** + * Get a message prompting the user to configure their package manager. + * Does NOT spawn child processes. + */ +export function getSelectionPrompt(): string; + +/** + * Generate a regex pattern string that matches commands for all package managers. + * @param action - Action like "dev", "install", "test", "build", or custom + * @returns Parenthesized alternation regex string, e.g., "(npm run dev|pnpm( run)? dev|...)" + */ +export function getCommandPattern(action: string): string; diff --git a/github_code/affaan-m__ECC/scripts/lib/package-manager.js b/github_code/affaan-m__ECC/scripts/lib/package-manager.js new file mode 100644 index 0000000000000000000000000000000000000000..def3870b0118bfdefd13da77e6ac9cd9418d740a --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/package-manager.js @@ -0,0 +1,434 @@ +/** + * Package Manager Detection and Selection + * Automatically detects the preferred package manager or lets user choose + * + * Supports: npm, pnpm, yarn, bun + */ + +const fs = require('fs'); +const path = require('path'); +const { commandExists, getClaudeDir, readFile, writeFile } = require('./utils'); + +// Package manager definitions +const PACKAGE_MANAGERS = { + npm: { + name: 'npm', + lockFile: 'package-lock.json', + installCmd: 'npm install', + runCmd: 'npm run', + execCmd: 'npx', + testCmd: 'npm test', + buildCmd: 'npm run build', + devCmd: 'npm run dev' + }, + pnpm: { + name: 'pnpm', + lockFile: 'pnpm-lock.yaml', + installCmd: 'pnpm install', + runCmd: 'pnpm', + execCmd: 'pnpm dlx', + testCmd: 'pnpm test', + buildCmd: 'pnpm build', + devCmd: 'pnpm dev' + }, + yarn: { + name: 'yarn', + lockFile: 'yarn.lock', + installCmd: 'yarn', + runCmd: 'yarn', + execCmd: 'yarn dlx', + testCmd: 'yarn test', + buildCmd: 'yarn build', + devCmd: 'yarn dev' + }, + bun: { + name: 'bun', + lockFile: 'bun.lock', + // Bun switched its default lockfile from the binary bun.lockb to the + // text-based bun.lock. Keep recognizing the legacy file too. + lockFileAliases: ['bun.lockb'], + installCmd: 'bun install', + runCmd: 'bun run', + execCmd: 'bunx', + testCmd: 'bun test', + buildCmd: 'bun run build', + devCmd: 'bun run dev' + } +}; + +// Priority order for detection +const DETECTION_PRIORITY = ['pnpm', 'bun', 'yarn', 'npm']; + +// Config file path +function getConfigPath() { + return path.join(getClaudeDir(), 'package-manager.json'); +} + +/** + * Load saved package manager configuration + */ +function loadConfig() { + const configPath = getConfigPath(); + const content = readFile(configPath); + + if (content) { + try { + return JSON.parse(content); + } catch { + return null; + } + } + return null; +} + +/** + * Save package manager configuration + */ +function saveConfig(config) { + const configPath = getConfigPath(); + writeFile(configPath, JSON.stringify(config, null, 2)); +} + +/** + * Detect package manager from lock file in project directory + */ +function detectFromLockFile(projectDir = process.cwd()) { + for (const pmName of DETECTION_PRIORITY) { + const pm = PACKAGE_MANAGERS[pmName]; + const lockFileNames = [pm.lockFile, ...(pm.lockFileAliases || [])]; + + if (lockFileNames.some(lockFileName => fs.existsSync(path.join(projectDir, lockFileName)))) { + return pmName; + } + } + return null; +} + +/** + * Detect package manager from package.json packageManager field + */ +function detectFromPackageJson(projectDir = process.cwd()) { + const packageJsonPath = path.join(projectDir, 'package.json'); + const content = readFile(packageJsonPath); + + if (content) { + try { + const pkg = JSON.parse(content); + if (pkg.packageManager) { + // Format: "pnpm@8.6.0" or just "pnpm" + const pmName = pkg.packageManager.split('@')[0]; + if (PACKAGE_MANAGERS[pmName]) { + return pmName; + } + } + } catch { + // Invalid package.json + } + } + return null; +} + +/** + * Get available package managers (installed on system) + * + * WARNING: This spawns child processes (where.exe on Windows, which on Unix) + * for each package manager. Do NOT call this during session startup hooks — + * it can exceed Bun's spawn limit on Windows and freeze the plugin. + * Use detectFromLockFile() or detectFromPackageJson() for hot paths. + */ +function getAvailablePackageManagers() { + const available = []; + + for (const pmName of Object.keys(PACKAGE_MANAGERS)) { + if (commandExists(pmName)) { + available.push(pmName); + } + } + + return available; +} + +/** + * Get the package manager to use for current project + * + * Detection priority: + * 1. Environment variable CLAUDE_PACKAGE_MANAGER + * 2. Project-specific config (in .claude/package-manager.json) + * 3. package.json packageManager field + * 4. Lock file detection + * 5. Global user preference (in ~/.claude/package-manager.json) + * 6. Default to npm (no child processes spawned) + * + * @param {object} options - Options + * @param {string} options.projectDir - Project directory to detect from (default: cwd) + * @returns {object} - { name, config, source } + */ +function getPackageManager(options = {}) { + const { projectDir = process.cwd() } = options; + + // 1. Check environment variable + const envPm = process.env.CLAUDE_PACKAGE_MANAGER; + if (envPm && PACKAGE_MANAGERS[envPm]) { + return { + name: envPm, + config: PACKAGE_MANAGERS[envPm], + source: 'environment' + }; + } + + // 2. Check project-specific config + const projectConfigPath = path.join(projectDir, '.claude', 'package-manager.json'); + const projectConfig = readFile(projectConfigPath); + if (projectConfig) { + try { + const config = JSON.parse(projectConfig); + if (config.packageManager && PACKAGE_MANAGERS[config.packageManager]) { + return { + name: config.packageManager, + config: PACKAGE_MANAGERS[config.packageManager], + source: 'project-config' + }; + } + } catch { + // Invalid config + } + } + + // 3. Check package.json packageManager field + const fromPackageJson = detectFromPackageJson(projectDir); + if (fromPackageJson) { + return { + name: fromPackageJson, + config: PACKAGE_MANAGERS[fromPackageJson], + source: 'package.json' + }; + } + + // 4. Check lock file + const fromLockFile = detectFromLockFile(projectDir); + if (fromLockFile) { + return { + name: fromLockFile, + config: PACKAGE_MANAGERS[fromLockFile], + source: 'lock-file' + }; + } + + // 5. Check global user preference + const globalConfig = loadConfig(); + if (globalConfig && globalConfig.packageManager && PACKAGE_MANAGERS[globalConfig.packageManager]) { + return { + name: globalConfig.packageManager, + config: PACKAGE_MANAGERS[globalConfig.packageManager], + source: 'global-config' + }; + } + + // 6. Default to npm (always available with Node.js) + // NOTE: Previously this called getAvailablePackageManagers() which spawns + // child processes (where.exe/which) for each PM. This caused plugin freezes + // on Windows (see #162) because session-start hooks run during Bun init, + // and the spawned processes exceed Bun's spawn limit. + // Steps 1-5 already cover all config-based and file-based detection. + // If none matched, npm is the safe default. + return { + name: 'npm', + config: PACKAGE_MANAGERS.npm, + source: 'default' + }; +} + +/** + * Set user's preferred package manager (global) + */ +function setPreferredPackageManager(pmName) { + if (!PACKAGE_MANAGERS[pmName]) { + throw new Error(`Unknown package manager: ${pmName}`); + } + + const config = loadConfig() || {}; + config.packageManager = pmName; + config.setAt = new Date().toISOString(); + + try { + saveConfig(config); + } catch (err) { + throw new Error(`Failed to save package manager preference: ${err.message}`); + } + + return config; +} + +/** + * Set project's preferred package manager + */ +function setProjectPackageManager(pmName, projectDir = process.cwd()) { + if (!PACKAGE_MANAGERS[pmName]) { + throw new Error(`Unknown package manager: ${pmName}`); + } + + const configDir = path.join(projectDir, '.claude'); + const configPath = path.join(configDir, 'package-manager.json'); + + const config = { + packageManager: pmName, + setAt: new Date().toISOString() + }; + + try { + writeFile(configPath, JSON.stringify(config, null, 2)); + } catch (err) { + throw new Error(`Failed to save package manager config to ${configPath}: ${err.message}`); + } + return config; +} + +// Allowed characters in script/binary names: alphanumeric, dash, underscore, dot, slash, @ +// This prevents shell metacharacter injection while allowing scoped packages (e.g., @scope/pkg) +const SAFE_NAME_REGEX = /^[@a-zA-Z0-9_./-]+$/; + +/** + * Get the command to run a script + * @param {string} script - Script name (e.g., "dev", "build", "test") + * @param {object} options - { projectDir } + * @throws {Error} If script name contains unsafe characters + */ +function getRunCommand(script, options = {}) { + if (!script || typeof script !== 'string') { + throw new Error('Script name must be a non-empty string'); + } + if (!SAFE_NAME_REGEX.test(script)) { + throw new Error(`Script name contains unsafe characters: ${script}`); + } + + const pm = getPackageManager(options); + + switch (script) { + case 'install': + return pm.config.installCmd; + case 'test': + return pm.config.testCmd; + case 'build': + return pm.config.buildCmd; + case 'dev': + return pm.config.devCmd; + default: + return `${pm.config.runCmd} ${script}`; + } +} + +// Allowed characters in arguments: alphanumeric, whitespace, dashes, dots, slashes, +// equals, colons, commas, quotes, @. Rejects shell metacharacters like ; | & ` $ ( ) { } < > ! +const SAFE_ARGS_REGEX = /^[@a-zA-Z0-9\s_./:=,'"*+-]+$/; + +/** + * Get the command to execute a package binary + * @param {string} binary - Binary name (e.g., "prettier", "eslint") + * @param {string} args - Arguments to pass + * @throws {Error} If binary name or args contain unsafe characters + */ +function getExecCommand(binary, args = '', options = {}) { + if (!binary || typeof binary !== 'string') { + throw new Error('Binary name must be a non-empty string'); + } + if (!SAFE_NAME_REGEX.test(binary)) { + throw new Error(`Binary name contains unsafe characters: ${binary}`); + } + if (args && typeof args === 'string' && !SAFE_ARGS_REGEX.test(args)) { + throw new Error(`Arguments contain unsafe characters: ${args}`); + } + + const pm = getPackageManager(options); + return `${pm.config.execCmd} ${binary}${args ? ' ' + args : ''}`; +} + +/** + * Interactive prompt for package manager selection + * Returns a message for Claude to show to user + * + * NOTE: Does NOT spawn child processes to check availability. + * Lists all supported PMs and shows how to configure preference. + */ +function getSelectionPrompt() { + let message = '[PackageManager] No package manager preference detected.\n'; + message += 'Supported package managers: ' + Object.keys(PACKAGE_MANAGERS).join(', ') + '\n'; + message += '\nTo set your preferred package manager:\n'; + message += ' - Global: Set CLAUDE_PACKAGE_MANAGER environment variable\n'; + message += ' - Or add to ~/.claude/package-manager.json: {"packageManager": "pnpm"}\n'; + message += ' - Or add to package.json: {"packageManager": "pnpm@8"}\n'; + message += ' - Or add a lock file to your project (e.g., pnpm-lock.yaml)\n'; + + return message; +} + +// Escape regex metacharacters in a string before interpolating into a pattern +function escapeRegex(str) { + return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); +} + +/** + * Generate a regex pattern that matches commands for all package managers + * @param {string} action - Action pattern (e.g., "run dev", "install", "test") + */ +function getCommandPattern(action) { + const patterns = []; + + // Trim spaces from action to handle leading/trailing whitespace gracefully + const trimmedAction = action.trim(); + + if (trimmedAction === 'dev') { + patterns.push( + 'npm run dev', + 'pnpm( run)? dev', + 'yarn dev', + 'bun run dev' + ); + } else if (trimmedAction === 'install') { + patterns.push( + 'npm install', + 'pnpm install', + 'yarn( install)?', + 'bun install' + ); + } else if (trimmedAction === 'test') { + patterns.push( + 'npm test', + 'pnpm test', + 'yarn test', + 'bun test' + ); + } else if (trimmedAction === 'build') { + patterns.push( + 'npm run build', + 'pnpm( run)? build', + 'yarn build', + 'bun run build' + ); + } else { + // Generic run command — escape regex metacharacters in action + const escaped = escapeRegex(trimmedAction); + patterns.push( + `npm run ${escaped}`, + `pnpm( run)? ${escaped}`, + `yarn ${escaped}`, + `bun run ${escaped}` + ); + } + + return `(${patterns.join('|')})`; +} + +module.exports = { + PACKAGE_MANAGERS, + DETECTION_PRIORITY, + getPackageManager, + setPreferredPackageManager, + setProjectPackageManager, + getAvailablePackageManagers, + detectFromLockFile, + detectFromPackageJson, + getRunCommand, + getExecCommand, + getSelectionPrompt, + getCommandPattern +}; diff --git a/github_code/affaan-m__ECC/scripts/lib/path-safety.js b/github_code/affaan-m__ECC/scripts/lib/path-safety.js new file mode 100644 index 0000000000000000000000000000000000000000..95a64138fb2154cebf1340fcdbe150cd18a13279 --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/path-safety.js @@ -0,0 +1,109 @@ +'use strict'; + +const fs = require('fs'); +const path = require('path'); + +/** + * Path containment helpers for install-state-driven file operations. + * + * Install-state files are project-local and therefore attacker-controllable + * (a cloned/forked repo can ship a crafted `.cursor/ecc-install-state.json`). + * `repair`/`uninstall`/`auto-update` replay recorded operations, so every + * write/delete destination MUST be confined to the adapter-derived trusted + * root - never trusted from the state file itself (GHSA-hfpv-w6mp-5g95). + */ + +function pathEntryExists(target) { + try { + fs.lstatSync(target); + return true; + } catch (error) { + if (error && (error.code === 'ENOENT' || error.code === 'ENOTDIR')) { + return false; + } + throw error; + } +} + +/** + * Canonicalize a path that may not exist yet: realpath its nearest existing + * ancestor, then re-append the missing tail. This defeats symlink escapes + * where an intermediate directory is a symlink pointing out of the root. + */ +function realpathNearestExisting(target) { + let current = path.resolve(target); + const tail = []; + while (!pathEntryExists(current)) { + const parent = path.dirname(current); + if (parent === current) { + break; + } + tail.unshift(path.basename(current)); + current = parent; + } + const real = fs.realpathSync(current); + return tail.length > 0 ? path.join(real, ...tail) : real; +} + +/** + * True when `target` resolves to `root` itself or a path beneath it, with + * symlinks resolved on both sides. + */ +function resolveContainment(target, root) { + const realRoot = realpathNearestExisting(root); + const realTarget = realpathNearestExisting(target); + const relativePath = path.relative(realRoot, realTarget); + const contained = relativePath === '' + || ( + relativePath !== '..' + && !relativePath.startsWith(`..${path.sep}`) + && !path.isAbsolute(relativePath) + ); + return { + contained, + realRoot, + realTarget + }; +} + +function isWithinRoot(target, root) { + if (!root) { + return false; + } + + try { + return resolveContainment(target, root).contained; + } catch { + return false; + } +} + +/** + * Fail-closed guard: throw unless `target` is contained within `root`. + * Returns the canonicalized target path on success. + */ +function assertWithinTrustedRoot(target, root, action = 'write') { + if (!target || typeof target !== 'string') { + throw new Error(`Refusing to ${action}: missing destination path.`); + } + if (!root) { + throw new Error(`Refusing to ${action} '${target}': no trusted install root resolved.`); + } + + let containment; + try { + containment = resolveContainment(target, root); + } catch { + containment = null; + } + if (!containment || !containment.contained) { + throw new Error(`Refusing to ${action} outside the install root: '${target}' is not within '${root}'.`); + } + return containment.realTarget; +} + +module.exports = { + realpathNearestExisting, + isWithinRoot, + assertWithinTrustedRoot +}; diff --git a/github_code/affaan-m__ECC/scripts/lib/plan-canvas/markdown.js b/github_code/affaan-m__ECC/scripts/lib/plan-canvas/markdown.js new file mode 100644 index 0000000000000000000000000000000000000000..94167141e4d5e83298484114333650c30ff42689 --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/plan-canvas/markdown.js @@ -0,0 +1,299 @@ +'use strict'; + +/** + * Minimal GitHub-flavored-markdown subset renderer for Plan Canvas. + * Renders .claude/plans/*.plan.md artifacts to HTML body content. + * + * Security model: the entire source line is HTML-escaped before any inline + * rule runs, so raw HTML in the markdown always displays as text. Link and + * image URLs are validated against an allowlist of protocols. + */ + +// Placeholders live in the Unicode private-use area so escaped output can +// never collide with them. Pre-existing occurrences are stripped from input. +const TOKEN_OPEN = '\uE000'; +const TOKEN_CLOSE = '\uE001'; +const TOKEN_RE = new RegExp(TOKEN_OPEN + '(\\d+)' + TOKEN_CLOSE, 'g'); +const STRIP_RE = new RegExp('[' + TOKEN_OPEN + TOKEN_CLOSE + ']', 'g'); + +const LIST_ITEM_RE = /^(\s*)([-*]|\d+\.)\s+(.*)$/; +const HR_RE = /^ {0,3}(-{3,}|\*{3,})\s*$/; + +function escapeHtml(value) { + return String(value ?? '') + .replace(/&/g, '&') + .replace(//g, '>') + .replace(/"/g, '"') + .replace(/'/g, '''); +} + +function slugify(text) { + return String(text ?? '') + .toLowerCase() + .replace(/[^a-z0-9\s-]/g, '') + .trim() + .replace(/[\s-]+/g, '-') + .replace(/^-+|-+$/g, ''); +} + +// Strip whitespace/control characters so "Ja vaScript:" style tricks cannot +// hide a scheme, then classify against the allowlist. +function classifyUrl(rawUrl) { + const compact = String(rawUrl) + .split('') + .filter((ch) => ch.charCodeAt(0) > 32) + .join('') + .toLowerCase(); + if (compact.startsWith('#')) return 'anchor'; + if (compact.startsWith('//')) return 'blocked'; + const scheme = compact.match(/^[a-z][a-z0-9+.-]*:/); + if (!scheme) return 'relative'; + if (scheme[0] === 'http:' || scheme[0] === 'https:') return 'http'; + if (scheme[0] === 'mailto:') return 'mailto'; + return 'blocked'; +} + +function applyEmphasis(s) { + return s + .replace(/\*\*([^*]+)\*\*/g, '$1') + .replace(/~~([^~]+)~~/g, '$1') + .replace(/\*([^*]+)\*/g, '$1') + .replace(/(^|[^\w])_([^_]+)_(?!\w)/g, '$1$2'); +} + +function renderInline(rawText) { + const tokens = []; + const stash = (html) => { + tokens.push(html); + return TOKEN_OPEN + (tokens.length - 1) + TOKEN_CLOSE; + }; + + let s = escapeHtml(rawText); + + // Code spans first: contents stay escaped and opt out of all other rules. + s = s.replace(/`([^`]+)`/g, (_m, code) => stash('' + code + '')); + + s = s.replace(/!\[([^\]]*)\]\(([^)]*)\)/g, (_m, alt, src) => { + const kind = classifyUrl(src); + if (kind !== 'http' && kind !== 'relative') return alt; + return stash('' + alt + ''); + }); + + s = s.replace(/\[([^\]]+)\]\(([^)]*)\)/g, (_m, label, url) => { + const kind = classifyUrl(url); + const text = applyEmphasis(label); + if (kind === 'blocked') return text; + const extra = kind === 'http' ? ' target="_blank" rel="noopener"' : ''; + return stash('' + text + ''); + }); + + s = applyEmphasis(s); + + // Stashed anchors may hold code-span tokens, so resolve until none remain. + while (s.includes(TOKEN_OPEN)) { + s = s.replace(TOKEN_RE, (_m, idx) => tokens[Number(idx)]); + } + return s; +} + +function splitTableRow(line) { + let s = line.trim(); + if (s.startsWith('|')) s = s.slice(1); + if (s.endsWith('|') && !s.endsWith('\\|')) s = s.slice(0, -1); + return s + .replace(/\\\|/g, TOKEN_OPEN) + .split('|') + .map((cell) => cell.split(TOKEN_OPEN).join('|').trim()); +} + +function isAlignmentRow(line) { + if (!line || !line.includes('|')) return false; + const cells = splitTableRow(line); + return cells.length > 0 && cells.every((cell) => /^:?-+:?$/.test(cell)); +} + +function cellAlign(spec) { + const left = spec.startsWith(':'); + const right = spec.endsWith(':'); + if (left && right) return 'center'; + if (right) return 'right'; + if (left) return 'left'; + return ''; +} + +function renderListItem(text) { + const task = text.match(/^\[([ xX])\]\s+(.*)$/); + if (task) { + const checked = task[1].trim() ? ' checked' : ''; + return '
  • ' + + renderInline(task[2]) + '
  • '; + } + return '
  • ' + renderInline(text) + '
  • '; +} + +function listTag(marker) { + return /^\d/.test(marker) ? 'ol' : 'ul'; +} + +function buildList(items, start, indent) { + const tag = listTag(items[start].marker); + const parts = []; + let i = start; + while (i < items.length && items[i].indent >= indent) { + if (items[i].indent > indent) { + // Deeper item: nest a sublist inside the previous
  • + const nested = buildList(items, i, items[i].indent); + if (parts.length > 0) { + const last = parts.pop(); + parts.push(last.replace(/<\/li>$/, '\n' + nested.html + '\n
  • ')); + } else { + parts.push('
  • \n' + nested.html + '\n
  • '); + } + i = nested.end; + } else { + // A marker-type change at the same indent starts a new list + // (CommonMark); stop here so the caller renders the next run with + // its own tag instead of absorbing it into this one. + if (listTag(items[i].marker) !== tag) break; + parts.push(renderListItem(items[i].text)); + i += 1; + } + } + return { html: '<' + tag + '>\n' + parts.join('\n') + '\n', end: i }; +} + +function buildListBlock(items) { + let lists = []; + let i = 0; + while (i < items.length) { + const list = buildList(items, i, items[i].indent); + lists = [...lists, list.html]; + i = list.end; + } + return lists.join('\n'); +} + +function startsBlock(line, nextLine) { + return /^```/.test(line) || + /^#{1,6}\s/.test(line) || + HR_RE.test(line) || + /^ {0,3}>/.test(line) || + LIST_ITEM_RE.test(line) || + (line.includes('|') && isAlignmentRow(nextLine || '')); +} + +function renderMarkdown(text) { + if (!text) return ''; + const lines = String(text) + .replace(STRIP_RE, '') + .replace(/\r\n?/g, '\n') + .split('\n'); + const out = []; + let i = 0; + + while (i < lines.length) { + const line = lines[i]; + + if (!line.trim()) { + i += 1; + continue; + } + + const fence = line.match(/^```(.*)$/); + if (fence) { + const lang = fence[1].trim().split(/\s+/)[0].toLowerCase().replace(/[^a-z0-9-]/g, ''); + const body = []; + i += 1; + while (i < lines.length && !/^```\s*$/.test(lines[i])) { + body.push(lines[i]); + i += 1; + } + i += 1; // skip closing fence (or run off EOF) + if (lang === 'mermaid') { + // Mermaid reads the element's textContent, and the browser decodes + // character references there — so escaping keeps `-->`/`<` intact for + // the renderer while preventing HTML injection or a breakout. + out.push('
    ' + escapeHtml(body.join('\n')) + '
    '); + continue; + } + const cls = lang ? ' class="language-' + lang + '"' : ''; + out.push('
    ' + escapeHtml(body.join('\n')) + '
    '); + continue; + } + + const heading = line.match(/^(#{1,6})\s+(.+?)\s*$/); + if (heading) { + const level = heading[1].length; + out.push('' + + renderInline(heading[2]) + ''); + i += 1; + continue; + } + + // Horizontal rule (alignment rows never reach here: tables consume them) + if (HR_RE.test(line)) { + out.push('
    '); + i += 1; + continue; + } + + // Blockquote: strip one `>` level and recurse, which handles nesting + if (/^ {0,3}>/.test(line)) { + const inner = []; + while (i < lines.length && /^ {0,3}>/.test(lines[i])) { + inner.push(lines[i].replace(/^ {0,3}> ?/, '')); + i += 1; + } + out.push('
    \n' + renderMarkdown(inner.join('\n')) + '\n
    '); + continue; + } + + // Table: header row followed by an alignment row + if (line.includes('|') && isAlignmentRow(lines[i + 1] || '')) { + const aligns = splitTableRow(lines[i + 1]).map(cellAlign); + const row = (tag, cells) => '' + cells.map((cell, idx) => { + const style = aligns[idx] ? ' style="text-align:' + aligns[idx] + '"' : ''; + return '<' + tag + style + '>' + renderInline(cell) + ''; + }).join('') + ''; + const head = row('th', splitTableRow(line)); + const body = []; + i += 2; + while (i < lines.length && lines[i].trim() && lines[i].includes('|')) { + body.push(row('td', splitTableRow(lines[i]))); + i += 1; + } + out.push('\n\n' + head + '\n\n\n' + + body.join('\n') + '\n\n
    '); + continue; + } + + if (LIST_ITEM_RE.test(line)) { + const items = []; + while (i < lines.length) { + const m = lines[i].match(LIST_ITEM_RE); + if (!m) break; + items.push({ indent: m[1].length, marker: m[2], text: m[3] }); + i += 1; + } + // An outdent below the first item's indentation ends that list. Render + // the remaining run as a sibling list so malformed indentation cannot + // silently drop content or create an empty parent item. + out.push(buildListBlock(items)); + continue; + } + + // Paragraph: run of plain lines up to a blank line or block start + const para = [line.trim()]; + i += 1; + while (i < lines.length && lines[i].trim() && !startsBlock(lines[i], lines[i + 1])) { + para.push(lines[i].trim()); + i += 1; + } + out.push('

    ' + renderInline(para.join('\n')) + '

    '); + } + + return out.join('\n'); +} + +module.exports = { renderMarkdown, escapeHtml, slugify }; diff --git a/github_code/affaan-m__ECC/scripts/lib/plan-canvas/sdk.js b/github_code/affaan-m__ECC/scripts/lib/plan-canvas/sdk.js new file mode 100644 index 0000000000000000000000000000000000000000..a5110914d9d7eff85717e84dfb314e1b5685b338 --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/plan-canvas/sdk.js @@ -0,0 +1,237 @@ +'use strict'; + +/** + * Plan Canvas artifact SDK — the script injected into the reviewed artifact. + * + * The artifact runs in a sandboxed iframe without allow-same-origin, so this + * script can only talk to the chrome via postMessage. It renders all of its + * own UI inside a shadow root so it never annotates itself and never leaks + * styles into the artifact. + */ + +function artifactSdkJs() { + return `'use strict'; +(() => { + if (window.parent === window) return; // only meaningful inside the canvas + if (window.__eccPlanCanvasSdk) return; + window.__eccPlanCanvasSdk = true; + + let annotate = true; + let card = null; + + const post = msg => window.parent.postMessage(msg, '*'); + + // --- shadow-root UI host -------------------------------------------- + const host = document.createElement('div'); + host.setAttribute('data-ecc-plan-canvas', 'ui'); + host.style.cssText = 'position:absolute;top:0;left:0;width:0;height:0;z-index:2147483647'; + const root = host.attachShadow({ mode: 'open' }); + root.innerHTML = \` + +
    + +
    +

    +
    + +
    + + +
    +
    Enter to queue · Cmd/Ctrl+Enter to queue & send
    +
    \`; + const attach = () => document.body ? document.body.appendChild(host) : null; + if (document.body) attach(); + else document.addEventListener('DOMContentLoaded', attach); + + const hl = root.querySelector('.hl'); + const selhint = root.querySelector('.selhint'); + const cardEl = root.querySelector('.card'); + const cardTitle = cardEl.querySelector('h4'); + const cardSnippet = cardEl.querySelector('.snippet'); + const cardText = cardEl.querySelector('textarea'); + + // --- selectors & context --------------------------------------------- + const esc = v => (window.CSS && CSS.escape) ? CSS.escape(v) : v.replace(/[^a-zA-Z0-9_-]/g, '\\\\$&'); + function selectorFor(el) { + const parts = []; + let node = el; + for (let depth = 0; node && node.nodeType === 1 && depth < 6; depth++) { + if (node.id) { parts.unshift('#' + esc(node.id)); return parts.join(' > '); } + const tag = node.tagName.toLowerCase(); + if (tag === 'body' || tag === 'html') { parts.unshift(tag); break; } + let nth = 1; + let sib = node; + while ((sib = sib.previousElementSibling)) if (sib.tagName === node.tagName) nth++; + parts.unshift(tag + ':nth-of-type(' + nth + ')'); + node = node.parentElement; + } + return parts.join(' > '); + } + function snippetFor(el) { + return (el.innerText || el.textContent || '').replace(/\\s+/g, ' ').trim().slice(0, 200); + } + const INTERACTIVE = new Set(['button', 'input', 'select', 'textarea', 'option', 'label', 'summary', 'a']); + function isInteractive(el) { + let node = el; + while (node && node.nodeType === 1) { + if (INTERACTIVE.has(node.tagName.toLowerCase()) || node.isContentEditable) return true; + node = node.parentElement; + } + return false; + } + const isOurs = el => el === host || host.contains(el); + + // --- annotation card --------------------------------------------------- + function openCard(target) { + card = target; + cardTitle.textContent = target.kindLabel; + cardSnippet.textContent = target.anchor.snippet || target.anchor.selector; + cardText.value = ''; + cardEl.style.display = 'block'; + const x = Math.min(target.x, window.innerWidth - 320) + window.scrollX; + const y = target.y + 12 + window.scrollY; + cardEl.style.left = Math.max(8, x) + 'px'; + cardEl.style.top = y + 'px'; + cardText.focus(); + } + function closeCard() { + card = null; + cardEl.style.display = 'none'; + } + function queueCard(sendNow) { + if (!card) return; + const text = cardText.value.trim(); + if (!text) { cardText.focus(); return; } + post({ + type: sendNow ? 'pc:queue-and-send' : 'pc:queue', + item: { kind: 'annotation', text, anchor: card.anchor } + }); + closeCard(); + } + cardEl.querySelector('.cancel').addEventListener('click', closeCard); + cardEl.querySelector('.queue').addEventListener('click', () => queueCard(false)); + cardText.addEventListener('keydown', e => { + if (e.key === 'Enter' && (e.metaKey || e.ctrlKey)) { e.preventDefault(); queueCard(true); } + else if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); queueCard(false); } + else if (e.key === 'Escape') closeCard(); + }); + + // --- element hover / click --------------------------------------------- + document.addEventListener('mousemove', e => { + if (!annotate || card) { hl.style.display = 'none'; return; } + const el = e.target; + if (!el || isOurs(el) || el === document.body || el === document.documentElement || isInteractive(el)) { + hl.style.display = 'none'; + return; + } + const rect = el.getBoundingClientRect(); + hl.style.display = 'block'; + hl.style.left = rect.left - 2 + 'px'; + hl.style.top = rect.top - 2 + 'px'; + hl.style.width = rect.width + 'px'; + hl.style.height = rect.height + 'px'; + }, true); + + document.addEventListener('click', e => { + if (!annotate) return; + const el = e.target; + if (isOurs(el)) return; + if (card) { if (!cardEl.contains(e.composedPath()[0])) closeCard(); return; } + if (isInteractive(el)) return; // let controls behave natively + const selection = window.getSelection(); + if (selection && !selection.isCollapsed) return; // handled by selection flow + if (el === document.body || el === document.documentElement) return; + e.preventDefault(); + e.stopPropagation(); + hl.style.display = 'none'; + openCard({ + kindLabel: 'Annotate <' + el.tagName.toLowerCase() + '>', + anchor: { selector: selectorFor(el), tag: el.tagName.toLowerCase(), snippet: snippetFor(el) }, + x: e.clientX, + y: e.clientY + }); + }, true); + + // --- text selection ------------------------------------------------------- + document.addEventListener('mouseup', e => { + if (!annotate || card || isOurs(e.target)) return; + setTimeout(() => { + const selection = window.getSelection(); + const text = selection ? String(selection).replace(/\\s+/g, ' ').trim() : ''; + if (!text || !selection.rangeCount) { selhint.style.display = 'none'; return; } + const rect = selection.getRangeAt(0).getBoundingClientRect(); + selhint.style.display = 'block'; + selhint.style.left = rect.left + window.scrollX + 'px'; + selhint.style.top = rect.bottom + 6 + window.scrollY + 'px'; + selhint.onclick = () => { + selhint.style.display = 'none'; + const anchorNode = selection.anchorNode; + const el = anchorNode && anchorNode.nodeType === 1 ? anchorNode : anchorNode && anchorNode.parentElement; + openCard({ + kindLabel: 'Annotate selection', + anchor: { + selector: el ? selectorFor(el) : 'body', + tag: 'text', + snippet: text.slice(0, 200), + textRange: { text: text.slice(0, 1000) } + }, + x: rect.left, + y: rect.bottom + }); + }; + }, 0); + }, true); + document.addEventListener('selectionchange', () => { + const selection = window.getSelection(); + if (!selection || selection.isCollapsed) selhint.style.display = 'none'; + }); + + // --- chrome bridge --------------------------------------------------------- + window.addEventListener('message', e => { + const msg = e.data || {}; + if (msg.type === 'pc:set-mode') { + annotate = Boolean(msg.annotate); + if (!annotate) { hl.style.display = 'none'; selhint.style.display = 'none'; closeCard(); } + } else if (msg.type === 'pc:restore-scroll') { + window.scrollTo(msg.x || 0, msg.y || 0); + } + }); + document.addEventListener('keydown', e => { + if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'i') { + e.preventDefault(); + post({ type: 'pc:toggle-mode' }); + } else if (e.key === 'Escape' && card) closeCard(); + }, true); + + let scrollTimer = null; + window.addEventListener('scroll', () => { + if (scrollTimer) return; + scrollTimer = setTimeout(() => { + scrollTimer = null; + post({ type: 'pc:scroll', x: window.scrollX, y: window.scrollY }); + }, 150); + }, { passive: true }); + + post({ type: 'pc:ready' }); +})();`; +} + +module.exports = { artifactSdkJs }; diff --git a/github_code/affaan-m__ECC/scripts/lib/plan-canvas/server.js b/github_code/affaan-m__ECC/scripts/lib/plan-canvas/server.js new file mode 100644 index 0000000000000000000000000000000000000000..11b44062a3c11d03bc5756a91aa7f7999e8e9e2f --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/plan-canvas/server.js @@ -0,0 +1,634 @@ +'use strict'; + +/** + * Plan Canvas loopback server. + * + * One detached process serves every open review session: the browser chrome, + * the rendered artifact, an SSE stream for live updates, and the long-poll + * endpoint agents block on. Sessions are keyed by canonical artifact path + * (see sessions.js). + */ + +const { EventEmitter } = require('events'); +const fs = require('fs'); +const http = require('http'); +const path = require('path'); + +const { buildAllowedHostnames, isAllowedHostHeader, isAllowedOrigin } = require('../loopback-guard'); +const { renderMarkdown } = require('./markdown'); +const { artifactSdkJs } = require('./sdk'); +const { + canvasCss, + canvasClientJs, + renderCanvasHtml, + renderMarkdownArtifactHtml, + renderSessionListHtml +} = require('./ui'); + +const DEFAULT_PORT = 4517; +const DEFAULT_HOST = '127.0.0.1'; +const DEFAULT_IDLE_TIMEOUT_MS = 30 * 60 * 1000; +const MAX_BODY_BYTES = 1024 * 1024; +// How long the "agent is thinking" indicator survives without the agent +// checking back in, before presence decays to the honest queued/waiting. +const DEFAULT_THINKING_STALE_MS = 90 * 1000; +// An explicit typing signal expires faster: it means "a reply is seconds away". +const DEFAULT_TYPING_EXPIRY_MS = 30 * 1000; +// Presence is push-based, so expiring states need a tick to re-broadcast on. +const DEFAULT_PRESENCE_SWEEP_MS = 5 * 1000; +const TYPING_STATES = new Set(['thinking', 'typing', 'idle']); + +const CONTENT_TYPES = { + '.css': 'text/css; charset=utf-8', + '.gif': 'image/gif', + '.html': 'text/html; charset=utf-8', + '.ico': 'image/x-icon', + '.jpeg': 'image/jpeg', + '.jpg': 'image/jpeg', + '.js': 'text/javascript; charset=utf-8', + '.json': 'application/json; charset=utf-8', + '.md': 'text/plain; charset=utf-8', + '.mjs': 'text/javascript; charset=utf-8', + '.png': 'image/png', + '.svg': 'image/svg+xml', + '.ttf': 'font/ttf', + '.txt': 'text/plain; charset=utf-8', + '.webp': 'image/webp', + '.woff': 'font/woff', + '.woff2': 'font/woff2' +}; + +function resolvePort(env = process.env) { + const value = Number.parseInt(env.ECC_PLAN_CANVAS_PORT || '', 10); + return Number.isInteger(value) && value >= 0 && value <= 65535 ? value : DEFAULT_PORT; +} + +function resolveIdleTimeoutMs(env = process.env) { + const raw = String(env.ECC_PLAN_CANVAS_IDLE_MS || '').trim().toLowerCase(); + if (raw === '0' || raw === 'off') return 0; + const value = Number.parseInt(raw, 10); + return Number.isInteger(value) && value > 0 ? value : DEFAULT_IDLE_TIMEOUT_MS; +} + +function readJsonBody(req) { + return new Promise((resolve, reject) => { + let size = 0; + const chunks = []; + req.on('data', chunk => { + size += chunk.length; + if (size > MAX_BODY_BYTES) { + reject(new Error('body too large')); + req.destroy(); + return; + } + chunks.push(chunk); + }); + req.on('end', () => { + if (chunks.length === 0) return resolve({}); + try { + resolve(JSON.parse(Buffer.concat(chunks).toString('utf8'))); + } catch { + reject(new Error('invalid JSON body')); + } + }); + req.on('error', reject); + }); +} + +function sendJson(res, statusCode, payload) { + const body = JSON.stringify(payload); + res.writeHead(statusCode, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' }); + res.end(body); +} + +function sendHtml(res, statusCode, html, { csp = true } = {}) { + const headers = { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-store' }; + if (csp) { + headers['content-security-policy'] = + "default-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:; frame-src 'self'"; + } + res.writeHead(statusCode, headers); + res.end(html); +} + +function createPlanCanvasServer({ + store, + host = DEFAULT_HOST, + version = '0.0.0', + idleTimeoutMs = DEFAULT_IDLE_TIMEOUT_MS, + heartbeatMs = 15000, + thinkingStaleMs = DEFAULT_THINKING_STALE_MS, + typingExpiryMs = DEFAULT_TYPING_EXPIRY_MS, + presenceSweepMs = DEFAULT_PRESENCE_SWEEP_MS, + onIdleShutdown = null, + log = () => {} +} = {}) { + if (!store) throw new Error('createPlanCanvasServer requires a session store'); + + const allowedHostnames = buildAllowedHostnames(host); + const wake = new EventEmitter(); + wake.setMaxListeners(0); + const sseClients = new Map(); // key -> Set + const awaitCounts = new Map(); // key -> active long-poll count + const workingKeys = new Map(); // key -> ms timestamp the agent took feedback + const typingKeys = new Map(); // key -> ms timestamp the agent signalled composing + const watchers = new Map(); // key -> fs.FSWatcher + const lastPresence = new Map(); // key -> last broadcast state, for sweep diffing + let idleTimer = null; + let presenceSweep = null; + let closed = false; + + // --- presence + SSE --------------------------------------------------- + + /** + * Presence never claims more than the server actually knows: + * + * ended session is closed + * typing agent signalled it is composing a reply (self-expiring) + * thinking agent took the feedback and is working on it (self-expiring) + * listening an `await` long poll is parked on this session right now + * queued feedback is sitting undelivered with nobody listening + * waiting nothing queued, nobody listening + * + * `thinking` and `typing` expire on their own so a crashed or distracted + * agent decays to an honest `queued`/`waiting` instead of spinning forever. + * The old `working` pill had no expiry and no re-broadcast, so it stuck at + * "agent working" while nothing at all was listening. + */ + function presenceFor(key, now = Date.now()) { + const session = store.get(key); + if (!session || session.status === 'ended') return 'ended'; + const typingAt = typingKeys.get(key); + if (typingAt !== undefined && now - typingAt < typingExpiryMs) return 'typing'; + const workingAt = workingKeys.get(key); + if (workingAt !== undefined && now - workingAt < thinkingStaleMs) return 'thinking'; + if ((awaitCounts.get(key) || 0) > 0) return 'listening'; + return session.pendingFeedback && session.pendingFeedback.length > 0 ? 'queued' : 'waiting'; + } + + function broadcast(key, event, payload) { + const clients = sseClients.get(key); + if (!clients) return; + const frameText = `event: ${event}\ndata: ${JSON.stringify(payload)}\n\n`; + for (const client of clients) client.write(frameText); + } + + function broadcastPresence(key) { + const state = presenceFor(key); + lastPresence.set(key, state); + broadcast(key, 'presence', { state }); + } + + // Re-broadcast only where an expiry actually changed the answer, so an + // untouched canvas sees the thinking bubble clear itself. + function sweepPresence() { + for (const key of sseClients.keys()) { + const state = presenceFor(key); + if (lastPresence.get(key) !== state) broadcastPresence(key); + } + } + + function startPresenceSweep() { + if (presenceSweep || !presenceSweepMs) return; + presenceSweep = setInterval(sweepPresence, presenceSweepMs); + if (presenceSweep.unref) presenceSweep.unref(); + } + + // The agent is off working on this feedback batch; start the thinking clock. + function markThinking(key) { + workingKeys.set(key, Date.now()); + typingKeys.delete(key); + } + + // A reply landed (or the agent picked the session back up): stop pretending. + function clearAgentActivity(key) { + workingKeys.delete(key); + typingKeys.delete(key); + } + + function connectionCount() { + let total = 0; + for (const clients of sseClients.values()) total += clients.size; + for (const count of awaitCounts.values()) total += count; + return total; + } + + function armIdleTimer() { + if (!idleTimeoutMs || closed) return; + if (connectionCount() > 0) return; + clearTimeout(idleTimer); + idleTimer = setTimeout(() => { + if (connectionCount() === 0 && !closed) { + log('[plan-canvas] idle timeout reached, shutting down'); + if (onIdleShutdown) onIdleShutdown(); + } + }, idleTimeoutMs); + if (idleTimer.unref) idleTimer.unref(); + } + + function noteConnectionOpened() { + clearTimeout(idleTimer); + } + + function noteConnectionClosed() { + armIdleTimer(); + } + + // --- artifact watching -------------------------------------------------- + + function watchSession(session) { + if (watchers.has(session.key)) return; + const dir = path.dirname(session.file); + const base = path.basename(session.file); + let debounce = null; + try { + const watcher = fs.watch(dir, (eventType, filename) => { + if (filename && filename !== base) return; + clearTimeout(debounce); + debounce = setTimeout(() => broadcast(session.key, 'reload', {}), 150); + }); + watcher.on('error', () => watchers.delete(session.key)); + watchers.set(session.key, watcher); + } catch { + // Watching is best-effort; manual reload still works. + } + } + + function unwatchSession(key) { + const watcher = watchers.get(key); + if (watcher) { + watcher.close(); + watchers.delete(key); + } + } + + // --- session actions ------------------------------------------------------ + + function endSession(key, endedBy) { + const session = store.end(key, endedBy); + if (!session) return null; + clearAgentActivity(key); + wake.emit(`wake:${key}`); + broadcast(key, 'ended', { endedBy: session.endedBy }); + broadcastPresence(key); + unwatchSession(key); + return session; + } + + // --- request handlers ------------------------------------------------------- + + async function handleApi(req, res, url) { + const { pathname } = url; + + if (req.method === 'POST' && pathname === '/api/sessions') { + const body = await readJsonBody(req); + if (!body.file || typeof body.file !== 'string') { + return sendJson(res, 400, { error: 'file is required' }); + } + if (!fs.existsSync(path.resolve(body.file))) { + return sendJson(res, 404, { error: `artifact not found: ${body.file}` }); + } + const { session, refused } = store.open(body.file, { reopen: Boolean(body.reopen) }); + if (refused) { + return sendJson(res, 409, { + status: 'user-ended', + key: session.key, + next_step: 'The user ended this review from the browser. Do not reopen it unless they ask; pass reopen:true when they do.' + }); + } + watchSession(session); + broadcastPresence(session.key); + return sendJson(res, 200, { + status: 'open', + key: session.key, + file: session.file, + url: `/canvas/${session.key}` + }); + } + + if (req.method === 'GET' && pathname === '/api/sessions') { + return sendJson(res, 200, { sessions: store.list() }); + } + + if (req.method === 'GET' && pathname === '/api/await') { + const keyParam = url.searchParams.get('key'); + const file = url.searchParams.get('file'); + if (keyParam && !/^[a-f0-9]{12}$/.test(keyParam)) return sendJson(res, 400, { error: 'invalid session key' }); + if (!keyParam && !file) return sendJson(res, 400, { error: 'key or file query parameter is required' }); + const session = keyParam ? store.get(keyParam) : store.findByFile(file); + if (!session) return sendJson(res, 200, { status: 'missing' }); + const key = session.key; + const timeoutRaw = url.searchParams.get('timeoutMs'); + const timeoutMs = timeoutRaw === null ? null : Math.max(0, Number.parseInt(timeoutRaw, 10) || 0); + + const first = store.takeFeedback(key); + if (first.status !== 'waiting') { + if (first.status === 'feedback') markThinking(key); + broadcastPresence(key); + return sendJson(res, 200, first); + } + + // Long poll: hold the request open until feedback or session end. + noteConnectionOpened(); + awaitCounts.set(key, (awaitCounts.get(key) || 0) + 1); + clearAgentActivity(key); + broadcastPresence(key); + + let settled = false; + let heartbeat = null; + let waitTimer = null; + const finish = payload => { + if (settled) return; + settled = true; + cleanup(); + if (payload) { + if (payload.status === 'feedback') markThinking(key); + res.end(JSON.stringify(payload)); + } + broadcastPresence(key); + noteConnectionClosed(); + }; + const onWake = () => { + const result = store.takeFeedback(key); + if (result.status !== 'waiting') finish(result); + }; + // Settle held polls on shutdown so server.close() can complete; the + // CLI tells agents to simply re-run await. + const onServerClose = () => + finish({ status: 'waiting', note: 'canvas server is shutting down; re-run await' }); + const cleanup = () => { + wake.removeListener(`wake:${key}`, onWake); + wake.removeListener('server-close', onServerClose); + clearInterval(heartbeat); + clearTimeout(waitTimer); + awaitCounts.set(key, Math.max(0, (awaitCounts.get(key) || 1) - 1)); + }; + + res.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' }); + // Leading whitespace keeps the connection visibly alive without + // corrupting the JSON payload written at the end. + res.write(' '); + heartbeat = setInterval(() => { + if (!settled) res.write(' '); + }, heartbeatMs); + if (timeoutMs !== null) { + waitTimer = setTimeout(() => finish({ status: 'waiting' }), timeoutMs); + } + wake.on(`wake:${key}`, onWake); + wake.once('server-close', onServerClose); + req.on('close', () => finish(null)); + return undefined; + } + + if (req.method === 'POST' && pathname === '/api/end') { + const body = await readJsonBody(req); + if (!body.file || typeof body.file !== 'string') { + return sendJson(res, 400, { error: 'file is required' }); + } + const session = store.findByFile(body.file); + if (!session) return sendJson(res, 404, { error: 'no session for that file' }); + endSession(session.key, 'agent'); + return sendJson(res, 200, { status: 'ended', endedBy: 'agent' }); + } + + const sessionMatch = pathname.match(/^\/api\/session\/([a-f0-9]{12})\/(feedback|end|reply|typing)$/); + if (sessionMatch && req.method === 'POST') { + const [, key, action] = sessionMatch; + const session = store.get(key); + if (!session) return sendJson(res, 404, { error: 'unknown session' }); + + if (action === 'feedback') { + const body = await readJsonBody(req); + const result = store.queueFeedback(key, body.items, { endSession: Boolean(body.endSession) }); + if (!result) return sendJson(res, 409, { error: 'session already ended' }); + wake.emit(`wake:${key}`); + broadcast(key, 'chat-sync', { chat: store.get(key).chat }); + if (body.endSession) broadcast(key, 'ended', { endedBy: 'user' }); + // A parked `await` takes the batch synchronously on the wake above, so + // presence is already `thinking` by now; with nobody listening it + // reports `queued`. Either way the browser must be told, which the + // original handler never did, leaving a stale pill on screen. + broadcastPresence(key); + return sendJson(res, 200, { + status: 'queued', + accepted: result.accepted.length, + pending: result.pending, + presence: presenceFor(key) + }); + } + + if (action === 'end') { + endSession(key, 'user'); + return sendJson(res, 200, { status: 'ended', endedBy: 'user' }); + } + + if (action === 'reply') { + const body = await readJsonBody(req); + if (!body.text || typeof body.text !== 'string') { + return sendJson(res, 400, { error: 'text is required' }); + } + const entry = store.addAgentReply(key, body.text); + clearAgentActivity(key); + broadcast(key, 'chat-sync', { chat: store.get(key).chat }); + broadcastPresence(key); + return sendJson(res, 200, { status: 'sent', at: entry.at }); + } + + // Agents drive the chat indicator explicitly: `thinking` while they work, + // `typing` right before a reply lands, `idle` to take the bubble down. + if (action === 'typing') { + const body = await readJsonBody(req); + const state = typeof body.state === 'string' ? body.state : 'typing'; + if (!TYPING_STATES.has(state)) { + return sendJson(res, 400, { error: `state must be one of: ${[...TYPING_STATES].join(', ')}` }); + } + if (state === 'idle') clearAgentActivity(key); + else if (state === 'typing') typingKeys.set(key, Date.now()); + else markThinking(key); + broadcastPresence(key); + return sendJson(res, 200, { status: 'ok', presence: presenceFor(key) }); + } + } + + return sendJson(res, 404, { error: 'not found' }); + } + + function handleEvents(req, res, key) { + const session = store.get(key); + if (!session) return sendJson(res, 404, { error: 'unknown session' }); + noteConnectionOpened(); + res.writeHead(200, { + 'content-type': 'text/event-stream', + 'cache-control': 'no-store', + connection: 'keep-alive' + }); + res.write(`event: chat-sync\ndata: ${JSON.stringify({ chat: session.chat })}\n\n`); + res.write(`event: presence\ndata: ${JSON.stringify({ state: presenceFor(key) })}\n\n`); + if (!sseClients.has(key)) sseClients.set(key, new Set()); + sseClients.get(key).add(res); + lastPresence.set(key, presenceFor(key)); + startPresenceSweep(); + const ping = setInterval(() => res.write(': ping\n\n'), 25000); + if (ping.unref) ping.unref(); + req.on('close', () => { + clearInterval(ping); + const clients = sseClients.get(key); + if (clients) { + clients.delete(res); + if (clients.size === 0) { + sseClients.delete(key); + lastPresence.delete(key); + } + } + noteConnectionClosed(); + }); + } + + function serveArtifact(res, key, assetPath) { + const session = store.get(key); + if (!session) return sendHtml(res, 404, '

    Unknown session

    '); + + if (!assetPath) { + let content; + try { + content = fs.readFileSync(session.file, 'utf8'); + } catch { + return sendHtml(res, 404, `

    Artifact missing

    ${session.file} no longer exists.

    `, { csp: false }); + } + const ext = path.extname(session.file).toLowerCase(); + if (ext === '.md' || ext === '.markdown') { + const html = renderMarkdownArtifactHtml(renderMarkdown(content), { + title: path.basename(session.file), + sdkSrc: '/sdk.js' + }); + return sendHtml(res, 200, html, { csp: false }); + } + const sdkTag = ''; + const injected = content.includes('') + ? content.replace('', `${sdkTag}\n`) + : `${content}\n${sdkTag}`; + return sendHtml(res, 200, injected, { csp: false }); + } + + // Sibling assets resolve relative to the artifact's directory and must + // stay confined to it. + const baseDir = path.dirname(session.file); + const resolved = path.resolve(baseDir, assetPath); + if (resolved !== baseDir && !resolved.startsWith(baseDir + path.sep)) { + return sendJson(res, 403, { error: 'asset path escapes artifact directory' }); + } + let data; + try { + data = fs.readFileSync(resolved); + } catch { + return sendJson(res, 404, { error: 'asset not found' }); + } + const type = CONTENT_TYPES[path.extname(resolved).toLowerCase()] || 'application/octet-stream'; + res.writeHead(200, { 'content-type': type, 'cache-control': 'no-store' }); + return res.end(data); + } + + const server = http.createServer((req, res) => { + if (!isAllowedHostHeader(req.headers.host, allowedHostnames)) { + return sendJson(res, 403, { error: 'forbidden host header' }); + } + if (!isAllowedOrigin(req.headers.origin, allowedHostnames)) { + return sendJson(res, 403, { error: 'forbidden origin' }); + } + const url = new URL(req.url, `http://${req.headers.host}`); + const { pathname } = url; + + Promise.resolve() + .then(() => { + if (req.method === 'GET' && pathname === '/health') { + return sendJson(res, 200, { ok: true, app: 'ecc-plan-canvas', version }); + } + if (req.method === 'POST' && pathname === '/shutdown') { + sendJson(res, 200, { status: 'stopping' }); + setImmediate(() => { + if (onIdleShutdown) onIdleShutdown(); + }); + return undefined; + } + if (req.method === 'GET' && pathname === '/') { + return sendHtml(res, 200, renderSessionListHtml(store.list())); + } + if (req.method === 'GET' && pathname === '/canvas.css') { + res.writeHead(200, { 'content-type': 'text/css; charset=utf-8', 'cache-control': 'no-store' }); + return res.end(canvasCss()); + } + if (req.method === 'GET' && pathname === '/client.js') { + res.writeHead(200, { 'content-type': 'text/javascript; charset=utf-8', 'cache-control': 'no-store' }); + return res.end(canvasClientJs()); + } + if (req.method === 'GET' && pathname === '/sdk.js') { + res.writeHead(200, { 'content-type': 'text/javascript; charset=utf-8', 'cache-control': 'no-store' }); + return res.end(artifactSdkJs()); + } + const canvasMatch = pathname.match(/^\/canvas\/([a-f0-9]{12})$/); + if (req.method === 'GET' && canvasMatch) { + const session = store.get(canvasMatch[1]); + if (!session) return sendHtml(res, 404, '

    Unknown session

    '); + return sendHtml(res, 200, renderCanvasHtml(session)); + } + const eventsMatch = pathname.match(/^\/events\/([a-f0-9]{12})$/); + if (req.method === 'GET' && eventsMatch) { + return handleEvents(req, res, eventsMatch[1]); + } + const artifactMatch = pathname.match(/^\/artifact\/([a-f0-9]{12})\/(.*)$/); + if (req.method === 'GET' && artifactMatch) { + const assetPath = decodeURIComponent(artifactMatch[2]); + return serveArtifact(res, artifactMatch[1], assetPath || null); + } + if (pathname.startsWith('/api/')) { + return handleApi(req, res, url); + } + return sendJson(res, 404, { error: 'not found' }); + }) + .catch(error => { + if (!res.headersSent) sendJson(res, 400, { error: error.message }); + else res.end(); + }); + }); + + function close() { + closed = true; + clearTimeout(idleTimer); + clearInterval(presenceSweep); + presenceSweep = null; + lastPresence.clear(); + for (const key of watchers.keys()) unwatchSession(key); + for (const clients of sseClients.values()) { + for (const client of clients) client.end(); + } + sseClients.clear(); + wake.emit('server-close'); + return new Promise((resolve, reject) => { + server.close(error => (error ? reject(error) : resolve())); + // Browser keep-alive sockets would otherwise hold close() open. + if (typeof server.closeIdleConnections === 'function') server.closeIdleConnections(); + }); + } + + function listen(port = resolvePort()) { + return new Promise((resolve, reject) => { + server.once('error', reject); + server.listen(port, host, () => { + armIdleTimer(); + resolve({ port: server.address().port, host }); + }); + }); + } + + return { server, listen, close, presenceFor, sweepPresence, watchSession }; +} + +module.exports = { + DEFAULT_HOST, + DEFAULT_PORT, + DEFAULT_THINKING_STALE_MS, + DEFAULT_TYPING_EXPIRY_MS, + createPlanCanvasServer, + resolveIdleTimeoutMs, + resolvePort +}; diff --git a/github_code/affaan-m__ECC/scripts/lib/plan-canvas/sessions.js b/github_code/affaan-m__ECC/scripts/lib/plan-canvas/sessions.js new file mode 100644 index 0000000000000000000000000000000000000000..799cf4b364860ce3400abada964b6d6e5f8b6c49 --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/plan-canvas/sessions.js @@ -0,0 +1,269 @@ +'use strict'; + +/** + * Plan Canvas session store. + * + * Sessions are keyed by the canonical artifact file path so agents never + * juggle opaque ids. State is persisted as JSON in the Plan Canvas state + * dir so queued human feedback survives a server restart. + */ + +const crypto = require('crypto'); +const fs = require('fs'); +const os = require('os'); +const path = require('path'); + +const FEEDBACK_KINDS = new Set(['chat', 'annotation', 'verdict']); +const VERDICTS = new Set(['approve', 'request-changes']); + +function resolveStateDir(env = process.env) { + const override = env.ECC_PLAN_CANVAS_STATE_DIR; + if (override && String(override).trim()) return path.resolve(String(override).trim()); + return path.join(os.homedir(), '.claude', 'plan-canvas'); +} + +// Canonicalize so `./plan.md`, symlinks, and absolute paths all land on the +// same session. +function canonicalizeArtifactPath(filePath) { + const absolute = path.resolve(filePath); + try { + return fs.realpathSync(absolute); + } catch { + return absolute; + } +} + +function sessionKeyFor(canonicalPath) { + return crypto.createHash('sha256').update(canonicalPath).digest('hex').slice(0, 12); +} + +function nowIso() { + return new Date().toISOString(); +} + +function sanitizeText(value, maxLength = 4000) { + if (typeof value !== 'string') return ''; + return value.slice(0, maxLength); +} + +// Normalize one browser-submitted feedback item into the shape delivered to +// the agent. Returns null for unusable input rather than throwing so a +// malformed item can never wedge the queue. +function normalizeFeedbackItem(raw, counter) { + if (!raw || typeof raw !== 'object') return null; + const kind = FEEDBACK_KINDS.has(raw.kind) ? raw.kind : null; + if (!kind) return null; + const item = { + id: `fb-${counter}`, + kind, + text: sanitizeText(raw.text), + at: nowIso() + }; + if (kind === 'verdict') { + if (!VERDICTS.has(raw.verdict)) return null; + item.verdict = raw.verdict; + } + if (kind === 'annotation') { + const anchor = raw.anchor && typeof raw.anchor === 'object' ? raw.anchor : null; + if (!anchor || typeof anchor.selector !== 'string') return null; + item.anchor = { + selector: sanitizeText(anchor.selector, 500), + tag: sanitizeText(anchor.tag, 60), + snippet: sanitizeText(anchor.snippet, 400) + }; + if (anchor.textRange && typeof anchor.textRange === 'object') { + item.anchor.textRange = { + text: sanitizeText(anchor.textRange.text, 1000) + }; + } + if (!item.text) return null; + } + if (kind === 'chat' && !item.text) return null; + return item; +} + +function createSessionStore({ stateDir = resolveStateDir() } = {}) { + const stateFile = path.join(stateDir, 'sessions.json'); + let state = { sessions: {}, feedbackCounter: 0 }; + + function load() { + try { + const parsed = JSON.parse(fs.readFileSync(stateFile, 'utf8')); + if (parsed && typeof parsed === 'object' && parsed.sessions) { + state = { + sessions: parsed.sessions, + feedbackCounter: Number(parsed.feedbackCounter) || 0 + }; + } + } catch { + // Missing or corrupt state starts fresh; queued feedback loss on a + // corrupt file beats refusing to start at all. + } + } + + function persist() { + fs.mkdirSync(stateDir, { recursive: true }); + const tmpFile = `${stateFile}.tmp`; + fs.writeFileSync(tmpFile, JSON.stringify(state, null, 2)); + fs.renameSync(tmpFile, stateFile); + } + + load(); + + function get(key) { + return state.sessions[key] || null; + } + + function findByFile(filePath) { + const canonical = canonicalizeArtifactPath(filePath); + return get(sessionKeyFor(canonical)); + } + + // Open (or resume) a session. A session the *user* ended from the browser + // is sticky: it refuses a plain reopen so agents do not pop the browser + // back up uninvited. Pass reopen:true only when the human asked. + function open(filePath, { reopen = false } = {}) { + const canonical = canonicalizeArtifactPath(filePath); + const key = sessionKeyFor(canonical); + const existing = state.sessions[key]; + if (existing && existing.status === 'ended' && existing.endedBy === 'user' && !reopen) { + return { session: existing, refused: true }; + } + const session = existing || { + key, + file: canonical, + chat: [], + pendingFeedback: [], + createdAt: nowIso() + }; + session.status = 'open'; + delete session.endedBy; + session.updatedAt = nowIso(); + state.sessions[key] = session; + persist(); + return { session, refused: false }; + } + + // Queue feedback from the browser. Chat-shaped items are mirrored into the + // session transcript immediately so the conversation panel stays coherent + // across reloads. + function queueFeedback(key, rawItems, { endSession = false } = {}) { + const session = get(key); + if (!session || session.status === 'ended') return null; + const accepted = []; + for (const raw of Array.isArray(rawItems) ? rawItems : []) { + state.feedbackCounter += 1; + const item = normalizeFeedbackItem(raw, state.feedbackCounter); + if (item) accepted.push(item); + } + session.pendingFeedback.push(...accepted); + for (const item of accepted) { + session.chat.push({ role: 'user', kind: item.kind, text: chatLineFor(item), at: item.at }); + } + if (endSession) { + session.status = 'ended'; + session.endedBy = 'user'; + } else if (accepted.length > 0) { + session.status = 'feedback'; + } + session.updatedAt = nowIso(); + persist(); + return { accepted, pending: session.pendingFeedback.length, session }; + } + + // Deliver-and-drain: feedback is handed to exactly one await call, after + // which the session flips back to open. An ended session keeps reporting + // ended (with attribution) so agents know to stop polling. + function takeFeedback(key) { + const session = get(key); + if (!session) return { status: 'missing' }; + if (session.pendingFeedback.length > 0) { + const items = session.pendingFeedback; + session.pendingFeedback = []; + const result = { status: 'feedback', items }; + if (session.status === 'ended') { + result.sessionEnded = true; + result.endedBy = session.endedBy; + } else { + session.status = 'open'; + } + session.updatedAt = nowIso(); + persist(); + return result; + } + if (session.status === 'ended') { + return { status: 'ended', endedBy: session.endedBy }; + } + return { status: 'waiting' }; + } + + function addAgentReply(key, text) { + const session = get(key); + if (!session) return null; + const entry = { role: 'agent', kind: 'chat', text: sanitizeText(text), at: nowIso() }; + session.chat.push(entry); + session.updatedAt = nowIso(); + persist(); + return entry; + } + + function end(key, endedBy) { + const session = get(key); + if (!session) return null; + session.status = 'ended'; + session.endedBy = endedBy === 'user' ? 'user' : 'agent'; + session.updatedAt = nowIso(); + persist(); + return session; + } + + function list() { + return Object.values(state.sessions).map(session => ({ + key: session.key, + file: session.file, + status: session.status, + endedBy: session.endedBy, + pending: session.pendingFeedback.length, + updatedAt: session.updatedAt + })); + } + + function hasOpenSessions() { + return Object.values(state.sessions).some(session => session.status !== 'ended'); + } + + return { + stateDir, + stateFile, + open, + get, + findByFile, + queueFeedback, + takeFeedback, + addAgentReply, + end, + list, + hasOpenSessions + }; +} + +// One-line rendering of a feedback item for the conversation transcript. +function chatLineFor(item) { + if (item.kind === 'verdict') { + const label = item.verdict === 'approve' ? 'Approved the plan' : 'Requested changes'; + return item.text ? `${label}: ${item.text}` : label; + } + if (item.kind === 'annotation') { + const where = item.anchor.snippet || item.anchor.selector; + return `[${where}] ${item.text}`; + } + return item.text; +} + +module.exports = { + canonicalizeArtifactPath, + createSessionStore, + normalizeFeedbackItem, + resolveStateDir, + sessionKeyFor +}; diff --git a/github_code/affaan-m__ECC/scripts/lib/plan-canvas/ui.js b/github_code/affaan-m__ECC/scripts/lib/plan-canvas/ui.js new file mode 100644 index 0000000000000000000000000000000000000000..df1f0562603784af83f59f875b2ea282fa20b381 --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/plan-canvas/ui.js @@ -0,0 +1,628 @@ +'use strict'; + +/** + * Plan Canvas browser chrome: the editor shell that frames an artifact, + * plus the rendered-markdown artifact template. + * + * Visual language mirrors the ECC web dashboard (scripts/dashboard-web.js): + * same design tokens, dark-first with a light theme, accent→pink brand + * gradient. Everything is served inline — no CDNs, no external assets. + */ + +const path = require('path'); + +const { escapeHtml } = require('./markdown'); + +// Pinned Mermaid ESM build, loaded in the browser only when an artifact +// actually contains a diagram. Override with a local/vendored URL (e.g. an +// air-gapped mirror) via ECC_PLAN_CANVAS_MERMAID_URL. If the fetch fails, the +// diagram source stays visible as a styled code block — nothing breaks. +const DEFAULT_MERMAID_URL = 'https://cdn.jsdelivr.net/npm/mermaid@11.4.1/dist/mermaid.esm.min.mjs'; + +function mermaidUrl(env = process.env) { + const override = env.ECC_PLAN_CANVAS_MERMAID_URL; + return override && String(override).trim() ? String(override).trim() : DEFAULT_MERMAID_URL; +} + +// Browser module that renders `
    ` blocks, themed to match
    +// the ECC canvas. Kept import-only so a CDN failure degrades gracefully.
    +function mermaidLoaderScript(url) {
    +  return ``;
    +}
    +
    +// Design tokens shared by the chrome and the markdown artifact template.
    +const TOKENS_CSS = `
    +  :root{
    +    --bg:#080a0e; --bg2:#0d0f14; --bg3:#13161e; --bg4:#191d2a;
    +    --surface:#101218; --surface-hover:#171a24; --border:#1d2130; --border-light:#272c3e;
    +    --text:#dfe2e9; --text2:#80859a; --text3:#4c5168;
    +    --accent:#6885e8; --accent-glow:rgba(104,133,232,0.15); --accent-dim:#3d5ab8;
    +    --green:#4acb8a; --green-glow:rgba(74,203,138,0.15);
    +    --orange:#eca85a; --orange-glow:rgba(236,168,90,0.15);
    +    --pink:#e26a9e; --pink-glow:rgba(226,106,158,0.15);
    +    --red:#e86060; --red-glow:rgba(232,96,96,0.15);
    +    --teal:#4acbbe; --teal-glow:rgba(74,203,190,0.15);
    +    --radius:8px; --radius-sm:5px;
    +    --font:-apple-system,BlinkMacSystemFont,'SF Pro Display','Inter','Segoe UI',Roboto,sans-serif;
    +    --mono:'SF Mono','Fira Code','JetBrains Mono','Cascadia Code',monospace;
    +    --shadow:0 1px 2px rgba(0,0,0,0.4);
    +    --shadow-lg:0 8px 32px rgba(0,0,0,0.6);
    +  }
    +  [data-theme="light"]{
    +    --bg:#f4f5f7; --bg2:#ffffff; --bg3:#eaecef; --bg4:#dfe2e6;
    +    --surface:#ffffff; --surface-hover:#f4f5f7; --border:#cdd1d9; --border-light:#dde1e8;
    +    --text:#181b23; --text2:#585e6e; --text3:#9197a8;
    +    --accent:#4560d0; --accent-glow:rgba(69,96,208,0.08); --accent-dim:#2f44a0;
    +    --green:#16a34a; --green-glow:rgba(22,163,74,0.08);
    +    --orange:#d97706; --orange-glow:rgba(217,119,6,0.08);
    +    --pink:#c73877; --pink-glow:rgba(199,56,119,0.08);
    +    --red:#dc2626; --red-glow:rgba(220,38,38,0.08);
    +    --teal:#0d9488; --teal-glow:rgba(13,148,136,0.08);
    +    --shadow:0 1px 2px rgba(0,0,0,0.04);
    +    --shadow-lg:0 8px 32px rgba(0,0,0,0.08);
    +  }
    +`;
    +
    +function canvasCss() {
    +  return `${TOKENS_CSS}
    +  *{margin:0;padding:0;box-sizing:border-box}
    +  html,body{height:100%}
    +  body{font-family:var(--font);background:var(--bg);color:var(--text);-webkit-font-smoothing:antialiased;line-height:1.4;overflow:hidden}
    +  ::selection{background:var(--accent);color:#fff}
    +  ::-webkit-scrollbar{width:8px;height:8px}
    +  ::-webkit-scrollbar-track{background:transparent}
    +  ::-webkit-scrollbar-thumb{background:var(--border);border-radius:4px}
    +  button{font-family:var(--font)}
    +
    +  .bar{display:flex;align-items:center;gap:12px;height:52px;padding:0 16px;background:color-mix(in srgb,var(--bg2) 88%,transparent);border-bottom:1px solid var(--border);backdrop-filter:blur(16px)}
    +  .brand{display:flex;align-items:center;gap:9px;min-width:0}
    +  .brand .logo{width:26px;height:26px;flex:none;background:linear-gradient(135deg,var(--accent),var(--pink));border-radius:6px;display:flex;align-items:center;justify-content:center;font-size:13px;font-weight:700;color:#fff}
    +  .brand .name{font-size:13.5px;font-weight:600;white-space:nowrap}
    +  .brand .file{font-size:11.5px;color:var(--text2);font-family:var(--mono);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:34vw}
    +  .bar .spacer{flex:1}
    +
    +  .presence{display:flex;align-items:center;gap:6px;font-size:11px;font-weight:500;color:var(--text2);background:var(--bg3);border:1px solid var(--border);border-radius:99px;padding:3px 10px 3px 8px;white-space:nowrap}
    +  .presence .dot{width:7px;height:7px;border-radius:99px;background:var(--text3)}
    +  .presence[data-state="listening"] .dot{background:var(--green);box-shadow:0 0 0 3px var(--green-glow);animation:pulse 2s infinite}
    +  .presence[data-state="thinking"] .dot,.presence[data-state="typing"] .dot{background:var(--accent);box-shadow:0 0 0 3px var(--accent-glow);animation:pulse 1.2s infinite}
    +  .presence[data-state="queued"] .dot{background:var(--orange);box-shadow:0 0 0 3px var(--orange-glow)}
    +  @keyframes pulse{0%,100%{opacity:1}50%{opacity:.45}}
    +
    +  .toggle{display:flex;align-items:center;gap:7px;font-size:11.5px;color:var(--text2);cursor:pointer;user-select:none}
    +  .toggle .track{width:30px;height:17px;border-radius:99px;background:var(--bg4);border:1px solid var(--border);position:relative;transition:background .15s}
    +  .toggle .knob{position:absolute;top:1px;left:1px;width:13px;height:13px;border-radius:99px;background:var(--text2);transition:transform .15s,background .15s}
    +  .toggle[aria-pressed="true"] .track{background:var(--accent);border-color:var(--accent-dim)}
    +  .toggle[aria-pressed="true"] .knob{transform:translateX(13px);background:#fff}
    +
    +  .icon-btn{height:28px;padding:0 10px;border-radius:6px;border:1px solid var(--border);background:var(--bg3);color:var(--text2);cursor:pointer;font-size:11.5px;display:flex;align-items:center;gap:5px;transition:all .12s}
    +  .icon-btn:hover{border-color:var(--border-light);color:var(--text);background:var(--bg4)}
    +  .icon-btn.danger:hover{border-color:var(--red);color:var(--red);background:var(--red-glow)}
    +
    +  .layout{display:flex;height:calc(100% - 52px)}
    +  .frame{flex:1;min-width:0;position:relative;background:var(--bg2)}
    +  .frame iframe{width:100%;height:100%;border:0;background:#fff}
    +  [data-theme] .frame iframe{background:var(--bg2)}
    +
    +  .panel{width:340px;flex:none;display:flex;flex-direction:column;border-left:1px solid var(--border);background:var(--bg2)}
    +  .panel h2{font-size:11px;font-weight:600;letter-spacing:.06em;text-transform:uppercase;color:var(--text3);padding:12px 14px 8px}
    +
    +  .verdict{display:flex;gap:8px;padding:0 14px 12px;border-bottom:1px solid var(--border)}
    +  .verdict button{flex:1;height:30px;border-radius:6px;font-size:12px;font-weight:600;cursor:pointer;transition:all .12s}
    +  .verdict .approve{border:1px solid var(--green);background:var(--green-glow);color:var(--green)}
    +  .verdict .approve:hover{background:var(--green);color:#fff}
    +  .verdict .changes{border:1px solid var(--orange);background:var(--orange-glow);color:var(--orange)}
    +  .verdict .changes:hover{background:var(--orange);color:#fff}
    +
    +  .chat{flex:1;overflow-y:auto;padding:10px 14px;display:flex;flex-direction:column;gap:8px}
    +  .msg{max-width:92%;padding:7px 10px;border-radius:10px;font-size:12.5px;white-space:pre-wrap;word-break:break-word}
    +  .msg.user{align-self:flex-end;background:var(--accent-glow);border:1px solid color-mix(in srgb,var(--accent) 35%,transparent);color:var(--text);border-bottom-right-radius:3px}
    +  .msg.agent{align-self:flex-start;background:var(--bg3);border:1px solid var(--border);color:var(--text);border-bottom-left-radius:3px}
    +  .msg .meta{display:block;font-size:9.5px;color:var(--text3);margin-top:3px}
    +  .msg.kind-annotation{border-left:2px solid var(--teal)}
    +  .msg.kind-verdict{border-left:2px solid var(--green)}
    +  .chat .empty{color:var(--text3);font-size:12px;text-align:center;margin-top:24px;line-height:1.6}
    +
    +  /* iMessage-style activity bubble: dots while the agent thinks or types. */
    +  .typing{align-self:flex-start;display:none;align-items:center;gap:8px;background:var(--bg3);border:1px solid var(--border);border-bottom-left-radius:3px;border-radius:10px;padding:9px 12px}
    +  .typing.show{display:flex}
    +  .typing .dots{display:flex;align-items:center;gap:3px}
    +  .typing .dots i{width:6px;height:6px;border-radius:99px;background:var(--text2);animation:typing-bounce 1.4s infinite ease-in-out both}
    +  .typing .dots i:nth-child(1){animation-delay:-.32s}
    +  .typing .dots i:nth-child(2){animation-delay:-.16s}
    +  .typing .label{font-size:11px;color:var(--text3)}
    +  @keyframes typing-bounce{0%,80%,100%{transform:translateY(0);opacity:.4}40%{transform:translateY(-4px);opacity:1}}
    +  @media (prefers-reduced-motion:reduce){
    +    .typing .dots i{animation:none;opacity:.7}
    +    .presence .dot{animation:none}
    +  }
    +  /* A queued message nobody is listening for gets an explicit, honest note. */
    +  .stalled{align-self:flex-start;display:none;gap:8px;background:var(--orange-glow);border:1px solid color-mix(in srgb,var(--orange) 35%,transparent);border-radius:10px;padding:8px 11px;font-size:11.5px;color:var(--text2);line-height:1.5}
    +  .stalled.show{display:flex}
    +
    +  .queue{padding:8px 14px 0;display:flex;flex-direction:column;gap:6px;max-height:180px;overflow-y:auto}
    +  .pill{display:flex;align-items:flex-start;gap:8px;background:var(--bg3);border:1px solid var(--border);border-left:2px solid var(--teal);border-radius:6px;padding:6px 8px;font-size:11.5px}
    +  .pill.kind-chat{border-left-color:var(--accent)}
    +  .pill.kind-verdict{border-left-color:var(--green)}
    +  .pill .where{color:var(--teal);font-family:var(--mono);font-size:10px;display:block;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
    +  .pill .body{flex:1;min-width:0;color:var(--text2)}
    +  .pill .txt{display:block;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;color:var(--text)}
    +  .pill button{border:none;background:none;color:var(--text3);cursor:pointer;font-size:13px;line-height:1;padding:1px}
    +  .pill button:hover{color:var(--red)}
    +
    +  .composer{padding:10px 14px 14px;border-top:1px solid var(--border);display:flex;flex-direction:column;gap:8px}
    +  .composer .hint{font-size:10px;color:var(--text3)}
    +  .composer textarea{width:100%;min-height:60px;max-height:160px;resize:vertical;background:var(--bg3);border:1px solid var(--border);border-radius:6px;padding:8px 10px;color:var(--text);font-size:12.5px;font-family:var(--font);outline:none;transition:all .15s}
    +  .composer textarea:focus{border-color:var(--accent);box-shadow:0 0 0 3px var(--accent-glow)}
    +  .composer .row{display:flex;gap:8px;align-items:center}
    +  .composer .send{flex:1;height:32px;border:none;border-radius:6px;background:var(--accent);color:#fff;font-size:12.5px;font-weight:600;cursor:pointer;transition:all .12s}
    +  .composer .send:hover{background:var(--accent-dim)}
    +  .composer .send:disabled{opacity:.5;cursor:default}
    +  .composer .status{font-size:10.5px;color:var(--text3)}
    +
    +  .overlay{position:absolute;inset:0;display:none;align-items:center;justify-content:center;background:color-mix(in srgb,var(--bg) 80%,transparent);backdrop-filter:blur(6px);z-index:50}
    +  .overlay.show{display:flex}
    +  .overlay .card{background:var(--surface);border:1px solid var(--border);border-radius:var(--radius);box-shadow:var(--shadow-lg);padding:26px 32px;text-align:center;max-width:340px}
    +  .overlay .card h3{font-size:14px;margin-bottom:6px}
    +  .overlay .card p{font-size:12px;color:var(--text2);line-height:1.5}
    +  `;
    +}
    +
    +// Client logic for the chrome page (runs in the top window).
    +function canvasClientJs() {
    +  return `'use strict';
    +(() => {
    +  const boot = JSON.parse(document.getElementById('pc-session').textContent);
    +  const key = boot.key;
    +  const $ = id => document.getElementById(id);
    +  const frame = $('artifact');
    +  const chatLog = $('chatLog');
    +  const queueEl = $('queue');
    +  const input = $('chatInput');
    +  const sendBtn = $('send');
    +  const statusEl = $('sendStatus');
    +  const presence = $('presence');
    +  const QKEY = 'ecc-plan-canvas:queue:' + key;
    +  let queue = [];
    +  let lastScroll = { x: 0, y: 0 };
    +  let ended = boot.status === 'ended';
    +  let sending = false;
    +
    +  try { queue = JSON.parse(sessionStorage.getItem(QKEY) || '[]'); } catch { queue = []; }
    +
    +  // --- theme ---------------------------------------------------------
    +  const themeKey = 'ecc-plan-canvas:theme';
    +  function applyTheme(t) {
    +    if (t === 'light') document.documentElement.setAttribute('data-theme', 'light');
    +    else document.documentElement.removeAttribute('data-theme');
    +    $('themeBtn').textContent = t === 'light' ? '\\u263E dark' : '\\u2600 light';
    +  }
    +  // Storage access throws outright when the browser blocks site data for this
    +  // origin (loopback is a common trigger). Unguarded, that killed the whole
    +  // client IIFE here, before the send button and Enter handlers bound below:
    +  // every control rendered and stayed inert. sessionStorage is already guarded
    +  // above and below; match it. See affaan-m/ECC#2702.
    +  function readTheme() {
    +    try { return localStorage.getItem(themeKey); } catch { return null; }
    +  }
    +  function writeTheme(v) {
    +    try { localStorage.setItem(themeKey, v); } catch { /* site data blocked */ }
    +  }
    +  let theme = readTheme() || 'dark';
    +  applyTheme(theme);
    +  $('themeBtn').addEventListener('click', () => {
    +    theme = theme === 'light' ? 'dark' : 'light';
    +    writeTheme(theme);
    +    applyTheme(theme);
    +  });
    +
    +  // --- annotate mode -------------------------------------------------
    +  let annotate = true;
    +  function setAnnotate(on) {
    +    annotate = on;
    +    $('annotate').setAttribute('aria-pressed', String(on));
    +    postToFrame({ type: 'pc:set-mode', annotate: on });
    +  }
    +  $('annotate').addEventListener('click', () => setAnnotate(!annotate));
    +  document.addEventListener('keydown', e => {
    +    if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 'i') {
    +      e.preventDefault();
    +      setAnnotate(!annotate);
    +    }
    +  }, true);
    +
    +  // --- iframe bridge --------------------------------------------------
    +  function postToFrame(msg) {
    +    if (frame.contentWindow) frame.contentWindow.postMessage(msg, '*');
    +  }
    +  window.addEventListener('message', e => {
    +    if (e.source !== frame.contentWindow) return;
    +    const msg = e.data || {};
    +    if (msg.type === 'pc:queue' && msg.item) addToQueue(msg.item);
    +    else if (msg.type === 'pc:queue-and-send' && msg.item) { addToQueue(msg.item); send(); }
    +    else if (msg.type === 'pc:scroll') lastScroll = { x: msg.x || 0, y: msg.y || 0 };
    +    else if (msg.type === 'pc:toggle-mode') setAnnotate(!annotate);
    +    else if (msg.type === 'pc:ready') {
    +      postToFrame({ type: 'pc:set-mode', annotate });
    +      postToFrame({ type: 'pc:restore-scroll', x: lastScroll.x, y: lastScroll.y });
    +    }
    +  });
    +
    +  // --- queue ----------------------------------------------------------
    +  function persistQueue() { try { sessionStorage.setItem(QKEY, JSON.stringify(queue)); } catch { /* full */ } }
    +  function addToQueue(item) { queue.push(item); persistQueue(); renderQueue(); }
    +  function renderQueue() {
    +    queueEl.innerHTML = '';
    +    queue.forEach((item, i) => {
    +      const pill = document.createElement('div');
    +      pill.className = 'pill kind-' + item.kind;
    +      const body = document.createElement('span');
    +      body.className = 'body';
    +      if (item.anchor) {
    +        const where = document.createElement('span');
    +        where.className = 'where';
    +        where.textContent = item.anchor.snippet || item.anchor.selector;
    +        body.appendChild(where);
    +      }
    +      const txt = document.createElement('span');
    +      txt.className = 'txt';
    +      txt.textContent = item.kind === 'verdict' ? (item.verdict === 'approve' ? 'Approve plan' : 'Request changes') + (item.text ? ': ' + item.text : '') : item.text;
    +      body.appendChild(txt);
    +      const rm = document.createElement('button');
    +      rm.textContent = '\\u00D7';
    +      rm.title = 'Remove';
    +      rm.addEventListener('click', () => { queue.splice(i, 1); persistQueue(); renderQueue(); });
    +      pill.append(body, rm);
    +      queueEl.appendChild(pill);
    +    });
    +  }
    +  renderQueue();
    +
    +  // --- activity indicators ---------------------------------------------
    +  // Built once and re-appended on every chat render so the animation never
    +  // restarts mid-thought.
    +  const typingEl = document.createElement('div');
    +  typingEl.className = 'typing';
    +  typingEl.setAttribute('role', 'status');
    +  typingEl.setAttribute('aria-live', 'polite');
    +  const dots = document.createElement('span');
    +  dots.className = 'dots';
    +  dots.append(document.createElement('i'), document.createElement('i'), document.createElement('i'));
    +  const typingLabel = document.createElement('span');
    +  typingLabel.className = 'label';
    +  typingEl.append(dots, typingLabel);
    +
    +  const stalledEl = document.createElement('div');
    +  stalledEl.className = 'stalled';
    +  stalledEl.setAttribute('role', 'status');
    +
    +  const TYPING_LABELS = { thinking: 'agent is thinking\\u2026', typing: 'agent is typing\\u2026' };
    +
    +  function renderActivity(state) {
    +    const typingText = TYPING_LABELS[state];
    +    typingEl.classList.toggle('show', Boolean(typingText));
    +    if (typingText) typingLabel.textContent = typingText;
    +    const stalled = state === 'queued';
    +    stalledEl.classList.toggle('show', stalled);
    +    if (stalled) {
    +      stalledEl.textContent =
    +        'Delivered to the queue. Your agent is not listening right now, so it picks this up the moment it checks in.';
    +    }
    +    if (typingText || stalled) scrollToEnd();
    +  }
    +
    +  // --- chat -----------------------------------------------------------
    +  function atBottom() {
    +    return chatLog.scrollHeight - chatLog.scrollTop - chatLog.clientHeight < 40;
    +  }
    +  function scrollToEnd() { chatLog.scrollTop = chatLog.scrollHeight; }
    +
    +  function renderChat(entries) {
    +    const pinned = atBottom();
    +    chatLog.innerHTML = '';
    +    if (!entries.length) {
    +      const empty = document.createElement('div');
    +      empty.className = 'empty';
    +      empty.textContent = 'Click anything in the plan to annotate it, or type below. Feedback goes straight to your agent.';
    +      chatLog.appendChild(empty);
    +    } else {
    +      for (const entry of entries) {
    +        const div = document.createElement('div');
    +        div.className = 'msg ' + (entry.role === 'agent' ? 'agent' : 'user') + ' kind-' + (entry.kind || 'chat');
    +        div.textContent = entry.text;
    +        const meta = document.createElement('span');
    +        meta.className = 'meta';
    +        meta.textContent = (entry.role === 'agent' ? 'agent' : 'you') + ' \\u00B7 ' + new Date(entry.at).toLocaleTimeString();
    +        div.appendChild(meta);
    +        chatLog.appendChild(div);
    +      }
    +    }
    +    // The indicators live at the tail of the log, so they survive re-render.
    +    chatLog.appendChild(typingEl);
    +    chatLog.appendChild(stalledEl);
    +    if (pinned) scrollToEnd();
    +  }
    +  renderChat(boot.chat || []);
    +
    +  // --- send -----------------------------------------------------------
    +  async function send(extraItems) {
    +    if (ended || sending) return;
    +    const items = queue.slice();
    +    if (extraItems) items.push(...extraItems);
    +    const text = input.value.trim();
    +    if (text) items.push({ kind: 'chat', text });
    +    if (!items.length) {
    +      statusEl.textContent = 'Nothing to send yet - annotate the plan or type a message.';
    +      return;
    +    }
    +    sending = true;
    +    sendBtn.disabled = true;
    +    statusEl.textContent = 'Sending\\u2026';
    +    try {
    +      const res = await fetch('/api/session/' + key + '/feedback', {
    +        method: 'POST',
    +        headers: { 'content-type': 'application/json' },
    +        body: JSON.stringify({ items })
    +      });
    +      if (!res.ok) throw new Error('HTTP ' + res.status);
    +      const body = await res.json().catch(() => ({}));
    +      queue = [];
    +      persistQueue();
    +      renderQueue();
    +      input.value = '';
    +      // Say what actually happened: a parked agent takes the batch on the
    +      // spot, otherwise it sits in the queue until the agent checks in.
    +      statusEl.textContent = body.presence === 'thinking' || body.presence === 'typing'
    +        ? 'Delivered. Your agent has it.'
    +        : 'Queued. Your agent picks this up the moment it checks in.';
    +      if (body.presence) applyPresence(body.presence);
    +    } catch (err) {
    +      statusEl.textContent = 'Send failed (' + err.message + ') - is the canvas server still running?';
    +    } finally {
    +      sending = false;
    +      sendBtn.disabled = ended;
    +    }
    +  }
    +  sendBtn.addEventListener('click', () => send());
    +  input.addEventListener('keydown', e => {
    +    if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault(); send(); }
    +  });
    +  $('approve').addEventListener('click', () => send([{ kind: 'verdict', verdict: 'approve' }]));
    +  $('changes').addEventListener('click', () => send([{ kind: 'verdict', verdict: 'request-changes' }]));
    +
    +  // --- session controls ------------------------------------------------
    +  $('reloadBtn').addEventListener('click', reloadArtifact);
    +  $('endBtn').addEventListener('click', async () => {
    +    if (!window.confirm('End this review session?')) return;
    +    try { await fetch('/api/session/' + key + '/end', { method: 'POST' }); } catch { /* server gone */ }
    +  });
    +  function reloadArtifact() {
    +    const base = frame.getAttribute('data-artifact-src');
    +    frame.src = base + '?t=' + Date.now();
    +  }
    +  function markEnded(endedBy) {
    +    ended = true;
    +    sendBtn.disabled = true;
    +    input.disabled = true;
    +    renderActivity('ended');
    +    presence.setAttribute('data-state', 'ended');
    +    presence.querySelector('.label').textContent = 'session ended';
    +    $('endedOverlay').classList.add('show');
    +    $('endedWho').textContent = endedBy === 'agent'
    +      ? 'Your agent closed this review.'
    +      : 'You ended this review. Head back to your agent session.';
    +  }
    +  if (ended) markEnded(boot.endedBy);
    +
    +  // --- server events ----------------------------------------------------
    +  const PRESENCE_LABELS = {
    +    waiting: 'agent not connected',
    +    listening: 'agent listening',
    +    thinking: 'agent is thinking\\u2026',
    +    typing: 'agent is typing\\u2026',
    +    queued: 'queued for your agent'
    +  };
    +  function applyPresence(state) {
    +    if (ended) return;
    +    presence.setAttribute('data-state', state);
    +    presence.querySelector('.label').textContent = PRESENCE_LABELS[state] || state;
    +    renderActivity(state);
    +  }
    +  function connectEvents() {
    +    const es = new EventSource('/events/' + key);
    +    es.addEventListener('chat-sync', e => renderChat(JSON.parse(e.data).chat || []));
    +    es.addEventListener('presence', e => applyPresence(JSON.parse(e.data).state));
    +    es.addEventListener('reload', reloadArtifact);
    +    es.addEventListener('ended', e => { markEnded(JSON.parse(e.data).endedBy); es.close(); });
    +    es.onerror = () => {
    +      if (ended) return;
    +      renderActivity('offline');
    +      presence.setAttribute('data-state', 'waiting');
    +      presence.querySelector('.label').textContent = 'canvas server offline';
    +    };
    +  }
    +  connectEvents();
    +})();`;
    +}
    +
    +// The chrome page: header bar, artifact iframe, conversation rail.
    +function renderCanvasHtml(session, { clientPath = '/client.js', cssPath = '/canvas.css' } = {}) {
    +  const name = path.basename(session.file);
    +  const bootstrap = JSON.stringify({
    +    key: session.key,
    +    file: session.file,
    +    status: session.status,
    +    endedBy: session.endedBy || null,
    +    chat: session.chat
    +  }).replace(/
    +
    +
    +
    +
    +${escapeHtml(name)} · Plan Canvas
    +
    +
    +
    +
    +
    +
    +
    + + Plan Canvas + ${escapeHtml(name)} +
    +
    +
    agent not connected
    +
    + Annotate +
    + + + +
    +
    +
    + +

    Session ended

    +
    + +
    + + +`; +} + +// ECC-styled document template for rendered markdown plan artifacts. +function renderMarkdownArtifactHtml(bodyHtml, { title, sdkSrc }) { + const hasMermaid = bodyHtml.includes('class="mermaid"'); + return ` + + + + +${escapeHtml(title)} + + + +
    +${bodyHtml} +
    +${hasMermaid ? mermaidLoaderScript(mermaidUrl()) : ''} + + +`; +} + +// Landing page listing sessions (GET /). +function renderSessionListHtml(sessions) { + const rows = sessions.map(s => { + const status = s.status === 'ended' ? `ended by ${escapeHtml(s.endedBy || 'agent')}` : s.status; + const link = s.status === 'ended' + ? escapeHtml(path.basename(s.file)) + : `${escapeHtml(path.basename(s.file))}`; + return `${link}${escapeHtml(s.file)}${status}`; + }).join('\n'); + return ` + + + +Plan Canvas · sessions + + + +

    Plan Canvas sessions

    +${sessions.length ? `${rows}
    ArtifactPathStatus
    ` : '

    No sessions yet. Ask your agent to open a plan with the plan-canvas skill.

    '} + +`; +} + +module.exports = { + canvasCss, + canvasClientJs, + renderCanvasHtml, + renderMarkdownArtifactHtml, + renderSessionListHtml +}; diff --git a/github_code/affaan-m__ECC/scripts/lib/powershell-destructive-command.js b/github_code/affaan-m__ECC/scripts/lib/powershell-destructive-command.js new file mode 100644 index 0000000000000000000000000000000000000000..6ec29445319b23324dd2f3dae662b5b2d2a49cf9 --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/powershell-destructive-command.js @@ -0,0 +1,2089 @@ +'use strict'; + +/** + * Pure PowerShell destructive-command classifier. + * + * This is deliberately a small policy parser rather than a PowerShell + * interpreter. It understands the quoting, escaping, subexpression, and + * nested-shell forms needed to make GateGuard and governance reach the same + * decision without retaining raw command text. + */ + +const RULE_IDS = Object.freeze({ + REMOVE_RECURSE: 'powershell.remove-item.recurse', + REMOVE_FORCE: 'powershell.remove-item.force', + REMOVE_WILDCARD: 'powershell.remove-item.wildcard', + REMOVE_SPLAT: 'powershell.remove-item.splat', + PIPELINE_RECURSE: 'powershell.remove-item.pipeline-recurse', + CLEAR_CONTENT: 'powershell.clear-content', + CLEAR_DISK: 'powershell.clear-disk', + FORMAT_VOLUME: 'powershell.format-volume', + DOTNET_DIRECTORY_DELETE: 'powershell.dotnet.directory-delete', + DOTNET_FILE_DELETE: 'powershell.dotnet.file-delete', + CMD_RECURSIVE_DELETE: 'powershell.cmd.recursive-delete', + DYNAMIC_EXECUTION: 'powershell.dynamic-execution', + SCAN_DEPTH_EXCEEDED: 'powershell.scan-depth-exceeded', +}); + +const DELETE_COMMANDS = new Set([ + 'remove-item', + 'remove-itemproperty', + 'rp', + 'ri', + 'rm', + 'rmdir', + 'rd', + 'del', + 'erase', +]); + +const POWERSHELL_COMMANDS = new Set(['powershell', 'pwsh']); +const CMD_DELETE_COMMANDS = new Set(['rd', 'rmdir', 'del', 'erase']); +const START_PROCESS_VALUE_PARAMETERS = new Set([ + 'argumentlist', + 'credential', + 'environment', + 'filepath', + 'redirectstandarderror', + 'redirectstandardinput', + 'redirectstandardoutput', + 'verb', + 'windowstyle', + 'workingdirectory', +]); +const START_PROCESS_SWITCH_PARAMETERS = new Set([ + 'loaduserprofile', + 'nonewwindow', + 'passthru', + 'usenewenvironment', + 'wait', +]); +const ALIAS_VALUE_PARAMETERS = new Set([ + 'name', 'value', 'description', 'option', 'scope', + 'erroraction', 'warningaction', 'informationaction', 'progressaction', + 'errorvariable', 'warningvariable', 'informationvariable', + 'outvariable', 'outbuffer', 'pipelinevariable', +]); +const ALIAS_SWITCH_PARAMETERS = new Set([ + 'force', 'passthru', 'whatif', 'confirm', 'verbose', 'debug', +]); +const ALIAS_PARAMETER_ABBREVIATIONS = Object.freeze({ + ea: 'erroraction', wa: 'warningaction', infa: 'informationaction', proga: 'progressaction', + ev: 'errorvariable', wv: 'warningvariable', iv: 'informationvariable', + ov: 'outvariable', ob: 'outbuffer', pv: 'pipelinevariable', + wi: 'whatif', cf: 'confirm', vb: 'verbose', db: 'debug', +}); +const MAX_SCAN_DEPTH = 4; +const MAX_CONTEXT_LENGTH = 4096; +const DYNAMIC_EXECUTION_MARKER = '__ecc_dynamic_execution__'; + +function normalizeSmartQuotes(value) { + return String(value || '') + .replace(/[\u2018\u2019\u201a\u201b]/g, "'") + .replace(/[\u201c\u201d\u201e]/g, '"') + .replace(/[\u2013\u2014\u2015]/g, '-'); +} + +function commandBasename(value) { + const parts = String(value || '').split(/[\\/]/); + return (parts[parts.length - 1] || '').replace(/\.exe$/i, '').toLowerCase(); +} + +function isParameterPrefix(token, parameter) { + const raw = String(token || ''); + if (!raw.startsWith('-')) return false; + const name = raw.replace(/^-+/, '').split(':')[0].toLowerCase(); + return name.length > 0 && parameter.startsWith(name); +} + +function isEnabledSwitch(token, parameter) { + if (!isParameterPrefix(token, parameter)) return false; + const separator = String(token).indexOf(':'); + if (separator === -1) return true; + return !/^\$?(?:false|null|0)$/i.test(String(token).slice(separator + 1)); +} + +function isEncodedCommandFlag(token) { + return isParameterPrefix(token, 'encodedcommand'); +} + +function isCommandFlag(token) { + const name = String(token || '').replace(/^-+/, '').split(':')[0].toLowerCase(); + return isParameterPrefix(token, 'command') || + isParameterPrefix(token, 'commandwithargs') || name === 'cwa'; +} + +function normalizeHereStrings(input, executablePayloads = []) { + const output = [...input]; + const replacements = []; + let ordinaryQuote = null; + let lineComment = false; + let blockComment = false; + let bracedVariable = false; + + for (let index = 0; index < input.length - 1; index += 1) { + const char = input[index]; + const next = input[index + 1]; + if (lineComment) { + if (char === '\n' || char === '\r') lineComment = false; + continue; + } + if (blockComment) { + if (char === '#' && next === '>') { + blockComment = false; + index += 1; + } + continue; + } + if (bracedVariable) { + if (char === '`') index += 1; + else if (char === '}') bracedVariable = false; + continue; + } + if (ordinaryQuote === "'") { + if (char === "'" && input[index + 1] === "'") index += 1; + else if (char === "'") ordinaryQuote = null; + continue; + } + if (char === '`') { + index += 1; + continue; + } + if (ordinaryQuote === '"') { + if (char === '"') ordinaryQuote = null; + continue; + } + + if (char === '$' && next === '{') { + bracedVariable = true; + index += 1; + continue; + } + if (char === '<' && next === '#') { + blockComment = true; + index += 1; + continue; + } + if (char === '#') { + lineComment = true; + continue; + } + + if (input[index] !== '@' || (input[index + 1] !== "'" && input[index + 1] !== '"')) { + if (char === "'" || char === '"') ordinaryQuote = char; + continue; + } + + const quote = input[index + 1]; + let openerLineEnd = index + 2; + while (input[openerLineEnd] === ' ' || input[openerLineEnd] === '\t') openerLineEnd += 1; + if (input[openerLineEnd] === '\r' && input[openerLineEnd + 1] === '\n') openerLineEnd += 1; + if (input[openerLineEnd] !== '\n') { + if (openerLineEnd >= input.length) break; + continue; + } + + let closingEnd = -1; + for (let lineStart = openerLineEnd + 1; lineStart < input.length;) { + let contentStart = lineStart; + while (input[contentStart] === ' ' || input[contentStart] === '\t') contentStart += 1; + if (input[contentStart] === quote && input[contentStart + 1] === '@') { + closingEnd = contentStart + 2; + break; + } + while (lineStart < input.length && input[lineStart] !== '\n') lineStart += 1; + if (lineStart < input.length) lineStart += 1; + } + + const contentEnd = closingEnd === -1 ? input.length : closingEnd - 2; + const content = input.slice(openerLineEnd + 1, contentEnd); + + // Represent a here-string as one ordinary literal token. Standalone + // literals remain inert, while static consumers such as Invoke-Expression + // and `pwsh -Command -` can recover the value from normal token flow. + replacements.push({ + end: closingEnd === -1 ? input.length : closingEnd, + start: index, + value: `'${content.replace(/'/g, "''")}'`, + }); + + // Expandable here-strings execute their unescaped subexpressions while the + // string value is being formed, independently of any later consumer. + if (quote === '"') { + for (let offset = openerLineEnd + 1; offset < contentEnd; offset += 1) { + if (input[offset] === '`') { + offset += 1; + continue; + } + if (input[offset] !== '$' || input[offset + 1] !== '(') continue; + const group = readBalancedGroup(input, offset + 1, '(', ')'); + if (!group || group.end > contentEnd) break; + executablePayloads.push(group.body); + offset = group.end - 1; + } + } + + if (closingEnd === -1) break; + index = closingEnd - 1; + } + + if (replacements.length === 0) return output.join(''); + let normalized = ''; + let cursor = 0; + for (const replacement of replacements) { + normalized += output.slice(cursor, replacement.start).join(''); + normalized += replacement.value; + cursor = replacement.end; + } + normalized += output.slice(cursor).join(''); + return normalized; +} + +function stripPowerShellComments(input) { + const output = [...input]; + let quote = null; + let lineComment = false; + let blockComment = false; + let bracedVariable = false; + + for (let index = 0; index < input.length; index += 1) { + const char = input[index]; + const next = input[index + 1]; + + if (lineComment) { + if (char === '\n' || char === '\r') { + lineComment = false; + } else { + output[index] = ' '; + } + continue; + } + + if (blockComment) { + if (char === '#' && next === '>') { + output[index] = ' '; + output[index + 1] = ' '; + blockComment = false; + index += 1; + } else if (char !== '\n' && char !== '\r') { + output[index] = ' '; + } + continue; + } + + if (bracedVariable) { + if (char === '`') index += 1; + else if (char === '}') bracedVariable = false; + continue; + } + + if (quote === "'") { + if (char === "'" && next === "'") { + index += 1; + } else if (char === "'") { + quote = null; + } + continue; + } + if (char === '`') { + index += 1; + continue; + } + if (quote === '"') { + if (char === '"') quote = null; + continue; + } + if (char === "'" || char === '"') { + quote = char; + continue; + } + + if (char === '$' && next === '{') { + bracedVariable = true; + index += 1; + continue; + } + + if (char === '<' && next === '#') { + output[index] = ' '; + output[index + 1] = ' '; + blockComment = true; + index += 1; + continue; + } + + if (char === '#') { + output[index] = ' '; + lineComment = true; + } + } + + return output.join(''); +} + +/** + * Read one balanced PowerShell container. Quotes do not affect delimiter + * balance, and a backtick protects exactly the following character. Callers + * stop after the first unmatched opener, which keeps malformed input linear. + */ +function readBalancedGroup(input, openingIndex, open, close) { + let depth = 1; + let quote = null; + let lineComment = false; + let blockComment = false; + let bracedVariable = false; + + for (let index = openingIndex + 1; index < input.length; index += 1) { + const char = input[index]; + const next = input[index + 1]; + + if (lineComment) { + if (char === '\n' || char === '\r') lineComment = false; + continue; + } + if (blockComment) { + if (char === '#' && next === '>') { + blockComment = false; + index += 1; + } + continue; + } + if (bracedVariable) { + if (char === '`') index += 1; + else if (char === '}') bracedVariable = false; + continue; + } + + if (quote === "'") { + if (char === "'" && input[index + 1] === "'") { + index += 1; + } else if (char === "'") { + quote = null; + } + continue; + } + if (char === '`') { + index += 1; + continue; + } + + if (quote === '"') { + if (char === '"') quote = null; + continue; + } + + if (char === "'" || char === '"') { + quote = char; + continue; + } + + if (char === '$' && next === '{') { + bracedVariable = true; + index += 1; + continue; + } + + if (char === '<' && next === '#') { + blockComment = true; + index += 1; + continue; + } + if (char === '#') { + lineComment = true; + continue; + } + + if (char === open) { + depth += 1; + } else if (char === close) { + depth -= 1; + if (depth === 0) { + return { + body: input.slice(openingIndex + 1, index), + end: index + 1, + }; + } + } + } + + return null; +} + +/** + * Decide whether a script block is executed at its declaration site. Function + * and variable declarations remain inert, while call operators, control-flow + * clauses, and common script-block-consuming commands execute their bodies. + */ +function currentClause(prefix) { + const clauseStart = Math.max( + prefix.lastIndexOf(';'), + prefix.lastIndexOf('\n'), + prefix.lastIndexOf('\r') + ); + return prefix.slice(clauseStart + 1).trim(); +} + +function invokesContainerResult(prefix) { + const clause = currentClause(prefix); + const pipelineStart = clause.lastIndexOf('|'); + const pipelineCommand = clause.slice(pipelineStart + 1).trim(); + return /(?:^|\s)(?:&|\.)\s*$/.test(clause) || + /\.\s*(?:foreach|where)\s*$/i.test(clause) || + /-(?:action|begin|command|end|expression|filter|initializationscript|parallel|process|scriptblock)(?:\s*:\s*)?$/i.test(clause) || + /^(?:(?:[\w.-]+\\)?(?:foreach-object|where-object|foreach|where|invoke-command|start-job|measure-command)|%|\?)(?:\s|$)/i.test(pipelineCommand); +} + +function invokesDynamicResult(prefix) { + return invokesContainerResult(prefix) || + /(?:^|\s)(?:iex|invoke-expression)\s*$/i.test(currentClause(prefix)); +} + +function deferredScriptBlockName(prefix) { + const clause = currentClause(prefix); + const functionMatch = clause.match(/^(?:function|filter|workflow)\s+(?:(?:global|local|script|private):)?([A-Za-z_][\w-]*)\b/i); + if (functionMatch) return functionMatch[1].toLowerCase(); + const classMatch = clause.match(/^class\s+([A-Za-z_][\w-]*)\b/i); + if (classMatch) return `__class__:${classMatch[1].toLowerCase()}`; + const variableMatch = clause.match( + /^((?:\$\{[^}]+\}|\$(?:[A-Za-z_][\w-]*:)?[A-Za-z_][\w-]*(?:\[[^\]]+\]|\.[A-Za-z_][\w-]*)*))\s*=\s*$/ + ); + return variableMatch ? variableMatch[1].toLowerCase() : null; +} + +function isExecutableScriptBlock(prefix, options = {}) { + if (options.executeBareScriptBlocks) return true; + const clause = currentClause(prefix); + const pipelineStart = clause.lastIndexOf('|'); + const pipelineCommand = clause.slice(pipelineStart + 1).trim(); + + if (invokesContainerResult(prefix)) return true; + if (/^(?:if|elseif|else|for|foreach|while|do|switch|default|try|catch|finally|trap|begin|process|end|dynamicparam|clean)\b/i.test(clause)) { + return true; + } + return /^(?:(?:[\w.-]+\\)?(?:foreach-object|where-object|foreach|where|invoke-command|start-job|measure-command)|%|\?)(?:\s|$)/i.test(pipelineCommand); +} + +function isInvokedAfterContainer(input, end) { + let index = end; + const skipSpacing = () => { + while (index < input.length) { + if (/\s/.test(input[index])) { + index += 1; + } else if (input[index] === '`' && /[\r\n]/.test(input[index + 1] || '')) { + index += input[index + 1] === '\r' && input[index + 2] === '\n' ? 3 : 2; + } else { + break; + } + } + }; + + while (index < input.length) { + skipSpacing(); + if (input[index] !== '.') return false; + index += 1; + skipSpacing(); + + let method = ''; + const quote = input[index] === "'" || input[index] === '"' ? input[index++] : null; + while (index < input.length) { + const char = input[index]; + if (char === '`' && index + 1 < input.length) { + method += input[index + 1]; + index += 2; + } else if (quote ? char === quote : !/[A-Za-z]/.test(char)) { + if (quote) index += 1; + break; + } else { + method += char; + index += 1; + } + } + skipSpacing(); + if (input[index] !== '(') return false; + + const normalizedMethod = method.toLowerCase(); + if (['invoke', 'invokereturnasis', 'invokewithcontext'].includes(normalizedMethod)) { + return true; + } + if (normalizedMethod !== 'getnewclosure') return false; + index += 1; + skipSpacing(); + if (input[index] !== ')') return false; + index += 1; + } + return false; +} + +function staticStringResult(body) { + const value = String(body || '').trim(); + if (value.length < 2) return null; + const quote = value[0]; + if ((quote !== "'" && quote !== '"') || value[value.length - 1] !== quote) return null; + const content = value.slice(1, -1); + return quote === "'" ? content.replace(/''/g, "'") : decodeDoubleQuotedString(content); +} + +function decodeDoubleQuotedString(content) { + const input = String(content || ''); + let value = ''; + for (let index = 0; index < input.length; index += 1) { + const char = input[index]; + if (char !== '`' || index + 1 >= input.length) { + value += char; + continue; + } + const escaped = input[index + 1]; + index += 1; + if (escaped === '\r' && input[index + 1] === '\n') index += 1; + if (escaped !== '\r' && escaped !== '\n') value += escaped; + } + return value; +} + +function expandStaticDoubleQuotedString(content, state, findings) { + const input = String(content || ''); + let value = ''; + + for (let index = 0; index < input.length; index += 1) { + const char = input[index]; + if (char === '`' && index + 1 < input.length) { + const escaped = input[index + 1]; + index += 1; + if (escaped === '\r' && input[index + 1] === '\n') index += 1; + if (escaped !== '\r' && escaped !== '\n') value += escaped; + continue; + } + if (char !== '$') { + value += char; + continue; + } + + if (input[index + 1] === '(') { + const group = readBalancedGroup(input, index + 1, '(', ')'); + const reference = group ? variableReference(group.body) : null; + const staticValue = reference ? state?.staticScalars.get(reference) : undefined; + if (!group || staticValue === undefined) { + findings.add(RULE_IDS.DYNAMIC_EXECUTION); + return null; + } + value += staticValue; + index = group.end - 1; + continue; + } + + const referenceMatch = input.slice(index).match( + /^(?:\$\{[^}]+\}|\$(?:[A-Za-z_][\w-]*:)?[A-Za-z_][\w-]*(?:\[[^\]]+\]|\.[A-Za-z_][\w-]*)*)/ + ); + if (!referenceMatch) { + value += char; + continue; + } + + const reference = variableReference(referenceMatch[0]); + const staticValue = reference ? state?.staticScalars.get(reference) : undefined; + if (staticValue === undefined) { + findings.add(RULE_IDS.DYNAMIC_EXECUTION); + return null; + } + value += staticValue; + index += referenceMatch[0].length - 1; + } + + return value; +} + +function leadingStaticStringResult(source) { + const input = String(source || ''); + let index = 0; + while (/\s/.test(input[index] || '')) index += 1; + const quote = input[index]; + if (quote !== "'" && quote !== '"') return null; + index += 1; + let value = ''; + while (index < input.length) { + const char = input[index]; + if (quote === "'" && char === "'" && input[index + 1] === "'") { + value += "'"; + index += 2; + continue; + } + if (quote === '"' && char === '`' && index + 1 < input.length) { + const escaped = input[index + 1]; + index += 2; + if (escaped === '\r' && input[index] === '\n') index += 1; + if (escaped !== '\r' && escaped !== '\n') value += escaped; + continue; + } + if (char === quote) return value; + value += char; + index += 1; + } + return null; +} + +function staticScalarResult(body, depth = 0) { + if (depth > MAX_SCAN_DEPTH) return null; + const value = String(body || '').trim(); + const literal = staticStringResult(value); + if (literal !== null) return literal; + + const isSubexpression = value.startsWith('$('); + const openingIndex = isSubexpression ? 1 : 0; + if (value[openingIndex] !== '(') return null; + const group = readBalancedGroup(value, openingIndex, '(', ')'); + if (!group || group.end !== value.length) return null; + return staticScalarResult(group.body, depth + 1); +} + +function staticCommandResult(body) { + const value = staticScalarResult(body); + const command = value === null ? '' : value.trim(); + return command && /^[A-Za-z_][\w./\\-]*$/.test(command) ? command : null; +} + +function staticStringArrayResult(body) { + const input = String(body || ''); + const items = []; + let item = ''; + let quote = null; + let depth = 0; + for (let index = 0; index < input.length; index += 1) { + const char = input[index]; + if (char === '`' && quote === '"' && index + 1 < input.length) { + item += char + input[index + 1]; + index += 1; + continue; + } + if (quote === "'" && char === "'" && input[index + 1] === "'") { + item += "''"; + index += 1; + continue; + } + if (char === "'" || char === '"') { + quote = quote === char ? null : (quote || char); + item += char; + continue; + } + if (!quote && char === '(') depth += 1; + if (!quote && char === ')') depth -= 1; + if (!quote && depth === 0 && char === ',') { + items.push(item); + item = ''; + continue; + } + item += char; + } + if (quote || depth !== 0) return null; + items.push(item); + const values = items.map(value => staticScalarResult(value)); + return values.length > 0 && values.every(value => value !== null) + ? values.join(' ') + : null; +} + +function staticTypeNameResult(body) { + const value = String(body || '').trim(); + const match = value.match(/^\[([A-Za-z_][\w-]*)\]$/); + if (match) return match[1]; + const scalar = staticScalarResult(value); + if (scalar !== null && /^[A-Za-z_][\w-]*$/.test(scalar)) return scalar; + const openingIndex = value.startsWith('(') ? 0 : -1; + if (openingIndex === -1) return null; + const group = readBalancedGroup(value, openingIndex, '(', ')'); + return group && group.end === value.length ? staticTypeNameResult(group.body) : null; +} + +function variableReference(value) { + const variable = String(value || '').trim(); + return /^(?:\$\{[^}]+\}|\$(?:[A-Za-z_][\w-]*:)?[A-Za-z_][\w-]*(?:\[[^\]]+\]|\.[A-Za-z_][\w-]*)*)$/.test(variable) + ? variable.toLowerCase() + : null; +} + +function staticOutputResult(body, depth = 0) { + if (depth > MAX_SCAN_DEPTH) return null; + const scalar = staticScalarResult(body); + if (scalar !== null) return scalar.trim(); + const value = String(body || '').trim(); + const openingIndex = value.startsWith('$(') ? 1 : 0; + if (value[openingIndex] === '(') { + const group = readBalancedGroup(value, openingIndex, '(', ')'); + if (group && group.end === value.length) { + return staticOutputResult(group.body, depth + 1); + } + } + const statements = parseStatements(value); + if (statements.length !== 1 || statements[0].length !== 1) return null; + const tokens = statements[0][0]; + const command = commandBasename(tokens[0]); + if ((command !== 'write-output' && command !== 'echo') || tokens.length < 2) return null; + return tokens.slice(1).join(' '); +} + +function isPipedToPowerShellStdin(input, end) { + return /^\s*\|\s*(?:pwsh|powershell)(?:\.exe)?\s+-(?:command|c)\s+-\s*(?:[;\r\n]|$)/i.test( + input.slice(end) + ); +} + +/** + * Extract executable `$()`, `@()`, grouping parentheses, and selected script + * blocks while masking every container from the outer statement pass. `$()` + * also executes inside double quotes. Other containers are literal there. + */ +function extractExecutableContainers(input, options = {}) { + const bodies = []; + const deferredFunctions = []; + const masked = [...input]; + let quote = null; + let bracedVariable = false; + let context = ''; + let contextTruncated = false; + + const resetContext = () => { + context = ''; + contextTruncated = false; + }; + + const appendContext = value => { + for (const contextChar of value) { + if (contextChar === ';' || contextChar === '}') { + resetContext(); + } else if (contextChar === '\n' || contextChar === '\r') { + const clause = currentClause(context); + if (/^(?:if|elseif|else|for|foreach|while|do|switch|default|try|catch|finally|trap|function|filter|workflow|begin|process|end|dynamicparam|clean)\b/i.test(clause)) { + if (context && !context.endsWith(' ')) context += ' '; + } else { + resetContext(); + } + } else if (/\s/.test(contextChar)) { + if (context && !context.endsWith(' ')) context += ' '; + } else { + context += contextChar; + } + if (context.length > MAX_CONTEXT_LENGTH) { + context = context.slice(-Math.floor(MAX_CONTEXT_LENGTH / 2)); + contextTruncated = true; + } + } + }; + + for (let index = 0; index < input.length; index += 1) { + const char = input[index]; + + if (bracedVariable) { + if (char === '`' && index + 1 < input.length) { + appendContext(input[index + 1]); + index += 1; + } else if (char === '}') { + context += char; + bracedVariable = false; + } else { + appendContext(char); + } + continue; + } + + if (quote === "'") { + if (char === "'" && input[index + 1] === "'") { + index += 1; + } else if (char === "'") { + quote = null; + } + continue; + } + if (char === '`') { + if (!quote && index + 1 < input.length) { + const escaped = input[index + 1]; + appendContext(escaped === '\n' || escaped === '\r' ? ' ' : escaped); + if (escaped === '\r' && input[index + 2] === '\n') index += 1; + } + index += 1; + continue; + } + + if (!quote && char === "'") { + quote = "'"; + appendContext(' '); + continue; + } + + if (!quote && char === '$' && input[index + 1] === '{') { + appendContext('${'); + bracedVariable = true; + index += 1; + continue; + } + + if (char === '"') { + quote = quote === '"' ? null : '"'; + if (quote === '"') appendContext(' '); + continue; + } + + const isSubexpression = char === '$' && input[index + 1] === '('; + if (quote === '"' && !isSubexpression) continue; + + const isArrayExpression = !quote && char === '@' && input[index + 1] === '('; + const isGroupingExpression = !quote && char === '('; + const isScriptBlock = !quote && char === '{'; + const isHashtable = isScriptBlock && input[index - 1] === '@'; + const isCmdPayloadGroup = isGroupingExpression && + /(?:^|\s)cmd(?:\.exe)?\s+\/[ck](?:\s|$)/i.test(currentClause(context)); + if (!isSubexpression && !isArrayExpression && !isGroupingExpression && !isScriptBlock) { + if (!quote) appendContext(char); + continue; + } + if (isCmdPayloadGroup) { + appendContext(char); + continue; + } + + const openingIndex = isSubexpression || isArrayExpression ? index + 1 : index; + const open = isScriptBlock ? '{' : '('; + const close = isScriptBlock ? '}' : ')'; + const group = readBalancedGroup(input, openingIndex, open, close); + if (!group) { + for (let offset = index; offset < input.length; offset += 1) masked[offset] = ' '; + break; + } + + const withinDoubleQuote = quote === '"'; + const prefix = context; + const invokedAfter = isInvokedAfterContainer(input, group.end); + const createsScriptBlock = /\[\s*(?:system\.management\.automation\.)?scriptblock\s*\]\s*::\s*create\s*$/i.test( + currentClause(prefix) + ); + const shouldScan = contextTruncated || !isScriptBlock || isHashtable || invokedAfter || + isExecutableScriptBlock(prefix, options); + if (shouldScan) { + const executesNestedScriptBlocks = isScriptBlock && /^switch\b/i.test(currentClause(prefix)); + bodies.push({ + body: group.body, + options: { + executeBareScriptBlocks: Boolean(options.executeBareScriptBlocks) || + invokedAfter || executesNestedScriptBlocks || + (!isScriptBlock && invokesContainerResult(prefix)), + }, + }); + } else { + const functionName = deferredScriptBlockName(prefix); + if (functionName) deferredFunctions.push({ body: group.body, functionName }); + } + if (createsScriptBlock && (invokedAfter || options.executeBareScriptBlocks)) { + const scalarReference = variableReference(group.body); + const scriptText = staticStringResult(group.body) || + (scalarReference ? options.staticScalars?.get(scalarReference) : null); + if (scriptText) { + bodies.push({ body: scriptText, options: { executeBareScriptBlocks: true } }); + } + } + for (let offset = index; offset < group.end; offset += 1) { + masked[offset] = ' '; + } + let resolvedCommand = null; + if (!isScriptBlock) { + if (isSubexpression || invokesContainerResult(prefix)) { + resolvedCommand = staticOutputResult(group.body); + if (resolvedCommand === null && isSubexpression) { + const scalarReference = variableReference(group.body); + if (scalarReference) { + resolvedCommand = options.staticScalars?.get(scalarReference) ?? null; + } + } + } else if (/^(?:start-process|saps|start)\b/i.test(currentClause(prefix))) { + resolvedCommand = staticStringArrayResult(group.body); + } else if (/^new-object\b/i.test(currentClause(prefix))) { + resolvedCommand = staticTypeNameResult(group.body); + } else if (isPipedToPowerShellStdin(input, group.end)) { + resolvedCommand = staticScalarResult(group.body); + } else { + resolvedCommand = staticCommandResult(group.body); + } + } + const executableBlockExpression = /\{|\[\s*(?:system\.management\.automation\.)?scriptblock\s*\]\s*::\s*create/i.test( + maskQuotedStrings(group.body) + ); + if (!resolvedCommand && !isScriptBlock && invokesDynamicResult(prefix) && !executableBlockExpression) { + resolvedCommand = DYNAMIC_EXECUTION_MARKER; + } + if (resolvedCommand) { + for (let offset = 0; offset < resolvedCommand.length; offset += 1) { + masked[index + offset] = resolvedCommand[offset]; + } + if (!withinDoubleQuote) appendContext(resolvedCommand); + } else if (isScriptBlock) { + if (invokesContainerResult(prefix)) { + context = prefix; + } else { + resetContext(); + } + } else if (!withinDoubleQuote) { + appendContext(' '); + } + index = group.end - 1; + } + + return { bodies, deferredFunctions, outer: masked.join('') }; +} + +/** + * Split PowerShell into statements, pipelines, and dequoted words. Backticks + * are interpreted before token comparison so `Rem`ove-Item` normalizes to the + * command PowerShell executes. Backslashes remain ordinary characters. + */ +function parseStatements(input) { + const statements = []; + let statement = []; + let segment = []; + let segmentQuotedTokens = []; + let segmentQuoteKinds = []; + let segmentTokenSources = []; + let segmentInlineValueQuoteKinds = []; + let word = ''; + let wordSource = ''; + let wordHasQuotedContent = false; + let wordHasUnquotedContent = false; + let wordQuoteKind = null; + let wordInlineValueQuoteKind = null; + let wordInlineValueQuoteClosed = false; + let quote = null; + let parenDepth = 0; + let callOperatorPending = false; + + const flushWord = () => { + if (word) { + segment.push(word); + segmentQuotedTokens.push(wordHasQuotedContent && !wordHasUnquotedContent); + segmentQuoteKinds.push( + wordHasQuotedContent && !wordHasUnquotedContent ? wordQuoteKind : null + ); + segmentTokenSources.push(wordSource); + segmentInlineValueQuoteKinds.push( + wordInlineValueQuoteClosed && wordInlineValueQuoteKind !== 'mixed' + ? wordInlineValueQuoteKind + : null + ); + } + word = ''; + wordSource = ''; + wordHasQuotedContent = false; + wordHasUnquotedContent = false; + wordQuoteKind = null; + wordInlineValueQuoteKind = null; + wordInlineValueQuoteClosed = false; + }; + const flushSegment = () => { + flushWord(); + if (segment.length) { + Object.defineProperties(segment, { + invokedByCallOperator: { value: callOperatorPending }, + quotedTokens: { value: segmentQuotedTokens }, + quoteKinds: { value: segmentQuoteKinds }, + tokenSources: { value: segmentTokenSources }, + inlineValueQuoteKinds: { value: segmentInlineValueQuoteKinds }, + }); + statement.push(segment); + callOperatorPending = false; + } + segment = []; + segmentQuotedTokens = []; + segmentQuoteKinds = []; + segmentTokenSources = []; + segmentInlineValueQuoteKinds = []; + }; + const flushStatement = () => { + flushSegment(); + if (statement.length) statements.push(statement); + statement = []; + }; + + for (let index = 0; index < input.length; index += 1) { + const char = input[index]; + + if (quote === "'") { + if (char === "'" && input[index + 1] === "'") { + word += "'"; + wordSource += "''"; + index += 1; + } else if (char === "'") { + quote = null; + if (wordInlineValueQuoteKind === "'") wordInlineValueQuoteClosed = true; + } else { + word += char; + wordSource += char; + wordHasQuotedContent = true; + } + continue; + } + + if (char === '`') { + if (index + 1 >= input.length) { + word += '`'; + wordSource += '`'; + continue; + } + const escaped = input[index + 1]; + wordSource += `\`${escaped}`; + index += 1; + if (escaped === '\n' || escaped === '\r') { + if (escaped === '\r' && input[index + 1] === '\n') { + wordSource += '\n'; + index += 1; + } + } else { + if (wordInlineValueQuoteClosed) wordInlineValueQuoteKind = 'mixed'; + word += escaped; + if (quote) wordHasQuotedContent = true; + else wordHasUnquotedContent = true; + } + continue; + } + + if (quote === '"') { + if (char === '"') { + quote = null; + if (wordInlineValueQuoteKind === '"') wordInlineValueQuoteClosed = true; + } else { + word += char; + wordSource += char; + wordHasQuotedContent = true; + } + continue; + } + + if (char === "'" || char === '"') { + if (wordInlineValueQuoteClosed) { + wordInlineValueQuoteKind = 'mixed'; + } else if (wordInlineValueQuoteKind === null && /^-+[^:\s]+:$/.test(word)) { + wordInlineValueQuoteKind = char; + } + quote = char; + wordHasQuotedContent = true; + wordQuoteKind = wordQuoteKind === null || wordQuoteKind === char ? char : 'mixed'; + continue; + } + + if (char === '(') { + if (wordInlineValueQuoteClosed) wordInlineValueQuoteKind = 'mixed'; + parenDepth += 1; + word += char; + wordSource += char; + wordHasUnquotedContent = true; + continue; + } + if (char === ')' && parenDepth > 0) { + if (wordInlineValueQuoteClosed) wordInlineValueQuoteKind = 'mixed'; + parenDepth -= 1; + word += char; + wordSource += char; + wordHasUnquotedContent = true; + continue; + } + + if (parenDepth === 0 && (char === ';' || char === '\n' || char === '\r')) { + flushStatement(); + continue; + } + if (parenDepth === 0 && char === '|') { + flushSegment(); + continue; + } + if (parenDepth === 0 && char === '&') { + if (word || segment.length) flushStatement(); + callOperatorPending = true; + continue; + } + if (/\s/.test(char)) { + flushWord(); + continue; + } + + if (wordInlineValueQuoteClosed) wordInlineValueQuoteKind = 'mixed'; + word += char; + wordSource += char; + wordHasUnquotedContent = true; + } + + flushStatement(); + return statements; +} + +function maskQuotedStrings(input) { + let output = ''; + let quote = null; + + for (let index = 0; index < input.length; index += 1) { + const char = input[index]; + if (quote === "'") { + output += ' '; + if (char === "'" && input[index + 1] === "'") { + output += ' '; + index += 1; + } else if (char === "'") { + quote = null; + } + continue; + } + if (char === '`') { + if (index + 1 < input.length) { + output += quote ? ' ' : input[index + 1]; + index += 1; + } else { + output += quote ? ' ' : '`'; + } + continue; + } + if (quote === '"') { + output += ' '; + if (char === '"') quote = null; + continue; + } + if (char === "'" || char === '"') { + quote = char; + output += ' '; + continue; + } + output += char; + } + + return output; +} + +function decodeUtf16LeBase64(value) { + const encoded = String(value || '').trim(); + if (!encoded || encoded.length % 4 !== 0 || !/^[A-Za-z0-9+/]+={0,2}$/.test(encoded)) { + return null; + } + + const bytes = Buffer.from(encoded, 'base64'); + if (bytes.length === 0 || bytes.length % 2 !== 0) return null; + if (bytes.toString('base64').replace(/=+$/, '') !== encoded.replace(/=+$/, '')) return null; + + const decoded = bytes.toString('utf16le'); + if (!decoded || decoded.includes('\uFFFD') || decoded.includes('\u0000')) return null; + return decoded; +} + +function createScanState() { + return { + deferredFunctions: new Map(), + invokedCommands: new Set(), + pendingInvocations: [], + resolvingFunctions: false, + scannedFunctions: new Set(), + staticScalars: new Map(), + aliases: new Map(), + }; +} + +function collectStaticScalarAssignments(input, state) { + const variable = String.raw`(\$\{[^}]+\}|\$(?:[A-Za-z_][\w-]*:)?[A-Za-z_][\w-]*(?:\[[^\]]+\]|\.[A-Za-z_][\w-]*)*)`; + const firstReferences = new Map(); + const referencePattern = new RegExp(variable, 'g'); + let reference; + while ((reference = referencePattern.exec(input)) !== null) { + const name = reference[1].toLowerCase(); + if (!firstReferences.has(name)) firstReferences.set(name, reference.index); + } + const assignmentCounts = new Map(); + const assignmentPattern = new RegExp(`${variable}\\s*(?:\\+=|-=|\\*=|\\/=|%=|=)`, 'g'); + let assignmentMatch; + while ((assignmentMatch = assignmentPattern.exec(input)) !== null) { + const name = assignmentMatch[1].toLowerCase(); + assignmentCounts.set(name, (assignmentCounts.get(name) || 0) + 1); + } + const pattern = new RegExp( + String.raw`(?:^|[;\r\n])\s*${variable}\s*=\s*(?:'((?:''|[^'])*)'|"((?:\x60[\s\S]|[^\x60"])*)")\s*(?=;|\r?\n|$)`, + 'g' + ); + let match; + while ((match = pattern.exec(input)) !== null) { + const name = match[1].toLowerCase(); + // The scan pre-collects immutable scalars for nested executable bodies. + // A value assigned after an earlier reference cannot explain that use. + // Keep it unresolved so dynamic execution remains gated. Counting even + // quoted references is deliberately conservative, with a linear scan. + const assignmentIndex = match.index + match[0].indexOf(match[1]); + if (firstReferences.get(name) !== assignmentIndex) continue; + if (match[3] !== undefined && /(^|[^`])\$/.test(match[3])) continue; + const value = match[2] !== undefined + ? match[2].replace(/''/g, "'") + : decodeDoubleQuotedString(match[3]); + state.staticScalars.set(name, value); + } + for (const [name, count] of assignmentCounts) { + if (count !== 1) state.staticScalars.delete(name); + } +} + +function recordInvocation(state, commandName) { + if (!commandName || state.invokedCommands.has(commandName)) return; + state.invokedCommands.add(commandName); + if (state.resolvingFunctions) state.pendingInvocations.push(commandName); +} + +function registerDeferredFunction(state, definition) { + const definitions = state.deferredFunctions.get(definition.functionName) || []; + definitions.push(definition); + state.deferredFunctions.set(definition.functionName, definitions); + if (state.resolvingFunctions && state.invokedCommands.has(definition.functionName)) { + state.pendingInvocations.push(definition.functionName); + } +} + +function addNestedScan(payload, depth, findings, analysis, options = {}, scanState = null) { + if (depth >= MAX_SCAN_DEPTH) { + findings.add(RULE_IDS.SCAN_DEPTH_EXCEEDED); + return; + } + scanPowerShell(payload, depth + 1, findings, analysis, options, scanState); +} + +function staticTokenValue(tokens, index, state, findings, inline = false) { + const value = inline ? parameterValue(tokens[index]) : tokens[index]; + const quoteKind = inline ? tokens.inlineValueQuoteKinds?.[index] : tokens.quoteKinds?.[index]; + if (quoteKind === "'") return value; + const source = inline + ? parameterValue(tokens.tokenSources?.[index] || tokens[index]) + : tokens.tokenSources?.[index] ?? value; + return expandStaticDoubleQuotedString(source, state, findings); +} + +function staticPipelineInput(tokens, state, findings) { + if (!tokens || tokens.length === 0) return null; + if (tokens.length === 1) return staticTokenValue(tokens, 0, state, findings); + const command = commandBasename(tokens[0]); + if ((command === 'write-output' || command === 'echo') && tokens.length === 2) { + return staticTokenValue(tokens, 1, state, findings); + } + return null; +} + +function scanNestedPowerShell(tokens, depth, findings, analysis, scanState, upstreamTokens = null) { + for (let index = 1; index < tokens.length; index += 1) { + const token = tokens[index]; + + if (isEncodedCommandFlag(token)) { + const inlinePayload = parameterValue(token); + let encodedPayload = inlinePayload || tokens[index + 1]; + const payloadIndex = index + 1; + const quoteKind = tokens.quoteKinds?.[payloadIndex]; + const inlineQuoteKind = tokens.inlineValueQuoteKinds?.[index]; + if ((inlinePayload && inlineQuoteKind !== "'") || + (!inlinePayload && encodedPayload && quoteKind !== "'")) { + const source = inlinePayload + ? parameterValue(tokens.tokenSources?.[index] || token) + : tokens.tokenSources?.[payloadIndex] ?? encodedPayload; + const expanded = expandStaticDoubleQuotedString( + source || encodedPayload, + scanState, + findings + ); + if (expanded === null) return; + encodedPayload = expanded; + } + const decoded = decodeUtf16LeBase64(encodedPayload); + if (decoded !== null) addNestedScan(decoded, depth, findings, analysis, {}, scanState); + return; + } + + if (isCommandFlag(token)) { + const inlinePayload = parameterValue(token); + let payload = inlinePayload + ? [inlinePayload, ...tokens.slice(index + 1)].join(' ') + : tokens.slice(index + 1).join(' '); + const pipelinePayload = payload === '-' ? staticPipelineInput(upstreamTokens, scanState, findings) : null; + const payloadIndex = index + 1; + const inlineQuoteKind = tokens.inlineValueQuoteKinds?.[index]; + if (inlinePayload && inlineQuoteKind !== "'") { + const inlineSource = parameterValue(tokens.tokenSources?.[index] || token); + const expanded = expandStaticDoubleQuotedString( + inlineSource || inlinePayload, + scanState, + findings + ); + if (expanded === null) return; + payload = [expanded, ...tokens.slice(index + 1)].join(' '); + } else if (inlinePayload) { + payload = [inlinePayload, ...tokens.slice(index + 1)].join(' '); + } else if (tokens[payloadIndex] && tokens.quoteKinds?.[payloadIndex] !== "'") { + const expanded = expandStaticDoubleQuotedString( + tokens.tokenSources?.[payloadIndex] ?? tokens[payloadIndex], + scanState, + findings + ); + if (expanded === null) return; + payload = [expanded, ...tokens.slice(payloadIndex + 1)].join(' '); + } else { + const payloadReference = tokens.quoteKinds?.[payloadIndex] === "'" + ? null + : variableReference(payload); + if (payloadReference) { + const staticValue = scanState?.staticScalars.get(payloadReference); + if (staticValue === undefined) { + findings.add(RULE_IDS.DYNAMIC_EXECUTION); + return; + } + payload = staticValue; + } + } + if (pipelinePayload || (payload && payload !== '-')) { + addNestedScan( + pipelinePayload || payload, + depth, + findings, + analysis, + { executeBareScriptBlocks: true }, + scanState + ); + } + return; + } + } +} + +function splitCmdSegments(payload) { + const segments = []; + let segment = ''; + let quote = false; + + for (let index = 0; index < payload.length; index += 1) { + const char = payload[index]; + if (char === '^' && index + 1 < payload.length) { + segment += payload[index + 1]; + index += 1; + continue; + } + if (char === '"') { + quote = !quote; + continue; + } + if (!quote && (char === '&' || char === '|')) { + if (segment.trim()) segments.push(segment.trim()); + segment = ''; + continue; + } + segment += char; + } + if (segment.trim()) segments.push(segment.trim()); + return segments; +} + +function scanCmdWords(inputWords, depth, findings, analysis, scanState, wrapperDepth = 0) { + if (wrapperDepth > 64) { + findings.add(RULE_IDS.SCAN_DEPTH_EXCEEDED); + return; + } + + let words = inputWords.filter(Boolean).map(word => String(word)); + if (words.length === 0) return; + words[0] = words[0].replace(/^@+/, '').replace(/^\(+/, ''); + words[words.length - 1] = words[words.length - 1].replace(/\)+$/, ''); + + while (words.length > 0 && /^\d*(?:>>?|<>?|< index > 0 && /^else$/i.test(word)); + const trueBranch = elseIndex === -1 ? words : words.slice(0, elseIndex); + let commandIndex = 1; + if (/^\/i$/i.test(trueBranch[commandIndex])) commandIndex += 1; + if (/^not$/i.test(trueBranch[commandIndex])) commandIndex += 1; + if (/^(?:exist|defined|errorlevel|cmdextversion)$/i.test(trueBranch[commandIndex])) { + commandIndex += 2; + } else if (/^(?:equ|neq|lss|leq|gtr|geq)$/i.test(trueBranch[commandIndex + 1])) { + commandIndex += 3; + } else { + commandIndex += 1; + } + scanCmdWords( + trueBranch.slice(commandIndex), + depth, + findings, + analysis, + scanState, + wrapperDepth + 1 + ); + if (elseIndex !== -1) { + scanCmdWords( + words.slice(elseIndex + 1), + depth, + findings, + analysis, + scanState, + wrapperDepth + 1 + ); + } + return; + } + if (firstCommand === 'for') { + const doIndex = words.findIndex(word => /^do$/i.test(word)); + if (doIndex !== -1) { + scanCmdWords( + words.slice(doIndex + 1), + depth, + findings, + analysis, + scanState, + wrapperDepth + 1 + ); + } + return; + } + if (firstCommand === 'call') { + scanCmdWords(words.slice(1), depth, findings, analysis, scanState, wrapperDepth + 1); + return; + } + if (firstCommand === 'start') { + words = words.slice(1); + while (words.length > 0 && /^\//.test(words[0])) { + const option = words.shift().toLowerCase(); + if (/^\/(?:d|node|affinity)$/.test(option)) words.shift(); + } + const knownCommands = new Set([ + ...CMD_DELETE_COMMANDS, + ...POWERSHELL_COMMANDS, + 'call', + 'cmd', + 'for', + 'if', + 'start', + ]); + if (words.length > 1 && !knownCommands.has(commandBasename(words[0]))) { + const commandIndex = words.findIndex(word => knownCommands.has(commandBasename(word))); + if (commandIndex > 0) words = words.slice(commandIndex); + } + scanCmdWords(words, depth, findings, analysis, scanState, wrapperDepth + 1); + return; + } + + if (POWERSHELL_COMMANDS.has(firstCommand) || firstCommand === 'cmd') { + addNestedScan( + [firstCommand, ...words.slice(1)].join(' '), + depth, + findings, + analysis, + { executeBareScriptBlocks: true }, + scanState + ); + return; + } + if (CMD_DELETE_COMMANDS.has(firstCommand) && words.slice(1).some(word => /^[-/]s$/i.test(word))) { + findings.add(RULE_IDS.CMD_RECURSIVE_DELETE); + } +} + +function scanCmd(tokens, depth, findings, analysis, scanState) { + const flagIndex = tokens.findIndex((token, index) => index > 0 && /^\/[ck]$/i.test(token)); + if (flagIndex === -1) return; + + const payload = tokens + .slice(flagIndex + 1) + .filter(token => token !== '--%') + .join(' '); + for (const segment of splitCmdSegments(payload)) { + scanCmdWords( + segment.trim().split(/\s+/), + depth, + findings, + analysis, + scanState + ); + } +} + +function scanDeleteSegment(tokens, findings, quotedTokens = []) { + if (tokens.length === 0) return false; + + const command = commandBasename(tokens[0]); + if (!DELETE_COMMANDS.has(command)) return false; + + const usesLiteralPath = tokens.slice(1).some( + (token, index) => !quotedTokens[index + 1] && isParameterPrefix(token, 'literalpath') + ); + for (let index = 1; index < tokens.length; index += 1) { + const token = tokens[index]; + if (!quotedTokens[index] && token.startsWith('@')) { + findings.add(RULE_IDS.REMOVE_SPLAT); + continue; + } + if (!quotedTokens[index] && isEnabledSwitch(token, 'recurse')) { + findings.add(RULE_IDS.REMOVE_RECURSE); + continue; + } + if (!quotedTokens[index] && isEnabledSwitch(token, 'force')) { + findings.add(RULE_IDS.REMOVE_FORCE); + continue; + } + if (!usesLiteralPath && !token.startsWith('-') && /[*?]/.test(token)) { + findings.add(RULE_IDS.REMOVE_WILDCARD); + } + } + + return true; +} + +function parameterValue(token) { + const separator = String(token || '').indexOf(':'); + return separator === -1 ? '' : String(token).slice(separator + 1); +} + +function startProcessParameterName(token) { + const raw = String(token || ''); + if (!raw.startsWith('-')) return null; + const name = raw.replace(/^-+/, '').split(':')[0].toLowerCase(); + if (name === 'args') return 'argumentlist'; + const candidates = [...START_PROCESS_VALUE_PARAMETERS, ...START_PROCESS_SWITCH_PARAMETERS] + .filter(parameter => parameter.startsWith(name)); + return candidates.length === 1 ? candidates[0] : null; +} + +function normalizeArgumentList(parts) { + let payload = parts.join(' ').trim(); + if (/^@?\(/.test(payload) && /\)$/.test(payload)) { + payload = payload.replace(/^@?\(\s*/, '').replace(/\s*\)$/, ''); + } + return payload.replace(/\s*,\s*/g, ' ').trim(); +} + +function scanStartProcess(tokens, depth, findings, analysis, scanState) { + const command = commandBasename(tokens[0]); + if (!['start-process', 'saps', 'start'].includes(command)) return; + if (tokens.slice(1).some((token, index) => + !(tokens.quotedTokens || [])[index + 1] && + /^@(?:(?:global|script|local|private):)?[A-Za-z_][\w-]*$/i.test(token) + )) { + findings.add(RULE_IDS.DYNAMIC_EXECUTION); + return; + } + + let executable = null; + let argumentParts = null; + const quotedTokens = tokens.quotedTokens || []; + + for (let index = 1; index < tokens.length; index += 1) { + if (quotedTokens[index]) continue; + const parameter = startProcessParameterName(tokens[index]); + if (parameter !== 'filepath') continue; + executable = parameterValue(tokens[index]) || tokens[index + 1] || null; + break; + } + + for (let index = 1; index < tokens.length; index += 1) { + const token = tokens[index]; + const quoted = quotedTokens[index] === true; + const parameter = quoted ? null : startProcessParameterName(token); + if (parameter === 'argumentlist') { + const inlineValue = parameterValue(token); + const end = tokens.findIndex( + (candidate, candidateIndex) => candidateIndex > index && + !quotedTokens[candidateIndex] && startProcessParameterName(candidate) + ); + const remaining = tokens.slice(index + 1, end === -1 ? tokens.length : end); + argumentParts = inlineValue ? [inlineValue, ...remaining] : remaining; + break; + } + if (parameter) { + if (START_PROCESS_VALUE_PARAMETERS.has(parameter) && !parameterValue(token)) index += 1; + continue; + } + if (!quoted && token.startsWith('-')) continue; + if (executable !== null) continue; + if (executable === null) { + executable = token; + } + } + + if (argumentParts === null && executable !== null) { + let executableSeen = false; + for (let index = 1; index < tokens.length; index += 1) { + const token = tokens[index]; + const parameter = quotedTokens[index] ? null : startProcessParameterName(token); + if (parameter) { + if (parameter === 'filepath') executableSeen = true; + if (START_PROCESS_VALUE_PARAMETERS.has(parameter) && !parameterValue(token)) index += 1; + continue; + } + if (!executableSeen && token === executable) { + executableSeen = true; + continue; + } + if (executableSeen) { + argumentParts = tokens.slice(index); + break; + } + if (!quotedTokens[index] && token.startsWith('-')) continue; + } + } + + const nestedCommand = commandBasename(executable); + let argumentList = argumentParts ? normalizeArgumentList(argumentParts) : ''; + if (POWERSHELL_COMMANDS.has(nestedCommand) || nestedCommand === 'cmd') { + const argumentReference = variableReference(argumentList); + if (argumentReference) { + const staticValue = scanState.staticScalars.get(argumentReference); + if (staticValue === undefined) { + findings.add(RULE_IDS.DYNAMIC_EXECUTION); + return; + } + argumentList = staticValue; + } + } + if ((POWERSHELL_COMMANDS.has(nestedCommand) || nestedCommand === 'cmd') && argumentList) { + addNestedScan( + `${executable} ${argumentList}`, + depth, + findings, + analysis, + { executeBareScriptBlocks: true }, + scanState + ); + } +} + +function isAssignmentTarget(value) { + const variable = String(value || ''); + const oneTarget = String.raw`(?:\$\{[^}]+\}|\$(?:[A-Za-z_][\w-]*:)?[A-Za-z_][\w-]*(?:\[[^\]]+\]|\.[A-Za-z_][\w-]*)*)`; + return new RegExp(`^(?:\\[[^\\]]+\\])?${oneTarget}(?:,${oneTarget})*$`).test(variable); +} + +function executableSegment(tokens) { + if (!tokens || tokens.length === 0) { + return { firstTokenQuoted: false, quotedTokens: [], tokens: [] }; + } + const first = String(tokens[0] || ''); + const inlineAssignment = first.match(/^(.+?)(\+=|-=|\*=|\/=|%=|=)(.+)$/); + if (inlineAssignment && isAssignmentTarget(inlineAssignment[1])) { + return { + firstTokenQuoted: false, + quotedTokens: [false, ...(tokens.quotedTokens || []).slice(1)], + tokens: [inlineAssignment[3], ...tokens.slice(1)], + }; + } + if (tokens.length >= 2 && isAssignmentTarget(first) && /^(?:=|\+=|-=|\*=|\/=|%=)$/.test(tokens[1])) { + return { + firstTokenQuoted: tokens.quotedTokens?.[2] === true, + quotedTokens: (tokens.quotedTokens || []).slice(2), + tokens: tokens.slice(2), + }; + } + if (/^(?:return)$/i.test(first) && tokens.length > 1) { + return { + firstTokenQuoted: tokens.quotedTokens?.[1] === true, + quotedTokens: (tokens.quotedTokens || []).slice(1), + tokens: tokens.slice(1), + }; + } + return { + firstTokenQuoted: tokens.quotedTokens?.[0] === true, + quotedTokens: tokens.quotedTokens || [], + tokens, + }; +} + +function newObjectClassName(tokens, quotedTokens = []) { + for (let index = 1; index < tokens.length; index += 1) { + const token = tokens[index]; + if (!quotedTokens[index] && isParameterPrefix(token, 'typename')) { + return parameterValue(token) || tokens[index + 1] || null; + } + if (!String(token).startsWith('-')) return token; + } + return null; +} + +function markPowerShellElevation(tokens, analysis) { + if (!analysis || analysis.elevated || tokens.length === 0) return; + const commandName = commandBasename(tokens[0]); + if (['set-acl', 'icacls', 'takeown', 'runas', 'sudo', 'chmod', 'chown'].includes(commandName)) { + analysis.elevated = true; + return; + } + if (!['start-process', 'saps', 'start'].includes(commandName)) return; + + for (let index = 1; index < tokens.length; index += 1) { + const token = tokens[index]; + if (!isParameterPrefix(token, 'verb')) continue; + const inlineValue = String(token).split(':').slice(1).join(':'); + const value = inlineValue || tokens[index + 1] || ''; + if (/^runas$/i.test(value)) analysis.elevated = true; + return; + } +} + +function scanScriptBlockConsumer(tokens, quotedTokens, findings, state) { + const command = commandBasename(tokens[0]); + const consumers = new Set([ + 'foreach', + 'foreach-object', + 'icm', + 'invoke-command', + 'measure-command', + 'register-engineevent', + 'register-objectevent', + 'register-wmievent', + 'start-job', + 'sajb', + 'trace-command', + 'where', + 'where-object', + '%', + '?', + ]); + if (!consumers.has(command)) return; + + for (const token of tokens.slice(1)) { + const reference = variableReference(token); + if (reference && state.deferredFunctions.has(reference)) recordInvocation(state, reference); + } + + if (tokens.length === 2) { + const positionalReference = variableReference(tokens[1]); + if (positionalReference) { + recordInvocation(state, positionalReference); + if (!state.deferredFunctions.has(positionalReference)) { + findings.add(RULE_IDS.DYNAMIC_EXECUTION); + } + return; + } + } + + const parameters = [ + 'action', + 'begin', + 'end', + 'expression', + 'filter', + 'initializationscript', + 'parallel', + 'process', + 'scriptblock', + ]; + for (let index = 1; index < tokens.length; index += 1) { + if (quotedTokens[index]) continue; + const parameter = parameters.find(name => isParameterPrefix(tokens[index], name)); + if (!parameter) continue; + const reference = variableReference(parameterValue(tokens[index]) || tokens[index + 1]); + if (!reference) continue; + recordInvocation(state, reference); + if (!state.deferredFunctions.has(reference)) findings.add(RULE_IDS.DYNAMIC_EXECUTION); + } +} + +function aliasParameterName(token) { + const name = String(token).replace(/^-+/, '').split(':')[0].toLowerCase(); + if (Object.hasOwn(ALIAS_PARAMETER_ABBREVIATIONS, name)) return ALIAS_PARAMETER_ABBREVIATIONS[name]; + const parameters = [...ALIAS_VALUE_PARAMETERS, ...ALIAS_SWITCH_PARAMETERS]; + if (parameters.includes(name)) return name; + const matches = parameters.filter(parameter => name && parameter.startsWith(name)); + return matches.length === 1 ? matches[0] : null; +} + +function aliasArguments(tokens, quotedTokens) { + const named = new Map(); + const positional = []; + let ambiguous = false; + for (let index = 1; index < tokens.length; index += 1) { + const token = String(tokens[index]); + if (quotedTokens[index] || !token.startsWith('-')) { + positional.push({ index, inline: false }); + if (!quotedTokens[index] && token.startsWith('@')) ambiguous = true; + continue; + } + const parameter = aliasParameterName(token); + if (!parameter) { + ambiguous = true; + continue; + } + if (named.has(parameter)) ambiguous = true; + const inline = token.includes(':'); + const argument = { index: ALIAS_VALUE_PARAMETERS.has(parameter) && !inline ? ++index : index, inline }; + if (ALIAS_VALUE_PARAMETERS.has(parameter) && tokens[argument.index] === undefined) ambiguous = true; + named.set(parameter, argument); + // Option accepts a comma-separated array; its continuation belongs to the + // named parameter rather than the remaining positional name/value slots. + if (parameter === 'option') { + while (index + 1 < tokens.length && !quotedTokens[index] && + (String(tokens[index]).endsWith(',') || String(tokens[index + 1]).startsWith(','))) index += 1; + } + } + return { named, positional, ambiguous }; +} + +function staticAliasDefinitions(tokens, quotedTokens, state) { + const args = aliasArguments(tokens, quotedTokens); + // Definitions stay inert. Uncertain binding is gated only when a candidate + // alias is invoked, without allowing auxiliary values to hide its target. + const unresolved = new Set(); + const resolve = argument => argument + ? staticTokenValue(tokens, argument.index, state, unresolved, argument.inline) + : null; + let positionalIndex = 0; + const nameArgument = args.named.get('name') || args.positional[positionalIndex++]; + const valueArgument = args.named.get('value') || args.positional[positionalIndex++]; + const name = resolve(nameArgument); + const value = resolve(valueArgument); + const ambiguous = args.ambiguous || positionalIndex < args.positional.length; + const possibleNames = args.named.has('value') ? args.positional : args.positional.slice(0, -1); + const names = ambiguous && !args.named.has('name') + ? [name, ...possibleNames.map(resolve)] + : [name]; + const target = ambiguous || value === null || /^@/.test(value) + ? DYNAMIC_EXECUTION_MARKER + : value; + if (!/^[A-Za-z_][\w./\\-]*$/.test(target || '')) return []; + return [...new Set(names.filter(candidate => /^[A-Za-z_][\w-]*$/.test(candidate || '')))] + .map(candidate => ({ name: candidate.toLowerCase(), value: target })); +} + +function scanInvokeScriptCalls(source, unquoted, depth, findings, analysis, state) { + const pattern = /(?:\$\{executioncontext\}|\$executioncontext)\.invokecommand\.invokescript\s*\(/gi; + while (pattern.exec(unquoted) !== null) { + const argumentSource = source.slice(pattern.lastIndex); + const payload = leadingStaticStringResult(argumentSource); + if (payload === null) { + findings.add(RULE_IDS.DYNAMIC_EXECUTION); + } else { + addNestedScan( + payload, + depth, + findings, + analysis, + { executeBareScriptBlocks: true }, + state + ); + } + } +} + +function scanPowerShell(command, depth, findings, analysis = null, options = {}, scanState = null) { + const raw = normalizeSmartQuotes(command); + if (!raw.trim()) return; + + const state = scanState || createScanState(); + + const hereStringExpressions = []; + const normalizedHereStrings = normalizeHereStrings(raw, hereStringExpressions); + const withoutComments = stripPowerShellComments(normalizedHereStrings); + collectStaticScalarAssignments(withoutComments, state); + const unquoted = maskQuotedStrings(withoutComments); + scanInvokeScriptCalls(withoutComments, unquoted, depth, findings, analysis, state); + if (/\[\s*(?:system\.)?io\.directory\s*\]\s*::\s*delete\s*\(/i.test(unquoted)) { + findings.add(RULE_IDS.DOTNET_DIRECTORY_DELETE); + } + if (/\[\s*(?:system\.)?io\.file\s*\]\s*::\s*delete\s*\(/i.test(unquoted)) { + findings.add(RULE_IDS.DOTNET_FILE_DELETE); + } + const activatorPattern = /\[\s*(?:system\.)?activator\s*\]\s*::\s*createinstance\s*\(\s*\[([A-Za-z_][\w-]*)\]/gi; + let activatorMatch; + while ((activatorMatch = activatorPattern.exec(unquoted)) !== null) { + recordInvocation(state, `__class__:${activatorMatch[1].toLowerCase()}`); + } + for (const payload of hereStringExpressions) { + addNestedScan(payload, depth, findings, analysis, { executeBareScriptBlocks: true }, state); + } + + const { bodies, deferredFunctions, outer } = extractExecutableContainers(withoutComments, { + ...options, + staticScalars: state.staticScalars, + }); + for (const definition of deferredFunctions) { + registerDeferredFunction(state, { ...definition, depth }); + } + const invokedBlockVariable = /(\$\{[^}]+\}|\$(?:[A-Za-z_][\w-]*:)?[A-Za-z_][\w-]*(?:\[[^\]]+\]|\.(?!getnewclosure\b)[A-Za-z_][\w-]*)*)(?:\.getnewclosure\s*\(\s*\))+\.\s*(?:invoke|invokereturnasis|invokewithcontext)\s*\(/gi; + let invokedBlockMatch; + while ((invokedBlockMatch = invokedBlockVariable.exec(unquoted)) !== null) { + recordInvocation(state, invokedBlockMatch[1].toLowerCase()); + } + for (const entry of bodies) { + addNestedScan(entry.body, depth, findings, analysis, entry.options, state); + } + + for (const statement of parseStatements(outer)) { + const deleteSegments = new Set(); + const recurseSegments = new Set(); + + for (let index = 0; index < statement.length; index += 1) { + const segmentTokens = statement[index]; + const executable = executableSegment(segmentTokens); + const tokens = executable.tokens; + if (tokens.length === 0) continue; + if (executable.firstTokenQuoted && !segmentTokens.invokedByCallOperator) continue; + const commandName = commandBasename(tokens[0]); + recordInvocation(state, commandName); + const aliasTarget = state.aliases.get(commandName); + if (aliasTarget) { + addNestedScan( + [aliasTarget, ...tokens.slice(1)].join(' '), + depth, + findings, + analysis, + { executeBareScriptBlocks: true }, + state + ); + } + if (['set-alias', 'new-alias', 'sal', 'nal'].includes(commandName)) { + for (const definition of staticAliasDefinitions(tokens, executable.quotedTokens, state)) { + state.aliases.set(definition.name, definition.value); + } + } + const classInvocation = commandName.match(/^\[([a-z_][\w-]*)\]::/i); + if (classInvocation) recordInvocation(state, `__class__:${classInvocation[1].toLowerCase()}`); + if (commandName === 'new-object') { + let className = newObjectClassName(tokens, executable.quotedTokens); + const classReference = variableReference(className); + if (classReference) { + const staticClassName = state.staticScalars.get(classReference); + if (staticClassName === undefined) { + findings.add(RULE_IDS.DYNAMIC_EXECUTION); + className = null; + } else { + className = staticClassName; + } + } + if (className && /^[A-Za-z_][\w-]*$/.test(className)) { + recordInvocation(state, `__class__:${className.toLowerCase()}`); + } + } + const invokedVariable = commandName.match( + /^((?:\$\{[^}]+\}|\$(?:[a-z_][\w-]*:)?[a-z_][\w-]*(?:\[[^\]]+\]|\.[a-z_][\w-]*)*))(?:\.getnewclosure\(\))*\.(?:invoke|invokereturnasis|invokewithcontext)(?:\(|$)/i + ); + if (invokedVariable) recordInvocation(state, invokedVariable[1].toLowerCase()); + if (commandName === '.' && tokens[1]) { + recordInvocation(state, commandBasename(tokens[1])); + } + markPowerShellElevation(tokens, analysis); + scanStartProcess(tokens, depth, findings, analysis, state); + scanScriptBlockConsumer(tokens, executable.quotedTokens, findings, state); + if (tokens.some(token => commandBasename(token) === DYNAMIC_EXECUTION_MARKER)) { + findings.add(RULE_IDS.DYNAMIC_EXECUTION); + } + + const invokedReference = segmentTokens.invokedByCallOperator + ? variableReference(tokens[0]) + : null; + if (invokedReference && !state.deferredFunctions.has(invokedReference)) { + const commandValue = state.staticScalars.get(invokedReference); + if (commandValue === undefined) { + findings.add(RULE_IDS.DYNAMIC_EXECUTION); + } else if (POWERSHELL_COMMANDS.has(commandBasename(commandValue))) { + scanNestedPowerShell( + [commandValue, ...tokens.slice(1)], + depth, + findings, + analysis, + state, + statement[index - 1] + ); + } else { + addNestedScan( + [commandValue, ...tokens.slice(1)].join(' '), + depth, + findings, + analysis, + { executeBareScriptBlocks: true }, + state + ); + } + } + + if (POWERSHELL_COMMANDS.has(commandName)) { + scanNestedPowerShell(tokens, depth, findings, analysis, state, statement[index - 1]); + } else if (commandName === 'cmd') { + scanCmd(tokens, depth, findings, analysis, state); + } else if (commandName === 'invoke-expression' || commandName === 'iex') { + let payload = tokens.slice(1).join(' '); + const payloadReference = variableReference(payload); + if (payloadReference) { + const staticValue = state.staticScalars.get(payloadReference); + if (staticValue === undefined) { + findings.add(RULE_IDS.DYNAMIC_EXECUTION); + payload = ''; + } else { + payload = staticValue; + } + } + if (payload) { + addNestedScan( + payload, + depth, + findings, + analysis, + { executeBareScriptBlocks: true }, + state + ); + } + } else if (commandName === 'clear-content' || commandName === 'clc') { + findings.add(RULE_IDS.CLEAR_CONTENT); + } else if (commandName === 'clear-disk') { + findings.add(RULE_IDS.CLEAR_DISK); + } else if (commandName === 'format-volume') { + findings.add(RULE_IDS.FORMAT_VOLUME); + } + + if (scanDeleteSegment(tokens, findings, executable.quotedTokens)) deleteSegments.add(index); + if (tokens.some( + (token, tokenIndex) => !executable.quotedTokens[tokenIndex] && + isEnabledSwitch(token, 'recurse') + )) { + recurseSegments.add(index); + } + } + + const hasUpstreamRecurse = [...recurseSegments].some(index => !deleteSegments.has(index)); + if (statement.length > 1 && deleteSegments.size > 0 && hasUpstreamRecurse) { + findings.add(RULE_IDS.PIPELINE_RECURSE); + } + } + +} + +function resolveDeferredFunctions(findings, analysis, state) { + state.pendingInvocations.push(...state.invokedCommands); + state.resolvingFunctions = true; + for (let cursor = 0; cursor < state.pendingInvocations.length; cursor += 1) { + const commandName = state.pendingInvocations[cursor]; + const definitions = state.deferredFunctions.get(commandName) || []; + for (const definition of definitions) { + if (state.scannedFunctions.has(definition)) continue; + state.scannedFunctions.add(definition); + const options = definition.functionName.startsWith('__class__:') + ? { executeBareScriptBlocks: true } + : {}; + addNestedScan(definition.body, definition.depth, findings, analysis, options, state); + } + } + state.resolvingFunctions = false; +} + +function classifyPowerShellDestructiveCommand(command) { + if (typeof command !== 'string' || !command.trim()) return []; + + const findings = new Set(); + const state = createScanState(); + scanPowerShell(command, 0, findings, null, {}, state); + resolveDeferredFunctions(findings, null, state); + return [...findings]; +} + +function isElevatedPowerShellCommand(command) { + if (typeof command !== 'string' || !command.trim()) return false; + + const analysis = { elevated: false }; + const state = createScanState(); + const findings = new Set(); + scanPowerShell(command, 0, findings, analysis, {}, state); + resolveDeferredFunctions(findings, analysis, state); + return analysis.elevated; +} + +module.exports = { + RULE_IDS, + classifyPowerShellDestructiveCommand, + isElevatedPowerShellCommand, +}; diff --git a/github_code/affaan-m__ECC/scripts/lib/project-detect.js b/github_code/affaan-m__ECC/scripts/lib/project-detect.js new file mode 100644 index 0000000000000000000000000000000000000000..8535946f287f68d44dfc4e266389588aa491e433 --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/project-detect.js @@ -0,0 +1,454 @@ +/** + * Project type and framework detection + * + * Cross-platform (Windows, macOS, Linux) project type detection + * by inspecting files in the working directory. + * + * Resolves: https://github.com/affaan-m/everything-claude-code/issues/293 + */ + +const fs = require('fs'); +const path = require('path'); + +/** + * Language detection rules. + * Each rule checks for marker files or glob patterns in the project root. + */ +const LANGUAGE_RULES = [ + { + type: 'python', + markers: ['requirements.txt', 'pyproject.toml', 'setup.py', 'setup.cfg', 'Pipfile', 'poetry.lock'], + extensions: ['.py'] + }, + { + type: 'typescript', + markers: ['tsconfig.json', 'tsconfig.build.json'], + extensions: ['.ts', '.tsx'] + }, + { + type: 'javascript', + markers: ['package.json', 'jsconfig.json'], + extensions: ['.js', '.jsx', '.mjs'] + }, + { + type: 'golang', + markers: ['go.mod', 'go.sum'], + extensions: ['.go'] + }, + { + type: 'rust', + markers: ['Cargo.toml', 'Cargo.lock'], + extensions: ['.rs'] + }, + { + type: 'ruby', + markers: ['Gemfile', 'Gemfile.lock', 'Rakefile'], + extensions: ['.rb'] + }, + { + type: 'java', + markers: ['pom.xml', 'build.gradle', 'build.gradle.kts'], + extensions: ['.java'] + }, + { + type: 'c', + markers: [], + extensions: ['.c'] + }, + { + type: 'csharp', + markers: [], + extensions: ['.cs', '.csproj', '.sln'] + }, + { + type: 'fsharp', + markers: [], + extensions: ['.fs', '.fsx', '.fsproj'] + }, + { + type: 'swift', + markers: ['Package.swift'], + extensions: ['.swift'] + }, + { + type: 'kotlin', + markers: [], + extensions: ['.kt', '.kts'] + }, + { + type: 'elixir', + markers: ['mix.exs'], + extensions: ['.ex', '.exs'] + }, + { + type: 'php', + markers: ['composer.json', 'composer.lock'], + extensions: ['.php'] + } +]; + +/** + * Framework detection rules. + * Checked after language detection for more specific identification. + */ +const FRAMEWORK_RULES = [ + // Python frameworks + { framework: 'django', language: 'python', markers: ['manage.py'], packageKeys: ['django'] }, + { framework: 'fastapi', language: 'python', markers: [], packageKeys: ['fastapi'] }, + { framework: 'flask', language: 'python', markers: [], packageKeys: ['flask'] }, + + // JavaScript/TypeScript frameworks + { framework: 'nextjs', language: 'typescript', markers: ['next.config.js', 'next.config.mjs', 'next.config.ts'], packageKeys: ['next'] }, + { framework: 'react', language: 'typescript', markers: [], packageKeys: ['react'] }, + { framework: 'vue', language: 'typescript', markers: ['vue.config.js'], packageKeys: ['vue'] }, + { framework: 'angular', language: 'typescript', markers: ['angular.json'], packageKeys: ['@angular/core'] }, + { framework: 'svelte', language: 'typescript', markers: ['svelte.config.js'], packageKeys: ['svelte'] }, + { framework: 'express', language: 'javascript', markers: [], packageKeys: ['express'] }, + { framework: 'nestjs', language: 'typescript', markers: ['nest-cli.json'], packageKeys: ['@nestjs/core'] }, + { framework: 'remix', language: 'typescript', markers: [], packageKeys: ['@remix-run/node', '@remix-run/react'] }, + { framework: 'astro', language: 'typescript', markers: ['astro.config.mjs', 'astro.config.ts'], packageKeys: ['astro'] }, + { framework: 'nuxt', language: 'typescript', markers: ['nuxt.config.js', 'nuxt.config.ts'], packageKeys: ['nuxt'] }, + { framework: 'electron', language: 'typescript', markers: [], packageKeys: ['electron'] }, + + // Ruby frameworks + { framework: 'rails', language: 'ruby', markers: ['config/routes.rb', 'bin/rails'], packageKeys: [] }, + + // Go frameworks + { framework: 'gin', language: 'golang', markers: [], packageKeys: ['github.com/gin-gonic/gin'] }, + { framework: 'echo', language: 'golang', markers: [], packageKeys: ['github.com/labstack/echo'] }, + + // Rust frameworks + { framework: 'actix', language: 'rust', markers: [], packageKeys: ['actix-web'] }, + { framework: 'axum', language: 'rust', markers: [], packageKeys: ['axum'] }, + + // Java frameworks + { framework: 'spring', language: 'java', markers: [], packageKeys: ['spring-boot', 'org.springframework'] }, + + // PHP frameworks + { framework: 'laravel', language: 'php', markers: ['artisan'], packageKeys: ['laravel/framework'] }, + { framework: 'symfony', language: 'php', markers: ['symfony.lock'], packageKeys: ['symfony/framework-bundle'] }, + + // Elixir frameworks + { framework: 'phoenix', language: 'elixir', markers: [], packageKeys: ['phoenix'] } +]; + +/** + * Check if a file exists relative to the project directory + * @param {string} projectDir - Project root directory + * @param {string} filePath - Relative file path + * @returns {boolean} + */ +function fileExists(projectDir, filePath) { + try { + return fs.existsSync(path.join(projectDir, filePath)); + } catch { + return false; + } +} + +/** + * Check if any file with given extension exists in the project root (non-recursive, top-level only) + * @param {string} projectDir - Project root directory + * @param {string[]} extensions - File extensions to check + * @returns {boolean} + */ +function hasFileWithExtension(projectDir, extensions) { + try { + const entries = fs.readdirSync(projectDir, { withFileTypes: true }); + return entries.some(entry => { + if (!entry.isFile()) return false; + const ext = path.extname(entry.name); + return extensions.includes(ext); + }); + } catch { + return false; + } +} + +/** + * Read and parse package.json dependencies + * @param {string} projectDir - Project root directory + * @returns {string[]} Array of dependency names + */ +function getPackageJsonDeps(projectDir) { + try { + const pkgPath = path.join(projectDir, 'package.json'); + if (!fs.existsSync(pkgPath)) return []; + const pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8')); + return [...Object.keys(pkg.dependencies || {}), ...Object.keys(pkg.devDependencies || {})]; + } catch { + return []; + } +} + +/** + * Read requirements.txt or pyproject.toml for Python package names + * @param {string} projectDir - Project root directory + * @returns {string[]} Array of dependency names (lowercase) + */ +function getPythonDeps(projectDir) { + const deps = []; + + // requirements.txt + try { + const reqPath = path.join(projectDir, 'requirements.txt'); + if (fs.existsSync(reqPath)) { + const content = fs.readFileSync(reqPath, 'utf8'); + content.split('\n').forEach(line => { + const trimmed = line.trim(); + if (trimmed && !trimmed.startsWith('#') && !trimmed.startsWith('-')) { + const name = trimmed + .split(/[\s>= { + const name = m + .replace(/"/g, '') + .split(/[\s>= { + const trimmed = line.trim(); + if (trimmed && !trimmed.startsWith('//')) { + const parts = trimmed.split(/\s+/); + if (parts[0]) deps.push(parts[0]); + } + }); + } + return deps; + } catch { + return []; + } +} + +/** + * Read Cargo.toml for Rust crate dependencies + * @param {string} projectDir - Project root directory + * @returns {string[]} Array of crate names + */ +function getRustDeps(projectDir) { + try { + const cargoPath = path.join(projectDir, 'Cargo.toml'); + if (!fs.existsSync(cargoPath)) return []; + const content = fs.readFileSync(cargoPath, 'utf8'); + const deps = []; + // Match [dependencies] and [dev-dependencies] sections + const sections = content.match(/\[(dev-)?dependencies\]([\s\S]*?)(?=\n\[|$)/g); + if (sections) { + sections.forEach(section => { + section.split('\n').forEach(line => { + const match = line.match(/^([a-zA-Z0-9_-]+)\s*=/); + if (match && !line.startsWith('[')) { + deps.push(match[1]); + } + }); + }); + } + return deps; + } catch { + return []; + } +} + +/** + * Read composer.json for PHP package dependencies + * @param {string} projectDir - Project root directory + * @returns {string[]} Array of package names + */ +function getComposerDeps(projectDir) { + try { + const composerPath = path.join(projectDir, 'composer.json'); + if (!fs.existsSync(composerPath)) return []; + const composer = JSON.parse(fs.readFileSync(composerPath, 'utf8')); + return [...Object.keys(composer.require || {}), ...Object.keys(composer['require-dev'] || {})]; + } catch { + return []; + } +} + +/** + * Read mix.exs for Elixir dependencies (simple pattern match) + * @param {string} projectDir - Project root directory + * @returns {string[]} Array of dependency atom names + */ +function getElixirDeps(projectDir) { + try { + const mixPath = path.join(projectDir, 'mix.exs'); + if (!fs.existsSync(mixPath)) return []; + const content = fs.readFileSync(mixPath, 'utf8'); + const deps = []; + const matches = content.match(/\{:(\w+)/g); + if (matches) { + matches.forEach(m => deps.push(m.replace('{:', ''))); + } + return deps; + } catch { + return []; + } +} + +/** + * Detect project languages and frameworks + * @param {string} [projectDir] - Project directory (defaults to cwd) + * @returns {{ languages: string[], frameworks: string[], primary: string, projectDir: string }} + */ +function detectProjectType(projectDir) { + projectDir = projectDir || process.cwd(); + const languages = []; + const frameworks = []; + + // Step 1: Detect languages + for (const rule of LANGUAGE_RULES) { + const hasMarker = rule.markers.some(m => fileExists(projectDir, m)); + const hasExt = rule.extensions.length > 0 && hasFileWithExtension(projectDir, rule.extensions); + + if (hasMarker || hasExt) { + languages.push(rule.type); + } + } + + // Deduplicate: if both typescript and javascript detected, keep typescript + if (languages.includes('typescript') && languages.includes('javascript')) { + const idx = languages.indexOf('javascript'); + if (idx !== -1) languages.splice(idx, 1); + } + + // Step 2: Detect frameworks based on markers and dependencies + const npmDeps = getPackageJsonDeps(projectDir); + const pyDeps = getPythonDeps(projectDir); + const goDeps = getGoDeps(projectDir); + const rustDeps = getRustDeps(projectDir); + const composerDeps = getComposerDeps(projectDir); + const elixirDeps = getElixirDeps(projectDir); + + for (const rule of FRAMEWORK_RULES) { + // Check marker files + const hasMarker = rule.markers.some(m => fileExists(projectDir, m)); + + // Check package dependencies + let hasDep = false; + if (rule.packageKeys.length > 0) { + let depList = []; + switch (rule.language) { + case 'python': + depList = pyDeps; + break; + case 'typescript': + case 'javascript': + depList = npmDeps; + break; + case 'golang': + depList = goDeps; + break; + case 'rust': + depList = rustDeps; + break; + case 'php': + depList = composerDeps; + break; + case 'elixir': + depList = elixirDeps; + break; + } + // Boundary-aware match: a dependency matches a packageKey only when it + // equals the key, or the key is a prefix immediately followed by a + // delimiter (/ . _ -). Plain substring matching wrongly classified + // `preact` / `reactive` as `react`. This still matches the real cases: + // react-dom, @remix-run/node, spring-boot-starter, org.springframework.boot, + // github.com/labstack/echo/v4, phoenix_live_view. + hasDep = rule.packageKeys.some(key => { + const k = key.toLowerCase(); + return depList.some(dep => { + const d = dep.toLowerCase(); + if (!d.startsWith(k)) return false; + return d.length === k.length || /[/._-]/.test(d[k.length]); + }); + }); + } + + if (hasMarker || hasDep) { + frameworks.push(rule.framework); + } + } + + // Step 3: Determine primary type + let primary = 'unknown'; + if (frameworks.length > 0) { + primary = frameworks[0]; + } else if (languages.length > 0) { + primary = languages[0]; + } + + // Determine if fullstack (both frontend and backend languages) + const frontendSignals = ['react', 'vue', 'angular', 'svelte', 'nextjs', 'nuxt', 'astro', 'remix']; + const backendSignals = ['django', 'fastapi', 'flask', 'express', 'nestjs', 'rails', 'spring', 'laravel', 'phoenix', 'gin', 'echo', 'actix', 'axum']; + const hasFrontend = frameworks.some(f => frontendSignals.includes(f)); + const hasBackend = frameworks.some(f => backendSignals.includes(f)); + + if (hasFrontend && hasBackend) { + primary = 'fullstack'; + } + + return { + languages, + frameworks, + primary, + projectDir + }; +} + +module.exports = { + detectProjectType, + LANGUAGE_RULES, + FRAMEWORK_RULES, + // Exported for testing + getPackageJsonDeps, + getPythonDeps, + getGoDeps, + getRustDeps, + getComposerDeps, + getElixirDeps +}; diff --git a/github_code/affaan-m__ECC/scripts/lib/resolve-ecc-root.js b/github_code/affaan-m__ECC/scripts/lib/resolve-ecc-root.js new file mode 100644 index 0000000000000000000000000000000000000000..396aac377b14525d9e77aa29cf114f13544933a6 --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/resolve-ecc-root.js @@ -0,0 +1,155 @@ +'use strict'; + +const fs = require('fs'); +const path = require('path'); +const os = require('os'); + +const CURRENT_PLUGIN_SLUG = 'ecc'; +const LEGACY_PLUGIN_SLUG = 'everything-claude-code'; +const CURRENT_PLUGIN_HANDLE = `${CURRENT_PLUGIN_SLUG}@${CURRENT_PLUGIN_SLUG}`; +const LEGACY_PLUGIN_HANDLE = `${LEGACY_PLUGIN_SLUG}@${LEGACY_PLUGIN_SLUG}`; +const PLUGIN_CACHE_SLUGS = [CURRENT_PLUGIN_SLUG, LEGACY_PLUGIN_SLUG]; +const PLUGIN_ROOT_SEGMENTS = [ + [CURRENT_PLUGIN_SLUG], + [CURRENT_PLUGIN_HANDLE], + ['marketplaces', CURRENT_PLUGIN_SLUG], + [LEGACY_PLUGIN_SLUG], + [LEGACY_PLUGIN_HANDLE], + ['marketplaces', LEGACY_PLUGIN_SLUG], +]; + +// Artifacts that identify a COMPLETE ECC root when the caller gives no explicit +// probe. A real ECC root ships both the script tree AND ECC's skills; a partial +// install (scripts copied, skills not) must not qualify for skill-resolving +// callers, which build `skills/...` paths against the resolved root (#2544). +// Checking "skills/ exists" is not enough — a user's own ~/.claude/skills/ can +// be present with none of ECC's skills — so we probe for a sentinel skill that +// ships in every ECC root and is exactly what the failing skill commands need. +// If that skill is ever renamed, move this sentinel with it. +const DEFAULT_SCRIPT_PROBE = path.join('scripts', 'lib', 'utils.js'); +const DEFAULT_SKILL_PROBE = path.join('skills', 'continuous-learning-v2'); + +/** + * Resolve the ECC source root directory. + * + * Tries, in order: + * 1. CLAUDE_PLUGIN_ROOT env var (set by Claude Code for hooks, or by user) + * 2. Standard install location (~/.claude/) — when scripts exist there + * 3. Known plugin roots under ~/.claude/plugins/ (current + legacy slugs) + * 4. Plugin cache auto-detection — scans ~/.claude/plugins/cache/{ecc,everything-claude-code}/ + * 5. Fallback to ~/.claude/ (original behaviour) + * + * @param {object} [options] + * @param {string} [options.homeDir] Override home directory (for testing) + * @param {string} [options.envRoot] Override CLAUDE_PLUGIN_ROOT (for testing) + * @param {string} [options.probe] Relative path used to verify a candidate + * root contains what the caller needs. When + * given, it is honored exactly (script + * consumers pass their own script path). When + * omitted, a candidate must contain BOTH the + * ECC script tree and a sentinel ECC skill, + * so a partial install (scripts without + * skills) is rejected for skill consumers. + * @returns {string} Resolved ECC root path + */ +function resolveEccRoot(options = {}) { + const envRoot = options.envRoot !== undefined + ? options.envRoot + : (process.env.CLAUDE_PLUGIN_ROOT || ''); + + if (envRoot && envRoot.trim()) { + return envRoot.trim(); + } + + const homeDir = options.homeDir || os.homedir(); + const claudeDir = path.join(homeDir, '.claude'); + + // Decide whether a candidate directory is a usable ECC root. An explicit + // caller probe is honored exactly (script consumers know the artifact they + // need). With the default probe the caller is a skill consumer, so a + // candidate must contain both ECC's scripts and a sentinel ECC skill — + // otherwise a scripts-only ~/.claude short-circuits and every skill path + // resolves to a location that does not exist (#2544). + const isRoot = options.probe + ? (dir) => fs.existsSync(path.join(dir, options.probe)) + : (dir) => fs.existsSync(path.join(dir, DEFAULT_SCRIPT_PROBE)) + && fs.existsSync(path.join(dir, DEFAULT_SKILL_PROBE)); + + // Standard install — files are copied directly into ~/.claude/ + if (isRoot(claudeDir)) { + return claudeDir; + } + + // Exact legacy plugin install locations. These preserve backwards + // compatibility without scanning arbitrary plugin trees. + const legacyPluginRoots = PLUGIN_ROOT_SEGMENTS.map((segments) => + path.join(claudeDir, 'plugins', ...segments) + ); + + for (const candidate of legacyPluginRoots) { + if (isRoot(candidate)) { + return candidate; + } + } + + // Plugin cache — Claude Code stores marketplace plugins under + // ~/.claude/plugins/cache//// + try { + for (const slug of PLUGIN_CACHE_SLUGS) { + const cacheBase = path.join(claudeDir, 'plugins', 'cache', slug); + const orgDirs = fs.readdirSync(cacheBase, { withFileTypes: true }); + + for (const orgEntry of orgDirs) { + if (!orgEntry.isDirectory()) continue; + const orgPath = path.join(cacheBase, orgEntry.name); + + let versionDirs; + try { + versionDirs = fs.readdirSync(orgPath, { withFileTypes: true }); + } catch { + continue; + } + + for (const verEntry of versionDirs) { + if (!verEntry.isDirectory()) continue; + const candidate = path.join(orgPath, verEntry.name); + if (isRoot(candidate)) { + return candidate; + } + } + } + } + } catch { + // Plugin cache doesn't exist or isn't readable — continue to fallback + } + + return claudeDir; +} + +/** + * Compact inline locator for embedding in hooks.json and command .md code blocks. + * + * Earlier revisions inlined the *entire* resolveEccRoot() search (~700 chars, + * duplicated ~80×). That blob used a spread (`...s`) over nested array literals, + * which broke Windows hook execution due to shell quoting (#2368). + * + * This minified form contains no spread, no nested array literals, and no + * escaped double quotes, so it survives `node -e "..."` quoting on every shell. + * When CLAUDE_PLUGIN_ROOT is set (as Claude Code does for plugin hooks and + * commands) it is used directly. Otherwise the inline probes the same set of + * locations resolveEccRoot() knows about — ~/.claude, the exact plugin roots + * under ~/.claude/plugins/, and the versioned plugin cache — only far enough to + * load the committed resolve-ecc-root module, then delegates the authoritative + * decision to resolveEccRoot(). This keeps discovery behaviour identical to the + * old inline while centralising the real logic in one tested module. + * + * Usage in commands: + * const _r = ; + * const sm = require(_r + '/scripts/lib/session-manager'); + */ +const INLINE_RESOLVE = `(function(){var p=require('path'),f=require('fs'),o=require('os');var e=process.env.CLAUDE_PLUGIN_ROOT;if(e&&e.trim())return e.trim();var d=p.join(o.homedir(),'.claude');function L(x){try{return require(p.join(x,'scripts','lib','resolve-ecc-root')).resolveEccRoot()}catch(_){return null}}var r=L(d);if(r)return r;var s=['ecc','ecc@ecc','marketplaces/ecc','everything-claude-code','everything-claude-code@everything-claude-code','marketplaces/everything-claude-code'];for(var i=0;i line.trim()) + .filter(Boolean); +} + +function ensureString(value, fieldPath) { + if (typeof value !== 'string' || value.length === 0) { + throw new Error(`Canonical session snapshot requires ${fieldPath} to be a non-empty string`); + } +} + +function ensureStringAllowEmpty(value, fieldPath) { + if (typeof value !== 'string') { + throw new Error(`Canonical session snapshot requires ${fieldPath} to be a string`); + } +} + +function ensureOptionalString(value, fieldPath) { + if (value !== null && value !== undefined && typeof value !== 'string') { + throw new Error(`Canonical session snapshot requires ${fieldPath} to be a string or null`); + } +} + +function ensureBoolean(value, fieldPath) { + if (typeof value !== 'boolean') { + throw new Error(`Canonical session snapshot requires ${fieldPath} to be a boolean`); + } +} + +function ensureArrayOfStrings(value, fieldPath) { + if (!Array.isArray(value) || value.some(item => typeof item !== 'string')) { + throw new Error(`Canonical session snapshot requires ${fieldPath} to be an array of strings`); + } +} + +function ensureInteger(value, fieldPath) { + if (!Number.isInteger(value) || value < 0) { + throw new Error(`Canonical session snapshot requires ${fieldPath} to be a non-negative integer`); + } +} + +const STALE_THRESHOLD_MS = 5 * 60 * 1000; + +function parseUpdatedMs(updated) { + if (typeof updated !== 'string' || updated.length === 0) return null; + const ms = Date.parse(updated); + return Number.isNaN(ms) ? null : ms; +} + +function deriveWorkerHealth(rawWorker) { + const state = (rawWorker.status && rawWorker.status.state) || 'unknown'; + const completedStates = ['completed', 'succeeded', 'success', 'done']; + const failedStates = ['failed', 'error']; + + if (failedStates.includes(state)) return 'degraded'; + if (completedStates.includes(state)) return 'healthy'; + + if (state === 'running' || state === 'active') { + const pane = rawWorker.pane; + if (pane && pane.dead) return 'degraded'; + + const updatedMs = parseUpdatedMs(rawWorker.status && rawWorker.status.updated); + if (updatedMs === null) return 'stale'; + if (Date.now() - updatedMs > STALE_THRESHOLD_MS) return 'stale'; + return 'healthy'; + } + + return 'unknown'; +} + +function buildAggregates(workers) { + const states = workers.reduce((accumulator, worker) => { + const state = worker.state || 'unknown'; + accumulator[state] = (accumulator[state] || 0) + 1; + return accumulator; + }, {}); + + const healths = workers.reduce((accumulator, worker) => { + const health = worker.health || 'unknown'; + accumulator[health] = (accumulator[health] || 0) + 1; + return accumulator; + }, {}); + + return { + workerCount: workers.length, + states, + healths + }; +} + +function summarizeRawWorkerStates(snapshot) { + if (isObject(snapshot.workerStates)) { + return snapshot.workerStates; + } + + return (snapshot.workers || []).reduce((counts, worker) => { + const state = worker && worker.status && worker.status.state + ? worker.status.state + : 'unknown'; + counts[state] = (counts[state] || 0) + 1; + return counts; + }, {}); +} + +function deriveDmuxSessionState(snapshot) { + const workerStates = summarizeRawWorkerStates(snapshot); + const totalWorkers = Number.isInteger(snapshot.workerCount) + ? snapshot.workerCount + : Object.values(workerStates).reduce((sum, count) => sum + count, 0); + + if (snapshot.sessionActive) { + return 'active'; + } + + if (totalWorkers === 0) { + return 'missing'; + } + + const failedCount = (workerStates.failed || 0) + (workerStates.error || 0); + if (failedCount > 0) { + return 'failed'; + } + + const completedCount = (workerStates.completed || 0) + + (workerStates.succeeded || 0) + + (workerStates.success || 0) + + (workerStates.done || 0); + if (completedCount === totalWorkers) { + return 'completed'; + } + + return 'idle'; +} + +function validateCanonicalSnapshot(snapshot) { + if (!isObject(snapshot)) { + throw new Error('Canonical session snapshot must be an object'); + } + + ensureString(snapshot.schemaVersion, 'schemaVersion'); + if (snapshot.schemaVersion !== SESSION_SCHEMA_VERSION) { + throw new Error(`Unsupported canonical session schema version: ${snapshot.schemaVersion}`); + } + + ensureString(snapshot.adapterId, 'adapterId'); + + if (!isObject(snapshot.session)) { + throw new Error('Canonical session snapshot requires session to be an object'); + } + + ensureString(snapshot.session.id, 'session.id'); + ensureString(snapshot.session.kind, 'session.kind'); + ensureString(snapshot.session.state, 'session.state'); + ensureOptionalString(snapshot.session.repoRoot, 'session.repoRoot'); + + if (!isObject(snapshot.session.sourceTarget)) { + throw new Error('Canonical session snapshot requires session.sourceTarget to be an object'); + } + + ensureString(snapshot.session.sourceTarget.type, 'session.sourceTarget.type'); + ensureString(snapshot.session.sourceTarget.value, 'session.sourceTarget.value'); + + if (!Array.isArray(snapshot.workers)) { + throw new Error('Canonical session snapshot requires workers to be an array'); + } + + snapshot.workers.forEach((worker, index) => { + if (!isObject(worker)) { + throw new Error(`Canonical session snapshot requires workers[${index}] to be an object`); + } + + ensureString(worker.id, `workers[${index}].id`); + ensureString(worker.label, `workers[${index}].label`); + ensureString(worker.state, `workers[${index}].state`); + ensureString(worker.health, `workers[${index}].health`); + ensureOptionalString(worker.branch, `workers[${index}].branch`); + ensureOptionalString(worker.worktree, `workers[${index}].worktree`); + + if (!isObject(worker.runtime)) { + throw new Error(`Canonical session snapshot requires workers[${index}].runtime to be an object`); + } + + ensureString(worker.runtime.kind, `workers[${index}].runtime.kind`); + ensureOptionalString(worker.runtime.command, `workers[${index}].runtime.command`); + ensureBoolean(worker.runtime.active, `workers[${index}].runtime.active`); + ensureBoolean(worker.runtime.dead, `workers[${index}].runtime.dead`); + + if (!isObject(worker.intent)) { + throw new Error(`Canonical session snapshot requires workers[${index}].intent to be an object`); + } + + ensureStringAllowEmpty(worker.intent.objective, `workers[${index}].intent.objective`); + ensureArrayOfStrings(worker.intent.seedPaths, `workers[${index}].intent.seedPaths`); + + if (!isObject(worker.outputs)) { + throw new Error(`Canonical session snapshot requires workers[${index}].outputs to be an object`); + } + + ensureArrayOfStrings(worker.outputs.summary, `workers[${index}].outputs.summary`); + ensureArrayOfStrings(worker.outputs.validation, `workers[${index}].outputs.validation`); + ensureArrayOfStrings(worker.outputs.remainingRisks, `workers[${index}].outputs.remainingRisks`); + + if (!isObject(worker.artifacts)) { + throw new Error(`Canonical session snapshot requires workers[${index}].artifacts to be an object`); + } + }); + + if (!isObject(snapshot.aggregates)) { + throw new Error('Canonical session snapshot requires aggregates to be an object'); + } + + ensureInteger(snapshot.aggregates.workerCount, 'aggregates.workerCount'); + if (snapshot.aggregates.workerCount !== snapshot.workers.length) { + throw new Error('Canonical session snapshot requires aggregates.workerCount to match workers.length'); + } + + if (!isObject(snapshot.aggregates.states)) { + throw new Error('Canonical session snapshot requires aggregates.states to be an object'); + } + + if (!isObject(snapshot.aggregates.healths)) { + throw new Error('Canonical session snapshot requires aggregates.healths to be an object'); + } + + for (const [state, count] of Object.entries(snapshot.aggregates.states)) { + ensureString(state, 'aggregates.states key'); + ensureInteger(count, `aggregates.states.${state}`); + } + + for (const [health, count] of Object.entries(snapshot.aggregates.healths)) { + ensureString(health, 'aggregates.healths key'); + ensureInteger(count, `aggregates.healths.${health}`); + } + + return snapshot; +} + +function resolveRecordingDir(options = {}) { + if (typeof options.recordingDir === 'string' && options.recordingDir.length > 0) { + return path.resolve(options.recordingDir); + } + + if (typeof process.env.ECC_SESSION_RECORDING_DIR === 'string' && process.env.ECC_SESSION_RECORDING_DIR.length > 0) { + return path.resolve(process.env.ECC_SESSION_RECORDING_DIR); + } + + return DEFAULT_RECORDING_DIR; +} + +function getFallbackSessionRecordingPath(snapshot, options = {}) { + validateCanonicalSnapshot(snapshot); + + return path.join( + resolveRecordingDir(options), + sanitizePathSegment(snapshot.adapterId), + `${sanitizePathSegment(snapshot.session.id)}.json` + ); +} + +function readExistingRecording(filePath) { + if (!fs.existsSync(filePath)) { + return null; + } + + try { + return JSON.parse(fs.readFileSync(filePath, 'utf8')); + } catch { + return null; + } +} + +function writeFallbackSessionRecording(snapshot, options = {}) { + const filePath = getFallbackSessionRecordingPath(snapshot, options); + const recordedAt = new Date().toISOString(); + const existing = readExistingRecording(filePath); + const snapshotChanged = !existing + || JSON.stringify(existing.latest) !== JSON.stringify(snapshot); + + const payload = { + schemaVersion: SESSION_RECORDING_SCHEMA_VERSION, + adapterId: snapshot.adapterId, + sessionId: snapshot.session.id, + createdAt: existing && typeof existing.createdAt === 'string' + ? existing.createdAt + : recordedAt, + updatedAt: recordedAt, + latest: snapshot, + history: Array.isArray(existing && existing.history) + ? (snapshotChanged + ? existing.history.concat([{ recordedAt, snapshot }]) + : existing.history) + : [{ recordedAt, snapshot }] + }; + + fs.mkdirSync(path.dirname(filePath), { recursive: true }); + fs.writeFileSync(filePath, JSON.stringify(payload, null, 2) + '\n', 'utf8'); + + return { + backend: 'json-file', + path: filePath, + recordedAt + }; +} + +function loadStateStore(options = {}) { + if (options.stateStore) { + return options.stateStore; + } + + const loadStateStoreImpl = options.loadStateStoreImpl || (() => require('../state-store')); + + try { + return loadStateStoreImpl(); + } catch (error) { + const missingRequestedModule = error + && error.code === 'MODULE_NOT_FOUND' + && typeof error.message === 'string' + && error.message.includes('../state-store'); + + if (missingRequestedModule) { + return null; + } + + throw error; + } +} + +function resolveStateStoreWriter(stateStore) { + if (!stateStore) { + return null; + } + + const candidates = [ + { owner: stateStore, fn: stateStore.persistCanonicalSessionSnapshot }, + { owner: stateStore, fn: stateStore.recordCanonicalSessionSnapshot }, + { owner: stateStore, fn: stateStore.persistSessionSnapshot }, + { owner: stateStore, fn: stateStore.recordSessionSnapshot }, + { owner: stateStore, fn: stateStore.writeSessionSnapshot }, + { + owner: stateStore.sessions, + fn: stateStore.sessions && stateStore.sessions.persistCanonicalSessionSnapshot + }, + { + owner: stateStore.sessions, + fn: stateStore.sessions && stateStore.sessions.recordCanonicalSessionSnapshot + }, + { + owner: stateStore.sessions, + fn: stateStore.sessions && stateStore.sessions.persistSessionSnapshot + }, + { + owner: stateStore.sessions, + fn: stateStore.sessions && stateStore.sessions.recordSessionSnapshot + } + ]; + + const writer = candidates.find(candidate => typeof candidate.fn === 'function'); + return writer ? writer.fn.bind(writer.owner) : null; +} + +function persistCanonicalSnapshot(snapshot, options = {}) { + validateCanonicalSnapshot(snapshot); + + if (options.persist === false) { + return { + backend: 'skipped', + path: null, + recordedAt: null + }; + } + + const stateStore = loadStateStore(options); + const writer = resolveStateStoreWriter(stateStore); + + if (stateStore && !writer) { + // The loaded object is a factory module (e.g. has createStateStore but no + // writer methods). Treat it the same as a missing state store and fall + // through to the JSON-file recording path below. + return writeFallbackSessionRecording(snapshot, options); + } + + if (writer) { + writer(snapshot, { + adapterId: snapshot.adapterId, + schemaVersion: snapshot.schemaVersion, + sessionId: snapshot.session.id + }); + + return { + backend: 'state-store', + path: null, + recordedAt: null + }; + } + + return writeFallbackSessionRecording(snapshot, options); +} + +function normalizeDmuxSnapshot(snapshot, sourceTarget) { + const workers = (snapshot.workers || []).map(worker => ({ + id: worker.workerSlug, + label: worker.workerSlug, + state: worker.status.state || 'unknown', + health: deriveWorkerHealth(worker), + branch: worker.status.branch || null, + worktree: worker.status.worktree || null, + runtime: { + kind: 'tmux-pane', + command: worker.pane ? worker.pane.currentCommand || null : null, + pid: worker.pane ? worker.pane.pid || null : null, + active: worker.pane ? Boolean(worker.pane.active) : false, + dead: worker.pane ? Boolean(worker.pane.dead) : false, + }, + intent: { + objective: worker.task.objective || '', + seedPaths: Array.isArray(worker.task.seedPaths) ? worker.task.seedPaths : [] + }, + outputs: { + summary: Array.isArray(worker.handoff.summary) ? worker.handoff.summary : [], + validation: Array.isArray(worker.handoff.validation) ? worker.handoff.validation : [], + remainingRisks: Array.isArray(worker.handoff.remainingRisks) ? worker.handoff.remainingRisks : [] + }, + artifacts: { + statusFile: worker.files.status, + taskFile: worker.files.task, + handoffFile: worker.files.handoff + } + })); + + return validateCanonicalSnapshot({ + schemaVersion: SESSION_SCHEMA_VERSION, + adapterId: 'dmux-tmux', + session: { + id: snapshot.sessionName, + kind: 'orchestrated', + state: deriveDmuxSessionState(snapshot), + repoRoot: snapshot.repoRoot || null, + sourceTarget + }, + workers, + aggregates: buildAggregates(workers) + }); +} + +function deriveClaudeWorkerId(session) { + if (session.shortId && session.shortId !== 'no-id') { + return session.shortId; + } + + return path.basename(session.filename || session.sessionPath || 'session', '.tmp'); +} + +function normalizeClaudeHistorySession(session, sourceTarget) { + const metadata = session.metadata || {}; + const workerId = deriveClaudeWorkerId(session); + const worker = { + id: workerId, + label: metadata.title || session.filename || workerId, + state: 'recorded', + health: 'healthy', + branch: metadata.branch || null, + worktree: metadata.worktree || null, + runtime: { + kind: 'claude-session', + command: 'claude', + pid: null, + active: false, + dead: true, + }, + intent: { + objective: metadata.inProgress && metadata.inProgress.length > 0 + ? metadata.inProgress[0] + : (metadata.title || ''), + seedPaths: parseContextSeedPaths(metadata.context) + }, + outputs: { + summary: Array.isArray(metadata.completed) ? metadata.completed : [], + validation: [], + remainingRisks: metadata.notes ? [metadata.notes] : [] + }, + artifacts: { + sessionFile: session.sessionPath, + context: metadata.context || null + } + }; + + return validateCanonicalSnapshot({ + schemaVersion: SESSION_SCHEMA_VERSION, + adapterId: 'claude-history', + session: { + id: workerId, + kind: 'history', + state: 'recorded', + repoRoot: metadata.worktree || null, + sourceTarget + }, + workers: [worker], + aggregates: buildAggregates([worker]) + }); +} + +function normalizeCodexWorktreeSession(session, sourceTarget) { + const state = session.active ? 'active' : 'recorded'; + const objective = typeof session.objective === 'string' ? session.objective : ''; + const worker = { + id: session.sessionId, + label: session.sessionId, + state, + health: 'healthy', + branch: session.branch || null, + worktree: session.cwd || null, + runtime: { + kind: 'codex-session', + command: 'codex', + pid: null, + active: Boolean(session.active), + dead: !session.active, + }, + intent: { + objective, + seedPaths: [] + }, + outputs: { + summary: [], + validation: [], + remainingRisks: [] + }, + artifacts: { + sessionFile: session.sessionPath || null, + model: session.model || null, + originator: session.originator || null, + cliVersion: session.cliVersion || null, + startedAt: session.startedAt || null, + recordCount: Number.isInteger(session.recordCount) ? session.recordCount : null + } + }; + + return validateCanonicalSnapshot({ + schemaVersion: SESSION_SCHEMA_VERSION, + adapterId: 'codex-worktree', + session: { + id: session.sessionId, + kind: 'codex-worktree', + state, + repoRoot: session.cwd || null, + sourceTarget + }, + workers: [worker], + aggregates: buildAggregates([worker]) + }); +} + +function normalizeOpencodeSession(session, sourceTarget) { + const state = session.active ? 'active' : 'recorded'; + const objective = typeof session.objective === 'string' ? session.objective : ''; + const worker = { + id: session.sessionId, + label: session.title || session.sessionId, + state, + health: 'healthy', + branch: session.branch || null, + worktree: session.cwd || null, + runtime: { + kind: 'opencode-session', + command: 'opencode', + pid: null, + active: Boolean(session.active), + dead: !session.active, + }, + intent: { + objective, + seedPaths: [] + }, + outputs: { + summary: [], + validation: [], + remainingRisks: [] + }, + artifacts: { + sessionFile: session.sessionPath || null, + projectId: session.projectId || null, + version: session.version || null, + model: session.model || null, + provider: session.provider || null, + title: session.title || null, + createdAt: session.createdAt || null, + updatedAt: session.updatedAt || null, + messageCount: Number.isInteger(session.messageCount) ? session.messageCount : null + } + }; + + return validateCanonicalSnapshot({ + schemaVersion: SESSION_SCHEMA_VERSION, + adapterId: 'opencode', + session: { + id: session.sessionId, + kind: 'opencode', + state, + repoRoot: session.cwd || null, + sourceTarget + }, + workers: [worker], + aggregates: buildAggregates([worker]) + }); +} + +module.exports = { + SESSION_SCHEMA_VERSION, + buildAggregates, + getFallbackSessionRecordingPath, + normalizeClaudeHistorySession, + normalizeCodexWorktreeSession, + normalizeDmuxSnapshot, + normalizeOpencodeSession, + persistCanonicalSnapshot, + validateCanonicalSnapshot +}; diff --git a/github_code/affaan-m__ECC/scripts/lib/session-adapters/claude-history.js b/github_code/affaan-m__ECC/scripts/lib/session-adapters/claude-history.js new file mode 100644 index 0000000000000000000000000000000000000000..a42c46283bf399cdc77f574dabb114b1d0409b65 --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/session-adapters/claude-history.js @@ -0,0 +1,160 @@ +'use strict'; + +const fs = require('fs'); +const path = require('path'); + +const sessionManager = require('../session-manager'); +const sessionAliases = require('../session-aliases'); +const { normalizeClaudeHistorySession, persistCanonicalSnapshot } = require('./canonical-session'); + +function parseClaudeTarget(target) { + if (typeof target !== 'string') { + return null; + } + + for (const prefix of ['claude-history:', 'claude:', 'history:']) { + if (target.startsWith(prefix)) { + return target.slice(prefix.length).trim(); + } + } + + return null; +} + +function isSessionFileTarget(target, cwd) { + if (typeof target !== 'string' || target.length === 0) { + return false; + } + + const absoluteTarget = path.resolve(cwd, target); + return fs.existsSync(absoluteTarget) + && fs.statSync(absoluteTarget).isFile() + && absoluteTarget.endsWith('.tmp'); +} + +function hydrateSessionFromPath(sessionPath) { + const filename = path.basename(sessionPath); + const parsed = sessionManager.parseSessionFilename(filename); + if (!parsed) { + throw new Error(`Unsupported session file: ${sessionPath}`); + } + + const content = sessionManager.getSessionContent(sessionPath); + const stats = fs.statSync(sessionPath); + + return { + ...parsed, + sessionPath, + content, + metadata: sessionManager.parseSessionMetadata(content), + stats: sessionManager.getSessionStats(content || ''), + size: stats.size, + modifiedTime: stats.mtime, + createdTime: stats.birthtime || stats.ctime + }; +} + +function resolveSessionRecord(target, cwd) { + const explicitTarget = parseClaudeTarget(target); + + if (explicitTarget) { + if (explicitTarget === 'latest') { + const [latest] = sessionManager.getAllSessions({ limit: 1 }).sessions; + if (!latest) { + throw new Error('No Claude session history found'); + } + + return { + session: sessionManager.getSessionById(latest.filename, true), + sourceTarget: { + type: 'claude-history', + value: 'latest' + } + }; + } + + const alias = sessionAliases.resolveAlias(explicitTarget); + if (alias) { + return { + session: hydrateSessionFromPath(alias.sessionPath), + sourceTarget: { + type: 'claude-alias', + value: explicitTarget + } + }; + } + + const session = sessionManager.getSessionById(explicitTarget, true); + if (!session) { + throw new Error(`Claude session not found: ${explicitTarget}`); + } + + return { + session, + sourceTarget: { + type: 'claude-history', + value: explicitTarget + } + }; + } + + if (isSessionFileTarget(target, cwd)) { + return { + session: hydrateSessionFromPath(path.resolve(cwd, target)), + sourceTarget: { + type: 'session-file', + value: path.resolve(cwd, target) + } + }; + } + + throw new Error(`Unsupported Claude session target: ${target}`); +} + +function createClaudeHistoryAdapter(options = {}) { + const persistCanonicalSnapshotImpl = options.persistCanonicalSnapshotImpl || persistCanonicalSnapshot; + + return { + id: 'claude-history', + description: 'Claude local session history and session-file snapshots', + targetTypes: ['claude-history', 'claude-alias', 'session-file'], + canOpen(target, context = {}) { + if (context.adapterId && context.adapterId !== 'claude-history') { + return false; + } + + if (context.adapterId === 'claude-history') { + return true; + } + + const cwd = context.cwd || process.cwd(); + return parseClaudeTarget(target) !== null || isSessionFileTarget(target, cwd); + }, + open(target, context = {}) { + const cwd = context.cwd || process.cwd(); + + return { + adapterId: 'claude-history', + getSnapshot() { + const { session, sourceTarget } = resolveSessionRecord(target, cwd); + const canonicalSnapshot = normalizeClaudeHistorySession(session, sourceTarget); + + persistCanonicalSnapshotImpl(canonicalSnapshot, { + loadStateStoreImpl: options.loadStateStoreImpl, + persist: context.persistSnapshots !== false && options.persistSnapshots !== false, + recordingDir: context.recordingDir || options.recordingDir, + stateStore: options.stateStore + }); + + return canonicalSnapshot; + } + }; + } + }; +} + +module.exports = { + createClaudeHistoryAdapter, + isSessionFileTarget, + parseClaudeTarget +}; diff --git a/github_code/affaan-m__ECC/scripts/lib/session-adapters/codex-worktree.js b/github_code/affaan-m__ECC/scripts/lib/session-adapters/codex-worktree.js new file mode 100644 index 0000000000000000000000000000000000000000..f90db16ca5c847e87efa53332de2c2bda83789a6 --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/session-adapters/codex-worktree.js @@ -0,0 +1,355 @@ +'use strict'; + +const fs = require('fs'); +const os = require('os'); +const path = require('path'); +const { execFileSync } = require('child_process'); + +const { normalizeCodexWorktreeSession, persistCanonicalSnapshot } = require('./canonical-session'); + +const CODEX_TARGET_PREFIXES = ['codex-worktree:', 'codex:']; +const ROLLOUT_PREFIX = 'rollout-'; +const RECENT_ACTIVITY_THRESHOLD_MS = 5 * 60 * 1000; + +function parseCodexTarget(target) { + if (typeof target !== 'string') { + return null; + } + + for (const prefix of CODEX_TARGET_PREFIXES) { + if (target.startsWith(prefix)) { + return target.slice(prefix.length).trim(); + } + } + + return null; +} + +function resolveSessionsDir(options = {}, context = {}) { + const explicit = options.sessionsDir + || context.codexSessionsDir + || process.env.CODEX_SESSIONS_DIR; + + if (typeof explicit === 'string' && explicit.length > 0) { + return path.resolve(explicit); + } + + return path.join(os.homedir(), '.codex', 'sessions'); +} + +function isRolloutFile(filePath) { + const base = path.basename(filePath); + return base.startsWith(ROLLOUT_PREFIX) && base.endsWith('.jsonl'); +} + +function isCodexRolloutFileTarget(target, cwd) { + if (typeof target !== 'string' || target.length === 0) { + return false; + } + + const absoluteTarget = path.resolve(cwd, target); + return fs.existsSync(absoluteTarget) + && fs.statSync(absoluteTarget).isFile() + && isRolloutFile(absoluteTarget); +} + +function listRolloutFiles(sessionsDir) { + if (!fs.existsSync(sessionsDir) || !fs.statSync(sessionsDir).isDirectory()) { + return []; + } + + const files = []; + const stack = [sessionsDir]; + + while (stack.length > 0) { + const current = stack.pop(); + let entries; + try { + entries = fs.readdirSync(current, { withFileTypes: true }); + } catch { + continue; + } + + for (const entry of entries) { + const entryPath = path.join(current, entry.name); + if (entry.isDirectory()) { + stack.push(entryPath); + } else if (entry.isFile() && isRolloutFile(entryPath)) { + files.push(entryPath); + } + } + } + + return files; +} + +function findLatestRollout(sessionsDir) { + const files = listRolloutFiles(sessionsDir); + if (files.length === 0) { + return null; + } + + return files + .map(filePath => ({ filePath, mtimeMs: fs.statSync(filePath).mtimeMs })) + .sort((a, b) => b.mtimeMs - a.mtimeMs)[0].filePath; +} + +function findRolloutById(sessionsDir, sessionId) { + return listRolloutFiles(sessionsDir) + .find(filePath => path.basename(filePath).includes(sessionId)) || null; +} + +function resolveRolloutPath(target, cwd, options, context) { + const explicitTarget = parseCodexTarget(target); + const sessionsDir = resolveSessionsDir(options, context); + + if (explicitTarget) { + if (explicitTarget === 'latest') { + const latest = findLatestRollout(sessionsDir); + if (!latest) { + throw new Error('No Codex rollout sessions found'); + } + + return { rolloutPath: latest, sourceTarget: { type: 'codex-worktree', value: 'latest' } }; + } + + const absoluteExplicit = path.resolve(cwd, explicitTarget); + if (fs.existsSync(absoluteExplicit) && isRolloutFile(absoluteExplicit)) { + return { rolloutPath: absoluteExplicit, sourceTarget: { type: 'codex-rollout-file', value: absoluteExplicit } }; + } + + const byId = findRolloutById(sessionsDir, explicitTarget); + if (byId) { + return { rolloutPath: byId, sourceTarget: { type: 'codex-worktree', value: explicitTarget } }; + } + + throw new Error(`Codex rollout session not found: ${explicitTarget}`); + } + + if (isCodexRolloutFileTarget(target, cwd)) { + const absoluteTarget = path.resolve(cwd, target); + return { rolloutPath: absoluteTarget, sourceTarget: { type: 'codex-rollout-file', value: absoluteTarget } }; + } + + throw new Error(`Unsupported Codex session target: ${target}`); +} + +function readJsonLines(filePath) { + const raw = fs.readFileSync(filePath, 'utf8'); + const records = []; + + for (const line of raw.split('\n')) { + const trimmed = line.trim(); + if (trimmed.length === 0) { + continue; + } + + try { + records.push(JSON.parse(trimmed)); + } catch { + // Rollout logs are append-only; skip partial/corrupt trailing lines. + } + } + + return records; +} + +function extractText(content) { + if (typeof content === 'string') { + return content; + } + + if (Array.isArray(content)) { + return content + .map(part => (part && typeof part.text === 'string' ? part.text : '')) + .join('') + .trim(); + } + + return ''; +} + +function stripLeadingMessageId(text) { + // Codex rollouts sometimes prepend a message UUID directly onto the user + // text (e.g. "019e52db-...please continue"). Drop it for a clean objective. + return text.replace(/^[0-9a-f]{8}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{4}-?[0-9a-f]{12}/i, '').trim(); +} + +function isPreambleText(text) { + // The first user record in a Codex rollout is the injected harness preamble + // (AGENTS.md / environment context), not the operator's actual objective. + return text.startsWith('#') + || text.startsWith('<') + || text.includes('') + || text.includes('AGENTS.md instructions'); +} + +function deriveObjective(records) { + for (const record of records) { + const payload = record && record.payload; + if (!payload || payload.type !== 'message' || payload.role !== 'user') { + continue; + } + + const text = stripLeadingMessageId(extractText(payload.content).trim()); + if (text.length === 0 || isPreambleText(text)) { + continue; + } + + return text.length > 280 ? `${text.slice(0, 277)}...` : text; + } + + return ''; +} + +function recordTimestampMs(record) { + const ts = record && record.timestamp; + if (typeof ts !== 'string') { + return null; + } + + const ms = Date.parse(ts); + return Number.isNaN(ms) ? null : ms; +} + +function deriveLastActivityMs(records, fallbackPath) { + for (let index = records.length - 1; index >= 0; index -= 1) { + const ms = recordTimestampMs(records[index]); + if (ms !== null) { + return ms; + } + } + + try { + return fs.statSync(fallbackPath).mtimeMs; + } catch { + return null; + } +} + +function deriveModel(meta, records) { + for (const record of records) { + if (record && record.type === 'turn_context' && record.payload) { + if (typeof record.payload.model === 'string' && record.payload.model.length > 0) { + return record.payload.model; + } + } + } + + if (meta && typeof meta.model === 'string' && meta.model.length > 0) { + return meta.model; + } + + if (meta && typeof meta.model_provider === 'string' && meta.model_provider.length > 0) { + return meta.model_provider; + } + + return null; +} + +function resolveGitBranch(cwd, resolveBranchImpl) { + if (typeof resolveBranchImpl === 'function') { + return resolveBranchImpl(cwd); + } + + if (typeof cwd !== 'string' || cwd.length === 0 || !fs.existsSync(cwd)) { + return null; + } + + try { + // Strip inherited git env (GIT_DIR etc., set when running inside a git + // hook) so the -C target is honored instead of the host repo. + const gitEnv = { ...process.env }; + for (const key of ['GIT_DIR', 'GIT_WORK_TREE', 'GIT_INDEX_FILE', 'GIT_COMMON_DIR', 'GIT_PREFIX']) { + delete gitEnv[key]; + } + const branch = execFileSync('git', ['-C', cwd, 'rev-parse', '--abbrev-ref', 'HEAD'], { + stdio: ['ignore', 'pipe', 'ignore'], + encoding: 'utf8', + env: gitEnv + }).trim(); + + return branch.length > 0 ? branch : null; + } catch { + return null; + } +} + +function parseCodexRollout(rolloutPath, options = {}) { + const records = readJsonLines(rolloutPath); + const metaRecord = records.find(record => record && record.type === 'session_meta'); + const meta = (metaRecord && metaRecord.payload) || {}; + + const cwd = typeof meta.cwd === 'string' && meta.cwd.length > 0 ? meta.cwd : null; + const lastActivityMs = deriveLastActivityMs(records, rolloutPath); + const isRecent = lastActivityMs !== null && (Date.now() - lastActivityMs) <= RECENT_ACTIVITY_THRESHOLD_MS; + + return { + sessionId: typeof meta.id === 'string' && meta.id.length > 0 + ? meta.id + : path.basename(rolloutPath, '.jsonl'), + sessionPath: rolloutPath, + cwd, + branch: resolveGitBranch(cwd, options.resolveBranchImpl), + objective: deriveObjective(records), + model: deriveModel(meta, records), + originator: typeof meta.originator === 'string' ? meta.originator : null, + cliVersion: typeof meta.cli_version === 'string' ? meta.cli_version : null, + startedAt: typeof meta.timestamp === 'string' ? meta.timestamp : null, + recordCount: records.length, + active: isRecent + }; +} + +function createCodexWorktreeAdapter(options = {}) { + const parseCodexRolloutImpl = options.parseCodexRolloutImpl || parseCodexRollout; + const persistCanonicalSnapshotImpl = options.persistCanonicalSnapshotImpl || persistCanonicalSnapshot; + + return { + id: 'codex-worktree', + description: 'Codex rollout sessions running in git worktrees, normalized to ecc.session.v1', + targetTypes: ['codex-worktree', 'codex'], + canOpen(target, context = {}) { + if (context.adapterId && context.adapterId !== 'codex-worktree') { + return false; + } + + if (context.adapterId === 'codex-worktree') { + return true; + } + + const cwd = context.cwd || process.cwd(); + return parseCodexTarget(target) !== null || isCodexRolloutFileTarget(target, cwd); + }, + open(target, context = {}) { + const cwd = context.cwd || process.cwd(); + + return { + adapterId: 'codex-worktree', + getSnapshot() { + const { rolloutPath, sourceTarget } = resolveRolloutPath(target, cwd, options, context); + const session = parseCodexRolloutImpl(rolloutPath, options); + const canonicalSnapshot = normalizeCodexWorktreeSession(session, sourceTarget); + + persistCanonicalSnapshotImpl(canonicalSnapshot, { + loadStateStoreImpl: options.loadStateStoreImpl, + persist: context.persistSnapshots !== false && options.persistSnapshots !== false, + recordingDir: context.recordingDir || options.recordingDir, + stateStore: options.stateStore + }); + + return canonicalSnapshot; + } + }; + } + }; +} + +module.exports = { + createCodexWorktreeAdapter, + parseCodexTarget, + parseCodexRollout, + isCodexRolloutFileTarget, + findLatestRollout, + findRolloutById +}; diff --git a/github_code/affaan-m__ECC/scripts/lib/session-adapters/dmux-tmux.js b/github_code/affaan-m__ECC/scripts/lib/session-adapters/dmux-tmux.js new file mode 100644 index 0000000000000000000000000000000000000000..40bd38991423bd2c5458a3a35403c9b6839aedfe --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/session-adapters/dmux-tmux.js @@ -0,0 +1,90 @@ +'use strict'; + +const fs = require('fs'); +const path = require('path'); + +const { collectSessionSnapshot } = require('../orchestration-session'); +const { normalizeDmuxSnapshot, persistCanonicalSnapshot } = require('./canonical-session'); + +function isPlanFileTarget(target, cwd) { + if (typeof target !== 'string' || target.length === 0) { + return false; + } + + const absoluteTarget = path.resolve(cwd, target); + return fs.existsSync(absoluteTarget) + && fs.statSync(absoluteTarget).isFile() + && path.extname(absoluteTarget) === '.json'; +} + +function isSessionNameTarget(target, cwd) { + if (typeof target !== 'string' || target.length === 0) { + return false; + } + + const coordinationDir = path.resolve(cwd, '.claude', 'orchestration', target); + return fs.existsSync(coordinationDir) && fs.statSync(coordinationDir).isDirectory(); +} + +function buildSourceTarget(target, cwd) { + if (isPlanFileTarget(target, cwd)) { + return { + type: 'plan', + value: path.resolve(cwd, target) + }; + } + + return { + type: 'session', + value: target + }; +} + +function createDmuxTmuxAdapter(options = {}) { + const collectSessionSnapshotImpl = options.collectSessionSnapshotImpl || collectSessionSnapshot; + const persistCanonicalSnapshotImpl = options.persistCanonicalSnapshotImpl || persistCanonicalSnapshot; + + return { + id: 'dmux-tmux', + description: 'Tmux/worktree orchestration snapshots from plan files or session names', + targetTypes: ['plan', 'session'], + canOpen(target, context = {}) { + if (context.adapterId && context.adapterId !== 'dmux-tmux') { + return false; + } + + if (context.adapterId === 'dmux-tmux') { + return true; + } + + const cwd = context.cwd || process.cwd(); + return isPlanFileTarget(target, cwd) || isSessionNameTarget(target, cwd); + }, + open(target, context = {}) { + const cwd = context.cwd || process.cwd(); + + return { + adapterId: 'dmux-tmux', + getSnapshot() { + const snapshot = collectSessionSnapshotImpl(target, cwd); + const canonicalSnapshot = normalizeDmuxSnapshot(snapshot, buildSourceTarget(target, cwd)); + + persistCanonicalSnapshotImpl(canonicalSnapshot, { + loadStateStoreImpl: options.loadStateStoreImpl, + persist: context.persistSnapshots !== false && options.persistSnapshots !== false, + recordingDir: context.recordingDir || options.recordingDir, + stateStore: options.stateStore + }); + + return canonicalSnapshot; + } + }; + } + }; +} + +module.exports = { + createDmuxTmuxAdapter, + isPlanFileTarget, + isSessionNameTarget +}; diff --git a/github_code/affaan-m__ECC/scripts/lib/session-adapters/opencode.js b/github_code/affaan-m__ECC/scripts/lib/session-adapters/opencode.js new file mode 100644 index 0000000000000000000000000000000000000000..19f88ff415a3830c8ef60c1f85bdca43f4a5a67f --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/session-adapters/opencode.js @@ -0,0 +1,319 @@ +'use strict'; + +const fs = require('fs'); +const os = require('os'); +const path = require('path'); +const { execFileSync } = require('child_process'); + +const { normalizeOpencodeSession, persistCanonicalSnapshot } = require('./canonical-session'); + +const OPENCODE_TARGET_PREFIXES = ['opencode:']; +const RECENT_ACTIVITY_THRESHOLD_MS = 5 * 60 * 1000; +const MAX_MESSAGE_SCAN = 40; + +function parseOpencodeTarget(target) { + if (typeof target !== 'string') { + return null; + } + + for (const prefix of OPENCODE_TARGET_PREFIXES) { + if (target.startsWith(prefix)) { + return target.slice(prefix.length).trim(); + } + } + + return null; +} + +function resolveStorageDir(options = {}, context = {}) { + const explicit = options.storageDir + || context.opencodeStorageDir + || process.env.OPENCODE_STORAGE_DIR; + + if (typeof explicit === 'string' && explicit.length > 0) { + return path.resolve(explicit); + } + + return path.join(os.homedir(), '.local', 'share', 'opencode', 'storage'); +} + +function isSessionInfoFile(filePath) { + const base = path.basename(filePath); + return base.startsWith('ses_') && base.endsWith('.json'); +} + +function isOpencodeSessionFileTarget(target, cwd) { + if (typeof target !== 'string' || target.length === 0) { + return false; + } + + const absoluteTarget = path.resolve(cwd, target); + return fs.existsSync(absoluteTarget) + && fs.statSync(absoluteTarget).isFile() + && isSessionInfoFile(absoluteTarget) + && `${path.sep}session${path.sep}`.length > 0 + && absoluteTarget.includes(`${path.sep}session${path.sep}`); +} + +function listSessionInfoFiles(storageDir) { + const sessionDir = path.join(storageDir, 'session'); + if (!fs.existsSync(sessionDir) || !fs.statSync(sessionDir).isDirectory()) { + return []; + } + + const files = []; + const stack = [sessionDir]; + + while (stack.length > 0) { + const current = stack.pop(); + let entries; + try { + entries = fs.readdirSync(current, { withFileTypes: true }); + } catch { + continue; + } + + for (const entry of entries) { + const entryPath = path.join(current, entry.name); + if (entry.isDirectory()) { + stack.push(entryPath); + } else if (entry.isFile() && isSessionInfoFile(entryPath)) { + files.push(entryPath); + } + } + } + + return files; +} + +function readSessionUpdatedMs(filePath) { + try { + const info = JSON.parse(fs.readFileSync(filePath, 'utf8')); + if (info && info.time && Number.isFinite(info.time.updated)) { + return info.time.updated; + } + } catch { + // fall through to file mtime + } + + try { + return fs.statSync(filePath).mtimeMs; + } catch { + return 0; + } +} + +function findLatestSessionInfo(storageDir) { + const files = listSessionInfoFiles(storageDir); + if (files.length === 0) { + return null; + } + + return files + .map(filePath => ({ filePath, updatedMs: readSessionUpdatedMs(filePath) })) + .sort((a, b) => b.updatedMs - a.updatedMs)[0].filePath; +} + +function findSessionInfoById(storageDir, sessionId) { + return listSessionInfoFiles(storageDir) + .find(filePath => path.basename(filePath, '.json') === sessionId) || null; +} + +function resolveSessionInfoPath(target, cwd, options, context) { + const explicitTarget = parseOpencodeTarget(target); + const storageDir = resolveStorageDir(options, context); + + if (explicitTarget) { + if (explicitTarget === 'latest') { + const latest = findLatestSessionInfo(storageDir); + if (!latest) { + throw new Error('No OpenCode sessions found'); + } + + return { sessionInfoPath: latest, sourceTarget: { type: 'opencode', value: 'latest' } }; + } + + const absoluteExplicit = path.resolve(cwd, explicitTarget); + if (fs.existsSync(absoluteExplicit) && isSessionInfoFile(absoluteExplicit)) { + return { sessionInfoPath: absoluteExplicit, sourceTarget: { type: 'opencode-session-file', value: absoluteExplicit } }; + } + + const byId = findSessionInfoById(storageDir, explicitTarget); + if (byId) { + return { sessionInfoPath: byId, sourceTarget: { type: 'opencode', value: explicitTarget } }; + } + + throw new Error(`OpenCode session not found: ${explicitTarget}`); + } + + if (isOpencodeSessionFileTarget(target, cwd)) { + const absoluteTarget = path.resolve(cwd, target); + return { sessionInfoPath: absoluteTarget, sourceTarget: { type: 'opencode-session-file', value: absoluteTarget } }; + } + + throw new Error(`Unsupported OpenCode session target: ${target}`); +} + +function readMessageFiles(messageDir) { + if (!fs.existsSync(messageDir) || !fs.statSync(messageDir).isDirectory()) { + return []; + } + + try { + return fs.readdirSync(messageDir) + .filter(name => name.startsWith('msg_') && name.endsWith('.json')) + .map(name => path.join(messageDir, name)); + } catch { + return []; + } +} + +function deriveModelFromMessages(messageFiles) { + for (const filePath of messageFiles.slice(0, MAX_MESSAGE_SCAN)) { + let message; + try { + message = JSON.parse(fs.readFileSync(filePath, 'utf8')); + } catch { + continue; + } + + if (message && message.role === 'assistant' && typeof message.modelID === 'string' && message.modelID.length > 0) { + return { + model: message.modelID, + provider: typeof message.providerID === 'string' ? message.providerID : null + }; + } + } + + return { model: null, provider: null }; +} + +function deriveObjective(title) { + if (typeof title !== 'string') { + return ''; + } + + const trimmed = title.trim(); + // OpenCode seeds an auto title ("New session - ") until the model + // renames it; treat that as no objective rather than noise. + if (trimmed.length === 0 || /^New session\b/i.test(trimmed)) { + return ''; + } + + return trimmed.length > 280 ? `${trimmed.slice(0, 277)}...` : trimmed; +} + +function resolveGitBranch(cwd, resolveBranchImpl) { + if (typeof resolveBranchImpl === 'function') { + return resolveBranchImpl(cwd); + } + + if (typeof cwd !== 'string' || cwd.length === 0 || !fs.existsSync(cwd)) { + return null; + } + + try { + // Strip inherited git env (GIT_DIR etc., set when running inside a git + // hook) so the -C target is honored instead of the host repo. + const gitEnv = { ...process.env }; + for (const key of ['GIT_DIR', 'GIT_WORK_TREE', 'GIT_INDEX_FILE', 'GIT_COMMON_DIR', 'GIT_PREFIX']) { + delete gitEnv[key]; + } + const branch = execFileSync('git', ['-C', cwd, 'rev-parse', '--abbrev-ref', 'HEAD'], { + stdio: ['ignore', 'pipe', 'ignore'], + encoding: 'utf8', + env: gitEnv + }).trim(); + + return branch.length > 0 ? branch : null; + } catch { + return null; + } +} + +function parseOpencodeSession(sessionInfoPath, options = {}) { + const storageDir = options.storageDir + ? path.resolve(options.storageDir) + : path.resolve(path.dirname(sessionInfoPath), '..', '..'); + const info = JSON.parse(fs.readFileSync(sessionInfoPath, 'utf8')); + + const sessionId = typeof info.id === 'string' && info.id.length > 0 + ? info.id + : path.basename(sessionInfoPath, '.json'); + const directory = typeof info.directory === 'string' && info.directory.length > 0 ? info.directory : null; + const updatedMs = info.time && Number.isFinite(info.time.updated) ? info.time.updated : null; + const createdMs = info.time && Number.isFinite(info.time.created) ? info.time.created : null; + + const messageFiles = readMessageFiles(path.join(storageDir, 'message', sessionId)); + const { model, provider } = deriveModelFromMessages(messageFiles); + + return { + sessionId, + sessionPath: sessionInfoPath, + cwd: directory, + branch: resolveGitBranch(directory, options.resolveBranchImpl), + objective: deriveObjective(info.title), + title: typeof info.title === 'string' ? info.title : null, + model, + provider, + version: typeof info.version === 'string' ? info.version : null, + projectId: typeof info.projectID === 'string' ? info.projectID : null, + createdAt: createdMs !== null ? new Date(createdMs).toISOString() : null, + updatedAt: updatedMs !== null ? new Date(updatedMs).toISOString() : null, + messageCount: messageFiles.length, + active: updatedMs !== null && (Date.now() - updatedMs) <= RECENT_ACTIVITY_THRESHOLD_MS + }; +} + +function createOpencodeAdapter(options = {}) { + const parseOpencodeSessionImpl = options.parseOpencodeSessionImpl || parseOpencodeSession; + const persistCanonicalSnapshotImpl = options.persistCanonicalSnapshotImpl || persistCanonicalSnapshot; + + return { + id: 'opencode', + description: 'OpenCode sessions normalized to ecc.session.v1', + targetTypes: ['opencode'], + canOpen(target, context = {}) { + if (context.adapterId && context.adapterId !== 'opencode') { + return false; + } + + if (context.adapterId === 'opencode') { + return true; + } + + const cwd = context.cwd || process.cwd(); + return parseOpencodeTarget(target) !== null || isOpencodeSessionFileTarget(target, cwd); + }, + open(target, context = {}) { + const cwd = context.cwd || process.cwd(); + + return { + adapterId: 'opencode', + getSnapshot() { + const { sessionInfoPath, sourceTarget } = resolveSessionInfoPath(target, cwd, options, context); + const session = parseOpencodeSessionImpl(sessionInfoPath, options); + const canonicalSnapshot = normalizeOpencodeSession(session, sourceTarget); + + persistCanonicalSnapshotImpl(canonicalSnapshot, { + loadStateStoreImpl: options.loadStateStoreImpl, + persist: context.persistSnapshots !== false && options.persistSnapshots !== false, + recordingDir: context.recordingDir || options.recordingDir, + stateStore: options.stateStore + }); + + return canonicalSnapshot; + } + }; + } + }; +} + +module.exports = { + createOpencodeAdapter, + parseOpencodeTarget, + parseOpencodeSession, + isOpencodeSessionFileTarget, + findLatestSessionInfo, + findSessionInfoById +}; diff --git a/github_code/affaan-m__ECC/scripts/lib/session-adapters/registry.js b/github_code/affaan-m__ECC/scripts/lib/session-adapters/registry.js new file mode 100644 index 0000000000000000000000000000000000000000..bac7434f0560e162deba968a79fcf249b350e259 --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/session-adapters/registry.js @@ -0,0 +1,148 @@ +'use strict'; + +const { createClaudeHistoryAdapter } = require('./claude-history'); +const { createDmuxTmuxAdapter } = require('./dmux-tmux'); +const { createCodexWorktreeAdapter } = require('./codex-worktree'); +const { createOpencodeAdapter } = require('./opencode'); + +const TARGET_TYPE_TO_ADAPTER_ID = Object.freeze({ + plan: 'dmux-tmux', + session: 'dmux-tmux', + 'claude-history': 'claude-history', + 'claude-alias': 'claude-history', + 'session-file': 'claude-history', + 'codex-worktree': 'codex-worktree', + codex: 'codex-worktree', + opencode: 'opencode' +}); + +function buildDefaultAdapterOptions(options, adapterId) { + const sharedOptions = { + loadStateStoreImpl: options.loadStateStoreImpl, + persistSnapshots: options.persistSnapshots, + recordingDir: options.recordingDir, + stateStore: options.stateStore + }; + + return { + ...sharedOptions, + ...(options.adapterOptions && options.adapterOptions[adapterId] + ? options.adapterOptions[adapterId] + : {}) + }; +} + +function createDefaultAdapters(options = {}) { + return [ + createClaudeHistoryAdapter(buildDefaultAdapterOptions(options, 'claude-history')), + createDmuxTmuxAdapter(buildDefaultAdapterOptions(options, 'dmux-tmux')), + createCodexWorktreeAdapter(buildDefaultAdapterOptions(options, 'codex-worktree')), + createOpencodeAdapter(buildDefaultAdapterOptions(options, 'opencode')) + ]; +} + +function coerceTargetValue(value) { + if (typeof value !== 'string' || value.trim().length === 0) { + throw new Error('Structured session targets require a non-empty string value'); + } + + return value.trim(); +} + +function normalizeStructuredTarget(target, context = {}) { + if (!target || typeof target !== 'object' || Array.isArray(target)) { + return { + target, + context: { ...context } + }; + } + + const value = coerceTargetValue(target.value); + const type = typeof target.type === 'string' ? target.type.trim() : ''; + if (type.length === 0) { + throw new Error('Structured session targets require a non-empty type'); + } + + const adapterId = target.adapterId || TARGET_TYPE_TO_ADAPTER_ID[type] || context.adapterId || null; + const nextContext = { + ...context, + adapterId + }; + + if (type === 'claude-history' || type === 'claude-alias') { + return { + target: `claude:${value}`, + context: nextContext + }; + } + + if (type === 'codex-worktree' || type === 'codex') { + return { + target: `codex:${value}`, + context: nextContext + }; + } + + if (type === 'opencode') { + return { + target: `opencode:${value}`, + context: nextContext + }; + } + + return { + target: value, + context: nextContext + }; +} + +function createAdapterRegistry(options = {}) { + const adapters = options.adapters || createDefaultAdapters(options); + + return { + adapters, + getAdapter(id) { + const adapter = adapters.find(candidate => candidate.id === id); + if (!adapter) { + throw new Error(`Unknown session adapter: ${id}`); + } + + return adapter; + }, + listAdapters() { + return adapters.map(adapter => ({ + id: adapter.id, + description: adapter.description || '', + targetTypes: Array.isArray(adapter.targetTypes) ? [...adapter.targetTypes] : [] + })); + }, + select(target, context = {}) { + const normalized = normalizeStructuredTarget(target, context); + const adapter = normalized.context.adapterId + ? this.getAdapter(normalized.context.adapterId) + : adapters.find(candidate => candidate.canOpen(normalized.target, normalized.context)); + if (!adapter) { + throw new Error(`No session adapter matched target: ${target}`); + } + + return adapter; + }, + open(target, context = {}) { + const normalized = normalizeStructuredTarget(target, context); + const adapter = this.select(normalized.target, normalized.context); + return adapter.open(normalized.target, normalized.context); + } + }; +} + +function inspectSessionTarget(target, options = {}) { + const registry = createAdapterRegistry(options); + return registry.open(target, options).getSnapshot(); +} + +module.exports = { + createAdapterRegistry, + createDefaultAdapters, + inspectSessionTarget, + normalizeStructuredTarget +}; diff --git a/github_code/affaan-m__ECC/scripts/lib/session-aliases.d.ts b/github_code/affaan-m__ECC/scripts/lib/session-aliases.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..3930dc722a626b23a6de669a421d91b5a0f94af1 --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/session-aliases.d.ts @@ -0,0 +1,136 @@ +/** + * Session Aliases Library for Claude Code. + * Manages named aliases for session files, stored in $ECC_AGENT_DATA_HOME/session-aliases.json (default ~/.claude). + */ + +/** Internal alias storage entry */ +export interface AliasEntry { + sessionPath: string; + createdAt: string; + updatedAt?: string; + title: string | null; +} + +/** Alias data structure stored on disk */ +export interface AliasStore { + version: string; + aliases: Record; + metadata: { + totalCount: number; + lastUpdated: string; + }; +} + +/** Resolved alias information returned by resolveAlias */ +export interface ResolvedAlias { + alias: string; + sessionPath: string; + createdAt: string; + title: string | null; +} + +/** Alias entry returned by listAliases */ +export interface AliasListItem { + name: string; + sessionPath: string; + createdAt: string; + updatedAt?: string; + title: string | null; +} + +/** Result from mutation operations (set, delete, rename, update, cleanup) */ +export interface AliasResult { + success: boolean; + error?: string; + [key: string]: unknown; +} + +export interface SetAliasResult extends AliasResult { + isNew?: boolean; + alias?: string; + sessionPath?: string; + title?: string | null; +} + +export interface DeleteAliasResult extends AliasResult { + alias?: string; + deletedSessionPath?: string; +} + +export interface RenameAliasResult extends AliasResult { + oldAlias?: string; + newAlias?: string; + sessionPath?: string; +} + +export interface CleanupResult { + totalChecked: number; + removed: number; + removedAliases: Array<{ name: string; sessionPath: string }>; + error?: string; +} + +export interface ListAliasesOptions { + /** Filter aliases by name or title (partial match, case-insensitive) */ + search?: string | null; + /** Maximum number of aliases to return */ + limit?: number | null; +} + +/** Get the path to the aliases JSON file */ +export function getAliasesPath(): string; + +/** Load all aliases from disk. Returns default structure if file doesn't exist. */ +export function loadAliases(): AliasStore; + +/** + * Save aliases to disk with atomic write (temp file + rename). + * Creates backup before writing; restores on failure. + */ +export function saveAliases(aliases: AliasStore): boolean; + +/** + * Resolve an alias name to its session data. + * @returns Alias data, or null if not found or invalid name + */ +export function resolveAlias(alias: string): ResolvedAlias | null; + +/** + * Create or update an alias for a session. + * Alias names must be alphanumeric with dashes/underscores. + * Reserved names (list, help, remove, delete, create, set) are rejected. + */ +export function setAlias(alias: string, sessionPath: string, title?: string | null): SetAliasResult; + +/** + * List all aliases, optionally filtered and limited. + * Results are sorted by updated time (newest first). + */ +export function listAliases(options?: ListAliasesOptions): AliasListItem[]; + +/** Delete an alias by name */ +export function deleteAlias(alias: string): DeleteAliasResult; + +/** + * Rename an alias. Fails if old alias doesn't exist or new alias already exists. + * New alias name must be alphanumeric with dashes/underscores. + */ +export function renameAlias(oldAlias: string, newAlias: string): RenameAliasResult; + +/** + * Resolve an alias or pass through a session path. + * First tries to resolve as alias; if not found, returns the input as-is. + */ +export function resolveSessionAlias(aliasOrId: string): string; + +/** Update the title of an existing alias. Pass null to clear. */ +export function updateAliasTitle(alias: string, title: string | null): AliasResult; + +/** Get all aliases that point to a specific session path */ +export function getAliasesForSession(sessionPath: string): Array<{ name: string; createdAt: string; title: string | null }>; + +/** + * Remove aliases whose sessions no longer exist. + * @param sessionExists - Function that returns true if a session path is valid + */ +export function cleanupAliases(sessionExists: (sessionPath: string) => boolean): CleanupResult; diff --git a/github_code/affaan-m__ECC/scripts/lib/session-aliases.js b/github_code/affaan-m__ECC/scripts/lib/session-aliases.js new file mode 100644 index 0000000000000000000000000000000000000000..bfc846315cee3ea4b92482dbc1cc370b5f553d8f --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/session-aliases.js @@ -0,0 +1,481 @@ +/** + * Session Aliases Library for Claude Code + * Manages session aliases stored in $ECC_AGENT_DATA_HOME/session-aliases.json (default ~/.claude). + */ + +const fs = require('fs'); +const path = require('path'); + +const { + getClaudeDir, + ensureDir, + readFile, + log +} = require('./utils'); + +// Aliases file path +function getAliasesPath() { + return path.join(getClaudeDir(), 'session-aliases.json'); +} + +// Current alias storage format version +const ALIAS_VERSION = '1.0'; + +/** + * Default aliases file structure + */ +function getDefaultAliases() { + return { + version: ALIAS_VERSION, + aliases: {}, + metadata: { + totalCount: 0, + lastUpdated: new Date().toISOString() + } + }; +} + +/** + * Load aliases from file + * @returns {object} Aliases object + */ +function loadAliases() { + const aliasesPath = getAliasesPath(); + + if (!fs.existsSync(aliasesPath)) { + return getDefaultAliases(); + } + + const content = readFile(aliasesPath); + if (!content) { + return getDefaultAliases(); + } + + try { + const data = JSON.parse(content); + + // Validate structure + if (!data.aliases || typeof data.aliases !== 'object') { + log('[Aliases] Invalid aliases file structure, resetting'); + return getDefaultAliases(); + } + + // Ensure version field + if (!data.version) { + data.version = ALIAS_VERSION; + } + + // Ensure metadata + if (!data.metadata) { + data.metadata = { + totalCount: Object.keys(data.aliases).length, + lastUpdated: new Date().toISOString() + }; + } + + return data; + } catch (err) { + log(`[Aliases] Error parsing aliases file: ${err.message}`); + return getDefaultAliases(); + } +} + +/** + * Save aliases to file with atomic write + * @param {object} aliases - Aliases object to save + * @returns {boolean} Success status + */ +function saveAliases(aliases) { + const aliasesPath = getAliasesPath(); + const tempPath = aliasesPath + '.tmp'; + const backupPath = aliasesPath + '.bak'; + + try { + // Update metadata + aliases.metadata = { + totalCount: Object.keys(aliases.aliases).length, + lastUpdated: new Date().toISOString() + }; + + const content = JSON.stringify(aliases, null, 2); + + // Ensure directory exists + ensureDir(path.dirname(aliasesPath)); + + // Create backup if file exists + if (fs.existsSync(aliasesPath)) { + fs.copyFileSync(aliasesPath, backupPath); + } + + // Atomic write: write to temp file, then rename + fs.writeFileSync(tempPath, content, 'utf8'); + + // On Windows, rename fails with EEXIST if destination exists, so delete first. + // On Unix/macOS, rename(2) atomically replaces the destination — skip the + // delete to avoid an unnecessary non-atomic window between unlink and rename. + if (process.platform === 'win32' && fs.existsSync(aliasesPath)) { + fs.unlinkSync(aliasesPath); + } + fs.renameSync(tempPath, aliasesPath); + + // Remove backup on success + if (fs.existsSync(backupPath)) { + fs.unlinkSync(backupPath); + } + + return true; + } catch (err) { + log(`[Aliases] Error saving aliases: ${err.message}`); + + // Restore from backup if exists + if (fs.existsSync(backupPath)) { + try { + fs.copyFileSync(backupPath, aliasesPath); + log('[Aliases] Restored from backup'); + } catch (restoreErr) { + log(`[Aliases] Failed to restore backup: ${restoreErr.message}`); + } + } + + // Clean up temp file (best-effort) + try { + if (fs.existsSync(tempPath)) { + fs.unlinkSync(tempPath); + } + } catch { + // Non-critical: temp file will be overwritten on next save + } + + return false; + } +} + +/** + * Resolve an alias to get session path + * @param {string} alias - Alias name to resolve + * @returns {object|null} Alias data or null if not found + */ +function resolveAlias(alias) { + if (!alias) return null; + + // Validate alias name (alphanumeric, dash, underscore) + if (!/^[a-zA-Z0-9_-]+$/.test(alias)) { + return null; + } + + const data = loadAliases(); + const aliasData = data.aliases[alias]; + + if (!aliasData) { + return null; + } + + return { + alias, + sessionPath: aliasData.sessionPath, + createdAt: aliasData.createdAt, + title: aliasData.title || null + }; +} + +/** + * Set or update an alias for a session + * @param {string} alias - Alias name (alphanumeric, dash, underscore) + * @param {string} sessionPath - Session directory path + * @param {string} title - Optional title for the alias + * @returns {object} Result with success status and message + */ +function setAlias(alias, sessionPath, title = null) { + // Validate alias name + if (!alias || alias.length === 0) { + return { success: false, error: 'Alias name cannot be empty' }; + } + + // Validate session path + if (!sessionPath || typeof sessionPath !== 'string' || sessionPath.trim().length === 0) { + return { success: false, error: 'Session path cannot be empty' }; + } + + if (alias.length > 128) { + return { success: false, error: 'Alias name cannot exceed 128 characters' }; + } + + if (!/^[a-zA-Z0-9_-]+$/.test(alias)) { + return { success: false, error: 'Alias name must contain only letters, numbers, dashes, and underscores' }; + } + + // Reserved alias names + const reserved = ['list', 'help', 'remove', 'delete', 'create', 'set']; + if (reserved.includes(alias.toLowerCase())) { + return { success: false, error: `'${alias}' is a reserved alias name` }; + } + + const data = loadAliases(); + const existing = data.aliases[alias]; + const isNew = !existing; + + data.aliases[alias] = { + sessionPath, + createdAt: existing ? existing.createdAt : new Date().toISOString(), + updatedAt: new Date().toISOString(), + title: title || null + }; + + if (saveAliases(data)) { + return { + success: true, + isNew, + alias, + sessionPath, + title: data.aliases[alias].title + }; + } + + return { success: false, error: 'Failed to save alias' }; +} + +/** + * List all aliases + * @param {object} options - Options object + * @param {string} options.search - Filter aliases by name (partial match) + * @param {number} options.limit - Maximum number of aliases to return + * @returns {Array} Array of alias objects + */ +function listAliases(options = {}) { + const { search = null, limit = null } = options; + const data = loadAliases(); + + let aliases = Object.entries(data.aliases).map(([name, info]) => ({ + name, + sessionPath: info.sessionPath, + createdAt: info.createdAt, + updatedAt: info.updatedAt, + title: info.title + })); + + // Sort by updated time (newest first) + aliases.sort((a, b) => (new Date(b.updatedAt || b.createdAt || 0).getTime() || 0) - (new Date(a.updatedAt || a.createdAt || 0).getTime() || 0)); + + // Apply search filter + if (search) { + const searchLower = search.toLowerCase(); + aliases = aliases.filter(a => + a.name.toLowerCase().includes(searchLower) || + (a.title && a.title.toLowerCase().includes(searchLower)) + ); + } + + // Apply limit + if (limit && limit > 0) { + aliases = aliases.slice(0, limit); + } + + return aliases; +} + +/** + * Delete an alias + * @param {string} alias - Alias name to delete + * @returns {object} Result with success status + */ +function deleteAlias(alias) { + const data = loadAliases(); + + if (!data.aliases[alias]) { + return { success: false, error: `Alias '${alias}' not found` }; + } + + const deleted = data.aliases[alias]; + delete data.aliases[alias]; + + if (saveAliases(data)) { + return { + success: true, + alias, + deletedSessionPath: deleted.sessionPath + }; + } + + return { success: false, error: 'Failed to delete alias' }; +} + +/** + * Rename an alias + * @param {string} oldAlias - Current alias name + * @param {string} newAlias - New alias name + * @returns {object} Result with success status + */ +function renameAlias(oldAlias, newAlias) { + const data = loadAliases(); + + if (!data.aliases[oldAlias]) { + return { success: false, error: `Alias '${oldAlias}' not found` }; + } + + // Validate new alias name (same rules as setAlias) + if (!newAlias || newAlias.length === 0) { + return { success: false, error: 'New alias name cannot be empty' }; + } + + if (newAlias.length > 128) { + return { success: false, error: 'New alias name cannot exceed 128 characters' }; + } + + if (!/^[a-zA-Z0-9_-]+$/.test(newAlias)) { + return { success: false, error: 'New alias name must contain only letters, numbers, dashes, and underscores' }; + } + + const reserved = ['list', 'help', 'remove', 'delete', 'create', 'set']; + if (reserved.includes(newAlias.toLowerCase())) { + return { success: false, error: `'${newAlias}' is a reserved alias name` }; + } + + if (data.aliases[newAlias]) { + return { success: false, error: `Alias '${newAlias}' already exists` }; + } + + const aliasData = data.aliases[oldAlias]; + delete data.aliases[oldAlias]; + + aliasData.updatedAt = new Date().toISOString(); + data.aliases[newAlias] = aliasData; + + if (saveAliases(data)) { + return { + success: true, + oldAlias, + newAlias, + sessionPath: aliasData.sessionPath + }; + } + + // Restore old alias and remove new alias on failure + data.aliases[oldAlias] = aliasData; + delete data.aliases[newAlias]; + // Attempt to persist the rollback + saveAliases(data); + return { success: false, error: 'Failed to save renamed alias — rolled back to original' }; +} + +/** + * Get session path by alias (convenience function) + * @param {string} aliasOrId - Alias name or session ID + * @returns {string|null} Session path or null if not found + */ +function resolveSessionAlias(aliasOrId) { + // First try to resolve as alias + const resolved = resolveAlias(aliasOrId); + if (resolved) { + return resolved.sessionPath; + } + + // If not an alias, return as-is (might be a session path) + return aliasOrId; +} + +/** + * Update alias title + * @param {string} alias - Alias name + * @param {string|null} title - New title (string or null to clear) + * @returns {object} Result with success status + */ +function updateAliasTitle(alias, title) { + if (title !== null && typeof title !== 'string') { + return { success: false, error: 'Title must be a string or null' }; + } + + const data = loadAliases(); + + if (!data.aliases[alias]) { + return { success: false, error: `Alias '${alias}' not found` }; + } + + data.aliases[alias].title = title || null; + data.aliases[alias].updatedAt = new Date().toISOString(); + + if (saveAliases(data)) { + return { + success: true, + alias, + title + }; + } + + return { success: false, error: 'Failed to update alias title' }; +} + +/** + * Get all aliases for a specific session + * @param {string} sessionPath - Session path to find aliases for + * @returns {Array} Array of alias names + */ +function getAliasesForSession(sessionPath) { + const data = loadAliases(); + const aliases = []; + + for (const [name, info] of Object.entries(data.aliases)) { + if (info.sessionPath === sessionPath) { + aliases.push({ + name, + createdAt: info.createdAt, + title: info.title + }); + } + } + + return aliases; +} + +/** + * Clean up aliases for non-existent sessions + * @param {Function} sessionExists - Function to check if session exists + * @returns {object} Cleanup result + */ +function cleanupAliases(sessionExists) { + if (typeof sessionExists !== 'function') { + return { totalChecked: 0, removed: 0, removedAliases: [], error: 'sessionExists must be a function' }; + } + + const data = loadAliases(); + const removed = []; + + for (const [name, info] of Object.entries(data.aliases)) { + if (!sessionExists(info.sessionPath)) { + removed.push({ name, sessionPath: info.sessionPath }); + delete data.aliases[name]; + } + } + + if (removed.length > 0 && !saveAliases(data)) { + log('[Aliases] Failed to save after cleanup'); + return { + success: false, + totalChecked: Object.keys(data.aliases).length + removed.length, + removed: removed.length, + removedAliases: removed, + error: 'Failed to save after cleanup' + }; + } + + return { + success: true, + totalChecked: Object.keys(data.aliases).length + removed.length, + removed: removed.length, + removedAliases: removed + }; +} + +module.exports = { + getAliasesPath, + loadAliases, + saveAliases, + resolveAlias, + setAlias, + listAliases, + deleteAlias, + renameAlias, + resolveSessionAlias, + updateAliasTitle, + getAliasesForSession, + cleanupAliases +}; diff --git a/github_code/affaan-m__ECC/scripts/lib/session-bridge.js b/github_code/affaan-m__ECC/scripts/lib/session-bridge.js new file mode 100644 index 0000000000000000000000000000000000000000..19033d633ca417221c3c307c0d143a114a93966e --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/session-bridge.js @@ -0,0 +1,148 @@ +'use strict'; + +/** + * Shared session bridge utilities for ECC hooks. + * + * The bridge file is a small JSON aggregate in /tmp that allows + * statusline, metrics-bridge, and context-monitor to share state + * without scanning large JSONL logs on every invocation. + */ + +const crypto = require('crypto'); +const fs = require('fs'); +const os = require('os'); +const path = require('path'); + +const MAX_SESSION_ID_LENGTH = 64; + +/** + * Sanitize a session ID for safe use in file paths. + * Rejects path traversal, strips unsafe chars, limits length. + * @param {string} raw + * @returns {string|null} Safe session ID or null if invalid + */ +function sanitizeSessionId(raw) { + if (!raw || typeof raw !== 'string') return null; + if (/[/\\]|\.\./.test(raw)) return null; + const safe = raw.replace(/[^a-zA-Z0-9_-]/g, '_').slice(0, MAX_SESSION_ID_LENGTH); + return safe || null; +} + +/** + * Get the bridge file path for a session. + * @param {string} sessionId - Already-sanitized session ID + * @returns {string} + */ +function getBridgePath(sessionId) { + return path.join(os.tmpdir(), `ecc-metrics-${sessionId}.json`); +} + +/** + * Read bridge data. Returns null on any error. + * @param {string} sessionId - Already-sanitized session ID + * @returns {object|null} + */ +function readBridge(sessionId) { + try { + const raw = fs.readFileSync(getBridgePath(sessionId), 'utf8'); + return JSON.parse(raw); + } catch { + return null; + } +} + +/** + * Write bridge data atomically (write unique-suffix tmp then rename). + * + * The tmp path includes `process.pid` plus a random nonce so concurrent + * writers (e.g. PostToolUse `ecc-metrics-bridge` and the background + * `ecc-statusline`, both writing to the same session bridge) do not + * clobber each other's tmp file mid-write. With a fixed `.tmp` suffix + * two writers could both call `writeFileSync` against the same path + * before either reaches `renameSync`, causing one writer's payload to + * silently overwrite the other and the second `renameSync` to throw + * ENOENT once the rename consumes the file. + * + * Same pattern already used by `writeCostWarningIfChanged` in + * `scripts/hooks/ecc-metrics-bridge.js` (commit 9b1d8918) for the + * cost-warning cache; this commit applies it to the session-bridge + * primitive too. + * + * @param {string} sessionId - Already-sanitized session ID + * @param {object} data + */ +function writeBridgeAtomic(sessionId, data) { + const target = getBridgePath(sessionId); + const tmp = `${target}.${process.pid}.${crypto.randomBytes(4).toString('hex')}.tmp`; + fs.writeFileSync(tmp, JSON.stringify(data), 'utf8'); + try { + renameWithRetry(tmp, target); + } catch (err) { + try { fs.unlinkSync(tmp); } catch { /* ignore */ } + throw err; + } +} + +/** + * Replace a file via rename, retrying briefly on transient OS-level errors. + * + * POSIX `rename(2)` is atomic between source and destination, so concurrent + * writers each rename onto the same target without conflict. Windows + * `MoveFileExW` is different: it fails with EPERM/EACCES/EBUSY if the + * target is currently being renamed by *another* process — a short race + * window that fires reliably under our PostToolUse + statusline concurrency. + * + * To stay portable, retry up to 5 times with exponential backoff (20 ms, + * 40, 80, 160, 320) on the Windows-only transient codes. POSIX runs hit + * the first try and exit immediately. Other error codes (ENOENT, ENOSPC, + * EROFS, …) re-throw without retry — they are not transient. + * + * Sleep uses `Atomics.wait` on a throwaway SharedArrayBuffer so the + * retry path does not busy-spin the CPU. This works on the main thread + * in Node ≥ 17 (and on workers in earlier versions). + * + * @param {string} tmp + * @param {string} target + */ +function renameWithRetry(tmp, target) { + const RETRY_CODES = new Set(['EPERM', 'EACCES', 'EBUSY']); + const MAX_ATTEMPTS = 5; + for (let attempt = 0; ; attempt++) { + try { + fs.renameSync(tmp, target); + return; + } catch (err) { + if (attempt + 1 >= MAX_ATTEMPTS || !RETRY_CODES.has(err.code)) { + throw err; + } + const delayMs = 20 << attempt; + try { + Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, delayMs); + } catch { + // Atomics.wait throws on the main thread in some older runtimes; + // fall back to a brief busy-wait so the retry path still has a delay. + const until = Date.now() + delayMs; + while (Date.now() < until) { /* spin */ } + } + } + } +} + +/** + * Resolve session ID from environment variables. + * @returns {string|null} Sanitized session ID or null + */ +function resolveSessionId() { + const raw = process.env.ECC_SESSION_ID || process.env.CLAUDE_SESSION_ID || ''; + return sanitizeSessionId(raw); +} + +module.exports = { + sanitizeSessionId, + getBridgePath, + readBridge, + writeBridgeAtomic, + renameWithRetry, + resolveSessionId, + MAX_SESSION_ID_LENGTH +}; diff --git a/github_code/affaan-m__ECC/scripts/lib/session-manager.d.ts b/github_code/affaan-m__ECC/scripts/lib/session-manager.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..5c90c424d53d8fb7aa10c3d06b82b374dee89ef2 --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/session-manager.d.ts @@ -0,0 +1,132 @@ +/** + * Session Manager Library for Claude Code. + * Provides CRUD operations for session files stored as markdown in + * ~/.claude/session-data/ with legacy read compatibility for ~/.claude/sessions/. + */ + +/** Parsed metadata from a session filename */ +export interface SessionFilenameMeta { + /** Original filename */ + filename: string; + /** Short ID extracted from filename, or "no-id" for old format */ + shortId: string; + /** Date string in YYYY-MM-DD format */ + date: string; + /** Parsed Date object from the date string */ + datetime: Date; +} + +/** Metadata parsed from session markdown content */ +export interface SessionMetadata { + title: string | null; + date: string | null; + started: string | null; + lastUpdated: string | null; + completed: string[]; + inProgress: string[]; + notes: string; + context: string; +} + +/** Statistics computed from session content */ +export interface SessionStats { + totalItems: number; + completedItems: number; + inProgressItems: number; + lineCount: number; + hasNotes: boolean; + hasContext: boolean; +} + +/** A session object returned by getAllSessions and getSessionById */ +export interface Session extends SessionFilenameMeta { + /** Full filesystem path to the session file */ + sessionPath: string; + /** Whether the file has any content */ + hasContent?: boolean; + /** File size in bytes */ + size: number; + /** Last modification time */ + modifiedTime: Date; + /** File creation time (falls back to ctime on Linux) */ + createdTime: Date; + /** Session markdown content (only when includeContent=true) */ + content?: string | null; + /** Parsed metadata (only when includeContent=true) */ + metadata?: SessionMetadata; + /** Session statistics (only when includeContent=true) */ + stats?: SessionStats; +} + +/** Pagination result from getAllSessions */ +export interface SessionListResult { + sessions: Session[]; + total: number; + offset: number; + limit: number; + hasMore: boolean; +} + +export interface GetAllSessionsOptions { + /** Maximum number of sessions to return (default: 50) */ + limit?: number; + /** Number of sessions to skip (default: 0) */ + offset?: number; + /** Filter by date in YYYY-MM-DD format */ + date?: string | null; + /** Search in short ID */ + search?: string | null; +} + +/** + * Parse a session filename to extract date and short ID. + * @returns Parsed metadata, or null if the filename doesn't match the expected pattern + */ +export function parseSessionFilename(filename: string): SessionFilenameMeta | null; + +/** Get the full filesystem path for a session filename */ +export function getSessionPath(filename: string): string; + +/** + * Read session markdown content from disk. + * @returns Content string, or null if the file doesn't exist + */ +export function getSessionContent(sessionPath: string): string | null; + +/** Parse session metadata from markdown content */ +export function parseSessionMetadata(content: string | null): SessionMetadata; + +/** + * Calculate statistics for a session. + * Accepts either a file path (absolute, ending in .tmp) or pre-read content string. + * Supports both Unix (/path/to/session.tmp) and Windows (C:\path\to\session.tmp) paths. + */ +export function getSessionStats(sessionPathOrContent: string): SessionStats; + +/** Get the title from a session file, or "Untitled Session" if none */ +export function getSessionTitle(sessionPath: string): string; + +/** Get human-readable file size (e.g., "1.2 KB") */ +export function getSessionSize(sessionPath: string): string; + +/** Get all sessions with optional filtering and pagination */ +export function getAllSessions(options?: GetAllSessionsOptions): SessionListResult; + +/** + * Find a session by short ID or filename. + * @param sessionId - Short ID prefix, full filename, or filename without .tmp + * @param includeContent - Whether to read and parse the session content + */ +export function getSessionById(sessionId: string, includeContent?: boolean): Session | null; + +/** Write markdown content to a session file */ +export function writeSessionContent(sessionPath: string, content: string): boolean; + +/** Append content to an existing session file */ +export function appendSessionContent(sessionPath: string, content: string): boolean; + +/** Delete a session file */ +export function deleteSession(sessionPath: string): boolean; + +/** Check if a session file exists and is a regular file */ +export function sessionExists(sessionPath: string): boolean; diff --git a/github_code/affaan-m__ECC/scripts/lib/session-manager.js b/github_code/affaan-m__ECC/scripts/lib/session-manager.js new file mode 100644 index 0000000000000000000000000000000000000000..a4b900058290d5725f9455ba6afc08f409a4595b --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/session-manager.js @@ -0,0 +1,545 @@ +/** + * Session Manager Library for Claude Code + * Provides core session CRUD operations for listing, loading, and managing sessions + * + * Sessions are stored as markdown files in ~/.claude/session-data/ with + * legacy read compatibility for ~/.claude/sessions/: + * - YYYY-MM-DD-session.tmp (old format) + * - YYYY-MM-DD--session.tmp (new format) + */ + +const fs = require('fs'); +const path = require('path'); + +const { + getSessionsDir, + getSessionSearchDirs, + readFile, + log +} = require('./utils'); + +// Session filename pattern: YYYY-MM-DD-[session-id]-session.tmp +// The session-id is optional (old format) and can include letters, digits, +// underscores, and hyphens, but must not start with a hyphen. +// Matches: "2026-02-01-session.tmp", "2026-02-01-a1b2c3d4-session.tmp", +// "2026-02-01-frontend-worktree-1-session.tmp", and +// "2026-02-01-ChezMoi_2-session.tmp" +const SESSION_FILENAME_REGEX = /^(\d{4}-\d{2}-\d{2})(?:-([a-zA-Z0-9_][a-zA-Z0-9_-]*))?-session\.tmp$/; + +/** + * Resolve a file's creation time, preferring birthtime but falling back to + * ctime when birthtime is unavailable. Some filesystems (e.g. overlayfs in + * containers) report birthtime as epoch 0; a Date object is always truthy, so + * `birthtime || ctime` would never fall back. Compare on milliseconds instead. + * @param {import('fs').Stats} stats + * @returns {Date} + */ +function resolveCreatedTime(stats) { + return stats.birthtimeMs > 0 ? stats.birthtime : stats.ctime; +} + +/** + * Parse session filename to extract metadata + * @param {string} filename - Session filename (e.g., "2026-01-17-abc123-session.tmp" or "2026-01-17-session.tmp") + * @returns {object|null} Parsed metadata or null if invalid + */ +function parseSessionFilename(filename) { + if (!filename || typeof filename !== 'string') return null; + const match = filename.match(SESSION_FILENAME_REGEX); + if (!match) return null; + + const dateStr = match[1]; + + // Validate date components are calendar-accurate (not just format) + const [year, month, day] = dateStr.split('-').map(Number); + if (month < 1 || month > 12 || day < 1 || day > 31) return null; + // Reject impossible dates like Feb 31, Apr 31 — Date constructor rolls + // over invalid days (e.g., Feb 31 → Mar 3), so check month roundtrips + const d = new Date(year, month - 1, day); + if (d.getMonth() !== month - 1 || d.getDate() !== day) return null; + + // match[2] is undefined for old format (no ID) + const shortId = match[2] || 'no-id'; + + return { + filename, + shortId, + date: dateStr, + // Use local-time constructor (consistent with validation on line 40) + // new Date(dateStr) interprets YYYY-MM-DD as UTC midnight which shows + // as the previous day in negative UTC offset timezones + datetime: new Date(year, month - 1, day) + }; +} + +/** + * Get the full path to a session file + * @param {string} filename - Session filename + * @returns {string} Full path to session file + */ +function getSessionPath(filename) { + return path.join(getSessionsDir(), filename); +} + +function getSessionCandidates(options = {}) { + const { + date = null, + search = null + } = options; + + const candidates = []; + + for (const sessionsDir of getSessionSearchDirs()) { + if (!fs.existsSync(sessionsDir)) { + continue; + } + + let entries; + try { + entries = fs.readdirSync(sessionsDir, { withFileTypes: true }); + } catch (error) { + log(`[SessionManager] Error reading sessions directory ${sessionsDir}: ${error.message}`); + continue; + } + + for (const entry of entries) { + if (!entry.isFile() || !entry.name.endsWith('.tmp')) continue; + + const filename = entry.name; + const metadata = parseSessionFilename(filename); + + if (!metadata) continue; + if (date && metadata.date !== date) continue; + if (search && !metadata.shortId.includes(search)) continue; + + const sessionPath = path.join(sessionsDir, filename); + + let stats; + try { + stats = fs.statSync(sessionPath); + } catch (error) { + log(`[SessionManager] Error stating session ${sessionPath}: ${error.message}`); + continue; + } + + candidates.push({ + ...metadata, + sessionPath, + hasContent: stats.size > 0, + size: stats.size, + modifiedTime: stats.mtime, + createdTime: resolveCreatedTime(stats) + }); + } + } + + const deduped = []; + const seenFilenames = new Set(); + + for (const session of candidates) { + if (seenFilenames.has(session.filename)) { + continue; + } + seenFilenames.add(session.filename); + deduped.push(session); + } + + deduped.sort((a, b) => b.modifiedTime - a.modifiedTime); + return deduped; +} + +function buildSessionRecord(sessionPath, metadata) { + let stats; + try { + stats = fs.statSync(sessionPath); + } catch (error) { + log(`[SessionManager] Error stating session ${sessionPath}: ${error.message}`); + return null; + } + + return { + ...metadata, + sessionPath, + hasContent: stats.size > 0, + size: stats.size, + modifiedTime: stats.mtime, + createdTime: resolveCreatedTime(stats) + }; +} + +function sessionMatchesId(metadata, normalizedSessionId) { + const filename = metadata.filename; + const shortIdMatch = metadata.shortId !== 'no-id' && metadata.shortId.startsWith(normalizedSessionId); + const filenameMatch = filename === normalizedSessionId || filename === `${normalizedSessionId}.tmp`; + const noIdMatch = metadata.shortId === 'no-id' && filename === `${normalizedSessionId}-session.tmp`; + + return shortIdMatch || filenameMatch || noIdMatch; +} + +function getMatchingSessionCandidates(normalizedSessionId) { + const matches = []; + const seenFilenames = new Set(); + + for (const sessionsDir of getSessionSearchDirs()) { + if (!fs.existsSync(sessionsDir)) { + continue; + } + + let entries; + try { + entries = fs.readdirSync(sessionsDir, { withFileTypes: true }); + } catch (error) { + log(`[SessionManager] Error reading sessions directory ${sessionsDir}: ${error.message}`); + continue; + } + + for (const entry of entries) { + if (!entry.isFile() || !entry.name.endsWith('.tmp')) continue; + + const metadata = parseSessionFilename(entry.name); + if (!metadata || !sessionMatchesId(metadata, normalizedSessionId)) { + continue; + } + + if (seenFilenames.has(metadata.filename)) { + continue; + } + + const sessionPath = path.join(sessionsDir, metadata.filename); + const sessionRecord = buildSessionRecord(sessionPath, metadata); + if (!sessionRecord) { + continue; + } + + seenFilenames.add(metadata.filename); + matches.push(sessionRecord); + } + } + + matches.sort((a, b) => b.modifiedTime - a.modifiedTime); + return matches; +} + +/** + * Read and parse session markdown content + * @param {string} sessionPath - Full path to session file + * @returns {string|null} Session content or null if not found + */ +function getSessionContent(sessionPath) { + return readFile(sessionPath); +} + +/** + * Parse session metadata from markdown content + * @param {string} content - Session markdown content + * @returns {object} Parsed metadata + */ +function parseSessionMetadata(content) { + const metadata = { + title: null, + date: null, + started: null, + lastUpdated: null, + project: null, + branch: null, + worktree: null, + completed: [], + inProgress: [], + notes: '', + context: '' + }; + + if (!content) return metadata; + + // Extract title from first heading + const titleMatch = content.match(/^#\s+(.+)$/m); + if (titleMatch) { + metadata.title = titleMatch[1].trim(); + } + + // Extract date + const dateMatch = content.match(/\*\*Date:\*\*\s*(\d{4}-\d{2}-\d{2})/); + if (dateMatch) { + metadata.date = dateMatch[1]; + } + + // Extract started time + const startedMatch = content.match(/\*\*Started:\*\*\s*([\d:]+)/); + if (startedMatch) { + metadata.started = startedMatch[1]; + } + + // Extract last updated + const updatedMatch = content.match(/\*\*Last Updated:\*\*\s*([\d:]+)/); + if (updatedMatch) { + metadata.lastUpdated = updatedMatch[1]; + } + + // Extract control-plane metadata + const projectMatch = content.match(/\*\*Project:\*\*\s*(.+)$/m); + if (projectMatch) { + metadata.project = projectMatch[1].trim(); + } + + const branchMatch = content.match(/\*\*Branch:\*\*\s*(.+)$/m); + if (branchMatch) { + metadata.branch = branchMatch[1].trim(); + } + + const worktreeMatch = content.match(/\*\*Worktree:\*\*\s*(.+)$/m); + if (worktreeMatch) { + metadata.worktree = worktreeMatch[1].trim(); + } + + // Extract completed items + const completedSection = content.match(/### Completed\s*\n([\s\S]*?)(?=###|\n\n|$)/); + if (completedSection) { + const items = completedSection[1].match(/- \[x\]\s*(.+)/g); + if (items) { + metadata.completed = items.map(item => item.replace(/- \[x\]\s*/, '').trim()); + } + } + + // Extract in-progress items + const progressSection = content.match(/### In Progress\s*\n([\s\S]*?)(?=###|\n\n|$)/); + if (progressSection) { + const items = progressSection[1].match(/- \[ \]\s*(.+)/g); + if (items) { + metadata.inProgress = items.map(item => item.replace(/- \[ \]\s*/, '').trim()); + } + } + + // Extract notes + const notesSection = content.match(/### Notes for Next Session\s*\n([\s\S]*?)(?=###|\n\n|$)/); + if (notesSection) { + metadata.notes = notesSection[1].trim(); + } + + // Extract context to load + const contextSection = content.match(/### Context to Load\s*\n```\n([\s\S]*?)```/); + if (contextSection) { + metadata.context = contextSection[1].trim(); + } + + return metadata; +} + +/** + * Calculate statistics for a session + * @param {string} sessionPathOrContent - Full path to session file, OR + * the pre-read content string (to avoid redundant disk reads when + * the caller already has the content loaded). + * @returns {object} Statistics object + */ +function getSessionStats(sessionPathOrContent) { + // Accept pre-read content string to avoid redundant file reads. + // If the argument looks like a file path (no newlines, ends with .tmp, + // starts with / on Unix or drive letter on Windows), read from disk. + // Otherwise treat it as content. + const looksLikePath = typeof sessionPathOrContent === 'string' && + !sessionPathOrContent.includes('\n') && + sessionPathOrContent.endsWith('.tmp') && + (sessionPathOrContent.startsWith('/') || /^[A-Za-z]:[/\\]/.test(sessionPathOrContent)); + const content = looksLikePath + ? getSessionContent(sessionPathOrContent) + : sessionPathOrContent; + + const metadata = parseSessionMetadata(content); + + return { + totalItems: metadata.completed.length + metadata.inProgress.length, + completedItems: metadata.completed.length, + inProgressItems: metadata.inProgress.length, + lineCount: content ? content.split('\n').length : 0, + hasNotes: !!metadata.notes, + hasContext: !!metadata.context + }; +} + +/** + * Get all sessions with optional filtering and pagination + * @param {object} options - Options object + * @param {number} options.limit - Maximum number of sessions to return + * @param {number} options.offset - Number of sessions to skip + * @param {string} options.date - Filter by date (YYYY-MM-DD format) + * @param {string} options.search - Search in short ID + * @returns {object} Object with sessions array and pagination info + */ +function getAllSessions(options = {}) { + const { + limit: rawLimit = 50, + offset: rawOffset = 0, + date = null, + search = null + } = options; + + // Clamp offset and limit to safe non-negative integers. + // Without this, negative offset causes slice() to count from the end, + // and NaN values cause slice() to return empty or unexpected results. + // Note: cannot use `|| default` because 0 is falsy — use isNaN instead. + const offsetNum = Number(rawOffset); + const offset = Number.isNaN(offsetNum) ? 0 : Math.max(0, Math.floor(offsetNum)); + const limitNum = Number(rawLimit); + const limit = Number.isNaN(limitNum) ? 50 : Math.max(1, Math.floor(limitNum)); + + const sessions = getSessionCandidates({ date, search }); + + if (sessions.length === 0) { + return { sessions: [], total: 0, offset, limit, hasMore: false }; + } + + // Apply pagination + const paginatedSessions = sessions.slice(offset, offset + limit); + + return { + sessions: paginatedSessions, + total: sessions.length, + offset, + limit, + hasMore: offset + limit < sessions.length + }; +} + +/** + * Get a single session by ID (short ID or full path) + * @param {string} sessionId - Short ID or session filename + * @param {boolean} includeContent - Include session content + * @returns {object|null} Session object or null if not found + */ +function getSessionById(sessionId, includeContent = false) { + if (typeof sessionId !== 'string') { + return null; + } + + const normalizedSessionId = sessionId.trim(); + if (!normalizedSessionId) { + return null; + } + + const sessions = getMatchingSessionCandidates(normalizedSessionId); + + for (const session of sessions) { + const sessionRecord = { ...session }; + + if (includeContent) { + sessionRecord.content = getSessionContent(sessionRecord.sessionPath); + sessionRecord.metadata = parseSessionMetadata(sessionRecord.content); + // Pass pre-read content to avoid a redundant disk read + sessionRecord.stats = getSessionStats(sessionRecord.content || ''); + } + + return sessionRecord; + } + + return null; +} + +/** + * Get session title from content + * @param {string} sessionPath - Full path to session file + * @returns {string} Title or default text + */ +function getSessionTitle(sessionPath) { + const content = getSessionContent(sessionPath); + const metadata = parseSessionMetadata(content); + + return metadata.title || 'Untitled Session'; +} + +/** + * Format session size in human-readable format + * @param {string} sessionPath - Full path to session file + * @returns {string} Formatted size (e.g., "1.2 KB") + */ +function getSessionSize(sessionPath) { + let stats; + try { + stats = fs.statSync(sessionPath); + } catch { + return '0 B'; + } + const size = stats.size; + + if (size < 1024) return `${size} B`; + if (size < 1024 * 1024) return `${(size / 1024).toFixed(1)} KB`; + return `${(size / (1024 * 1024)).toFixed(1)} MB`; +} + +/** + * Write session content to file + * @param {string} sessionPath - Full path to session file + * @param {string} content - Markdown content to write + * @returns {boolean} Success status + */ +function writeSessionContent(sessionPath, content) { + try { + fs.writeFileSync(sessionPath, content, 'utf8'); + return true; + } catch (err) { + log(`[SessionManager] Error writing session: ${err.message}`); + return false; + } +} + +/** + * Append content to a session + * @param {string} sessionPath - Full path to session file + * @param {string} content - Content to append + * @returns {boolean} Success status + */ +function appendSessionContent(sessionPath, content) { + try { + fs.appendFileSync(sessionPath, content, 'utf8'); + return true; + } catch (err) { + log(`[SessionManager] Error appending to session: ${err.message}`); + return false; + } +} + +/** + * Delete a session file + * @param {string} sessionPath - Full path to session file + * @returns {boolean} Success status + */ +function deleteSession(sessionPath) { + try { + if (fs.existsSync(sessionPath)) { + fs.unlinkSync(sessionPath); + return true; + } + return false; + } catch (err) { + log(`[SessionManager] Error deleting session: ${err.message}`); + return false; + } +} + +/** + * Check if a session exists + * @param {string} sessionPath - Full path to session file + * @returns {boolean} True if session exists + */ +function sessionExists(sessionPath) { + try { + return fs.statSync(sessionPath).isFile(); + } catch { + return false; + } +} + +module.exports = { + parseSessionFilename, + getSessionPath, + getSessionContent, + parseSessionMetadata, + getSessionStats, + getSessionTitle, + getSessionSize, + getAllSessions, + getSessionById, + writeSessionContent, + appendSessionContent, + deleteSession, + sessionExists +}; diff --git a/github_code/affaan-m__ECC/scripts/lib/shell-split.js b/github_code/affaan-m__ECC/scripts/lib/shell-split.js new file mode 100644 index 0000000000000000000000000000000000000000..0d09623768bb6d9f0e3a34055894d4c62dc1ab90 --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/shell-split.js @@ -0,0 +1,86 @@ +'use strict'; + +/** + * Split a shell command into segments by operators (&&, ||, ;, &) + * while respecting quoting (single/double) and escaped characters. + * Redirection operators (&>, >&, 2>&1) are NOT treated as separators. + */ +function splitShellSegments(command) { + const segments = []; + let current = ''; + let quote = null; + + for (let i = 0; i < command.length; i++) { + const ch = command[i]; + + // Inside quotes: handle escapes and closing quote + if (quote) { + if (ch === '\\' && i + 1 < command.length) { + current += ch + command[i + 1]; + i++; + continue; + } + if (ch === quote) quote = null; + current += ch; + continue; + } + + // Backslash escape outside quotes + if (ch === '\\' && i + 1 < command.length) { + current += ch + command[i + 1]; + i++; + continue; + } + + // Opening quote + if (ch === '"' || ch === "'") { + quote = ch; + current += ch; + continue; + } + + const next = command[i + 1] || ''; + const prev = i > 0 ? command[i - 1] : ''; + + // && operator + if (ch === '&' && next === '&') { + if (current.trim()) segments.push(current.trim()); + current = ''; + i++; + continue; + } + + // || operator + if (ch === '|' && next === '|') { + if (current.trim()) segments.push(current.trim()); + current = ''; + i++; + continue; + } + + // ; separator + if (ch === ';') { + if (current.trim()) segments.push(current.trim()); + current = ''; + continue; + } + + // Single & — but skip redirection patterns (&>, >&, digit>&) + if (ch === '&' && next !== '&') { + if (next === '>' || prev === '>') { + current += ch; + continue; + } + if (current.trim()) segments.push(current.trim()); + current = ''; + continue; + } + + current += ch; + } + + if (current.trim()) segments.push(current.trim()); + return segments; +} + +module.exports = { splitShellSegments }; diff --git a/github_code/affaan-m__ECC/scripts/lib/shell-substitution.js b/github_code/affaan-m__ECC/scripts/lib/shell-substitution.js new file mode 100644 index 0000000000000000000000000000000000000000..a2241770d7609fb9906a3296361d0bdbc8a3d511 --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/shell-substitution.js @@ -0,0 +1,481 @@ +'use strict'; + +/** @returns {{ body: string, endIndex: number }} */ +function readBacktickSubstitution(source, startIndex) { + let body = ''; + let endIndex = startIndex + 1; + while (endIndex < source.length) { + const inner = source[endIndex]; + if (inner === '\\') { + const escaped = source[endIndex + 1]; + body = escaped === undefined ? `${body}\\` : `${body}\\${escaped}`; + endIndex += escaped === undefined ? 1 : 2; + continue; + } + if (inner === '`') break; + body = `${body}${inner}`; + endIndex += 1; + } + return { body, endIndex }; +} + +/** @returns {{ body: string, endIndex: number }} */ +function readDollarSubstitution(source, startIndex) { + let body = ''; + let depth = 1; + let inSingle = false; + let inDouble = false; + let endIndex = startIndex + 2; + while (endIndex < source.length && depth > 0) { + const inner = source[endIndex]; + if (inner === '\\' && !inSingle) { + const escaped = source[endIndex + 1]; + body = escaped === undefined ? `${body}\\` : `${body}\\${escaped}`; + endIndex += escaped === undefined ? 1 : 2; + continue; + } + if (inner === "'" && !inDouble) inSingle = !inSingle; + else if (inner === '"' && !inSingle) inDouble = !inDouble; + else if (!inSingle && !inDouble && inner === '(') depth += 1; + else if (!inSingle && !inDouble && inner === ')') depth -= 1; + if (depth > 0) body = `${body}${inner}`; + endIndex += depth > 0 ? 1 : 0; + } + return { body, endIndex }; +} + +/** + * Iterate over command-substitution bodies, followed by nested bodies. + * Quote characters in an unquoted heredoc are literal only at the outer level; + * substitutions still use normal shell quote semantics internally. + * + * @param {string} input + * @param {{ literalOuterQuotes?: boolean }} [options] + * @returns {Generator} + */ +function* iterateCommandSubstitutions(input, options = {}) { + const source = String(input || ''); + const literalOuterQuotes = options.literalOuterQuotes === true; + let inSingle = false; + let inDouble = false; + for (let i = 0; i < source.length; i += 1) { + const ch = source[i]; + if (ch === '\\' && !inSingle) { + i += 1; + continue; + } + if (!literalOuterQuotes && ch === "'" && !inDouble) { + inSingle = !inSingle; + continue; + } + if (!literalOuterQuotes && ch === '"' && !inSingle) { + inDouble = !inDouble; + continue; + } + if (inSingle) continue; + const span = ch === '`' ? readBacktickSubstitution(source, i) : null; + const substitution = ch === '$' && source[i + 1] === '(' ? readDollarSubstitution(source, i) : span; + if (!substitution) continue; + i = substitution.endIndex; + if (!substitution.body.trim()) continue; + yield substitution.body; + yield* iterateCommandSubstitutions(substitution.body); + } +} + +/** + * Extract executable command-substitution bodies from a shell line. + * + * @param {string} input + * @param {{ literalOuterQuotes?: boolean }} [options] + * @returns {string[]} + */ +function extractCommandSubstitutions(input, options = {}) { + return [...iterateCommandSubstitutions(input, options)]; +} + +/** + * Extract bodies of plain `(...)` subshell groups. + * + * Bash treats `(npm run dev)` as a subshell that executes its contents, but + * the regex-light segment splitters used by our PreToolUse hooks don't peer + * inside those parens. This helper finds top-level `(...)` groups (skipping + * `$(...)` command substitutions and backticks, which `extractCommandSubstitutions` + * already covers) and returns each body, recursing for nested groups. + * + * Quote semantics: + * - Single quotes are literal: `'( ... )'` is a string, not a subshell. + * - Double quotes are literal *for parens*: `"( ... )"` is a string too — + * bash only honors `$( )` inside double quotes, not bare `( )`. + * + * @param {string} input + * @returns {string[]} + */ +function extractSubshellGroups(input) { + const source = String(input || ''); + const groups = []; + let inSingle = false; + let inDouble = false; + + for (let i = 0; i < source.length; i++) { + const ch = source[i]; + const prev = source[i - 1]; + + if (ch === '\\' && !inSingle) { + i += 1; + continue; + } + + if (ch === "'" && !inDouble && prev !== '\\') { + inSingle = !inSingle; + continue; + } + + if (ch === '"' && !inSingle && prev !== '\\') { + inDouble = !inDouble; + continue; + } + + if (inSingle || inDouble) { + continue; + } + + if (ch === '$' && source[i + 1] === '(') { + let depth = 1; + let skipInSingle = false; + let skipInDouble = false; + i += 2; + while (i < source.length && depth > 0) { + const inner = source[i]; + const innerPrev = source[i - 1]; + if (inner === '\\' && !skipInSingle) { + i += 2; + continue; + } + if (inner === "'" && !skipInDouble && innerPrev !== '\\') { + skipInSingle = !skipInSingle; + } else if (inner === '"' && !skipInSingle && innerPrev !== '\\') { + skipInDouble = !skipInDouble; + } else if (!skipInSingle && !skipInDouble) { + if (inner === '(') depth += 1; + else if (inner === ')') depth -= 1; + } + i += 1; + } + i -= 1; + continue; + } + + if (ch === '`') { + i += 1; + while (i < source.length && source[i] !== '`') { + if (source[i] === '\\' && i + 1 < source.length) { + i += 2; + continue; + } + i += 1; + } + continue; + } + + if (ch === '(') { + let depth = 1; + let body = ''; + let bodyInSingle = false; + let bodyInDouble = false; + i += 1; + while (i < source.length && depth > 0) { + const inner = source[i]; + const innerPrev = source[i - 1]; + if (inner === '\\' && !bodyInSingle) { + body += inner; + if (i + 1 < source.length) { + body += source[i + 1]; + i += 2; + } else { + // Trailing backslash at end of an unterminated span: advance past + // it so it is not appended a second time by the fallthrough below. + i += 1; + } + continue; + } + if (inner === "'" && !bodyInDouble && innerPrev !== '\\') { + bodyInSingle = !bodyInSingle; + } else if (inner === '"' && !bodyInSingle && innerPrev !== '\\') { + bodyInDouble = !bodyInDouble; + } else if (!bodyInSingle && !bodyInDouble) { + if (inner === '(') { + depth += 1; + } else if (inner === ')') { + depth -= 1; + if (depth === 0) { + break; + } + } + } + body += inner; + i += 1; + } + if (body.trim()) { + groups.push(body); + groups.push(...extractSubshellGroups(body)); + } + } + } + + return groups; +} + +/** + * Extract bodies of `{ ...; }` brace groups. + * + * Bash brace groups run their body in the *current* shell (unlike `(...)`, + * which forks a subshell). Both forms group multiple commands, so for the + * purposes of destructive-bash and dev-server detection they are equivalent: + * a `rm -rf` or `npm run dev` inside `{ ...; }` still executes. + * + * Recognition rules match bash's own reserved-word semantics: + * - `{` is a reserved word only when followed by whitespace and preceded by + * the line start, whitespace, or a shell operator (`;`, `|`, `&`, `(`). + * So `{npm run dev}` is NOT a brace group (single token starting with `{`). + * - `}` closes the group only when preceded by `;` or whitespace. + * So `foo}` inside the body is not a closing brace. + * - Single quotes are literal; double quotes are also literal for `{`/`}`. + * - `$(...)`, backticks, and plain `(...)` spans are skipped so we don't + * double-extract bodies the sibling extractors already cover. + * + * @param {string} input + * @returns {string[]} + */ +function extractBraceGroups(input) { + const source = String(input || ''); + const groups = []; + let inSingle = false; + let inDouble = false; + + for (let i = 0; i < source.length; i++) { + const ch = source[i]; + const prev = source[i - 1]; + + if (ch === '\\' && !inSingle) { + i += 1; + continue; + } + + if (ch === "'" && !inDouble && prev !== '\\') { + inSingle = !inSingle; + continue; + } + + if (ch === '"' && !inSingle && prev !== '\\') { + inDouble = !inDouble; + continue; + } + + if (inSingle || inDouble) { + continue; + } + + if (ch === '$' && source[i + 1] === '(') { + let depth = 1; + let skipInSingle = false; + let skipInDouble = false; + i += 2; + while (i < source.length && depth > 0) { + const inner = source[i]; + const innerPrev = source[i - 1]; + if (inner === '\\' && !skipInSingle) { + i += 2; + continue; + } + if (inner === "'" && !skipInDouble && innerPrev !== '\\') { + skipInSingle = !skipInSingle; + } else if (inner === '"' && !skipInSingle && innerPrev !== '\\') { + skipInDouble = !skipInDouble; + } else if (!skipInSingle && !skipInDouble) { + if (inner === '(') depth += 1; + else if (inner === ')') depth -= 1; + } + i += 1; + } + i -= 1; + continue; + } + + if (ch === '`') { + i += 1; + while (i < source.length && source[i] !== '`') { + if (source[i] === '\\' && i + 1 < source.length) { + i += 2; + continue; + } + i += 1; + } + continue; + } + + if (ch === '(') { + let depth = 1; + let skipInSingle = false; + let skipInDouble = false; + i += 1; + while (i < source.length && depth > 0) { + const inner = source[i]; + const innerPrev = source[i - 1]; + if (inner === '\\' && !skipInSingle) { + i += 2; + continue; + } + if (inner === "'" && !skipInDouble && innerPrev !== '\\') { + skipInSingle = !skipInSingle; + } else if (inner === '"' && !skipInSingle && innerPrev !== '\\') { + skipInDouble = !skipInDouble; + } else if (!skipInSingle && !skipInDouble) { + if (inner === '(') depth += 1; + else if (inner === ')') depth -= 1; + } + i += 1; + } + i -= 1; + continue; + } + + if (ch === '{' && /\s/.test(source[i + 1] || '')) { + const prevIsBoundary = i === 0 || /[\s;|&(]/.test(prev); + if (!prevIsBoundary) continue; + + let depth = 1; + let body = ''; + let bodyInSingle = false; + let bodyInDouble = false; + i += 1; + while (i < source.length && depth > 0) { + const inner = source[i]; + const innerPrev = source[i - 1]; + if (inner === '\\' && !bodyInSingle) { + body += inner; + if (i + 1 < source.length) { + body += source[i + 1]; + i += 2; + } else { + // Trailing backslash at end of an unterminated span: advance past + // it so it is not appended a second time by the fallthrough below. + i += 1; + } + continue; + } + if (inner === "'" && !bodyInDouble && innerPrev !== '\\') { + bodyInSingle = !bodyInSingle; + body += inner; + i += 1; + continue; + } + if (inner === '"' && !bodyInSingle && innerPrev !== '\\') { + bodyInDouble = !bodyInDouble; + body += inner; + i += 1; + continue; + } + if (bodyInSingle || bodyInDouble) { + body += inner; + i += 1; + continue; + } + // Skip $(...) spans — a quoted `}` or `}`-as-text inside a + // substitution body must not close the enclosing brace group. + if (inner === '$' && source[i + 1] === '(') { + body += inner + source[i + 1]; + let subDepth = 1; + let subInSingle = false; + let subInDouble = false; + i += 2; + while (i < source.length && subDepth > 0) { + const c = source[i]; + const p = source[i - 1]; + body += c; + if (c === '\\' && !subInSingle && i + 1 < source.length) { + body += source[i + 1]; + i += 2; + continue; + } + if (c === "'" && !subInDouble && p !== '\\') subInSingle = !subInSingle; + else if (c === '"' && !subInSingle && p !== '\\') subInDouble = !subInDouble; + else if (!subInSingle && !subInDouble) { + if (c === '(') subDepth += 1; + else if (c === ')') subDepth -= 1; + } + i += 1; + } + continue; + } + // Skip backtick spans for the same reason. + if (inner === '`') { + body += inner; + i += 1; + while (i < source.length && source[i] !== '`') { + if (source[i] === '\\' && i + 1 < source.length) { + body += source[i] + source[i + 1]; + i += 2; + continue; + } + body += source[i]; + i += 1; + } + if (i < source.length) { + body += source[i]; + i += 1; + } + continue; + } + // Skip plain (...) subshell spans for the same reason. + if (inner === '(') { + body += inner; + let subDepth = 1; + let subInSingle = false; + let subInDouble = false; + i += 1; + while (i < source.length && subDepth > 0) { + const c = source[i]; + const p = source[i - 1]; + body += c; + if (c === '\\' && !subInSingle && i + 1 < source.length) { + body += source[i + 1]; + i += 2; + continue; + } + if (c === "'" && !subInDouble && p !== '\\') subInSingle = !subInSingle; + else if (c === '"' && !subInSingle && p !== '\\') subInDouble = !subInDouble; + else if (!subInSingle && !subInDouble) { + if (c === '(') subDepth += 1; + else if (c === ')') subDepth -= 1; + } + i += 1; + } + continue; + } + if (inner === '{' && /\s/.test(source[i + 1] || '')) { + // Match the outer-scan boundary rule for nested `{` so + // tokens like `foo{` (no boundary, but followed by space + // via `foo{ bar`) cannot bump nested depth. + const nestedPrevIsBoundary = /[\s;|&(]/.test(innerPrev); + if (nestedPrevIsBoundary) depth += 1; + } else if (inner === '}' && (innerPrev === ';' || /\s/.test(innerPrev))) { + depth -= 1; + if (depth === 0) { + break; + } + } + body += inner; + i += 1; + } + if (body.trim()) { + groups.push(body); + groups.push(...extractBraceGroups(body)); + } + } + } + + return groups; +} + +module.exports = { extractCommandSubstitutions, extractSubshellGroups, extractBraceGroups }; diff --git a/github_code/affaan-m__ECC/scripts/lib/skill-evolution/dashboard.js b/github_code/affaan-m__ECC/scripts/lib/skill-evolution/dashboard.js new file mode 100644 index 0000000000000000000000000000000000000000..7049707bd495cb61033d8a8ada89bf19434b2483 --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/skill-evolution/dashboard.js @@ -0,0 +1,401 @@ +'use strict'; + +const health = require('./health'); +const tracker = require('./tracker'); +const versioning = require('./versioning'); + +const DAY_IN_MS = 24 * 60 * 60 * 1000; +const SPARKLINE_CHARS = '\u2581\u2582\u2583\u2584\u2585\u2586\u2587\u2588'; +const EMPTY_BLOCK = '\u2591'; +const FILL_BLOCK = '\u2588'; +const DEFAULT_PANEL_WIDTH = 64; +const VALID_PANELS = new Set(['success-rate', 'failures', 'amendments', 'versions']); + +function sparkline(values) { + if (!Array.isArray(values) || values.length === 0) { + return ''; + } + + return values.map(value => { + if (value === null || value === undefined) { + return EMPTY_BLOCK; + } + + const clamped = Math.max(0, Math.min(1, value)); + const index = Math.min(Math.round(clamped * (SPARKLINE_CHARS.length - 1)), SPARKLINE_CHARS.length - 1); + return SPARKLINE_CHARS[index]; + }).join(''); +} + +function horizontalBar(value, max, width) { + if (max <= 0 || width <= 0) { + return EMPTY_BLOCK.repeat(width || 0); + } + + const filled = Math.round((Math.min(value, max) / max) * width); + const empty = width - filled; + return FILL_BLOCK.repeat(filled) + EMPTY_BLOCK.repeat(empty); +} + +function panelBox(title, lines, width) { + const innerWidth = width || DEFAULT_PANEL_WIDTH; + const output = []; + output.push('\u250C\u2500 ' + title + ' ' + '\u2500'.repeat(Math.max(0, innerWidth - title.length - 4)) + '\u2510'); + + for (const line of lines) { + const truncated = line.length > innerWidth - 2 + ? line.slice(0, innerWidth - 2) + : line; + output.push('\u2502 ' + truncated.padEnd(innerWidth - 2) + '\u2502'); + } + + output.push('\u2514' + '\u2500'.repeat(innerWidth - 1) + '\u2518'); + return output.join('\n'); +} + +function bucketByDay(records, nowMs, days) { + const buckets = []; + for (let i = days - 1; i >= 0; i -= 1) { + const dayEnd = nowMs - (i * DAY_IN_MS); + const dayStart = dayEnd - DAY_IN_MS; + const dateStr = new Date(dayEnd).toISOString().slice(0, 10); + buckets.push({ date: dateStr, start: dayStart, end: dayEnd, records: [] }); + } + + for (const record of records) { + const recordMs = Date.parse(record.recorded_at); + if (Number.isNaN(recordMs)) { + continue; + } + + for (const bucket of buckets) { + if (recordMs > bucket.start && recordMs <= bucket.end) { + bucket.records.push(record); + break; + } + } + } + + return buckets.map(bucket => ({ + date: bucket.date, + rate: bucket.records.length > 0 + ? health.calculateSuccessRate(bucket.records) + : null, + runs: bucket.records.length, + })); +} + +function getTrendArrow(successRate7d, successRate30d) { + if (successRate7d === null || successRate30d === null) { + return '\u2192'; + } + + const delta = successRate7d - successRate30d; + if (delta >= 0.1) { + return '\u2197'; + } + + if (delta <= -0.1) { + return '\u2198'; + } + + return '\u2192'; +} + +function formatPercent(value) { + if (value === null) { + return 'n/a'; + } + + return `${Math.round(value * 100)}%`; +} + +function groupRecordsBySkill(records) { + return records.reduce((grouped, record) => { + const skillId = record.skill_id; + if (!grouped.has(skillId)) { + grouped.set(skillId, []); + } + + grouped.get(skillId).push(record); + return grouped; + }, new Map()); +} + +function renderSuccessRatePanel(records, skills, options = {}) { + const nowMs = Date.parse(options.now || new Date().toISOString()); + const days = options.days || 30; + const width = options.width || DEFAULT_PANEL_WIDTH; + const recordsBySkill = groupRecordsBySkill(records); + + const skillData = []; + const skillIds = Array.from(new Set([ + ...Array.from(recordsBySkill.keys()), + ...skills.map(s => s.skill_id), + ])).sort(); + + for (const skillId of skillIds) { + const skillRecords = recordsBySkill.get(skillId) || []; + const dailyRates = bucketByDay(skillRecords, nowMs, days); + const rateValues = dailyRates.map(b => b.rate); + const records7d = health.filterRecordsWithinDays(skillRecords, nowMs, 7); + const records30d = health.filterRecordsWithinDays(skillRecords, nowMs, 30); + const current7d = health.calculateSuccessRate(records7d); + const current30d = health.calculateSuccessRate(records30d); + const trend = getTrendArrow(current7d, current30d); + + skillData.push({ + skill_id: skillId, + daily_rates: dailyRates, + sparkline: sparkline(rateValues), + current_7d: current7d, + trend, + }); + } + + const lines = []; + if (skillData.length === 0) { + lines.push('No skill execution data available.'); + } else { + for (const skill of skillData) { + const nameCol = skill.skill_id.slice(0, 14).padEnd(14); + const sparkCol = skill.sparkline.slice(0, 30); + const rateCol = formatPercent(skill.current_7d).padStart(5); + lines.push(`${nameCol} ${sparkCol} ${rateCol} ${skill.trend}`); + } + } + + return { + text: panelBox('Success Rate (30d)', lines, width), + data: { skills: skillData }, + }; +} + +function renderFailureClusterPanel(records, options = {}) { + const width = options.width || DEFAULT_PANEL_WIDTH; + const failures = records.filter(r => r.outcome === 'failure'); + + const clusterMap = new Map(); + for (const record of failures) { + const reason = (record.failure_reason || 'unknown').toLowerCase().trim(); + if (!clusterMap.has(reason)) { + clusterMap.set(reason, { count: 0, skill_ids: new Set() }); + } + + const cluster = clusterMap.get(reason); + cluster.count += 1; + cluster.skill_ids.add(record.skill_id); + } + + const clusters = Array.from(clusterMap.entries()) + .map(([pattern, data]) => ({ + pattern, + count: data.count, + skill_ids: Array.from(data.skill_ids).sort(), + percentage: failures.length > 0 + ? Math.round((data.count / failures.length) * 100) + : 0, + })) + .sort((a, b) => b.count - a.count || a.pattern.localeCompare(b.pattern)); + + const maxCount = clusters.length > 0 ? clusters[0].count : 0; + const lines = []; + + if (clusters.length === 0) { + lines.push('No failure patterns detected.'); + } else { + for (const cluster of clusters) { + const label = cluster.pattern.slice(0, 20).padEnd(20); + const bar = horizontalBar(cluster.count, maxCount, 16); + const skillCount = cluster.skill_ids.length; + const suffix = skillCount === 1 ? 'skill' : 'skills'; + lines.push(`${label} ${bar} ${String(cluster.count).padStart(3)} (${skillCount} ${suffix})`); + } + } + + return { + text: panelBox('Failure Patterns', lines, width), + data: { clusters, total_failures: failures.length }, + }; +} + +function renderAmendmentPanel(skillsById, options = {}) { + const width = options.width || DEFAULT_PANEL_WIDTH; + const amendments = []; + + for (const [skillId, skill] of skillsById) { + if (!skill.skill_dir) { + continue; + } + + const log = versioning.getEvolutionLog(skill.skill_dir, 'amendments'); + for (const entry of log) { + const status = typeof entry.status === 'string' ? entry.status : null; + const isPending = status + ? health.PENDING_AMENDMENT_STATUSES.has(status) + : entry.event === 'proposal'; + + if (isPending) { + amendments.push({ + skill_id: skillId, + event: entry.event || 'proposal', + status: status || 'pending', + created_at: entry.created_at || null, + }); + } + } + } + + amendments.sort((a, b) => { + const timeA = a.created_at ? Date.parse(a.created_at) : 0; + const timeB = b.created_at ? Date.parse(b.created_at) : 0; + return timeB - timeA; + }); + + const lines = []; + if (amendments.length === 0) { + lines.push('No pending amendments.'); + } else { + for (const amendment of amendments) { + const name = amendment.skill_id.slice(0, 14).padEnd(14); + const event = amendment.event.padEnd(10); + const status = amendment.status.padEnd(10); + const time = amendment.created_at ? amendment.created_at.slice(0, 19) : '-'; + lines.push(`${name} ${event} ${status} ${time}`); + } + + lines.push(''); + lines.push(`${amendments.length} amendment${amendments.length === 1 ? '' : 's'} pending review`); + } + + return { + text: panelBox('Pending Amendments', lines, width), + data: { amendments, total: amendments.length }, + }; +} + +function renderVersionTimelinePanel(skillsById, options = {}) { + const width = options.width || DEFAULT_PANEL_WIDTH; + const skillVersions = []; + + for (const [skillId, skill] of skillsById) { + if (!skill.skill_dir) { + continue; + } + + const versions = versioning.listVersions(skill.skill_dir); + if (versions.length === 0) { + continue; + } + + const amendmentLog = versioning.getEvolutionLog(skill.skill_dir, 'amendments'); + const reasonByVersion = new Map(); + for (const entry of amendmentLog) { + if (entry.version && entry.reason) { + reasonByVersion.set(entry.version, entry.reason); + } + } + + skillVersions.push({ + skill_id: skillId, + versions: versions.map(v => ({ + version: v.version, + created_at: v.created_at, + reason: reasonByVersion.get(v.version) || null, + })), + }); + } + + skillVersions.sort((a, b) => a.skill_id.localeCompare(b.skill_id)); + + const lines = []; + if (skillVersions.length === 0) { + lines.push('No version history available.'); + } else { + for (const skill of skillVersions) { + lines.push(skill.skill_id); + for (const version of skill.versions) { + const date = version.created_at ? version.created_at.slice(0, 10) : '-'; + const reason = version.reason || '-'; + lines.push(` v${version.version} \u2500\u2500 ${date} \u2500\u2500 ${reason}`); + } + } + } + + return { + text: panelBox('Version History', lines, width), + data: { skills: skillVersions }, + }; +} + +function renderDashboard(options = {}) { + const now = options.now || new Date().toISOString(); + const nowMs = Date.parse(now); + if (Number.isNaN(nowMs)) { + throw new Error(`Invalid now timestamp: ${now}`); + } + + const dashboardOptions = { ...options, now }; + const records = tracker.readSkillExecutionRecords(dashboardOptions); + const skillsById = health.discoverSkills(dashboardOptions); + const report = health.collectSkillHealth(dashboardOptions); + const summary = health.summarizeHealthReport(report); + + const panelRenderers = { + 'success-rate': () => renderSuccessRatePanel(records, report.skills, dashboardOptions), + 'failures': () => renderFailureClusterPanel(records, dashboardOptions), + 'amendments': () => renderAmendmentPanel(skillsById, dashboardOptions), + 'versions': () => renderVersionTimelinePanel(skillsById, dashboardOptions), + }; + + const selectedPanel = options.panel || null; + if (selectedPanel && !VALID_PANELS.has(selectedPanel)) { + throw new Error(`Unknown panel: ${selectedPanel}. Valid panels: ${Array.from(VALID_PANELS).join(', ')}`); + } + + const panels = {}; + const textParts = []; + + const header = [ + 'ECC Skill Health Dashboard', + `Generated: ${now}`, + `Skills: ${summary.total_skills} total, ${summary.healthy_skills} healthy, ${summary.declining_skills} declining`, + '', + ]; + + textParts.push(header.join('\n')); + + if (selectedPanel) { + const result = panelRenderers[selectedPanel](); + panels[selectedPanel] = result.data; + textParts.push(result.text); + } else { + for (const [panelName, renderer] of Object.entries(panelRenderers)) { + const result = renderer(); + panels[panelName] = result.data; + textParts.push(result.text); + } + } + + const text = textParts.join('\n\n') + '\n'; + const data = { + generated_at: now, + summary, + panels, + }; + + return { text, data }; +} + +module.exports = { + VALID_PANELS, + bucketByDay, + horizontalBar, + panelBox, + renderAmendmentPanel, + renderDashboard, + renderFailureClusterPanel, + renderSuccessRatePanel, + renderVersionTimelinePanel, + sparkline, +}; diff --git a/github_code/affaan-m__ECC/scripts/lib/skill-evolution/health.js b/github_code/affaan-m__ECC/scripts/lib/skill-evolution/health.js new file mode 100644 index 0000000000000000000000000000000000000000..309f160943cf27bc8ca95a88486400ad20bfb19d --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/skill-evolution/health.js @@ -0,0 +1,263 @@ +'use strict'; + +const fs = require('fs'); +const path = require('path'); + +const provenance = require('./provenance'); +const tracker = require('./tracker'); +const versioning = require('./versioning'); + +const DAY_IN_MS = 24 * 60 * 60 * 1000; +const PENDING_AMENDMENT_STATUSES = Object.freeze(new Set(['pending', 'proposed', 'queued', 'open'])); + +function roundRate(value) { + if (value === null) { + return null; + } + + return Math.round(value * 10000) / 10000; +} + +function formatRate(value) { + if (value === null) { + return 'n/a'; + } + + return `${Math.round(value * 100)}%`; +} + +function summarizeHealthReport(report) { + const totalSkills = report.skills.length; + const decliningSkills = report.skills.filter(skill => skill.declining).length; + const healthySkills = totalSkills - decliningSkills; + + return { + total_skills: totalSkills, + healthy_skills: healthySkills, + declining_skills: decliningSkills, + }; +} + +function listSkillsInRoot(rootPath) { + if (!rootPath || !fs.existsSync(rootPath)) { + return []; + } + + return fs.readdirSync(rootPath, { withFileTypes: true }) + .filter(entry => entry.isDirectory()) + .map(entry => ({ + skill_id: entry.name, + skill_dir: path.join(rootPath, entry.name), + })) + .filter(entry => fs.existsSync(path.join(entry.skill_dir, 'SKILL.md'))); +} + +function discoverSkills(options = {}) { + const roots = provenance.getSkillRoots(options); + const discoveredSkills = [ + ...listSkillsInRoot(options.skillsRoot || roots.curated).map(skill => ({ + ...skill, + skill_type: provenance.SKILL_TYPES.CURATED, + })), + ...listSkillsInRoot(options.learnedRoot || roots.learned).map(skill => ({ + ...skill, + skill_type: provenance.SKILL_TYPES.LEARNED, + })), + ...listSkillsInRoot(options.importedRoot || roots.imported).map(skill => ({ + ...skill, + skill_type: provenance.SKILL_TYPES.IMPORTED, + })), + ]; + + return discoveredSkills.reduce((skillsById, skill) => { + if (!skillsById.has(skill.skill_id)) { + skillsById.set(skill.skill_id, skill); + } + return skillsById; + }, new Map()); +} + +function calculateSuccessRate(records) { + if (records.length === 0) { + return null; + } + + const successfulRecords = records.filter(record => record.outcome === 'success').length; + return roundRate(successfulRecords / records.length); +} + +function filterRecordsWithinDays(records, nowMs, days) { + const cutoff = nowMs - (days * DAY_IN_MS); + return records.filter(record => { + const recordedAtMs = Date.parse(record.recorded_at); + return !Number.isNaN(recordedAtMs) && recordedAtMs >= cutoff && recordedAtMs <= nowMs; + }); +} + +function getFailureTrend(successRate7d, successRate30d, warnThreshold) { + if (successRate7d === null || successRate30d === null) { + return 'stable'; + } + + const delta = roundRate(successRate7d - successRate30d); + if (delta <= (-1 * warnThreshold)) { + return 'worsening'; + } + + if (delta >= warnThreshold) { + return 'improving'; + } + + return 'stable'; +} + +function countPendingAmendments(skillDir) { + if (!skillDir) { + return 0; + } + + return versioning.getEvolutionLog(skillDir, 'amendments') + .filter(entry => { + if (typeof entry.status === 'string') { + return PENDING_AMENDMENT_STATUSES.has(entry.status); + } + + return entry.event === 'proposal'; + }) + .length; +} + +function getLastRun(records) { + if (records.length === 0) { + return null; + } + + return records + .map(record => ({ + timestamp: record.recorded_at, + timeMs: Date.parse(record.recorded_at), + })) + .filter(entry => !Number.isNaN(entry.timeMs)) + .sort((left, right) => left.timeMs - right.timeMs) + .at(-1)?.timestamp || null; +} + +function collectSkillHealth(options = {}) { + const now = options.now || new Date().toISOString(); + const nowMs = Date.parse(now); + if (Number.isNaN(nowMs)) { + throw new Error(`Invalid now timestamp: ${now}`); + } + + const warnThreshold = typeof options.warnThreshold === 'number' + ? options.warnThreshold + : Number(options.warnThreshold || 0.1); + if (!Number.isFinite(warnThreshold) || warnThreshold < 0) { + throw new Error(`Invalid warn threshold: ${options.warnThreshold}`); + } + + const records = tracker.readSkillExecutionRecords(options); + const skillsById = discoverSkills(options); + const recordsBySkill = records.reduce((groupedRecords, record) => { + if (!groupedRecords.has(record.skill_id)) { + groupedRecords.set(record.skill_id, []); + } + + groupedRecords.get(record.skill_id).push(record); + return groupedRecords; + }, new Map()); + + for (const skillId of recordsBySkill.keys()) { + if (!skillsById.has(skillId)) { + skillsById.set(skillId, { + skill_id: skillId, + skill_dir: null, + skill_type: provenance.SKILL_TYPES.UNKNOWN, + }); + } + } + + const skills = Array.from(skillsById.values()) + .sort((left, right) => left.skill_id.localeCompare(right.skill_id)) + .map(skill => { + const skillRecords = recordsBySkill.get(skill.skill_id) || []; + const records7d = filterRecordsWithinDays(skillRecords, nowMs, 7); + const records30d = filterRecordsWithinDays(skillRecords, nowMs, 30); + const successRate7d = calculateSuccessRate(records7d); + const successRate30d = calculateSuccessRate(records30d); + const currentVersionNumber = skill.skill_dir ? versioning.getCurrentVersion(skill.skill_dir) : 0; + const failureTrend = getFailureTrend(successRate7d, successRate30d, warnThreshold); + + return { + skill_id: skill.skill_id, + skill_type: skill.skill_type, + current_version: currentVersionNumber > 0 ? `v${currentVersionNumber}` : null, + pending_amendments: countPendingAmendments(skill.skill_dir), + success_rate_7d: successRate7d, + success_rate_30d: successRate30d, + failure_trend: failureTrend, + declining: failureTrend === 'worsening', + last_run: getLastRun(skillRecords), + run_count_7d: records7d.length, + run_count_30d: records30d.length, + }; + }); + + return { + generated_at: now, + warn_threshold: warnThreshold, + skills, + }; +} + +function formatHealthReport(report, options = {}) { + if (options.json) { + return `${JSON.stringify(report, null, 2)}\n`; + } + + const summary = summarizeHealthReport(report); + + if (!report.skills.length) { + return [ + 'ECC skill health', + `Generated: ${report.generated_at}`, + '', + 'No skill execution records found.', + '', + ].join('\n'); + } + + const lines = [ + 'ECC skill health', + `Generated: ${report.generated_at}`, + `Skills: ${summary.total_skills} total, ${summary.healthy_skills} healthy, ${summary.declining_skills} declining`, + '', + 'skill version 7d 30d trend pending last run', + '--------------------------------------------------------------------------', + ]; + + for (const skill of report.skills) { + const statusLabel = skill.declining ? '!' : ' '; + lines.push([ + `${statusLabel}${skill.skill_id}`.padEnd(16), + String(skill.current_version || '-').padEnd(9), + formatRate(skill.success_rate_7d).padEnd(6), + formatRate(skill.success_rate_30d).padEnd(6), + skill.failure_trend.padEnd(11), + String(skill.pending_amendments).padEnd(9), + skill.last_run || '-', + ].join(' ')); + } + + return `${lines.join('\n')}\n`; +} + +module.exports = { + PENDING_AMENDMENT_STATUSES, + calculateSuccessRate, + collectSkillHealth, + discoverSkills, + filterRecordsWithinDays, + formatHealthReport, + summarizeHealthReport, +}; diff --git a/github_code/affaan-m__ECC/scripts/lib/skill-evolution/index.js b/github_code/affaan-m__ECC/scripts/lib/skill-evolution/index.js new file mode 100644 index 0000000000000000000000000000000000000000..baed650cc0534bd3cfa5991910e126e52faff87a --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/skill-evolution/index.js @@ -0,0 +1,20 @@ +'use strict'; + +const provenance = require('./provenance'); +const versioning = require('./versioning'); +const tracker = require('./tracker'); +const health = require('./health'); +const dashboard = require('./dashboard'); + +module.exports = { + ...provenance, + ...versioning, + ...tracker, + ...health, + ...dashboard, + provenance, + versioning, + tracker, + health, + dashboard, +}; diff --git a/github_code/affaan-m__ECC/scripts/lib/skill-evolution/provenance.js b/github_code/affaan-m__ECC/scripts/lib/skill-evolution/provenance.js new file mode 100644 index 0000000000000000000000000000000000000000..1062514a39059819ec1971d3be8b8751a6f077c7 --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/skill-evolution/provenance.js @@ -0,0 +1,187 @@ +'use strict'; + +const fs = require('fs'); +const os = require('os'); +const path = require('path'); + +const { ensureDir } = require('../utils'); + +const PROVENANCE_FILE_NAME = '.provenance.json'; +const SKILL_TYPES = Object.freeze({ + CURATED: 'curated', + LEARNED: 'learned', + IMPORTED: 'imported', + UNKNOWN: 'unknown', +}); + +function resolveRepoRoot(repoRoot) { + if (repoRoot) { + return path.resolve(repoRoot); + } + + return path.resolve(__dirname, '..', '..', '..'); +} + +function resolveHomeDir(homeDir) { + return homeDir ? path.resolve(homeDir) : os.homedir(); +} + +function normalizeSkillDir(skillPath) { + if (!skillPath || typeof skillPath !== 'string') { + throw new Error('skillPath is required'); + } + + const resolvedPath = path.resolve(skillPath); + if (path.basename(resolvedPath) === 'SKILL.md') { + return path.dirname(resolvedPath); + } + + return resolvedPath; +} + +function isWithinRoot(targetPath, rootPath) { + const relativePath = path.relative(rootPath, targetPath); + return relativePath === '' || ( + !relativePath.startsWith('..') + && !path.isAbsolute(relativePath) + ); +} + +function getSkillRoots(options = {}) { + const repoRoot = resolveRepoRoot(options.repoRoot); + const homeDir = resolveHomeDir(options.homeDir); + + return { + curated: path.join(repoRoot, 'skills'), + learned: path.join(homeDir, '.claude', 'skills', 'learned'), + imported: path.join(homeDir, '.claude', 'skills', 'imported'), + }; +} + +function classifySkillPath(skillPath, options = {}) { + const skillDir = normalizeSkillDir(skillPath); + const roots = getSkillRoots(options); + + if (isWithinRoot(skillDir, roots.curated)) { + return SKILL_TYPES.CURATED; + } + + if (isWithinRoot(skillDir, roots.learned)) { + return SKILL_TYPES.LEARNED; + } + + if (isWithinRoot(skillDir, roots.imported)) { + return SKILL_TYPES.IMPORTED; + } + + return SKILL_TYPES.UNKNOWN; +} + +function requiresProvenance(skillPath, options = {}) { + const skillType = classifySkillPath(skillPath, options); + return skillType === SKILL_TYPES.LEARNED || skillType === SKILL_TYPES.IMPORTED; +} + +function getProvenancePath(skillPath) { + return path.join(normalizeSkillDir(skillPath), PROVENANCE_FILE_NAME); +} + +function isIsoTimestamp(value) { + if (typeof value !== 'string' || value.trim().length === 0) { + return false; + } + + const timestamp = Date.parse(value); + return !Number.isNaN(timestamp); +} + +function validateProvenance(record) { + const errors = []; + + if (!record || typeof record !== 'object' || Array.isArray(record)) { + errors.push('provenance record must be an object'); + return { + valid: false, + errors, + }; + } + + if (typeof record.source !== 'string' || record.source.trim().length === 0) { + errors.push('source is required'); + } + + if (!isIsoTimestamp(record.created_at)) { + errors.push('created_at must be an ISO timestamp'); + } + + if (typeof record.confidence !== 'number' || Number.isNaN(record.confidence)) { + errors.push('confidence must be a number'); + } else if (record.confidence < 0 || record.confidence > 1) { + errors.push('confidence must be between 0 and 1'); + } + + if (typeof record.author !== 'string' || record.author.trim().length === 0) { + errors.push('author is required'); + } + + return { + valid: errors.length === 0, + errors, + }; +} + +function assertValidProvenance(record) { + const validation = validateProvenance(record); + if (!validation.valid) { + throw new Error(`Invalid provenance metadata: ${validation.errors.join('; ')}`); + } +} + +function readProvenance(skillPath, options = {}) { + const skillDir = normalizeSkillDir(skillPath); + const provenancePath = getProvenancePath(skillDir); + const provenanceRequired = options.required === true || requiresProvenance(skillDir, options); + + if (!fs.existsSync(provenancePath)) { + if (provenanceRequired) { + throw new Error(`Missing provenance metadata for ${skillDir}`); + } + + return null; + } + + const record = JSON.parse(fs.readFileSync(provenancePath, 'utf8')); + assertValidProvenance(record); + return record; +} + +function writeProvenance(skillPath, record, options = {}) { + const skillDir = normalizeSkillDir(skillPath); + + if (!requiresProvenance(skillDir, options)) { + throw new Error(`Provenance metadata is only required for learned or imported skills: ${skillDir}`); + } + + assertValidProvenance(record); + + const provenancePath = getProvenancePath(skillDir); + ensureDir(skillDir); + fs.writeFileSync(provenancePath, `${JSON.stringify(record, null, 2)}\n`, 'utf8'); + + return { + path: provenancePath, + record: { ...record }, + }; +} + +module.exports = { + PROVENANCE_FILE_NAME, + SKILL_TYPES, + classifySkillPath, + getProvenancePath, + getSkillRoots, + readProvenance, + requiresProvenance, + validateProvenance, + writeProvenance, +}; diff --git a/github_code/affaan-m__ECC/scripts/lib/skill-evolution/tracker.js b/github_code/affaan-m__ECC/scripts/lib/skill-evolution/tracker.js new file mode 100644 index 0000000000000000000000000000000000000000..0ea0ba1ccf862ace62f8a4ba708e6de9a7f142d5 --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/skill-evolution/tracker.js @@ -0,0 +1,196 @@ +'use strict'; + +const fs = require('fs'); +const os = require('os'); +const path = require('path'); + +const { ensureDir } = require('../utils'); + +const VALID_OUTCOMES = new Set(['success', 'failure', 'partial']); +const VALID_FEEDBACK = new Set(['accepted', 'corrected', 'rejected']); + +// Retention bound for the JSONL sink. The dashboard only aggregates recent +// runs, so an unbounded append-only file is pure cost. Trim from the front +// once the file grows past the cap. +const MAX_RUN_RECORDS = 5000; +// Owner-only. The sink lives under the user's home and is local telemetry; +// nothing else on the machine needs to read it. +const RUNS_FILE_MODE = 0o600; + +function resolveHomeDir(homeDir) { + return homeDir ? path.resolve(homeDir) : os.homedir(); +} + +function getRunsFilePath(options = {}) { + if (options.runsFilePath) { + return path.resolve(options.runsFilePath); + } + + return path.join(resolveHomeDir(options.homeDir), '.claude', 'state', 'skill-runs.jsonl'); +} + +function toNullableNumber(value, fieldName) { + if (value === null || typeof value === 'undefined') { + return null; + } + + const numericValue = Number(value); + if (!Number.isFinite(numericValue)) { + throw new Error(`${fieldName} must be a number`); + } + + return numericValue; +} + +function normalizeExecutionRecord(input, options = {}) { + if (!input || typeof input !== 'object' || Array.isArray(input)) { + throw new Error('skill execution payload must be an object'); + } + + const skillId = input.skill_id || input.skillId; + const skillVersion = input.skill_version || input.skillVersion; + const taskDescription = input.task_description || input.task_attempted || input.taskAttempted; + const outcome = input.outcome; + const recordedAt = input.recorded_at || options.now || new Date().toISOString(); + const userFeedback = input.user_feedback || input.userFeedback || null; + + if (typeof skillId !== 'string' || skillId.trim().length === 0) { + throw new Error('skill_id is required'); + } + + if (typeof skillVersion !== 'string' || skillVersion.trim().length === 0) { + throw new Error('skill_version is required'); + } + + if (typeof taskDescription !== 'string' || taskDescription.trim().length === 0) { + throw new Error('task_description is required'); + } + + if (!VALID_OUTCOMES.has(outcome)) { + throw new Error('outcome must be one of success, failure, or partial'); + } + + if (userFeedback !== null && !VALID_FEEDBACK.has(userFeedback)) { + throw new Error('user_feedback must be accepted, corrected, rejected, or null'); + } + + if (Number.isNaN(Date.parse(recordedAt))) { + throw new Error('recorded_at must be an ISO timestamp'); + } + + return { + skill_id: skillId, + skill_version: skillVersion, + task_description: taskDescription, + outcome, + failure_reason: input.failure_reason || input.failureReason || null, + tokens_used: toNullableNumber(input.tokens_used ?? input.tokensUsed, 'tokens_used'), + duration_ms: toNullableNumber(input.duration_ms ?? input.durationMs, 'duration_ms'), + user_feedback: userFeedback, + recorded_at: recordedAt, + }; +} + +function readJsonl(filePath) { + if (!fs.existsSync(filePath)) { + return []; + } + + return fs.readFileSync(filePath, 'utf8') + .split('\n') + .map(line => line.trim()) + .filter(Boolean) + .reduce((rows, line) => { + try { + rows.push(JSON.parse(line)); + } catch { + // Ignore malformed rows so analytics remain best-effort. + } + return rows; + }, []); +} + +// Append one record to the JSONL sink with owner-only permissions, then +// enforce the retention cap. `fs.appendFileSync`'s mode only applies when it +// creates the file, so an existing world-readable sink is chmod'd on the way +// past — cheap, and it repairs files written before this bound existed. +function appendRunRecord(runsFilePath, record, options = {}) { + const maxRecords = Number.isInteger(options.maxRecords) && options.maxRecords > 0 + ? options.maxRecords + : MAX_RUN_RECORDS; + + ensureDir(path.dirname(runsFilePath)); + fs.appendFileSync(runsFilePath, `${JSON.stringify(record)}\n`, { encoding: 'utf8', mode: RUNS_FILE_MODE }); + + try { + fs.chmodSync(runsFilePath, RUNS_FILE_MODE); + } catch { + // Windows and some mounts do not support POSIX modes; the record still lands. + } + + pruneRunRecords(runsFilePath, maxRecords); +} + +// Keep only the newest `maxRecords` lines. Rewrites the whole file, which is +// fine because the file is bounded by this very cap; it only runs on the +// appends that actually cross the line. +function pruneRunRecords(runsFilePath, maxRecords) { + try { + const lines = fs.readFileSync(runsFilePath, 'utf8').split('\n').filter(Boolean); + if (lines.length <= maxRecords) { + return; + } + fs.writeFileSync( + runsFilePath, + `${lines.slice(-maxRecords).join('\n')}\n`, + { encoding: 'utf8', mode: RUNS_FILE_MODE } + ); + } catch { + // Retention is best-effort; never fail a recorded run over it. + } +} + +function recordSkillExecution(input, options = {}) { + const record = normalizeExecutionRecord(input, options); + + if (options.stateStore && typeof options.stateStore.recordSkillExecution === 'function') { + try { + const result = options.stateStore.recordSkillExecution(record); + return { + storage: 'state-store', + record, + result, + }; + } catch { + // Fall back to JSONL until the formal state-store exists on this branch. + } + } + + const runsFilePath = getRunsFilePath(options); + appendRunRecord(runsFilePath, record, options); + + return { + storage: 'jsonl', + path: runsFilePath, + record, + }; +} + +function readSkillExecutionRecords(options = {}) { + if (options.stateStore && typeof options.stateStore.listSkillExecutionRecords === 'function') { + return options.stateStore.listSkillExecutionRecords(); + } + + return readJsonl(getRunsFilePath(options)); +} + +module.exports = { + MAX_RUN_RECORDS, + RUNS_FILE_MODE, + VALID_FEEDBACK, + VALID_OUTCOMES, + getRunsFilePath, + normalizeExecutionRecord, + readSkillExecutionRecords, + recordSkillExecution, +}; diff --git a/github_code/affaan-m__ECC/scripts/lib/skill-evolution/versioning.js b/github_code/affaan-m__ECC/scripts/lib/skill-evolution/versioning.js new file mode 100644 index 0000000000000000000000000000000000000000..6aa7a932d09bb01996894ee0cbff40c299e7bd87 --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/skill-evolution/versioning.js @@ -0,0 +1,237 @@ +'use strict'; + +const fs = require('fs'); +const path = require('path'); + +const { appendFile, ensureDir } = require('../utils'); + +const VERSION_DIRECTORY_NAME = '.versions'; +const EVOLUTION_DIRECTORY_NAME = '.evolution'; +const EVOLUTION_LOG_TYPES = Object.freeze([ + 'observations', + 'inspections', + 'amendments', +]); + +function normalizeSkillDir(skillPath) { + if (!skillPath || typeof skillPath !== 'string') { + throw new Error('skillPath is required'); + } + + const resolvedPath = path.resolve(skillPath); + if (path.basename(resolvedPath) === 'SKILL.md') { + return path.dirname(resolvedPath); + } + + return resolvedPath; +} + +function getSkillFilePath(skillPath) { + return path.join(normalizeSkillDir(skillPath), 'SKILL.md'); +} + +function ensureSkillExists(skillPath) { + const skillFilePath = getSkillFilePath(skillPath); + if (!fs.existsSync(skillFilePath)) { + throw new Error(`Skill file not found: ${skillFilePath}`); + } + + return skillFilePath; +} + +function getVersionsDir(skillPath) { + return path.join(normalizeSkillDir(skillPath), VERSION_DIRECTORY_NAME); +} + +function getEvolutionDir(skillPath) { + return path.join(normalizeSkillDir(skillPath), EVOLUTION_DIRECTORY_NAME); +} + +function getEvolutionLogPath(skillPath, logType) { + if (!EVOLUTION_LOG_TYPES.includes(logType)) { + throw new Error(`Unknown evolution log type: ${logType}`); + } + + return path.join(getEvolutionDir(skillPath), `${logType}.jsonl`); +} + +function ensureSkillVersioning(skillPath) { + ensureSkillExists(skillPath); + + const versionsDir = getVersionsDir(skillPath); + const evolutionDir = getEvolutionDir(skillPath); + + ensureDir(versionsDir); + ensureDir(evolutionDir); + + for (const logType of EVOLUTION_LOG_TYPES) { + const logPath = getEvolutionLogPath(skillPath, logType); + if (!fs.existsSync(logPath)) { + fs.writeFileSync(logPath, '', 'utf8'); + } + } + + return { + versionsDir, + evolutionDir, + }; +} + +function parseVersionNumber(fileName) { + const match = /^v(\d+)\.md$/.exec(fileName); + if (!match) { + return null; + } + + return Number(match[1]); +} + +function listVersions(skillPath) { + const versionsDir = getVersionsDir(skillPath); + if (!fs.existsSync(versionsDir)) { + return []; + } + + return fs.readdirSync(versionsDir) + .map(fileName => { + const version = parseVersionNumber(fileName); + if (version === null) { + return null; + } + + const filePath = path.join(versionsDir, fileName); + const stats = fs.statSync(filePath); + + return { + version, + path: filePath, + created_at: stats.mtime.toISOString(), + }; + }) + .filter(Boolean) + .sort((left, right) => left.version - right.version); +} + +function getCurrentVersion(skillPath) { + const skillFilePath = getSkillFilePath(skillPath); + if (!fs.existsSync(skillFilePath)) { + return 0; + } + + const versions = listVersions(skillPath); + if (versions.length === 0) { + return 1; + } + + return versions[versions.length - 1].version; +} + +function appendEvolutionRecord(skillPath, logType, record) { + ensureSkillVersioning(skillPath); + appendFile(getEvolutionLogPath(skillPath, logType), `${JSON.stringify(record)}\n`); + return { ...record }; +} + +function readJsonl(filePath) { + if (!fs.existsSync(filePath)) { + return []; + } + + return fs.readFileSync(filePath, 'utf8') + .split('\n') + .map(line => line.trim()) + .filter(Boolean) + .reduce((rows, line) => { + try { + rows.push(JSON.parse(line)); + } catch { + // Ignore malformed rows so the log remains append-only and resilient. + } + return rows; + }, []); +} + +function getEvolutionLog(skillPath, logType) { + return readJsonl(getEvolutionLogPath(skillPath, logType)); +} + +function createVersion(skillPath, options = {}) { + const skillFilePath = ensureSkillExists(skillPath); + ensureSkillVersioning(skillPath); + + const versions = listVersions(skillPath); + const nextVersion = versions.length === 0 ? 1 : versions[versions.length - 1].version + 1; + const snapshotPath = path.join(getVersionsDir(skillPath), `v${nextVersion}.md`); + const skillContent = fs.readFileSync(skillFilePath, 'utf8'); + const createdAt = options.timestamp || new Date().toISOString(); + + fs.writeFileSync(snapshotPath, skillContent, 'utf8'); + appendEvolutionRecord(skillPath, 'amendments', { + event: 'snapshot', + version: nextVersion, + reason: options.reason || null, + author: options.author || null, + status: 'applied', + created_at: createdAt, + }); + + return { + version: nextVersion, + path: snapshotPath, + created_at: createdAt, + }; +} + +function rollbackTo(skillPath, targetVersion, options = {}) { + const normalizedTargetVersion = Number(targetVersion); + if (!Number.isInteger(normalizedTargetVersion) || normalizedTargetVersion <= 0) { + throw new Error(`Invalid target version: ${targetVersion}`); + } + + ensureSkillExists(skillPath); + ensureSkillVersioning(skillPath); + + const targetPath = path.join(getVersionsDir(skillPath), `v${normalizedTargetVersion}.md`); + if (!fs.existsSync(targetPath)) { + throw new Error(`Version not found: v${normalizedTargetVersion}`); + } + + const currentVersion = getCurrentVersion(skillPath); + const targetContent = fs.readFileSync(targetPath, 'utf8'); + fs.writeFileSync(getSkillFilePath(skillPath), targetContent, 'utf8'); + + const createdVersion = createVersion(skillPath, { + timestamp: options.timestamp, + reason: options.reason || `rollback to v${normalizedTargetVersion}`, + author: options.author || null, + }); + + appendEvolutionRecord(skillPath, 'amendments', { + event: 'rollback', + version: createdVersion.version, + source_version: currentVersion, + target_version: normalizedTargetVersion, + reason: options.reason || null, + author: options.author || null, + status: 'applied', + created_at: options.timestamp || new Date().toISOString(), + }); + + return createdVersion; +} + +module.exports = { + EVOLUTION_DIRECTORY_NAME, + EVOLUTION_LOG_TYPES, + VERSION_DIRECTORY_NAME, + appendEvolutionRecord, + createVersion, + ensureSkillVersioning, + getCurrentVersion, + getEvolutionDir, + getEvolutionLog, + getEvolutionLogPath, + getVersionsDir, + listVersions, + rollbackTo, +}; diff --git a/github_code/affaan-m__ECC/scripts/lib/skill-improvement/amendify.js b/github_code/affaan-m__ECC/scripts/lib/skill-improvement/amendify.js new file mode 100644 index 0000000000000000000000000000000000000000..c95f0e91481b4a20d13107923f502258e7375391 --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/skill-improvement/amendify.js @@ -0,0 +1,89 @@ +'use strict'; + +const { buildSkillHealthReport } = require('./health'); + +const AMENDMENT_SCHEMA_VERSION = 'ecc.skill-amendment-proposal.v1'; + +function createProposalId(skillId) { + return `amend-${skillId}-${Date.now()}`; +} + +function summarizePatchPreview(skillId, health) { + const lines = [ + '## Failure-Driven Amendments', + '', + `- Focus skill routing for \`${skillId}\` when tasks match the proven success cases.`, + ]; + + if (health.recurringErrors[0]) { + lines.push(`- Add explicit guardrails for recurring failure: ${health.recurringErrors[0].error}.`); + } + + if (health.recurringTasks[0]) { + lines.push(`- Add an example workflow for task pattern: ${health.recurringTasks[0].task}.`); + } + + if (health.recurringFeedback[0]) { + lines.push(`- Address repeated user feedback: ${health.recurringFeedback[0].feedback}.`); + } + + lines.push('- Add a verification checklist before declaring the skill output complete.'); + return lines.join('\n'); +} + +function proposeSkillAmendment(skillId, records, options = {}) { + const report = buildSkillHealthReport(records, { + ...options, + skillId, + minFailureCount: options.minFailureCount || 1 + }); + const [health] = report.skills; + + if (!health || health.failures === 0) { + return { + schemaVersion: AMENDMENT_SCHEMA_VERSION, + skill: { + id: skillId, + path: null + }, + status: 'insufficient-evidence', + rationale: ['No failed observations were available for this skill.'], + patch: null + }; + } + + const preview = summarizePatchPreview(skillId, health); + + return { + schemaVersion: AMENDMENT_SCHEMA_VERSION, + proposalId: createProposalId(skillId), + generatedAt: new Date().toISOString(), + status: 'proposed', + skill: { + id: skillId, + path: health.skill.path || null + }, + evidence: { + totalRuns: health.totalRuns, + failures: health.failures, + successRate: health.successRate, + recurringErrors: health.recurringErrors, + recurringTasks: health.recurringTasks, + recurringFeedback: health.recurringFeedback + }, + rationale: [ + 'Proposals are generated from repeated failed runs rather than a single anecdotal error.', + 'The suggested patch is additive so the original SKILL.md intent remains auditable.' + ], + patch: { + format: 'markdown-fragment', + targetPath: health.skill.path || `skills/${skillId}/SKILL.md`, + preview + } + }; +} + +module.exports = { + AMENDMENT_SCHEMA_VERSION, + proposeSkillAmendment +}; diff --git a/github_code/affaan-m__ECC/scripts/lib/skill-improvement/evaluate.js b/github_code/affaan-m__ECC/scripts/lib/skill-improvement/evaluate.js new file mode 100644 index 0000000000000000000000000000000000000000..f45023d549b0fc5ad0ac96ac1fef3eb5306bd5d9 --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/skill-improvement/evaluate.js @@ -0,0 +1,59 @@ +'use strict'; + +const EVALUATION_SCHEMA_VERSION = 'ecc.skill-evaluation.v1'; + +function roundRate(value) { + return Math.round(value * 1000) / 1000; +} + +function summarize(records) { + const runs = records.length; + const successes = records.filter(record => record.outcome && record.outcome.success).length; + const failures = runs - successes; + return { + runs, + successes, + failures, + successRate: runs > 0 ? roundRate(successes / runs) : 0 + }; +} + +function buildSkillEvaluationScaffold(skillId, records, options = {}) { + const minimumRunsPerVariant = options.minimumRunsPerVariant || 2; + const amendmentId = options.amendmentId || null; + const filtered = records.filter(record => record.skill && record.skill.id === skillId); + const baseline = filtered.filter(record => !record.run || record.run.variant !== 'amended'); + const amended = filtered.filter(record => record.run && record.run.variant === 'amended') + .filter(record => !amendmentId || record.run.amendmentId === amendmentId); + + const baselineSummary = summarize(baseline); + const amendedSummary = summarize(amended); + const delta = { + successRate: roundRate(amendedSummary.successRate - baselineSummary.successRate), + failures: amendedSummary.failures - baselineSummary.failures + }; + + let recommendation = 'insufficient-data'; + if (baselineSummary.runs >= minimumRunsPerVariant && amendedSummary.runs >= minimumRunsPerVariant) { + recommendation = delta.successRate > 0 ? 'promote-amendment' : 'keep-baseline'; + } + + return { + schemaVersion: EVALUATION_SCHEMA_VERSION, + generatedAt: new Date().toISOString(), + skillId, + amendmentId, + gate: { + minimumRunsPerVariant + }, + baseline: baselineSummary, + amended: amendedSummary, + delta, + recommendation + }; +} + +module.exports = { + EVALUATION_SCHEMA_VERSION, + buildSkillEvaluationScaffold +}; diff --git a/github_code/affaan-m__ECC/scripts/lib/skill-improvement/health.js b/github_code/affaan-m__ECC/scripts/lib/skill-improvement/health.js new file mode 100644 index 0000000000000000000000000000000000000000..8aba59861e9bfc4c1e4263f103808c7999632663 --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/skill-improvement/health.js @@ -0,0 +1,118 @@ +'use strict'; + +const HEALTH_SCHEMA_VERSION = 'ecc.skill-health.v1'; + +function roundRate(value) { + return Math.round(value * 1000) / 1000; +} + +function rankCounts(values) { + return Array.from(values.entries()) + .map(([value, count]) => ({ value, count })) + .sort((left, right) => right.count - left.count || left.value.localeCompare(right.value)); +} + +function summarizeVariantRuns(records) { + return records.reduce((accumulator, record) => { + const key = record.run && record.run.variant ? record.run.variant : 'baseline'; + if (!accumulator[key]) { + accumulator[key] = { runs: 0, successes: 0, failures: 0 }; + } + + accumulator[key].runs += 1; + if (record.outcome && record.outcome.success) { + accumulator[key].successes += 1; + } else { + accumulator[key].failures += 1; + } + + return accumulator; + }, {}); +} + +function deriveSkillStatus(skillSummary, options = {}) { + const minFailureCount = options.minFailureCount || 2; + if (skillSummary.failures >= minFailureCount) { + return 'failing'; + } + + if (skillSummary.failures > 0) { + return 'watch'; + } + + return 'healthy'; +} + +function buildSkillHealthReport(records, options = {}) { + const filterSkillId = options.skillId || null; + const filtered = filterSkillId + ? records.filter(record => record.skill && record.skill.id === filterSkillId) + : records.slice(); + + const grouped = filtered.reduce((accumulator, record) => { + const skillId = record.skill.id; + if (!accumulator.has(skillId)) { + accumulator.set(skillId, []); + } + accumulator.get(skillId).push(record); + return accumulator; + }, new Map()); + + const skills = Array.from(grouped.entries()) + .map(([skillId, skillRecords]) => { + const successes = skillRecords.filter(record => record.outcome && record.outcome.success).length; + const failures = skillRecords.length - successes; + const recurringErrors = new Map(); + const recurringTasks = new Map(); + const recurringFeedback = new Map(); + + skillRecords.forEach(record => { + if (!record.outcome || record.outcome.success) { + return; + } + + if (record.outcome.error) { + recurringErrors.set(record.outcome.error, (recurringErrors.get(record.outcome.error) || 0) + 1); + } + if (record.task) { + recurringTasks.set(record.task, (recurringTasks.get(record.task) || 0) + 1); + } + if (record.outcome.feedback) { + recurringFeedback.set(record.outcome.feedback, (recurringFeedback.get(record.outcome.feedback) || 0) + 1); + } + }); + + const summary = { + skill: { + id: skillId, + path: skillRecords[0].skill.path || null + }, + totalRuns: skillRecords.length, + successes, + failures, + successRate: skillRecords.length > 0 ? roundRate(successes / skillRecords.length) : 0, + status: 'healthy', + recurringErrors: rankCounts(recurringErrors).map(entry => ({ error: entry.value, count: entry.count })), + recurringTasks: rankCounts(recurringTasks).map(entry => ({ task: entry.value, count: entry.count })), + recurringFeedback: rankCounts(recurringFeedback).map(entry => ({ feedback: entry.value, count: entry.count })), + variants: summarizeVariantRuns(skillRecords) + }; + + summary.status = deriveSkillStatus(summary, options); + return summary; + }) + .sort((left, right) => right.failures - left.failures || left.skill.id.localeCompare(right.skill.id)); + + return { + schemaVersion: HEALTH_SCHEMA_VERSION, + generatedAt: new Date().toISOString(), + totalObservations: filtered.length, + skillCount: skills.length, + skills + }; +} + +module.exports = { + HEALTH_SCHEMA_VERSION, + buildSkillHealthReport +}; diff --git a/github_code/affaan-m__ECC/scripts/lib/skill-improvement/observations.js b/github_code/affaan-m__ECC/scripts/lib/skill-improvement/observations.js new file mode 100644 index 0000000000000000000000000000000000000000..1544c4b9fa899b159abe285dd2a7137e14a87041 --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/skill-improvement/observations.js @@ -0,0 +1,108 @@ +'use strict'; + +const fs = require('fs'); +const path = require('path'); +const os = require('os'); + +const OBSERVATION_SCHEMA_VERSION = 'ecc.skill-observation.v1'; + +function resolveProjectRoot(options = {}) { + return path.resolve(options.projectRoot || options.cwd || process.cwd()); +} + +function getSkillTelemetryRoot(options = {}) { + return path.join(resolveProjectRoot(options), '.claude', 'ecc', 'skills'); +} + +function getSkillObservationsPath(options = {}) { + return path.join(getSkillTelemetryRoot(options), 'observations.jsonl'); +} + +function ensureString(value, label) { + if (typeof value !== 'string' || value.trim().length === 0) { + throw new Error(`${label} must be a non-empty string`); + } + + return value.trim(); +} + +function createObservationId() { + return `obs-${Date.now()}-${process.pid}-${Math.random().toString(16).slice(2, 8)}`; +} + +function createSkillObservation(input) { + const task = ensureString(input.task, 'task'); + const skillId = ensureString(input.skill && input.skill.id, 'skill.id'); + const skillPath = typeof input.skill.path === 'string' && input.skill.path.trim().length > 0 + ? input.skill.path.trim() + : null; + const success = Boolean(input.success); + const error = input.error === null || input.error === undefined ? null : String(input.error); + const feedback = input.feedback === null || input.feedback === undefined ? null : String(input.feedback); + const variant = typeof input.variant === 'string' && input.variant.trim().length > 0 + ? input.variant.trim() + : 'baseline'; + + return { + schemaVersion: OBSERVATION_SCHEMA_VERSION, + observationId: typeof input.observationId === 'string' && input.observationId.length > 0 + ? input.observationId + : createObservationId(), + timestamp: typeof input.timestamp === 'string' && input.timestamp.length > 0 + ? input.timestamp + : new Date().toISOString(), + task, + skill: { + id: skillId, + path: skillPath + }, + outcome: { + success, + status: success ? 'success' : 'failure', + error, + feedback + }, + run: { + variant, + amendmentId: input.amendmentId || null, + sessionId: input.sessionId || null, + source: input.source || 'manual' + } + }; +} + +function appendSkillObservation(observation, options = {}) { + const outputPath = getSkillObservationsPath(options); + fs.mkdirSync(path.dirname(outputPath), { recursive: true }); + fs.appendFileSync(outputPath, `${JSON.stringify(observation)}${os.EOL}`, 'utf8'); + return outputPath; +} + +function readSkillObservations(options = {}) { + const observationPath = path.resolve(options.observationsPath || getSkillObservationsPath(options)); + if (!fs.existsSync(observationPath)) { + return []; + } + + return fs.readFileSync(observationPath, 'utf8') + .split(/\r?\n/) + .filter(Boolean) + .map(line => { + try { + return JSON.parse(line); + } catch { + return null; + } + }) + .filter(record => record && record.schemaVersion === OBSERVATION_SCHEMA_VERSION); +} + +module.exports = { + OBSERVATION_SCHEMA_VERSION, + appendSkillObservation, + createSkillObservation, + getSkillObservationsPath, + getSkillTelemetryRoot, + readSkillObservations, + resolveProjectRoot +}; diff --git a/github_code/affaan-m__ECC/scripts/lib/state-store/index.js b/github_code/affaan-m__ECC/scripts/lib/state-store/index.js new file mode 100644 index 0000000000000000000000000000000000000000..49b6204d635330401ede6fd734c72f9588466f78 --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/state-store/index.js @@ -0,0 +1,367 @@ +'use strict'; + +const fs = require('fs'); +const crypto = require('crypto'); +const os = require('os'); +const path = require('path'); +const initSqlJs = require('sql.js'); + +const { applyMigrations, getAppliedMigrations } = require('./migrations'); +const { createQueryApi } = require('./queries'); +const { assertValidEntity, validateEntity } = require('./schema'); +const { + buildInstallStateStoreRecord, + projectInstallState, + reconcileCurrentInstallState, + reconcileInstallStateProjections, + removeInstallStateProjection, + summarizeProjectedInstallHealth, +} = require('./install-state-projection'); + +const DEFAULT_STATE_STORE_RELATIVE_PATH = path.join('.claude', 'ecc', 'state.db'); +const PRIVATE_DIRECTORY_MODE = 0o700; +const PRIVATE_FILE_MODE = 0o600; + +function stateStorePathError(targetPath, detail) { + return new Error(`Unsafe state-store path '${targetPath}': ${detail}`); +} + +function lstatIfPresent(targetPath) { + try { + return fs.lstatSync(targetPath); + } catch (error) { + if (error && error.code === 'ENOENT') { + return null; + } + throw error; + } +} + +function isAllowedPlatformSymlink(targetPath, stats) { + if (process.platform !== 'darwin' || !stats || stats.uid !== 0) { + return false; + } + + const allowedTargets = new Map([ + ['/var', '/private/var'], + ['/tmp', '/private/tmp'], + ['/etc', '/private/etc'], + ]); + const expectedTarget = allowedTargets.get(targetPath); + if (!expectedTarget) { + return false; + } + + try { + return fs.realpathSync(targetPath) === expectedTarget; + } catch (_error) { + return false; + } +} + +function assertNotSymlink(targetPath, stats) { + if (stats && stats.isSymbolicLink()) { + if (isAllowedPlatformSymlink(targetPath, stats)) { + return; + } + throw stateStorePathError(targetPath, 'a symlink is not allowed'); + } +} + +function ensurePrivateDirectory(directoryPath) { + const absolutePath = path.resolve(directoryPath); + const parsed = path.parse(absolutePath); + const segments = absolutePath.slice(parsed.root.length).split(path.sep).filter(Boolean); + let currentPath = parsed.root; + + for (const segment of segments) { + currentPath = path.join(currentPath, segment); + let stats = lstatIfPresent(currentPath); + assertNotSymlink(currentPath, stats); + + if (!stats) { + try { + fs.mkdirSync(currentPath, { mode: PRIVATE_DIRECTORY_MODE }); + } catch (error) { + if (!error || error.code !== 'EEXIST') { + throw error; + } + } + stats = fs.lstatSync(currentPath); + assertNotSymlink(currentPath, stats); + } + + if (!stats.isDirectory() && !isAllowedPlatformSymlink(currentPath, stats)) { + throw stateStorePathError(currentPath, 'an intermediate component is not a directory'); + } + } + + return absolutePath; +} + +function assertSafeDatabaseFile(dbPath) { + const stats = lstatIfPresent(dbPath); + assertNotSymlink(dbPath, stats); + if (stats && !stats.isFile()) { + throw stateStorePathError(dbPath, 'database path is not a regular file'); + } + return stats; +} + +function readDatabaseFile(dbPath) { + assertSafeDatabaseFile(dbPath); + const noFollow = fs.constants.O_NOFOLLOW || 0; + const fileDescriptor = fs.openSync(dbPath, fs.constants.O_RDONLY | noFollow); + try { + const stats = fs.fstatSync(fileDescriptor); + if (!stats.isFile()) { + throw stateStorePathError(dbPath, 'database path is not a regular file'); + } + return fs.readFileSync(fileDescriptor); + } finally { + fs.closeSync(fileDescriptor); + } +} + +function syncDirectory(directoryPath) { + if (process.platform === 'win32') { + return; + } + + let fileDescriptor; + try { + fileDescriptor = fs.openSync(directoryPath, fs.constants.O_RDONLY); + fs.fsyncSync(fileDescriptor); + } catch (_error) { + // Some filesystems do not permit directory fsync. The file was still + // atomically replaced and fsynced before this durability best effort. + } finally { + if (fileDescriptor !== undefined) { + fs.closeSync(fileDescriptor); + } + } +} + +function writeDatabaseFileAtomic(dbPath, data) { + const directoryPath = ensurePrivateDirectory(path.dirname(dbPath)); + assertSafeDatabaseFile(dbPath); + const temporaryPath = path.join( + directoryPath, + `.${path.basename(dbPath)}.${process.pid}.${crypto.randomBytes(8).toString('hex')}.tmp` + ); + const noFollow = fs.constants.O_NOFOLLOW || 0; + const flags = fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL | noFollow; + let fileDescriptor; + + try { + fileDescriptor = fs.openSync(temporaryPath, flags, PRIVATE_FILE_MODE); + fs.writeFileSync(fileDescriptor, data); + fs.fchmodSync(fileDescriptor, PRIVATE_FILE_MODE); + fs.fsyncSync(fileDescriptor); + fs.closeSync(fileDescriptor); + fileDescriptor = undefined; + + // A final-path symlink is never followed. If one appeared after this + // check, rename replaces the link itself rather than its target. + assertSafeDatabaseFile(dbPath); + fs.renameSync(temporaryPath, dbPath); + syncDirectory(directoryPath); + } finally { + if (fileDescriptor !== undefined) { + fs.closeSync(fileDescriptor); + } + try { + fs.unlinkSync(temporaryPath); + } catch (error) { + if (!error || error.code !== 'ENOENT') { + // Preserve the original persistence result. The temporary file is + // private, exclusively created, and never used as canonical state. + } + } + } +} + +function resolveStateStorePath(options = {}) { + if (options.dbPath) { + if (options.dbPath === ':memory:') { + return options.dbPath; + } + return path.resolve(options.dbPath); + } + + const homeDir = options.homeDir || process.env.HOME || os.homedir(); + return path.join(homeDir, DEFAULT_STATE_STORE_RELATIVE_PATH); +} + +/** + * Wraps a sql.js Database with a better-sqlite3-compatible API surface so + * that the rest of the state-store code (migrations.js, queries.js) can + * operate without knowing which driver is in use. + * + * IMPORTANT: sql.js db.export() implicitly ends any active transaction, so + * we must defer all disk writes until after the transaction commits. + */ +function wrapSqlJsDatabase(rawDb, dbPath) { + let inTransaction = false; + + function saveToDisk() { + if (dbPath === ':memory:' || inTransaction) { + return; + } + const data = rawDb.export(); + const buffer = Buffer.from(data); + writeDatabaseFileAtomic(dbPath, buffer); + } + + const db = { + exec(sql) { + rawDb.run(sql); + saveToDisk(); + }, + + pragma(pragmaStr) { + try { + rawDb.run(`PRAGMA ${pragmaStr}`); + } catch (_error) { + // Ignore unsupported pragmas (e.g. WAL for in-memory databases). + } + }, + + prepare(sql) { + return { + all(...positionalArgs) { + const stmt = rawDb.prepare(sql); + if (positionalArgs.length === 1 && typeof positionalArgs[0] !== 'object') { + stmt.bind([positionalArgs[0]]); + } else if (positionalArgs.length > 1) { + stmt.bind(positionalArgs); + } + + const rows = []; + while (stmt.step()) { + rows.push(stmt.getAsObject()); + } + stmt.free(); + return rows; + }, + + get(...positionalArgs) { + const stmt = rawDb.prepare(sql); + if (positionalArgs.length === 1 && typeof positionalArgs[0] !== 'object') { + stmt.bind([positionalArgs[0]]); + } else if (positionalArgs.length > 1) { + stmt.bind(positionalArgs); + } + + let row = null; + if (stmt.step()) { + row = stmt.getAsObject(); + } + stmt.free(); + return row; + }, + + run(namedParams) { + const stmt = rawDb.prepare(sql); + if (namedParams && typeof namedParams === 'object' && !Array.isArray(namedParams)) { + const sqlJsParams = {}; + for (const [key, value] of Object.entries(namedParams)) { + sqlJsParams[`@${key}`] = value === undefined ? null : value; + } + stmt.bind(sqlJsParams); + } + stmt.step(); + stmt.free(); + saveToDisk(); + }, + }; + }, + + transaction(fn) { + return (...args) => { + rawDb.run('BEGIN'); + inTransaction = true; + try { + const result = fn(...args); + rawDb.run('COMMIT'); + inTransaction = false; + saveToDisk(); + return result; + } catch (error) { + try { + rawDb.run('ROLLBACK'); + } catch (_rollbackError) { + // Transaction may already be rolled back. + } + inTransaction = false; + throw error; + } + }; + }, + + close() { + saveToDisk(); + rawDb.close(); + }, + }; + + return db; +} + +async function openDatabase(SQL, dbPath) { + if (dbPath !== ':memory:') { + ensurePrivateDirectory(path.dirname(dbPath)); + } + + let rawDb; + if (dbPath !== ':memory:' && assertSafeDatabaseFile(dbPath)) { + const fileBuffer = readDatabaseFile(dbPath); + rawDb = new SQL.Database(fileBuffer); + } else { + rawDb = new SQL.Database(); + } + + const db = wrapSqlJsDatabase(rawDb, dbPath); + db.pragma('foreign_keys = ON'); + try { + db.pragma('journal_mode = WAL'); + } catch (_error) { + // Some SQLite environments reject WAL for in-memory or readonly contexts. + } + return db; +} + +async function createStateStore(options = {}) { + const dbPath = resolveStateStorePath(options); + const SQL = await initSqlJs(); + const db = await openDatabase(SQL, dbPath); + const appliedMigrations = applyMigrations(db); + const queryApi = createQueryApi(db); + + return { + dbPath, + close() { + db.close(); + }, + getAppliedMigrations() { + return getAppliedMigrations(db); + }, + validateEntity, + assertValidEntity, + ...queryApi, + _database: db, + _migrations: appliedMigrations, + }; +} + +module.exports = { + DEFAULT_STATE_STORE_RELATIVE_PATH, + buildInstallStateStoreRecord, + createStateStore, + projectInstallState, + reconcileCurrentInstallState, + reconcileInstallStateProjections, + removeInstallStateProjection, + resolveStateStorePath, + summarizeProjectedInstallHealth, +}; diff --git a/github_code/affaan-m__ECC/scripts/lib/state-store/install-state-projection.js b/github_code/affaan-m__ECC/scripts/lib/state-store/install-state-projection.js new file mode 100644 index 0000000000000000000000000000000000000000..d63ba7911c23dc58b251b3fd0dd7acd248ec8fbd --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/state-store/install-state-projection.js @@ -0,0 +1,362 @@ +'use strict'; + +const path = require('path'); + +const MANAGED_FILE_HEALTH_CODES = new Set([ + 'missing-target-root', + 'unsafe-managed-destination', + 'unsafe-repair-source', + 'missing-managed-files', + 'drifted-managed-files', + 'missing-source-files', + 'unverified-managed-operations', +]); + +function cloneJsonValue(value) { + return value === undefined ? undefined : JSON.parse(JSON.stringify(value)); +} + +function buildInstallStateStoreRecord(state) { + if (!state || !state.target || !state.request || !state.resolution || !state.source) { + throw new Error('Invalid canonical install-state: required projection fields are missing'); + } + + return { + targetId: state.target.id, + targetRoot: state.target.root, + profile: state.request.profile ?? null, + modules: Array.isArray(state.resolution.selectedModules) + ? [...state.resolution.selectedModules] + : [], + operations: Array.isArray(state.operations) + ? state.operations.map(operation => cloneJsonValue(operation)) + : [], + installedAt: state.installedAt, + sourceVersion: state.source.repoVersion ?? null, + }; +} + +function warningFor(record, code, message) { + return { + code, + message, + targetId: record && record.adapter ? record.adapter.id : null, + targetRoot: record && record.targetRoot ? record.targetRoot : null, + installStatePath: record && record.installStatePath ? record.installStatePath : null, + }; +} + +function getRecordIdentity(record) { + if ( + !record + || !record.adapter + || typeof record.adapter.id !== 'string' + || record.adapter.id.length === 0 + || typeof record.targetRoot !== 'string' + || record.targetRoot.length === 0 + ) { + return null; + } + + return { + targetId: record.adapter.id, + targetRoot: record.targetRoot, + }; +} + +function pathsMatch(left, right) { + return typeof left === 'string' + && left.length > 0 + && typeof right === 'string' + && right.length > 0 + && path.resolve(left) === path.resolve(right); +} + +function stateMatchesDiscoveryRecord(state, record) { + return Boolean( + state + && state.target + && state.target.id === record.adapter.id + && pathsMatch(state.target.root, record.targetRoot) + && pathsMatch(state.target.installStatePath, record.installStatePath) + ); +} + +function projectInstallState(store, state) { + try { + const record = buildInstallStateStoreRecord(state); + store.upsertInstallState(record); + return { + status: 'projected', + record, + warning: null, + }; + } catch (error) { + return { + status: 'warning', + record: null, + warning: { + code: 'projection-write-failed', + message: error.message, + targetId: state && state.target ? state.target.id : null, + targetRoot: state && state.target ? state.target.root : null, + installStatePath: state && state.target ? state.target.installStatePath : null, + }, + }; + } +} + +function removeInstallStateProjection(store, identity) { + try { + return { + status: 'removed', + removed: store.deleteInstallState(identity), + warning: null, + }; + } catch (error) { + return { + status: 'warning', + removed: false, + warning: { + code: 'projection-delete-failed', + message: error.message, + targetId: identity && identity.targetId ? identity.targetId : null, + targetRoot: identity && identity.targetRoot ? identity.targetRoot : null, + installStatePath: null, + }, + }; + } +} + +function createReconciliationResult(discoveredCount) { + return { + status: 'ok', + discoveredCount, + projectedCount: 0, + removedCount: 0, + warningCount: 0, + warnings: [], + scopedTargets: [], + managedFileHealth: [], + }; +} + +function addWarning(result, warning) { + return { + ...result, + status: 'warning', + warningCount: result.warningCount + 1, + warnings: [...result.warnings, warning], + }; +} + +function removeDiscoverableProjection(store, identity, result) { + const removal = removeInstallStateProjection(store, identity); + if (removal.warning) { + return addWarning(result, removal.warning); + } + return { + ...result, + removedCount: result.removedCount + (removal.removed ? 1 : 0), + }; +} + +/** + * Reconcile only the identities enumerated by install target discovery. + * Canonical JSON files remain authoritative, and rows from other home or + * project scopes are deliberately left unchanged. + */ +function reconcileInstallStateProjections(store, discoveryRecords) { + const records = Array.isArray(discoveryRecords) ? discoveryRecords : []; + let result = { + ...createReconciliationResult(records.length), + scopedTargets: records.map(getRecordIdentity).filter(Boolean), + }; + + for (const record of records) { + const identity = getRecordIdentity(record); + if (!identity) { + result = addWarning(result, warningFor( + record, + 'invalid-discovery-record', + 'Install target discovery returned an invalid target identity' + )); + continue; + } + + if (!record.exists) { + result = removeDiscoverableProjection(store, identity, result); + continue; + } + + if (record.error || !record.state) { + result = removeDiscoverableProjection(store, identity, result); + result = addWarning(result, warningFor( + record, + 'invalid-install-state', + record.error || 'Canonical install-state could not be read' + )); + continue; + } + + if (!stateMatchesDiscoveryRecord(record.state, record)) { + result = removeDiscoverableProjection(store, identity, result); + result = addWarning(result, warningFor( + record, + 'install-state-identity-mismatch', + 'Canonical install-state identity does not match its discovered target' + )); + continue; + } + + const projection = projectInstallState(store, record.state); + if (projection.warning) { + result = addWarning(result, projection.warning); + continue; + } + result = { + ...result, + projectedCount: result.projectedCount + 1, + }; + } + + return result; +} + +function inspectManagedFileHealth(options) { + const buildReport = options.buildDoctorReport + || require('../install-lifecycle').buildDoctorReport; + const report = buildReport({ + repoRoot: options.repoRoot, + homeDir: options.homeDir, + projectRoot: options.projectRoot, + targets: options.targets, + }); + + return report.results.map(result => { + const issues = Array.isArray(result.issues) + ? result.issues.filter(issue => MANAGED_FILE_HEALTH_CODES.has(issue.code)) + : []; + const status = issues.some(issue => issue.severity === 'error') + ? 'error' + : issues.some(issue => issue.severity === 'warning') ? 'warning' : 'ok'; + return { + targetId: result.adapter.id, + targetRoot: result.targetRoot, + status, + issues: issues.map(issue => cloneJsonValue(issue)), + }; + }); +} + +function identityKey(identity) { + return `${identity.targetId}\u0000${path.resolve(identity.targetRoot)}`; +} + +function summarizeProjectedInstallHealth(installHealth, reconciliation) { + const healthEntries = Array.isArray(reconciliation && reconciliation.managedFileHealth) + ? reconciliation.managedFileHealth + : []; + const healthByIdentity = new Map(healthEntries.map(entry => [identityKey(entry), entry])); + const healthCheckFailed = Boolean( + reconciliation + && Array.isArray(reconciliation.warnings) + && reconciliation.warnings.some(warning => warning.code === 'install-health-check-failed') + ); + const scopedIdentities = new Set( + Array.isArray(reconciliation && reconciliation.scopedTargets) + ? reconciliation.scopedTargets.map(identityKey) + : [] + ); + const installations = installHealth.installations.map(installation => { + const key = identityKey(installation); + const canonicalHealth = healthByIdentity.get(key); + if (canonicalHealth) { + return { + ...installation, + status: canonicalHealth.status === 'ok' ? installation.status : 'warning', + canonicalStatus: canonicalHealth.status, + issues: canonicalHealth.issues.map(issue => cloneJsonValue(issue)), + }; + } + + if (healthCheckFailed && scopedIdentities.has(key)) { + return { + ...installation, + status: 'warning', + canonicalStatus: 'unverified', + issues: [{ + severity: 'warning', + code: 'install-health-check-failed', + message: 'Canonical managed-file health could not be verified', + }], + }; + } + + return installation; + }); + const healthyCount = installations.filter(installation => installation.status === 'healthy').length; + const warningCount = installations.length - healthyCount; + + return { + ...installHealth, + status: installations.length === 0 + ? 'missing' + : warningCount > 0 ? 'warning' : 'healthy', + healthyCount, + warningCount, + installations, + }; +} + +function reconcileCurrentInstallState(store, options = {}) { + try { + const discover = options.discoverInstalledStates + || require('../install-lifecycle').discoverInstalledStates; + const records = discover({ + homeDir: options.homeDir, + projectRoot: options.projectRoot, + targets: options.targets, + env: options.env, + }); + let result = reconcileInstallStateProjections(store, records); + try { + result = { + ...result, + managedFileHealth: inspectManagedFileHealth(options), + }; + } catch (error) { + result = addWarning(result, { + code: 'install-health-check-failed', + message: error.message, + targetId: null, + targetRoot: null, + installStatePath: null, + }); + } + return result; + } catch (error) { + return { + ...createReconciliationResult(0), + status: 'warning', + warningCount: 1, + warnings: [{ + code: 'install-state-discovery-failed', + message: error.message, + targetId: null, + targetRoot: null, + installStatePath: null, + }], + }; + } +} + +module.exports = { + buildInstallStateStoreRecord, + projectInstallState, + reconcileCurrentInstallState, + reconcileInstallStateProjections, + removeInstallStateProjection, + stateMatchesDiscoveryRecord, + summarizeProjectedInstallHealth, +}; diff --git a/github_code/affaan-m__ECC/scripts/lib/state-store/migrations.js b/github_code/affaan-m__ECC/scripts/lib/state-store/migrations.js new file mode 100644 index 0000000000000000000000000000000000000000..7716c992589341e4db89a403139a2fd7db040894 --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/state-store/migrations.js @@ -0,0 +1,209 @@ +'use strict'; + +const INITIAL_SCHEMA_SQL = ` +CREATE TABLE IF NOT EXISTS schema_migrations ( + version INTEGER PRIMARY KEY, + name TEXT NOT NULL, + applied_at TEXT NOT NULL +); + +CREATE TABLE IF NOT EXISTS sessions ( + id TEXT PRIMARY KEY, + adapter_id TEXT NOT NULL, + harness TEXT NOT NULL, + state TEXT NOT NULL, + repo_root TEXT, + started_at TEXT, + ended_at TEXT, + snapshot TEXT NOT NULL CHECK (json_valid(snapshot)) +); + +CREATE INDEX IF NOT EXISTS idx_sessions_state_started_at + ON sessions (state, started_at DESC); +CREATE INDEX IF NOT EXISTS idx_sessions_started_at + ON sessions (started_at DESC); + +CREATE TABLE IF NOT EXISTS skill_runs ( + id TEXT PRIMARY KEY, + skill_id TEXT NOT NULL, + skill_version TEXT NOT NULL, + session_id TEXT NOT NULL, + task_description TEXT NOT NULL, + outcome TEXT NOT NULL, + failure_reason TEXT, + tokens_used INTEGER, + duration_ms INTEGER, + user_feedback TEXT, + created_at TEXT NOT NULL, + FOREIGN KEY (session_id) REFERENCES sessions (id) ON DELETE CASCADE +); + +CREATE INDEX IF NOT EXISTS idx_skill_runs_session_id_created_at + ON skill_runs (session_id, created_at DESC); +CREATE INDEX IF NOT EXISTS idx_skill_runs_created_at + ON skill_runs (created_at DESC); +CREATE INDEX IF NOT EXISTS idx_skill_runs_outcome_created_at + ON skill_runs (outcome, created_at DESC); + +CREATE TABLE IF NOT EXISTS skill_versions ( + skill_id TEXT NOT NULL, + version TEXT NOT NULL, + content_hash TEXT NOT NULL, + amendment_reason TEXT, + promoted_at TEXT, + rolled_back_at TEXT, + PRIMARY KEY (skill_id, version) +); + +CREATE INDEX IF NOT EXISTS idx_skill_versions_promoted_at + ON skill_versions (promoted_at DESC); + +CREATE TABLE IF NOT EXISTS decisions ( + id TEXT PRIMARY KEY, + session_id TEXT NOT NULL, + title TEXT NOT NULL, + rationale TEXT NOT NULL, + alternatives TEXT NOT NULL CHECK (json_valid(alternatives)), + supersedes TEXT, + status TEXT NOT NULL, + created_at TEXT NOT NULL, + FOREIGN KEY (session_id) REFERENCES sessions (id) ON DELETE CASCADE, + FOREIGN KEY (supersedes) REFERENCES decisions (id) ON DELETE SET NULL +); + +CREATE INDEX IF NOT EXISTS idx_decisions_session_id_created_at + ON decisions (session_id, created_at DESC); +CREATE INDEX IF NOT EXISTS idx_decisions_status_created_at + ON decisions (status, created_at DESC); + +CREATE TABLE IF NOT EXISTS install_state ( + target_id TEXT NOT NULL, + target_root TEXT NOT NULL, + profile TEXT, + modules TEXT NOT NULL CHECK (json_valid(modules)), + operations TEXT NOT NULL CHECK (json_valid(operations)), + installed_at TEXT NOT NULL, + source_version TEXT, + PRIMARY KEY (target_id, target_root) +); + +CREATE INDEX IF NOT EXISTS idx_install_state_installed_at + ON install_state (installed_at DESC); + +CREATE TABLE IF NOT EXISTS governance_events ( + id TEXT PRIMARY KEY, + session_id TEXT, + event_type TEXT NOT NULL, + payload TEXT NOT NULL CHECK (json_valid(payload)), + resolved_at TEXT, + resolution TEXT, + created_at TEXT NOT NULL, + FOREIGN KEY (session_id) REFERENCES sessions (id) ON DELETE SET NULL +); + +CREATE INDEX IF NOT EXISTS idx_governance_events_resolved_at_created_at + ON governance_events (resolved_at, created_at DESC); +CREATE INDEX IF NOT EXISTS idx_governance_events_session_id_created_at + ON governance_events (session_id, created_at DESC); +`; + +const WORK_ITEMS_SQL = ` +CREATE TABLE IF NOT EXISTS work_items ( + id TEXT PRIMARY KEY, + source TEXT NOT NULL, + source_id TEXT, + title TEXT NOT NULL, + status TEXT NOT NULL, + priority TEXT, + url TEXT, + owner TEXT, + repo_root TEXT, + session_id TEXT, + metadata TEXT NOT NULL CHECK (json_valid(metadata)), + created_at TEXT NOT NULL, + updated_at TEXT NOT NULL, + FOREIGN KEY (session_id) REFERENCES sessions (id) ON DELETE SET NULL +); + +CREATE INDEX IF NOT EXISTS idx_work_items_status_updated_at + ON work_items (status, updated_at DESC); +CREATE INDEX IF NOT EXISTS idx_work_items_source_source_id + ON work_items (source, source_id); +CREATE INDEX IF NOT EXISTS idx_work_items_session_id_updated_at + ON work_items (session_id, updated_at DESC); +`; + +const MIGRATIONS = [ + { + version: 1, + name: '001_initial_state_store', + sql: INITIAL_SCHEMA_SQL, + }, + { + version: 2, + name: '002_work_items', + sql: WORK_ITEMS_SQL, + }, +]; + +function ensureMigrationTable(db) { + db.exec(` + CREATE TABLE IF NOT EXISTS schema_migrations ( + version INTEGER PRIMARY KEY, + name TEXT NOT NULL, + applied_at TEXT NOT NULL + ); + `); +} + +function getAppliedMigrations(db) { + ensureMigrationTable(db); + return db + .prepare(` + SELECT version, name, applied_at + FROM schema_migrations + ORDER BY version ASC + `) + .all() + .map(row => ({ + version: row.version, + name: row.name, + appliedAt: row.applied_at, + })); +} + +function applyMigrations(db) { + ensureMigrationTable(db); + + const appliedVersions = new Set( + db.prepare('SELECT version FROM schema_migrations').all().map(row => row.version) + ); + const insertMigration = db.prepare(` + INSERT INTO schema_migrations (version, name, applied_at) + VALUES (@version, @name, @applied_at) + `); + + const applyPending = db.transaction(() => { + for (const migration of MIGRATIONS) { + if (appliedVersions.has(migration.version)) { + continue; + } + + db.exec(migration.sql); + insertMigration.run({ + version: migration.version, + name: migration.name, + applied_at: new Date().toISOString(), + }); + } + }); + + applyPending(); + return getAppliedMigrations(db); +} + +module.exports = { + MIGRATIONS, + applyMigrations, + getAppliedMigrations, +}; diff --git a/github_code/affaan-m__ECC/scripts/lib/state-store/queries.js b/github_code/affaan-m__ECC/scripts/lib/state-store/queries.js new file mode 100644 index 0000000000000000000000000000000000000000..0225f476182ab68c77285d1e2f398637b7c20bbc --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/state-store/queries.js @@ -0,0 +1,944 @@ +'use strict'; + +const { assertValidEntity } = require('./schema'); + +const ACTIVE_SESSION_STATES = ['active', 'running', 'idle']; +const SUCCESS_OUTCOMES = new Set(['success', 'succeeded', 'passed']); +const FAILURE_OUTCOMES = new Set(['failure', 'failed', 'error']); +const CLOSED_WORK_ITEM_STATUSES = new Set(['done', 'closed', 'resolved', 'merged', 'cancelled']); +const ATTENTION_WORK_ITEM_STATUSES = new Set(['blocked', 'needs-review', 'failed', 'stalled']); + +function normalizeLimit(value, fallback) { + if (value === undefined || value === null) { + return fallback; + } + + const parsed = Number.parseInt(value, 10); + if (!Number.isFinite(parsed) || parsed <= 0) { + throw new Error(`Invalid limit: ${value}`); + } + + return parsed; +} + +function parseJsonColumn(value, fallback) { + if (value === null || value === undefined || value === '') { + return fallback; + } + + return JSON.parse(value); +} + +function stringifyJson(value, label) { + try { + return JSON.stringify(value); + } catch (error) { + throw new Error(`Failed to serialize ${label}: ${error.message}`); + } +} + +function mapSessionRow(row) { + const snapshot = parseJsonColumn(row.snapshot, {}); + return { + id: row.id, + adapterId: row.adapter_id, + harness: row.harness, + state: row.state, + repoRoot: row.repo_root, + startedAt: row.started_at, + endedAt: row.ended_at, + snapshot, + workerCount: Array.isArray(snapshot && snapshot.workers) ? snapshot.workers.length : 0, + }; +} + +function mapSkillRunRow(row) { + return { + id: row.id, + skillId: row.skill_id, + skillVersion: row.skill_version, + sessionId: row.session_id, + taskDescription: row.task_description, + outcome: row.outcome, + failureReason: row.failure_reason, + tokensUsed: row.tokens_used, + durationMs: row.duration_ms, + userFeedback: row.user_feedback, + createdAt: row.created_at, + }; +} + +function mapSkillVersionRow(row) { + return { + skillId: row.skill_id, + version: row.version, + contentHash: row.content_hash, + amendmentReason: row.amendment_reason, + promotedAt: row.promoted_at, + rolledBackAt: row.rolled_back_at, + }; +} + +function mapDecisionRow(row) { + return { + id: row.id, + sessionId: row.session_id, + title: row.title, + rationale: row.rationale, + alternatives: parseJsonColumn(row.alternatives, []), + supersedes: row.supersedes, + status: row.status, + createdAt: row.created_at, + }; +} + +function mapInstallStateRow(row) { + const modules = parseJsonColumn(row.modules, []); + const operations = parseJsonColumn(row.operations, []); + const status = row.source_version && row.installed_at ? 'healthy' : 'warning'; + + return { + targetId: row.target_id, + targetRoot: row.target_root, + profile: row.profile, + modules, + operations, + installedAt: row.installed_at, + sourceVersion: row.source_version, + moduleCount: Array.isArray(modules) ? modules.length : 0, + operationCount: Array.isArray(operations) ? operations.length : 0, + status, + }; +} + +function mapGovernanceEventRow(row) { + return { + id: row.id, + sessionId: row.session_id, + eventType: row.event_type, + payload: parseJsonColumn(row.payload, null), + resolvedAt: row.resolved_at, + resolution: row.resolution, + createdAt: row.created_at, + }; +} + +function mapWorkItemRow(row) { + return { + id: row.id, + source: row.source, + sourceId: row.source_id, + title: row.title, + status: row.status, + priority: row.priority, + url: row.url, + owner: row.owner, + repoRoot: row.repo_root, + sessionId: row.session_id, + metadata: parseJsonColumn(row.metadata, null), + createdAt: row.created_at, + updatedAt: row.updated_at, + }; +} + +function classifyOutcome(outcome) { + const normalized = String(outcome || '').toLowerCase(); + if (SUCCESS_OUTCOMES.has(normalized)) { + return 'success'; + } + + if (FAILURE_OUTCOMES.has(normalized)) { + return 'failure'; + } + + return 'unknown'; +} + +function classifyWorkItemStatus(status) { + const normalized = String(status || '').toLowerCase(); + if (CLOSED_WORK_ITEM_STATUSES.has(normalized)) { + return 'closed'; + } + + if (ATTENTION_WORK_ITEM_STATUSES.has(normalized)) { + return 'attention'; + } + + return 'open'; +} + +function toPercent(numerator, denominator) { + if (denominator === 0) { + return null; + } + + return Number(((numerator / denominator) * 100).toFixed(1)); +} + +function summarizeSkillRuns(skillRuns) { + const summary = { + totalCount: skillRuns.length, + knownCount: 0, + successCount: 0, + failureCount: 0, + unknownCount: 0, + successRate: null, + failureRate: null, + }; + + for (const skillRun of skillRuns) { + const classification = classifyOutcome(skillRun.outcome); + if (classification === 'success') { + summary.successCount += 1; + summary.knownCount += 1; + } else if (classification === 'failure') { + summary.failureCount += 1; + summary.knownCount += 1; + } else { + summary.unknownCount += 1; + } + } + + summary.successRate = toPercent(summary.successCount, summary.knownCount); + summary.failureRate = toPercent(summary.failureCount, summary.knownCount); + return summary; +} + +function summarizeInstallHealth(installations) { + if (installations.length === 0) { + return { + status: 'missing', + totalCount: 0, + healthyCount: 0, + warningCount: 0, + installations: [], + }; + } + + const summary = installations.reduce((result, installation) => { + if (installation.status === 'healthy') { + result.healthyCount += 1; + } else { + result.warningCount += 1; + } + return result; + }, { + totalCount: installations.length, + healthyCount: 0, + warningCount: 0, + }); + + return { + status: summary.warningCount > 0 ? 'warning' : 'healthy', + ...summary, + installations, + }; +} + +function summarizeWorkItems(workItems) { + const summary = { + totalCount: workItems.length, + openCount: 0, + blockedCount: 0, + closedCount: 0, + items: workItems, + }; + + for (const workItem of workItems) { + const classification = classifyWorkItemStatus(workItem.status); + if (classification === 'closed') { + summary.closedCount += 1; + } else if (classification === 'attention') { + summary.openCount += 1; + summary.blockedCount += 1; + } else { + summary.openCount += 1; + } + } + + return summary; +} + +function summarizeReadiness({ activeSessionCount, skillRuns, installHealth, pendingGovernanceCount, workItems }) { + const failedSkillRuns = skillRuns.summary.failureCount; + const warningInstallations = installHealth.warningCount; + const pendingGovernanceEvents = pendingGovernanceCount; + const blockedWorkItems = workItems.blockedCount; + const attentionCount = failedSkillRuns + warningInstallations + pendingGovernanceEvents + blockedWorkItems; + + return { + status: attentionCount > 0 ? 'attention' : 'ok', + attentionCount, + activeSessions: activeSessionCount, + failedSkillRuns, + warningInstallations, + pendingGovernanceEvents, + blockedWorkItems, + }; +} + +function normalizeSessionInput(session) { + return { + id: session.id, + adapterId: session.adapterId, + harness: session.harness, + state: session.state, + repoRoot: session.repoRoot ?? null, + startedAt: session.startedAt ?? null, + endedAt: session.endedAt ?? null, + snapshot: session.snapshot ?? {}, + }; +} + +function normalizeSkillRunInput(skillRun) { + return { + id: skillRun.id, + skillId: skillRun.skillId, + skillVersion: skillRun.skillVersion, + sessionId: skillRun.sessionId, + taskDescription: skillRun.taskDescription, + outcome: skillRun.outcome, + failureReason: skillRun.failureReason ?? null, + tokensUsed: skillRun.tokensUsed ?? null, + durationMs: skillRun.durationMs ?? null, + userFeedback: skillRun.userFeedback ?? null, + createdAt: skillRun.createdAt || new Date().toISOString(), + }; +} + +function normalizeSkillVersionInput(skillVersion) { + return { + skillId: skillVersion.skillId, + version: skillVersion.version, + contentHash: skillVersion.contentHash, + amendmentReason: skillVersion.amendmentReason ?? null, + promotedAt: skillVersion.promotedAt ?? null, + rolledBackAt: skillVersion.rolledBackAt ?? null, + }; +} + +function normalizeDecisionInput(decision) { + return { + id: decision.id, + sessionId: decision.sessionId, + title: decision.title, + rationale: decision.rationale, + alternatives: decision.alternatives === undefined || decision.alternatives === null + ? [] + : decision.alternatives, + supersedes: decision.supersedes ?? null, + status: decision.status, + createdAt: decision.createdAt || new Date().toISOString(), + }; +} + +function normalizeInstallStateInput(installState) { + return { + targetId: installState.targetId, + targetRoot: installState.targetRoot, + profile: installState.profile ?? null, + modules: installState.modules === undefined || installState.modules === null + ? [] + : installState.modules, + operations: installState.operations === undefined || installState.operations === null + ? [] + : installState.operations, + installedAt: installState.installedAt || new Date().toISOString(), + sourceVersion: installState.sourceVersion ?? null, + }; +} + +function normalizeInstallStateIdentity(identity) { + if (!identity || typeof identity !== 'object') { + throw new Error('Invalid installState identity: expected targetId and targetRoot'); + } + + const targetId = identity.targetId; + const targetRoot = identity.targetRoot; + if (typeof targetId !== 'string' || targetId.length === 0) { + throw new Error('Invalid installState identity: targetId must be a non-empty string'); + } + if (typeof targetRoot !== 'string' || targetRoot.length === 0) { + throw new Error('Invalid installState identity: targetRoot must be a non-empty string'); + } + + return { targetId, targetRoot }; +} + +function normalizeGovernanceEventInput(governanceEvent) { + return { + id: governanceEvent.id, + sessionId: governanceEvent.sessionId ?? null, + eventType: governanceEvent.eventType, + payload: governanceEvent.payload ?? null, + resolvedAt: governanceEvent.resolvedAt ?? null, + resolution: governanceEvent.resolution ?? null, + createdAt: governanceEvent.createdAt || new Date().toISOString(), + }; +} + +function normalizeWorkItemInput(workItem) { + const now = new Date().toISOString(); + return { + id: workItem.id, + source: workItem.source, + sourceId: workItem.sourceId ?? null, + title: workItem.title, + status: workItem.status, + priority: workItem.priority ?? null, + url: workItem.url ?? null, + owner: workItem.owner ?? null, + repoRoot: workItem.repoRoot ?? null, + sessionId: workItem.sessionId ?? null, + metadata: workItem.metadata ?? null, + createdAt: workItem.createdAt || now, + updatedAt: workItem.updatedAt || now, + }; +} + +function createQueryApi(db) { + const listRecentSessionsStatement = db.prepare(` + SELECT * + FROM sessions + ORDER BY COALESCE(started_at, ended_at, '') DESC, id DESC + LIMIT ? + `); + const countSessionsStatement = db.prepare(` + SELECT COUNT(*) AS total_count + FROM sessions + `); + const getSessionStatement = db.prepare(` + SELECT * + FROM sessions + WHERE id = ? + `); + const getSessionSkillRunsStatement = db.prepare(` + SELECT * + FROM skill_runs + WHERE session_id = ? + ORDER BY created_at DESC, id DESC + `); + const getSessionDecisionsStatement = db.prepare(` + SELECT * + FROM decisions + WHERE session_id = ? + ORDER BY created_at DESC, id DESC + `); + const listActiveSessionsStatement = db.prepare(` + SELECT * + FROM sessions + WHERE ended_at IS NULL + AND state IN ('active', 'running', 'idle') + ORDER BY COALESCE(started_at, ended_at, '') DESC, id DESC + LIMIT ? + `); + const countActiveSessionsStatement = db.prepare(` + SELECT COUNT(*) AS total_count + FROM sessions + WHERE ended_at IS NULL + AND state IN ('active', 'running', 'idle') + `); + const listRecentSkillRunsStatement = db.prepare(` + SELECT * + FROM skill_runs + ORDER BY created_at DESC, id DESC + LIMIT ? + `); + const listInstallStateStatement = db.prepare(` + SELECT * + FROM install_state + ORDER BY installed_at DESC, target_id ASC + `); + const getInstallStateStatement = db.prepare(` + SELECT target_id + FROM install_state + WHERE target_id = ? AND target_root = ? + `); + const countPendingGovernanceStatement = db.prepare(` + SELECT COUNT(*) AS total_count + FROM governance_events + WHERE resolved_at IS NULL + `); + const listPendingGovernanceStatement = db.prepare(` + SELECT * + FROM governance_events + WHERE resolved_at IS NULL + ORDER BY created_at DESC, id DESC + LIMIT ? + `); + const listWorkItemsStatement = db.prepare(` + SELECT * + FROM work_items + ORDER BY updated_at DESC, id DESC + LIMIT ? + `); + const countWorkItemsStatement = db.prepare(` + SELECT COUNT(*) AS total_count + FROM work_items + `); + const listAllWorkItemsStatement = db.prepare(` + SELECT * + FROM work_items + ORDER BY updated_at DESC, id DESC + `); + const getWorkItemStatement = db.prepare(` + SELECT * + FROM work_items + WHERE id = ? + `); + const getSkillVersionStatement = db.prepare(` + SELECT * + FROM skill_versions + WHERE skill_id = ? AND version = ? + `); + + const upsertSessionStatement = db.prepare(` + INSERT INTO sessions ( + id, + adapter_id, + harness, + state, + repo_root, + started_at, + ended_at, + snapshot + ) VALUES ( + @id, + @adapter_id, + @harness, + @state, + @repo_root, + @started_at, + @ended_at, + @snapshot + ) + ON CONFLICT(id) DO UPDATE SET + adapter_id = excluded.adapter_id, + harness = excluded.harness, + state = excluded.state, + repo_root = excluded.repo_root, + started_at = excluded.started_at, + ended_at = excluded.ended_at, + snapshot = excluded.snapshot + `); + + const insertSkillRunStatement = db.prepare(` + INSERT INTO skill_runs ( + id, + skill_id, + skill_version, + session_id, + task_description, + outcome, + failure_reason, + tokens_used, + duration_ms, + user_feedback, + created_at + ) VALUES ( + @id, + @skill_id, + @skill_version, + @session_id, + @task_description, + @outcome, + @failure_reason, + @tokens_used, + @duration_ms, + @user_feedback, + @created_at + ) + ON CONFLICT(id) DO UPDATE SET + skill_id = excluded.skill_id, + skill_version = excluded.skill_version, + session_id = excluded.session_id, + task_description = excluded.task_description, + outcome = excluded.outcome, + failure_reason = excluded.failure_reason, + tokens_used = excluded.tokens_used, + duration_ms = excluded.duration_ms, + user_feedback = excluded.user_feedback, + created_at = excluded.created_at + `); + + const upsertSkillVersionStatement = db.prepare(` + INSERT INTO skill_versions ( + skill_id, + version, + content_hash, + amendment_reason, + promoted_at, + rolled_back_at + ) VALUES ( + @skill_id, + @version, + @content_hash, + @amendment_reason, + @promoted_at, + @rolled_back_at + ) + ON CONFLICT(skill_id, version) DO UPDATE SET + content_hash = excluded.content_hash, + amendment_reason = excluded.amendment_reason, + promoted_at = excluded.promoted_at, + rolled_back_at = excluded.rolled_back_at + `); + + const insertDecisionStatement = db.prepare(` + INSERT INTO decisions ( + id, + session_id, + title, + rationale, + alternatives, + supersedes, + status, + created_at + ) VALUES ( + @id, + @session_id, + @title, + @rationale, + @alternatives, + @supersedes, + @status, + @created_at + ) + ON CONFLICT(id) DO UPDATE SET + session_id = excluded.session_id, + title = excluded.title, + rationale = excluded.rationale, + alternatives = excluded.alternatives, + supersedes = excluded.supersedes, + status = excluded.status, + created_at = excluded.created_at + `); + + const upsertInstallStateStatement = db.prepare(` + INSERT INTO install_state ( + target_id, + target_root, + profile, + modules, + operations, + installed_at, + source_version + ) VALUES ( + @target_id, + @target_root, + @profile, + @modules, + @operations, + @installed_at, + @source_version + ) + ON CONFLICT(target_id, target_root) DO UPDATE SET + profile = excluded.profile, + modules = excluded.modules, + operations = excluded.operations, + installed_at = excluded.installed_at, + source_version = excluded.source_version + `); + const deleteInstallStateStatement = db.prepare(` + DELETE FROM install_state + WHERE target_id = @target_id AND target_root = @target_root + `); + + const insertGovernanceEventStatement = db.prepare(` + INSERT INTO governance_events ( + id, + session_id, + event_type, + payload, + resolved_at, + resolution, + created_at + ) VALUES ( + @id, + @session_id, + @event_type, + @payload, + @resolved_at, + @resolution, + @created_at + ) + ON CONFLICT(id) DO UPDATE SET + session_id = excluded.session_id, + event_type = excluded.event_type, + payload = excluded.payload, + resolved_at = excluded.resolved_at, + resolution = excluded.resolution, + created_at = excluded.created_at + `); + + const upsertWorkItemStatement = db.prepare(` + INSERT INTO work_items ( + id, + source, + source_id, + title, + status, + priority, + url, + owner, + repo_root, + session_id, + metadata, + created_at, + updated_at + ) VALUES ( + @id, + @source, + @source_id, + @title, + @status, + @priority, + @url, + @owner, + @repo_root, + @session_id, + @metadata, + @created_at, + @updated_at + ) + ON CONFLICT(id) DO UPDATE SET + source = excluded.source, + source_id = excluded.source_id, + title = excluded.title, + status = excluded.status, + priority = excluded.priority, + url = excluded.url, + owner = excluded.owner, + repo_root = excluded.repo_root, + session_id = excluded.session_id, + metadata = excluded.metadata, + updated_at = excluded.updated_at + `); + + function getSessionById(id) { + const row = getSessionStatement.get(id); + return row ? mapSessionRow(row) : null; + } + + function getWorkItemById(id) { + const row = getWorkItemStatement.get(id); + return row ? mapWorkItemRow(row) : null; + } + + function listRecentSessions(options = {}) { + const limit = normalizeLimit(options.limit, 10); + return { + totalCount: countSessionsStatement.get().total_count, + sessions: listRecentSessionsStatement.all(limit).map(mapSessionRow), + }; + } + + function getSessionDetail(id) { + const session = getSessionById(id); + if (!session) { + return null; + } + + const workers = Array.isArray(session.snapshot && session.snapshot.workers) + ? session.snapshot.workers.map(worker => ({ ...worker })) + : []; + + return { + session, + workers, + skillRuns: getSessionSkillRunsStatement.all(id).map(mapSkillRunRow), + decisions: getSessionDecisionsStatement.all(id).map(mapDecisionRow), + }; + } + + function listWorkItems(options = {}) { + const limit = normalizeLimit(options.limit, 20); + return { + totalCount: countWorkItemsStatement.get().total_count, + items: listWorkItemsStatement.all(limit).map(mapWorkItemRow), + }; + } + + function getStatus(options = {}) { + const activeLimit = normalizeLimit(options.activeLimit, 5); + const recentSkillRunLimit = normalizeLimit(options.recentSkillRunLimit, 20); + const pendingLimit = normalizeLimit(options.pendingLimit, 5); + const workItemLimit = normalizeLimit(options.workItemLimit, 10); + + const activeSessions = listActiveSessionsStatement.all(activeLimit).map(mapSessionRow); + const activeSessionCount = countActiveSessionsStatement.get().total_count; + const recentSkillRuns = listRecentSkillRunsStatement.all(recentSkillRunLimit).map(mapSkillRunRow); + const installations = listInstallStateStatement.all().map(mapInstallStateRow); + const pendingGovernanceEvents = listPendingGovernanceStatement.all(pendingLimit).map(mapGovernanceEventRow); + const workItems = summarizeWorkItems(listAllWorkItemsStatement.all().map(mapWorkItemRow)); + workItems.items = listWorkItemsStatement.all(workItemLimit).map(mapWorkItemRow); + const skillRuns = { + windowSize: recentSkillRunLimit, + summary: summarizeSkillRuns(recentSkillRuns), + recent: recentSkillRuns, + }; + const installHealth = summarizeInstallHealth(installations); + const pendingGovernanceCount = countPendingGovernanceStatement.get().total_count; + + return { + generatedAt: new Date().toISOString(), + readiness: summarizeReadiness({ + activeSessionCount, + skillRuns, + installHealth, + pendingGovernanceCount, + workItems, + }), + activeSessions: { + activeCount: activeSessionCount, + sessions: activeSessions, + }, + skillRuns, + installHealth, + governance: { + pendingCount: pendingGovernanceCount, + events: pendingGovernanceEvents, + }, + workItems, + }; + } + + return { + deleteInstallState(identity) { + const normalized = normalizeInstallStateIdentity(identity); + const existing = getInstallStateStatement.get(normalized.targetId, normalized.targetRoot); + if (!existing) { + return false; + } + deleteInstallStateStatement.run({ + target_id: normalized.targetId, + target_root: normalized.targetRoot, + }); + return true; + }, + getSessionById, + getSessionDetail, + getWorkItemById, + getStatus, + insertDecision(decision) { + const normalized = normalizeDecisionInput(decision); + assertValidEntity('decision', normalized); + insertDecisionStatement.run({ + id: normalized.id, + session_id: normalized.sessionId, + title: normalized.title, + rationale: normalized.rationale, + alternatives: stringifyJson(normalized.alternatives, 'decision.alternatives'), + supersedes: normalized.supersedes, + status: normalized.status, + created_at: normalized.createdAt, + }); + return normalized; + }, + insertGovernanceEvent(governanceEvent) { + const normalized = normalizeGovernanceEventInput(governanceEvent); + assertValidEntity('governanceEvent', normalized); + insertGovernanceEventStatement.run({ + id: normalized.id, + session_id: normalized.sessionId, + event_type: normalized.eventType, + payload: stringifyJson(normalized.payload, 'governanceEvent.payload'), + resolved_at: normalized.resolvedAt, + resolution: normalized.resolution, + created_at: normalized.createdAt, + }); + return normalized; + }, + insertSkillRun(skillRun) { + const normalized = normalizeSkillRunInput(skillRun); + assertValidEntity('skillRun', normalized); + insertSkillRunStatement.run({ + id: normalized.id, + skill_id: normalized.skillId, + skill_version: normalized.skillVersion, + session_id: normalized.sessionId, + task_description: normalized.taskDescription, + outcome: normalized.outcome, + failure_reason: normalized.failureReason, + tokens_used: normalized.tokensUsed, + duration_ms: normalized.durationMs, + user_feedback: normalized.userFeedback, + created_at: normalized.createdAt, + }); + return normalized; + }, + listRecentSessions, + listWorkItems, + upsertInstallState(installState) { + const normalized = normalizeInstallStateInput(installState); + assertValidEntity('installState', normalized); + upsertInstallStateStatement.run({ + target_id: normalized.targetId, + target_root: normalized.targetRoot, + profile: normalized.profile, + modules: stringifyJson(normalized.modules, 'installState.modules'), + operations: stringifyJson(normalized.operations, 'installState.operations'), + installed_at: normalized.installedAt, + source_version: normalized.sourceVersion, + }); + return normalized; + }, + upsertWorkItem(workItem) { + const normalized = normalizeWorkItemInput(workItem); + assertValidEntity('workItem', normalized); + upsertWorkItemStatement.run({ + id: normalized.id, + source: normalized.source, + source_id: normalized.sourceId, + title: normalized.title, + status: normalized.status, + priority: normalized.priority, + url: normalized.url, + owner: normalized.owner, + repo_root: normalized.repoRoot, + session_id: normalized.sessionId, + metadata: stringifyJson(normalized.metadata, 'workItem.metadata'), + created_at: normalized.createdAt, + updated_at: normalized.updatedAt, + }); + const row = getWorkItemStatement.get(normalized.id); + return row ? mapWorkItemRow(row) : null; + }, + upsertSession(session) { + const normalized = normalizeSessionInput(session); + assertValidEntity('session', normalized); + upsertSessionStatement.run({ + id: normalized.id, + adapter_id: normalized.adapterId, + harness: normalized.harness, + state: normalized.state, + repo_root: normalized.repoRoot, + started_at: normalized.startedAt, + ended_at: normalized.endedAt, + snapshot: stringifyJson(normalized.snapshot, 'session.snapshot'), + }); + return getSessionById(normalized.id); + }, + upsertSkillVersion(skillVersion) { + const normalized = normalizeSkillVersionInput(skillVersion); + assertValidEntity('skillVersion', normalized); + upsertSkillVersionStatement.run({ + skill_id: normalized.skillId, + version: normalized.version, + content_hash: normalized.contentHash, + amendment_reason: normalized.amendmentReason, + promoted_at: normalized.promotedAt, + rolled_back_at: normalized.rolledBackAt, + }); + const row = getSkillVersionStatement.get(normalized.skillId, normalized.version); + return row ? mapSkillVersionRow(row) : null; + }, + }; +} + +module.exports = { + ACTIVE_SESSION_STATES, + FAILURE_OUTCOMES, + SUCCESS_OUTCOMES, + createQueryApi, +}; diff --git a/github_code/affaan-m__ECC/scripts/lib/state-store/schema.js b/github_code/affaan-m__ECC/scripts/lib/state-store/schema.js new file mode 100644 index 0000000000000000000000000000000000000000..915e0481d3ff8d810573ef0f9f6bae8cb3151e76 --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/state-store/schema.js @@ -0,0 +1,93 @@ +'use strict'; + +const fs = require('fs'); +const path = require('path'); +const Ajv = require('ajv'); + +const SCHEMA_PATH = path.join(__dirname, '..', '..', '..', 'schemas', 'state-store.schema.json'); + +const ENTITY_DEFINITIONS = { + session: 'session', + skillRun: 'skillRun', + skillVersion: 'skillVersion', + decision: 'decision', + installState: 'installState', + governanceEvent: 'governanceEvent', + workItem: 'workItem', +}; + +let cachedSchema = null; +let cachedAjv = null; +const cachedValidators = new Map(); + +function readSchema() { + if (cachedSchema) { + return cachedSchema; + } + + cachedSchema = JSON.parse(fs.readFileSync(SCHEMA_PATH, 'utf8')); + return cachedSchema; +} + +function getAjv() { + if (cachedAjv) { + return cachedAjv; + } + + cachedAjv = new Ajv({ + allErrors: true, + strict: false, + }); + return cachedAjv; +} + +function getEntityValidator(entityName) { + if (cachedValidators.has(entityName)) { + return cachedValidators.get(entityName); + } + + const schema = readSchema(); + const definitionName = ENTITY_DEFINITIONS[entityName]; + + if (!definitionName || !schema.$defs || !schema.$defs[definitionName]) { + throw new Error(`Unknown state-store schema entity: ${entityName}`); + } + + const validatorSchema = { + $schema: schema.$schema, + ...schema.$defs[definitionName], + $defs: schema.$defs, + }; + const validator = getAjv().compile(validatorSchema); + cachedValidators.set(entityName, validator); + return validator; +} + +function formatValidationErrors(errors = []) { + return errors + .map(error => `${error.instancePath || '/'} ${error.message}`) + .join('; '); +} + +function validateEntity(entityName, payload) { + const validator = getEntityValidator(entityName); + const valid = validator(payload); + return { + valid, + errors: validator.errors || [], + }; +} + +function assertValidEntity(entityName, payload, label) { + const result = validateEntity(entityName, payload); + if (!result.valid) { + throw new Error(`Invalid ${entityName}${label ? ` (${label})` : ''}: ${formatValidationErrors(result.errors)}`); + } +} + +module.exports = { + assertValidEntity, + formatValidationErrors, + readSchema, + validateEntity, +}; diff --git a/github_code/affaan-m__ECC/scripts/lib/terminal-spinner.js b/github_code/affaan-m__ECC/scripts/lib/terminal-spinner.js new file mode 100644 index 0000000000000000000000000000000000000000..d28d96c63f5e09278d9727323855022c67c5a998 --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/terminal-spinner.js @@ -0,0 +1,77 @@ +'use strict'; + +const { spawn } = require('child_process'); + +const CLEAR_LINE = '\r\x1b[2K'; +const FRAMES = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏']; +const FRAME_INTERVAL_MS = 80; + +function runAnimator(label, options = {}) { + const output = options.output || process.stdout; + const schedule = options.schedule || setInterval; + const clearSchedule = options.clearSchedule || clearInterval; + const onDisconnect = options.onDisconnect + || (handler => process.on('disconnect', handler)); + const exit = options.exit || (code => process.exit(code)); + let frameIndex = 1; + const timer = schedule(() => { + output.write(`\r${FRAMES[frameIndex]} ${label}`); + frameIndex = (frameIndex + 1) % FRAMES.length; + }, FRAME_INTERVAL_MS); + + onDisconnect(() => { + clearSchedule(timer); + exit(0); + }); +} + +function startTerminalSpinner(label, options = {}) { + const output = options.output || process.stdout; + const spawnProcess = options.spawnProcess || spawn; + const onAnimatorError = options.onAnimatorError; + output.write(`${FRAMES[0]} ${label}`); + + let animator; + try { + animator = spawnProcess( + process.execPath, + [__filename, '--animate', label], + { + stdio: ['ignore', 'inherit', 'inherit', 'ipc'], + } + ); + animator.on?.('error', error => { + // Preserve a stable visible fallback if the child cannot animate. + output.write(`\r${FRAMES[0]} ${label}`); + onAnimatorError?.(error); + }); + } catch { + // The first frame still provides visible progress if animation cannot start. + } + + let stopped = false; + return { + stop() { + if (stopped) return; + stopped = true; + animator?.once?.('close', () => { + // A child can render between kill() and close; clear that final frame. + output.write(CLEAR_LINE); + }); + animator?.kill(); + output.write(CLEAR_LINE); + }, + }; +} + +// c8 ignore next 3 -- exercised as the independently instrumented child process. +if (require.main === module && process.argv[2] === '--animate') { + runAnimator(process.argv[3] || 'Working...'); +} + +module.exports = { + CLEAR_LINE, + FRAMES, + runAnimator, + startTerminalSpinner, +}; diff --git a/github_code/affaan-m__ECC/scripts/lib/terminal-welcome.js b/github_code/affaan-m__ECC/scripts/lib/terminal-welcome.js new file mode 100644 index 0000000000000000000000000000000000000000..a943284728c1cd51d16c21fd30046451f89a2750 --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/terminal-welcome.js @@ -0,0 +1,146 @@ +'use strict'; + +const { version: ECC_VERSION } = require('../../package.json'); + +const COMMUNITY_LINKS = Object.freeze({ + github: 'https://github.com/affaan-m/ECC', + discord: 'https://discord.gg/36yGMHGFbR', + documentation: 'https://github.com/affaan-m/ECC#readme', + githubApp: 'https://github.com/apps/ecc-tools', +}); + +const SUCCESS_ACTIONS = Object.freeze([ + 'installed', + 'updated', + 'migrated', + 'resumed', + 'already-migrated', + 'configured', +]); +const SUCCESS_MESSAGES = Object.freeze({ + installed: 'Welcome to ECC!', + updated: 'ECC is updated — thank you for using ECC!', + migrated: 'ECC is configured — thank you for using ECC!', + resumed: 'ECC is configured — thank you for using ECC!', + 'already-migrated': 'ECC is configured — thank you for using ECC!', + configured: 'ECC is configured — thank you for using ECC!', +}); +// CFonts' default "block" face: https://github.com/dominikwilkowski/cfonts +const ECC_WORDMARK = Object.freeze([ + ' ███████╗ ██████╗ ██████╗', + ' ██╔════╝ ██╔════╝ ██╔════╝', + ' █████╗ ██║ ██║', + ' ██╔══╝ ██║ ██║', + ' ███████╗ ╚██████╗ ╚██████╗', + ' ╚══════╝ ╚═════╝ ╚═════╝', +]); +const ECC_GRADIENT = Object.freeze({ + start: Object.freeze({ red: 215, green: 151, blue: 107 }), + end: Object.freeze({ red: 100, green: 131, blue: 160 }), +}); +const ECC_VERSION_PATTERN = /^[0-9]+(?:\.[0-9]+){2}(?:-[0-9A-Za-z.-]+)?(?:\+[0-9A-Za-z.-]+)?$/; +const WORDMARK_START_COLUMN = Math.min(...ECC_WORDMARK.map(line => line.search(/\S/))); +const WORDMARK_END_COLUMN = Math.max( + ...ECC_WORDMARK.map(line => line.trimEnd().length - 1) +); + +function colorize(value, code, enabled) { + return enabled ? `\x1b[${code}m${value}\x1b[0m` : value; +} + +function interpolateChannel(start, end, ratio) { + return Math.round(start + ((end - start) * ratio)); +} + +function gradientColorAt(column) { + const span = WORDMARK_END_COLUMN - WORDMARK_START_COLUMN; + const ratio = span === 0 ? 0 : (column - WORDMARK_START_COLUMN) / span; + return { + red: interpolateChannel(ECC_GRADIENT.start.red, ECC_GRADIENT.end.red, ratio), + green: interpolateChannel(ECC_GRADIENT.start.green, ECC_GRADIENT.end.green, ratio), + blue: interpolateChannel(ECC_GRADIENT.start.blue, ECC_GRADIENT.end.blue, ratio), + }; +} + +function renderWordmark(color) { + if (!color) return ECC_WORDMARK.join('\n'); + + return ECC_WORDMARK.map(line => ( + [...line].map((character, column) => { + if (character === ' ') return character; + const value = gradientColorAt(column); + return `\x1b[38;2;${value.red};${value.green};${value.blue}m${character}`; + }).join('') + '\x1b[0m' + )).join('\n'); +} + +function renderCommunityLinks() { + const rows = Object.freeze([ + `GitHub: ${COMMUNITY_LINKS.github}`, + `Discord: ${COMMUNITY_LINKS.discord}`, + `Documentation: ${COMMUNITY_LINKS.documentation}`, + `GitHub App: ${COMMUNITY_LINKS.githubApp}`, + ]); + const contentWidth = Math.max(...rows.map(row => row.length)); + const border = '─'.repeat(contentWidth + 2); + + return [ + ` ╭${border}╮`, + ...rows.map(row => ` │ ${row.padEnd(contentWidth)} │`), + ` ╰${border}╯`, + ]; +} + +function renderTerminalWelcome(options = {}) { + const color = options.color === true; + const installedVersion = options.version || ECC_VERSION; + if (!ECC_VERSION_PATTERN.test(installedVersion)) { + throw new Error(`Invalid ECC version: ${installedVersion}`); + } + const graphic = renderWordmark(color); + const successMessage = SUCCESS_MESSAGES[options.action] || SUCCESS_MESSAGES.installed; + const welcomeMessage = colorize(successMessage, '1;35', color); + const version = colorize(`v${installedVersion}`, '2', color); + const versionLine = color ? `\x1b[1G ${version}` : ` ${version}`; + + return [ + '', + graphic, + '', + ` ${welcomeMessage}`, + versionLine, + '', + ...renderCommunityLinks(), + '', + ].join('\n'); +} + +function showTerminalWelcome(options = {}) { + const { + action, + dryRun = false, + env = process.env, + interactive = false, + json = false, + output = process.stdout, + } = options; + const shouldShow = ( + interactive + && output.isTTY === true + && !dryRun + && !json + && SUCCESS_ACTIONS.includes(action) + ); + if (!shouldShow) return false; + + const color = env.NO_COLOR === undefined && env.TERM !== 'dumb'; + output.write(renderTerminalWelcome({ action, color })); + return true; +} + +module.exports = { + COMMUNITY_LINKS, + ECC_VERSION_PATTERN, + renderTerminalWelcome, + showTerminalWelcome, +}; diff --git a/github_code/affaan-m__ECC/scripts/lib/tmux-worktree-orchestrator.js b/github_code/affaan-m__ECC/scripts/lib/tmux-worktree-orchestrator.js new file mode 100644 index 0000000000000000000000000000000000000000..4c9cfa920a63cb5d657017e837aa423a770de914 --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/tmux-worktree-orchestrator.js @@ -0,0 +1,598 @@ +'use strict'; + +const fs = require('fs'); +const path = require('path'); +const { spawnSync } = require('child_process'); + +function slugify(value, fallback = 'worker') { + const normalized = String(value || '') + .trim() + .toLowerCase() + .replace(/[^a-z0-9]+/g, '-') + .replace(/^-+|-+$/g, ''); + return normalized || fallback; +} + +function renderTemplate(template, variables) { + if (typeof template !== 'string' || template.trim().length === 0) { + throw new Error('launcherCommand must be a non-empty string'); + } + + return template.replace(/\{([a-z_]+)\}/g, (match, key) => { + if (!(key in variables)) { + throw new Error(`Unknown template variable: ${key}`); + } + return String(variables[key]); + }); +} + +function shellQuote(value) { + return `'${String(value).replace(/'/g, `'\\''`)}'`; +} + +function formatCommand(program, args) { + return [program, ...args.map(shellQuote)].join(' '); +} + +function buildTemplateVariables(values) { + return Object.entries(values).reduce((accumulator, [key, value]) => { + const stringValue = String(value); + const quotedValue = shellQuote(stringValue); + + accumulator[key] = stringValue; + accumulator[`${key}_raw`] = stringValue; + accumulator[`${key}_sh`] = quotedValue; + return accumulator; + }, {}); +} + +function buildSessionBannerCommand(sessionName, coordinationDir) { + return `printf '%s\\n' ${shellQuote(`Session: ${sessionName}`)} ${shellQuote(`Coordination: ${coordinationDir}`)}`; +} + +function normalizeSeedPaths(seedPaths, repoRoot) { + const resolvedRepoRoot = path.resolve(repoRoot); + const entries = Array.isArray(seedPaths) ? seedPaths : []; + const seen = new Set(); + const normalized = []; + + for (const entry of entries) { + if (typeof entry !== 'string' || entry.trim().length === 0) { + continue; + } + + const absolutePath = path.resolve(resolvedRepoRoot, entry); + const relativePath = path.relative(resolvedRepoRoot, absolutePath); + + if ( + relativePath.startsWith('..') || + path.isAbsolute(relativePath) + ) { + throw new Error(`seedPaths entries must stay inside repoRoot: ${entry}`); + } + + const normalizedPath = relativePath.split(path.sep).join('/'); + if (seen.has(normalizedPath)) { + continue; + } + + seen.add(normalizedPath); + normalized.push(normalizedPath); + } + + return normalized; +} + +function overlaySeedPaths({ repoRoot, seedPaths, worktreePath }) { + const normalizedSeedPaths = normalizeSeedPaths(seedPaths, repoRoot); + + for (const seedPath of normalizedSeedPaths) { + const sourcePath = path.join(repoRoot, seedPath); + const destinationPath = path.join(worktreePath, seedPath); + + if (!fs.existsSync(sourcePath)) { + throw new Error(`Seed path does not exist in repoRoot: ${seedPath}`); + } + + fs.mkdirSync(path.dirname(destinationPath), { recursive: true }); + fs.rmSync(destinationPath, { force: true, recursive: true }); + fs.cpSync(sourcePath, destinationPath, { + dereference: false, + force: true, + preserveTimestamps: true, + recursive: true + }); + } +} + +function buildWorkerArtifacts(workerPlan) { + const seededPathsSection = workerPlan.seedPaths.length > 0 + ? [ + '', + '## Seeded Local Overlays', + ...workerPlan.seedPaths.map(seedPath => `- \`${seedPath}\``) + ] + : []; + + return { + dir: workerPlan.coordinationDir, + files: [ + { + path: workerPlan.taskFilePath, + content: [ + `# Worker Task: ${workerPlan.workerName}`, + '', + `- Session: \`${workerPlan.sessionName}\``, + `- Repo root: \`${workerPlan.repoRoot}\``, + `- Worktree: \`${workerPlan.worktreePath}\``, + `- Branch: \`${workerPlan.branchName}\``, + `- Launcher status file: \`${workerPlan.statusFilePath}\``, + `- Launcher handoff file: \`${workerPlan.handoffFilePath}\``, + ...seededPathsSection, + '', + '## Objective', + workerPlan.task, + '', + '## Completion', + 'Do not spawn subagents or external agents for this task.', + 'Report results in your final response.', + `The worker launcher captures your response in \`${workerPlan.handoffFilePath}\` automatically.`, + `The worker launcher updates \`${workerPlan.statusFilePath}\` automatically.` + ].join('\n') + }, + { + path: workerPlan.handoffFilePath, + content: [ + `# Handoff: ${workerPlan.workerName}`, + '', + '## Summary', + '- Pending', + '', + '## Files Changed', + '- Pending', + '', + '## Tests / Verification', + '- Pending', + '', + '## Follow-ups', + '- Pending' + ].join('\n') + }, + { + path: workerPlan.statusFilePath, + content: [ + `# Status: ${workerPlan.workerName}`, + '', + '- State: not started', + `- Worktree: \`${workerPlan.worktreePath}\``, + `- Branch: \`${workerPlan.branchName}\`` + ].join('\n') + } + ] + }; +} + +function buildOrchestrationPlan(config = {}) { + const repoRoot = path.resolve(config.repoRoot || process.cwd()); + const repoName = path.basename(repoRoot); + const workers = Array.isArray(config.workers) ? config.workers : []; + const globalSeedPaths = normalizeSeedPaths(config.seedPaths, repoRoot); + const sessionName = slugify(config.sessionName || repoName, 'session'); + const worktreeRoot = path.resolve(config.worktreeRoot || path.dirname(repoRoot)); + const coordinationRoot = path.resolve( + config.coordinationRoot || path.join(repoRoot, '.orchestration') + ); + const coordinationDir = path.join(coordinationRoot, sessionName); + const baseRef = config.baseRef || 'HEAD'; + const defaultLauncher = config.launcherCommand || ''; + + if (workers.length === 0) { + throw new Error('buildOrchestrationPlan requires at least one worker'); + } + + const seenSlugs = new Set(); + const workerPlans = workers.map((worker, index) => { + if (!worker || typeof worker.task !== 'string' || worker.task.trim().length === 0) { + throw new Error(`Worker ${index + 1} is missing a task`); + } + + const workerName = worker.name || `worker-${index + 1}`; + const workerSlug = slugify(workerName, `worker-${index + 1}`); + + if (seenSlugs.has(workerSlug)) { + throw new Error(`Workers must have unique slugs — duplicate: ${workerSlug}`); + } + seenSlugs.add(workerSlug); + + const branchName = `orchestrator-${sessionName}-${workerSlug}`; + const worktreePath = path.join(worktreeRoot, `${repoName}-${sessionName}-${workerSlug}`); + const workerCoordinationDir = path.join(coordinationDir, workerSlug); + const taskFilePath = path.join(workerCoordinationDir, 'task.md'); + const handoffFilePath = path.join(workerCoordinationDir, 'handoff.md'); + const statusFilePath = path.join(workerCoordinationDir, 'status.md'); + const launcherCommand = worker.launcherCommand || defaultLauncher; + const workerSeedPaths = normalizeSeedPaths(worker.seedPaths, repoRoot); + const seedPaths = normalizeSeedPaths([...globalSeedPaths, ...workerSeedPaths], repoRoot); + const templateVariables = buildTemplateVariables({ + branch_name: branchName, + handoff_file: handoffFilePath, + repo_root: repoRoot, + session_name: sessionName, + status_file: statusFilePath, + task_file: taskFilePath, + worker_name: workerName, + worker_slug: workerSlug, + worktree_path: worktreePath + }); + + if (!launcherCommand) { + throw new Error(`Worker ${workerName} is missing a launcherCommand`); + } + + const gitArgs = ['worktree', 'add', '-b', branchName, worktreePath, baseRef]; + + return { + branchName, + coordinationDir: workerCoordinationDir, + gitArgs, + gitCommand: formatCommand('git', gitArgs), + handoffFilePath, + launchCommand: renderTemplate(launcherCommand, templateVariables), + repoRoot, + sessionName, + seedPaths, + statusFilePath, + task: worker.task.trim(), + taskFilePath, + workerName, + workerSlug, + worktreePath + }; + }); + + const tmuxCommands = [ + { + cmd: 'tmux', + args: ['new-session', '-d', '-s', sessionName, '-n', 'orchestrator', '-c', repoRoot], + description: 'Create detached tmux session' + }, + { + cmd: 'tmux', + args: [ + 'send-keys', + '-t', + sessionName, + buildSessionBannerCommand(sessionName, coordinationDir), + 'C-m' + ], + description: 'Print orchestrator session details' + } + ]; + + for (const workerPlan of workerPlans) { + tmuxCommands.push( + { + cmd: 'tmux', + args: ['split-window', '-d', '-t', sessionName, '-c', workerPlan.worktreePath], + description: `Create pane for ${workerPlan.workerName}` + }, + { + cmd: 'tmux', + args: ['select-layout', '-t', sessionName, 'tiled'], + description: 'Arrange panes in tiled layout' + }, + { + cmd: 'tmux', + args: ['select-pane', '-t', '', '-T', workerPlan.workerSlug], + description: `Label pane ${workerPlan.workerSlug}` + }, + { + cmd: 'tmux', + args: [ + 'send-keys', + '-t', + '', + `cd ${shellQuote(workerPlan.worktreePath)} && ${workerPlan.launchCommand}`, + 'C-m' + ], + description: `Launch worker ${workerPlan.workerName}` + } + ); + } + + return { + baseRef, + coordinationDir, + replaceExisting: Boolean(config.replaceExisting), + repoRoot, + sessionName, + tmuxCommands, + workerPlans + }; +} + +function materializePlan(plan) { + for (const workerPlan of plan.workerPlans) { + const artifacts = buildWorkerArtifacts(workerPlan); + fs.mkdirSync(artifacts.dir, { recursive: true }); + for (const file of artifacts.files) { + fs.writeFileSync(file.path, file.content + '\n', 'utf8'); + } + } +} + +function runCommand(program, args, options = {}) { + const result = spawnSync(program, args, { + cwd: options.cwd, + encoding: 'utf8', + stdio: ['ignore', 'pipe', 'pipe'] + }); + + if (result.error) { + throw result.error; + } + if (result.status !== 0) { + const stderr = (result.stderr || '').trim(); + throw new Error(`${program} ${args.join(' ')} failed${stderr ? `: ${stderr}` : ''}`); + } + return result; +} + +function commandSucceeds(program, args, options = {}) { + const result = spawnSync(program, args, { + cwd: options.cwd, + encoding: 'utf8', + stdio: ['ignore', 'pipe', 'pipe'] + }); + return result.status === 0; +} + +function canonicalizePath(targetPath) { + const resolvedPath = path.resolve(targetPath); + + try { + return fs.realpathSync.native(resolvedPath); + } catch (_error) { + const parentPath = path.dirname(resolvedPath); + + try { + return path.join(fs.realpathSync.native(parentPath), path.basename(resolvedPath)); + } catch (_parentError) { + return resolvedPath; + } + } +} + +function branchExists(repoRoot, branchName) { + return commandSucceeds('git', ['show-ref', '--verify', '--quiet', `refs/heads/${branchName}`], { + cwd: repoRoot + }); +} + +function listWorktrees(repoRoot) { + const listed = runCommand('git', ['worktree', 'list', '--porcelain'], { cwd: repoRoot }); + const lines = (listed.stdout || '').split('\n'); + const worktrees = []; + + for (const line of lines) { + if (line.startsWith('worktree ')) { + const listedPath = line.slice('worktree '.length).trim(); + worktrees.push({ + listedPath, + canonicalPath: canonicalizePath(listedPath) + }); + } + } + + return worktrees; +} + +function cleanupExisting(plan) { + runCommand('git', ['worktree', 'prune', '--expire', 'now'], { cwd: plan.repoRoot }); + + const hasSession = spawnSync('tmux', ['has-session', '-t', plan.sessionName], { + encoding: 'utf8', + stdio: ['ignore', 'pipe', 'pipe'] + }); + + if (hasSession.status === 0) { + runCommand('tmux', ['kill-session', '-t', plan.sessionName], { cwd: plan.repoRoot }); + } + + for (const workerPlan of plan.workerPlans) { + const expectedWorktreePath = canonicalizePath(workerPlan.worktreePath); + const existingWorktree = listWorktrees(plan.repoRoot).find( + worktree => worktree.canonicalPath === expectedWorktreePath + ); + + if (existingWorktree) { + runCommand('git', ['worktree', 'remove', '--force', existingWorktree.listedPath], { + cwd: plan.repoRoot + }); + } + + if (fs.existsSync(workerPlan.worktreePath)) { + fs.rmSync(workerPlan.worktreePath, { force: true, recursive: true }); + } + + runCommand('git', ['worktree', 'prune', '--expire', 'now'], { cwd: plan.repoRoot }); + + if (branchExists(plan.repoRoot, workerPlan.branchName)) { + runCommand('git', ['branch', '-D', workerPlan.branchName], { cwd: plan.repoRoot }); + } + } +} + +function rollbackCreatedResources(plan, createdState, runtime = {}) { + const runCommandImpl = runtime.runCommand || runCommand; + const listWorktreesImpl = runtime.listWorktrees || listWorktrees; + const branchExistsImpl = runtime.branchExists || branchExists; + const errors = []; + + if (createdState.sessionCreated) { + try { + runCommandImpl('tmux', ['kill-session', '-t', plan.sessionName], { cwd: plan.repoRoot }); + } catch (error) { + errors.push(error.message); + } + } + + for (const workerPlan of [...createdState.workerPlans].reverse()) { + const expectedWorktreePath = canonicalizePath(workerPlan.worktreePath); + const existingWorktree = listWorktreesImpl(plan.repoRoot).find( + worktree => worktree.canonicalPath === expectedWorktreePath + ); + + if (existingWorktree) { + try { + runCommandImpl('git', ['worktree', 'remove', '--force', existingWorktree.listedPath], { + cwd: plan.repoRoot + }); + } catch (error) { + errors.push(error.message); + } + } else if (fs.existsSync(workerPlan.worktreePath)) { + fs.rmSync(workerPlan.worktreePath, { force: true, recursive: true }); + } + + try { + runCommandImpl('git', ['worktree', 'prune', '--expire', 'now'], { cwd: plan.repoRoot }); + } catch (error) { + errors.push(error.message); + } + + if (branchExistsImpl(plan.repoRoot, workerPlan.branchName)) { + try { + runCommandImpl('git', ['branch', '-D', workerPlan.branchName], { cwd: plan.repoRoot }); + } catch (error) { + errors.push(error.message); + } + } + } + + if (createdState.removeCoordinationDir && fs.existsSync(plan.coordinationDir)) { + fs.rmSync(plan.coordinationDir, { force: true, recursive: true }); + } + + if (errors.length > 0) { + throw new Error(`rollback failed: ${errors.join('; ')}`); + } +} + +function executePlan(plan, runtime = {}) { + const spawnSyncImpl = runtime.spawnSync || spawnSync; + const runCommandImpl = runtime.runCommand || runCommand; + const materializePlanImpl = runtime.materializePlan || materializePlan; + const overlaySeedPathsImpl = runtime.overlaySeedPaths || overlaySeedPaths; + const cleanupExistingImpl = runtime.cleanupExisting || cleanupExisting; + const rollbackCreatedResourcesImpl = runtime.rollbackCreatedResources || rollbackCreatedResources; + const createdState = { + workerPlans: [], + sessionCreated: false, + removeCoordinationDir: !fs.existsSync(plan.coordinationDir) + }; + + runCommandImpl('git', ['rev-parse', '--is-inside-work-tree'], { cwd: plan.repoRoot }); + runCommandImpl('tmux', ['-V']); + + if (plan.replaceExisting) { + cleanupExistingImpl(plan); + } else { + const hasSession = spawnSyncImpl('tmux', ['has-session', '-t', plan.sessionName], { + encoding: 'utf8', + stdio: ['ignore', 'pipe', 'pipe'] + }); + if (hasSession.status === 0) { + throw new Error(`tmux session already exists: ${plan.sessionName}`); + } + } + + try { + materializePlanImpl(plan); + + for (const workerPlan of plan.workerPlans) { + runCommandImpl('git', workerPlan.gitArgs, { cwd: plan.repoRoot }); + createdState.workerPlans.push(workerPlan); + overlaySeedPathsImpl({ + repoRoot: plan.repoRoot, + seedPaths: workerPlan.seedPaths, + worktreePath: workerPlan.worktreePath + }); + } + + runCommandImpl( + 'tmux', + ['new-session', '-d', '-s', plan.sessionName, '-n', 'orchestrator', '-c', plan.repoRoot], + { cwd: plan.repoRoot } + ); + createdState.sessionCreated = true; + runCommandImpl( + 'tmux', + [ + 'send-keys', + '-t', + plan.sessionName, + buildSessionBannerCommand(plan.sessionName, plan.coordinationDir), + 'C-m' + ], + { cwd: plan.repoRoot } + ); + + for (const workerPlan of plan.workerPlans) { + const splitResult = runCommandImpl( + 'tmux', + ['split-window', '-d', '-P', '-F', '#{pane_id}', '-t', plan.sessionName, '-c', workerPlan.worktreePath], + { cwd: plan.repoRoot } + ); + const paneId = splitResult.stdout.trim(); + + if (!paneId) { + throw new Error(`tmux split-window did not return a pane id for ${workerPlan.workerName}`); + } + + runCommandImpl('tmux', ['select-layout', '-t', plan.sessionName, 'tiled'], { cwd: plan.repoRoot }); + runCommandImpl('tmux', ['select-pane', '-t', paneId, '-T', workerPlan.workerSlug], { + cwd: plan.repoRoot + }); + runCommandImpl( + 'tmux', + [ + 'send-keys', + '-t', + paneId, + `cd ${shellQuote(workerPlan.worktreePath)} && ${workerPlan.launchCommand}`, + 'C-m' + ], + { cwd: plan.repoRoot } + ); + } + } catch (error) { + try { + rollbackCreatedResourcesImpl(plan, createdState, { + branchExists: runtime.branchExists, + listWorktrees: runtime.listWorktrees, + runCommand: runCommandImpl + }); + } catch (cleanupError) { + error.message = `${error.message}; cleanup failed: ${cleanupError.message}`; + } + throw error; + } + + return { + coordinationDir: plan.coordinationDir, + sessionName: plan.sessionName, + workerCount: plan.workerPlans.length + }; +} + +module.exports = { + buildOrchestrationPlan, + executePlan, + materializePlan, + normalizeSeedPaths, + overlaySeedPaths, + rollbackCreatedResources, + renderTemplate, + slugify +}; diff --git a/github_code/affaan-m__ECC/scripts/lib/transcript-context.js b/github_code/affaan-m__ECC/scripts/lib/transcript-context.js new file mode 100644 index 0000000000000000000000000000000000000000..853a35b2a57d8b22641867dd24d7694d0ee803f1 --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/transcript-context.js @@ -0,0 +1,292 @@ +/** + * Transcript context-size helpers for the strategic-compact hook (#2155). + * + * Reads the latest assistant `usage` record from a Claude Code session + * transcript (JSONL) and derives a context-size signal: + * + * - `input_tokens + cache_read_input_tokens + cache_creation_input_tokens` + * partition the prompt, so their sum is the true context size of the turn. + * - The context window is detected from the model id (`[1m]` marker) or from + * the observed token count (anything above 200k implies a 1M window even + * when logs drop the suffix). + * - Thresholds are window-scaled and env-overridable; re-reminders fire in + * fixed token "buckets" above the threshold so the suggestion only repeats + * after real context growth. + * + * Only the tail of the transcript is read (latest records live at the end), + * keeping the PreToolUse hook fast even for very large sessions. + */ + +const fs = require('fs'); + +const STANDARD_CONTEXT_WINDOW_TOKENS = 200000; +const LARGE_CONTEXT_WINDOW_TOKENS = 1000000; +const DEFAULT_CONTEXT_THRESHOLD_STANDARD = 160000; +const DEFAULT_CONTEXT_THRESHOLD_LARGE = 250000; +const DEFAULT_CONTEXT_INTERVAL_TOKENS = 60000; +const DEFAULT_TRANSCRIPT_TAIL_BYTES = 256 * 1024; +const MAX_TOKEN_SETTING = 10000000; +const LARGE_WINDOW_MODEL_MARKER = '[1m]'; + +// Known large-window model families whose ids carry no `[1m]` marker (#2461). +// Matched boundary-aware against the model id — covers dated/region-prefixed +// variants (e.g. `us.anthropic.claude-fable-5-20260115-v1:0`) without matching +// hypothetical smaller tiers sharing the prefix (e.g. `claude-fable-5-mini`). +// Checked in order, first match wins. Best-effort and expected to lag new +// releases; the env override remains the escape hatch for unlisted models. +const KNOWN_MODEL_WINDOW_TOKENS = [ + ['claude-opus-5', LARGE_CONTEXT_WINDOW_TOKENS], + ['claude-fable-5', LARGE_CONTEXT_WINDOW_TOKENS], + ['claude-mythos-5', LARGE_CONTEXT_WINDOW_TOKENS] +]; + +/** + * True when `model` contains `familyId` ending at a token boundary: end of id, + * a delimiter (`[`, `:`, `.`), or a dated/versioned suffix (`-20260115`). + * Alphanumeric continuations and letter suffixes (`-mini`) are different + * models, possibly with smaller windows, and must not match. + */ +function isKnownModelFamilyMatch(model, familyId) { + const start = model.indexOf(familyId); + if (start === -1) { + return false; + } + const rest = model.slice(start + familyId.length); + return !/^[A-Za-z0-9]/.test(rest) && !/^-[A-Za-z]/.test(rest); +} + +/** + * Read the trailing `tailBytes` of a file as UTF-8. + * Returns null when the file is missing or unreadable. + */ +function readFileTail(filePath, tailBytes) { + let fd; + try { + fd = fs.openSync(filePath, 'r'); + } catch { + return null; + } + + try { + const size = fs.fstatSync(fd).size; + const start = Math.max(0, size - tailBytes); + const length = size - start; + if (length <= 0) { + return { text: '', truncated: false }; + } + + const buffer = Buffer.alloc(length); + const bytesRead = fs.readSync(fd, buffer, 0, length, start); + return { + text: buffer.toString('utf8', 0, bytesRead), + truncated: start > 0 + }; + } catch { + return null; + } finally { + try { + fs.closeSync(fd); + } catch { + /* ignore */ + } + } +} + +/** + * Extract the context token total from a transcript record's usage block. + * Returns 0 when the record carries no usable usage data. + */ +function extractUsageTokens(record) { + const usage = record && record.message && record.message.usage; + if (!usage || typeof usage !== 'object') { + return 0; + } + + const total = + (Number.isFinite(usage.input_tokens) ? usage.input_tokens : 0) + + (Number.isFinite(usage.cache_read_input_tokens) ? usage.cache_read_input_tokens : 0) + + (Number.isFinite(usage.cache_creation_input_tokens) ? usage.cache_creation_input_tokens : 0); + + return total > 0 ? total : 0; +} + +/** + * Scan a session transcript (JSONL) backwards for the most recent record with + * a non-empty `message.usage` block. + * + * @param {string} transcriptPath - Absolute path to the transcript JSONL. + * @param {object} [options] + * @param {number} [options.tailBytes] - How many trailing bytes to scan. + * @returns {{ tokens: number, model: string } | null} Latest context size, or + * null when the transcript is missing, unreadable, or has no usage records. + */ +function readLatestContextTokens(transcriptPath, options = {}) { + if (typeof transcriptPath !== 'string' || !transcriptPath) { + return null; + } + + const tailBytes = Number.isInteger(options.tailBytes) && options.tailBytes > 0 ? options.tailBytes : DEFAULT_TRANSCRIPT_TAIL_BYTES; + + const tail = readFileTail(transcriptPath, tailBytes); + if (!tail) { + return null; + } + + const lines = tail.text.split('\n'); + // The first line of a truncated tail is almost certainly partial JSON. + const firstLine = tail.truncated ? 1 : 0; + + for (let i = lines.length - 1; i >= firstLine; i--) { + const line = lines[i].trim(); + if (!line) continue; + + let record; + try { + record = JSON.parse(line); + } catch { + continue; + } + + const tokens = extractUsageTokens(record); + if (tokens > 0) { + const model = record.message && typeof record.message.model === 'string' ? record.message.model : ''; + return { tokens, model }; + } + } + + return null; +} + +/** + * Detect the context window size for a turn, and report whether that size was + * positively detected or merely assumed. + * + * `inferred: false` means the size came from evidence — an explicit env + * override, the `[1m]` marker, or a known large-window family. An observed + * token count above the standard window selects the safer large-window + * thresholds, but remains inferred because the true denominator could be an + * unmarked intermediate size such as 400k. Callers must not present inferred + * windows as fact. + * + * @returns {{ windowTokens: number, inferred: boolean }} + */ +function resolveContextWindow(tokens, model) { + // Explicit window override wins: 400k models (e.g. Opus 4.x) match neither the + // 200k default nor the 1M marker and would otherwise report ~double usage (#2290). + // Honor ECC's own knob and Claude Code's native CLAUDE_CODE_AUTO_COMPACT_WINDOW. + const env = (typeof process !== 'undefined' && process.env) || {}; + const envWindow = Number.parseInt(env.ECC_CONTEXT_WINDOW_TOKENS || env.CLAUDE_CODE_AUTO_COMPACT_WINDOW || '', 10); + if (Number.isInteger(envWindow) && envWindow > 0) { + return { windowTokens: envWindow, inferred: false }; + } + + if (typeof model === 'string' && model.includes(LARGE_WINDOW_MODEL_MARKER)) { + return { windowTokens: LARGE_CONTEXT_WINDOW_TOKENS, inferred: false }; + } + + // Large-window model families without a [1m] marker fall through the checks + // above and would be misreported against the 200k default (#2461). + if (typeof model === 'string') { + const known = KNOWN_MODEL_WINDOW_TOKENS.find(([familyId]) => isKnownModelFamilyMatch(model, familyId)); + if (known) { + return { windowTokens: known[1], inferred: false }; + } + } + + if (Number.isFinite(tokens) && tokens > STANDARD_CONTEXT_WINDOW_TOKENS) { + return { windowTokens: LARGE_CONTEXT_WINDOW_TOKENS, inferred: true }; + } + + return { windowTokens: STANDARD_CONTEXT_WINDOW_TOKENS, inferred: true }; +} + +/** + * Detect the context window size for a turn. + * 1M when the model id carries the `[1m]` marker, matches a known large-window + * model family, or when the observed token count already exceeds the standard + * 200k window (covers logs that drop the suffix); otherwise the standard 200k + * window. + */ +function resolveContextWindowTokens(tokens, model) { + return resolveContextWindow(tokens, model).windowTokens; +} + +/** + * True when the resolved window is the assumed 200k default rather than a + * detected size. Opt-in large-window models that ship no `[1m]` marker in the + * transcript (e.g. a 1M-context Opus tier, where the base tier is 200k and the + * two are indistinguishable by model id) land here, so a percentage computed + * against 200k can be wildly wrong while usage sits below that mark. + */ +function isContextWindowInferred(tokens, model) { + return resolveContextWindow(tokens, model).inferred; +} + +/** + * Resolve the context-size suggestion threshold (tokens). + * `COMPACT_CONTEXT_THRESHOLD=0` disables the context signal entirely; + * other invalid values fall back to the window-scaled default. + */ +function resolveContextThreshold(env, windowTokens) { + const raw = env && env.COMPACT_CONTEXT_THRESHOLD; + if (raw !== undefined && raw !== null && raw !== '') { + const parsed = Number.parseInt(raw, 10); + if (parsed === 0) { + return 0; + } + if (Number.isInteger(parsed) && parsed > 0 && parsed <= MAX_TOKEN_SETTING) { + return parsed; + } + } + + return windowTokens >= LARGE_CONTEXT_WINDOW_TOKENS ? DEFAULT_CONTEXT_THRESHOLD_LARGE : DEFAULT_CONTEXT_THRESHOLD_STANDARD; +} + +/** + * Resolve the re-reminder step (tokens of additional context growth before + * the suggestion repeats). Invalid values fall back to the default. + */ +function resolveContextInterval(env) { + const raw = env && env.COMPACT_CONTEXT_INTERVAL; + const parsed = Number.parseInt(raw, 10); + return Number.isInteger(parsed) && parsed > 0 && parsed <= MAX_TOKEN_SETTING ? parsed : DEFAULT_CONTEXT_INTERVAL_TOKENS; +} + +/** + * Map a context size onto a suggestion bucket. + * Returns -1 below the threshold; bucket 0 at the threshold; +1 for every + * `interval` tokens of growth beyond it. The hook fires only when the bucket + * rises above the last bucket it already fired for. + */ +function computeContextBucket(tokens, threshold, interval) { + if (!Number.isFinite(tokens) || threshold <= 0 || tokens < threshold) { + return -1; + } + + const step = Number.isInteger(interval) && interval > 0 ? interval : DEFAULT_CONTEXT_INTERVAL_TOKENS; + return Math.floor((tokens - threshold) / step); +} + +/** + * Human-readable label for a context window size (e.g. "200k", "1M"). + */ +function formatWindowLabel(windowTokens) { + return windowTokens >= LARGE_CONTEXT_WINDOW_TOKENS ? '1M' : `${Math.round(windowTokens / 1000)}k`; +} + +module.exports = { + STANDARD_CONTEXT_WINDOW_TOKENS, + LARGE_CONTEXT_WINDOW_TOKENS, + DEFAULT_CONTEXT_THRESHOLD_STANDARD, + DEFAULT_CONTEXT_THRESHOLD_LARGE, + DEFAULT_CONTEXT_INTERVAL_TOKENS, + DEFAULT_TRANSCRIPT_TAIL_BYTES, + readLatestContextTokens, + resolveContextWindow, + resolveContextWindowTokens, + isContextWindowInferred, + resolveContextThreshold, + resolveContextInterval, + computeContextBucket, + formatWindowLabel +}; diff --git a/github_code/affaan-m__ECC/scripts/lib/utils.d.ts b/github_code/affaan-m__ECC/scripts/lib/utils.d.ts new file mode 100644 index 0000000000000000000000000000000000000000..9e980c6994f6bf22e5154b07db478708ac96e99f --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/utils.d.ts @@ -0,0 +1,202 @@ +/** + * Cross-platform utility functions for Claude Code hooks and scripts. + * Works on Windows, macOS, and Linux. + */ + +import type { ExecSyncOptions } from 'child_process'; + +// Platform detection +export const isWindows: boolean; +export const isMacOS: boolean; +export const isLinux: boolean; + +// --- Directories --- + +/** Get the user's home directory (cross-platform) */ +export function getHomeDir(): string; + +/** + * ECC agent data root for memory persistence and related state. + * Defaults to ~/.claude; override with ECC_AGENT_DATA_HOME (e.g. ~/.cursor/ecc). + */ +export function getAgentDataHome(): string; + +/** Get the agent data directory (alias of getAgentDataHome) */ +export function getClaudeDir(): string; + +/** Get the canonical ECC sessions directory ($ECC_AGENT_DATA_HOME/session-data) */ +export function getSessionsDir(): string; + +/** Get the legacy sessions directory ($ECC_AGENT_DATA_HOME/sessions) */ +export function getLegacySessionsDir(): string; + +/** Get session directories to search, with canonical storage first and legacy fallback second */ +export function getSessionSearchDirs(): string[]; + +/** Get the learned skills directory ($ECC_AGENT_DATA_HOME/skills/learned) */ +export function getLearnedSkillsDir(): string; + +/** Get the temp directory (cross-platform) */ +export function getTempDir(): string; + +/** + * Ensure a directory exists, creating it recursively if needed. + * Handles EEXIST race conditions from concurrent creation. + * @throws If directory cannot be created (e.g., permission denied) + */ +export function ensureDir(dirPath: string): string; + +// --- Date/Time --- + +/** Get current date in YYYY-MM-DD format */ +export function getDateString(): string; + +/** Get current time in HH:MM format */ +export function getTimeString(): string; + +/** Get current datetime in YYYY-MM-DD HH:MM:SS format */ +export function getDateTimeString(): string; + +// --- Session/Project --- + +/** + * Sanitize a string for use as a session filename segment. + * Replaces invalid characters, strips leading dots, and returns null when + * nothing meaningful remains. Non-ASCII names are hashed for stability. + */ +export function sanitizeSessionId(raw: string | null | undefined): string | null; + +/** + * Get short session ID from CLAUDE_SESSION_ID environment variable. + * Returns last 8 characters, falls back to a sanitized project name then the provided fallback. + */ +export function getSessionIdShort(fallback?: string): string; + +/** Get the git repository name from the current working directory */ +export function getGitRepoName(): string | null; + +/** Get project name from git repo or current directory basename */ +export function getProjectName(): string | null; + +// --- File operations --- + +export interface FileMatch { + /** Absolute path to the matching file */ + path: string; + /** Modification time in milliseconds since epoch */ + mtime: number; +} + +export interface FindFilesOptions { + /** Maximum age in days. Only files modified within this many days are returned. */ + maxAge?: number | null; + /** Whether to search subdirectories recursively */ + recursive?: boolean; +} + +/** + * Find files matching a glob-like pattern in a directory. + * Supports `*` (any chars), `?` (single char), and `.` (literal dot). + * Results are sorted by modification time (newest first). + */ +export function findFiles(dir: string, pattern: string, options?: FindFilesOptions): FileMatch[]; + +/** + * Read a text file safely. Returns null if the file doesn't exist or can't be read. + */ +export function readFile(filePath: string): string | null; + +/** Write a text file, creating parent directories if needed */ +export function writeFile(filePath: string, content: string): void; + +/** Append to a text file, creating parent directories if needed */ +export function appendFile(filePath: string, content: string): void; + +export interface ReplaceInFileOptions { + /** + * When true and search is a string, replaces ALL occurrences (uses String.replaceAll). + * Ignored for RegExp patterns — use the `g` flag instead. + */ + all?: boolean; +} + +/** + * Replace text in a file (cross-platform sed alternative). + * @returns true if the file was found and updated, false if file not found + */ +export function replaceInFile(filePath: string, search: string | RegExp, replace: string, options?: ReplaceInFileOptions): boolean; + +/** + * Count occurrences of a pattern in a file. + * The global flag is enforced automatically for correct counting. + */ +export function countInFile(filePath: string, pattern: string | RegExp): number; + +export interface GrepMatch { + /** 1-based line number */ + lineNumber: number; + /** Full content of the matching line */ + content: string; +} + +/** Search for a pattern in a file and return matching lines with line numbers */ +export function grepFile(filePath: string, pattern: string | RegExp): GrepMatch[]; + +// --- Hook I/O --- + +export interface ReadStdinJsonOptions { + /** + * Timeout in milliseconds. Prevents hooks from hanging indefinitely + * if stdin never closes. Default: 5000 + */ + timeoutMs?: number; + /** + * Maximum stdin data size in bytes. Prevents unbounded memory growth. + * Default: 1048576 (1MB) + */ + maxSize?: number; +} + +/** + * Read JSON from stdin (for hook input). + * Returns an empty object if stdin is empty, times out, or contains invalid JSON. + * Never rejects — safe to use without try-catch in hooks. + */ +export function readStdinJson(options?: ReadStdinJsonOptions): Promise>; + +/** Log a message to stderr (visible to user in Claude Code terminal) */ +export function log(message: string): void; + +/** Output data to stdout (returned to Claude's context) */ +export function output(data: string | Record): void; + +// --- System --- + +/** + * Check if a command exists in PATH. + * Only allows alphanumeric, dash, underscore, and dot characters. + * WARNING: Spawns a child process (where.exe on Windows, which on Unix). + */ +export function commandExists(cmd: string): boolean; + +export interface CommandResult { + success: boolean; + /** Trimmed stdout on success, stderr or error message on failure */ + output: string; +} + +/** + * Run a shell command and return the output. + * SECURITY: Only use with trusted, hardcoded commands. + * Never pass user-controlled input directly. + */ +export function runCommand(cmd: string, options?: ExecSyncOptions): CommandResult; + +/** Check if the current directory is inside a git repository */ +export function isGitRepo(): boolean; + +/** + * Get git modified files (staged + unstaged), optionally filtered by regex patterns. + * Invalid regex patterns are silently skipped. + */ +export function getGitModifiedFiles(patterns?: string[]): string[]; diff --git a/github_code/affaan-m__ECC/scripts/lib/utils.js b/github_code/affaan-m__ECC/scripts/lib/utils.js new file mode 100644 index 0000000000000000000000000000000000000000..5e29868eb51663c75122297e9062b5a9d027da73 --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/utils.js @@ -0,0 +1,669 @@ +/** + * Cross-platform utility functions for Claude Code hooks and scripts + * Works on Windows, macOS, and Linux + */ + +const fs = require('fs'); +const path = require('path'); +const os = require('os'); +const crypto = require('crypto'); +const { execSync, spawnSync } = require('child_process'); + +// Platform detection +const isWindows = process.platform === 'win32'; +const isMacOS = process.platform === 'darwin'; +const isLinux = process.platform === 'linux'; +const SESSION_DATA_DIR_NAME = 'session-data'; +const LEGACY_SESSIONS_DIR_NAME = 'sessions'; +const { + resolveAgentDataHome, +} = require('./agent-data-home'); +const WINDOWS_RESERVED_SESSION_IDS = new Set([ + 'CON', 'PRN', 'AUX', 'NUL', + 'COM1', 'COM2', 'COM3', 'COM4', 'COM5', 'COM6', 'COM7', 'COM8', 'COM9', + 'LPT1', 'LPT2', 'LPT3', 'LPT4', 'LPT5', 'LPT6', 'LPT7', 'LPT8', 'LPT9' +]); + +/** + * Get the user's home directory (cross-platform) + */ +function getHomeDir() { + const explicitHome = process.env.HOME || process.env.USERPROFILE; + if (explicitHome && explicitHome.trim().length > 0) { + return path.resolve(explicitHome); + } + return os.homedir(); +} + +/** + * ECC agent data root for memory persistence (see scripts/lib/agent-data-home.js). + */ +function getAgentDataHome() { + return resolveAgentDataHome(); +} + +/** + * Get the Claude config directory (alias of getAgentDataHome for backwards compatibility). + */ +function getClaudeDir() { + return getAgentDataHome(); +} + + +/** + * Get the sessions directory + */ +function getSessionsDir() { + return path.join(getClaudeDir(), SESSION_DATA_DIR_NAME); +} + +/** + * Get the legacy sessions directory used by older ECC installs + */ +function getLegacySessionsDir() { + return path.join(getClaudeDir(), LEGACY_SESSIONS_DIR_NAME); +} + +/** + * Get all session directories to search, in canonical-first order + */ +function getSessionSearchDirs() { + return Array.from(new Set([getSessionsDir(), getLegacySessionsDir()])); +} + +/** + * Get the learned skills directory + */ +function getLearnedSkillsDir() { + return path.join(getClaudeDir(), 'skills', 'learned'); +} + +/** + * Get the temp directory (cross-platform) + */ +function getTempDir() { + return os.tmpdir(); +} + +/** + * Ensure a directory exists (create if not) + * @param {string} dirPath - Directory path to create + * @returns {string} The directory path + * @throws {Error} If directory cannot be created (e.g., permission denied) + */ +function ensureDir(dirPath) { + try { + if (!fs.existsSync(dirPath)) { + fs.mkdirSync(dirPath, { recursive: true }); + } + } catch (err) { + // EEXIST is fine (race condition with another process creating it) + if (err.code !== 'EEXIST') { + throw new Error(`Failed to create directory '${dirPath}': ${err.message}`); + } + } + return dirPath; +} + +/** + * Get current date in YYYY-MM-DD format + */ +function getDateString() { + const now = new Date(); + const year = now.getFullYear(); + const month = String(now.getMonth() + 1).padStart(2, '0'); + const day = String(now.getDate()).padStart(2, '0'); + return `${year}-${month}-${day}`; +} + +/** + * Get current time in HH:MM format + */ +function getTimeString() { + const now = new Date(); + const hours = String(now.getHours()).padStart(2, '0'); + const minutes = String(now.getMinutes()).padStart(2, '0'); + return `${hours}:${minutes}`; +} + +/** + * Get the git repository name + */ +function getGitRepoName() { + const result = runCommand('git rev-parse --show-toplevel'); + if (!result.success) return null; + return path.basename(result.output); +} + +/** + * Get project name from git repo or current directory + */ +function getProjectName() { + const repoName = getGitRepoName(); + if (repoName) return repoName; + return path.basename(process.cwd()) || null; +} + +/** + * Sanitize a string for use as a session filename segment. + * Replaces invalid characters with hyphens, collapses runs, strips + * leading/trailing hyphens, and removes leading dots so hidden-dir names + * like ".claude" map cleanly to "claude". + * + * Pure non-ASCII inputs get a stable 8-char hash so distinct names do not + * collapse to the same fallback session id. Mixed-script inputs retain their + * ASCII part and gain a short hash suffix for disambiguation. + */ +function sanitizeSessionId(raw) { + if (!raw || typeof raw !== 'string') return null; + + const hasNonAscii = Array.from(raw).some(char => char.codePointAt(0) > 0x7f); + const normalized = raw.replace(/^\.+/, ''); + const sanitized = normalized + .replace(/[^a-zA-Z0-9_-]/g, '-') + .replace(/-{2,}/g, '-') + .replace(/^-+|-+$/g, ''); + + if (sanitized.length > 0) { + const suffix = crypto.createHash('sha256').update(normalized).digest('hex').slice(0, 6); + if (WINDOWS_RESERVED_SESSION_IDS.has(sanitized.toUpperCase())) { + return `${sanitized}-${suffix}`; + } + if (!hasNonAscii) return sanitized; + return `${sanitized}-${suffix}`; + } + + const meaningful = normalized.replace(/[\s\p{P}]/gu, ''); + if (meaningful.length === 0) return null; + + return crypto.createHash('sha256').update(normalized).digest('hex').slice(0, 8); +} + +/** + * Get short session ID from CLAUDE_SESSION_ID environment variable + * Returns last 8 characters, falls back to a sanitized project name then 'default'. + */ +function getSessionIdShort(fallback = 'default') { + const sessionId = process.env.CLAUDE_SESSION_ID; + if (sessionId && sessionId.length > 0) { + const sanitized = sanitizeSessionId(sessionId.slice(-8)); + if (sanitized) return sanitized; + } + return sanitizeSessionId(getProjectName()) || sanitizeSessionId(fallback) || 'default'; +} + +/** + * Get current datetime in YYYY-MM-DD HH:MM:SS format + */ +function getDateTimeString() { + const now = new Date(); + const year = now.getFullYear(); + const month = String(now.getMonth() + 1).padStart(2, '0'); + const day = String(now.getDate()).padStart(2, '0'); + const hours = String(now.getHours()).padStart(2, '0'); + const minutes = String(now.getMinutes()).padStart(2, '0'); + const seconds = String(now.getSeconds()).padStart(2, '0'); + return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`; +} + +/** + * Find files matching a pattern in a directory (cross-platform alternative to find) + * @param {string} dir - Directory to search + * @param {string} pattern - File pattern (e.g., "*.tmp", "*.md") + * @param {object} options - Options { maxAge: days, recursive: boolean } + */ +function findFiles(dir, pattern, options = {}) { + if (!dir || typeof dir !== 'string') return []; + if (!pattern || typeof pattern !== 'string') return []; + + const { maxAge = null, recursive = false } = options; + const results = []; + + if (!fs.existsSync(dir)) { + return results; + } + + // Escape all regex special characters, then convert glob wildcards. + // Order matters: escape specials first, then convert * and ? to regex equivalents. + const regexPattern = pattern + .replace(/[.+^${}()|[\]\\]/g, '\\$&') + .replace(/\*/g, '.*') + .replace(/\?/g, '.'); + const regex = new RegExp(`^${regexPattern}$`); + + function searchDir(currentDir) { + try { + const entries = fs.readdirSync(currentDir, { withFileTypes: true }); + + for (const entry of entries) { + const fullPath = path.join(currentDir, entry.name); + + if (entry.isFile() && regex.test(entry.name)) { + let stats; + try { + stats = fs.statSync(fullPath); + } catch { + continue; // File deleted between readdir and stat + } + + if (maxAge !== null) { + const ageInDays = (Date.now() - stats.mtimeMs) / (1000 * 60 * 60 * 24); + if (ageInDays <= maxAge) { + results.push({ path: fullPath, mtime: stats.mtimeMs }); + } + } else { + results.push({ path: fullPath, mtime: stats.mtimeMs }); + } + } else if (entry.isDirectory() && recursive) { + searchDir(fullPath); + } + } + } catch (_err) { + // Ignore permission errors + } + } + + searchDir(dir); + + // Sort by modification time (newest first) + results.sort((a, b) => b.mtime - a.mtime); + + return results; +} + +/** + * Read JSON from stdin (for hook input) + * @param {object} options - Options + * @param {number} options.timeoutMs - Timeout in milliseconds (default: 5000). + * Prevents hooks from hanging indefinitely if stdin never closes. + * @returns {Promise} Parsed JSON object, or empty object if stdin is empty + */ +async function readStdinJson(options = {}) { + const { timeoutMs = 5000, maxSize = 1024 * 1024 } = options; + + return new Promise((resolve) => { + let data = ''; + let settled = false; + let overflowed = false; + + const timer = setTimeout(() => { + if (!settled) { + settled = true; + // Clean up stdin listeners so the event loop can exit + process.stdin.removeAllListeners('data'); + process.stdin.removeAllListeners('end'); + process.stdin.removeAllListeners('error'); + if (process.stdin.unref) process.stdin.unref(); + // Oversized input is always rejected. Otherwise, resolve with whatever + // arrived before the timeout rather than hanging. + if (overflowed) { + resolve({}); + return; + } + try { + resolve(data.trim() ? JSON.parse(data) : {}); + } catch { + resolve({}); + } + } + }, timeoutMs); + + process.stdin.setEncoding('utf8'); + process.stdin.on('data', chunk => { + if (settled) return; + if (overflowed) return; + // Mark oversized input as rejected and discard the buffered prefix. + // Continue consuming the stream without retaining later chunks so a + // finite parent can finish writing without EPIPE. Resolution happens at + // EOF or the existing timeout, which also bounds never-closing writers. + if (data.length + chunk.length > maxSize) { + overflowed = true; + data = ''; + process.stderr.write( + `[readStdinJson] stdin exceeded ${maxSize} bytes; input truncated and treated as empty\n` + ); + return; + } + data += chunk; + }); + + process.stdin.on('end', () => { + if (settled) { + clearTimeout(timer); + return; + } + settled = true; + clearTimeout(timer); + if (overflowed) { + resolve({}); + return; + } + try { + resolve(data.trim() ? JSON.parse(data) : {}); + } catch { + // Consistent with timeout path: resolve with empty object + // so hooks don't crash on malformed input + resolve({}); + } + }); + + process.stdin.on('error', () => { + if (settled) { + clearTimeout(timer); + return; + } + settled = true; + clearTimeout(timer); + // Resolve with empty object so hooks don't crash on stdin errors + resolve({}); + }); + }); +} + +/** + * Log to stderr (visible to user in Claude Code) + */ +function log(message) { + console.error(message); +} + +/** + * Output to stdout (returned to Claude) + */ +function output(data) { + if (typeof data === 'object') { + console.log(JSON.stringify(data)); + } else { + console.log(data); + } +} + +/** + * Read a text file safely + */ +function readFile(filePath) { + try { + return fs.readFileSync(filePath, 'utf8'); + } catch { + return null; + } +} + +/** + * Write a text file + */ +function writeFile(filePath, content) { + ensureDir(path.dirname(filePath)); + fs.writeFileSync(filePath, content, 'utf8'); +} + +/** + * Append to a text file + */ +function appendFile(filePath, content) { + ensureDir(path.dirname(filePath)); + fs.appendFileSync(filePath, content, 'utf8'); +} + +/** + * Check if a command exists in PATH + * Uses execFileSync to prevent command injection + */ +function commandExists(cmd) { + // Validate command name - only allow alphanumeric, dash, underscore, dot + if (!/^[a-zA-Z0-9_.-]+$/.test(cmd)) { + return false; + } + + try { + if (isWindows) { + // Use spawnSync to avoid shell interpolation + const result = spawnSync('where', [cmd], { stdio: 'pipe' }); + return result.status === 0; + } else { + const result = spawnSync('which', [cmd], { stdio: 'pipe' }); + return result.status === 0; + } + } catch { + return false; + } +} + +/** + * Run a command and return output + * + * SECURITY NOTE: This function executes shell commands. Only use with + * trusted, hardcoded commands. Never pass user-controlled input directly. + * For user input, use spawnSync with argument arrays instead. + * + * @param {string} cmd - Command to execute (should be trusted/hardcoded) + * @param {object} options - execSync options + */ +function runCommand(cmd, options = {}) { + // Allowlist: only permit known-safe command prefixes + const allowedPrefixes = ['git ', 'node ', 'npx ', 'which ', 'where ']; + if (!allowedPrefixes.some(prefix => cmd.startsWith(prefix))) { + return { success: false, output: 'runCommand blocked: unrecognized command prefix' }; + } + + // Reject shell metacharacters. $() and backticks are evaluated inside + // double quotes, so block $ and ` anywhere in cmd. Other operators + // (;|&) are literal inside quotes, so only check unquoted portions. + const unquoted = cmd.replace(/"[^"]*"/g, '').replace(/'[^']*'/g, ''); + if (/[;|&\n]/.test(unquoted) || /[`$]/.test(cmd)) { + return { success: false, output: 'runCommand blocked: shell metacharacters not allowed' }; + } + + try { + const result = execSync(cmd, { + encoding: 'utf8', + stdio: ['pipe', 'pipe', 'pipe'], + ...options + }); + return { success: true, output: result.trim() }; + } catch (err) { + return { success: false, output: err.stderr || err.message }; + } +} + +/** + * Check if current directory is a git repository + */ +function isGitRepo() { + return runCommand('git rev-parse --git-dir').success; +} + +/** + * Get git modified files, optionally filtered by regex patterns + * @param {string[]} patterns - Array of regex pattern strings to filter files. + * Invalid patterns are silently skipped. + * @returns {string[]} Array of modified file paths + */ +function getGitModifiedFiles(patterns = []) { + if (!isGitRepo()) return []; + + const result = runCommand('git diff --name-only HEAD'); + if (!result.success) return []; + + let files = result.output.split('\n').filter(Boolean); + + if (patterns.length > 0) { + // Pre-compile patterns, skipping invalid ones + const compiled = []; + for (const pattern of patterns) { + if (typeof pattern !== 'string' || pattern.length === 0) continue; + try { + compiled.push(new RegExp(pattern)); + } catch { + // Skip invalid regex patterns + } + } + if (compiled.length > 0) { + files = files.filter(file => compiled.some(regex => regex.test(file))); + } + } + + return files; +} + +/** + * Replace text in a file (cross-platform sed alternative) + * @param {string} filePath - Path to the file + * @param {string|RegExp} search - Pattern to search for. String patterns replace + * the FIRST occurrence only; use a RegExp with the `g` flag for global replacement. + * @param {string} replace - Replacement string + * @param {object} options - Options + * @param {boolean} options.all - When true and search is a string, replaces ALL + * occurrences (uses String.replaceAll). Ignored for RegExp patterns. + * @returns {boolean} true if file was written, false on error + */ +function replaceInFile(filePath, search, replace, options = {}) { + const content = readFile(filePath); + if (content === null) return false; + + try { + let newContent; + if (options.all && typeof search === 'string') { + newContent = content.replaceAll(search, replace); + } else { + newContent = content.replace(search, replace); + } + writeFile(filePath, newContent); + return true; + } catch (err) { + log(`[Utils] replaceInFile failed for ${filePath}: ${err.message}`); + return false; + } +} + +/** + * Count occurrences of a pattern in a file + * @param {string} filePath - Path to the file + * @param {string|RegExp} pattern - Pattern to count. Strings are treated as + * global regex patterns. RegExp instances are used as-is but the global + * flag is enforced to ensure correct counting. + * @returns {number} Number of matches found + */ +function countInFile(filePath, pattern) { + const content = readFile(filePath); + if (content === null) return 0; + + let regex; + try { + if (pattern instanceof RegExp) { + // Always create new RegExp to avoid shared lastIndex state; ensure global flag + regex = new RegExp(pattern.source, pattern.flags.includes('g') ? pattern.flags : pattern.flags + 'g'); + } else if (typeof pattern === 'string') { + regex = new RegExp(pattern, 'g'); + } else { + return 0; + } + } catch { + return 0; // Invalid regex pattern + } + const matches = content.match(regex); + return matches ? matches.length : 0; +} + +/** + * Strip all ANSI escape sequences from a string. + * + * Handles: + * - CSI sequences: \x1b[ … (colors, cursor movement, erase, etc.) + * - OSC sequences: \x1b] … BEL/ST (window titles, hyperlinks) + * - Charset selection: \x1b(B + * - Bare ESC + single letter: \x1b (e.g. \x1bM for reverse index) + * + * @param {string} str - Input string possibly containing ANSI codes + * @returns {string} Cleaned string with all escape sequences removed + */ +function stripAnsi(str) { + if (typeof str !== 'string') return ''; + // eslint-disable-next-line no-control-regex + return str.replace(/\x1b(?:\[[0-9;?]*[A-Za-z]|\][^\x07\x1b]*(?:\x07|\x1b\\)|\([A-Z]|[A-Z])/g, ''); +} + +/** + * Search for pattern in file and return matching lines with line numbers + */ +function grepFile(filePath, pattern) { + const content = readFile(filePath); + if (content === null) return []; + + let regex; + try { + if (pattern instanceof RegExp) { + // Always create a new RegExp without the 'g' flag to prevent lastIndex + // state issues when using .test() in a loop (g flag makes .test() stateful, + // causing alternating match/miss on consecutive matching lines) + const flags = pattern.flags.replace('g', ''); + regex = new RegExp(pattern.source, flags); + } else { + regex = new RegExp(pattern); + } + } catch { + return []; // Invalid regex pattern + } + const lines = content.split('\n'); + const results = []; + + lines.forEach((line, index) => { + if (regex.test(line)) { + results.push({ lineNumber: index + 1, content: line }); + } + }); + + return results; +} + +module.exports = { + // Platform info + isWindows, + isMacOS, + isLinux, + + // Directories + getHomeDir, + getAgentDataHome, + getClaudeDir, + getSessionsDir, + getLegacySessionsDir, + getSessionSearchDirs, + getLearnedSkillsDir, + getTempDir, + ensureDir, + + // Date/Time + getDateString, + getTimeString, + getDateTimeString, + + // Session/Project + sanitizeSessionId, + getSessionIdShort, + getGitRepoName, + getProjectName, + + // File operations + findFiles, + readFile, + writeFile, + appendFile, + replaceInFile, + countInFile, + grepFile, + + // String sanitisation + stripAnsi, + + // Hook I/O + readStdinJson, + log, + output, + + // System + commandExists, + runCommand, + isGitRepo, + getGitModifiedFiles +}; diff --git a/github_code/affaan-m__ECC/scripts/lib/worktree-lifecycle/git.js b/github_code/affaan-m__ECC/scripts/lib/worktree-lifecycle/git.js new file mode 100644 index 0000000000000000000000000000000000000000..86f09fa1ee2d1d0396646012211fe710fbf4474a --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/worktree-lifecycle/git.js @@ -0,0 +1,151 @@ +'use strict'; + +const { spawnSync } = require('child_process'); + +// Thin, injectable git command layer. All git interaction in the lifecycle +// service goes through a runner so tests can feed canned output without a real +// repository. The default runner shells out with spawnSync. +// Git env vars that, if inherited (e.g. when this service runs inside a git +// hook), would override the -C/cwd target and point git at the host repo. +const INHERITED_GIT_ENV = ['GIT_DIR', 'GIT_WORK_TREE', 'GIT_INDEX_FILE', 'GIT_COMMON_DIR', 'GIT_PREFIX']; + +function hermeticGitEnv() { + const env = { ...process.env }; + for (const key of INHERITED_GIT_ENV) { + delete env[key]; + } + return env; +} + +function defaultRunImpl(args, options = {}) { + const result = spawnSync('git', args, { + cwd: options.cwd, + encoding: 'utf8', + stdio: ['ignore', 'pipe', 'pipe'], + maxBuffer: 32 * 1024 * 1024, + env: hermeticGitEnv() + }); + + return { + status: typeof result.status === 'number' ? result.status : 1, + stdout: result.stdout || '', + stderr: result.stderr || '' + }; +} + +function createGitRunner(repoRoot, runImpl = defaultRunImpl) { + function run(args) { + return runImpl(args, { cwd: repoRoot }); + } + + function succeeds(args) { + return run(args).status === 0; + } + + function stdoutOf(args) { + const result = run(args); + return result.status === 0 ? (result.stdout || '').trim() : ''; + } + + return { + repoRoot, + run, + succeeds, + + isGitRepo() { + return succeeds(['rev-parse', '--is-inside-work-tree']); + }, + + branchExists(branch) { + return succeeds(['show-ref', '--verify', '--quiet', `refs/heads/${branch}`]); + }, + + // Porcelain worktree list -> [{ path, branch, head, detached, bare }] + listWorktrees() { + const result = run(['worktree', 'list', '--porcelain']); + if (result.status !== 0) { + return []; + } + + const worktrees = []; + let current = null; + + for (const rawLine of (result.stdout || '').split('\n')) { + const line = rawLine.trim(); + if (line.startsWith('worktree ')) { + if (current) { + worktrees.push(current); + } + current = { path: line.slice('worktree '.length).trim(), branch: null, head: null, detached: false, bare: false }; + } else if (current && line.startsWith('branch ')) { + current.branch = line.slice('branch '.length).replace(/^refs\/heads\//, '').trim(); + } else if (current && line.startsWith('HEAD ')) { + current.head = line.slice('HEAD '.length).trim(); + } else if (current && line === 'detached') { + current.detached = true; + } else if (current && line === 'bare') { + current.bare = true; + } + } + + if (current) { + worktrees.push(current); + } + + return worktrees; + }, + + // Uncommitted changes in a worktree (status --porcelain over its own path). + isDirty(worktreePath) { + const result = runImpl(['status', '--porcelain'], { cwd: worktreePath }); + return result.status === 0 ? (result.stdout || '').trim().length > 0 : false; + }, + + // Commits a branch is ahead of / behind its base. Returns null if either + // ref is missing (e.g. branch already merged-and-deleted). + aheadBehind(branch, baseBranch) { + const out = stdoutOf(['rev-list', '--left-right', '--count', `${baseBranch}...${branch}`]); + const match = out.match(/^(\d+)\s+(\d+)$/); + if (!match) { + return null; + } + return { behind: Number(match[1]), ahead: Number(match[2]) }; + }, + + // Last commit time (epoch ms) on a branch. + lastCommitMs(branch) { + const out = stdoutOf(['log', '-1', '--format=%ct', branch]); + const seconds = Number(out); + return Number.isFinite(seconds) && seconds > 0 ? seconds * 1000 : null; + }, + + // Predict merge conflicts WITHOUT touching the working tree using + // `git merge-tree`. Prefers the modern --write-tree form (Git 2.38+), + // which exits non-zero and lists conflicted paths on conflict. + predictMergeConflicts(branch, baseBranch) { + const modern = run(['merge-tree', '--write-tree', '--name-only', baseBranch, branch]); + if (modern.status === 0) { + return { conflicted: false, files: [], method: 'merge-tree' }; + } + + // Non-zero with parseable output => real conflict (modern form). + if (modern.stdout && /\S/.test(modern.stdout)) { + const lines = modern.stdout.split('\n').map(l => l.trim()).filter(Boolean); + // First line is the tree oid; subsequent lines are conflicted paths. + const files = lines.slice(1).filter(line => !/^[0-9a-f]{40}$/i.test(line)); + return { conflicted: true, files, method: 'merge-tree' }; + } + + // Fallback to the legacy form (older Git): conflict markers in output. + const legacy = run(['merge-tree', baseBranch, baseBranch, branch]); + const hasMarkers = /^<{7}|^={7}|^>{7}/m.test(legacy.stdout || '') + || /\+<{7}|changed in both/m.test(legacy.stdout || ''); + return { conflicted: hasMarkers, files: [], method: 'merge-tree-legacy' }; + } + }; +} + +module.exports = { + createGitRunner, + defaultRunImpl +}; diff --git a/github_code/affaan-m__ECC/scripts/lib/worktree-lifecycle/lifecycle.js b/github_code/affaan-m__ECC/scripts/lib/worktree-lifecycle/lifecycle.js new file mode 100644 index 0000000000000000000000000000000000000000..56d08e2a0f217f5f121dc4f9b953cdb295fdd329 --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/lib/worktree-lifecycle/lifecycle.js @@ -0,0 +1,192 @@ +'use strict'; + +const { createGitRunner } = require('./git'); + +const DEFAULT_STALE_MS = 7 * 24 * 60 * 60 * 1000; // 7 days + +// Lifecycle states for a worktree, derived deterministically from git facts. +// main - the primary worktree (== baseBranch / repo root) +// detached - no branch checked out +// dirty - has uncommitted changes (work in progress, never auto-GC) +// conflict - would conflict if merged into base (queued for resolution) +// merge-ready - ahead of base, clean, no predicted conflicts +// merged - fully merged into base (ahead == 0), safe to clean +// stale - clean + no recent activity past the stale threshold +// idle - clean, behind/even with base, nothing to merge +const STATES = Object.freeze({ + MAIN: 'main', + DETACHED: 'detached', + DIRTY: 'dirty', + CONFLICT: 'conflict', + MERGE_READY: 'merge-ready', + MERGED: 'merged', + STALE: 'stale', + IDLE: 'idle' +}); + +function classifyWorktree(facts, { staleThresholdMs, nowMs }) { + if (facts.isMain) { + return STATES.MAIN; + } + + if (facts.detached || !facts.branch) { + return STATES.DETACHED; + } + + if (facts.dirty) { + return STATES.DIRTY; + } + + // Clean from here on. + const ahead = facts.aheadBehind ? facts.aheadBehind.ahead : 0; + + // No unique commits => branch work is already in base => safe to garbage-collect. + if (facts.aheadBehind && ahead === 0) { + return STATES.MERGED; + } + + if (facts.conflict) { + return STATES.CONFLICT; + } + + // Has unmerged commits (ahead > 0, or unknown merge-base). Stale = unmerged + // work that has gone quiet past the threshold: a salvage candidate, never a + // blind delete. Recent unmerged work is merge-ready. + const isOld = facts.lastCommitMs !== null && (nowMs - facts.lastCommitMs) > staleThresholdMs; + if (ahead > 0 || facts.aheadBehind === null) { + return isOld ? STATES.STALE : STATES.MERGE_READY; + } + + return STATES.IDLE; +} + +function analyzeWorktree(worktree, options, git) { + const { baseBranch, staleThresholdMs, nowMs } = options; + const isMain = worktree.canonicalRepoRoot === git.repoRoot + || worktree.path === git.repoRoot + || worktree.branch === baseBranch; + + const branch = worktree.branch; + const dirty = git.isDirty(worktree.path); + const aheadBehind = (!isMain && branch) ? git.aheadBehind(branch, baseBranch) : null; + const lastCommitMs = branch ? git.lastCommitMs(branch) : null; + + // Only run conflict prediction when it matters: a clean, ahead branch. + const ahead = aheadBehind ? aheadBehind.ahead : 0; + let conflictResult = { conflicted: false, files: [], method: null }; + if (!isMain && !dirty && branch && ahead > 0) { + conflictResult = git.predictMergeConflicts(branch, baseBranch); + } + + const facts = { + isMain, + branch, + detached: Boolean(worktree.detached), + dirty, + aheadBehind, + lastCommitMs, + conflict: conflictResult.conflicted + }; + + const state = classifyWorktree(facts, { staleThresholdMs, nowMs }); + const ageMs = lastCommitMs !== null ? Math.max(0, nowMs - lastCommitMs) : null; + + return { + path: worktree.path, + branch: branch || null, + state, + head: worktree.head || null, + dirty, + ahead: aheadBehind ? aheadBehind.ahead : null, + behind: aheadBehind ? aheadBehind.behind : null, + lastCommitMs, + ageMs, + conflictFiles: conflictResult.files, + conflictMethod: conflictResult.method + }; +} + +function buildLifecycleReport(repoRoot, options = {}, deps = {}) { + const git = deps.git || createGitRunner(repoRoot, deps.runImpl); + const baseBranch = options.baseBranch || 'main'; + const staleThresholdMs = Number.isFinite(options.staleThresholdMs) + ? options.staleThresholdMs + : DEFAULT_STALE_MS; + const nowMs = Number.isFinite(options.nowMs) ? options.nowMs : Date.now(); + + const worktrees = git.listWorktrees().map(worktree => + analyzeWorktree(worktree, { baseBranch, staleThresholdMs, nowMs }, git) + ); + + const conflictQueue = worktrees.filter(w => w.state === STATES.CONFLICT); + const staleQueue = worktrees.filter(w => w.state === STATES.STALE); + const mergeReady = worktrees.filter(w => w.state === STATES.MERGE_READY); + + const states = worktrees.reduce((acc, w) => { + acc[w.state] = (acc[w.state] || 0) + 1; + return acc; + }, {}); + + return { + schemaVersion: 'ecc.worktree-lifecycle.v1', + repoRoot, + baseBranch, + staleThresholdMs, + worktrees, + conflictQueue, + staleQueue, + mergeReady, + aggregates: { + worktreeCount: worktrees.length, + states, + conflictCount: conflictQueue.length, + staleCount: staleQueue.length, + mergeReadyCount: mergeReady.length + } + }; +} + +// Plan which worktrees are SAFE to garbage-collect. Safety rule: only fully +// merged trees, or stale trees that are clean AND have nothing unmerged +// (ahead == 0 or no tracked branch). Dirty or merge-ready/conflict trees are +// never proposed for removal so in-progress or unmerged work is preserved +// (mirrors the reference-arch salvage safeguard). +function planCleanup(report) { + const remove = []; + const salvage = []; + const keep = []; + + for (const w of report.worktrees) { + if (w.state === 'main') { + continue; + } + + const unmergedWork = (w.ahead || 0) > 0; + + if (w.state === 'merged') { + // Safe to remove: nothing unique to lose. + remove.push({ path: w.path, branch: w.branch, reason: 'fully merged into base' }); + } else if (w.dirty) { + keep.push({ path: w.path, branch: w.branch, reason: 'has uncommitted changes' }); + } else if (w.state === 'stale') { + // Unmerged + inactive: preserve first (push/bundle), then remove. Never + // a blind delete of unmerged work. + salvage.push({ path: w.path, branch: w.branch, reason: `unmerged + stale (age ${Math.round((w.ageMs || 0) / 86400000)}d, ${w.ahead} ahead) - push/bundle before removing` }); + } else if (unmergedWork) { + keep.push({ path: w.path, branch: w.branch, reason: `unmerged work (${w.ahead} commits ahead)` }); + } else { + keep.push({ path: w.path, branch: w.branch, reason: `state ${w.state}` }); + } + } + + return { remove, salvage, keep }; +} + +module.exports = { + STATES, + DEFAULT_STALE_MS, + classifyWorktree, + analyzeWorktree, + buildLifecycleReport, + planCleanup +}; diff --git a/github_code/affaan-m__ECC/scripts/list-installed.js b/github_code/affaan-m__ECC/scripts/list-installed.js new file mode 100644 index 0000000000000000000000000000000000000000..4b9418c997f46b620693cbfff8ee6d124271a9e5 --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/list-installed.js @@ -0,0 +1,92 @@ +#!/usr/bin/env node + +const os = require('os'); +const { discoverInstalledStates } = require('./lib/install-lifecycle'); +const { SUPPORTED_INSTALL_TARGETS } = require('./lib/install-manifests'); + +function showHelp(exitCode = 0) { + console.log(` +Usage: node scripts/list-installed.js [--target <${SUPPORTED_INSTALL_TARGETS.join('|')}>] [--json] + +Inspect ECC install-state files for the current home/project context. +`); + process.exit(exitCode); +} + +function parseArgs(argv) { + const args = argv.slice(2); + const parsed = { + targets: [], + json: false, + help: false, + }; + + for (let index = 0; index < args.length; index += 1) { + const arg = args[index]; + + if (arg === '--target') { + parsed.targets.push(args[index + 1] || null); + index += 1; + } else if (arg === '--json') { + parsed.json = true; + } else if (arg === '--help' || arg === '-h') { + parsed.help = true; + } else { + throw new Error(`Unknown argument: ${arg}`); + } + } + + return parsed; +} + +function printHuman(records) { + if (records.length === 0) { + console.log('No ECC install-state files found for the current home/project context.'); + return; + } + + console.log('Installed ECC targets:\n'); + for (const record of records) { + if (record.error) { + console.log(`- ${record.adapter.id}: INVALID (${record.error})`); + continue; + } + + const state = record.state; + console.log(`- ${record.adapter.id}`); + console.log(` Root: ${state.target.root}`); + console.log(` Installed: ${state.installedAt}`); + console.log(` Profile: ${state.request.profile || '(legacy/custom)'}`); + console.log(` Modules: ${(state.resolution.selectedModules || []).join(', ') || '(none)'}`); + console.log(` Legacy languages: ${(state.request.legacyLanguages || []).join(', ') || '(none)'}`); + console.log(` Source version: ${state.source.repoVersion || '(unknown)'}`); + } +} + +function main() { + try { + const options = parseArgs(process.argv); + if (options.help) { + showHelp(0); + } + + const records = discoverInstalledStates({ + homeDir: process.env.HOME || os.homedir(), + env: process.env, + projectRoot: process.cwd(), + targets: options.targets, + }).filter(record => record.exists); + + if (options.json) { + console.log(JSON.stringify({ records }, null, 2)); + return; + } + + printHuman(records); + } catch (error) { + console.error(`Error: ${error.message}`); + process.exit(1); + } +} + +main(); diff --git a/github_code/affaan-m__ECC/scripts/loop-status.js b/github_code/affaan-m__ECC/scripts/loop-status.js new file mode 100644 index 0000000000000000000000000000000000000000..16c0d69876bcdb5e6fe5f1804ed833a5403a6a31 --- /dev/null +++ b/github_code/affaan-m__ECC/scripts/loop-status.js @@ -0,0 +1,820 @@ +#!/usr/bin/env node +'use strict'; + +const fs = require('fs'); +const os = require('os'); +const path = require('path'); +const crypto = require('crypto'); + +const DEFAULT_BASH_TIMEOUT_SECONDS = 30 * 60; +const DEFAULT_LIMIT = 10; +const DEFAULT_WAKE_GRACE_MULTIPLIER = 2; +const DEFAULT_WATCH_INTERVAL_SECONDS = 5; + +function usage() { + console.log([ + 'Usage:', + ' node scripts/loop-status.js [--json] [--home ] [--limit ] [--watch]', + ' node scripts/loop-status.js --transcript [--json] [--watch]', + '', + 'Options:', + ' --json Emit machine-readable status JSON', + ' --home Override the home directory to scan', + ' --transcript Inspect one transcript directly', + ' --limit Maximum recent transcripts to inspect (default: 10)', + ' --bash-timeout-seconds Age before a pending Bash call is stale (default: 1800)', + ' --wake-grace-multiplier ScheduleWakeup grace multiplier (default: 2)', + ' --now