@devorch/cli-linux-x64 0.11.0 → 0.12.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,58 @@
1
+ # DevOrch companion mod (DEV-47 C6, DEV-56)
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.
7
+
8
+ ## Install
9
+
10
+ The mod ships beside the `devorch` binary (npm platform package `bin/claude-mod/`, NuGet tool
11
+ `tools/net10.0/any/claude-mod/`):
12
+
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
+
19
+ After upgrading the CLI, run `devorch companion install` again, then
20
+ `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.
23
+
24
+ ## Status
25
+
26
+ | Piece | File | Status |
27
+ |---|---|---|
28
+ | 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 |
30
+ | CLI option contract (R12): `test/cli-options.json`, checked by the mod tests and by `CompanionArgvContractTests` (C#) | `test/` | built, tested |
31
+ | `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
+ | `.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 |
34
+
35
+ The spike still decides three things the adapter assumes: that `$.process.spawn` of the native `devorch.exe` shows no
36
+ 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.
39
+
40
+ ## Tests
41
+
42
+ ```bash
43
+ cd packaging/claude-mod/devorch-companion
44
+ npm test # node --test test/*.test.ts (Node >= 22.18 runs the TypeScript directly)
45
+ ```
46
+
47
+ The hooks use only erasable TypeScript (no enums, no parameter properties) so Node runs them without a build step.
48
+
49
+ ## Contract with the CLI
50
+
51
+ - `devorch run watch <runId> [--since <token>] [--base-url <url>]`: one `run.position` platform event envelope (v1) per
52
+ line on stdout, per position change, until the run is terminal. Exit 0 terminal, 77 auth, 66 not found, 75 transport;
53
+ any other code is a usage error (rung 4).
54
+ - `devorch run wait <runId> --since <token> [--seconds 25] [--base-url <url>]`: exactly one line (rung 3).
55
+ - `devorch blocker answer <slug> <ref> --stdin --json [--base-url <url>]`: the answer is piped, never in argv.
56
+ - `devorch version --json`: `{version, path, features, hub}`; the mod requires `run-watch` and `run-wait`.
57
+ - Lines carry ids, refs and enums only. The mod passes no server string to a prompt or command except the run id it
58
+ already holds.
@@ -0,0 +1,304 @@
1
+ /**
2
+ * DevOrch companion mod: the pure core (DEV-47 C6).
3
+ *
4
+ * Everything here is plain TypeScript with no dependency on the Claude Code mod API (`$`), so it is unit-tested with
5
+ * `node --test` and survives mod API changes. `register.ts` (the thin adapter over `$`, built once the phase 3
6
+ * Windows spike settles rung 3 and the turn-end signal) wires these pieces to processes, timers, commands and the
7
+ * status band.
8
+ *
9
+ * Contract with the CLI: `devorch run watch <runId>` prints one platform event envelope (v1) per line on stdout.
10
+ * Lines carry ids, refs and enums only (CC-4), and this module never forwards any server string to a prompt or a
11
+ * command except the run id it already holds.
12
+ */
13
+
14
+ // ---- the envelope (the subset the mod reads) ----------------------------------------------------------------
15
+
16
+ export interface PlatformEventEnvelope {
17
+ id: string
18
+ type: string
19
+ version: number
20
+ occurredAt: string
21
+ org: string
22
+ actor: { kind: string; externalId: string } | null
23
+ subject: { kind: string; externalId: string }
24
+ run: { externalId: string } | null
25
+ data: Record<string, unknown>
26
+ }
27
+
28
+ /** The `data` of a `run.position` envelope (the members the mod uses). */
29
+ export interface RunPositionData {
30
+ position: string
31
+ runStatus: string
32
+ control: 'CONTINUE' | 'WAIT' | 'DONE' | 'ESCALATE' | 'ABORT' | string
33
+ kind: string | null
34
+ instructionId: string | null
35
+ openBlockers: { ref: string; kind: string }[]
36
+ reasonCode: string | null
37
+ leaseHeld: boolean
38
+ }
39
+
40
+ export const RUN_POSITION = 'run.position'
41
+
42
+ /** Parse one line into an envelope, or null for anything that is not one (malformed lines are skipped, never fatal). */
43
+ export function parseEnvelope(line: string): PlatformEventEnvelope | null {
44
+ const trimmed = line.trim()
45
+ if (trimmed.length === 0 || trimmed.length > 64 * 1024) return null
46
+ try {
47
+ const value = JSON.parse(trimmed) as Partial<PlatformEventEnvelope>
48
+ if (typeof value !== 'object' || value === null) return null
49
+ if (typeof value.id !== 'string' || typeof value.type !== 'string') return null
50
+ if (typeof value.subject !== 'object' || value.subject === null) return null
51
+ if (typeof value.data !== 'object' || value.data === null) return null
52
+ return value as PlatformEventEnvelope
53
+ } catch {
54
+ return null
55
+ }
56
+ }
57
+
58
+ export function positionOf(envelope: PlatformEventEnvelope): RunPositionData | null {
59
+ if (envelope.type !== RUN_POSITION) return null
60
+ const d = envelope.data as Partial<RunPositionData>
61
+ return typeof d.position === 'string' && typeof d.control === 'string' ? (d as RunPositionData) : null
62
+ }
63
+
64
+ // ---- NDJSON framing across stdout chunks ----------------------------------------------------------------------
65
+
66
+ /** Splits a child's stdout chunks into whole lines; a line split across chunks is joined. */
67
+ export class LineSplitter {
68
+ private buffer = ''
69
+
70
+ push(chunk: string): string[] {
71
+ this.buffer += chunk
72
+ const parts = this.buffer.split(/\r?\n/)
73
+ this.buffer = parts.pop() ?? ''
74
+ return parts.filter((p) => p.length > 0)
75
+ }
76
+
77
+ /** The unterminated tail, when the stream ends. */
78
+ flush(): string[] {
79
+ const tail = this.buffer
80
+ this.buffer = ''
81
+ return tail.length > 0 ? [tail] : []
82
+ }
83
+ }
84
+
85
+ // ---- the generic event hook (AC-5, AC-903) --------------------------------------------------------------------
86
+
87
+ export type EventHandler = (envelope: PlatformEventEnvelope) => void | Promise<void>
88
+ export type EventPredicate = (envelope: PlatformEventEnvelope) => boolean
89
+
90
+ /**
91
+ * The generic platform event hook: anyone (this mod, another mod through the exported dispatcher) registers a
92
+ * handler for a type (`run.position`), a prefix wildcard (`blocker.*`) or every type (`*`). A throwing handler is
93
+ * reported and never stops the other handlers or the source. Envelopes are deduped by id.
94
+ */
95
+ export class EventDispatcher {
96
+ private readonly handlers: { pattern: string; predicate?: EventPredicate; handler: EventHandler }[] = []
97
+ private readonly seen: string[] = []
98
+ private readonly onError: (error: unknown, pattern: string) => void
99
+
100
+ // No parameter properties: the file stays erasable TypeScript so `node --test` runs it without a build step.
101
+ constructor(onError: (error: unknown, pattern: string) => void = () => {}) {
102
+ this.onError = onError
103
+ }
104
+
105
+ on(pattern: string, handler: EventHandler): () => void
106
+ on(pattern: string, predicate: EventPredicate, handler: EventHandler): () => void
107
+ on(pattern: string, a: EventHandler | EventPredicate, b?: EventHandler): () => void {
108
+ const entry = b ? { pattern, predicate: a as EventPredicate, handler: b } : { pattern, handler: a as EventHandler }
109
+ this.handlers.push(entry)
110
+ return () => {
111
+ const i = this.handlers.indexOf(entry)
112
+ if (i >= 0) this.handlers.splice(i, 1)
113
+ }
114
+ }
115
+
116
+ async dispatch(envelope: PlatformEventEnvelope): Promise<number> {
117
+ if (this.seen.includes(envelope.id)) return 0
118
+ this.seen.push(envelope.id)
119
+ if (this.seen.length > 512) this.seen.splice(0, this.seen.length - 512)
120
+
121
+ let ran = 0
122
+ for (const { pattern, predicate, handler } of [...this.handlers]) {
123
+ if (!matches(pattern, envelope.type)) continue
124
+ try {
125
+ if (predicate && !predicate(envelope)) continue
126
+ ran += 1
127
+ await handler(envelope)
128
+ } catch (error) {
129
+ this.onError(error, pattern)
130
+ }
131
+ }
132
+ return ran
133
+ }
134
+ }
135
+
136
+ export function matches(pattern: string, type: string): boolean {
137
+ if (pattern === '*') return true
138
+ if (pattern.endsWith('.*')) return type.startsWith(pattern.slice(0, -1))
139
+ return pattern === type
140
+ }
141
+
142
+ // ---- the source ladder (AC-5, AC-902) -------------------------------------------------------------------------
143
+
144
+ /**
145
+ * Rung 1: a long-lived `devorch run watch` child. Rung 2: restarting it after it died (bounded). Rung 3: one-shot
146
+ * long-polls (`devorch run wait`; the M3-B fetch alternative is decided by the phase 3 spike). Rung 4: a timer only,
147
+ * reported `healthy: false` so the skill keeps its own wakeup.
148
+ */
149
+ export type Rung = 1 | 2 | 3 | 4
150
+
151
+ export interface LadderState {
152
+ rung: Rung
153
+ restarts: number
154
+ reason: string
155
+ }
156
+
157
+ export const MAX_RESTARTS = 3
158
+
159
+ /** Exit codes from the CLI (`ExitCodes.cs`). */
160
+ export const EXIT = { done: 0, auth: 77, notFound: 66, transport: 75 } as const
161
+
162
+ /** The next rung after the watch child exited with `exitCode` (null: it was killed or failed to start). */
163
+ export function afterChildExit(state: LadderState, exitCode: number | null): LadderState {
164
+ if (exitCode === EXIT.done) return { ...state, reason: 'run finished' }
165
+ if (exitCode === EXIT.auth) return { rung: 4, restarts: state.restarts, reason: 'devorch is not signed in (exit 77)' }
166
+ if (exitCode === EXIT.notFound) return { rung: 4, restarts: state.restarts, reason: 'run not found or server too old (exit 66)' }
167
+ if (state.restarts < MAX_RESTARTS) return { rung: 2, restarts: state.restarts + 1, reason: `watch child exited (${exitCode ?? 'killed'}); restarting` }
168
+ return { rung: 3, restarts: state.restarts, reason: 'watch child keeps dying; using one-shot long-polls' }
169
+ }
170
+
171
+ /** A child that has stayed up long enough heals the ladder back to rung 1. */
172
+ export function afterHealthyChild(_state: LadderState): LadderState {
173
+ return { rung: 1, restarts: 0, reason: 'watching' }
174
+ }
175
+
176
+ /** The CLI handshake (`devorch version --json`): too old or missing -> rung 4. */
177
+ export const MIN_CLI = '0.10.0'
178
+ export const REQUIRED_FEATURES = ['run-watch', 'run-wait'] as const
179
+
180
+ export function cliSupports(versionJson: string | null): { ok: boolean; reason: string } {
181
+ if (!versionJson) return { ok: false, reason: 'devorch CLI not found' }
182
+ try {
183
+ const v = JSON.parse(versionJson) as { version?: string; features?: string[] }
184
+ const missing = REQUIRED_FEATURES.filter((f) => !(v.features ?? []).includes(f))
185
+ if (missing.length > 0) return { ok: false, reason: `devorch CLI lacks ${missing.join(', ')} (need ${MIN_CLI}+)` }
186
+ if (compareVersions(v.version ?? '0.0.0', MIN_CLI) < 0) return { ok: false, reason: `devorch CLI ${v.version} < ${MIN_CLI}` }
187
+ return { ok: true, reason: `devorch ${v.version}` }
188
+ } catch {
189
+ return { ok: false, reason: 'devorch version --json printed something unexpected' }
190
+ }
191
+ }
192
+
193
+ export function compareVersions(a: string, b: string): number {
194
+ const pa = a.split(/[.+-]/).slice(0, 3).map((n) => Number.parseInt(n, 10) || 0)
195
+ const pb = b.split(/[.+-]/).slice(0, 3).map((n) => Number.parseInt(n, 10) || 0)
196
+ for (let i = 0; i < 3; i += 1) if ((pa[i] ?? 0) !== (pb[i] ?? 0)) return (pa[i] ?? 0) - (pb[i] ?? 0)
197
+ return 0
198
+ }
199
+
200
+ // ---- the wake decision (AC-2, CC-5, CC-6) ---------------------------------------------------------------------
201
+
202
+ /** How long the session must be idle before a wake is submitted (CC-5). */
203
+ export const SETTLE_MS = 3_000
204
+
205
+ export interface WakeInputs {
206
+ /** The run the session watches (the only id ever passed to a command). */
207
+ watchedRunId: string | null
208
+ /** A main-loop turn is running. */
209
+ turnRunning: boolean
210
+ /** Milliseconds since the last main-loop turn ended (null: none yet this session). */
211
+ idleForMs: number | null
212
+ /** The Stop-hook interactive host is armed (`.claude/hooks/interactive-loop/state/armed.json` exists). */
213
+ stopHookArmed: boolean
214
+ /** A wake for this run is queued and not yet consumed by a claim. */
215
+ wakePending: boolean
216
+ /** The latest run.position envelope for the watched run. */
217
+ latest: PlatformEventEnvelope | null
218
+ }
219
+
220
+ export type WakeDecision =
221
+ | { wake: true; runId: string }
222
+ | { wake: false; reason: string; retryInMs?: number }
223
+
224
+ /**
225
+ * Decide whether to wake the session with `/devorch-step <runId>`. Rules: no decision during a main-loop turn (the
226
+ * latest envelope is re-evaluated once idle); wait out the settle window; never while the Stop-hook host is armed;
227
+ * one pending wake per run; wake only on a CONTINUE that nobody holds the lease on, or a DONE/ABORT the driver must
228
+ * see to finish. A WAIT never wakes: the run is waiting on a human, and the next position change will.
229
+ */
230
+ export function decideWake(i: WakeInputs): WakeDecision {
231
+ const held = sessionHold(i)
232
+ if (held) return held
233
+ const runId = i.watchedRunId as string
234
+ const latest = i.latest as PlatformEventEnvelope
235
+ // GUIDs compare case-insensitively: the server writes them lowercase, a person may type them uppercase.
236
+ if (latest.run?.externalId && latest.run.externalId.toLowerCase() !== runId.toLowerCase())
237
+ return { wake: false, reason: 'envelope for another run' }
238
+ const p = positionOf(latest)
239
+ if (!p) return { wake: false, reason: 'not a position' }
240
+ if (p.control === 'CONTINUE') return p.leaseHeld ? { wake: false, reason: 'instruction already leased' } : { wake: true, runId }
241
+ if (p.control === 'DONE' || p.control === 'ABORT') return { wake: true, runId }
242
+ return { wake: false, reason: `run is ${p.control}` }
243
+ }
244
+
245
+ /** The session-side reasons not to wake yet (no run, Stop-hook host, a turn, settling, a queued wake, no position),
246
+ * or null when the session may be woken and `watchedRunId` and `latest` are set. */
247
+ function sessionHold(i: WakeInputs): WakeDecision | null {
248
+ if (!i.watchedRunId) return { wake: false, reason: 'no run watched' }
249
+ if (i.stopHookArmed) return { wake: false, reason: 'Stop-hook host armed' }
250
+ if (i.turnRunning) return { wake: false, reason: 'turn running; re-evaluate when idle' }
251
+ if (i.idleForMs !== null && i.idleForMs < SETTLE_MS)
252
+ return { wake: false, reason: 'settling', retryInMs: SETTLE_MS - i.idleForMs }
253
+ if (i.wakePending) return { wake: false, reason: 'a wake is already queued' }
254
+ if (!i.latest) return { wake: false, reason: 'no position yet' }
255
+ return null
256
+ }
257
+
258
+ /** The pending-wake guard clears once the claim is visible (the lease is held) or the run moved on. */
259
+ export function clearsPendingWake(envelope: PlatformEventEnvelope): boolean {
260
+ const p = positionOf(envelope)
261
+ return p !== null && (p.leaseHeld || p.control !== 'CONTINUE')
262
+ }
263
+
264
+ // ---- the status band (no blocker or question text, ever) ------------------------------------------------------
265
+
266
+ /** How the status band names each rung of the source ladder. */
267
+ const RUNG_LABELS: Record<Rung, string> = { 1: 'live', 2: 'reconnecting', 3: 'polling', 4: 'offline' }
268
+
269
+ export function bandText(runId: string | null, latest: PlatformEventEnvelope | null, ladder: LadderState, stopHookArmed: boolean): string {
270
+ if (stopHookArmed) return 'DevOrch: Stop-hook host armed'
271
+ if (!runId) return 'DevOrch: not watching a run (/devorch-watch <runId>)'
272
+ const short = runId.slice(0, 8)
273
+ const rung = RUNG_LABELS[ladder.rung]
274
+ const p = latest ? positionOf(latest) : null
275
+ if (!p) return `DevOrch ${short}: waiting for position (${rung})`
276
+ const blockers = p.openBlockers.length > 0 ? ` | blockers: ${p.openBlockers.map((b) => `${b.ref} [${b.kind}]`).join(', ')}` : ''
277
+ const why = p.reasonCode ? ` (${p.reasonCode})` : ''
278
+ return `DevOrch ${short}: ${p.control}${why}${blockers} | ${rung}`
279
+ }
280
+
281
+ // ---- /devorch-answer (the answer text never goes in argv) -----------------------------------------------------
282
+
283
+ /** The argv for `devorch blocker answer` with the answer in a temp file (never on the command line). */
284
+ export function answerArgv(devorch: string, slug: string, blockerRef: string, answerFile: string): string[] {
285
+ // A leading '-' would be parsed by the CLI as an option (--text, --stdin...), so ids must start alphanumeric.
286
+ if (!/^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$/.test(slug)) throw new Error('invalid work item slug')
287
+ if (!/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/.test(blockerRef)) throw new Error('invalid blocker ref')
288
+ return [devorch, 'blocker', 'answer', slug, blockerRef, '--file', answerFile, '--json']
289
+ }
290
+
291
+ /** Parse `/devorch-answer <slug> <ref> <answer...>`. */
292
+ export function parseAnswerArgs(args: string): { slug: string; blockerRef: string; answer: string } | null {
293
+ const match = /^\s*(\S+)\s+(\S+)\s+([\s\S]+)$/.exec(args)
294
+ if (!match) return null
295
+ const [, slug = '', blockerRef = '', rest = ''] = match
296
+ const answer = rest.trim()
297
+ return answer.length > 0 ? { slug, blockerRef, answer } : null
298
+ }
299
+
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 } {
302
+ if (!/^[0-9a-fA-F-]{36}$/.test(runId)) throw new Error('not a run id')
303
+ return { command: 'devorch-step', args: runId }
304
+ }
@@ -0,0 +1 @@
1
+ { "modules": ["./register.ts"] }