@bridge_gpt/mcp-server 0.2.73 → 0.2.74

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.
Files changed (90) hide show
  1. package/README.md +5 -5
  2. package/build/agent-launchers/claude-executor-adapter.js +12 -0
  3. package/build/agents.generated.js +3 -3
  4. package/build/bridge-config.js +7 -1
  5. package/build/bridge-permissions.js +3 -0
  6. package/build/command-provisioning.js +4 -3
  7. package/build/commands.generated.js +5 -5
  8. package/build/conductor/bridge-api-client.js +26 -1
  9. package/build/conductor/command-drift.js +1 -1
  10. package/build/conductor/declared-extras.js +335 -0
  11. package/build/conductor/doctor.js +2 -0
  12. package/build/conductor/driver-pass-output.js +104 -0
  13. package/build/conductor/driver-pass.js +571 -0
  14. package/build/conductor/epic-branch-ci-inspection.js +61 -16
  15. package/build/conductor/epic-implementer-cli.js +33 -0
  16. package/build/conductor/epic-server-sfcc-upload.js +1567 -0
  17. package/build/conductor/epic-server-sfcc.js +58 -80
  18. package/build/conductor/epic-server.js +57 -4
  19. package/build/conductor/gate-discovery.js +46 -6
  20. package/build/conductor/gate-settings-review.js +51 -14
  21. package/build/credential-delivery.js +280 -0
  22. package/build/credential-launch-safety.js +142 -0
  23. package/build/credential-materialization.js +91 -16
  24. package/build/credential-references-node-deps.js +29 -0
  25. package/build/credential-references.js +1394 -0
  26. package/build/credential-references.test-fixtures.js +211 -0
  27. package/build/credential-scan-conventions.js +145 -0
  28. package/build/credential-scan.js +517 -0
  29. package/build/credential-store.js +50 -0
  30. package/build/credentials-cli.js +252 -3
  31. package/build/dependency-install-declarations.js +47 -1
  32. package/build/docs.generated.js +8 -1
  33. package/build/doctor.js +41 -0
  34. package/build/drive-epic.js +297 -37
  35. package/build/epic-branch-ci-summary.js +18 -1
  36. package/build/epic-capability-statement.js +71 -3
  37. package/build/epic-ci-workflow-drift.js +52 -13
  38. package/build/epic-ci-workflow-install.js +31 -6
  39. package/build/epic-ci-workflow-v3.js +273 -0
  40. package/build/epic-ci-workflow.js +128 -7
  41. package/build/epic-implementer-bin.js +161 -70
  42. package/build/epic-launch-context.js +102 -7
  43. package/build/epic-server-record.js +30 -15
  44. package/build/executor/credential-delivery-step.js +168 -0
  45. package/build/executor/deps.js +3 -1
  46. package/build/executor/env.js +39 -1
  47. package/build/executor/epic-server-context.js +23 -7
  48. package/build/executor/guarded-fast-forward-push.js +13 -8
  49. package/build/executor/job-runner.js +159 -17
  50. package/build/executor/permissions.js +85 -3
  51. package/build/executor/prompt-spec.js +37 -3
  52. package/build/executor-launch.js +4 -2
  53. package/build/git-exclude-lock.js +187 -0
  54. package/build/index.js +398 -269
  55. package/build/install-bridge-conductor-answers.js +84 -21
  56. package/build/install-bridge-conductor-apply.js +30 -1
  57. package/build/install-bridge-conductor-assessment.js +375 -48
  58. package/build/install-bridge-conductor-compact.js +27 -2
  59. package/build/install-bridge-conductor-contracts.js +10 -1
  60. package/build/install-bridge-conductor-gate.js +124 -11
  61. package/build/install-bridge-conductor-setup.js +46 -8
  62. package/build/install-bridge-conductor.js +625 -113
  63. package/build/install-bridge.js +88 -11
  64. package/build/install-doctor.js +38 -8
  65. package/build/install-sfcc-detection.js +120 -0
  66. package/build/install-sfcc-setup.js +185 -0
  67. package/build/mcp-grant-candidates.js +108 -96
  68. package/build/mcp-invoke.js +168 -4
  69. package/build/mcp-provisioning.js +21 -4
  70. package/build/mcp-server-invocation.js +13 -0
  71. package/build/merge-workflow-install.js +9 -1
  72. package/build/pipelines.generated.js +2 -1
  73. package/build/plane/status.js +8 -2
  74. package/build/printed-remedy-commands.js +5 -0
  75. package/build/project-root.js +40 -0
  76. package/build/readme.generated.js +1 -1
  77. package/build/repository-state-paths.js +5 -2
  78. package/build/repository-toolchains.js +6 -3
  79. package/build/setup-epic.js +116 -15
  80. package/build/sfcc/credentials.js +3 -2
  81. package/build/sfcc/hostname.js +98 -2
  82. package/build/sfcc/tool-wrapper.js +6 -95
  83. package/build/start-tickets.js +193 -29
  84. package/build/test-support/executor-source-files.js +200 -0
  85. package/build/testing-config-client.js +25 -2
  86. package/build/third-party-mcp-targets.js +35 -4
  87. package/build/version.generated.js +3 -3
  88. package/build/with-credentials.js +208 -0
  89. package/build/worktree-credential-delivery.js +340 -0
  90. package/package.json +1 -1
@@ -144,6 +144,8 @@ export const MERGE_WORKFLOW_INSTALL_FAILURE_REASONS = [
144
144
  // --- BAPI-1536 -----------------------------------------------------------
145
145
  /** The CI workflow's toolchain set is outside the closed vocabulary. */
146
146
  "toolchains_invalid",
147
+ /** BAPI-1677 — an approved install command cannot be written into the CI workflow safely. */
148
+ "dependency_install_invalid",
147
149
  /** A pull request from an earlier published renderer version's managed branch is still open. */
148
150
  "historical_managed_pr_open",
149
151
  ];
@@ -214,6 +216,7 @@ const REMEDIATION = {
214
216
  worktree_failed: "A temporary git worktree could not be created; check free disk space and `git worktree list`, then re-run.",
215
217
  test_command_invalid: "Give a valid one-line test command with --test-command, then re-run setup; Bridge proves it before it is used.",
216
218
  toolchains_invalid: "Re-run setup so the repository's dependency files are inspected again; nothing was written.",
219
+ dependency_install_invalid: "Correct the install commands through setup, without a credential, token, environment reference, or expression; nothing was written.",
217
220
  historical_managed_pr_open: "An earlier Bridge setup pull request is still open for this workflow; merge or close it, then re-run. Bridge does not close or rewrite it.",
218
221
  };
219
222
  /** The remediation sentence for a reason. */
@@ -265,7 +268,8 @@ function parseIncludedResponse(stdout) {
265
268
  cut = lf + 2;
266
269
  else
267
270
  return null;
268
- return { status: Number(status[1]), body: stdout.slice(cut) };
271
+ const contentType = /^content-type:[ \t]*([^;\r\n]*)/im.exec(stdout.slice(0, cut));
272
+ return { status: Number(status[1]), contentType: contentType ? contentType[1].trim().toLowerCase() : null, body: stdout.slice(cut) };
269
273
  }
270
274
  /**
271
275
  * Read one file's RAW bytes from the remote at an immutable commit, through
@@ -290,6 +294,10 @@ async function readRemoteFile(deps, repository, sha, relPath) {
290
294
  const parsed = parseIncludedResponse(result.stdout ?? "");
291
295
  if (!parsed)
292
296
  return { kind: "unverifiable" };
297
+ // Asked for raw bytes, GitHub answers a folder with 200 and a JSON listing. A real
298
+ // file, JSON included, comes back as application/vnd.github.raw.
299
+ if (parsed.status === 200 && parsed.contentType === "application/json")
300
+ return { kind: "unverifiable" };
293
301
  if (parsed.status === 200 && result.status === 0)
294
302
  return { kind: "present", content: parsed.body };
295
303
  if (parsed.status === 404)
@@ -752,6 +752,7 @@ export const INSTRUCTIONS = {
752
752
  "create-pr.md": "# Create a pull request for the just-pushed branch\n\nThe implementation has been committed and pushed. Open a PR for the current branch against the PR base resolved in Step 3 — which is `main` only when nothing higher in that order of precedence supplies a base — with a descriptive title derived from the commit you just made.\n\n## Step 1 — Read the commit subject line\n\nRun `git log -1 --pretty=%s` to get the most recent commit subject. The implement-ticket pipeline asks the commit step to use the form `{ticket_key}: <description>`, so this line is normally already a good PR title.\n\n## Step 2 — Determine the head branch\n\nUse `git branch --show-current`. This is the head branch.\n\n## Step 2.5 — Run the file-scope guard (warn-only, before opening the PR)\n\nBefore opening or updating the PR, run the Epic Implementer file-scope guard so\nan out-of-scope diff is surfaced in the PR-creation context:\n\n```bash\nnode \"$BAPI_EPIC_IMPLEMENTER_CLI_FILE\" file-scope-guard\n```\n\nOnly the `start-tickets --conductor` launch sets `BAPI_EPIC_IMPLEMENTER_CLI_FILE`.\nA v2 Epic Implementer worker does not have it. When it is unset, run\n`epic-implementer file-scope-guard` if the packaged binary is on PATH, or\n`npx -y -p @bridge_gpt/mcp-server epic-implementer file-scope-guard`. If no form\nof the command can start, note that the guard did not run and continue to Step 3.\n\nThis guard is **warn-only and fail-open** — it **always exits 0 and never blocks\nPR creation**. Behavior:\n\n- If `BAPI_EPIC_IMPLEMENTER_DECLARED_TOUCHED_FILES_JSON` is **absent, empty, or invalid**,\n the guard is a **no-op** — it prints nothing and you **continue** to Step 3\n normally. Do not treat a missing declaration as an error.\n- If the guard prints a warning that your branch diff touched files **outside** the\n ticket's declared touched-file set, **surface that warning in the PR-creation\n context** (include it in your summary to the user / PR notes) but **do not block**\n — proceed to open the PR. The warning is advisory: it flags a possible\n sibling-scope over-reach for human review, it does not stop the workflow.\n\n## Step 2.6 — Ask the server whether this work may be published\n\nCall `get_ticket_delivery_readiness` with `ticket_key` `{ticket_key}` and `boundary`\n`publish` before you open anything. The server, not this step, decides whether the\nwork may be published.\n\n- `bound: false` — this branch has no delivery binding. Continue to Step 3 exactly as\n before.\n- Otherwise, report the `outcome` (`blocked`, `verification_failed`,\n `evidence_missing_or_stale`, `awaiting_post_pr`, or `complete`), any `blockers`, and\n `publication.action` with its `guidance`. Then continue to Step 3. The same check\n runs again, authoritatively, when `create_pull_request` is called, so do not stop\n here on your own reading of it.\n\nWhen the outcome is `evidence_missing_or_stale` because a commit landed after the\npre-PR verification was recorded, the head moved. Re-run the targeted verification on\nthe current head, record the `pre_pr_verification` phase result again with\n`record_phase_result`, and call `get_ticket_delivery_readiness` again before Step 3.\n\n## Step 2.7 — Pre-PR checks fallback (targeted scope only)\n\nVerification scope: `{verification_scope}`. In `targeted` scope, check that\n`.conductor/pre-pr-checks.json` exists and its `tested_head` equals\n`git rev-parse HEAD`. When no such record exists, run the pre-PR checks step from\nthe pre-PR verification phase now, using only the attempt's remaining 600-second\nallowance (none remains when it was spent), and write the record. If that step\nalready ran but its record could not be written, disclose that and do not start a\nfresh discovery or verification pass. Then continue to Step 3 whatever the checks\nfound. These advisory checks never block the pull request; the readiness check and\nevery other authorization rule here still apply as written. In `full` scope, skip\nthis step.\n\n## Step 3 — Resolve the base, compose the body, and call create_pull_request\n\n### Resolve the PR base\n\nResolve `base_branch` through this ordered precedence, taking the first tier that yields a usable value:\n\n1. **`BAPI_BASE_BRANCH` from the environment, when set and non-empty.** Read it explicitly with Bash — never infer the base from branch ancestry or from the repository default branch:\n\n ```bash\n echo \"${BAPI_BASE_BRANCH:-}\"\n ```\n\n The non-failing `:-` form returns an empty line when the variable is unset, so the read never errors. `start-tickets` exports this variable into **every** worker's shell for the run's resolved base — always, including the ordinary `main` case, not only an epic branch (BAPI-847). Treating it as an epic-only signal is what let the config-field tier below become the effective resolver and opened an unrelated ticket's PR against an epic branch. It is the run's own answer, so it is the highest-priority tier.\n2. **A PR base the user supplied at the commit step.** The commit step advertises PR base as an adjustable field, so an override given there carries forward into this call rather than being silently replaced by a lower tier.\n3. **The repository's configured base branch.** Call `config_field` with `operation: \"get\"` and `field_name: \"base_branch\"`. Tiers 2-4 are compatibility paths for a legacy or independently invoked run: a packaged worker always arrives with tier 1 set, so reaching this tier in a `start-tickets` run means the export did not happen.\n4. **`main`** — the normal fallback default when no tier above supplied a base.\n\nTreat a null, empty, or whitespace-only configured value, an HTTP `400`, or any lookup error as **unset** and continue quietly to the `main` fallback. Missing configuration is an ordinary outcome here, not a failure of this step.\n\n### Compose the PR body\n\nBuild `body` in this reading order:\n\n1. A concise summary line for the ticket — what this pull request changes.\n2. A plainly labeled reference to the local implementation plan, as plain text rather than a markdown hyperlink (the path is local to whoever pulls the branch): `Implementation plan available locally at <docs_dir>/plans/{ticket_key}-plan.md`. Use the plan location this recipe already knows when it has one; otherwise resolve `<docs_dir>` by calling the `ping` MCP tool and reading `docs_dir` from its first (JSON) content item.\n3. The checklist text of `.github/PULL_REQUEST_TEMPLATE.md`, read from the current worktree when that file exists, appended after the plan reference without rewriting its markdown structure. Omit this part when the file is absent.\n\nGitHub's REST API does not automatically apply the repository pull request template — that template is a web-UI affordance only. A pull request opened through this tool therefore carries an empty description unless the recipe inlines the checklist into `body` itself, which is exactly why the checklist is read from the worktree and appended here.\n\n**This is enforced, not advisory (BAPI-824).** The server rejects a missing, empty, or whitespace-only `body` with a `422` and creates no pull request. Composing the body is a hard prerequisite of this step, not a courtesy: skipping it fails the call outright rather than opening a pull request with a blank description — which is what happened twice before the check existed. The response reports the length actually sent as `detail.body_len`.\n\n### Call the tool and report the PR URL\n\nCall the `create_pull_request` MCP tool directly with:\n\n- `head_branch`: value from `git branch --show-current`\n- `base_branch`: the base resolved above\n- `title`: the commit subject from Step 1 (the derived PR title) — unless the user supplied a different PR title at the commit step, in which case use that value instead.\n- `body`: the body composed above\n- `ticket_number`: `{ticket_key}`, so the server checks this ticket's delivery binding\n- `draft`: `true` only when the user explicitly asked for a draft pull request, or when\n Step 2.6 returned `publication.action` `draft_pr`. Otherwise omit it.\n\nHonor any PR title / PR base overrides the user gave at the commit step's plan; the commit step advertises those fields as adjustable, so any override the user gave there must carry forward into this tool call rather than being silently replaced by a lower-precedence value.\n\n`create_pull_request` is the only mechanism this recipe uses to open a pull request. Do not shell out to a VCS command-line client to create it.\n\nReport the returned `pr_url` to the user, and whether the pull request was opened as a\ndraft.\n\n### What the server may decide\n\nFor a bound branch, the server enforces readiness when this call is made:\n\n- **Ordinary pull request.** Opened when the implementation and every applicable\n pre-PR verification are complete. This includes the case where the only open\n obligations are accepted checks that need an open pull request (`awaiting_post_pr`).\n Those checks are closed by the post-PR phase. Merge and ticket completion stay\n refused until they are resolved.\n- **Draft pull request.** Opened only on an explicit draft request, or automatically\n when required work is still unfinished **and** an accepted check needs an open pull\n request to make progress. A draft is not a finished delivery.\n- **Unsupported draft.** Some providers (Bitbucket) cannot open drafts. Then the server\n keeps the branch and opens no ordinary pull request in its place. Treat it as the\n hold below.\n- **Hold (blocked checkpoint).** The call returns HTTP `409` with\n `error: \"TICKET_DELIVERY_HOLD\"` and `publication.action: \"checkpoint_only\"`, plus the\n bound ticket, the readiness view, and diagnostics. Nothing was opened.\n\nBridge never promotes a draft to ready for review. Promotion is done only by a person\nor by the provider, and promoting a draft does not make the ticket complete while\nrequired work remains.\n\n### A hold is a saved checkpoint\n\nA `TICKET_DELIVERY_HOLD` means the server kept your work and opened nothing. It is\nnot a missing pull request error and it is not success. It also does not end your\njob: the whole ticket is the goal, and a checkpoint saves progress. When you receive\nit:\n\n1. Do **not** retry the call with different inputs, and do **not** open a pull request\n any other way — no VCS command-line client, no web UI, no draft retry.\n2. Make sure the held head is durable: apply `checkpoint-work.md`'s blocked-result rule\n (push the current head and prove the origin tip equals it).\n3. Read each remaining obligation in `blockers` and `post_pr_outstanding`. A blocker may\n carry an advisory `origin` and `next_action`:\n - `self_recorded` with `continue_work` is your own unfinished work. Address it\n through genuine work or a real recheck, record the result with\n `record_phase_result`, then call `create_pull_request` again.\n - `external` with `report_and_end` needs a person, a credential, a service, or an\n environment you cannot supply.\n - `external` with `wait_for_ci` is a `post_pr_outstanding` obligation. Only an open\n pull request can move it, so no work of yours clears it before the pull request\n exists.\n\n These fields are guidance. They never change what the server permits.\n4. A blocker may also carry `repeated_unchanged: true`: the previous hold saw the same\n blocker in the same state. That is checkpoint guidance, never permission to ignore\n another blocker. A flag inherited from an earlier session never justifies ending by\n itself. The current session must first make its own genuine attempt on that blocker.\n5. End the run as a **blocked checkpoint** only when every remaining blocker is\n external, or has stayed unchanged after your genuine attempt in this session. One\n repeated blocker does not excuse another blocker that is new or that you have not\n attempted. When you end, report the preserved branch (`preserved_branch`), the\n preserved head (`preserved_head_sha`), the readiness `outcome`, and each remaining\n obligation from `blockers` and `post_pr_outstanding`. Do not run the post-PR phase,\n the status transition, or CI monitoring, because there is no pull request for them\n to act on.\n\nAn older server, or one that cannot read its hold history, may omit `origin`,\n`next_action`, and `repeated_unchanged`. Then use this session's own history: when you\nworked on a blocker, re-recorded it, and the next hold still lists it unchanged, that\nis one genuine unsuccessful attempt.\n\nHonest recording is always allowed. Record what you actually ran and what you\nobserved. Never mark unrun work `executed` to clear a hold.\n\n**Exception: granted gap authority.** This applies only when Step 2.6's readiness view\nshows `gap_authority: granted` (its `gap_authority.granted` is `true`), which the server\nsets only for an unattended Epic Implementer run. In that case a verification-only\nescalation does not hold the pull request: the server carries it as a gap, so call\n`create_pull_request` normally. When `gap_authority` is absent or carries a refusal\ntoken, the hold text above applies unchanged. A `TICKET_DELIVERY_HOLD` that still comes\nback, even after granted authority was observed, is not a verification gap and is not\ndismissible: follow the steps above unchanged.\n\n### The PR URL is a hard prerequisite for everything downstream\n\nThis step completes the durable artifact that the rest of the pipeline — and, under\nthe Epic Implementer, the reconciler — binds to. It therefore has a strict success\ncondition: the call must yield a **non-empty PR URL**, either for a pull request it\nnewly opened or for an already-open pull request on this head branch that the\nresponse identifies.\n\nIf the tool is unavailable, errors, or returns neither a usable new PR URL nor an\nexisting one, **stop here and report the failure**. Do not advance to the\npost-finalization verification phase, which exists only to add work on top of an\nopen pull request. The one exception is the delivery hold above: ending as a blocked\ncheckpoint is allowed only on the conditions given there, and is reported as such, not\nas a failure of this step. A `503`\nmeans the server could not check readiness; that is a failure, and it opens nothing.\n\nThen run `git rev-parse HEAD` and record the current pushed head SHA, so the\ndownstream phases report the same durable head this pull request points at.\n\n## Return\n\nReturn the head branch, the base branch that was used, the pull request URL, whether\nit is a draft, the current pushed HEAD SHA, and the server readiness outcome when the\nbranch is bound. If the server held the branch and the conditions above for ending are\nmet, return the blocked checkpoint instead: the preserved branch and head, the readiness\noutcome, and the remaining obligations — the run ends there as a blocked checkpoint. If no usable pull request URL was obtained\nfor any other reason, return that failure instead — the pipeline stops rather than\nproceeding to verification.\n",
753
753
  "decompose-epic-candidate.md": "Decompose an Epic parent draft into ordered child tickets with idempotency and per-child duplicate checks.\n\n## Inputs\n\n- Epic parent draft: `{docs_dir}/tickets/EPIC-{slug}.md`.\n- Research pack: `{docs_dir}/idea-to-ticket/{slug}-{run_id}/research-pack.md` / `.json`.\n- Standards checklist: `{docs_dir}/idea-to-ticket/{slug}-{run_id}/standards-checklist.json`.\n- Resolved uncertainties: `{docs_dir}/idea-to-ticket/{slug}-{run_id}/resolved-uncertainties.md`.\n- Goals & NFR framing: `{docs_dir}/idea-to-ticket/{slug}-{run_id}/goals-and-nfrs.md` (its System Goals/NFRs and any provisional Recommended Implementation Order should inform the child breakdown and ordering).\n- Hard cap variable `{max_children}` (string integer; default `\"10\"` when not set by the caller). The default `\"10\"` is a **hard ceiling / upper bound, not a target** child count — it caps how many children are allowed, and is **not a goal to fill**. The normal target child count is smaller (fewer, larger M/L slices); see the sizing heuristics in step 2.\n\n## Instructions\n\n1. Read the Epic parent draft, research pack, standards checklist, and resolved uncertainties. Use only this context plus optional narrow web search; do not call deep research from this step.\n\n2. Propose ordered child tickets that, together, fully implement the Epic.\n\n **Sizing.** The canonical ladder is the posture block at the end of this file. Size each proposed child by its expected **file-touch breadth and depth plus rough lines of code (LOC) changed**, and apply the posture's target priority: **L (target) -> XL (when the work does not fit in L) -> M (third choice) -> S (only when unavoidable)**. An XL child is allowed and preferred over splitting a coherent slice to fit `L`. Only a child running past roughly 40 files / ~3000 LOC is rejected before output, and it is rejected rather than shipped with a note.\n\n Bias the decomposition toward **fewer, larger, independently implementable vertical slices** rather than many tiny one-feature children. The Bridge implementation tooling works better on large vertical slices, and a swarm of tiny S children magnifies sibling merge risk under parallel execution while spending the run's budget on coordination. Each child should be an independently implementable vertical slice; if a proposed child outgrows L, emit it as one XL child rather than halving it.\n\n Each proposed child must include:\n - `summary` — Jira title.\n - `issue_type` — typically `Task`; use `Spike` only for primarily discovery children.\n - `rationale` — short explanation of why this child exists and what it produces. Include a brief size estimate inside this existing field (do **not** add a new `size` field), e.g. `Estimated size: M (~4 files / ~150 LOC)`.\n - `draft_path` — `{docs_dir}/tickets/TICKET-{slug}-child-<N>.md` (drafts written by `jira-ticket-writer` later).\n - `depends_on` — array of the 1-based child indexes that are **hard prerequisites** (must land first), or empty. Keep this list minimal and real.\n - `recommended_after` — array of child indexes that are **soft sequencing** preferences (nicer to do after, but not blockers), or empty.\n - `order_rationale` — one line explaining why this child sits at this point in the order.\n - `owns_verifications` — array of `{epic_ac, obligation}` entries, exactly as `review-epic-coherence.md` defines the field. `epic_ac` is the id of one of the Epic parent draft's acceptance criteria. `obligation` is the concrete part of that criterion's **verification** sentence this child will carry out, in words a reviewer can hold against the verification sentence. Fill it in during this pass, the same pass that freezes the split — never as a later step. Together, the children's entries should give every epic acceptance criterion an owner. The claim is checked by the epic coherence review; it is never proof by itself.\n - `acceptance_criteria` — the planned acceptance criteria for this child: the epic criteria text it helps satisfy, plus each of its `owns_verifications` obligations word for word. This is the child evidence the coherence review reads; the writer later renders the same obligations verbatim.\n\n **Non-child owners.** When the Epic parent draft's design names an **owner-run** step — for example a step in a release checklist that a person runs outside the Epic Implementer — and that step is what proves an epic acceptance criterion, do **not** force a child to own it. Record it instead in a plan-level `non_child_owners` array beside `children`, exactly as `review-epic-coherence.md` defines the field. Each entry carries `id` (for example `OR-1`, never equal to a child index), `kind` (`owner_run`), `who` (the named person or role), `step_ref` (for example \"Release checklist step 6\"), `step_text` (the step's text copied **verbatim** from the parent draft's design), `records_result_in` (where the result is recorded), and `owns_verifications` (`{epic_ac, obligation}` entries). A child's `owns_verifications` holds only that child's own obligations; an owner-run obligation never appears in a child's `owns_verifications` or `acceptance_criteria`.\n\n Keep hard prerequisites (`depends_on`) strictly separate from soft sequencing (`recommended_after`). These fields drive the recommended implementation order posted to the epic later; they do **not** create Jira dependency links.\n\n3. Hard cap enforcement. First attempt a normal, smaller M/L-biased decomposition per the step 2 sizing heuristics. Then count proposed children: `{max_children}` is a hard ceiling that **halts on exceed**, not a target to fill. If the count exceeds `{max_children}` (parsed as an integer), halt locally with a clear \"split first\" message: ask the user to split the idea into multiple smaller Epics or to raise `--max-children` deliberately. Do not silently truncate.\n\n4. Per-child duplicate lookup. For each proposed child (in order), call `get_tickets` once with a title/keyword search built from the child's summary. If a clear duplicate exists, drop that child from the plan and record the drop reason; never halt the whole run because a child has a duplicate. Re-number `<N>` only after all drops are finalized so child indexes are contiguous.\n\n5. Per-child research is restricted to the parent research pack plus optional narrow web search. Do not call deep research per child.\n\n6. **This ordered plan is the frozen manifest.** Once written it is the sole source of child summaries, rationale, size bands, `depends_on`, `recommended_after`, order rationale, `owns_verifications`, the plan-level `non_child_owners`, confirmed real keys when created, and `draft_path`. Body rendering fans out against it (`render-ticket-manifest.md`) and must not re-decide any of those fields. Do not decompose a second time anywhere downstream: two independent decisions about one split disagree, and the disagreement surfaces as children that overlap or contradict their parent.\n\n **Amendments replace the frozen decomposition; rendering never re-splits it.** When the epic coherence review asks for an amendment (a child added or rescoped, or an obligation reassigned), the caller repeats this pass with the finding's `smallest_amendment` as extra input and writes a **new** `decomposition-plan.json` that replaces the old one. The new file has a new manifest identity, so a coherence record written for the old one can never clear it. The coherence review's `manifest` array is normalized from the ordered `children` array of the file on disk and from nothing else, so the manifest that was reviewed is exactly the manifest that renders.\n\n7. Write `{docs_dir}/idea-to-ticket/{slug}-{run_id}/decomposition-plan.json` with at minimum:\n - `parent_summary` — copy from the parent draft.\n - `max_children` — the resolved integer value used for the cap.\n - `children` — ordered array of surviving children with all fields from step 2 (including `depends_on`, `recommended_after`, `order_rationale`, `owns_verifications`, and `acceptance_criteria`). After re-numbering in step 4, fix up the `depends_on`/`recommended_after` indexes so they still point at the correct surviving children.\n - `dropped_children` — array of `{proposed_summary, reason}` for children removed by duplicate lookup.\n - `non_child_owners` — the plan-level owner-run entries from step 2, when any exist. Omit the field when there are none. The coherence input copies it unchanged.\n\n\n<!-- BEGIN BRIDGE TICKET-AUTHORING POSTURE -->\n<!-- Canonical source: docs/bridge-ticket-authoring.md.\n This block is duplicated byte-identically onto every carrier. Never edit a\n copy: edit the canonical source and re-copy it verbatim. A cross-surface\n byte-equality test fails the build if any copy drifts by a single byte. -->\n\n## Ticket-authoring posture\n\nDeep reference: `docs/bridge-ticket-authoring.md`.\n\n**Draft through the writer.** Every ticket body — an epic parent, an epic child,\nand an ordinary sibling alike — is drafted by the `jira-ticket-writer` agent\nbefore `create_ticket` is called. Do not compose a ticket description inline.\n\n**Size the work.** Size each ticket by file-touch breadth and depth plus rough\nlines of code (LOC) changed:\n\n- `S = 1-2 files / <~80 LOC`\n- `M = ~3-8 files / ~80-400 LOC`\n- `L = ~8-15 files / ~400-900 LOC`\n- `XL = >15 files / >~900 LOC`\n\nTarget size priority: **L (target) -> XL (when the work does not fit in L) -> M\n(third choice) -> S (only when unavoidable)**. This applies equally to a\nstandalone ticket and to an epic child.\n\nAim each slice at L. When one will not fit, grow it to XL rather than splitting\nit — split only when the slice is genuinely two independent pieces of work,\nnever merely to land inside a band. Bridge's grooming and implementation process\nhandles a large vertical slice well and is overkill on small ones: every extra\nticket is another worktree, another PR, another rebase, and another chance for\ntwo workers to touch the same file. Reach for M because the work genuinely is\nthat size, not to avoid an XL.\n\nBeyond roughly 40 files or ~3000 LOC, split anyway. Past that point review\nturnaround and rebase cost dominate the run's budget, and a review that wedges\nholds the gate to its full retry ceiling before anyone notices.\n\n**Group at three.** Three or more implementable tickets is an epic: propose an\nepic parent plus an ordered child manifest, and resolve this surface's own\napproval gate before anything is created. One or two tickets are ordinary\nsiblings — no epic parent, no manifest. The threshold is exactly three.\n\n**Hand off once.** An epic handoff names exactly one conductor entry point,\n`drive-epic`, which selects the runnable path itself. Never present a choice\nbetween conductors.\n\n**Departure is closed-list only.** These three exceptions, and no others, permit\ndeparting from the rules above. Invoking one requires no announcement.\n\n- **E1 External-tracker mirroring** — a recorded upstream identifier exists and\n its granularity is contractual. Bypasses sizing and the epic threshold.\n- **E2 Discovery-only spike** — no committed production-code deliverable.\n Bypasses sizing only; does not bypass drafting through the writer.\n- **E3 Authorized incident containment** — tied to an active incident record,\n not to schedule pressure. Bypasses sizing and the epic threshold.\n\nThe list is closed. Anything outside it is an escalation to the operator, not a\njudgement call. Explicitly refused as grounds for departure: a single-file\ntrivial fix (that is `S` reached through the normal path, not an exception),\ngeneric time pressure, \"already well specified\", \"faster without the writer\",\ndeveloper discretion, minor refactor, unattended mode, context limits, and \"hard\nto decompose\" (XL is the normal overflow, so that is the ordinary path and not a\ndeparture). Writer unavailability escalates; it never silently authorizes inline\ndrafting.\n\n<!-- END BRIDGE TICKET-AUTHORING POSTURE -->\n\n## Return\n\nConfirm `decomposition-plan.json` was written, report the final child count and the number of children dropped for duplicate reasons.\n",
754
754
  "decompose-epic.md": "Decompose the epic into manageable sub-tasks and get user approval.\n\n## Epic Description\n\n{epic_description}\n\n## Instructions\n\n1. Read the following artifacts to establish full context. If a file does not exist or is empty, proceed without it:\n - `{docs_dir}/epic-plans/{epic_slug}/research-findings.md`\n - `{docs_dir}/epic-plans/{epic_slug}/codebase-exploration.md`\n\n2. Reason about the epic and produce a decomposition. Consider:\n - Logical groupings of work that can be implemented and tested independently\n - Dependencies between sub-tasks (what must be built first)\n - A reasonable scope for each sub-task (each should be achievable in a single implementation session)\n\n **Size every sub-task with the canonical ladder** in the posture block at the end of this file, by file-touch breadth and depth plus rough LOC changed. Apply its target priority: **L (target) -> XL (when the work does not fit in L) -> M (third choice) -> S (only when unavoidable)**. **A sub-task may be XL.** When one will not fit in `L`, grow it to `XL` rather than splitting it; split only when it is genuinely two independent pieces of work, or when it runs past roughly 40 files / ~3000 LOC. Bias toward fewer, larger, independently implementable vertical slices: a swarm of tiny children magnifies sibling merge risk under parallel Epic Implementer execution and spends the run's budget on coordination.\n\n **Decompose once.** This pass freezes the split. Emit the same ordered-manifest shape the `idea-to-ticket` path uses (`decompose-epic-candidate.md`), so that per sub-task you record: title, scope boundary, **size band**, `depends_on` (hard prerequisites that must land first), `recommended_after` (soft sequencing preferences that are not blockers), a one-line order rationale, `owns_verifications`, and planned acceptance criteria. `owns_verifications` is a list of `{epic_ac, obligation}` entries, exactly as `review-epic-coherence.md` defines the field: `epic_ac` is the id of one of the epic's acceptance criteria, and `obligation` is the concrete part of that criterion's **verification** sentence this sub-task will carry out. Fill it in during this pass, the same pass that freezes the split — never as a later step. The planned acceptance criteria are the epic criteria text the sub-task helps satisfy plus each of its obligations word for word. Keep hard prerequisites strictly separate from soft sequencing — the recommended implementation order is derived from them, and conflating the two serializes work that could have run in parallel. No later stage re-derives a sub-task's scope while rendering its body.\n\n **Three or more sub-tasks is an epic; one or two would ordinarily be siblings.** The threshold is exactly three. This surface is the one place that threshold does *not* decide the shape: `/plan-epic` runs against an epic ticket that already exists, so the grouping decision was made upstream and is not yours to reverse here. If the epic genuinely decomposes into only one or two sub-tasks, **say so plainly to the user** — that is a signal the epic was over-scoped and may be better as ordinary sibling tickets — and then continue with the steps below as written. Do not manufacture filler sub-tasks to reach three, and do not skip the artifacts step 3 requires; the `plan-epic` step sequence is fixed and every later step reads them. The epic coherence check in step 3 also still runs for one or two sub-tasks.\n\n3. Write the decomposition to `{docs_dir}/epic-plans/{epic_slug}/epic-plan.md` with this format:\n\n```markdown\n# Epic Decomposition\n\n## Sub-tasks\n\n### 1. {Sub-task title}\n- **Scope**: {What this sub-task covers}\n- **Size**: {S | M | L | XL}\n- **Key files/areas**: {Files and code areas involved}\n- **Dependencies**: {Other sub-task numbers this depends on, or \"None\"}\n- **Recommended after**: {Soft sequencing preferences that are not blockers, or \"None\"}\n- **Order rationale**: {One line on why this sub-task sits at this point in the order}\n- **Owns verifications**: {One entry per owned epic AC: the AC id, then the obligation, word for word as in the JSON authoring manifest}\n\n### 2. {Sub-task title}\n...\n\n## Epic coherence\n\nSee `epic-coherence.json` (authoritative) and `epic-coherence.md` (human summary) in this directory.\n```\n\n Keep the `## Epic coherence` section to that pointer. The coverage map lives in the record; do not keep a second, editable copy of it here.\n\n Also write the **JSON authoring manifest** to `{docs_dir}/epic-plans/{epic_slug}/epic-manifest.json`, from the same structured decomposition data (never by re-parsing the markdown). It is the frozen manifest the epic coherence review checks, and it uses the input field names `review-epic-coherence.md` defines:\n\n```json\n{\n \"manifest\": [\n {\n \"id\": \"1\",\n \"title\": \"Sub-task title\",\n \"scope\": \"What this sub-task covers\",\n \"size_band\": \"L\",\n \"depends_on\": [],\n \"recommended_after\": [],\n \"touched_files\": [\"api/routes/example.py\"],\n \"read_files\": [\"api/library/example_reader.py\"],\n \"owns_verifications\": [\n { \"epic_ac\": \"AC-1\", \"obligation\": \"The concrete part of AC-1's verification this sub-task carries out\" }\n ]\n }\n ],\n \"child_evidence\": [\n { \"id\": \"1\", \"acceptance_criteria\": [\"Each planned acceptance criterion of the sub-task, verbatim\"] }\n ],\n \"non_child_owners\": [\n {\n \"id\": \"OR-1\",\n \"kind\": \"owner_run\",\n \"who\": \"Release owner\",\n \"step_ref\": \"Release checklist step 6\",\n \"step_text\": \"The step's text, copied verbatim from the epic's design\",\n \"records_result_in\": \"a comment on the epic\",\n \"owns_verifications\": [\n { \"epic_ac\": \"AC-2\", \"obligation\": \"The concrete part of AC-2's verification the owner-run step carries out\" }\n ]\n }\n ]\n}\n```\n\n - `manifest` is the complete, ordered sub-task list. `id` is the 1-based position as a string. `depends_on` and `recommended_after` hold those ids.\n - `child_evidence` has one entry per sub-task, keyed by the same `id`. Its `acceptance_criteria` are the sub-task's planned acceptance criteria: the ratified epic criteria text it satisfies, plus every `owns_verifications` obligation word for word.\n - `touched_files` lists the files a sub-task edits or creates. `read_files` is optional and lists files it only reads, when known; reads never count as an edit overlap or toward the high-risk path check.\n - `non_child_owners` is optional. When the ratified design assigns an epic acceptance criterion's verification to a concrete **owner-run** step (for example a release-checklist step a person runs outside the Epic Implementer), declare it here, with every field `review-epic-coherence.md` defines, instead of forcing a sub-task to own it. Copy `step_text` verbatim from the design. An owner-run obligation never appears in a sub-task's `owns_verifications` or planned acceptance criteria.\n - `owns_verifications` and the planned acceptance criteria are **authoring-only** fields. They live in `epic-manifest.json` and in the coherence input. **Never** add them, or any other field not listed in the sidecar rules below, to `epic-plan.dag.json`: that file is server-consumed and its schema does not change.\n\n In addition, you MUST also write a structured JSON sidecar at\n `{docs_dir}/epic-plans/{epic_slug}/epic-plan.dag.json`. This is unconditional —\n it applies to a one- or two-sub-task decomposition exactly as it does to a larger\n one. `plan-epic.json`'s step sequence is fixed (the orchestrator supports no\n conditional steps), so every later step reads these artifacts regardless of the\n sub-task count, and omitting them strands the run rather than simplifying it.\n This file is the machine-readable intermediate that the later, separate launch\n workflow stores and approves in the backend — `/plan-epic` itself does neither.\n It must be written from your structured decomposition data, NEVER by\n re-parsing the markdown.\n\n The sidecar format is:\n\n```json\n{\n \"plan_version\": 1,\n \"nodes\": [\n {\n \"ticket_key\": \"TBD-1\",\n \"status\": \"planned\",\n \"depends_on\": [],\n \"touched_files\": [\"api/routes/example.py\", \"src/python/llms/ai_client.py\"],\n \"automations\": [\n { \"kind\": \"start-tickets\" }\n ]\n }\n ],\n \"edges\": [\n { \"from\": \"TBD-1\", \"to\": \"TBD-2\" }\n ]\n}\n```\n\n Rules for the sidecar:\n - `plan_version` must be 1 for a new plan (an integer, never a float).\n - Each node `ticket_key` is the placeholder `TBD-1`, `TBD-2`, and so on, in\n node order. Keep every key as `TBD-N` until the child tickets exist. Never\n guess a Jira key for a ticket that has not been created.\n - `ticket_key` values must be unique and non-empty after trimming.\n - `depends_on` lists the `ticket_key` values this node depends on (mirrors\n the markdown Dependencies field). `depends_on` is the **canonical**\n dependency declaration.\n - `status` must be `\"planned\"` for newly-created sub-tasks.\n - `touched_files` is **required on every node** — the sorted, deduplicated,\n repository-relative POSIX paths this sub-task is predicted to change.\n Populate it from your current code research and the sub-task's ownership,\n the same analysis that tells you which sub-tasks collide.\n - Include **anticipated tests, fixtures, golden files, guard allowlists,\n and policy files** — not only the production modules. Every observed\n overlap failure was this class: two children shared a production module\n *and its test*, or a pair of golden files, and because nobody predicted\n the shared file no ordering edge was synthesized.\n - No leading `./`, no absolute paths, no `..` traversal segments, no\n temporary-worktree paths, and no prose. Declare **concrete files**: the\n backend intersects these paths as exact strings, so a directory or glob\n entry matches nothing and protects nothing.\n - `[]` is permitted **only** when the decomposition explicitly establishes\n that the sub-task changes no repository files. Unknown file ownership is\n **blocking** — resolve it or flag it; never represent it as an empty\n array, which silently disables file-overlap protection.\n - `automations` lists automation kinds to run on the ticket — valid values\n are `\"start-tickets\"` and `\"review-tickets\"`. Use an empty array if none.\n - `edges` is an explicit list of directed dependency edges (from → to, where\n `from` is the predecessor). It may be empty if all dependencies are captured\n in `depends_on`, but any edge you do write must encode the same graph as\n `depends_on` — a contradictory graph blocks readiness.\n - Do **not** set `base_lineage` on any node. It affects the plan hash but has\n no consumer in the Epic Implementer, so setting it invalidates the approved hash\n for no behavioral gain.\n - The DAG must be acyclic (no circular dependencies).\n - The deterministic Jira-dependency-link DAG builder is the documented\n fallback/recovery path if this sidecar is lost or corrupted (not built here).\n\n **Placeholders are finalized later, not here.** `TBD-N` remains the correct\n node identity for the window before the epic's Jira tickets exist. The\n standalone `emit-conductor-bundle.md` task replaces every placeholder with the\n real ticket key and finalizes `touched_files` after the tickets are created and\n before the plan is stored or approved. Write your best `touched_files`\n prediction here anyway — that task reconciles it against the whole epic.\n\n `/plan-epic` ends before storage: it never stores or approves this sidecar.\n Finalization replaces every `TBD-N` placeholder before the plan is stored or\n approved, and both `setup-epic` and the server refuse a plan whose node keys\n are still `TBD-N`.\n\n **Run the epic coherence check.** After `epic-plan.md`, `epic-manifest.json`, and `epic-plan.dag.json` are all written, and before anything is presented for approval in step 5, check the sub-tasks as a set against the epic's acceptance criteria. **This check runs on every `/plan-epic` decomposition, including one or two sub-tasks.** Elsewhere, a one- or two-ticket outcome is an ordinary sibling pair and skips the check. This surface is different: the epic already exists, so its children must still cover it however few there are.\n\n 1. **Source the epic acceptance criteria.** When `{epic_key}` is non-empty, read that epic with `get_ticket` and take its acceptance criteria and their verification sentences. When it is empty (this run started from free-form text), take them from the Epic Description above and from `{docs_dir}/epic-plans/{epic_slug}/goals-and-nfrs.md`. Give each an id (`AC-1`, `AC-2`, and so on) in the order found. If no acceptance criteria can be found, do not invent them: the check cannot run, the verdict is `not_checked`, and step 5 offers the attended retry-or-reasoned-bypass decision.\n 2. **Write the normalized input** to `{docs_dir}/epic-plans/{epic_slug}/epic-coherence-input.json`, in the input document shape `review-epic-coherence.md` defines. `epic` carries `key` (the epic key when there is one) or `slug` (the epic slug otherwise), plus `title` and `acceptance_criteria`. `design_text` holds the epic description plus the goals and design text from `goals-and-nfrs.md` and `codebase-exploration.md`. `manifest` and `child_evidence` are copied **unchanged** from `epic-manifest.json`, so `child_evidence` carries each sub-task's planned acceptance criteria and its verbatim `owns_verifications` obligations. When `epic-manifest.json` has `non_child_owners`, copy that array **unchanged** into the input too; include the design text each `step_text` was copied from in `design_text`.\n 3. **Bind all three identities.** Compute `manifest_sha256` over the `manifest` array, `child_evidence_sha256` over the `child_evidence` array, and `non_child_owners_sha256` over the `non_child_owners` array (an absent array hashes as an empty array), with the canonical JSON encoding `review-epic-coherence.md` specifies. The record must carry all three.\n 4. **Run the shared procedure.** Follow `review-epic-coherence.md` in `drafting` mode. Its input document path is `{docs_dir}/epic-plans/{epic_slug}/epic-coherence-input.json`, its output directory is `{docs_dir}/epic-plans/{epic_slug}/`, and the run is attended. It writes `epic-coherence.json` and `epic-coherence.md` beside the plan. When it asks for an amendment, amend the decomposition (add or rescope a sub-task, or reassign an obligation), rewrite `epic-plan.md`, `epic-manifest.json`, `epic-plan.dag.json`, and the input, and let the procedure re-check. Its bound is the procedure's risk-scaled round limit: maximum ordinary rounds (two low-risk and three high-risk), ending earlier after a round with zero foundation blockers. An amendment after the last allowed round gets one confirmation pass, never an older round's clearance. Read the procedure at `.bridge/procedures/review-epic-coherence-procedure.md` in this project, where the Bridge installer scaffolds it. Only if that file does not exist, read `docs/install/review-epic-coherence-procedure.md`; only if that file does not exist either, read `mcp_server/instructions/review-epic-coherence.md` in this checkout. A file that exists but cannot be read is a failure: never fall back to a later location. If it is unreadable or none of the three exists, stop: the shared procedure is not usable, so re-run the Bridge installer or upgrade the Bridge package. Never improvise a substitute review.\n\n4. **Soft limit check**: If the decomposition results in more than 8 sub-tasks, you must verbally warn the user: \"This decomposition has N sub-tasks, which exceeds the recommended limit of 8. Consider splitting this feature into multiple epics.\" Then proceed with the approval flow.\n\n5. Present the decomposition to the user and ask for their feedback. Explain the reasoning behind the breakdown and the dependency ordering.\n\n Lead with the gap-check result, in this order, before asking for approval. Use the plain words in \"What the user sees\" in `review-epic-coherence.md`; the record keeps its technical values.\n - **Result** — the verdict from `epic-coherence.json`, shown as `No gaps found`, `Accepted with known gaps`, `Needs your decision`, or `Couldn't check`. When a passing record carries ticket-local findings, show `No gaps found (N notes added to tickets)`. Never describe `Couldn't check` as a pass.\n - **Less independent**, shown prominently, when the record says `independent: false`: \"this check ran in my own session, not by a separate reviewer, so it's less independent.\" Offer a fresh-context rerun of the check.\n - **Remaining blocking findings**, each with its id and smallest amendment — or, when the review could not run, the reviewer failure. A carried ticket-local finding is shown as a note added to ticket N.\n - **Who covers each requirement** — one plain bullet per epic AC: the AC id, the owning sub-task (or, for an owner-run owner, the words \"owner-run\" with the person or role and the step reference), and the obligation that proves it.\n - **Recorded reasons** — every accepted finding and every bypass, with its typed reason.\n\n Each remaining **foundation** blocking finding must be either **fixed** (amend the decomposition, which rewrites the artifacts and re-runs the check) or **accepted** with a typed reason. Ticket-local blockers are carried to their child ticket and do not require acceptance at this epic approval gate. Record an accepted foundation finding in `epic-coherence.json` as an override of kind `accept` with its `finding_id`, `reason`, `accepted_by`, and `round`. When every remaining foundation blocking finding is accepted, the verdict becomes `accepted_with_gaps`. When the verdict is `not_checked`, offer a retry, or a bypass with a typed reason recorded as an override of kind `bypass`; the verdict stays `not_checked`.\n\n6. You MUST stop and wait for the user to respond. Do NOT assume approval. Do NOT proceed to the next step.\n\n7. If the user provides feedback or rejects the decomposition:\n - Incorporate their feedback\n - Rewrite `{docs_dir}/epic-plans/{epic_slug}/epic-plan.md` with the revised version, and rewrite `epic-manifest.json`, `epic-plan.dag.json`, and `epic-coherence-input.json` from the same revised data\n - Re-run the epic coherence check from step 3 on the new manifest. A changed manifest, changed child evidence, or changed non-child owners has a new digest, so never reuse the old record for it\n - Present the revised decomposition and the new coherence result, and ask for approval again\n - Repeat until the user explicitly approves\n\n8. Only after explicit user approval, confirm: \"Decomposition approved. Proceeding to sub-task exploration.\"\n\n That confirmation is allowed only when `epic-coherence.json` matches **all three** current digests, its top-level digests equal its last round's digests (the only exception is the attended `amended_after_final_round: true` bypass the procedure defines, whose verdict is `not_checked`), no required council is left unresolved without a typed acceptance (a `declined_by_operator` council is resolved and needs no override), and its verdict is one of:\n - `pass`;\n - `accepted_with_gaps`, with every remaining foundation blocking finding accepted and recorded with its finding id and a non-empty reason;\n - `not_checked`, with a recorded `bypass` override carrying a non-empty reason typed by the user.\n\n A `blocked` verdict, or a `not_checked` verdict without a recorded bypass, **cannot** be confirmed as approved, even if the user says yes. Say which finding or failure still blocks, and return to step 5. There is no unattended bypass on this surface.\n\n\n<!-- BEGIN BRIDGE TICKET-AUTHORING POSTURE -->\n<!-- Canonical source: docs/bridge-ticket-authoring.md.\n This block is duplicated byte-identically onto every carrier. Never edit a\n copy: edit the canonical source and re-copy it verbatim. A cross-surface\n byte-equality test fails the build if any copy drifts by a single byte. -->\n\n## Ticket-authoring posture\n\nDeep reference: `docs/bridge-ticket-authoring.md`.\n\n**Draft through the writer.** Every ticket body — an epic parent, an epic child,\nand an ordinary sibling alike — is drafted by the `jira-ticket-writer` agent\nbefore `create_ticket` is called. Do not compose a ticket description inline.\n\n**Size the work.** Size each ticket by file-touch breadth and depth plus rough\nlines of code (LOC) changed:\n\n- `S = 1-2 files / <~80 LOC`\n- `M = ~3-8 files / ~80-400 LOC`\n- `L = ~8-15 files / ~400-900 LOC`\n- `XL = >15 files / >~900 LOC`\n\nTarget size priority: **L (target) -> XL (when the work does not fit in L) -> M\n(third choice) -> S (only when unavoidable)**. This applies equally to a\nstandalone ticket and to an epic child.\n\nAim each slice at L. When one will not fit, grow it to XL rather than splitting\nit — split only when the slice is genuinely two independent pieces of work,\nnever merely to land inside a band. Bridge's grooming and implementation process\nhandles a large vertical slice well and is overkill on small ones: every extra\nticket is another worktree, another PR, another rebase, and another chance for\ntwo workers to touch the same file. Reach for M because the work genuinely is\nthat size, not to avoid an XL.\n\nBeyond roughly 40 files or ~3000 LOC, split anyway. Past that point review\nturnaround and rebase cost dominate the run's budget, and a review that wedges\nholds the gate to its full retry ceiling before anyone notices.\n\n**Group at three.** Three or more implementable tickets is an epic: propose an\nepic parent plus an ordered child manifest, and resolve this surface's own\napproval gate before anything is created. One or two tickets are ordinary\nsiblings — no epic parent, no manifest. The threshold is exactly three.\n\n**Hand off once.** An epic handoff names exactly one conductor entry point,\n`drive-epic`, which selects the runnable path itself. Never present a choice\nbetween conductors.\n\n**Departure is closed-list only.** These three exceptions, and no others, permit\ndeparting from the rules above. Invoking one requires no announcement.\n\n- **E1 External-tracker mirroring** — a recorded upstream identifier exists and\n its granularity is contractual. Bypasses sizing and the epic threshold.\n- **E2 Discovery-only spike** — no committed production-code deliverable.\n Bypasses sizing only; does not bypass drafting through the writer.\n- **E3 Authorized incident containment** — tied to an active incident record,\n not to schedule pressure. Bypasses sizing and the epic threshold.\n\nThe list is closed. Anything outside it is an escalation to the operator, not a\njudgement call. Explicitly refused as grounds for departure: a single-file\ntrivial fix (that is `S` reached through the normal path, not an exception),\ngeneric time pressure, \"already well specified\", \"faster without the writer\",\ndeveloper discretion, minor refactor, unattended mode, context limits, and \"hard\nto decompose\" (XL is the normal overflow, so that is the ordinary path and not a\ndeparture). Writer unavailability escalates; it never silently authorizes inline\ndrafting.\n\n<!-- END BRIDGE TICKET-AUTHORING POSTURE -->\n\n## Return\n\nConfirm \"Decomposition approved.\" and report the final sub-task count plus the path to `{docs_dir}/epic-plans/{epic_slug}/epic-plan.md`. Flag if the count exceeded the recommended limit of 8.\n\nAlso report the gap-check result in the plain words from `review-epic-coherence.md` (`No gaps found`, `Accepted with known gaps`, `Needs your decision`, or `Couldn't check`), whether the check was independent (if not, say it is less independent), and the record path `{docs_dir}/epic-plans/{epic_slug}/epic-coherence.json`.\n",
755
+ "define-tickets-epic-handoff.md": "# `/define-tickets` epic hand-off procedure\n\nThis procedure carries the epic-only parts of `/define-tickets` Stage 9. The command\nreads it once per run, after it has frozen a split of three or more slices, and then\nfollows one section of it at each epic-only pointer in Stage 9. Do not run every\nsection right after loading it. Each section uses the working state the command\nalready holds: the frozen manifest, the exploration document, the drafting plan, and\nthe run mode. Sections that mention \"the command\" mean `/define-tickets`. Nothing in\nthis file changes the command-owned steps: the split rules, the `--max-children`\ncap, the writer fan-out, the upload gate, Handling changes, creation, tracking, the\nmaterials pass, and the Final Report all stay in the command.\n\n## Step 2 — Epic gap check (frozen manifest)\n\n**For an epic, check the frozen manifest before any writer runs.** This runs only for an epic, after the split is frozen and before drafting:\n\n1. Write the frozen manifest as JSON to `{docs_dir}/epic-plans/{slug}/epic-manifest.json`, the same directory step 4 of this procedure uses for `epic-plan.dag.json`. It holds the arrays in the input field names `review-epic-coherence.md` defines. `manifest` is the complete, ordered child list (`id` as the 1-based position, `title`, `scope`, `size_band`, `depends_on`, `recommended_after`, `touched_files` from the design's file list — the files the child edits or creates — `read_files` for files it only reads, when known, and `owns_verifications`). `child_evidence` has one entry per child with its planned acceptance criteria: the ratified criteria text the child satisfies plus each of its `owns_verifications` obligations word for word. `non_child_owners`, when the epic has any, sits beside `manifest` and `child_evidence`.\n2. Write the review input to `{docs_dir}/epic-plans/{slug}/epic-coherence-input.json`. `epic` carries the `slug`, the epic title, and the ratified acceptance criteria from the exploration doc, each with its `id`, its text, and its verification sentence. `design_text` is the doc's `## Goals & NFRs` section, verbatim, followed by its `## Proposed Design`; the reviewer checks the split against the NFRs as well as the criteria. `manifest`, `child_evidence`, and `non_child_owners` (when present) are copied unchanged from `epic-manifest.json`.\n3. **Apply the recorded gap-check policy.** An attended run asks no gap-check question: Stage 6 already recorded `drafting_plan.gap_check_policy`, and this step executes it before any writer runs. It also asks no council question: the Stage 6 plan already decided that, and no further split-review question is needed.\n - **Epic, `run_if_epic`.** Run the procedure as described next, in `drafting` mode, attended.\n - **Epic, `skip`.** Run no reviewer. Write a skip record to `{docs_dir}/epic-plans/{slug}/epic-coherence.json`: `schema_version` `3`, verdict `not_checked`, `skipped_by_operator: true`, `rounds: []`, the three current digests computed from `epic-manifest.json`, an empty coverage map, and one override of kind `bypass` with reason `Operator chose to skip the gap check` and `accepted_by: \"operator\"`. Then go on to drafting.\n - **Siblings.** Run no epic reviewer, write no coherence record, show no extra outline line, and ask no extra prompt. The conditional policy stays recorded in the plan.\n\n Follow `review-epic-coherence.md` in `drafting` mode, attended, with that input path and `{docs_dir}/epic-plans/{slug}/` as the output directory. Pass `council_preapproval` with `value` set to the legacy `council_choice` recorded from the drafting plan (`approved` for `before` and `after`, `declined` for `none`) and `source` set to the exact string `define-tickets council answer`, so the procedure asks no council question of its own. Also pass `auto_amend: true`: the procedure fixes gaps by amending the manifest within its existing round and confirmation bounds, with no question, and any foundation gap still left after the bound goes to the upload gate with an agent-drafted reason instead of a question. It computes `manifest_sha256`, `child_evidence_sha256`, and `non_child_owners_sha256`, applies its risk-scaled round limit, and writes `epic-coherence.json` and `epic-coherence.md` there. Read the coherence procedure through the command-owned lookup in `/define-tickets` Stage 9 (the paragraph headed \"Coherence procedure lookup\"), which keeps the installed, legacy `docs/install/`, and checkout locations in order, the unreadable-file failure rule, and the repair guidance. Never improvise a substitute review.\n\n**Only under --auto:** the coherence run is unattended. Execute the recommended plan recorded in Stage 6, which always includes the gap check for an epic. Pass the literal `auto_approve_external = \"true\"` and no `council_preapproval`, never write a skip record, and use the procedure's bounded amend-and-recheck behavior instead of the operator-directed fix loop below. It clears only with no foundation blockers and every ticket-local blocker carried; it halts as `epic_coherence` with verdict `blocked` when foundation blockers remain after the bound or non-convergence. Clearance is independent: `independent: false` fails even on `pass`, `not_checked` fails, and an attended-only bypass or accept cannot clear an auto run. Halt before any writer or `create_ticket` on `blocked`, `not_checked`, `independent: false`, an unresolved required council, or any other non-clearing record. Name the specific cause in prose and halt as `epic_coherence` with the record path and a `coherence_verdict` of only `blocked` or `not_checked`. If the procedure is unavailable or cannot be invoked, halt as `stage_failed` naming Stage 9; never fabricate a coherence result. Siblings keep their no-coherence path. For an epic, skip the pending-acceptance list, the upload gate, and its reply parsing in the command's Stage 9 step 3: drafting and creation proceed only once the record clears, with no prompt. For siblings, skip the upload gate and its reply parsing in the command's Stage 9 step 3: creation proceeds with no prompt once every auto gate and draft-completeness requirement has cleared.\n\n**Resolve the result at the gate.** Every remaining **foundation** blocking finding (a gap in how the work is split) must be fixed or accepted before creation. Ticket-local blockers are carried into their child ticket, shown as \"a note added to ticket N\", and do not require acceptance at this epic gate. There is no separate fix-or-accept question: the upload gate below is the one surface that resolves foundation findings (the upload gate in the command's Stage 9 step 3). Use the plain words in \"What the user sees\" in `review-epic-coherence.md` for everything the user reads; the record keeps its technical values.\n- **Fixed automatically.** Under `auto_amend: true`, the procedure amends the manifest between rounds within its existing bounds, with no question. Each amendment re-freezes it: rewrite `epic-manifest.json` and the input before the next round.\n- **Change how the tickets are split** (fix) — only when the user explicitly asks for it by replying \"change something\" at the command's upload gate. Amend the manifest (add or rescope a child, or reassign an obligation). That re-freezes it: rewrite `epic-manifest.json` and the input, re-run the check within the existing bounds, redraft the affected entries as described under Handling changes in the command's Stage 9 step 3, and return to the updated upload gate. The budget is one operator-directed fix plus one additional whole-manifest confirmation pass, counted across every coherence-check re-run in the same attended define-tickets run. A fix made after the procedure's last allowed round gets its one confirmation pass, so the record's last round still bears the final digests. Once the budget is spent, only accept or `blocked` remain.\n- **Create anyway, and record the gap on the epic** (accept) — the default for every foundation gap still left after the bound. The reason is agent-drafted, non-empty, and shown on the upload gate. Record it in `epic-coherence.json` as an override of kind `accept` with the `finding_id`, the `reason`, `accepted_by`, and the `round`. When every remaining foundation blocking finding is accepted, the verdict is `accepted_with_gaps`.\n- A finding that is declined, or left without a reason, keeps the verdict `blocked` and keeps creation blocked.\n- **Couldn't check** (reviewer unavailable) — say \"Couldn't check\" and offer to try again or to create without it. Creating without it needs a reason the operator types, recorded as an override of kind `bypass`. The internal verdict stays `not_checked`. Never show or treat it as a pass. This exception stays outside the ordinary upload gate. It fails closed: retries are operator-initiated, and neither creation preflight clears it without the recorded typed bypass.\n\n**Enforce ticket scope after amendments (attended only).** Re-check the implementation-ticket count against `ticket_scope` after every coherence amendment or operator-requested split change, before any writer or ticket creation. If the count differs, use the Stage 8 scope-change agreement and implications checkpoint before proceeding; rebuild and revalidate the frozen split and any affected coherence record, and regenerate any affected drafts. Count only children or ordinary tickets; show an epic parent as additional. The upload approval never substitutes for agreement to a changed count. This does not add an attended scope gate under `--auto`.\n\n## Step 3 — Record check and full clearance\n\n**Check the record before any writer.** For an epic, the coherence record is validated before drafting, but attended pre-writer validation is narrower than full clearance. Attended pre-writer validation checks frozen-entry identity, sizing, readable recognized records, all three current digests, last-round identity or the existing attended exceptions, finding scopes, child references, carry completeness, confirmation budgets, and required-council resolution. The single attended exception: the only uncleared items may be foundation gaps that are each listed individually under `Known gaps that will be recorded on the epic`. Keep each proposed acceptance in working state, bound to its finding id, its exact non-empty agent-drafted reason, its round, and the manifest and evidence identities. Do not persist it as an operator acceptance before approval. Under `--auto`, full clearance applies before any writer, exactly as below.\n\n**Full clearance, before the first `create_ticket` call (and before any writer under `--auto`).** Refuse to create an epic unless all of these hold, with actual persisted acceptances for every remaining foundation blocker:\n- `epic-coherence.json` exists in `{docs_dir}/epic-plans/{slug}/` and is readable;\n- its `schema_version` is `1`, `2`, or `3`; legacy blocking findings are foundation findings. For version `3`, validate scope, child references, carry completeness, confirmation budget, and the foundation-only verdict before any writer call;\n- its `manifest_sha256` matches the frozen manifest shown at the gate, its `child_evidence_sha256` matches the current child evidence, **and** its `non_child_owners_sha256` matches the current non-child owners, all computed from `epic-manifest.json` with the encoding `review-epic-coherence.md` specifies (an absent array hashes as an empty array; a version `1` record without the third digest matches only when there are no non-child owners);\n- its `rounds` array is non-empty and its top-level digests equal its last round's digests. The only exception is an attended record with `amended_after_final_round: true`, a typed `bypass` override, and verdict `not_checked`, whose top-level digests still match the current input. A second exception is the attended skip record: `skipped_by_operator: true`, an empty `rounds` array, verdict `not_checked`, a `bypass` override with a non-empty reason, and top-level digests that match the current input;\n- no required council is left `still_running`, `failed`, or `timed_out` unless an attended `accept` override with a typed reason names its `council_id`;\n- its verdict is `pass`, including a version 3 record with carried ticket-local blockers, or `accepted_with_gaps` with every remaining foundation blocking finding accepted with a non-empty reason, or `not_checked` with a recorded override of kind `bypass` carrying a non-empty reason.\n\nFor a skip record, the parent writer's coverage map is derived from manifest ownership, and the parent's `## Epic coverage map` is built from the manifest's `owns_verifications` and `non_child_owners`, and says plainly that the gap check was skipped by the operator.\n\nA council outcome of `declined_by_operator` is resolved and needs no `accept` override, whether it was declined at the pre-round-1 ask or through legacy `council_preapproval: declined`. A legacy `accept` override targeting `council: \"declined_by_operator\"` remains valid but is ignored for clearance.\n\nThe displayed reasons and override targets must stay unchanged between approval and creation. If either changed, show the gate again rather than treating the earlier reply as authorization. Unknown record fields are ignored and never authorize anything. A missing or unreadable record, an unrecognized schema version, a digest mismatch, top-level digests that differ from the last round's, an unresolved required council, `blocked`, or an un-bypassed `not_checked` stops here: report which one, and create nothing. This is the same rule as the epic coherence preflight in `render-ticket-manifest.md`, which holds its canonical wording; this command adds only the attended pre-writer timing exception above, and the canonical instruction is unchanged. This command does not route through that instruction, so the rule is stated here too.\n\n## Step 3 — Epic outline items 1–3\n\nThese three lines come first in an epic's plan outline. The command's outline then\ncontinues with its own items 4 through 9.\n\n1. **Gap check** (epic only, first) — the outcome in plain words: `No gaps found` (or `No gaps found (N notes added to tickets)` when ticket-local findings are carried), `Accepted with known gaps`, `Needs your decision`, `Skipped, your choice`, or `Couldn't check`. When the initial council was declined, add the information line `Council: skipped, your choice`. That line is not a warning, not an unresolved item, and not something to accept.\n2. **Independence and notes** (epic only) — when the record says `independent: false`, say: this check ran in my own session, not by a separate reviewer, so it's less independent. List each carried ticket-local finding as \"a note added to ticket N\" with a short summary. An attended operator may discuss or fix a carried finding.\n3. **Who covers each requirement** (epic only) — one plain bullet per epic AC: the AC id, the owning child (or, for an owner-run owner, \"owner-run\" with the person or role and the step reference), then the obligation that proves it.\n\n## Step 3 — Known gaps (epic only)\n\n**Known gaps (epic only).** After the outline, list under `Known gaps that will be recorded on the epic` each foundation gap still left after the automatic fixes. For each, give a plain-language description of what is wrong and the non-empty, agent-drafted reason that would be recorded, so the operator reads it before approving. This is a list, not a question: there are no per-gap options. A \"yes\" at the upload question records them; \"change something\" lets the operator ask for a split change instead. A declined initial council is not a gap and is never an acceptance target. An unfinished required council (`still_running`, `failed`, or `timed_out`) is shown as its own unresolved item.\n\n## Step 4 — Write the plan DAG\n\nIn local mode, retain every confirmed minted epic/child key in the manifest immediately and emit neither plan file while a required key is missing or creation is uncertain; use those real keys rather than `TBD-N` placeholders. After an epic's tickets are created, write the Epic Implementer's plan sidecar to `{docs_dir}/epic-plans/{slug}/epic-plan.dag.json`. You already hold everything it needs: the frozen manifest carries each child's `depends_on`, and Stage 8's design named the files each slice touches. Nothing downstream derives this from an epic key, so if you skip it the handoff dead-ends.\n\n```json\n{\n \"plan_version\": 1,\n \"nodes\": [\n {\n \"ticket_key\": \"KEY-2\",\n \"status\": \"planned\",\n \"depends_on\": [],\n \"touched_files\": [\"src/example/service.py\", \"src/example/handler.py\"]\n }\n ],\n \"edges\": []\n}\n```\n\nOne node per child, in manifest order, using the **real** keys just created — never a `TBD-N` placeholder, since the tickets already exist. `depends_on` carries the manifest's hard prerequisites only; leave `recommended_after` out, because soft sequencing is not a dependency and encoding it there serializes work that could run in parallel. `edges` may be `[]` when `depends_on` already expresses the graph. The graph must be acyclic and every `depends_on` entry must name a node in the file.\n\nPopulate `touched_files` on every node from the design's file list, as repository-relative POSIX paths — concrete files only, never a directory or a glob. It is what lets the Epic Implementer serialize two children that would otherwise collide, and it matters more the larger the slices are. An omitted list is accepted by the server as an explicit opt-out, so leaving it off does not fail — it silently turns plan-time overlap protection off. Use `[]` only when a ticket genuinely touches no repository files. Which overlaps get an ordering edge is decided by the server, not by you: on runs created from a repository with a confirmed gate profile, only children whose files both fall under one of the repository's must-order paths (for example a migrations directory, declared in the gate profile and confirmed by the owner) are ordered, and ordinary shared files run in parallel and are resolved at merge time. Do not add `depends_on` entries just because two children share an ordinary file.\n\nThen write the plan's epic key beside it, at `{docs_dir}/epic-plans/{slug}/epic-plan.meta.json`, holding exactly:\n\n```json\n{\"epic_key\": \"<EPIC-KEY>\"}\n```\n\nUse the real epic key just created. This path runs no `finalize` step, so it writes the file itself. It is how `drive-epic` finds this epic's plan without being handed a path.\n\nInclude the files that are easy to forget, because those are the ones that actually collided: **anticipated tests, fixtures, golden files, guard allowlists, and policy files**, not only the production modules. Both known misses were exactly this class — two children shared `ticket_type_evaluator.py` *and its test*, and another pair shared golden files and a `save_repo_to_db` test — and in each case nobody predicted the shared file, so no ordering edge was synthesized and both PRs merged over each other. Paths are compared as exact strings after normalization, so name concrete files: a directory or a glob matches nothing.\n\n## Step 5 — Hand off once\n\nPresent these sections in order:\n\n- **Plan/tickets saved** — confirm the epic, real child keys, and saved DAG/metadata. Saved work remains successful even when launch readiness is refused or unconfirmed.\n- **Readiness preview** — only when the concrete epic key, finalized child keys, `epic-plan.dag.json`, and `epic-plan.meta.json` exist and you recommend launch, use the Completion advisory section at the end of this procedure. Resolve the trusted multiword launcher prefix once, quote dynamic arguments independently, and run `drive-epic '<EPIC>' --dry-run --json` at most once with a 60-second command timeout/cancellation. Parse valid authoritative JSON regardless of exit status. Render selected target, returned reason/remedy, and any `availability_text` verbatim; retain conditional cold-start distinctions. State **ready at preview time**, refusal, or **readiness not confirmed**, never an execution guarantee. If the bounded seam or preview is unavailable, offer the same command for a later user-initiated retry and continue the saved-work report. No automatic rerun on later turns, no second readiness call, and no create/start/approve/provision/index/schedule action.\n- **Launch next step** — point at exactly one launch, by host, conditional on the preview result. Ticket creation does not establish executor, policy, VCS, or indexing readiness. Missing keys, unresolved `TBD-N` entries, or unfinished artifacts receive neutral finalization guidance without probing a nonexistent epic. Ordinary ticket-definition and sibling/lone-ticket requests require no completion readiness call.\n\nPreserve these canonical host routes:\n\n- **Claude Code or Cursor:** `/drive-epic-run {EPIC-KEY}`\n- **Codex or Copilot:** `npx -y @bridge_gpt/mcp-server drive-epic {EPIC-KEY}`\n\nBoth launch through `drive-epic`, and both find the plan through `epic-plan.meta.json`. **The one command both creates and drives the run:** `/drive-epic-run` previews the launch, asks for an explicit yes, creates the run through `drive-epic`, starts its executor, and then drives it. On Codex or Copilot, `drive-epic` creates the run and starts its executor, and the first-run steps are in `docs/install/epic-implementer-install.md` (write or refresh it with `npx -y @bridge_gpt/mcp-server install`).\n\nWith no target flag, `drive-epic` targets production and uses this repository's stored Bridge credential, so no `BAPI_BASE_URL` export or temporary notification terminal is needed when the authoritative preview confirms readiness. A fresh project may still have the returned unmet requirements; planning success does not remove them. For a local or other non-production target, `drive-epic --help-advanced` lists the owner options. A conflicting target, or a stored key approved for a different server, refuses before any authenticated request.\n\n`drive-epic` defaults to the unattended posture. Escalations go to the account's email address; a `--policy-file` is needed only when the account has no email for escalations. Pass `--attended` to opt out of the unattended default. `drive-epic` reads Epic Implementer readiness and selects the runnable path itself. Do not name an underlying launch path, and never present a choice between two of them — two transition authorities on one epic is the failure this single entry point exists to remove. A sibling pair or a lone ticket gets no Epic Implementer handoff at all.\n\n**Only under --auto:** render this handoff as a report line and never invoke it.\n\nEvery unattended epic-branch run so far has needed operator recoveries within minutes of a trigger, and the reconciler never applies them. That is why the one command both creates and drives the run: the session that launched it stays to apply the sanctioned recovery verbs.\n\n## Completion advisory — saved epic plans and tickets\n\nThis pattern is for a completion handoff that recommends launch, outside\n`/drive-epic-run`'s Stage 0. It is read-only and adds no mandatory launch gate.\n\nEligibility requires a concrete epic key, finalized real child keys (no `TBD-N`),\nand the actual `epic-plan.dag.json` and `epic-plan.meta.json` artifacts. Free-form\nplans, missing keys, and unfinished artifacts receive boundary guidance only.\nRun at most one eligible preview per completion; do not automatically rerun it on\nlater turns of that completion. Ordinary ticket definition needs no preview.\n\nResolve `<launcher>` once using `/drive-epic-run` Stage 0 operation 3's trusted\ncommand-prefix convention. Preserve multiword prefixes such as\n`node /absolute/path/to/mcp_server/build/index.js`; never quote the entire prefix\nas one executable. Independently escape and single-quote every dynamic argument:\n\n```bash\n<launcher> drive-epic '<EPIC>' --dry-run --json\n```\n\nRetain `--plan-file '<path>'` only when actual plan selection requires it. Use the\nhost's command timeout seam to impose a **60-second** wall-clock limit and cancel\nthe read-only child where supported. If bounded execution is unavailable, report\n**readiness not confirmed** without starting an unbounded operation.\n\nParse authoritative JSON regardless of exit status, including nonzero refusals.\nValidate it using `/drive-epic-run` Stage 0 operation 4's existing schema and\ncontradictions checks.\nReport the selected `target.kind` and `target.base_url`; render `refusal.reason_id`\nand `refusal.remedy` verbatim, falling back to `readiness.reason_id` and\n`readiness.remedy` when refusal is null. Relay any supplied `availability_text`\nverbatim without substituting generic VCS/indexing advice. A `stop` decision\nreports the returned plan status/candidates and finalization remedy. Never invent\nfields or an independent readiness rule.\n\nAn ordinary successful `create` or `attach` preview is **ready at preview time**.\nA `cold_start` create is conditional: live-run existence was not checked and\n`summary.server_validation` is partial; guarded startup and live validation must\nstill succeed. It is never a promise of launch readiness. Malformed, unavailable,\nthrowing, or timed-out previews mean **readiness not confirmed**. Retain planning\nsuccess and offer the same preview command for a later user-initiated retry.\n\nPresent **Plan/tickets saved → Readiness preview → Launch next step**. Planning\nand ticket creation establish neither executor, policy, VCS, nor indexing\nreadiness. Reproduce only actual unmet dependencies and returned remedies.\nNever create, start, approve, provision, index, or schedule anything from this\nadvisory. Preserve actual launch consent and `drive-epic` admission; do not invoke\n`/drive-epic-run` Stage 0's launch, health check, or second advisory-read\noperations here.\n\n## Return\n\nThis procedure returns nothing on its own. After each section, go back to the\n`/define-tickets` Stage 9 pointer that sent you here and continue from that point.\nReport the outcome of the section you just followed in the command's own terms: the\ngap-check outcome and record path, the clearance result, the saved DAG and metadata\npaths, or the hand-off sections shown. A halt keeps the command's halt reason and\nterminal contract; this procedure adds no halt reason and no terminal field.\n",
755
756
  "draft-and-critique.md": "Draft the ticket(s) for this idea, run a BAPI-320 hygiene pass, and emit structured draft metadata.\n\n## Inputs\n\n- Run manifest: `{docs_dir}/idea-to-ticket/{slug}-{run_id}/run-manifest.json`.\n- Research pack: `{docs_dir}/idea-to-ticket/{slug}-{run_id}/research-pack.md` / `.json`.\n- Duplicate assessment: `{docs_dir}/idea-to-ticket/{slug}-{run_id}/duplicate-assessment.json`.\n- Standards checklist: `{docs_dir}/idea-to-ticket/{slug}-{run_id}/standards-checklist.json`.\n- Resolved uncertainties: `{docs_dir}/idea-to-ticket/{slug}-{run_id}/resolved-uncertainties.md`.\n- Goals & NFR framing: `{docs_dir}/idea-to-ticket/{slug}-{run_id}/goals-and-nfrs.md`.\n- Comp→codebase map (optional): `{docs_dir}/idea-to-ticket/{slug}-{run_id}/comp-analysis.json`. Produced upstream by the gated `comp-analysis.md` perception step. A missing, unreadable, or `applicable: false` map is treated exactly like `applicable: false` — a no-op: it never halts drafting and this step injects no visual-fidelity/comp language on its own.\n\n## Instructions\n\n1. **Resolve the regression-completeness gate once, before drafting.** Call the `config_field` MCP tool with `operation` set to `\"get\"` and `field_name` set to `enable_regression_checks`. Normalize the response: only the exact value `true` (a JSON boolean `true`, or the case-insensitive string `\"true\"`) counts as enabled. Treat a missing tool, a tool error, `null`, `false`, or any other/malformed value as disabled — this lookup is fail-open and defaults OFF. Store the normalized boolean as `enable_regression_checks` and reuse the same stored value for every `jira-ticket-writer` invocation this flow makes (including any later critique/revision call) — do not re-resolve it per call. The `jira-ticket-writer` sub-agent must not call `config_field` itself.\n\n2. Read the six required input artifacts in full before drafting, plus the comp-analysis map when it is present. The manifest's `scope` (`task`, `spike`, or `epic_candidate`) determines the drafting path.\n\n The goals-and-nfrs.md framing must shape every draft. Lead each draft with the **business goal** and **desired end-state**, and include an explicit **Non-Functional Requirements** section (and, where it clarifies behavior, the required **system behavior**). For the **epic_candidate** parent, these belong in the Epic description itself (the parent's `slim_description` should at least name the business goal + end-state, and the attached full draft must carry the Goals / Desired End-State / Non-Functional Requirements sections). Any NFR still marked `open` in the framing must be written into the draft as an explicit assumption plus an open-risk note — never silently dropped. This flow is documentary: do not generate a decision page and do not pause for clarification here.\n\n3. Drafting path by scope:\n - **task** or **spike**:\n - Call the `jira-ticket-writer` sub-agent with an explicit output path of `{docs_dir}/tickets/TICKET-{slug}.md`. The sub-agent must write the full markdown draft to that exact file. Pass the comp-analysis map path (`{docs_dir}/idea-to-ticket/{slug}-{run_id}/comp-analysis.json`) into the sub-agent prompt alongside the six existing input artifacts (run manifest, research pack, duplicate assessment, standards checklist, resolved uncertainties, goals-and-nfrs) and the stored `enable_regression_checks` value from step 1.\n - **Pass the manifest's already-resolved `scope` explicitly into the sub-agent prompt**, stated as `scope: task` or `scope: spike`. The writer selects the spike ticket format on `scope: spike` alone, and on nothing else — never ask it to judge whether the work \"feels\" investigative or is primarily discovery/research, and never leave the value unstated for it to infer. The objective decision was already made once, at `preflight-and-readiness.md`, against the E2 condition \"no committed production-code deliverable\"; a missing, malformed, or unrecognized value means the writer produces the ordinary code-ticket format.\n - **epic_candidate**:\n - Call `jira-ticket-writer` to draft only the Epic parent. Use the explicit output path `{docs_dir}/tickets/EPIC-{slug}.md`. Pass the same comp-analysis map path into the sub-agent prompt alongside the six existing input artifacts and the stored `enable_regression_checks` value from step 1. Child tickets are produced later by `decompose-epic-candidate.md`; do not draft them here.\n\n Comp-analysis map consumption (both paths): when `comp-analysis.json` has `applicable: true`, tell the writer its Requirements MUST use the mapped components/templates/tokens/routes as concrete implementation guidance (e.g. \"reuse component X\", \"use token Z\", \"extend template Y\", \"wire route R\"). When the map has `applicable: false` or is missing/unreadable, tell the writer to ignore the artifact entirely and avoid mentioning comp analysis, design comps, or visual fidelity unless the original request independently requires those materials. This step only feeds the text JSON map to the writer — it never opens images, calls `describe_image()`, or performs vision analysis itself.\n\n Regression-gate consumption (both paths): state `enable_regression_checks: {stored value from step 1}` explicitly in the sub-agent prompt, and tell the writer this value was already resolved by the caller and must not be looked up again. The writer only runs its Regression Completeness Pass when this value is exactly `true`.\n\n4. **Every body goes through the writer, and the split is not yours to change.** The ticket-authoring posture (`docs/bridge-ticket-authoring.md`, carried verbatim by `decompose-epic-candidate.md` in this same flow) requires that every Jira body — Epic parent, child, and ordinary sibling alike — is drafted by `jira-ticket-writer`. State that posture explicitly in each sub-agent prompt, together with the approved manifest entry the invocation is bound to when one exists, so the writer knows it is rendering a frozen entry rather than deciding one.\n\n This applies identically to the **initial draft** and to any **revision** the hygiene/critique pass triggers. A revision re-invokes `jira-ticket-writer` with the *same* manifest entry and the *same* posture. Critique may improve a body's prose, evidence, and precision. It may not change the approved ticket count, the ordering, the parent relationship, an entry's dependency lists, its scope boundary, or its sizing classification — those were settled by the decomposition pass, and a critique pass sees one body at a time, so a split re-decided here is re-decided on strictly less information. A critique that believes the split is wrong reports that to the caller; it does not act on it.\n\n5. Issue type policy:\n - Default ambiguous ideas to `Task`.\n - Choose `Spike` only when the work is primarily discovery/research/learning with no clear acceptance criteria yet.\n - The Epic parent uses Jira issue type `Epic`.\n\n6. Hygiene pass (BAPI-320 forbidden tokens). After the sub-agent writes the draft, read it back and ensure none of these tokens are present:\n - markdown tables (any `|`-separated header row).\n - escaped pipe-table patterns (e.g. `\\|`).\n - task-list checkboxes such as `- [ ]` or `- [x]`.\n - angle-bracket placeholder tokens (any `<placeholder>` form, even inside backticks).\n - raw HTML blocks (`<div>`, `<br>`, `<table>`, etc.).\n When a forbidden token is found, rewrite the surrounding paragraph in plain prose or bullet form and save the cleaned draft over the same path.\n\n **One exemption, and only one:** on a `spike` draft, the canonical execution-class marker line `<!-- bridge:execution-class=investigation -->` is NOT a forbidden raw-HTML token. Leave it exactly as the writer wrote it — same spelling, same single occurrence, same position immediately after the title. Cleaning it away would silently strip the ticket's only machine-readable class signal. This exemption covers that one literal on a spike draft and nothing else; every other angle-bracket construct stays forbidden, and a `task` draft has no exemption because it carries no marker.\n\n7. Write `{docs_dir}/idea-to-ticket/{slug}-{run_id}/draft-metadata.json` describing what Jira should later create.\n\n For **task** / **spike** scope, the metadata shape is:\n - `summary` — Jira ticket title.\n - `issue_type` — `Task` or `Spike`.\n - `slim_description` — short Jira-safe description (no forbidden tokens). The full draft is uploaded as an attachment. It must include a CONCISE, high-level summary of the draft's `## Materials & Access` inventory (Planning Assets, Downloadable Assets, Planning & Downloadable Assets vs. unphased record-only material), noting that the exhaustive list lives in the attached full draft. This keeps the missing-materials record visible to human reviewers and to description-reading review/critique flows.\n\n **Marker preservation (`spike` scope).** The Jira issue is created from `slim_description`, not from the full draft — the draft only becomes an attachment. So a marker that survives only in the attachment leaves the persisted ticket record with no machine-readable signal at all, which defeats the marker's entire purpose. When slimming a `spike` draft, carry the draft's title line and the canonical `<!-- bridge:execution-class=investigation -->` line into `slim_description` first, in that original order, before the summarized body — exactly one occurrence, byte-for-byte, alone on its own line. Do not rewrite it, reformat it, translate it into a label, move it below the body, or leave it behind in the attachment.\n\n **No marker synthesis (`task` scope).** A `task` draft carries no marker, and slimming must not invent one. Writing a marker here would fabricate an execution-class signal the author never declared.\n - `attachment_path` — `{docs_dir}/tickets/TICKET-{slug}.md` (or the equivalent path used above).\n\n For **epic_candidate** scope, the metadata shape is:\n - `parent.summary` — Epic title.\n - `parent.issue_type` — `Epic`.\n - `parent.slim_description` — short Epic description. It must include a CONCISE, high-level summary of the Epic draft's `## Materials & Access` inventory (Planning Assets, Downloadable Assets, Planning & Downloadable Assets vs. unphased record-only material), noting that the exhaustive list lives in the attached full draft.\n - `parent.attachment_path` — `{docs_dir}/tickets/EPIC-{slug}.md`.\n - `children` — placeholder array. Populated later by `decompose-epic-candidate.md`; leave as an empty array here.\n\n8. Save the metadata exactly once. Downstream steps read this file; do not move it.\n\n## Return\n\nConfirm the draft path, the metadata path, and the chosen scope (`task`, `spike`, or `epic_candidate`).\n",
756
757
  "duplicate-and-context-scan.md": "Detect existing tickets that duplicate or relate to this idea before any ticket mutation.\n\n## Inputs\n\n- Run manifest: `{docs_dir}/idea-to-ticket/{slug}-{run_id}/run-manifest.json`.\n- Research pack: `{docs_dir}/idea-to-ticket/{slug}-{run_id}/research-pack.md` (if produced).\n- Pipeline variable `allow_duplicate` controls override behavior (for this run, `allow_duplicate` = `{allow_duplicate}`). Treat the literal string `\"true\"` as override; any other value (including `\"false\"`, missing, or empty) is non-override.\n\n## Callers\n\nTwo callers use this procedure. The **recipe path** is everything under Instructions below and uses label-free searches. The **define-tickets path** is the separate branch at the end of that section; it is used only by `/define-tickets --auto`, and both paths omit labels.\n\n## Instructions\n\n> **Orchestrator-directed step.** This agent task is part of the full-automation chain and is authorized to call `get_tickets` as directed below — performing an orchestrator-directed tool call is not \"re-orchestrating\".\n\n1. Build at least two ticket searches from the manifest using the `query` parameter:\n - **Title/keyword query**: use the most salient nouns from `idea` and `slug` as title/text keywords. Prefer 2-4 concrete terms over long natural-language sentences. Run via `get_tickets`.\n - **Candidate-title query**: run `get_tickets` with a concise candidate ticket title. Compare returned scope with the idea rather than treating a text match as proof.\n - Never pass `labels`. Cross-run duplicate detection is a title/text assessment in both Jira and local mode, not a stable idea-hash guarantee. Same-run creation recovery uses confirmed real keys in `upload-state.json`; never use a search result to reconcile an uncertain create automatically.\n\n2. For each returned ticket, capture: ticket key, summary, status, and a short reason it matched (which query, which keyword).\n\n3. Classify the overall verdict as one of:\n - `duplicate` — at least one returned ticket clearly describes the same work as `idea`.\n - `related` — returned tickets are adjacent or partial overlaps but not the same work.\n - `none_found` — no meaningful matches.\n - `unable_to_check` — the ticket search itself failed (network error, auth error, JQL rejection). Record the failure and pick this verdict.\n\n4. Write `{docs_dir}/idea-to-ticket/{slug}-{run_id}/duplicate-assessment.json` with at minimum:\n - `verdict` — one of the four values above.\n - `matches` — array of `{ticket_key, summary, status, reason}` objects (may be empty).\n - `queries_used` — array of the actual JQL/search strings sent.\n - `allow_duplicate` — the resolved value of `{allow_duplicate}` for this run.\n\n5. Halt behavior:\n - If `verdict` is `duplicate` and `allow_duplicate` is not `\"true\"`, halt locally. Do not continue the pipeline. Tell the user that the duplicate halt is strict and that re-running with `--allow-duplicate` overrides it.\n - If `verdict` is `duplicate` and `allow_duplicate` is `\"true\"`, continue the pipeline but keep the duplicate evidence in the assessment file so downstream steps can reference it (e.g., to add a \"supersedes\" note to the draft).\n - For `related`, `none_found`, and `unable_to_check`, continue without halting.\n\n### Define-tickets path\n\nUsed only when `/define-tickets --auto` runs this procedure. The command names the artifact directory, a unique local run id, and the resolved `allow_duplicate` literal in its invocation. There is no run manifest and no label.\n\n1. Run at least two `get_tickets` searches using its `query` parameter: one keyword search built from the salient nouns of the task, and one search on the candidate ticket title. Never pass `labels`; both caller paths use label-free queries.\n2. Capture each returned ticket's key, summary, status, and a short reason it matched. Classify the verdict as `duplicate`, `related`, `none_found`, or `unable_to_check`, using the same definitions as above.\n3. Write `duplicate-assessment.json` to the named artifact directory with `verdict`, `matches`, `queries_used`, and the resolved `allow_duplicate` value.\n4. Halt behavior for this path: a `duplicate` verdict halts the command unless `allow_duplicate` is the literal string `\"true\"`. That override applies only to a known `duplicate` verdict. An `unable_to_check` verdict is never overridden. The command halts as `stage_failed` and names the duplicate scan. Matches found here were not created by this run.\n\n## Return\n\nConfirm `duplicate-assessment.json` was written, report `verdict`, and report whether the run is halting or continuing.\n",
757
758
  "emit-conductor-bundle.md": "Harmonize an epic's sibling tickets against each other and emit the artifacts the Epic Implementer needs, after the tickets exist and before the plan is approved.\n\nEach sibling ticket was drafted by a separate writer session that could not see\nits siblings. Each independently re-researched the codebase and re-derived\ninterfaces, names, and file ownership, so siblings routinely disagree exactly at\nthe seams where they must agree — the dependency edges. The decomposition itself\nwas coherent (one agent, one context, wrote `epic-plan.md` and every exploration\ndocument); that coherence is discarded at the handoff. This task reads every\nsibling in one context and restores it.\n\nThe window is forced. Real ticket keys exist only after creation, and description\nrewrites are free before approval but trip `spec_stale` after it.\n\n**This is a standalone task, deliberately not a step in `plan-epic.json`.**\n`plan-epic` creates no tickets, so wiring this in there would guarantee it runs\nbefore any sibling exists. The local agent invokes it directly, immediately after\ncreating the epic's tickets, passing the ordered node→key mapping it already\nholds.\n\n## Inputs\n\n- `epic_key` — the Jira key of the epic (e.g. `BAPI-634`). **Required.**\n `setup-epic --dry-run` needs it, it cannot be derived safely from the slug, and\n it cannot be recovered from Jira: `get_tickets` filters only by free-text\n `search` and `labels`, with no `parent_key` filter.\n- `epic_slug` — the sanitized slug naming the epic-plan directory.\n- An **ordered array of mapping entries**, one per sidecar node, each with:\n - `plan_node_id` — the node's identity in `epic-plan.dag.json` (a `TBD-N`\n placeholder on the initial run, or the real key on a rerun).\n - `ticket_key` — the real Jira key created for that node.\n - `exploration_path` — that sub-task's exploration document, relative to the\n epic-plan directory.\n - `draft_path` — that sub-task's draft, relative to the epic-plan directory.\n\n**Node identity comes only from `plan_node_id`.** Never infer which node a ticket\nbelongs to from mapping order, ticket titles, description text, or a Jira search.\nA key list plus `epic_slug` cannot determine which real key replaces which\n`TBD-N`, and guessing attaches one ticket's dependencies to another.\n\n## Instructions\n\nResolve `docs_dir` by calling the `ping` MCP tool (no parameters) and reading\n`docs_dir` from its first (JSON) content item. The\nsole workspace for this task is `{docs_dir}/epic-plans/{epic_slug}`. Never read or\nwrite outside it.\n\nExecute the following phases **in this order**. The ordering is the safety\nproperty: every external write is gated behind local validation, so a failure\nleaves Jira untouched rather than half-mutated. Pipeline ordering cannot protect a\nmanual or recovery run, so this task owns it.\n\n### Phase 1 — Non-mutating run-state precheck\n\nBefore reading artifacts, confirm the epic is still in the pre-approval window:\n\n```bash\nnpx -y -p @bridge_gpt/mcp-server epic-implementer epic-status --epic-key <epic_key> --json\n```\n\nThis is read-only. Interpret the result:\n\n- `{\"status\": \"unknown\", \"state\": null}` — no run exists yet. **Proceed**; the\n dry-run does not create one. A run is created later, only through\n `/drive-epic-run <epic_key>` (which launches via `drive-epic`).\n- `epic_run.status` is `planning` **and** its plan version is not yet stored —\n a single unapproved planning run. **Proceed**; it may be reused.\n- `epic_run.status` is `active`, `blocked`, `done`, or `abandoned` — **halt.**\n- `epic_run.approved_plan_hash` is non-null (the plan is approved) — **halt.**\n- The sidecar's `plan_version` is already stored — **halt.** Plan blobs are\n immutable and post-approval description rewrites are forbidden; this needs an\n explicit re-plan.\n- Multiple runs, or any ambiguous/unreadable state — **halt.** Never guess.\n\nHalting here means reporting the state and stopping. Do not attempt a repair.\n\n### Phase 2 — Validate inputs and source artifacts\n\nAssemble the mapping into a JSON input document. Both the ordered mapping and\nthe `decomposition_fingerprint` are derived from the **approved ordered manifest**\n— the split the decomposition pass froze and the approval gate accepted — and\nnever from a fresh decomposition performed here. This task harmonizes bodies\nagainst each other; it does not re-decide the split, and a fingerprint computed\nover a newly derived decomposition would silently detach the bundle from the plan\nthat was actually approved.\n\n```json\n{\n \"epic_key\": \"<epic_key>\",\n \"epic_slug\": \"<epic_slug>\",\n \"decomposition_fingerprint\": \"<stable fingerprint of this decomposition>\",\n \"mappings\": [\n {\n \"plan_node_id\": \"TBD-1\",\n \"ticket_key\": \"BAPI-635\",\n \"exploration_path\": \"explorations/01-<subtask-slug>.md\",\n \"draft_path\": \"drafts/01-<subtask-slug>.md\"\n }\n ]\n}\n```\n\nThen run the deterministic entry validation **before reading any mapped file,\nfetching any ticket, or writing any artifact**:\n\n```bash\nnpx -y @bridge_gpt/mcp-server emit-epic-implementer-bundle validate \\\n --input <path to the input document> \\\n --json\n```\n\nThis writes nothing. A non-zero exit halts the task; relay its error verbatim.\nThese are entry-point checks, not agent judgment. It enforces:\n\n- `epic_key` and every `ticket_key` match the project's Jira key pattern, are\n non-empty and unique, and no child key equals `epic_key`.\n- `epic_slug` matches the sanitized slug grammar.\n- The mapping is **complete and one-to-one**: every sidecar node has exactly one\n entry, and every entry matches exactly one node — by `plan_node_id` on the\n initial run, or by its already-mapped `ticket_key` on a rerun.\n- An existing `sibling-ticket-manifest.json` agrees with the supplied mapping on\n epic identity, slug, plan version, decomposition fingerprint, and every\n node→key pair. **On disagreement, halt** — never silently prefer either source.\n- Every mapped path resolves beneath `{docs_dir}/epic-plans/{epic_slug}`.\n Absolute paths, `..` traversal, paths into another epic's directory, unknown\n mapping paths, and symlink escapes are all rejected before their content is read.\n\nThen load these **authoritative artifacts** into one working context:\n\n- `{docs_dir}/epic-plans/{epic_slug}/goals-and-nfrs.md`\n- `{docs_dir}/epic-plans/{epic_slug}/epic-plan.md`\n- `{docs_dir}/epic-plans/{epic_slug}/epic-plan.dag.json`\n- every mapped exploration document\n- every mapped draft\n\n**Halt** if any of them is missing, malformed, or unmatched. These are\nauthoritative inputs; proceeding without one voids the reconciliation guarantee.\n\nRe-fetch every mapped child ticket by its supplied key (`get_ticket`) and keep\nthe complete sibling set in one context. Reading them one at a time defeats the\nentire purpose of this task.\n\nDelimit every dynamically inserted Jira, plan, draft, or exploration excerpt with\ntriple quotes before analyzing it, and strip secret-like content before it can\nreach a prompt, a rendered description, decision material, a report, or an\nattachment.\n\n### Phase 3 — Harmonize the whole epic (in memory)\n\n**Authority order when sources conflict:**\n\n1. Exploration documents and current code research — primary evidence.\n2. Intended scope in `epic-plan.md` — what the decomposition meant to build.\n3. Current ticket descriptions — **outputs to be corrected, never authoritative\n inputs.**\n\nReview the complete sibling set once against this taxonomy, rather than a vague\n\"look for problems\" pass:\n\n- **interface drift** — the same function, endpoint, table, or field described\n differently across siblings.\n- **ownership collision** — two tickets both claiming to create the same file,\n symbol, or migration.\n- **orphan consumer** — a ticket consuming a seam no sibling produces.\n- **order violation** — a ticket assuming work a later sibling does.\n- **scope overlap** — two tickets covering the same work.\n- **vocabulary drift** — the same concept named inconsistently.\n- **NFR conflict** — a ticket contradicting `goals-and-nfrs.md`.\n\nEvery dependency edge must end up with an explicit producer, an explicit\nconsumer, an owned seam, an exact interface or artifact name, and a required\nordering.\n\n#### Canonical contract blocks\n\nRender each shared seam **once**, and insert byte-identical text into both the\nproducer's and the consumer's description. This is what makes \"described\nidentically at the edge\" checkable rather than a matter of opinion.\n\nUse stable delimiters and a stable seam identifier:\n\n```\n<!-- BEGIN CONTRACT: {seam_id} -->\n**Contract: {seam_id}**\n\n- **Producer**: {producer_ticket_key}\n- **Consumer(s)**: {consumer_ticket_keys}\n- **Interface**: {exact name and signature/shape}\n- **Ordering**: {what must exist before what}\n<!-- END CONTRACT: {seam_id} -->\n```\n\n`{seam_id}` is derived deterministically from the seam's identity (the interface\nor artifact name), so the same seam keeps the same id across runs. Everything\noutside a contract block stays ticket-specific: each ticket keeps its own\nsummary, scope, requirements, acceptance criteria, constraints, and risks.\n\n#### Fold in the exploration document\n\nThe description is the **only** channel an Epic Implementer worker can see. The\nreconciler resolves the spec and ships it in the job payload; the worker reads the\nticket, not the repo. `docs/tmp/epic-plans/` is gitignored and worker worktrees\nare cut from a pinned `origin/<base>` SHA, so exploration documents are never on\ndisk for the implementing agent.\n\nFold each sub-task's exploration document into its ticket under a deterministic\ndelimited section:\n\n```\n<!-- BEGIN EXPLORATION: {ticket_key} -->\n...\n<!-- END EXPLORATION: {ticket_key} -->\n```\n\nPreserve every implementation-relevant file, symbol, interface, constraint,\ndecision, and open risk. Resolve every mapped `TBD-N` token to its real key in\nticket prose, exploration content, drafts, and contract blocks — not only in the\nsidecar. Drafts authored before the tickets existed refer to siblings as `TBD-N`;\na worker receiving that text has no actionable dependency reference.\n\n#### The spec length bound — fail loud\n\nValidate every complete rendered description against the bound. The Epic Implementer's\npayload bound is **64,000 characters** (the reconciler no longer truncates\nsilently — overflow beyond its own bound is visibly marked). For Jira-backed\ntickets the **practical** limit binds far earlier: Jira caps a description at\n**32,767 characters**, so treat that as the real-world ceiling there.\n\nCount **Unicode code points**, not UTF-16 code units — the server's bound is a\nPython `len()`, so an astral character (an emoji, say) counts once there but\ntwice under a naive JavaScript `.length`, which would reject a description that\nactually fits.\n\n- Compact repetition and non-actionable prose **first**, without dropping\n actionable content.\n- If the required content still will not fit, **fail loud and escalate** as a\n decomposition/scope finding.\n- An attachment is **not** a workaround — the worker cannot see it.\n- Raising the server-side bound is out of scope.\n\n#### Auto-resolve vs escalate\n\n**Auto-resolve only** when the authoritative artifacts make the intended contract\nunambiguous: normalizing vocabulary, or copying a producer's already-defined\ninterface name to its consumer.\n\n**Escalate** any proposed change to scope, decomposition, ownership boundaries,\ndependencies, public contracts, migrations, NFRs, or acceptance criteria. A\ncontradiction implying a scope or decomposition change is not a wording fix;\nauto-resolving one silently is worse than the contradiction, because it launders a\nreal decision into prose nobody reviewed.\n\n#### Build `touched_files`\n\nThe file-ownership map you built to detect **ownership collision** *is*\n`touched_files`. This step is the only place with a whole-epic view, and nothing\nelse emits the field today.\n\n- Sorted, deduplicated, repository-relative POSIX paths — no leading `./`, no\n absolute paths, no `..` traversal, no temporary-worktree paths, no prose. The\n `finalize` step rejects anything else rather than dropping it. Concrete files\n only: the backend intersects these as exact strings, so a directory or glob\n entry protects nothing.\n- Every node carries the field. `[]` is valid **only** where the ticket genuinely\n touches no repository files and that is explicit.\n- **Unknown ownership is escalated, never encoded as `[]`** — an empty array\n silently disables overlap protection.\n- When two tickets legitimately touch the same file, **both** keep it. If one\n consumes an interface the other produces, add the semantic dependency\n explicitly rather than relying on overlap serialization for ordering.\n\n##### What `touched_files` can and cannot prove (BAPI-848)\n\n`touched_files` is a **pre-implementation prediction**, written before the work\nexists. Overlap serialization intersects those declared lists as exact strings,\nso it proves ordering **only for paths both nodes actually declared**. Its\ncoverage scope is `declared_files_only`, and the server now reports that scope\nalongside the counts.\n\nTwo consequences, both load-bearing:\n\n- **A passing dry run and `inserted_edges: 0` prove nothing about the\n implementation.** Zero edges means \"no two nodes declared the same path\". It\n does not mean the implementations will avoid each other. In epic BAPI-776 the\n plan reported `inserted_edges: 0` and all three tickets converged on one line\n of one undeclared file.\n- **An undeclared file is invisible to serialization**, whatever the work ends\n up touching. This is a **deliberately accepted limitation**: an implementation\n that touches a genuinely undeclared, non-discoverable file is not\n automatically serialized against its siblings. Merge-conflict detection plus\n `JOB_TYPE_REBASE` remains the reactive backstop.\n\nThe obvious \"fix\" — attaching a blanket set of hotspot paths to every node — is\n**wrong and must not be done.** It would serialize unrelated siblings and\neffectively disable the parallelism the Epic Implementer exists to provide.\n\n**Prefer removing a hotspot structurally over scheduling around it.** A test\nrunner, build manifest, or route table that enumerates its members by hand is a\nrepository-wide serialization point: every ticket that adds a member must edit\nthat one shared line, so any two such tickets conflict by construction, and a\nmember left off it silently runs nowhere. Replacing the enumeration with\ndiscovery removes the conflict class outright. Where that has been done, adding a\nmember no longer implies touching the shared file — so do not declare it as\nthough it does. Check the current state of the repository you are planning for\nrather than assuming either shape.\n\n### Phase 4 — Escalate and halt, if there are escalations\n\nAssign this invocation a local `harmonization_run_id`, and give each finding a\nstable id derived deterministically from its normalized class, its sorted\naffected ticket keys, and its seam or file identity — so the same contradiction\nkeeps the same id across runs and a resumed decision still applies.\n\nIf any finding is escalated, build **one consolidated decision page** using the\ninteraction established in `clarify-open-nfrs.md` — call `generate_decision_page`\nwith `artifact_type: \"pre_ticket_planning\"`, `ticket_key: {epic_slug}`,\n`output_subdir: \"epic-plans/{epic_slug}\"`, and\n`output_filename: \"{epic_slug}-harmonization-decisions.html\"`. Give each item its\ntaxonomy class, affected tickets, bounded conflicting evidence, options, and a\nrecommended resolution.\n\nBefore halting, atomically persist the validated manifest, the provisional report,\nand the decision-page reference. Then **halt without changing the sidecar or\nJira**. Stop and wait for the user; do not assume a resolution.\n\n**On resume**: read the manifest, re-fetch all tickets, re-evaluate the complete\nsibling set, apply the recorded decision, and continue from this phase. Do not\nrestart `plan-epic` — that risks recreating tickets or losing the key mapping. Do\nnot post a duplicate decision page or order comments.\n\n### Phase 5 — Stage the local bundle\n\nAdd the whole-epic ownership map to the input document as\n`touched_files_by_key` (real Jira key → its predicted files), then finalize:\n\n```bash\nnpx -y @bridge_gpt/mcp-server emit-epic-implementer-bundle finalize \\\n --input <path to the input document> \\\n --json\n```\n\nThis atomically writes, in one deterministic step:\n\n1. The finalized `{docs_dir}/epic-plans/{epic_slug}/epic-plan.dag.json` — the\n validated node→key map applied across `nodes[].ticket_key`,\n `nodes[].depends_on`, and `edges[].from`/`to`, with each node's normalized\n `touched_files` attached and nothing else mutated. It rejects residual `TBD-`,\n duplicate keys, unknown references, self-dependencies, cycles, and ordinary\n edges that contradict the canonical `depends_on` graph.\n2. `{docs_dir}/epic-plans/{epic_slug}/sibling-ticket-manifest.json` — versioned\n schema, epic identity, sidecar plan version, decomposition fingerprint, the\n ordered mapping, run phase, decisions, and completed-mutation markers. It\n records both the validated source-sidecar identity and the finalized-sidecar\n identity, so a rerun can tell a legitimate finalized sidecar from a different\n decomposition, and it excludes descriptions, credentials, exploration bodies,\n and raw Jira responses.\n3. `{docs_dir}/epic-plans/{epic_slug}/epic-plan.meta.json` — the epic-key\n identity `drive-epic` uses to find this plan.\n\nEvery write is a temp file in the destination directory followed by a rename, so\nan interrupted run cannot leave a partial recovery source. A non-zero exit halts\nthe task; relay its error verbatim.\n\nThen write the report artifacts:\n\n4. `{docs_dir}/epic-plans/{epic_slug}/harmonization-report.json` — versioned\n schema, run metadata, and bounded findings.\n5. A run-scoped archive beside it\n (`harmonization-report.{harmonization_run_id}.json`), **without replacing\n earlier archives**. The fixed path holds only the latest run, so without the\n archive one idempotent rerun would erase the only measurement of what this gate\n ever caught.\n\n- **Preserve `plan_version`.** Do not bump it: these changes finalize version 1\n *before* it is stored.\n- **Never set `base_lineage`.** It affects the plan hash but has no consumer in\n the Epic Implementer, so setting it invalidates the approved hash for no gain.\n\n### Phase 6 — The dry-run gate\n\n```bash\nnpx -y @bridge_gpt/mcp-server setup-epic \\\n --epic-key <epic_key> \\\n --plan-file <docs_dir>/epic-plans/<epic_slug>/epic-plan.dag.json \\\n --dry-run \\\n --json\n```\n\n`validateEpicPlanSidecar()` is a pure local function over the parsed sidecar —\nplan version, key uniqueness, `touched_files`, acyclicity — with no Jira\ndependency. Running it first costs nothing and removes the partial-mutation\nfailure mode entirely.\n\n- **Any non-zero exit halts.** Relay the command's failure text verbatim; it is\n already actionable.\n- **Any `touched_files` warning halts**, even on a successful exit. That warning\n means a node's ownership is undeclared, which is the exact gap this task exists\n to close: an undeclared node is never pre-serialized against an overlapping\n sibling, so it relies entirely on reactive conflict detection at the merge gate.\n Go back and declare it before proceeding.\n\n This halt is **this task's own planning-quality bar, not a server rejection.**\n Plan storage *accepts* an omitted `touched_files` as an explicit opt-out\n (BAPI-722), so nothing downstream will stop you — which is precisely why the\n standard has to be held here. A successful dry run reports\n `undeclared_nodes` and `undeclared_pairs_skipped` next to `inserted_edges`\n (BAPI-848); read those before treating a clean exit as coverage. (A *malformed* `touched_files` is different: the\n server does reject that outright with `VALIDATION`.)\n- **Never fall back** to POSTing `/jira/epic-runs/runs` directly, storing the\n plan, or approving it. A duplicate active run wedges the epic permanently.\n\nIf staging or the dry-run fails, leave Jira descriptions and attachments\nuntouched.\n\n### Phase 7 — Apply the external mutations\n\nOnly on a passing dry-run. Repeat the **Phase 1 run-state precheck immediately\nbefore the first Jira write**, and halt if it now shows approval, activation,\nblocking, plan storage, multiple runs, or an ambiguous state. On a resume,\nre-fetch all sibling tickets and re-evaluate the complete set before applying any\nrecorded decision.\n\n**Descriptions.** Compare each complete proposed description against the ticket's\ncurrent Jira description using the same normalization as\n`normalize_ticket_spec()`: collapse every run of whitespace to a single space and\ntrim, so cosmetic diffs never trigger a rewrite. A pure reflow or indentation\nedit is deliberately **not** a material change — the server treats it the same\nway, and diverging here would false-freeze tickets via `spec_stale`. Call\n`update_ticket_description` **only when the normalized descriptions differ\nmaterially**, and pass the **complete rendered description** — this is a full\nrewrite, not an append. Record each successful description mutation in the\nmanifest before moving to the next one, so a retry converges without duplicating\nwork.\n\n**Drafts and attachments.** Resolve backend mode once before this behavior with `config_field`, `operation: \"get\"`, `field_name: \"ticket_backend_mode\"`. Only positively recognized `local` selects local behavior; absent, null, unreadable, and unrecognized results retain Jira behavior. In local mode, refresh the complete local draft and record its mutation in the manifest, skip attachment upload, and report its sanitized local draft reference under **Local-only records**. Preserve `update_ticket_description` in both modes. Only a terminal HTTP `409` with error `UNSUPPORTED_IN_LOCAL_MODE` from draft attachment upload has this same local-only outcome; unrelated errors keep their existing handling.\n\nFor Jira behavior, refresh the local draft with the reconciled complete\ndocument, then upload it with the `attachment` tool\n(`operation: \"upload\"`, `replace_existing: true`), which replaces any existing\nattachment of the same filename. Note it is delete-then-create rather than an\natomic revision, so the attachment id changes. If replacement is unavailable,\nmark the superseded local draft prominently and upload one deterministically named\nreconciled document instead. Skip the upload when an equivalent revision is\nalready present. **Do not add a Jira comment solely to refresh or supersede an\nattachment.** Record each draft/attachment mutation in the manifest so a retry\nskips completed equivalent work.\n\n**Finalize the reports.** After the required mutations converge, atomically\nrewrite the fixed and run-scoped reports with the actual mutation outcomes.\n\n### Updating one approved node's `ticket_spec` mid-run\n\nA specification larger than Jira's 32,767-character description cap does **not**\nhave to be cut down. An operator can store it on the approved plan node instead.\nNo CLI verb or MCP tool exposes this route, so this task never calls it by hand;\nreport the need to the user instead:\n\n```\nPATCH /jira/epic-runs/runs/<epic_run_id>/plan/nodes/<ticket_key>/ticket-spec\nbody: repo_name, expected_plan_hash, ticket_spec\n```\n\n- Bounded at **64,000 characters**, stored verbatim — never truncated. The\n reconciler consults the plan node **first** when building a spec-review prompt,\n so the reviewer sees the complete text on the next tick.\n- **Safe mid-run.** It changes only that node's `ticket_spec` (plus the plan hash),\n and never the plan version, the approval pointers, or any `epic_ticket_status`\n row. No ticket is re-seeded and no in-flight gate state is disturbed.\n- **`expected_plan_hash` is required** and must match the currently approved hash.\n A stale hash on a real content change returns **409**; re-read the approved plan\n and retry. Re-sending content that already matches is an idempotent no-op\n (`updated: false`) and succeeds even with a stale hash, because nothing would be\n overwritten.\n- This is **not** the same as re-storing the full plan at a new version and\n re-approving it. That path re-seeds ticket rows and moves approval pointers, and\n remains unsafe for casual mid-run spec edits.\n\n### Clean reruns\n\nA rerun over an already-harmonized epic is a **clean no-op**. It must not call\n`update_ticket_description`, upload a duplicate attachment, add a comment, alter\nplan semantics, bump `plan_version`, approve anything, or create status rows. It\nstill runs the final dry-run validation, still emits the fixed report (with an\nempty `findings` array), and still preserves every prior archive. It may rewrite\nidentical local JSON whose bytes differ only by normalization.\n\n### Never do these\n\n- Never create or seed `epic_ticket_status` rows, and never add a fallback\n seeding path. Seeding is owned by `approve_epic_plan`, which seeds one\n `planned` row per plan node idempotently before flipping the run to `active`.\n- Never approve a plan, activate a run, or POST to `/jira/epic-runs/runs`.\n- Never set `base_lineage`.\n- Never rewrite a description after the run reaches `active` — that trips\n `spec_stale`.\n\n## Return\n\nReport:\n\n- The manifest path.\n- The fixed report path and the run-scoped archive path.\n- The ticket keys whose descriptions **changed**, and those left **unchanged**.\n- Attachment outcomes per ticket.\n- The dry-run result.\n- Exactly one status: **`ready_for_approval`** or **`decision_required`**.\n\nState explicitly that **approval remains a separate subsequent action** — this\ntask never approves the plan. On `ready_for_approval`, the operator's next\naction is `/drive-epic-run <epic_key>` (or `drive-epic <epic_key>` in Codex or\nCopilot), which asks for confirmation before it creates a run.\n",
@@ -775,7 +776,7 @@ export const INSTRUCTIONS = {
775
776
  "learn-documentation-instructions.md": "## Objective\n\nExplore the codebase to identify implementation documentation patterns — the markdown records that document what was built, why, and when — then draft `documentation_instructions` for the project config.\n\n## Instructions\n\n### Phase 1 — Explore Implementation Record Patterns\n\nFocus on how the project records what was built, why, and when. These records serve as persistent project memory. Code-level documentation (docstrings, inline comments) is handled by correctness standards, not here.\n\n1. **Implementation Record Discovery**: Search for:\n - Ticket-numbered documents matching `BAPI-*.md` or `PROJ-*.md` in `docs/` and subdirectories\n - Feature/migration documents in `docs/`, `documentation/`, or similar directories\n - Architecture Decision Records (ADRs) in `adr/`, `decisions/`, or similar\n - Changelogs (`CHANGELOG.md`, release notes)\n\n Count how many records exist and identify the naming convention.\n\n2. **Record Structure Analysis**: Read 3-5 representative implementation records (mix of early and recent). Document:\n - Sections present (Summary, Architecture, Database Changes, API Reference, etc.)\n - Level of detail provided\n - Types of information captured (motivation, design decisions, schema changes, file paths, API contracts)\n - How code examples and diagrams are used\n\n3. **Documentation Location and Organization**: Read the directory structure of `docs/` to identify where records are stored, the file naming convention, whether there is a table of contents or index, and whether subdirectories serve different purposes.\n\n### Phase 2 — Draft\n\nDraft `documentation_instructions` as **exactly one concise prose paragraph** that an AI agent will follow when writing implementation documentation after completing a feature. The drafted value is inlined verbatim into a generated plan step, so it has hard formatting constraints:\n\n- The output MUST be **one prose paragraph under 1,500 characters**.\n- The output MUST avoid **markdown headings, bullets, numbered lists, and intentional blank lines**. Write flowing prose (semicolon-separated clauses are fine), not a document outline or multi-section manual.\n- The paragraph MUST cover, in prose: the discovered **file naming convention** (or a sensible default), the **file location** where implementation records live, and the **key content to include** (what changed and why, important files and design decisions, any API/configuration/database impacts, and brief usage or validation examples).\n- The paragraph SHOULD include **skip guidance**: skip implementation documentation for trivial, test-only, or docs-only changes where appropriate.\n\nKeep the scope to implementation records only; code-level documentation (docstrings, inline comments) belongs in correctness standards.\n\nIf there is nothing repository-specific to cite, say that no repository evidence was found and write a short conservative standard; do not invent files, commands, or conventions.\n\nWrite the draft to `{docs_dir}/standards/documentation_instructions.md`.\n\n## Length Budget\n\nThe general platform ceiling for a configuration field is **40,000 characters**, but\n`documentation_instructions` has a stricter **effective limit of 1,500 characters** enforced by the\nserver for this field specifically, because the value is inlined verbatim into a generated plan step.\nThe uploaded draft must satisfy the 1,500-character limit — the 40,000-character ceiling is not the\nconstraint that applies here.\n\n1. When the draft is complete, measure its length in **characters** — not tokens, not words, not\n bytes.\n2. If it exceeds 1,500 characters, condense it: remove redundancy, tighten the prose, and drop\n examples before anything else.\n3. Keep all four required topics (naming convention, location, key content, skip guidance) and the\n single-paragraph form. Never meet the budget by dropping a required topic, and never truncate the\n paragraph mid-sentence.\n4. Re-measure after condensing and repeat until the draft is at most 1,500 characters.\n\n## Return\n\nReturn a brief summary of what was learned about the project's implementation-record conventions (naming, location, required sections), citing the key files inspected, and confirm the draft was written to `{docs_dir}/standards/documentation_instructions.md`.\n\nAlso report the draft's final length in characters, the applicable maximum (1,500 characters),\nwhether the draft was condensed to meet that maximum (`condensed`: true/false), and — when it was\ncondensed — the reason it needed condensing.\n",
776
777
  "learn-e2e-testing.md": "## Objective\n\nDetect whether an E2E testing framework exists in the codebase, document how to run and write E2E tests, then draft `e2e_testing_instructions` for the project config.\n\n## Instructions\n\n### Phase 1 — Detect E2E Framework\n\nSearch for config files and indicators:\n- **Playwright**: Search for `playwright.config.ts`, `playwright.config.js`, `@playwright/test` in `package.json`\n- **Cypress**: Search for `cypress.json`, `cypress.config.*`, `cypress/` directory\n- **Selenium/WebDriver**: Search for `selenium` in `requirements.in` or `package.json`\n- **Puppeteer**: Search for `puppeteer` in `package.json`\n- **TestCafe**: Search for `.testcaferc.json`\n\nAlso read `package.json` for E2E-related scripts and search for test directories containing E2E tests.\n\nIf NO E2E testing framework is detected, write \"No E2E testing framework detected in this repository.\" to `{docs_dir}/standards/e2e_testing_instructions.md` and stop.\n\nIf there is nothing repository-specific to cite, say that no repository evidence was found and write a short conservative standard; do not invent files, commands, or conventions.\n\n### Phase 2 — Explore E2E Testing Conventions\n\n1. **Test Execution**: Read the E2E config file and `package.json` scripts to determine exact commands (all tests, single file, headed/headless), prerequisites (server running, database seeded), and environment requirements.\n\n2. **Test Patterns**: Read 2-3 representative E2E test files in `tests/playwright/` to identify structure (page objects, fixtures, helpers), login/auth flows, test data setup/teardown, async waiting strategies, and selector patterns.\n\n3. **Common Pitfalls**: Search for hard-coded waits (`setTimeout`, `page.waitForTimeout`), test isolation issues, and browser state management patterns across E2E test files.\n\n### Phase 3 — Draft\n\nDraft `e2e_testing_instructions` as clear, actionable instructions for an AI agent writing E2E tests. Cover:\n- How to run tests (exact commands, prerequisites)\n- Test structure and organization\n- Authentication and setup patterns\n- How to wait for async operations (never hard-coded sleeps)\n- Common pitfalls with browser automation\n- Guards against common AI weaknesses: flaky tests, brittle selectors, hard-coded waits\n\nWrite the draft to `{docs_dir}/standards/e2e_testing_instructions.md`.\n\n## Length Budget\n\nThe platform ceiling for a configuration field is **40,000 characters**, and the server enforces it\nat upload time: a draft over the limit is rejected outright and ``e2e_testing_instructions`` is simply not learned. Bound\nthe draft here, at write time, rather than discovering the limit through a failed upload.\n\n1. When the draft is complete, measure its length in **characters** — not tokens, not words, not\n bytes.\n2. If it exceeds 40,000 characters, condense it: remove redundancy, collapse repetitive passages, and\n shorten or drop verbose code examples.\n3. Keep every required section listed above. Never meet the budget by deleting a required section,\n and never truncate the draft mid-sentence.\n4. Re-measure after condensing and repeat until the draft is at most 40,000 characters.\n\n## Return\n\nReturn a brief summary of what was learned about the project's E2E testing setup (framework detected, run commands, test patterns) — or state that no framework was detected — citing the key files inspected, and confirm the draft was written to `{docs_dir}/standards/e2e_testing_instructions.md`.\n\nAlso report the draft's final length in characters, the applicable maximum (40,000 characters),\nwhether the draft was condensed to meet that maximum (`condensed`: true/false), and — when it was\ncondensed — the reason it needed condensing.\n",
777
778
  "learn-frontend-correctness.md": "## Objective\n\nExplore the codebase to identify correctness standards for frontend code, then draft the corresponding correctness standards document.\n\n## Target Type\n\n- **Type**: `frontend_correctness`\n- **Field name**: `frontend_correctness_standards`\n- **Scope**: JS, TS, JSX, TSX files: React/Vue/Angular/Svelte components, client-side logic, state management.\n\n## Instructions\n\n### Phase 1 — Explore Correctness Patterns\n\nFocus on implementation correctness: how to write code that is correct, idiomatic, and robust within this project's conventions.\n\n1. **File Type Detection**: Search by filename pattern for files matching `**/*.js`, `**/*.ts`, `**/*.jsx`, `**/*.tsx` (excluding `node_modules/` and `build/`). If very few or no files exist, note this and draft minimal instructions.\n\n2. **Convention Analysis**: Read 3-5 representative frontend files to identify:\n - Structure patterns (imports, exports, class structure, function ordering)\n - Naming conventions (variables, functions, classes, files)\n - Framework conventions and idioms\n - Best practices followed\n - Issues and inconsistencies\n\n### Phase 2 — Draft\n\nDraft correctness standards as clear, actionable instructions for an AI code generation agent. Cover:\n- Code structure and organization requirements\n- Naming conventions to follow\n- Framework-specific patterns and idioms\n- Security requirements relevant to this code type\n- Performance considerations\n- Common mistakes to avoid\n- Guards against common AI weaknesses: duplicative code, verbose implementations, security vulnerabilities\n\nWrite the draft to `{docs_dir}/standards/frontend_correctness_standards.md`.\n\n## Length Budget\n\nThe platform ceiling for a configuration field is **40,000 characters**, and the server enforces it\nat upload time: a draft over the limit is rejected outright and ``frontend_correctness_standards`` is simply not learned. Bound\nthe draft here, at write time, rather than discovering the limit through a failed upload.\n\n1. When the draft is complete, measure its length in **characters** — not tokens, not words, not\n bytes.\n2. If it exceeds 40,000 characters, condense it: remove redundancy, collapse repetitive passages, and\n shorten or drop verbose code examples.\n3. Keep every required section listed above. Never meet the budget by deleting a required section,\n and never truncate the draft mid-sentence.\n4. Re-measure after condensing and repeat until the draft is at most 40,000 characters.\n\n## Return\n\nReturn a brief summary of what was learned about frontend correctness conventions (structure, naming, framework idioms), citing the key files inspected, and confirm the draft was written to `{docs_dir}/standards/frontend_correctness_standards.md`.\n\nAlso report the draft's final length in characters, the applicable maximum (40,000 characters),\nwhether the draft was condensed to meet that maximum (`condensed`: true/false), and — when it was\ncondensed — the reason it needed condensing.\n",
778
- "learn-repository-confirmations.md": "## Objective\n\nApply the configuration fields that the server requires a human to confirm — in **one** batched round\nat the very end of the run, after everything that could be applied unattended already has been.\n\nFields carrying `requires_confirmation: true` can never be written on derivation alone: the\nrequirement is a server-side registry property, not a client-side courtesy. This task is where the\nhuman is asked, exactly once, with the full run behind them.\n\nTwo of those fields describe the repository's MCP servers. `selected_mcp_slugs` picks Bridge's\ncurated validation manuals; `learned_mcp_guidance` holds repository-local generic guidance for the\nservers Bridge has no manual for. Both are fed by one local discovery pass, described in Step 2, that\nyou — the agent running this task, acting as the repository's own MCP client — perform entirely on\nthe local machine.\n\n## Operating rules\n\n1. **One question, not one per field.** Every candidate is presented together in a single round.\n2. **Only explicitly approved values are applied.** Silence is not approval.\n3. **Never stall.** If no human response can be obtained, omit the unconfirmed fields, report them,\n and finish successfully.\n4. **This step never invalidates the run.** The learned fields were already uploaded by earlier\n steps. A decline, a rejection, or a conflict here is a reportable outcome for that one field — it\n never undoes or discards anything already applied.\n5. **Discovery is local and read-only.** Every MCP server is enumerated, introspected, and described\n by the local agent. Bridge's backend must never call a third-party MCP server, and nothing that\n leaves this step may carry a credential.\n\n## Step 1 — Read the manifest once\n\n1. Call the `get_install_manifest` MCP tool **exactly once**, with `save_locally: false` — this is a\n confirmation round, not an install artifact worth writing to disk.\n2. Keep the returned `snapshot_token` **verbatim**. The apply call in Step 4 must present that same\n token. Do not re-read the manifest before applying; a fresh read invalidates the token you are\n about to use.\n3. Select candidates from the manifest's field groups using the manifest's own metadata:\n - the field's `requires_confirmation` is `true`, **and**\n - the field's `is_set` is `false`.\n\n A confirmation-required field that is already set is **not** a candidate: record it as\n `skipped_existing` and leave it alone. Do not maintain your own list of which fields require\n confirmation — the manifest is the authority, so a field the server adds later is picked up here\n with no change to this instruction.\n\n This rule is applied to `selected_mcp_slugs` and to `learned_mcp_guidance` **independently**. One\n of them being already set says nothing about the other: an already-set field is `skipped_existing`\n while its sibling can still be a candidate. Discovery (Step 2) still runs and its outcomes are still\n reported for a `skipped_existing` field, but that field is never merged into, appended to, cleared,\n or written by this task.\n\n## Step 2 — Derive a proposed value for each candidate\n\n### Discover the repository's configured MCP servers\n\nRun this discovery pass once, before deriving either MCP field. Its output — one de-duplicated,\nscrubbed entry per configured server — feeds both `selected_mcp_slugs` and `learned_mcp_guidance`\nand is reported under `mcp_discovery` in the Return.\n\n#### Sources: repository-local only\n\nInspect **only** these repository sources:\n\n- the repository-root `.mcp.json`,\n- the repository-root `.cursor/mcp.json`, and\n- repository dependency and configuration files — `package.json` dependencies and similar\n dependency declarations, plus other safe configuration markers checked into the repository.\n\nUser-level and global MCP configurations (a home-directory or editor-wide MCP registration, a\nper-user settings file) are **explicitly excluded**: they describe the person's machine, not the\nrepository, and must never be inspected or cited.\n\n`.mcp.json` and `.cursor/mcp.json` are **independent evidence sources**:\n\n- A **missing** file contributes no evidence. It is not an error and is not reported as one.\n- An **unreadable or malformed** file produces one **non-blocking sanitized warning** naming only its\n safe repository-relative path and its condition (for example `.cursor/mcp.json: malformed JSON`).\n Never quote the file's content in the warning.\n- When any one source is unavailable, discovery **continues** through the other registration file,\n the dependency declarations, and the safe configuration markers. Never infer that the repository\n has no MCP servers merely because one source could not be used.\n\n#### Server identity, de-duplication, and conflicts\n\n- The **configured server key** — the key under which the server is registered — is the server's\n identity.\n- Equivalent registrations of the same server in both project files are **de-duplicated into one\n entry** that retains both safe source paths as evidence.\n- Two registrations under the same key whose **non-secret metadata conflicts** (a different package,\n command, or transport kind) become **one conflict-marked entry**. Do not call `tools/list` for a\n conflict-marked entry, and never persist anything for it unless the human explicitly approves the\n conflict-marked proposal in the batched round of Step 3.\n\n#### Introspection is the local agent's job\n\n- For each de-duplicated entry that is **reachable**, you — acting as the MCP client, through the\n repository's own configuration — call that server's `tools/list` **at most once**, and record only a\n **bounded summary**: the server key or a safe label, the tool names, and short non-sensitive\n descriptions.\n- **Bridge's backend must never call a third-party MCP server.** Introspection happens on the local\n machine only. There is no retry loop and no backend fallback: if the one `tools/list` attempt does\n not answer, the server is unreachable for this run.\n- An **unreachable** server is still a **successful discovery**. Record it with the exact outcome\n `unreachable; configuration-only evidence`, mark its tool metadata unavailable, and cite only its\n scrubbed configuration, dependency, or marker evidence. Unreachability never fails the learn run.\n- Never retain tool schemas, command arguments, transport settings, arbitrary server responses, or\n raw `tools/list` payloads — not in evidence, not in confirmation text, not in drafted guidance, not\n in diagnostics, and not in any persistence payload.\n\n#### Scrub boundary: nothing leaves this step with a secret in it\n\nBefore any discovered evidence is **presented**, **drafted** into guidance, or **submitted**, scrub\nit. Remove, without exception:\n\n- every environment value and every environment-variable reference (the `env` block of a\n registration, dollar-brace and bare-dollar variable references, and any value read from the process environment);\n- every token, key, and password field, whatever it is named;\n- `Authorization` headers and basic-auth data;\n- private keys;\n- connection strings;\n- credential-bearing URLs (a URL carrying a token, key, or user:password segment); and\n- any value that cannot be rendered safely.\n\nReplace anything removed with a high-visibility placeholder such as `[REDACTED_TOKEN]`, following the\n`gather-and-attach-materials` redaction precedent, and never echo the original. Retained evidence is\nlimited to: the server identity, safe repository-relative configuration paths, safe dependency and\nconfiguration markers, and bounded non-sensitive tool names with short descriptions. Nothing else\nsurvives the boundary.\n\n#### Dispatch: curated slug or generic guidance, decided deterministically\n\nRoute every discovered server to exactly one destination:\n\n1. **Curated** — the server's stable server key, package name, or command **exactly matches** a\n supported catalog slug listed in the manifest's supported values for `selected_mcp_slugs`. Propose\n that slug on the `selected_mcp_slugs` path below.\n2. **Generic** — every other server. Draft repository-local generic guidance on the\n `learned_mcp_guidance` path below.\n\nCurated matching is exact-identity only. **Heuristic name similarity, approximate slug matching, and\nLLM inference are prohibited** when choosing a curated slug: a near miss is a generic server, never a\nguessed slug. A curated match proposes **only the slug**; it never regenerates, copies, replaces, or\noverwrites the curated manual body, which stays Bridge's.\n\n### `selected_mcp_slugs`\n\nMCP validation manuals are supplied to the final plan reviewer. Propose them **only** from clear\nrepository markers, and record the evidence you used for each:\n\n| Evidence in the repository | Proposed slug |\n| --- | --- |\n| SFCC cartridges, or Salesforce Commerce Cloud markers | `b2c-commerce-developer` |\n| A Playwright configuration file | `playwright-mcp` |\n| PWA Kit markers | `pwa-kit-mcp` |\n\nThe table above is the explicit marker mapping. Beyond it, the general rule from the discovery pass\napplies to the **whole** curated catalog: a configured MCP server whose stable server key, package\nname, or command exactly matches a supported catalog slug is proposed as that slug, with the\nscrubbed discovery evidence cited. Any other configured server is **not** a curated candidate; it\nroutes to `learned_mcp_guidance`.\n\nRules:\n\n- Every proposed slug must come from the manifest's supported values for the field. Never propose a\n slug that is not in the catalog — the server rejects unknown slugs outright.\n- Every proposed slug needs concrete evidence, named in the question. Cite the file or marker, or the\n scrubbed discovery entry.\n- Curated mappings propose only the slug through `selected_mcp_slugs`. Never regenerate, copy, replace,\n or overwrite the curated manual body.\n- **No clear marker means the field is `not_applicable`** — report it as such and omit it from the\n question. Do not guess, and do not propose a manual on weak evidence: a wrong manual degrades the\n reviewer's behavior.\n- If `selected_mcp_slugs` is already set it is `skipped_existing`: discovery outcomes may still be\n reported, but the stored value is never merged, appended, cleared, or written by this task.\n\n### `learned_mcp_guidance`\n\nEach discovered server that the dispatch rule routed to **generic** gets one drafted entry. The entry's\nexact shape, field limits, and closed vocabularies are governed by the manifest's metadata for\n`learned_mcp_guidance` — read the field's `guidance` and `validation_summary` from the manifest you\nalready hold, and draft to them. Do not hard-code the field's object keys or its scope vocabulary\nfrom memory; the manifest is the authority, exactly as it is for candidate selection.\n\nEvery generic draft must, in prose:\n\n- explain **what the MCP is**;\n- summarize its **relevant capabilities**, from the bounded tool summary when the server was reachable\n and from the configuration and dependency markers otherwise;\n- identify its **concern** — the kind of work it bears on;\n- state **how and where it is useful** in this repository, so its usefulness is self-justifying rather\n than an opaque tag;\n- give a **ticket-scope classification** drawn from the manifest's vocabulary for the field, justified\n by the usefulness write-up (a Playwright-alternative browser-testing MCP is frontend-facing); and\n- cite **one concise scrubbed evidence summary**.\n\nConstraints on the draft:\n\n- Keep every value within the manifest's stated limits. Raw configuration, raw server responses,\n credential material, and environment references never appear in guidance or evidence.\n- Operational discovery metadata — reachability flags, tool collections, configuration paths — must\n **not** be added as ad hoc persisted object keys. Safe source-path information belongs only inside\n the concise evidence content the manifest permits.\n- A conflict-marked server's draft is labeled as such and is never persisted without explicit approval.\n- If `learned_mcp_guidance` is already set it is `skipped_existing`: discovery outcomes may still be\n reported, but the stored value is never merged, appended, cleared, or written by this task.\n- If the manifest does not carry `learned_mcp_guidance` at all, Step 1's rule holds: the field is not\n a candidate, nothing is submitted for it, and each generic draft is reported in `mcp_discovery` with\n outcome `field_unavailable` so the discovery is not lost.\n\n### `project_description`\n\nIf `project_description` is still unset after install, derive a concise candidate description from the\nlocal codebase, following the field's manifest `guidance`. If it is already set, it is\n`skipped_existing`.\n\n### Any other confirmation-required candidate\n\nFor a candidate this instruction does not name explicitly, follow the field's manifest `guidance` to\nderive a value, and apply the same rule: no clear evidence means omit it rather than guess.\n\n## Step 3 — Ask once\n\nPresent **all** candidates in a **single** batched question. Separate per-field confirmation rounds\nare prohibited — the entire point of this step is that the human is interrupted exactly once.\n\nCurated-slug proposals, generic-guidance drafts, and every other confirmation-required candidate\nappear together in that one question. There is no second round: an entry that goes unanswered stays\nunapproved and is never inferred as accepted.\n\nFor each candidate include:\n\n- the **field name**,\n- the **proposed value**,\n- the **evidence** behind the proposal, and\n- the **impact** of setting it — what changes about Bridge's behavior once the value is applied.\n\nFor each discovered MCP proposal — a curated slug or a generic draft — also include:\n\n- its **destination field** (`selected_mcp_slugs` or `learned_mcp_guidance`),\n- the **proposed value or draft** in full,\n- the **scrubbed cited evidence**,\n- the **dispatch reason** — the exact curated identity match, or \"no exact curated match\", and\n- an explicit label when the entry is **conflict-marked** or **unreachable**, using the exact wording\n `unreachable; configuration-only evidence` for the latter.\n\nLet the human approve or decline each field individually within that one round — and, within the two\nMCP fields, approve or decline **each discovered server's entry individually**. Approval is per entry,\nnever per field-level array.\n\nSanitized warnings about an unreadable or malformed source are shown alongside, clearly separate from\nthe approvable entries: a warning never fabricates a discovered server and never suppresses evidence\ngathered from the healthy sources.\n\n## Step 4 — Apply the approved fields (one call)\n\n1. Make **at most one** `apply_install_manifest` call, passing the exact `snapshot_token` from Step 1.\n2. Submit every approved field in the `fields` map as `{ \"value\": <approved value>, \"confirmed\": true }`.\n The `confirmed: true` metadata is what satisfies the server's confirmation requirement.\n3. **Omit** declined fields and unanswered fields entirely — do not send them with `confirmed: false`,\n and do not send a placeholder value.\n4. If no field was approved, make no apply call at all.\n5. The apply is partial-tolerant. A field returned in the `rejected` bucket, or in the `conflict`\n bucket because it changed since the manifest was read, is reported as that field's outcome — the\n other approved fields still commit, and the learned fields uploaded earlier are untouched. Do not\n retry the whole apply because one field failed.\n\nFor the two MCP fields, build each array from the per-entry answers:\n\n- `selected_mcp_slugs` is built **solely** from the explicitly approved curated entries.\n- `learned_mcp_guidance` is built **solely** from the explicitly approved generic entries, each in the\n manifest-defined entry shape and within its validation limits.\n- Every declined or unanswered entry is **excluded** from its array — no placeholder, no\n `confirmed: false`.\n- Each non-empty approved subset is submitted as `{ \"value\": <approved subset>, \"confirmed\": true }`\n in the same `fields` map, alongside any other approved confirmation-required field, in the single\n call above with the unchanged snapshot token.\n- When a field's approved subset is empty — including when every proposal for it was declined or\n unanswered — **omit that field** from the call.\n- Server-side validation remains the final boundary: it enforces the supported curated slugs, the\n generic-guidance shape, the confirmation requirement, and snapshot conflicts. This task adds no\n manifest, registry, backend, or catalog-exposure change to get around it.\n\n## Step 5 — Headless safety\n\nIf interaction is unavailable, or no response can be obtained (a non-interactive or headless\nsession):\n\n- Do **not** wait indefinitely and do **not** abandon the run.\n- Omit **every** unconfirmed field from the apply.\n- Report each candidate as `pending human input`, using that exact phrase.\n- Finish successfully. Everything else the run applied stays applied — an unconfirmed field never\n blocks a confirmed or already-uploaded one.\n\nEvery unconfirmed MCP proposal — each curated slug and each generic draft — is reported as\n`pending human input` too. An unset `selected_mcp_slugs` or `learned_mcp_guidance` whose entries could\nnot be confirmed lands in `pending_human_input`; an already-set one stays `skipped_existing`. A headless\nrun issues **no** apply call for those unconfirmed fields, performs no retry and no backend fallback,\nand still finishes successfully.\n\n## Return\n\nReturn a single JSON object listing each field name in its outcome bucket, plus one `mcp_discovery`\narray describing the discovery pass:\n\n```json\n{\n \"approved\": [],\n \"applied\": [],\n \"declined\": [],\n \"pending_human_input\": [],\n \"not_applicable\": [],\n \"skipped_existing\": [],\n \"conflict\": [],\n \"rejected\": [],\n \"mcp_discovery\": []\n}\n```\n\n- `approved` — the human approved the proposed value this round.\n- `applied` — the server committed the value.\n- `declined` — the human explicitly rejected the proposal.\n- `pending_human_input` — presented but unanswered, or never presentable (headless).\n- `not_applicable` — no clear evidence supported a proposal, so none was made.\n- `skipped_existing` — already set; never re-proposed.\n- `conflict` — changed since the manifest snapshot was read.\n- `rejected` — failed server-side validation.\n\n`mcp_discovery` carries **one entry per de-duplicated discovered server**. Each entry names the server\nkey, its **routing** (`curated` with the matched slug, or `generic`), its **outcome** — `approved`,\n`declined`, `pending human input`, `skipped_existing`, `conflict-marked`,\n`unreachable; configuration-only evidence`, or `field_unavailable` — and its bounded, scrubbed\nevidence: safe source paths, safe markers, and non-sensitive tool names only. The eight field buckets\nabove are unchanged; `mcp_discovery` is additive and is the only place discovery detail is reported.\n",
779
+ "learn-repository-confirmations.md": "## Objective\n\nApply the configuration fields that the server requires a human to confirm — in **one** batched round\nat the very end of the run, after everything that could be applied unattended already has been.\n\nFields carrying `requires_confirmation: true` can never be written on derivation alone: the\nrequirement is a server-side registry property, not a client-side courtesy. This task is where the\nhuman is asked, exactly once, with the full run behind them.\n\nTwo of those fields describe the repository's MCP servers. `selected_mcp_slugs` picks Bridge's\ncurated validation manuals; `learned_mcp_guidance` holds repository-local generic guidance for the\nservers Bridge has no manual for. Both are fed by one local discovery pass, described in Step 2, that\nyou — the agent running this task, acting as the repository's own MCP client — perform entirely on\nthe local machine.\n\n## Operating rules\n\n1. **One question, not one per field.** Every candidate is presented together in a single round.\n2. **Only explicitly approved values are applied.** Silence is not approval.\n3. **Never stall.** If no human response can be obtained, omit the unconfirmed fields, report them,\n and finish successfully.\n4. **This step never invalidates the run.** The learned fields were already uploaded by earlier\n steps. A decline, a rejection, or a conflict here is a reportable outcome for that one field — it\n never undoes or discards anything already applied.\n5. **Discovery is local and read-only.** Every MCP server is enumerated, introspected, and described\n by the local agent. Bridge's backend must never call a third-party MCP server, and nothing that\n leaves this step may carry a credential.\n\n## Step 1 — Read the manifest once\n\n1. Call the `get_install_manifest` MCP tool **exactly once**, with `save_locally: false` — this is a\n confirmation round, not an install artifact worth writing to disk.\n2. Keep the returned `snapshot_token` **verbatim**. The apply call in Step 4 must present that same\n token. Do not re-read the manifest before applying; a fresh read invalidates the token you are\n about to use.\n3. Select candidates from the manifest's field groups using the manifest's own metadata:\n - the field's `requires_confirmation` is `true`, **and**\n - the field's `is_set` is `false`.\n\n A confirmation-required field that is already set is **not** a candidate: record it as\n `skipped_existing` and leave it alone. Do not maintain your own list of which fields require\n confirmation — the manifest is the authority, so a field the server adds later is picked up here\n with no change to this instruction.\n\n This rule is applied to `selected_mcp_slugs` and to `learned_mcp_guidance` **independently**. One\n of them being already set says nothing about the other: an already-set field is `skipped_existing`\n while its sibling can still be a candidate. Discovery (Step 2) still runs and its outcomes are still\n reported for a `skipped_existing` field, but that field is never merged into, appended to, cleared,\n or written by this task.\n\n## Step 2 — Derive a proposed value for each candidate\n\n### Discover the repository's configured MCP servers\n\nRun this discovery pass once, before deriving either MCP field. Its output — one de-duplicated,\nscrubbed entry per configured server — feeds both `selected_mcp_slugs` and `learned_mcp_guidance`\nand is reported under `mcp_discovery` in the Return.\n\n#### Sources: repository-local only\n\nInspect **only** these repository sources:\n\n- the repository-root `.mcp.json`,\n- the repository-root `.cursor/mcp.json`, and\n- repository dependency and configuration files — `package.json` dependencies and similar\n dependency declarations, plus other safe configuration markers checked into the repository, and\n- the repository's own `.bridge/config`, a narrow read-only **identity source** (see Bridge's own\n server below). Read it only to recognize the Bridge MCP target. Never retain launch settings,\n credentials, or unrelated configuration from it.\n\nUser-level and global MCP configurations (a home-directory or editor-wide MCP registration, a\nper-user settings file) are **explicitly excluded**: they describe the person's machine, not the\nrepository, and must never be inspected or cited.\n\n`.mcp.json` and `.cursor/mcp.json` are **independent evidence sources**:\n\n- A **missing** file contributes no evidence. It is not an error and is not reported as one. This\n includes a missing `.bridge/config`.\n- An **unreadable or malformed** file produces one **non-blocking sanitized warning** naming only its\n safe repository-relative path and its condition (for example `.cursor/mcp.json: malformed JSON`).\n Never quote the file's content in the warning. This includes `.bridge/config`.\n- When any one source is unavailable, discovery **continues** through the other registration file,\n the dependency declarations, and the safe configuration markers. Never infer that the repository\n has no MCP servers merely because one source could not be used.\n\n#### Bridge's own server is never discovered\n\nBridge's own MCP server is always present, so it is never a candidate. Before introspection and\ndispatch, drop every entry that matches either rule, under any configured key:\n\n- its package is `@bridge_gpt/mcp-server`, matched case-insensitively and including versioned forms; or\n- its key is one of the fixed Bridge keys `bridge-api`, `bridge-gpt`, `bridge`, or `bapi`.\n\n`.bridge/config` holds `[[mcp]] target = \"bapi\"`. That entry has no server-key property. It maps to\nthe Bridge targets `bridge`, legacy `bridge-api`, and `bapi`, so use it only to recognize them.\n\nA dropped entry gets no `tools/list` call, no curated slug, no generic draft, no question, and no\n`mcp_discovery` entry. If `.bridge/config` is missing, unreadable, or malformed, package matching and\nthe fixed keys still apply. Continue from the healthy sources and never infer absence.\n\n#### Server identity, de-duplication, and conflicts\n\n- The **configured server key** — the key under which the server is registered — is the server's\n identity.\n- Equivalent registrations of the same server in both project files are **de-duplicated into one\n entry** that retains both safe source paths as evidence.\n- Two registrations under the same key whose **non-secret metadata conflicts** (a different package,\n command, or transport kind) become **one conflict-marked entry**. Do not call `tools/list` for a\n conflict-marked entry, and never persist anything for it unless the human explicitly approves the\n conflict-marked proposal in the batched round of Step 3.\n\n#### Introspection is the local agent's job\n\n- For each de-duplicated entry that is **reachable**, you — acting as the MCP client, through the\n repository's own configuration — call that server's `tools/list` **at most once**, and record only a\n **bounded summary**: the server key or a safe label, the tool names, and short non-sensitive\n descriptions.\n- **Bridge's backend must never call a third-party MCP server.** Introspection happens on the local\n machine only. There is no retry loop and no backend fallback: if the one `tools/list` attempt does\n not answer, the server is unreachable for this run.\n- An **unreachable** server is still a **successful discovery**. Record it with the exact outcome\n `unreachable; configuration-only evidence`, mark its tool metadata unavailable, and cite only its\n scrubbed configuration, dependency, or marker evidence. Unreachability never fails the learn run.\n- Never retain tool schemas, command arguments, transport settings, arbitrary server responses, or\n raw `tools/list` payloads — not in evidence, not in confirmation text, not in drafted guidance, not\n in diagnostics, and not in any persistence payload.\n\n#### Scrub boundary: nothing leaves this step with a secret in it\n\nBefore any discovered evidence is **presented**, **drafted** into guidance, or **submitted**, scrub\nit. Remove, without exception:\n\n- every environment value and every environment-variable reference (the `env` block of a\n registration, dollar-brace and bare-dollar variable references, and any value read from the process environment);\n- every token, key, and password field, whatever it is named;\n- `Authorization` headers and basic-auth data;\n- private keys;\n- connection strings;\n- credential-bearing URLs (a URL carrying a token, key, or user:password segment); and\n- any value that cannot be rendered safely.\n\nReplace anything removed with a high-visibility placeholder such as `[REDACTED_TOKEN]`, following the\n`gather-and-attach-materials` redaction precedent, and never echo the original. Retained evidence is\nlimited to: the server identity, safe repository-relative configuration paths, safe dependency and\nconfiguration markers, and bounded non-sensitive tool names with short descriptions. Nothing else\nsurvives the boundary.\n\n#### Dispatch: curated slug or generic guidance, decided deterministically\n\nRoute every discovered server to exactly one destination:\n\n1. **Curated** — the server's stable server key, package name, or command **exactly matches** a\n supported catalog slug listed in the manifest's supported values for `selected_mcp_slugs`. Propose\n that slug on the `selected_mcp_slugs` path below.\n2. **Generic** — every other server. Draft repository-local generic guidance on the\n `learned_mcp_guidance` path below.\n\nCurated matching is exact-identity only. **Heuristic name similarity, approximate slug matching, and\nLLM inference are prohibited** when choosing a curated slug: a near miss is a generic server, never a\nguessed slug. A curated match proposes **only the slug**; it never regenerates, copies, replaces, or\noverwrites the curated manual body, which stays Bridge's.\n\n### `selected_mcp_slugs`\n\nMCP validation manuals are supplied to the final plan reviewer. Propose them **only** from clear\nrepository markers, and record the evidence you used for each:\n\n| Evidence in the repository | Proposed slug |\n| --- | --- |\n| SFCC cartridges, or Salesforce Commerce Cloud markers | `b2c-commerce-developer` |\n| A Playwright configuration file | `playwright-mcp` |\n| PWA Kit markers | `pwa-kit-mcp` |\n\nThe table above is the explicit marker mapping. Beyond it, the general rule from the discovery pass\napplies to the **whole** curated catalog: a configured MCP server whose stable server key, package\nname, or command exactly matches a supported catalog slug is proposed as that slug, with the\nscrubbed discovery evidence cited. Any other configured server is **not** a curated candidate; it\nroutes to `learned_mcp_guidance`.\n\nRules:\n\n- Every proposed slug must come from the manifest's supported values for the field. Never propose a\n slug that is not in the catalog — the server rejects unknown slugs outright.\n- Every proposed slug needs concrete evidence, named in the question. Cite the file or marker, or the\n scrubbed discovery entry.\n- Curated mappings propose only the slug through `selected_mcp_slugs`. Never regenerate, copy, replace,\n or overwrite the curated manual body.\n- **No clear marker means the field is `not_applicable`** — report it as such and omit it from the\n question. Do not guess, and do not propose a manual on weak evidence: a wrong manual degrades the\n reviewer's behavior.\n- If `selected_mcp_slugs` is already set it is `skipped_existing`: discovery outcomes may still be\n reported, but the stored value is never merged, appended, cleared, or written by this task.\n\n### `learned_mcp_guidance`\n\nEach discovered server that the dispatch rule routed to **generic** gets one drafted entry. The entry's\nexact shape, field limits, and closed vocabularies are governed by the manifest's metadata for\n`learned_mcp_guidance` — read the field's `guidance` and `validation_summary` from the manifest you\nalready hold, and draft to them. Do not hard-code the field's object keys or its scope vocabulary\nfrom memory; the manifest is the authority, exactly as it is for candidate selection.\n\nEvery generic draft must, in prose:\n\n- explain **what the MCP is**;\n- summarize its **relevant capabilities**, from the bounded tool summary when the server was reachable\n and from the configuration and dependency markers otherwise;\n- identify its **concern** — the kind of work it bears on;\n- state **how and where it is useful** in this repository, so its usefulness is self-justifying rather\n than an opaque tag;\n- give a **ticket-scope classification** drawn from the manifest's vocabulary for the field, justified\n by the usefulness write-up (a Playwright-alternative browser-testing MCP is frontend-facing); and\n- cite **one concise scrubbed evidence summary**.\n\nConstraints on the draft:\n\n- Keep every value within the manifest's stated limits. Raw configuration, raw server responses,\n credential material, and environment references never appear in guidance or evidence.\n- Operational discovery metadata — reachability flags, tool collections, configuration paths — must\n **not** be added as ad hoc persisted object keys. Safe source-path information belongs only inside\n the concise evidence content the manifest permits.\n- A conflict-marked server's draft is labeled as such and is never persisted without explicit approval.\n- If `learned_mcp_guidance` is already set it is `skipped_existing`: discovery outcomes may still be\n reported, but the stored value is never merged, appended, cleared, or written by this task.\n- If the manifest does not carry `learned_mcp_guidance` at all, Step 1's rule holds: the field is not\n a candidate, nothing is submitted for it, and each generic draft is reported in `mcp_discovery` with\n outcome `field_unavailable` so the discovery is not lost.\n\n### `project_description`\n\nIf `project_description` is still unset after install, derive a concise candidate description from the\nlocal codebase, following the field's manifest `guidance`. If it is already set, it is\n`skipped_existing`.\n\n### Any other confirmation-required candidate\n\nFor a candidate this instruction does not name explicitly, follow the field's manifest `guidance` to\nderive a value, and apply the same rule: no clear evidence means omit it rather than guess.\n\n## Step 3 — Ask once\n\nPresent **all** candidates in a **single** batched question. Separate per-field confirmation rounds\nare prohibited — the entire point of this step is that the human is interrupted exactly once.\n\nCurated-slug proposals, generic-guidance drafts, and every other confirmation-required candidate\nappear together in that one question. There is no second round: an entry that goes unanswered stays\nunapproved and is never inferred as accepted.\n\nFor each candidate include:\n\n- the **field name**,\n- the **proposed value**,\n- the **evidence** behind the proposal, and\n- the **impact** of setting it — what changes about Bridge's behavior once the value is applied.\n\nFor each discovered MCP proposal — a curated slug or a generic draft — also include:\n\n- its **destination field** (`selected_mcp_slugs` or `learned_mcp_guidance`),\n- the **proposed value or draft** in full,\n- the **scrubbed cited evidence**,\n- the **dispatch reason** — the exact curated identity match, or \"no exact curated match\", and\n- an explicit label when the entry is **conflict-marked** or **unreachable**, using the exact wording\n `unreachable; configuration-only evidence` for the latter.\n\nLet the human approve or decline each field individually within that one round — and, within the two\nMCP fields, approve or decline **each discovered server's entry individually**. Approval is per entry,\nnever per field-level array.\n\nSanitized warnings about an unreadable or malformed source are shown alongside, clearly separate from\nthe approvable entries: a warning never fabricates a discovered server and never suppresses evidence\ngathered from the healthy sources.\n\n## Step 4 — Apply the approved fields (one call)\n\n1. Make **at most one** `apply_install_manifest` call, passing the exact `snapshot_token` from Step 1.\n2. Submit every approved field in the `fields` map as `{ \"value\": <approved value>, \"confirmed\": true }`.\n The `confirmed: true` metadata is what satisfies the server's confirmation requirement.\n3. **Omit** declined fields and unanswered fields entirely — do not send them with `confirmed: false`,\n and do not send a placeholder value.\n4. If no field was approved, make no apply call at all.\n5. The apply is partial-tolerant. A field returned in the `rejected` bucket, or in the `conflict`\n bucket because it changed since the manifest was read, is reported as that field's outcome — the\n other approved fields still commit, and the learned fields uploaded earlier are untouched. Do not\n retry the whole apply because one field failed.\n\nFor the two MCP fields, build each array from the per-entry answers:\n\n- `selected_mcp_slugs` is built **solely** from the explicitly approved curated entries.\n- `learned_mcp_guidance` is built **solely** from the explicitly approved generic entries, each in the\n manifest-defined entry shape and within its validation limits.\n- Every declined or unanswered entry is **excluded** from its array — no placeholder, no\n `confirmed: false`.\n- Each non-empty approved subset is submitted as `{ \"value\": <approved subset>, \"confirmed\": true }`\n in the same `fields` map, alongside any other approved confirmation-required field, in the single\n call above with the unchanged snapshot token.\n- When a field's approved subset is empty — including when every proposal for it was declined or\n unanswered — **omit that field** from the call.\n- Server-side validation remains the final boundary: it enforces the supported curated slugs, the\n generic-guidance shape, the confirmation requirement, and snapshot conflicts. This task adds no\n manifest, registry, backend, or catalog-exposure change to get around it.\n\n## Step 5 — Headless safety\n\nIf interaction is unavailable, or no response can be obtained (a non-interactive or headless\nsession):\n\n- Do **not** wait indefinitely and do **not** abandon the run.\n- Omit **every** unconfirmed field from the apply.\n- Report each candidate as `pending human input`, using that exact phrase.\n- Finish successfully. Everything else the run applied stays applied — an unconfirmed field never\n blocks a confirmed or already-uploaded one.\n\nEvery unconfirmed MCP proposal — each curated slug and each generic draft — is reported as\n`pending human input` too. An unset `selected_mcp_slugs` or `learned_mcp_guidance` whose entries could\nnot be confirmed lands in `pending_human_input`; an already-set one stays `skipped_existing`. A headless\nrun issues **no** apply call for those unconfirmed fields, performs no retry and no backend fallback,\nand still finishes successfully.\n\n## Return\n\nReturn a single JSON object listing each field name in its outcome bucket, plus one `mcp_discovery`\narray describing the discovery pass:\n\n```json\n{\n \"approved\": [],\n \"applied\": [],\n \"declined\": [],\n \"pending_human_input\": [],\n \"not_applicable\": [],\n \"skipped_existing\": [],\n \"conflict\": [],\n \"rejected\": [],\n \"mcp_discovery\": []\n}\n```\n\n- `approved` — the human approved the proposed value this round.\n- `applied` — the server committed the value.\n- `declined` — the human explicitly rejected the proposal.\n- `pending_human_input` — presented but unanswered, or never presentable (headless).\n- `not_applicable` — no clear evidence supported a proposal, so none was made.\n- `skipped_existing` — already set; never re-proposed.\n- `conflict` — changed since the manifest snapshot was read.\n- `rejected` — failed server-side validation.\n\n`mcp_discovery` carries **one entry per de-duplicated discovered server**. Each entry names the server\nkey, its **routing** (`curated` with the matched slug, or `generic`), its **outcome** — `approved`,\n`declined`, `pending human input`, `skipped_existing`, `conflict-marked`,\n`unreachable; configuration-only evidence`, or `field_unavailable` — and its bounded, scrubbed\nevidence: safe source paths, safe markers, and non-sensitive tool names only. The eight field buckets\nabove are unchanged; `mcp_discovery` is additive and is the only place discovery detail is reported.\n",
779
780
  "learn-repository-fan-out.md": "## Objective\n\nResearch all ten learned configuration fields for this repository **in parallel**, one isolated\nsubagent per field, and leave a bounded, upload-ready draft on disk for each field that needs one.\n\nThis step performs research only. It never uploads: the ten declarative `config_field` update steps\nthat follow this task own every write.\n\n## Operating rules (apply to the whole task)\n\n1. **Local research only.** Every field is learned by reading *this checkout* on local disk. Do not\n delegate research to the Bridge API backend or any server-side index — the backend has a vector\n index of the code, not the working tree in front of you.\n2. **One isolated subagent per missing field.** Use the host coding agent's own subagent/task\n mechanism. Each subagent gets exactly one field and does not see the others' work.\n3. **Launch before you await.** Start every missing-field subagent first, then collect results. Never\n spawn a subagent, wait for it to finish, and only then spawn the next one — a sequential\n spawn-and-wait loop defeats the entire purpose of this step.\n4. **Subagents never upload and never talk to the human.** A subagent's only outputs are its draft\n file and its structured result. All human interaction is deferred to the final confirmation step.\n5. **A failed field is not a failed run.** Isolate each failure to its own field, let the other\n subagents finish, and return a successful aggregate result naming the gap.\n\n## Step 1 — Classify each field from the ten preceding fetch results\n\nThe ten `config_field` steps immediately before this task already read the current value of every\nlearned field. Use **those results** — do not re-read the fields and do not infer state from whether\na draft file happens to exist on disk from an earlier run.\n\nFor each field, read the fetch response's `value` and `is_catalog_default` properties. Those are the\nauthoritative signals:\n\n- `value` is `null`, absent, or contains only whitespace → the field is **missing** (needs research).\n- `is_catalog_default` is `true` → the field is **missing** (needs research). The stored content is an\n unmodified Bridge-seeded catalog default, not learned knowledge; the server's guarded write permits\n replacing it while still protecting user-edited or previously learned content.\n- `value` holds any other content → the field is **populated** (already learned).\n\nIf a fetch step warned and returned no usable response at all, treat that field as **missing**.\n\nRecord every populated field as `skipped_existing` and do not spawn a subagent for it. This is what\nmakes a rerun after a partial failure cheap: only the fields that are still empty are researched\nagain.\n\n## Step 2 — Prepare the artifact targets (before any subagent starts)\n\nThe upload steps that follow this task read a fixed file path per field. Stale content at one of\nthose paths would be uploaded as if it were this run's work, so:\n\n1. For every **missing** field, delete any existing file at its draft path. A field whose subagent\n later fails must leave *no* file behind, so the declarative upload has nothing to send.\n2. For every **skipped_existing** field, write the value you just fetched to that field's draft path,\n so the unchanged upload step has a readable file. The upload carries `only_if_null: true`, so the\n server skips the write for learned or user-edited content — and if the value is a still-default\n catalog seed, re-sending the same bytes is a harmless self-copy under the widened\n null-or-default guard.\n\n## Step 3 — Fan out\n\nLaunch one subagent for every missing field, all of them, before awaiting any result. Then await all\nof them and collect each result.\n\nGive each subagent the prompt block for its field from the matrix below. Every prompt block already\ncarries the field name, the draft path, the research responsibilities, the evidence expectations, and\nthe character budget. Pass each block through verbatim, substituting `{docs_dir}` with the resolved\ndocs directory.\n\n### Shared subagent contract\n\nInclude this contract in every subagent prompt, in addition to the field-specific block:\n\n\"\"\"\nYou are researching exactly one configuration field for this repository. Read the local checkout on\ndisk — the actual files, not a summary of them. Cite concrete file paths as evidence for every claim\nyou make; a pattern you cannot point at a file for does not belong in the draft.\n\nWrite your finished draft to the draft path given below, and nothing else. Do not call any\nconfiguration-update tool, do not upload your draft anywhere, and do not ask the human any question:\nanother step owns writing and another step owns asking.\n\n**Length budget — this is a hard limit, measured in characters.**\n\n- Your draft must be at most the maximum character count stated in your field block below, measured\n in **characters** (not tokens, not words, not bytes).\n- When your draft is complete, measure its length in characters.\n- If it exceeds the budget, condense it: remove redundancy, collapse repetitive passages, and shorten\n or drop verbose code examples. Keep every required section — never meet the budget by deleting a\n required section, and never truncate mid-sentence.\n- Re-measure after condensing, and repeat until the draft is within budget.\n- The budget is enforced by the server at upload time, so a draft over the limit is rejected outright\n and the field is simply not learned. Condensing is how the field gets learned at all.\n\nReturn a JSON object:\n`{\"field_name\": \"...\", \"draft_path\": \"...\", \"character_count\": <int>, \"max_character_count\": <int>,\n\"condensed\": <bool>, \"condensation_reason\": \"<why you condensed, or empty>\"}`\n\"\"\"\n\n### Field matrix\n\nTen fields. Each row names the field, its draft path, its character budget, and the research\nresponsibilities to expand into that subagent's prompt block. The responsibilities mirror the\nmatching standalone `learn-*.md` instruction, which remains the fuller reference for that field.\n\n| Field | Draft path | Max characters | Mirrors |\n| --- | --- | --- | --- |\n| `architecture_instructions` | `{docs_dir}/standards/architecture_instructions.md` | 40000 | `learn-architecture.md` |\n| `review_instructions` | `{docs_dir}/standards/review_instructions.md` | 40000 | `learn-review-instructions.md` |\n| `documentation_instructions` | `{docs_dir}/standards/documentation_instructions.md` | 1500 | `learn-documentation-instructions.md` |\n| `unit_testing_instructions` | `{docs_dir}/standards/unit_testing_instructions.md` | 40000 | `learn-unit-testing.md` |\n| `e2e_testing_instructions` | `{docs_dir}/standards/e2e_testing_instructions.md` | 40000 | `learn-e2e-testing.md` |\n| `frontend_correctness_standards` | `{docs_dir}/standards/frontend_correctness_standards.md` | 40000 | `learn-frontend-correctness.md` |\n| `backend_correctness_standards` | `{docs_dir}/standards/backend_correctness_standards.md` | 40000 | `learn-backend-correctness.md` |\n| `template_correctness_standards` | `{docs_dir}/standards/template_correctness_standards.md` | 40000 | `learn-template-correctness.md` |\n| `style_correctness_standards` | `{docs_dir}/standards/style_correctness_standards.md` | 40000 | `learn-style-correctness.md` |\n| `design_principles` | `{docs_dir}/standards/design_principles.md` | 40000 | `learn-design-principles.md` |\n\n#### `architecture_instructions` — max 40000 characters\n\n\"\"\"\nDraft `architecture_instructions` to `{docs_dir}/standards/architecture_instructions.md`, at most\n40000 characters.\n\nExplore the codebase for architectural principles, directory conventions, design patterns, and data\nflow. Examine at least 5 representative files per area and cite file paths for every pattern.\nClassify each pattern's evidence level as `ENFORCED` (violations would be bugs), `CONVENTION`\n(commonly observed, deviations exist), or `ASPIRATIONAL` (intended, not yet consistent).\n\nCover: architectural coding patterns and layer boundaries; design patterns (factories, strategies,\nmiddleware, registries, dependency injection); dependency management; error-handling architecture;\nconfiguration management; tech-stack detection; security/auth architecture; and agent prompting\nconventions. Trace 2-3 complete request paths end to end. Do NOT document testing patterns — skip the\ntests directory entirely.\n\nRequired sections: 1. Core Principles; 2. Layered Architecture; 3. Directory Conventions; 4. Data\nFlow Patterns; 5. Technical Standards; 6. Error Handling & Monitoring; 7. Security & Authentication;\n8. Agent Prompting Conventions; 9. Integration Points; 10. AI Code Generation Guidelines.\n\nIf there is nothing repository-specific to cite, say that no repository evidence was found and\nwrite a short conservative standard; do not invent files, commands, or conventions.\n\"\"\"\n\n#### `review_instructions` — max 40000 characters\n\n\"\"\"\nDraft `review_instructions` to `{docs_dir}/standards/review_instructions.md`, at most 40000\ncharacters.\n\nFollow the responsibilities in `learn-review-instructions.md`: research what this repository's code\nreviewers actually enforce, and turn it into instructions the AI code reviewer can apply. Cite file\npaths as evidence for every rule, and preserve that instruction's required sections.\n\nIf there is nothing repository-specific to cite, say that no repository evidence was found and\nwrite a short conservative standard; do not invent files, commands, or conventions.\n\"\"\"\n\n#### `documentation_instructions` — max 1500 characters\n\n\"\"\"\nDraft `documentation_instructions` to `{docs_dir}/standards/documentation_instructions.md`, at most\n**1500 characters**.\n\nThis field's limit is far stricter than the platform's general 40000-character ceiling, because the\nserver enforces 1500 characters for this field specifically and the value is inlined verbatim into a\ngenerated plan step.\n\nProduce **a single concise prose paragraph**: no markdown headings, no bullets, no numbered lists, no\nintentional blank lines. The paragraph must cover the implementation-document file naming convention,\nwhere documentation lives, the key content to capture, and when to skip documentation.\n\nBecause 1500 characters is tight, expect to condense. Cut redundancy and examples first; keep all\nfour required topics.\n\nIf there is nothing repository-specific to cite, say that no repository evidence was found and\nwrite a short conservative standard; do not invent files, commands, or conventions.\n\"\"\"\n\n#### `unit_testing_instructions` — max 40000 characters\n\n\"\"\"\nDraft `unit_testing_instructions` to `{docs_dir}/standards/unit_testing_instructions.md`, at most\n40000 characters.\n\nFollow the responsibilities in `learn-unit-testing.md`: research this repository's unit-testing\nconventions — framework, layout, fixtures, mocking boundaries, and assertion style — and cite file\npaths for every convention. Preserve that instruction's required sections.\n\nIf there is nothing repository-specific to cite, say that no repository evidence was found and\nwrite a short conservative standard; do not invent files, commands, or conventions.\n\"\"\"\n\n#### `e2e_testing_instructions` — max 40000 characters\n\n\"\"\"\nDraft `e2e_testing_instructions` to `{docs_dir}/standards/e2e_testing_instructions.md`, at most 40000\ncharacters.\n\nFollow the responsibilities in `learn-e2e-testing.md`: research this repository's end-to-end testing\nconventions — runner, prerequisites, page/selector patterns, and how tests are executed — and cite\nfile paths for every convention. Preserve that instruction's required sections.\n\nIf there is nothing repository-specific to cite, say that no repository evidence was found and\nwrite a short conservative standard; do not invent files, commands, or conventions.\n\"\"\"\n\n#### `frontend_correctness_standards` — max 40000 characters\n\n\"\"\"\nDraft `frontend_correctness_standards` to\n`{docs_dir}/standards/frontend_correctness_standards.md`, at most 40000 characters.\n\nFollow the responsibilities in `learn-frontend-correctness.md`: research the correctness rules that\napply to this repository's frontend code and cite file paths as evidence. Preserve that\ninstruction's required sections. If the repository has no frontend code, say so explicitly rather\nthan inventing standards.\n\"\"\"\n\n#### `backend_correctness_standards` — max 40000 characters\n\n\"\"\"\nDraft `backend_correctness_standards` to `{docs_dir}/standards/backend_correctness_standards.md`, at\nmost 40000 characters.\n\nFollow the responsibilities in `learn-backend-correctness.md`: research the correctness rules that\napply to this repository's backend code and cite file paths as evidence. Preserve that instruction's\nrequired sections.\n\nIf there is nothing repository-specific to cite, say that no repository evidence was found and\nwrite a short conservative standard; do not invent files, commands, or conventions.\n\"\"\"\n\n#### `template_correctness_standards` — max 40000 characters\n\n\"\"\"\nDraft `template_correctness_standards` to `{docs_dir}/standards/template_correctness_standards.md`,\nat most 40000 characters.\n\nFollow the responsibilities in `learn-template-correctness.md`: research the correctness rules that\napply to this repository's template files and cite file paths as evidence. Preserve that\ninstruction's required sections. If the repository has no templates, say so explicitly rather than\ninventing standards.\n\"\"\"\n\n#### `style_correctness_standards` — max 40000 characters\n\n\"\"\"\nDraft `style_correctness_standards` to `{docs_dir}/standards/style_correctness_standards.md`, at most\n40000 characters.\n\nFollow the responsibilities in `learn-style-correctness.md`: research the style and formatting rules\nthat apply to this repository's styling files and cite file paths as evidence. Preserve that\ninstruction's required sections. If the repository has no styling files, say so explicitly rather\nthan inventing standards.\n\"\"\"\n\n#### `design_principles` — max 40000 characters\n\n\"\"\"\nDraft `design_principles` to `{docs_dir}/standards/design_principles.md`, at most 40000 characters.\n\nFollow the responsibilities in `learn-design-principles.md`: research this repository's design\ntokens, component inventory, layout patterns, and composition rules, and cite file paths as evidence.\nPreserve that instruction's required sections. If the repository has no user interface, say so\nexplicitly rather than inventing principles.\n\"\"\"\n\n## Step 4 — Verify each result before marking it upload-ready\n\nFor every subagent that returned successfully:\n\n1. Confirm the draft file exists at the field's draft path.\n2. Measure the file's length in characters **yourself**. Do not trust the subagent's reported count —\n an oversized draft handed to the declarative upload is rejected by the server, and the field is\n silently not learned.\n3. If the file is within the field's budget, mark the field `drafted`.\n4. If the file is still over budget, condense it yourself to fit — preserving its required sections —\n then re-measure. If you cannot bring it within budget, delete the draft file and record the field\n as `failed` with the reason, so the upload sends nothing rather than something the server rejects.\n\nFor every subagent that failed, errored, or returned nothing usable: leave the draft path absent,\nrecord the field as `failed` with a short sanitized reason (no credentials, tokens, URLs, or raw\nstack traces), and continue. Do not abandon the other fields and do not fail this task.\n\n## Return\n\nReturn a single JSON object. This task succeeds even when some fields failed — the summary is how a\ngap gets reported, not an exception.\n\n```json\n{\n \"fields\": [\n {\n \"field_name\": \"architecture_instructions\",\n \"status\": \"drafted\",\n \"draft_path\": \"{docs_dir}/standards/architecture_instructions.md\",\n \"character_count\": 18240,\n \"max_character_count\": 40000,\n \"condensed\": false,\n \"condensation_reason\": \"\",\n \"failure_reason\": \"\"\n }\n ],\n \"drafted\": [\"architecture_instructions\"],\n \"skipped_existing\": [],\n \"condensed\": [],\n \"failed\": []\n}\n```\n\nRules for the return value:\n\n- `status` is exactly one of `drafted`, `skipped_existing`, or `failed`.\n- Every one of the ten fields appears exactly once in `fields`.\n- `condensed` is `true` only when the draft was shortened to meet the budget; `condensation_reason`\n explains why whenever `condensed` is `true`.\n- `failure_reason` is populated only for `failed` fields and is sanitized.\n- The four aggregate arrays list the field names in each outcome, so the command's closing summary\n can report them without re-deriving them from prose.\n",
780
781
  "learn-review-instructions.md": "## Objective\n\nExplore the codebase to identify self-verification patterns, downstream impact analysis techniques, and local validation tooling, then draft `review_instructions` for the project config.\n\n## Instructions\n\n### Phase 1 — Explore Self-Verification Patterns\n\nFocus on how an AI agent working in a code editor (with capabilities to search file contents by text pattern, search by filename pattern, read files, and call MCP tools) can verify its own code changes before requesting human review. Do NOT document test runners or CI/CD — focus on static analysis by reading code and searching for patterns.\n\nIf there is nothing repository-specific to cite, say that no repository evidence was found and write a short conservative standard; do not invent files, commands, or conventions.\n\n1. **Code Correctness Patterns**: Read 3-5 representative modules in `api/routes/` and `api/library/` to identify:\n - Function signature conventions (return types, parameter patterns)\n - Import conventions and layer boundaries (deprecated modules, import restrictions)\n - Return value handling (structured results, tuple unpacking)\n - Auth pattern compliance (required decorators, dependency injections, call order)\n - Naming conventions (files, functions, classes, variables)\n - Error handling patterns (try/except structure, ordering, logging)\n\n2. **Downstream Impact Analysis**: For each technique, demonstrate with a concrete codebase example:\n - Caller discovery (text-pattern search for finding all callers of utility functions)\n - Import graph analysis (finding all files importing from a module)\n - Route registration verification (checking new routes are properly included)\n - Database schema impact (finding queries referencing a given table/column)\n - Model/schema usage (verifying model changes don't break dependents)\n\n3. **Local Validation Tooling**: Discover available MCP tools and validation capabilities:\n - Database MCP tools (schema verification, query validation)\n - Project API MCP tools (config verification, health checks)\n - Hooks and guards (pre-commit hooks, pre-tool hooks)\n - Safety model (read-only vs. mutating operations)\n - Runtime smoke verification capability: Document which tools the executor can use to _run_ code safely (test runners, dbhub MCP, local dev servers, fixture loaders) and whether mutations are permitted against local/ephemeral state. The per-repo `allow_mutating_smoke_ops` flag (on `config_code_repositories`) controls whether the final reviewer is allowed to plan mutating verification steps.\n\n4. **Correctness Standards Integration**: Read files in `{docs_dir}/standards/` matching `*_correctness_standards.md`. Extract key verification checkpoints that can be statically verified.\n\n### Phase 2 — Draft\n\nDraft `review_instructions` with these required sections:\n1. **Self-Verification Checklist** — Concise, scannable checklist with concrete actions and tools.\n2. **Local Code Verification** — Detailed static analysis instructions (function calls, imports, auth, error handling, naming).\n3. **Downstream Effect Analysis** — Finding callers, checking signature compatibility, import tracking, schema impact, route registration.\n4. **Validation Using Local Tooling** — Database validation, project API validation, hooks and guards.\n5. **Correctness Standards Reference** — Distilled checkpoints from loaded standards, or placeholder paths.\n6. **Common AI Agent Mistakes** — Verification-framed guards against duplication, unnecessary abstraction, data leaks, edge cases.\n\nWrite the draft to `{docs_dir}/standards/review_instructions.md`.\n\n## Length Budget\n\nThe platform ceiling for a configuration field is **40,000 characters**, and the server enforces it\nat upload time: a draft over the limit is rejected outright and ``review_instructions`` is simply not learned. Bound\nthe draft here, at write time, rather than discovering the limit through a failed upload.\n\n1. When the draft is complete, measure its length in **characters** — not tokens, not words, not\n bytes.\n2. If it exceeds 40,000 characters, condense it: remove redundancy, collapse repetitive passages, and\n shorten or drop verbose code examples.\n3. Keep every required section listed above. Never meet the budget by deleting a required section,\n and never truncate the draft mid-sentence.\n4. Re-measure after condensing and repeat until the draft is at most 40,000 characters.\n\n## Return\n\nReturn a brief summary of what was learned about the project's self-review and downstream-impact analysis patterns (verification checkpoints, local validation tooling), citing the key files inspected, and confirm the draft was written to `{docs_dir}/standards/review_instructions.md`.\n\nAlso report the draft's final length in characters, the applicable maximum (40,000 characters),\nwhether the draft was condensed to meet that maximum (`condensed`: true/false), and — when it was\ncondensed — the reason it needed condensing.\n",
781
782
  "learn-style-correctness.md": "## Objective\n\nExplore the codebase to identify correctness standards for style files, then draft the corresponding correctness standards document.\n\n## Target Type\n\n- **Type**: `style_correctness`\n- **Field name**: `style_correctness_standards`\n- **Scope**: Style files: CSS, SCSS, SASS, LESS, Styled Components, Tailwind configs.\n\n## Instructions\n\n### Phase 1 — Explore Correctness Patterns\n\nFocus on implementation correctness: how to write code that is correct, idiomatic, and robust within this project's conventions.\n\n1. **File Type Detection**: Search by filename pattern for files matching `**/*.css`, `**/*.scss`, `**/*.sass`, `**/*.less` (excluding `node_modules/`). If very few or no files exist, note this and draft minimal instructions.\n\n2. **Convention Analysis**: Read 3-5 representative style files to identify:\n - Structure patterns (imports, exports, class structure, function ordering)\n - Naming conventions (variables, functions, classes, files)\n - Framework conventions and idioms\n - Best practices followed\n - Issues and inconsistencies\n\n### Phase 2 — Draft\n\nDraft correctness standards as clear, actionable instructions for an AI code generation agent. Cover:\n- Code structure and organization requirements\n- Naming conventions to follow\n- Framework-specific patterns and idioms\n- Security requirements relevant to this code type\n- Performance considerations\n- Common mistakes to avoid\n- Guards against common AI weaknesses: duplicative code, verbose implementations, security vulnerabilities\n\nWrite the draft to `{docs_dir}/standards/style_correctness_standards.md`.\n\n## Length Budget\n\nThe platform ceiling for a configuration field is **40,000 characters**, and the server enforces it\nat upload time: a draft over the limit is rejected outright and ``style_correctness_standards`` is simply not learned. Bound\nthe draft here, at write time, rather than discovering the limit through a failed upload.\n\n1. When the draft is complete, measure its length in **characters** — not tokens, not words, not\n bytes.\n2. If it exceeds 40,000 characters, condense it: remove redundancy, collapse repetitive passages, and\n shorten or drop verbose code examples.\n3. Keep every required section listed above. Never meet the budget by deleting a required section,\n and never truncate the draft mid-sentence.\n4. Re-measure after condensing and repeat until the draft is at most 40,000 characters.\n\n## Return\n\nReturn a brief summary of what was learned about style-file correctness conventions (structure, naming, methodology), citing the key files inspected, and confirm the draft was written to `{docs_dir}/standards/style_correctness_standards.md`.\n\nAlso report the draft's final length in characters, the applicable maximum (40,000 characters),\nwhether the draft was condensed to meet that maximum (`condensed`: true/false), and — when it was\ncondensed — the reason it needed condensing.\n",
@@ -9,6 +9,7 @@
9
9
  import { planeManifestLifecycle, planeManifestSnapshot, probeManifestMembers, readPlaneManifest, } from "./manifest.js";
10
10
  import { PLANE_RESTART_MIN_SCHEMA_VERSION, PLANE_RUNTIME_DIR, PLANE_RUNTIME_LOG_PATH, } from "./types.js";
11
11
  import { WORKER_STALE_EXIT_CODE } from "./worker-exit-code.js";
12
+ import { BRIDGE_RUN_STATE_DIR } from "../bridge-permissions.js";
12
13
  /** Read the manifest and probe every recorded pid. Strictly read-only. */
