owenloop 0.5.3 → 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 (38) hide show
  1. package/CHANGELOG.md +17 -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 +18 -5
  9. package/dist/packages/work/src/harness/codex.js +7 -0
  10. package/dist/packages/work/src/harness/contract.d.ts +22 -3
  11. package/dist/packages/work/src/harness/contract.js +22 -3
  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/cli.js +203 -6
  15. package/dist/src/config-dir.d.ts +62 -0
  16. package/dist/src/config-dir.js +87 -0
  17. package/dist/src/crypto/trust-roots.d.ts +8 -4
  18. package/dist/src/crypto/trust-roots.js +18 -12
  19. package/dist/src/defs.js +57 -16
  20. package/dist/src/engine.js +25 -3
  21. package/dist/src/hub.d.ts +5 -1
  22. package/dist/src/hub.js +7 -8
  23. package/dist/src/paths.d.ts +47 -4
  24. package/dist/src/paths.js +36 -5
  25. package/dist/src/work-settings.d.ts +8 -5
  26. package/dist/src/work-settings.js +15 -12
  27. package/docs/authoring.md +40 -13
  28. package/docs/bundles.md +9 -0
  29. package/docs/cli.md +121 -24
  30. package/docs/crypto.md +8 -8
  31. package/docs/design.md +20 -2
  32. package/docs/embedding.md +5 -4
  33. package/docs/wire-contracts.md +3 -2
  34. package/package.json +1 -1
  35. package/plugins/claude-code/plugin/.claude-plugin/plugin.json +1 -1
  36. package/plugins/claude-code/plugin/.mcp.json +1 -1
  37. package/plugins/codex/plugins/owenloop/.codex-plugin/plugin.json +1 -1
  38. package/plugins/codex/plugins/owenloop/.mcp.json +1 -1
package/dist/src/cli.js CHANGED
@@ -1125,6 +1125,14 @@ ${' '.repeat(41)}start a published workflow on the bound hub (human credential)
1125
1125
  ${' '.repeat(41)}--modifier names one value from the def's declared \`modifiers:\` set; every
1126
1126
  ${' '.repeat(41)}step's capability is then offered as \`<capability>:<modifier>\`. Omit it and
1127
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.
1128
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)
1129
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)
1130
1138
  capability unbind <capability> <crew> [--hub <url>] remove one (capability, crew) route
@@ -1214,6 +1222,8 @@ export const COMMAND_OPTIONS = new Map([
1214
1222
  ['trust', cmdOpts('force', 'key', 'principal', 'pools', 'labels', 'namespaces', 'delegate', 'signing-key', 'output', 'reason', 'effective-from')],
1215
1223
  ['push', cmdOpts('dry-run', 'force', 'hub', 'as', 'bundle')],
1216
1224
  ['start', cmdOpts('hub', 'crew', 'title', 'provide', 'modifier')],
1225
+ ['cancel', cmdOpts('hub', 'reason')],
1226
+ ['instance', cmdOpts('hub')],
1217
1227
  ['agent', cmdOpts('crews', 'hub', 'scopes', 'shift')],
1218
1228
  ['capability', cmdOpts('hub')],
1219
1229
  ['crew', cmdOpts('hub', 'kind', 'owner')],
@@ -3884,11 +3894,11 @@ async function dispatchPush(io, args) {
3884
3894
  }
3885
3895
  }
3886
3896
  /**
3887
- * Resolve the hub for `start` without ever falling through to the production
3888
- * default or an ambient `OWENLOOP_HUB`. A connected project supplies the
3889
- * durable default. `--hub` is allowed for an unbound directory, but must agree
3890
- * with an existing binding so a copied command cannot silently start a run on
3891
- * 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.
3892
3902
  */
3893
3903
  function resolveStartHub(io, args) {
3894
3904
  const binding = readHubBinding(hubBindingPath(io.cwd));
@@ -4023,6 +4033,189 @@ async function dispatchStart(io, args) {
4023
4033
  });
4024
4034
  return 0;
4025
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
+ }
4026
4219
  /**
4027
4220
  * `owenloop mcp` — serve the human control plane to a local MCP host over stdio.
4028
4221
  * A thin adapter: read the optional `--hub <url>` flag and hand `io` (which
@@ -5888,7 +6081,7 @@ async function runDoctor(io, origin) {
5888
6081
  * the async path, so every existing command and test keeps working exactly as
5889
6082
  * before.
5890
6083
  */
5891
- 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']);
5892
6085
  export async function mainAsync(argv, io = defaultIO()) {
5893
6086
  // Delegate execution-side and shift argv tails before root parsing. Their
5894
6087
  // roles own their option grammars, including repeated/value forms that the
@@ -5934,6 +6127,10 @@ export async function mainAsync(argv, io = defaultIO()) {
5934
6127
  return await dispatchPush(io, args);
5935
6128
  case 'start':
5936
6129
  return await dispatchStart(io, args);
6130
+ case 'cancel':
6131
+ return await dispatchCancel(io, args);
6132
+ case 'instance':
6133
+ return await dispatchInstance(io, args);
5937
6134
  case 'agent':
5938
6135
  return await dispatchAgent(io, args);
5939
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;
@@ -0,0 +1,87 @@
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
+ import { isAbsolute, join } from 'node:path';
55
+ /** Read an env var, treating blank and whitespace-only as unset. */
56
+ function present(value) {
57
+ if (value === undefined)
58
+ return undefined;
59
+ return value.trim() === '' ? undefined : value;
60
+ }
61
+ /**
62
+ * Resolve owenloop's user-level config directory from caller-supplied env.
63
+ *
64
+ * Throws when no rung of the ladder yields a value, rather than guessing a home
65
+ * directory from the ambient process.
66
+ */
67
+ export function owenloopConfigDir(env) {
68
+ const explicit = present(env.OWENLOOP_CONFIG_DIR);
69
+ if (explicit !== undefined) {
70
+ if (!isAbsolute(explicit)) {
71
+ throw new Error(`OWENLOOP_CONFIG_DIR must be an absolute path, received ${JSON.stringify(explicit)} — ` +
72
+ 'a relative config dir resolves against each step\'s own working directory');
73
+ }
74
+ return explicit;
75
+ }
76
+ const xdg = present(env.XDG_CONFIG_HOME);
77
+ if (xdg !== undefined)
78
+ return join(xdg, 'owenloop');
79
+ const home = present(env.HOME);
80
+ if (home !== undefined)
81
+ return join(home, '.config', 'owenloop');
82
+ throw new Error('cannot locate a config directory: set OWENLOOP_CONFIG_DIR, XDG_CONFIG_HOME, or HOME');
83
+ }
84
+ /** A file inside owenloop's config directory. */
85
+ export function owenloopConfigFile(env, ...segments) {
86
+ return join(owenloopConfigDir(env), ...segments);
87
+ }
@@ -1,9 +1,10 @@
1
1
  /**
2
2
  * Resolution of the local SSHSIG trust root used for workflow publications.
3
3
  *
4
- * The path is derived only from injected environment state. XDG_CONFIG_HOME
5
- * wins over HOME, matching the execution settings path; no ambient home
6
- * directory lookup is allowed here. An absent file is a normal result so the
4
+ * The path is derived only from injected environment state, through the shared
5
+ * `owenloopConfigDir` ladder (`OWENLOOP_CONFIG_DIR` > `XDG_CONFIG_HOME` >
6
+ * `HOME`); no ambient home directory lookup is allowed here. An absent file is
7
+ * a normal result so the
7
8
  * publication verifier can classify it as `unverifiable` instead of confusing
8
9
  * a missing trust root with an unsigned bundle.
9
10
  */
@@ -17,7 +18,10 @@ export interface AllowedSignersAbsent {
17
18
  path: string;
18
19
  }
19
20
  export type AllowedSignersResolution = AllowedSignersPresent | AllowedSignersAbsent;
20
- /** Resolve `<config>/owenloop/allowed_signers` from caller-supplied env. */
21
+ /**
22
+ * Resolve `<owenloop config dir>/allowed_signers` from caller-supplied env,
23
+ * through the one shared ladder in `../config-dir.ts`.
24
+ */
21
25
  export declare function allowedSignersPath(env: Record<string, string | undefined>): string;
22
26
  /**
23
27
  * Read the trust root without collapsing absence and malformed contents. A
@@ -1,23 +1,29 @@
1
1
  /**
2
2
  * Resolution of the local SSHSIG trust root used for workflow publications.
3
3
  *
4
- * The path is derived only from injected environment state. XDG_CONFIG_HOME
5
- * wins over HOME, matching the execution settings path; no ambient home
6
- * directory lookup is allowed here. An absent file is a normal result so the
4
+ * The path is derived only from injected environment state, through the shared
5
+ * `owenloopConfigDir` ladder (`OWENLOOP_CONFIG_DIR` > `XDG_CONFIG_HOME` >
6
+ * `HOME`); no ambient home directory lookup is allowed here. An absent file is
7
+ * a normal result so the
7
8
  * publication verifier can classify it as `unverifiable` instead of confusing
8
9
  * a missing trust root with an unsigned bundle.
9
10
  */
10
11
  import { existsSync, lstatSync, readFileSync } from 'node:fs';
11
- import { join } from 'node:path';
12
- /** Resolve `<config>/owenloop/allowed_signers` from caller-supplied env. */
12
+ import { owenloopConfigFile } from "../config-dir.js";
13
+ /**
14
+ * Resolve `<owenloop config dir>/allowed_signers` from caller-supplied env,
15
+ * through the one shared ladder in `../config-dir.ts`.
16
+ */
13
17
  export function allowedSignersPath(env) {
14
- const xdg = env.XDG_CONFIG_HOME;
15
- if (xdg !== undefined && xdg.trim() !== '')
16
- return join(xdg, 'owenloop', 'allowed_signers');
17
- const home = env.HOME;
18
- if (home !== undefined && home.trim() !== '')
19
- return join(home, '.config', 'owenloop', 'allowed_signers');
20
- throw new Error('cannot locate an allowed_signers path: set HOME or XDG_CONFIG_HOME');
18
+ try {
19
+ return owenloopConfigFile(env, 'allowed_signers');
20
+ }
21
+ catch (err) {
22
+ // Keep this resolver's own subject in the message. The shared ladder names
23
+ // the VARIABLES; this prefix names WHICH path could not be located, which
24
+ // is what the publication verifier reports to the operator.
25
+ throw new Error(`cannot locate an allowed_signers path: ${err instanceof Error ? err.message : String(err)}`);
26
+ }
21
27
  }
22
28
  /**
23
29
  * Read the trust root without collapsing absence and malformed contents. A
package/dist/src/defs.js CHANGED
@@ -667,8 +667,15 @@ export function buildDef(raw, source, baseDir) {
667
667
  * Prefix all names/stems in a StepDef with `${prefix}.`. Pure — returns a new StepDef.
668
668
  * Rewrites: step name, consume stems, produce stems, generates stems, invalidates, and
669
669
  * effect.onInvalidate step-name strings (but not 'pin'/'escalate').
670
+ *
671
+ * `defInputs` is the INCLUDED definition's declared input names, unprefixed. A
672
+ * `workdirFrom` stem may name one of those instead of one of the step's own
673
+ * consumes, and that stem is prefixed exactly like a consume stem is, because
674
+ * an unmapped child input is hoisted into the parent under `${prefix}.${name}`.
675
+ * Omitting the list would leave such a stem unparseable here and therefore
676
+ * silently unprefixed, pointing at a stem the expanded definition does not have.
670
677
  */
671
- function prefixStep(step, prefix) {
678
+ function prefixStep(step, prefix, defInputs = []) {
672
679
  const prefixStem = (stem) => `${prefix}.${stem}`;
673
680
  const newConsumes = step.consumes.map((c) => {
674
681
  const stem = prefixStem(c.stem);
@@ -710,11 +717,12 @@ function prefixStep(step, prefix) {
710
717
  // judges: marker names a local stem (unlike calls:, which names an external
711
718
  // workflow) — it must be prefixed to keep pointing at the (now-prefixed) produce.
712
719
  const newJudges = step.judges !== undefined ? prefixStem(step.judges) : undefined;
713
- // workdirFrom names a local consumed stem followed by a dotted value path.
714
- // Prefix only the stem; the value path is a field path inside the consumed value.
720
+ // workdirFrom names a local consumed stem or a declared input of the included
721
+ // definition, followed by a dotted value path. Prefix only the stem; the value
722
+ // path is a field path inside that artifact's value.
715
723
  let newWorkdirFrom = step.workdirFrom;
716
724
  if (step.workdirFrom !== undefined) {
717
- const parsed = parseWorkdirFrom(step.workdirFrom, step.consumes);
725
+ const parsed = parseWorkdirFrom(step.workdirFrom, step.consumes, defInputs);
718
726
  if (parsed)
719
727
  newWorkdirFrom = `${prefixStem(parsed.stem)}.${parsed.path}`;
720
728
  }
@@ -785,7 +793,8 @@ export function expandIncludes(def, resolve, stack) {
785
793
  }
786
794
  }
787
795
  // (e) prefix child steps
788
- const prefixedSteps = child.steps.map((l) => prefixStep(l, inc.as));
796
+ const childInputList = child.inputs.map((inp) => inp.name);
797
+ const prefixedSteps = child.steps.map((l) => prefixStep(l, inc.as, childInputList));
789
798
  // (f) handle inputs: mapped inputs become internal edges; unmapped are hoisted
790
799
  const inputRewrites = new Map(); // prefixed-stem -> outer artifact
791
800
  for (const childInp of child.inputs) {
@@ -800,6 +809,7 @@ export function expandIncludes(def, resolve, stack) {
800
809
  }
801
810
  }
802
811
  // Apply input rewrites to prefixed steps
812
+ const prefixedChildInputStems = child.inputs.map((inp) => `${inc.as}.${inp.name}`);
803
813
  const rewrittenSteps = prefixedSteps.map((l) => {
804
814
  const rewrittenConsumes = l.consumes.map((c) => {
805
815
  const outer = inputRewrites.get(c.stem);
@@ -809,7 +819,19 @@ export function expandIncludes(def, resolve, stack) {
809
819
  }
810
820
  return c;
811
821
  });
812
- return { ...l, consumes: rewrittenConsumes };
822
+ // A workdirFrom stem naming a MAPPED child input has to follow the same
823
+ // rewrite its consumes just took, or it would keep pointing at the
824
+ // child-local stem that this expansion just replaced. Split against the
825
+ // pre-rewrite consumes plus every prefixed child input, because the stem
826
+ // may be either and both are subject to the mapping.
827
+ let rewrittenWorkdirFrom = l.workdirFrom;
828
+ if (l.workdirFrom !== undefined) {
829
+ const parsed = parseWorkdirFrom(l.workdirFrom, l.consumes, prefixedChildInputStems);
830
+ const outer = parsed ? inputRewrites.get(parsed.stem) : undefined;
831
+ if (parsed && outer !== undefined)
832
+ rewrittenWorkdirFrom = `${outer}.${parsed.path}`;
833
+ }
834
+ return { ...l, consumes: rewrittenConsumes, workdirFrom: rewrittenWorkdirFrom };
813
835
  });
814
836
  resultSteps.push(...rewrittenSteps);
815
837
  // (g) merge child outputs
@@ -1103,25 +1125,44 @@ export function validateDef(def) {
1103
1125
  if (l.workdirFrom === undefined)
1104
1126
  continue;
1105
1127
  const raw = l.workdirFrom.trim();
1106
- const bareConsume = l.consumes.find((c) => c.stem === raw);
1107
- if (bareConsume) {
1108
- errors.push(`step '${l.name}': workdirFrom must use '<consumedStem>.<dotted.path>' with a non-empty value path`);
1128
+ // A stem that is itself dotted (`a.b`) would otherwise split into `a` + `b`
1129
+ // and report a confusing missing-stem error, so name the real mistake first:
1130
+ // the expression is a bare artifact name with no value path after it.
1131
+ const bareStem = l.consumes.some((c) => c.stem === raw) || inputNames.has(raw);
1132
+ if (bareStem) {
1133
+ errors.push(`step '${l.name}': workdirFrom must use '<stem>.<dotted.path>' with a non-empty value path`);
1109
1134
  continue;
1110
1135
  }
1111
1136
  const firstDot = raw.indexOf('.');
1112
1137
  const valuePath = firstDot >= 0 ? raw.slice(firstDot + 1) : '';
1113
1138
  if (firstDot <= 0 || valuePath.length === 0) {
1114
- errors.push(`step '${l.name}': workdirFrom must use '<consumedStem>.<dotted.path>' with a non-empty value path`);
1139
+ errors.push(`step '${l.name}': workdirFrom must use '<stem>.<dotted.path>' with a non-empty value path`);
1115
1140
  continue;
1116
1141
  }
1117
- // Security boundary: a workdirFrom value becomes a filesystem path. The
1118
- // source stem must be a plain consumed artifact so its value has passed the
1119
- // engine's consume-side verification gate before a worker can cd into it.
1120
- const parsed = parseWorkdirFrom(raw, l.consumes);
1142
+ // A workdirFrom value becomes a filesystem path, so the stem must name
1143
+ // something this def actually declares: one of the step's own plain
1144
+ // consumes, or one of the definition's declared inputs.
1145
+ //
1146
+ // The input form exists because a COMMAND step cannot consume a human seed
1147
+ // at all — `exec/instructions.ts` gates command orders with `hardRule:
1148
+ // true`, and `consumed-verifier.ts` refuses any consumed value lacking a
1149
+ // producer signature, which a human-supplied input never has. Naming the
1150
+ // input here routes it through `OrderPacket.workdir` instead, which is a
1151
+ // spawn parameter rather than shell text or a consumed artifact.
1152
+ //
1153
+ // This deliberately relaxes an earlier rule that demanded a CONSUME, on the
1154
+ // stated grounds that the value must pass the consume-side gate "before a
1155
+ // worker can cd into it". That protection was not real: the engine resolves
1156
+ // this expression itself and ships a plain string as `OrderPacket.workdir`,
1157
+ // an explicitly "opaque location hint" that no proof covers and that the
1158
+ // command worker uses unverified. See `paths.ts`'s parseWorkdirFrom header
1159
+ // for the full argument, and note that the runtime bound on a worker's cwd
1160
+ // is the operator's declared work roots, not this check.
1161
+ const parsed = parseWorkdirFrom(raw, l.consumes, [...inputNames]);
1121
1162
  if (!parsed) {
1122
1163
  const stem = raw.slice(0, firstDot);
1123
- errors.push(`step '${l.name}': workdirFrom stem '${stem}' is not in consumes; ` +
1124
- 'a step may only take its workdir from an artifact it consumes');
1164
+ errors.push(`step '${l.name}': workdirFrom stem '${stem}' is neither in consumes nor a declared input; ` +
1165
+ "a step may only take its workdir from an artifact it consumes or from one of the definition's inputs");
1125
1166
  }
1126
1167
  else if (parsed.mode !== 'plain') {
1127
1168
  errors.push(`step '${l.name}': workdirFrom stem '${parsed.stem}' uses a ${parsed.mode} consume; ` +
@@ -1389,14 +1389,36 @@ export class Engine {
1389
1389
  };
1390
1390
  let resolvedWorkdir;
1391
1391
  if (step.workdirFrom !== undefined) {
1392
- const parsed = parseWorkdirFrom(step.workdirFrom, step.consumes);
1392
+ const parsed = parseWorkdirFrom(step.workdirFrom, step.consumes, def.inputs.map((i) => i.name));
1393
1393
  if (!parsed) {
1394
- return unresolved(`workdirFrom '${step.workdirFrom}': expected a consumed stem followed by a non-empty dotted value path`);
1394
+ return unresolved(`workdirFrom '${step.workdirFrom}': expected a consumed or declared-input stem followed by a non-empty dotted value path`);
1395
1395
  }
1396
1396
  if (parsed.mode !== 'plain') {
1397
1397
  return unresolved(`workdirFrom '${step.workdirFrom}': source stem '${parsed.stem}' is not a plain consume`);
1398
1398
  }
1399
- let value = consumes[parsed.stem];
1399
+ // A CONSUMED stem reads out of the firing's resolved consume map, exactly
1400
+ // as before. An INPUT stem the step does not consume is not in that map,
1401
+ // so it reads out of the instance's artifact table instead.
1402
+ //
1403
+ // The green check is what makes this an ordering edge without a consume.
1404
+ // `unresolved` defers the firing rather than failing it, so a step whose
1405
+ // workdir comes from a still-owed input simply is not offered yet and is
1406
+ // reconsidered on the next tick — the same wait a consume would have
1407
+ // produced, without putting the value in `order.consumes` (where the
1408
+ // command launch gate would hard-refuse it for having no producer
1409
+ // signature: a human seed has none). See `paths.ts`'s parseWorkdirFrom
1410
+ // header for why an input-authored cwd is admissible at all.
1411
+ let value;
1412
+ if (parsed.source === 'consume') {
1413
+ value = consumes[parsed.stem];
1414
+ }
1415
+ else {
1416
+ const art = arts.get(parsed.stem);
1417
+ if (art === undefined || art.acceptance !== 'green') {
1418
+ return unresolved(`workdirFrom '${step.workdirFrom}': input '${parsed.stem}' is not green yet`);
1419
+ }
1420
+ value = art.value;
1421
+ }
1400
1422
  const segments = parsed.path.split('.');
1401
1423
  for (let i = 0; i < segments.length; i++) {
1402
1424
  const segment = segments[i];