@bridge_gpt/mcp-server 0.2.74 → 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/prompt.js +9 -21
- package/build/agents.generated.js +2 -2
- package/build/authored-plan.js +542 -0
- package/build/bridge-permissions.js +8 -0
- package/build/commands.generated.js +5 -5
- package/build/conductor/bridge-api-client.js +666 -46
- package/build/conductor/epic-implementer-cli.js +337 -93
- package/build/conductor/gate-discovery.js +209 -9
- package/build/conductor/gate-settings-review.js +7 -11
- 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/docs.generated.js +2 -2
- package/build/drive-epic.js +387 -12
- package/build/epic-ci-workflow.js +3 -2
- package/build/epic-implementer-bin.js +152 -38
- 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/executor/completion-contract.js +24 -1
- package/build/executor/gate-qualification-job.js +193 -23
- package/build/executor/gate-qualification-tests-ran.js +232 -0
- package/build/executor/job-runner.js +9 -722
- package/build/executor/job-type-wrappers.js +734 -0
- package/build/executor/preflight.js +6 -2
- package/build/executor/process-containment.js +8 -1
- 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/generated/ticket-status.js +20 -0
- package/build/index.js +391 -257
- package/build/install-bridge-conductor-answers.js +28 -1
- package/build/install-bridge-conductor-apply.js +11 -3
- package/build/install-bridge-conductor-assessment.js +114 -12
- package/build/install-bridge-conductor-compact.js +2 -0
- package/build/install-bridge-conductor-gate.js +257 -80
- package/build/install-bridge-conductor-setup.js +4 -4
- package/build/install-bridge-conductor-trial-report.js +170 -0
- package/build/install-bridge-conductor.js +303 -31
- package/build/pipelines.generated.js +7 -7
- package/build/plan-generation.js +17 -0
- package/build/printed-remedy-commands.js +54 -0
- package/build/readme.generated.js +1 -1
- package/build/repository-toolchains.js +11 -5
- package/build/scripts/saved-commands-config-field-driver.js +65 -0
- package/build/setup-epic.js +10 -1
- package/build/test-support/executor-source-files.js +1 -1
- package/build/v2-readiness-requirements.js +5 -1
- package/build/version.generated.js +3 -3
- package/build/worker-guard-hook-bin.js +2 -2
- 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
|
@@ -66,8 +66,11 @@ const JAVASCRIPT_LOCKFILES = [
|
|
|
66
66
|
"bun.lockb",
|
|
67
67
|
];
|
|
68
68
|
const PYTHON_LOCKFILES = ["uv.lock", "poetry.lock", "requirements.txt"];
|
|
69
|
-
/**
|
|
70
|
-
|
|
69
|
+
/**
|
|
70
|
+
* Python manifests that name dependencies but that Bridge does not install.
|
|
71
|
+
* BAPI-1698: exported so dependency discovery can name them as coverage gaps.
|
|
72
|
+
*/
|
|
73
|
+
export const UNSUPPORTED_PYTHON_MANIFESTS = ["pyproject.toml", "Pipfile", "setup.py", "environment.yml"];
|
|
71
74
|
/** Whether the set provisions nothing. */
|
|
72
75
|
export function hasNoProvisionedToolchain(toolchains) {
|
|
73
76
|
return toolchains.javascript === null && toolchains.python === null && toolchains.go === null;
|
|
@@ -530,11 +533,14 @@ export function installArgvForJavaScript(js) {
|
|
|
530
533
|
}
|
|
531
534
|
/**
|
|
532
535
|
* BAPI-1551 — the fixed install argv for a Python toolchain. pip's argv is kept
|
|
533
|
-
* for the description only: a bare `pip install` targets whatever
|
|
534
|
-
* first on `PATH`, so a dependency refresh never proposes
|
|
536
|
+
* for the toolchain description only: a bare `pip install` targets whatever
|
|
537
|
+
* interpreter is first on `PATH`, so a dependency refresh never proposes THIS
|
|
538
|
+
* argv. BAPI-1698: discovery may instead propose a separate, checkout-local
|
|
539
|
+
* `.venv` bootstrap for pip (see `proposeDependencyInstall`); this function and
|
|
540
|
+
* its description are unchanged by that.
|
|
535
541
|
*
|
|
536
542
|
* BAPI-1677 — `extras` holds only keys the install target declares. With none, every
|
|
537
|
-
* caller's argv is byte-identical to before. pip takes none
|
|
543
|
+
* caller's argv is byte-identical to before. pip takes none.
|
|
538
544
|
*/
|
|
539
545
|
export function installArgvForPython(py, extras = []) {
|
|
540
546
|
switch (py.manager) {
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
/**
|
|
3
|
+
* Saved Epic Implementer test commands: built-MCP `config_field` driver (BAPI-1699).
|
|
4
|
+
*
|
|
5
|
+
* A Python `subprocess` boundary that lets a real pytest suite drive the REAL built
|
|
6
|
+
* MCP server (`build/index.js`) over its normal stdio transport against the real
|
|
7
|
+
* FastAPI `/jira/config-field/*` routes, using only the registered `config_field`
|
|
8
|
+
* tool. It is test-support infrastructure, not an MCP tool.
|
|
9
|
+
*
|
|
10
|
+
* node saved-commands-config-field-driver.js <commandsJsonPath> <resultsJsonPath>
|
|
11
|
+
*
|
|
12
|
+
* `commandsJsonPath` holds `{ baseUrl, apiKey, repoName, calls: [...] }` and each call is
|
|
13
|
+
* `{ operation: "get" | "update", field_name, value? }`. Credentials arrive through the
|
|
14
|
+
* file and the child environment only, never argv. One MCP session serves every call;
|
|
15
|
+
* the results file gets `{ tools: string[], results: [{ isError, text }] }`. stdout stays
|
|
16
|
+
* empty so a caller never captures incidental noise.
|
|
17
|
+
*/
|
|
18
|
+
import fs from "node:fs";
|
|
19
|
+
import path from "node:path";
|
|
20
|
+
import { fileURLToPath } from "node:url";
|
|
21
|
+
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
|
22
|
+
import { StdioClientTransport } from "@modelcontextprotocol/sdk/client/stdio.js";
|
|
23
|
+
async function main() {
|
|
24
|
+
const [commandsPath, resultsPath] = process.argv.slice(2);
|
|
25
|
+
if (!commandsPath || !resultsPath) {
|
|
26
|
+
process.stderr.write("usage: saved-commands-config-field-driver <commandsJsonPath> <resultsJsonPath>\n");
|
|
27
|
+
process.exit(2);
|
|
28
|
+
}
|
|
29
|
+
const input = JSON.parse(fs.readFileSync(commandsPath, "utf-8"));
|
|
30
|
+
const here = path.dirname(fileURLToPath(import.meta.url));
|
|
31
|
+
const transport = new StdioClientTransport({
|
|
32
|
+
command: "node",
|
|
33
|
+
args: [path.join(here, "..", "index.js")],
|
|
34
|
+
env: {
|
|
35
|
+
...process.env,
|
|
36
|
+
BAPI_BASE_URL: input.baseUrl,
|
|
37
|
+
BAPI_API_KEY: input.apiKey,
|
|
38
|
+
BAPI_REPO_NAME: input.repoName,
|
|
39
|
+
BAPI_MCP_UPDATE_CHECK_ENABLED: "false",
|
|
40
|
+
},
|
|
41
|
+
stderr: "ignore",
|
|
42
|
+
});
|
|
43
|
+
const client = new Client({ name: "saved-commands-contract-driver", version: "0.0.1" });
|
|
44
|
+
const results = [];
|
|
45
|
+
let tools = [];
|
|
46
|
+
try {
|
|
47
|
+
await client.connect(transport);
|
|
48
|
+
tools = (await client.listTools()).tools.map((t) => t.name);
|
|
49
|
+
for (const call of input.calls) {
|
|
50
|
+
const response = (await client.callTool({ name: "config_field", arguments: { ...call } }));
|
|
51
|
+
const text = (response.content ?? []).map((c) => (c.type === "text" ? c.text ?? "" : "")).join("\n");
|
|
52
|
+
results.push({ isError: response.isError === true, text });
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
finally {
|
|
56
|
+
await transport.close();
|
|
57
|
+
}
|
|
58
|
+
const tmp = `${resultsPath}.tmp`;
|
|
59
|
+
fs.writeFileSync(tmp, JSON.stringify({ tools, results }), "utf-8");
|
|
60
|
+
fs.renameSync(tmp, resultsPath);
|
|
61
|
+
}
|
|
62
|
+
main().catch((error) => {
|
|
63
|
+
process.stderr.write(`saved-commands-config-field-driver failed: ${error instanceof Error ? error.message : String(error)}\n`);
|
|
64
|
+
process.exit(1);
|
|
65
|
+
});
|
package/build/setup-epic.js
CHANGED
|
@@ -2993,6 +2993,8 @@ export async function runSetupEpicWorkflow(argv, overrides = {}, handoff) {
|
|
|
2993
2993
|
...(sink.runPosture !== undefined ? { runPosture: sink.runPosture } : {}),
|
|
2994
2994
|
...(sink.launchOutcome !== undefined ? { launchOutcome: sink.launchOutcome } : {}),
|
|
2995
2995
|
...(sink.runStatus !== undefined ? { runStatus: sink.runStatus } : {}),
|
|
2996
|
+
...(sink.storedPlanHash !== undefined ? { storedPlanHash: sink.storedPlanHash } : {}),
|
|
2997
|
+
...(sink.orderingEdgesAdded !== undefined ? { orderingEdgesAdded: sink.orderingEdgesAdded } : {}),
|
|
2996
2998
|
...(sink.observations !== undefined && sink.observations.length > 0
|
|
2997
2999
|
? { observations: [...sink.observations] }
|
|
2998
3000
|
: {}),
|
|
@@ -4527,8 +4529,15 @@ async function executeSetupEpic(argv, overrides, runIdSink, handoff) {
|
|
|
4527
4529
|
result.plan_stored = true;
|
|
4528
4530
|
runIdSink.planStored = true;
|
|
4529
4531
|
const serverHash = stored?.plan_hash;
|
|
4530
|
-
if (typeof serverHash === "string")
|
|
4532
|
+
if (typeof serverHash === "string") {
|
|
4531
4533
|
result.plan_hash = serverHash;
|
|
4534
|
+
runIdSink.storedPlanHash = serverHash;
|
|
4535
|
+
}
|
|
4536
|
+
// BAPI-1706 — optional: an older server omits it, and absence stays absence.
|
|
4537
|
+
const edgesAdded = stored?.ordering_edges_added;
|
|
4538
|
+
if (typeof edgesAdded === "number" && Number.isSafeInteger(edgesAdded) && edgesAdded >= 0) {
|
|
4539
|
+
runIdSink.orderingEdgesAdded = edgesAdded;
|
|
4540
|
+
}
|
|
4532
4541
|
say(`Plan: stored v${plan.plan_version}`);
|
|
4533
4542
|
}
|
|
4534
4543
|
catch (err) {
|
|
@@ -53,6 +53,7 @@ export const EXECUTOR_FLAT_IMPORT_BASELINE = [
|
|
|
53
53
|
"./interrupted-worktree.js",
|
|
54
54
|
"./job-errors.js",
|
|
55
55
|
"./job-log-registry.js",
|
|
56
|
+
"./job-type-wrappers.js",
|
|
56
57
|
"./job-types.js",
|
|
57
58
|
"./live-worker-registry.js",
|
|
58
59
|
"./merge-job.js",
|
|
@@ -74,7 +75,6 @@ export const EXECUTOR_FLAT_IMPORT_BASELINE = [
|
|
|
74
75
|
"./resume-pre-spawn.js",
|
|
75
76
|
"./spawn-job-driver.js",
|
|
76
77
|
"./stale-artifacts.js",
|
|
77
|
-
"./terminal-mutation.js",
|
|
78
78
|
"./types.js",
|
|
79
79
|
"./verdict-artifact.js",
|
|
80
80
|
"./verification-hints.js",
|
|
@@ -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"];
|
|
@@ -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
|
`)}}));
|
package/docs/EPIC-IMPLEMENTER.md
CHANGED
|
@@ -34,10 +34,10 @@ typed run-control record that says why and what clears it.
|
|
|
34
34
|
`abandoned`. A ticket that needs a person **parks** as `needs_human`. See
|
|
35
35
|
[Recovering a parked run](#recovering-a-stuck-or-parked-run).
|
|
36
36
|
|
|
37
|
-
**The v1 `epic-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
37
|
+
**The v1 `epic-tick` command is retired.** It is no longer a command, and the
|
|
38
|
+
CLI refuses it as an unknown command. There is nothing to schedule locally. If
|
|
39
|
+
you registered a schedule for it with an older release, remove it; it is a dead
|
|
40
|
+
timer.
|
|
41
41
|
|
|
42
42
|
## Drive an epic: `drive-epic`
|
|
43
43
|
|
|
@@ -49,17 +49,26 @@ to confirm.
|
|
|
49
49
|
|
|
50
50
|
What happens:
|
|
51
51
|
|
|
52
|
-
1. The command opens
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
52
|
+
1. The command opens a Bridge **connect page** in your browser, which sends you to GitHub
|
|
53
|
+
to sign in. Choose the GitHub account you use for this repository.
|
|
54
|
+
2. Bridge lists the installations of the app where you can **change** at least one
|
|
55
|
+
repository (push, maintain, or admin). Pick one, or choose **Install on a new GitHub
|
|
56
|
+
account** to install the app — on GitHub, pick the repositories under **Repository
|
|
57
|
+
access** (see [Choosing repositories](#choosing-repositories)) and click **Install**.
|
|
58
|
+
GitHub then asks you to sign in once more so Bridge can check your access.
|
|
59
|
+
3. Bridge shows a **Confirm GitHub access for this Bridge project** page naming your GitHub
|
|
60
|
+
login, the GitHub account, the Bridge project, and the repositories Bridge may use.
|
|
61
|
+
Click **Confirm connection** only if you started this connection yourself.
|
|
62
|
+
4. The browser lands on *"GitHub connection received — return to your terminal."*
|
|
63
|
+
5. Back in the terminal, the command shows who confirmed GitHub access and the
|
|
64
|
+
repositories you can change, and asks which one to connect. **Every connection is
|
|
65
|
+
confirmed by hand** — even when there is exactly one repository. There is no `--yes`
|
|
66
|
+
flag.
|
|
67
|
+
6. Choose one, and it prints the connected `owner/repo`.
|
|
68
|
+
|
|
69
|
+
**Bridge connects only repositories you can change on GitHub.** A read-only collaborator
|
|
70
|
+
cannot connect an installation, and nobody can connect more repositories than they could
|
|
71
|
+
already push to.
|
|
63
72
|
|
|
64
73
|
**You are never asked for a GitHub token, password, or installation ID.** You
|
|
65
74
|
authenticate to GitHub in your own browser; the terminal only ever carries a short-lived
|
|
@@ -78,11 +87,12 @@ If an organization owns the repository and you are not an owner, GitHub sends an
|
|
|
78
87
|
entirely on GitHub's side and **does not return to your terminal**, so `connect-github`
|
|
79
88
|
cannot wait for it — the command exits, and the 15-minute request expires.
|
|
80
89
|
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
90
|
+
Once an owner approves, run `connect-github` again. The connect page signs you in to
|
|
91
|
+
GitHub and lists the approved installation, provided you can push to at least one of its
|
|
92
|
+
repositories. If you cannot, the approving owner can connect it instead — or use
|
|
93
|
+
[Option A-2 — delegated handoff](#option-a-2--delegated-handoff-someone-else-installs-it):
|
|
94
|
+
its link stays valid for 72 hours and `--resume` reports `awaiting organization approval`
|
|
95
|
+
while you wait.
|
|
86
96
|
|
|
87
97
|
---
|
|
88
98
|
|
|
@@ -111,12 +121,19 @@ The link is valid for **72 hours** and is **single-use**.
|
|
|
111
121
|
|
|
112
122
|
### 2. Send it to your GitHub org admin
|
|
113
123
|
|
|
114
|
-
They open it
|
|
115
|
-
|
|
116
|
-
|
|
124
|
+
They open it and sign in to GitHub. Bridge lists the installations where they can change
|
|
125
|
+
at least one repository, or lets them install the app on a new account. After that,
|
|
126
|
+
Bridge shows a **confirmation page** naming their GitHub login, the GitHub account, the
|
|
127
|
+
requesting Bridge project and account, and the repositories Bridge may use. Nothing is
|
|
128
|
+
staged until they click **Confirm connection**. They then land on a page that tells them
|
|
129
|
+
whether their part succeeded.
|
|
117
130
|
|
|
118
|
-
|
|
119
|
-
and the
|
|
131
|
+
Before they prove access on GitHub, the pages show nothing about your project. Bridge
|
|
132
|
+
records the GitHub user ID and login of the person who proved access, with the proof, so
|
|
133
|
+
`--resume` can show you who confirmed. Bridge does not keep their GitHub token.
|
|
134
|
+
|
|
135
|
+
If the person has no write access to any repository in the installation, they see the
|
|
136
|
+
failure page and are asked to contact you. Ask someone who can push to the repository.
|
|
120
137
|
|
|
121
138
|
### 3. Finish the connection
|
|
122
139
|
|
|
@@ -139,14 +156,14 @@ Possible states `--resume` will report:
|
|
|
139
156
|
|---|---|
|
|
140
157
|
| `pending` | Nobody has opened the link yet. |
|
|
141
158
|
| `awaiting organization approval` | They requested the install; a GitHub org owner must approve it. The link stays usable until it expires. |
|
|
142
|
-
| `staged` | Ready — pick a repository
|
|
159
|
+
| `staged` | Ready — `--resume` shows who confirmed GitHub access, then you pick a repository they can change. |
|
|
160
|
+
| `verification-failed` | Access could not be confirmed, or the confirmation is more than 72 hours old. Mint a new link. |
|
|
143
161
|
| `expired` / `revoked` | Mint a new link with `--handoff`. |
|
|
144
162
|
| `connected` | Already finished. |
|
|
145
163
|
|
|
146
|
-
**A staged handoff stays confirmable after the
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
safe. Only the click window expires.
|
|
164
|
+
**A staged handoff stays confirmable for 72 hours after the delegate proved access**,
|
|
165
|
+
even past the link's own deadline. Confirmation re-checks the repositories with GitHub
|
|
166
|
+
at that moment. After 72 hours the proof is too old and you mint a new link.
|
|
150
167
|
|
|
151
168
|
### Revoking a link
|
|
152
169
|
|
|
@@ -161,11 +178,9 @@ even if it had already staged.
|
|
|
161
178
|
|
|
162
179
|
### If the app is already installed on that organization
|
|
163
180
|
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
not claim to have detected an installation it cannot safely see. In that case use
|
|
168
|
-
[Option C](#option-c--manual-install--installation-id-fallback).
|
|
181
|
+
The same link works. After signing in to GitHub, the recipient sees the existing
|
|
182
|
+
installation in the list and can choose it — as long as they can push to at least one of
|
|
183
|
+
its repositories.
|
|
169
184
|
|
|
170
185
|
---
|
|
171
186
|
|
|
@@ -173,27 +188,23 @@ not claim to have detected an installation it cannot safely see. In that case us
|
|
|
173
188
|
|
|
174
189
|
Bridge captures the installation automatically — you never copy an ID by hand.
|
|
175
190
|
|
|
176
|
-
1. Open your project's **Get Started** page in the Bridge web UI
|
|
177
|
-
on the GitHub connection task
|
|
178
|
-
2. In the **1. Connect GitHub** panel, click **Connect GitHub**. Bridge
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
GitHub, links it to your project, and stores the installation automatically. If the
|
|
189
|
-
installation covers exactly one repo — or one repo clearly matches your project —
|
|
190
|
-
Bridge binds it for you; otherwise it shows a short **repository picker** so you can
|
|
191
|
-
confirm which repo maps to this project.
|
|
192
|
-
7. The outcome appears in the **1. Connect GitHub** panel itself — you should see
|
|
191
|
+
1. Open your project's **Get Started** page in the Bridge web UI, signed in to Bridge. The
|
|
192
|
+
page opens directly on the GitHub connection task.
|
|
193
|
+
2. In the **1. Connect GitHub** panel, click **Connect GitHub**. Bridge sends you to GitHub
|
|
194
|
+
to sign in (choose the GitHub account you use for this repository).
|
|
195
|
+
3. Bridge lists the installations where you can change at least one repository. Choose
|
|
196
|
+
one, or choose **Install on a new GitHub account**: on GitHub, pick the repositories
|
|
197
|
+
under **Repository access** (see [Choosing repositories](#choosing-repositories)) and
|
|
198
|
+
click **Install** (or **Install & request** / **Request** if an org owner must approve).
|
|
199
|
+
4. Bridge confirms your access with GitHub and links the installation to your project. If
|
|
200
|
+
exactly one repository you can change — or one that clearly matches your project — is
|
|
201
|
+
available, Bridge binds it for you; otherwise it shows a short **repository picker**.
|
|
202
|
+
5. The outcome appears in the **1. Connect GitHub** panel — you should see
|
|
193
203
|
**GitHub connected** naming the repository Bridge linked.
|
|
194
204
|
|
|
195
|
-
|
|
196
|
-
|
|
205
|
+
The connection link works only in a browser signed in to the Bridge account that owns the
|
|
206
|
+
project. If an app installation is waiting for organization approval, click **Connect
|
|
207
|
+
GitHub** again after the owner approves.
|
|
197
208
|
|
|
198
209
|
Connecting an editor over MCP is **optional** and is not a prerequisite for any of the
|
|
199
210
|
above. If you need it, the Get Started page keeps that setup in a collapsed
|
|
@@ -202,45 +213,14 @@ if you want it.
|
|
|
202
213
|
|
|
203
214
|
---
|
|
204
215
|
|
|
205
|
-
## Option C —
|
|
206
|
-
|
|
207
|
-
This is the **advanced fallback**, not the normal path — use it only if none of the
|
|
208
|
-
`connect-github` command (Option A), the
|
|
209
|
-
[delegated handoff](#option-a-2--delegated-handoff-someone-else-installs-it) (Option A-2),
|
|
210
|
-
or the one-click **Connect GitHub** button (Option B) is available to you, or if automatic
|
|
211
|
-
linking failed. The main case that still lands here is a GitHub App **already installed**
|
|
212
|
-
on the owning organization, where GitHub may send no callback for Bridge to act on. Get
|
|
213
|
-
Started links to it from the manual-fallback note under the GitHub panel.
|
|
214
|
-
|
|
215
|
-
### 1. Install the app
|
|
216
|
-
|
|
217
|
-
Go to the public install page and install it on the owning account/organization,
|
|
218
|
-
selecting the repository/repositories you want Bridge to access:
|
|
219
|
-
|
|
220
|
-
<https://github.com/apps/bridge-gpt-ai-tools-for-sfcc/installations/new>
|
|
221
|
-
|
|
222
|
-
(Same repository-selection and permissions-review screen as Option B, steps 3–5.)
|
|
223
|
-
|
|
224
|
-
### 2. Find the Installation ID
|
|
225
|
-
|
|
226
|
-
The Installation ID is the trailing number in the app's **Configure** URL:
|
|
227
|
-
|
|
228
|
-
- **Personal account:** open **Settings → Applications → Installed GitHub Apps**, click
|
|
229
|
-
**Configure** next to *Bridge GPT - AI Tools for SFCC*. The URL is
|
|
230
|
-
`https://github.com/settings/installations/<INSTALLATION_ID>`.
|
|
231
|
-
- **Organization:** open **Organization Settings → Third-party Access → GitHub Apps**,
|
|
232
|
-
click **Configure** next to the app. The URL is
|
|
233
|
-
`https://github.com/organizations/<ORG>/settings/installations/<INSTALLATION_ID>`.
|
|
234
|
-
|
|
235
|
-
For example, `https://github.com/organizations/Bridge-GPT/settings/installations/61661616`
|
|
236
|
-
has Installation ID **`61661616`**.
|
|
237
|
-
|
|
238
|
-
### 3. Enter it in Bridge
|
|
216
|
+
## Option C — retired
|
|
239
217
|
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
218
|
+
Earlier versions let you paste an Installation ID on the project's **Setup** page. That
|
|
219
|
+
path is retired: a GitHub App connection is made only through Option A, A-2, or B, where
|
|
220
|
+
you prove access to the installation on GitHub. The Setup page still shows the stored
|
|
221
|
+
values, accepts saving them unchanged, and lets you disconnect GitHub by clearing both the
|
|
222
|
+
installation ID and the repository together. It refuses a new installation ID or a
|
|
223
|
+
different repository for a GitHub App connection. Bitbucket settings are unaffected.
|
|
244
224
|
|
|
245
225
|
---
|
|
246
226
|
|
|
@@ -286,7 +266,7 @@ After linking, confirm Bridge can act on the repo:
|
|
|
286
266
|
a VCS connection.)
|
|
287
267
|
|
|
288
268
|
If a GitHub-dependent tool refuses, the installation isn't linked to that project yet —
|
|
289
|
-
re-run Option A
|
|
269
|
+
re-run Option A or B.
|
|
290
270
|
|
|
291
271
|
## Managing or removing the app
|
|
292
272
|
|
|
@@ -311,13 +291,20 @@ persists no long-lived GitHub token.
|
|
|
311
291
|
|---|---|
|
|
312
292
|
| `GIT_APP_ID` | The app's numeric App ID — `954077` for *Bridge GPT - AI Tools for SFCC*. |
|
|
313
293
|
| `GIT_PRIVATE_KEY` | **base64-encoded PEM** private key generated for the app (GitHub → app settings → *Generate a private key*). This is the one true secret. |
|
|
314
|
-
| `GITHUB_APP_INSTALL_URL` | The public install URL
|
|
294
|
+
| `GITHUB_APP_INSTALL_URL` | The public install URL, used when someone chooses to install on a new account from the connect page: `https://github.com/apps/bridge-gpt-ai-tools-for-sfcc/installations/new`. |
|
|
295
|
+
| `GITHUB_APP_CLIENT_ID` / `GITHUB_APP_CLIENT_SECRET` | The app's OAuth client, used to prove a person's access to an installation. Without both, Bridge refuses to start a GitHub connection. Removing the secret stops new connections; existing ones keep working. |
|
|
296
|
+
| `BAPI_PUBLIC_BASE_URL` | This deployment's public origin. The connect link and the OAuth callback URL are built from it. |
|
|
315
297
|
| `GITHUB_WEBHOOK_SECRET` | App-level shared secret validating signed `installation` / merge webhooks. If unset, those webhooks are disabled (the redirect-callback path still works). |
|
|
316
298
|
| `BGPT_ENCRYPTION_KEY` | Fernet key used to encrypt per-repo credentials at rest. |
|
|
317
299
|
|
|
318
300
|
The app's **Setup URL** (in GitHub app settings) must point at the deployment's
|
|
319
|
-
`GET /setup/github/callback` endpoint
|
|
320
|
-
|
|
301
|
+
`GET /setup/github/callback` endpoint, which sends the person into the access-proof flow
|
|
302
|
+
after an install. The app's **Callback URL** must be exactly
|
|
303
|
+
`<BAPI_PUBLIC_BASE_URL>/setup/github/authorized` (no trailing slash), with wildcard
|
|
304
|
+
callback matching turned off. Leave **Request user authorization (OAuth) during
|
|
305
|
+
installation** off; Bridge runs GitHub's web application flow itself. See the
|
|
306
|
+
[GitHub installation claims runbook](../../../docs/claude/runbooks/github-installation-claims.md)
|
|
307
|
+
for the rollout checklist. Webhook endpoints used by the integration include the code-review hook
|
|
321
308
|
(e.g. `https://<deployment-host>/github/code-review`); configure these on the app to match
|
|
322
309
|
your deployment host.
|
|
323
310
|
|