13
14
  export async function getPlaneStatus(repoRoot, deps) {
14
15
  const read = await readPlaneManifest(repoRoot, deps.fs);
@@ -80,8 +81,13 @@ function describeLifecycle(phase) {
80
81
  case "ready":
81
82
  return "plane ready (this reports PROCESSES, not whether the run is dispatchable)";
82
83
  case "lanes-failed":
83
- return ("executor lanes FAILED — the lane cohort was stopped and the control plane was " +
84
- "left running; nothing is claiming jobs. Wind it down with `plane down`.");
84
+ // This phase covers two cases the manifest cannot tell apart: lanes that were
85
+ // requested and failed to start, and a launch that ended before lanes were
86
+ // requested at all. The text names both and never blames the lanes alone.
87
+ return ("executor lanes did not start, or the launch ended before lanes were requested — " +
88
+ "the control plane was left running and nothing is claiming jobs. " +
89
+ `See launch-outcome.json in ${BRIDGE_RUN_STATE_DIR}/<EPIC>/ for how the launch ended, ` +
90
+ "then wind it down with `plane down`.");
85
91
  }
86
92
  }
87
93
  /**
@@ -106,6 +106,11 @@ export const READINESS_PREREQUISITE_FIXES = {
106
106
  reindex_manual: "Re-index the repository (/parse-repository).",
107
107
  none: "",
108
108
  };
109
+ /**
110
+ * BAPI-1678: the fix for a readiness item that only means setup has not been saved yet.
111
+ * Client-only: it is never sent on the wire, so it stays out of the generated table above.
112
+ */
113
+ export const PRE_SETUP_READINESS_REMEDY = "Run setup; this item is checked again once this setup is saved.";
109
114
  const PUBLISHED_INSTALL_COMMAND = `${LAUNCHER} install epic-implementer --required-check "epic-implementer-ci / gate"`;
110
115
  /**
111
116
  * BAPI-1635 — the fix texts the PUBLISHED client (0.2.72) accepts from a server.
@@ -33,6 +33,46 @@ export async function hasProjectRootMarker(cwd, stat) {
33
33
  return false;
34
34
  }
35
35
  }
36
+ /**
37
+ * BAPI-1664: the closed, extensible list of markers that prove a folder is a
38
+ * repository root for `install epic-implementer`. A worktree's `.git` is a FILE,
39
+ * so only existence is checked. Add a marker here to widen the guard.
40
+ */
41
+ export const VCS_WORK_TREE_MARKERS = [".git"];
42
+ /**
43
+ * Whether `cwd` is the user's home directory. Compares RESOLVED LEXICAL paths
44
+ * only and performs no filesystem I/O; it intentionally does not resolve
45
+ * symlinks, so a symlinked home directory is not detected. Returns `false` when
46
+ * `homeDir` is absent or empty, and never throws.
47
+ */
48
+ export function isHomeDirectory(cwd, homeDir) {
49
+ if (!homeDir)
50
+ return false;
51
+ try {
52
+ return path.resolve(cwd) === path.resolve(homeDir);
53
+ }
54
+ catch {
55
+ return false;
56
+ }
57
+ }
58
+ /**
59
+ * Whether `cwd` holds a repository marker from {@link VCS_WORK_TREE_MARKERS},
60
+ * checked through the injected `stat` probe. Any probe failure counts as that
61
+ * marker being absent; this never throws. Sibling of {@link hasProjectRootMarker},
62
+ * which stays the `.git`-only prompt hint for ordinary `install` and `--init`.
63
+ */
64
+ export async function hasVcsWorkTreeMarker(cwd, stat) {
65
+ for (const marker of VCS_WORK_TREE_MARKERS) {
66
+ try {
67
+ await stat(path.join(cwd, marker));
68
+ return true;
69
+ }
70
+ catch {
71
+ /* try the next marker */
72
+ }
73
+ }
74
+ return false;
75
+ }
36
76
  /**
37
77
  * Validate an explicit project root: it must exist, be a directory, and contain
38
78
  * `.git` (a directory, or the `.git` FILE a worktree has) or `.bridge/config`.