@bridge_gpt/mcp-server 0.2.73 → 0.2.75
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +14 -7
- package/build/agent-launchers/claude-executor-adapter.js +12 -0
- package/build/agent-launchers/prompt.js +9 -21
- package/build/agents.generated.js +4 -4
- package/build/authored-plan.js +542 -0
- package/build/bridge-config.js +7 -1
- package/build/bridge-permissions.js +11 -0
- package/build/command-provisioning.js +4 -3
- package/build/commands.generated.js +6 -6
- package/build/conductor/bridge-api-client.js +692 -47
- package/build/conductor/command-drift.js +1 -1
- package/build/conductor/declared-extras.js +335 -0
- package/build/conductor/doctor.js +2 -0
- package/build/conductor/driver-pass-output.js +104 -0
- package/build/conductor/driver-pass.js +571 -0
- package/build/conductor/epic-branch-ci-inspection.js +61 -16
- package/build/conductor/epic-implementer-cli.js +370 -93
- package/build/conductor/epic-server-sfcc-upload.js +1567 -0
- package/build/conductor/epic-server-sfcc.js +58 -80
- package/build/conductor/epic-server.js +57 -4
- package/build/conductor/gate-discovery.js +253 -13
- package/build/conductor/gate-settings-review.js +58 -25
- package/build/conductor/launch-plan.js +58 -12
- package/build/conductor/open-decision-phrases.js +50 -0
- package/build/conductor/prerequisite-inputs.js +181 -14
- package/build/connect-github-api.js +18 -0
- package/build/connect-github.js +35 -18
- package/build/credential-delivery.js +280 -0
- package/build/credential-launch-safety.js +142 -0
- package/build/credential-materialization.js +91 -16
- package/build/credential-references-node-deps.js +29 -0
- package/build/credential-references.js +1394 -0
- package/build/credential-references.test-fixtures.js +211 -0
- package/build/credential-scan-conventions.js +145 -0
- package/build/credential-scan.js +517 -0
- package/build/credential-store.js +50 -0
- package/build/credentials-cli.js +252 -3
- package/build/dependency-install-declarations.js +47 -1
- package/build/docs.generated.js +8 -1
- package/build/doctor.js +41 -0
- package/build/drive-epic.js +684 -49
- package/build/epic-branch-ci-summary.js +18 -1
- package/build/epic-capability-statement.js +71 -3
- package/build/epic-ci-workflow-drift.js +52 -13
- package/build/epic-ci-workflow-install.js +31 -6
- package/build/epic-ci-workflow-v3.js +273 -0
- package/build/epic-ci-workflow.js +129 -7
- package/build/epic-implementer-bin.js +288 -83
- package/build/epic-implementer-bundle-cli.js +61 -0
- package/build/epic-implementer-claude-hook-bin.js +1 -1
- package/build/epic-implementer-env.js +3 -4
- package/build/epic-integration-pr.js +5 -2
- package/build/epic-launch-context.js +102 -7
- package/build/epic-server-record.js +30 -15
- package/build/executor/completion-contract.js +24 -1
- package/build/executor/credential-delivery-step.js +168 -0
- package/build/executor/deps.js +3 -1
- package/build/executor/env.js +39 -1
- package/build/executor/epic-server-context.js +23 -7
- package/build/executor/gate-qualification-job.js +193 -23
- package/build/executor/gate-qualification-tests-ran.js +232 -0
- package/build/executor/guarded-fast-forward-push.js +13 -8
- package/build/executor/job-runner.js +167 -738
- package/build/executor/job-type-wrappers.js +734 -0
- package/build/executor/permissions.js +85 -3
- package/build/executor/preflight.js +6 -2
- package/build/executor/process-containment.js +8 -1
- package/build/executor/prompt-spec.js +37 -3
- package/build/executor/required-verification.js +28 -2
- package/build/executor/runner.js +4 -1
- package/build/executor/types.js +9 -0
- package/build/executor/worker-database.js +6 -1
- package/build/executor/worker-guard-hook.js +24 -2
- package/build/executor-launch.js +4 -2
- package/build/generated/ticket-status.js +20 -0
- package/build/git-exclude-lock.js +187 -0
- package/build/index.js +589 -326
- package/build/install-bridge-conductor-answers.js +112 -22
- package/build/install-bridge-conductor-apply.js +38 -1
- package/build/install-bridge-conductor-assessment.js +482 -53
- package/build/install-bridge-conductor-compact.js +29 -2
- package/build/install-bridge-conductor-contracts.js +10 -1
- package/build/install-bridge-conductor-gate.js +379 -89
- package/build/install-bridge-conductor-setup.js +46 -8
- package/build/install-bridge-conductor-trial-report.js +170 -0
- package/build/install-bridge-conductor.js +925 -141
- package/build/install-bridge.js +88 -11
- package/build/install-doctor.js +38 -8
- package/build/install-sfcc-detection.js +120 -0
- package/build/install-sfcc-setup.js +185 -0
- package/build/mcp-grant-candidates.js +108 -96
- package/build/mcp-invoke.js +168 -4
- package/build/mcp-provisioning.js +21 -4
- package/build/mcp-server-invocation.js +13 -0
- package/build/merge-workflow-install.js +9 -1
- package/build/pipelines.generated.js +8 -7
- package/build/plan-generation.js +17 -0
- package/build/plane/status.js +8 -2
- package/build/printed-remedy-commands.js +59 -0
- package/build/project-root.js +40 -0
- package/build/readme.generated.js +1 -1
- package/build/repository-state-paths.js +5 -2
- package/build/repository-toolchains.js +16 -7
- package/build/scripts/saved-commands-config-field-driver.js +65 -0
- package/build/setup-epic.js +126 -16
- package/build/sfcc/credentials.js +3 -2
- package/build/sfcc/hostname.js +98 -2
- package/build/sfcc/tool-wrapper.js +6 -95
- package/build/start-tickets.js +193 -29
- package/build/test-support/executor-source-files.js +200 -0
- package/build/testing-config-client.js +25 -2
- package/build/third-party-mcp-targets.js +35 -4
- package/build/v2-readiness-requirements.js +5 -1
- package/build/version.generated.js +3 -3
- package/build/with-credentials.js +208 -0
- package/build/worker-guard-hook-bin.js +2 -2
- package/build/worktree-credential-delivery.js +340 -0
- package/docs/EPIC-IMPLEMENTER.md +4 -4
- package/docs/install/github-app.md +79 -92
- package/package.json +1 -1
- package/build/conductor/epic-reconcile.js +0 -603
- package/build/conductor/epic-runtime.js +0 -2020
- package/build/conductor/epic-state.js +0 -774
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { mergeReadinessPrerequisites, formatReadinessPrerequisites } from "./conductor/readiness-prerequisites.js";
|
|
2
2
|
import { READINESS_PREREQUISITE_BY_ID, READINESS_LEGACY_IDS } from "./readiness-prerequisites.generated.js";
|
|
3
|
+
import { indexedWorkflowsDisplayRemedy } from "./printed-remedy-commands.js";
|
|
3
4
|
/**
|
|
4
5
|
* The v2 readiness requirement catalog and its row projection (BAPI-1452).
|
|
5
6
|
*
|
|
@@ -185,7 +186,10 @@ export const V2_READINESS_REQUIREMENTS = [
|
|
|
185
186
|
...NEW_IDS.filter(id => id !== 'server.unattended-notify-default').map(id => ({
|
|
186
187
|
id, describe: READINESS_PREREQUISITE_BY_ID.get(id).label, governedRowIds: [id], unattendedOnly: true,
|
|
187
188
|
satisfied: (r) => !r.prerequisites?.some(p => p.id === id && p.check_status === 'not_met' && p.impact === 'blocking'),
|
|
188
|
-
remedyFor: (r) =>
|
|
189
|
+
remedyFor: (r) => {
|
|
190
|
+
const row = r.prerequisites?.find(p => p.id === id);
|
|
191
|
+
return row === undefined ? 'Retry readiness.' : indexedWorkflowsDisplayRemedy(row, r);
|
|
192
|
+
},
|
|
189
193
|
})),
|
|
190
194
|
// BAPI-1585 — two launch checks the server evaluates only on a launch path. The
|
|
191
195
|
// webhook row is unattended-only (it is not_applicable otherwise). The provider
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
// AUTO-GENERATED — do not edit manually. Regenerate with: npm run build
|
|
2
|
-
export const VERSION = "0.2.
|
|
3
|
-
export const BUILD_COMMIT = "
|
|
4
|
-
export const LAUNCHER_ARGS = ["-y", "--prefer-offline", "@bridge_gpt/mcp-server@0.2.
|
|
2
|
+
export const VERSION = "0.2.75";
|
|
3
|
+
export const BUILD_COMMIT = "e66184422c92";
|
|
4
|
+
export const LAUNCHER_ARGS = ["-y", "--prefer-offline", "@bridge_gpt/mcp-server@0.2.75", "serve"];
|
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* BAPI-1647: `with-credentials --repo <repo> -- <agent argv>` — an internal
|
|
3
|
+
* subcommand that `start-tickets` puts in front of the agent in each tab.
|
|
4
|
+
*
|
|
5
|
+
* It resolves the repository's approved SANDBOX shell variables through child
|
|
6
|
+
* 1's `forWorkerLaunch()` in its OWN process, at the moment the agent starts,
|
|
7
|
+
* and then runs the agent with those variables in its environment. So a value
|
|
8
|
+
* never appears in the tab command, in any argv, in a prompt file, or in a
|
|
9
|
+
* `start-tickets` summary, and a rotated value is picked up at the next start
|
|
10
|
+
* with no Bridge step.
|
|
11
|
+
*
|
|
12
|
+
* - The repository identity comes from `--repo`, which `start-tickets` writes
|
|
13
|
+
* from the repository it resolved itself — never from the worktree.
|
|
14
|
+
* - Only the variable channel is applied here. File credentials were already
|
|
15
|
+
* linked into the worktree before the tab opened; MCP credentials are
|
|
16
|
+
* resolved by the `mcp-invoke` shim.
|
|
17
|
+
* - Missing credentials are a notice on stderr, never a failure: the agent
|
|
18
|
+
* starts either way and its exit status is returned unchanged. stdout belongs
|
|
19
|
+
* to the agent alone.
|
|
20
|
+
* - A reserved worker-environment name (child 1 already refuses it in the
|
|
21
|
+
* record) is rechecked and dropped with a notice naming only the variable.
|
|
22
|
+
*/
|
|
23
|
+
import { spawn } from "child_process";
|
|
24
|
+
import { existsSync } from "fs";
|
|
25
|
+
import path from "path";
|
|
26
|
+
import { validateRepoName } from "./bridge-config.js";
|
|
27
|
+
import { forWorkerLaunch } from "./credential-references.js";
|
|
28
|
+
import { createLaunchCredentialReferenceDeps, formatNoticeLines, launchResolveOptions, } from "./credential-delivery.js";
|
|
29
|
+
import { isWorkerEnvNameReserved } from "./executor/env.js";
|
|
30
|
+
import { spawnMcpCommand } from "./mcp-invoke.js";
|
|
31
|
+
export const WITH_CREDENTIALS_SUBCOMMAND = "with-credentials";
|
|
32
|
+
// ---------------------------------------------------------------------------
|
|
33
|
+
// Windows `.cmd` / `.bat` agents
|
|
34
|
+
// ---------------------------------------------------------------------------
|
|
35
|
+
/**
|
|
36
|
+
* Node cannot spawn a `.cmd`/`.bat` shim (how npm installs `claude` on
|
|
37
|
+
* Windows) without a shell. Rather than `shell: true`, which joins argv
|
|
38
|
+
* unquoted, the shim is run through `cmd.exe /d /s /c "<line>"` with every part
|
|
39
|
+
* escaped for both the C runtime and cmd's metacharacters (the scheme
|
|
40
|
+
* `cross-spawn` uses), and `windowsVerbatimArguments` so Node adds nothing.
|
|
41
|
+
*/
|
|
42
|
+
const CMD_META = /([()\][%!^"`<>&|;, *?])/g;
|
|
43
|
+
function escapeWindowsArgument(arg) {
|
|
44
|
+
let escaped = arg.replace(/(\\*)"/g, '$1$1\\"').replace(/(\\*)$/, "$1$1");
|
|
45
|
+
escaped = `"${escaped}"`;
|
|
46
|
+
// Twice: once for cmd parsing the line, once for the .cmd shim re-parsing `%*`.
|
|
47
|
+
return escaped.replace(CMD_META, "^$1").replace(CMD_META, "^$1");
|
|
48
|
+
}
|
|
49
|
+
function escapeWindowsCommand(command) {
|
|
50
|
+
return command.replace(CMD_META, "^$1");
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Resolve the agent on Windows through `PATH`/`PATHEXT`. A `.cmd`/`.bat`
|
|
54
|
+
* resolves to a `cmd.exe` invocation; anything else is spawned directly.
|
|
55
|
+
*/
|
|
56
|
+
export function resolveWindowsAgentInvocation(command, args, env, fileExists) {
|
|
57
|
+
const exts = (env.PATHEXT ?? ".COM;.EXE;.BAT;.CMD").split(";").filter((e) => e.length > 0);
|
|
58
|
+
const hasSep = /[\\/]/.test(command);
|
|
59
|
+
const dirs = hasSep ? [""] : (env.PATH ?? env.Path ?? "").split(";").filter((d) => d.length > 0);
|
|
60
|
+
let resolved = null;
|
|
61
|
+
for (const dir of dirs) {
|
|
62
|
+
const base = dir.length === 0 ? command : path.win32.join(dir, command);
|
|
63
|
+
const hasExt = exts.some((e) => base.toLowerCase().endsWith(e.toLowerCase()));
|
|
64
|
+
for (const candidate of hasExt ? [base] : exts.map((e) => `${base}${e}`)) {
|
|
65
|
+
if (fileExists(candidate)) {
|
|
66
|
+
resolved = candidate;
|
|
67
|
+
break;
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
if (resolved)
|
|
71
|
+
break;
|
|
72
|
+
}
|
|
73
|
+
if (resolved && /\.(cmd|bat)$/i.test(resolved)) {
|
|
74
|
+
const line = [escapeWindowsCommand(path.win32.normalize(resolved)), ...args.map(escapeWindowsArgument)].join(" ");
|
|
75
|
+
return { command: env.ComSpec ?? env.COMSPEC ?? "cmd.exe", args: ["/d", "/s", "/c", `"${line}"`], verbatim: true };
|
|
76
|
+
}
|
|
77
|
+
return { command: resolved ?? command, args: [...args], verbatim: false };
|
|
78
|
+
}
|
|
79
|
+
export function getWithCredentialsUsage() {
|
|
80
|
+
return [
|
|
81
|
+
"Usage: with-credentials --repo <repo> -- <agent> [args...]",
|
|
82
|
+
"",
|
|
83
|
+
"Internal: run an agent with the repository's approved sandbox credential",
|
|
84
|
+
"variables in its environment. Used by start-tickets tabs.",
|
|
85
|
+
].join("\n");
|
|
86
|
+
}
|
|
87
|
+
/** Parse argv (after the subcommand). Never echoes an agent argument. */
|
|
88
|
+
export function parseWithCredentialsArgs(argv) {
|
|
89
|
+
const separator = argv.indexOf("--");
|
|
90
|
+
const head = separator === -1 ? [...argv] : argv.slice(0, separator);
|
|
91
|
+
if (head.includes("--help") || head.includes("-h"))
|
|
92
|
+
return { status: "help" };
|
|
93
|
+
if (separator === -1)
|
|
94
|
+
return { status: "error", message: "missing '--' before the agent command" };
|
|
95
|
+
let repo;
|
|
96
|
+
for (let i = 0; i < head.length; i++) {
|
|
97
|
+
if (head[i] === "--repo") {
|
|
98
|
+
if (repo !== undefined)
|
|
99
|
+
return { status: "error", message: "--repo was given more than once" };
|
|
100
|
+
const value = head[i + 1];
|
|
101
|
+
if (value === undefined)
|
|
102
|
+
return { status: "error", message: "--repo needs a value" };
|
|
103
|
+
repo = value;
|
|
104
|
+
i++;
|
|
105
|
+
continue;
|
|
106
|
+
}
|
|
107
|
+
return { status: "error", message: "unknown option before '--'" };
|
|
108
|
+
}
|
|
109
|
+
if (repo === undefined)
|
|
110
|
+
return { status: "error", message: "--repo is required" };
|
|
111
|
+
const validated = validateRepoName(repo);
|
|
112
|
+
if (!validated.ok)
|
|
113
|
+
return { status: "error", message: `invalid --repo: ${validated.error}` };
|
|
114
|
+
const agent = argv.slice(separator + 1);
|
|
115
|
+
if (agent.length === 0 || agent[0].length === 0) {
|
|
116
|
+
return { status: "error", message: "the agent command after '--' is empty" };
|
|
117
|
+
}
|
|
118
|
+
return { status: "ok", repo: validated.value, command: agent[0], args: agent.slice(1) };
|
|
119
|
+
}
|
|
120
|
+
/**
|
|
121
|
+
* Build the agent environment: the inherited environment plus admitted
|
|
122
|
+
* variables. A reserved name is dropped. Returns names-only notices.
|
|
123
|
+
*/
|
|
124
|
+
export function buildAgentEnv(parentEnv, values) {
|
|
125
|
+
const env = { ...parentEnv };
|
|
126
|
+
const notices = [];
|
|
127
|
+
const admitted = [];
|
|
128
|
+
for (const [name, value] of Object.entries(values)) {
|
|
129
|
+
if (isWorkerEnvNameReserved(name)) {
|
|
130
|
+
notices.push({ name, reason: "reserved_name" });
|
|
131
|
+
continue;
|
|
132
|
+
}
|
|
133
|
+
// Same rule as the executor's admitDeclaredCredentialEnv: an approved
|
|
134
|
+
// credential never overrides a variable the agent's environment already
|
|
135
|
+
// sets. The collision is named (never its value) and the inherited value wins.
|
|
136
|
+
if (env[name] !== undefined) {
|
|
137
|
+
notices.push({ name, reason: "name_collision" });
|
|
138
|
+
continue;
|
|
139
|
+
}
|
|
140
|
+
env[name] = value;
|
|
141
|
+
admitted.push(name);
|
|
142
|
+
}
|
|
143
|
+
return { env, notices, admitted };
|
|
144
|
+
}
|
|
145
|
+
/** Run the subcommand. Returns the agent's exit status (never calls `process.exit`). */
|
|
146
|
+
export async function runWithCredentialsCli(argv, overrides = {}) {
|
|
147
|
+
const stderr = overrides.stderr ?? ((m) => process.stderr.write(`${m}\n`));
|
|
148
|
+
const env = overrides.env ?? process.env;
|
|
149
|
+
const cwd = overrides.cwd ?? process.cwd();
|
|
150
|
+
const parsed = parseWithCredentialsArgs(argv);
|
|
151
|
+
if (parsed.status === "help") {
|
|
152
|
+
// Usage goes to stderr so stdout stays the agent's.
|
|
153
|
+
stderr(getWithCredentialsUsage());
|
|
154
|
+
return 0;
|
|
155
|
+
}
|
|
156
|
+
if (parsed.status === "error") {
|
|
157
|
+
stderr(`Error: ${parsed.message}`);
|
|
158
|
+
stderr(getWithCredentialsUsage());
|
|
159
|
+
return 2;
|
|
160
|
+
}
|
|
161
|
+
let resolution;
|
|
162
|
+
try {
|
|
163
|
+
resolution = overrides.resolve
|
|
164
|
+
? await overrides.resolve(parsed.repo, cwd)
|
|
165
|
+
: await forWorkerLaunch(parsed.repo, createLaunchCredentialReferenceDeps(env, cwd), launchResolveOptions(cwd));
|
|
166
|
+
}
|
|
167
|
+
catch {
|
|
168
|
+
resolution = { state: "record_unusable", files: [], env: {}, unavailable: [] };
|
|
169
|
+
}
|
|
170
|
+
// Only the variable channel applies here; file specs were linked before the tab opened.
|
|
171
|
+
const values = resolution.state === "ok" ? resolution.env : {};
|
|
172
|
+
const built = buildAgentEnv(env, values);
|
|
173
|
+
const notices = [
|
|
174
|
+
...resolution.unavailable.map((u) => ({ name: u.name, reason: u.reason })),
|
|
175
|
+
...built.notices,
|
|
176
|
+
];
|
|
177
|
+
for (const line of formatNoticeLines(resolution.state, notices))
|
|
178
|
+
stderr(`Warning: ${line}`);
|
|
179
|
+
const invocation = { command: parsed.command, args: parsed.args, env: built.env };
|
|
180
|
+
try {
|
|
181
|
+
if (overrides.spawnAgent)
|
|
182
|
+
return await overrides.spawnAgent(invocation);
|
|
183
|
+
const platform = overrides.platform ?? process.platform;
|
|
184
|
+
const win = platform === "win32"
|
|
185
|
+
? resolveWindowsAgentInvocation(invocation.command, invocation.args, invocation.env, existsSync)
|
|
186
|
+
: null;
|
|
187
|
+
const spawnFn = win?.verbatim
|
|
188
|
+
? ((command, args, options) => spawn(command, args, { ...options, windowsVerbatimArguments: true }))
|
|
189
|
+
: spawn;
|
|
190
|
+
return await spawnMcpCommand({
|
|
191
|
+
spawn: spawnFn,
|
|
192
|
+
command: win ? win.command : invocation.command,
|
|
193
|
+
args: win ? win.args : invocation.args,
|
|
194
|
+
env: invocation.env,
|
|
195
|
+
onSignal: (s, h) => {
|
|
196
|
+
process.on(s, h);
|
|
197
|
+
},
|
|
198
|
+
offSignal: (s, h) => {
|
|
199
|
+
process.off(s, h);
|
|
200
|
+
},
|
|
201
|
+
});
|
|
202
|
+
}
|
|
203
|
+
catch {
|
|
204
|
+
// Fixed text: never the command, its arguments, or the error.
|
|
205
|
+
stderr("Error: the agent could not be started");
|
|
206
|
+
return 127;
|
|
207
|
+
}
|
|
208
|
+
}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
import{readFileSync}from"node:fs";import path from"node:path";var WORKER_GUARD_REASON_PREFIX="bridge worker guard",WORKER_GUARD_MALFORMED_LINE=`${WORKER_GUARD_REASON_PREFIX}: payload could not be read; continuing fail-open`;function renderWorkerGuardReason(category,family,form){if(category==="git-ambiguous")return`${WORKER_GUARD_REASON_PREFIX}: denied ${family} (${category}). This shell form cannot be safely resolved: substitution, redirection, or stdin-fed arguments hide what git will run. Use literal arguments instead; for a commit message, write it to a file and run git commit -F <file>.`;if(form==="shell_form"){let pattern=category==="git-push"?"If the destination is your own branch and no force is used, run git push origin HEAD:<your work branch> alone.":category==="git-reset-hard"?"If resetting your own branch, run git reset --hard origin/<your work branch> alone.":category==="filesystem-clean"?"If all pathspecs are inside your worktree, run git clean with literal worktree-contained pathspecs alone.":category==="filesystem-remove"?"If all paths are inside your worktree, run rm with literal worktree-contained paths alone.":"If arguments are read-only, run literal read-only arguments alone, without redirects or $VAR.";return`${WORKER_GUARD_REASON_PREFIX}: denied ${family} (${category}). Shell form cannot be checked: redirects, pipes, substitution, or stdin-fed arguments. `+pattern}let restriction={"git-push":"Push only to your own branch, without force. Use HEAD:<your work branch> as the destination.","git-reset-hard":"Hard reset only against your own branch ref.","filesystem-clean":"Clean only literal paths inside your worktree.","filesystem-remove":"Remove only literal paths inside your worktree.","database-destructive":"Destructive SQL is prohibited. Use read-only database arguments.","network-mutating":"Mutating requests are prohibited. Use read-only network arguments."};return restriction[category]?`${WORKER_GUARD_REASON_PREFIX}: denied ${family} (${category}). ${restriction[category]}`:category==="workflow-entry"||category==="workflow-launch-skill"||category==="workflow-launch-shell"||category==="workflow-planner-tool"?`${WORKER_GUARD_REASON_PREFIX}: denied ${family} (${category}). A correction worker must not start a full workflow. Reading or editing files that mention a workflow is allowed; make the focused correction directly.`:category==="correction-context-invalid"?`${WORKER_GUARD_REASON_PREFIX}: denied ${family} (${category}). The correction context for this worker is not valid, so no tool call can be checked. Stop and report the launch problem.`:category==="operator-verb"&&family==="regenerate-plan"?`${WORKER_GUARD_REASON_PREFIX}: denied ${family} (${category}). Choosing the route a failed plan is regenerated on is the run driver's decision, made outside the worker. Do not run regenerate-plan or call its route; record the step escalated with its reason and continue.`:category==="operator-verb"&&family==="acknowledge-gaps"?`${WORKER_GUARD_REASON_PREFIX}: denied ${family} (${category}). Acknowledging the run's carried-gap list is the run owner's decision, made outside the worker. Do not run acknowledge-gaps or call its route; record what you could not verify in your phase result and continue.`:category==="operator-verb"?`${WORKER_GUARD_REASON_PREFIX}: denied ${family} (${category}). Resolving a verification hand-off is the run owner's decision, made outside the worker. Do not run resolve-handoff or call its route; record the step escalated with its hand-off and continue.`:category==="correction-payload-invalid"?`${WORKER_GUARD_REASON_PREFIX}: denied ${family} (${category}). The tool call could not be read as a tool name with a tool input, so it cannot be checked. Retry with a well-formed call.`:`${WORKER_GUARD_REASON_PREFIX}: denied ${family} (${category}). This command family is restricted to the worker's own branch, worktree, and read-only network access. Use a different approach and continue.`}var UNSAFE_UNQUOTED=new Set(["$","`",">","<"]),SEPARATORS=new Set([";","|","&"]);function tokenizeShellCommand(command){let commands=[],argv=[],current="",hasCurrent=!1,unsafe=!1,endToken=()=>{hasCurrent&&(argv.push(current),current="",hasCurrent=!1)},endCommand=()=>{endToken(),(argv.length>0||unsafe)&&commands.push({argv,unsafe}),argv=[],unsafe=!1};for(let i=0;i<command.length;i+=1){let ch=command[i];if(ch==="\\"){let next=command[i+1];next!==void 0&&(current+=next,hasCurrent=!0,i+=1);continue}if(ch==="'"){let close=command.indexOf("'",i+1);if(close===-1){unsafe=!0,current+=command.slice(i+1),hasCurrent=!0;break}current+=command.slice(i+1,close),hasCurrent=!0,i=close;continue}if(ch==='"'){let j=i+1,body="",closed=!1;for(;j<command.length;){let c=command[j];if(c==="\\"&&j+1<command.length){body+=command[j+1],j+=2;continue}if(c==='"'){closed=!0;break}(c==="$"||c==="`")&&(unsafe=!0),body+=c,j+=1}closed||(unsafe=!0),current+=body,hasCurrent=!0,i=j;continue}if(UNSAFE_UNQUOTED.has(ch)){unsafe=!0,current+=ch,hasCurrent=!0;continue}if(SEPARATORS.has(ch)){endCommand();continue}if(ch===`
|
|
2
|
+
import{readFileSync}from"node:fs";import path from"node:path";var WORKER_GUARD_REASON_PREFIX="bridge worker guard",WORKER_GUARD_MALFORMED_LINE=`${WORKER_GUARD_REASON_PREFIX}: payload could not be read; continuing fail-open`;function renderWorkerGuardReason(category,family,form){if(category==="git-ambiguous")return`${WORKER_GUARD_REASON_PREFIX}: denied ${family} (${category}). This shell form cannot be safely resolved: substitution, redirection, or stdin-fed arguments hide what git will run. Use literal arguments instead; for a commit message, write it to a file and run git commit -F <file>.`;if(form==="shell_form"){let pattern=category==="git-push"?"If the destination is your own branch and no force is used, run git push origin HEAD:<your work branch> alone.":category==="git-reset-hard"?"If resetting your own branch, run git reset --hard origin/<your work branch> alone.":category==="filesystem-clean"?"If all pathspecs are inside your worktree, run git clean with literal worktree-contained pathspecs alone.":category==="filesystem-remove"?"If all paths are inside your worktree, run rm with literal worktree-contained paths alone.":"If arguments are read-only, run literal read-only arguments alone, without redirects or $VAR.";return`${WORKER_GUARD_REASON_PREFIX}: denied ${family} (${category}). Shell form cannot be checked: redirects, pipes, substitution, or stdin-fed arguments. `+pattern}let restriction={"git-push":"Push only to your own branch, without force. Use HEAD:<your work branch> as the destination.","git-reset-hard":"Hard reset only against your own branch ref.","filesystem-clean":"Clean only literal paths inside your worktree.","filesystem-remove":"Remove only literal paths inside your worktree.","database-destructive":"Destructive SQL is prohibited. Use read-only database arguments.","network-mutating":"Mutating requests are prohibited. Use read-only network arguments."};return restriction[category]?`${WORKER_GUARD_REASON_PREFIX}: denied ${family} (${category}). ${restriction[category]}`:category==="workflow-entry"||category==="workflow-launch-skill"||category==="workflow-launch-shell"||category==="workflow-planner-tool"?`${WORKER_GUARD_REASON_PREFIX}: denied ${family} (${category}). A correction worker must not start a full workflow. Reading or editing files that mention a workflow is allowed; make the focused correction directly.`:category==="correction-context-invalid"?`${WORKER_GUARD_REASON_PREFIX}: denied ${family} (${category}). The correction context for this worker is not valid, so no tool call can be checked. Stop and report the launch problem.`:category==="operator-verb"&&family==="regenerate-plan"?`${WORKER_GUARD_REASON_PREFIX}: denied ${family} (${category}). Choosing the route a failed plan is regenerated on is the run driver's decision, made outside the worker. Do not run regenerate-plan or call its route; record the step escalated with its reason and continue.`:category==="operator-verb"&&(family==="reserve-council"||family==="record-decision")?`${WORKER_GUARD_REASON_PREFIX}: denied ${family} (${category}). Convening or settling an open-decision council is the run driver's decision, made outside the worker. Do not run reserve-council or record-decision; record the open choice as an escalated step with its reason and continue.`:category==="operator-verb"&&family==="acknowledge-gaps"?`${WORKER_GUARD_REASON_PREFIX}: denied ${family} (${category}). Acknowledging the run's carried-gap list is the run owner's decision, made outside the worker. Do not run acknowledge-gaps or call its route; record what you could not verify in your phase result and continue.`:category==="operator-verb"?`${WORKER_GUARD_REASON_PREFIX}: denied ${family} (${category}). Resolving a verification hand-off is the run owner's decision, made outside the worker. Do not run resolve-handoff or call its route; record the step escalated with its hand-off and continue.`:category==="correction-payload-invalid"?`${WORKER_GUARD_REASON_PREFIX}: denied ${family} (${category}). The tool call could not be read as a tool name with a tool input, so it cannot be checked. Retry with a well-formed call.`:`${WORKER_GUARD_REASON_PREFIX}: denied ${family} (${category}). This command family is restricted to the worker's own branch, worktree, and read-only network access. Use a different approach and continue.`}var UNSAFE_UNQUOTED=new Set(["$","`",">","<"]),SEPARATORS=new Set([";","|","&"]);function tokenizeShellCommand(command){let commands=[],argv=[],current="",hasCurrent=!1,unsafe=!1,endToken=()=>{hasCurrent&&(argv.push(current),current="",hasCurrent=!1)},endCommand=()=>{endToken(),(argv.length>0||unsafe)&&commands.push({argv,unsafe}),argv=[],unsafe=!1};for(let i=0;i<command.length;i+=1){let ch=command[i];if(ch==="\\"){let next=command[i+1];next!==void 0&&(current+=next,hasCurrent=!0,i+=1);continue}if(ch==="'"){let close=command.indexOf("'",i+1);if(close===-1){unsafe=!0,current+=command.slice(i+1),hasCurrent=!0;break}current+=command.slice(i+1,close),hasCurrent=!0,i=close;continue}if(ch==='"'){let j=i+1,body="",closed=!1;for(;j<command.length;){let c=command[j];if(c==="\\"&&j+1<command.length){body+=command[j+1],j+=2;continue}if(c==='"'){closed=!0;break}(c==="$"||c==="`")&&(unsafe=!0),body+=c,j+=1}closed||(unsafe=!0),current+=body,hasCurrent=!0,i=j;continue}if(UNSAFE_UNQUOTED.has(ch)){unsafe=!0,current+=ch,hasCurrent=!0;continue}if(SEPARATORS.has(ch)){endCommand();continue}if(ch===`
|
|
3
3
|
`){endCommand();continue}if(ch===" "||ch===" "||ch==="\r"){endToken();continue}current+=ch,hasCurrent=!0}return endCommand(),commands}function diagnosticProjections(command){if(command.length>WORKER_GUARD_MAX_PAYLOAD_BYTES)return[];let result=[],start=0,masked="",quote="",uncertain=!1,finish=end=>{let original=tokenizeShellCommand(command.slice(start,end)),projected=tokenizeShellCommand(masked),value=!uncertain&&projected.length===1?{argv:projected[0].argv,complete:!projected[0].unsafe}:void 0;result.push(...original.map((_,i)=>i===0?value:void 0)),masked="",uncertain=!1,start=end+1};for(let i=0;i<command.length;i+=1){let ch=command[i];if(ch==="\\"&"e!=="'"){masked+=command.slice(i,i+2),i+=1;continue}if(quote){masked+=ch,ch===quote&&(quote="");continue}if(ch==="'"||ch==='"'){quote=ch,masked+=ch;continue}if(ch===">"||ch==="<"){masked=masked.replace(/(^|\s)\d+$/,"$1");let j=i+1;for(command[j]===ch&&(j+=1),command[j]==="&"&&(j+=1);/[ \t]/.test(command[j]??"")&&j<command.length;)j+=1;let operandStart=j,operandQuote="";for(;j<command.length;){let c=command[j];if(c==="\\"&&operandQuote!=="'"){j+=2;continue}if(operandQuote){c===operandQuote&&(operandQuote=""),j+=1;continue}if(c==="'"||c==='"'){operandQuote=c,j+=1;continue}if(/[\s;|&<>]/.test(c))break;j+=1}(j===operandStart||operandQuote||command.slice(i,j).startsWith("<<"))&&(uncertain=!0),masked+=" ",i=j-1;continue}if(SEPARATORS.has(ch)||ch===`
|
|
4
|
-
`){finish(i);continue}masked+=ch}return quote&&(uncertain=!0),finish(command.length),result}var WORKER_GUARD_MAX_PAYLOAD_BYTES=1e6;function asRecord(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)?value:void 0}function isInside(root,candidate){let rel=path.relative(root,candidate);return rel===""?!0:rel.startsWith("..")?!1:!path.isAbsolute(rel)}function resolveEffectiveCwd(ctx,payloadCwd){let root=ctx.worktreePath;if(typeof root!="string"||!path.isAbsolute(root))return;let normalizedRoot=path.resolve(root);if(payloadCwd===void 0)return normalizedRoot;if(typeof payloadCwd!="string"||payloadCwd.length===0)return;let resolved=path.isAbsolute(payloadCwd)?path.resolve(payloadCwd):path.resolve(normalizedRoot,payloadCwd);return isInside(normalizedRoot,resolved)?resolved:void 0}function allTargetsContained(ctx,cwd,targets){let root=ctx.worktreePath;if(typeof root!="string"||!path.isAbsolute(root)||cwd===void 0)return!1;let normalizedRoot=path.resolve(root);return targets.every(target=>{if(target.length===0||target==="~"||target.startsWith("~/"))return!1;let resolved=path.isAbsolute(target)?path.resolve(target):path.resolve(cwd,target);return isInside(normalizedRoot,resolved)})}function parseGitInvocation(argv,baseCwd){let cwd=baseCwd,unsafe=!1,i=1;for(;i<argv.length;){let token=argv[i];if(token==="-C"){let dir=argv[i+1];dir===void 0||cwd===void 0?(unsafe=!0,cwd=void 0):cwd=path.isAbsolute(dir)?path.resolve(dir):path.resolve(cwd,dir),i+=2;continue}if(token==="-c"||token==="--namespace"||token==="--git-dir"||token==="--work-tree"){unsafe=!0,i+=2;continue}if(token.startsWith("-")){i+=1;continue}break}return{subcommand:argv[i]??"",args:argv.slice(i+1),cwd,unsafe}}function isOwnBranchDestination(destination,workerBranch){let colon=destination.indexOf(":"),dst=colon===-1?destination:destination.slice(colon+1);if(dst.length===0)return!1;let bare=dst.startsWith("+")?dst.slice(1):dst;return bare===workerBranch||bare===`refs/heads/${workerBranch}`}function evaluateGitPush(args,ctx){let deny={kind:"deny",category:"git-push",family:"git"},positional=[];for(let i=0;i<args.length;i+=1){let token=args[i];if(token==="--"){positional.push(...args.slice(i+1));break}if(token.startsWith("-")){if(token==="--tags"||token==="--delete"||token==="-d"||token==="--mirror"||token==="--all"||token==="--follow-tags"||token.startsWith("--repo"))return deny;(token==="-o"||token==="--push-option"||token==="--receive-pack"||token==="--exec")&&(i+=1);continue}positional.push(token)}let workerBranch=ctx.workerBranch;return typeof workerBranch!="string"||workerBranch.length===0?deny:positional.length<=1?{kind:"allow"}:positional.slice(1).every(d=>isOwnBranchDestination(d,workerBranch))?{kind:"allow"}:deny}function evaluateGitReset(args,ctx){let deny={kind:"deny",category:"git-reset-hard",family:"git"};if(!args.includes("--hard"))return{kind:"allow"};let positional=[];for(let i=0;i<args.length;i+=1){let token=args[i];if(token==="--"){positional.push(...args.slice(i+1));break}token.startsWith("-")||positional.push(token)}if(positional.length===0)return{kind:"allow"};let workerBranch=ctx.workerBranch;if(typeof workerBranch!="string"||workerBranch.length===0)return deny;let allowed=new Set([workerBranch,`origin/${workerBranch}`,`refs/heads/${workerBranch}`,`refs/remotes/origin/${workerBranch}`]);return positional.every(ref=>allowed.has(ref))?{kind:"allow"}:deny}function evaluateGitClean(args,ctx,cwd){let deny={kind:"deny",category:"filesystem-clean",family:"git"};if(cwd===void 0||!allTargetsContained(ctx,cwd,[cwd]))return deny;let pathspecs=[];for(let i=0;i<args.length;i+=1){let token=args[i];if(token==="--"){pathspecs.push(...args.slice(i+1));break}if(token==="-e"||token==="--exclude"){i+=1;continue}token.startsWith("-")||pathspecs.push(token)}return pathspecs.length===0?{kind:"allow"}:allTargetsContained(ctx,cwd,pathspecs)?{kind:"allow"}:deny}function isRecursiveForcedRemove(args){let recursive=!1,force=!1;for(let token of args){if(token==="--")break;if(token==="--recursive")recursive=!0;else if(token==="--force")force=!0;else{if(token.startsWith("--"))continue;if(token.startsWith("-")&&token.length>1)for(let flag of token.slice(1))(flag==="r"||flag==="R")&&(recursive=!0),flag==="f"&&(force=!0)}}return recursive&&force}function evaluateRemove(argv,ctx,cwd){let deny={kind:"deny",category:"filesystem-remove",family:"rm"},args=argv.slice(1);if(!isRecursiveForcedRemove(args))return{kind:"allow"};let targets=[],sawDoubleDash=!1;for(let token of args){if(!sawDoubleDash&&token==="--"){sawDoubleDash=!0;continue}!sawDoubleDash&&token.startsWith("-")&&token.length>1||targets.push(token)}return targets.length===0?deny:allTargetsContained(ctx,cwd,targets)?{kind:"allow"}:deny}function isDatabaseCommand(executable){let base=path.basename(executable);return base==="psql"||base.startsWith("pg_")}var DESTRUCTIVE_SQL=/\b(?:DROP|TRUNCATE)\b/i;function evaluateDatabase(argv){let deny={kind:"deny",category:"database-destructive",family:"psql"};return argv.slice(1).some(arg=>DESTRUCTIVE_SQL.test(arg))?deny:{kind:"allow"}}var MUTATING_METHODS=new Set(["POST","PUT","PATCH","DELETE"]);function evaluateNetwork(argv){let deny={kind:"deny",category:"network-mutating",family:"curl"},base=path.basename(argv[0]??""),args=argv.slice(1);for(let i=0;i<args.length;i+=1){let token=args[i];if(token==="-X"||token==="--request"||token==="--method"){let value=args[i+1];if(value===void 0||MUTATING_METHODS.has(value.toUpperCase()))return deny;i+=1;continue}if(token.startsWith("-X")&&token.length>2){if(MUTATING_METHODS.has(token.slice(2).toUpperCase()))return deny;continue}if(token.startsWith("--request=")||token.startsWith("--method=")){let value=token.slice(token.indexOf("=")+1);if(MUTATING_METHODS.has(value.toUpperCase()))return deny;continue}if(token==="--data"||token.startsWith("--data=")||token.startsWith("--data-")||token==="--form"||token==="-F"||token==="--upload-file"||token==="-T"||token==="--post-data"||token.startsWith("--post-data=")||token==="--post-file"||token.startsWith("--post-file=")||token==="--body-data"||token.startsWith("--body-data=")||token==="--body-file"||token.startsWith("--body-file=")||base==="curl"&&token==="-d")return deny}return{kind:"allow"}}function classify(executable){let base=path.basename(executable);return base==="git"?"git":base==="rm"?"rm":isDatabaseCommand(base)?"database":base==="curl"||base==="wget"?"network":null}function unsafeGitCategory(argv){let{subcommand}=parseGitInvocation(argv,void 0);return subcommand==="push"?"git-push":subcommand==="reset"?"git-reset-hard":subcommand==="clean"?"filesystem-clean":"git-ambiguous"}function diagnosticPushForce(args){return args.some(t=>t==="--force"||t==="-f"||t==="--force-with-lease"||t.startsWith("--force-with-lease=")||t.startsWith("+"))}function diagnosticViolation(family,diagnostic,ctx,cwd){let full=unwrapTransparentPrefixes(diagnostic.argv),unknown=diagnostic.complete?-1:full.findIndex(t=>/[$`]/.test(t)),argv=unknown<0?full:full.slice(0,unknown);if(family==="database")return evaluateDatabase(argv).kind==="deny";if(family==="network")return evaluateNetwork(argv).kind==="deny";let git=parseGitInvocation(argv,cwd);return family==="git"&&git.subcommand==="push"&&diagnosticPushForce(git.args)?!0:diagnostic.complete?family==="rm"?evaluateRemove(argv,ctx,cwd).kind==="deny":git.unsafe?!0:git.subcommand==="push"?evaluateGitPush(git.args,ctx).kind==="deny":git.subcommand==="reset"?evaluateGitReset(git.args,ctx).kind==="deny":git.subcommand==="clean"?evaluateGitClean(git.args,ctx,git.cwd).kind==="deny":!1:family==="rm"?argv.slice(1).some(t=>!t.startsWith("-"))&&evaluateRemove(argv,ctx,cwd).kind==="deny":git.subcommand==="push"?git.args.filter(t=>!t.startsWith("-")).length>=2&&evaluateGitPush(git.args,ctx).kind==="deny":git.subcommand==="reset"?git.args.some(t=>!t.startsWith("-"))&&evaluateGitReset(git.args,ctx).kind==="deny":git.subcommand==="clean"?evaluateGitClean(git.args,ctx,git.cwd).kind==="deny":!1}function unsafeSegmentDecision(family,argv,ctx,cwd,diagnostic){let category=family==="git"?unsafeGitCategory(argv):family==="rm"?"filesystem-remove":family==="database"?"database-destructive":"network-mutating",decision={kind:"deny",category,family:family==="database"?"psql":family==="network"?"curl":family};return diagnostic&&category!=="git-ambiguous"&&!diagnosticViolation(family,diagnostic,ctx,cwd)?{...decision,form:"shell_form"}:decision}var TRANSPARENT_PREFIXES=new Set(["sudo","env","command","nohup","time","nice","exec"]),STDIN_ARGUMENT_PREFIXES=new Set(["xargs"]),SHELL_EXECUTABLES=new Set(["sh","bash","zsh","dash","ksh"]),EVAL_BUILTINS=new Set(["eval"]);function unwrapTransparentPrefixes(argv){let rest=argv;for(let depth=0;depth<8;depth+=1){let head=rest[0];if(head===void 0||!TRANSPARENT_PREFIXES.has(path.basename(head)))return rest;let i=1;for(;i<rest.length;){let token=rest[i];if(path.basename(head)==="env"&&/^[A-Za-z_][A-Za-z0-9_]*=/.test(token)){i+=1;continue}if(token.startsWith("-")){i+=1;continue}break}rest=rest.slice(i)}return rest}function stripStdinPrefixOptions(argv){let VALUE_OPTS=new Set(["-I","-i","-L","-n","-P","-s","-d","-E","-e","-a","--replace","--max-lines","--max-args","--max-procs","--max-chars","--delimiter","--eof","--arg-file"]),i=1;for(;i<argv.length;){let token=argv[i];if(token==="--"){i+=1;break}if(!token.startsWith("-"))break;if(token.includes("=")){i+=1;continue}i+=VALUE_OPTS.has(token)?2:1}return argv.slice(i)}var WORKFLOW_NAMES="implement-ticket|plan-ticket|idea-to-pr|review-and-implement",WORKFLOW_SLASH_LAUNCH=new RegExp(`(?:^|\\s)/(?:bridge-)?(?:${WORKFLOW_NAMES})(?=\\s|$)`,"i"),WORKFLOW_NAME_EXACT=new RegExp(`^/?(?:[A-Za-z0-9_-]+:)?(?:bridge-)?(?:${WORKFLOW_NAMES})$`,"i"),CLAUDE_PACKAGE_TOKEN=/^(?:@anthropic-ai\/)?claude(?:-code)?(?:@\S+)?$/;function claudeLaunchArgs(argv){let base=path.basename(argv[0]??"");if(base==="claude")return argv.slice(1);if(base==="npx"){let index=argv.findIndex((token,i)=>i>0&&CLAUDE_PACKAGE_TOKEN.test(token));return index===-1?void 0:argv.slice(index+1)}}function isClaudeWorkflowPrintLaunch(segment){let args=claudeLaunchArgs(segment.argv);return args===void 0||!args.some(token=>token==="-p"||token==="--print"||token.startsWith("--print="))?!1:segment.unsafe?!0:args.some(token=>{let value=token.startsWith("--print=")?token.slice(8):token;return WORKFLOW_SLASH_LAUNCH.test(value)})}var OPERATOR_ONLY_VERBS=["resolve-handoff","regenerate-plan","acknowledge-gaps"],BRIDGE_PACKAGE_TOKEN=/^@bridge_gpt\/mcp-server(?:@\S+)?$/,PACKAGE_RUNNERS=new Set(["npx","pnpx","bunx"]),BRIDGE_SERVER_BINS=new Set(["mcp-server","bridge-api-mcp-server"]),ROUTE_TEXT_ONLY_EXECUTABLES=new Set(["grep","egrep","fgrep","rg","ag","cat","echo","printf","head","tail","wc","diff","less","more","ls","sort","uniq","tr","cut","jq"]);function isTextOnlyInvocation(argv){let executable=path.basename(argv[0]??"");return ROUTE_TEXT_ONLY_EXECUTABLES.has(executable)?!0:executable==="git"?!argv.some(token=>/alias\.[^=]*=\s*!/i.test(token)):executable==="find"?!argv.some(token=>["-exec","-execdir","-ok","-okdir"].includes(token)):!1}function namedOperatorOnlyRoute(token){let decoded=token;for(let i=0;i<3;i+=1){let next;try{next=decodeURIComponent(decoded)}catch{break}if(next===decoded)break;decoded=next}return OPERATOR_ONLY_VERBS.find(verb=>decoded.toLowerCase().includes(`/${verb}`)||token.toLowerCase().includes(`/${verb}`))}var NODE_VALUE_OPTIONS=new Set(["-r","--require","--import","--loader","--experimental-loader","-C","--conditions","--env-file","--input-type","--title","--stack-size","--max-old-space-size"]),NPM_EXEC_SUBCOMMANDS=new Set(["exec","x"]);function runnerPackageIndex(argv,start){for(let i=start;i<argv.length;i+=1){let token=argv[i];if(BRIDGE_PACKAGE_TOKEN.test(token))return{index:i,inline:!1};let inline=/^(?:--package|-p)=(.*)$/.exec(token);if(inline&&BRIDGE_PACKAGE_TOKEN.test(inline[1]))return{index:i,inline:!0}}}function firstOperand(args){return args.find(token=>!token.startsWith("-"))}function epicImplementerArgs(argv){let base=path.basename(argv[0]??""),afterEpicImplementer=rest=>rest.length===0?[]:rest[0]==="epic-implementer"?rest.slice(1):void 0;if(base==="epic-implementer")return argv.slice(1);if(BRIDGE_SERVER_BINS.has(base))return afterEpicImplementer(argv.slice(1));let runnerStart=PACKAGE_RUNNERS.has(base)?1:base==="npm"&&NPM_EXEC_SUBCOMMANDS.has(argv[1]??"")?2:-1;if(runnerStart!==-1){let operands=from=>argv.slice(from).filter(t=>t!=="--"),found=runnerPackageIndex(argv,runnerStart);if(found!==void 0){let rest=operands(found.index+1),commandAt=rest.findIndex(t=>!t.startsWith("-"));return afterEpicImplementer(commandAt===-1?[]:rest.slice(commandAt))}let first=argv.slice(runnerStart).find(t=>!t.startsWith("-"));return first==="epic-implementer"?operands(argv.indexOf(first,runnerStart)+1):void 0}if(base==="node"||base==="nodejs"){let scriptIndex=-1;for(let i=1;i<argv.length;i+=1){let token=argv[i];if(NODE_VALUE_OPTIONS.has(token)){i+=1;continue}if(!token.startsWith("-")){scriptIndex=i;break}}if(scriptIndex===-1)return;let script=argv[scriptIndex].replace(/\\/g,"/"),rest=argv.slice(scriptIndex+1);if(path.posix.basename(script)==="epic-implementer-bin.js")return rest;if(/(?:^|\/)build\/index\.js$/.test(script))return afterEpicImplementer(rest)}}function operatorVerbDecision(segment,stdinFed){let denyFor=family=>({kind:"deny",category:"operator-verb",family}),argv=segment.argv,cliArgs=epicImplementerArgs(argv);if(cliArgs!==void 0){let verb=firstOperand(cliArgs),named=OPERATOR_ONLY_VERBS.find(v=>verb===v||cliArgs.includes(v));if(named!==void 0)return denyFor(named);if(verb===void 0&&stdinFed||segment.unsafe&&(verb===void 0||/[$`]/.test(verb)))return denyFor("resolve-handoff")}if(!isTextOnlyInvocation(argv))for(let token of argv){let routeVerb=namedOperatorOnlyRoute(token);if(routeVerb!==void 0)return denyFor(routeVerb)}return null}function evaluateSimpleCommand(segment,ctx,payloadCwd,depth=0,stdinFed=!1,diagnostic){let argv=unwrapTransparentPrefixes(segment.argv),executable=argv[0];if(executable===void 0)return{kind:"allow"};if(SHELL_EXECUTABLES.has(path.basename(executable))&&depth<4){let cIndex=argv.findIndex(t=>t==="-c"),inner=cIndex===-1?void 0:argv[cIndex+1];if(inner!==void 0){let projections=diagnostic?.complete?diagnosticProjections(inner):[];for(let[i,nested]of tokenizeShellCommand(inner).entries()){let decision=evaluateSimpleCommand(nested,ctx,payloadCwd,depth+1,stdinFed,projections[i]);if(decision.kind==="deny")return decision}return{kind:"allow"}}}if(EVAL_BUILTINS.has(path.basename(executable))&&depth<4){let inner=argv.slice(1).join(" "),projections=diagnostic?.complete?diagnosticProjections(inner):[];for(let[i,nested]of tokenizeShellCommand(inner).entries()){let decision=evaluateSimpleCommand(nested,ctx,payloadCwd,depth+1,stdinFed,projections[i]);if(decision.kind==="deny")return decision}return{kind:"allow"}}if(STDIN_ARGUMENT_PREFIXES.has(path.basename(executable))&&depth<4){let rest=stripStdinPrefixOptions(argv);return rest.length===0?{kind:"allow"}:evaluateSimpleCommand({argv:rest,unsafe:segment.unsafe},ctx,payloadCwd,depth+1,!0,diagnostic?{argv:stripStdinPrefixOptions(unwrapTransparentPrefixes(diagnostic.argv)),complete:!1}:void 0)}segment={argv,unsafe:segment.unsafe};let operatorVerb=operatorVerbDecision(segment,stdinFed);if(operatorVerb!==null)return operatorVerb;if(ctx.correctionEnforced&&isClaudeWorkflowPrintLaunch(segment))return{kind:"deny",category:"workflow-launch-shell",family:"workflow"};let family=classify(executable);if(family===null)return{kind:"allow"};if(stdinFed||segment.unsafe)return unsafeSegmentDecision(family,segment.argv,ctx,resolveEffectiveCwd(ctx,payloadCwd),diagnostic);let cwd=resolveEffectiveCwd(ctx,payloadCwd);if(family==="rm")return evaluateRemove(segment.argv,ctx,cwd);if(family==="database")return evaluateDatabase(segment.argv);if(family==="network")return evaluateNetwork(segment.argv);let git=parseGitInvocation(segment.argv,cwd);return git.subcommand==="push"?git.unsafe?unsafeSegmentDecision("git",segment.argv,ctx,cwd,diagnostic):evaluateGitPush(git.args,ctx):git.subcommand==="reset"?git.unsafe?unsafeSegmentDecision("git",segment.argv,ctx,cwd,diagnostic):evaluateGitReset(git.args,ctx):git.subcommand==="clean"?git.unsafe?unsafeSegmentDecision("git",segment.argv,ctx,cwd,diagnostic):evaluateGitClean(git.args,ctx,git.cwd):{kind:"allow"}}function workflowDeny(category){return{kind:"deny",category,family:"workflow"}}var FILE_TOOLS=new Set(["Read","Edit","Write","MultiEdit","NotebookEdit","Grep","Glob"]),INVOCATION_FIELDS={Skill:["skill","args"],Task:["prompt","description"],Agent:["prompt","description"],SlashCommand:["command"]},PLANNER_TOOL_NAME=/(?:request_plan_generation|get_pipeline_recipe|plan_ticket|implement_ticket)/i;function evaluateCorrectionToolRole(toolName,input){if(FILE_TOOLS.has(toolName))return{kind:"allow"};if(toolName==="Bash")return;let fields=INVOCATION_FIELDS[toolName];if(fields!==void 0){for(let field of fields){let value=input[field];if(value===void 0)continue;if(typeof value!="string")return workflowDeny("workflow-launch-skill");let nameField=toolName==="Skill"?field==="skill":toolName==="SlashCommand";if(WORKFLOW_SLASH_LAUNCH.test(value)||nameField&&WORKFLOW_NAME_EXACT.test(value.trim().split(/\s+/)[0]??""))return workflowDeny("workflow-launch-skill")}return{kind:"allow"}}if(/^mcp__/i.test(toolName)&&PLANNER_TOOL_NAME.test(toolName))return workflowDeny("workflow-planner-tool");let args=Object.values(input).filter(v=>typeof v=="string").join(" ");return WORKFLOW_SLASH_LAUNCH.test(args)?workflowDeny("workflow-entry"):void 0}function evaluateWorkerGuardPayload(payload,ctx){if(ctx.correctionContextInvalid)return workflowDeny("correction-context-invalid");let root=asRecord(payload);if(root===void 0)return ctx.correctionEnforced?workflowDeny("correction-payload-invalid"):{kind:"malformed"};let toolName=root.tool_name??root.toolName;if(typeof toolName!="string")return ctx.correctionEnforced?workflowDeny("correction-payload-invalid"):{kind:"malformed"};let input=asRecord(root.tool_input??root.toolInput);if(ctx.correctionEnforced){if(input===void 0)return workflowDeny("correction-payload-invalid");let decision=evaluateCorrectionToolRole(toolName,input);if(decision!==void 0)return decision}if(toolName!=="Bash")return{kind:"allow"};if(input===void 0)return{kind:"malformed"};let command=input.command;if(typeof command!="string")return ctx.correctionEnforced?workflowDeny("correction-payload-invalid"):{kind:"malformed"};let rawCwd=root.cwd??input.cwd,payloadCwd=typeof rawCwd=="string"?rawCwd:void 0,projections=diagnosticProjections(command);for(let[i,segment]of tokenizeShellCommand(command).entries()){let decision=evaluateSimpleCommand(segment,ctx,payloadCwd,0,!1,projections[i]);if(decision.kind==="deny")return decision}return{kind:"allow"}}function evaluateWorkerGuardInput(raw,ctx){let unreadable=()=>ctx.correctionContextInvalid?workflowDeny("correction-context-invalid"):ctx.correctionEnforced?workflowDeny("correction-payload-invalid"):{kind:"malformed"};if(typeof raw!="string"||raw.length>WORKER_GUARD_MAX_PAYLOAD_BYTES||raw.trim().length===0)return unreadable();let parsed;try{parsed=JSON.parse(raw)}catch{return unreadable()}try{return evaluateWorkerGuardPayload(parsed,ctx)}catch{return unreadable()}}var WORKER_GUARD_ROOT_FLAG="--worktree-root";function resolveWorkerGuardContext(env,cwd,argv=[]){let ctx={},root;for(let i=0;i<argv.length;i+=1){if(argv[i]===WORKER_GUARD_ROOT_FLAG){root=argv[i+1];break}if(argv[i].startsWith(`${WORKER_GUARD_ROOT_FLAG}=`)){root=argv[i].slice(WORKER_GUARD_ROOT_FLAG.length+1);break}}root===void 0&&typeof cwd=="string"&&(root=cwd),typeof root=="string"&&path.isAbsolute(root)&&(ctx.worktreePath=path.resolve(root));let branch=env.BAPI_WORKER_BRANCH;typeof branch=="string"&&branch.trim().length>0&&(ctx.workerBranch=branch.trim());let flagIndex=argv.indexOf("--correction-intent-version"),flagValue=flagIndex>=0?argv[flagIndex+1]:void 0,envValue=env.BAPI_CORRECTION_INTENT_VERSION;return ctx.correctionEnforced=flagValue==="1"||envValue==="1",ctx.correctionContextInvalid=flagIndex>=0&&flagValue!=="1"||envValue!==void 0&&envValue!=="1"||flagIndex>=0&&envValue!==void 0&&envValue!==flagValue,ctx}function runWorkerGuardHook(io){let exitCode=0,correctionRequested=io.argv.includes("--correction-intent-version")||io.env.BAPI_CORRECTION_INTENT_VERSION!==void 0;try{let raw=io.readStdin(),ctx=resolveWorkerGuardContext(io.env,io.cwd,io.argv),decision=evaluateWorkerGuardInput(raw,ctx);decision.kind==="deny"?(io.writeStderr(renderWorkerGuardReason(decision.category,decision.family,decision.form)),exitCode=2):decision.kind==="malformed"&&(io.writeStderr(WORKER_GUARD_MALFORMED_LINE),exitCode=0)}catch{try{io.writeStderr(correctionRequested?renderWorkerGuardReason("correction-payload-invalid","workflow"):WORKER_GUARD_MALFORMED_LINE)}catch{}exitCode=correctionRequested?2:0}return exitCode}function readStdinSync(){return readFileSync(0,"utf-8")}process.exit(runWorkerGuardHook({readStdin:readStdinSync,env:process.env,cwd:process.cwd(),argv:process.argv.slice(2),writeStderr:text=>{process.stderr.write(`${text}
|
|
4
|
+
`){finish(i);continue}masked+=ch}return quote&&(uncertain=!0),finish(command.length),result}var WORKER_GUARD_MAX_PAYLOAD_BYTES=1e6;function asRecord(value){return value!==null&&typeof value=="object"&&!Array.isArray(value)?value:void 0}function isInside(root,candidate){let rel=path.relative(root,candidate);return rel===""?!0:rel.startsWith("..")?!1:!path.isAbsolute(rel)}function resolveEffectiveCwd(ctx,payloadCwd){let root=ctx.worktreePath;if(typeof root!="string"||!path.isAbsolute(root))return;let normalizedRoot=path.resolve(root);if(payloadCwd===void 0)return normalizedRoot;if(typeof payloadCwd!="string"||payloadCwd.length===0)return;let resolved=path.isAbsolute(payloadCwd)?path.resolve(payloadCwd):path.resolve(normalizedRoot,payloadCwd);return isInside(normalizedRoot,resolved)?resolved:void 0}function allTargetsContained(ctx,cwd,targets){let root=ctx.worktreePath;if(typeof root!="string"||!path.isAbsolute(root)||cwd===void 0)return!1;let normalizedRoot=path.resolve(root);return targets.every(target=>{if(target.length===0||target==="~"||target.startsWith("~/"))return!1;let resolved=path.isAbsolute(target)?path.resolve(target):path.resolve(cwd,target);return isInside(normalizedRoot,resolved)})}function parseGitInvocation(argv,baseCwd){let cwd=baseCwd,unsafe=!1,i=1;for(;i<argv.length;){let token=argv[i];if(token==="-C"){let dir=argv[i+1];dir===void 0||cwd===void 0?(unsafe=!0,cwd=void 0):cwd=path.isAbsolute(dir)?path.resolve(dir):path.resolve(cwd,dir),i+=2;continue}if(token==="-c"||token==="--namespace"||token==="--git-dir"||token==="--work-tree"){unsafe=!0,i+=2;continue}if(token.startsWith("-")){i+=1;continue}break}return{subcommand:argv[i]??"",args:argv.slice(i+1),cwd,unsafe}}function isOwnBranchDestination(destination,workerBranch){let colon=destination.indexOf(":"),dst=colon===-1?destination:destination.slice(colon+1);if(dst.length===0)return!1;let bare=dst.startsWith("+")?dst.slice(1):dst;return bare===workerBranch||bare===`refs/heads/${workerBranch}`}function evaluateGitPush(args,ctx){let deny={kind:"deny",category:"git-push",family:"git"},positional=[];for(let i=0;i<args.length;i+=1){let token=args[i];if(token==="--"){positional.push(...args.slice(i+1));break}if(token.startsWith("-")){if(token==="--tags"||token==="--delete"||token==="-d"||token==="--mirror"||token==="--all"||token==="--follow-tags"||token.startsWith("--repo"))return deny;(token==="-o"||token==="--push-option"||token==="--receive-pack"||token==="--exec")&&(i+=1);continue}positional.push(token)}let workerBranch=ctx.workerBranch;return typeof workerBranch!="string"||workerBranch.length===0?deny:positional.length<=1?{kind:"allow"}:positional.slice(1).every(d=>isOwnBranchDestination(d,workerBranch))?{kind:"allow"}:deny}function evaluateGitReset(args,ctx){let deny={kind:"deny",category:"git-reset-hard",family:"git"};if(!args.includes("--hard"))return{kind:"allow"};let positional=[];for(let i=0;i<args.length;i+=1){let token=args[i];if(token==="--"){positional.push(...args.slice(i+1));break}token.startsWith("-")||positional.push(token)}if(positional.length===0)return{kind:"allow"};let workerBranch=ctx.workerBranch;if(typeof workerBranch!="string"||workerBranch.length===0)return deny;let allowed=new Set([workerBranch,`origin/${workerBranch}`,`refs/heads/${workerBranch}`,`refs/remotes/origin/${workerBranch}`]);return positional.every(ref=>allowed.has(ref))?{kind:"allow"}:deny}function evaluateGitClean(args,ctx,cwd){let deny={kind:"deny",category:"filesystem-clean",family:"git"};if(cwd===void 0||!allTargetsContained(ctx,cwd,[cwd]))return deny;let pathspecs=[];for(let i=0;i<args.length;i+=1){let token=args[i];if(token==="--"){pathspecs.push(...args.slice(i+1));break}if(token==="-e"||token==="--exclude"){i+=1;continue}token.startsWith("-")||pathspecs.push(token)}return pathspecs.length===0?{kind:"allow"}:allTargetsContained(ctx,cwd,pathspecs)?{kind:"allow"}:deny}function isRecursiveForcedRemove(args){let recursive=!1,force=!1;for(let token of args){if(token==="--")break;if(token==="--recursive")recursive=!0;else if(token==="--force")force=!0;else{if(token.startsWith("--"))continue;if(token.startsWith("-")&&token.length>1)for(let flag of token.slice(1))(flag==="r"||flag==="R")&&(recursive=!0),flag==="f"&&(force=!0)}}return recursive&&force}function evaluateRemove(argv,ctx,cwd){let deny={kind:"deny",category:"filesystem-remove",family:"rm"},args=argv.slice(1);if(!isRecursiveForcedRemove(args))return{kind:"allow"};let targets=[],sawDoubleDash=!1;for(let token of args){if(!sawDoubleDash&&token==="--"){sawDoubleDash=!0;continue}!sawDoubleDash&&token.startsWith("-")&&token.length>1||targets.push(token)}return targets.length===0?deny:allTargetsContained(ctx,cwd,targets)?{kind:"allow"}:deny}function isDatabaseCommand(executable){let base=path.basename(executable);return base==="psql"||base.startsWith("pg_")}var DESTRUCTIVE_SQL=/\b(?:DROP|TRUNCATE)\b/i;function evaluateDatabase(argv){let deny={kind:"deny",category:"database-destructive",family:"psql"};return argv.slice(1).some(arg=>DESTRUCTIVE_SQL.test(arg))?deny:{kind:"allow"}}var MUTATING_METHODS=new Set(["POST","PUT","PATCH","DELETE"]);function evaluateNetwork(argv){let deny={kind:"deny",category:"network-mutating",family:"curl"},base=path.basename(argv[0]??""),args=argv.slice(1);for(let i=0;i<args.length;i+=1){let token=args[i];if(token==="-X"||token==="--request"||token==="--method"){let value=args[i+1];if(value===void 0||MUTATING_METHODS.has(value.toUpperCase()))return deny;i+=1;continue}if(token.startsWith("-X")&&token.length>2){if(MUTATING_METHODS.has(token.slice(2).toUpperCase()))return deny;continue}if(token.startsWith("--request=")||token.startsWith("--method=")){let value=token.slice(token.indexOf("=")+1);if(MUTATING_METHODS.has(value.toUpperCase()))return deny;continue}if(token==="--data"||token.startsWith("--data=")||token.startsWith("--data-")||token==="--form"||token==="-F"||token==="--upload-file"||token==="-T"||token==="--post-data"||token.startsWith("--post-data=")||token==="--post-file"||token.startsWith("--post-file=")||token==="--body-data"||token.startsWith("--body-data=")||token==="--body-file"||token.startsWith("--body-file=")||base==="curl"&&token==="-d")return deny}return{kind:"allow"}}function classify(executable){let base=path.basename(executable);return base==="git"?"git":base==="rm"?"rm":isDatabaseCommand(base)?"database":base==="curl"||base==="wget"?"network":null}function unsafeGitCategory(argv){let{subcommand}=parseGitInvocation(argv,void 0);return subcommand==="push"?"git-push":subcommand==="reset"?"git-reset-hard":subcommand==="clean"?"filesystem-clean":"git-ambiguous"}function diagnosticPushForce(args){return args.some(t=>t==="--force"||t==="-f"||t==="--force-with-lease"||t.startsWith("--force-with-lease=")||t.startsWith("+"))}function diagnosticViolation(family,diagnostic,ctx,cwd){let full=unwrapTransparentPrefixes(diagnostic.argv),unknown=diagnostic.complete?-1:full.findIndex(t=>/[$`]/.test(t)),argv=unknown<0?full:full.slice(0,unknown);if(family==="database")return evaluateDatabase(argv).kind==="deny";if(family==="network")return evaluateNetwork(argv).kind==="deny";let git=parseGitInvocation(argv,cwd);return family==="git"&&git.subcommand==="push"&&diagnosticPushForce(git.args)?!0:diagnostic.complete?family==="rm"?evaluateRemove(argv,ctx,cwd).kind==="deny":git.unsafe?!0:git.subcommand==="push"?evaluateGitPush(git.args,ctx).kind==="deny":git.subcommand==="reset"?evaluateGitReset(git.args,ctx).kind==="deny":git.subcommand==="clean"?evaluateGitClean(git.args,ctx,git.cwd).kind==="deny":!1:family==="rm"?argv.slice(1).some(t=>!t.startsWith("-"))&&evaluateRemove(argv,ctx,cwd).kind==="deny":git.subcommand==="push"?git.args.filter(t=>!t.startsWith("-")).length>=2&&evaluateGitPush(git.args,ctx).kind==="deny":git.subcommand==="reset"?git.args.some(t=>!t.startsWith("-"))&&evaluateGitReset(git.args,ctx).kind==="deny":git.subcommand==="clean"?evaluateGitClean(git.args,ctx,git.cwd).kind==="deny":!1}function unsafeSegmentDecision(family,argv,ctx,cwd,diagnostic){let category=family==="git"?unsafeGitCategory(argv):family==="rm"?"filesystem-remove":family==="database"?"database-destructive":"network-mutating",decision={kind:"deny",category,family:family==="database"?"psql":family==="network"?"curl":family};return diagnostic&&category!=="git-ambiguous"&&!diagnosticViolation(family,diagnostic,ctx,cwd)?{...decision,form:"shell_form"}:decision}var TRANSPARENT_PREFIXES=new Set(["sudo","env","command","nohup","time","nice","exec"]),STDIN_ARGUMENT_PREFIXES=new Set(["xargs"]),SHELL_EXECUTABLES=new Set(["sh","bash","zsh","dash","ksh"]),EVAL_BUILTINS=new Set(["eval"]);function unwrapTransparentPrefixes(argv){let rest=argv;for(let depth=0;depth<8;depth+=1){let head=rest[0];if(head===void 0||!TRANSPARENT_PREFIXES.has(path.basename(head)))return rest;let i=1;for(;i<rest.length;){let token=rest[i];if(path.basename(head)==="env"&&/^[A-Za-z_][A-Za-z0-9_]*=/.test(token)){i+=1;continue}if(token.startsWith("-")){i+=1;continue}break}rest=rest.slice(i)}return rest}function stripStdinPrefixOptions(argv){let VALUE_OPTS=new Set(["-I","-i","-L","-n","-P","-s","-d","-E","-e","-a","--replace","--max-lines","--max-args","--max-procs","--max-chars","--delimiter","--eof","--arg-file"]),i=1;for(;i<argv.length;){let token=argv[i];if(token==="--"){i+=1;break}if(!token.startsWith("-"))break;if(token.includes("=")){i+=1;continue}i+=VALUE_OPTS.has(token)?2:1}return argv.slice(i)}var WORKFLOW_NAMES="implement-ticket|plan-ticket|idea-to-pr|review-and-implement",WORKFLOW_SLASH_LAUNCH=new RegExp(`(?:^|\\s)/(?:bridge-)?(?:${WORKFLOW_NAMES})(?=\\s|$)`,"i"),WORKFLOW_NAME_EXACT=new RegExp(`^/?(?:[A-Za-z0-9_-]+:)?(?:bridge-)?(?:${WORKFLOW_NAMES})$`,"i"),CLAUDE_PACKAGE_TOKEN=/^(?:@anthropic-ai\/)?claude(?:-code)?(?:@\S+)?$/;function claudeLaunchArgs(argv){let base=path.basename(argv[0]??"");if(base==="claude")return argv.slice(1);if(base==="npx"){let index=argv.findIndex((token,i)=>i>0&&CLAUDE_PACKAGE_TOKEN.test(token));return index===-1?void 0:argv.slice(index+1)}}function isClaudeWorkflowPrintLaunch(segment){let args=claudeLaunchArgs(segment.argv);return args===void 0||!args.some(token=>token==="-p"||token==="--print"||token.startsWith("--print="))?!1:segment.unsafe?!0:args.some(token=>{let value=token.startsWith("--print=")?token.slice(8):token;return WORKFLOW_SLASH_LAUNCH.test(value)})}var OPERATOR_ONLY_VERBS=["resolve-handoff","regenerate-plan","acknowledge-gaps","reserve-council","record-decision"],BRIDGE_PACKAGE_TOKEN=/^@bridge_gpt\/mcp-server(?:@\S+)?$/,PACKAGE_RUNNERS=new Set(["npx","pnpx","bunx"]),BRIDGE_SERVER_BINS=new Set(["mcp-server","bridge-api-mcp-server"]),ROUTE_TEXT_ONLY_EXECUTABLES=new Set(["grep","egrep","fgrep","rg","ag","cat","echo","printf","head","tail","wc","diff","less","more","ls","sort","uniq","tr","cut","jq"]);function isTextOnlyInvocation(argv){let executable=path.basename(argv[0]??"");return ROUTE_TEXT_ONLY_EXECUTABLES.has(executable)?!0:executable==="git"?!argv.some(token=>/alias\.[^=]*=\s*!/i.test(token)):executable==="find"?!argv.some(token=>["-exec","-execdir","-ok","-okdir"].includes(token)):!1}function namedOperatorOnlyRoute(token){let decoded=token;for(let i=0;i<3;i+=1){let next;try{next=decodeURIComponent(decoded)}catch{break}if(next===decoded)break;decoded=next}let haystacks=[decoded.toLowerCase(),token.toLowerCase()];for(let text of haystacks){let council=/\/driver-councils(\/[^/?#\s"'`]+)?/.exec(text);if(council)return council[1]?"record-decision":"reserve-council"}return OPERATOR_ONLY_VERBS.find(verb=>haystacks.some(text=>text.includes(`/${verb}`)))}var NODE_VALUE_OPTIONS=new Set(["-r","--require","--import","--loader","--experimental-loader","-C","--conditions","--env-file","--input-type","--title","--stack-size","--max-old-space-size"]),NPM_EXEC_SUBCOMMANDS=new Set(["exec","x"]);function runnerPackageIndex(argv,start){for(let i=start;i<argv.length;i+=1){let token=argv[i];if(BRIDGE_PACKAGE_TOKEN.test(token))return{index:i,inline:!1};let inline=/^(?:--package|-p)=(.*)$/.exec(token);if(inline&&BRIDGE_PACKAGE_TOKEN.test(inline[1]))return{index:i,inline:!0}}}function firstOperand(args){return args.find(token=>!token.startsWith("-"))}function epicImplementerArgs(argv){let base=path.basename(argv[0]??""),afterEpicImplementer=rest=>rest.length===0?[]:rest[0]==="epic-implementer"?rest.slice(1):void 0;if(base==="epic-implementer")return argv.slice(1);if(BRIDGE_SERVER_BINS.has(base))return afterEpicImplementer(argv.slice(1));let runnerStart=PACKAGE_RUNNERS.has(base)?1:base==="npm"&&NPM_EXEC_SUBCOMMANDS.has(argv[1]??"")?2:-1;if(runnerStart!==-1){let operands=from=>argv.slice(from).filter(t=>t!=="--"),found=runnerPackageIndex(argv,runnerStart);if(found!==void 0){let rest=operands(found.index+1),commandAt=rest.findIndex(t=>!t.startsWith("-"));return afterEpicImplementer(commandAt===-1?[]:rest.slice(commandAt))}let first=argv.slice(runnerStart).find(t=>!t.startsWith("-"));return first==="epic-implementer"?operands(argv.indexOf(first,runnerStart)+1):void 0}if(base==="node"||base==="nodejs"){let scriptIndex=-1;for(let i=1;i<argv.length;i+=1){let token=argv[i];if(NODE_VALUE_OPTIONS.has(token)){i+=1;continue}if(!token.startsWith("-")){scriptIndex=i;break}}if(scriptIndex===-1)return;let script=argv[scriptIndex].replace(/\\/g,"/"),rest=argv.slice(scriptIndex+1);if(path.posix.basename(script)==="epic-implementer-bin.js")return rest;if(/(?:^|\/)build\/index\.js$/.test(script))return afterEpicImplementer(rest)}}function operatorVerbDecision(segment,stdinFed){let denyFor=family=>({kind:"deny",category:"operator-verb",family}),argv=segment.argv,cliArgs=epicImplementerArgs(argv);if(cliArgs!==void 0){let verb=firstOperand(cliArgs),named=OPERATOR_ONLY_VERBS.find(v=>verb===v||cliArgs.includes(v));if(named!==void 0)return denyFor(named);if(verb===void 0&&stdinFed||segment.unsafe&&(verb===void 0||/[$`]/.test(verb)))return denyFor("resolve-handoff")}if(!isTextOnlyInvocation(argv))for(let token of argv){let routeVerb=namedOperatorOnlyRoute(token);if(routeVerb!==void 0)return denyFor(routeVerb)}return null}function evaluateSimpleCommand(segment,ctx,payloadCwd,depth=0,stdinFed=!1,diagnostic){let argv=unwrapTransparentPrefixes(segment.argv),executable=argv[0];if(executable===void 0)return{kind:"allow"};if(SHELL_EXECUTABLES.has(path.basename(executable))&&depth<4){let cIndex=argv.findIndex(t=>t==="-c"),inner=cIndex===-1?void 0:argv[cIndex+1];if(inner!==void 0){let projections=diagnostic?.complete?diagnosticProjections(inner):[];for(let[i,nested]of tokenizeShellCommand(inner).entries()){let decision=evaluateSimpleCommand(nested,ctx,payloadCwd,depth+1,stdinFed,projections[i]);if(decision.kind==="deny")return decision}return{kind:"allow"}}}if(EVAL_BUILTINS.has(path.basename(executable))&&depth<4){let inner=argv.slice(1).join(" "),projections=diagnostic?.complete?diagnosticProjections(inner):[];for(let[i,nested]of tokenizeShellCommand(inner).entries()){let decision=evaluateSimpleCommand(nested,ctx,payloadCwd,depth+1,stdinFed,projections[i]);if(decision.kind==="deny")return decision}return{kind:"allow"}}if(STDIN_ARGUMENT_PREFIXES.has(path.basename(executable))&&depth<4){let rest=stripStdinPrefixOptions(argv);return rest.length===0?{kind:"allow"}:evaluateSimpleCommand({argv:rest,unsafe:segment.unsafe},ctx,payloadCwd,depth+1,!0,diagnostic?{argv:stripStdinPrefixOptions(unwrapTransparentPrefixes(diagnostic.argv)),complete:!1}:void 0)}segment={argv,unsafe:segment.unsafe};let operatorVerb=operatorVerbDecision(segment,stdinFed);if(operatorVerb!==null)return operatorVerb;if(ctx.correctionEnforced&&isClaudeWorkflowPrintLaunch(segment))return{kind:"deny",category:"workflow-launch-shell",family:"workflow"};let family=classify(executable);if(family===null)return{kind:"allow"};if(stdinFed||segment.unsafe)return unsafeSegmentDecision(family,segment.argv,ctx,resolveEffectiveCwd(ctx,payloadCwd),diagnostic);let cwd=resolveEffectiveCwd(ctx,payloadCwd);if(family==="rm")return evaluateRemove(segment.argv,ctx,cwd);if(family==="database")return evaluateDatabase(segment.argv);if(family==="network")return evaluateNetwork(segment.argv);let git=parseGitInvocation(segment.argv,cwd);return git.subcommand==="push"?git.unsafe?unsafeSegmentDecision("git",segment.argv,ctx,cwd,diagnostic):evaluateGitPush(git.args,ctx):git.subcommand==="reset"?git.unsafe?unsafeSegmentDecision("git",segment.argv,ctx,cwd,diagnostic):evaluateGitReset(git.args,ctx):git.subcommand==="clean"?git.unsafe?unsafeSegmentDecision("git",segment.argv,ctx,cwd,diagnostic):evaluateGitClean(git.args,ctx,git.cwd):{kind:"allow"}}function workflowDeny(category){return{kind:"deny",category,family:"workflow"}}var FILE_TOOLS=new Set(["Read","Edit","Write","MultiEdit","NotebookEdit","Grep","Glob"]),INVOCATION_FIELDS={Skill:["skill","args"],Task:["prompt","description"],Agent:["prompt","description"],SlashCommand:["command"]},PLANNER_TOOL_NAME=/(?:request_plan_generation|get_pipeline_recipe|plan_ticket|implement_ticket)/i;function evaluateCorrectionToolRole(toolName,input){if(FILE_TOOLS.has(toolName))return{kind:"allow"};if(toolName==="Bash")return;let fields=INVOCATION_FIELDS[toolName];if(fields!==void 0){for(let field of fields){let value=input[field];if(value===void 0)continue;if(typeof value!="string")return workflowDeny("workflow-launch-skill");let nameField=toolName==="Skill"?field==="skill":toolName==="SlashCommand";if(WORKFLOW_SLASH_LAUNCH.test(value)||nameField&&WORKFLOW_NAME_EXACT.test(value.trim().split(/\s+/)[0]??""))return workflowDeny("workflow-launch-skill")}return{kind:"allow"}}if(/^mcp__/i.test(toolName)&&PLANNER_TOOL_NAME.test(toolName))return workflowDeny("workflow-planner-tool");let args=Object.values(input).filter(v=>typeof v=="string").join(" ");return WORKFLOW_SLASH_LAUNCH.test(args)?workflowDeny("workflow-entry"):void 0}function evaluateWorkerGuardPayload(payload,ctx){if(ctx.correctionContextInvalid)return workflowDeny("correction-context-invalid");let root=asRecord(payload);if(root===void 0)return ctx.correctionEnforced?workflowDeny("correction-payload-invalid"):{kind:"malformed"};let toolName=root.tool_name??root.toolName;if(typeof toolName!="string")return ctx.correctionEnforced?workflowDeny("correction-payload-invalid"):{kind:"malformed"};let input=asRecord(root.tool_input??root.toolInput);if(ctx.correctionEnforced){if(input===void 0)return workflowDeny("correction-payload-invalid");let decision=evaluateCorrectionToolRole(toolName,input);if(decision!==void 0)return decision}if(toolName!=="Bash")return{kind:"allow"};if(input===void 0)return{kind:"malformed"};let command=input.command;if(typeof command!="string")return ctx.correctionEnforced?workflowDeny("correction-payload-invalid"):{kind:"malformed"};let rawCwd=root.cwd??input.cwd,payloadCwd=typeof rawCwd=="string"?rawCwd:void 0,projections=diagnosticProjections(command);for(let[i,segment]of tokenizeShellCommand(command).entries()){let decision=evaluateSimpleCommand(segment,ctx,payloadCwd,0,!1,projections[i]);if(decision.kind==="deny")return decision}return{kind:"allow"}}function evaluateWorkerGuardInput(raw,ctx){let unreadable=()=>ctx.correctionContextInvalid?workflowDeny("correction-context-invalid"):ctx.correctionEnforced?workflowDeny("correction-payload-invalid"):{kind:"malformed"};if(typeof raw!="string"||raw.length>WORKER_GUARD_MAX_PAYLOAD_BYTES||raw.trim().length===0)return unreadable();let parsed;try{parsed=JSON.parse(raw)}catch{return unreadable()}try{return evaluateWorkerGuardPayload(parsed,ctx)}catch{return unreadable()}}var WORKER_GUARD_ROOT_FLAG="--worktree-root";function resolveWorkerGuardContext(env,cwd,argv=[]){let ctx={},root;for(let i=0;i<argv.length;i+=1){if(argv[i]===WORKER_GUARD_ROOT_FLAG){root=argv[i+1];break}if(argv[i].startsWith(`${WORKER_GUARD_ROOT_FLAG}=`)){root=argv[i].slice(WORKER_GUARD_ROOT_FLAG.length+1);break}}root===void 0&&typeof cwd=="string"&&(root=cwd),typeof root=="string"&&path.isAbsolute(root)&&(ctx.worktreePath=path.resolve(root));let branch=env.BAPI_WORKER_BRANCH;typeof branch=="string"&&branch.trim().length>0&&(ctx.workerBranch=branch.trim());let flagIndex=argv.indexOf("--correction-intent-version"),flagValue=flagIndex>=0?argv[flagIndex+1]:void 0,envValue=env.BAPI_CORRECTION_INTENT_VERSION;return ctx.correctionEnforced=flagValue==="1"||envValue==="1",ctx.correctionContextInvalid=flagIndex>=0&&flagValue!=="1"||envValue!==void 0&&envValue!=="1"||flagIndex>=0&&envValue!==void 0&&envValue!==flagValue,ctx}function runWorkerGuardHook(io){let exitCode=0,correctionRequested=io.argv.includes("--correction-intent-version")||io.env.BAPI_CORRECTION_INTENT_VERSION!==void 0;try{let raw=io.readStdin(),ctx=resolveWorkerGuardContext(io.env,io.cwd,io.argv),decision=evaluateWorkerGuardInput(raw,ctx);decision.kind==="deny"?(io.writeStderr(renderWorkerGuardReason(decision.category,decision.family,decision.form)),exitCode=2):decision.kind==="malformed"&&(io.writeStderr(WORKER_GUARD_MALFORMED_LINE),exitCode=0)}catch{try{io.writeStderr(correctionRequested?renderWorkerGuardReason("correction-payload-invalid","workflow"):WORKER_GUARD_MALFORMED_LINE)}catch{}exitCode=correctionRequested?2:0}return exitCode}function readStdinSync(){return readFileSync(0,"utf-8")}process.exit(runWorkerGuardHook({readStdin:readStdinSync,env:process.env,cwd:process.cwd(),argv:process.argv.slice(2),writeStderr:text=>{process.stderr.write(`${text}
|
|
5
5
|
`)}}));
|