diff --git a/integrations/claude-code-plugin/.claude-plugin/plugin.json b/integrations/claude-code-plugin/.claude-plugin/plugin.json index cb2d6376b5..332d72dc29 100644 --- a/integrations/claude-code-plugin/.claude-plugin/plugin.json +++ b/integrations/claude-code-plugin/.claude-plugin/plugin.json @@ -1,7 +1,7 @@ { "name": "loom", "displayName": "ClickHouse Loom", - "version": "1.2.45", + "version": "1.2.47", "description": "Shared long-term memory and code intelligence for Claude Code, self-hosted on ClickHouse. MCP tools to save and recall decisions, preferences and corrections across sessions and teammates; lifecycle hooks that capture each session with no model call; a code index that answers where-is, who-calls and blast-radius questions with line-accurate units instead of whole-file reads.", "author": { "name": "ClickHouse" diff --git a/integrations/claude-code-plugin/README.md b/integrations/claude-code-plugin/README.md index f7a7b76373..c042bae60c 100644 --- a/integrations/claude-code-plugin/README.md +++ b/integrations/claude-code-plugin/README.md @@ -32,6 +32,21 @@ tokens per `tools/list`; every other op runs through `loom_op {op, arguments}`. > **Bare mode skips hooks.** `claude --bare` (chosen by some agent harnesses for prompt-cache and cost reasons) does not run PreToolUse hooks, so the token shunt and the outcome capture in this plugin do not fire there. A harness that wants the shunt under bare mode needs the SDK backend's hook path instead. +A `SessionStart` event with `source: startup` establishes one durable session +family before automatic hook work. Concurrent startup hooks use that same +family; existing privacy marks never reset. Other lifecycle events resolve an +existing family. Unknown, damaged or protected families stay silent, including +automatic signup and the session primer. Binding uses the hook's raw +`session_id`; a payload containing only `sessionId` stays silent. The hooks do +not declare protection for direct MCP responses. Native startup, response +observation and private-content publication remain unqualified. + +On Windows, the local authority uses the process token owner and protected +owner-only access controls on NTFS. A bounded helper checks record handles and +contains its compiler children. Unsupported storage or unverifiable authority +stays silent. Native execution, startup timing and failure cleanup remain +unqualified. + ## Data handling The hooks and scripts send data only to the Loom server the plugin is configured @@ -104,8 +119,12 @@ Its files in the system temp directory, which can hold prompt and reply text, are also mode 0600. A queued write whose delivery process stopped before sending it stays until you replay or delete it; `loom-status` counts these and names the directory. A write the server refuses, or that cannot reach the server, is -discarded. A batch of the per-file read and grep records above that fails to -send is discarded too. Chat turns that fail are sent again at the end of the +discarded. Per-file read and grep reports retain their original producer's +privacy roots. A report with unknown or protected producer state is not sent. +Those reports and failed delivery claims stay on disk without acknowledgement; +failed claims are not replayed automatically. Pending and claimed shunt reports +are excluded from the current plugin's cleanup. Older plugin versions can still +expire older-format files. Chat turns that fail are sent again at the end of the next reply, and a brief's events at the next brief save. At session start the plugin tries to remove other state files untouched for a day. They can remain longer, especially when no new session starts. The log of which tool calls the plugin redirected diff --git a/integrations/claude-code-plugin/hooks/loom-blast-radius.mjs b/integrations/claude-code-plugin/hooks/loom-blast-radius.mjs index d152bc317e..46dfc9f556 100644 --- a/integrations/claude-code-plugin/hooks/loom-blast-radius.mjs +++ b/integrations/claude-code-plugin/hooks/loom-blast-radius.mjs @@ -24,6 +24,7 @@ import { gitToplevel, postBounded, readStdinJson, + runHookMain, DIFF_ARGS, diffHeaders, resolveServerUrl, @@ -122,4 +123,4 @@ async function main() { scheduleExit(0); } -main().catch(() => scheduleExit(0)); +runHookMain(main); diff --git a/integrations/claude-code-plugin/hooks/loom-code-shunt.mjs b/integrations/claude-code-plugin/hooks/loom-code-shunt.mjs index bdad1917e9..83f68f925c 100755 --- a/integrations/claude-code-plugin/hooks/loom-code-shunt.mjs +++ b/integrations/claude-code-plugin/hooks/loom-code-shunt.mjs @@ -21,7 +21,7 @@ // user's decision log (tmpStatePath "shunt-log") and its unflushed copy, one // batch per reporting scope and session (repo.pending, named by batchKind in // lib/shunt-ledger.mjs), all through lib/tmp-state.mjs's private-file helpers, -// flushed as code.outcome rows (fire-and-forget, 300 ms) on a deny or every +// flushed as code.outcome rows (300 ms per request) on a deny or every // SHUNT_FLUSH_EVERY lines (lib/shunt-ledger.mjs). import fs from "node:fs"; import path from "node:path"; @@ -31,8 +31,8 @@ import { gitToplevel, pathUnder, postBounded, - postFireAndForget, readStdinJson, + runHookMain, resolveServerUrl, resolveToken, redactSecrets, @@ -69,6 +69,8 @@ import { estimateTokensRead, estimateTokensSaved, formatShuntLine, + formatShuntBatchLine, + parseShuntBatch, shouldFlushShunt, } from "../lib/shunt-ledger.mjs"; import { repoLookupOutcome, resolveIndexedRepo, resolveTimeoutMs } from "../lib/repo-scope.mjs"; @@ -82,6 +84,13 @@ import { writeSessionState, } from "../lib/tmp-state.mjs"; +import { sessionIsProtected } from "../lib/session-protection.mjs"; +import { + automaticSessionIsProtected, + sessionProtectionContext, + withCapturedSessionProtection, +} from "../lib/session-response.mjs"; + const ENABLED = envSwitch("LOOM_CODE_SHUNT", true); const MAX_LINES = Number(process.env.LOOM_SHUNT_MAX_LINES || DEFAULT_MAX_LINES); const READ_CAP = Math.max(0, Number(process.env.LOOM_SHUNT_READ_CAP || DEFAULT_READ_CAP) || 0); @@ -101,8 +110,7 @@ const LOG_PATH = tmpStatePath("shunt-log", UID, { ext: ".log" }); /** The unflushed batch, set on `repo` in main: `kind` names the reporting scope * (server, token, repository) every batch of it shares, `path` this session's - * batch, a name nobody can create ahead of the session. Batches and claimed - * batches are swept with the other state files. A flush also claims the + * batch. Unacknowledged batches and claims do not expire. A flush also claims the * scope's other batches: those ended or crashed sessions left, and those of * sessions still running. */ function pendingFor(repo, sessionId) { @@ -112,7 +120,7 @@ function pendingFor(repo, sessionId) { org: repo.org || "", namespace: repo.namespace || "", }); - return { kind, path: sessionStatePath(kind, sessionId, { ext: ".log" }) }; + return { kind, path: sessionStatePath(kind, sessionId, { ext: ".log.control" }) }; } function countLines(abs) { @@ -183,32 +191,59 @@ function fileBytes(abs) { } } -/** Append one decision locally; returns the number of unflushed lines. Sync - * appends of one short line — microseconds, and never on the network. */ -function logDecision(pending, { decision, tool, tokensSaved, reason, passReason, path, startLine, endLine }) { - if (!LOG_ON) return 0; - const line = formatShuntLine({ - decision, - tool, - tokensSaved, - reason, - passReason, - path, - startLine, - endLine, - }); +/** Only a newly created lock may be released. A crashed producer leaves evidence. */ +function withBatchLock(file, callback) { + const lock = `${file}.lock`; try { - writePrivateFile(LOG_PATH, line, { append: true }); + fs.mkdirSync(lock, { mode: 0o700 }); } catch { - /* tmp not writable, or a file we do not own: fine */ + return undefined; } try { - writePrivateFile(pending.path, line, { append: true }); - const text = readPrivateFile(pending.path); - return text.split("\n").length - 1; + return callback(); + } finally { + try { + fs.rmdirSync(lock); + } catch { + /* Leave a lock we cannot release; never force another writer's state. */ + } + } +} + +function rootsAreClean(roots) { + try { + return Boolean(roots?.length) && roots.every((root) => !sessionIsProtected(root)); } catch { - return 0; + return false; + } +} + +/** The diagnostic TSV stays readable; only the separate queue carries control. */ +function logDecision(pending, { decision, tool, tokensSaved, reason, passReason, path, startLine, endLine }) { + if (!LOG_ON || automaticSessionIsProtected()) return 0; + const roots = sessionProtectionContext()?.roots; + const line = formatShuntLine({ decision, tool, tokensSaved, reason, passReason, path, startLine, endLine }); + const row = formatShuntBatchLine(line, roots); + if (!row || !rootsAreClean(roots)) return 0; + try { + if (automaticSessionIsProtected()) return 0; + writePrivateFile(LOG_PATH, line, { append: true }); + } catch { + /* tmp not writable, or a file we do not own: fine */ } + return ( + withBatchLock(pending.path, () => { + try { + // Do not append over damaged or unattributed evidence. + if (fs.existsSync(pending.path) && !parseShuntBatch(readPrivateFile(pending.path))) return 0; + if (automaticSessionIsProtected()) return 0; + writePrivateFile(pending.path, row, { append: true }); + return parseShuntBatch(readPrivateFile(pending.path))?.lines || 0; + } catch { + return 0; + } + }) || 0 + ); } /** The batch files of this reporting scope that this user owns: this @@ -224,7 +259,7 @@ function scopeBatches(pending) { return []; } return names - .filter((n) => n.startsWith(prefix) && n.endsWith(".log")) + .filter((n) => n.startsWith(prefix) && n.endsWith(".log.control")) .map((n) => path.join(dir, n)) .filter((file) => { try { @@ -236,46 +271,67 @@ function scopeBatches(pending) { }); } -/** Claim one batch by renaming it to a name of this process, read it with the - * private-file checks, and remove it: of two hooks flushing at once only one - * gets each batch. "" when another hook claimed it first, or it is not ours. */ +/** Locking serializes appends and rename, so a claimed file has no producer writer. */ function claimBatch(file) { - const claimed = tmpStatePath("shunt-claim", `${file}:${process.pid}:${crypto.randomBytes(8).toString("hex")}`, { - ext: ".log", + return withBatchLock(file, () => { + let claimed; + try { + const before = parseShuntBatch(readPrivateFile(file)); + if (!before || !rootsAreClean(before.roots)) return null; + claimed = tmpStatePath( + "shunt-protected-claim", + `${file}:${process.pid}:${crypto.randomBytes(8).toString("hex")}`, + { + ext: ".log.control", + }, + ); + fs.renameSync(file, claimed); + // Re-read after claim: a changed control record is never sent as the old one. + const batch = parseShuntBatch(readPrivateFile(claimed)); + return { claimed, batch }; + } catch { + return claimed ? { claimed, batch: null } : null; + } }); +} + +/** Acknowledge only after every bounded post and the final producer-root check. */ +async function flushPending(repo) { + if (!REPORT_ON || automaticSessionIsProtected()) return; + const claims = scopeBatches(repo.pending).map(claimBatch).filter(Boolean); + if (!claims.length) return; + const ready = claims.filter(({ batch }) => batch && rootsAreClean(batch.roots)); + const roots = ready.flatMap(({ batch }) => batch.roots); + let acknowledged = false; try { - fs.renameSync(file, claimed); - } catch { - return ""; - } - let text = ""; - try { - text = readPrivateFile(claimed); + await withCapturedSessionProtection(roots, async () => { + const agg = aggregateShuntLog(ready.map(({ batch }) => batch.text).join("")); + const bodies = [agg.hit, ...agg.passes].filter(Boolean); + if (!bodies.length) return; + const scope = { org: repo.org || "", namespace: repo.namespace || "", consumer: "claude-code-shunt" }; + for (const body of bodies) { + if (automaticSessionIsProtected()) return; + const answer = await postBounded("code.outcome", { ...scope, ...body }, { timeoutMs: FLUSH_TIMEOUT_MS }); + if (!answer || automaticSessionIsProtected()) return; + } + acknowledged = !automaticSessionIsProtected(); + }); } catch { - /* replaced between the check and the rename: not ours to post */ + // Observer or control failure withholds acknowledgment; claims retain their evidence. + } finally { + for (const claim of claims) { + if (acknowledged && ready.includes(claim) && rootsAreClean(roots)) removeFile(claim.claimed); + // Refusals and ambiguous outcomes stay outside the automatic queue. + // Keeping the claim avoids replaying an unchanged protected operation. + } } - removeFile(claimed); - return text; -} - -/** Ship the scope's pending batches as code.outcome rows. Fire-and-forget with - * a 300 ms ceiling; a lost batch costs a few counter ticks. Each batch is - * claimed before it is read, so it is posted at most once. */ -function flushPending(repo) { - if (!REPORT_ON) return; - const text = scopeBatches(repo.pending).map(claimBatch).join(""); - if (!text) return; - const agg = aggregateShuntLog(text); - const opts = { timeoutMs: FLUSH_TIMEOUT_MS }; - const scope = { org: repo.org || "", namespace: repo.namespace || "", consumer: "claude-code-shunt" }; - if (agg.hit) postFireAndForget("code.outcome", { ...scope, ...agg.hit }, opts); - for (const body of agg.passes) postFireAndForget("code.outcome", { ...scope, ...body }, opts); } /** Every decision funnels through here: deny + log + maybe flush. * `verdict` is classifyRead/classifyGrep's {deny, reason}; `tokens` is the * estimate kept out (hit) or let in (pass); `span` the lines covered. */ function settle(repo, { tool, verdict, tokens, path = "", span = { start: 0, end: 0 } }) { + if (automaticSessionIsProtected()) return; const denied = Boolean(verdict.deny); if (denied) deny(verdict.deny); const unflushed = logDecision(repo.pending, { @@ -288,7 +344,7 @@ function settle(repo, { tool, verdict, tokens, path = "", span = { start: 0, end startLine: span.start, endLine: span.end, }); - if (shouldFlushShunt({ denied, pending: unflushed })) flushPending(repo); + if (shouldFlushShunt({ denied, pending: unflushed })) void flushPending(repo); return denied; } @@ -575,6 +631,4 @@ async function settleBashBulk(repo, { bulk, cwd, sessionId, ctxBase }) { return settle(repo, { tool: "Bash:grep", verdict, tokens: 0, path: rel || "" }); } -main() - .catch(() => {}) - .finally(() => scheduleExit(0)); +runHookMain(main).finally(() => scheduleExit(0)); diff --git a/integrations/claude-code-plugin/hooks/loom-conversation.mjs b/integrations/claude-code-plugin/hooks/loom-conversation.mjs index 30095a1813..16f2308651 100644 --- a/integrations/claude-code-plugin/hooks/loom-conversation.mjs +++ b/integrations/claude-code-plugin/hooks/loom-conversation.mjs @@ -30,6 +30,7 @@ import { } from "../lib/loom-client.mjs"; import { dispatchFlush } from "../lib/flush-job.mjs"; import { readRecording } from "../lib/recording.mjs"; +import { automaticSessionIsProtected } from "../lib/session-response.mjs"; import { readCursor, writeCursor } from "../lib/tmp-state.mjs"; import { fileSize, readLinesFrom } from "../lib/transcript.mjs"; import { appendTurn, journalCursorPath, readJournal, readJournalCursor, rowsSince } from "../lib/turn-journal.mjs"; @@ -82,6 +83,7 @@ function turnFrom(obj) { * only when all land. Falls back to inline fire-and-forget without * advancing the cursor, so the next Stop retries. */ function dispatch(appends, cursorFile, advanceTo) { + if (automaticSessionIsProtected()) return; // The owner switched recording off for this namespace (the // server said so on a recent append): nothing would be kept, so send // nothing and move the cursor past these turns. Re-asked after the cache's @@ -91,7 +93,7 @@ function dispatch(appends, cursorFile, advanceTo) { writeCursor(cursorFile, advanceTo); return; } - if (!dispatchFlush({ appends, cursorPath: cursorFile, advanceTo })) { + if (!dispatchFlush({ appends, cursorPath: cursorFile, advanceTo }) && !automaticSessionIsProtected()) { for (const a of appends) postFireAndForget("conversation.append", a); } } @@ -103,6 +105,7 @@ function dispatch(appends, cursorFile, advanceTo) { * on, so a Stop carries the prompt(s) since the last Stop plus the reply. * Returns true when it handled the event. */ function fromEvents(payload, sessionId, scope) { + if (automaticSessionIsProtected()) return true; const reply = typeof payload.last_assistant_message === "string" ? payload.last_assistant_message.trim() : ""; if (!reply) return false; appendTurn(sessionId, "assistant", reply); @@ -130,6 +133,7 @@ async function main() { return scheduleExit(0); } const payload = await readStdinJson(); + if (automaticSessionIsProtected()) return scheduleExit(0); const sessionId = String(payload.session_id || ""); const transcript = String(payload.transcript_path || ""); if (!sessionId) return scheduleExit(0); @@ -141,6 +145,7 @@ async function main() { // Let a just-finished assistant message flush before we read (see SETTLE_MS). if (SETTLE_MS > 0) await new Promise((r) => setTimeout(r, SETTLE_MS)); + if (automaticSessionIsProtected()) return scheduleExit(0); if (!fileSize(transcript)) { fromEvents(payload, sessionId, scope); // transcript named but unreadable @@ -179,6 +184,7 @@ async function main() { }); } + if (automaticSessionIsProtected()) return scheduleExit(0); if (appends.length === 0) { // Nothing new — advance past scanned lines and exit. A transcript in a // shape this script does not parse yields nothing every time; the diff --git a/integrations/claude-code-plugin/hooks/loom-file-context.mjs b/integrations/claude-code-plugin/hooks/loom-file-context.mjs index 161161af3c..616ba0f36b 100644 --- a/integrations/claude-code-plugin/hooks/loom-file-context.mjs +++ b/integrations/claude-code-plugin/hooks/loom-file-context.mjs @@ -25,6 +25,7 @@ import { gitToplevel, postBounded, readStdinJson, + runHookMain, resolveScope, resolveServerUrl, resolveToken, @@ -40,6 +41,7 @@ import { teamRulesNamespace, } from "../lib/file-context.mjs"; import { readCache } from "../lib/repo-scope.mjs"; +import { automaticSessionIsProtected } from "../lib/session-response.mjs"; import { readSessionState, writeSessionState } from "../lib/tmp-state.mjs"; const ENABLED = envSwitch("LOOM_FILE_CONTEXT", true); @@ -87,6 +89,7 @@ async function main() { post: postBounded, bound: { token, serverUrl: resolveServerUrl() }, }); + if (automaticSessionIsProtected()) return; // Record the lookup whether or not it hit: an empty answer is also an answer // for this session. writeSessionState("file-context", payload.session_id, decision.cache); @@ -98,4 +101,4 @@ async function main() { scheduleExit(0); } -main().catch(() => scheduleExit(0)); +runHookMain(main); diff --git a/integrations/claude-code-plugin/hooks/loom-flush.mjs b/integrations/claude-code-plugin/hooks/loom-flush.mjs index 5b059d88f2..4bd214fae7 100644 --- a/integrations/claude-code-plugin/hooks/loom-flush.mjs +++ b/integrations/claude-code-plugin/hooks/loom-flush.mjs @@ -62,4 +62,4 @@ async function main() { removeFile(jobPath); } -runHookMain(main); +runHookMain(main, { detachedJob: true }); diff --git a/integrations/claude-code-plugin/hooks/loom-run.mjs b/integrations/claude-code-plugin/hooks/loom-run.mjs index 82257d5d31..79764a04d5 100644 --- a/integrations/claude-code-plugin/hooks/loom-run.mjs +++ b/integrations/claude-code-plugin/hooks/loom-run.mjs @@ -41,6 +41,7 @@ import { } from "../lib/run-hook.mjs"; import { sessionStatePath, writeJsonFile } from "../lib/tmp-state.mjs"; import { appendTurn, lastAssistant, readJournal } from "../lib/turn-journal.mjs"; +import { automaticSessionIsProtected } from "../lib/session-response.mjs"; const ENABLED = envSwitch("LOOM_RUN_LEDGER", true); @@ -69,6 +70,7 @@ async function main() { const prompt = String(payload.prompt || ""); // Every prompt goes to the turn journal: the consumers // read it when the client hands them no parseable transcript. + if (automaticSessionIsProtected()) return scheduleExit(0); appendTurn(sessionId, "user", prompt); const prior = readRunState(sessionId); if (prior.begun || prior.refused) { @@ -80,6 +82,7 @@ async function main() { // the first redacted body (the README's hooks table has the retry rules). const body = prior.attempted && prior.body ? prior.body : beginBody(scope, payload, prompt); const res = await postBoundedResult("run.begin", body, opts); + if (automaticSessionIsProtected()) return scheduleExit(0); const runId = res.status >= 200 && res.status < 300 && res.body ? res.body.run_id : ""; // 408, 429 and a 2xx with no usable id may still have opened the run. const transient = res.status === 408 || res.status === 429 || res.status >= 500 || res.status < 300; @@ -102,6 +105,7 @@ async function main() { deadline = Date.now() + 900; const beginOpts = { ...opts, timeoutMs: Math.min(opts.timeoutMs, 400) }; const res = await postBoundedResult("run.begin", state.body || beginBody(scope, payload, ""), beginOpts); + if (automaticSessionIsProtected()) return scheduleExit(0); const runId = res.status >= 200 && res.status < 300 && res.body ? res.body.run_id : ""; if (typeof runId === "string" && runId) writeRunBegun(sessionId, runId); state = readRunState(sessionId); @@ -122,6 +126,7 @@ async function main() { // No longer begun, so a resumed session's next prompt opens a new run. The // id stays for the other SessionEnd hooks, which run beside this one; the // stale-file sweep removes it later. + if (automaticSessionIsProtected()) return scheduleExit(0); writeJsonFile(sp, { run_id: state.run_id }); if (deadline !== undefined) { // Body and state preparation spend the same budget as both requests. diff --git a/integrations/claude-code-plugin/hooks/loom-session-start.mjs b/integrations/claude-code-plugin/hooks/loom-session-start.mjs index 40b17a16af..407657e268 100755 --- a/integrations/claude-code-plugin/hooks/loom-session-start.mjs +++ b/integrations/claude-code-plugin/hooks/loom-session-start.mjs @@ -54,6 +54,8 @@ import { cacheIsFresh, countsBody, renderTaskLine, summarizeCounts } from "../li import { listBody, renderCollectionsLine, toolsetAllows } from "../lib/collections-line.mjs"; import { briefPrimerEnabled, primerLine } from "../lib/session-brief.mjs"; import { readJsonFile, sweepStaleStateFiles, tmpStatePath, writeJsonFile } from "../lib/tmp-state.mjs"; +import { automaticSessionIsProtected } from "../lib/session-response.mjs"; +import { SessionProtectionUnavailable } from "../lib/session-protection.mjs"; async function main() { // A token given at `claude plugin install --config token=…` @@ -81,6 +83,7 @@ async function main() { // silent. The token lands in ~/.loom/config.json for every later hook; // this process keeps using it through LOOM_API_KEY. const signup = await ensureCredential({ hasToken: false, client: hookClient(), serverUrl: resolveServerUrl() }); + if (automaticSessionIsProtected()) return; firstSessionNotice = renderFirstSessionNotice(signup, resolveServerUrl()); if (signup.status === "created") { process.env.LOOM_API_KEY = signup.token; @@ -101,6 +104,7 @@ async function main() { const serverUrl = resolveServerUrl(); const health = probeHealth(serverUrl) .then(({ ms, body }) => { + if (automaticSessionIsProtected()) return ""; if (ms) recordRoundTrip(serverUrl, ms); return serverVersionLine(body, { serverUrl }); }) @@ -123,6 +127,7 @@ async function main() { recordingState(scope, token), envSwitch("LOOM_COLLECTIONS_LINE", true) ? collectionsLine(scope, token) : "", ]); + if (automaticSessionIsProtected()) return; // A user-scope MCP entry duplicating this plugin's mount. const dup = hookClient() === "claude-code" ? duplicateNotice({ serverUrl }) : ""; @@ -151,6 +156,7 @@ async function recordingState(scope, token) { const cached = readRecording(serverUrl, scope.org, scope.namespace); if (cached !== null) return cached; const body = await postBounded("namespace.get", { org: scope.org, namespace: scope.namespace }, { token, serverUrl }); + if (automaticSessionIsProtected()) return null; const on = recordingFromNamespace(body); writeRecording(serverUrl, scope.org, scope.namespace, on); return on; @@ -172,6 +178,7 @@ async function taskInboxLine(scope, token) { const cached = readJsonFile(cp, null); if (cacheIsFresh(cached)) return cached.line; const result = await postBounded("task.counts", countsBody(scope), { token, serverUrl: resolveServerUrl() }); + if (automaticSessionIsProtected()) return ""; const line = renderTaskLine(summarizeCounts(result)); writeJsonFile(cp, { ts: Date.now(), line }); return line; @@ -197,6 +204,7 @@ async function collectionsLine(scope, token) { const cached = readJsonFile(cp, null); if (cacheIsFresh(cached)) return cached.line; const result = await postBounded("collection.list", listBody(scope), { token, serverUrl: resolveServerUrl() }); + if (automaticSessionIsProtected()) return ""; let line = ""; try { line = renderCollectionsLine(result, allows); @@ -244,7 +252,12 @@ async function buildCodeBlock(scope, token, cwd) { : "# Loom code index: not inside a git checkout; set LOOM_CODE_REPO=/ " + "(or the plugin's code_repo option, or code_repo in ~/.loom/config.json) to use a repository's index.\n\n"; } - const post = (op, body, o) => postBounded(op, body, { ...o, serverUrl }); + const post = async (op, body, o) => { + if (automaticSessionIsProtected()) throw new SessionProtectionUnavailable(); + const result = await postBounded(op, body, { ...o, serverUrl }); + if (automaticSessionIsProtected()) throw new SessionProtectionUnavailable(); + return result; + }; const { entry, status } = await lookupIndexedRepo(root, { token, post, diff --git a/integrations/claude-code-plugin/hooks/loom-test-gate.mjs b/integrations/claude-code-plugin/hooks/loom-test-gate.mjs index b4084c7bfa..e3b27da68c 100644 --- a/integrations/claude-code-plugin/hooks/loom-test-gate.mjs +++ b/integrations/claude-code-plugin/hooks/loom-test-gate.mjs @@ -24,6 +24,7 @@ import { pathUnder, postBounded, readStdinJson, + runHookMain, DIFF_ARGS, diffHeaders, resolveServerUrl, @@ -140,4 +141,4 @@ async function main() { scheduleExit(0); } -main().catch(() => scheduleExit(0)); +runHookMain(main); diff --git a/integrations/claude-code-plugin/hooks/loom-validate-gate.mjs b/integrations/claude-code-plugin/hooks/loom-validate-gate.mjs index 13be736cde..2b5413f7a4 100644 --- a/integrations/claude-code-plugin/hooks/loom-validate-gate.mjs +++ b/integrations/claude-code-plugin/hooks/loom-validate-gate.mjs @@ -14,6 +14,7 @@ import { postBounded, readStdinJson, + runHookMain, resolveScope, resolveServerUrl, resolveToken, @@ -71,4 +72,4 @@ async function main() { scheduleExit(0); } -main().catch(() => scheduleExit(0)); +runHookMain(main); diff --git a/integrations/claude-code-plugin/lib/flush-job.mjs b/integrations/claude-code-plugin/lib/flush-job.mjs index 98bf476cb1..26d7c4693a 100644 --- a/integrations/claude-code-plugin/lib/flush-job.mjs +++ b/integrations/claude-code-plugin/lib/flush-job.mjs @@ -20,6 +20,8 @@ import os from "node:os"; import path from "node:path"; import { fileURLToPath } from "node:url"; +import { sessionIsProtected } from "./session-protection.mjs"; +import { sessionProtectionContext, withCapturedSessionProtection } from "./session-response.mjs"; import { writePrivateFile } from "./tmp-state.mjs"; const FLUSHER = fileURLToPath(new URL("../hooks/loom-flush.mjs", import.meta.url)); @@ -33,14 +35,20 @@ export function flushJobPath(tmp = os.tmpdir(), now = Date.now(), pid = process. * True when the flusher was started; false (job file removed) otherwise. */ export function dispatchFlush(job, { timeoutMs = 15000, spawnImpl = spawn, tmp } = {}) { + const roots = sessionProtectionContext()?.roots; + if (!roots?.length || roots.some(sessionIsProtected)) return false; const jobPath = flushJobPath(tmp); try { // The job carries session text: owner-only, like the other tmp state. - writePrivateFile(jobPath, JSON.stringify(job)); + writePrivateFile(jobPath, JSON.stringify({ ...job, protectionRoots: roots.map(({ base, id }) => ({ base, id })) })); } catch { return false; } try { + if (roots.some(sessionIsProtected)) { + fs.unlinkSync(jobPath); + return false; + } const child = spawnImpl(process.execPath, [FLUSHER, jobPath], { detached: true, stdio: "ignore", @@ -73,30 +81,48 @@ export function dispatchFlush(job, { timeoutMs = 15000, spawnImpl = spawn, tmp } */ export async function runFlushJob(input, { post, cursor, noteRecording = () => {} }) { const job = input && typeof input === "object" ? input : {}; - const appends = Array.isArray(job.appends) ? job.appends : []; - const posts = (Array.isArray(job.posts) ? job.posts : []).filter((p) => p && typeof p.op === "string" && p.body); - const settled = async (calls) => - (await Promise.allSettled(calls)).map((r) => (r.status === "fulfilled" ? r.value : null)); - - let postsOk = false; - if (posts.length) { - const replies = await settled(posts.map((p) => post(p.op, p.body))); - postsOk = replies.every(Boolean); - } - // A sender that moved its cursor ahead optimistically names rollbackTo: on - // failure the cursor goes back, unless a later job has moved it on since. - if (!appends.length && job.cursorPath && Number.isInteger(job.rollbackTo) && !postsOk) { - if (cursor.read(job.cursorPath).trim() === String(job.advanceTo)) cursor.write(job.cursorPath, job.rollbackTo); + const roots = Object.freeze( + (Array.isArray(job.protectionRoots) ? job.protectionRoots : []).map((root) => + Object.freeze({ base: root?.base, id: root?.id }), + ), + ); + const protectedNow = () => !roots.length || roots.some(sessionIsProtected); + const rollback = () => { + if (!(Array.isArray(job.appends) && job.appends.length) && job.cursorPath && Number.isInteger(job.rollbackTo)) { + if (cursor.read(job.cursorPath).trim() === String(job.advanceTo)) cursor.write(job.cursorPath, job.rollbackTo); + } + }; + if (protectedNow()) { + rollback(); + return { postsOk: false, appendsOk: false }; } + const result = withCapturedSessionProtection(roots, async () => { + const send = (op, body) => (protectedNow() ? null : post(op, body)); + const appends = Array.isArray(job.appends) ? job.appends : []; + const posts = (Array.isArray(job.posts) ? job.posts : []).filter((p) => p && typeof p.op === "string" && p.body); + const settled = async (calls) => + (await Promise.allSettled(calls)).map((r) => (r.status === "fulfilled" ? r.value : null)); - let appendsOk = false; - if (appends.length) { - const replies = await settled(appends.map((a) => post("conversation.append", a))); - appendsOk = replies.every(Boolean); - noteRecording(appends, replies); - // The cursor moves only when every turn landed; otherwise the next Stop - // re-reads and retries (msg_id makes a resend idempotent). - if (appendsOk && job.cursorPath && Number.isInteger(job.advanceTo)) cursor.write(job.cursorPath, job.advanceTo); - } - return { postsOk, appendsOk }; + let postsOk = false; + if (posts.length) { + const replies = await settled(posts.map((p) => send(p.op, p.body))); + postsOk = replies.every(Boolean) && !protectedNow(); + } + // A failed or suppressed post must not acknowledge an optimistic cursor. + if (!postsOk) rollback(); + + let appendsOk = false; + if (appends.length) { + const replies = await settled(appends.map((a) => send("conversation.append", a))); + appendsOk = replies.every(Boolean) && !protectedNow(); + if (!protectedNow()) noteRecording(appends, replies); + if (appendsOk && !protectedNow() && job.cursorPath && Number.isInteger(job.advanceTo)) { + cursor.write(job.cursorPath, job.advanceTo); + } + } + return { postsOk, appendsOk }; + }); + if (result !== undefined) return result; + rollback(); + return { postsOk: false, appendsOk: false }; } diff --git a/integrations/claude-code-plugin/lib/hook-protection.mjs b/integrations/claude-code-plugin/lib/hook-protection.mjs new file mode 100644 index 0000000000..8699e179e0 --- /dev/null +++ b/integrations/claude-code-plugin/lib/hook-protection.mjs @@ -0,0 +1,62 @@ +// Native startup declares a root; inherited and passive hooks resolve known state. +import { + establishProtectionAlias, + findProtectionAlias, + protectSession, + SessionProtectionUnavailable, +} from "./session-protection.mjs"; + +function sameRoot(first, second) { + return first?.base === second?.base && first?.id === second?.id; +} + +function refuse(roots) { + for (const root of roots) { + try { + protectSession(root); + } catch { + // A failed mark must not leave another known contributor clean. + } + } + throw new SessionProtectionUnavailable(); +} + +/** Only an explicit native startup establishes its first application-owned anchor. */ +export function bindHookProtection(payload, { host, event, base, knownRoots = [] } = {}) { + const roots = [...knownRoots]; + try { + if ( + !["claude-code", "codex", "cline"].includes(host) || + !payload || + typeof payload !== "object" || + Array.isArray(payload) || + typeof payload.session_id !== "string" || + !payload.session_id || + payload.session_id.length > 1024 + ) + throw new SessionProtectionUnavailable(); + // Resolve this anchor even when another known contributor is unusable. + const startup = + !roots.length && + ["claude-code", "codex"].includes(host) && + event === "SessionStart" && + payload.hook_event_name === "SessionStart" && + payload.source === "startup"; + // The initializer waits for concurrent publication before inspecting it. + const root = startup + ? establishProtectionAlias(host, payload.session_id, { base }) + : findProtectionAlias(host, payload.session_id, { base }); + if (root) roots.push(root); + if ( + typeof event !== "string" || + !event || + (payload.hook_event_name !== undefined && payload.hook_event_name !== event) + ) { + throw new SessionProtectionUnavailable(); + } + if (!root || roots.some((anchor) => !sameRoot(anchor, root))) throw new SessionProtectionUnavailable(); + return root; + } catch { + return refuse(roots); + } +} diff --git a/integrations/claude-code-plugin/lib/loom-client.mjs b/integrations/claude-code-plugin/lib/loom-client.mjs index 01b9c6668a..f34af8385d 100644 --- a/integrations/claude-code-plugin/lib/loom-client.mjs +++ b/integrations/claude-code-plugin/lib/loom-client.mjs @@ -31,6 +31,16 @@ import { fileURLToPath } from "node:url"; // than that, and a shorter grace would kill a fire-and-forget post before it // left a slow link. import { DEFAULT_BOUND_MS, boundMs, rttCachePath } from "./hook-bounds.mjs"; +import { bindHookProtection } from "./hook-protection.mjs"; +import { SessionProtectionUnavailable } from "./session-protection.mjs"; +import { + automaticSessionIsProtected, + observeSessionResponse, + observeSessionResponses, + refuseSessionResponse, + sessionProtectionContext, + withAutomaticSessionProtection, +} from "./session-response.mjs"; import { readJsonFile, tmpStatePath, writeJsonFile } from "./tmp-state.mjs"; let _rttCache; @@ -731,6 +741,10 @@ export async function requestJson( { method = "POST", body, token = "", timeoutMs = requestTimeoutMs(), headers = {}, fetchImpl = fetch } = {}, ) { try { + const protection = sessionProtectionContext(); + if (protection?.automatic && automaticSessionIsProtected()) { + return { status: 0, body: null, suppressed: true }; + } const res = await fetchImpl(url, { method, headers: { @@ -741,11 +755,18 @@ export async function requestJson( ...(body === undefined ? {} : { body: JSON.stringify(body) }), signal: AbortSignal.timeout(timeoutMs), }); + if (res.status === 204 || res.status === 304) return { status: res.status, body: null }; let parsed = null; try { parsed = await res.json(); } catch { - /* an error body may not be JSON */ + if (protection) refuseSessionResponse(protection.roots); + /* an unbound error body may not be JSON */ + } + if (protection) { + if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) refuseSessionResponse(protection.roots); + observeSessionResponses(protection.roots, parsed); + if (protection.automatic && automaticSessionIsProtected()) throw new SessionProtectionUnavailable(); } return { status: res.status, body: parsed }; } catch (e) { @@ -1009,11 +1030,23 @@ export function diffHeaders(diff, max) { * fails the host session. With LOOM_HOOK_DEBUG=on the error's first line, * redacted, goes to stderr, which is how a broken hook shows itself. */ -export function runHookMain(main) { - Promise.resolve() - .then(main) +export function runHookMain(main, { detachedJob = false } = {}) { + return Promise.resolve() + .then(async () => { + // A detached flusher restores only the producer roots in its private job. + if (detachedJob) return main(); + const raw = await rawHookPayload(); + const root = bindHookProtection(raw, { + host: process.argv[3] || "claude-code", + event: process.argv[2], + knownRoots: sessionProtectionContext()?.roots, + }); + const reply = normalizePayload(raw).tool_response; + observeSessionResponse(root, typeof reply === "string" ? { content: [{ type: "text", text: reply }] } : reply); + return withAutomaticSessionProtection(root, main); + }) .catch((e) => { - if (envSwitch("LOOM_HOOK_DEBUG", false)) { + if (!(e instanceof SessionProtectionUnavailable) && envSwitch("LOOM_HOOK_DEBUG", false)) { const line = String((e && (e.stack || e.message)) || e).split("\n")[0]; process.stderr.write(`loom hook ${basename(process.argv[1] || "")}: ${redactHead(line, 300).slice(0, 300)}\n`); } @@ -1079,16 +1112,18 @@ export function normalizePayload(raw) { * gives up waiting after a second, so a host that never closes stdin * cannot hold a hook open. */ const MAX_STDIN_CHARS = 32 * 1024 * 1024; +let hookPayload; -export function readStdinJson() { - return new Promise((resolve) => { +function rawHookPayload() { + hookPayload ??= new Promise((resolve) => { let raw = ""; let settled = false; const done = () => { if (settled) return; settled = true; try { - resolve(normalizePayload(raw.trim() ? JSON.parse(raw) : {})); + const payload = raw.trim() ? JSON.parse(raw) : {}; + resolve(payload && typeof payload === "object" && !Array.isArray(payload) ? payload : {}); } catch { resolve({}); } @@ -1110,4 +1145,9 @@ export function readStdinJson() { } setTimeout(done, 1000).unref(); }); + return hookPayload; +} + +export function readStdinJson() { + return rawHookPayload().then(normalizePayload); } diff --git a/integrations/claude-code-plugin/lib/session-protection.mjs b/integrations/claude-code-plugin/lib/session-protection.mjs index 2a4fca2a22..0374129708 100644 --- a/integrations/claude-code-plugin/lib/session-protection.mjs +++ b/integrations/claude-code-plugin/lib/session-protection.mjs @@ -7,9 +7,11 @@ import os from "node:os"; import path from "node:path"; import { readPrivateFile } from "./tmp-state.mjs"; +import { windowsSessionProtection, windowsFailureDiagnostic } from "./windows-session-protection.mjs"; const ROOT_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/; const VERSION = 1; +const ALIAS_CLAIM_MS = 500; const defaultBase = () => path.join(os.homedir(), ".loom", "session-protection", "v1"); export class SessionProtectionUnavailable extends Error { @@ -19,12 +21,25 @@ export class SessionProtectionUnavailable extends Error { } } +function protectionUnavailable(error) { + const unavailable = new SessionProtectionUnavailable(); + const diagnostic = windowsFailureDiagnostic(error); + if (diagnostic) { + Object.defineProperty(unavailable, "cause", { value: diagnostic, enumerable: true }); + // TAP preserves the original error code when it unwraps a test failure. + const code = `LSP1:${diagnostic.phase}:${diagnostic.exitCode ?? "_"}:${diagnostic.workerExit ?? "_"}:${diagnostic.signal}:${diagnostic.errorCode ?? "_"}:${diagnostic.elapsedMs}:${Number(diagnostic.timedOut)}:${diagnostic.stdoutUnits}:${diagnostic.stderrUnits}:${diagnostic.validFrames}:${diagnostic.rejectedLines}:${diagnostic.helperErrorCode ?? "_"}:${diagnostic.lastValidatedPhase}`; + Object.defineProperty(unavailable, "code", { value: code, enumerable: true }); + } + return unavailable; +} + function privateDirectory(directory) { // POSIX mode bits do not establish Windows DACL authority. if (process.platform === "win32" || typeof process.getuid !== "function") throw new SessionProtectionUnavailable(); const st = fs.lstatSync(directory); if (!st.isDirectory() || st.isSymbolicLink() || (st.mode & 0o077) !== 0) throw new SessionProtectionUnavailable(); if (typeof process.getuid === "function" && st.uid !== process.getuid()) throw new SessionProtectionUnavailable(); + return st; } function syncDirectory(directory) { @@ -76,6 +91,9 @@ function durableCreate(file, value) { export function createProtectionRoot({ base = defaultBase() } = {}) { try { if (!path.isAbsolute(base)) throw new SessionProtectionUnavailable(); + if (process.platform === "win32") { + return Object.freeze({ base, id: windowsSessionProtection("create", { base }) }); + } fs.mkdirSync(base, { recursive: true, mode: 0o700 }); privateDirectory(base); const root = Object.freeze({ base, id: crypto.randomUUID() }); @@ -86,14 +104,15 @@ export function createProtectionRoot({ base = defaultBase() } = {}) { syncDirectory(base); if (sessionIsProtected(root)) throw new SessionProtectionUnavailable(); return root; - } catch { - throw new SessionProtectionUnavailable(); + } catch (error) { + throw protectionUnavailable(error); } } /** Unknown, damaged or inaccessible state suppresses automatic sends. */ export function sessionIsProtected(root) { try { + if (process.platform === "win32") return windowsSessionProtection("inspect", root); const directory = location(root); return privateText(path.join(directory, "state")) !== "0\n"; } catch { @@ -104,6 +123,10 @@ export function sessionIsProtected(root) { /** Complete this durable write before exposing a mirrored response to its caller. */ export function protectSession(root) { try { + if (process.platform === "win32") { + windowsSessionProtection("protect", root); + return; + } const directory = location(root); // A missing record is unknown, never a clean session. Append-only state // also turns a partial write into protection rather than a false absence. @@ -120,8 +143,8 @@ export function protectSession(root) { } finally { fs.closeSync(fd); } - } catch { - throw new SessionProtectionUnavailable(); + } catch (error) { + throw protectionUnavailable(error); } } @@ -150,8 +173,8 @@ function aliasDirectory(base, create = false) { return directory; } -function readAlias(file, key) { - const record = JSON.parse(privateText(file)); +function parseAlias(text, key) { + const record = JSON.parse(text); if ( !record || record.version !== VERSION || @@ -164,29 +187,187 @@ function readAlias(file, key) { return record.root; } +function readAlias(file, key) { + return parseAlias(privateText(file), key); +} + +function sameDirectory(directory, receipt) { + const current = privateDirectory(directory); + if (current.dev !== receipt.dev || current.ino !== receipt.ino) throw new SessionProtectionUnavailable(); +} + +function confirmPublishedAlias(base, key) { + const directory = aliasDirectory(base); + const file = path.join(directory, key + ".json"); + const fd = fs.openSync(file, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW ?? 0) | (fs.constants.O_NONBLOCK ?? 0)); + let root; + try { + const held = fs.fstatSync(fd); + const current = fs.lstatSync(file); + if ( + !held.isFile() || + held.nlink !== 1 || + held.size > 65536 || + (held.mode & 0o077) !== 0 || + held.uid !== process.getuid() || + held.dev !== current.dev || + held.ino !== current.ino + ) + throw new SessionProtectionUnavailable(); + const bytes = Buffer.alloc(held.size); + if (fs.readSync(fd, bytes, 0, bytes.length, 0) !== bytes.length || fs.fstatSync(fd).size !== bytes.length) { + throw new SessionProtectionUnavailable(); + } + root = Object.freeze({ base, id: parseAlias(bytes.toString("utf8"), key) }); + location(root); + fs.fsyncSync(fd); + } finally { + fs.closeSync(fd); + } + syncDirectory(directory); + syncDirectory(base); + return root; +} + +function privateClaim(claim) { + const st = fs.lstatSync(claim); + if (!st.isFile() || st.nlink !== 1 || st.size !== 0 || (st.mode & 0o077) !== 0 || st.uid !== process.getuid()) { + throw new SessionProtectionUnavailable(); + } + return st; +} + +function withAliasClaim(base, key, operation, boundRoot) { + const directory = aliasDirectory(base, true); + const flags = fs.constants.O_RDONLY | fs.constants.O_DIRECTORY | (fs.constants.O_NOFOLLOW ?? 0); + const directoryFd = fs.openSync(directory, flags); + let directoryReceipt; + const claim = path.join(directory, key + ".claim"); + let claimFd; + let receipt; + const checkReceipt = () => { + sameDirectory(directory, directoryReceipt); + const current = privateClaim(claim); + const held = fs.fstatSync(claimFd); + if ( + current.dev !== receipt.dev || + current.ino !== receipt.ino || + held.dev !== receipt.dev || + held.ino !== receipt.ino + ) { + throw new SessionProtectionUnavailable(); + } + }; + try { + directoryReceipt = fs.fstatSync(directoryFd); + sameDirectory(directory, directoryReceipt); + const deadline = performance.now() + ALIAS_CLAIM_MS; + const wait = new Int32Array(new SharedArrayBuffer(4)); + for (;;) { + if (performance.now() >= deadline) throw new SessionProtectionUnavailable(); + sameDirectory(directory, directoryReceipt); + try { + // Exclusive open returns the exact created object, with no mkdir/open gap. + claimFd = fs.openSync( + claim, + fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL | (fs.constants.O_NOFOLLOW ?? 0), + 0o600, + ); + break; + } catch (error) { + if (error?.code !== "EEXIST") throw error; + try { + privateClaim(claim); + } catch (claimError) { + if (claimError?.code !== "ENOENT") throw claimError; + } + let published; + try { + published = confirmPublishedAlias(base, key); + } catch { + // A busy publisher can expose incomplete bytes; never repair them. + } + if (published) { + if (boundRoot && boundRoot.id !== published.id) throw new SessionProtectionUnavailable(); + return published; + } + const remaining = deadline - performance.now(); + if (remaining <= 0) throw new SessionProtectionUnavailable(); + Atomics.wait(wait, 0, 0, Math.min(10, remaining)); + } + } + receipt = fs.fstatSync(claimFd); + checkReceipt(); + fs.fsyncSync(claimFd); + syncDirectory(directory); + const result = operation(); + checkReceipt(); + return result; + } finally { + try { + // Retain the marker on success, failure and crash. A complete alias is + // reusable; an unpublished claim never authorizes another initializer. + if (claimFd !== undefined) fs.closeSync(claimFd); + } finally { + fs.closeSync(directoryFd); + } + } +} + +function publishAlias(root, key) { + location(root); + const directory = aliasDirectory(root.base, true); + const file = path.join(directory, key + ".json"); + try { + durableCreate(file, JSON.stringify({ version: VERSION, identity: key, root: root.id })); + } catch (error) { + if (error?.code !== "EEXIST" || readAlias(file, key) !== root.id) throw error; + // Confirm another initializer's data before a caller relies on the alias. + const fd = fs.openSync(file, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW ?? 0)); + try { + fs.fsyncSync(fd); + } finally { + fs.closeSync(fd); + } + syncDirectory(directory); + } + syncDirectory(root.base); +} + /** Bind only a verified host identity; an existing alias can never choose a new root. */ export function bindProtectionAlias(root, host, identity) { try { + if (process.platform === "win32") { + windowsSessionProtection("bind", { ...root, key: aliasKey(host, identity) }); + return; + } location(root); const key = aliasKey(host, identity); - const directory = aliasDirectory(root.base, true); - const file = path.join(directory, key + ".json"); - try { - durableCreate(file, JSON.stringify({ version: VERSION, identity: key, root: root.id })); - } catch (error) { - if (error?.code !== "EEXIST" || readAlias(file, key) !== root.id) throw error; - // Confirm another initializer's data before a caller relies on the alias. - const fd = fs.openSync(file, fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW ?? 0)); - try { - fs.fsyncSync(fd); - } finally { - fs.closeSync(fd); - } - syncDirectory(directory); + withAliasClaim(root.base, key, () => publishAlias(root, key), root); + } catch (error) { + throw protectionUnavailable(error); + } +} + +/** Only a verified new-session declaration may call this atomic initializer. */ +export function establishProtectionAlias(host, identity, { base = defaultBase() } = {}) { + try { + const key = aliasKey(host, identity); + if (typeof base !== "string" || !path.isAbsolute(base)) throw new SessionProtectionUnavailable(); + if (process.platform === "win32") { + return Object.freeze({ base, id: windowsSessionProtection("establish", { base, key }) }); } - syncDirectory(root.base); - } catch { - throw new SessionProtectionUnavailable(); + fs.mkdirSync(base, { recursive: true, mode: 0o700 }); + privateDirectory(base); + return withAliasClaim(base, key, () => { + const existing = findProtectionAlias(host, identity, { base }); + if (existing) return existing; + const root = createProtectionRoot({ base }); + publishAlias(root, key); + return root; + }); + } catch (error) { + throw protectionUnavailable(error); } } @@ -194,6 +375,10 @@ export function bindProtectionAlias(root, host, identity) { export function findProtectionAlias(host, identity, { base = defaultBase() } = {}) { try { const key = aliasKey(host, identity); + if (process.platform === "win32") { + const id = windowsSessionProtection("find", { base, key }); + return id === null ? undefined : Object.freeze({ base, id }); + } let id; try { const directory = aliasDirectory(base); @@ -205,8 +390,8 @@ export function findProtectionAlias(host, identity, { base = defaultBase() } = { const root = Object.freeze({ base, id }); location(root); return root; - } catch { - throw new SessionProtectionUnavailable(); + } catch (error) { + throw protectionUnavailable(error); } } diff --git a/integrations/claude-code-plugin/lib/session-response.mjs b/integrations/claude-code-plugin/lib/session-response.mjs new file mode 100644 index 0000000000..87442f3664 --- /dev/null +++ b/integrations/claude-code-plugin/lib/session-response.mjs @@ -0,0 +1,134 @@ +// Response observation precedes the caller's rendering and automatic callbacks. +// A binding is application-owned; it is never selected by wire arguments. + +import { AsyncLocalStorage } from "node:async_hooks"; + +import { protectSession, sessionIsProtected, SessionProtectionUnavailable } from "./session-protection.mjs"; + +const context = new AsyncLocalStorage(); +const MAX_ENVELOPES = 10000; +const MAX_TEXT_BYTES = 4 * 1024 * 1024; + +export function sessionProtectionContext() { + return context.getStore(); +} + +/** Automatic work never treats missing lineage as a clean family. */ +export function automaticSessionIsProtected() { + const roots = context.getStore()?.roots; + return !roots?.length || roots.some(sessionIsProtected); +} + +function retainedRoots(roots) { + const known = new Map(); + for (const root of roots) { + const copy = Object.freeze({ base: root?.base, id: root?.id }); + known.set(JSON.stringify([copy.base, copy.id]), copy); + } + return Object.freeze([...known.values()]); +} + +function joinedRoots(root) { + return retainedRoots([...(context.getStore()?.roots ?? []), root]); +} + +/** Explicit operations remain available while retaining every response observer. */ +export function withSessionProtection(root, callback) { + return context.run(Object.freeze({ roots: joinedRoots(root), automatic: false }), callback); +} + +/** A detached producer resumes its own frozen control, independent of its flusher. */ +export function withCapturedSessionProtection(roots, callback) { + const retained = retainedRoots(roots); + if (!retained.length || retained.some(sessionIsProtected)) return undefined; + return context.run(Object.freeze({ roots: retained, automatic: true }), callback); +} + +/** Nested automatic callbacks cannot drop any contributing parent's protection. */ +export function withAutomaticSessionProtection(root, callback) { + return withCapturedSessionProtection(joinedRoots(root), callback); +} + +function markedEnvelope(value) { + const pending = [value]; + const visited = new Set(); + let remaining = MAX_ENVELOPES; + let textBytes = MAX_TEXT_BYTES; + while (pending.length) { + if (--remaining < 0) throw new SessionProtectionUnavailable(); + const item = pending.pop(); + if (!item || typeof item !== "object" || Array.isArray(item)) continue; + if (visited.has(item)) throw new SessionProtectionUnavailable(); + visited.add(item); + if (Object.hasOwn(item, "mirrored") && typeof item.mirrored !== "boolean") { + throw new SessionProtectionUnavailable(); + } + if (item.mirrored === true) return true; + for (const key of ["result", "structuredContent"]) { + if (item[key] && typeof item[key] === "object") pending.push(item[key]); + } + // JSON-RPC failures retain response metadata in error.data after unwrapping. + if (item.error && typeof item.error === "object" && item.error.data && typeof item.error.data === "object") { + pending.push(item.error.data); + } + if (Array.isArray(item.items)) { + if (pending.length + item.items.length > remaining) throw new SessionProtectionUnavailable(); + pending.push(...item.items); + } + if (Array.isArray(item.content)) { + if (pending.length + item.content.length > remaining) throw new SessionProtectionUnavailable(); + remaining -= item.content.length; + for (const content of item.content) { + if (content?.type !== "text" || typeof content.text !== "string") continue; + // Charge every block before parsing; repeated source text must not + // allocate a separate unbounded decoded object for each occurrence. + if (content.text.length > textBytes) throw new SessionProtectionUnavailable(); + textBytes -= Buffer.byteLength(content.text, "utf8"); + if (textBytes < 0) throw new SessionProtectionUnavailable(); + const text = content.text.trim(); + if (!text.startsWith("{")) continue; + try { + pending.push(JSON.parse(text)); + } catch { + throw new SessionProtectionUnavailable(); + } + } + } + } + return false; +} + +function markEveryFamily(roots) { + let failed = false; + for (const root of roots) { + try { + protectSession(root); + } catch { + failed = true; + } + } + return failed; +} + +/** Unknown response state protects every known family before withholding output. */ +export function refuseSessionResponse(roots) { + markEveryFamily(roots); + throw new SessionProtectionUnavailable(); +} + +/** Parse once and attempt every durable mark, including after another mark fails. */ +export function observeSessionResponses(roots, value) { + let marked; + try { + marked = markedEnvelope(value); + } catch { + return refuseSessionResponse(roots); + } + if (marked && markEveryFamily(roots)) throw new SessionProtectionUnavailable(); + return value; +} + +/** Consume only response envelopes; arbitrary arguments cannot choose a binding. */ +export function observeSessionResponse(root, value) { + return observeSessionResponses(joinedRoots(root), value); +} diff --git a/integrations/claude-code-plugin/lib/shunt-ledger.mjs b/integrations/claude-code-plugin/lib/shunt-ledger.mjs index 1959975977..0c15237c09 100644 --- a/integrations/claude-code-plugin/lib/shunt-ledger.mjs +++ b/integrations/claude-code-plugin/lib/shunt-ledger.mjs @@ -6,6 +6,7 @@ // per pass reason), so tokens kept out and let in are a production series. import { createHash } from "node:crypto"; +import path from "node:path"; import { PASS_REASONS, readSpan } from "./code-shunt.mjs"; @@ -19,7 +20,75 @@ export const SHUNT_CLIENT_SOURCE = "claude-code-shunt"; export function batchKind({ serverUrl = "", token = "", org = "", namespace = "" } = {}) { const tokenId = createHash("sha256").update(String(token)).digest("hex").slice(0, 16); const scope = createHash("sha256").update(`${serverUrl}|${tokenId}|${org}/${namespace}`).digest("hex").slice(0, 12); - return `shunt-pending-${scope}`; + // Older consumers select shunt-pending; they must not consume root-aware rows. + return `shunt-protected-${scope}`; +} + +const ROOT_ID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/; +const MAX_BATCH_BYTES = 4 * 1024 * 1024; + +function batchRoots(roots) { + if (!Array.isArray(roots) || !roots.length) return null; + const known = new Map(); + for (const root of roots) { + if ( + !root || + typeof root !== "object" || + Array.isArray(root) || + Object.keys(root).sort().join(",") !== "base,id" || + typeof root.base !== "string" || + !path.isAbsolute(root.base) || + typeof root.id !== "string" || + !ROOT_ID.test(root.id) + ) + return null; + const copy = Object.freeze({ base: root.base, id: root.id }); + known.set(JSON.stringify([copy.base, copy.id]), copy); + } + return Object.freeze([...known.values()]); +} + +function validDecisionLine(line) { + if (typeof line !== "string" || !line.endsWith("\n") || line.slice(0, -1).includes("\n")) return false; + const cells = line.slice(0, -1).split("\t"); + return cells.length === 9 && ["hit", "pass"].includes(cells[1]); +} + +/** Only the producer's captured context supplies roots; log fields carry no authority. */ +export function formatShuntBatchLine(line, roots) { + const retained = batchRoots(roots); + if (!retained || !validDecisionLine(line)) return null; + return JSON.stringify({ version: 1, protectionRoots: retained, line }) + "\n"; +} + +/** Any unattributed or damaged row withholds the entire batch, preserving its bytes. */ +export function parseShuntBatch(text) { + if (typeof text !== "string" || !text || !text.endsWith("\n") || Buffer.byteLength(text, "utf8") > MAX_BATCH_BYTES) + return null; + const roots = []; + const lines = []; + for (const raw of text.slice(0, -1).split("\n")) { + let row; + try { + row = JSON.parse(raw); + } catch { + return null; + } + if ( + !row || + typeof row !== "object" || + Array.isArray(row) || + Object.keys(row).sort().join(",") !== "line,protectionRoots,version" || + row.version !== 1 || + !validDecisionLine(row.line) + ) + return null; + const retained = batchRoots(row.protectionRoots); + if (!retained) return null; + roots.push(...retained); + lines.push(row.line); + } + return Object.freeze({ roots: batchRoots(roots), text: lines.join(""), lines: lines.length }); } /** Tokens the model did not ingest because a hit denied the read: bytes/4 diff --git a/integrations/claude-code-plugin/lib/tmp-state.mjs b/integrations/claude-code-plugin/lib/tmp-state.mjs index 07433b5270..164ad79324 100644 --- a/integrations/claude-code-plugin/lib/tmp-state.mjs +++ b/integrations/claude-code-plugin/lib/tmp-state.mjs @@ -159,10 +159,10 @@ export function writeCursor(file, n) { } export const STALE_STATE_MS = 24 * 60 * 60 * 1000; -// tmpStatePath's names but the code shunt's decision log (a log the user reads, not -// session state), and the recalled-key and code-trace stashes named by session id. +// Decision logs and unacknowledged shunt queues/claims retain their evidence. +// Other tmpStatePath names and recalled-key/code-trace stashes expire. const STATE_FILE_RE = - /^loom-(?!shunt-log-)(?:[a-z0-9-]+-[0-9a-f]{12}(?:\.[a-z]+)?|(?:recalled|code-trace)-[\w-]+\.json)$/; + /^loom-(?!shunt-(?:log|pending|protected|claim)-)(?:[a-z0-9-]+-[0-9a-f]{12}(?:\.[a-z]+)?|(?:recalled|code-trace)-[\w-]+\.json)$/; /** Remove this user's state files in `tmp` untouched for `maxAgeMs`: a session's * journal and cursors outlive it, since SessionEnd hooks run in parallel and none diff --git a/integrations/claude-code-plugin/lib/windows-compiler-job.ps1 b/integrations/claude-code-plugin/lib/windows-compiler-job.ps1 new file mode 100644 index 0000000000..f87188105e --- /dev/null +++ b/integrations/claude-code-plugin/lib/windows-compiler-job.ps1 @@ -0,0 +1,263 @@ +# Native timer callbacks contain emitted IL only; they need no PowerShell +# runspace, managed timer, Node event loop or compiler to stop a blocked worker. +$script:loomTimerRoots = [System.Collections.Generic.List[System.Delegate]]::new() +function Start-LoomNativeTimer([type]$native, [string]$method, [IntPtr]$context, [long]$deadline) { + Write-LoomProtectionPhase 'native-timer' + $callbackType = $native.Assembly.GetType('LoomNativeTimerCallback', $true) + $callback = [Delegate]::CreateDelegate($callbackType, $native.GetMethod($method)) + $script:loomTimerRoots.Add($callback) + $pointer = [Runtime.InteropServices.Marshal]::GetFunctionPointerForDelegate($callback) + $timer = [IntPtr]::Zero + # Callback and job setup consume the same absolute operation budget. + $remaining = $deadline - [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() + if ($remaining -le 0 -or $remaining -gt 1500) { throw 'Unavailable' } + # A one-shot callback on the native timer thread performs one short API call. + if (-not $native::CreateTimerQueueTimer([ref]$timer, [IntPtr]::Zero, $pointer, $context, ([uint32]$remaining), 0, 0x28)) { + $nativeCode = [Runtime.InteropServices.Marshal]::GetLastWin32Error() + Write-LoomProtectionPhase 'native-timer' $nativeCode + throw 'Unavailable' + } + # Timers and delegate roots live through OS exit; no stale handle reuse. +} + +function Start-LoomGuardianDeadline([type]$native) { + Write-LoomProtectionPhase 'guardian-deadline' + $deadline = 0L + if (-not [long]::TryParse($env:LOOM_PRIVATE_DEADLINE_UTC, [ref]$deadline)) { throw 'Unavailable' } + $now = [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() + $remaining = $deadline - $now + if ($remaining -le 0) { throw 'Unavailable' } + # Anchor both native deadlines before creating or assigning either job. + $remaining = [Math]::Min(1500L, $remaining) + $deadline = $now + $remaining + # An outer self-job covers worker creation as well as compilation. Even + # death between Process.Start and inner assignment closes this handle. + $outer = New-LoomCompilerJob $native + if (-not $native::AssignProcessToJobObject($outer, $native::GetCurrentProcess())) { + $nativeCode = [Runtime.InteropServices.Marshal]::GetLastWin32Error() + Write-LoomProtectionPhase 'native-job' $nativeCode + throw 'Unavailable' + } + Start-LoomNativeTimer $native 'StopJob' $outer $deadline + return @{ Deadline = $deadline; Job = $outer } +} + +function New-LoomCompilerJob([type]$native) { + Write-LoomProtectionPhase 'native-job' + $handle = $native::CreateJobObjectW([IntPtr]::Zero, [IntPtr]::Zero) + if ($handle -eq [IntPtr]::Zero) { + $nativeCode = [Runtime.InteropServices.Marshal]::GetLastWin32Error() + Write-LoomProtectionPhase 'native-job' $nativeCode + throw 'Unavailable' + } + $size = if ([IntPtr]::Size -eq 8) { 144 } else { 112 } + $limits = [Runtime.InteropServices.Marshal]::AllocHGlobal($size) + try { + [Runtime.InteropServices.Marshal]::Copy(([byte[]]::new($size)), 0, $limits, $size) + [Runtime.InteropServices.Marshal]::WriteInt32($limits, 16, 0x2000) + if (-not $native::SetInformationJobObject($handle, 9, $limits, $size)) { + $nativeCode = [Runtime.InteropServices.Marshal]::GetLastWin32Error() + Write-LoomProtectionPhase 'native-job' $nativeCode + throw 'Unavailable' + } + return $handle + } catch { + [void]$native::CloseHandle($handle) + throw + } finally { [Runtime.InteropServices.Marshal]::FreeHGlobal($limits) } +} + +# Compiler output stays inside the exclusive invocation directory. Only bounded +# counts, fixed format tags and numeric compiler IDs leave, never text or paths. +function Write-LoomCompilerCodes([string]$file) { + $stream = [IO.File]::Open($file, [IO.FileMode]::Open, [IO.FileAccess]::Read, [IO.FileShare]::Read) + try { + $bytes = [byte[]]::new(8192) + $count = $stream.Read($bytes, 0, $bytes.Length) + $text = [Text.Encoding]::ASCII.GetString($bytes, 0, $count) + $pattern = '^(?:[^\r\n]{1,2048}\([0-9]{1,6}(?:,[0-9]{1,6})?\): )?(?:fatal error|error|warning) CS([0-9]{4}):' + $codes = [Collections.Generic.HashSet[int]]::new() + foreach ($line in $text.Split([char]10)) { + $match = [Text.RegularExpressions.Regex]::Match($line, $pattern) + if ($match.Success) { + $code = [int]::Parse($match.Groups[1].Value, [Globalization.CultureInfo]::InvariantCulture) + if ($codes.Add($code)) { Write-LoomProtectionPhase 'compile' $code } + if ($codes.Count -ge 4) { break } + } + } + } finally { $stream.Dispose() } + # These tags describe the bounded prefix; they do not choose a decoder. + $format = 6 + if ($count -eq 0) { $format = 0 } + elseif ($count -ge 4 -and $bytes[0] -eq 255 -and $bytes[1] -eq 254 -and $bytes[2] -eq 0 -and $bytes[3] -eq 0) { $format = 4 } + elseif ($count -ge 4 -and $bytes[0] -eq 0 -and $bytes[1] -eq 0 -and $bytes[2] -eq 254 -and $bytes[3] -eq 255) { $format = 5 } + elseif ($count -ge 3 -and $bytes[0] -eq 239 -and $bytes[1] -eq 187 -and $bytes[2] -eq 191) { $format = 1 } + elseif ($count -ge 2 -and $bytes[0] -eq 255 -and $bytes[1] -eq 254) { $format = 2 } + elseif ($count -ge 2 -and $bytes[0] -eq 254 -and $bytes[1] -eq 255) { $format = 3 } + Write-LoomProtectionPhase 'compiler-bytes' $count + Write-LoomProtectionPhase 'compiler-format' $format + Write-LoomProtectionPhase 'compiler-scanned' +} + +# All callers supply fixed plugin/test arguments. Session JSON never selects +# the application, command line, environment, working directory or source. +function Invoke-LoomCompilerProcess([type]$native, [IntPtr]$job, [long]$deadline, + [string]$directory, [string]$arguments, [scriptblock]$observe = $null) { + $application = [IO.Path]::Combine([Runtime.InteropServices.RuntimeEnvironment]::GetRuntimeDirectory(), 'csc.exe') + if ($application.Contains('"')) { throw 'Unavailable' } + $command = [Text.StringBuilder]::new('"' + $application + '" ' + $arguments) + $attributeList = $startup = $information = $handleList = $security = $environment = [IntPtr]::Zero + $nul = $compilerLog = $process = $thread = [IntPtr]::Zero + $attributesInitialized = $false + $compilerLogPath = [IO.Path]::Combine($directory, 'compiler-output.log') + try { + $pointerSize = [IntPtr]::Size + $startupSize = if ($pointerSize -eq 8) { 104 } else { 68 } + $extendedSize = $startupSize + $pointerSize + $startup = [Runtime.InteropServices.Marshal]::AllocHGlobal($extendedSize) + [Runtime.InteropServices.Marshal]::Copy([byte[]]::new($extendedSize), 0, $startup, $extendedSize) + [Runtime.InteropServices.Marshal]::WriteInt32($startup, 0, $extendedSize) + $information = [Runtime.InteropServices.Marshal]::AllocHGlobal(2 * $pointerSize + 8) + [Runtime.InteropServices.Marshal]::Copy([byte[]]::new(2 * $pointerSize + 8), 0, $information, 2 * $pointerSize + 8) + $securitySize = if ($pointerSize -eq 8) { 24 } else { 12 } + $security = [Runtime.InteropServices.Marshal]::AllocHGlobal($securitySize) + [Runtime.InteropServices.Marshal]::Copy([byte[]]::new($securitySize), 0, $security, $securitySize) + [Runtime.InteropServices.Marshal]::WriteInt32($security, 0, $securitySize) + [Runtime.InteropServices.Marshal]::WriteInt32($security, $(if ($pointerSize -eq 8) { 16 } else { 8 }), 1) + $nul = $native::CreateFileW('NUL', [uint32]3221225472, 3, $security, 3, 0, [IntPtr]::Zero) + if ($nul.ToInt64() -eq -1) { $nul = [IntPtr]::Zero; throw 'Unavailable' } + # CREATE_NEW under the pinned owner-only invocation directory. + $compilerLog = $native::CreateFileW($compilerLogPath, [uint32]3221225472, 0, $security, 1, 0x80, [IntPtr]::Zero) + if ($compilerLog.ToInt64() -eq -1) { $compilerLog = [IntPtr]::Zero; throw 'Unavailable' } + # Only stdin NUL and private compiler output are inherited. + # Job and pinned-directory handles remain noninherited. + $size = [IntPtr]::Zero + $initialized = $native::InitializeProcThreadAttributeList([IntPtr]::Zero, 1, 0, [ref]$size) + $sizeError = [Runtime.InteropServices.Marshal]::GetLastWin32Error() + if ($initialized -or $sizeError -ne 122 -or $size.ToInt64() -le 0 -or $size.ToInt64() -gt 65536) { throw 'Unavailable' } + $attributeList = [Runtime.InteropServices.Marshal]::AllocHGlobal($size) + if (-not $native::InitializeProcThreadAttributeList($attributeList, 1, 0, [ref]$size)) { throw 'Unavailable' } + $attributesInitialized = $true + $handleList = [Runtime.InteropServices.Marshal]::AllocHGlobal(2 * $pointerSize) + [Runtime.InteropServices.Marshal]::WriteIntPtr($handleList, 0, $nul) + [Runtime.InteropServices.Marshal]::WriteIntPtr($handleList, $pointerSize, $compilerLog) + if (-not $native::UpdateProcThreadAttribute($attributeList, 0, [IntPtr]0x20002, + $handleList, [IntPtr](2 * $pointerSize), [IntPtr]::Zero, [IntPtr]::Zero)) { throw 'Unavailable' } + [Runtime.InteropServices.Marshal]::WriteIntPtr($startup, $startupSize, $attributeList) + [Runtime.InteropServices.Marshal]::WriteInt32($startup, $(if ($pointerSize -eq 8) { 60 } else { 44 }), 0x100) + $standardOffset = if ($pointerSize -eq 8) { 80 } else { 56 } + [Runtime.InteropServices.Marshal]::WriteIntPtr($startup, $standardOffset, $nul) + [Runtime.InteropServices.Marshal]::WriteIntPtr($startup, $standardOffset + $pointerSize, $compilerLog) + [Runtime.InteropServices.Marshal]::WriteIntPtr($startup, $standardOffset + 2 * $pointerSize, $compilerLog) + Write-LoomProtectionPhase 'compiler-environment' + $variables = [Environment]::GetEnvironmentVariables() + $variables['TEMP'] = $directory + $variables['TMP'] = $directory + # Win32 requires case-insensitive Unicode ordering without locale. + $names = [string[]]::new($variables.Count) + $index = 0 + foreach ($name in $variables.Keys) { $names[$index++] = [string]$name } + [Array]::Sort($names, [StringComparer]::OrdinalIgnoreCase) + $entries = [string[]]::new($names.Length) + for ($index = 0; $index -lt $names.Length; $index++) { + $entries[$index] = $names[$index] + '=' + [string]$variables[$names[$index]] + } + $environment = [Runtime.InteropServices.Marshal]::StringToHGlobalUni(($entries -join "`0") + "`0`0") + if ([DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() -ge $deadline) { throw 'Unavailable' } + Write-LoomProtectionPhase 'worker-start' + Write-LoomProtectionPhase 'compiler-launch' + # CREATE_SUSPENDED | CREATE_UNICODE_ENVIRONMENT | + # EXTENDED_STARTUPINFO_PRESENT | CREATE_NO_WINDOW. Never BREAKAWAY. + if (-not $native::CreateProcessW($application, $command, [IntPtr]::Zero, [IntPtr]::Zero, + $true, 0x08080404, $environment, $directory, $startup, $information)) { throw 'Unavailable' } + $process = [Runtime.InteropServices.Marshal]::ReadIntPtr($information, 0) + $thread = [Runtime.InteropServices.Marshal]::ReadIntPtr($information, $pointerSize) + $pidValue = [Runtime.InteropServices.Marshal]::ReadInt32($information, 2 * $pointerSize) + if ($process -eq [IntPtr]::Zero -or $thread -eq [IntPtr]::Zero -or $pidValue -le 0) { throw 'Unavailable' } + Write-LoomProtectionPhase 'worker-assign' + if (-not $native::AssignProcessToJobObject($job, $process)) { throw 'Unavailable' } + if ($null -ne $observe) { & $observe $process $pidValue $true } + # A fired timer cannot grant a late compiler a new execution window. + if ([DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() -ge $deadline) { throw 'Unavailable' } + if ($native::ResumeThread($thread) -eq [uint32]::MaxValue) { throw 'Unavailable' } + do { + if ($null -ne $observe) { & $observe $process $pidValue } + $wait = $native::WaitForSingleObject($process, 10) + if ($wait -ne 0 -and $wait -ne 258) { throw 'Unavailable' } + } while ($wait -eq 258) + $exitCode = [uint32]0 + if (-not $native::GetExitCodeProcess($process, [ref]$exitCode)) { throw 'Unavailable' } + if ($exitCode -gt [int]::MaxValue) { Write-LoomProtectionPhase 'worker-exit' -1 } + else { Write-LoomProtectionPhase 'worker-exit' ([int]$exitCode) } + if ($exitCode -ne 0) { + # Read no output until the exact compiler has exited AND every + # descendant is stopped, including after a native deadline exit. + Stop-LoomCompilerJob $native $job + Write-LoomProtectionPhase 'compiler-stopped' + if (-not $native::CloseHandle($compilerLog)) { + $nativeCode = [Runtime.InteropServices.Marshal]::GetLastWin32Error() + Write-LoomProtectionPhase 'compiler-close' $nativeCode + throw 'Unavailable' + } + $compilerLog = [IntPtr]::Zero + Write-LoomProtectionPhase 'compiler-closed' + Write-LoomCompilerCodes $compilerLogPath + throw 'Unavailable' + } + } finally { + if ($process -ne [IntPtr]::Zero) { + if ($native::WaitForSingleObject($process, 0) -ne 0) { + # Covers assignment/resume failure too. Outer self-job bounds + # this exact-handle wait if termination itself cannot complete. + [void]$native::TerminateProcess($process, 1) + if ($native::WaitForSingleObject($process, [uint32]::MaxValue) -ne 0) { throw 'Unavailable' } + } + [void]$native::CloseHandle($process) + } + if ($thread -ne [IntPtr]::Zero) { [void]$native::CloseHandle($thread) } + if ($attributesInitialized) { $native::DeleteProcThreadAttributeList($attributeList) } + foreach ($allocation in @($environment, $handleList, $attributeList, $information, $startup, $security)) { + if ($allocation -ne [IntPtr]::Zero) { [Runtime.InteropServices.Marshal]::FreeHGlobal($allocation) } + } + if ($compilerLog -ne [IntPtr]::Zero) { [void]$native::CloseHandle($compilerLog) } + if ($nul -ne [IntPtr]::Zero) { [void]$native::CloseHandle($nul) } + } +} + +function Stop-LoomCompilerJob([type]$native, [IntPtr]$job) { + if (-not $native::TerminateJobObject($job, 1)) { + $nativeCode = [Runtime.InteropServices.Marshal]::GetLastWin32Error() + Write-LoomProtectionPhase 'compiler-stop' $nativeCode + throw 'Unavailable' + } + $accounting = [Runtime.InteropServices.Marshal]::AllocHGlobal(48) + try { + do { + if (-not $native::QueryInformationJobObject($job, 1, $accounting, 48, [IntPtr]::Zero)) { + $nativeCode = [Runtime.InteropServices.Marshal]::GetLastWin32Error() + Write-LoomProtectionPhase 'compiler-query' $nativeCode + throw 'Unavailable' + } + $active = [Runtime.InteropServices.Marshal]::ReadInt32($accounting, 40) + if ($active -gt 0) { [Threading.Thread]::Sleep(1) } + } while ($active -gt 0) + } finally { [Runtime.InteropServices.Marshal]::FreeHGlobal($accounting) } +} + +function Invoke-LoomGuardedCompiler([type]$native, [scriptblock]$compilerOperation) { + $guardian = Start-LoomGuardianDeadline $native + $deadline = $guardian.Deadline + if (($deadline - [DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds()) -le 150) { throw 'Unavailable' } + $job = New-LoomCompilerJob $native + Start-LoomNativeTimer $native 'StopJob' $job ($deadline - 150) + $value = Invoke-LoomCompilerScope $native $false { + param($directory) + & $compilerOperation $native $job ($deadline - 150) $directory + } { + # Runs before any compile-scope handle release or file deletion. + Stop-LoomCompilerJob $native $job + } + return @{ Value = $value; Guardian = $guardian } + # Retain both job handles and native callback roots through process exit; + # no timer may later operate on a recycled handle value. +} diff --git a/integrations/claude-code-plugin/lib/windows-native-bootstrap.ps1 b/integrations/claude-code-plugin/lib/windows-native-bootstrap.ps1 new file mode 100644 index 0000000000..db212233db --- /dev/null +++ b/integrations/claude-code-plugin/lib/windows-native-bootstrap.ps1 @@ -0,0 +1,70 @@ +# Fixed P/Invoke declarations needed before source compilation can begin. +function New-LoomBootstrapApi { + $assemblyName = [System.Reflection.AssemblyName]::new('LoomPrivateCompilerBootstrap') + $assembly = [AppDomain]::CurrentDomain.DefineDynamicAssembly($assemblyName, [System.Reflection.Emit.AssemblyBuilderAccess]::Run) + $module = $assembly.DefineDynamicModule($assemblyName.Name) + $callback = $module.DefineType('LoomNativeTimerCallback', [System.Reflection.TypeAttributes]'Public, Sealed', [MulticastDelegate]) + $callingConvention = [Runtime.InteropServices.UnmanagedFunctionPointerAttribute].GetConstructor([type[]]@([Runtime.InteropServices.CallingConvention])) + $callback.SetCustomAttribute(([Reflection.Emit.CustomAttributeBuilder]::new($callingConvention, + [object[]]@([Runtime.InteropServices.CallingConvention]::Winapi)))) + $constructor = $callback.DefineConstructor([System.Reflection.MethodAttributes]'Public, HideBySig, RTSpecialName', + [System.Reflection.CallingConventions]::Standard, [type[]]@([object], [IntPtr])) + $constructor.SetImplementationFlags([System.Reflection.MethodImplAttributes]'Runtime, Managed') + $invoke = $callback.DefineMethod('Invoke', [System.Reflection.MethodAttributes]'Public, HideBySig, NewSlot, Virtual', + [void], [type[]]@([IntPtr], [byte])) + $invoke.SetImplementationFlags([System.Reflection.MethodImplAttributes]'Runtime, Managed') + [void]$callback.CreateType() + $builder = $module.DefineType('LoomPrivateCompilerBootstrap', [System.Reflection.TypeAttributes]'Public, Abstract, Sealed') + $nativeMethods = @{} + function Add-Native([string]$name, [string]$dll, [type]$returns, [type[]]$parameters) { + $method = $builder.DefinePInvokeMethod($name, $dll, + [System.Reflection.MethodAttributes]'Public, Static, PinvokeImpl', + [System.Reflection.CallingConventions]::Standard, $returns, $parameters, + [System.Runtime.InteropServices.CallingConvention]::Winapi, [System.Runtime.InteropServices.CharSet]::Unicode) + $method.SetImplementationFlags($method.GetMethodImplementationFlags() -bor [System.Reflection.MethodImplAttributes]::PreserveSig) + $constructor = [System.Runtime.InteropServices.DllImportAttribute].GetConstructor([type[]]@([string])) + $fields = [System.Reflection.FieldInfo[]]@( + [System.Runtime.InteropServices.DllImportAttribute].GetField('SetLastError'), + [System.Runtime.InteropServices.DllImportAttribute].GetField('CharSet'), + [System.Runtime.InteropServices.DllImportAttribute].GetField('ExactSpelling'), + [System.Runtime.InteropServices.DllImportAttribute].GetField('CallingConvention')) + $attribute = [System.Reflection.Emit.CustomAttributeBuilder]::new($constructor, [object[]]@($dll), + $fields, [object[]]@($true, [System.Runtime.InteropServices.CharSet]::Unicode, $true, + [System.Runtime.InteropServices.CallingConvention]::Winapi)) + $method.SetCustomAttribute($attribute) + $nativeMethods[$name] = $method + } + $refPointer = [IntPtr].MakeByRefType() + Add-Native 'CreateFileW' 'kernel32.dll' ([IntPtr]) ([type[]]@([string], [uint32], [uint32], [IntPtr], [uint32], [uint32], [IntPtr])) + Add-Native 'CreateDirectoryW' 'kernel32.dll' ([bool]) ([type[]]@([string], [IntPtr])) + Add-Native 'GetFileInformationByHandle' 'kernel32.dll' ([bool]) ([type[]]@([IntPtr], [IntPtr])) + Add-Native 'CloseHandle' 'kernel32.dll' ([bool]) ([type[]]@([IntPtr])) + Add-Native 'GetSecurityInfo' 'advapi32.dll' ([uint32]) ([type[]]@([IntPtr], [int], [uint32], $refPointer, $refPointer, $refPointer, $refPointer, $refPointer)) + Add-Native 'GetSecurityDescriptorLength' 'advapi32.dll' ([uint32]) ([type[]]@([IntPtr])) + Add-Native 'LocalFree' 'kernel32.dll' ([IntPtr]) ([type[]]@([IntPtr])) + Add-Native 'GetCurrentProcess' 'kernel32.dll' ([IntPtr]) ([type[]]@()) + Add-Native 'CreateJobObjectW' 'kernel32.dll' ([IntPtr]) ([type[]]@([IntPtr], [IntPtr])) + Add-Native 'SetInformationJobObject' 'kernel32.dll' ([bool]) ([type[]]@([IntPtr], [int], [IntPtr], [uint32])) + Add-Native 'AssignProcessToJobObject' 'kernel32.dll' ([bool]) ([type[]]@([IntPtr], [IntPtr])) + Add-Native 'TerminateJobObject' 'kernel32.dll' ([bool]) ([type[]]@([IntPtr], [uint32])) + Add-Native 'WaitForSingleObject' 'kernel32.dll' ([uint32]) ([type[]]@([IntPtr], [uint32])) + Add-Native 'QueryInformationJobObject' 'kernel32.dll' ([bool]) ([type[]]@([IntPtr], [int], [IntPtr], [uint32], [IntPtr])) + Add-Native 'InitializeProcThreadAttributeList' 'kernel32.dll' ([bool]) ([type[]]@([IntPtr], [int], [uint32], $refPointer)) + Add-Native 'UpdateProcThreadAttribute' 'kernel32.dll' ([bool]) ([type[]]@([IntPtr], [uint32], [IntPtr], [IntPtr], [IntPtr], [IntPtr], [IntPtr])) + Add-Native 'DeleteProcThreadAttributeList' 'kernel32.dll' ([void]) ([type[]]@([IntPtr])) + Add-Native 'CreateProcessW' 'kernel32.dll' ([bool]) ([type[]]@([string], [Text.StringBuilder], [IntPtr], [IntPtr], [bool], [uint32], [IntPtr], [string], [IntPtr], [IntPtr])) + Add-Native 'ResumeThread' 'kernel32.dll' ([uint32]) ([type[]]@([IntPtr])) + Add-Native 'TerminateProcess' 'kernel32.dll' ([bool]) ([type[]]@([IntPtr], [uint32])) + Add-Native 'GetExitCodeProcess' 'kernel32.dll' ([bool]) ([type[]]@([IntPtr], [uint32].MakeByRefType())) + Add-Native 'CreateTimerQueueTimer' 'kernel32.dll' ([bool]) ([type[]]@($refPointer, [IntPtr], [IntPtr], [IntPtr], [uint32], [uint32], [uint32])) + $method = $builder.DefineMethod('StopJob', [System.Reflection.MethodAttributes]'Public, Static', + [void], [type[]]@([IntPtr], [byte])) + $il = $method.GetILGenerator() + $il.Emit([System.Reflection.Emit.OpCodes]::Ldarg_0) + # Distinguish native deadline termination from ordinary failure code 1. + $il.Emit([System.Reflection.Emit.OpCodes]::Ldc_I4, [int]1460) + $il.Emit([System.Reflection.Emit.OpCodes]::Call, $nativeMethods['TerminateJobObject']) + $il.Emit([System.Reflection.Emit.OpCodes]::Pop) + $il.Emit([System.Reflection.Emit.OpCodes]::Ret) + return $builder.CreateType() +} diff --git a/integrations/claude-code-plugin/lib/windows-private-records.cs b/integrations/claude-code-plugin/lib/windows-private-records.cs new file mode 100644 index 0000000000..fbfec18d0f --- /dev/null +++ b/integrations/claude-code-plugin/lib/windows-private-records.cs @@ -0,0 +1,678 @@ +// Windows authority and durable I/O for one session's content-free records. +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Runtime.InteropServices; +using System.Security.AccessControl; +using System.Security.Principal; +using System.Text; +using System.Text.RegularExpressions; +using System.Threading; +using Microsoft.Win32.SafeHandles; + +public sealed class WindowsPrivateRecords +{ + const uint READ_CONTROL = 0x20000, READ_ATTRIBUTES = 0x80; + const uint GENERIC_READ = 0x80000000, GENERIC_WRITE = 0x40000000; + const uint OPEN_EXISTING = 3, CREATE_NEW = 1; + const uint OPEN_REPARSE = 0x00200000, BACKUP_SEMANTICS = 0x02000000; + const uint WRITE_THROUGH = 0x80000000, NORMAL = 0x80; + const uint DIRECTORY = 0x10, REPARSE = 0x400; + const int EXISTS = 183, FILE_EXISTS = 80, FULL = 0x001f01ff; + const int MaxRecord = 65536; + const int AliasClaimMilliseconds = 500; + readonly string basePath; + readonly SecurityIdentifier principal; + readonly byte[] descriptor; + + [StructLayout(LayoutKind.Sequential)] + struct SecurityAttributes { public int Length; public IntPtr Descriptor; public int Inherit; } + [StructLayout(LayoutKind.Sequential)] + struct FileInformation { + public uint Attributes; + public System.Runtime.InteropServices.ComTypes.FILETIME Creation, Access, Write; + public uint Volume, SizeHigh, SizeLow, Links, IndexHigh, IndexLow; + } + + [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true, ExactSpelling = true)] + static extern SafeFileHandle CreateFileW(string p, uint access, uint share, ref SecurityAttributes sa, + uint disposition, uint flags, IntPtr template); + [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true, ExactSpelling = true)] + static extern bool CreateDirectoryW(string p, ref SecurityAttributes sa); + [DllImport("kernel32.dll", SetLastError = true)] + static extern bool GetFileInformationByHandle(SafeFileHandle h, out FileInformation info); + [DllImport("kernel32.dll", SetLastError = true)] + static extern uint GetFileType(SafeFileHandle h); + [DllImport("kernel32.dll", SetLastError = true)] + static extern bool GetFileSizeEx(SafeFileHandle h, out long size); + [DllImport("kernel32.dll", SetLastError = true)] + static extern bool ReadFile(SafeFileHandle h, [Out] byte[] bytes, uint length, out uint read, IntPtr overlap); + [DllImport("kernel32.dll", SetLastError = true)] + static extern bool WriteFile(SafeFileHandle h, byte[] bytes, uint length, out uint written, IntPtr overlap); + [DllImport("kernel32.dll", SetLastError = true)] + static extern bool SetFilePointerEx(SafeFileHandle h, long offset, out long position, uint origin); + [DllImport("kernel32.dll", SetLastError = true)] + static extern bool FlushFileBuffers(SafeFileHandle h); + [DllImport("kernel32.dll")] + static extern IntPtr GetCurrentProcess(); + [DllImport("advapi32.dll", SetLastError = true)] + static extern bool OpenProcessToken(IntPtr process, uint access, out SafeFileHandle token); + [DllImport("advapi32.dll", SetLastError = true)] + static extern bool GetTokenInformation(SafeFileHandle token, int kind, IntPtr data, uint length, out uint needed); + [DllImport("advapi32.dll", SetLastError = true)] + static extern uint GetSecurityInfo(SafeFileHandle h, int kind, uint fields, out IntPtr owner, + out IntPtr group, out IntPtr dacl, out IntPtr sacl, out IntPtr sd); + [DllImport("advapi32.dll")] + static extern uint GetSecurityDescriptorLength(IntPtr descriptor); + [DllImport("kernel32.dll")] + static extern IntPtr LocalFree(IntPtr memory); + [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true, ExactSpelling = true)] + static extern bool GetVolumeInformationW(string root, StringBuilder volumeName, uint volumeCapacity, + out uint serial, out uint maxComponent, out uint flags, StringBuilder fsName, uint fsCapacity); + + sealed class Unavailable : InvalidOperationException { + public readonly int NativeCode; + public Unavailable(int nativeCode = 0) : base("Session protection state could not be confirmed") { NativeCode = nativeCode; } + } + static void Require(bool value) { + if (!value) throw new Unavailable(); + } + + static SecurityIdentifier ProcessPrincipal() { + SafeFileHandle token; + Require(OpenProcessToken(GetCurrentProcess(), 8, out token)); // TOKEN_QUERY + using (token) { + uint needed; + bool first = GetTokenInformation(token, 1, IntPtr.Zero, 0, out needed); // TokenUser + int firstError = Marshal.GetLastWin32Error(); + Require(!first && firstError == 122 && needed > 0 && needed < 65536); + IntPtr data = Marshal.AllocHGlobal((int)needed); + try { + Require(GetTokenInformation(token, 1, data, needed, out needed)); + return new SecurityIdentifier(Marshal.ReadIntPtr(data)); + } finally { Marshal.FreeHGlobal(data); } + } + } + + public WindowsPrivateRecords(string trustedStartupBase) { + basePath = Path.GetFullPath(trustedStartupBase).TrimEnd('\\'); + // This implementation requires local NTFS with persistent ACLs. + Require(Regex.IsMatch(basePath, @"^[a-zA-Z]:\\.+$")); + string volumeRoot = Path.GetPathRoot(basePath); + uint serial, max, flags; + StringBuilder fsName = new StringBuilder(32); + Require(GetVolumeInformationW(volumeRoot, null, 0, out serial, out max, out flags, fsName, 32)); + Require((flags & 8) != 0 && String.Equals(fsName.ToString(), "NTFS", StringComparison.OrdinalIgnoreCase)); + principal = ProcessPrincipal(); + RawSecurityDescriptor sd = new RawSecurityDescriptor("O:" + principal.Value + "D:P(A;;FA;;;" + principal.Value + ")"); + descriptor = new byte[sd.BinaryLength]; + sd.GetBinaryForm(descriptor, 0); + } + + SecurityAttributes Attributes(out IntPtr allocated) { + allocated = Marshal.AllocHGlobal(descriptor.Length); + Marshal.Copy(descriptor, 0, allocated, descriptor.Length); + return new SecurityAttributes { Length = Marshal.SizeOf(typeof(SecurityAttributes)), Descriptor = allocated, Inherit = 0 }; + } + + void Check(SafeFileHandle handle, bool directory, bool privateAcl) { + FileInformation info = new FileInformation(); + Require(!handle.IsInvalid && GetFileInformationByHandle(handle, out info)); + Require(GetFileType(handle) == 1); // FILE_TYPE_DISK + Require((info.Attributes & REPARSE) == 0 && ((info.Attributes & DIRECTORY) != 0) == directory); + if (!directory) Require(info.Links == 1); + if (!privateAcl) return; + IntPtr owner, group, dacl, sacl, sd; + Require(GetSecurityInfo(handle, 1, 5, out owner, out group, out dacl, out sacl, out sd) == 0); + try { + Require(owner != IntPtr.Zero && dacl != IntPtr.Zero && sd != IntPtr.Zero); + uint length = GetSecurityDescriptorLength(sd); + Require(length > 0 && length <= 65536); + byte[] bytes = new byte[(int)length]; + Marshal.Copy(sd, bytes, 0, bytes.Length); + RawSecurityDescriptor actual = new RawSecurityDescriptor(bytes, 0); + Require(principal.Equals(actual.Owner)); + Require((actual.ControlFlags & ControlFlags.DiscretionaryAclPresent) != 0); + Require((actual.ControlFlags & ControlFlags.DiscretionaryAclProtected) != 0); + Require(actual.DiscretionaryAcl != null && actual.DiscretionaryAcl.Count == 1); + CommonAce ace = actual.DiscretionaryAcl[0] as CommonAce; + Require(ace != null && !ace.IsCallback && ace.AceQualifier == AceQualifier.AccessAllowed); + Require(ace.AceFlags == AceFlags.None && ace.AccessMask == FULL && principal.Equals(ace.SecurityIdentifier)); + } finally { if (sd != IntPtr.Zero) LocalFree(sd); } + } + + SafeFileHandle OpenDirectory(string p, bool privateAcl) { + SecurityAttributes empty = new SecurityAttributes { Length = Marshal.SizeOf(typeof(SecurityAttributes)) }; + // No FILE_SHARE_DELETE: retained directory handles exclude rename/delete. + SafeFileHandle h = CreateFileW(p, READ_CONTROL | READ_ATTRIBUTES, 3, ref empty, + OPEN_EXISTING, OPEN_REPARSE | BACKUP_SEMANTICS, IntPtr.Zero); + if (h.IsInvalid) { int error = Marshal.GetLastWin32Error(); h.Dispose(); throw new Unavailable(error); } + try { Check(h, true, privateAcl); return h; } catch { h.Dispose(); throw; } + } + + void CreateDirectoryIfMissing(string p) { + IntPtr allocation; + SecurityAttributes sa = Attributes(out allocation); + try { + if (!CreateDirectoryW(p, ref sa)) Require(Marshal.GetLastWin32Error() == EXISTS); + } finally { Marshal.FreeHGlobal(allocation); } + // An existing directory is inspected below, never chmod/repaired. + } + + static void CheckComponent(string component) { + Require(component != null && Regex.IsMatch(component, @"^[a-zA-Z0-9][a-zA-Z0-9_.-]{0,127}$")); + Require(!component.EndsWith(".", StringComparison.Ordinal)); + string stem = component.Split('.')[0]; + Require(!Regex.IsMatch(stem, @"^(CON|PRN|AUX|NUL|COM[1-9]|LPT[1-9])$", RegexOptions.IgnoreCase)); + } + + // External ancestors are pinned and checked for reparse/type. The actual + // privacy base and every descendant must also pass the exact owner/DACL. + List PinDirectories(string[] components, bool create, out string leaf) { + Require(components != null && components.Length > 0 && components.Length <= 4); + foreach (string component in components) CheckComponent(component); + List held = new List(); + try { + string root = Path.GetPathRoot(basePath); + held.Add(OpenDirectory(root, false)); + string current = root; + string[] baseParts = basePath.Substring(root.Length).Split('\\'); + for (int i = 0; i < baseParts.Length; i++) { + // Startup components may contain spaces, but no alternate stream. + Require(baseParts[i].Length > 0 && baseParts[i].IndexOf(':') < 0); + current = Path.Combine(current, baseParts[i]); + if (create) CreateDirectoryIfMissing(current); + held.Add(OpenDirectory(current, i == baseParts.Length - 1)); + } + for (int i = 0; i < components.Length - 1; i++) { + current = Path.Combine(current, components[i]); + if (create) CreateDirectoryIfMissing(current); + held.Add(OpenDirectory(current, true)); + } + leaf = Path.Combine(current, components[components.Length - 1]); + return held; + } catch { CloseDirectories(held); throw; } + } + + static void CloseDirectories(List handles) { + for (int i = handles.Count - 1; i >= 0; i--) handles[i].Dispose(); + } + + SafeFileHandle OpenRecord(string file, bool write) { + SecurityAttributes empty = new SecurityAttributes { Length = Marshal.SizeOf(typeof(SecurityAttributes)) }; + SafeFileHandle h = CreateFileW(file, GENERIC_READ | READ_CONTROL | READ_ATTRIBUTES | (write ? GENERIC_WRITE : 0), + write ? 0u : 1u, ref empty, OPEN_EXISTING, OPEN_REPARSE | (write ? WRITE_THROUGH : 0), IntPtr.Zero); + if (h.IsInvalid) { int error = Marshal.GetLastWin32Error(); h.Dispose(); throw new Unavailable(error); } + try { Check(h, false, true); return h; } catch { h.Dispose(); throw; } + } + + byte[] ReadChecked(SafeFileHandle h) { + long length; + Require(GetFileSizeEx(h, out length) && length >= 0 && length <= MaxRecord); + byte[] bytes = new byte[(int)length]; + if (length != 0) { + uint count; + Require(ReadFile(h, bytes, (uint)bytes.Length, out count, IntPtr.Zero) && count == bytes.Length); + } + return bytes; + } + + static void WriteAndFlush(SafeFileHandle h, byte[] bytes) { + Require(bytes != null && bytes.Length <= MaxRecord); + uint written; + Require(WriteFile(h, bytes, (uint)bytes.Length, out written, IntPtr.Zero) && written == bytes.Length); + Require(FlushFileBuffers(h)); + } + + public byte[] ReadExisting(string[] components) { + string leaf; + List held = PinDirectories(components, false, out leaf); + try { using (SafeFileHandle h = OpenRecord(leaf, false)) return ReadChecked(h); } + finally { CloseDirectories(held); } + } + + // CreateRoot retains every parent; each record still reopens and checks them. + void CreateRootRecord(string[] components, byte[] bytes) { + Require(bytes != null && bytes.Length <= MaxRecord); + string leaf; + List held = PinDirectories(components, false, out leaf); + try { + IntPtr allocation; + SecurityAttributes sa = Attributes(out allocation); + try { + using (SafeFileHandle h = CreateFileW(leaf, GENERIC_READ | GENERIC_WRITE | READ_CONTROL | READ_ATTRIBUTES, + 0, ref sa, CREATE_NEW, NORMAL | OPEN_REPARSE | WRITE_THROUGH, IntPtr.Zero)) { + Check(h, false, true); + WriteAndFlush(h, bytes); + } + } finally { Marshal.FreeHGlobal(allocation); } + } finally { CloseDirectories(held); } + } + + public void AppendProtection(string rootId) { + Require(rootId != null && Regex.IsMatch(rootId, @"^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$")); + string leaf; + List held = PinDirectories(new string[] { rootId, "state" }, false, out leaf); + try { + // Validate semantic fields rather than requiring one JSON encoding. + string manifestFile = Path.Combine(Path.GetDirectoryName(leaf), "root.json"); + using (SafeFileHandle manifest = OpenRecord(manifestFile, false)) { + CheckManifest(ReadChecked(manifest), rootId); + using (SafeFileHandle state = OpenRecord(leaf, true)) { + WriteRecordPhase("protect-open"); + long position; + Require(SetFilePointerEx(state, 0, out position, 2)); + WriteAndFlush(state, new byte[] { 49, 10 }); + WriteRecordPhase("protect-flushed"); + } + } + } finally { CloseDirectories(held); } + } + + string ConfirmPublishedAlias(string key) { + string id = FindAlias(key); + if (id == null) return null; + string file; + List held = PinDirectories(new string[] { "aliases", key + ".json" }, false, out file); + try { + using (SafeFileHandle h = OpenRecord(file, true)) { + Require(CheckAlias(ReadChecked(h), key) == id); + Require(FlushFileBuffers(h)); + } + return id; + } finally { CloseDirectories(held); } + } + + string WithAliasClaim(string key, string boundRoot, Func operation) { + Require(key != null && Regex.IsMatch(key, "^[0-9a-f]{64}$")); + string claimFile; + List held = PinDirectories(new string[] { "aliases", key + ".claim" }, true, out claimFile); + SafeFileHandle claim = null; + try { + Stopwatch elapsed = Stopwatch.StartNew(); + while (true) { + Require(elapsed.ElapsedMilliseconds < AliasClaimMilliseconds); + IntPtr allocation; + SecurityAttributes sa = Attributes(out allocation); + try { + claim = CreateFileW(claimFile, GENERIC_READ | GENERIC_WRITE | READ_CONTROL | READ_ATTRIBUTES, + 0, ref sa, CREATE_NEW, NORMAL | OPEN_REPARSE | WRITE_THROUGH, IntPtr.Zero); + if (!claim.IsInvalid) { + try { Check(claim, false, true); Require(FlushFileBuffers(claim)); } + catch { claim.Dispose(); claim = null; throw; } + break; + } + int error = Marshal.GetLastWin32Error(); + claim.Dispose(); + claim = null; + Require(error == EXISTS || error == FILE_EXISTS || error == 32); // Sharing violation while claimed. + } finally { Marshal.FreeHGlobal(allocation); } + string published = null; + try { published = ConfirmPublishedAlias(key); } + catch (Unavailable) { + // An in-progress record stays unavailable until complete. + } + if (published != null) { + Require(boundRoot == null || published == boundRoot); + return published; + } + int remaining = AliasClaimMilliseconds - (int)elapsed.ElapsedMilliseconds; + Require(remaining > 0); + Thread.Sleep(Math.Min(10, remaining)); + } + return operation(); + } finally { + try { + if (claim != null) { + try { + // A retained claim prevents a new root if its alias is lost. + Check(claim, false, true); + } finally { claim.Dispose(); } + } + } finally { CloseDirectories(held); } + } + } + + public string EstablishAlias(string key) { + return WithAliasClaim(key, null, delegate { + string id = FindAlias(key); + if (id != null) return id; + id = CreateRoot(); + BindAliasClaimed(key, id); + return id; + }); + } + + public void BindAlias(string aliasKey, string rootId) { + Require(aliasKey != null && Regex.IsMatch(aliasKey, "^[0-9a-f]{64}$")); + Require(RootId(rootId)); + IsProtected(rootId); // Validate existing root/state before creating an alias claim. + WithAliasClaim(aliasKey, rootId, delegate { + BindAliasClaimed(aliasKey, rootId); + return rootId; + }); + } + + void BindAliasClaimed(string aliasKey, string rootId) { + Require(aliasKey != null && Regex.IsMatch(aliasKey, "^[0-9a-f]{64}$")); + Require(rootId != null && Regex.IsMatch(rootId, @"^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$")); + string stateFile; + List rootHeld = PinDirectories(new string[] { rootId, "state" }, false, out stateFile); + try { + using (SafeFileHandle manifest = OpenRecord(Path.Combine(Path.GetDirectoryName(stateFile), "root.json"), false)) + using (SafeFileHandle state = OpenRecord(stateFile, false)) { + CheckManifest(ReadChecked(manifest), rootId); + ReadChecked(state); // Missing or unreadable state cannot acquire a new alias. + string aliasFile; + List aliasHeld = PinDirectories(new string[] { "aliases", aliasKey + ".json" }, true, out aliasFile); + try { + string expected = "{\"version\":1,\"identity\":\"" + aliasKey + "\",\"root\":\"" + rootId + "\"}"; + byte[] bytes = Encoding.UTF8.GetBytes(expected); + IntPtr allocation; + SecurityAttributes sa = Attributes(out allocation); + try { + using (SafeFileHandle h = CreateFileW(aliasFile, GENERIC_READ | GENERIC_WRITE | READ_CONTROL | READ_ATTRIBUTES, + 0, ref sa, CREATE_NEW, NORMAL | OPEN_REPARSE | WRITE_THROUGH, IntPtr.Zero)) { + if (!h.IsInvalid) { + Check(h, false, true); + WriteAndFlush(h, bytes); + return; + } + int error = Marshal.GetLastWin32Error(); + Require(error == EXISTS || error == FILE_EXISTS); + } + } finally { Marshal.FreeHGlobal(allocation); } + // Existing aliases are confirmed and flushed, never rebound. + using (SafeFileHandle h = OpenRecord(aliasFile, true)) { + Require(CheckAlias(ReadChecked(h), aliasKey) == rootId); + Require(FlushFileBuffers(h)); + } + } finally { CloseDirectories(aliasHeld); } + } + } finally { CloseDirectories(rootHeld); } + } + + static bool RootId(string value) { + return value != null && Regex.IsMatch(value, @"^[0-9a-f]{8}(-[0-9a-f]{4}){3}-[0-9a-f]{12}$"); + } + + public static Dictionary ParseRequest(string text) { + Require(text != null && text.Length <= 4096); + Dictionary fields = new RecordReader(text).Read(true); + object operation; + Require(fields.TryGetValue("op", out operation) && operation is string); + string op = (string)operation; + string[] keys; + switch (op) { + case "create": keys = new string[] { "base", "op" }; break; + case "inspect": case "protect": keys = new string[] { "base", "id", "op" }; break; + case "bind": keys = new string[] { "base", "id", "key", "op" }; break; + case "find": case "establish": keys = new string[] { "base", "key", "op" }; break; + default: throw new Unavailable(); + } + Require(fields.Count == keys.Length); + Dictionary request = new Dictionary(StringComparer.Ordinal); + foreach (string key in keys) { + object value; + Require(fields.TryGetValue(key, out value) && value is string); + request[key] = (string)value; + } + Require(request["base"].Length <= 2048 && Path.IsPathRooted(request["base"])); + return request; + } + + public static string EncodeResponse(string op, object value) { + string json; + switch (op) { + case "inspect": + Require(value is bool); + json = (bool)value ? "true" : "false"; + break; + case "protect": case "bind": + Require(value == null); + json = "null"; + break; + case "create": case "establish": case "find": + if (value == null) { + Require(op == "find"); + json = "null"; + } else { + string id = value as string; + Require(id != null && id.Length == 36 && RootId(id)); + json = "\"" + id + "\""; + } + break; + default: throw new Unavailable(); + } + return "{\"ok\":true,\"value\":" + json + "}"; + } + + // Stored duplicate keys retain their last value, matching JSON.parse. Earlier + // overwritten values still need strict syntax, even if not schema values. + sealed class RecordReader { + readonly string text; + int offset; + public RecordReader(byte[] bytes) : this(Encoding.UTF8.GetString(bytes)) {} + public RecordReader(string text) { this.text = text; } + void Space() { + while (offset < text.Length && (text[offset] == ' ' || text[offset] == '\t' || text[offset] == '\r' || text[offset] == '\n')) offset++; + } + bool Take(char expected) { + Space(); + if (offset == text.Length || text[offset] != expected) return false; + offset++; + return true; + } + string String() { + Require(Take('"')); + StringBuilder value = new StringBuilder(); + while (offset < text.Length) { + char next = text[offset++]; + if (next == '"') return value.ToString(); + Require(next >= 0x20); + if (next != '\\') { value.Append(next); continue; } + Require(offset < text.Length); + switch (text[offset++]) { + case '"': value.Append('"'); break; + case '\\': value.Append('\\'); break; + case '/': value.Append('/'); break; + case 'b': value.Append('\b'); break; + case 'f': value.Append('\f'); break; + case 'n': value.Append('\n'); break; + case 'r': value.Append('\r'); break; + case 't': value.Append('\t'); break; + case 'u': + Require(offset + 4 <= text.Length); + int code = 0; + for (int i = 0; i < 4; i++) { + char digit = text[offset++]; + int hex = digit >= '0' && digit <= '9' ? digit - '0' : + digit >= 'a' && digit <= 'f' ? digit - 'a' + 10 : + digit >= 'A' && digit <= 'F' ? digit - 'A' + 10 : -1; + Require(hex >= 0); + code = code * 16 + hex; + } + value.Append((char)code); + break; + default: throw new Unavailable(); + } + } + throw new Unavailable(); + } + bool Digit() { return offset < text.Length && text[offset] >= '0' && text[offset] <= '9'; } + double Number() { + Space(); + int start = offset; + if (offset < text.Length && text[offset] == '-') offset++; + Require(Digit()); + if (text[offset] == '0') offset++; + else { while (Digit()) offset++; } + if (offset < text.Length && text[offset] == '.') { + offset++; + Require(Digit()); + while (Digit()) offset++; + } + if (offset < text.Length && (text[offset] == 'e' || text[offset] == 'E')) { + offset++; + if (offset < text.Length && (text[offset] == '+' || text[offset] == '-')) offset++; + Require(Digit()); + while (Digit()) offset++; + } + double value; + if (!Double.TryParse(text.Substring(start, offset - start), System.Globalization.NumberStyles.Float, + System.Globalization.CultureInfo.InvariantCulture, out value)) { + // Valid numbers outside the Framework double parser's range + // cannot equal schema version 1, but may be overwritten keys. + value = text[start] == '-' ? Double.NegativeInfinity : Double.PositiveInfinity; + } + return value; + } + object Value() { + Space(); + Require(offset < text.Length); + if (text[offset] == '"') return String(); + if (text[offset] == '{' || text[offset] == '[') { Composite(); return new object(); } + foreach (string literal in new string[] { "true", "false", "null" }) { + if (text.Length - offset >= literal.Length && + System.String.CompareOrdinal(text, offset, literal, 0, literal.Length) == 0) { + offset += literal.Length; + return new object(); + } + } + return Number(); + } + void NestedValue(List states) { + Space(); + Require(offset < text.Length); + if (text[offset] == '{') { offset++; states.Add(0); } + else if (text[offset] == '[') { offset++; states.Add(5); } + else { Value(); } + } + void Composite() { + // An explicit stack avoids recursive parsing of overwritten values. + List states = new List(); + NestedValue(states); + while (states.Count > 0) { + int top = states.Count - 1; + switch (states[top]) { + case 0: // Object: first key or close. + if (Take('}')) { states.RemoveAt(top); break; } + String(); states[top] = 2; break; + case 1: // Object: required key after comma. + String(); states[top] = 2; break; + case 2: + Require(Take(':')); states[top] = 3; break; + case 3: + states[top] = 4; NestedValue(states); break; + case 4: + if (Take('}')) { states.RemoveAt(top); break; } + Require(Take(',')); states[top] = 1; break; + case 5: // Array: first value or close. + if (Take(']')) { states.RemoveAt(top); break; } + states[top] = 7; NestedValue(states); break; + case 6: // Array: required value after comma. + states[top] = 7; NestedValue(states); break; + case 7: + if (Take(']')) { states.RemoveAt(top); break; } + Require(Take(',')); states[top] = 6; break; + default: throw new Unavailable(); + } + } + } + public Dictionary Read(bool rejectDuplicates = false) { + Dictionary result = new Dictionary(StringComparer.Ordinal); + Require(Take('{')); + if (!Take('}')) { + do { + string key = String(); + if (rejectDuplicates) Require(!result.ContainsKey(key)); + Require(Take(':')); + Space(); + Require(offset < text.Length); + result[key] = Value(); + if (Take('}')) break; + Require(Take(',')); + } while (true); + } + Space(); + Require(offset == text.Length); + return result; + } + } + + static Dictionary Record(byte[] bytes, string[] keys) { + Dictionary record = new RecordReader(bytes).Read(); + Require(record.Count == keys.Length); + foreach (string key in keys) Require(record.ContainsKey(key)); + object version = record["version"]; + Require(version is double && (double)version == 1); + return record; + } + + static void CheckManifest(byte[] bytes, string id) { + Dictionary record = Record(bytes, new string[] { "id", "version" }); + Require(record["id"] is string && (string)record["id"] == id); + } + + static string CheckAlias(byte[] bytes, string key) { + Dictionary record = Record(bytes, new string[] { "identity", "root", "version" }); + Require(record["identity"] is string && (string)record["identity"] == key); + string id = record["root"] as string; + Require(RootId(id)); + return id; + } + + static void WriteRecordPhase(string phase) { + try { + Console.Error.WriteLine("LSP1:" + phase + ":0"); + Console.Error.Flush(); + } catch (Exception) { // Diagnostic I/O must not interrupt authority or cleanup. + } + } + + public string CreateRoot() { + WriteRecordPhase("root-entry"); + string id = Guid.NewGuid().ToString("D"); + string unused; + List baseHeld = PinDirectories(new string[] { "root.json" }, true, out unused); + try { + IntPtr allocation; + SecurityAttributes sa = Attributes(out allocation); + string rootPath = Path.Combine(basePath, id); + try { Require(CreateDirectoryW(rootPath, ref sa)); } + finally { Marshal.FreeHGlobal(allocation); } + using (SafeFileHandle root = OpenDirectory(rootPath, true)) { + CreateRootRecord(new string[] { id, "state" }, Encoding.UTF8.GetBytes("0\n")); + CreateRootRecord(new string[] { id, "root.json" }, Encoding.UTF8.GetBytes("{\"version\":1,\"id\":\"" + id + "\"}")); + WriteRecordPhase("root-flushed"); + Require(!IsProtected(id)); + return id; + } + } finally { CloseDirectories(baseHeld); } + } + + public bool IsProtected(string id) { + Require(RootId(id)); + string stateFile; + List held = PinDirectories(new string[] { id, "state" }, false, out stateFile); + try { + using (SafeFileHandle manifest = OpenRecord(Path.Combine(Path.GetDirectoryName(stateFile), "root.json"), false)) + using (SafeFileHandle state = OpenRecord(stateFile, false)) { + CheckManifest(ReadChecked(manifest), id); + byte[] bytes = ReadChecked(state); + return !(bytes.Length == 2 && bytes[0] == 48 && bytes[1] == 10); + } + } finally { CloseDirectories(held); } + } + + public string FindAlias(string key) { + Require(key != null && Regex.IsMatch(key, "^[0-9a-f]{64}$")); + string id; + try { id = CheckAlias(ReadExisting(new string[] { "aliases", key + ".json" }), key); } + catch (Unavailable error) { if (error.NativeCode == 2 || error.NativeCode == 3) return null; throw; } + // Only the alias lookup reports absence. A dangling alias is damaged. + CheckManifest(ReadExisting(new string[] { id, "root.json" }), id); + return id; + } +} diff --git a/integrations/claude-code-plugin/lib/windows-session-protection.mjs b/integrations/claude-code-plugin/lib/windows-session-protection.mjs new file mode 100644 index 0000000000..f0ab46a4b0 --- /dev/null +++ b/integrations/claude-code-plugin/lib/windows-session-protection.mjs @@ -0,0 +1,240 @@ +// One checked native operation per Windows session-protection call. +import { spawnSync } from "node:child_process"; +import crypto from "node:crypto"; +import os from "node:os"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +// Startup configuration is a locator under the process-owner trust model. +// Hook/session data can select neither the executable nor the fixed source. +const startupSystemRoot = process.env.SystemRoot; +const startupHome = os.homedir(); +const script = fileURLToPath(new URL("./windows-session-protection.ps1", import.meta.url)); +const operationTimeoutMs = 2000; +const cleanupReserveMs = 500; +const failureDiagnostics = new WeakMap(); +const phases = new Set([ + "entry", + "encoding-new", + "encoding-created", + "encoding-input", + "encoding-output", + "startup", + "bootstrap", + "worker-bootstrap", + "guardian-deadline", + "native-job", + "native-timer", + "worker-start", + "worker-assign", + "compiler-private", + "compiler-identity", + "compiler-path", + "compiler-security", + "compiler-parents", + "compiler-directory", + "compiler-receipt", + "compiler-environment", + "compiler-launch", + "compiler-stopped", + "compiler-closed", + "compiler-scanned", + "compiler-bytes", + "compiler-format", + "compiler-stop", + "compiler-query", + "compiler-close", + "compile", + "request", + "request-parse", + "request-keys", + "native-op", + "record-construct", + "record-dispatch", + "root-entry", + "root-flushed", + "protect-open", + "protect-flushed", + "output-encode", + "cleanup", + "protocol", +]); +const boundedCode = (value) => (Number.isInteger(value) && value >= -2147483648 && value <= 2147483647 ? value : null); +const boundedCount = (value) => Math.min(1024, Math.max(0, Number.isSafeInteger(value) ? value : 0)); +const unavailable = (diagnostic) => { + const error = new Error("Session protection state could not be confirmed"); + if (diagnostic) failureDiagnostics.set(error, Object.freeze(diagnostic)); + return error; +}; + +export const windowsFailureDiagnostic = (error) => failureDiagnostics.get(error); + +function helperDiagnostic(stderr) { + let phase = "unknown", + failurePhase = null, + errorCode = null, + workerExit = null; + let unexpected = false; + let validFrames = 0, + rejectedLines = 0; + const lines = (stderr ?? "").replace(/^\uFEFF/, "").split(/\r?\n/); + if (lines.at(-1) === "") lines.pop(); + for (const line of lines) { + const match = /^LSP1:([a-z-]+):(-?[0-9]{1,10})$/.exec(line); + const code = match ? boundedCode(Number(match[2])) : null; + if ( + !match || + code === null || + (match[1] === "compiler-bytes" && (code < 0 || code > 8192)) || + (match[1] === "compiler-format" && (code < 0 || code > 6)) || + (["root-entry", "root-flushed", "protect-open", "protect-flushed"].includes(match[1]) && code !== 0) || + (!phases.has(match[1]) && match[1] !== "worker-exit" && match[1] !== "helper-exit") + ) { + unexpected = true; + rejectedLines = boundedCount(rejectedLines + 1); + continue; + } + validFrames = boundedCount(validFrames + 1); + if (match[1] === "compiler-bytes" || match[1] === "compiler-format") continue; + if (match[1] === "worker-exit") { + workerExit = code; + if (code !== 0 && failurePhase === null) failurePhase = phase; + } else if (match[1] === "helper-exit") { + if (code !== 0 && failurePhase === null) failurePhase = phase; + } else if (phases.has(match[1])) { + phase = match[1]; + if (code !== 0) { + if (failurePhase === null) failurePhase = phase; + if (errorCode === null) errorCode = code; + } + } else unexpected = true; + } + return { + phase: failurePhase ?? phase, + lastValidatedPhase: phase, + errorCode, + workerExit, + unexpected, + failed: failurePhase !== null, + validFrames, + rejectedLines, + }; +} + +function failedOperation(result, started, phase) { + const helper = helperDiagnostic(result.stderr); + return unavailable({ + phase: phase ?? helper.phase, + lastValidatedPhase: helper.lastValidatedPhase, + exitCode: boundedCode(result.status), + workerExit: helper.workerExit, + signal: result.signal === "SIGTERM" ? 15 : result.signal === "SIGKILL" ? 9 : result.signal ? -1 : 0, + errorCode: boundedCode(result.error?.errno) ?? helper.errorCode, + helperErrorCode: helper.errorCode, + elapsedMs: Math.min(60000, Math.max(0, Math.round(performance.now() - started))), + timedOut: result.error?.code === "ETIMEDOUT", + stdoutUnits: boundedCount(result.stdout?.length), + stderrUnits: boundedCount(result.stderr?.length), + validFrames: helper.validFrames, + rejectedLines: helper.rejectedLines, + }); +} + +export function windowsSessionProtection(op, args) { + if (process.platform !== "win32" || !startupSystemRoot || !path.isAbsolute(startupSystemRoot)) throw unavailable(); + if (!["create", "inspect", "protect", "bind", "find", "establish"].includes(op)) throw unavailable(); + if (!args || typeof args.base !== "string" || !path.isAbsolute(args.base) || args.base.length > 2048) + throw unavailable(); + if (["inspect", "protect", "bind"].includes(op) && !/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/.test(args.id)) { + throw unavailable(); + } + if (["bind", "find", "establish"].includes(op) && !/^[0-9a-f]{64}$/.test(args.key)) throw unavailable(); + const request = JSON.stringify({ ...args, op }); + if (Buffer.byteLength(request, "utf8") > 4096) throw unavailable(); + const system32 = path.join(startupSystemRoot, "System32"); + const powershellHome = path.join(system32, "WindowsPowerShell", "v1.0"); + const compilationId = crypto.randomBytes(16).toString("hex"); + const started = performance.now(); + const deadline = started + operationTimeoutMs; + const executable = path.join(powershellHome, "powershell.exe"); + const arguments_ = ["-NoLogo", "-NoProfile", "-NonInteractive", "-File", script]; + const options = { + encoding: "utf8", + windowsHide: true, + cwd: system32, + maxBuffer: 1024, + env: { + SystemRoot: startupSystemRoot, + WINDIR: startupSystemRoot, + PATH: system32, + PSModulePath: path.join(powershellHome, "Modules"), + LOOM_PRIVATE_COMPILER_BASE: path.join(startupHome, ".loom", "session-protection-compiler"), + LOOM_PRIVATE_COMPILATION_ID: compilationId, + LOOM_PRIVATE_DEADLINE_UTC: String(Date.now() + operationTimeoutMs - cleanupReserveMs), + }, + }; + const result = spawnSync(executable, arguments_, { + ...options, + input: request, + timeout: operationTimeoutMs - cleanupReserveMs, + }); + if (result.error || result.signal) { + // Cleanup has its own exact invocation receipt, no compiler and no retry + // of the failed session operation. It shares the original overall budget. + const remaining = Math.floor(deadline - performance.now()); + let cleanupConfirmed = false; + if (remaining > 0) { + const cleanup = spawnSync(executable, [...arguments_, "-CleanupCompilation"], { + ...options, + env: { ...options.env, LOOM_PRIVATE_DEADLINE_UTC: String(Date.now() + remaining) }, + input: "", + timeout: remaining, + }); + const cleanupDiagnostic = helperDiagnostic(cleanup.stderr); + if ( + !cleanup.error && + !cleanup.signal && + cleanup.status === 0 && + !cleanupDiagnostic.unexpected && + !cleanupDiagnostic.failed + ) { + try { + const response = JSON.parse(cleanup.stdout.replace(/^\uFEFF/, "")); + cleanupConfirmed = + response?.ok === true && response.value === null && Object.keys(response).sort().join(",") === "ok,value"; + } catch { + cleanupConfirmed = false; + } + } + } + const error = failedOperation(result, started); + error.cleanupPending = !cleanupConfirmed; + throw error; + } + const helper = helperDiagnostic(result.stderr); + if (result.error || result.signal || result.status !== 0 || helper.unexpected || helper.failed) + throw failedOperation(result, started); + let response; + try { + response = JSON.parse(result.stdout.replace(/^\uFEFF/, "")); + } catch { + throw failedOperation(result, started, "protocol"); + } + if (!response || Object.keys(response).sort().join(",") !== "ok,value" || response.ok !== true) + throw failedOperation(result, started, "protocol"); + const value = response.value; + if ( + ["create", "establish"].includes(op) && + (typeof value !== "string" || !/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/.test(value)) + ) + throw failedOperation(result, started, "protocol"); + if (op === "inspect" && typeof value !== "boolean") throw failedOperation(result, started, "protocol"); + if (["protect", "bind"].includes(op) && value !== null) throw failedOperation(result, started, "protocol"); + if ( + op === "find" && + value !== null && + (typeof value !== "string" || !/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/.test(value)) + ) + throw failedOperation(result, started, "protocol"); + return value; +} diff --git a/integrations/claude-code-plugin/lib/windows-session-protection.ps1 b/integrations/claude-code-plugin/lib/windows-session-protection.ps1 new file mode 100644 index 0000000000..4c17ebc12f --- /dev/null +++ b/integrations/claude-code-plugin/lib/windows-session-protection.ps1 @@ -0,0 +1,291 @@ +# Durable session records use one native operation per helper invocation. +param([switch]$CleanupCompilation, [switch]$DefinitionsOnly) +$ErrorActionPreference = 'Stop' +# Fixed ASCII diagnostics precede cmdlet and encoding initialization. +$loomDiagnosticStream = [Console]::OpenStandardError() +$loomDiagnosticStream.Write([byte[]](76, 83, 80, 49, 58, 101, 110, 116, 114, 121, 58, 48, 10), 0, 13) +$loomDiagnosticStream.Flush() +$ProgressPreference = 'SilentlyContinue' +$loomDiagnosticStream.Write([byte[]](76, 83, 80, 49, 58, 101, 110, 99, 111, 100, 105, 110, 103, 45, 110, 101, 119, 58, 48, 10), 0, 20) +$loomDiagnosticStream.Flush() +$loomInputEncoding = [Text.UTF8Encoding]::new($false) +$loomDiagnosticStream.Write([byte[]](76, 83, 80, 49, 58, 101, 110, 99, 111, 100, 105, 110, 103, 45, 99, 114, 101, 97, 116, 101, 100, 58, 48, 10), 0, 24) +$loomDiagnosticStream.Flush() +[Console]::InputEncoding = $loomInputEncoding +$loomDiagnosticStream.Write([byte[]](76, 83, 80, 49, 58, 101, 110, 99, 111, 100, 105, 110, 103, 45, 105, 110, 112, 117, 116, 58, 48, 10), 0, 22) +$loomDiagnosticStream.Flush() +[Console]::OutputEncoding = [Text.UTF8Encoding]::new($false) +$loomDiagnosticStream.Write([byte[]](76, 83, 80, 49, 58, 101, 110, 99, 111, 100, 105, 110, 103, 45, 111, 117, 116, 112, 117, 116, 58, 48, 10), 0, 23) +$loomDiagnosticStream.Flush() +function Write-LoomProtectionPhase([string]$phase, [int]$code = 0) { + if ($phase -cnotin @('entry', 'encoding-new', 'encoding-created', 'encoding-input', 'encoding-output', 'startup', 'bootstrap', 'worker-bootstrap', 'guardian-deadline', 'native-job', 'native-timer', 'worker-start', 'worker-assign', 'compiler-private', 'compiler-identity', 'compiler-path', 'compiler-security', 'compiler-parents', 'compiler-directory', 'compiler-receipt', 'compiler-environment', 'compiler-launch', 'compiler-stopped', 'compiler-closed', 'compiler-scanned', 'compiler-bytes', 'compiler-format', 'compiler-stop', 'compiler-query', 'compiler-close', 'compile', 'request', 'request-parse', 'request-keys', 'native-op', 'record-construct', 'record-dispatch', 'root-entry', 'root-flushed', 'output-encode', 'cleanup', 'worker-exit', 'helper-exit')) { throw 'Unavailable' } + if ($phase -cnotin @('worker-exit', 'helper-exit', 'compiler-bytes', 'compiler-format')) { $script:loomProtectionPhase = $phase } + try { + [Console]::Error.WriteLine('LSP1:' + $phase + ':' + $code.ToString([Globalization.CultureInfo]::InvariantCulture)) + [Console]::Error.Flush() + } catch { $script:loomProtectionDiagnosticFailed = $true } +} +function Invoke-LoomCompilerScope([type]$native, [bool]$CleanupCompilation, [scriptblock]$Operation, [scriptblock]$BeforeCleanup = $null) { +$held = [System.Collections.Generic.List[System.IntPtr]]::new() +$compileDirectory = $null +$compilerHandleStart = -1 +$result = $null +$succeeded = $false + +try { + Write-LoomProtectionPhase $(if ($CleanupCompilation) { 'cleanup' } else { 'compiler-private' }) + if ($ExecutionContext.SessionState.LanguageMode -ne 'FullLanguage') { throw 'Unavailable' } + Write-LoomProtectionPhase 'compiler-identity' + $sid = [System.Security.Principal.WindowsIdentity]::GetCurrent().User + + function Pin-Directory([string]$directory, [bool]$private, [bool]$allowMissing = $false) { + # READ_CONTROL | FILE_READ_ATTRIBUTES; no FILE_SHARE_DELETE. + $handle = $native::CreateFileW($directory, 0x20080, 3, [IntPtr]::Zero, 3, 0x02200000, [IntPtr]::Zero) + if ($handle.ToInt64() -eq -1) { + $openError = [Runtime.InteropServices.Marshal]::GetLastWin32Error() + if ($allowMissing -and ($openError -eq 2 -or $openError -eq 3)) { return $false } + throw 'Unavailable' + } + $held.Add($handle) + $information = [Runtime.InteropServices.Marshal]::AllocHGlobal(52) + try { + if (-not $native::GetFileInformationByHandle($handle, $information)) { throw 'Unavailable' } + $attributes = [Runtime.InteropServices.Marshal]::ReadInt32($information) + if (($attributes -band 0x400) -ne 0 -or ($attributes -band 0x10) -eq 0) { throw 'Unavailable' } + } finally { [Runtime.InteropServices.Marshal]::FreeHGlobal($information) } + if (-not $private) { return $true } + $owner = $group = $dacl = $sacl = $sd = [IntPtr]::Zero + if ($native::GetSecurityInfo($handle, 1, 5, [ref]$owner, [ref]$group, [ref]$dacl, [ref]$sacl, [ref]$sd) -ne 0) { throw 'Unavailable' } + try { + if ($owner -eq [IntPtr]::Zero -or $dacl -eq [IntPtr]::Zero -or $sd -eq [IntPtr]::Zero) { throw 'Unavailable' } + $length = $native::GetSecurityDescriptorLength($sd) + if ($length -lt 1 -or $length -gt 65536) { throw 'Unavailable' } + $bytes = [byte[]]::new($length) + [Runtime.InteropServices.Marshal]::Copy($sd, $bytes, 0, $length) + $actual = [System.Security.AccessControl.RawSecurityDescriptor]::new($bytes, 0) + if (-not $sid.Equals($actual.Owner) -or ($actual.ControlFlags -band 0x1004) -ne 0x1004 -or $null -eq $actual.DiscretionaryAcl -or $actual.DiscretionaryAcl.Count -ne 1) { throw 'Unavailable' } + $ace = $actual.DiscretionaryAcl[0] + if ($ace -isnot [System.Security.AccessControl.CommonAce] -or $ace.IsCallback -or $ace.AceQualifier -ne [System.Security.AccessControl.AceQualifier]::AccessAllowed -or $ace.AceFlags -ne 3 -or $ace.AccessMask -ne 0x1f01ff -or -not $sid.Equals($ace.SecurityIdentifier)) { throw 'Unavailable' } + } finally { if ($sd -ne [IntPtr]::Zero) { [void]$native::LocalFree($sd) } } + return $true + } + + function New-PrivateDirectory([string]$directory, [bool]$allowExisting) { + $binary = $security.GetSecurityDescriptorBinaryForm() + $descriptor = [Runtime.InteropServices.Marshal]::AllocHGlobal($binary.Length) + $attributeSize = if ([IntPtr]::Size -eq 8) { 24 } else { 12 } + $pointerOffset = if ([IntPtr]::Size -eq 8) { 8 } else { 4 } + $attributes = [Runtime.InteropServices.Marshal]::AllocHGlobal($attributeSize) + try { + [Runtime.InteropServices.Marshal]::Copy($binary, 0, $descriptor, $binary.Length) + [Runtime.InteropServices.Marshal]::WriteInt32($attributes, 0, $attributeSize) + [Runtime.InteropServices.Marshal]::WriteIntPtr($attributes, $pointerOffset, $descriptor) + [Runtime.InteropServices.Marshal]::WriteInt32($attributes, $pointerOffset + [IntPtr]::Size, 0) + if (-not $native::CreateDirectoryW($directory, $attributes)) { + $errorCode = [Runtime.InteropServices.Marshal]::GetLastWin32Error() + if (-not $allowExisting -or $errorCode -ne 183) { throw 'Unavailable' } + } + } finally { + [Runtime.InteropServices.Marshal]::FreeHGlobal($attributes) + [Runtime.InteropServices.Marshal]::FreeHGlobal($descriptor) + } + } + + Write-LoomProtectionPhase 'compiler-path' + $compilerBase = [IO.Path]::GetFullPath($env:LOOM_PRIVATE_COMPILER_BASE) + $compilationId = $env:LOOM_PRIVATE_COMPILATION_ID + if ($compilationId -notmatch '^[0-9a-f]{32}$') { throw 'Unavailable' } + $root = [IO.Path]::GetPathRoot($compilerBase) + if ($root -notmatch '^[A-Za-z]:\\$') { throw 'Unavailable' } + Write-LoomProtectionPhase 'compiler-security' + $security = [System.Security.AccessControl.DirectorySecurity]::new() + $security.SetOwner($sid) + $security.SetAccessRuleProtection($true, $false) + # Compiler-created files must inherit owner-only authority themselves; + # directory traversal checks may be bypassed by SeChangeNotifyPrivilege. + $inherit = [System.Security.AccessControl.InheritanceFlags]'ObjectInherit, ContainerInherit' + $security.AddAccessRule(([System.Security.AccessControl.FileSystemAccessRule]::new($sid, + [System.Security.AccessControl.FileSystemRights]::FullControl, $inherit, + [System.Security.AccessControl.PropagationFlags]::None, [System.Security.AccessControl.AccessControlType]::Allow))) + Write-LoomProtectionPhase 'compiler-parents' + [void](Pin-Directory $root $false) + $current = $root + $missing = $false + $parts = $compilerBase.Substring($root.Length).Split([char]'\') + for ($i = 0; $i -lt $parts.Length; $i++) { + $current = [IO.Path]::Combine($current, $parts[$i]) + if (-not (Pin-Directory $current ($i -eq $parts.Length - 1) $true)) { + if ($CleanupCompilation) { + $missing = $true + break + } + # Existing ancestors need no directory creation or descriptor copy. + New-PrivateDirectory $current $true + [void](Pin-Directory $current ($i -eq $parts.Length - 1)) + } + } + $candidate = [IO.Path]::Combine($compilerBase, $compilationId) + if ($CleanupCompilation) { + if (-not $missing) { + $compilerHandleStart = $held.Count + if (Pin-Directory $candidate $true $true) { + # A receipt is written only after exclusive directory creation. + # Without it cleanup refuses rather than deleting unknown data. + $marker = [IO.File]::ReadAllText([IO.Path]::Combine($candidate, 'created')) + if ($marker -ne ('loom-compiler-v1:' + $compilationId)) { throw 'Unavailable' } + $compileDirectory = $candidate + } + } + $succeeded = $true + $result = $null + } else { + Write-LoomProtectionPhase 'compiler-directory' + New-PrivateDirectory $candidate $false + $compileDirectory = $candidate + $compilerHandleStart = $held.Count + [void](Pin-Directory $compileDirectory $true) + Write-LoomProtectionPhase 'compiler-receipt' + [IO.File]::WriteAllText([IO.Path]::Combine($compileDirectory, 'created'), ('loom-compiler-v1:' + $compilationId)) + + $result = & $Operation $compileDirectory + $succeeded = $true + } +} catch { + Write-LoomProtectionPhase $script:loomProtectionPhase ([int]$_.Exception.HResult) + $succeeded = $false +} finally { + if ($null -ne $BeforeCleanup) { & $BeforeCleanup } + Write-LoomProtectionPhase 'cleanup' + if ($compilerHandleStart -ge 0) { + for ($i = $held.Count - 1; $i -ge $compilerHandleStart; $i--) { + if (-not $native::CloseHandle($held[$i])) { $succeeded = $false } + $held.RemoveAt($i) + } + } + if ($null -ne $compileDirectory) { + try { + foreach ($file in [IO.Directory]::GetFileSystemEntries($compileDirectory)) { + $attributes = [IO.File]::GetAttributes($file) + if (($attributes -band 0x410) -ne 0) { throw 'Unavailable' } + [IO.File]::Delete($file) + } + [IO.Directory]::Delete($compileDirectory, $false) + } catch { + Write-LoomProtectionPhase 'cleanup' ([int]$_.Exception.HResult) + $succeeded = $false + } + } + for ($i = $held.Count - 1; $i -ge 0; $i--) { + if (-not $native::CloseHandle($held[$i])) { $succeeded = $false } + } +} +if (-not $succeeded) { throw 'Unavailable' } +return $result +} + +function Invoke-LoomCompileRecords([type]$native, [IntPtr]$job, [long]$deadline, [string]$directory) { + Write-LoomProtectionPhase 'compile' + $source = [IO.File]::ReadAllText([IO.Path]::Combine($PSScriptRoot, 'windows-private-records.cs')) + [IO.File]::WriteAllText([IO.Path]::Combine($directory, 'records.cs'), $source, [Text.UTF8Encoding]::new($true)) + # Fixed names under the exclusive, pinned invocation directory. No request + # value reaches the compiler or its response file. + if ($directory.Contains('"') -or $directory.Contains("`r") -or $directory.Contains("`n")) { throw 'Unavailable' } + $runtime = [Runtime.InteropServices.RuntimeEnvironment]::GetRuntimeDirectory() + if ($runtime.Contains('"') -or $runtime.Contains("`r") -or $runtime.Contains("`n")) { throw 'Unavailable' } + $options = @('/target:library', '/optimize+', '/warnaserror+', '/debug-', '/nostdlib+', + ('/reference:"' + [IO.Path]::Combine($runtime, 'mscorlib.dll') + '"'), + ('/reference:"' + [IO.Path]::Combine($runtime, 'System.dll') + '"'), + ('/reference:"' + [IO.Path]::Combine($runtime, 'System.Core.dll') + '"'), + ('/out:"' + [IO.Path]::Combine($directory, 'records.dll') + '"'), + ('"' + [IO.Path]::Combine($directory, 'records.cs') + '"')) + [IO.File]::WriteAllLines([IO.Path]::Combine($directory, 'compile.rsp'), $options, [Text.UTF8Encoding]::new($true)) + Invoke-LoomCompilerProcess $native $job $deadline $directory ('/noconfig @"' + [IO.Path]::Combine($directory, 'compile.rsp') + '"') + Stop-LoomCompilerJob $native $job + if ([DateTimeOffset]::UtcNow.ToUnixTimeMilliseconds() -ge $deadline) { throw 'Unavailable' } + # Byte loading avoids locking the owned DLL during exact cleanup. Resolve + # the authority type from THIS assembly, never an ambient type-name cache. + return [Reflection.Assembly]::Load([IO.File]::ReadAllBytes([IO.Path]::Combine($directory, 'records.dll'))) +} + +function Invoke-LoomRecordOperation([Reflection.Assembly]$assembly) { + Write-LoomProtectionPhase 'request' + $buffer = [char[]]::new(4097) + $count = 0 + while ($count -lt $buffer.Length) { + $read = [Console]::In.Read($buffer, $count, $buffer.Length - $count) + if ($read -eq 0) { break } + $count += $read + } + if ($count -gt 4096) { throw 'Unavailable' } + $codecType = $assembly.GetType('WindowsPrivateRecords', $true, $false) + Write-LoomProtectionPhase 'request-parse' + $request = $codecType::ParseRequest(([string]::new($buffer, 0, $count))) + Write-LoomProtectionPhase 'request-keys' + Write-LoomProtectionPhase 'native-op' + $recordType = $assembly.GetType('WindowsPrivateRecords', $true, $false) + Write-LoomProtectionPhase 'record-construct' + $store = [Activator]::CreateInstance($recordType, [object[]]@($request['base'])) + Write-LoomProtectionPhase 'record-dispatch' + $result = switch ($request['op']) { + 'create' { $store.CreateRoot() } + 'inspect' { $store.IsProtected($request['id']) } + 'protect' { $store.AppendProtection($request['id']); $null } + 'bind' { $store.BindAlias($request['key'], $request['id']); $null } + 'find' { $store.FindAlias($request['key']) } + 'establish' { $store.EstablishAlias($request['key']) } + } + Write-LoomProtectionPhase 'output-encode' + return $recordType::EncodeResponse($request['op'], $result) +} + +if ($DefinitionsOnly) { return } +$loomTerminalReady = $false +$loomTerminalExitAttempted = $false +try { + Write-LoomProtectionPhase 'startup' + if ($ExecutionContext.SessionState.LanguageMode -ne 'FullLanguage') { throw 'Unavailable' } + . ([IO.Path]::Combine($PSScriptRoot, 'windows-native-bootstrap.ps1')) + . ([IO.Path]::Combine($PSScriptRoot, 'windows-compiler-job.ps1')) + Write-LoomProtectionPhase 'bootstrap' + $native = New-LoomBootstrapApi + if ($CleanupCompilation) { + [void](Start-LoomGuardianDeadline $native) + [void](Invoke-LoomCompilerScope $native $true $null) + [Console]::Out.Write('{"ok":true,"value":null}') + } else { + $compiled = Invoke-LoomGuardedCompiler $native { + param($compilerNative, $compilerJob, $compilerDeadline, $directory) + Invoke-LoomCompileRecords $compilerNative $compilerJob $compilerDeadline $directory + } + $loomTerminalReady = $true + # Compilation descendants and owned files are already gone. Preserve + # the original earlier native-operation cutoff on this same self-job. + Start-LoomNativeTimer $native 'StopJob' $compiled.Guardian.Job ($compiled.Guardian.Deadline - 150) + $result = Invoke-LoomRecordOperation $compiled.Value + [Console]::Out.Write($result) + } + Write-LoomProtectionPhase 'helper-exit' 0 + if ($script:loomProtectionDiagnosticFailed) { throw 'Unavailable' } + if ($loomTerminalReady) { + $loomTerminalExitAttempted = $true + [Console]::Out.Flush() + [Console]::Error.Flush() + [void]$native::TerminateProcess($native::GetCurrentProcess(), [uint32]0) + # Exact-self termination must not return, including a false API result. + throw 'Unavailable' + } + exit 0 +} catch { + Write-LoomProtectionPhase $script:loomProtectionPhase ([int]$_.Exception.HResult) + Write-LoomProtectionPhase 'helper-exit' 1 + [Console]::Out.Write('{"ok":false}') + if ($loomTerminalReady -and -not $loomTerminalExitAttempted) { + $loomTerminalExitAttempted = $true + try { + [Console]::Out.Flush() + [Console]::Error.Flush() + [void]$native::TerminateProcess($native::GetCurrentProcess(), [uint32]1) + } catch { } # Terminal failure remains failure under the existing watchdogs. + } + exit 1 +} diff --git a/integrations/claude-code-plugin/tests/agent-mode-fallback.test.mjs b/integrations/claude-code-plugin/tests/agent-mode-fallback.test.mjs index 10dff4d39d..dc99890d2f 100644 --- a/integrations/claude-code-plugin/tests/agent-mode-fallback.test.mjs +++ b/integrations/claude-code-plugin/tests/agent-mode-fallback.test.mjs @@ -3,6 +3,7 @@ // person saved on this machine, nor sign a new identity up. Both run as the // host runs them, against a server whose token endpoint is away. import "./temp-home.mjs"; +import { establishFixtureSession } from "./established-session.mjs"; import { test } from "node:test"; import assert from "node:assert/strict"; import { spawn } from "node:child_process"; @@ -36,8 +37,10 @@ function run(rel, url, stdin = "") { fs.writeFileSync(path.join(home, ".loom", "config.json"), JSON.stringify({ token: PERSONAL, url }), { mode: 0o600, }); + const args = rel.startsWith("hooks/") ? ["SessionStart"] : []; + if (rel.startsWith("hooks/")) establishFixtureSession(home, "agent-fallback-session"); return new Promise((resolve) => { - const child = spawn(process.execPath, [entry(rel)], { + const child = spawn(process.execPath, [entry(rel), ...args], { cwd: home, env: hostEnv({ PATH: process.env.PATH, @@ -58,7 +61,7 @@ function run(rel, url, stdin = "") { } for (const [name, rel, stdin] of [ - ["the SessionStart hook", "hooks/loom-session-start.mjs", "{}"], + ["the SessionStart hook", "hooks/loom-session-start.mjs", JSON.stringify({ session_id: "agent-fallback-session" })], ["the MCP headers helper", "bin/loom-mcp-headers.mjs", ""], ]) { test(`${name} sends neither the person's saved token nor a sign-up when the exchange fails`, async () => { diff --git a/integrations/claude-code-plugin/tests/code-hooks-failopen.test.mjs b/integrations/claude-code-plugin/tests/code-hooks-failopen.test.mjs index 7e8e83ff39..eae1c5cbdc 100644 --- a/integrations/claude-code-plugin/tests/code-hooks-failopen.test.mjs +++ b/integrations/claude-code-plugin/tests/code-hooks-failopen.test.mjs @@ -4,6 +4,7 @@ // Every case exits 0 within its bound and says nothing, or only what local // policy decides without the server. import "./temp-home.mjs"; +import { establishFixtureSession } from "./established-session.mjs"; import { test } from "node:test"; import assert from "node:assert/strict"; import fs from "node:fs"; @@ -14,6 +15,8 @@ import { execFileSync, spawn } from "node:child_process"; import { fileURLToPath } from "node:url"; import { cachePathFor } from "../lib/repo-scope.mjs"; import { hostEnv } from "./host-env.mjs"; +import { protectSession, sessionIsProtected } from "../lib/session-protection.mjs"; +import { sessionStatePath, writeSessionState } from "../lib/tmp-state.mjs"; const HOOKS = path.join(path.dirname(fileURLToPath(import.meta.url)), "..", "hooks"); const BIG = Array.from({ length: 400 }, (_, i) => `int f${i}() { return ${i}; }`).join("\n") + "\n"; @@ -35,8 +38,10 @@ function checkout() { return dir; } -function freshTmp() { - return fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "loom-failopen-tmp-"))); +function freshTmp(existingSessions = []) { + const tmp = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "loom-failopen-tmp-"))); + for (const sessionId of existingSessions) establishFixtureSession(tmp, sessionId); + return tmp; } function seedIndexed(root, tmp) { @@ -50,7 +55,14 @@ function seedIndexed(root, tmp) { function run(hook, stdin, { tmp, url = REFUSED, token = "t", env = {} }) { return new Promise((resolve) => { const started = Date.now(); - const child = spawn(process.execPath, [path.join(HOOKS, hook), "X"], { + const event = { + "loom-code-shunt.mjs": "PreToolUse", + "loom-file-context.mjs": "PreToolUse", + "loom-blast-radius.mjs": "PostToolUse", + "loom-test-gate.mjs": "Stop", + "loom-validate-gate.mjs": "Stop", + }[hook]; + const child = spawn(process.execPath, [path.join(HOOKS, hook), event], { env: hostEnv({ PATH: process.env.PATH, HOME: tmp, @@ -138,7 +150,7 @@ test("malformed, empty and non-object stdin: every code hook exits 0 and prints test("no token: nothing is asked of the server and nothing is printed", async () => { const dir = checkout(); await withServer(200, async (url, seen) => { - const tmp = freshTmp(); + const tmp = freshTmp(["s"]); const read = { tool_name: "Read", tool_input: { file_path: path.join(dir, "src/a.cpp") }, @@ -168,7 +180,7 @@ test("no token: nothing is asked of the server and nothing is printed", async () test("shunt: a refused connection with no cached entry passes and is retried soon, not cached as not-indexed", async () => { const dir = checkout(); - const tmp = freshTmp(); + const tmp = freshTmp(["s"]); const r = await run( "loom-code-shunt.mjs", { tool_name: "Read", tool_input: { file_path: path.join(dir, "src/a.cpp") }, cwd: dir, session_id: "s" }, @@ -184,7 +196,7 @@ test("shunt: a refused connection with no cached entry passes and is retried soo test("shunt: a 401 from the repository lookup passes the call and records it unresolved", async () => { const dir = checkout(); await withServer(401, async (url, seen) => { - const tmp = freshTmp(); + const tmp = freshTmp(["s"]); const r = await run( "loom-code-shunt.mjs", { tool_name: "Read", tool_input: { file_path: path.join(dir, "src/a.cpp") }, cwd: dir, session_id: "s" }, @@ -200,7 +212,7 @@ test("shunt: a 401 from the repository lookup passes the call and records it unr test("shunt: a server that never answers holds the call no longer than the lookup bound", async () => { const dir = checkout(); await withServer(null, async (url) => { - const tmp = freshTmp(); + const tmp = freshTmp(["s"]); const r = await run( "loom-code-shunt.mjs", { tool_name: "Read", tool_input: { file_path: path.join(dir, "src/a.cpp") }, cwd: dir, session_id: "s" }, @@ -215,7 +227,7 @@ test("shunt: a server that never answers holds the call no longer than the looku test("shunt: an indexed entry decides locally; a symbol grep whose answer hangs keeps the plain redirect", async () => { const dir = checkout(); await withServer(null, async (url, seen, arrived) => { - const tmp = freshTmp(); + const tmp = freshTmp(["s"]); seedIndexed(dir, tmp); const r = await run( "loom-code-shunt.mjs", @@ -249,7 +261,7 @@ test("shunt: an indexed entry decides locally; a symbol grep whose answer hangs }); test("shunt: outside a git checkout, or a tool it does not judge, nothing happens", async () => { - const tmp = freshTmp(); + const tmp = freshTmp(["s"]); const r = await run( "loom-code-shunt.mjs", { tool_name: "Read", tool_input: { file_path: path.join(tmp, "x") }, cwd: tmp, session_id: "s" }, @@ -263,10 +275,10 @@ test("shunt: outside a git checkout, or a tool it does not judge, nothing happen }); /** A dirty indexed checkout and a transcript whose Edit named the file. */ -function dirtySession() { +function dirtySession(existingSessions) { const dir = checkout(); fs.appendFileSync(path.join(dir, "src/a.cpp"), "int g() { return 1; }\n"); - const tmp = freshTmp(); + const tmp = freshTmp(existingSessions); seedIndexed(dir, tmp); const transcript = path.join(tmp, "t.jsonl"); fs.writeFileSync( @@ -292,7 +304,7 @@ test("Stop gates: 401 and a hanging server both let the stop through", async () // A request can fail before the server observes it; require a witnessed run. let r; for (let attempt = 0; attempt < 3; attempt++) { - const { dir, tmp, transcript } = dirtySession(); + const { dir, tmp, transcript } = dirtySession(["s"]); arrived.delete(op); r = await run( hook, @@ -319,7 +331,7 @@ test("Stop gates: 401 and a hanging server both let the stop through", async () test("Stop gates: a Stop the gate itself caused never blocks again", async () => { await withServer(200, async (url, seen) => { for (const hook of ["loom-test-gate.mjs", "loom-validate-gate.mjs"]) { - const { dir, tmp, transcript } = dirtySession(); + const { dir, tmp, transcript } = dirtySession(["s"]); const r = await run( hook, { cwd: dir, session_id: "s", transcript_path: transcript, stop_hook_active: true }, @@ -342,7 +354,7 @@ test("blast radius and file context: 401 and a hanging server add nothing to the // A request can fail before the server observes it; require a witnessed run. let r; for (let attempt = 0; attempt < 3; attempt++) { - const { dir, tmp } = dirtySession(); + const { dir, tmp } = dirtySession([`s-${hook}-${attempt}`]); const edit = { tool_name: "Edit", tool_input: { file_path: path.join(dir, "src/a.cpp") }, @@ -373,7 +385,7 @@ test("blast radius and file context: 401 and a hanging server add nothing to the test("shunt: the whole hook ends by its deadline even when one answer is slower than it", async () => { const dir = checkout(); await withServer(null, async (url, seen) => { - const tmp = freshTmp(); + const tmp = freshTmp(["s"]); seedIndexed(dir, tmp); const r = await run( "loom-code-shunt.mjs", @@ -389,7 +401,7 @@ test("shunt: the whole hook ends by its deadline even when one answer is slower test("shunt: a tracker search reaches tracker.duplicate_check redacted", async () => { const dir = checkout(); - const tmp = freshTmp(); + const tmp = freshTmp(["s"]); seedIndexed(dir, tmp); const bodies = await withCapturingServer(async (url) => { const command = 'gh issue list --search "login fails password=hunter2"'; @@ -405,7 +417,7 @@ test("shunt: a tracker search reaches tracker.duplicate_check redacted", async ( }); test("blast radius and test gate: only the diff's paths and hunk headers reach the server", async () => { - const { dir, tmp, transcript } = dirtySession(); + const { dir, tmp, transcript } = dirtySession(["s"]); fs.appendFileSync(path.join(dir, "src/a.cpp"), 'const char* api_key = "s3cr3t-value";\n'); // a second change three lines above the first: two hunks unless they are merged const src = path.join(dir, "src/a.cpp"); @@ -454,7 +466,7 @@ test("blast radius and test gate: only the diff's paths and hunk headers reach t }); test("blast radius: a change with no path or range for the server sends nothing", async () => { - const { dir, tmp } = dirtySession(); + const { dir, tmp } = dirtySession(["s"]); execFileSync("git", ["checkout", "-q", "--", "src/a.cpp"], { cwd: dir }); fs.chmodSync(path.join(dir, "src/a.cpp"), 0o755); const bodies = await withCapturingServer(async (url) => { @@ -471,3 +483,72 @@ test("blast radius: a change with no path or range for the server sends nothing" [], ); }); + +for (const mode of ["ordinary", "mirrored", "late-sibling-mark"]) { + test(`file context ${mode} guards acknowledgment and output after its lookup`, async () => { + const dir = checkout(); + const tmp = freshTmp(); + let server; + try { + const sessionId = `file-context-${mode}`; + const root = establishFixtureSession(tmp, sessionId); + const statePath = sessionStatePath("file-context", sessionId, { tmp }); + writeSessionState("file-context", sessionId, { seen: { "prior.cpp": Date.now() } }, { tmp }); + const before = fs.readFileSync(statePath); + const seen = []; + server = http.createServer((req, res) => { + req.resume(); + req.on("end", () => { + seen.push(req.url); + if (req.url !== "/v1/memory.for_file") { + res.writeHead(500).end("{}"); + return; + } + // The actual hook has dispatched and is waiting for this response. + if (mode === "late-sibling-mark") protectSession(root); + res.setHeader("content-type", "application/json"); + res.end( + JSON.stringify({ + total: 1, + rendered: mode === "ordinary" ? "ORDINARY FILE RULE" : "PRIVATE FILE RULE", + mirrored: mode === "mirrored", + }), + ); + }); + }); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + const answer = await run( + "loom-file-context.mjs", + { + tool_name: "Edit", + tool_input: { file_path: path.join(dir, "src/a.cpp") }, + cwd: dir, + session_id: sessionId, + }, + { tmp, url: `http://127.0.0.1:${server.address().port}` }, + ); + assert.equal(answer.code, 0, answer.err); + assert.equal(answer.err, ""); + assert.deepEqual(seen, ["/v1/memory.for_file"]); + if (mode === "ordinary") { + const context = JSON.parse(answer.out).hookSpecificOutput.additionalContext; + assert.match(context, /ORDINARY FILE RULE/); + const state = JSON.parse(fs.readFileSync(statePath, "utf8")); + assert.equal(typeof state.seen["src/a.cpp"], "number"); + assert.notDeepEqual(fs.readFileSync(statePath), before); + assert.equal(sessionIsProtected(root), false); + } else { + assert.equal(answer.out, ""); + assert.deepEqual(fs.readFileSync(statePath), before); + assert.equal(sessionIsProtected(root), true); + } + } finally { + if (server) { + server.closeAllConnections(); + await new Promise((resolve) => server.close(resolve)); + } + fs.rmSync(tmp, { recursive: true, force: true }); + fs.rmSync(dir, { recursive: true, force: true }); + } + }); +} diff --git a/integrations/claude-code-plugin/tests/code-shunt-hook.test.mjs b/integrations/claude-code-plugin/tests/code-shunt-hook.test.mjs index cdfeec817b..d58576a40f 100644 --- a/integrations/claude-code-plugin/tests/code-shunt-hook.test.mjs +++ b/integrations/claude-code-plugin/tests/code-shunt-hook.test.mjs @@ -3,6 +3,7 @@ // seeded in the shared cache (no code.repos call), the hook run as Claude // Code runs it, and a local server only where a call is expected. import "./temp-home.mjs"; +import { establishFixtureSession } from "./established-session.mjs"; import { test } from "node:test"; import assert from "node:assert/strict"; import fs from "node:fs"; @@ -11,8 +12,10 @@ import os from "node:os"; import path from "node:path"; import { execFileSync, spawn } from "node:child_process"; import { fileURLToPath } from "node:url"; +import { performance } from "node:perf_hooks"; import { cachePathFor } from "../lib/repo-scope.mjs"; -import { batchKind } from "../lib/shunt-ledger.mjs"; +import { batchKind, parseShuntBatch } from "../lib/shunt-ledger.mjs"; +import { protectSession, sessionIsProtected } from "../lib/session-protection.mjs"; import { sessionStatePath, tmpStatePath } from "../lib/tmp-state.mjs"; import { hostEnv } from "./host-env.mjs"; @@ -45,7 +48,7 @@ function checkout(files) { /** A fresh TMPDIR holding the repo entry the session-start primer would have * written. */ -function seed(root, { asOf = FAR_BEHIND } = {}) { +function seed(root, { asOf = FAR_BEHIND, existingSessions = [] } = {}) { const tmp = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "loom-shunt-tmp-"))); fs.writeFileSync( cachePathFor(root, tmp), @@ -61,10 +64,83 @@ function seed(root, { asOf = FAR_BEHIND } = {}) { fetchedAt: "", }), ); + for (const sessionId of existingSessions) establishFixtureSession(tmp, sessionId); return tmp; } -function runHook(payload, { tmp, url = "http://127.0.0.1:9", env = {} }) { +function recordFixtureEvent(observation, event, details = {}) { + if (!observation || observation.events.length >= 32) return; + observation.events.push({ event, elapsedMs: Math.round(performance.now() - observation.startedAt), ...details }); +} + +function observedFailure(error, observation) { + error.message += `; shunt fixture observation ${JSON.stringify(observation.events)}`; + return error; +} + +function observedClaimControl(file) { + const unavailable = { readable: false, controlValid: null, rows: null, roots: null }; + if (typeof process.getuid !== "function" || !fs.constants.O_NOFOLLOW || !fs.constants.O_NONBLOCK) { + return unavailable; + } + let fd; + try { + fd = fs.openSync(file, fs.constants.O_RDONLY | fs.constants.O_NOFOLLOW | fs.constants.O_NONBLOCK); + const held = fs.fstatSync(fd); + if ( + !held.isFile() || + held.nlink !== 1 || + held.uid !== process.getuid() || + (held.mode & 0o077) !== 0 || + !Number.isSafeInteger(held.size) || + held.size < 0 || + held.size > 65536 + ) { + return unavailable; + } + const bytes = Buffer.alloc(held.size); + if (fs.readSync(fd, bytes, 0, bytes.length, 0) !== bytes.length) return unavailable; + const current = fs.fstatSync(fd); + if (current.size !== held.size || current.nlink !== 1) return unavailable; + const batch = parseShuntBatch(bytes.toString("utf8")); + return { + readable: true, + controlValid: Boolean(batch), + rows: batch?.lines ?? null, + roots: batch?.roots.length ?? null, + }; + } catch { + return unavailable; + } finally { + if (fd !== undefined) fs.closeSync(fd); + } +} + +function observedRetainedClaims(tmp) { + const claims = []; + let directory; + let complete = false; + try { + directory = fs.opendirSync(tmp); + for (let scanned = 0; scanned < 64 && claims.length < 4; scanned++) { + const entry = directory.readSync(); + if (!entry) { + complete = true; + break; + } + if (entry.name.startsWith("loom-shunt-protected-claim-") && entry.name.endsWith(".log.control")) { + claims.push(observedClaimControl(path.join(tmp, entry.name))); + } + } + return { limited: !complete, claims }; + } finally { + if (directory) directory.closeSync(); + } +} + +function runHook(payload, { tmp, url = "http://127.0.0.1:9", env = {}, observation }) { + const startedAt = performance.now(); + const childNumber = observation ? ++observation.children : 0; return new Promise((resolve) => { const child = spawn(process.execPath, [HOOK, "PreToolUse"], { env: hostEnv({ @@ -82,7 +158,13 @@ function runHook(payload, { tmp, url = "http://127.0.0.1:9", env = {} }) { child.stdout.on("data", (c) => { out += c; }); - child.on("close", () => { + child.on("close", (code, signal) => { + recordFixtureEvent(observation, "hook-close", { + child: childNumber, + code: Number.isInteger(code) && code >= -2147483648 && code <= 2147483647 ? code : null, + signal: typeof signal === "string" && /^SIG[A-Z0-9]{1,12}$/.test(signal) ? signal : null, + childElapsedMs: Math.round(performance.now() - startedAt), + }); let log = ""; try { log = fs.readFileSync(logPath(tmp), "utf8"); @@ -90,7 +172,13 @@ function runHook(payload, { tmp, url = "http://127.0.0.1:9", env = {} }) { /* no decision logged */ } const hso = out ? JSON.parse(out).hookSpecificOutput : {}; - resolve({ deny: hso.permissionDecisionReason ?? null, updatedInput: hso.updatedInput ?? null, log }); + resolve({ + code, + stdout: out, + deny: hso.permissionDecisionReason ?? null, + updatedInput: hso.updatedInput ?? null, + log, + }); }); child.stdin.end(JSON.stringify(payload)); }); @@ -98,20 +186,26 @@ function runHook(payload, { tmp, url = "http://127.0.0.1:9", env = {} }) { async function withServer(answers, fn) { const seen = []; + const observation = { startedAt: performance.now(), children: 0, requests: 0, events: [] }; const server = http.createServer((req, res) => { + const request = ++observation.requests; + recordFixtureEvent(observation, "request-open", { request }); + res.once("finish", () => recordFixtureEvent(observation, "response-finish", { request })); let raw = ""; req.on("data", (c) => { raw += c; }); req.on("end", () => { + recordFixtureEvent(observation, "request-end", { request }); seen.push({ url: req.url, body: raw ? JSON.parse(raw) : {} }); res.setHeader("content-type", "application/json"); - res.end(JSON.stringify(answers[req.url] || {})); + const answer = answers[req.url]; + res.end(JSON.stringify(typeof answer === "function" ? answer() : answer || {})); }); }); await new Promise((r) => server.listen(0, "127.0.0.1", r)); try { - return await fn(`http://127.0.0.1:${server.address().port}`, seen); + return await fn(`http://127.0.0.1:${server.address().port}`, seen, observation); } finally { server.close(); } @@ -126,7 +220,7 @@ const readOf = (dir, rel) => ({ test("a checkout far behind the index is still shunted", async () => { const { dir } = checkout({ "src/a.cpp": BIG }); - const r = await runHook(readOf(dir, "src/a.cpp"), { tmp: seed(dir) }); + const r = await runHook(readOf(dir, "src/a.cpp"), { tmp: seed(dir, { existingSessions: ["e2e"] }) }); assert.match( r.deny, /^loom-code-shunt: src\/a\.cpp is 900 lines and is in loom's code index \(as of 0123456789ab\)\./, @@ -137,7 +231,7 @@ test("a checkout far behind the index is still shunted", async () => { test("local_first stands the shunt down entirely, even when HEAD is the indexed commit", async () => { const { dir, head } = checkout({ "src/a.cpp": BIG }); for (const env of [{ LOOM_CODE_LOCAL_FIRST: "on" }, { CLAUDE_PLUGIN_OPTION_LOCAL_FIRST: "true" }]) { - const tmp = seed(dir, { asOf: head }); + const tmp = seed(dir, { asOf: head, existingSessions: ["e2e"] }); const r = await runHook(readOf(dir, "src/a.cpp"), { tmp, env }); assert.equal(r.deny, null); assert.equal(r.log, "", "no decision at all"); @@ -152,7 +246,7 @@ test("local_first stands the shunt down entirely, even when HEAD is the indexed test("a modified file still passes: the index cannot describe uncommitted edits", async () => { const { dir } = checkout({ "src/a.cpp": BIG }); fs.appendFileSync(path.join(dir, "src/a.cpp"), "// mine\n"); - const r = await runHook(readOf(dir, "src/a.cpp"), { tmp: seed(dir) }); + const r = await runHook(readOf(dir, "src/a.cpp"), { tmp: seed(dir, { existingSessions: ["e2e"] }) }); assert.equal(r.deny, null); assert.match(r.log, /\tpass\tRead\t\d+\t\tmodified\t/); }); @@ -166,7 +260,7 @@ test("a tree-wide grep for matching lines runs: it costs less than its redirect" cwd: dir, session_id: "e2e", }, - { tmp: seed(dir) }, + { tmp: seed(dir, { existingSessions: ["e2e"] }) }, ); assert.equal(r.deny, null); assert.match(r.log, /\tpass\tGrep\t\d+\t\ttree_content_grep\t/); @@ -182,7 +276,7 @@ test("a tree-wide grep that lists files (Claude Code's default) passes", async ( cwd: dir, session_id: `e2e-${output_mode}`, }, - { tmp: seed(dir) }, + { tmp: seed(dir, { existingSessions: [`e2e-${output_mode}`] }) }, ); assert.equal(r.deny, null, String(output_mode)); assert.match(r.log, /\tpass\tGrep\t\d+\t\tfile_list_grep\t/); @@ -196,7 +290,7 @@ test("a one-file grep asking for line numbers or context runs as content", async const tool_input = { pattern: "busy_timeout|max_data_size", path: file, ...flags }; const r = await runHook( { tool_name: "Grep", tool_input, cwd: dir, session_id: `lines-${Object.keys(flags)[0]}` }, - { tmp: seed(dir) }, + { tmp: seed(dir, { existingSessions: [`lines-${Object.keys(flags)[0]}`] }) }, ); assert.equal(r.deny, null); assert.deepEqual(r.updatedInput, { ...tool_input, output_mode: "content" }); @@ -207,7 +301,10 @@ test("a one-file grep asking for line numbers or context runs as content", async { pattern: "busy_timeout", path: file, "-n": true, output_mode: "count" }, { pattern: "busy_timeout", path: path.join(dir, "src"), "-n": true }, ]) { - const r = await runHook({ tool_name: "Grep", tool_input, cwd: dir, session_id: "lines-no" }, { tmp: seed(dir) }); + const r = await runHook( + { tool_name: "Grep", tool_input, cwd: dir, session_id: "lines-no" }, + { tmp: seed(dir, { existingSessions: ["lines-no"] }) }, + ); assert.equal(r.updatedInput, null, JSON.stringify(tool_input)); } }); @@ -234,7 +331,7 @@ test("a symbol grep is answered by the index; a named file you modified gets its cwd: dir, session_id: "e2e", }; - const r = await withServer(answers, (url) => runHook(cmd, { tmp: seed(dir), url })); + const r = await withServer(answers, (url) => runHook(cmd, { tmp: seed(dir, { existingSessions: ["e2e"] }), url })); assert.match( r.deny, /Index answer: DB::MergeTreeData::renameTempPartAndAdd is defined at src\/a\.cpp:7327-7344 \(code-x @ 012345678, scip tier\)\./, @@ -248,7 +345,7 @@ test("a symbol grep is answered by the index; a named file you modified gets its test("a chained Bash read is judged segment by segment; the first deny wins", async () => { const { dir } = checkout({ "src/a.cpp": BIG, "src/small.cpp": "int x;\n" }); - const tmp = seed(dir); + const tmp = seed(dir, { existingSessions: ["e2e"] }); const bash = (command) => ({ tool_name: "Bash", tool_input: { command }, cwd: dir, session_id: "e2e" }); // As a Git Bash command names it on Windows: forward slashes. const cdDir = dir.replace(/\\/g, "/"); @@ -258,7 +355,9 @@ test("a chained Bash read is judged segment by segment; the first deny wins", as assert.equal(lines.length, 2, "the small read passed and was counted, the big one denied"); assert.match(lines[0], /\tpass\tBash:cat\t.*\tsrc\/small\.cpp\t/); assert.match(lines[1], /\thit\tBash:cat\t/); - const p = await runHook(bash("cd src && sed -n '1,40p' a.cpp; echo ---"), { tmp: seed(dir) }); + const p = await runHook(bash("cd src && sed -n '1,40p' a.cpp; echo ---"), { + tmp: seed(dir, { existingSessions: ["e2e"] }), + }); assert.equal(p.deny, null, "a ranged read passes (no read cap set)"); assert.match(p.log, /\tpass\tBash:sed\t.*targeted_span\tsrc\/a\.cpp\t1\t40/); }); @@ -266,7 +365,10 @@ test("a chained Bash read is judged segment by segment; the first deny wins", as // The hook's pending batch for the seeded repository (o/code-x), the server at // `url`, runHook's token and a session. const pendingPath = (tmp, url, session = "e2e", namespace = "code-x") => - sessionStatePath(batchKind({ serverUrl: url, token: "t", org: "o", namespace }), session, { ext: ".log", tmp }); + sessionStatePath(batchKind({ serverUrl: url, token: "t", org: "o", namespace }), session, { + ext: ".log.control", + tmp, + }); const reporting = { LOOM_SHUNT_REPORT: "on", LOOM_SHUNT_READ_CAP: "200" }; const rangedRead = (dir) => ({ ...readOf(dir, "src/a.cpp"), @@ -280,7 +382,7 @@ const posix = process.platform !== "win32"; test("a deny claims the pending batch, posts it as code.outcome and removes it", async () => { const { dir } = checkout({ "src/a.cpp": BIG }); - const tmp = seed(dir); + const tmp = seed(dir, { existingSessions: ["e2e"] }); await withServer({}, async (url, seen) => { const r = await runHook(readOf(dir, "src/a.cpp"), { tmp, url, env: reporting }); assert.ok(r.deny); @@ -290,7 +392,7 @@ test("a deny claims the pending batch, posts it as code.outcome and removes it", assert.equal(fs.existsSync(pendingPath(tmp, url)), false); }); assert.deepEqual( - fs.readdirSync(tmp).filter((n) => n.startsWith("loom-shunt-claim-")), + fs.readdirSync(tmp).filter((n) => n.startsWith("loom-shunt-protected-claim-")), [], "the claimed batch is removed", ); @@ -299,7 +401,7 @@ test("a deny claims the pending batch, posts it as code.outcome and removes it", test("the read cap denies a file twice per session, then passes it as cap_spent", async () => { const { dir } = checkout({ "src/a.cpp": BIG }); - const tmp = seed(dir); + const tmp = seed(dir, { existingSessions: ["e2e"] }); const env = { LOOM_SHUNT_READ_CAP: "200" }; for (let i = 0; i < 2; i++) assert.ok((await runHook(rangedRead(dir), { tmp, env })).deny, `denial ${i + 1}`); const third = await runHook(rangedRead(dir), { tmp, env }); @@ -311,7 +413,7 @@ test("symlinks planted at the shunt's tmp files are not followed and cannot lock skip: !posix, }, async () => { const { dir } = checkout({ "src/a.cpp": BIG }); - const tmp = seed(dir); + const tmp = seed(dir, { existingSessions: ["e2e"] }); const planted = {}; const victims = {}; await withServer({}, async (url, seen) => { @@ -341,7 +443,7 @@ test("symlinks planted at the shunt's tmp files are not followed and cannot lock test("a hard link planted at the pending batch is neither posted nor truncated", { skip: !posix }, async () => { const { dir } = checkout({ "src/a.cpp": BIG }); - const tmp = seed(dir); + const tmp = seed(dir, { existingSessions: ["e2e"] }); const victim = path.join(tmp, "victim-log"); fs.writeFileSync(victim, plantedBatch); await withServer({}, async (url, seen) => { @@ -357,7 +459,7 @@ test("a flush also posts the batch another session left behind", async () => { const { dir } = checkout({ "src/a.cpp": BIG }); fs.appendFileSync(path.join(dir, "src/a.cpp"), "// mine\n"); const { dir: other } = checkout({ "src/a.cpp": BIG }); - const tmp = seed(dir); + const tmp = seed(dir, { existingSessions: ["A", "B"] }); fs.writeFileSync(cachePathFor(other, tmp), fs.readFileSync(cachePathFor(dir, tmp))); await withServer({}, async (url, seen) => { const a = await runHook({ ...readOf(dir, "src/a.cpp"), session_id: "A" }, { tmp, url, env: reporting }); @@ -380,7 +482,7 @@ test("a flush also posts the batch another session left behind", async () => { test("a flush leaves another reporting scope's batch alone", async () => { const { dir } = checkout({ "src/a.cpp": BIG }); - const tmp = seed(dir); + const tmp = seed(dir, { existingSessions: ["e2e"] }); await withServer({}, async (url, seen) => { // Another repository's batch, and one this repository's lines would go to under another server. const others = [pendingPath(tmp, url, "X", "code-other"), pendingPath(tmp, "http://127.0.0.1:9", "Y")]; @@ -402,7 +504,7 @@ const plantCap = (tmp, session = "e2e") => { test("a symbol grep whose budget cannot be written passes as budget_unrecorded", { skip: !posix }, async () => { const { dir } = checkout({ "src/a.h": "bool renameTempPartAndAdd(\n", "src/a.cpp": "// def\n" }); - const tmp = seed(dir); + const tmp = seed(dir, { existingSessions: ["e2e"] }); const victim = plantCap(tmp); const cmd = { tool_name: "Bash", @@ -420,7 +522,7 @@ test("an answered tracker search whose budget cannot be written passes as budget skip: !posix, }, async () => { const { dir } = checkout({ "src/a.cpp": "// x\n" }); - const tmp = seed(dir); + const tmp = seed(dir, { existingSessions: ["e2e"] }); const victim = plantCap(tmp); const cmd = { tool_name: "Bash", @@ -444,20 +546,243 @@ test("an answered tracker search whose budget cannot be written passes as budget test("an over-cap read whose budget cannot be written passes as budget_unrecorded", { skip: !posix }, async () => { const { dir } = checkout({ "src/a.cpp": BIG }); - const tmp = seed(dir); + const tmp = seed(dir, { existingSessions: ["e2e"] }); plantCap(tmp); const r = await runHook(rangedRead(dir), { tmp, env: { LOOM_SHUNT_READ_CAP: "200" } }); assert.equal(r.deny, null); assert.match(r.log, /\tpass\tRead\t\d+\t\tbudget_unrecorded\t/); }); +test("a producer protected after queuing keeps its bytes while an unrelated clean hit posts", async () => { + const { dir } = checkout({ "src/a.cpp": BIG }); + fs.appendFileSync(path.join(dir, "src/a.cpp"), "// private producer change\n"); + const { dir: other } = checkout({ "src/b.cpp": BIG }); + const tmp = seed(dir, { existingSessions: ["A", "B"] }); + const rootA = establishFixtureSession(tmp, "A"); + const rootB = establishFixtureSession(tmp, "B"); + fs.writeFileSync(cachePathFor(other, tmp), fs.readFileSync(cachePathFor(dir, tmp))); + try { + await withServer({}, async (url, seen) => { + const a = await runHook({ ...readOf(dir, "src/a.cpp"), session_id: "A" }, { tmp, url, env: reporting }); + assert.equal(a.deny, null); + const queuedA = pendingPath(tmp, url, "A"); + const before = fs.readFileSync(queuedA); + assert.ok(before.length > 0); + assert.equal(outcomes(seen).length, 0); + protectSession(rootA); + assert.equal(sessionIsProtected(rootA), true); + assert.equal(sessionIsProtected(rootB), false); + const b = await runHook({ ...readOf(other, "src/b.cpp"), session_id: "B" }, { tmp, url, env: reporting }); + assert.ok(b.deny); + await settle(); + assert.equal(outcomes(seen).length, 1, "the clean producer's own hit is sent"); + assert.equal(outcomes(seen)[0].body.action, "shunt_hit"); + assert.ok(outcomes(seen)[0].body.spans.some((span) => span.startsWith("src/b.cpp:"))); + assert.equal(JSON.stringify(outcomes(seen)).includes("src/a.cpp"), false); + assert.equal( + outcomes(seen).some((entry) => entry.body.source === "modified"), + false, + ); + assert.deepEqual(fs.readFileSync(queuedA), before, "protected evidence is neither claimed nor changed"); + assert.equal(fs.existsSync(pendingPath(tmp, url, "B")), false); + assert.equal(sessionIsProtected(rootB), false); + }); + } finally { + for (const owned of [tmp, dir, other]) fs.rmSync(owned, { recursive: true, force: true }); + } +}); + +test("a marked aggregate response protects every producer and retains both unacknowledged claims", async () => { + const { dir } = checkout({ "src/a.cpp": BIG }); + fs.appendFileSync(path.join(dir, "src/a.cpp"), "// producer change\n"); + const { dir: other } = checkout({ "src/b.cpp": BIG }); + const tmp = seed(dir, { existingSessions: ["A", "B"] }); + const rootA = establishFixtureSession(tmp, "A"); + const rootB = establishFixtureSession(tmp, "B"); + fs.writeFileSync(cachePathFor(other, tmp), fs.readFileSync(cachePathFor(dir, tmp))); + try { + await withServer({ "/v1/code.outcome": { mirrored: true } }, async (url, seen, observation) => { + let queuedA; + try { + const a = await runHook( + { ...readOf(dir, "src/a.cpp"), session_id: "A" }, + { tmp, url, env: reporting, observation }, + ); + assert.equal(a.deny, null); + queuedA = pendingPath(tmp, url, "A"); + const beforeA = fs.readFileSync(queuedA, "utf8"); + assert.equal(outcomes(seen).length, 0); + assert.equal(sessionIsProtected(rootA), false); + assert.equal(sessionIsProtected(rootB), false); + const b = await runHook( + { ...readOf(other, "src/b.cpp"), session_id: "B" }, + { tmp, url, env: reporting, observation }, + ); + assert.ok(b.deny); + await settle(); + assert.equal(outcomes(seen).length, 1, "the first marked answer suppresses the aggregate's second body"); + assert.equal(outcomes(seen)[0].body.action, "shunt_hit"); + assert.equal(sessionIsProtected(rootA), true); + assert.equal(sessionIsProtected(rootB), true); + assert.equal(fs.existsSync(queuedA), false); + assert.equal(fs.existsSync(pendingPath(tmp, url, "B")), false); + const claims = fs.readdirSync(tmp).filter((name) => name.startsWith("loom-shunt-protected-claim-")); + assert.equal(claims.length, 2, "claiming moves evidence; a marked answer does not acknowledge it"); + const retained = claims.map((name) => fs.readFileSync(path.join(tmp, name), "utf8")); + assert.ok(retained.includes(beforeA), "producer A's exact queued bytes remain in its claim"); + const rows = retained.flatMap((text) => + text + .trimEnd() + .split("\n") + .map((line) => JSON.parse(line)), + ); + assert.equal(rows.length, 2); + const rowA = rows.find((row) => + row.protectionRoots.some((root) => root.base === rootA.base && root.id === rootA.id), + ); + const rowB = rows.find((row) => + row.protectionRoots.some((root) => root.base === rootB.base && root.id === rootB.id), + ); + assert.ok(rowA && rowB, "both actual producer roots stay attached to their evidence"); + assert.match(rowA.line, /\tpass\tRead\t.*\tmodified\tsrc\/a\.cpp\t/); + assert.match(rowB.line, /\thit\tRead\t.*\tsrc\/b\.cpp\t/); + const scopePrefix = `loom-${batchKind({ serverUrl: url, token: "t", org: "o", namespace: "code-x" })}-`; + assert.deepEqual( + fs.readdirSync(tmp).filter((name) => name.startsWith(scopePrefix) && name.endsWith(".log.control")), + [], + ); + } catch (error) { + try { + const aTracked = queuedA !== undefined; + const aExists = aTracked ? fs.existsSync(queuedA) : null; + const names = fs.readdirSync(tmp); + recordFixtureEvent(observation, "marked-queue-snapshot", { + aPendingTracked: aTracked, + aPendingExists: aExists, + aPendingBytes: aTracked ? (aExists ? fs.statSync(queuedA).size : 0) : null, + ownedClaimCount: names.filter((name) => name.startsWith("loom-shunt-protected-claim-")).length, + ownedClaimPayloadCount: names.filter( + (name) => name.startsWith("loom-shunt-protected-claim-") && name.endsWith(".log.control"), + ).length, + }); + } catch { + recordFixtureEvent(observation, "snapshot-unavailable"); + } + throw observedFailure(error, observation); + } + }); + } finally { + for (const owned of [tmp, dir, other]) fs.rmSync(owned, { recursive: true, force: true }); + } +}); + +test("an unattributed batch in the same protected scope stays untouched while a clean hit posts", async () => { + const { dir } = checkout({ "src/b.cpp": BIG }); + const tmp = seed(dir, { existingSessions: ["B"] }); + try { + await withServer({}, async (url, seen, observation) => { + try { + const unattributed = pendingPath(tmp, url, "unknown-producer"); + fs.writeFileSync(unattributed, plantedBatch, { mode: 0o600 }); + const before = fs.readFileSync(unattributed); + const b = await runHook( + { ...readOf(dir, "src/b.cpp"), session_id: "B" }, + { tmp, url, env: reporting, observation }, + ); + assert.ok(b.deny); + await settle(); + assert.equal(outcomes(seen).length, 1); + assert.equal(outcomes(seen)[0].body.action, "shunt_hit"); + assert.ok(outcomes(seen)[0].body.spans.some((span) => span.startsWith("src/b.cpp:"))); + assert.equal(carriesPlanted(seen), false); + assert.deepEqual(fs.readFileSync(unattributed), before, "a matching filename cannot supply producer authority"); + assert.equal(fs.existsSync(pendingPath(tmp, url, "B")), false); + assert.deepEqual( + fs.readdirSync(tmp).filter((name) => name.startsWith("loom-shunt-protected-claim-")), + [], + ); + } catch (error) { + try { + const pending = pendingPath(tmp, url, "B"); + const pendingExists = fs.existsSync(pending); + recordFixtureEvent(observation, "queue-snapshot", { + bPendingExists: pendingExists, + bPendingBytes: pendingExists ? fs.statSync(pending).size : 0, + ownedClaimCount: fs.readdirSync(tmp).filter((name) => name.startsWith("loom-shunt-protected-claim-")) + .length, + unattributedFileExists: fs.existsSync(pendingPath(tmp, url, "unknown-producer")), + claimControl: observedRetainedClaims(tmp), + }); + } catch { + recordFixtureEvent(observation, "snapshot-unavailable"); + } + throw observedFailure(error, observation); + } + }); + } finally { + for (const owned of [tmp, dir]) fs.rmSync(owned, { recursive: true, force: true }); + } +}); + +for (const mode of ["mirrored", "late-sibling-mark"]) { + test(`a symbol reply ${mode} withholds the actual shunt denial and decision log`, async () => { + const { dir } = checkout({ "src/a.cpp": "bool renameTempPartAndAdd();\n" }); + const tmp = seed(dir, { existingSessions: ["e2e"] }); + const root = establishFixtureSession(tmp, "e2e"); + try { + const answers = { + "/v1/code.symbol": () => { + // The real hook has dispatched and is awaiting this response. + if (mode === "late-sibling-mark") protectSession(root); + return { + mirrored: mode === "mirrored", + definitions: [ + { + path: "src/a.cpp", + start_line: 1, + end_line: 1, + symbol: "DB::MergeTreeData::renameTempPartAndAdd", + tier: "scip", + }, + ], + }; + }, + }; + await withServer(answers, async (url, seen) => { + const answer = await runHook( + { + tool_name: "Bash", + tool_input: { command: "grep -n renameTempPartAndAdd src/a.cpp" }, + cwd: dir, + session_id: "e2e", + }, + { tmp, url }, + ); + assert.equal(answer.code, 0); + assert.deepEqual( + seen.map((request) => request.url), + ["/v1/code.symbol"], + ); + assert.equal(answer.stdout, ""); + assert.equal(answer.deny, null); + assert.equal(answer.updatedInput, null); + assert.equal(answer.log, ""); + assert.equal(sessionIsProtected(root), true); + }); + } finally { + fs.rmSync(tmp, { recursive: true, force: true }); + fs.rmSync(dir, { recursive: true, force: true }); + } + }); +} + for (const status of ["modified", "untracked"]) { for (const tool of ["Grep", "Bash"]) { test(`${status} ${tool} single-file grep stays local without indexed requests`, async (t) => { const { dir } = checkout({ "src/parser.py": "field_value = 1\n" }); const rel = status === "untracked" ? "src/local_parser.py" : "src/parser.py"; fs.writeFileSync(path.join(dir, rel), "field_value = 2\n"); - const tmp = seed(dir); + const tmp = seed(dir, { existingSessions: ["local-query"] }); t.after(() => { fs.rmSync(dir, { recursive: true, force: true }); fs.rmSync(tmp, { recursive: true, force: true }); diff --git a/integrations/claude-code-plugin/tests/e2e/agent-session.mjs b/integrations/claude-code-plugin/tests/e2e/agent-session.mjs index d4ef57b318..ad7ab58115 100644 --- a/integrations/claude-code-plugin/tests/e2e/agent-session.mjs +++ b/integrations/claude-code-plugin/tests/e2e/agent-session.mjs @@ -26,6 +26,9 @@ // nothing on stderr; with --no-node, when every hook failed on the missing // node, none with exit 2, and the turn's command ran. Otherwise exit 1 // naming what is missing. +// With node available, a second session receives a marked startup pack. The +// ordinary pack must reach model input; the marked pack must not reach model +// input, CLI output or automatic Loom writes. This does not inspect host storage. import { execFileSync, spawn } from "node:child_process"; import fs from "node:fs"; import http from "node:http"; @@ -36,6 +39,12 @@ import { fileURLToPath } from "node:url"; const repoRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..", "..", "..", ".."); const TOKEN = "loom-e2e-token"; const MODEL_KEY = "e2e-model-key"; +const STARTUP_MARKER = "LOOM_E2E_STARTUP_PUBLICATION_7ca8d9e4"; + +function reportFailure(value) { + const text = value instanceof Error ? value.stack || value.message : String(value); + console.error(text.replaceAll(STARTUP_MARKER, "[startup marker]")); +} function parseArgs(argv) { const out = { agent: argv[0], bin: "", port: 7777, nodeOffPath: false, noNode: false, expectTool: "" }; @@ -133,10 +142,12 @@ function responsesTurn(body, res) { } /** The fake: the model API under /v1/messages and /v1/responses, Loom for - * everything else (any op answers an empty success, MCP answers 401). - * `seen` records each request's path and Authorization header. */ -async function startFake(port) { + * everything else (a startup marker, otherwise empty success; MCP answers 401). + * `seen` retains request bodies and their order around the startup response. */ +async function startFake(port, { marked }) { const seen = []; + let order = 0; + let startupResponseOrder = 0; const handler = (req, res) => { let raw = ""; req.on("data", (d) => (raw += d)); @@ -148,7 +159,15 @@ async function startFake(port) { /* a non-JSON body is recorded like any other */ } const url = req.url || ""; - seen.push({ path: url.split("?")[0], auth: req.headers.authorization || "", mode: body.mode, repos: body.repos }); + const request = { + path: url.split("?")[0], + auth: req.headers.authorization || "", + mode: body.mode, + repos: body.repos, + body, + order: ++order, + }; + seen.push(request); if (url.startsWith("/v1/messages/count_tokens")) { res.writeHead(200, { "content-type": "application/json" }); res.end('{"input_tokens":1}'); @@ -160,7 +179,13 @@ async function startFake(port) { res.end("{}"); } else { res.writeHead(200, { "content-type": "application/json" }); - res.end(JSON.stringify({ rendered: "", results: [], repos: [] })); + const startup = request.path === "/v1/context.pack" && body.mode === "startup"; + const reply = { rendered: startup ? STARTUP_MARKER : "", results: [], repos: [] }; + if (startup) { + if (marked) reply.mirrored = true; + startupResponseOrder = ++order; + } + res.end(JSON.stringify(reply)); } }); }; @@ -180,7 +205,7 @@ async function startFake(port) { } } const close = () => Promise.all(servers.map((s) => new Promise((r) => s.close(r)))); - return { seen, close }; + return { seen, close, startupResponseOrder: () => startupResponseOrder }; } function run(cmd, args, { env, cwd, timeoutMs = 180000, input = "" }) { @@ -299,7 +324,7 @@ function baseEnv(home) { return env; } -async function claudeSession(opts, box, url) { +async function claudeSession(opts, box, url, { marked }) { const env = baseEnv(box.home); env.ANTHROPIC_API_KEY = MODEL_KEY; env.ANTHROPIC_BASE_URL = url; @@ -369,7 +394,7 @@ async function claudeSession(opts, box, url) { return { problems, transcript: r.stdout + r.stderr }; } // A hook's stdout reaches the agent: the primer is SessionStart's. - if (!hooks.some((h) => h.hook_event === "SessionStart" && String(h.output || "").includes("# Loom"))) { + if (!marked && !hooks.some((h) => h.hook_event === "SessionStart" && String(h.output || "").includes("# Loom"))) { problems.push("SessionStart's primer never reached Claude Code"); } for (const h of hooks) { @@ -452,18 +477,61 @@ function expectedCalls(agent) { }; } -async function main() { - const opts = parseArgs(process.argv.slice(2)); - const fake = await startFake(opts.port); +function startupPublicationProblems(fake, result, { marked }) { + const problems = []; + const responseOrder = fake.startupResponseOrder(); + const modelRequests = fake.seen.filter((s) => ["/v1/messages", "/v1/responses"].includes(s.path)); + const modelInput = (s) => + JSON.stringify( + s.path === "/v1/messages" + ? { system: s.body.system, messages: s.body.messages } + : { instructions: s.body.instructions, input: s.body.input }, + ); + if (!responseOrder) problems.push("no startup marker response was served"); + if (!modelRequests.length || modelRequests[0].order <= responseOrder) + problems.push("no model request followed the startup marker response"); + if (!marked) { + if (!modelRequests.some((s) => modelInput(s).includes(STARTUP_MARKER))) + problems.push("the ordinary startup marker never reached native model input"); + return problems; + } + if (modelRequests.some((s) => modelInput(s).includes(STARTUP_MARKER))) + problems.push("the marked startup marker reached native model input"); + if ((result.transcript || "").includes(STARTUP_MARKER)) + problems.push("the marked startup marker reached a native CLI output stream"); + const loomRequests = fake.seen.filter( + (s) => s.path.startsWith("/v1/") && !s.path.startsWith("/v1/messages") && s.path !== "/v1/responses", + ); + if (loomRequests.some((s) => JSON.stringify(s.body).includes(STARTUP_MARKER))) + problems.push("the marked startup marker reached an automatic Loom request body"); + // These writes are each required by the ordinary event witnesses below. + const eventWrites = new Set([ + "/v1/run.begin", + "/v1/observe.record", + "/v1/cost.record_turns", + "/v1/conversation.append", + ]); + for (const request of loomRequests) { + if (request.order > responseOrder && eventWrites.has(request.path)) + problems.push(`an automatic event write followed the marked startup response: ${request.path}`); + // Startup reads may already be in flight when the marked response is sent. + if (modelRequests.length && request.order > modelRequests[0].order) + problems.push(`an automatic Loom request followed model startup: ${request.path}`); + } + return problems; +} + +async function sessionScenario(opts, scenario) { + const fake = await startFake(opts.port, scenario); const url = `http://localhost:${opts.port}`; const box = scratch(); const EXPECTED_CALLS = expectedCalls(opts.agent); let result; try { - result = await (opts.agent === "claude" ? claudeSession : codexSession)(opts, box, url); + result = await (opts.agent === "claude" ? claudeSession : codexSession)(opts, box, url, scenario); // Stop hands its posts to a detached flusher: give it time to land. const deadline = opts.noNode ? 0 : Date.now() + 20000; - while (Date.now() < deadline && !fake.seen.some(EXPECTED_CALLS.Stop)) { + while (Date.now() < deadline && (scenario.marked || !fake.seen.some(EXPECTED_CALLS.Stop))) { await new Promise((r) => setTimeout(r, 250)); } const used = path.join(box.home, "nvm-node-used"); @@ -472,7 +540,7 @@ async function main() { result.problems.push("no hook ran the version manager's node"); } const lookedUp = (s) => s.path === "/v1/code.repos" && JSON.stringify(s.repos || []).includes("example/e2e"); - if (box.checkout && !opts.noNode && !fake.seen.some(lookedUp)) { + if (!scenario.marked && box.checkout && !opts.noNode && !fake.seen.some(lookedUp)) { result.problems.push("no hook looked the checkout's repository up"); } } finally { @@ -485,29 +553,36 @@ async function main() { } } const { problems } = result; + if (!opts.noNode) problems.push(...startupPublicationProblems(fake, result, scenario)); const bearer = `Bearer ${TOKEN}`; if (!opts.noNode && !fake.seen.some((s) => s.path === "/mcp" && s.auth === bearer)) { problems.push("the MCP header helper never sent the token"); } for (const [event, call] of Object.entries(EXPECTED_CALLS)) { - if (!opts.noNode && !fake.seen.some((s) => call(s) && s.auth === bearer)) + if (!scenario.marked && !opts.noNode && !fake.seen.some((s) => call(s) && s.auth === bearer)) problems.push(`${event}: its Loom call never came with the token`); } const mode = opts.nodeOffPath ? " (node off PATH)" : opts.noNode ? " (no node)" : ""; - const label = `${opts.agent} on ${process.platform}-${process.arch}${mode}`; + const label = `${opts.agent} on ${process.platform}-${process.arch}${mode}${scenario.marked ? " (marked startup)" : ""}`; if (problems.length) { - console.error(`FAIL ${label}`); - for (const p of problems) console.error(` - ${p}`); + reportFailure(`FAIL ${label}`); + for (const p of problems) reportFailure(` - ${p}`); const shown = fake.seen.map((s) => `${s.path}${s.mode ? `(${s.mode})` : ""}${s.auth ? " +auth" : ""}`); - console.error("Loom requests:", shown.join(", ")); - console.error(result.transcript || ""); + reportFailure(`Loom requests: ${shown.join(", ")}`); + reportFailure(result.transcript || ""); process.exitCode = 1; } else { console.log(`PASS ${label}: ${fake.seen.length} requests`); } } +async function main() { + const opts = parseArgs(process.argv.slice(2)); + await sessionScenario(opts, { marked: false }); + if (!opts.noNode) await sessionScenario(opts, { marked: true }); +} + main().catch((e) => { - console.error(e); + reportFailure(e); process.exitCode = 1; }); diff --git a/integrations/claude-code-plugin/tests/established-session.mjs b/integrations/claude-code-plugin/tests/established-session.mjs new file mode 100644 index 0000000000..ca9537a053 --- /dev/null +++ b/integrations/claude-code-plugin/tests/established-session.mjs @@ -0,0 +1,13 @@ +// Explicit fixture input for a host identity established before hook delivery. +import fs from "node:fs"; +import path from "node:path"; +import { bindProtectionAlias, createProtectionRoot, findProtectionAlias } from "../lib/session-protection.mjs"; + +export function establishFixtureSession(home, sessionId, host = "claude-code") { + const base = path.join(home, ".loom", "session-protection", "v1"); + const existing = fs.existsSync(base) ? findProtectionAlias(host, sessionId, { base }) : undefined; + if (existing) return existing; + const root = createProtectionRoot({ base }); + bindProtectionAlias(root, host, sessionId); + return root; +} diff --git a/integrations/claude-code-plugin/tests/file-rules-team.test.mjs b/integrations/claude-code-plugin/tests/file-rules-team.test.mjs index 6e28861237..de7c1e1dbf 100644 --- a/integrations/claude-code-plugin/tests/file-rules-team.test.mjs +++ b/integrations/claude-code-plugin/tests/file-rules-team.test.mjs @@ -1,6 +1,7 @@ // The file-context hook reads the repository's primary code // namespace (team file rules) beside the person's own, in one request. import "./temp-home.mjs"; +import { establishFixtureSession } from "./established-session.mjs"; import { test } from "node:test"; import assert from "node:assert/strict"; import { execFileSync, spawn } from "node:child_process"; @@ -138,6 +139,7 @@ async function runFileContextHook(rendered) { const hook = fileURLToPath(new URL("../hooks/loom-file-context.mjs", import.meta.url)); const dir = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "loom-fc-hook-"))); const tmp = fs.realpathSync(fs.mkdtempSync(path.join(os.tmpdir(), "loom-fc-tmp-"))); + establishFixtureSession(tmp, "s"); fs.mkdirSync(path.join(dir, "src")); fs.writeFileSync(path.join(dir, "src/a.cpp"), "int x;\n"); const g = (...a) => execFileSync("git", ["-c", "user.email=t@t", "-c", "user.name=t", ...a], { cwd: dir }); @@ -161,7 +163,7 @@ async function runFileContextHook(rendered) { await new Promise((r) => srv.listen(0, "127.0.0.1", r)); try { const out = await new Promise((resolve) => { - const child = spawn(process.execPath, [hook], { + const child = spawn(process.execPath, [hook, "PreToolUse"], { cwd: dir, env: hostEnv({ PATH: process.env.PATH, diff --git a/integrations/claude-code-plugin/tests/flush-hook.test.mjs b/integrations/claude-code-plugin/tests/flush-hook.test.mjs index df0c753b4a..e536b0c07e 100644 --- a/integrations/claude-code-plugin/tests/flush-hook.test.mjs +++ b/integrations/claude-code-plugin/tests/flush-hook.test.mjs @@ -1,6 +1,7 @@ // The detached flusher keeps its cursor in a shared tmp dir: a symlink planted // at the cursor path is refused, and the file it points to stays as it was. import "./temp-home.mjs"; +import { establishFixtureSession } from "./established-session.mjs"; import { test } from "node:test"; import assert from "node:assert/strict"; import { spawn } from "node:child_process"; @@ -43,11 +44,17 @@ const posix = process.platform !== "win32"; test("the flusher advances a cursor it owns and never follows a symlink at the cursor path", { skip: !posix, }, async () => { - const { srv, url } = await server(); const dir = fs.mkdtempSync(path.join(os.tmpdir(), "loom-flushhook-")); + const root = establishFixtureSession(dir, "append-producer"); + const { srv, url } = await server(); try { const own = path.join(dir, "loom-conv-a.offset"); - const jobPath = await flush(dir, url, { appends: [append], cursorPath: own, advanceTo: 42 }); + const jobPath = await flush(dir, url, { + protectionRoots: [root], + appends: [append], + cursorPath: own, + advanceTo: 42, + }); assert.equal(fs.readFileSync(own, "utf8"), "42"); assert.equal(fs.existsSync(jobPath), false); @@ -55,7 +62,12 @@ test("the flusher advances a cursor it owns and never follows a symlink at the c fs.writeFileSync(victim, "keep"); const planted = path.join(dir, "loom-conv-b.offset"); fs.symlinkSync(victim, planted); - const plantedJob = await flush(dir, url, { appends: [append], cursorPath: planted, advanceTo: 42 }); + const plantedJob = await flush(dir, url, { + protectionRoots: [root], + appends: [append], + cursorPath: planted, + advanceTo: 42, + }); assert.equal(fs.readFileSync(victim, "utf8"), "keep"); assert.equal(fs.existsSync(plantedJob), false); assert.ok(fs.lstatSync(planted).isSymbolicLink()); @@ -66,9 +78,11 @@ test("the flusher advances a cursor it owns and never follows a symlink at the c }); test("a failed post rolls back a cursor it owns and never a symlink at the cursor path", { skip: !posix }, async () => { - const { srv, url } = await server(500); const dir = fs.mkdtempSync(path.join(os.tmpdir(), "loom-flushhook-")); + const root = establishFixtureSession(dir, "post-producer"); + const { srv, url } = await server(500); const job = (cursorPath) => ({ + protectionRoots: [root], posts: [{ op: "memory.set", body: { k: 1 } }], cursorPath, advanceTo: 42, diff --git a/integrations/claude-code-plugin/tests/flush-job-protection.test.mjs b/integrations/claude-code-plugin/tests/flush-job-protection.test.mjs new file mode 100644 index 0000000000..0d778804b9 --- /dev/null +++ b/integrations/claude-code-plugin/tests/flush-job-protection.test.mjs @@ -0,0 +1,257 @@ +import "./temp-home.mjs"; +import assert from "node:assert/strict"; +import { EventEmitter } from "node:events"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { afterEach, test } from "node:test"; + +import { dispatchFlush, runFlushJob } from "../lib/flush-job.mjs"; +import { requestJson } from "../lib/loom-client.mjs"; +import { createProtectionRoot, protectSession, sessionIsProtected } from "../lib/session-protection.mjs"; +import { + sessionProtectionContext, + withAutomaticSessionProtection, + withSessionProtection, +} from "../lib/session-response.mjs"; + +const owned = new Set(); +function fixture() { + const parent = fs.mkdtempSync(path.join(os.tmpdir(), "loom-flush-protection-")); + owned.add(parent); + const directory = process.platform === "win32" ? path.join(parent, "private") : parent; + return { directory, root: createProtectionRoot({ base: directory }) }; +} +afterEach(() => { + for (const directory of owned) fs.rmSync(directory, { recursive: true, force: true }); + owned.clear(); +}); + +function cursor() { + return { + value: "10", + read() { + return this.value; + }, + write(_path, value) { + this.value = String(value); + }, + }; +} + +test("automatic contexts refuse missing protection roots", () => { + let ran = false; + withAutomaticSessionProtection({ base: path.resolve("missing"), id: "00000000-0000-0000-0000-000000000000" }, () => { + ran = true; + }); + assert.equal(ran, false); +}); +{ + test("unknown and protected producers leave no queued content or child", () => { + const { directory, root } = fixture(); + const before = fs.readdirSync(directory); + let spawns = 0; + const options = { + tmp: directory, + spawnImpl() { + spawns++; + throw new Error("must not spawn"); + }, + }; + assert.equal(dispatchFlush({ posts: [{ op: "memory.set_from_messages", body: {} }] }, options), false); + protectSession(root); + assert.equal( + withSessionProtection(root, () => dispatchFlush({ appends: [{}] }, options)), + false, + ); + assert.equal(spawns, 0); + assert.deepEqual(fs.readdirSync(directory), before); + }); + + test("a queued job captures its producer root rather than a supplied replacement", () => { + const { directory, root } = fixture(); + const replacement = createProtectionRoot({ base: directory }); + let job; + const options = { + tmp: directory, + spawnImpl(_command, args) { + job = JSON.parse(fs.readFileSync(args[1], "utf8")); + const child = new EventEmitter(); + child.unref = () => {}; + return child; + }, + }; + assert.equal( + withAutomaticSessionProtection(root, () => + dispatchFlush({ protectionRoots: [replacement], appends: [{}] }, options), + ), + true, + ); + assert.deepEqual(job.protectionRoots, [root]); + protectSession(root); + assert.equal(sessionIsProtected(replacement), false); + }); + + test("late protection discards a detached job despite a different clean caller", async () => { + const { root, directory } = fixture(); + const replacement = createProtectionRoot({ base: directory }); + const job = { protectionRoots: [root], appends: [{}], cursorPath: "/cursor", advanceTo: 99 }; + protectSession(root); + let sends = 0; + const position = cursor(); + const result = await withSessionProtection(replacement, () => + runFlushJob(job, { + post: async () => { + sends++; + return { stored: true }; + }, + cursor: position, + }), + ); + assert.deepEqual(result, { postsOk: false, appendsOk: false }); + assert.equal(sends, 0); + assert.equal(position.value, "10"); + }); + + test("a marked post prevents the append phase and success cursor", async () => { + const { root } = fixture(); + const position = cursor(); + const sends = []; + let notes = 0; + const result = await runFlushJob( + { + protectionRoots: [root], + posts: [{ op: "session.brief_save", body: {} }], + appends: [{}], + cursorPath: "/cursor", + advanceTo: 99, + }, + { + async post(op, body) { + sends.push(op); + assert.equal(sessionProtectionContext().automatic, true); + return ( + await requestJson(`http://server/v1/${op}`, { + body, + fetchImpl: async () => ({ status: 200, json: async () => ({ mirrored: true }) }), + }) + ).body; + }, + cursor: position, + noteRecording() { + notes++; + }, + }, + ); + assert.deepEqual(sends, ["session.brief_save"]); + assert.deepEqual(result, { postsOk: false, appendsOk: false }); + assert.equal(position.value, "10"); + assert.equal(notes, 0); + assert.equal(sessionIsProtected(root), true); + }); + + test("each dispatch rechecks protection even within the same parallel phase", async () => { + const { root } = fixture(); + let sends = 0; + const result = await runFlushJob( + { + protectionRoots: [root], + posts: [ + { op: "session.brief_save", body: {} }, + { op: "memory.set_from_messages", body: {} }, + ], + }, + { + async post() { + sends++; + protectSession(root); + return { stored: true }; + }, + cursor: cursor(), + }, + ); + assert.equal(sends, 1); + assert.deepEqual(result, { postsOk: false, appendsOk: false }); + }); + + test("a damaged queued root refuses delivery and a protected final reply never advances", async () => { + const { root, directory } = fixture(); + const position = cursor(); + let sends = 0; + const job = { protectionRoots: [root], appends: [{}], cursorPath: "/cursor", advanceTo: 99 }; + const io = { + async post() { + sends++; + protectSession(root); + return { stored: true }; + }, + cursor: position, + }; + assert.equal((await runFlushJob(job, io)).appendsOk, false); + assert.equal(sends, 1); + assert.equal(position.value, "10"); + fs.unlinkSync(path.join(directory, root.id, "state")); + await runFlushJob(job, io); + await runFlushJob({ appends: [{}] }, io); + assert.equal(sends, 1); + }); + + test("queued root identity cannot switch across an awaited post", async () => { + const { root, directory } = fixture(); + const replacement = createProtectionRoot({ base: directory }); + const reference = { ...root }; + const position = cursor(); + let sends = 0; + const result = await runFlushJob( + { + protectionRoots: [reference], + posts: [{ op: "session.brief_save", body: {} }], + appends: [{}], + cursorPath: "/cursor", + advanceTo: 99, + }, + { + async post() { + sends++; + protectSession(root); + Object.assign(reference, replacement); + await Promise.resolve(); + return { stored: true }; + }, + cursor: position, + }, + ); + assert.equal(sends, 1); + assert.equal(position.value, "10"); + assert.deepEqual(result, { postsOk: false, appendsOk: false }); + }); + + test("suppressed optimistic jobs roll back rather than acknowledging unsent posts", async () => { + const { root } = fixture(); + protectSession(root); + for (const protectionRoots of [undefined, [root]]) { + const position = cursor(); + position.value = "99"; + let sends = 0; + const result = await runFlushJob( + { + protectionRoots, + posts: [{ op: "session.brief_save", body: {} }], + cursorPath: "/cursor", + advanceTo: 99, + rollbackTo: 10, + }, + { + post: async () => { + sends++; + return { stored: true }; + }, + cursor: position, + }, + ); + assert.deepEqual(result, { postsOk: false, appendsOk: false }); + assert.equal(sends, 0); + assert.equal(position.value, "10"); + } + }); +} diff --git a/integrations/claude-code-plugin/tests/flush-job.test.mjs b/integrations/claude-code-plugin/tests/flush-job.test.mjs index 4a9feb0afc..54db9a09e8 100644 --- a/integrations/claude-code-plugin/tests/flush-job.test.mjs +++ b/integrations/claude-code-plugin/tests/flush-job.test.mjs @@ -1,4 +1,5 @@ import "./temp-home.mjs"; +import { establishFixtureSession } from "./established-session.mjs"; import { test } from "node:test"; import assert from "node:assert/strict"; import { EventEmitter } from "node:events"; @@ -6,6 +7,7 @@ import fs from "node:fs"; import os from "node:os"; import path from "node:path"; import { dispatchFlush, flushJobPath, runFlushJob } from "../lib/flush-job.mjs"; +import { withAutomaticSessionProtection } from "../lib/session-response.mjs"; const tmp = () => fs.mkdtempSync(path.join(os.tmpdir(), "loom-flushjob-")); @@ -20,6 +22,7 @@ test("job files carry the name the client status check counts", () => { test("dispatchFlush writes the job and spawns the flusher detached with the request bound", () => { const dir = tmp(); + const root = establishFixtureSession(os.homedir(), "dispatch"); const calls = []; const spawnImpl = (cmd, args, opts) => { calls.push({ cmd, args, opts }); @@ -27,31 +30,45 @@ test("dispatchFlush writes the job and spawns the flusher detached with the requ child.unref = () => {}; return child; }; - assert.equal(dispatchFlush({ posts: [{ op: "x", body: {} }] }, { timeoutMs: 1234, spawnImpl, tmp: dir }), true); + assert.equal( + withAutomaticSessionProtection(root, () => + dispatchFlush({ posts: [{ op: "x", body: {} }] }, { timeoutMs: 1234, spawnImpl, tmp: dir }), + ), + true, + ); assert.equal(calls.length, 1); assert.match(calls[0].args[0], /hooks[\\/]loom-flush\.mjs$/); assert.equal(calls[0].opts.detached, true); assert.equal(calls[0].opts.windowsHide, true); assert.equal(calls[0].opts.env.LOOM_HOOK_TIMEOUT_MS, "1234"); - const job = JSON.parse(fs.readFileSync(calls[0].args[1], "utf8")); + const { protectionRoots, ...job } = JSON.parse(fs.readFileSync(calls[0].args[1], "utf8")); + assert.deepEqual(protectionRoots, [root]); assert.deepEqual(job, { posts: [{ op: "x", body: {} }] }); }); test("a spawn that throws leaves no job behind; a later spawn error does not crash the hook", () => { const dir = tmp(); + const root = establishFixtureSession(os.homedir(), "spawn-errors"); const throwing = () => { throw new Error("EAGAIN"); }; - assert.equal(dispatchFlush({ posts: [] }, { spawnImpl: throwing, tmp: dir }), false); + assert.equal( + withAutomaticSessionProtection(root, () => dispatchFlush({ posts: [] }, { spawnImpl: throwing, tmp: dir })), + false, + ); assert.deepEqual(fs.readdirSync(dir), []); const child = new EventEmitter(); child.unref = () => {}; - assert.equal(dispatchFlush({ posts: [] }, { spawnImpl: () => child, tmp: dir }), true); + assert.equal( + withAutomaticSessionProtection(root, () => dispatchFlush({ posts: [] }, { spawnImpl: () => child, tmp: dir })), + true, + ); assert.doesNotThrow(() => child.emit("error", new Error("spawn failed"))); }); test("appends advance the cursor only when every one landed", async () => { - const job = { appends: [{ msg_id: "a" }, { msg_id: "b" }], cursorPath: "/c", advanceTo: 99 }; + const root = establishFixtureSession(os.homedir(), "append-job"); + const job = { protectionRoots: [root], appends: [{ msg_id: "a" }, { msg_id: "b" }], cursorPath: "/c", advanceTo: 99 }; const ok = memCursor({ "/c": "10" }); assert.deepEqual(await runFlushJob(job, { post: async () => ({ stored: true }), cursor: ok }), { postsOk: false, @@ -69,8 +86,9 @@ test("appends advance the cursor only when every one landed", async () => { test("the replies reach the recording note", async () => { const seen = []; + const root = establishFixtureSession(os.homedir(), "recording-job"); await runFlushJob( - { appends: [{ org: "o", namespace: "n" }] }, + { protectionRoots: [root], appends: [{ org: "o", namespace: "n" }] }, { post: async () => ({ stored: false, reason: "logging_disabled" }), cursor: memCursor(), @@ -82,6 +100,7 @@ test("the replies reach the recording note", async () => { test("a failed optimistic post rolls its cursor back unless a later job moved it", async () => { const job = { + protectionRoots: [establishFixtureSession(os.homedir(), "optimistic-job")], posts: [{ op: "session.brief_save", body: { a: 1 } }], cursorPath: "/b", advanceTo: 50, @@ -101,7 +120,11 @@ test("a failed optimistic post rolls its cursor back unless a later job moved it test("malformed jobs deliver nothing", async () => { const calls = []; const post = async (op) => (calls.push(op), {}); - await runFlushJob({ posts: [null, { op: 1, body: {} }, { op: "x" }], appends: "no" }, { post, cursor: memCursor() }); + const root = establishFixtureSession(os.homedir(), "malformed-job"); + await runFlushJob( + { protectionRoots: [root], posts: [null, { op: 1, body: {} }, { op: "x" }], appends: "no" }, + { post, cursor: memCursor() }, + ); await runFlushJob(null, { post, cursor: memCursor() }); assert.deepEqual(calls, []); }); diff --git a/integrations/claude-code-plugin/tests/hook-contract.test.mjs b/integrations/claude-code-plugin/tests/hook-contract.test.mjs index 7150c7da1b..cecfee943b 100644 --- a/integrations/claude-code-plugin/tests/hook-contract.test.mjs +++ b/integrations/claude-code-plugin/tests/hook-contract.test.mjs @@ -4,6 +4,7 @@ // output shape its event allows. Each case runs the real script as the host // does (`node