SLOPSHOPPER

foundry

Palantir Foundry for Claude Code: Orthanc tools, an approval ladder for Foundry mutations, scoped Foundry context, one slash command per Foundry resource and a…

panebandguardcommandtoastprompt
★ 1v0.5.0MITupdated 2026-10-23zaycruz/claude-foundry
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · foundry
│ ┃ Foundry context ✕ › fix the failing auth test and add an audit log call │ ┃ unknown │ ┃ ~278 tokens in the system prompt · approval ⏺ Read(src/auth.ts) │ ┃ auto · branch none ⎿ Read 6 lines │ ┃ Nothing selected. /open sets the stack, ⏺ Update(src/auth.ts) │ ┃ ontology, namespace and projects. ⎿ Added 2 lines, removed 1 line │ ┃ ⏺ Bash(bun test) │ ┃ [ Close ] ⎿ 3 pass, 1 fail │ │ ● Done. refresh now rejects expired claims and logs an audit event. │ │ ✻ Worked for 42s · done 4:20 PM │ │ › /foundry │ ⎿ foundry: Foundry context is open (Esc closes it). │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · Foundry context
unknown ~278 tokens in the system prompt · approval auto · branch none Nothing selected. /open sets the stack, ontology, namespace and projects. [ Close ]
Pane · foundry-picker
Nothing to choose.
README

foundry: Palantir Foundry for Claude Code

A Claude Code mod that lets Claude work in Palantir Foundry through the Orthanc CLI, with the operator in control of every change. Orthanc is the only path into Foundry: when it can't do something, the mod says so instead of falling back to REST.

  • Two tools. orthanc_help discovers Orthanc's command surface; orthanc_cli runs a command in agent mode and returns its foundry-agent-v1 envelope. A waiting command (repository checks wait, ontology branch-index-status --wait, sql wait) runs as long as its own --timeout and --publish-grace plus a margin, from 300 s up to 1,920 s. Output over 20,000 chars is cut for the model, with row names, counts and the page token kept above the cut and the whole envelope written to a file.
  • An approval ladder on every Foundry mutation, through the tools, Bash or a Palantir MCP server: ask-always, allow-edits, auto (a Haiku guard judges each mutation) and yolo. Destructive changes always ask; protected branches ask unless yolo; branch-scoped work needs an agent branch; calls naming the Compass root are denied; a call repeated three times is blocked.
  • A branch rule that no approval mode can turn off: agent work happens on branches, never on a production main. Ontology writes must pass --branch <global branch RID>; dataset, stream and build writes must name a work branch; code goes to a work branch through orthanc repository push and a pull request. Branchless writes, writes to main/master, proposal merges and approvals, default-branch pushes, raw git push to a Foundry repository and Foundry writes outside Orthanc are blocked. A release tag (repository tag create --apply) is not blocked: it asks the operator in every mode, naming the tag, the commit and the repository. Orthanc writes run only through orthanc_cli: Bash may read through Orthanc but not write, however the shell wraps the call. Text that only mentions Orthanc (a commit message, a PR body, an echo) is not a call.
  • FDE mode (/fde on, or /fde <goal>): binds the session to one agent global branch. Ontology writes are pinned to it, each --apply needs a dry run of the same call first, and /fde end hands the branch back to the operator, still open.
  • Foundry context in the system prompt (stack, ontology, projects, types, resources), and in the mod's own subagents.
  • Slash commands for choosing that context, and /foundry, a live view of what is in context, like /context for Foundry.
  • Tracing to Langfuse or any OTLP/HTTP collector: one trace per turn that touched Foundry, with each tool call, the gate's decision and token usage, redacted before it leaves the machine.
  • Agents (foundry-scout, foundry-builder, foundry-reviewer, foundry-oracle) and skills for the Foundry delivery lifecycle.

Install

1. Orthanc (required)

The mod does all of its Foundry work through the orthanc binary. Install the latest release and set up a profile for your stack:

curl -fsSL https://github.com/zaycruz/orthanc/releases/latest/download/install.sh | sh
export PATH="$HOME/.local/bin:$PATH"
orthanc --version
orthanc onboarding        # skipped by the installer if a profile already exists

The mod runs orthanc from PATH (or ORTHANC_BIN). Add more stacks with orthanc configure profile create. Tokens stay in the macOS Keychain and never pass through Claude: /auth prints the command for you to run in your own terminal.

2. The mod

/plugin marketplace add zaycruz/claude-foundry
/plugin install foundry@claude-foundry

Or load a checkout for one session: claude --plugin-dir ./claude-foundry. Function hooks must be enabled (CLAUDE_CODE_ENABLE_FUNCTION_HOOKS=1). /onboard checks that Orthanc, the profile and the credentials all work.

Commands

CommandDoes
/foundryThe Foundry resources in context: counts, items, clear buttons, prompt size
/openStack, then ontology, then namespace, then projects
/onboard, /mcp-statusCheck orthanc, profiles, stack, credentials, context
/auth [profile]How to store credentials, and whether they work
/profile, /ontology, /namespace, /projectChoose the stack, ontology, namespace, projects
/object-type, /action-typeOntology types in scope
/folder /dataset /media-set /repository /contour /source /developer-console /aip-chatbotCompass resources in scope
/media-item, /objects, /function, /language-model, /permission, /searchLookups added to context
`/scope [show\clear\ontology], /approval [mode\rules], /recap`Context, approval mode and guard rules, a two-paragraph recap
/fde on, /fde <goal>, /fde goal <text>, /fde --branch <rid> [goal], /fde, /fde resume, /fde endFDE mode: start on a new agent branch (with or without a goal) or adopt any open one, set the goal, show status, rebind after a restart, hand off
/traceTrace export status, and whether the last Foundry trace reached Langfuse

Every command has one name; there are no aliases. Every list command takes a filter, and clear. /link-type, /interface, /egress-policy, /certificate and /automation wait on Orthanc list commands and say so; the mod never falls back to Foundry REST.

/namespace scopes the context to one Compass namespace (orthanc's space): /project and the Compass pickers list only its projects, /search stays under its path, and the prompt tells Claude to do the same. Choosing a different namespace clears the projects and Compass resources picked before; choosing the same one or clearing it keeps them. Outside FDE mode it steers discovery only; the gate does not deny writes outside it. FDE mode holds a session to it (below).

FDE mode

/fde on puts the session in FDE mode: it creates agent/fde-<timestamp> as a global branch on the selected ontology and binds the session, subagents included, to it. /fde <goal> does the same with a goal, which names the branch (agent/fde-<goal>-<timestamp>) and heads the prompt and the handoff; /fde goal <text> sets or changes it later. /fde --branch <rid> [goal] adopts an open global branch on the selected ontology instead, whoever made it (a Foundry AI FDE branch is ai-fde/<user>/<slug>). The agent still creates only agent/ branches, and a branch not named agent/ is adopted only when you type the command yourself (the terminal or Remote Control; not a -p run or the Agent SDK), not when a peer session, a relay, a channel, a trigger or another plugin sends it. /fde end needs you to type it the same way, and so does /fde resume of a branch not named agent/. Such a branch is flagged in the status, the prompt (others may have work on it) and the handoff, which leaves closing it to its owner; a name that is not a plain branch name shows as its RID, and an open proposal on it is named when it is adopted. While bound:

  • Ontology writes go to that branch. A write that needs a branch and names none gets it; a call that names any other global branch, another ontology, --profile or an abbreviated branch flag is refused. Dataset, stream and build writes keep the branch rule (a work branch, never main) but are not pinned to the global branch.
  • The agent cannot create, close or merge global branches, or touch proposals, while bound; global-branch add-repo runs on the bound branch only.
  • Plan, then apply: an --apply runs only after a clean dry run of the same call. The plan pins every file the call reads (--*-file values, @file, a short flag with its file attached (-s@schema.json), and any path-like argument that reads as a file) by SHA-256, checked again just before the call runs, and a file naming another global branch or ontology is refused. Each dry run licenses one apply: the apply takes it before running, so two identical applies in parallel cannot share it, and a refused apply, or one Orthanc rejects as a usage error, gives it back; any other failure keeps it spent, since Foundry may have changed. Directory arguments are not hashed, and a file over 20 MB is refused.
  • With a namespace in scope (/namespace), FDE mode holds the session to it. /fde on and /fde --branch first check that the ontology is in it, and refuse before any branch exists if it is not, if it is in no namespace, or if the check cannot run. While bound, every resource a write names, in its arguments or in the files it reads, inputs included, must be in that namespace: a RID (looked up with resource batch-get, once per binding, but a folder it did not return is looked up again at every write) or a Compass path under another namespace is refused, and so is a Compass folder batch-get does not return, since it sits in no namespace the session can see. A RID or path written as JSON escapes (\u002e, \/, a string encoded twice) is scanned as Orthanc reads it, and space create is refused: a new space is outside the namespace. RIDs batch-get does not know (branches, transactions, malformed ones) pass. If the lookup itself fails, the write asks the operator, naming the RIDs it could not check (Run unchecked or not) instead of failing closed; with no one to ask, it does not run. Reads are not checked. A space name or path that is not plain shows as its RID. /namespace and the pane's clear button leave the namespace as it is until /fde end; /scope clear keeps it on the stack the session is bound to.
  • The goal, branch and namespace go into the system prompt and a band above the prompt, and every turn is traced (not only the ones that touch Foundry).

/fde end prints a handoff (branch, namespace, applied writes, how to close it) and leaves the branch open: merging or closing it is the operator's call. If a session ends while bound, the next one offers /fde resume. The mode only adds checks. The branch rule, the approval ladder and the destructive rule judge every bound call as before, in every approval mode.

Operator rules and auto mode

In auto, a Haiku guard judges each Foundry write. Give it your own rules in ~/.claude/foundry/rules.md, one per line. A project can add .claude/foundry-rules.md; since a cloned repository can carry that file, its rules may only make the guard stricter. Claude cannot edit either file, nor read ~/.claude/foundry/; /approval rules shows the rules. For example:

Approve writes in the Sandbox project on agent/ branches.
Ask before any change to the Person or Organization object types.

/approval rules shows what the guard reads. The rules steer the guard only: the branch rule and the destructive rule run first and cannot be loosened.

Claude Code's own auto-mode classifier judges tool calls before the mod sees them, and by default it can refuse Foundry writes as changes to shared resources. To let branch-scoped Foundry work run in auto mode, add an allow rule under autoMode.allow in ~/.claude/settings.json (keep the defaults from claude auto-mode defaults, since a custom list replaces them):

Foundry Branch Work: Palantir Foundry writes made through the foundry Claude Code mod, and the
mod's foundry-* subagents doing them, when every write targets an agent work branch (an agent/
global branch or its ri.branch. RID, an agent- dataset branch, a non-default code branch, or a
resource this session created). The mod denies writes on main/master, merges and
default-branch pushes itself. Does NOT cover writes on main, master or the production
ontology, merges or approvals, permission changes, or deleting resources the session did
not create.

Run claude auto-mode critique after editing.

Tracing

Each turn that touches Foundry (Orthanc tools, Orthanc in Bash, a gated call, a Palantir MCP tool) becomes one OTLP trace: the prompt and answer, a span per tool call with the gate's outcome and reason, and a generation span with the model and token usage. Only Foundry calls carry their input and output; other tools in the turn are named, not shown. Turns in one Claude Code session share a Langfuse session. Nothing is exported until you configure an endpoint, in the environment or in ~/.claude/foundry/otel.env. The mod reads that file once per session as KEY=value lines (it never runs it), and Claude can neither read nor edit it. A value can be a 1Password reference, resolved with op read, so the file holds no keys:

# Langfuse
LANGFUSE_BASE_URL=https://cloud.langfuse.com
LANGFUSE_PUBLIC_KEY="op://Vault/Langfuse/public_key"
LANGFUSE_SECRET_KEY="op://Vault/Langfuse/secret_key"
# or any OTLP/HTTP collector
OTEL_EXPORTER_OTLP_TRACES_ENDPOINT=https://collector.example.com/v1/traces
OTEL_EXPORTER_OTLP_HEADERS=Authorization=Basic%20...

Prefer the file to exported variables: keys in the session's environment are visible to any shell command Claude runs. FOUNDRY_OTEL=off turns tracing off, FOUNDRY_OTEL=all exports every turn, FOUNDRY_OTEL_TOOL_IO=off drops tool input and output, and OTEL_SERVICE_NAME / OTEL_RESOURCE_ATTRIBUTES set the resource. Before export, values under sensitive keys (tokens, RIDs, hosts, names), inside Orthanc envelopes too, are replaced, and tokens, credentials, RIDs, emails, phone numbers, private IPs and internal hostnames are redacted; add your own domains with FOUNDRY_OTEL_REDACT_DOMAINS=.... /trace shows the collector's host, never a header. Export is fire-and-forget and never changes what a tool call does.

Develop

claude plugin validate .
claude plugin test .

hooks/*.test.ts cover the ladder, parity, the context view and trace export. For an E2E run against your own stack, record real Orthanc output and replay it:

FOUNDRY_E2E_PROFILE=<profile> FOUNDRY_E2E_PROJECT=<project rid> \
FOUNDRY_E2E_ONTOLOGY=<ontology rid> ./scripts/record.sh

That writes hooks/fixtures.local.ts, which hooks/e2e.local.test.ts replays. Both stay out of git: they hold your stack's data.

License

MIT

Source 8 files
hooks/register.tsx 1832 lines
1// foundry: a governed Palantir Foundry lane as a Claude Code mod.
2// Orthanc tools, the approval ladder, Foundry context in the system prompt,
3// one slash command per Foundry resource, and /foundry, the visual view of what is in context.
4// Orthanc is the only path to Foundry: what it cannot do waits on an orthanc bead.
5
6import { atom, read, update } from 'claude-code'
7import type { Args, EngineInterface, EventResult, Next, Register } from 'claude-code'
8
9import type { FdeSession, FoundryNamed, FoundryNamespace, FoundryPicker, FoundryPickerKind, FoundryPickItem, FoundryResource, FoundryResourceKind, FoundryScope } from '../types'
10import {
11  applyClear,
12  blockedText,
13  type ClearTarget,
14  COMMAND_TABLE,
15  type CommandEntry,
16  COMPASS_KINDS,
17  type CompassKind,
18  contextLines,
19  emptyScope,
20  foundryTree,
21  hasFocus,
22  mergeSelections,
23  namespaceChanged,
24  normalizeScope,
25  OBJECT_QUERY_BEAD,
26  objectsQuery,
27  ontologyChanged,
28  RESOURCE_LABELS,
29  resourceArgs,
30  resourceRows,
31} from './catalog'
32import {
33  adoptable,
34  batchGetArgs,
35  branchCreateArgs,
36  COMPASS_FOLDER_RID,
37  foreignRids,
38  goalLabel,
39  takePlan,
40  branchRidFrom,
41  contentHash,
42  fdeBind,
43  fdeBranchName,
44  fdeContext,
45  fdeHandoff,
46  fdeStatus,
47  fileCandidates,
48  hasApply,
49  isAgentBranch,
50  namespaceDeny,
51  namespaceScan,
52  normalizeFde,
53  openProposal,
54  parseFdeArgs,
55  planGate,
56  planSignature,
57  plainSpace,
58  recordApply,
59  recordPlan,
60  spacesOf,
61} from './fde'
62import {
63  CLI_TIMEOUT_FLOOR_MS,
64  cliTimeoutMs,
65  type Envelope,
66  failure,
67  guideEnvelope,
68  isCredentialCommand,
69  isErrorEnvelope,
70  isOversized,
71  isUsageError,
72  listItems,
73  manifestFrom,
74  normalizeCommand,
75  parseEnvelope,
76  renderCommand,
77  renderListing,
78  rowsOf,
79  serialize,
80} from './orthanc'
81import { PROCESS_RUN_MAX_MS, type ProcessOutput, readToExit } from './process'
82import {
83  APPROVAL_MODES,
84  type ApprovalMode,
85  type ManifestCommand,
86  classifyCall,
87  classifyOrthancCommand,
88  compassRootReason,
89  DEFAULT_APPROVAL_MODE,
90  type GateClassification,
91  type GuardVerdict,
92  FOUNDRY_GIT_PUSH_REASON,
93  gitPushDirectories,
94  gitPushNamesFoundry,
95  ladderDecision,
96  loopStep,
97  modeGuidance,
98  ORTHANC_CLI,
99  ORTHANC_HELP,
100  parseApprovalMode,
101  resolveOrthancCommand,
102  rulesWriteReason,
103} from './policy'
104import {
105  domainPatterns,
106  langfuseApiBase,
107  otlpBody,
108  parseEnvFile,
109  randomHex,
110  redactString,
111  resourceAttributes,
112  serializePayload,
113  type SpanRecord,
114  type TraceConfig,
115  type TraceEnv,
116  traceConfig,
117} from './telemetry'
118
119const SCOPE = { plugin: 'foundry', key: 'scope' } as const
120const PICKER = { plugin: 'foundry', key: 'picker' } as const
121const BRANCH = { plugin: 'foundry', key: 'workingBranch' } as const
122const FDE = { plugin: 'foundry', key: 'fde' } as const
123const PANE = 'foundry-picker'
124const CONTEXT_PANE = 'foundry-context'
125const pickerAtom = atom(PICKER, null)
126const scopeAtom = atom(SCOPE, emptyScope('unknown', ''))
127const fdeAtom = atom(FDE, null)
128const GUARD_MODEL = 'claude-haiku-5-5'
129const VISIBLE_ROWS = 12
130const TREE_ROWS = 8
131const ROOT_CONCURRENCY = 6
132
133let loop: { identity: string; streak: number } | null = null
134let manifestCache: readonly ManifestCommand[] | undefined
135const helpCache = new Map<string, string>()
136const refusedCommands: string[] = []
137
138const asString = (value: unknown) => (typeof value === 'string' ? value : '')
139const errorsOf = (envelope: Envelope) => JSON.stringify(envelope.errors).slice(0, 400)
140
141async function orthancBin($: EngineInterface): Promise<string> {
142  return (await $.env.get('ORTHANC_BIN'))?.trim() || 'orthanc'
143}
144
145// $.process.run stops at ten minutes: a longer wait streams under its own deadline.
146async function runLong($: EngineInterface, command: readonly string[], timeoutMs: number): Promise<ProcessOutput> {
147  let expire = () => {}
148  const expired = new Promise<void>(resolve => {
149    expire = resolve
150  })
151  const timer = $.clock.after(timeoutMs, () => expire())
152  try {
153    return await readToExit($.process.spawn({ argv: command }), expired, timeoutMs)
154  } finally {
155    timer.cancel()
156  }
157}
158
159// orthanc in agent mode, argv only, no shell; any failure comes back as an
160// envelope so callers handle one shape.
161async function runOrthanc(
162  $: EngineInterface,
163  argv: readonly string[],
164  profile?: string,
165  timeoutMs = CLI_TIMEOUT_FLOOR_MS,
166): Promise<Envelope> {
167  const full = ['--agent', '--non-interactive', ...(profile ? ['--profile', profile] : []), ...argv]
168  try {
169    const command = [await orthancBin($), ...full]
170    const ran = timeoutMs > PROCESS_RUN_MAX_MS ? await runLong($, command, timeoutMs) : await $.process.run(command, { timeoutMs })
171    return (
172      parseEnvelope(ran.stdout) ??
173      failure('orthanc-launch-error', `orthanc exited ${ran.exitCode} with no foundry-agent-v1 envelope`, argv.join(' '), {
174        exit_code: ran.exitCode,
175        stderr: ran.stderr.slice(0, 4000),
176      })
177    )
178  } catch (error) {
179    return failure('orthanc-launch-error', error instanceof Error ? error.message : String(error), argv.join(' '), {
180      timeout_seconds: timeoutMs / 1000,
181    })
182  }
183}
184
185async function loadManifest($: EngineInterface): Promise<readonly ManifestCommand[]> {
186  if (manifestCache !== undefined) return manifestCache
187  const loaded = manifestFrom(await runOrthanc($, ['agent-manifest'], undefined, 30_000))
188  if (loaded.length === 0) throw new Error('orthanc agent-manifest returned no commands')
189  manifestCache = loaded
190  return loaded
191}
192
193async function helpText($: EngineInterface, path: string): Promise<string | null> {
194  const cached = helpCache.get(path)
195  if (cached !== undefined) return cached
196  try {
197    const ran = await $.process.run([await orthancBin($), ...path.split(' '), '--help'], { timeoutMs: 15_000 })
198    const text = `${ran.stdout}${ran.stderr}`.trim()
199    if (text === '') return null
200    helpCache.set(path, text)
201    return text
202  } catch {
203    return null
204  }
205}
206
207async function renderHelp($: EngineInterface, input: { group?: string; command?: string; query?: string }): Promise<string> {
208  const commands = await loadManifest($)
209  if (!input.command) return renderListing(commands, input)
210  const path = normalizeCommand(input.command)
211  const command = commands.find(entry => entry.path === path)
212  if (command === undefined) return `Unknown Orthanc command '${path}'. Use orthanc_help with query to search commands.`
213  return renderCommand(command, await helpText($, command.path))
214}
215
216async function executeCli($: EngineInterface, input: { command: string; args: string[]; profile?: string }): Promise<Envelope> {
217  const commands = await loadManifest($)
218  // The same resolution the guard classified, so what runs is what was judged.
219  const resolved = resolveOrthancCommand(input.command, input.args, commands)
220  const command = commands.find(entry => entry.path === resolved.path)
221  if (command === undefined) {
222    return failure('unknown-command', `Unknown Orthanc command '${input.command}'. Call orthanc_help first.`, input.command)
223  }
224  if (isCredentialCommand(command)) {
225    return failure(
226      'credential-command-denied',
227      `Orthanc command '${command.path}' requires credential input and is not available through orthanc_cli. The operator runs it in a terminal.`,
228      command.path,
229    )
230  }
231  const envelope = await runOrthanc($, [...command.path.split(' '), ...resolved.args], input.profile, cliTimeoutMs(command, resolved.args))
232  return guideEnvelope(envelope, command, isUsageError(envelope) ? await helpText($, command.path) : null)
233}
234
235async function storedScopes($: EngineInterface): Promise<Record<string, unknown>> {
236  const value = await $.store.get('scopes')
237  return typeof value === 'object' && value !== null ? (value as Record<string, unknown>) : {}
238}
239
240async function saveScope($: EngineInterface, scope: FoundryScope): Promise<void> {
241  const next = { ...scope, updatedAt: new Date().toISOString() }
242  await $.state.set(SCOPE, next)
243  await $.store.set('scopes', { ...(await storedScopes($)), [next.profile]: next })
244}
245
246async function approvalMode($: EngineInterface): Promise<ApprovalMode> {
247  return parseApprovalMode(asString(await $.store.get('approvalMode'))) ?? DEFAULT_APPROVAL_MODE
248}
249
250type Profile = { name: string; host: string; isDefault: boolean; status: string }
251
252async function listProfiles($: EngineInterface): Promise<Profile[]> {
253  const envelope = await runOrthanc($, ['configure', 'list'], undefined, 30_000)
254  return listItems(envelope, 'profiles').map(entry => ({
255    name: asString(entry.name),
256    host: asString(entry.host),
257    isDefault: entry.is_default === true,
258    status: asString(entry.status),
259  }))
260}
261
262async function activateProfile($: EngineInterface, profile: Profile): Promise<FoundryScope> {
263  const next = normalizeScope((await storedScopes($))[profile.name], profile.name, profile.host)
264  await $.env.set('FOUNDRY_PROFILE', profile.name)
265  await $.store.set('defaultProfile', profile.name)
266  await $.state.set(BRANCH, null)
267  await saveScope($, { ...next, host: profile.host || next.host })
268  return next
269}
270
271async function startupScope($: EngineInterface): Promise<void> {
272  const profiles = await listProfiles($)
273  const wanted = (await $.env.get('FOUNDRY_PROFILE')) || asString(await $.store.get('defaultProfile'))
274  const chosen = profiles.find(profile => profile.name === wanted) ?? profiles.find(profile => profile.isDefault)
275  if (chosen === undefined) {
276    await $.state.set(SCOPE, emptyScope(wanted || 'unknown', ''))
277    return
278  }
279  const scope = normalizeScope((await storedScopes($))[chosen.name], chosen.name, chosen.host)
280  await $.env.set('FOUNDRY_PROFILE', chosen.name)
281  await $.state.set(SCOPE, { ...scope, host: chosen.host || scope.host })
282}
283
284async function currentScope($: EngineInterface): Promise<FoundryScope> {
285  return normalizeScope((await $.state.get(SCOPE)).value, 'unknown', '')
286}
287
288const profileArg = (scope: FoundryScope) => (scope.profile === 'unknown' ? undefined : scope.profile)
289
290const spaceArgs = (scope: FoundryScope) => (scope.namespace ? ['--space-rid', scope.namespace.rid] : [])
291
292function contextText(scope: FoundryScope, mode: ApprovalMode): string {
293  const lines = [
294    '# Palantir Foundry',
295    'Tools: `mcp__foundry__orthanc_help` (orthanc_help in the skills) discovers the Orthanc command surface; ' +
296      '`mcp__foundry__orthanc_cli` (orthanc_cli) runs Orthanc in agent mode. Prefer them over raw `orthanc` in Bash ' +
297      'and over any Palantir MCP server, which is a read-only fallback for documentation.',
298    `Foundry stack: ${scope.profile}${scope.host ? ` (${scope.host})` : ''}. The operator switches it with /profile; do not pass --profile.`,
299    ...contextLines(scope),
300  ]
301  if (hasFocus(scope)) {
302    lines.push(
303      'Start Foundry resource discovery from the selected ontology, projects and resources.',
304      'For a bounded change: inspect the target, make the smallest reversible change, then run focused verification.',
305      'Read documentation only for a concrete unknown, a tool error, or a high-risk irreversible operation.',
306    )
307  }
308  lines.push(modeGuidance(mode))
309  return lines.join('\n')
310}
311
312const RULES_LIMIT = 4000
313
314// Operator rules for the Haiku guard: ~/.claude/foundry/rules.md (the
315// operator's), then the project's .claude/foundry-rules.md, which a cloned
316// repository can carry and so may only make the guard stricter. They steer the
317// guard only; the branch rule and the destructive rule run before it.
318type OperatorRule = { path: string; text: string; isProject: boolean }
319// Read once per session: an edit made mid-session (by anyone) waits for the next.
320let rulesSnapshot: OperatorRule[] | undefined
321
322async function operatorRules($: EngineInterface): Promise<OperatorRule[]> {
323  if (rulesSnapshot !== undefined) return rulesSnapshot
324  const home = (await $.env.get('HOME'))?.trim()
325  const paths = [...(home ? [{ path: `${home}/.claude/foundry/rules.md`, isProject: false }] : []), { path: '.claude/foundry-rules.md', isProject: true }]
326  const found: { path: string; text: string; isProject: boolean }[] = []
327  for (const { path, isProject } of paths) {
328    const text = await $.fs.read(path).then(String).catch(() => '')
329    if (text.trim() !== '') found.push({ path, text: text.trim().slice(0, RULES_LIMIT), isProject })
330  }
331  rulesSnapshot = found
332  return found
333}
334
335// The auto tier's classifier: a Haiku call.
336// Anything but a clean JSON verdict is null, which the ladder turns into ask.
337// Project rules can come with a cloned repository, so they only tighten: the
338// guard runs with and without them and the stricter verdict stands.
339async function guardVerdict(
340  $: EngineInterface,
341  tool: string,
342  input: unknown,
343  classification: GateClassification,
344): Promise<GuardVerdict | null> {
345  const rules = await operatorRules($)
346  const operator = rules.filter(rule => !rule.isProject).map(rule => rule.text).join('\n\n')
347  const project = rules.filter(rule => rule.isProject).map(rule => rule.text).join('\n\n')
348  const base = await guardOnce($, tool, input, classification, operator, '')
349  if (project === '' || base === null || base.action === 'deny') return base
350  const withProject = await guardOnce($, tool, input, classification, operator, project)
351  if (withProject === null) return null
352  return GUARD_RANK[withProject.action] > GUARD_RANK[base.action] ? withProject : base
353}
354
355const GUARD_RANK = { approve: 0, ask: 1, deny: 2 } as const
356
357async function guardOnce(
358  $: EngineInterface,
359  tool: string,
360  input: unknown,
361  classification: GateClassification,
362  operator: string,
363  project: string,
364): Promise<GuardVerdict | null> {
365  const answer = await $.model.complete({
366    model: GUARD_MODEL,
367    maxTokens: 200,
368    timeoutMs: 15_000,
369    system:
370      'You review one Palantir Foundry mutation an agent wants to run. Answer only JSON: ' +
371      '{"action":"approve"|"ask"|"deny","reason":"<one sentence>"}. approve: routine, reversible, ' +
372      'scoped work on an agent branch. ask: unclear blast radius, shared or production resources, ' +
373      'permissions, schema or ontology changes. deny: clearly destructive or targeting main/master or production.' +
374      (operator === '' ? '' : `\nThe operator's rules, which take precedence over the defaults above:\n${operator}`) +
375      (project === ''
376        ? ''
377        : `\nThe project's rules, which may only make you more cautious:\n${project}`),
378    prompt: JSON.stringify({ tool, input, classification }).slice(0, 8000),
379  })
380  if (!answer.isAnswered) return null
381  try {
382    const parsed: unknown = JSON.parse(answer.text.replace(/^```(json)?|```$/g, '').trim())
383    if (typeof parsed !== 'object' || parsed === null) return null
384    const { action, reason } = parsed as Record<string, unknown>
385    if (action !== 'approve' && action !== 'ask' && action !== 'deny') return null
386    return { action, reason: `guard: ${asString(reason) || action}` }
387  } catch {
388    return null
389  }
390}
391
392// The session's directory; '/' where the host has none (the test kit).
393async function sessionCwd($: EngineInterface): Promise<string> {
394  try {
395    return await $.session.cwd()
396  } catch {
397    return '/'
398  }
399}
400
401async function homeDir($: EngineInterface): Promise<string> {
402  try {
403    return (await $.env.get('HOME'))?.trim() ?? ''
404  } catch {
405    return ''
406  }
407}
408
409// Tracing: one OTLP trace per turn that touched Foundry, sent to Langfuse or
410// any OTLP/HTTP collector. Config comes from the environment, else from an env
411// file (~/.claude/foundry/otel.env, which Claude cannot write) sourced in a
412// subprocess; keys and headers stay in the mod's memory and are never shown.
413// Tracing never changes a gate outcome and never blocks a turn.
414type Tracing = { config: TraceConfig; resource: Record<string, string>; redact: RegExp[]; everyTurn: boolean; source: string }
415type TurnTrace = { traceId: string; rootSpanId: string; startMs: number; prompt: string; spans: SpanRecord[]; touched: boolean; dropped: number }
416type GateNote = { outcome?: string; reason?: string; command?: string; foundry: boolean }
417let tracing: Tracing | null = null
418let literalNote = ''
419let tracingNote = 'off: no OTLP endpoint or Langfuse keys configured'
420let lastExport: { traceId: string; status: string; atMs: number } | null = null
421const turnTraces = new Map<string, TurnTrace>()
422const ENV_FILE_TIMEOUT_MS = 10_000
423const MAX_SPANS = 200
424const STALE_TURN_MS = 3_600_000
425
426// Read as data (parseEnvFile), never sourced. 1Password references resolve
427// through `op read` by argv, in-process; the values never reach the model.
428async function traceEnvFromFile($: EngineInterface, path: string): Promise<TraceEnv | null> {
429  const text = await $.fs.read(path).then(String).catch(() => null)
430  if (text === null) return null
431  const { env, refs, literalSecrets } = parseEnvFile(text)
432  if (literalSecrets.length > 0) literalNote = ` (ignored ${literalSecrets.join(', ')}: write them as op:// references)`
433  // Together, so a hung `op` costs one timeout, not one per reference.
434  await Promise.all(
435    Object.entries(refs).map(async ([key, ref]) => {
436      const ran = await $.process.run(['op', 'read', '--no-newline', ref], { timeoutMs: ENV_FILE_TIMEOUT_MS }).catch(() => null)
437      if (ran && ran.exitCode === 0 && ran.stdout.trim() !== '') env[key] = ran.stdout.trim()
438    }),
439  )
440  return env
441}
442
443async function loadTracing($: EngineInterface, profile: string | null): Promise<void> {
444  tracing = null
445  literalNote = ''
446  // $.env.get takes literal names, so the variables the mod reads stay listable.
447  const read = (value: string | undefined) => value || undefined
448  const env: TraceEnv = {
449    OTEL_EXPORTER_OTLP_TRACES_ENDPOINT: read(await $.env.get('OTEL_EXPORTER_OTLP_TRACES_ENDPOINT')),
450    OTEL_EXPORTER_OTLP_ENDPOINT: read(await $.env.get('OTEL_EXPORTER_OTLP_ENDPOINT')),
451    OTEL_EXPORTER_OTLP_HEADERS: read(await $.env.get('OTEL_EXPORTER_OTLP_HEADERS')),
452    LANGFUSE_BASE_URL: read(await $.env.get('LANGFUSE_BASE_URL')),
453    LANGFUSE_HOST: read(await $.env.get('LANGFUSE_HOST')),
454    LANGFUSE_PUBLIC_KEY: read(await $.env.get('LANGFUSE_PUBLIC_KEY')),
455    LANGFUSE_SECRET_KEY: read(await $.env.get('LANGFUSE_SECRET_KEY')),
456    FOUNDRY_OTEL: read(await $.env.get('FOUNDRY_OTEL')),
457    FOUNDRY_OTEL_TOOL_IO: read(await $.env.get('FOUNDRY_OTEL_TOOL_IO')),
458    PALANTIR_AGENT_OTEL_TOOL_IO: read(await $.env.get('PALANTIR_AGENT_OTEL_TOOL_IO')),
459    OTEL_SERVICE_NAME: read(await $.env.get('OTEL_SERVICE_NAME')),
460    OTEL_RESOURCE_ATTRIBUTES: read(await $.env.get('OTEL_RESOURCE_ATTRIBUTES')),
461    FOUNDRY_OTEL_REDACT_DOMAINS: read(await $.env.get('FOUNDRY_OTEL_REDACT_DOMAINS')),
462  }
463  for (const key of Object.keys(env)) if (env[key] === undefined) delete env[key]
464  let source = 'environment'
465  if ((env.FOUNDRY_OTEL ?? '').toLowerCase() === 'off') {
466    tracingNote = 'off: FOUNDRY_OTEL=off'
467    return
468  }
469  if (traceConfig(env) === null) {
470    const home = await homeDir($)
471    // Only the operator's own file: a path from the environment could come with a project.
472    if (home === '') return
473    const path = `${home}/.claude/foundry/otel.env`
474    const fromFile = await traceEnvFromFile($, path).catch(() => null)
475    if (fromFile === null) return
476    Object.assign(env, fromFile)
477    source = '~/.claude/foundry/otel.env'
478  }
479  const config = traceConfig(env)
480  if (config === null) {
481    tracingNote = (env.FOUNDRY_OTEL ?? '').toLowerCase() === 'off' ? 'off: FOUNDRY_OTEL=off' : `off: ${source} has no OTLP endpoint or Langfuse keys (or a key reference did not resolve)`
482    return
483  }
484  tracing = {
485    config,
486    resource: resourceAttributes(env, profile),
487    redact: domainPatterns(env.FOUNDRY_OTEL_REDACT_DOMAINS),
488    everyTurn: (env.FOUNDRY_OTEL ?? '').toLowerCase() === 'all',
489    source,
490  }
491  $.ui.log(`foundry: tracing to ${config.host}`, { to: 'debug' })
492  tracingNote = `on: ${config.host} (from ${source}${config.toolIo ? '' : ', tool input and output off'}${tracing.everyTurn ? ', every turn' : ', Foundry turns'})`
493}
494
495function startTurn(key: string, prompt: string, nowMs: number): TurnTrace {
496  for (const [stale, turn] of turnTraces) if (stale !== 'main' && nowMs - turn.startMs > STALE_TURN_MS) turnTraces.delete(stale)
497  const turn = { traceId: randomHex(32), rootSpanId: randomHex(16), startMs: nowMs, prompt, spans: [], touched: false, dropped: 0 }
498  turnTraces.set(key, turn)
499  return turn
500}
501
502function recordTool(key: string, tool: string, input: unknown, ran: unknown, note: GateNote, startMs: number, endMs: number): void {
503  if (tracing === null) return
504  const turn = turnTraces.get(key) ?? startTurn(key, '', startMs)
505  turn.touched ||= note.foundry
506  if (turn.spans.length >= MAX_SPANS) {
507    turn.dropped += 1
508    return
509  }
510  const result = (ran ?? {}) as Record<string, unknown>
511  const denied = typeof result.deny === 'string' ? result.deny : undefined
512  const output = denied ?? result.text ?? result.result
513  // Only Foundry calls carry their input and output; other tools in the turn are named, not shown.
514  const io = tracing.config.toolIo && note.foundry
515  const attributes: SpanRecord['attributes'] = {
516    'langfuse.observation.type': 'tool',
517    'gen_ai.tool.name': tool,
518    ...(note.command ? { 'foundry.command': redactString(note.command, tracing.redact) } : {}),
519    ...(note.outcome ? { 'foundry.gate.outcome': note.outcome } : {}),
520    ...(note.reason ? { 'foundry.gate.reason': serializePayload(note.reason, tracing.redact) ?? '' } : {}),
521  }
522  const inputJson = io ? serializePayload(input, tracing.redact) : undefined
523  const outputJson = io ? serializePayload(output, tracing.redact) : undefined
524  if (inputJson) attributes['langfuse.observation.input'] = inputJson
525  if (outputJson) attributes['langfuse.observation.output'] = outputJson
526  turn.spans.push({
527    spanId: randomHex(16),
528    parentSpanId: turn.rootSpanId,
529    name: `tool ${tool}${note.command ? ` ${redactString(note.command, tracing.redact)}` : ''}`,
530    startMs,
531    endMs,
532    attributes,
533    ...(denied ? { error: `denied: ${denied}` } : result.isError === true ? { error: 'tool error' } : {}),
534  })
535}
536
537async function exportTurn($: EngineInterface, key: string, answer: string, usage: unknown, reason: string, endMs: number): Promise<void> {
538  const turn = turnTraces.get(key)
539  turnTraces.delete(key)
540  // In FDE mode every turn is part of the engagement, so every turn is exported.
541  const fde = await fdeState($).catch(() => null)
542  if (tracing === null || turn === undefined || !(turn.touched || tracing.everyTurn || fde !== null)) return
543  const sessionId = await $.session.id().catch(() => 'unknown')
544  const redact = tracing.redact
545  const root: SpanRecord = {
546    spanId: turn.rootSpanId,
547    name: key === 'main' ? 'claude-foundry turn' : 'claude-foundry subagent turn',
548    startMs: turn.startMs,
549    endMs,
550    attributes: {
551      'langfuse.observation.type': 'agent',
552      'langfuse.trace.name': key === 'main' ? 'claude-foundry turn' : 'claude-foundry subagent turn',
553      'langfuse.session.id': sessionId,
554      'session.id': sessionId,
555      'foundry.turn.reason': reason,
556      'foundry.tool.count': turn.spans.length,
557      ...(turn.dropped > 0 ? { 'foundry.spans.dropped': turn.dropped } : {}),
558      ...(key === 'main' ? {} : { 'foundry.agent.id': key }),
559      ...(fde ? { 'foundry.fde.branch': redactString(fde.branchRid, redact), 'foundry.fde.goal': redactString(fde.goal, redact) } : {}),
560    },
561    ...(reason === 'error' || reason === 'refusal' ? { error: reason } : {}),
562  }
563  const prompt = serializePayload(turn.prompt || undefined, redact)
564  const output = serializePayload(answer || undefined, redact)
565  if (prompt) root.attributes['langfuse.observation.input'] = prompt
566  if (output) root.attributes['langfuse.observation.output'] = output
567  const spans = [root, ...turn.spans]
568  const counted = usage as { input_tokens?: number; output_tokens?: number; cache_read_input_tokens?: number; cache_creation_input_tokens?: number; model?: string } | undefined
569  if (counted?.model) {
570    spans.push({
571      spanId: randomHex(16),
572      parentSpanId: turn.rootSpanId,
573      name: 'model',
574      startMs: turn.startMs,
575      endMs,
576      attributes: {
577        'langfuse.observation.type': 'generation',
578        'gen_ai.request.model': counted.model,
579        'langfuse.observation.model.name': counted.model,
580        'langfuse.observation.usage_details': JSON.stringify({
581          input: counted.input_tokens ?? 0,
582          output: counted.output_tokens ?? 0,
583          cache_read_input_tokens: counted.cache_read_input_tokens ?? 0,
584          cache_creation_input_tokens: counted.cache_creation_input_tokens ?? 0,
585        }),
586      },
587    })
588  }
589  const body = otlpBody(turn.traceId, tracing.resource, spans)
590  const sent = { traceId: turn.traceId, status: 'sending', atMs: endMs }
591  lastExport = sent
592  try {
593    const response = await $.http.fetch(tracing.config.url, { method: 'POST', headers: tracing.config.headers, body })
594    sent.status = `HTTP ${response.status}`
595  } catch (error) {
596    sent.status = `failed: ${redactString(error instanceof Error ? error.message : 'fetch error').slice(0, 120)}`
597  }
598}
599
600function touchesFoundry(tool: string, input: Record<string, unknown>, classified: boolean): boolean {
601  if (classified || tool === ORTHANC_CLI || tool === ORTHANC_HELP) return true
602  if (tool === 'Bash') return /\borthanc\b/.test(asString(input.command))
603  return /^mcp__.*(palantir|foundry)/i.test(tool)
604}
605
606async function traceText($: EngineInterface): Promise<string> {
607  const lines = [`Tracing ${tracingNote}${literalNote}.`]
608  if (tracing === null) {
609    lines.push('Set OTEL_EXPORTER_OTLP_TRACES_ENDPOINT and OTEL_EXPORTER_OTLP_HEADERS, or LANGFUSE_BASE_URL, LANGFUSE_PUBLIC_KEY and LANGFUSE_SECRET_KEY, in the environment or in ~/.claude/foundry/otel.env (KEY=value lines; keys as op:// references; read once per session).')
610    return lines.join('\n')
611  }
612  if (lastExport === null) {
613    lines.push('No Foundry turn exported yet this session.')
614    return lines.join('\n')
615  }
616  lines.push(`Last trace ${lastExport.traceId}: ${lastExport.status}.`)
617  const api = langfuseApiBase(tracing.config)
618  if (api === null || !lastExport.status.startsWith('HTTP 2')) return lines.join('\n')
619  const headers = Object.fromEntries(Object.entries(tracing.config.headers).filter(([name]) => name.toLowerCase() !== 'content-type'))
620  const found = await $.http.fetch(`${api}/traces/${lastExport.traceId}`, { headers }).catch(() => null)
621  if (found?.ok) {
622    let count = '?'
623    try {
624      const parsed = JSON.parse(found.text) as { observations?: unknown[] }
625      count = String(parsed.observations?.length ?? '?')
626    } catch {}
627    lines.push(`Langfuse has it: ${count} observations.`)
628  } else {
629    lines.push(`Langfuse lookup: ${found ? `HTTP ${found.status}` : 'failed'} (ingestion can take a few seconds; run /trace again).`)
630  }
631  return lines.join('\n')
632}
633
634async function askOperator($: EngineInterface, reason: string): Promise<boolean> {
635  try {
636    const answer = await $.ui.ask(`Approve Foundry mutation? ${reason}`, {
637      header: 'Foundry',
638      options: ['Approve', 'Decline'],
639    })
640    return answer === 'Approve'
641  } catch {
642    return false
643  }
644}
645
646// `notRun` is a failure Orthanc refused before reaching Foundry (a usage error);
647// any other failure may have changed something.
648async function serveTool($: EngineInterface, tool: string, input: Record<string, unknown>): Promise<{ out: EventResult<'tool.call'>; failed: boolean; notRun: boolean }> {
649  if (tool === ORTHANC_HELP) {
650    return { failed: false, notRun: false, out: {
651      result: await renderHelp($, {
652        group: asString(input.group).trim() || undefined,
653        command: asString(input.command).trim() || undefined,
654        query: asString(input.query).trim() || undefined,
655      }),
656    } }
657  }
658  const scope = await currentScope($)
659  const envelope = await executeCli($, {
660    command: normalizeCommand(asString(input.command)),
661    args: Array.isArray(input.args) ? input.args.map(String) : [],
662    profile: profileArg(scope),
663  })
664  const failed = isErrorEnvelope(envelope)
665  return { failed, notRun: failed && isUsageError(envelope), out: { result: serialize(envelope, await spill($, input.command, envelope)), ...(failed ? { context: ['The Orthanc call returned errors; read them before retrying.'] } : {}) } }
666}
667
668// Writes an oversized envelope where the model can read it whole; undefined when
669// it fits inline or the write fails (the cut text still carries the page token).
670async function spill($: EngineInterface, command: unknown, envelope: Envelope): Promise<string | undefined> {
671  if (!isOversized(envelope)) return undefined
672  const base = ((await $.env.get('TMPDIR')) || '/tmp').replace(/\/$/, '')
673  const path = `${base}/foundry-orthanc/${Date.now()}-${asString(command).trim().replace(/\W+/g, '-') || 'output'}.json`
674  try {
675    await $.fs.write(path, JSON.stringify(envelope, null, 2))
676    return path
677  } catch {
678    return undefined
679  }
680}
681
682// ---------- /fde ----------
683
684async function fdeState($: EngineInterface): Promise<FdeSession | null> {
685  return normalizeFde((await $.state.get(FDE)).value)
686}
687
688// The session's binding, mirrored to the store so the next session can offer /fde resume.
689// A new binding looks its RIDs up again: the namespace cache is the binding's.
690async function setFde($: EngineInterface, fde: FdeSession | null): Promise<void> {
691  spaceCache.clear()
692  await $.state.set(FDE, fde)
693  await $.state.set(BRANCH, fde?.branchRid ?? null)
694  await $.store.set('fdeOpen', fde)
695}
696
697async function fdeFromEarlier($: EngineInterface): Promise<FdeSession | null> {
698  return normalizeFde(await $.store.get('fdeOpen').catch(() => null))
699}
700
701// rid -> the namespace it is in, for the lookups of one binding. Only a
702// successful batch-get is cached, so a failed one is looked up again, and the
703// operator's answer to a failed check is never remembered.
704const spaceCache = new Map<string, string | null>()
705const SPACE_CACHE_MAX = 10_000
706
707function rememberSpaces(spaces: ReadonlyMap<string, string | null>): void {
708  for (const [rid, spaceRid] of spaces) {
709    // A folder batch-get did not return may exist by the next write: ask again, never remember it as missing.
710    if (spaceRid === null && rid.startsWith(COMPASS_FOLDER_RID)) continue
711    spaceCache.set(rid, spaceRid)
712    if (spaceCache.size <= SPACE_CACHE_MAX) continue
713    const oldest = spaceCache.keys().next().value
714    if (typeof oldest === 'string') spaceCache.delete(oldest)
715  }
716}
717
718/** While bound, the namespace in scope is the session's: nothing may move it. */
719const namespaceLocked = (fde: FdeSession) =>
720  `FDE mode (${fde.branchName}) holds this session to ${fde.namespace ? `namespace ${fde.namespace.name}` : 'no namespace'}; /fde end first.`
721
722/** `space list` as namespaces: rid, display name (or path) and path, each plain enough to show. */
723function spacesFrom(envelope: Envelope): FoundryNamespace[] {
724  return listItems(envelope, 'spaces').flatMap(entry => {
725    const rid = asString(entry.rid)
726    const path = asString(entry.path)
727    return rid === '' ? [] : [plainSpace({ rid, name: asString(entry.display_name) || path, path })]
728  })
729}
730
731const couldNotBind = (ontology: FoundryNamed, namespace: FoundryNamespace, why: string) =>
732  `Could not check that the ontology ${ontology.name} is in ${namespace.name} (${why}). FDE mode stays off; try /fde on again.`
733
734/** The RIDs a check could not place, first 20: what the ask and the refusal name. */
735const shownRids = (rids: readonly string[]) =>
736  rids.length <= 20 ? rids.join(', ') : `${rids.slice(0, 20).join(', ')} and ${rids.length - 20} more`
737
738/**
739 * Why a write names something outside the bound namespace, or null. A RID this
740 * session has not placed costs one batch-get, cached for the binding; a lookup
741 * that cannot run asks the operator rather than failing closed, and names what
742 * it could not check.
743 */
744async function namespaceCheck($: EngineInterface, fde: FdeSession, args: string[], texts: readonly string[]): Promise<string | null> {
745  const scanned = namespaceScan(fde, args, texts)
746  if ('deny' in scanned) return scanned.deny
747  const placed = new Map<string, string | null>()
748  const unchecked: string[] = []
749  const failures: string[] = []
750  for (const rid of scanned.lookup) {
751    if (spaceCache.has(rid)) placed.set(rid, spaceCache.get(rid) ?? null)
752  }
753  for (const argv of batchGetArgs(scanned.lookup.filter(rid => !spaceCache.has(rid)))) {
754    const envelope = await runOrthanc($, argv, fde.profile, 60_000)
755    if (isErrorEnvelope(envelope)) {
756      failures.push(errorsOf(envelope))
757      unchecked.push(...argv.slice(2))
758      continue
759    }
760    const spaces = spacesOf(envelope.data, argv.slice(2))
761    rememberSpaces(spaces)
762    for (const [rid, spaceRid] of spaces) placed.set(rid, spaceRid)
763  }
764  const denied = namespaceDeny(fde, placed)
765  if (denied !== null || failures.length === 0 || fde.namespace === null) return denied
766  const error = failures.join('; ')
767  const shown = shownRids(unchecked)
768  const answer = await $.ui
769    .ask(`FDE mode (${fde.branchName}): the namespace check could not run for ${shown} (${error}). Run this write anyway, unchecked against ${fde.namespace.name}?`, {
770      header: 'FDE',
771      options: ['Run unchecked', 'Do not run'],
772    })
773    .catch(() => null)
774  return answer === 'Run unchecked'
775    ? null
776    : `FDE mode (${fde.branchName}): the namespace check could not run for ${shown} (${error}), and the operator declined or could not be asked, so the call was not run.`
777}
778
779/**
780 * The global branch's name when it is an OPEN branch of the ontology, with the
781 * proposal open on it. Otherwise a reason, with `transient` set when the lookup
782 * failed rather than the branch being unfit, so a resume can keep the binding
783 * and try again.
784 */
785async function openBranch(
786  $: EngineInterface,
787  rid: string,
788  profile: string,
789  ontologyRid: string,
790): Promise<{ name: string; proposal: string | null } | { reason: string; transient: boolean }> {
791  const envelope = await runOrthanc($, ['global-branch', 'get', rid], profile, 60_000)
792  if (isErrorEnvelope(envelope)) return { reason: `global-branch get ${rid} failed: ${errorsOf(envelope)}`, transient: true }
793  const fit = adoptable(envelope.data, ontologyRid)
794  return typeof fit === 'string' ? { reason: fit, transient: false } : { name: fit.name, proposal: openProposal(envelope.data) }
795}
796
797// FDE mode: pin the call to the session's branch and hold each --apply to its
798// dry run. It only adds checks; the branch rule and the ladder still judge the
799// bound call. Returns the bound input and its plan, or why it is refused.
800const MAX_PINNED_FILE = 20_000_000
801type FdePlan = { signature: string; isApply: boolean; command: string; files: string[] }
802
803async function filesSignature(
804  $: EngineInterface,
805  fde: FdeSession,
806  command: string,
807  args: string[],
808  files: { required: string[]; optional: string[] },
809): Promise<{ signature: string; texts: string[] } | { deny: string }> {
810  const hashes: Record<string, string> = {}
811  const texts: string[] = []
812  for (const file of [...files.required, ...files.optional]) {
813    // Only regular files are read, and only up to a size, so a device or FIFO
814    // argument cannot hang the gate.
815    const stat = await $.fs.stat(file).catch(() => null)
816    if (stat !== null && stat.kind === 'file' && stat.size > MAX_PINNED_FILE) {
817      return { deny: `FDE mode: ${file} is over ${MAX_PINNED_FILE / 1_000_000} MB, too large to check against its dry run, so the call was not run.` }
818    }
819    const text = stat?.kind === 'file' ? await $.fs.read(file).then(String).catch(() => null) : null
820    if (text === null && files.required.includes(file)) return { deny: `FDE mode: could not read ${file} to check it against its dry run, so the call was not run.` }
821    if (text === null) continue
822    const foreign = foreignRids(fde, text)
823    if (foreign) return { deny: `FDE mode: ${foreign}` }
824    hashes[file] = await contentHash(text)
825    texts.push(text)
826  }
827  return { signature: planSignature(command, args, hashes), texts }
828}
829
830async function fdeGate(
831  $: EngineInterface,
832  fde: FdeSession,
833  input: Record<string, unknown>,
834  manifest: readonly ManifestCommand[],
835): Promise<{ deny: string } | { input: Record<string, unknown>; plan: FdePlan | null }> {
836  const resolved = resolveOrthancCommand(asString(input.command), Array.isArray(input.args) ? input.args.map(String) : [], manifest)
837  const isMutation = resolved.path !== '' && resolved.path !== 'repository clone' && classifyOrthancCommand(resolved.path, manifest) === 'mutation'
838  const bound = fdeBind(fde, resolved.path, resolved.args, (await currentScope($)).profile, isMutation)
839  if ('deny' in bound) return bound
840  const next = { ...input, command: resolved.path, args: bound.args }
841  if (!isMutation) return { input: next, plan: null }
842  const files = fileCandidates(bound.args, await sessionCwd($), await homeDir($))
843  const pinned = await filesSignature($, fde, resolved.path, bound.args, files)
844  if ('deny' in pinned) return pinned
845  const signature = pinned.signature
846  const isApply = hasApply(bound.args)
847  const gated = planGate(fde, signature, isApply)
848  if (gated) return { deny: gated }
849  const outside = await namespaceCheck($, fde, bound.args, pinned.texts)
850  if (outside !== null) return { deny: outside }
851  return { input: next, plan: { signature, isApply, command: resolved.path, files: [...files.required, ...files.optional] } }
852}
853
854// A /fde from one of these is the person's own typing: the terminal and Remote
855// Control. An SDK turn (`claude -p`, the Agent SDK), peers, relays, channels,
856// triggers and plugins are not (zay, 2026-10-21: "Not you").
857const PERSON_ORIGINS = new Set(['composer', 'bridge'])
858// Loose by design: a turn that carries no origin is nobody's.
859type CommandOrigin = { kind?: string }
860const isPerson = (origin: CommandOrigin | undefined) => PERSON_ORIGINS.has(origin?.kind ?? '')
861
862/** Why a resume of a branch FDE mode did not make is left to the person. */
863const notYourResume = (branchName: string, origin: CommandOrigin | undefined) =>
864  `Only you can resume FDE mode on a branch it did not make: type /fde resume yourself. This one came from ${
865    origin?.kind || 'an unknown source'
866  }, and ${branchName} is not an agent/ branch. FDE mode stays off.`
867
868/** Puts a namespace in one stored stack's scope, leaving the active stack alone. */
869async function storeNamespace($: EngineInterface, profile: string, namespace: FoundryNamespace | null): Promise<void> {
870  const stored = await storedScopes($)
871  const entry = normalizeScope(stored[profile], profile, '')
872  const next = entry.namespace?.rid === namespace?.rid ? entry : namespaceChanged(entry, namespace)
873  await $.store.set('scopes', { ...stored, [profile]: { ...next, updatedAt: new Date().toISOString() } })
874}
875
876async function fdeCommand($: EngineInterface, args: string, origin: CommandOrigin | undefined): Promise<string> {
877  const parsed = parseFdeArgs(args)
878  const active = await fdeState($)
879  const earlier = active ? null : await fdeFromEarlier($)
880  if (parsed.kind === 'error') return parsed.reason
881  if (parsed.kind === 'status') {
882    if (active) return fdeStatus(active)
883    return [
884      'FDE mode is off. /fde on (or /fde <goal>) creates an agent global branch on the selected ontology and binds this session to it; /fde --branch <rid> [goal] adopts an open one.',
885      ...(earlier ? [`An earlier session left ${earlier.branchName} (${goalLabel(earlier.goal)}) bound: /fde resume rebinds it, /fde end hands it off.`] : []),
886    ].join('\n')
887  }
888  if (parsed.kind === 'end') {
889    const ending = active ?? earlier
890    if (ending === null) return 'FDE mode is off.'
891    // Ending the mode ends the hold on it: the person's call alone.
892    if (!isPerson(origin)) {
893      return `Only you can end FDE mode: type /fde end yourself. This one came from ${
894        origin?.kind || 'an unknown source'
895      }, so ${active ? 'FDE mode stays on' : `${ending.branchName} stays bound for /fde resume`}.`
896    }
897    await setFde($, null)
898    const history = await $.store.get('fdeHandoffs').catch(() => null)
899    await $.store.set('fdeHandoffs', [...(Array.isArray(history) ? history : []), { ...ending, endedAt: new Date().toISOString() }].slice(-10))
900    return fdeHandoff(ending)
901  }
902  if (parsed.kind === 'goal') {
903    if (!active) return 'FDE mode is off, so there is no goal to set. /fde on starts it.'
904    const next = { ...active, goal: parsed.goal }
905    await setFde($, next)
906    return `Goal set.\n${fdeStatus(next)}`
907  }
908  if (parsed.kind === 'resume') {
909    if (active) return fdeStatus(active)
910    if (earlier === null) return 'No FDE branch to resume. /fde on starts one.'
911    // Only the person resumes a branch FDE mode did not make, as with /fde --branch.
912    if (!isAgentBranch(earlier.branchName) && !isPerson(origin)) return notYourResume(earlier.branchName, origin)
913    const open = await openBranch($, earlier.branchRid, earlier.profile, earlier.ontologyRid)
914    if ('reason' in open) {
915      if (open.transient) return `${open.reason} Not resumed; the earlier binding is kept, so /fde resume can try again.`
916      await $.store.set('fdeOpen', null)
917      return `${open.reason} Not resumed; the earlier binding is forgotten.`
918    }
919    if (!isAgentBranch(open.name) && !isPerson(origin)) return notYourResume(open.name, origin)
920    // The prompt must show what the resumed session is held to, not what was in
921    // scope while the mode was off. On another stack, only its own scope changes.
922    const bound = await currentScope($)
923    if (bound.profile === earlier.profile) {
924      if (bound.namespace?.rid !== earlier.namespace?.rid) await saveScope($, namespaceChanged(bound, earlier.namespace))
925    } else {
926      await storeNamespace($, earlier.profile, earlier.namespace)
927    }
928    await setFde($, earlier)
929    return `Resumed.\n${fdeStatus(earlier)}`
930  }
931  if (active) return `Already in FDE mode:\n${fdeStatus(active)}\n/fde end first.`
932  const scope = await currentScope($)
933  if (scope.profile === 'unknown') return 'No Foundry stack is active. Run /profile first.'
934  if (scope.ontology === null) return 'Choose the ontology first (/ontology): the branch is made on it.'
935  // With a namespace in scope, the session holds it: nothing is made until the
936  // ontology is in it, so a refused start leaves no branch behind.
937  const namespace = scope.namespace
938  let spaces: FoundryNamespace[] = []
939  if (namespace !== null) {
940    const listed = await runOrthanc($, ['space', 'list'], scope.profile, 60_000)
941    if (isErrorEnvelope(listed)) return couldNotBind(scope.ontology, namespace, `space list failed: ${errorsOf(listed)}`)
942    spaces = spacesFrom(listed)
943    const located = await runOrthanc($, ['resource', 'batch-get', scope.ontology.rid], scope.profile, 60_000)
944    if (isErrorEnvelope(located)) return couldNotBind(scope.ontology, namespace, `batch-get failed: ${errorsOf(located)}`)
945    const spaceRid = spacesOf(located.data, [scope.ontology.rid]).get(scope.ontology.rid) ?? null
946    if (spaceRid === null)
947      return `The ontology ${scope.ontology.name} is not in any namespace, so FDE mode cannot hold the session to ${namespace.name}. /namespace clear runs FDE mode without one. FDE mode stays off.`
948    if (spaceRid !== namespace.rid) {
949      const found = spaces.find(space => space.rid === spaceRid)
950      return `The ontology ${scope.ontology.name} is in ${found ? found.name : `another namespace (${spaceRid})`}, not ${namespace.name}, the namespace in scope. Choose an ontology in ${namespace.name} (/ontology) or another namespace (/namespace). FDE mode stays off.`
951    }
952  }
953  let branchRid: string
954  let branchName: string
955  let proposal: string | null = null
956  if (parsed.kind === 'start') {
957    branchName = fdeBranchName(parsed.goal, new Date())
958    const envelope = await runOrthanc($, branchCreateArgs(branchName, scope.ontology.rid, parsed.goal), scope.profile, 120_000)
959    const rid = branchRidFrom(envelope)
960    if (rid === null) return `global-branch create ${branchName} failed, so FDE mode stays off: ${errorsOf(envelope)}`
961    branchRid = rid
962  } else {
963    const open = await openBranch($, parsed.rid, scope.profile, scope.ontology.rid)
964    if ('reason' in open) return `${open.reason} FDE mode stays off.`
965    // Only the person binds the session to a branch FDE mode did not make; an
966    // agent/ branch is nobody else's, so it adopts from anywhere.
967    if (!isAgentBranch(open.name) && !isPerson(origin)) {
968      return `Only you can bind FDE mode to a branch it did not make: type /fde --branch ${parsed.rid} yourself. This one came from ${origin?.kind || 'an unknown source'}, and ${open.name} is not an agent/ branch. FDE mode stays off.`
969    }
970    branchRid = parsed.rid
971    branchName = open.name
972    proposal = open.proposal
973  }
974  const fde: FdeSession = {
975    goal: parsed.goal,
976    profile: scope.profile,
977    ontologyRid: scope.ontology.rid,
978    branchRid,
979    branchName,
980    startedAt: new Date().toISOString(),
981    plans: [],
982    applied: [],
983    namespace: scope.namespace,
984    spaces,
985  }
986  await setFde($, fde)
987  return [
988    fdeStatus(fde),
989    ...(proposal ? [`It has an open proposal (${proposal}): every write here changes what its reviewers see.`] : []),
990    'Ontology writes in this session now go to this branch only, and each --apply needs its dry run first.',
991  ].join('\n')
992}
993
994// ---------- pickers ----------
995
996type Source = { title: string; isMulti: boolean; items: FoundryPickItem[]; resourceKind?: FoundryResourceKind }
997type PickerOptions = { resourceKind?: FoundryResourceKind; chain?: FoundryPickerKind[] }
998
999const toItems = (resources: readonly FoundryResource[]): FoundryPickItem[] =>
1000  resources.map(entry => ({ key: entry.rid, label: entry.name, hint: entry.hint }))
1001
1002async function inBatches<T, R>(values: readonly T[], size: number, run: (value: T) => Promise<R>): Promise<R[]> {
1003  const out: R[] = []
1004  for (let index = 0; index < values.length; index += size) out.push(...(await Promise.all(values.slice(index, index + size).map(run))))
1005  return out
1006}
1007
1008/** Compass resources of one kind under the selected projects, or every visible project. */
1009async function compassSource($: EngineInterface, scope: FoundryScope, kind: CompassKind, query: string): Promise<Source | string> {
1010  const def = COMPASS_KINDS[kind]
1011  let roots = scope.projects.map(project => project.rid)
1012  if (roots.length === 0) {
1013    const projects = await runOrthanc($, ['project', 'list', ...spaceArgs(scope)], scope.profile, 120_000)
1014    if (isErrorEnvelope(projects)) return `project list failed: ${errorsOf(projects)}`
1015    roots = listItems(projects, 'projects').map(entry => asString(entry.rid)).filter(Boolean)
1016  }
1017  if (roots.length === 0) return `No projects are visible ${scope.namespace ? `in ${scope.namespace.name}` : 'on this stack'}. No selection was saved.`
1018  const search = kind === 'folders' && !query.trim() ? 'ri.compass.main.folder.' : query
1019  const envelopes = await inBatches(roots, ROOT_CONCURRENCY, root =>
1020    runOrthanc($, resourceArgs(search, def.typeId, root), scope.profile, 180_000),
1021  )
1022  const failed = envelopes.filter(isErrorEnvelope)
1023  if (failed.length === envelopes.length && failed[0]) return `resource listing failed: ${errorsOf(failed[0])}`
1024  const rows = resourceRows(envelopes.flatMap(envelope => rowsOf(envelope, ['resources'])))
1025  return {
1026    title: `${def.label}${scope.projects.length > 0 ? ' in selected projects' : scope.namespace ? ` in ${scope.namespace.name}` : ''}`,
1027    isMulti: true,
1028    items: toItems(rows),
1029    resourceKind: kind,
1030  }
1031}
1032
1033async function pickerSource(
1034  $: EngineInterface,
1035  kind: FoundryPickerKind,
1036  scope: FoundryScope,
1037  query: string,
1038  resourceKind?: FoundryResourceKind,
1039): Promise<Source | string> {
1040  if (kind === 'profile') {
1041    const profiles = await listProfiles($)
1042    return {
1043      title: 'Foundry stack',
1044      isMulti: false,
1045      items: profiles.map(profile => ({
1046        key: profile.name,
1047        label: profile.name,
1048        hint: [profile.host, profile.status, profile.name === scope.profile ? 'active' : ''].filter(Boolean).join(' · '),
1049      })),
1050    }
1051  }
1052  if (scope.profile === 'unknown') return 'No Foundry stack is active. Run /profile first.'
1053  if (kind === 'resource') {
1054    if (resourceKind && resourceKind in COMPASS_KINDS) return compassSource($, scope, resourceKind as CompassKind, query)
1055    return 'This resource kind has no listing; use its lookup command.'
1056  }
1057  if (kind === 'namespace') {
1058    const envelope = await runOrthanc($, ['space', 'list'], scope.profile, 60_000)
1059    if (isErrorEnvelope(envelope)) return `space list failed: ${errorsOf(envelope)}`
1060    const rows = spacesFrom(envelope).map(space => ({ key: space.rid, label: space.name, hint: space.path }))
1061    if (rows.length === 0) return 'No namespaces are visible on this stack. No selection was saved.'
1062    return {
1063      title: 'Namespace',
1064      isMulti: false,
1065      items: [{ key: '', label: 'All namespaces', hint: 'no namespace in scope' }, ...rows],
1066    }
1067  }
1068  if (kind === 'ontology') {
1069    const envelope = await runOrthanc($, ['ontology', 'list'], scope.profile, 60_000)
1070    if (isErrorEnvelope(envelope)) return `ontology list failed: ${errorsOf(envelope)}`
1071    return {
1072      title: 'Ontology',
1073      isMulti: false,
1074      items: listItems(envelope, 'data').map(entry => ({
1075        key: asString(entry.rid),
1076        label: asString(entry.display_name) || asString(entry.api_name),
1077        hint: asString(entry.rid),
1078      })),
1079    }
1080  }
1081  if (kind === 'project') {
1082    const envelope = await runOrthanc($, ['project', 'list', ...spaceArgs(scope)], scope.profile, 120_000)
1083    if (isErrorEnvelope(envelope)) return `project list failed: ${errorsOf(envelope)}`
1084    return {
1085      title: scope.namespace ? `Projects in ${scope.namespace.name}` : 'Projects',
1086      isMulti: true,
1087      items: listItems(envelope, 'projects').map(entry => ({
1088        key: asString(entry.rid),
1089        label: asString(entry.display_name) || asString(entry.name),
1090        hint: asString(entry.path),
1091      })),
1092    }
1093  }
1094  if (scope.ontology === null) return 'No ontology is selected. Run /ontology first.'
1095  const isAction = kind === 'action-type'
1096  const envelope = await runOrthanc(
1097    $,
1098    ['ontology', isAction ? 'action-type-list' : 'object-type-list', scope.ontology.rid],
1099    scope.profile,
1100    120_000,
1101  )
1102  if (isErrorEnvelope(envelope)) return `${isAction ? 'action' : 'object'}-type-list failed: ${errorsOf(envelope)}`
1103  return {
1104    title: isAction ? 'Action types' : 'Object types',
1105    isMulti: true,
1106    items: listItems(envelope, isAction ? 'action_types' : 'object_types').map(entry => ({
1107      key: asString(entry.api_name),
1108      label: asString(entry.display_name) || asString(entry.api_name),
1109      hint: asString(entry.api_name),
1110    })),
1111  }
1112}
1113
1114async function applyPick($: EngineInterface, picker: FoundryPicker, keys: readonly string[]): Promise<string> {
1115  const scope = await currentScope($)
1116  const chosen = picker.items.filter(item => keys.includes(item.key))
1117  if (picker.kind === 'profile') {
1118    const profile = (await listProfiles($)).find(entry => entry.name === chosen[0]?.key)
1119    if (profile === undefined) return 'No stack selected.'
1120    const next = await activateProfile($, profile)
1121    return `Foundry stack: ${next.profile}${next.ontology ? `, ontology ${next.ontology.name}` : ''}.`
1122  }
1123  if (picker.kind === 'ontology') {
1124    const pick = chosen[0]
1125    if (pick === undefined) return 'No ontology selected.'
1126    await saveScope($, ontologyChanged(scope, { rid: pick.key, name: pick.label }))
1127    return `Ontology: ${pick.label}. Projects, types, functions and object instances were cleared.`
1128  }
1129  if (picker.kind === 'namespace') {
1130    const bound = await fdeState($)
1131    if (bound !== null) return namespaceLocked(bound)
1132    const pick = chosen[0]
1133    if (pick === undefined) return 'No namespace selected.'
1134    if (pick.key === '') {
1135      await saveScope($, namespaceChanged(scope, null))
1136      return 'All namespaces: no namespace in scope.'
1137    }
1138    const next = namespaceChanged(scope, { rid: pick.key, name: pick.label, path: pick.hint })
1139    await saveScope($, next)
1140    const dropped = next.projects.length !== scope.projects.length || JSON.stringify(next.resources) !== JSON.stringify(scope.resources)
1141    return `Namespace: ${pick.label}.${dropped ? ' Projects and Compass resources picked before were cleared.' : ''}`
1142  }
1143  if (picker.kind === 'project') {
1144    await saveScope($, { ...scope, projects: chosen.map(item => ({ rid: item.key, name: item.label })) })
1145    return `Projects: ${chosen.map(item => item.label).join(', ') || 'none'}.`
1146  }
1147  if (picker.kind === 'resource' && picker.resourceKind) {
1148    const kind = picker.resourceKind
1149    const asResource = (item: FoundryPickItem): FoundryResource => ({ rid: item.key, name: item.label, hint: item.hint })
1150    const merged = mergeSelections(scope.resources[kind] ?? [], chosen.map(asResource), picker.items.map(asResource))
1151    await saveScope($, { ...scope, resources: { ...scope.resources, [kind]: merged } })
1152    return `${RESOURCE_LABELS[kind]}: ${merged.map(entry => entry.name).join(', ') || 'none'}.`
1153  }
1154  const key = picker.kind === 'action-type' ? 'actionTypes' : 'objectTypes'
1155  await saveScope($, { ...scope, [key]: chosen.map(item => ({ apiName: item.key, displayName: item.label })) })
1156  return `${picker.title}: ${chosen.map(item => item.label).join(', ') || 'none'}.`
1157}
1158
1159const matches = (item: FoundryPickItem, filter: string) => {
1160  const haystack = `${item.label} ${item.hint} ${item.key}`.toLowerCase()
1161  return filter.toLowerCase().split(/\s+/).filter(Boolean).every(term => haystack.includes(term))
1162}
1163
1164function preselected(scope: FoundryScope, kind: FoundryPickerKind, resourceKind?: FoundryResourceKind): string[] {
1165  if (kind === 'project') return scope.projects.map(project => project.rid)
1166  if (kind === 'object-type') return scope.objectTypes.map(type => type.apiName)
1167  if (kind === 'action-type') return scope.actionTypes.map(type => type.apiName)
1168  if (kind === 'resource' && resourceKind) return (scope.resources[resourceKind] ?? []).map(entry => entry.rid)
1169  return []
1170}
1171
1172/** Opens the picker pane on `source`, or answers in text where no pane can be placed. */
1173async function openPicker($: EngineInterface, kind: FoundryPickerKind, source: Source, query: string, chain: FoundryPickerKind[]): Promise<string> {
1174  const scope = await currentScope($)
1175  if (source.items.length === 0) return `No ${source.title.toLowerCase()} found. No selection was saved.`
1176  const picker: FoundryPicker = {
1177    kind,
1178    ...(source.resourceKind ? { resourceKind: source.resourceKind } : {}),
1179    title: source.title,
1180    isMulti: source.isMulti,
1181    items: source.items,
1182    chosen: preselected(scope, kind, source.resourceKind),
1183    filter: kind === 'resource' ? '' : query,
1184    chain,
1185  }
1186  const filtered = source.items.filter(item => matches(item, picker.filter))
1187  const only = filtered.length === 1 ? filtered[0] : undefined
1188  if (query !== '' && only) return applyPick($, picker, [...new Set([...picker.chosen, only.key])])
1189  await $.state.set(PICKER, picker)
1190  const opened = await $.ui.open({ id: PANE, title: source.title, focus: true, closeOnEscape: true })
1191  if (!opened.isPlaced) {
1192    await $.state.set(PICKER, null)
1193    const lines = filtered.slice(0, 20).map(item => `- ${item.label}  (${item.hint || item.key})`)
1194    return [`${filtered.length} ${source.title.toLowerCase()}; widen the terminal for the picker, or narrow the command with a filter.`, ...lines].join('\n')
1195  }
1196  return `Choose ${source.title.toLowerCase()} in the picker (type to filter, Enter or a click selects, Esc cancels).`
1197}
1198
1199async function runPicker($: EngineInterface, kind: FoundryPickerKind, args: string, options: PickerOptions = {}): Promise<string> {
1200  const scope = await currentScope($)
hooks/catalog.ts 399 lines
1// Pure: the slash-command table (one name per resource), scope shape and edits,
2// resource rows, the prompt block and the /foundry context tree.
3// Everything that runs orthanc stays in register.tsx, where `$` lives.
4
5import type {
6  FoundryNamed,
7  FoundryNamespace,
8  FoundryObjectType,
9  FoundryPickerKind,
10  FoundryResource,
11  FoundryResourceKind,
12  FoundryScope,
13} from '../types'
14import { isRecord } from './orthanc'
15import { plainSpace } from './fde'
16
17/** Compass resource kinds orthanc lists with `resource list|search --type`. */
18export const COMPASS_KINDS = {
19  folders: { label: 'Folders', typeId: 'COMPASS_FOLDER' },
20  datasets: { label: 'Datasets', typeId: 'FOUNDRY_DATASET' },
21  mediaSets: { label: 'Media sets', typeId: 'MIO_MEDIA_SET' },
22  repositories: { label: 'Repositories', typeId: 'STEMMA_REPOSITORY' },
23  contourAnalyses: { label: 'Contour analyses', typeId: 'CONTOUR_ANALYSIS' },
24  sources: { label: 'Sources', typeId: 'MAGRITTE_SOURCE' },
25  developerConsoles: { label: 'Developer Console', typeId: 'THIRD_PARTY_APPLICATIONS_APPLICATION' },
26  aipChatbots: { label: 'AIP chatbots', typeId: 'AIP_AGENTS_AGENT' },
27} as const
28export type CompassKind = keyof typeof COMPASS_KINDS
29
30export const RESOURCE_LABELS: Record<FoundryResourceKind, string> = {
31  ...Object.fromEntries(Object.entries(COMPASS_KINDS).map(([kind, def]) => [kind, def.label])),
32  mediaItems: 'Media items',
33  objectInstances: 'Object instances',
34  functions: 'Functions',
35  languageModels: 'Language models',
36  permissions: 'Permissions',
37  searchResults: 'Search results',
38} as Record<FoundryResourceKind, string>
39
40/** Resource kinds that belong to the ontology and go when it changes. */
41const ONTOLOGY_KINDS: readonly FoundryResourceKind[] = ['objectInstances', 'functions']
42
43/** Resource kinds addressed by a Compass path, so they go when the namespace changes. */
44const NAMESPACE_KINDS: readonly FoundryResourceKind[] = [
45  ...(Object.keys(COMPASS_KINDS) as CompassKind[]),
46  'mediaItems',
47  'permissions',
48  'searchResults',
49]
50
51export type Lookup = 'media-item' | 'objects' | 'function' | 'language-model' | 'permission' | 'search'
52
53export type CommandAction =
54  | { type: 'picker'; kind: Exclude<FoundryPickerKind, 'resource'> }
55  | { type: 'resource'; kind: CompassKind }
56  | { type: 'lookup'; lookup: Lookup; kind: FoundryResourceKind }
57  | { type: 'blocked'; bead: string; what: string }
58  | { type: 'open' | 'onboard' | 'auth' | 'scope' | 'approval' | 'mcp-status' | 'foundry' | 'trace' | 'fde' }
59
60export type CommandEntry = { name: string; description: string; argumentHint?: string; action: CommandAction }
61
62const CLEARABLE = '[filter | clear]'
63const LINK_BEAD = 'orthanc-ra6'
64const LISTING_BEAD = 'orthanc-qm5'
65export const OBJECT_QUERY_BEAD = 'orthanc-4f7'
66
67const picker = (name: string, kind: Exclude<FoundryPickerKind, 'resource'>, description: string): CommandEntry => ({
68  name,
69  description,
70  argumentHint: kind === 'profile' ? '[name]' : CLEARABLE,
71  action: { type: 'picker', kind },
72})
73const resource = (name: string, kind: CompassKind): CommandEntry => ({
74  name,
75  description: `Choose ${COMPASS_KINDS[kind].label.toLowerCase()} in scope`,
76  argumentHint: CLEARABLE,
77  action: { type: 'resource', kind },
78})
79const blocked = (name: string, what: string, bead: string): CommandEntry =>
80  ({ name, description: `Choose ${what} (waits on orthanc ${bead})`, action: { type: 'blocked', bead, what } })
81
82export const COMMAND_TABLE: readonly CommandEntry[] = [
83  { name: 'foundry', description: 'Show the Foundry resources in context (like /context, for Palantir)', action: { type: 'foundry' } },
84  { name: 'open', description: 'Set working context: stack, then ontology, namespace and projects', action: { type: 'open' } },
85  { name: 'onboard', description: 'Check Foundry setup: orthanc, stack, credentials, context', action: { type: 'onboard' } },
86  { name: 'auth', description: 'Show how to authenticate a Foundry stack', argumentHint: '[profile]', action: { type: 'auth' } },
87  picker('profile', 'profile', 'Choose the Foundry stack (orthanc profile)'),
88  picker('ontology', 'ontology', 'Choose the active Foundry ontology'),
89  picker('namespace', 'namespace', 'Choose the Compass namespace (space) in scope'),
90  picker('project', 'project', 'Choose the Foundry projects in scope'),
91  picker('object-type', 'object-type', 'Choose the ontology object types in scope'),
92  picker('action-type', 'action-type', 'Choose the ontology action types in scope'),
93  blocked('link-type', 'ontology link types', LINK_BEAD),
94  blocked('interface', 'ontology interfaces', LINK_BEAD),
95  resource('folder', 'folders'),
96  resource('dataset', 'datasets'),
97  resource('media-set', 'mediaSets'),
98  resource('repository', 'repositories'),
99  resource('contour', 'contourAnalyses'),
100  resource('source', 'sources'),
101  resource('developer-console', 'developerConsoles'),
102  resource('aip-chatbot', 'aipChatbots'),
103  blocked('egress-policy', 'egress policies', LISTING_BEAD),
104  blocked('certificate', 'certificates', LISTING_BEAD),
105  blocked('automation', 'automations', LISTING_BEAD),
106  {
107    name: 'media-item',
108    description: 'Add a media item by media-set RID and item path or RID',
109    argumentHint: '<media-set-rid> <path|rid> | clear',
110    action: { type: 'lookup', lookup: 'media-item', kind: 'mediaItems' },
111  },
112  {
113    name: 'objects',
114    description: 'Search object instances of the selected object types',
115    argumentHint: '<property>=<text> | clear',
116    action: { type: 'lookup', lookup: 'objects', kind: 'objectInstances' },
117  },
118  {
119    name: 'function',
120    description: 'Search Foundry functions and add them to context',
121    argumentHint: '<query> | clear',
122    action: { type: 'lookup', lookup: 'function', kind: 'functions' },
123  },
124  {
125    name: 'language-model',
126    description: 'Choose the stack language models in context',
127    argumentHint: CLEARABLE,
128    action: { type: 'lookup', lookup: 'language-model', kind: 'languageModels' },
129  },
130  {
131    name: 'permission',
132    description: 'Inspect role grants on a resource and add them to context',
133    argumentHint: '<resource-rid> | clear',
134    action: { type: 'lookup', lookup: 'permission', kind: 'permissions' },
135  },
136  {
137    name: 'search',
138    description: 'Search Foundry resource titles across the stack',
139    argumentHint: '<text> | clear',
140    action: { type: 'lookup', lookup: 'search', kind: 'searchResults' },
141  },
142  { name: 'scope', description: 'Show the Foundry context; `clear` resets it, `ontology` re-picks it', argumentHint: '[show | clear | ontology]', action: { type: 'scope' } },
143  { name: 'approval', description: 'Show or set the Foundry approval mode, or show the guard rules', argumentHint: '[mode|rules]', action: { type: 'approval' } },
144  {
145    name: 'fde',
146    description: 'FDE mode: bind this session to one global branch (a new agent one, or one you adopt); writes plan before they apply',
147    argumentHint: 'on | <goal> | goal <text> | --branch <rid> [goal] | resume | end',
148    action: { type: 'fde' },
149  },
150  { name: 'trace', description: 'Show trace export status (Langfuse/OTLP) and check the last Foundry trace landed', action: { type: 'trace' } },
151  { name: 'mcp-status', description: 'Show Orthanc and Foundry stack status', action: { type: 'mcp-status' } },
152]
153
154export const blockedText = (what: string, bead: string) =>
155  `Orthanc cannot list ${what} yet, so this command is waiting on bead ${bead} ` +
156  `in the orthanc tracker. It does not fall back to Foundry REST.`
157
158// ---------- scope ----------
159
160const asString = (value: unknown) => (typeof value === 'string' ? value : '')
161
162const named = (value: unknown): FoundryNamed | null =>
163  isRecord(value) && typeof value.rid === 'string' ? { rid: value.rid, name: asString(value.name) || value.rid } : null
164
165const namespaceOf = (value: unknown): FoundryNamespace | null =>
166  isRecord(value) && typeof value.rid === 'string'
167    ? plainSpace({ rid: value.rid, name: asString(value.name) || value.rid, path: asString(value.path) })
168    : null
169
170const types = (value: unknown): FoundryObjectType[] =>
171  Array.isArray(value)
172    ? value.filter(isRecord).flatMap(entry =>
173        typeof entry.apiName === 'string'
174          ? [{ apiName: entry.apiName, displayName: asString(entry.displayName) || entry.apiName, ...(typeof entry.rid === 'string' ? { rid: entry.rid } : {}) }]
175          : [],
176      )
177    : []
178
179const resourcesOf = (value: unknown): FoundryResource[] =>
180  Array.isArray(value)
181    ? value.filter(isRecord).flatMap(entry =>
182        typeof entry.rid === 'string' ? [{ rid: entry.rid, name: asString(entry.name) || entry.rid, hint: asString(entry.hint) }] : [],
183      )
184    : []
185
186export const emptyScope = (profile: string, host: string): FoundryScope => ({
187  profile,
188  host,
189  ontology: null,
190  namespace: null,
191  projects: [],
192  objectTypes: [],
193  actionTypes: [],
194  resources: {},
195  updatedAt: new Date().toISOString(),
196})
197
198/** Any stored value (v0.1 scopes included) as a whole FoundryScope. */
199export function normalizeScope(value: unknown, profile: string, host: string): FoundryScope {
200  if (!isRecord(value)) return emptyScope(profile, host)
201  const resources: FoundryScope['resources'] = {}
202  if (isRecord(value.resources)) {
203    for (const kind of Object.keys(RESOURCE_LABELS) as FoundryResourceKind[]) {
204      const list = resourcesOf(value.resources[kind])
205      if (list.length > 0) resources[kind] = list
206    }
207  }
208  return {
209    profile: asString(value.profile) || profile,
210    host: asString(value.host) || host,
211    ontology: named(value.ontology),
212    namespace: namespaceOf(value.namespace),
213    projects: Array.isArray(value.projects) ? value.projects.map(named).filter((entry): entry is FoundryNamed => entry !== null) : [],
214    objectTypes: types(value.objectTypes),
215    actionTypes: types(value.actionTypes),
216    resources,
217    updatedAt: asString(value.updatedAt) || new Date().toISOString(),
218  }
219}
220
221export function ontologyChanged(scope: FoundryScope, ontology: FoundryNamed | null): FoundryScope {
222  const resources = { ...scope.resources }
223  for (const kind of ONTOLOGY_KINDS) resources[kind] = []
224  return { ...scope, ontology, projects: [], objectTypes: [], actionTypes: [], resources }
225}
226
227/** A different namespace drops what was picked under the old one; clearing or re-picking keeps it. */
228export function namespaceChanged(scope: FoundryScope, namespace: FoundryNamespace | null): FoundryScope {
229  if (namespace === null || namespace.rid === scope.namespace?.rid) return { ...scope, namespace }
230  const resources = { ...scope.resources }
231  for (const kind of NAMESPACE_KINDS) resources[kind] = []
232  return { ...scope, namespace, projects: [], resources }
233}
234
235// ---------- orthanc rows ----------
236
237export function resourceArgs(query: string, typeId: string, root: string): string[] {
238  const trimmed = query.trim()
239  return [...(trimmed ? ['resource', 'search', trimmed] : ['resource', 'list']), '--type', typeId, '--folder-rid', root]
240}
241
242/** orthanc rows as resources: RID required, first RID wins. */
243export function resourceRows(rows: readonly Record<string, unknown>[], hintKeys: readonly string[] = ['path', 'type']): FoundryResource[] {
244  const seen = new Set<string>()
245  return rows.flatMap(row => {
246    const rid = asString(row.rid) || asString(row.__rid) || asString(row.api_name) || asString(row.apiName)
247    if (!rid || seen.has(rid)) return []
248    seen.add(rid)
249    const name =
250      asString(row.display_name) || asString(row.displayName) || asString(row.name) || asString(row.__title) || asString(row.api_name) || rid
251    const hint = hintKeys.map(key => row[key]).map(value => (isRecord(value) ? asString(value.name) : asString(value))).find(Boolean) ?? ''
252    return [{ rid, name, hint }]
253  })
254}
255
256/** The new selection, plus earlier selections the listing did not show. */
257export function mergeSelections(
258  existing: readonly FoundryResource[],
259  selected: readonly FoundryResource[],
260  visible: readonly FoundryResource[],
261): FoundryResource[] {
262  const shown = new Set(visible.map(entry => entry.rid))
263  return [...existing.filter(entry => !shown.has(entry.rid)), ...selected]
264}
265
266export function objectsQuery(args: string): { property: string; text: string } | null {
267  const match = /^\s*([A-Za-z_][\w.]*)\s*=\s*(.+?)\s*$/.exec(args)
268  return match?.[1] && match[2] ? { property: match[1], text: match[2] } : null
269}
270
271// ---------- prompt block ----------
272
273const list = (entries: readonly FoundryResource[]) => entries.map(entry => `${entry.name} (${entry.rid})`).join(', ')
274
275export function contextLines(scope: FoundryScope): string[] {
276  const lines: string[] = []
277  if (scope.ontology) lines.push(`Ontology: ${scope.ontology.name} (${scope.ontology.rid}).`)
278  if (scope.namespace) {
279    // A RID standing in for a path that is not plain is no path to search under.
280    const path = scope.namespace.path.startsWith('/') ? scope.namespace.path : ''
281    lines.push(`Namespace: ${scope.namespace.name} (${scope.namespace.rid})${path ? `, path ${path}` : ''}.`)
282    lines.push(
283      `Keep Compass work inside it: pass --space-rid ${scope.namespace.rid} to project list and project search` +
284        `${path ? `, --path-prefix ${path} to search` : ''}, and list or search resources under its projects.`,
285    )
286  }
287  if (scope.projects.length > 0) {
288    lines.push(`Projects: ${scope.projects.map(project => `${project.name} (${project.rid})`).join(', ')}.`)
289    lines.push('Keep project discovery within the selected project subtrees.')
290  }
291  if (scope.objectTypes.length > 0) {
292    lines.push(`Object types: ${scope.objectTypes.map(type => `${type.displayName} (${type.apiName})`).join(', ')}.`)
293  }
294  if (scope.actionTypes.length > 0) {
295    lines.push(`Action types: ${scope.actionTypes.map(type => `${type.displayName} (${type.apiName})`).join(', ')}.`)
296  }
297  for (const [kind, label] of Object.entries(RESOURCE_LABELS) as [FoundryResourceKind, string][]) {
298    const entries = scope.resources[kind] ?? []
299    if (entries.length > 0) lines.push(`${label}: ${list(entries)}.`)
300  }
301  return lines
302}
303
304export const hasFocus = (scope: FoundryScope) =>
305  scope.ontology !== null || scope.namespace !== null || scope.projects.length > 0 || Object.values(scope.resources).some(entries => (entries?.length ?? 0) > 0)
306
307// ---------- /foundry tree ----------
308
309export type ClearTarget =
310  | { type: 'ontology' | 'namespace' }
311  | { type: 'projects' | 'objectTypes' | 'actionTypes' }
312  | { type: 'resource'; kind: FoundryResourceKind }
313  | { type: 'item'; section: 'projects' | 'objectTypes' | 'actionTypes'; key: string }
314  | { type: 'resource-item'; kind: FoundryResourceKind; rid: string }
315
316export type TreeNode = { id: string; label: string; detail: string; count: number; command: string; clear?: ClearTarget; children: TreeNode[] }
317
318const leaf = (id: string, label: string, detail: string, clear: ClearTarget): TreeNode => ({ id, label, detail, count: 0, command: '', clear, children: [] })
319
320const COMMAND_FOR: Record<FoundryResourceKind, string> = {
321  folders: '/folder',
322  datasets: '/dataset',
323  mediaSets: '/media-set',
324  mediaItems: '/media-item',
325  repositories: '/repository',
326  contourAnalyses: '/contour',
327  sources: '/source',
328  developerConsoles: '/developer-console',
329  aipChatbots: '/aip-chatbot',
330  objectInstances: '/objects',
331  functions: '/function',
332  languageModels: '/language-model',
333  permissions: '/permission',
334  searchResults: '/search',
335}
336
337/** The sections that hold something, top-level, in reading order. */
338export function foundryTree(scope: FoundryScope): TreeNode[] {
339  const nodes: TreeNode[] = []
340  if (scope.ontology) {
341    nodes.push({ id: 'ontology', label: 'Ontology', detail: scope.ontology.name, count: 1, command: '/ontology', clear: { type: 'ontology' }, children: [] })
342  }
343  if (scope.namespace) {
344    nodes.push({ id: 'namespace', label: 'Namespace', detail: scope.namespace.name, count: 1, command: '/namespace', clear: { type: 'namespace' }, children: [] })
345  }
346  const typed = (id: 'projects' | 'objectTypes' | 'actionTypes', label: string, command: string, entries: { key: string; label: string; detail: string }[]) => {
347    if (entries.length === 0) return
348    nodes.push({
349      id,
350      label,
351      detail: '',
352      count: entries.length,
353      command,
354      clear: { type: id },
355      children: entries.map(entry => leaf(`${id}:${entry.key}`, entry.label, entry.detail, { type: 'item', section: id, key: entry.key })),
356    })
357  }
358  typed('projects', 'Projects', '/project', scope.projects.map(project => ({ key: project.rid, label: project.name, detail: project.rid })))
359  typed('objectTypes', 'Object types', '/object-type', scope.objectTypes.map(type => ({ key: type.apiName, label: type.displayName, detail: type.apiName })))
360  typed('actionTypes', 'Action types', '/action-type', scope.actionTypes.map(type => ({ key: type.apiName, label: type.displayName, detail: type.apiName })))
361  for (const [kind, label] of Object.entries(RESOURCE_LABELS) as [FoundryResourceKind, string][]) {
362    const entries = scope.resources[kind] ?? []
363    if (entries.length === 0) continue
364    nodes.push({
365      id: `resource:${kind}`,
366      label,
367      detail: '',
368      count: entries.length,
369      command: COMMAND_FOR[kind],
370      clear: { type: 'resource', kind },
371      children: entries.map(entry => leaf(`${kind}:${entry.rid}`, entry.name, entry.hint || entry.rid, { type: 'resource-item', kind, rid: entry.rid })),
372    })
373  }
374  return nodes
375}
376
377export function applyClear(scope: FoundryScope, target: ClearTarget): FoundryScope {
378  switch (target.type) {
379    case 'ontology':
380      return ontologyChanged(scope, null)
381    case 'namespace':
382      return namespaceChanged(scope, null)
383    case 'projects':
384    case 'objectTypes':
385    case 'actionTypes':
386      return { ...scope, [target.type]: [] }
387    case 'resource':
388      return { ...scope, resources: { ...scope.resources, [target.kind]: [] } }
389    case 'resource-item':
390      return {
391        ...scope,
392        resources: { ...scope.resources, [target.kind]: (scope.resources[target.kind] ?? []).filter(entry => entry.rid !== target.rid) },
393      }
394    case 'item':
395      if (target.section === 'projects') return { ...scope, projects: scope.projects.filter(entry => entry.rid !== target.key) }
396      return { ...scope, [target.section]: scope[target.section].filter(entry => entry.apiName !== target.key) }
397  }
398}
399
hooks/fde.ts 472 lines
1// FDE mode (/fde): one session, one goal, one global branch (an agent/ one it
2// made, or one the person adopted), and the namespace in scope, if any. Pure
3// functions, shared by the hooks and the tests. The mode only adds checks: the
4// branch rule, the ladder and the destructive rule run as they do without it.
5//
6// While bound:
7//  - every ontology write is pinned to the session's global branch (injected
8//    when the call names none, refused when it names another);
9//  - no global-branch or proposal changes (but add-repo on the bound branch):
10//    closing or merging is the operator's;
11//  - --apply runs only after a clean dry run of the same call, with every file
12//    it reads pinned by SHA-256; each dry run licenses one apply;
13//  - when a namespace is bound, every resource a write names, in its arguments
14//    or the files it reads, must be in it (reads may look anywhere).
15
16import type { FdeSession, FoundryNamespace } from '../types'
17import { isRecord } from './orthanc'
18import { BRANCH_FLAGS, flagValues, requiresBranch, unquote, validateBranchName } from './policy'
19
20const PREFIX = 'agent/fde-'
21const NAME_MAX = 64
22const GOAL_MAX = 200
23const RECORD_MAX = 50
24const GLOBAL_BRANCH = /^ri\.branch\.\.branch\.[A-Za-z0-9-]+$/
25const PROPOSAL_RID = /^ri\.branch\.\.proposal\.[A-Za-z0-9-]+$/
26// A display name safe to show: one plain branch name, no spaces, quotes or control characters.
27const PLAIN_NAME = /^[A-Za-z0-9][A-Za-z0-9._/-]{0,99}$/
28const FOREIGN_LINE = 'not an agent/ branch: FDE mode adopted it, and others may have work on it'
29const GLOBAL_BRANCH_ANY = /ri\.branch\.\.branch\.[A-Za-z0-9-]+/g
30const ONTOLOGY_RID = /ri\.ontology\.main\.ontology\.[A-Za-z0-9-]+/g
31// Any Compass resource RID: RIDs a mutation names go to batch-get for their namespace.
32const RESOURCE_RID = /ri\.[a-z0-9-]+\.[a-z0-9-]*\.[a-z0-9-]+\.[A-Za-z0-9-]+/g
33// A quoted path in a file the call reads: an unquoted word in prose is not a path.
34const QUOTED_PATH = /(?:"[^"\n]*"|'[^'\n]*')/g
35// A path right after a quote: what a decoded double encoding leaves when its quotes no longer pair.
36const QUOTE_OPENED_PATH = /["'](\/[^"'\n]*)/g
37const BRANCH_RID_PREFIX = 'ri.branch.'
38// A Compass folder RID: what `resource batch-get` may leave out, and what a write must then place.
39export const COMPASS_FOLDER_RID = 'ri.compass.main.folder.'
40const BATCH_MAX = 1000
41// Flags that could be read as a branch flag by a lenient parser: a --br… prefix, or -b inside a bundle.
42const AMBIGUOUS_BRANCH_FLAG = /^(--br(?!anch(=|$))[a-z-]*(=.*)?|-[a-z]*b[a-z]+|-[a-z]+b)$/i
43const PROFILE_FLAG = /^--profile(=|$)/
44// While bound, only this branch command runs, and only on the bound branch.
45const GLOBAL_BRANCH_ALLOWED = new Set(['global-branch add-repo'])
46
47// One JSON string escape and its letter forms, in one alternation: one pass never turns
48// `\\u002e` into `\.`, only into `\u002e`.
49const JSON_ESCAPE = /\\(?:u([0-9a-fA-F]{4})|(["\\/bfnrt]))/g
50const ESCAPED: Record<string, string> = { '"': '"', '\\': '\\', '/': '/', b: '\b', f: '\f', n: '\n', r: '\r', t: '\t' }
51
52/** The text, then each JSON-unescaped copy of it until one stops changing (at most 8): what a parser reads out of an escaped or doubly encoded string. */
53export function decodings(text: string): string[] {
54  const out = [text]
55  let current = text
56  for (let pass = 0; pass < 8; pass += 1) {
57    const next = current.replace(JSON_ESCAPE, (_whole, hex: string | undefined, letter: string | undefined) =>
58      hex !== undefined ? String.fromCharCode(parseInt(hex, 16)) : (ESCAPED[letter!] ?? letter!),
59    )
60    if (next === current || out.includes(next)) break
61    out.push(next)
62    current = next
63  }
64  return out
65}
66
67// A name or path that is safe to show: no control, line-breaking or bidi character, at most 100 of them.
68const NOT_PLAIN = /[\u0000-\u001f\u007f-\u009f\u2028\u2029\u202a-\u202e\u2066-\u2069]/
69
70/** The space as it may be shown: a name or path that is not plain shows as the space's RID. */
71export function plainSpace(space: FoundryNamespace): FoundryNamespace {
72  const shown = (value: string) => (value.length <= 100 && !NOT_PLAIN.test(value) ? value : space.rid)
73  return { rid: space.rid, name: shown(space.name), path: shown(space.path) }
74}
75
76/** One line, no control characters, at most 200 characters. */
77const cleanGoal = (text: string) =>
78  text
79    .replace(/[\u0000-\u001f\u007f]+/g, ' ')
80    .replace(/\s+/g, ' ')
81    .trim()
82    .slice(0, GOAL_MAX)
83
84export type FdeArgs =
85  | { kind: 'status' }
86  | { kind: 'end' }
87  | { kind: 'resume' }
88  | { kind: 'start'; goal: string }
89  | { kind: 'adopt'; rid: string; goal: string }
90  | { kind: 'goal'; goal: string }
91  | { kind: 'error'; reason: string }
92
93/** The goal as shown; a session started with /fde on has none until /fde goal sets one. */
94export const goalLabel = (goal: string) => (goal === '' ? 'no goal set' : goal)
95
96export function parseFdeArgs(text: string): FdeArgs {
97  const trimmed = text.trim()
98  if (trimmed === '' || trimmed === 'status') return { kind: 'status' }
99  if (trimmed === 'end') return { kind: 'end' }
100  if (trimmed === 'resume') return { kind: 'resume' }
101  if (trimmed.toLowerCase() === 'on') return { kind: 'start', goal: '' }
102  const setGoal = /^goal(?:\s+([\s\S]*))?$/.exec(trimmed)
103  if (setGoal) {
104    const goal = cleanGoal(setGoal[1] ?? '')
105    return goal === '' ? { kind: 'error', reason: 'Name the goal: /fde goal <text>.' } : { kind: 'goal', goal }
106  }
107  const adopt = /^--branch(?:=|\s+)(\S+)\s*([\s\S]*)$/.exec(trimmed)
108  if (adopt) {
109    const rid = adopt[1]!
110    const goal = cleanGoal(adopt[2] ?? '')
111    if (!GLOBAL_BRANCH.test(rid)) return { kind: 'error', reason: `'${rid}' is not a global branch RID (ri.branch..branch.…).` }
112    return { kind: 'adopt', rid, goal }
113  }
114  return { kind: 'start', goal: cleanGoal(trimmed) }
115}
116
117const stamp = (now: Date) => now.toISOString().replace(/\D/g, '').slice(0, 12)
118
119/** agent/fde-<goal slug>-<yyyymmddhhmm>, at most 64 characters, valid for global-branch create. */
120export function fdeBranchName(goal: string, now: Date): string {
121  const suffix = `-${stamp(now)}`
122  const room = NAME_MAX - PREFIX.length - suffix.length
123  let slug = goal
124    .normalize('NFKD')
125    .toLowerCase()
126    .replace(/[^a-z0-9]+/g, '-')
127    .replace(/^-+|-+$/g, '')
128  if (slug.length > room) slug = slug.slice(0, room).replace(/-[^-]*$/, '') || slug.slice(0, room)
129  slug = slug.replace(/-+$/, '')
130  const name = slug === '' ? `${PREFIX}${stamp(now)}` : `${PREFIX}${slug}${suffix}`
131  return validateBranchName('global-branch create', name).ok ? name : `${PREFIX}work${suffix}`
132}
133
134export function branchCreateArgs(name: string, ontologyRid: string, goal: string): string[] {
135  return ['global-branch', 'create', name, '--ontology-rid', ontologyRid, '--description', (goal === '' ? 'claude-foundry FDE session' : `claude-foundry FDE: ${goal}`).slice(0, GOAL_MAX), '--apply']
136}
137
138/** The global branch RID in a clean orthanc envelope; null on errors or none. */
139export function branchRidFrom(envelope: { data?: unknown; errors?: unknown }): string | null {
140  if (Array.isArray(envelope.errors) && envelope.errors.length > 0) return null
141  const found = /ri\.branch\.\.branch\.[A-Za-z0-9-]+/.exec(JSON.stringify(envelope.data ?? null))
142  return found ? found[0] : null
143}
144
145export const hasApply = (args: readonly string[]) => args.some(arg => /^--apply(=.*)?$/.test(unquote(arg)))
146
147const FILE_FLAG = /^--(?:[a-z0-9-]+-)?file$/
148const absolute = (path: string, cwd: string, home: string) => {
149  const expanded = home !== '' ? path.replace(/^~(?=\/|$)/, home) : path
150  return expanded.startsWith('/') ? expanded : `${cwd.replace(/\/$/, '')}/${expanded}`
151}
152// Any word that could name a file: not a flag, RID, URL or number. A word that
153// is not a file simply does not read, and is left out of the plan.
154const looksLikePath = (value: string) =>
155  value !== '' && !value.startsWith('-') && !/^ri\./.test(value) && !/^[a-z]+:\/\//i.test(value) && !/^[0-9.:]+$/.test(value) && !/[\n{}]/.test(value)
156
157/** Files a call may read, absolute against `cwd`: `required` (values of --file
158 * and --*-file flags, and @name references) must be readable; `optional`
159 * (every other word that could be a path) is hashed when it reads. Directories
160 * do not read, so their contents are not pinned. */
161export function fileCandidates(args: readonly string[], cwd: string, home = ''): { required: string[]; optional: string[] } {
162  const required: string[] = []
163  const optional: string[] = []
164  for (let index = 0; index < args.length; index += 1) {
165    const arg = unquote(args[index] ?? '')
166    if (FILE_FLAG.test(arg) && args[index + 1] !== undefined) {
167      required.push(absolute(unquote(args[index + 1]!).replace(/^@/, ''), cwd, home))
168      index += 1
169      continue
170    }
171    // A short flag with its file attached: -s@/work/schema.json is that file.
172    const attached = /^-[A-Za-z]=?@(.+)$/.exec(arg)
173    if (attached !== null) {
174      required.push(absolute(attached[1]!, cwd, home))
175      continue
176    }
177    const joined = /^(--[a-z0-9-]+)=(.+)$/i.exec(arg)
178    const raw = joined ? unquote(joined[2]!) : arg
179    const value = raw.replace(/^@/, '')
180    if ((joined && FILE_FLAG.test(joined[1]!)) || (raw.startsWith('@') && value !== '')) required.push(absolute(value, cwd, home))
181    else if (looksLikePath(value)) optional.push(absolute(value, cwd, home))
182  }
183  return { required, optional }
184}
185
186/** SHA-256 of the text, with its length: what a plan pins a file to. */
187export async function contentHash(text: string): Promise<string> {
188  const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(text))
189  return `${text.length}:${Array.from(new Uint8Array(digest), byte => byte.toString(16).padStart(2, '0')).join('')}`
190}
191
192/** One call, --apply removed, with the hash of every file it reads. */
193export function planSignature(path: string, args: readonly string[], fileHashes: Record<string, string>): string {
194  const kept = args.filter(arg => !/^--apply(=.*)?$/.test(unquote(arg))).map(unquote)
195  const files = Object.keys(fileHashes)
196    .sort()
197    .map(file => [file, fileHashes[file]])
198  return JSON.stringify([path, kept, files])
199}
200
201export function planGate(fde: FdeSession, signature: string, isApply: boolean): string | null {
202  if (!isApply || fde.plans.includes(signature)) return null
203  return (
204    'FDE mode: --apply runs only after a clean dry run of the same call. Run it without --apply first, ' +
205    'read the plan, then apply with identical arguments. Each dry run licenses one apply, and editing a file the call reads voids it.'
206  )
207}
208
209export const recordPlan = (fde: FdeSession, signature: string): FdeSession =>
210  fde.plans.includes(signature) ? fde : { ...fde, plans: [...fde.plans, signature].slice(-RECORD_MAX) }
211
212/** Takes the plan for one apply, so a second identical apply (even in parallel) finds it gone. */
213export function takePlan(fde: FdeSession, signature: string): { fde: FdeSession; taken: boolean } {
214  if (!fde.plans.includes(signature)) return { fde, taken: false }
215  return { fde: { ...fde, plans: fde.plans.filter(plan => plan !== signature) }, taken: true }
216}
217
218/** Why a file the call reads is refused: it names another global branch or ontology, escaped or not. */
219export function foreignRids(fde: FdeSession, text: string): string | null {
220  const decoded = decodings(text)
221  const branches = new Set(decoded.flatMap(copy => copy.match(GLOBAL_BRANCH_ANY) ?? []))
222  branches.delete(fde.branchRid)
223  const ontologies = new Set(decoded.flatMap(copy => copy.match(ONTOLOGY_RID) ?? []))
224  ontologies.delete(fde.ontologyRid)
225  const found = [...branches, ...ontologies]
226  return found.length === 0 ? null : `a file this call reads names ${found.join(', ')}; the session works on ${fde.branchRid} in ${fde.ontologyRid} only.`
227}
228
229/** An apply consumes its dry run: the next apply needs a new one. */
230export const recordApply = (fde: FdeSession, command: string, signature: string, now: Date): FdeSession => ({
231  ...fde,
232  plans: fde.plans.filter(plan => plan !== signature),
233  applied: [...fde.applied, { command, at: now.toISOString() }].slice(-RECORD_MAX),
234})
235
236/** Binds one orthanc_cli call to the session: the (possibly rewritten) args, or why it is refused. */
237export function fdeBind(
238  fde: FdeSession,
239  path: string,
240  args: readonly string[],
241  profile: string,
242  isMutation: boolean,
243): { args: string[] } | { deny: string } {
244  const tag = `FDE mode (${fde.branchName})`
245  const words = args.map(unquote)
246  // The stack is the session's: no call may switch it, read or write.
247  if (words.some(word => PROFILE_FLAG.test(word))) return { deny: `${tag}: --profile is not allowed while bound; the session runs on stack '${fde.profile}'.` }
248  if (!isMutation) return { args: [...args] }
249  if (profile !== fde.profile) {
250    return { deny: `${tag}: the session's branch is on stack '${fde.profile}', but the active stack is '${profile}'. Switch back with /profile ${fde.profile}, or /fde end.` }
251  }
252  if (fde.namespace !== null && path === 'space create') {
253    return { deny: `${tag}: the session works in ${fde.namespace.name} only, and a new space is outside it. The operator ends the mode with /fde end.` }
254  }
255  if (path === 'global-branch create') {
256    return { deny: `${tag}: this session works on ${fde.branchRid} only. Do not create another global branch; the operator ends the mode with /fde end.` }
257  }
258  if ((path.startsWith('global-branch ') && !GLOBAL_BRANCH_ALLOWED.has(path)) || path.startsWith('proposal ')) {
259    return { deny: `${tag}: '${path}' changes branches or proposals, which is the operator's decision at handoff. Report that the work is ready instead.` }
260  }
261  const decoded = words.flatMap(word => decodings(word))
262  const foreign = new Set(decoded.flatMap(word => word.match(GLOBAL_BRANCH_ANY) ?? []))
263  foreign.delete(fde.branchRid)
264  if (foreign.size > 0) return { deny: `${tag}: this call names ${[...foreign].join(', ')}; the session works on ${fde.branchRid} only.` }
265  if (path.startsWith('global-branch ') && !words.includes(fde.branchRid)) {
266    return { deny: `${tag}: '${path}' must name the session's branch ${fde.branchRid}.` }
267  }
268  const ontologies = new Set(decoded.flatMap(word => word.match(ONTOLOGY_RID) ?? []))
269  ontologies.delete(fde.ontologyRid)
270  if (ontologies.size > 0) {
271    return { deny: `${tag}: the branch belongs to ontology ${fde.ontologyRid}; this call names ${[...ontologies].join(', ')}.` }
272  }
273  if (!path.startsWith('ontology ')) return { args: [...args] }
274  if (words.some(word => AMBIGUOUS_BRANCH_FLAG.test(word))) {
275    return { deny: `${tag}: spell the branch flag as --branch (or leave it out and the mode supplies it).` }
276  }
277  const branches = flagValues(args, BRANCH_FLAGS)
278  if (branches.length === 0) return { args: requiresBranch(path) ? [...args, '--branch', fde.branchRid] : [...args] }
279  if (branches.length === 1 && branches[0] === fde.branchRid) return { args: [...args] }
280  const named = branches.filter(Boolean).join(', ') || '(no value)'
281  return { deny: `${tag}: ontology writes go to ${fde.branchRid}; this call names --branch ${named}. Drop --branch and the mode supplies it.` }
282}
283
284/** A stored binding: junk is null, and a session from before namespaces has `namespace: null, spaces: []`. */
285export function normalizeFde(stored: unknown): FdeSession | null {
286  if (!isRecord(stored) || typeof stored.branchRid !== 'string') return null
287  const space = (value: unknown): FoundryNamespace | null =>
288    isRecord(value) && typeof value.rid === 'string' && value.rid !== '' && typeof value.name === 'string' && typeof value.path === 'string'
289      ? { rid: value.rid, name: value.name, path: value.path }
290      : null
291  const plain = (value: unknown): FoundryNamespace | null => {
292    const found = space(value)
293    return found === null ? null : plainSpace(found)
294  }
295  return {
296    ...(stored as object as FdeSession),
297    namespace: plain(stored.namespace),
298    spaces: Array.isArray(stored.spaces) ? stored.spaces.map(plain).filter((entry): entry is FoundryNamespace => entry !== null) : [],
299  }
300}
301
302/** Why a write is refused: what it names, the namespace it is in, and that inputs count too. */
303const refusal = (fde: FdeSession, target: string, spaceRid: string): string => {
304  const ns = fde.namespace!
305  const listed = fde.spaces.find(space => space.rid === spaceRid)
306  const label = listed ? listed.name : `another namespace (${spaceRid})`
307  return (
308    `FDE mode (${fde.branchName}): ${target} is in ${label}, not ${ns.name}; the session works in ${ns.name} only, ` +
309    'and every resource a write names (in its arguments or the files it reads) must be in it.'
310  )
311}
312
313/** The space `path` names, by whole segments: `/Acme` does not claim `/Acme Dev/x`. Only a real path places one: a RID or an empty path standing in for a path claims nothing. */
314const placePath = (fde: FdeSession, path: string): FoundryNamespace | undefined =>
315  fde.spaces.find(space => space.path.startsWith('/') && (path === space.path || path.startsWith(space.path + '/')))
316
317/** The arg as a path: `--flag=/x` carries `/x`; anything that is not absolute is not a path. */
318const argPath = (arg: string): string => {
319  const word = unquote(arg)
320  const joined = /^--[a-z0-9-]+=(.*)$/i.exec(word)
321  return joined ? unquote(joined[1]!) : word
322}
323
324/**
325 * What a write names that could sit outside the bound namespace: the RIDs left
326 * to look up, or why the call is refused now. Without a bound namespace nothing
327 * is checked; a path under no listed space is nobody's business.
328 */
329export function namespaceScan(fde: FdeSession, args: readonly string[], texts: readonly string[]): { deny: string } | { lookup: string[] } {
330  if (fde.namespace === null) return { lookup: [] }
331  const skip = new Set([fde.branchRid, fde.ontologyRid, fde.namespace.rid])
332  const found: string[] = []
333  for (const arg of args) found.push(...decodings(unquote(arg)).flatMap(copy => copy.match(RESOURCE_RID) ?? []))
334  for (const text of texts) found.push(...decodings(text).flatMap(copy => copy.match(RESOURCE_RID) ?? []))
335  const lookup: string[] = []
336  for (const rid of new Set(found)) {
337    if (skip.has(rid) || rid.startsWith(BRANCH_RID_PREFIX)) continue
338    // batch-get never returns a namespace's own space, so a listed one is refused by the list.
339    const named = fde.spaces.find(space => space.rid === rid)
340    if (named !== undefined) return { deny: refusal(fde, rid, named.rid) }
341    lookup.push(rid)
342  }
343  // Whole args are paths; inside an arg (inline JSON) or a file, only quoted strings
344  // and paths that open right after a quote are, in every decoding.
345  const paths = [
346    ...args.flatMap(arg => decodings(arg).map(argPath)),
347    ...[...args, ...texts].flatMap(text =>
348      decodings(text).flatMap(copy => [
349        ...(copy.match(QUOTED_PATH) ?? []).map(unquote),
350        ...Array.from(copy.matchAll(QUOTE_OPENED_PATH), match => match[1]!),
351      ]),
352    ),
353  ]
354  for (const path of paths) {
355    if (!path.startsWith('/')) continue
356    const placed = placePath(fde, path)
357    if (placed !== undefined && placed.rid !== fde.namespace.rid) return { deny: refusal(fde, path, placed.rid) }
358  }
359  return { lookup }
360}
361
362/** `resource batch-get` argv for one call: at most 1000 RIDs each, in order. */
363export function batchGetArgs(rids: readonly string[]): string[][] {
364  const chunks: string[][] = []
365  for (let index = 0; index < rids.length; index += BATCH_MAX) chunks.push(['resource', 'batch-get', ...rids.slice(index, index + BATCH_MAX)])
366  return chunks
367}
368
369/** Each asked RID's spaceRid in a batch-get `data`, in asked order: null when batch-get left it out. */
370export function spacesOf(data: unknown, asked: readonly string[]): Map<string, string | null> {
371  const rows = isRecord(data) && Array.isArray(data.resources) ? data.resources.filter(isRecord) : []
372  const spaces = new Map(rows.flatMap(row => (typeof row.rid === 'string' && typeof row.spaceRid === 'string' ? [[row.rid, row.spaceRid] as [string, string]] : [])))
373  return new Map(asked.map(rid => [rid, spaces.get(rid) ?? null] as [string, string | null]))
374}
375
376/** Why this write names something outside the bound namespace; null when nothing looked-up is outside. */
377export function namespaceDeny(fde: FdeSession, spaces: ReadonlyMap<string, string | null>): string | null {
378  if (fde.namespace === null) return null
379  const ns = fde.namespace
380  for (const [rid, spaceRid] of spaces) {
381    if (spaceRid === null) {
382      if (!rid.startsWith(COMPASS_FOLDER_RID)) continue
383      return (
384        `FDE mode (${fde.branchName}): ${rid} is a Compass folder resource batch-get did not return, so it cannot be placed in ${ns.name}; ` +
385        `the session works in ${ns.name} only, and every resource a write names (in its arguments or the files it reads) must be in it.`
386      )
387    }
388    if (spaceRid !== ns.rid) return refusal(fde, rid, spaceRid)
389  }
390  return null
391}
392
393/**
394 * The branch to show when `data` (global-branch get) is an OPEN branch of
395 * `ontologyRid`, whatever its prefix (a Foundry AI FDE branch is named
396 * ai-fde/<user>/<slug>): its display name when that is a plain branch name,
397 * its RID when it is not. Anything else is a reason it cannot be adopted.
398 */
399export function adoptable(data: unknown, ontologyRid: string): { name: string } | string {
400  const record = (data as { branch_record?: Record<string, unknown> } | null)?.branch_record
401  if (typeof record !== 'object' || record === null) return 'global-branch get returned no branch record.'
402  if (record.branch_status !== 'OPEN') return `The branch is ${String(record.branch_status ?? 'unknown')}, not OPEN.`
403  if (record.ontology_rid !== ontologyRid) return `The branch belongs to ontology ${String(record.ontology_rid ?? 'unknown')}, not the selected ${ontologyRid}.`
404  const name = typeof record.display_name === 'string' && PLAIN_NAME.test(record.display_name) ? record.display_name : ''
405  if (name !== '') return { name }
406  if (typeof record.branch_rid === 'string' && GLOBAL_BRANCH.test(record.branch_rid)) return { name: record.branch_rid }
407  return 'The branch has no plain name, and global-branch get returned no branch RID to show instead.'
408}
409
410/** The proposal `data` (global-branch get) has open on the branch; null when it has none. */
411export function openProposal(data: unknown): string | null {
412  const rid = (data as { branch_record?: Record<string, unknown> } | null)?.branch_record?.active_proposal
413  return typeof rid === 'string' && PROPOSAL_RID.test(rid) ? rid : null
414}
415
416/** A branch FDE mode could have made itself; every other one belongs to someone else. */
417export function isAgentBranch(name: string): boolean {
418  return name.startsWith('agent/') && validateBranchName('global-branch create', name).ok
419}
420
421const adoptedForeign = (fde: FdeSession) => !isAgentBranch(fde.branchName)
422
423const appliedLines = (fde: FdeSession) =>
424  fde.applied.length === 0 ? ['- nothing applied'] : fde.applied.map(entry => `- ${entry.at} ${entry.command}`)
425
426export function fdeContext(fde: FdeSession): string {
427  return [
428    '# FDE mode',
429    `Goal: ${goalLabel(fde.goal)}${fde.goal === '' ? ' (the operator works with you turn by turn; /fde goal sets one)' : ''}`,
430    `This session works on one global branch: ${fde.branchName} (${fde.branchRid}) on ontology ${fde.ontologyRid}, stack ${fde.profile}.`,
431    ...(adoptedForeign(fde)
432      ? [`This is ${FOREIGN_LINE}. Change only what the goal needs, and leave what you did not make as you found it.`]
433      : []),
434    ...(fde.namespace ? [`Writes are limited to namespace ${fde.namespace.name} (${fde.namespace.path}): every resource a write names (in its arguments or the files it reads) must be in it, or the write is refused. Reads may look anywhere.`] : []),
435    'Ontology writes are pinned to it: omit --branch and the mode adds it; any other branch, --profile or a new branch is refused. ' +
436      'Pass --branch with that RID on reads you mean to see the branch (`ontology definition --object-type X --branch <rid>`); reads without it see main.',
437    'Plan, then apply: run each write as a dry run (no --apply), read the plan, then repeat it with --apply and identical arguments. ' +
438      'Each dry run licenses one apply, and editing a file the call reads voids it. Keep request files outside ~/.claude.',
439    'Work as an FDE: scout what exists, make the smallest change on the branch, verify it on the branch, then report. ' +
440      'Never create, close or merge branches: the operator ends the mode with /fde end and decides what lands.',
441  ].join('\n')
442}
443
444export function fdeStatus(fde: FdeSession): string {
445  return [
446    `FDE mode on · ${goalLabel(fde.goal)}`,
447    `branch ${fde.branchName} (${fde.branchRid})`,
448    ...(adoptedForeign(fde) ? [FOREIGN_LINE] : []),
449    `stack ${fde.profile} · ontology ${fde.ontologyRid} · since ${fde.startedAt}`,
450    ...(fde.namespace ? [`namespace ${fde.namespace.name} (${fde.namespace.path}): writes naming resources outside it are refused`] : []),
451    `${fde.applied.length} applied · ${fde.plans.length} planned`,
452    '/fde end hands off and leaves the branch open.',
453  ].join('\n')
454}
455
456export function fdeHandoff(fde: FdeSession): string {
457  return [
458    `# FDE handoff: ${goalLabel(fde.goal)}`,
459    '',
460    `- Branch: ${fde.branchName} (${fde.branchRid}), still OPEN and not merged.`,
461    `- Stack ${fde.profile}, ontology ${fde.ontologyRid}, started ${fde.startedAt}.`,
462    ...(fde.namespace ? [`- Namespace: ${fde.namespace.name} (${fde.namespace.path}).`] : []),
463    `- Applied writes (${fde.applied.length}):`,
464    ...appliedLines(fde).map(line => `  ${line}`),
465    '',
466    adoptedForeign(fde)
467      ? 'This is not an agent/ branch: FDE mode adopted it and leaves it as it found it, open. Whoever owns it decides whether it merges or closes.'
468      : 'The operator reviews the branch, then merges it through a proposal or closes it: ' +
469        `orthanc global-branch close ${fde.branchRid} --apply --yes.`,
470  ].join('\n')
471}
472
hooks/orthanc.ts 249 lines
1// The orthanc_help and orthanc_cli tools' pure half.
2// Pure: the envelope, the manifest and the help text. Running orthanc stays
3// in register.tsx, where `$` lives.
4
5import { DENIED_COMMANDS, type ManifestCommand, type ManifestFlag } from './policy'
6
7export type Envelope = {
8  schema_version: string
9  data?: unknown
10  errors?: unknown[]
11  meta?: Record<string, unknown>
12  warnings?: unknown[]
13  [key: string]: unknown
14}
15
16const INLINE_LIMIT = 20_000
17const ROW_NAMES_LIMIT = 8_000
18
19/** A row's identity for a cut listing: api name, else display name, else RID. */
20const rowName = (row: Record<string, unknown>) =>
21  [row.api_name, row.apiName, row.display_name, row.name, row.rid].find((value): value is string => typeof value === 'string' && value !== '') ?? ''
22const USAGE_ERRORS = ['required arguments were not provided', 'unexpected argument', 'usage: orthanc', 'invalid value']
23
24export const isRecord = (value: unknown): value is Record<string, unknown> =>
25  typeof value === 'object' && value !== null && !Array.isArray(value)
26
27export function parseEnvelope(stdout: string): Envelope | null {
28  try {
29    const parsed: unknown = JSON.parse(stdout)
30    return isRecord(parsed) && parsed.schema_version === 'foundry-agent-v1' ? (parsed as Envelope) : null
31  } catch {
32    return null
33  }
34}
35
36export const failure = (type: string, message: string, operation: string, extra: Record<string, unknown> = {}): Envelope => ({
37  schema_version: 'foundry-agent-v1',
38  data: null,
39  errors: [{ type, message, ...extra }],
40  meta: { operation },
41  warnings: [],
42})
43
44export function manifestFrom(envelope: Envelope): ManifestCommand[] {
45  const commands = isRecord(envelope.data) && Array.isArray(envelope.data.commands) ? envelope.data.commands : []
46  return commands.filter(isRecord).flatMap(entry =>
47    typeof entry.path === 'string'
48      ? [{
49          path: entry.path,
50          kind: typeof entry.kind === 'string' ? entry.kind : undefined,
51          auth: typeof entry.auth === 'string' ? entry.auth : undefined,
52          input: typeof entry.input === 'string' ? entry.input : undefined,
53          flags: flagsFrom(entry.args),
54        }]
55      : [],
56  )
57}
58
59function flagsFrom(args: unknown): ManifestFlag[] {
60  if (!Array.isArray(args)) return []
61  return args.filter(isRecord).flatMap(arg =>
62    typeof arg.flag === 'string'
63      ? [{ flag: arg.flag, takesValue: arg.takes_value === true, ...(typeof arg.default === 'string' ? { default: arg.default } : {}) }]
64      : [],
65  )
66}
67
68// orthanc_cli's process timer. Waiting commands (repository checks wait,
69// ontology branch-index-status --wait, sql wait, …) run as long as their own
70// --timeout, plus --publish-grace after the checks pass. The timer gives them
71// that wait, one poll interval (Orthanc can overshoot its deadline by one) and
72// a margin, so Orthanc reports its own timeout instead of being killed. The
73// floor is the old fixed 300 s; the cap is Orthanc's longest default wait
74// (branch-index-status, 1800 s) plus the margin.
75const CLI_MARGIN_S = 120
76const CLI_LONGEST_WAIT_S = 1800
77export const CLI_TIMEOUT_FLOOR_MS = 300_000
78export const CLI_TIMEOUT_CAP_MS = (CLI_LONGEST_WAIT_S + CLI_MARGIN_S) * 1000
79const WAIT_FLAGS = ['--timeout', '--publish-grace']
80const POLL_FLAGS = ['--interval', '--poll-interval']
81
82/** The last value given for `flag` (`--flag v` or `--flag=v`); '' when it dangles, undefined when absent. */
83function flagArgument(args: readonly string[], flag: string): string | undefined {
84  let value: string | undefined
85  args.forEach((arg, index) => {
86    if (arg === flag) value = args[index + 1] ?? ''
87    else if (arg.startsWith(`${flag}=`)) value = arg.slice(flag.length + 1)
88  })
89  return value
90}
91
92/** How long orthanc_cli lets `command` run with `args` (the resolved args, flags included), in ms. */
93export function cliTimeoutMs(command: ManifestCommand | undefined, args: readonly string[]): number {
94  const flags = command?.flags ?? []
95  const declares = (flag: string) => flags.some(entry => entry.flag === flag)
96  const passes = (flag: string) => args.some(arg => arg === flag || arg.startsWith(`${flag}=`))
97  const seconds = (flag: string) => {
98    const raw = flagArgument(args, flag) ?? flags.find(entry => entry.flag === flag)?.default
99    const value = raw === undefined || raw.trim() === '' ? NaN : Number(raw)
100    return Number.isFinite(value) && value > 0 ? value : 0
101  }
102  // A command with a --wait switch only waits when it is passed; --no-wait never waits.
103  const waits = !passes('--no-wait') && (!declares('--wait') || passes('--wait'))
104  const wait = waits ? WAIT_FLAGS.reduce((sum, flag) => sum + seconds(flag), 0) : 0
105  if (wait === 0) return CLI_TIMEOUT_FLOOR_MS
106  const poll = Math.max(...POLL_FLAGS.map(seconds))
107  const total = (wait + poll + CLI_MARGIN_S) * 1000
108  return Math.min(CLI_TIMEOUT_CAP_MS, Math.max(CLI_TIMEOUT_FLOOR_MS, total))
109}
110
111export const normalizeCommand = (command: string) => command.trim().replace(/\s+/g, ' ')
112
113const groupOf = (path: string) => path.split(' ')[0] ?? path
114
115function commandLine(command: ManifestCommand): string {
116  const traits = [command.kind, command.auth && `auth: ${command.auth}`, command.input && `input: ${command.input}`]
117    .filter(Boolean)
118    .join(', ')
119  return `${command.path}${traits ? ` — ${traits}` : ''}`
120}
121
122export const isCredentialCommand = (command: ManifestCommand) =>
123  DENIED_COMMANDS.has(command.path) || command.input === 'token-on-stdin'
124
125export function renderCommand(command: ManifestCommand, help: string | null): string {
126  const lines = [commandLine(command)]
127  if (help) {
128    lines.push('', help.slice(0, 4000), '')
129    lines.push(
130      'For orthanc_cli, put positionals first in args, then exact flags. Do not invent flags. ' +
131        'Agent/non-interactive flags and the profile are supplied by the tool.',
132    )
133  }
134  if (isCredentialCommand(command)) {
135    lines.push('This credential-input command is not executable through orthanc_cli; the operator runs it in a terminal.')
136  }
137  return lines.join('\n')
138}
139
140export function renderListing(
141  commands: readonly ManifestCommand[],
142  input: { group?: string; query?: string },
143): string {
144  if (input.query) {
145    const terms = input.query.toLowerCase().split(/\s+/).filter(Boolean)
146    const hits = commands
147      .map(command => ({ command, score: terms.filter(term => command.path.toLowerCase().includes(term)).length }))
148      .filter(hit => hit.score > 0)
149      .sort((left, right) => right.score - left.score || left.command.path.localeCompare(right.command.path))
150      .slice(0, 20)
151    if (hits.length === 0) return `No Orthanc commands matched '${input.query}'.`
152    return [`Orthanc search '${input.query}': ${hits.length} hit${hits.length === 1 ? '' : 's'}.`, '', ...hits.map(hit => commandLine(hit.command))].join('\n')
153  }
154  if (input.group) {
155    const matches = commands.filter(command => groupOf(command.path) === input.group)
156    if (matches.length === 0) {
157      return `Unknown Orthanc group '${input.group}'. Groups: ${[...new Set(commands.map(command => groupOf(command.path)))].sort().join(', ')}.`
158    }
159    return [`Orthanc group '${input.group}': ${matches.length} command${matches.length === 1 ? '' : 's'}.`, '', ...matches.map(commandLine)].join('\n')
160  }
161  const counts = new Map<string, number>()
162  for (const command of commands) counts.set(groupOf(command.path), (counts.get(groupOf(command.path)) ?? 0) + 1)
163  return [
164    `Orthanc command surface: ${commands.length} commands in ${counts.size} groups.`,
165    'Call orthanc_help with a group to list commands, with a command path to inspect it, or with query to search.',
166    '',
167    ...[...counts.entries()].sort(([left], [right]) => left.localeCompare(right)).map(([group, count]) => `${group} (${count})`),
168  ].join('\n')
169}
170
171function verificationHint(path: string): string {
172  if (path.startsWith('global-branch create')) return "verify with 'global-branch get <branch_rid>' before reporting success"
173  if (path.startsWith('dataset branches create')) return "verify with 'dataset branches list <dataset_rid>' before reporting success"
174  if (path.startsWith('dataset create')) return "verify with 'dataset get <dataset_rid>' before reporting success"
175  if (path.startsWith('ontology ')) return 'verify with the matching ontology read for the changed type before reporting success'
176  return 'verify the change with the matching read operation before reporting success'
177}
178
179export const isErrorEnvelope = (envelope: Envelope) => Array.isArray(envelope.errors) && envelope.errors.length > 0
180
181export function isUsageError(envelope: Envelope): boolean {
182  const reason = JSON.stringify(envelope.errors ?? []).toLowerCase()
183  return USAGE_ERRORS.some(pattern => reason.includes(pattern))
184}
185
186/** Usage hint on usage errors; verification hint or uncertain-mutation flag on mutations. */
187export function guideEnvelope(envelope: Envelope, command: ManifestCommand, help: string | null): Envelope {
188  const usage = isUsageError(envelope)
189  let guided = usage && help ? { ...envelope, usage_hint: help.slice(0, 4000) } : envelope
190  if (command.kind !== 'mutation') return guided
191  if (!isErrorEnvelope(guided)) return { ...guided, verification_hint: verificationHint(command.path) }
192  if (!usage && JSON.stringify(guided.errors).includes('orthanc-launch-error')) {
193    guided = { ...guided, uncertain_mutation: true, guidance: 'reconcile observable Foundry state before any retry' }
194  }
195  return guided
196}
197
198/**
199 * The envelope as text for the model. Over the inline limit it is cut, with the
200 * page token and list sizes hoisted above the cut (they sit in `data`, which the
201 * cut can hide) and, when given, the path the whole envelope was written to.
202 */
203export function serialize(value: unknown, spillPath?: string): string {
204  const text = JSON.stringify(value, null, 2) ?? 'null'
205  if (text.length <= INLINE_LIMIT) return text
206  const header = [`orthanc output is ${text.length} chars; showing the first ${INLINE_LIMIT}.`]
207  if (spillPath) header.push(`The whole envelope is in ${spillPath}: read it with the Read tool (offset/limit) or jq.`)
208  const data = isRecord(value) ? value.data : undefined
209  if (isRecord(data)) {
210    const token = data.next_page_token ?? data.nextPageToken
211    if (typeof token === 'string' && token) header.push(`next_page_token: ${token} (pass --page-token to read the next page).`)
212    const sizes = Object.entries(data).filter(([, entry]) => Array.isArray(entry)).map(([key, entry]) => `${key}: ${(entry as unknown[]).length}`)
213    if (sizes.length > 0) header.push(`rows on this page: ${sizes.join(', ')}.`)
214    for (const [key, entry] of Object.entries(data)) {
215      if (!Array.isArray(entry)) continue
216      const names = entry.filter(isRecord).map(rowName).filter(Boolean)
217      if (names.length === 0) continue
218      const joined = names.join(', ')
219      header.push(`${key}: ${joined.length > ROW_NAMES_LIMIT ? `${joined.slice(0, ROW_NAMES_LIMIT)} …` : joined}`)
220    }
221  }
222  if (!spillPath) header.push('Narrow the call (--page-size, a get command) for less output.')
223  return `${header.join('\n')}\n\n${text.slice(0, INLINE_LIMIT)}\n... truncated`
224}
225
226export const isOversized = (value: unknown) => (JSON.stringify(value, null, 2)?.length ?? 0) > INLINE_LIMIT
227
228/** The list inside an orthanc list envelope, wherever the envelope keeps it. */
229export function listItems(envelope: Envelope, key: string): Record<string, unknown>[] {
230  const data = envelope.data
231  if (Array.isArray(data)) return data.filter(isRecord)
232  if (!isRecord(data)) return []
233  const list = data[key] ?? data.data
234  return Array.isArray(list) ? list.filter(isRecord) : []
235}
236
237/** The rows of an envelope whose list key varies by command: the named keys, then the first list in data. */
238export function rowsOf(envelope: Envelope, keys: readonly string[]): Record<string, unknown>[] {
239  const data = envelope.data
240  if (Array.isArray(data)) return data.filter(isRecord)
241  if (!isRecord(data)) return []
242  for (const key of [...keys, 'data']) {
243    const list = data[key]
244    if (Array.isArray(list)) return list.filter(isRecord)
245  }
246  const first = Object.values(data).find(Array.isArray)
247  return Array.isArray(first) ? first.filter(isRecord) : []
248}
249
hooks/process.ts 44 lines
1// Running a child longer than $.process.run allows. $.process.run kills its
2// child after ten minutes at most, while an Orthanc wait (repository checks
3// wait --timeout 1500, branch-index-status --wait) can need up to 32. Past that
4// cap register.tsx spawns the child with $.process.spawn and a $.clock.after
5// deadline, and readToExit reads the stream. `$` stays in register.tsx.
6
7import type { HookStream, ProcessSpawnChunk, ProcessSpawnResult } from 'claude-code'
8
9/** The longest timeoutMs $.process.run takes. */
10export const PROCESS_RUN_MAX_MS = 600_000
11
12export type ProcessOutput = { exitCode: number; stdout: string; stderr: string }
13
14/** Reads a spawned child to its exit, as $.process.run would answer: a child
15 * ended by a signal reads as exit code 1. Rejects when the child cannot start
16 * or `expired` settles first; leaving the stream then kills the child. */
17export async function readToExit(
18  child: HookStream<ProcessSpawnChunk, ProcessSpawnResult>,
19  expired: Promise<unknown>,
20  timeoutMs: number,
21): Promise<ProcessOutput> {
22  const timedOut = expired.then(() => 'expired' as const)
23  let finished = false
24  let stdout = ''
25  let stderr = ''
26  try {
27    for (;;) {
28      const pull = child.next()
29      // A pull still pending when time runs out may reject later; that is not news.
30      pull.catch(() => {})
31      const next = await Promise.race([pull, timedOut])
32      if (next === 'expired') throw new Error(`still running after ${timeoutMs / 1000} s; stopped`)
33      if (next.done) {
34        finished = true
35        return { exitCode: next.value.code ?? 1, stdout, stderr }
36      }
37      if (next.value.stream === 'stdout') stdout += next.value.text
38      else stderr += next.value.text
39    }
40  } finally {
41    if (!finished) child.return({ code: null, signal: null }).catch(() => {})
42  }
43}
44
hooks/policy.ts 1059 lines
1// The approval ladder, the branch gate and the approval modes. Pure functions:
2// no `$`, so the test kit and the hooks share them. Read/mutation comes from
3// orthanc's own agent-manifest `kind`.
4
5/** One option of a manifest command, as Orthanc's agent-manifest lists it. */
6export type ManifestFlag = { flag: string; takesValue: boolean; default?: string }
7export type ManifestCommand = { path: string; kind?: string; auth?: string; input?: string; flags?: ManifestFlag[] }
8
9export const APPROVAL_MODES = ['ask-always', 'allow-edits', 'auto', 'yolo'] as const
10export type ApprovalMode = (typeof APPROVAL_MODES)[number]
11export const DEFAULT_APPROVAL_MODE: ApprovalMode = 'auto'
12
13export function parseApprovalMode(value: string): ApprovalMode | null {
14  const normalized = value.trim().toLowerCase()
15  return APPROVAL_MODES.find(mode => mode === normalized) ?? null
16}
17
18export const ORTHANC_CLI = 'mcp__foundry__orthanc_cli'
19export const ORTHANC_HELP = 'mcp__foundry__orthanc_help'
20
21const PROTECTED_BRANCHES = ['main', 'master']
22const BRANCH_CREATION_PATHS = ['global-branch create', 'dataset branches create']
23// The branch rule: agent work happens on branches, never on a production main.
24// Each of these writes must name a non-protected --branch; ontology writes must
25// name a global branch RID, the one branch shape that is provably not main.
26const BRANCH_REQUIRED_PATHS = new Set([
27  'compute manage',
28  'compute execute',
29  'dataset files upload',
30  'dataset files delete',
31  'dataset schema set',
32  'dataset schema apply',
33  'dataset schema update',
34  'dataset transactions start',
35  'ontology action-apply',
36  'ontology object-type-create',
37  'ontology object-type-upsert',
38  'ontology object-type-guarded-upsert',
39  'ontology object-type-add-property',
40  'ontology object-type-delete',
41  'ontology object-type-guarded-delete',
42  'ontology link-type-create',
43  'ontology link-type-upsert',
44  'ontology link-type-delete',
45  'ontology action-type-upsert',
46  'ontology action-type-update',
47  'ontology action-type-set-function-version',
48  'ontology action-type-delete',
49  'streams dataset create',
50  'streams stream create',
51  'streams stream publish',
52  'streams stream publish-batch',
53  'streams stream reset',
54  'orchestration builds create',
55  'cp',
56])
57export const requiresBranch = (path: string) => BRANCH_REQUIRED_PATHS.has(path)
58// Ontology writes Orthanc cannot branch: they change live data on main.
59const MAIN_ONLY_WRITES = new Set(['ontology object-upsert', 'ontology object-upsert-batch', 'ontology action-apply-with-overrides'])
60// Promotion into main is the operator's decision, not the agent's. A release
61// tag is not here: it asks the operator each time (see releaseTagCall).
62const PROMOTIONS = new Set(['proposal merge', 'proposal accept', 'proposal approve'])
63export const BRANCH_FLAGS = ['--branch', '-b']
64const BRANCH_VALUE = /^[A-Za-z0-9._/-]+$/
65// Orthanc flags that take no value, so the word after one is a positional.
66const BOOLEAN_FLAGS = new Set([
67  '--agent', '--apply', '--allow-default-branch', '--non-interactive', '--dry-run', '--force',
68  '--recursive', '-r', '--schema', '--fail-fast', '--debug', '--help', '-h',
69])
70const GLOBAL_BRANCH_RID = 'ri.branch.'
71const GLOBAL_BRANCH_PREFIX = 'agent/'
72const DATASET_BRANCH_PREFIX = 'agent-'
73const BRANCH_NAME_MAX_LEN = 64
74const READ_VERBS = new Set([
75  'get', 'list', 'search', 'describe', 'check', 'health', 'inspect',
76  'preview', 'query', 'read', 'view', 'help', 'export', 'status', 'download',
77])
78export const DENIED_COMMANDS = new Set(['auth store', 'onboarding'])
79// Orthanc `local` commands that only read local state.
80const LOCAL_READS = new Set([
81  'version', 'hello', 'agent-manifest', 'capabilities', 'completion show',
82  'configure list', 'alias list', 'alias show', 'alias resolve', 'alias export',
83])
84
85export type GateClassification = {
86  command: string | null
87  kind: 'mutation' | 'branch-creation'
88  isBranchScoped: boolean
89  hasWorkingBranch: boolean
90  targetsProtected: boolean
91  isDestructive: boolean
92  proposedName?: string
93  /** The question to put to the operator for a release tag apply, in every mode. */
94  release?: string
95  error?: string
96}
97
98export type LadderDecision = { outcome: 'run' | 'ask' | 'block'; reason: string }
99
100export type GuardVerdict = { action: 'approve' | 'ask' | 'deny'; reason: string }
101
102const lastWord = (text: string) => text.split(/\s+/).at(-1) ?? ''
103
104export function classifyOrthancCommand(
105  command: string,
106  manifest: readonly ManifestCommand[],
107): 'read' | 'mutation' {
108  const normalized = command.trim().toLowerCase()
109  const declared = manifest.find(entry => entry.path === normalized)
110  if (declared?.kind === 'read-only') return 'read'
111  if (declared?.kind === 'local' && LOCAL_READS.has(normalized)) return 'read'
112  if (declared === undefined && READ_VERBS.has(lastWord(normalized))) return 'read'
113  return 'mutation'
114}
115
116function isDestructiveCommand(command: string): boolean {
117  return lastWord(command.trim().toLowerCase()).split('-').at(-1) === 'delete'
118}
119
120/** True when any arg names one of these flags, in any case, with or without a
121 * `=value` (`--force`, `-f`, `--APPLY`, `--apply=true`). Over-matching only asks more. */
122function argsNameFlag(args: readonly string[], names: readonly string[]): boolean {
123  return args.some(arg => {
124    const flag = unquote(arg).trim().toLowerCase().replace(/=.*$/, '')
125    return names.includes(flag)
126  })
127}
128
129function argsHaveForce(args: readonly string[]): boolean {
130  return argsNameFlag(args, ['--force', '-f'])
131}
132
133// `main`, `refs/heads/main`, `+refs/heads/main`, `:main`, `./main/` all name main.
134const branchCore = (value: string) =>
135  value
136    .trim()
137    .toLowerCase()
138    .replace(/^[+:]+|:+$/g, '')
139    .replace(/\/{2,}/g, '/')
140    .replace(/^(\.\/)+/, '')
141    .replace(/^(refs\/)?heads\//, '')
142    .replace(/[/.]+$/, '')
143const isProtectedValue = (value: string) => PROTECTED_BRANCHES.includes(branchCore(value)) || branchCore(value) === 'head'
144
145export function branchIsWorking(branch: string | null | undefined): boolean {
146  return typeof branch === 'string' && branch.trim() !== '' && !isProtectedValue(branch)
147}
148
149export function validateBranchName(
150  path: string,
151  name: string,
152): { ok: true; name: string } | { ok: false; reason: string } {
153  const trimmed = name.trim()
154  if (trimmed.length > BRANCH_NAME_MAX_LEN) {
155    return { ok: false, reason: `branch name exceeds ${BRANCH_NAME_MAX_LEN} characters` }
156  }
157  const prefix = path === 'global-branch create' ? GLOBAL_BRANCH_PREFIX : DATASET_BRANCH_PREFIX
158  if (!trimmed.startsWith(prefix)) {
159    const kind = prefix === GLOBAL_BRANCH_PREFIX ? 'global' : 'dataset'
160    return {
161      ok: false,
162      reason: `${kind} branch name must start with '${prefix}', e.g. '${prefix}foundry-fix-12'`,
163    }
164  }
165  const body = trimmed.slice(prefix.length)
166  const isKebab = body !== '' && body.split('-').every(part => /^[a-z0-9]+$/.test(part))
167  if (!isKebab) {
168    return {
169      ok: false,
170      reason: 'branch name body must be lowercase alphanumeric segments separated by single hyphens',
171    }
172  }
173  return { ok: true, name: trimmed }
174}
175
176export function proposedBranchName(args: readonly string[]): string | null {
177  const candidate = args.find(item => {
178    const trimmed = item.trim()
179    return trimmed !== '' && !trimmed.startsWith('--') && !trimmed.startsWith('ri.')
180  })
181  return candidate ? candidate.trim() : null
182}
183
184const isBranchFlag = (value: unknown) =>
185  typeof value === 'string' && value.replace(/^-+/, '').toLowerCase() === 'branch'
186
187function targetsProtected(input: unknown): boolean {
188  if (typeof input === 'string') return false
189  if (Array.isArray(input)) {
190    const flagPair = input.some((flag, index) => {
191      const value = input[index + 1]
192      return isBranchFlag(flag) && typeof value === 'string' && isProtectedValue(value)
193    })
194    return flagPair || input.some(item => targetsProtected(item))
195  }
196  if (typeof input !== 'object' || input === null) return false
197  return Object.entries(input).some(([key, value]) => {
198    const field = key.replace(/^-+/, '').toLowerCase()
199    const isBranchField = field === 'branch' || field === 'branchname' || field === 'branch_name'
200    return (
201      (isBranchField && typeof value === 'string' && isProtectedValue(value)) ||
202      targetsProtected(value)
203    )
204  })
205}
206
207export const unquote = (value: string) => value.trim().replace(/^(['"])(.*)\1$/, '$2')
208
209/** Every value of the named flags (`--name value`, `--name=value`, `-bvalue`), unquoted; '' for a flag with no value. */
210export function flagValues(args: readonly string[], names: readonly string[]): string[] {
211  const found: string[] = []
212  for (let index = 0; index < args.length; index += 1) {
213    const arg = unquote(args[index] ?? '')
214    for (const name of names) {
215      if (arg === name) {
216        const value = unquote(args[index + 1] ?? '')
217        if (value === '' || value.startsWith('-')) found.push('')
218        else {
219          found.push(value)
220          index += 1
221        }
222        break
223      }
224      if (arg.startsWith(`${name}=`)) {
225        found.push(unquote(arg.slice(name.length + 1)))
226        break
227      }
228      if (/^-[a-z]$/.test(name) && arg.startsWith(name) && arg.length > 2) {
229        found.push(unquote(arg.slice(2)))
230        break
231      }
232    }
233  }
234  return found
235}
236
237/** The first value of `--name value` or `--name=value`, unquoted; '' when the flag has no value. */
238export function flagValue(args: readonly string[], name: string): string | null {
239  return flagValues(args, [name])[0] ?? null
240}
241
242const positionals = (args: readonly string[]) => {
243  const found: string[] = []
244  for (let index = 0; index < args.length; index += 1) {
245    const arg = unquote(args[index] ?? '')
246    if (arg.startsWith('-')) {
247      const takesValue = !arg.includes('=') && !BOOLEAN_FLAGS.has(arg.toLowerCase())
248      if (takesValue && args[index + 1] !== undefined && !unquote(args[index + 1] ?? '').startsWith('-')) index += 1
249      continue
250    }
251    found.push(arg)
252  }
253  return found
254}
255
256/** Why the branch rule refuses this Orthanc write, or null. Applies in every approval mode. */
257export function branchRuleReason(command: string, args: readonly string[]): string | null {
258  if (MAIN_ONLY_WRITES.has(command)) {
259    return `'${command}' writes live data on the main ontology branch and cannot take --branch. Agents do not run it: use 'ontology action-apply --branch <global branch RID>' or hand it to the operator.`
260  }
261  if (PROMOTIONS.has(command)) {
262    return `'${command}' promotes work (a merge, an approval or a release). The operator does it; the agent does not.`
263  }
264  if (command === 'repository push') {
265    if (args.some(arg => unquote(arg).replace(/=.*$/, '').toLowerCase() === '--allow-default-branch')) {
266      return "'repository push --allow-default-branch' pushes to the default branch. Push to a work branch and open a pull request."
267    }
268    const found = positionals(args)
269    if (found.length !== 3) {
270      return `'repository push' takes exactly <repository rid> <local ref> <destination ref>; found ${found.length} positionals, so the destination cannot be checked.`
271    }
272    const destination = found[2]!
273    if (isProtectedValue(destination)) {
274      return `'repository push' to ${destination} targets the default branch. Push to a work branch and open a pull request.`
275    }
276    return null
277  }
278  if (!BRANCH_REQUIRED_PATHS.has(command)) return null
279  const branches = flagValues(args, BRANCH_FLAGS)
280  if (branches.length > 1) return `'${command}' names --branch ${branches.length} times. Name one work branch.`
281  const branch = branches[0] ?? null
282  if (branch === null || branch === '') {
283    return command.startsWith('ontology ')
284      ? `'${command}' names no --branch, so it would change the main ontology. Pass --branch <global branch RID> (ri.branch..branch.…); create one with 'global-branch create ${GLOBAL_BRANCH_PREFIX}<name>'.`
285      : `'${command}' names no --branch, so it would write the default branch (master). Pass --branch <work branch>; create one with 'dataset branches create <dataset> ${DATASET_BRANCH_PREFIX}<name>' or use a global branch.`
286  }
287  if (!BRANCH_VALUE.test(branch)) return `'${command}' branch '${branch}' has characters no branch name uses.`
288  if (isProtectedValue(branch)) return `'${command}' targets ${branch}. Agent work happens on branches, never on main or master.`
289  if (command.startsWith('ontology ') && !branch.startsWith(GLOBAL_BRANCH_RID)) {
290    return `'${command}' must target a global branch RID (ri.branch..branch.…), not '${branch}': only a global branch is provably not the main ontology branch.`
291  }
292  return null
293}
294
295// A release tag: what it publishes must be plain enough for the operator to
296// read the question. Anything else is refused, so nothing half-read is asked.
297const TAG_REPOSITORY = /^ri\.stemma\.main\.repository\.[A-Za-z0-9-]+$/
298const TAG_NAME = /^[A-Za-z0-9][A-Za-z0-9._+\/-]{0,127}$/
299const TAG_COMMIT = /^[0-9a-f]{40,64}$/i
300const TAG_BRANCH_RID = /^ri\.[a-z0-9-]+\.[a-z0-9-]*\.[a-z0-9-]+\.[A-Za-z0-9-]+$/
301const TAG_REFUSAL =
302  "'repository tag create --apply' must name a repository RID, a plain tag and one --commit-hash <hex> (and one plain --foundry-branch-rid, if any), so the operator can see what they approve."
303
304/** The question a `repository tag create --apply` puts to the operator, or why it is refused. */
305function releaseTagCall(args: readonly string[]): { release: string } | { error: string } {
306  // Orthanc gets the raw args, so a quoted, padded or newline-carrying arg is
307  // not what the operator would read. Any such arg is refused.
308  if (args.some(arg => unquote(arg) !== arg)) return { error: TAG_REFUSAL }
309  const found = positionals(args)
310  const repository = found[0] ?? ''
311  const tag = found[1] ?? ''
312  const commits = flagValues(args, ['--commit-hash'])
313  const links = flagValues(args, ['--foundry-branch-rid'])
314  const commit = commits[0] ?? ''
315  const link = links[0] ?? null
316  if (
317    commits.length > 1 ||
318    links.length > 1 ||
319    !TAG_REPOSITORY.test(repository) ||
320    !TAG_NAME.test(tag) ||
321    !TAG_COMMIT.test(commit) ||
322    (link !== null && !TAG_BRANCH_RID.test(link))
323  ) {
324    return { error: TAG_REFUSAL }
325  }
326  const linked = link === null ? '' : ` (linked to Foundry branch ${link})`
327  return {
328    release: `'repository tag create' publishes ${tag} at commit ${commit} of ${repository}${linked}. A tag is a release: the operator approves each one, in every mode.`,
329  }
330}
331
332function orthancClassification(
333  command: string,
334  args: readonly string[],
335  rawInput: unknown,
336  workingBranch: string | null,
337): GateClassification {
338  const base = {
339    command,
340    hasWorkingBranch: branchIsWorking(workingBranch),
341    targetsProtected: targetsProtected(rawInput),
342  }
343  if (!BRANCH_CREATION_PATHS.includes(command)) {
344    const refused = branchRuleReason(command, args)
345    const release =
346      refused === null && command === 'repository tag create' && argsNameFlag(args, ['--apply'])
347        ? releaseTagCall(args)
348        : null
349    return {
350      ...base,
351      kind: 'mutation',
352      isBranchScoped: BRANCH_REQUIRED_PATHS.has(command),
353      isDestructive: isDestructiveCommand(command) || argsHaveForce(args),
354      ...(release !== null ? release : {}),
355      ...(refused ? { error: refused } : {}),
356    }
357  }
358  const creation = { ...base, kind: 'branch-creation' as const, isBranchScoped: false, isDestructive: false }
359  const proposed = proposedBranchName(args)
360  if (proposed === null) {
361    return {
362      ...creation,
363      error: `branch creation blocked: the call proposes no branch name; name branches '${GLOBAL_BRANCH_PREFIX}<kebab>' for global branches`,
364    }
365  }
366  const validated = validateBranchName(command, proposed)
367  return validated.ok
368    ? { ...creation, targetsProtected: false, proposedName: proposed }
369    : { ...creation, proposedName: proposed, error: `branch name '${proposed}' rejected: ${validated.reason}` }
370}
371
372/** An orthanc_cli command as the manifest path it names (lowercased, longest
373 * prefix) and its args; words past the path lead the args. Classifier and
374 * executor both resolve through here, so they see the same command. The path
375 * may split across the two ('repository' plus ['tag', 'create', …]): the argv
376 * rebuilt from the path is the same words either way. */
377export function resolveOrthancCommand(
378  command: string,
379  args: readonly string[],
380  manifest: readonly ManifestCommand[],
381): { path: string; args: string[] } {
382  const words = command.trim().split(/\s+/).filter(word => word !== '')
383  const paths = new Set(manifest.map(entry => entry.path))
384  const head = words.map(word => word.toLowerCase())
385  for (const arg of args) {
386    const word = unquote(arg).toLowerCase()
387    if (!/^[a-z0-9-]+$/.test(word)) break
388    head.push(word)
389  }
390  for (let width = head.length; width >= 1; width -= 1) {
391    const path = head.slice(0, width).join(' ')
392    if (!paths.has(path)) continue
393    return width <= words.length
394      ? { path, args: [...words.slice(width), ...args] }
395      : { path, args: args.slice(width - words.length) }
396  }
397  return { path: words.join(' ').toLowerCase(), args: [...args] }
398}
399
400const SHELL_OPERATORS = ';&|()`<>'
401
402/** A shell command as segments of words: quotes kept together, split at
403 * ; & | ( ) ` < > $( and newlines. A quoted word that holds a command
404 * (`bash -c "…"`) is split again and its segments added. */
405export function shellSegments(command: string, depth = 0): string[][] {
406  const segments: string[][] = []
407  let words: string[] = []
408  let word = ''
409  let quote: string | null = null
410  let quoted = false
411  const endWord = () => {
412    if (word !== '' || quoted) words.push(word)
413    word = ''
414    quoted = false
415  }
416  const endSegment = () => {
417    endWord()
418    if (words.length > 0) segments.push(words)
419    words = []
420  }
421  for (let index = 0; index < command.length; index += 1) {
422    const char = command[index]!
423    if (quote !== null) {
424      if (char === quote) quote = null
425      else if (char === '\\' && quote === '"' && index + 1 < command.length) word += command[++index]
426      else word += char
427    } else if (char === "'" || char === '"') {
428      quote = char
429      quoted = true
430    } else if (char === '\\' && index + 1 < command.length) word += command[++index]
431    else if (char === '\n') endSegment()
432    else if (/\s/.test(char)) endWord()
433    else if (char === '$' && command[index + 1] === '(') {
434      endSegment()
435      index += 1
436    } else if (SHELL_OPERATORS.includes(char)) endSegment()
437    else word += char
438  }
439  endSegment()
440  if (depth >= 3) return segments
441  const nested = segments.flatMap(found =>
442    found.filter(item => /[\s;&|()`<>]|\$\(/.test(item)).flatMap(item => shellSegments(item, depth + 1)),
443  )
444  return [...segments, ...nested]
445}
446
447/** Where the `$(` … `)` whose `(` is at `open` ends: its `)`, or the end of
448 * `text`. Quotes and nested parentheses inside it are honored. */
449function substitutionEnd(text: string, open: number): number {
450  let depth = 0
451  let quote: string | null = null
452  for (let index = open; index < text.length; index += 1) {
453    const char = text[index]!
454    if (quote === "'") {
455      if (char === "'") quote = null
456    } else if (char === '\\') index += 1
457    else if (quote === '"') {
458      if (char === '"') quote = null
459    } else if (char === "'" || char === '"') quote = char
460    else if (char === '(') depth += 1
461    else if (char === ')' && (depth -= 1) === 0) return index
462  }
463  return text.length
464}
465
466/** Where the backquoted command whose opening backquote is at `open` ends. */
467function backquoteEnd(text: string, open: number): number {
468  for (let index = open + 1; index < text.length; index += 1) {
469    if (text[index] === '\\') index += 1
470    else if (text[index] === '`') return index
471  }
472  return text.length
473}
474
475/** The `$(…)` and backquoted commands in text the shell expands (a
476 * double-quoted word, an unquoted heredoc body). `text[at]` starts one or not. */
477function substitutionAt(text: string, at: number): { body: string; end: number } | null {
478  if (text[at] === '$' && text[at + 1] === '(') {
479    const end = substitutionEnd(text, at + 1)
480    return { body: text.slice(at + 2, end), end }
481  }
482  if (text[at] === '`') {
483    const end = backquoteEnd(text, at)
484    return { body: text.slice(at + 1, end), end }
485  }
486  return null
487}
488
489function substitutionsIn(text: string): string[] {
490  const found: string[] = []
491  for (let index = 0; index < text.length; index += 1) {
492    if (text[index] === '\\') {
493      index += 1
494      continue
495    }
496    const substitution = substitutionAt(text, index)
497    if (substitution === null) continue
498    found.push(substitution.body)
499    index = substitution.end
500  }
501  return found
502}
503
504/** What a command does with the text fed to its stdin by a heredoc or a
505 * here-string: a shell (or ssh) runs it as shell code, an interpreter runs it
506 * as its own code, anything else reads it as data. */
507function stdinReader(words: readonly string[]): 'shell' | 'interpreter' | null {
508  let head = 0
509  while (head < words.length && ASSIGNMENT.test(words[head]!)) head += 1
510  if (head >= words.length || NON_EXECUTING.has(basename(words[head]))) return null
511  if (words.some(word => SHELLS.test(basename(word)) || basename(word) === 'ssh')) return 'shell'
512  if (words.some(word => CODE_RUNNERS.test(basename(word)))) return 'interpreter'
513  return null
514}
515
516/** One pass over a shell line as the shell reads it: the words of each simple
517 * command, plus the command text the shell runs from inside words (`$(…)` and
518 * backquotes in double quotes or an unquoted heredoc). Redirect targets are
519 * data. A heredoc or here-string is data too, unless its command reads stdin
520 * as code: then a shell's text is code, and an interpreter's text that
521 * mentions orthanc makes the line `hidden`. Single-quoted text stays literal. */
522function shellWords(command: string): { segments: string[][]; code: string[]; hidden: boolean } {
523  const segments: string[][] = []
524  const code: string[] = []
525  const heredocs: { delimiter: string; expands: boolean; tabs: boolean; owner: string[] }[] = []
526  // Text fed to a command's stdin, judged once its line is complete.
527  const fed: { owner: string[]; text: string }[] = []
528  let words: string[] = []
529  let word = ''
530  let quote: string | null = null
531  let quoted = false
532  let target: 'file' | 'herestring' | 'heredoc' | 'heredoc-tabs' | null = null
533  const endWord = () => {
534    if (word !== '' || quoted) {
535      if (target === 'heredoc' || target === 'heredoc-tabs') {
536        heredocs.push({ delimiter: word, expands: !quoted, tabs: target === 'heredoc-tabs', owner: words })
537      } else if (target === 'herestring') fed.push({ owner: words, text: word })
538      else if (target === null) words.push(word)
539      target = null
540    }
541    word = ''
542    quoted = false
543  }
544  const endSegment = () => {
545    endWord()
546    target = null
547    if (words.length > 0) segments.push(words)
548    words = []
549  }
550  // At a newline: skip the bodies of the heredocs opened on the line that ends here.
551  const skipHeredocs = (newline: number): number => {
552    let end = newline
553    for (const heredoc of heredocs.splice(0)) {
554      const body: string[] = []
555      while (end < command.length) {
556        const start = end + 1
557        const next = command.indexOf('\n', start)
558        end = next < 0 ? command.length : next
559        const line = command.slice(start, end)
560        if ((heredoc.tabs ? line.replace(/^\t+/, '') : line) === heredoc.delimiter) break
561        body.push(line)
562      }
563      if (heredoc.expands) code.push(...substitutionsIn(body.join('\n')))
564      fed.push({ owner: heredoc.owner, text: body.join('\n') })
565    }
566    return end
567  }
568  for (let index = 0; index < command.length; index += 1) {
569    const char = command[index]!
570    if (quote === "'") {
571      if (char === "'") quote = null
572      else word += char
573      continue
574    }
575    if (quote === '"') {
576      const substitution = substitutionAt(command, index)
577      if (char === '"') quote = null
578      else if (char === '\\' && index + 1 < command.length) word += command[++index]
579      else if (substitution !== null) {
580        code.push(substitution.body)
581        word += command.slice(index, substitution.end + 1)
582        index = substitution.end
583      } else word += char
584      continue
585    }
586    if (char === "'" || char === '"') {
587      quote = char
588      quoted = true
589    } else if (char === '\\' && index + 1 < command.length) word += command[++index]
590    else if (char === '\n') {
591      endSegment()
592      index = skipHeredocs(index)
593    } else if (/\s/.test(char)) endWord()
594    else if (char === '$' && command[index + 1] === '(') {
595      endSegment()
596      index += 1
597    } else if (char === '<' || char === '>' || (char === '&' && command[index + 1] === '>')) {
598      // A file descriptor glued to the redirect (`2>`, `0<<`) is not a word.
599      if (!quoted && /^[0-9]+$/.test(word)) word = ''
600      endWord()
601      let last = index
602      while ('<>&|'.includes(command[last + 1] ?? ' ')) last += 1
603      const operator = command.slice(index, last + 1)
604      index = last
605      if (command[last + 1] === '(') {
606        // <(…) and >(…) run a command: read it as its own segment.
607        endSegment()
608        index += 1
609      } else if (operator === '<<<') target = 'herestring'
610      else if (operator === '<<') {
611        const tabs = command[last + 1] === '-'
612        if (tabs) index += 1
613        target = tabs ? 'heredoc-tabs' : 'heredoc'
614      } else target = 'file'
615    } else if (SHELL_OPERATORS.includes(char)) endSegment()
616    else word += char
617  }
618  endSegment()
619  let hidden = false
620  for (const { owner, text } of fed) {
621    const reader = stdinReader(owner)
622    if (reader === 'shell') code.push(text)
623    else if (reader === 'interpreter' && MENTIONS_ORTHANC.test(text)) hidden = true
624  }
625  return { segments, code, hidden }
626}
627
628const SHELLS = /^(sh|bash|zsh|dash|ksh|mksh|ash|fish|busybox)$/
629// Heads whose following words are one command line the shell runs (eval, ssh host …).
630const LINE_RUNNERS = new Set(['eval', 'ssh', 'watch', 'tmux', 'screen', 'parallel'])
631const CODE_FLAG = /^-[A-Za-z]*[cS]$/
632const NESTING_LIMIT = 3
633// Words after which a later word is the program that runs (`docker exec -i c sh`).
634const LAUNCHERS = new Set([
635  'exec', 'run', 'ssh', 'sudo', 'doas', 'env', 'xargs', 'nohup', 'timeout', 'nice', 'stdbuf', 'setsid', 'chroot',
636  'unshare', 'nsenter', 'flock', 'time', 'command', 'caffeinate',
637])
638// A segment hidesOrthanc refuses whenever the line mentions orthanc.
639const UNREADABLE = ['$']
640
641/** The words of a segment that the shell runs as code: the value after -c
642 * (sh -c, bash -lc, su -c, npx -c), env -S, and everything after eval or ssh.
643 * Free-text heads (git, echo, grep, …) run none of their words. */
644function codeWords(words: readonly string[]): string[] {
645  let head = 0
646  while (head < words.length && ASSIGNMENT.test(words[head]!)) head += 1
647  if (head >= words.length || NON_EXECUTING.has(basename(words[head]))) return []
648  const code: string[] = []
649  for (let index = head; index < words.length; index += 1) {
650    if (LINE_RUNNERS.has(basename(words[index]))) {
651      code.push(words.slice(index + 1).join(' '))
652      break
653    }
654    if (CODE_FLAG.test(words[index]!) && words[index + 1] !== undefined) code.push(words[index + 1]!)
655  }
656  return code
657}
658
659/** The simple commands a Bash line runs, for the Orthanc guard. Unlike
660 * shellSegments, a quoted word is read as a command only where the shell runs
661 * it (see codeWords and shellWords), so free text that mentions orthanc in a
662 * commit message, a PR body or an echo stays text. Code nested past the limit
663 * comes back as a `$` segment, which hidesOrthanc refuses. */
664export function commandSegments(command: string, depth = 0): string[][] {
665  const { segments, code, hidden } = shellWords(command)
666  const own = hidden ? [...segments, UNREADABLE] : segments
667  const nested = [...code, ...segments.flatMap(codeWords)].filter(item => item.trim() !== '')
668  if (nested.length === 0) return own
669  if (depth >= NESTING_LIMIT) return [...own, UNREADABLE]
670  return [...own, ...nested.flatMap(item => commandSegments(item, depth + 1))]
671}
672
673const basename = (word: string | undefined) => (word ?? '').split('/').at(-1)?.replace(/^!/, '') ?? ''
674const ASSIGNMENT = /^[A-Za-z_][A-Za-z0-9_]*=/
675const MENTIONS_ORTHANC = /(^|[^\w/.-])orthanc([^\w.-]|$)|ORTHANC_BIN/i
676const isOrthancWord = (word: string) => basename(word).toLowerCase() === 'orthanc' || /\$\{?ORTHANC_BIN\}?/.test(word)
677const WRAPPERS = new Set([
678  'env', 'command', 'exec', 'time', 'nohup', 'sudo', 'doas', 'xargs', 'nice', 'timeout', 'caffeinate',
679  'builtin', 'stdbuf', 'then', 'do', 'else', '!', '{',
680])
681const INDIRECT = new Set(['eval', 'source', '.'])
682const CODE_RUNNERS = /^(python[0-9.]*|node|deno|bun|ruby|perl|osascript|awk)$/
683
684// Heads that name orthanc without running it (`grep orthanc`, `cd orthanc`).
685const NON_EXECUTING = new Set([
686  'grep', 'egrep', 'fgrep', 'rg', 'ag', 'cat', 'bat', 'less', 'more', 'head', 'tail', 'wc', 'ls', 'cd', 'pushd',
687  'man', 'which', 'whereis', 'type', 'echo', 'printf', 'git', 'make', 'file', 'stat', 'open', 'code', 'vim',
688  'nano', 'brew', 'mkdir', 'rm', 'cp', 'mv', 'touch', 'tree', 'du', 'diff', 'cargo', 'sed', 'awk',
689])
690
691/** Where Orthanc starts in a segment: the command word, or the first orthanc
692 * word after any head that can run another program (env, sudo, xargs, find
693 * -exec, npx, ssh, `!`, …). -1 when the segment does not run Orthanc. */
694function orthancStart(words: readonly string[]): number {
695  let index = 0
696  while (index < words.length && ASSIGNMENT.test(words[index]!)) index += 1
697  if (index >= words.length) return -1
698  if (isOrthancWord(words[index]!)) return index
699  if (NON_EXECUTING.has(basename(words[index]))) return -1
700  return words.findIndex((word, position) => position > index && isOrthancWord(word))
701}
702
703/** True when a segment runs Orthanc in a form the parser cannot read: a
704 * variable or eval as the command, code passed to an interpreter, or an
705 * Orthanc command stored in a variable. `command` is the whole shell line. */
706function hidesOrthanc(words: readonly string[], command: string): boolean {
707  if (!MENTIONS_ORTHANC.test(command)) return false
708  let index = 0
709  // Wrappers, their flags and the numbers they take (`timeout 5`, `nice -n 10`).
710  while (index < words.length && (ASSIGNMENT.test(words[index]!) || WRAPPERS.has(basename(words[index])) || words[index]!.startsWith('-') || /^[0-9.]+[smhd]?$/.test(words[index]!))) {
711    if (ASSIGNMENT.test(words[index]!) && MENTIONS_ORTHANC.test(words[index]!.replace(ASSIGNMENT, ''))) return true
712    index += 1
713  }
714  const head = words[index]
715  if (head === undefined) return false
716  if (head.startsWith('$')) return true
717  const rest = words.slice(index + 1)
718  if (INDIRECT.has(head)) return rest.some(word => MENTIONS_ORTHANC.test(word))
719  // A shell or interpreter in command position (the head, after `--`, or after
720  // a launcher such as `kubectl exec -i p -- bash`, `docker exec -i c sh`)
721  // reads its code from stdin when it has no script, a script of - or
722  // /dev/stdin, or (a shell) -s.
723  const runner = words.findIndex(
724    (word, position) =>
725      position >= index &&
726      (SHELLS.test(basename(word)) || CODE_RUNNERS.test(basename(word))) &&
727      (position === index || words[position - 1] === '--' || words.slice(index, position).some(earlier => LAUNCHERS.has(basename(earlier)))),
728  )
729  if (runner >= 0 && (runner === index || !NON_EXECUTING.has(basename(head)))) {
730    const after = words.slice(runner + 1)
731    const script = after.find(word => word === '-' || !word.startsWith('-'))
732    if (script === undefined || script === '-' || script === '/dev/stdin') return true
733    if (SHELLS.test(basename(words[runner])) && after.some(word => /^-[A-Za-z]*s[A-Za-z]*$/.test(word))) return true
734  }
735  // Interpreter code inline (`python3 -c "…orthanc…"`): a word holding code, or the one after -c/-e.
736  return CODE_RUNNERS.test(basename(head)) &&
737    rest.some((word, position) => MENTIONS_ORTHANC.test(word) && (/[\s()'"\[\];]/.test(word) || /^-(c|e|-eval)$/.test(rest[position - 1] ?? '')))
738}
739
740/** The Orthanc command a Bash segment runs: global flags skipped, then the longest manifest path. */
741function orthancShellCall(
742  words: readonly string[],
743  start: number,
744  manifest: readonly ManifestCommand[],
745): { path: string; known: boolean; help: boolean } {
746  const rest = words.slice(start + 1)
747  let index = 0
748  while (index < rest.length && rest[index]!.startsWith('-')) index += rest[index] === '--profile' ? 2 : 1
749  const tail = rest.slice(index)
750  const ended = rest.indexOf('--')
751  const flags = ended < 0 ? rest : rest.slice(0, ended)
752  const help = flags.some(word => ['-h', '--help', '-V', '--version'].includes(word)) || tail[0] === 'help'
753  const leading: string[] = []
754  for (const word of tail) {
755    if (word.startsWith('-')) break
756    leading.push(word)
757  }
758  const paths = new Set(manifest.map(entry => entry.path))
759  for (let width = leading.length; width >= 1; width -= 1) {
760    const path = leading.slice(0, width).join(' ').toLowerCase()
761    if (paths.has(path)) return { path, known: true, help }
762  }
763  return { path: leading.join(' ').toLowerCase(), known: false, help }
764}
765
766// Bash may read through Orthanc; every Orthanc write goes through orthanc_cli,
767// where the branch rule and the ladder see its arguments as data, not shell.
768function shellClassification(
769  command: string,
770  manifest: readonly ManifestCommand[],
771  workingBranch: string | null,
772): GateClassification | null {
773  const refuse = (path: string | null, error: string): GateClassification => ({
774    command: path,
775    kind: 'mutation',
776    isBranchScoped: false,
777    hasWorkingBranch: branchIsWorking(workingBranch),
778    targetsProtected: false,
779    isDestructive: false,
780    error,
781  })
782  for (const words of commandSegments(command)) {
783    if (hidesOrthanc(words, command)) {
784      return refuse(null, 'This shell command runs Orthanc in a form the Foundry guard cannot read (a variable, eval or interpreter code). Run Orthanc reads as plain `orthanc …` and writes with orthanc_cli.')
785    }
786    const start = orthancStart(words)
787    if (start < 0) continue
788    const call = orthancShellCall(words, start, manifest)
789    if (call.path === '' && !call.help && /\$|`/.test(command)) {
790      return refuse(null, 'This shell command builds an Orthanc command from a substitution or variable, which the Foundry guard cannot read. Run Orthanc reads as plain `orthanc …` and writes with orthanc_cli.')
791    }
792    if (call.help || call.path === '' || call.path === 'repository clone') continue
793    if (!call.known) {
794      return refuse(call.path, `Bash runs 'orthanc ${call.path}', which is not a command in Orthanc's agent manifest. Look it up with orthanc_help, then run it with orthanc_cli.`)
795    }
796    if (classifyOrthancCommand(call.path, manifest) === 'read') continue
797    return refuse(call.path, `Orthanc writes run through orthanc_cli, where the branch rule and approval ladder apply, not Bash. Run '${call.path}' with orthanc_cli.`)
798  }
799  return null
800}
801
802const PALANTIR_MCP = /^mcp__palantir(-mcp)?__/
803const WRITE_WORDS = new Set(['add', 'apply', 'build', 'create', 'delete', 'deploy', 'edit', 'install', 'post', 'publish', 'put', 'remove', 'rename', 'set', 'submit', 'update', 'write'])
804const AMBIGUOUS_WORDS = new Set(['call', 'execute', 'invoke', 'run', 'trigger'])
805const READ_WORDS = new Set(['check', 'describe', 'get', 'health', 'inspect', 'list', 'preview', 'query', 'read', 'search', 'view'])
806
807export function classifyMcpIntent(inner: string): 'read' | 'write' | 'unknown' {
808  const words = inner.toLowerCase().split(/[^a-z]+/)
809  if (words.some(word => WRITE_WORDS.has(word))) return 'write'
810  if (words.some(word => AMBIGUOUS_WORDS.has(word))) return 'unknown'
811  if (words.some(word => READ_WORDS.has(word))) return 'read'
812  return 'unknown'
813}
814
815/** A Foundry call the guard cannot read: blocked in every mode, so it never runs blind. */
816function unreadableCall(input: unknown, workingBranch: string | null, error: string): GateClassification {
817  return {
818    command: null,
819    kind: 'mutation',
820    isBranchScoped: false,
821    hasWorkingBranch: branchIsWorking(workingBranch),
822    targetsProtected: targetsProtected(input),
823    isDestructive: false,
824    error,
825  }
826}
827
828/** Null: a read, or a tool outside the Foundry lane. Never reaches the ladder. */
829export function classifyCall(
830  tool: string,
831  input: Record<string, unknown>,
832  manifest: readonly ManifestCommand[],
833  workingBranch: string | null,
834): GateClassification | null {
835  if (tool === ORTHANC_CLI) {
836    // Without the manifest the guard cannot tell which command this call runs, and
837    // the executor loads the manifest again for itself. Nothing unreadable runs.
838    if (manifest.length === 0) {
839      return unreadableCall(input, workingBranch, "Orthanc's agent manifest could not be loaded, so the Foundry guard cannot tell which command this call runs. Try again.")
840    }
841    const raw = typeof input.command === 'string' ? input.command : ''
842    const resolved = resolveOrthancCommand(raw, Array.isArray(input.args) ? input.args.map(String) : [], manifest)
843    // Words that name no command at all: nothing safe to run, so nothing runs.
844    if (resolved.path === '' && resolved.args.length > 0) {
845      return unreadableCall(input, workingBranch, `Orthanc's agent manifest has no command starting with '${resolved.args.join(' ')}'. Look it up with orthanc_help, then call orthanc_cli with the command name in \`command\`.`)
846    }
847    if (resolved.path === '' || resolved.path === 'repository clone') return null
848    if (classifyOrthancCommand(resolved.path, manifest) === 'read') return null
849    return orthancClassification(resolved.path, resolved.args, { ...input, args: resolved.args }, workingBranch)
850  }
851  if (tool === 'Bash' && typeof input.command === 'string') return shellClassification(input.command, manifest, workingBranch)
852  if (PALANTIR_MCP.test(tool)) {
853    const inner = tool.replace(PALANTIR_MCP, '')
854    if (classifyMcpIntent(inner) === 'read') return null
855    return {
856      command: null,
857      kind: 'mutation',
858      isBranchScoped: false,
859      hasWorkingBranch: branchIsWorking(workingBranch),
860      targetsProtected: targetsProtected(input),
861      isDestructive: inner.toLowerCase().split(/[^a-z]+/).includes('delete'),
862      error: `${tool} writes to Foundry outside Orthanc, with no branch. Orthanc is the only write path: use orthanc_cli with --branch.`,
863    }
864  }
865  return null
866}
867
868export function ladderDecision(
869  mode: ApprovalMode,
870  classification: GateClassification,
871  verdict?: GuardVerdict | null,
872): LadderDecision {
873  if (classification.error) return { outcome: 'block', reason: classification.error }
874  if (classification.release) return { outcome: 'ask', reason: classification.release }
875  if (classification.kind === 'branch-creation') {
876    if (mode === 'ask-always') {
877      return {
878        outcome: 'ask',
879        reason: `ask-always mode: branch creation '${classification.proposedName ?? '?'}' waits for approval`,
880      }
881    }
882    return { outcome: 'run', reason: 'branch creation is pre-authorized and reversible' }
883  }
884  const command = classification.command ?? '(foundry mcp write)'
885  const note = verdict ? ` ${verdict.reason}` : ''
886  if (classification.isDestructive) {
887    return { outcome: 'ask', reason: `destructive mutation '${command}' asks in every mode${note}` }
888  }
889  if (classification.targetsProtected && mode !== 'yolo') {
890    return {
891      outcome: 'ask',
892      reason: `'${command}' targets a protected baseline (main/master branch or the production ontology)${note}`,
893    }
894  }
895  if (mode === 'yolo') return { outcome: 'run', reason: 'yolo mode: no guardrails outside destructive paths' }
896  if (mode === 'ask-always') return { outcome: 'ask', reason: `ask-always mode: mutation '${command}' waits for approval` }
897  if (mode === 'allow-edits') return { outcome: 'run', reason: 'allow-edits mode: non-protected mutations run' }
898  if (!verdict) return { outcome: 'ask', reason: `'${command}': guard unavailable; failing closed to a human decision` }
899  if (verdict.action === 'approve') return { outcome: 'run', reason: verdict.reason }
900  return { outcome: 'ask', reason: `'${command}': ${verdict.reason}` }
901}
902
903export function modeGuidance(mode: ApprovalMode): string {
904  return (
905    'Branch rule: agent work happens on branches, never on a production main. Every ontology write ' +
906    'passes --branch <global branch RID> (ri.branch..branch.…; create one with global-branch create agent/<name>); ' +
907    'dataset, stream and build writes pass --branch <work branch>; code goes to a work branch and a pull request. ' +
908    'Writes without a branch, merges and default-branch pushes are blocked in every mode. ' +
909    'Release tags (repository tag create --apply) ask the operator in every mode. ' +
910    `Foundry approval mode: ${mode}. Foundry mutations may surface an approval dialog for the ` +
911    'operator: the call continues once approved; if the operator declines or no one can be asked, ' +
912    'the call is blocked — report it, do not retry blindly.'
913  )
914}
915
916const COMPASS_ROOT = 'ri.compass.main.folder.0'
917
918function containsCompassRoot(value: unknown): boolean {
919  if (typeof value === 'string') return value.trim().toLowerCase() === COMPASS_ROOT
920  if (Array.isArray(value)) return value.some(containsCompassRoot)
921  if (typeof value === 'object' && value !== null) return Object.values(value).some(containsCompassRoot)
922  return false
923}
924
925export function compassRootReason(tool: string, input: unknown): string | null {
926  if (!containsCompassRoot(input)) return null
927  return `Compass root folder ${COMPASS_ROOT} is not a valid scope for ${tool}. Provide a verified child folder RID; root resource search is not supported.`
928}
929
930function stable(value: unknown): unknown {
931  if (Array.isArray(value)) return value.map(stable)
932  if (typeof value !== 'object' || value === null) return value
933  return Object.fromEntries(
934    Object.entries(value).sort(([left], [right]) => left.localeCompare(right)),
935  )
936}
937
938/** Third consecutive identical call (tool + top-level-sorted input) is blocked. */
939export function loopStep(
940  previous: { identity: string; streak: number } | null,
941  tool: string,
942  input: unknown,
943): { next: { identity: string; streak: number }; reason: string | null } {
944  const identity = JSON.stringify({ input: stable(input), tool })
945  const streak = previous?.identity === identity ? previous.streak + 1 : 1
946  const reason =
947    streak > 2
948      ? 'Loop guard blocks a third identical tool call. Use existing evidence or change the experiment.'
949      : null
950  return { next: { identity, streak }, reason }
951}
952
953// Raw `git push` from a Foundry clone skips Orthanc's default-branch refusal.
954// Every directory a `git … push` in a shell command could run in: '' (the
955// session's), each cd/pushd target, each -C, --git-dir and --work-tree value.
956// Over-counting only costs a remote check. Null when nothing pushes.
957export function gitPushDirectories(command: string): string[] | null {
958  const directories = new Set<string>([''])
959  let pushes = false
960  for (const words of shellSegments(command)) {
961    words.forEach((word, index) => {
962      if (word === 'cd' || word === 'pushd') {
963        const target = words.slice(index + 1).find(next => !next.startsWith('-'))
964        if (target !== undefined) directories.add(target)
965      }
966      const env = /^(?:GIT_DIR|GIT_WORK_TREE)=(.+)$/.exec(word)
967      if (env) directories.add(env[1]!)
968    })
969    const git = words.findIndex(word => basename(word) === 'git')
970    if (git < 0) continue
971    const rest = words.slice(git + 1)
972    for (let index = 0; index < rest.length; index += 1) {
973      const word = rest[index]!
974      if (word === '-C' || word === '--git-dir' || word === '--work-tree') {
975        if (rest[index + 1] !== undefined) directories.add(rest[index + 1]!)
976        index += 1
977        continue
978      }
979      if (word === '-c' || word === '--namespace' || word === '--config-env') {
980        // An alias set on the command line can be push under another name.
981        if (/^alias\./i.test(rest[index + 1] ?? '')) pushes = true
982        index += 1
983        continue
984      }
985      const joined = /^--(git-dir|work-tree)=(.+)$/.exec(word)
986      if (joined) directories.add(joined[2]!)
987      if (word.startsWith('-')) continue
988      if (word === 'push') pushes = true
989      break
990    }
991  }
992  return pushes ? [...directories] : null
993}
994
995/** A push that names a Foundry repository URL outright, from any directory. */
996export function gitPushNamesFoundry(command: string): boolean {
997  return gitPushDirectories(command) !== null && command.includes('ri.stemma.')
998}
999
1000export const FOUNDRY_GIT_PUSH_REASON =
1001  "Raw 'git push' to a Foundry code repository bypasses Orthanc. Push with " +
1002  "'orthanc repository push <repository rid> refs/heads/<work branch> refs/heads/<work branch>' and open a pull request; it refuses the default branch."
1003
1004// The operator's files steer the write guard and the trace export, so only the
1005// operator edits them: ~/.claude/foundry/ (rules.md, otel.env) and a project's
1006// .claude/foundry-rules.md. otel.env can name a collector and key references,
1007// so Claude does not read the directory either. The mod reads them once at
1008// session start, so a change made mid-session waits for the next one.
1009const FILE_WRITERS = new Set(['Write', 'Edit', 'MultiEdit', 'NotebookEdit'])
1010const FILE_READERS = new Set(['Read', 'Grep', 'Glob', 'LS'])
1011const PROTECTED_FILE = /(^|\/)\.claude\/(foundry-rules\.md|foundry(\/|$))/
1012const SECRET_DIR = /(^|\/)\.claude\/foundry(\/|$)/
1013// Any shell mention of these is denied, read or write.
1014const SHELL_PROTECTED = /\.claude\/+(\.\/+)*foundry\b|foundry-rules|otel\.env|\.claude\/*\*/i
1015// A loose mention (a relative foundry/…md path) is denied with a writer.
1016const SHELL_MENTION = /\bfound\S*\/\S*\.md/i
1017const SHELL_WRITES =
1018  /(>|\btee\b|\bsed\b|\bmv\b|\bcp\b|\brm\b|\bln\b|\btruncate\b|\binstall\b|\bdd\b|\btouch\b|\bperl\b|\bpython[0-9.]*\b|\bnode\b|\bruby\b|\bed\b|\bex\b|\bvim?\b|\bnvim\b|\bcurl\b|\bwget\b|\bchmod\b|\bunlink\b|\brsync\b|\bbun\b|\bdeno\b|\bphp\b|\bawk\b|\blua\b|\bswift\b|\bosascript\b|\btar\b|\bunzip\b|\bcpio\b|\bditto\b|\bpatch\b|\bgit\b|\b(ba|z|da|k|c|tc|fi)?sh\b)/
1019// Removing or moving ~/.claude itself removes the operator's rules with it.
1020const CLAUDE_DIR_REMOVAL = /\b(rm|mv|rsync|unlink)\b[^;&|]*\.claude\/?(?=["'\s;&|)]|$)/
1021export const RULES_WRITE_REASON =
1022  'Foundry operator files (~/.claude/foundry/: rules.md, otel.env; .claude/foundry-rules.md) steer the write guard and tracing, so only the operator reads and edits them. Suggest the change and let the operator make it.'
1023
1024/** A file path as the filesystem sees it: absolute against `cwd`, ~ expanded, . and // collapsed, lowercased (macOS). */
1025export function normalizedPath(path: string, cwd: string, home: string): string {
1026  const expanded = path.trim().replace(/^~(?=\/|$)/, home)
1027  const absolute = expanded.startsWith('/') ? expanded : `${cwd.replace(/\/$/, '')}/${expanded}`
1028  const parts: string[] = []
1029  for (const part of absolute.split('/')) {
1030    if (part === '' || part === '.') continue
1031    if (part === '..') parts.pop()
1032    else parts.push(part)
1033  }
1034  return `/${parts.join('/')}`.toLowerCase()
1035}
1036
1037export function rulesWriteReason(tool: string, input: Record<string, unknown>, cwd = '/', home = ''): string | null {
1038  const paths = [input.file_path, input.notebook_path, input.path].filter((value): value is string => typeof value === 'string')
1039  if (FILE_WRITERS.has(tool) && paths.some(path => PROTECTED_FILE.test(normalizedPath(path, cwd, home)))) return RULES_WRITE_REASON
1040  if (FILE_READERS.has(tool)) {
1041    const base = paths[0] ?? cwd
1042    const targets = [base, ...(typeof input.pattern === 'string' && tool === 'Glob' ? [`${base.replace(/\/$/, '')}/${input.pattern}`] : [])]
1043    const NAMES_OPERATOR_FILES = /otel|foundry-rules|\.claude/i
1044    if (typeof input.glob === 'string' && NAMES_OPERATOR_FILES.test(input.glob)) return RULES_WRITE_REASON
1045    if (tool === 'Glob' && typeof input.pattern === 'string' && NAMES_OPERATOR_FILES.test(input.pattern)) return RULES_WRITE_REASON
1046    // A search rooted at ~/.claude reaches the directory; one rooted at ~ is left
1047    // alone (it would stop every home-directory session), and otel.env holds only references.
1048    if (tool !== 'Read' && home !== '' && normalizedPath(base, cwd, home) === normalizedPath('~/.claude', '/', home)) return RULES_WRITE_REASON
1049    if (targets.some(target => SECRET_DIR.test(normalizedPath(target, cwd, home)))) return RULES_WRITE_REASON
1050  }
1051  if (tool === 'Bash' && typeof input.command === 'string') {
1052    const command = input.command
1053    if (SHELL_PROTECTED.test(command) || CLAUDE_DIR_REMOVAL.test(command)) return RULES_WRITE_REASON
1054    if (SHELL_MENTION.test(command) && SHELL_WRITES.test(command)) return RULES_WRITE_REASON
1055    if (PROTECTED_FILE.test(normalizedPath(cwd, '/', home))) return RULES_WRITE_REASON
1056  }
1057  return null
1058}
1059
hooks/telemetry.ts 306 lines
1// Trace export: one OTLP trace per Foundry turn, sent to any OTLP/HTTP
2// collector (Langfuse's /api/public/otel among them). Pure functions: the
3// hooks hold the state and do the fetch. Every exported value is redacted at
4// source; a value that cannot be serialized is dropped, never sent raw.
5
6export type TraceConfig = { url: string; headers: Record<string, string>; host: string; toolIo: boolean }
7
8export type TraceEnv = Partial<Record<string, string>>
9
10export const TRACE_ENV_KEYS: readonly string[] = [
11  'OTEL_EXPORTER_OTLP_TRACES_ENDPOINT',
12  'OTEL_EXPORTER_OTLP_ENDPOINT',
13  'OTEL_EXPORTER_OTLP_HEADERS',
14  'LANGFUSE_BASE_URL',
15  'LANGFUSE_HOST',
16  'LANGFUSE_PUBLIC_KEY',
17  'LANGFUSE_SECRET_KEY',
18  'FOUNDRY_OTEL',
19  'FOUNDRY_OTEL_TOOL_IO',
20  'PALANTIR_AGENT_OTEL_TOOL_IO',
21  'OTEL_SERVICE_NAME',
22  'OTEL_RESOURCE_ATTRIBUTES',
23  'FOUNDRY_OTEL_REDACT_DOMAINS',
24]
25
26/**
27 * An env file read as data, never run: `[export ]KEY=VALUE` lines for the
28 * TRACE_ENV_KEYS only, quotes stripped. A value that is a 1Password reference
29 * (op://vault/item/field) is returned in `refs` for the caller to resolve
30 * through `op read` by argv; anything that looks like shell ($, `) is dropped,
31 * and a credential written literally is ignored and named in `literalSecrets`.
32 */
33// Keys that carry credentials: in the file they must be op:// references, so
34// the file itself holds nothing secret even if something reads it.
35const SECRET_ENV_KEYS = new Set(['LANGFUSE_PUBLIC_KEY', 'LANGFUSE_SECRET_KEY', 'OTEL_EXPORTER_OTLP_HEADERS'])
36// A URL with userinfo or a query string can carry a credential too.
37const URL_ENV_KEYS = new Set(['OTEL_EXPORTER_OTLP_TRACES_ENDPOINT', 'OTEL_EXPORTER_OTLP_ENDPOINT', 'LANGFUSE_BASE_URL', 'LANGFUSE_HOST'])
38
39export function parseEnvFile(text: string): { env: TraceEnv; refs: Record<string, string>; literalSecrets: string[] } {
40  const env: TraceEnv = {}
41  const refs: Record<string, string> = {}
42  const literalSecrets: string[] = []
43  for (const raw of text.split(/\r?\n/)) {
44    const match = /^\s*(?:export\s+)?([A-Z_][A-Z0-9_]*)=(.*)$/.exec(raw)
45    if (!match || !TRACE_ENV_KEYS.includes(match[1]!)) continue
46    let value = match[2]!.trim()
47    const quoted = /^(["'])(.*)\1$/.exec(value)
48    if (quoted) value = quoted[2]!
49    else value = value.replace(/\s+#.*$/, '')
50    if (value === '' || /[`$]/.test(value)) continue
51    if (/^op:\/\/.+/.test(value)) refs[match[1]!] = value
52    else if (SECRET_ENV_KEYS.has(match[1]!)) literalSecrets.push(match[1]!)
53    else if (URL_ENV_KEYS.has(match[1]!) && /^[a-z]+:\/\/[^/?#]*@|\?/i.test(value)) literalSecrets.push(match[1]!)
54    else env[match[1]!] = value
55  }
56  return { env, refs, literalSecrets }
57}
58
59const BASE64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
60
61function utf8(text: string): number[] {
62  const out: number[] = []
63  for (const char of text) {
64    const code = char.codePointAt(0)!
65    if (code < 0x80) out.push(code)
66    else if (code < 0x800) out.push(0xc0 | (code >> 6), 0x80 | (code & 63))
67    else if (code < 0x10000) out.push(0xe0 | (code >> 12), 0x80 | ((code >> 6) & 63), 0x80 | (code & 63))
68    else out.push(0xf0 | (code >> 18), 0x80 | ((code >> 12) & 63), 0x80 | ((code >> 6) & 63), 0x80 | (code & 63))
69  }
70  return out
71}
72
73export function base64(text: string): string {
74  const bytes = utf8(text)
75  let out = ''
76  for (let index = 0; index < bytes.length; index += 3) {
77    const [a, b, c] = [bytes[index]!, bytes[index + 1], bytes[index + 2]]
78    out += BASE64[a >> 2]! + BASE64[((a & 3) << 4) | ((b ?? 0) >> 4)]!
79    out += b === undefined ? '=' : BASE64[((b & 15) << 2) | ((c ?? 0) >> 6)]!
80    out += c === undefined ? '=' : BASE64[c & 63]!
81  }
82  return out
83}
84
85/** `k=v,k2=v2`, values percent-decoded, as the OTel spec writes OTEL_EXPORTER_OTLP_HEADERS. */
86export function parseOtlpHeaders(raw: string | undefined): Record<string, string> {
87  const headers: Record<string, string> = {}
88  for (const pair of (raw ?? '').split(',')) {
89    const at = pair.indexOf('=')
90    if (at <= 0) continue
91    try {
92      headers[pair.slice(0, at).trim()] = decodeURIComponent(pair.slice(at + 1).trim())
93    } catch {
94      headers[pair.slice(0, at).trim()] = pair.slice(at + 1).trim()
95    }
96  }
97  return headers
98}
99
100/** Where traces go, or null when tracing is off or unconfigured. OTEL_* first, then LANGFUSE_*. */
101export function traceConfig(env: TraceEnv): TraceConfig | null {
102  if ((env.FOUNDRY_OTEL ?? '').toLowerCase() === 'off') return null
103  const toolIo = ![env.FOUNDRY_OTEL_TOOL_IO, env.PALANTIR_AGENT_OTEL_TOOL_IO].some(value => (value ?? '').toLowerCase() === 'off')
104  const exact = env.OTEL_EXPORTER_OTLP_TRACES_ENDPOINT?.trim()
105  const base = env.OTEL_EXPORTER_OTLP_ENDPOINT?.trim()
106  let url = exact || (base ? `${base.replace(/\/$/, '')}/v1/traces` : '')
107  let headers = parseOtlpHeaders(env.OTEL_EXPORTER_OTLP_HEADERS)
108  const langfuse = (env.LANGFUSE_BASE_URL || env.LANGFUSE_HOST)?.trim()
109  if (url === '' && langfuse && env.LANGFUSE_PUBLIC_KEY && env.LANGFUSE_SECRET_KEY) {
110    url = `${langfuse.replace(/\/$/, '')}/api/public/otel/v1/traces`
111    headers = { Authorization: `Basic ${base64(`${env.LANGFUSE_PUBLIC_KEY}:${env.LANGFUSE_SECRET_KEY}`)}` }
112  }
113  if (!/^https?:\/\//.test(url)) return null
114  const host = /^https?:\/\/([^/?#]+)/.exec(url)?.[1]?.replace(/^[^@]*@/, '') ?? ''
115  return { url, headers: { ...headers, 'Content-Type': 'application/json' }, host, toolIo }
116}
117
118/** The OTel resource: service name and OTEL_RESOURCE_ATTRIBUTES (k=v,…), plus the mod's own. */
119export function resourceAttributes(env: TraceEnv, profile: string | null): Record<string, string> {
120  return {
121    'service.name': env.OTEL_SERVICE_NAME?.trim() || 'claude-foundry',
122    ...parseOtlpHeaders(env.OTEL_RESOURCE_ATTRIBUTES),
123    'agent.harness': 'claude-code',
124    ...(profile ? { 'palantir.agent.profile': profile } : {}),
125  }
126}
127
128/** The Langfuse public API base for a trace URL that ends in /api/public/otel/v1/traces; null for other collectors. */
129export function langfuseApiBase(config: TraceConfig): string | null {
130  const match = /^(.*\/api\/public)\/otel\/v1\/traces\/?$/.exec(config.url)
131  return match ? match[1]! : null
132}
133
134// Redaction: field names, then patterns, then URLs, before the 64 KiB cap,
135// so a secret can never straddle the cut.
136const FIELD_MAX_CHARS = 64 * 1024
137const REDACTED = '[REDACTED]'
138const SUBSTRING_KEY_TERMS = [
139  'token', 'secret', 'password', 'apikey', 'api_key', 'api-key', 'authorization', 'bearer', 'cookie',
140  'credential', 'privatekey', 'private_key', 'private-key', 'ssn', 'cardnumber', 'card_number', 'card-number',
141  'rid', 'org', 'tenant', 'space', 'host', 'cluster', 'node', 'vmid', 'ctid', 'amount', 'balance', 'price',
142]
143const EXACT_KEY_TERMS = new Set(['name', 'address', 'street', 'city'])
144const KEY_REDACTION_EXEMPT = new Set(['userid', 'user_id', 'sessionid', 'session_id'])
145
146export function isSensitiveKey(key: string): boolean {
147  const lowered = key.toLowerCase()
148  if (KEY_REDACTION_EXEMPT.has(lowered)) return false
149  return EXACT_KEY_TERMS.has(lowered) || SUBSTRING_KEY_TERMS.some(term => lowered.includes(term))
150}
151
152function redactUrls(value: string): string {
153  return value.replace(/(?<![a-z0-9+.-])([a-z][a-z0-9+.-]{0,30}:\/\/)([^\s"')\]]+)/gi, (_whole, scheme: string, rest: string) => {
154    let out = rest.replace(/^[^:@/?#]+(:[^@/?#]*)?@/, `${REDACTED}@`)
155    out = out.replace(/\?[^#\s]*/, `?${REDACTED}`)
156    out = out.replace(/(hooks\.slack\.com\/services\/)[^?\s]*/i, `$1${REDACTED}`)
157    out = out.replace(/(\/)[A-Za-z0-9_-]{20,}(?=\/|$)/g, `$1${REDACTED}`)
158    return scheme + out
159  })
160}
161
162// Token prefixes match without a leading boundary: a token glued to other text still goes.
163const REDACTION_PATTERNS: RegExp[] = [
164  /-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?(-----END [A-Z ]*PRIVATE KEY-----|$)/g,
165  /sk-(proj|ant|svcacct)-[A-Za-z0-9_-]{20,}/g,
166  /[sr]k_live_[A-Za-z0-9]{20,}\b/g,
167  /github_pat_[A-Za-z0-9_]{22,}\b/g,
168  /gh[pousr]_[A-Za-z0-9]{36,}\b/g,
169  /\beyJ[A-Za-z0-9_-]{5,}\.[A-Za-z0-9_-]{5,}\.[A-Za-z0-9_-]{5,}\b/g,
170  /A[KS]IA[0-9A-Z]{16}\b/g,
171  /xox[baprs]-[A-Za-z0-9-]{10,}\b/g,
172  /Bearer\s+[A-Za-z0-9._~+/-]+=*/gi,
173  /(?<![A-Za-z0-9._%+-])[A-Za-z0-9._%+-]{1,64}@[A-Za-z0-9.-]{1,253}\.[A-Za-z]{2,24}/g,
174  /\b\d{3}-\d{2}-\d{4}\b/g,
175  /\b[0-9]{4}[- ]?[0-9]{4}[- ]?[0-9]{4}[- ]?[0-9]{4}\b/g,
176  /\b(?:10|100)\.\d{1,3}\.\d{1,3}\.\d{1,3}\b/g,
177  /\b(?:172\.(?:1[6-9]|2\d|3[01])|192\.168)\.\d{1,3}\.\d{1,3}\b/g,
178  /(?<![A-Za-z0-9.-])[A-Za-z0-9][A-Za-z0-9.-]{0,252}\.(?:local|internal|lan|corp)\b/gi,
179  /\+?[0-9][0-9 .-]{7,}[0-9]/g,
180  /\bBasic\s+[A-Za-z0-9+/=]{8,}\b/gi,
181  /npm_[A-Za-z0-9]{30,}\b/g,
182  /\bsk-[A-Za-z0-9_-]{16,}\b/g,
183  /(?<![A-Za-z0-9_-])[A-Za-z0-9_-]{0,40}(password|passwd|pwd|token|secret|api[-_]?key|private[-_]?key|credential)[A-Za-z0-9_-]{0,40}["']?\s*[=:]\s*["']?[^\s&"',}]{4,}/gi,
184  /\b(pk|sk)-lf-[A-Za-z0-9-]{6,}/g,
185  /Authorization["']?\s*[=:]\s*["']?(Basic|Bearer)?(\s|%20)*[A-Za-z0-9._~+/=%-]{6,}/gi,
186  /Basic%20[A-Za-z0-9+/=%]{8,}/gi,
187  /(\s-u\s+|--user[=\s]+)\S+:\S+/g,
188  /\bri\.[a-z0-9-]+\.[a-z0-9-]*\.[A-Za-z0-9._-]+/g,
189]
190
191const SECRET_FLAG = /^--?(password|passwd|token|secret|api-?key|key|auth|credential|private-key)$/i
192
193/** An args array with the value after a secret-bearing flag (and --flag=value) redacted. */
194export function redactArgs(args: readonly unknown[]): unknown[] {
195  return args.map((arg, index) => {
196    if (typeof arg !== 'string') return arg
197    const joined = /^(--?[A-Za-z-]+)=/.exec(arg)
198    if (joined && SECRET_FLAG.test(joined[1]!)) return `${joined[1]}=${REDACTED}`
199    const previous = args[index - 1]
200    return typeof previous === 'string' && SECRET_FLAG.test(previous) ? REDACTED : arg
201  })
202}
203
204/** Extra hostname suffixes to redact (FOUNDRY_OTEL_REDACT_DOMAINS, comma-separated). */
205export function domainPatterns(raw: string | undefined): RegExp[] {
206  return (raw ?? '')
207    .split(',')
208    .map(domain => domain.trim().replace(/^\.+/, ''))
209    .filter(domain => /^[A-Za-z0-9.-]+$/.test(domain))
210    .map(domain => new RegExp(`(?<![A-Za-z0-9.-])[A-Za-z0-9][A-Za-z0-9.-]{0,252}\\.${domain.replace(/\./g, '\\.')}\\b`, 'gi'))
211}
212
213export function redactString(value: string, extra: readonly RegExp[] = []): string {
214  let out = redactUrls(value)
215  for (const pattern of [...REDACTION_PATTERNS, ...extra]) out = out.replace(pattern, REDACTED)
216  return out
217}
218
219const cap = (value: string) => (value.length > FIELD_MAX_CHARS ? `${value.slice(0, FIELD_MAX_CHARS)}[TRUNCATED]` : value)
220
221/** Redacted, capped JSON for one attribute; undefined when the value cannot be serialized. */
222export function serializePayload(value: unknown, extra: readonly RegExp[] = []): string | undefined {
223  if (value === undefined || value === null) return undefined
224  try {
225    const json = JSON.stringify(value, (key, item: unknown) => {
226      if (key && isSensitiveKey(key)) return REDACTED
227      if (Array.isArray(item)) return redactArgs(item)
228      if (typeof item !== 'string') return item
229      // A JSON document carried as a string (an Orthanc envelope) is redacted by key too.
230      if (/^\s*[[{]/.test(item)) {
231        let parsed: unknown
232        try {
233          parsed = JSON.parse(item)
234        } catch {}
235        if (typeof parsed === 'object' && parsed !== null) {
236          const nested = serializePayload(parsed, extra)
237          try {
238            return JSON.parse(nested ?? 'null')
239          } catch {
240            return nested
241          }
242        }
243      }
244      return redactString(item, extra)
245    })
246    return json === undefined ? undefined : cap(json)
247  } catch {
248    return undefined
249  }
250}
251
252export type SpanRecord = {
253  spanId: string
254  parentSpanId?: string
255  name: string
256  startMs: number
257  endMs: number
258  attributes: Record<string, string | number | boolean | string[]>
259  error?: string
260}
261
262export function randomHex(length: number): string {
263  let out = ''
264  while (out.length < length) out += Math.floor(Math.random() * 0x100000000).toString(16).padStart(8, '0')
265  return out.slice(0, length)
266}
267
268function attributeValue(value: string | number | boolean | string[]) {
269  if (Array.isArray(value)) return { arrayValue: { values: value.map(item => ({ stringValue: item })) } }
270  if (typeof value === 'number') return Number.isInteger(value) ? { intValue: value } : { doubleValue: value }
271  if (typeof value === 'boolean') return { boolValue: value }
272  return { stringValue: value }
273}
274
275const attributes = (record: Record<string, string | number | boolean | string[]>) =>
276  Object.entries(record).map(([key, value]) => ({ key, value: attributeValue(value) }))
277
278const nanos = (ms: number) => `${Math.round(ms)}000000`
279
280/** One trace as an OTLP/JSON ExportTraceServiceRequest body. */
281export function otlpBody(traceId: string, resource: Record<string, string>, spans: readonly SpanRecord[]): string {
282  return JSON.stringify({
283    resourceSpans: [
284      {
285        resource: { attributes: attributes(resource) },
286        scopeSpans: [
287          {
288            scope: { name: 'claude-foundry' },
289            spans: spans.map(span => ({
290              traceId,
291              spanId: span.spanId,
292              ...(span.parentSpanId ? { parentSpanId: span.parentSpanId } : {}),
293              name: span.name,
294              kind: 1,
295              startTimeUnixNano: nanos(span.startMs),
296              endTimeUnixNano: nanos(Math.max(span.endMs, span.startMs)),
297              attributes: attributes(span.attributes),
298              status: span.error ? { code: 2, message: span.error.slice(0, 500) } : { code: 1 },
299            })),
300          },
301        ],
302      },
303    ],
304  })
305}
306
types/index.d.ts 84 lines
1export type FoundryNamed = { rid: string; name: string }
2
3export type FoundryObjectType = { apiName: string; displayName: string; rid?: string }
4
5/** One Compass namespace (what orthanc calls a space): its RID, display name and path. */
6export type FoundryNamespace = { rid: string; name: string; path: string }
7
8/** The scope keys that hold selected Foundry resources. */
9export type FoundryResourceKind =
10  | 'folders'
11  | 'datasets'
12  | 'mediaSets'
13  | 'mediaItems'
14  | 'repositories'
15  | 'contourAnalyses'
16  | 'sources'
17  | 'developerConsoles'
18  | 'aipChatbots'
19  | 'objectInstances'
20  | 'functions'
21  | 'languageModels'
22  | 'permissions'
23  | 'searchResults'
24
25/** One selected resource: its RID (or key), display name and a path or type hint. */
26export type FoundryResource = { rid: string; name: string; hint: string }
27
28export type FoundryScope = {
29  profile: string
30  host: string
31  ontology: FoundryNamed | null
32  namespace: FoundryNamespace | null
33  projects: FoundryNamed[]
34  objectTypes: FoundryObjectType[]
35  actionTypes: FoundryObjectType[]
36  resources: Partial<Record<FoundryResourceKind, FoundryResource[]>>
37  updatedAt: string
38}
39
40export type FoundryPickItem = { key: string; label: string; hint: string }
41
42export type FoundryPickerKind = 'profile' | 'ontology' | 'namespace' | 'project' | 'object-type' | 'action-type' | 'resource'
43
44export type FoundryPicker = {
45  kind: FoundryPickerKind
46  /** The scope key a 'resource' picker writes. */
47  resourceKind?: FoundryResourceKind
48  title: string
49  isMulti: boolean
50  items: FoundryPickItem[]
51  chosen: string[]
52  filter: string
53  /** Pickers to open after this one, in order (the /open guided flow). */
54  chain: FoundryPickerKind[]
55}
56
57/** /fde: a session bound to one agent global branch. */
58export type FdeSession = {
59  goal: string
60  profile: string
61  ontologyRid: string
62  branchRid: string
63  branchName: string
64  startedAt: string
65  /** Signatures of clean dry runs; an --apply must match one. */
66  plans: string[]
67  applied: { command: string; at: string }[]
68  /** The namespace in scope at /fde on: a write naming a resource outside it is refused. Null: no namespace check. */
69  namespace: FoundryNamespace | null
70  /** The stack's namespaces at /fde on (empty without a namespace), to name them in refusals and to place Compass paths. */
71  spaces: FoundryNamespace[]
72}
73
74declare module 'claude-code' {
75  interface PluginState {
76    foundry: {
77      scope: FoundryScope
78      picker: FoundryPicker | null
79      workingBranch: string | null
80      fde: FdeSession | null
81    }
82  }
83}
84