@devorch/cli-linux-x64 0.19.0 → 0.21.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,12 @@
1
+ {
2
+ "name": "devorch-cli",
3
+ "owner": { "name": "Dev Orchestrator" },
4
+ "description": "The Claude Code companion mod shipped with the devorch CLI. Added by 'devorch companion install' from the folder beside the CLI binary.",
5
+ "plugins": [
6
+ {
7
+ "name": "devorch-companion",
8
+ "source": "./devorch-companion",
9
+ "description": "The DevOrch skills (/devorch-companion:sdlc-drive, /devorch-companion:devorch-step), the devorch-step-worker agent and a DevOrch MCP server, plus a mod that wakes an idle step session when a watched run can move, shows run position and open blockers, and answers blockers from a slash command."
10
+ }
11
+ ]
12
+ }
@@ -0,0 +1,52 @@
1
+ {
2
+ "name": "devorch-companion",
3
+ "version": "0.21.0",
4
+ "description": "DevOrch companion: the sdlc-drive and devorch-step skills, the devorch-step-worker agent and a DevOrch MCP server (the devorch CLI's `companion mcp`), plus a mod that watches DevOrch runs and wakes an idle /devorch-companion:devorch-step session on platform events instead of ScheduleWakeup polling (wakeMode: auto, push or poll). Status line, /devorch-watch, /devorch-unwatch, /devorch-answer, the devorch_companion tool and a $.devorch event hook for other plugins.",
5
+ "author": {
6
+ "name": "Dev Orchestrator"
7
+ },
8
+ "license": "UNLICENSED",
9
+ "types": "./types/index.d.ts",
10
+ "userConfig": {
11
+ "devorchExe": {
12
+ "type": "string",
13
+ "title": "devorch executable",
14
+ "description": "Full path of the devorch executable the mod runs for watches and answers. Leave empty to use the path `devorch companion install` recorded (the DEVORCH_EXE environment variable wins over both). The MCP server always runs the recorded path: rerun `devorch companion install` to change it.",
15
+ "required": false,
16
+ "default": ""
17
+ },
18
+ "apiBase": {
19
+ "type": "string",
20
+ "title": "DevOrch API base URL",
21
+ "description": "The DevOrch server the MCP server and run watches use. Default: the hosted API, https://api.devorchestrator.com (an empty value means the same). Set http://localhost:8700 to dogfood against a local backend. DEVORCH_API_BASE in the environment wins over this; a single watch can also name its own base URL.",
22
+ "required": false,
23
+ "default": "https://api.devorchestrator.com"
24
+ },
25
+ "wakeMode": {
26
+ "type": "string",
27
+ "title": "Wake mode",
28
+ "description": "Who wakes an interactive run between steps. auto (default): the companion mod wakes the session the moment the run can move while it is healthy, else the step skill polls with /loop + ScheduleWakeup. push: the companion only; if it is unhealthy the skill reports that and stops instead of polling. poll: always /loop + ScheduleWakeup (the mod still shows the status line but never wakes). DEVORCH_WAKE_MODE in the environment wins over this.",
29
+ "required": false,
30
+ "default": "auto",
31
+ "options": [
32
+ "auto",
33
+ "push",
34
+ "poll"
35
+ ]
36
+ },
37
+ "fallbackWakeupSeconds": {
38
+ "type": "number",
39
+ "title": "Fallback wakeup (seconds)",
40
+ "description": "Under poll, the safety-net ScheduleWakeup the step skill sets while a worker runs, in case it never hands back. 60 to 3600, default 1800. DEVORCH_FALLBACK_WAKEUP_SECONDS in the environment wins over this.",
41
+ "required": false,
42
+ "default": 1800
43
+ },
44
+ "longPollSeconds": {
45
+ "type": "number",
46
+ "title": "Long-poll seconds",
47
+ "description": "When the mod's live watch keeps failing it falls back to one-shot long-polls (devorch run wait --seconds N). 5 to 25 (the server's limit), default 25. DEVORCH_LONG_POLL_SECONDS in the environment wins over this.",
48
+ "required": false,
49
+ "default": 25
50
+ }
51
+ }
52
+ }
@@ -0,0 +1,9 @@
1
+ {
2
+ "mcpServers": {
3
+ "devorch": {
4
+ "type": "stdio",
5
+ "command": "devorch",
6
+ "args": ["companion", "mcp", "--api-base", "${user_config.apiBase}"]
7
+ }
8
+ }
9
+ }
@@ -1,41 +1,164 @@
1
- # DevOrch companion mod (DEV-47 C6, DEV-56)
1
+ # DevOrch companion plugin (DEV-47 C6, DEV-56)
2
2
 
