SLOPSHOPPER

cortex-guard

Two rules no settings hook enforces, refused at the tool call: wiki pages and their generated ADR mirrors are written only through the Cortex wiki tool, and…

guardtoastprocess
v0.1.5no licenseupdated 2026-10-23cdeust/claude-mods/mods/cortex-guard
A shopper browsing a rack in a slop shop
README

claude-mods

Claude Code mods and a separate Codex adapter for the ai-architect.tools harness. The Claude mods keep one concern per mod, state shared through dependencies:

ModOwnsDepends on
cortex-guardrefusals: wiki pages only through wiki_write, worktrees inside <repo>/.claude/worktrees/nothing
cortex-wiki/wiki <wiki/**.md> to PDFnothing
zetetic-geniusstate: the request grade (task class → effort), the genius patterns and skills it matchesnothing
zetetic-autopilotcontext, policy, phases: effort ladder, model routing (a subagent's call, then its own definition, then its prompt's DESIGN block, never lowered by pressure), the dispatch table (hooks/dispatch-table.ts): an inheriting subagent nobody designed runs at the model and effort of its task's class, graded by one classifier completion (cls/review on each spawn record the table decided, absent before 0.11.0), an inheriting subagent's effort from the turn's grade when its call names a model but no effort (effort on each spawn record, absent before 0.10.0), the quota's cap on the main loop's parallel subagents, offloaded tool results; the phase each loop is in, on each run the steps a stuck escalation raised (escalated, absent before 0.8.0), and the advisor callszetetic-genius
zetetic-insightsinsights: the turn ledger across sessions ($.store), joined with /insights session outcomes and .zetetic/goals; per-phase effort proposals, `/calibrate apply\reset`, the calibration file the autopilot readszetetic-autopilot, zetetic-genius
mission-controlrenderer; the /mission pane: the turn's lanes by phase (bar height = effort, advisor calls, failed calls), effort per phase, learning curves per phase. Pixels in kitty or Ghostty outside tmux, coloured cells elsewherezetetic-autopilot, zetetic-insights
harness-fleetfleet: the owner's plugins, installed vs offered version, open PRs with CI, open issues (a defect is taken and fixed, a feature request goes to the owner); /fleet. Reads only (gh pr list, gh issue list, git remote): every outward action is a button the owner presses, which puts a prompt in front of the modelguard, genius, autopilot
superpowersthird-party skills library (obra/superpowers, MIT), pinned to v7.0.0 bb92a77: listed here so it installs with the mods; which skills we keep is decided after measurementnothing

Audience

Each output of a mod has one reader, and the engine fixes the reader by the API the output goes through (there is no per-call option): $.ui.toast, $.ui.log, $.ui.status, panes and rows are the user's, and the model never sees them; a tool.call result's context, a prompt.submit context and prompt.compose sections are Claude's, and the user never sees them; a deny is the model's tool error (the transcript draws it too). A text is written for its reader, and one string is never sent to both. The mods that send to both say which text is whose:

  • zetetic-autopilot: the user reads a toast when main implements (what main ran) and when a subagent spawn is refused (which spawn, how many run, the cap and the window: no instruction); Claude reads, in the context of main's first implementing tool result of a turn, the rule to delegate to a subagent, and, as the Agent tool's error, the cap refusal with the way out (wait for a running agent to finish, spawn again).
  • cortex-guard: the user reads a toast for each refusal, for a worktree that was not registered, and for a guard that failed; Claude reads the refusal's rule and fix as the tool's error (the same error when the guard itself failed), and, in the context of the result of its git worktree add, that the worktree was not registered and its cleanup is not covered.
  • harness-fleet: the user reads the /fleet pane and its toasts; Claude reads only what a button the user presses puts in front of it (review, take an issue, draft an issue), as "The harness-fleet plugin sent a message: ..." in the plugin's own voice: the owner is "the owner" in it, never "me" or "I".

Developing

Each mod is validated, tested and type-checked on its own:

cd mods/<mod> && claude plugin validate . && claude plugin test && npx -y -p typescript tsc -p . --noEmit

tsc needs the engine to have loaded the mod once (it lays .claude-plugin/types/); keep --noEmit, since a plain tsc -p . writes .js files beside the sources. For hot reload in a session, link the mod into that session's ~/.claude/dev-mods/<session>/ folder; the engine watches the folder a link names.

A mod cannot import a file from another mod (the engine refuses it: "outside the plugin's folder"), so the few small pure files several mods need are copied into each of them: hooks/paths.ts (where ~/ lands: HOME, else USERPROFILE, CLAUDE_CONFIG_DIR for ~/.claude) in five mods, and hooks/design.ts (the one parser of a prompt's DESIGN block) in zetetic-insights and zetetic-autopilot, each with its test. After editing one, copy it over the others; this fails when a copy differs:

sh scripts/check-shared.sh

Installing

.claude-plugin/marketplace.json lists each mod as "source": "./mods/<mod>", so the repository is the marketplace. From another machine:

/plugin install <mod> --marketplace cdeust/claude-mods

y adds the marketplace, then the user scope. On this machine a folder marketplace reads the mods from the checkout, with no copy: claude plugin marketplace add <this folder>, then /plugin install <mod> and /reload-plugins after an edit.

Without write access to settings.json

claude plugin marketplace add and claude plugin install both write enabledPlugins and extraKnownMarketplaces into settings.json. Where that file cannot be changed, load the mods by directory instead: nothing is written, and each mod is registered for the session as <name>@inline.

MODS=/path/to/claude-mods/mods

# repeat --plugin-dir once per mod
claude \
  --plugin-dir $MODS/cortex-guard \
  --plugin-dir $MODS/cortex-wiki \
  --plugin-dir $MODS/zetetic-genius \
  --plugin-dir $MODS/zetetic-autopilot \
  --plugin-dir $MODS/zetetic-insights \
  --plugin-dir $MODS/mission-control \
  --plugin-dir $MODS/harness-fleet

# or one variable, colon separated
CLAUDE_CODE_PLUGIN_DIRS=$MODS/cortex-guard:$MODS/cortex-wiki:$MODS/zetetic-genius:$MODS/zetetic-autopilot:$MODS/zetetic-insights:$MODS/mission-control:$MODS/harness-fleet claude

# an alias in the shell profile: it sets MODS itself, because the alias body is single-quoted and
# is expanded each time it runs, not when the profile is read
alias claude-mods='MODS=/path/to/claude-mods/mods; CLAUDE_CODE_PLUGIN_DIRS=$MODS/cortex-guard:$MODS/cortex-wiki:$MODS/zetetic-genius:$MODS/zetetic-autopilot:$MODS/zetetic-insights:$MODS/mission-control:$MODS/harness-fleet claude'

Which form to prefer: an interactive session may ask for a login when CLAUDE_CONFIG_DIR points at an empty directory (seen once in an isolated directory, where headless claude -p did not ask). On the machine's own configuration directory, which is already logged in, that does not apply; use the repeated --plugin-dir or the alias there, and keep an isolated CLAUDE_CONFIG_DIR for tests only.

claude plugin list shows them under "Session-only plugins" with Status: loaded.

What then must hold:

  • The dependencies of a mod are resolved among the mods loaded in the same command, so load a mod together with what it names: zetetic-autopilot needs zetetic-genius; harness-fleet needs cortex-guard, zetetic-autopilot and zetetic-genius. A mod whose dependency is absent is listed disabled, with the error Dependency "<name>" is not installed.
  • Options cannot be set (they live in settings.json under pluginConfigs), so every default in a plugin.json has to be right on any machine:
ModOptionDefaultNotes
cortex-guardhygiene_script~/Developments/disk-hygiene/disk_hygiene.py~/ is the home of the user running the session, read at runtime. When the file is not there, one toast per session says hygiene script not found at <path>; worktrees are not registered; an empty value disables the registration without a toast. A python3 that fails to start gets one toast naming the cause, and no further worktree is registered for the session (no retry)
zetetic-geniusmode, classifier_modelobserve, haikuthe grade is one low-effort completion on the haiku alias
zetetic-autopilotpolicy_mode, quota_pressure_percent, max_parallel_agents, offload_threshold_chars, offload_preview_charsenforce, 80, 5, 30000, 2000the cap counts and refuses only the main loop's own spawns (a fork of main included): a subagent's nested spawn, a workflow script's agent() and a teammate are neither refused nor counted. A result past the threshold is written whole to a file in the session's tool-results directory (the engine's cleanupPeriodDays sweeps it, 30 days by default; the mod deletes nothing); the model reads the preview, the path and the size
mission-controlrendererautoauto draws pixels in kitty or Ghostty outside tmux (TMUX, TERM, TERM_PROGRAM, KITTY_WINDOW_ID), cells elsewhere; cells or pixels forces one
harness-fleetgithub_owner, refresh_on_startcdeust, truereads gh pr list, gh issue list and git remote
  • The machine must let the mods do what they ask: python3 (guard), gh and a route to api.github.com (fleet), the files under ~/.claude/plugins/ (fleet), pandoc and xelatex (wiki), and the model aliases (genius, autopilot).

Measured, on one Mac (Claude Code 2.1.293, no company sandbox): with a pristine settings.json holding {} and an isolated CLAUDE_CONFIG_DIR, loading the mods by CLAUDE_CODE_PLUGIN_DIRS lists them as loaded and leaves settings.json at {}; zetetic-autopilot loaded alone is disabled with the dependency error above.

Not measured: the managed-settings lock itself (it could not be reproduced), whether a company policy accepts --plugin-dir, any refusal of a real sandbox (blocked network, denied exec, unreadable ~/.claude), the model aliases, and whether /config lists the options of directory-loaded mods in an interactive session.

Source 5 files
hooks/register.ts 187 lines
1import { atom, update } from 'claude-code'
2import type { EngineInterface, Register } from 'claude-code'
3
4import type { Refusal } from '../types'
5import { type CallInput, judgeCall, judgePath, worktreeAddPath } from './guard'
6import { placePath } from './paths'
7import { PYTHON_CANDIDATES } from './rules'
8
9const REFUSALS_CAP = 200 // source: bounds $.state size; a viewer shows the last rows only
10const REASON_CAP = 80 // source: own choice, a toast shows a cause in a line
11// `git worktree add` waits for both runs below (the result carries the news to Claude), so a hung child
12// delays it by its whole timeout; the engine default is 30 s each (`ProcessRunInit.timeoutMs`). A rejection on
13// timeout takes the same catch path as a child that cannot start: reported, never blocking the add.
14const PROBE_TIMEOUT_MS = 5_000 // source: own choice, `python --version` prints and exits at once; 5 s is generous
15const REGISTER_TIMEOUT_MS = 10_000 // source: own choice, the script writes one registry entry; 10 s covers a cold disk
16
17const refusals = atom({ plugin: 'cortex-guard', key: 'refusals' } as const, [] as Refusal[])
18
19// Module state: where the repo is and which script registers a worktree. A hot reload runs
20// session.start again, so all of it is set afresh. `script` is the option as configured (`~/` is
21// the running user's home, computed per machine); `missingSaid` keeps the "not found" toast, and the
22// "no python could run" toast, to one per session and stops further attempts after either. `python`
23// is the first of PYTHON_CANDIDATES that starts, resolved once per session.
24let repo = ''
25let script = ''
26let missingSaid = false
27let python: { argv0: string } | { reason: string } | undefined
28
29// Where a path lands once links and `..` are resolved; the spelling when it does not exist yet.
30async function realPathOf($: EngineInterface, path: string): Promise<string> {
31  try {
32    const stat = await $.fs.stat(path, { resolve: true })
33    return (stat as { realPath?: string }).realPath ?? path
34  } catch {
35    return path
36  }
37}
38
39const why = (error: unknown): string =>
40  (error instanceof Error ? error.message : String(error)).slice(0, REASON_CAP)
41
42// The script's place on this machine, or the reason it has none: `~/` is the home of the user
43// running the session (HOME, else USERPROFILE), read from the environment, never a path baked into
44// the mod.
45async function scriptPath($: EngineInterface): Promise<{ path: string } | { reason: string }> {
46  if (!script.startsWith('~/')) return { path: script }
47  try {
48    return placePath(
49      { home: await $.env.get('HOME'), userProfile: await $.env.get('USERPROFILE'), configDir: await $.env.get('CLAUDE_CONFIG_DIR') },
50      script,
51    )
52  } catch (error) {
53    return { reason: `the environment is unreadable: ${why(error)}` }
54  }
55}
56
57// The first python that starts, `--version` exiting 0: a Store alias that exits non-zero, a name the
58// machine does not have and a launch the sandbox refuses are all "not this one", and when none
59// starts the answer is every reason, in order.
60async function pythonOf($: EngineInterface): Promise<{ argv0: string } | { reason: string }> {
61  if (python !== undefined) return python
62  const tried: string[] = []
63  for (const candidate of PYTHON_CANDIDATES) {
64    try {
65      const ran = await $.process.run([candidate, '--version'], { timeoutMs: PROBE_TIMEOUT_MS })
66      if (ran.exitCode === 0) return (python = { argv0: candidate })
67      tried.push(`${candidate}: exit ${ran.exitCode}`)
68    } catch (error) {
69      tried.push(`${candidate}: could not start (${why(error)})`)
70    }
71  }
72
73  return (python = { reason: tried.join('; ') })
74}
75
76// Says once per session that the script is missing; later worktrees stay unregistered without a
77// second toast (the first one named the path and the cause).
78function sayMissing($: EngineInterface, where: string, reason: string): void {
79  if (missingSaid) return
80  missingSaid = true
81  $.ui.toast(`hygiene script not found at ${where}; worktrees are not registered (${reason})`)
82}
83
84// Pairs with the worktree rule: a worktree that exists is registered, as CLAUDE.md prescribes
85// (the registered cleanup procedure, 2026-09-26). Two readers, two channels: a failure is toasted to the user
86// (who reads the toast alone) and returned as its reason, which the tool call carries to Claude in its
87// result's `context` (what the model reads and the user never sees). Undefined: registered, or not asked for
88// (the option is empty, no cleanup was promised).
89async function registerWorktree($: EngineInterface, path: string): Promise<string | undefined> {
90  if (script === '') return undefined
91  if (missingSaid) return 'an earlier registration failed this session and none is tried again'
92  const placed = await scriptPath($)
93  if ('reason' in placed) {
94    sayMissing($, script, placed.reason)
95    return `the hygiene script has no place: ${placed.reason}`
96  }
97  try {
98    await $.fs.stat(placed.path)
99  } catch (error) {
100    sayMissing($, placed.path, why(error))
101    return `the hygiene script was not found at ${placed.path}: ${why(error)}`
102  }
103  const py = await pythonOf($)
104  if ('reason' in py) {
105    // No python will start for the next worktree either: say it once, with every reason, and stop
106    // trying for the session (no retry, no fallback).
107    missingSaid = true
108    $.ui.toast(`worktree NOT registered (no python could run: ${py.reason}); no further worktree is registered this session`)
109    return `no python could run: ${py.reason}`
110  }
111  const real = await realPathOf($, path)
112  try {
113    const ran = await $.process.run(
114      [py.argv0, placed.path, '--host', 'claude', '--session', await $.session.id(), 'register-worktree', '--repo', repo, '--path', real],
115      { timeoutMs: REGISTER_TIMEOUT_MS },
116    )
117    if (ran.exitCode === 0) {
118      $.ui.toast(`worktree registered: ${real}`)
119      return undefined
120    }
121    const stderr = ran.stderr.slice(0, REASON_CAP)
122    $.ui.toast(`worktree NOT registered (${stderr})`)
123    return stderr === '' ? `the script exited ${ran.exitCode}` : stderr
124  } catch (error) {
125    missingSaid = true
126    $.ui.toast(`worktree NOT registered (${py.argv0} could not run the script: ${why(error)}); no further worktree is registered this session`)
127    return `${py.argv0} could not run the script: ${why(error)}`
128  }
129}
130
131// What Claude reads on the result of the `git worktree add` it ran, when the worktree was not registered: the
132// user was toasted (a toast is the user's alone), and Claude, which made the worktree, is the one who can
133// register it by hand. Cleanup of an unregistered worktree is not done by the hooks.
134const unregistered = (path: string, reason: string): string =>
135  `cortex-guard: the worktree ${path} was NOT registered with the hygiene script (${reason}), so its cleanup is not covered. ` +
136  'Register it by hand with disk_hygiene.py register-worktree, or tell the owner it is unregistered.'
137
138export const register: Register = (on, options) => {
139  script = String(options.hygiene_script ?? '')
140
141  on('session.start', async ($, e, next) => {
142    repo = (await $.session.repo())?.root ?? e.cwd
143    missingSaid = false
144    python = undefined
145
146    return next(e)
147  })
148
149  // Fail closed: a guard that throws refuses.
150  on('tool.call', { tool: ['Edit', 'Write', 'NotebookEdit', 'Bash'] }, async ($, e, next) => {
151    const tool = String(e.tool)
152    const input = e as CallInput
153    let verdict = judgeCall(tool, input)
154    if (verdict.allow && input.file_path !== undefined)
155      verdict = judgePath(await realPathOf($, input.file_path))
156    if (verdict.allow) {
157      const ran = await next(e)
158      // A call another plugin refused ran nothing: no worktree exists, so none is registered or reported.
159      if (ran.deny !== undefined || ran.isError) return ran
160      const added = tool === 'Bash' ? worktreeAddPath(input.command ?? '') : undefined
161      if (added === undefined) return ran
162      // Awaited: the result of this call is where Claude can be told the worktree is not covered.
163      // A registration that throws must not turn a call that ran into a refusal: it is a reason, like any other.
164      const reason = await registerWorktree($, added).catch((error: unknown) => `registration failed: ${why(error)}`)
165      return reason === undefined ? ran : { ...ran, context: [...(ran.context ?? []), unregistered(added, reason)] }
166    }
167    const target = input.file_path ?? input.notebook_path ?? (input.command ?? '').slice(0, 60)
168    const at = await $.clock.now()
169    await update($, refusals, (list) =>
170      [...list, { at, tool, rule: verdict.rule, target }].slice(-REFUSALS_CAP),
171    )
172    $.ui.toast(`refused ${tool}: ${verdict.rule}`)
173
174    return { deny: `cortex-guard (${verdict.rule}): ${verdict.reason}` }
175  }).catch(($, e, next) => {
176    if (next.called) return next(e)
177    // Two readers: Claude reads the deny as the tool's error; the user reads a toast, or learns nothing of a
178    // guard that stopped working.
179    try {
180      $.ui.toast(`cortex-guard failed on ${String(e.tool)}: the call was refused`)
181    } catch {
182      // The deny below is the answer whether or not the user could be told.
183    }
184    return { deny: `cortex-guard: its guard failed on ${String(e.tool)}, so the call was refused.` }
185  })
186}
187
hooks/guard.ts 111 lines
1// Pure verdicts for the two rules no settings hook enforces: wiki pages are written only
2// through the wiki tool, and every git worktree lives inside the repo.
3
4import { isInsideWorktreeRoot, withSlashes } from './rules'
5
6// source: the generated mirrors carry "Read-only mirror: edit the canonical wiki page"
7// (docs/adr/ADR-1060-*.md header); the canonical pages live under wiki/ (wiki/README.md).
8const MIRROR = /(^|\/)docs\/adr\/ADR-\d+[^/]*\.md$/
9const CANONICAL = /(^|\/)wiki\/(adr|specs|lessons)\/.+\.md$/
10
11export type Verdict = { allow: true } | { allow: false; rule: string; reason: string }
12
13const ALLOW: Verdict = { allow: true }
14
15export const WIKI_RULE = 'wiki-write-only'
16export const WORKTREE_RULE = 'worktree-inside-repo'
17
18const refuseWiki = (path: string, why: string): Verdict => ({
19  allow: false,
20  rule: WIKI_RULE,
21  reason: `${path}: ${why} Use the Cortex wiki_write tool (wiki_adr for a decision); wiki_reindex regenerates the mirror.`,
22})
23
24// The patterns are written with `/`; a Windows path is matched in its slashed spelling and reported
25// as it was typed.
26export const judgePath = (path: string): Verdict => {
27  const slashed = withSlashes(path)
28  if (MIRROR.test(slashed)) return refuseWiki(path, 'a generated read-only mirror.')
29  if (CANONICAL.test(slashed))
30    return refuseWiki(path, 'a canonical wiki page, written only through the wiki tool.')
31  return ALLOW
32}
33
34const WRITES_FILES = /(^|[\s;&|(])(sed\s+-i|tee|cp|mv|rm|truncate|dd|perl\s+-pi)\b|>>?\s*\S/
35
36const tokensOf = (command: string): string[] =>
37  command.split(/\s+/).map((t) => t.replace(/^['"]|['"]$/g, ''))
38
39// Best effort: a shell command that names a protected path and writes.
40export const judgeShellWiki = (command: string): Verdict => {
41  if (!WRITES_FILES.test(command)) return ALLOW
42  for (const path of tokensOf(command)) {
43    const verdict = judgePath(path)
44    if (!verdict.allow) return verdict
45  }
46  return ALLOW
47}
48
49// source: `git [-C <path>] [-c <name>=<value>] [--git-dir=<path>|--git-dir <path>] ...
50// <command>` (git(1) SYNOPSIS); these global options take a value when given separately.
51const GIT_VALUED_OPTIONS = new Set(['-C', '-c', '--git-dir', '--work-tree', '--namespace', '--exec-path'])
52
53// Index of the subcommand after `git` at `at`, skipping git's own global options.
54const gitSubcommandIndex = (t: string[], at: number): number => {
55  let i = at + 1
56  while (i < t.length && (t[i] ?? '').startsWith('-')) {
57    i += GIT_VALUED_OPTIONS.has(t[i] ?? '') ? 2 : 1
58  }
59  return i
60}
61
62// `git [global options] worktree add [options] <path> [<commit-ish>]`: the path is the
63// first token after `add` that is not an option and not an option's value (-b/-B/--orphan).
64export const worktreeAddPath = (command: string): string | undefined => {
65  const t = tokensOf(command)
66  let at = -1
67  for (let i = 0; i < t.length && at < 0; i++) {
68    if (t[i] !== 'git') continue
69    const sub = gitSubcommandIndex(t, i)
70    if (t[sub] === 'worktree' && t[sub + 1] === 'add') at = sub
71  }
72  if (at < 0) return undefined
73  const args = t.slice(at + 2)
74  for (let i = 0; i < args.length; i++) {
75    const a = args[i] ?? ''
76    if (a === '-b' || a === '-B' || a === '--orphan') {
77      i++
78      continue
79    }
80    if (a.startsWith('-')) continue
81    return a
82  }
83  return undefined
84}
85
86export const judgeShellWorktree = (command: string): Verdict => {
87  const path = worktreeAddPath(command)
88  if (path === undefined || isInsideWorktreeRoot(path)) return ALLOW
89  return {
90    allow: false,
91    rule: WORKTREE_RULE,
92    reason: `git worktree add ${path}: a worktree lives at <repo>/.claude/worktrees/<name>/ (.Codex/worktrees/ for Codex), never outside the repo.`,
93  }
94}
95
96export const judgeShell = (command: string): Verdict => {
97  const wiki = judgeShellWiki(command)
98  return wiki.allow ? judgeShellWorktree(command) : wiki
99}
100
101export type CallInput = { file_path?: string; command?: string; notebook_path?: string }
102
103export const judgeCall = (tool: string, input: CallInput): Verdict => {
104  if ((tool === 'Edit' || tool === 'Write') && input.file_path !== undefined)
105    return judgePath(input.file_path)
106  if (tool === 'NotebookEdit' && input.notebook_path !== undefined)
107    return judgePath(input.notebook_path)
108  if (tool === 'Bash' && input.command !== undefined) return judgeShell(input.command)
109  return ALLOW
110}
111
hooks/paths.ts 41 lines
1// Where `~/` lands on the machine a mod runs on. Pure: the engine follows `$` only inside the module
2// that spells it, so each mod's register file reads the three variables and hands their values here.
3//
4// This file exists once per mod that expands `~/` (a mod cannot import a file from another mod: the
5// engine refuses it, "outside the plugin's folder"), and every copy is byte-identical;
6// scripts/check-shared.sh fails when one differs.
7
8export type PathVars = { home: string | undefined; userProfile: string | undefined; configDir: string | undefined }
9export type Placed = { path: string } | { reason: string }
10
11const isSet = (value: string | undefined): value is string => value !== undefined && value !== ''
12const trimmed = (dir: string): string => dir.replace(/[\\/]+$/, '')
13
14// source: HOME is the home on macOS and Linux, USERPROFILE on Windows (cmd and PowerShell set it,
15// not HOME); Node's os.homedir() reads them in that order on each platform. Unset in a sandbox: no
16// place, said as such, never `/`.
17export const homeOf = (vars: PathVars): Placed =>
18  isSet(vars.home) ? { path: trimmed(vars.home) } : isSet(vars.userProfile) ? { path: trimmed(vars.userProfile) } : { reason: 'neither HOME nor USERPROFILE is set' }
19
20// source: CLAUDE_CONFIG_DIR relocates the engine's `~/.claude` (plugins/, reference/, settings.json);
21// without it the config directory is `<home>/.claude`.
22export const configDirOf = (vars: PathVars): Placed => {
23  if (isSet(vars.configDir)) return { path: trimmed(vars.configDir) }
24  const home = homeOf(vars)
25
26  return 'path' in home ? { path: `${home.path}/.claude` } : home
27}
28
29const CONFIG_PREFIX = '~/.claude'
30
31// A path as the mods spell it: `~/.claude/...` is under the config directory, any other `~/...` under
32// the home, anything else is already a place.
33export const placePath = (vars: PathVars, path: string): Placed => {
34  if (!path.startsWith('~/')) return { path }
35  const isConfig = path === CONFIG_PREFIX || path.startsWith(`${CONFIG_PREFIX}/`)
36  const base = isConfig ? configDirOf(vars) : homeOf(vars)
37  if ('reason' in base) return { reason: `${path} has no place: ${base.reason}` }
38
39  return { path: `${base.path}/${path.slice(isConfig ? CONFIG_PREFIX.length + 1 : 2)}` }
40}
41
hooks/rules.ts 26 lines
1// The facts cortex-guard enforces, once. Pure, no `$`.
2//
3// This file exists in both mods (a mod cannot import a file from another mod: the engine refuses it,
4// "outside the plugin's folder") and the two copies are byte-identical; scripts/check-shared.sh fails
5// when they differ.
6
7// source: ~/.claude/CLAUDE.md rule 2 and Cortex CLAUDE.md: <repo>/.claude/worktrees/<name>/,
8// .Codex/worktrees/<name>/ for Codex.
9export const WORKTREE_ROOTS = ['/.claude/worktrees/', '/.Codex/worktrees/'] as const
10
11// A Windows path spells its separators `\`; the rules below are written with `/`.
12export const withSlashes = (path: string): string => path.replace(/\\/g, '/')
13
14export const isInsideWorktreeRoot = (path: string): boolean => {
15  const slashed = withSlashes(path)
16
17  return WORKTREE_ROOTS.some((root) => slashed.includes(root))
18}
19
20// source: the python that runs the hygiene script is the first of these that starts: Cortex's own
21// hooks resolve `command -v python3 || command -v python`; `py` is the Python launcher for Windows
22// (PEP 397). Assumed, not measured here: that a Windows python3 may be a Store alias that fails, and
23// that `py` is present when the launcher option was installed. The logic needs only that a candidate
24// which cannot start, or exits non-zero on --version, is skipped for the next one.
25export const PYTHON_CANDIDATES = ['python3', 'python', 'py'] as const
26
types/index.d.ts 16 lines
1// One refused call: when, which tool, which rule, and what it aimed at.
2export type Refusal = {
3  at: number
4  tool: string
5  rule: string
6  target: string
7}
8
9declare module 'claude-code' {
10  interface PluginState {
11    'cortex-guard': {
12      refusals: Refusal[]
13    }
14  }
15}
16