owenloop 0.5.2 → 0.5.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/CHANGELOG.md +25 -0
  2. package/README.md +6 -2
  3. package/dist/packages/work/src/agent/brief.d.ts +6 -0
  4. package/dist/packages/work/src/agent/brief.js +46 -2
  5. package/dist/packages/work/src/agent/loop.js +3 -0
  6. package/dist/packages/work/src/exec/loop.js +153 -9
  7. package/dist/packages/work/src/harness/child-env.js +8 -0
  8. package/dist/packages/work/src/harness/claude.js +82 -9
  9. package/dist/packages/work/src/harness/codex.js +63 -8
  10. package/dist/packages/work/src/harness/contract.d.ts +84 -1
  11. package/dist/packages/work/src/harness/contract.js +75 -0
  12. package/dist/packages/work/src/settings/settings.d.ts +12 -4
  13. package/dist/packages/work/src/settings/settings.js +14 -11
  14. package/dist/src/bundle/runtime.d.ts +1 -1
  15. package/dist/src/bundle/runtime.js +9 -0
  16. package/dist/src/cli.js +226 -8
  17. package/dist/src/config-dir.d.ts +62 -0
  18. package/dist/src/config-dir.js +87 -0
  19. package/dist/src/crypto/trust-roots.d.ts +8 -4
  20. package/dist/src/crypto/trust-roots.js +18 -12
  21. package/dist/src/defs.js +57 -16
  22. package/dist/src/engine.js +25 -3
  23. package/dist/src/hub.d.ts +5 -1
  24. package/dist/src/hub.js +7 -8
  25. package/dist/src/paths.d.ts +47 -4
  26. package/dist/src/paths.js +36 -5
  27. package/dist/src/work-settings.d.ts +8 -5
  28. package/dist/src/work-settings.js +15 -12
  29. package/docs/agent-runner.md +26 -1
  30. package/docs/authoring.md +40 -13
  31. package/docs/bundles.md +9 -0
  32. package/docs/cli.md +121 -24
  33. package/docs/crypto.md +8 -8
  34. package/docs/design.md +20 -2
  35. package/docs/embedding.md +5 -4
  36. package/docs/wire-contracts.md +3 -2
  37. package/package.json +1 -1
  38. package/plugins/claude-code/plugin/.claude-plugin/plugin.json +1 -1
  39. package/plugins/claude-code/plugin/.mcp.json +1 -1
  40. package/plugins/codex/plugins/owenloop/.codex-plugin/plugin.json +1 -1
  41. package/plugins/codex/plugins/owenloop/.mcp.json +1 -1
@@ -97,7 +97,11 @@ export interface StepPermissions {
97
97
  filesystem?: FilesystemPermission;
98
98
  /** Network authority requested by the workflow definition. */
99
99
  network?: NetworkPermission;
100
- /** Opaque adapter permission mode. Each adapter validates its own vocabulary. */
100
+ /**
101
+ * Adapter permission mode. Each adapter validates its own vocabulary, PLUS the
102
+ * neutral values every adapter must either translate or refuse — see
103
+ * `NEUTRAL_PERMISSION_MODES`.
104
+ */
101
105
  permissionMode?: string;
102
106
  /** Only ever a positive integer; anything else was dropped in normalization. */
103
107
  maxTurns?: number;
@@ -108,6 +112,85 @@ export interface StepPermissions {
108
112
  * no adapter needs a null check. */
109
113
  extensions: Record<string, unknown>;
110
114
  }
115
+ /**
116
+ * The HARNESS-NEUTRAL `permissionMode` vocabulary: three distinct positions on
117
+ * ONE axis — how much a step may do before a human is consulted.
118
+ *
119
+ * WHY THIS EXISTS. `permissionMode` sits in `NEUTRAL_KEYS` (see
120
+ * `./permissions.ts`) alongside `filesystem` and `network`, but it did not
121
+ * behave like them. `filesystem: unrestricted` is an INTENT the step states and
122
+ * each adapter translates into its own dialect — one shipped adapter turns it
123
+ * into that vendor's own sandbox setting. `permissionMode` had no translation
124
+ * layer at all: the authored string went to the adapter verbatim, and the
125
+ * shipped adapters accept DISJOINT vocabularies for the same ideas, each
126
+ * refusing the other's at preflight. A step therefore had to name one vendor's
127
+ * word, which pinned it to that vendor as surely as an explicit `id:` would
128
+ * have. That is exactly the pin the neutral-key contract exists to prevent.
129
+ *
130
+ * THE THREE POSITIONS ARE NOT INTERCHANGEABLE. Both shipped harnesses draw the
131
+ * same three distinctions, so collapsing any two would lose a real one:
132
+ *
133
+ * - `ask` — the harness consults a human before anything beyond trivially safe
134
+ * reads. The human is the gate.
135
+ * - `auto-safe` — a model-side classifier judges each action: it proceeds on
136
+ * ordinary work and consults a human only when an action is potentially
137
+ * dangerous. The classifier is the gate; a human is the exception path.
138
+ * - `full-access` — nothing is gated. The harness never consults a human, and
139
+ * a failed action is simply reported back to the model.
140
+ *
141
+ * `auto-safe` is NOT a milder `full-access`: the position it names still has a
142
+ * human exception path. A headless step that must not stall wants
143
+ * `full-access`, and the two exist separately so that choice is stated rather
144
+ * than inferred.
145
+ *
146
+ * WHAT `auto-safe` COSTS YOU TODAY, MEASURED. The three positions above
147
+ * describe the vocabulary, not a guarantee about how far any given classifier
148
+ * actually goes before it consults someone. On one shipped adapter the
149
+ * classifier was probed with five actions — among them a recursive delete on an
150
+ * absolute path outside the session working directory, an outbound network
151
+ * request, and a read of a file outside that directory — and it consulted the
152
+ * host on none of them and reported no auto-denial for any of them; four ran.
153
+ * On the other, the position that maps to `auto-safe` keys its judgment on
154
+ * filesystem access being restricted, so a step that also declares
155
+ * `filesystem: unrestricted` moves it close to `full-access` as well.
156
+ *
157
+ * The practical consequence for a definition author: choosing `auto-safe`
158
+ * because you want a person consulted on the dangerous cases may get you
159
+ * neither the prompt nor a record that one was skipped. Choose `ask` when a
160
+ * human decision genuinely has to happen, and `full-access` when it genuinely
161
+ * must not. Treat `auto-safe` as the classifier's own judgment with no
162
+ * guaranteed appeal, not as a supervised `full-access`.
163
+ *
164
+ * `ask` and `auto-safe` are meaningful only where something can answer a
165
+ * prompt. In a Shift-dispatched run nothing can, so a prompt is a stall: the
166
+ * Step Agent stops mid-turn, submits nothing, and the hub re-arms the step into
167
+ * a retry storm whose every worker dies in the same place. That is a reason for
168
+ * a definition author to choose `full-access` for unattended steps, not a
169
+ * reason for an adapter to silently upgrade one value into another.
170
+ *
171
+ * WHAT AN ADAPTER OWES THIS VOCABULARY. For each value an adapter must either
172
+ * map it onto the vendor mode with the same meaning, or refuse it in
173
+ * `preflight` with a `PermissionIssue` naming `permissionMode`. Refusing is a
174
+ * legitimate answer and fails closed: the worker releases its claim and starts
175
+ * no model process. Mapping a value onto a mode that grants MORE than the value
176
+ * describes is never legitimate.
177
+ *
178
+ * VENDOR VALUES ARE UNCHANGED. Each adapter still accepts its own native
179
+ * vocabulary and still refuses every other adapter's. These values are an
180
+ * ADDITION, so no already-published definition changes meaning.
181
+ */
182
+ export declare const NEUTRAL_PERMISSION_MODES: readonly ["ask", "auto-safe", "full-access"];
183
+ export type NeutralPermissionMode = (typeof NEUTRAL_PERMISSION_MODES)[number];
184
+ /**
185
+ * An adapter's neutral-vocabulary translation table.
186
+ *
187
+ * EXHAUSTIVE BY TYPE, and that is the point: adding a fourth neutral value
188
+ * breaks compilation in every adapter until each one decides what it means
189
+ * there. `null` is the explicit "this adapter has no equivalent" decision and
190
+ * makes `preflight` refuse — distinct from an adapter that simply forgot.
191
+ */
192
+ export type NeutralPermissionModeMap = Readonly<Record<NeutralPermissionMode, string | null>>;
193
+ export declare function isNeutralPermissionMode(value: string): value is NeutralPermissionMode;
111
194
  /** One fail-closed adapter preflight refusal. */
112
195
  export interface PermissionIssue {
113
196
  /** The normalized permission field or extension key responsible, when one exists. */
@@ -1,3 +1,78 @@
1
+ /**
2
+ * The HARNESS-NEUTRAL `permissionMode` vocabulary: three distinct positions on
3
+ * ONE axis — how much a step may do before a human is consulted.
4
+ *
5
+ * WHY THIS EXISTS. `permissionMode` sits in `NEUTRAL_KEYS` (see
6
+ * `./permissions.ts`) alongside `filesystem` and `network`, but it did not
7
+ * behave like them. `filesystem: unrestricted` is an INTENT the step states and
8
+ * each adapter translates into its own dialect — one shipped adapter turns it
9
+ * into that vendor's own sandbox setting. `permissionMode` had no translation
10
+ * layer at all: the authored string went to the adapter verbatim, and the
11
+ * shipped adapters accept DISJOINT vocabularies for the same ideas, each
12
+ * refusing the other's at preflight. A step therefore had to name one vendor's
13
+ * word, which pinned it to that vendor as surely as an explicit `id:` would
14
+ * have. That is exactly the pin the neutral-key contract exists to prevent.
15
+ *
16
+ * THE THREE POSITIONS ARE NOT INTERCHANGEABLE. Both shipped harnesses draw the
17
+ * same three distinctions, so collapsing any two would lose a real one:
18
+ *
19
+ * - `ask` — the harness consults a human before anything beyond trivially safe
20
+ * reads. The human is the gate.
21
+ * - `auto-safe` — a model-side classifier judges each action: it proceeds on
22
+ * ordinary work and consults a human only when an action is potentially
23
+ * dangerous. The classifier is the gate; a human is the exception path.
24
+ * - `full-access` — nothing is gated. The harness never consults a human, and
25
+ * a failed action is simply reported back to the model.
26
+ *
27
+ * `auto-safe` is NOT a milder `full-access`: the position it names still has a
28
+ * human exception path. A headless step that must not stall wants
29
+ * `full-access`, and the two exist separately so that choice is stated rather
30
+ * than inferred.
31
+ *
32
+ * WHAT `auto-safe` COSTS YOU TODAY, MEASURED. The three positions above
33
+ * describe the vocabulary, not a guarantee about how far any given classifier
34
+ * actually goes before it consults someone. On one shipped adapter the
35
+ * classifier was probed with five actions — among them a recursive delete on an
36
+ * absolute path outside the session working directory, an outbound network
37
+ * request, and a read of a file outside that directory — and it consulted the
38
+ * host on none of them and reported no auto-denial for any of them; four ran.
39
+ * On the other, the position that maps to `auto-safe` keys its judgment on
40
+ * filesystem access being restricted, so a step that also declares
41
+ * `filesystem: unrestricted` moves it close to `full-access` as well.
42
+ *
43
+ * The practical consequence for a definition author: choosing `auto-safe`
44
+ * because you want a person consulted on the dangerous cases may get you
45
+ * neither the prompt nor a record that one was skipped. Choose `ask` when a
46
+ * human decision genuinely has to happen, and `full-access` when it genuinely
47
+ * must not. Treat `auto-safe` as the classifier's own judgment with no
48
+ * guaranteed appeal, not as a supervised `full-access`.
49
+ *
50
+ * `ask` and `auto-safe` are meaningful only where something can answer a
51
+ * prompt. In a Shift-dispatched run nothing can, so a prompt is a stall: the
52
+ * Step Agent stops mid-turn, submits nothing, and the hub re-arms the step into
53
+ * a retry storm whose every worker dies in the same place. That is a reason for
54
+ * a definition author to choose `full-access` for unattended steps, not a
55
+ * reason for an adapter to silently upgrade one value into another.
56
+ *
57
+ * WHAT AN ADAPTER OWES THIS VOCABULARY. For each value an adapter must either
58
+ * map it onto the vendor mode with the same meaning, or refuse it in
59
+ * `preflight` with a `PermissionIssue` naming `permissionMode`. Refusing is a
60
+ * legitimate answer and fails closed: the worker releases its claim and starts
61
+ * no model process. Mapping a value onto a mode that grants MORE than the value
62
+ * describes is never legitimate.
63
+ *
64
+ * VENDOR VALUES ARE UNCHANGED. Each adapter still accepts its own native
65
+ * vocabulary and still refuses every other adapter's. These values are an
66
+ * ADDITION, so no already-published definition changes meaning.
67
+ */
68
+ export const NEUTRAL_PERMISSION_MODES = Object.freeze([
69
+ 'ask',
70
+ 'auto-safe',
71
+ 'full-access',
72
+ ]);
73
+ export function isNeutralPermissionMode(value) {
74
+ return NEUTRAL_PERMISSION_MODES.includes(value);
75
+ }
1
76
  /** The `code` every `ResumeUnavailableError` carries. Match on THIS, not on the class. */
2
77
  export const RESUME_UNAVAILABLE = 'RESUME_UNAVAILABLE';
3
78
  /**
@@ -154,10 +154,18 @@ export interface SettingsInspection extends ValidatedSettings {
154
154
  exists: boolean;
155
155
  }
156
156
  /**
157
- * Resolve the settings file path from the caller's env:
158
- * `$XDG_CONFIG_HOME/owenloop/settings.json` when `XDG_CONFIG_HOME` is set and
159
- * non-empty, else `$HOME/.config/owenloop/settings.json`. Throws when neither
160
- * is available rather than guessing a home directory.
157
+ * Resolve the settings file path from the caller's env, through the one shared
158
+ * ladder in `src/config-dir.ts`: `$OWENLOOP_CONFIG_DIR/settings.json` when
159
+ * `OWENLOOP_CONFIG_DIR` is set and non-blank (it must be absolute), else
160
+ * `$XDG_CONFIG_HOME/owenloop/settings.json`, else
161
+ * `$HOME/.config/owenloop/settings.json`. Throws when no rung yields a value
162
+ * rather than guessing a home directory.
163
+ *
164
+ * `OWENLOOP_CONFIG_DIR` is the variable an operator running SEVERAL shifts on
165
+ * one machine should reach for. Setting `XDG_CONFIG_HOME` per shift also works,
166
+ * but a shift spreads its whole environment into every worker and every command
167
+ * step's child, so relocating `XDG_CONFIG_HOME` relocates the config of `gh`,
168
+ * `git`, `gcloud`, and everything else those steps shell out to.
161
169
  */
162
170
  export declare function settingsPath(env: Record<string, string | undefined>): string;
163
171
  /**
@@ -14,6 +14,7 @@
14
14
  */
15
15
  import { existsSync, readFileSync } from 'node:fs';
16
16
  import { join } from 'node:path';
17
+ import { owenloopConfigDir } from "../../../../src/config-dir.js";
17
18
  import { validateCapabilityModels } from "../agent/capability-model.js";
18
19
  /** The known settings keys, in the order `owenloop work settings` prints them. */
19
20
  export const KNOWN_SETTINGS_KEYS = [
@@ -42,19 +43,21 @@ export const KNOWN_SETTINGS_KEYS = [
42
43
  */
43
44
  export const RETIRED_IGNORED_KEYS = ['escalateAt', 'escalationExtensionKey'];
44
45
  /**
45
- * Resolve the settings file path from the caller's env:
46
- * `$XDG_CONFIG_HOME/owenloop/settings.json` when `XDG_CONFIG_HOME` is set and
47
- * non-empty, else `$HOME/.config/owenloop/settings.json`. Throws when neither
48
- * is available rather than guessing a home directory.
46
+ * Resolve the settings file path from the caller's env, through the one shared
47
+ * ladder in `src/config-dir.ts`: `$OWENLOOP_CONFIG_DIR/settings.json` when
48
+ * `OWENLOOP_CONFIG_DIR` is set and non-blank (it must be absolute), else
49
+ * `$XDG_CONFIG_HOME/owenloop/settings.json`, else
50
+ * `$HOME/.config/owenloop/settings.json`. Throws when no rung yields a value
51
+ * rather than guessing a home directory.
52
+ *
53
+ * `OWENLOOP_CONFIG_DIR` is the variable an operator running SEVERAL shifts on
54
+ * one machine should reach for. Setting `XDG_CONFIG_HOME` per shift also works,
55
+ * but a shift spreads its whole environment into every worker and every command
56
+ * step's child, so relocating `XDG_CONFIG_HOME` relocates the config of `gh`,
57
+ * `git`, `gcloud`, and everything else those steps shell out to.
49
58
  */
50
59
  export function settingsPath(env) {
51
- const xdg = env.XDG_CONFIG_HOME;
52
- if (xdg !== undefined && xdg.trim() !== '')
53
- return join(xdg, 'owenloop', 'settings.json');
54
- const home = env.HOME;
55
- if (home !== undefined && home.trim() !== '')
56
- return join(home, '.config', 'owenloop', 'settings.json');
57
- throw new Error('cannot locate a settings directory: set HOME or XDG_CONFIG_HOME');
60
+ return join(owenloopConfigDir(env), 'settings.json');
58
61
  }
59
62
  /**
60
63
  * Validate a parsed settings object. Checks the TYPE of every known key
@@ -1,6 +1,6 @@
1
1
  import type { BundleRuntimeRequirements } from './types.ts';
2
2
  /** Runtime features implemented by this Owenloop release. */
3
- export declare const SUPPORTED_RUNTIME_FEATURES: readonly ["harness-policy-enforcement.v1", "native-judge-policy-inheritance.v1"];
3
+ export declare const SUPPORTED_RUNTIME_FEATURES: readonly ["harness-policy-enforcement.v1", "native-judge-policy-inheritance.v1", "neutral-approval-modes.v1"];
4
4
  export interface RuntimeCompatibilityEnvironment {
5
5
  /** The running Owenloop package version. `0.0.0` is the unavailable-version sentinel. */
6
6
  version: string;
@@ -6,6 +6,15 @@ const semver = createRequire(import.meta.url)('semver');
6
6
  export const SUPPORTED_RUNTIME_FEATURES = Object.freeze([
7
7
  'harness-policy-enforcement.v1',
8
8
  'native-judge-policy-inheritance.v1',
9
+ // A def may write `x.harness.permissionMode` as one of the three neutral
10
+ // values (`ask`, `auto-safe`, `full-access`) and every adapter translates it
11
+ // into the vendor mode with the same meaning, or refuses it at preflight.
12
+ // A def that uses one MUST require this id: on a CLI that predates it, every
13
+ // adapter refuses the neutral value as out-of-vocabulary, so the step fails
14
+ // closed — correct, but with a message about a bad permission mode rather
15
+ // than about an old runtime. Requiring the id moves the diagnosis to the
16
+ // bundle check, before any order is offered.
17
+ 'neutral-approval-modes.v1',
9
18
  ]);
10
19
  /** True only for one canonical strict SemVer value, with no prefix, range, or whitespace. */
11
20
  export function isCanonicalSemver(value) {
package/dist/src/cli.js CHANGED
@@ -1120,8 +1120,19 @@ Commands:
1120
1120
  push [<defName>...] [--bundle <bundle.wnlp>] [--force] [--dry-run] [--hub <origin>] [--as <slot>]
1121
1121
  publish local workflow defs, or exact bundle-backed defs, to the safely resolved hub (server-diffed, idempotent)
1122
1122
  --as names the credential slot: human (default), agent, or agent:<account>
1123
- start <defName> [--provide name=json ...] [--crew <name>] [--title <text>] [--hub <url>]
1123
+ start <defName> [--provide name=json ...] [--crew <name>] [--title <text>] [--modifier <name>] [--hub <url>]
1124
1124
  ${' '.repeat(41)}start a published workflow on the bound hub (human credential)
1125
+ ${' '.repeat(41)}--modifier names one value from the def's declared \`modifiers:\` set; every
1126
+ ${' '.repeat(41)}step's capability is then offered as \`<capability>:<modifier>\`. Omit it and
1127
+ ${' '.repeat(41)}the run carries no modifier and its steps are offered on BARE capabilities.
1128
+ cancel <workflow> [--reason <text>] [--hub <url>]
1129
+ ${' '.repeat(41)}cancel a running instance on the bound hub (human credential; agents cannot cancel).
1130
+ ${' '.repeat(41)}Closes every open lease so the run stops being re-offered, and records the
1131
+ ${' '.repeat(41)}terminal status \`cancelled\`. Cancelling an already-terminal instance is a no-op.
1132
+ instance show <workflow> [--hub <url>]
1133
+ ${' '.repeat(41)}print one instance's live state on the bound hub: whether it is done, what it
1134
+ ${' '.repeat(41)}owes, which steps are eligible or blocked, which runs are in flight, and whether
1135
+ ${' '.repeat(41)}the loaded def has drifted from the version the instance is pinned to.
1125
1136
  agent new <name> [--crews <a,b>] [--scopes <a,b>] [--shift] [--hub <url>] mint a new Scoped Identity on the hub and store its token in slot agent:<name> (the token is never printed; --shift = --scopes work,run)
1126
1137
  capability bind <capability> <crew> [--hub <url>] add a crew to a workflow capability on the hub org — a capability may bind many crews (admin; human credential)
1127
1138
  capability unbind <capability> <crew> [--hub <url>] remove one (capability, crew) route
@@ -1210,7 +1221,9 @@ export const COMMAND_OPTIONS = new Map([
1210
1221
  ['publish', cmdOpts('unsigned', 'output', 'source', 'hub')],
1211
1222
  ['trust', cmdOpts('force', 'key', 'principal', 'pools', 'labels', 'namespaces', 'delegate', 'signing-key', 'output', 'reason', 'effective-from')],
1212
1223
  ['push', cmdOpts('dry-run', 'force', 'hub', 'as', 'bundle')],
1213
- ['start', cmdOpts('hub', 'crew', 'title', 'provide')],
1224
+ ['start', cmdOpts('hub', 'crew', 'title', 'provide', 'modifier')],
1225
+ ['cancel', cmdOpts('hub', 'reason')],
1226
+ ['instance', cmdOpts('hub')],
1214
1227
  ['agent', cmdOpts('crews', 'hub', 'scopes', 'shift')],
1215
1228
  ['capability', cmdOpts('hub')],
1216
1229
  ['crew', cmdOpts('hub', 'kind', 'owner')],
@@ -3881,11 +3894,11 @@ async function dispatchPush(io, args) {
3881
3894
  }
3882
3895
  }
3883
3896
  /**
3884
- * Resolve the hub for `start` without ever falling through to the production
3885
- * default or an ambient `OWENLOOP_HUB`. A connected project supplies the
3886
- * durable default. `--hub` is allowed for an unbound directory, but must agree
3887
- * with an existing binding so a copied command cannot silently start a run on
3888
- * the wrong control plane.
3897
+ * Resolve the hub for the per-run commands (`start`, `cancel`) without ever
3898
+ * falling through to the production default or an ambient `OWENLOOP_HUB`. A
3899
+ * connected project supplies the durable default. `--hub` is allowed for an
3900
+ * unbound directory, but must agree with an existing binding so a copied
3901
+ * command cannot silently start — or cancel — a run on the wrong control plane.
3889
3902
  */
3890
3903
  function resolveStartHub(io, args) {
3891
3904
  const binding = readHubBinding(hubBindingPath(io.cwd));
@@ -3951,6 +3964,13 @@ async function dispatchStart(io, args) {
3951
3964
  // Validate request-only options before project binding, Keychain, or network access.
3952
3965
  const crew = requiredTextOption('crew', 'name');
3953
3966
  const title = requiredTextOption('title', 'text');
3967
+ // The run's ONE routing modifier. Validated by the hub against the def's
3968
+ // declared `modifiers:` set (a value outside it is a 400 `modifier_refused`),
3969
+ // so the CLI only enforces the shape every other text option enforces:
3970
+ // `--modifier` with no value, or with an empty one, is a usage error rather
3971
+ // than a silent unmodified run. Omitting the flag entirely IS the unmodified
3972
+ // run — that is the difference `requiredTextOption` preserves.
3973
+ const modifier = requiredTextOption('modifier', 'name');
3954
3974
  const origin = resolveStartHub(io, args);
3955
3975
  const slot = { principal: 'human' };
3956
3976
  const cred = readCredential(io, origin, slot);
@@ -3963,6 +3983,10 @@ async function dispatchStart(io, args) {
3963
3983
  ...(Object.keys(provide).length > 0 ? { provide } : {}),
3964
3984
  ...(crew !== undefined ? { default_crew: crew } : {}),
3965
3985
  ...(title !== undefined ? { title } : {}),
3986
+ // Spread-conditional, not `modifier` outright: the route reads `''` and
3987
+ // absent as the same thing, but sending an explicit `undefined` would put a
3988
+ // `modifier` key in the JSON body with a null value. Omitted means omitted.
3989
+ ...(modifier !== undefined ? { modifier } : {}),
3966
3990
  };
3967
3991
  const { res, cred: used } = await authedPost(io, origin, slot, cred, '/api/start_run', request);
3968
3992
  if (res.status === 401)
@@ -3997,11 +4021,201 @@ async function dispatchStart(io, args) {
3997
4021
  workflow: wire.workflow,
3998
4022
  def: wire.def,
3999
4023
  status: wire.status,
4024
+ // Echoed from the REQUEST, not the response — `start_run` returns no
4025
+ // `modifier` field. That is not an assumption about what the hub stored: a
4026
+ // value outside the def's declared `modifiers:` set is refused with a 400
4027
+ // before any instance exists, so reaching this line at all proves the hub
4028
+ // accepted exactly this value. Printed only when the flag was passed, so an
4029
+ // unmodified run's output is byte-identical to what it was before.
4030
+ ...(modifier !== undefined ? { modifier } : {}),
4000
4031
  ...(Array.isArray(wire.stampedCrews) ? { stampedCrews: wire.stampedCrews } : {}),
4001
4032
  ...(Array.isArray(wire.validatedCrews) ? { validatedCrews: wire.validatedCrews } : {}),
4002
4033
  });
4003
4034
  return 0;
4004
4035
  }
4036
+ /**
4037
+ * `owenloop cancel` — stop a running instance from the terminal.
4038
+ *
4039
+ * The counterpart to `start`, and the only local way out of a run that can no
4040
+ * longer make progress: a step whose worktree was deleted, or an instance
4041
+ * pinned to a def version its shift can no longer satisfy. Without this, such a
4042
+ * run is re-offered forever and permanently occupies one of a shift's dispatch
4043
+ * slots, because nothing else on this machine can move it to a terminal state.
4044
+ *
4045
+ * Three properties of the hub verb this command deliberately surfaces rather
4046
+ * than hides (`hub-core/src/verbs/cancel-run.ts`):
4047
+ *
4048
+ * - It is HUMAN-ROLE-ONLY. `cancel_run` has no agent-scope entry, so an agent
4049
+ * credential is refused by the hub. This command therefore never consults
4050
+ * `--as` and always reads the `human` slot — offering `--as` would only
4051
+ * produce a 403 further down.
4052
+ * - It is IDEMPOTENT. Cancelling an instance that already reached a terminal
4053
+ * state returns `cancelled: false` plus that state, and writes nothing. That
4054
+ * is a success, not an error, so it exits 0 — a retried cancel must not look
4055
+ * like a failure.
4056
+ * - Its receipt records `outcome: 'failed'`, because the receipt union is only
4057
+ * `done|failed`. The true cancel fact lives in the instance's distinct
4058
+ * `cancelled` status and an `action: 'cancel'` audit row. We print the
4059
+ * status, not the receipt outcome, so the output does not imply the run
4060
+ * failed on its own.
4061
+ */
4062
+ async function dispatchCancel(io, args) {
4063
+ const workflow = need(args, 1, 'workflow');
4064
+ if (args.missingOptionValues.has('reason')) {
4065
+ throw new CliError('missing value for --reason: expected --reason <text>');
4066
+ }
4067
+ const reason = last(args, 'reason');
4068
+ if (reason !== undefined && reason.trim() === '') {
4069
+ throw new CliError('invalid empty value for --reason: expected --reason <text>');
4070
+ }
4071
+ const origin = resolveStartHub(io, args);
4072
+ const slot = { principal: 'human' };
4073
+ const cred = readCredential(io, origin, slot);
4074
+ if (cred === null) {
4075
+ throw new CliError(`no human credential for ${origin} — run: owenloop login --hub ${origin}`, { exitCode: 3 });
4076
+ }
4077
+ const request = {
4078
+ workflow,
4079
+ ...(reason !== undefined ? { reason } : {}),
4080
+ };
4081
+ const { res, cred: used } = await authedPost(io, origin, slot, cred, '/api/cancel_run', request);
4082
+ if (res.status === 401)
4083
+ assertAuthOk(res, used, origin);
4084
+ if (!res.ok) {
4085
+ const message = await hubRequestMessage(res);
4086
+ throw new CliError(message ?? `hub ${origin} rejected the request (HTTP ${res.status})`);
4087
+ }
4088
+ let body;
4089
+ try {
4090
+ body = (await res.json());
4091
+ }
4092
+ catch {
4093
+ throw new CliError('cancel_run: malformed success response — body is not valid JSON');
4094
+ }
4095
+ if (typeof body !== 'object' || body === null || Array.isArray(body)) {
4096
+ throw new CliError('cancel_run: malformed success response — body is not an object');
4097
+ }
4098
+ const wire = body;
4099
+ if (typeof wire.cancelled !== 'boolean') {
4100
+ throw new CliError('cancel_run: malformed success response — missing cancelled flag');
4101
+ }
4102
+ print(io, {
4103
+ ok: true,
4104
+ hub: origin,
4105
+ workflow,
4106
+ cancelled: wire.cancelled,
4107
+ // Present only on the already-terminal path, where the hub reports the state
4108
+ // it found instead of the one it set. On the cancelling path the status is
4109
+ // `cancelled` by construction, so we state it rather than inventing a field
4110
+ // the hub did not send.
4111
+ status: typeof wire.status === 'string' ? wire.status : 'cancelled',
4112
+ // The runs whose leases were closed. Absent on the no-op path.
4113
+ ...(Array.isArray(wire.closedRuns) ? { closedRuns: wire.closedRuns } : {}),
4114
+ ...(reason !== undefined ? { reason } : {}),
4115
+ });
4116
+ return 0;
4117
+ }
4118
+ /**
4119
+ * `owenloop instance` — read a HUB instance's live state from the terminal.
4120
+ *
4121
+ * The read counterpart to `start` and `cancel`. Two naming constraints forced
4122
+ * this word, and both are collisions with commands that already exist:
4123
+ *
4124
+ * - NOT `status`. `owenloop status` is the LOCAL engine's status and takes
4125
+ * `--db`; it has no hub credential and rejects `--hub`.
4126
+ * - NOT `runs`. `owenloop runs <workflow> [--open]` already lists runs out of
4127
+ * the LOCAL sqlite store. Reusing it would have silently rerouted a local
4128
+ * command to the network.
4129
+ *
4130
+ * `instance` is the hub's own term for a started workflow — `setInstanceStatus`,
4131
+ * `listInstancesWithStatus`, and `cancel_run`'s own "already-terminal instance"
4132
+ * all use it — so a hub instance and a local run stay distinct objects with
4133
+ * distinct commands rather than one command whose meaning flips on a flag.
4134
+ *
4135
+ * Only `show` exists today, and that is a hub limitation rather than a design
4136
+ * choice. `getStatus` is the one instance-read verb with a REST route
4137
+ * (`GET /api/status/:wf`). The verb that lists instances,
4138
+ * `listInstancesWithStatus`, and the two that carry receipt bodies —
4139
+ * `listReceipts` and `getReceiptDetail`, which is where a reviewer's reject
4140
+ * reason actually lives — are exposed only over tRPC for the console. Adding
4141
+ * `instance list`, or any command that can print WHY a step was rejected,
4142
+ * therefore requires new routes on `apps/hub-edge/src/api/routes.ts` and a hub
4143
+ * deploy; it is not something this CLI can reach today. The subcommand form
4144
+ * exists so those arrive as `instance list` without renaming anything.
4145
+ *
4146
+ * Like `cancel`, this reads the `human` slot and never consults `--as`, and it
4147
+ * resolves the hub through `resolveStartHub` so an ambient `OWENLOOP_HUB` can
4148
+ * never silently redirect the read to a different control plane than the one
4149
+ * the project is bound to.
4150
+ */
4151
+ async function dispatchInstance(io, args) {
4152
+ const USAGE_FORMS = 'usage: owenloop instance show <workflow> [--hub <url>]';
4153
+ const sub = args.positionals[1];
4154
+ if (sub !== 'show') {
4155
+ throw new CliError(`unknown instance subcommand '${sub ?? ''}' — ${USAGE_FORMS}`);
4156
+ }
4157
+ const workflow = args.positionals[2];
4158
+ if (workflow === undefined || workflow === '') {
4159
+ throw new CliError(`missing required argument: workflow (${USAGE_FORMS})`);
4160
+ }
4161
+ const origin = resolveStartHub(io, args);
4162
+ const slot = { principal: 'human' };
4163
+ const cred = readCredential(io, origin, slot);
4164
+ if (cred === null) {
4165
+ throw new CliError(`no human credential for ${origin} — run: owenloop login --hub ${origin}`, { exitCode: 3 });
4166
+ }
4167
+ // The workflow id is a path segment, so it must be encoded — an id carrying a
4168
+ // slash would otherwise silently address a different route.
4169
+ const path = `/api/status/${encodeURIComponent(workflow)}`;
4170
+ const { res, cred: used } = await authedGet(io, origin, slot, cred, path);
4171
+ if (res.status === 401)
4172
+ assertAuthOk(res, used, origin);
4173
+ if (!res.ok) {
4174
+ const message = await hubRequestMessage(res);
4175
+ throw new CliError(message ?? `hub ${origin} rejected the request (HTTP ${res.status})`);
4176
+ }
4177
+ let body;
4178
+ try {
4179
+ body = (await res.json());
4180
+ }
4181
+ catch {
4182
+ throw new CliError('get_status: malformed success response — body is not valid JSON');
4183
+ }
4184
+ if (typeof body !== 'object' || body === null || Array.isArray(body)) {
4185
+ throw new CliError('get_status: malformed success response — body is not an object');
4186
+ }
4187
+ const wire = body;
4188
+ // `done` is the one field every status carries and the one a script branches
4189
+ // on, so its absence means we are not looking at a status at all. Refuse
4190
+ // rather than print a shape that reads as "not done".
4191
+ if (typeof wire.done !== 'boolean') {
4192
+ throw new CliError('get_status: malformed success response — missing done flag');
4193
+ }
4194
+ const arrayOr = (value) => (Array.isArray(value) ? value : []);
4195
+ print(io, {
4196
+ ok: true,
4197
+ hub: origin,
4198
+ workflow,
4199
+ done: wire.done,
4200
+ // Owed inputs the instance is waiting on, each with its acceptance and
4201
+ // whether the engine considers it stalled.
4202
+ debts: arrayOr(wire.debts),
4203
+ // Steps that could be dispatched now, and steps whose preconditions are not
4204
+ // met yet. A run that is neither done nor eligible nor in flight is stuck.
4205
+ eligible: arrayOr(wire.eligible),
4206
+ blocked: arrayOr(wire.blocked),
4207
+ inFlight: arrayOr(wire.inFlight),
4208
+ // True when the def loaded on the hub has moved on from the snapshot this
4209
+ // instance is pinned to. A pinned instance never picks up the new version,
4210
+ // so this is the field that explains "I published a fix and the run still
4211
+ // does the old thing".
4212
+ defDrift: wire.defDrift === true,
4213
+ // Present only when a step's capability has no crew bound to it, which
4214
+ // looks identical to "nothing is picking this up" from the outside.
4215
+ ...(Array.isArray(wire.waitingOnCapabilities) ? { waitingOnCapabilities: wire.waitingOnCapabilities } : {}),
4216
+ });
4217
+ return 0;
4218
+ }
4005
4219
  /**
4006
4220
  * `owenloop mcp` — serve the human control plane to a local MCP host over stdio.
4007
4221
  * A thin adapter: read the optional `--hub <url>` flag and hand `io` (which
@@ -5867,7 +6081,7 @@ async function runDoctor(io, origin) {
5867
6081
  * the async path, so every existing command and test keeps working exactly as
5868
6082
  * before.
5869
6083
  */
5870
- export const ASYNC_COMMANDS = new Set(['add', 'login', 'logout', 'connect', 'publish', 'trust', 'push', 'start', 'agent', 'capability', 'crew', 'setup', 'doctor', 'enrollments', 'mcp', 'shift']);
6084
+ export const ASYNC_COMMANDS = new Set(['add', 'login', 'logout', 'connect', 'publish', 'trust', 'push', 'start', 'cancel', 'instance', 'agent', 'capability', 'crew', 'setup', 'doctor', 'enrollments', 'mcp', 'shift']);
5871
6085
  export async function mainAsync(argv, io = defaultIO()) {
5872
6086
  // Delegate execution-side and shift argv tails before root parsing. Their
5873
6087
  // roles own their option grammars, including repeated/value forms that the
@@ -5913,6 +6127,10 @@ export async function mainAsync(argv, io = defaultIO()) {
5913
6127
  return await dispatchPush(io, args);
5914
6128
  case 'start':
5915
6129
  return await dispatchStart(io, args);
6130
+ case 'cancel':
6131
+ return await dispatchCancel(io, args);
6132
+ case 'instance':
6133
+ return await dispatchInstance(io, args);
5916
6134
  case 'agent':
5917
6135
  return await dispatchAgent(io, args);
5918
6136
  case 'capability':
@@ -0,0 +1,62 @@
1
+ /**
2
+ * The ONE resolver for owenloop's own user-level config directory — the
3
+ * directory that directly holds `settings.json`, `credentials.json`,
4
+ * `allowed_signers`, `org-root.pub`, `roster/`, and `revocations/`.
5
+ *
6
+ * WHY THIS MODULE EXISTS. Until now four call sites each re-derived the same
7
+ * ladder — `$XDG_CONFIG_HOME/owenloop` else `$HOME/.config/owenloop` — and
8
+ * `XDG_CONFIG_HOME` was therefore the ONLY lever an operator had for pointing
9
+ * one owenloop process at a different settings file than another. That lever is
10
+ * not owenloop's to take. `XDG_CONFIG_HOME` is a machine-wide contract that
11
+ * `gh`, `git`, `gcloud`, `npm`, and most of the rest of a developer's toolchain
12
+ * also read, and `owenloop shift start` spreads its whole environment into
13
+ * every worker it dispatches (`shift/spawn.ts`), which in turn passes it to
14
+ * every command step's child process (`exec/` sets exactly three variables of
15
+ * its own on top). So an operator running two shifts with different
16
+ * `capabilityModels` had to set `XDG_CONFIG_HOME` per shift, and that silently
17
+ * relocated the config of every other tool the workflow's scripts shell out to.
18
+ *
19
+ * MEASURED, not theorized. On run `wf_8b2abe6b` the delivery line's `merge-gate`
20
+ * and `merger` steps both failed inside their `gh` probes, because `gh` looked
21
+ * for `hosts.yml` under the shift profile's `XDG_CONFIG_HOME` and found no
22
+ * credential there. `merge-gate` burned its full 40-minute wall clock deferring
23
+ * on a fail-open CI verdict; `merger` then failed four times running with
24
+ * `could not resolve a pull request handle for the branch`. Both probes returned
25
+ * the correct answer the instant they were run with the operator's real
26
+ * `XDG_CONFIG_HOME`. Nothing was wrong with either script.
27
+ *
28
+ * THE FIX IS AN OWENLOOP-SPECIFIC VARIABLE. `OWENLOOP_CONFIG_DIR` names the
29
+ * owenloop config directory ITSELF — no `owenloop` path segment is appended to
30
+ * it — so an operator can scope owenloop's config per process while leaving
31
+ * `XDG_CONFIG_HOME` alone for everything else:
32
+ *
33
+ * OWENLOOP_CONFIG_DIR=~/.config/owenloop-shifts/utility/owenloop \
34
+ * owenloop shift start utility …
35
+ *
36
+ * PRECEDENCE, highest first:
37
+ * 1. `OWENLOOP_CONFIG_DIR` → used verbatim
38
+ * 2. `XDG_CONFIG_HOME` → `<xdg>/owenloop`
39
+ * 3. `HOME` → `<home>/.config/owenloop`
40
+ * Blank or whitespace-only values are treated as unset at every rung, matching
41
+ * the behaviour the four previous copies already had for `XDG_CONFIG_HOME`.
42
+ *
43
+ * ABSOLUTE PATHS ONLY. A relative `OWENLOOP_CONFIG_DIR` would resolve against
44
+ * whatever the current working directory happens to be, and a worker's cwd
45
+ * changes per step (`workdirFrom` points each step at its own worktree). That
46
+ * is the same class of ambient-state bug this module exists to remove, so a
47
+ * relative value is a hard error naming the variable rather than a path that
48
+ * silently means something different in every step.
49
+ *
50
+ * Imports node builtins only. Both closures — the root CLI under `src/` and the
51
+ * execution engine under `packages/work/src/` — import this module directly, so
52
+ * the ladder cannot drift between them again.
53
+ */
54
+ /**
55
+ * Resolve owenloop's user-level config directory from caller-supplied env.
56
+ *
57
+ * Throws when no rung of the ladder yields a value, rather than guessing a home
58
+ * directory from the ambient process.
59
+ */
60
+ export declare function owenloopConfigDir(env: Record<string, string | undefined>): string;
61
+ /** A file inside owenloop's config directory. */
62
+ export declare function owenloopConfigFile(env: Record<string, string | undefined>, ...segments: string[]): string;