3
- A shareable Claude Code mod that turns DevOrch platform events into actions in the session: it watches a run with
4
- `devorch run watch <runId>`, shows the run's position and open blockers in a status line, and wakes an idle session
5
- with `/devorch-step <runId>` the moment the run can move (a blocker answered, a step's result applied), so an
6
- interactive run no longer polls. It is separate from this workspace's own `devorch-guard` mod.
3
+ A self-contained Claude Code plugin for driving DevOrch runs from any repository:
7
4
 
8
- ## Install
5
+ | Piece | Path | What it is |
6
+ |---|---|---|
7
+ | `/devorch-companion:sdlc-drive` | `skills/sdlc-drive/` | Claim an assigned tracker issue, start an SDLC run, drive it (Interactive or `--headless`). |
8
+ | `/devorch-companion:devorch-step` | `skills/devorch-step/` | Process a run's next instruction and keep going; the mod wakes it between instructions (push), or `/loop` does (poll). |
9
+ | `devorch-companion:devorch-step-worker` | `agents/` | The subagent that does one instruction's work in a fresh context. |
10
+ | MCP server `devorch` | `.mcp.json` | `devorch companion mcp`: the CLI's stdio MCP server (full profile, no admin band). Tools read `mcp__plugin_devorch-companion_devorch__<tool>`. |
11
+ | The mod | `hooks/` | Watches a run with `devorch run watch <runId>`, shows its position and open blockers in a status line, and wakes an idle session with `/devorch-companion:devorch-step <runId>` the moment the run can move, so an interactive run no longer polls. |
9
12
 
10
- The mod ships beside the `devorch` binary (npm platform package `bin/claude-mod/`, NuGet tool
11
- `tools/net10.0/any/claude-mod/`):
13
+ Everything targets **one backend**: the plugin's `apiBase` setting, default the hosted API
14
+ `https://api.devorchestrator.com` (empty means the same). `DEVORCH_API_BASE` in the environment wins over the setting,
15
+ and a single watch can name its own base URL. The CLI's own default (`http://localhost:8700`) is untouched: the plugin
16
+ always passes its URL explicitly. It is separate from the DevOrch workspace's own `devorch-guard` mod.
12
17
 
13
- ```bash
14
- devorch companion install # records this devorch in the mod, prints the two commands
15
- claude plugin marketplace add "<path printed above>"
16
- claude plugin install devorch-companion@devorch-cli
17
- ```
18
+ ## First run (new user)
19
+
20
+ 1. **Install the CLI** (either channel):
21
+
22
+ ```bash
23
+ npm i -g dev-orchestrator-cli # or: dotnet tool install -g dev-orchestrator-cli
24
+ ```
25
+
26
+ 2. **Sign in to the hosted API.** `devorch login` honours `--base-url` and `DEVORCH_API_BASE` but defaults to
27
+ `http://localhost:8700`, so name the server; tokens are cached per base URL in `~/.devorch/token.json`, and the
28
+ plugin's MCP server reuses that session:
29
+
30
+ ```bash
31
+ devorch login --oauth --base-url https://api.devorchestrator.com
32
+ ```
33
+
34
+ 3. **Prepare and install the plugin.** `companion install` records this `devorch` in the plugin (`cli.json` for the
35
+ mod, and the `command` of `.mcp.json` for the MCP server) and prints the two `claude plugin` commands:
36
+
37
+ ```bash
38
+ devorch companion install
39
+ claude plugin marketplace add "<path printed above>"
40
+ claude plugin install devorch-companion@devorch-cli
41
+ ```
42
+
43
+ 4. **Start Claude Code** in your repository, check `/mcp` lists `plugin:devorch-companion:devorch` as connected, then
44
+ run `/devorch-companion:sdlc-drive <integrationExternalId>`.
18
45
 
19
46
  After upgrading the CLI, run `devorch companion install` again, then
20
47
  `claude plugin marketplace update devorch-cli && claude plugin update devorch-companion@devorch-cli`.
21
- `DEVORCH_EXE` (or the plugin's `devorchExe` setting) overrides the recorded executable; `apiBase` (or a watch's own
22
- base URL) points it at a worktree slot.
48
+ `DEVORCH_EXE` (or the plugin's `devorchExe` setting) overrides the executable the mod runs; the MCP server always runs
49
+ the one `companion install` recorded.
50
+
51
+ ## Wake modes
52
+
53
+ Between instructions an interactive run needs something to wake the session: a worker is running, or the run is
54
+ waiting on a human. Two mechanisms, and exactly one owns the wake at a time:
55
+
56
+ - **push** (realtime): the mod watches the run and submits `/devorch-companion:devorch-step <runId>` within seconds of
57
+ it becoming actionable. `sdlc-drive` runs the step skill **once, with no `/loop`**, and the step skill schedules no
58
+ wakeups. After a worker hands back, the step skill goes straight on to the next instruction in the same turn.
59
+ - **poll** (timed): `sdlc-drive` runs `/loop /devorch-companion:devorch-step <runId>` and the step skill keeps its own
60
+ `ScheduleWakeup`s: `retryAfterSeconds` on a `WAIT`, and a safety-net wakeup while a worker runs.
61
+
62
+ The `devorch_companion` tool's `status` and `watch` answers carry the resolved policy, which is the one field the skills
63
+ branch on:
64
+
65
+ ```json
66
+ "wake": { "mode": "auto", "effective": "push", "owner": "companion", "fallbackWakeupSeconds": 1800, "reason": "..." }
67
+ ```
68
+
69
+ `effective` is `push`, `poll`, or `unavailable` (`wakeMode` is `push` but the companion is unhealthy: the skill reports
70
+ `reason` and stops). `status` also returns `config`: each setting's value, its source (`env`, `option` or `default`)
71
+ and any warnings.
72
+
73
+ | Setting (plugin option) | Environment override | Default | Values |
74
+ |---|---|---|---|
75
+ | `wakeMode` | `DEVORCH_WAKE_MODE` | `auto` | `auto`: push while the companion is healthy, else poll. `push`: the companion only; unhealthy means report and stop, never poll. `poll`: always `/loop` + `ScheduleWakeup`; the mod still shows the status line (with `wake: poll`) but submits no wakes and reports `healthy: false`. An unknown value is `auto`, with a warning in `status`. |
76
+ | `fallbackWakeupSeconds` | `DEVORCH_FALLBACK_WAKEUP_SECONDS` | `1800` | The safety-net `ScheduleWakeup` under poll while a worker runs, and after a `WAIT` with no `retryAfterSeconds`. Clamped to 60..3600. |
77
+ | `longPollSeconds` | `DEVORCH_LONG_POLL_SECONDS` | `25` | The mod's rung-3 fallback (`devorch run wait --seconds N`, used only when the live watch keeps failing). Clamped to 5..25, the server's limit. |
78
+
79
+ Each setting resolves **environment variable, then plugin option, then default**; the first one that is set (not
80
+ empty) decides. Set the options with `/plugin configure devorch-companion@devorch-cli` (or the `/config` menu), or with
81
+ `claude plugin configure devorch-companion@devorch-cli --values-stdin`. The environment variables win because a
82
+ project-scope plugin option may not apply while a project's `env` does, so to pin a mode for one repository put it in
83
+ that project's `.claude/settings.json`:
84
+
85
+ ```json
86
+ { "env": { "DEVORCH_WAKE_MODE": "poll" } }
87
+ ```
88
+
89
+ A new setting takes effect when the mod reloads (a changed option reloads it; an environment change needs a new
90
+ session).
91
+
92
+ ## Design notes
93
+
94
+ - **Which `devorch` runs.** `devorch companion install` writes the executable it is running as into the plugin folder
95
+ before `claude plugin install` copies it into Claude Code's cache: `cli.json` (read by the mod) and the
96
+ `mcpServers.devorch.command` of `.mcp.json`. That path is the npm platform package's `bin/devorch(.exe)` (beside
97
+ `claude-mod/`) or, for the NuGet tool, the stable shim `~/.dotnet/tools/devorch(.exe)`, never the versioned
98
+ `.store/` folder that `dotnet tool update` deletes. No PATH lookup, no Node, no shell shim (`devorch.cmd` would need
99
+ `cmd /c` on Windows). The shipped `.mcp.json` says `devorch` so an unprepared copy (a `--plugin-dir` load of the
100
+ source) still starts from PATH.
101
+ - **Why `devorch companion mcp` rather than `devorch mcp serve`.** It is `mcp serve` over stdio with the plugin's base
102
+ URL rule built in: `DEVORCH_API_BASE`, then `--api-base ${user_config.apiBase}`, then the hosted API. A value that is
103
+ not an http(s) URL (empty, or an unsubstituted placeholder) is skipped, so "empty means prod" holds even though
104
+ `${user_config.*}` cannot express a fallback. The mod applies the same rule (`resolveBaseUrl` in
105
+ `hooks/supervision.ts`), so watches and the skills' tools hit one server.
106
+ - **Wake command.** Claude Code names plugin skills `/<plugin>:<skill>`. Before each wake the mod lists the session's
107
+ commands and submits `devorch-companion:devorch-step` whenever it is listed, even beside a project-level
108
+ `devorch-step` (this plugin's copy ships with the mod and the CLI, so they stay in step). It falls back to a listed
109
+ bare `devorch-step` only when the plugin's skill is missing. A rejected wake reads as `healthy: false`, so under
110
+ `auto` the next firing sees `wake.effective: poll` and the skill keeps its own `ScheduleWakeup` (it starts `/loop`
111
+ when it wasn't under one).
112
+ - **Tool names.** The skills name `mcp__plugin_devorch-companion_devorch__*` in `allowed-tools` and refer to verbs by
113
+ their bare name in the body ("the DevOrch MCP server's `get_next_instruction`"), so any DevOrch MCP server with the
114
+ same tools also works. Keep the server key `devorch`: renaming it renames every tool.
115
+ - **Stage work outside the workspace.** The worker follows `execute-instruction` / `evaluate-gate` and the stage skills
116
+ when the session has them (the DevOrch workspace does); elsewhere it runs the server-assembled step prompt
117
+ (`get_step_prompt`). Workspace-only steps (worktrees via `scripts/worktree_manage.py`, `app_run.py`, slot rules) are
118
+ guarded behind "in the DevOrch workspace".
119
+ - The worker's result-schema block is a copy of the workspace-rendered rule (`openapi/result-schema-rule.json`);
120
+ refresh it when that rule changes.
121
+
122
+ ## Dogfooding locally (the DevOrch workspace)
123
+
124
+ Point the plugin at the local backend so the bundled MCP server and the watches both hit it. Either set the plugin's
125
+ option at project scope, in the workspace's `.claude/settings.local.json`:
126
+
127
+ ```json
128
+ { "pluginConfigs": { "devorch-companion@devorch-cli": { "options": { "apiBase": "http://localhost:8700" } } } }
129
+ ```
130
+
131
+ or user-wide with `echo '{"apiBase":"http://localhost:8700"}' | claude plugin configure devorch-companion@devorch-cli --values-stdin`,
132
+ or set `DEVORCH_API_BASE=http://localhost:8700` in the environment Claude Code starts with (it wins over the option).
133
+ Sign in once for that URL: `devorch login --base-url http://localhost:8700` (password or `--oauth`).
134
+
135
+ - **Worktree slots.** A slot's backend is on `http://localhost:87NN`. Start Claude Code for that slot with
136
+ `DEVORCH_API_BASE=http://localhost:87NN` so the bundled server targets it, or pass `baseUrl` on a single watch
137
+ (`/devorch-watch <runId> http://localhost:87NN`).
138
+ - **The workspace's own MCP servers** (`devorch-local`, `devorch-local-mcp` in `.mcp.json`) stay for ad-hoc and admin
139
+ use: `devorch-local` runs `mcp serve --allow-control` (the admin band the plugin's server never exposes). The
140
+ shipped skills use the plugin's server; the workspace's project copies of `devorch-step`, `sdlc-drive` and
141
+ `devorch-step-worker` can be deleted once this plugin version is installed (the wake already prefers the plugin's
142
+ skill).
143
+ - To run the plugin straight from source: `devorch companion install` from a build output
144
+ (`src/DevOrchestrator.Cli/bin/Debug/net10.0/`), then the two `claude plugin` commands against the printed path.
23
145
 
24
146
  ## Status
25
147
 
26
148
  | Piece | File | Status |
27
149
  |---|---|---|
28
150
  | Envelope parsing, NDJSON framing, generic event hook, wake decision, source ladder, CLI handshake, band text | `hooks/core.ts` | built, tested |
29
- | Supervision decisions: exit-code mapping (unknown -> rung 4), rung-3 backoff, heal/retry timers, pending-wake expiry, position dedupe, hand-back wake, terminal rule, watch cap, exe and base-URL resolution, multi-run status, `healthy` | `hooks/supervision.ts` | built, tested |
151
+ | Supervision decisions: exit-code mapping (unknown -> rung 4), rung-3 backoff, heal/retry timers, pending-wake expiry, position dedupe, hand-back wake, terminal rule, watch cap, exe and base-URL resolution, multi-run status, `healthy`, wake settings (env > option > default) and the wake policy | `hooks/supervision.ts` | built, tested |
30
152
  | CLI option contract (R12): `test/cli-options.json`, checked by the mod tests and by `CompanionArgvContractTests` (C#) | `test/` | built, tested |
31
153
  | `register.ts`: the adapter over `$` (process spawn, turn tracking, `$.command.run`, status line, `/devorch-watch`, `/devorch-unwatch`, `/devorch-answer`, tool `devorch_companion`, `$.devorch.on` for other plugins) | `hooks/register.ts` | built; **behaviour unverified until the Windows spike** (`sdlc/devorch-companion-mod-platform-events/implement/spike-tq27.md`) and QA |
32
154
  | `.claude-plugin/plugin.json`, `hooks/hooks.json`, marketplace manifest | `.claude-plugin/`, `../.claude-plugin/` | built |
33
- | Shipping in the npm and NuGet packages; `CLI_PATHS` and `on.push.paths`; `devorch companion install` | CLI | built |
155
+ | Shipping in the npm and NuGet packages; `CLI_PATHS` and `on.push.paths`; `devorch companion install` (records the exe in `cli.json` and `.mcp.json`); `devorch companion mcp` | CLI | built |
156
+ | Skills `sdlc-drive`, `devorch-step`, agent `devorch-step-worker`, MCP server `devorch` | `skills/`, `agents/`, `.mcp.json` | built; live OAuth against the hosted API unverified |
34
157
 
35
158
  The spike still decides three things the adapter assumes: that `$.process.spawn` of the native `devorch.exe` shows no
36
159
  console window on Windows, which event marks the end of a main-loop turn, and that
37
- `$.command.run({command: "devorch-step"})` queues until idle and rejects an unknown command. Every host failure
38
- reads as `healthy: false`, so the skills fall back to `ScheduleWakeup` rather than stalling.
160
+ `$.command.run({command: "devorch-companion:devorch-step"})` queues until idle and rejects an unknown command. Every host failure
161
+ reads as `healthy: false`, so under `wakeMode: auto` the skills fall back to `ScheduleWakeup` rather than stalling.
39
162
 
40
163
  ## Tests
41
164
 
@@ -0,0 +1,135 @@
1
+ ---
2
+ name: devorch-step-worker
3
+ description: Performs the work of exactly one DevOrch run instruction in a fresh context, writing that step's stage documents and code changes to disk, and returns one result JSON object. Launched by the devorch-step skill with a runId, an instructionId and an optional worktree path. Use only for dispatching a DevOrch instruction.
4
+ ---
5
+
6
+ # DevOrch Step Worker
7
+
8
+ You do the work of **one** DevOrch instruction. The orchestrator that launched you only fetches instructions,
9
+ applies results and prints status, so everything else happens here: reading context, stage docs and source,
10
+ making edits, running tests.
11
+
12
+ **Tools.** The DevOrch verbs below (`get_instruction`, `get_context_for_instruction`, `get_step_prompt`,
13
+ `put_step_output`, `record_decision`, `raise_blocker`, `submit_verdict`) are tools of the DevOrch MCP server. The
14
+ companion plugin bundles one, so they read `mcp__plugin_devorch-companion_devorch__<verb>`; if that server is absent,
15
+ use the same verb from the DevOrch MCP server this session has (for example `mcp__devorch-local-mcp__<verb>`).
16
+
17
+ **Writing files is the work, not a report.** Each stage produces documents under `sdlc/{slug}/`, such as
18
+ `problem.md`, `synthesis.md` and the stage `INDEX.md`. Those are the step's deliverables, and later steps read them
19
+ from disk. Write them with the Write and Edit tools as the stage guidance directs. Never put a document's body into
20
+ the result JSON instead of the file: the result only references files through `artifacts[].ref`. Your findings for
21
+ the orchestrator are the result JSON's `outputs.summary`, not a separate file.
22
+
23
+ Your prompt gives you `runId`, `instructionId`, `worktree` (an absolute path, or `none`) and `driverId`.
24
+
25
+ ## Procedure
26
+
27
+ 1. **Read the envelope.** Call `get_instruction(runId)`. If its `instructionId` differs from the one you were
28
+ given, stop and return a `blocked` result with a blocker of type `error` that names both ids.
29
+ 2. **Gather.** Call `get_context_for_instruction(runId)`. Always do this, before any other work. It carries the work
30
+ intent, upstream outputs, prior decisions, open questions, blockers and open steering `directives[]` (honor any
31
+ that apply). Its `workItem` section lists every BQ/TQ, AC, G and TC key the work item already has: reuse a key
32
+ when you write about the same item, number a new one from `nextKeys`, and never renumber.
33
+ 3. **Dispatch on `kind`**, matching case and separators loosely:
34
+ - `execute_step`: if an `execute-instruction` skill is available in this session, follow it. Otherwise call
35
+ `get_step_prompt(runId, instructionId)`: the server assembles the full step prompt (stage and step guidance,
36
+ inputs, each output slot's contract, the postconditions it will check, and the result instructions). Do what it
37
+ says, using the stage skill named by `spec.skill` (`research-build`, `plan-build`, `implement-build`,
38
+ `review-build`, `qa-build`) when this session has it, and the prompt's own guidance when it doesn't.
39
+ - `evaluate`: if an `evaluate-gate` skill is available, follow it. Otherwise judge the gate `spec.check` against
40
+ the context bundle and the subjects `inputs` reference, and return one `evaluate.result.v1` with
41
+ `outputs.verdict` (`approved`, `rejected` or `approvedWithGaps`), `outputs.rationale` and
42
+ `outputs.confidence`. Don't echo or name the boundary: the server resolves it.
43
+ - `record_backedge`: do what `spec` asks and report it as a `record_backedge.result.v1`.
44
+ - anything else: return a `blocked` result naming the kind.
45
+ 4. **Signal as needed** while you work: `record_decision` for settled calls later steps should see, `raise_blocker`
46
+ for a hard stop.
47
+ 5. **Report.** Your final message is one result JSON object and nothing else: no prose, no code fences.
48
+
49
+ ## Where work happens
50
+
51
+ - Stage documents go under `sdlc/{slug}/` at the project root (the main checkout, not a worktree).
52
+ - Never name a `.md` file starting with `analysis`, `report`, `summary` or `findings`. Claude Code refuses
53
+ a subagent's Write of those ("Subagents should return findings as text, not write report files"). Use
54
+ names like `cross-cutting.md` or `verdict.md` instead.
55
+ - When `worktree` is a path, all code changes, builds, tests and running services happen inside it. In the DevOrch
56
+ workspace that means `<worktree>/app/backend` and `<worktree>/app/frontend` on that worktree's slot ports, never
57
+ slot 0 (`app/` at the workspace root, ports 8700 and 8800).
58
+ - When `worktree` is `none`, code changes happen in the current checkout. Never commit to, merge to or push the
59
+ default branch; leave changes for the person to review.
60
+ - Rendered and behavioural checks belong to QA. The implement step stops at build and lint.
61
+ - In the DevOrch workspace, for browser work run `uv run scripts/app_run.py e2e-token [email]` from the worktree root
62
+ immediately beforehand, because the token expires within minutes.
63
+ - Never read secret files (`.env*`, credential stores). Learn whether something is configured from how the app
64
+ behaves.
65
+
66
+ ## Result rules
67
+
68
+ - Report in the schema your envelope's `outputContract.schema` names (or another of its
69
+ `outputContract.acceptedSchemas`). The rule, rendered from the backend's published artifact:
70
+
71
+ <!-- result-schema-rule:begin (generated by scripts/result_schema_rule_check.py --write from app/backend/openapi/result-schema-rule.json; do not edit by hand) -->
72
+ **Accepted result schemas.** The server judges the body's `schema` against the instruction's kind. Omitting `schema` means the preferred one; any other schema is rejected with 422 `result_schema_mismatch` naming the expected schemas. The envelope's `outputContract.acceptedSchemas` carries the same list.
73
+
74
+ | Instruction kind | Preferred (`outputContract.schema`) | Also accepted |
75
+ |---|---|---|
76
+ | `execute_step` | `execute_step.result.v1` | `execute_step.result.v2` |
77
+ | `evaluate` | `evaluate.result.v1` | none |
78
+ | `record_backedge` | `record_backedge.result.v1` | none |
79
+
80
+ > In execute_step.result.v2, outputs holds only slot names (each a receipt or an inline value); summary is a top-level member, and v1 report members (passes, gaps) do not belong in it.
81
+
82
+ Example bodies (each is accepted for its kind; pinned by the backend's golden contract test):
83
+
84
+ - `execute_step` / `execute_step.result.v1`: `{"schema":"execute_step.result.v1","status":"succeeded","outputs":{"summary":"One paragraph of what the step did.","passes":1,"gaps":[]},"evidence":{"harness":"claude"}}`
85
+ - `execute_step` / `execute_step.result.v2`: `{"schema":"execute_step.result.v2","status":"succeeded","summary":"One paragraph of what the step did.","outputs":{"synthesis":{"receipt":{"kind":"artifact-revision","ref":"<receipt ref from put_step_output>","version":"1"}}},"evidence":{"harness":"claude"}}`
86
+ - `evaluate` / `evaluate.result.v1`: `{"schema":"evaluate.result.v1","status":"succeeded","outputs":{"verdict":"approved","rationale":"Why the gate passes or fails.","confidence":0.8},"evidence":{"harness":"claude"}}`
87
+ - `record_backedge` / `record_backedge.result.v1`: `{"schema":"record_backedge.result.v1","status":"succeeded","outputs":{"summary":"What was recorded."},"evidence":{"harness":"claude"}}`
88
+ <!-- result-schema-rule:end -->
89
+
90
+ - `status` is exactly one of `succeeded`, `failed`, `blocked` or `skipped`. Never `completed`, `done` or `ok`.
91
+ - Set `evidence.harness` to `"claude"`, and `evidence.sessionId` to the value of `$CLAUDE_CODE_SESSION_ID`.
92
+ - `deliverables` is a **top-level** field, next to `status` and `outputs`. Never put it under `outputs`.
93
+ - Never ask the user anything. If only a human can answer, return `status: "blocked"` with a `blocker`.
94
+ - To re-ask a question the work item already has (`workItem.questions` in the context), set the `BQ`/`TQ` blocker's
95
+ `ref` to its key (`"ref": "BQ-2"`, on the result blocker or `raise_blocker`) so the blocker links to it instead of
96
+ creating a duplicate. The prefix must match the type; a mismatch is rejected. Omit `ref` for a new question.
97
+ - If only a person can **do** something (a spike on real hardware, an interactive session, a third-party console),
98
+ return `blocked` with a `human_task` blocker and a `runbook`: `prerequisites`, ordered `steps` with exact
99
+ `command`s, `doneWhen` and `reportFormat` (what to paste back). Keep `question` to the one-sentence ask. A
100
+ `human_task` without steps is rejected. Commands never contain secret values; name the env var or file instead.
101
+
102
+ ## Storing slot outputs
103
+
104
+ - **Parse slot JSON locally before `put_step_output`** (or any tool that takes a JSON `body`). A stray brace is the
105
+ most common failure, and it is cheaper to catch before the call.
106
+ - **When a store call fails, report its exact text**, in `outputs.gaps` or the blocker. Don't paraphrase it.
107
+ - **An opaque failure is not a `driverId` problem.** Don't change or drop `driverId` to work around an error you
108
+ can't read; a lease problem comes back as a typed problem that says so.
109
+ - **Use the `driverId` your prompt gives you, as given (the bare session id).** Never copy the envelope's
110
+ `lease.holder` (`driver:<id>`): the server adds the `driver:` prefix itself, so the prefixed form is a lease
111
+ conflict (409 `instruction_lease_conflict`) on every store call.
112
+ - A `malformed_request` result names the parser `detail`, `line` and `byte_position`. **Positions are 0-based**
113
+ (`position_base: 0`), as in the detail text: line 0 is the first line. Fix the body and retry.
114
+ - An `internal_error` result is a server fault, not your mistake. Retry once; if it persists, put its `trace_id`
115
+ in the blocker.
116
+
117
+ ## When a tool call is refused
118
+
119
+ A refusal is something to understand, not to route around. Don't retry the same call, don't reach the same result
120
+ another way (a shell write instead of Write, a different path, a document's text pasted into the result), and don't
121
+ ask the orchestrator to do it for you. Instead:
122
+
123
+ 1. Copy the refusal text exactly, character for character, including any bracketed rule name and any mention of
124
+ auto mode, a hook, a permission rule or a classifier.
125
+ 2. Note what was refused: the tool, the path or command, and what you were trying to produce.
126
+ 3. Work out which mechanism refused it, with your evidence. An auto-mode classifier block names a rule in brackets,
127
+ such as `[Data Exfiltration]`; a permission rule names the rule; a hook says it is a hook. If you can't tell, say so.
128
+ 4. Return `status: "blocked"` with a `blocker` of type `env` whose `question` holds all of the above. Keep the
129
+ work you completed, and list in `outputs.gaps` what the refusal left undone.
130
+
131
+ ## Do not
132
+
133
+ - Call `get_next_instruction` or `apply_instruction_result`. Those belong to the orchestrator.
134
+ - Call `answer_blocker` (or `devorch blocker answer`). A blocker is answered by a human; raise it and return `blocked`.
135
+ - Merge to `main` or push to `main`.
@@ -215,6 +215,8 @@ export interface WakeInputs {
215
215
  wakePending: boolean
216
216
  /** The latest run.position envelope for the watched run. */
217
217
  latest: PlatformEventEnvelope | null
218
+ /** False under `wakeMode: poll`: the skill owns the wake, so the mod submits none (default true). */
219
+ modWakes?: boolean
218
220
  }
219
221
 
220
222
  export type WakeDecision =
@@ -246,6 +248,7 @@ export function decideWake(i: WakeInputs): WakeDecision {
246
248
  * or null when the session may be woken and `watchedRunId` and `latest` are set. */
247
249
  function sessionHold(i: WakeInputs): WakeDecision | null {
248
250
  if (!i.watchedRunId) return { wake: false, reason: 'no run watched' }
251
+ if (i.modWakes === false) return { wake: false, reason: 'wakeMode poll: the skill owns the wake' }
249
252
  if (i.stopHookArmed) return { wake: false, reason: 'Stop-hook host armed' }
250
253
  if (i.turnRunning) return { wake: false, reason: 'turn running; re-evaluate when idle' }
251
254
  if (i.idleForMs !== null && i.idleForMs < SETTLE_MS)
@@ -297,8 +300,28 @@ export function parseAnswerArgs(args: string): { slug: string; blockerRef: strin
297
300
  return answer.length > 0 ? { slug, blockerRef, answer } : null
298
301
  }
299
302
 
300
- /** The only command the mod ever submits: `/devorch-step <runId>` with the id it holds (CC-4, AC-906). */
301
- export function wakeCommand(runId: string): { command: string; args: string } {
303
+ /** The step skill this plugin ships, as Claude Code names a plugin skill: `/<plugin>:<skill>`. */
304
+ export const PLUGIN_STEP_COMMAND = 'devorch-companion:devorch-step'
305
+ /** A project- or user-level `devorch-step` skill (this workspace's own copy, before it is deleted). */
306
+ export const BARE_STEP_COMMAND = 'devorch-step'
307
+
308
+ /**
309
+ * Which step command the wake submits, from the session's command names (`$.command.list()`). The plugin's own skill
310
+ * wins whenever it is listed, even beside a project-level `devorch-step`: it is the copy that ships with this mod and
311
+ * its CLI, so the two stay in step. The bare name is used only when the plugin's skill is not listed (a host that
312
+ * does not namespace plugin skills, or the mod loaded without its skills folder). With no list (the call failed),
313
+ * the plugin's name.
314
+ */
315
+ export function stepCommandName(available: readonly string[] | null): string {
316
+ if (!available || available.includes(PLUGIN_STEP_COMMAND)) return PLUGIN_STEP_COMMAND
317
+ return available.includes(BARE_STEP_COMMAND) ? BARE_STEP_COMMAND : PLUGIN_STEP_COMMAND
318
+ }
319
+
320
+ /**
321
+ * The only command the mod ever submits: the step skill (see `stepCommandName`) with the run id it holds and nothing
322
+ * else (CC-4, AC-906).
323
+ */
324
+ export function wakeCommand(runId: string, available: readonly string[] | null = null): { command: string; args: string } {
302
325
  if (!/^[0-9a-fA-F-]{36}$/.test(runId)) throw new Error('not a run id')
303
- return { command: 'devorch-step', args: runId }
326
+ return { command: stepCommandName(available), args: runId }
304
327
  }
@@ -6,9 +6,10 @@ import {
6
6
  } from './core.ts'
7
7
  import {
8
8
  HEAL_MS, LOG_MAX_BYTES, WAKE_EXPIRY_MS, afterPoll, afterWakeClaimed, afterWakeExpired, afterWatchExit,
9
- answerStdinArgv, canWatch, dedupe, handBackWake, health, isBaseUrl, logLine, parseUnwatchArgs, parseWatchArgs,
10
- resolveBaseUrl, resolveExe, respawnDelayMs, restoreWatched, runStatus, statusLine, terminalAction, tokenOf,
11
- updateHint, versionArgv, waitArgv, watchArgv, type WakeHealth, type WatchEntry,
9
+ answerStdinArgv, canWatch, dedupe, handBackWake, health, isBaseUrl, logLine, modWakes, parseUnwatchArgs,
10
+ parseWatchArgs, pollTimeoutMs, resolveBaseUrl, resolveExe, resolveSettings, respawnDelayMs, restoreWatched, runStatus,
11
+ statusLine, terminalAction, tokenOf, updateHint, versionArgv, waitArgv, wakePolicy, watchArgv, type Settings,
12
+ type WakeHealth, type WatchEntry,
12
13
  } from './supervision.ts'
13
14
 
14
15
  /**
@@ -23,7 +24,8 @@ import {
23
24
  * Long-lived loops (one per watched run) keep running after that hook returns, as the host's spawn example shows.
24
25
  *
25
26
  * Invariants (design-L0 Domain Integrity Constraints):
26
- * - only `wakeCommand(runId)` reaches `$.command.run`, with a run id the mod validated (CC-4);
27
+ * - only `wakeCommand(runId, names)` reaches `$.command.run`: the step skill (the plugin's own
28
+ * `devorch-companion:devorch-step`, else a listed bare `devorch-step`) with a run id the mod validated (CC-4);
27
29
  * - no blocker or question text in the status line, toasts, tool results, command replies or the log (CC-4, D19);
28
30
  * - no wake inside a main-loop turn or within SETTLE_MS of its end (CC-5), none while the Stop-hook host is armed (CC-6);
29
31
  * - one long-lived `devorch run watch` child per watched run on rungs 1-2, zero processes per event (AC-4);
@@ -31,7 +33,7 @@ import {
31
33
  *
32
34
  * Spike-conditional branches (design-L0): this file implements the DEFAULT branch of each row (no console flash on
33
35
  * spawn/run, main-loop `turn.complete` with `agentId` undefined, `$.command.run` queues until idle and accepts the
34
- * `devorch-step` skill, a `clock.after` scheduled in `turn.complete` runs outside the turn). The Windows spike
36
+ * step skill, a `clock.after` scheduled in `turn.complete` runs outside the turn). The Windows spike
35
37
  * (`spike-tq27.md`) confirms or changes them; a rejected wake already degrades to `healthy: false`.
36
38
  */
37
39
 
@@ -39,8 +41,6 @@ const TOOL = 'mcp__devorch-companion__devorch_companion'
39
41
  const STOP_HOOK_MARKER = '.claude/hooks/interactive-loop/state/armed.json'
40
42
  /** How long tool `watch` waits for the first envelope or child exit before it answers (D16). */
41
43
  const FIRST_SIGNAL_MS = 5_000
42
- /** A rung-3 `run wait` parks 25 s on the server; the process gets 10 s more. */
43
- const POLL_TIMEOUT_MS = 35_000
44
44
 
45
45
  type Run = {
46
46
  entry: WatchEntry
@@ -81,6 +81,8 @@ export const register: Register = (on, options) => {
81
81
  let wakeHealth: WakeHealth = { misses: 0, wakeBroken: false }
82
82
  let turnRunning = false
83
83
  let lastTurnEnd: number | null = null
84
+ /** Wake mode and timing knobs: the plugin options now, refined with the DEVORCH_* environment at session start. */
85
+ let settings: Settings = resolveSettings({}, options)
84
86
  /** Diagnostics for the status action: the last wake decision and how far the last submit got. */
85
87
  const diag: { decision?: { at: number; wake: boolean; reason?: string }; submit?: { at: number; stage: string } } = {}
86
88
 
@@ -90,13 +92,29 @@ export const register: Register = (on, options) => {
90
92
  // ---- pure views over the state (no host calls) ----------------------------------------------------------------
91
93
 
92
94
  function healthOf(run: Run | null): { healthy: boolean; reason?: string } {
93
- return health({ cliOk: cli.ok, cliReason: cli.reason, stopHookArmed, wakeBroken: wakeHealth.wakeBroken, rung: run ? run.ladder.rung : null })
95
+ return health({
96
+ pollMode: settings.wakeMode === 'poll', cliOk: cli.ok, cliReason: cli.reason, stopHookArmed,
97
+ wakeBroken: wakeHealth.wakeBroken, rung: run ? run.ladder.rung : null,
98
+ })
99
+ }
100
+
101
+ /** The effective wake policy the skills branch on (`wake.effective`). */
102
+ function wakeOf(run: Run | null): ReturnType<typeof wakePolicy> {
103
+ return wakePolicy(settings.wakeMode, healthOf(run), settings.fallbackWakeupSeconds)
94
104
  }
95
105
 
96
106
  function statusObject(runId?: string): Record<string, unknown> {
97
107
  const asked = runId ? runs.get(runId) ?? null : null
98
108
  return {
99
109
  ...healthOf(asked),
110
+ wake: wakeOf(asked),
111
+ config: {
112
+ wakeMode: settings.wakeMode,
113
+ fallbackWakeupSeconds: settings.fallbackWakeupSeconds,
114
+ longPollSeconds: settings.longPollSeconds,
115
+ sources: settings.sources,
116
+ warnings: settings.warnings,
117
+ },
100
118
  cli: { ok: cli.ok, version: cli.version, path: cli.exe },
101
119
  stopHookArmed,
102
120
  wakeBroken: wakeHealth.wakeBroken,
@@ -160,7 +178,8 @@ export const register: Register = (on, options) => {
160
178
 
161
179
  function redraw(): void {
162
180
  const views = [...runs.values()].map((r) => ({ runId: r.entry.runId, latest: r.latest, ladder: r.ladder }))
163
- const hint = cli.ok && cli.version ? updateHint(modVersion, cli.version) : null
181
+ const hints = [cli.ok && cli.version ? updateHint(modVersion, cli.version) : null, settings.wakeMode === 'poll' ? 'wake: poll' : null]
182
+ const hint = hints.filter((h) => h !== null).join(' | ') || null
164
183
  $.ui.status(cli.ok ? statusLine(views, stopHookArmed, hint) : `DevOrch: offline (${cli.reason})`)
165
184
  }
166
185
 
@@ -170,7 +189,7 @@ export const register: Register = (on, options) => {
170
189
  run.handedBack = false
171
190
  return
172
191
  }
173
- if (handBackWake({ reportedHealthy: run.reportedHealthy, nowHealthy, stopHookArmed, handedBack: run.handedBack })) {
192
+ if (modWakes(settings.wakeMode) && handBackWake({ reportedHealthy: run.reportedHealthy, nowHealthy, stopHookArmed, handedBack: run.handedBack })) {
174
193
  run.handedBack = true
175
194
  run.reportedHealthy = false
176
195
  $.clock.after(0, () => void submit(run.entry.runId, 'hand-back'))
@@ -203,6 +222,7 @@ export const register: Register = (on, options) => {
203
222
  stopHookArmed,
204
223
  wakePending: run.pendingWake,
205
224
  latest: run.latest,
225
+ modWakes: modWakes(settings.wakeMode),
206
226
  })
207
227
  diag.decision = { at: now(), wake: decision.wake, ...(decision.wake ? {} : { reason: decision.reason }) }
208
228
  if (decision.wake) {
@@ -238,8 +258,10 @@ export const register: Register = (on, options) => {
238
258
  wakeInFlight = runId
239
259
  log(runId, why === 'wake' ? 'wake-submitted' : 'hand-back-submitted', { token: run.lastToken })
240
260
  try {
261
+ // The plugin's step skill (/devorch-companion:devorch-step) unless only a bare devorch-step is listed.
262
+ const names = await $.command.list().then((list) => list.map((c) => c.name)).catch(() => null)
241
263
  diag.submit = { at: now(), stage: 'command.run called' }
242
- await $.command.run(wakeCommand(runId))
264
+ await $.command.run(wakeCommand(runId, names))
243
265
  diag.submit = { at: now(), stage: 'command.run resolved' }
244
266
  } catch (err) {
245
267
  diag.submit = { at: now(), stage: `command.run rejected: ${String(err).slice(0, 200)}` }
@@ -248,7 +270,7 @@ export const register: Register = (on, options) => {
248
270
  run.pendingWake = false
249
271
  run.expiry?.cancel()
250
272
  wakeHealth = { ...wakeHealth, wakeBroken: true }
251
- $.ui.toast('DevOrch: could not wake the session; /devorch-step keeps its own wakeup')
273
+ $.ui.toast('DevOrch: could not wake the session; the step skill keeps its own wakeup')
252
274
  log(runId, 'wake-rejected')
253
275
  redraw()
254
276
  for (const r of runs.values()) checkHandBack(r)
@@ -379,7 +401,8 @@ export const register: Register = (on, options) => {
379
401
  let exitCode = 75
380
402
  let stdout = ''
381
403
  try {
382
- const r = await $.process.run(waitArgv(exe, run.entry.runId, run.entry.baseUrl, run.lastToken), { timeoutMs: POLL_TIMEOUT_MS })
404
+ const argv = waitArgv(exe, run.entry.runId, run.entry.baseUrl, run.lastToken, settings.longPollSeconds)
405
+ const r = await $.process.run(argv, { timeoutMs: pollTimeoutMs(settings.longPollSeconds) })
383
406
  exitCode = r.exitCode
384
407
  stdout = r.stdout
385
408
  } catch {
@@ -552,6 +575,18 @@ export const register: Register = (on, options) => {
552
575
  ops = { watch, unwatch, firstSignal, evaluateAll, answer, shutdown }
553
576
 
554
577
  void (async () => {
578
+ try {
579
+ // The DEVORCH_* variables win over the plugin options (project-scope options may not apply; project `env` does).
580
+ // Literal names: the host lists the variables a module reads. Keep them equal to supervision's SETTING_ENV.
581
+ settings = resolveSettings({
582
+ wakeMode: (await $.env.get('DEVORCH_WAKE_MODE')) ?? undefined,
583
+ fallbackWakeupSeconds: (await $.env.get('DEVORCH_FALLBACK_WAKEUP_SECONDS')) ?? undefined,
584
+ longPollSeconds: (await $.env.get('DEVORCH_LONG_POLL_SECONDS')) ?? undefined,
585
+ }, options)
586
+ for (const w of settings.warnings) $.ui.toast(`DevOrch: ${w}`)
587
+ } catch {
588
+ // keep the option-only settings
589
+ }
555
590
  try {
556
591
  const env = await $.process.hookEnv()
557
592
  pluginRoot = env.CLAUDE_PLUGIN_ROOT ?? ''
@@ -565,10 +600,12 @@ export const register: Register = (on, options) => {
565
600
  await $.tool.register({
566
601
  name: 'devorch_companion',
567
602
  description:
568
- 'The DevOrch companion mod. status {runId?}: whether this session wakes itself for the run (healthy) or the ' +
569
- 'skill must keep its own ScheduleWakeup (healthy:false), plus each watched run\'s rung, control, lease and ' +
570
- 'open blocker refs. watch {runId, baseUrl?}: arm the wake for a run this session drives in a loop (answers ' +
571
- 'after the first event, at most 5 s). unwatch {runId}: stop.',
603
+ 'The DevOrch companion mod. status {runId?}: the wake policy for the run in `wake` (effective "push": the ' +
604
+ 'companion wakes this session, run the step once and schedule nothing; "poll": the skill drives /loop + ' +
605
+ 'ScheduleWakeup with wake.fallbackWakeupSeconds; "unavailable": wakeMode push but the companion is ' +
606
+ 'unhealthy, report and stop), plus healthy, config and each watched run\'s rung, control, lease and open ' +
607
+ 'blocker refs. watch {runId, baseUrl?}: arm the watch for a run this session drives (answers after the ' +
608
+ 'first event, at most 5 s, with the same wake field). unwatch {runId}: stop.',
572
609
  inputSchema: {
573
610
  type: 'object',
574
611
  properties: {
@@ -654,7 +691,7 @@ export const register: Register = (on, options) => {
654
691
  await ops.firstSignal(run)
655
692
  const h = healthOf(run)
656
693
  run.reportedHealthy = h.healthy
657
- return reply({ watching: runs.has(runId), ...h })
694
+ return reply({ watching: runs.has(runId), ...h, wake: wakePolicy(settings.wakeMode, h, settings.fallbackWakeupSeconds) })
658
695
  }
659
696
  if (input.action === 'unwatch') {
660
697
  await ops.unwatch(String(input.runId ?? ''))
@@ -26,11 +26,13 @@ export const CLI_OPTIONS = {
26
26
  'run wait': ['--since', '--seconds', '--base-url'],
27
27
  'blocker answer': ['--stdin', '--json', '--base-url'],
28
28
  version: ['--json'],
29
+ // Not built by the mod: the plugin's .mcp.json runs it (checked by a test against that file).
30
+ 'companion mcp': ['--api-base'],
29
31
  } as const satisfies Record<string, readonly string[]>
30
32
 
31
33
  export type CliCommand = keyof typeof CLI_OPTIONS
32
34
 
33
- /** Rung-3 long-poll length in seconds (the server's park limit). */
35
+ /** Rung-3 long-poll length in seconds by default: the server's park limit (the CLI accepts 0-25). */
34
36
  export const WAIT_SECONDS = 25
35
37
 
36
38
  /** `devorch run watch <runId> --base-url <url> [--since <token>]`: the long-lived child (rungs 1-2, D15). */
@@ -39,10 +41,17 @@ export function watchArgv(exe: string, runId: string, baseUrl: string, since: st
39
41
  return [exe, 'run', 'watch', runId, '--base-url', baseUrl, ...(since ? ['--since', since] : [])]
40
42
  }
41
43
 
42
- /** `devorch run wait <runId> --seconds 25 --base-url <url> [--since <token>]`: one rung-3 long-poll (D5). */
43
- export function waitArgv(exe: string, runId: string, baseUrl: string, since: string | null): string[] {
44
+ /** `devorch run wait <runId> --seconds <n> --base-url <url> [--since <token>]`: one rung-3 long-poll (D5). `seconds`
45
+ * is the `longPollSeconds` setting, clamped again here so a bad value can never reach argv. */
46
+ export function waitArgv(exe: string, runId: string, baseUrl: string, since: string | null, seconds: number = WAIT_SECONDS): string[] {
44
47
  assertRunId(runId)
45
- return [exe, 'run', 'wait', runId, '--seconds', String(WAIT_SECONDS), '--base-url', baseUrl, ...(since ? ['--since', since] : [])]
48
+ const s = clampInt(seconds, LONG_POLL_RANGE[0], LONG_POLL_RANGE[1], WAIT_SECONDS)
49
+ return [exe, 'run', 'wait', runId, '--seconds', String(s), '--base-url', baseUrl, ...(since ? ['--since', since] : [])]
50
+ }
51
+
52
+ /** How long the mod lets one `run wait` process live: its park time plus 10 s. */
53
+ export function pollTimeoutMs(longPollSeconds: number): number {
54
+ return (clampInt(longPollSeconds, LONG_POLL_RANGE[0], LONG_POLL_RANGE[1], WAIT_SECONDS) + 10) * 1_000
46
55
  }
47
56
 
48
57
  /** Append the run's base URL (D14). */
@@ -68,7 +77,7 @@ export function versionArgv(exe: string): string[] {
68
77
  /** The command (`run watch`, `version`, ...) and the options an argv uses, for the contract test. */
69
78
  export function optionsOf(argv: readonly string[]): { command: string; options: string[] } {
70
79
  const words = argv.slice(1)
71
- const command = words[0] === 'run' || words[0] === 'blocker' ? `${words[0]} ${words[1]}` : (words[0] ?? '')
80
+ const command = words[0] === 'run' || words[0] === 'blocker' || words[0] === 'companion' ? `${words[0]} ${words[1]}` : (words[0] ?? '')
72
81
  return { command, options: words.filter((w) => w.startsWith('--')) }
73
82
  }
74
83
 
@@ -258,10 +267,20 @@ export function resolveExe(s: ExeSources): { exe: string; source: 'env' | 'userC
258
267
 
259
268
  // ---- base URL (D14) -------------------------------------------------------------------------------------------
260
269
 
261
- /** Explicit argument -> `userConfig.apiBase` -> `DEVORCH_API_BASE` -> the CLI default. Trailing slashes trimmed. */
270
+ /**
271
+ * The hosted DevOrch API: the plugin's default when nothing names another server. Keep equal to
272
+ * `CompanionCli.ProdApiBase` (C#, used by `devorch companion mcp`) and the `apiBase` default in plugin.json.
273
+ */
274
+ export const PROD_API_BASE = 'https://api.devorchestrator.com'
275
+
276
+ /**
277
+ * Explicit argument (a watch's own base URL) -> `DEVORCH_API_BASE` -> `userConfig.apiBase` -> the hosted API, the same
278
+ * rule `devorch companion mcp` applies to the bundled MCP server, so the watches and the skills' tools hit one server.
279
+ * A value that is not an http(s) URL (empty included) is skipped. Trailing slashes trimmed.
280
+ */
262
281
  export function resolveBaseUrl(explicit: unknown, userConfig: unknown, env: string | undefined): string {
263
- const pick = [explicit, userConfig, env].find(nonEmpty)
264
- return (pick ?? 'http://localhost:8700').trim().replace(/\/+$/, '')
282
+ const pick = [explicit, env, userConfig].map((v) => (typeof v === 'string' ? v.trim() : v)).find(isBaseUrl)
283
+ return (pick ?? PROD_API_BASE).replace(/\/+$/, '')
265
284
  }
266
285
 
267
286
  /** Only an absolute http(s) URL may reach argv as `--base-url`. */
@@ -290,6 +309,9 @@ export function updateHint(modVersion: string, cliVersion: string): string | nul
290
309
  // ---- health (D6) ----------------------------------------------------------------------------------------------
291
310
 
292
311
  export interface HealthInputs {
312
+ /** `wakeMode` is `poll`: the skill owns the wake, so the mod never reports itself healthy (an older skill copy that
313
+ * branches on `healthy` then keeps its own wakeup). */
314
+ pollMode?: boolean
293
315
  cliOk: boolean
294
316
  cliReason: string
295
317
  stopHookArmed: boolean
@@ -305,9 +327,129 @@ export function health(i: HealthInputs): { healthy: boolean; reason?: string } {
305
327
  if (i.stopHookArmed) return { healthy: false, reason: 'Stop-hook host armed' }
306
328
  if (i.wakeBroken) return { healthy: false, reason: 'wake mechanism broken' }
307
329
  if (i.rung === 4) return { healthy: false, reason: 'run offline (rung 4)' }
330
+ if (i.pollMode) return { healthy: false, reason: 'wakeMode poll: the skill owns the wake' }
308
331
  return { healthy: true }
309
332
  }
310
333
 
334
+ // ---- wake modes: who wakes an interactive run, and the settings behind it --------------------------------------
335
+
336
+ /**
337
+ * `auto` (default): the companion wakes the session while it is healthy, else the skill polls with `/loop` and
338
+ * `ScheduleWakeup`. `push`: the companion only; when it is unhealthy the skill reports that and stops instead of
339
+ * polling. `poll`: never rely on the companion's wake (the mod submits none; it still shows the status line).
340
+ */
341
+ export const WAKE_MODES = ['auto', 'push', 'poll'] as const
342
+ export type WakeMode = (typeof WAKE_MODES)[number]
343
+
344
+ export const FALLBACK_WAKEUP_DEFAULT = 1800
345
+ export const FALLBACK_WAKEUP_RANGE = [60, 3600] as const
346
+ export const LONG_POLL_RANGE = [5, WAIT_SECONDS] as const
347
+
348
+ export type SettingSource = 'env' | 'option' | 'default'
349
+
350
+ /** The environment variable that overrides each plugin option. It wins, because project-scope plugin options may not
351
+ * apply while a project's settings `env` does. */
352
+ export const SETTING_ENV = {
353
+ wakeMode: 'DEVORCH_WAKE_MODE',
354
+ fallbackWakeupSeconds: 'DEVORCH_FALLBACK_WAKEUP_SECONDS',
355
+ longPollSeconds: 'DEVORCH_LONG_POLL_SECONDS',
356
+ } as const
357
+
358
+ export type SettingName = keyof typeof SETTING_ENV
359
+
360
+ export interface Settings {
361
+ wakeMode: WakeMode
362
+ /** The skill's safety-net `ScheduleWakeup` under poll, in seconds. */
363
+ fallbackWakeupSeconds: number
364
+ /** Rung-3 `devorch run wait --seconds`. */
365
+ longPollSeconds: number
366
+ /** Where each value came from. */
367
+ sources: Record<SettingName, SettingSource>
368
+ /** Invalid or clamped values, reported in the tool's `status` (never fatal). */
369
+ warnings: string[]
370
+ }
371
+
372
+ /**
373
+ * Resolve the wake settings. Per setting, the first non-empty of the `DEVORCH_*` environment variable, the plugin
374
+ * option, then the default. An unknown mode falls back to `auto` and a non-number to its default, each with a
375
+ * warning; a number outside its range is clamped, with a warning.
376
+ */
377
+ export function resolveSettings(env: Partial<Record<SettingName, string | undefined>>, options: Partial<Record<SettingName, unknown>> | undefined): Settings {
378
+ const warnings: string[] = []
379
+ const pick = (name: SettingName): { value: unknown; source: SettingSource } => {
380
+ if (present(env[name])) return { value: env[name], source: 'env' }
381
+ if (present(options?.[name])) return { value: options?.[name], source: 'option' }
382
+ return { value: undefined, source: 'default' }
383
+ }
384
+ const label = (name: SettingName, source: SettingSource): string => (source === 'env' ? SETTING_ENV[name] : `option ${name}`)
385
+
386
+ const mode = pick('wakeMode')
387
+ let wakeMode: WakeMode = 'auto'
388
+ if (mode.source !== 'default') {
389
+ const v = String(mode.value).trim().toLowerCase()
390
+ if ((WAKE_MODES as readonly string[]).includes(v)) wakeMode = v as WakeMode
391
+ else warnings.push(`${label('wakeMode', mode.source)}: unknown wake mode "${String(mode.value).trim().slice(0, 20)}"; using auto`)
392
+ }
393
+
394
+ const number = (name: SettingName, range: readonly [number, number], fallback: number): { value: number; source: SettingSource } => {
395
+ const p = pick(name)
396
+ if (p.source === 'default') return { value: fallback, source: 'default' }
397
+ const n = typeof p.value === 'number' ? p.value : Number(String(p.value).trim())
398
+ if (!Number.isFinite(n)) {
399
+ warnings.push(`${label(name, p.source)}: not a number; using ${fallback}`)
400
+ return { value: fallback, source: p.source }
401
+ }
402
+ const clamped = clampInt(n, range[0], range[1], fallback)
403
+ if (clamped !== n) warnings.push(`${label(name, p.source)}: ${n} is outside ${range[0]}..${range[1]}; using ${clamped}`)
404
+ return { value: clamped, source: p.source }
405
+ }
406
+ const fallback = number('fallbackWakeupSeconds', FALLBACK_WAKEUP_RANGE, FALLBACK_WAKEUP_DEFAULT)
407
+ const longPoll = number('longPollSeconds', LONG_POLL_RANGE, WAIT_SECONDS)
408
+
409
+ return {
410
+ wakeMode,
411
+ fallbackWakeupSeconds: fallback.value,
412
+ longPollSeconds: longPoll.value,
413
+ sources: { wakeMode: mode.source, fallbackWakeupSeconds: fallback.source, longPollSeconds: longPoll.source },
414
+ warnings,
415
+ }
416
+ }
417
+
418
+ export interface WakePolicy {
419
+ mode: WakeMode
420
+ /** `push`: the companion wakes the session (run the step once, no /loop, schedule nothing). `poll`: the skill wakes
421
+ * itself (/loop + ScheduleWakeup). `unavailable`: `push` was asked for but the companion is unhealthy; the skill
422
+ * reports it and stops. */
423
+ effective: 'push' | 'poll' | 'unavailable'
424
+ owner: 'companion' | 'skill' | 'none'
425
+ fallbackWakeupSeconds: number
426
+ reason: string
427
+ }
428
+
429
+ /** The one field the skills branch on: the configured mode resolved against the companion's health right now. */
430
+ export function wakePolicy(mode: WakeMode, h: { healthy: boolean; reason?: string }, fallbackWakeupSeconds: number): WakePolicy {
431
+ const base = { mode, fallbackWakeupSeconds }
432
+ if (mode === 'poll') return { ...base, effective: 'poll', owner: 'skill', reason: 'wakeMode poll: /loop + ScheduleWakeup' }
433
+ if (h.healthy) return { ...base, effective: 'push', owner: 'companion', reason: 'the companion is healthy and wakes the session' }
434
+ const why = h.reason ?? 'companion unhealthy'
435
+ if (mode === 'push') return { ...base, effective: 'unavailable', owner: 'none', reason: `wakeMode push, but ${why}` }
436
+ return { ...base, effective: 'poll', owner: 'skill', reason: `companion unhealthy (${why}); the skill polls` }
437
+ }
438
+
439
+ /** Whether the mod itself submits wakes (position-change and hand-back): every mode but `poll`. */
440
+ export function modWakes(mode: WakeMode): boolean {
441
+ return mode !== 'poll'
442
+ }
443
+
444
+ function present(v: unknown): boolean {
445
+ return (typeof v === 'string' && v.trim().length > 0) || (typeof v === 'number' && !Number.isNaN(v))
446
+ }
447
+
448
+ function clampInt(n: number, min: number, max: number, fallback: number): number {
449
+ if (!Number.isFinite(n)) return fallback
450
+ return Math.min(max, Math.max(min, Math.round(n)))
451
+ }
452
+
311
453
  // ---- the status line (D7) -------------------------------------------------------------------------------------
312
454
 
313
455
  export interface RunView {
@@ -0,0 +1,115 @@
1
+ ---
2
+ name: devorch-step
3
+ argument-hint: "<runId>"
4
+ description: Processes the next instruction of a DevOrch run by dispatching its work to a devorch-step-worker subagent, keeping the main thread as a thin orchestrator; the companion mod wakes it for the next one (push) or /loop does (poll). TRIGGERS - devorch step, next devorch step, step this run, loop devorch run. USE WHEN - driving a DevOrch SDLC run one instruction at a time with /devorch-companion:devorch-step <runId>, woken by the companion mod or repeated with /loop /devorch-companion:devorch-step <runId>.
5
+ allowed-tools: mcp__plugin_devorch-companion_devorch__get_next_instruction, mcp__plugin_devorch-companion_devorch__apply_instruction_result, mcp__plugin_devorch-companion_devorch__get_run_position, mcp__plugin_devorch-companion_devorch__raise_blocker, mcp__devorch-companion__devorch_companion, Bash(uv run scripts/worktree_manage.py *), Bash(uv run scripts/app_run.py *)
6
+ ---
7
+
8
+ # DevOrch Step
9
+
10
+ `/devorch-companion:devorch-step <runId>` processes the run's next instruction and, after the worker hands back, goes
11
+ straight on to the one after. Between instructions that can't start yet (a worker running, a `WAIT`), something
12
+ must wake the session again: the companion mod (**push**, realtime) or `/loop` with `ScheduleWakeup` (**poll**, timed).
13
+ The **Wake** check below decides which, on every firing.
14
+
15
+ **The main thread only orchestrates.** Never read stage docs, source files or the context bundle here, and never
16
+ call `get_context_for_instruction`. The worker does all of that. The only output per instruction is one status line.
17
+
18
+ **Tools.** Every DevOrch verb below (`get_next_instruction`, `apply_instruction_result`, `get_run_position`,
19
+ `raise_blocker`) is a tool of the DevOrch MCP server. This plugin bundles one, so the tools read
20
+ `mcp__plugin_devorch-companion_devorch__<verb>`. If that server is absent, use the same verb from whichever DevOrch MCP
21
+ server this session has (for example `mcp__devorch-local-mcp__<verb>`); never mix two servers within one run, because
22
+ they may point at different backends.
23
+
24
+ ## Wake: check it at the start of every firing
25
+
26
+ Exactly one thing wakes this session for a run. Before anything else in a firing (a launch, a wake from the mod, a
27
+ `/loop` tick or a worker's hand-back):
28
+
29
+ 1. If the companion tool `mcp__devorch-companion__devorch_companion` exists, call it with `{action: "watch", runId}`.
30
+ Re-watching a watched run is cheap and answers at once. Add `baseUrl` only when this run lives on a different
31
+ server from the plugin's `apiBase` setting (or `DEVORCH_API_BASE`), such as a worktree slot
32
+ `http://localhost:8704`. Read **`wake.effective`** and `wake.fallbackWakeupSeconds` from the answer. Don't
33
+ re-derive the policy from `healthy`.
34
+ 2. No companion tool: treat it as `poll` with a 1800-second fallback.
35
+ 3. Hold that value for the rest of the firing:
36
+
37
+ | `wake.effective` | Who wakes the session | What this firing does about it |
38
+ |---|---|---|
39
+ | `push` | The companion mod: it submits `/devorch-companion:devorch-step <runId>` within seconds of the run becoming actionable (a blocker answered, a lease freed or lapsed, the run finished), and hands the wake back once if it turns unhealthy. | **Schedule no wakeup, anywhere.** If this firing runs under `/loop`, stop the loop once (`ScheduleWakeup(stop: true)`) and say in one line that the companion owns the wake now; then carry on. |
40
+ | `poll` | You: `ScheduleWakeup` under `/loop`. | Schedule the wakeups named below. If this firing is not under `/loop` (no `ScheduleWakeup` to call), start `/loop /devorch-companion:devorch-step <runId>` at the point where a wakeup is due instead, and end the turn; its first firing picks up from there. |
41
+ | `unavailable` | Nobody: `wakeMode` is `push` but the companion is unhealthy. | Finish a worker's hand-back if this firing is one (steps 5 to 7, so no work is lost), then launch nothing: print `wake.reason`, say `/devorch-companion:devorch-step <runId>` resumes the run once the companion is fixed (or `wakeMode` is set to `auto`/`poll`), stop any `/loop` with `ScheduleWakeup(stop: true)`, and end the turn. |
42
+
43
+ "Schedule a wakeup" below always means: under `poll` only, as this table says.
44
+
45
+ ## A firing has two halves
46
+
47
+ Subagents run asynchronously, so one instruction spans two turns: **launch** ends the turn, and the worker's
48
+ hand-back starts **finish**.
49
+
50
+ ### Launch
51
+
52
+ 1. **Don't double-dispatch.** If a worker launched in this session for this run hasn't handed back, launch nothing.
53
+ Under `poll`, schedule another fallback wakeup (`wake.fallbackWakeupSeconds`); under `push`, schedule nothing.
54
+ End the turn.
55
+ 2. Call `get_next_instruction(runId, driverId)` and branch on `control`. `driverId` is this session's id
56
+ (`$CLAUDE_CODE_SESSION_ID`); use the same value on `apply_instruction_result`, because the instruction is leased
57
+ to it. Pass the **bare** id: the envelope's `lease.holder` reads `driver:<id>` because the server adds that prefix
58
+ itself, so sending the prefixed form back becomes `driver:driver:<id>` and every lease-checked call is a 409. If
59
+ the tool doesn't offer `driverId`, omit it on both calls:
60
+
61
+ | `control` | Action |
62
+ |---|---|
63
+ | `DONE` / `ESCALATE` / `ABORT` | PushNotification with the outcome and `reason`. Under `/loop`, `ScheduleWakeup(stop: true)`. Never self-heal. |
64
+ | `WAIT` | Print the `reason` and open blockers from `get_run_position`. Under `push`, end the turn: the mod wakes the session when the run can move. Under `poll`, schedule a wakeup after `retryAfterSeconds` (else `wake.fallbackWakeupSeconds`). |
65
+ | `CONTINUE` | Go to 3. |
66
+
67
+ The answer to a blocker can be given from here with `/devorch-answer <slug> <ref> <answer>` (mod) or
68
+ `devorch blocker answer <slug> <ref> --text ...` (CLI); never answer it yourself.
69
+
70
+ Re-fetching an instruction that was dispatched but never applied returns the same `instructionId`, so resuming
71
+ after a crash is safe.
72
+ 3. **Worktree, when `node.stage` is `implement`, `review` or `qa`.**
73
+ - **In the DevOrch workspace** (the project root has `scripts/worktree_manage.py` and `scripts/app_run.py`): the
74
+ worktree is named after `inputs.workItemSlug`. Check `uv run scripts/worktree_manage.py list`; if it's absent,
75
+ run `uv run scripts/worktree_manage.py create <slug>` (or `create <slug> --start` to create and start it in one
76
+ command). Then run `uv run scripts/app_run.py up --wait` from the worktree root (exit 4 = started but not healthy
77
+ in time; 5 = its port is held by another checkout's process). Pass its absolute path to the worker.
78
+ - **Anywhere else**, pass `none`: the worker works in the current checkout.
79
+
80
+ For earlier stages, pass `none`.
81
+ 4. Launch one `devorch-step-worker` subagent (this plugin's is `devorch-companion:devorch-step-worker`; a project-level
82
+ `devorch-step-worker` does the same job) with this prompt, then end the turn:
83
+
84
+ ```
85
+ runId: <runId>
86
+ instructionId: <instructionId>
87
+ worktree: <absolute path | none>
88
+ driverId: <this session's bare id, never the "driver:"-prefixed lease holder>
89
+ Do this step's work, including writing its stage documents under sdlc/<slug>/ and any code changes, then
90
+ return the result JSON. Parse slot JSON locally before put_step_output; if a store call fails, report its
91
+ exact text, and don't blame driverId for an opaque failure.
92
+ ```
93
+
94
+ Under `poll`, first schedule a fallback wakeup of `wake.fallbackWakeupSeconds` (1800 by default) in case the
95
+ worker never hands back. Under `push`, schedule nothing: the mod wakes the session if the worker's instruction
96
+ lease lapses without a result.
97
+
98
+ ### Finish (on the worker's hand-back)
99
+
100
+ 5. Parse the hand-back as one JSON object. If it doesn't parse, or step 6 rejects it, relaunch the worker once with
101
+ the error appended. On a second failure, call `raise_blocker` with type `error` and treat the run as `WAIT`.
102
+ 6. Call `apply_instruction_result(runId, instructionId, <result JSON>, driverId)`.
103
+ 7. Print one line and nothing else about the work, such as `qa/execute DONE (pass 1) - 12/12 passed`.
104
+ 8. **Don't wait for a wakeup, with or without `/loop`: go straight back to Launch step 2 in this same turn** and fetch
105
+ the next instruction (after the Wake check, unless it said `unavailable`). A `CONTINUE` launches the next worker
106
+ now; a `WAIT` or terminal `control` is handled by the step 2 table. This is what keeps a push-driven run snappy:
107
+ the mod only has to wake the session when the run was waiting on something outside it.
108
+
109
+ ## Anti-patterns
110
+
111
+ - Doing a step's work in the main thread.
112
+ - Echoing the worker's result, or a summary longer than the status line.
113
+ - Scheduling a wakeup, or starting `/loop`, while `wake.effective` is `push`: two wake owners fire twice.
114
+ - Polling when `wake.effective` is `unavailable`: the user chose push only.
115
+ - Merging to `main` during a run. That's a human confirmation after `DONE`.
@@ -0,0 +1,188 @@
1
+ ---
2
+ name: sdlc-drive
3
+ argument-hint: "<integrationExternalId | issueKey | --run <runId>> [--headless | --interactive] [--integration <id>]"
4
+ description: The Claude-side in-session entry + demo wedge for the Sequential Autopilot - discover an assigned issue, claim it, verify the subscription, start an SDLC run, then drive it to DONE either Interactive (default, live in-session turns) or Headless (--headless, devorch run supervise, backgrounded). TRIGGERS - sdlc drive, claim and run my issue, claim my assigned issue, drive my ticket, autopilot my issue, run my assigned issue. USE WHEN - the user wants to claim an assigned tracker issue from Claude Code and have the autopilot take it research->qa to DONE, watched live; or to launch/host a Sequential Autopilot run.
5
+ allowed-tools: mcp__plugin_devorch-companion_devorch__list_assigned_issues, mcp__plugin_devorch-companion_devorch__next_assigned_issue, mcp__plugin_devorch-companion_devorch__claim_issue, mcp__plugin_devorch-companion_devorch__start_sdlc_for_issue, mcp__plugin_devorch-companion_devorch__whoami, mcp__plugin_devorch-companion_devorch__get_next_instruction, mcp__plugin_devorch-companion_devorch__apply_instruction_result, mcp__plugin_devorch-companion_devorch__get_run_position, mcp__devorch-companion__devorch_companion, Bash(devorch run *), Bash(*devorch.exe run *), Bash(*/devorch run *)
6
+ ---
7
+
8
+ # SDLC Drive
9
+
10
+ The **in-session entry point + demo wedge** for the Sequential Autopilot: from inside Claude Code the
11
+ user says *"claim and run my assigned issue"* and this skill discovers an assigned tracker issue,
12
+ claims it race-safely, verifies the subscription, opens an SDLC run, and then **drives that run to a
13
+ terminal state** in one of two run modes.
14
+
15
+ This skill **does NOT implement the loop.** Both run modes wrap the **same `step_once` primitive**:
16
+
17
+ - **Interactive** (default, the headline demo) — `/devorch-companion:devorch-step` runs **inside this
18
+ session**, woken by the companion mod the moment the run can move (push), or under `/loop` when the mod can't
19
+ (poll); each step's work happens in a subagent, and you steer between steps.
20
+ - **Headless** (opt-in with `--headless`, the proven spine) — the loop runs **detached** in
21
+ `devorch run supervise` (fresh `claude -p` per step, `ANTHROPIC_API_KEY`-strip → guaranteed
22
+ subscription billing); you watch via the **portal**.
23
+
24
+ On a terminal `control` the skill **NOTIFIES** (PushNotification) — it does **not** self-heal. That is
25
+ the explicit design boundary: the backend program counter owns advancement; this skill claims, starts,
26
+ launches/hosts, and reports.
27
+
28
+ ## Tools and server
29
+
30
+ Every verb below (`list_assigned_issues`, `next_assigned_issue`, `claim_issue`, `whoami`, `start_sdlc_for_issue`,
31
+ `get_next_instruction`, `apply_instruction_result`, `get_run_position`) is a tool of the **DevOrch MCP server**. This
32
+ plugin bundles one (`devorch companion mcp`), so the tools read `mcp__plugin_devorch-companion_devorch__<verb>`. If that
33
+ server is missing, use the same verb from whichever DevOrch MCP server this session has, and keep to one server for
34
+ the whole run.
35
+
36
+ The bundled server, the companion mod's watches and the commands below all target one backend: the plugin's
37
+ `apiBase` setting (default `https://api.devorchestrator.com`), overridden by `DEVORCH_API_BASE`. Call that URL
38
+ `<apiBase>` below.
39
+
40
+ **If a tool call fails with 401 / "Run `devorch login` first"**, the CLI has no session for `<apiBase>`. Tell the user
41
+ to run `devorch login --oauth --base-url <apiBase>` in a terminal (it opens a browser) and then reconnect the server
42
+ with `/mcp`; don't try to log in for them.
43
+
44
+ ## Protocol
45
+
46
+ **Resuming an existing run:** if the argument is a run id (a GUID passed as `--run <runId>`), skip steps 1-4 and
47
+ go straight to RUN with it.
48
+
49
+ ### 1. DISCOVER — find an assigned issue (Read band, always available)
50
+
51
+ You need the **integration's externalId** (`{id}` below) — the issue-tracking integration whose agent
52
+ account holds the assigned issues. Take it from the user/args, or list the user's integrations first.
53
+
54
+ - **`list_assigned_issues(id)`** → `[{issue_key, title, status, claim_state, dispatch_external_id?}]`
55
+ (`claim_state` ∈ `unclaimed | queued | leased | running | completed | failed | cancelled`).
56
+ - **`next_assigned_issue(id)`** → the first still-`unclaimed` issue, or `null` when nothing is claimable.
57
+
58
+ Pick the target issue (prefer `next_assigned_issue` for the simple "do my next ticket" flow).
59
+
60
+ ### 2. CLAIM — atomically claim it (`pipeline.control`)
61
+
62
+ **`claim_issue`** with body `{"integration_id": "<integration externalId>", "issue_key": "DEV-103"}` →
63
+ `{dispatch_external_id, leased, issue_key}`. The wire is **snake_case**: a camelCase body
64
+ (`integrationId`/`issueKey`) is rejected with 400 `issue_key is required`. An issue key does not have to appear in
65
+ `list_assigned_issues` to be claimed.
66
+
67
+ - `leased: true` → **you won the claim**; carry `dispatch_external_id` to START.
68
+ - `leased: false` → **someone already claimed it** (race lost — a 200 VALUE, never an error). **Move to
69
+ the next issue** (`next_assigned_issue` again, or the next `unclaimed` row) and re-claim. This is a
70
+ clean loop, not a failure.
71
+
72
+ ### 3. VERIFY SUBSCRIPTION — check the gate, warn (don't block) in v1
73
+
74
+ Call **`whoami`** and inspect the active org + plan/entitlement. The hard binary **402
75
+ `upgrade_required`** gate ships later on the claim/start verbs; **in v1 this skill only
76
+ checks and WARNS** — if there is no active subscription/plan, surface a clear warning that the run may
77
+ be blocked once that gate lands, then proceed. (SuperAdmin/system bypass; don't hard-stop here.)
78
+
79
+ ### 4. START — open the run (`pipeline.control`)
80
+
81
+ **`start_sdlc_for_issue({id: dispatch_external_id})`** →
82
+ `{workItemSlug, runNumber, runExternalId, issueLink, instruction}`.
83
+
84
+ - `instruction` is the **inline informational envelope**: prompt-shaped first task with
85
+ **`instructionId: null`** — **informational only**, it does NOT advance the program counter. Use it to
86
+ preview the first step; the driver/host fetches the real instruction via `get_next_instruction`.
87
+ - Keep `runExternalId` (the run id every `devorch run` / `get_next_instruction` call needs) and
88
+ `workItemSlug`.
89
+
90
+ ### 5. RUN — branch on mode
91
+
92
+ **Default = Interactive** unless the user asked for `--headless`.
93
+
94
+ #### Interactive (default — the headline demo)
95
+
96
+ The main thread only orchestrates: each instruction's work runs in a `devorch-step-worker` subagent, and the session
97
+ is idle between firings so the user can steer. `devorch-step` handles the terminal `control` notifications (step 6).
98
+ A project-level `/devorch-step` is the same skill where one exists.
99
+
100
+ **Pick the wake from the companion (DEV-47, DEV-56).** Exactly one thing wakes the session between firings: the
101
+ companion mod (push, realtime) or `/loop` with `ScheduleWakeup` (poll, timed). Decide once, from the mod:
102
+
103
+ 1. If the companion tool `mcp__devorch-companion__devorch_companion` exists, call it with
104
+ `{action: "watch", runId: <runExternalId>}`; add `baseUrl` only when the run lives on a different server from
105
+ `<apiBase>` (for example a worktree slot). Read **`wake.effective`** from the answer and don't re-derive it from
106
+ `healthy`.
107
+ 2. Branch on it:
108
+
109
+ | `wake.effective` | Start the run with |
110
+ |---|---|
111
+ | `push` | **`/devorch-companion:devorch-step <runExternalId>` once, with no `/loop`.** The mod submits the next firing itself whenever the run can move (a blocker answered, a lease freed, the run finished) and hands the wake back if it turns unhealthy. |
112
+ | `poll` | **`/loop /devorch-companion:devorch-step <runExternalId>`**, as before: the step skill schedules its own wakeups (`wake.fallbackWakeupSeconds` as the safety net). |
113
+ | `unavailable` | Nothing. `wakeMode` is `push` but the companion is unhealthy: tell the user `wake.reason`, and that `/devorch-companion:devorch-step <runExternalId>` resumes the run once it's fixed (or set `wakeMode` to `auto`/`poll`). Stop. |
114
+
115
+ **No companion tool:** use `poll`. The one exception is a user who set `wakeMode: push` (or `DEVORCH_WAKE_MODE=push`)
116
+ and said so: report that the companion is missing and stop.
117
+
118
+ The mode comes from the plugin's `wakeMode` setting (`auto` by default: push while the companion is healthy, else
119
+ poll), overridden by `DEVORCH_WAKE_MODE`; see the plugin README's "Wake modes". Blockers can be answered from the
120
+ session with `/devorch-answer <slug> <ref> <answer>` (mod) or `devorch blocker answer <slug> <ref> --text ...`;
121
+ headless `devorch run supervise` parks a WAIT on the server and resumes on its own.
122
+
123
+ > **Billing:** Interactive runs on your already-logged-in subscription — **no key-strip** (you launched
124
+ > Claude logged in). **Claude-only** for now.
125
+
126
+ #### Headless (`--headless` — the proven spine)
127
+
128
+ Launch the restart-safe supervisor **backgrounded** so this session stays responsive:
129
+
130
+ ```
131
+ <devorch> run supervise <runExternalId> --base-url <apiBase>
132
+ ```
133
+
134
+ `<devorch>` is the CLI the companion recorded, in this order:
135
+
136
+ 1. the `cli.path` the companion tool reports (`{action: "status"}`), which `devorch companion install` recorded;
137
+ 2. in the DevOrch workspace, `${CLAUDE_PROJECT_DIR}/tools/devorch/devorch.exe` when it exists (a local build of
138
+ `main`; rebuild it from `app/backend/src/DevOrchestrator.Cli` if it is stale);
139
+ 3. `devorch` on PATH.
140
+
141
+ If the chosen binary answers `Error: 'run' is not a command.`, it predates the `run` commands: say so and ask the user
142
+ to update the CLI (`npm i -g dev-orchestrator-cli@latest` or `dotnet tool update -g dev-orchestrator-cli`), then
143
+ `devorch companion install` again. Don't fall back to another binary silently.
144
+
145
+ Run it with the **Bash tool's `run_in_background: true`**. Then surface the **portal URL** so the user can watch the
146
+ run live (stages / gates / linked sessions): `/app/work-items/{workItemSlug}` on the web app that pairs with
147
+ `<apiBase>` (hosted: `https://app.devorchestrator.com/app/work-items/{workItemSlug}`; a local backend on port 87NN
148
+ pairs with `http://localhost:88NN`). A specific run is `/app/work-items/{workItemSlug}/runs/{runNumber}`. Poll status
149
+ with `get_run_position` or the portal; do not block this session on it.
150
+
151
+ > **Permission gate:** the Headless child spawns `claude -p`, so the actual launch is gated on the
152
+ > `Bash(claude *)` permission (and the `devorch run *` permission). If those aren't granted,
153
+ > report the exact command for the user to run and stop — do not attempt to bypass the gate.
154
+
155
+ ### 6. NOTIFY on terminal `control` (NOT self-heal)
156
+
157
+ When the run reaches a terminal `control`, branch and **notify** with a PushNotification — never
158
+ auto-fix:
159
+
160
+ | Terminal `control` | Action |
161
+ |---|---|
162
+ | `DONE` | PushNotification: run complete; link the card/portal. |
163
+ | `ESCALATE` | PushNotification: surfaced blockers/defects + the run digest; a human takes it. |
164
+ | `ABORT` | PushNotification: the run was aborted (operator/quota/guard). |
165
+
166
+ ## Operator stop / abort (stop a runaway run)
167
+
168
+ A back-edge loop or quota-burning run must be stoppable from the operator side:
169
+
170
+ - **Headless:** `<devorch> run abort <runExternalId>` (the same binary as the supervisor, chosen as above) — reaps
171
+ the tracked headless `claude -p` children for the driver process (best-effort operator stop). Also stop the
172
+ backgrounded `supervise` task.
173
+ - **Interactive (in-session control):** unwatch the run with `/devorch-unwatch <runId>` so the companion submits no
174
+ further firing (push), and under `/loop` (poll) tell the session to stop the loop; it calls
175
+ `ScheduleWakeup(stop: true)`.
176
+
177
+ ## Anti-patterns
178
+
179
+ - **Self-healing on a terminal control** — DONE/ESCALATE/ABORT → **notify**, never auto-retry/auto-fix.
180
+ The backend PC owns advancement and back-edges.
181
+ - **Advancing the PC by hand in Headless** — the `devorch run` driver owns `get_next_instruction` /
182
+ `apply_instruction_result` there; don't call them yourself for a Headless run.
183
+ - **Treating `leased:false` as an error** — it's the race-lost VALUE; move to the next issue.
184
+ - **Trusting the START `instruction` as binding** — its `instructionId` is null (informational only);
185
+ the real first instruction comes from `get_next_instruction`.
186
+ - **Hard-blocking on the subscription in v1** — check + warn; the binary 402 gate comes later.
187
+ - **Doing a step's work in this session** — Interactive routes every step through `devorch-step`'s worker.
188
+ - **Mixing backends** — the MCP server, the watch and `devorch run` must all point at `<apiBase>`.
@@ -31,9 +31,27 @@ export type DevorchRunStatus = {
31
31
  pendingWake: boolean
32
32
  }
33
33
 
34
+ /** Who wakes an interactive run: `push` the companion, `poll` the skill's /loop + ScheduleWakeup, `unavailable`
35
+ * wakeMode push with an unhealthy companion. */
36
+ export type DevorchWakePolicy = {
37
+ mode: 'auto' | 'push' | 'poll'
38
+ effective: 'push' | 'poll' | 'unavailable'
39
+ owner: 'companion' | 'skill' | 'none'
40
+ fallbackWakeupSeconds: number
41
+ reason: string
42
+ }
43
+
34
44
  export type DevorchStatus = {
35
45
  healthy: boolean
36
46
  reason?: string
47
+ wake: DevorchWakePolicy
48
+ config: {
49
+ wakeMode: 'auto' | 'push' | 'poll'
50
+ fallbackWakeupSeconds: number
51
+ longPollSeconds: number
52
+ sources: Record<'wakeMode' | 'fallbackWakeupSeconds' | 'longPollSeconds', 'env' | 'option' | 'default'>
53
+ warnings: string[]
54
+ }
37
55
  cli: { ok: boolean; version: string | null; path: string | null }
38
56
  stopHookArmed: boolean
39
57
  wakeBroken: boolean
package/bin/devorch CHANGED
@@ -1,4 +1,4 @@
1
1
  [diffend] Oversized file quarantined before diffing.
2
2
  name: package/bin/devorch
3
- size: 107100913 bytes
4
- sha256: 597a5255e8e6b1cdad08e0d9ba439766d9c08c0e604761debe40af0df259f5c6
3
+ size: 107103985 bytes
4
+ sha256: daf94f1065c07146affea737d5519d29ce8d2c4df85bb0cd2a5486ec9fb59a77
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@devorch/cli-linux-x64",
3
- "version": "0.19.0",
3
+ "version": "0.21.0",
4
4
  "description": "Dev Orchestrator CLI (devorch) prebuilt binary for linux-x64 (.NET RID linux-x64). Installed automatically by dev-orchestrator-cli; not meant to be installed directly.",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {