owenloop 0.4.0 → 0.5.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.
Files changed (155) hide show
  1. package/CHANGELOG.md +45 -0
  2. package/README.md +98 -25
  3. package/bin/owenloop.mjs +2 -2
  4. package/dist/packages/work/src/agent/brief.d.ts +172 -0
  5. package/dist/packages/work/src/agent/brief.js +193 -0
  6. package/dist/packages/work/src/agent/loop.d.ts +135 -0
  7. package/dist/packages/work/src/agent/loop.js +542 -0
  8. package/dist/packages/work/src/agent/workdir.d.ts +210 -0
  9. package/dist/packages/work/src/agent/workdir.js +319 -0
  10. package/dist/packages/work/src/bundle/cache.d.ts +90 -0
  11. package/dist/packages/work/src/bundle/cache.js +324 -0
  12. package/dist/packages/work/src/bundle/fetch.d.ts +85 -0
  13. package/dist/packages/work/src/bundle/fetch.js +325 -0
  14. package/dist/packages/work/src/bundle/types.d.ts +160 -0
  15. package/dist/packages/work/src/bundle/types.js +1 -0
  16. package/dist/packages/work/src/credentials/owenloop.d.ts +11 -0
  17. package/dist/packages/work/src/credentials/owenloop.js +28 -0
  18. package/dist/packages/work/src/credentials/reader.d.ts +36 -0
  19. package/dist/packages/work/src/credentials/reader.js +32 -0
  20. package/dist/packages/work/src/credentials/resolve.d.ts +19 -0
  21. package/dist/packages/work/src/credentials/resolve.js +56 -0
  22. package/dist/packages/work/src/exec/loop.d.ts +29 -0
  23. package/dist/packages/work/src/exec/loop.js +215 -0
  24. package/dist/packages/work/src/exec/receipt.d.ts +38 -0
  25. package/dist/packages/work/src/exec/receipt.js +21 -0
  26. package/dist/packages/work/src/exec/runner.d.ts +65 -0
  27. package/dist/packages/work/src/exec/runner.js +185 -0
  28. package/dist/packages/work/src/harness/child-env.d.ts +100 -0
  29. package/dist/packages/work/src/harness/child-env.js +127 -0
  30. package/dist/packages/work/src/harness/claude.d.ts +128 -0
  31. package/dist/packages/work/src/harness/claude.js +635 -0
  32. package/dist/packages/work/src/harness/codex.d.ts +110 -0
  33. package/dist/packages/work/src/harness/codex.js +896 -0
  34. package/dist/packages/work/src/harness/contract.d.ts +283 -0
  35. package/dist/packages/work/src/harness/contract.js +32 -0
  36. package/dist/packages/work/src/harness/fake.d.ts +59 -0
  37. package/dist/packages/work/src/harness/fake.js +90 -0
  38. package/dist/packages/work/src/harness/jsonrpc-stdio.d.ts +108 -0
  39. package/dist/packages/work/src/harness/jsonrpc-stdio.js +344 -0
  40. package/dist/packages/work/src/harness/permissions.d.ts +62 -0
  41. package/dist/packages/work/src/harness/permissions.js +93 -0
  42. package/dist/packages/work/src/harness/registry.d.ts +47 -0
  43. package/dist/packages/work/src/harness/registry.js +45 -0
  44. package/dist/packages/work/src/harness/session-store.d.ts +163 -0
  45. package/dist/packages/work/src/harness/session-store.js +319 -0
  46. package/dist/packages/work/src/harness/types.d.ts +29 -0
  47. package/dist/packages/work/src/harness/types.js +14 -0
  48. package/dist/packages/work/src/harnesses.d.ts +38 -0
  49. package/dist/packages/work/src/harnesses.js +38 -0
  50. package/dist/packages/work/src/hold/loop.d.ts +36 -0
  51. package/dist/packages/work/src/hold/loop.js +23 -0
  52. package/dist/packages/work/src/hold/mcp.d.ts +55 -0
  53. package/dist/packages/work/src/hold/mcp.js +149 -0
  54. package/dist/packages/work/src/hub/client.d.ts +22 -0
  55. package/dist/packages/work/src/hub/client.js +78 -0
  56. package/dist/packages/work/src/hub/types.d.ts +290 -0
  57. package/dist/packages/work/src/hub/types.js +28 -0
  58. package/dist/packages/work/src/lease/loop.d.ts +94 -0
  59. package/dist/packages/work/src/lease/loop.js +277 -0
  60. package/dist/packages/work/src/main.d.ts +1 -0
  61. package/dist/packages/work/src/main.js +48 -0
  62. package/dist/packages/work/src/mcp/server.d.ts +125 -0
  63. package/dist/packages/work/src/mcp/server.js +320 -0
  64. package/dist/packages/work/src/roles/agent-run.d.ts +118 -0
  65. package/dist/packages/work/src/roles/agent-run.js +447 -0
  66. package/dist/packages/work/src/roles/exec.d.ts +40 -0
  67. package/dist/packages/work/src/roles/exec.js +203 -0
  68. package/dist/packages/work/src/roles/hold.d.ts +68 -0
  69. package/dist/packages/work/src/roles/hold.js +324 -0
  70. package/dist/packages/work/src/roles/join.d.ts +18 -0
  71. package/dist/packages/work/src/roles/join.js +204 -0
  72. package/dist/packages/work/src/roles/lint.d.ts +59 -0
  73. package/dist/packages/work/src/roles/lint.js +200 -0
  74. package/dist/packages/work/src/roles/prepare.d.ts +1 -0
  75. package/dist/packages/work/src/roles/prepare.js +249 -0
  76. package/dist/packages/work/src/roles/release.d.ts +48 -0
  77. package/dist/packages/work/src/roles/release.js +137 -0
  78. package/dist/packages/work/src/roles/sessions.d.ts +61 -0
  79. package/dist/packages/work/src/roles/sessions.js +180 -0
  80. package/dist/packages/work/src/roles/settings.d.ts +6 -0
  81. package/dist/packages/work/src/roles/settings.js +66 -0
  82. package/dist/packages/work/src/roles/shift.d.ts +12 -0
  83. package/dist/packages/work/src/roles/shift.js +228 -0
  84. package/dist/packages/work/src/roles/signals.d.ts +55 -0
  85. package/dist/packages/work/src/roles/signals.js +62 -0
  86. package/dist/packages/work/src/settings/provision.d.ts +21 -0
  87. package/dist/packages/work/src/settings/provision.js +47 -0
  88. package/dist/packages/work/src/settings/settings.d.ts +120 -0
  89. package/dist/packages/work/src/settings/settings.js +116 -0
  90. package/dist/packages/work/src/shift/client.d.ts +24 -0
  91. package/dist/packages/work/src/shift/client.js +124 -0
  92. package/dist/packages/work/src/shift/loop.d.ts +120 -0
  93. package/dist/packages/work/src/shift/loop.js +468 -0
  94. package/dist/packages/work/src/shift/protocol.d.ts +91 -0
  95. package/dist/packages/work/src/shift/protocol.js +24 -0
  96. package/dist/packages/work/src/shift/routing.d.ts +35 -0
  97. package/dist/packages/work/src/shift/routing.js +50 -0
  98. package/dist/packages/work/src/shift/runtime.d.ts +43 -0
  99. package/dist/packages/work/src/shift/runtime.js +274 -0
  100. package/dist/packages/work/src/shift/server.d.ts +23 -0
  101. package/dist/packages/work/src/shift/server.js +716 -0
  102. package/dist/packages/work/src/shift/spawn.d.ts +86 -0
  103. package/dist/packages/work/src/shift/spawn.js +100 -0
  104. package/dist/packages/work/src/shift/state.d.ts +77 -0
  105. package/dist/packages/work/src/shift/state.js +162 -0
  106. package/dist/packages/work/src/usage.d.ts +6 -0
  107. package/dist/packages/work/src/usage.js +175 -0
  108. package/dist/{add.d.ts → src/add.d.ts} +12 -40
  109. package/dist/{add.js → src/add.js} +11 -176
  110. package/dist/src/cli.d.ts +147 -0
  111. package/dist/{cli.js → src/cli.js} +1643 -353
  112. package/dist/src/credentials.d.ts +280 -0
  113. package/dist/src/credentials.js +697 -0
  114. package/dist/{defs.js → src/defs.js} +59 -36
  115. package/dist/{engine.d.ts → src/engine.d.ts} +8 -8
  116. package/dist/{engine.js → src/engine.js} +29 -20
  117. package/dist/{hub.d.ts → src/hub.d.ts} +330 -2
  118. package/dist/{hub.js → src/hub.js} +531 -1
  119. package/dist/{index.d.ts → src/index.d.ts} +3 -1
  120. package/dist/{index.js → src/index.js} +2 -1
  121. package/dist/src/lock.d.ts +80 -0
  122. package/dist/src/lock.js +217 -0
  123. package/dist/src/mcp/serve.d.ts +85 -0
  124. package/dist/src/mcp/serve.js +702 -0
  125. package/dist/src/mcp/server.d.ts +132 -0
  126. package/dist/src/mcp/server.js +327 -0
  127. package/dist/{model.d.ts → src/model.d.ts} +59 -4
  128. package/dist/{model.js → src/model.js} +149 -22
  129. package/dist/{types.d.ts → src/types.d.ts} +66 -24
  130. package/dist/{util.d.ts → src/util.d.ts} +25 -0
  131. package/dist/{util.js → src/util.js} +26 -0
  132. package/dist/src/work-settings.d.ts +57 -0
  133. package/dist/src/work-settings.js +84 -0
  134. package/docs/authoring.md +102 -53
  135. package/docs/cli.md +883 -29
  136. package/docs/design.md +119 -45
  137. package/docs/embedding.md +39 -14
  138. package/examples/workflows/{command-worker.yaml → command-executor.yaml} +15 -15
  139. package/examples/workflows/compile-dev-playbook.yaml +338 -0
  140. package/examples/workflows/judges/gate-sharpness.md +39 -0
  141. package/examples/workflows/judges/security.md +34 -0
  142. package/package.json +17 -8
  143. package/dist/cli.d.ts +0 -83
  144. /package/dist/{defs.d.ts → src/defs.d.ts} +0 -0
  145. /package/dist/{factory.d.ts → src/factory.d.ts} +0 -0
  146. /package/dist/{factory.js → src/factory.js} +0 -0
  147. /package/dist/{paths.d.ts → src/paths.d.ts} +0 -0
  148. /package/dist/{paths.js → src/paths.js} +0 -0
  149. /package/dist/{schema.d.ts → src/schema.d.ts} +0 -0
  150. /package/dist/{schema.js → src/schema.js} +0 -0
  151. /package/dist/{store.d.ts → src/store.d.ts} +0 -0
  152. /package/dist/{store.js → src/store.js} +0 -0
  153. /package/dist/{types.js → src/types.js} +0 -0
  154. /package/dist/{untar.d.ts → src/untar.d.ts} +0 -0
  155. /package/dist/{untar.js → src/untar.js} +0 -0
@@ -0,0 +1,204 @@
1
+ /**
2
+ * `owenloop work join <code> [--hub <origin>] [--as <account>]` — a ONE-TIME
3
+ * PROVISIONING role (NOT runtime): redeem an `ojc_` join code against the
4
+ * hub's unauthenticated `POST /enroll/redeem`, then write the returned
5
+ * `olp_` Scoped Identity token into owenloop's credential store via owenloop's public
6
+ * `storeCredential`. `join` is the SOLE credential-store writer in owenloop —
7
+ * every other role reads the store through `CredentialReader` and never
8
+ * writes it (see src/credentials/resolve.ts).
9
+ *
10
+ * ORIGIN RULE (security-critical): the origin comes ONLY from `--hub` or the
11
+ * existing `settings.hubOrigin` — never from the join code, and never from
12
+ * the hub's own response body. The human states the hub; the code merely
13
+ * redeems there. A pasted code must never be able to redirect a box to an
14
+ * attacker's hub, so no line of this module parses, slices, or inspects
15
+ * `<code>` for anything beyond passing it verbatim in the POST body, and the
16
+ * response's `hubOrigin` field is ignored for every control decision.
17
+ *
18
+ * Settings write: first-write-wins via `recordHubOrigin` (settings/provision.ts)
19
+ * — a differing existing `hubOrigin` is left untouched, with a warning, not
20
+ * overwritten.
21
+ *
22
+ * The redeemed token and the join code appear in NO output line (stdout or
23
+ * stderr) under any code path — they are process→store only.
24
+ *
25
+ * Exit codes: 0 ok · 1 runtime failure (settings load, redeem, store write,
26
+ * unexpected hub response, hub error status) · 2 usage (bad args, missing
27
+ * origin, invalid origin).
28
+ */
29
+ import { hostname } from 'node:os';
30
+ import { normalizeOrigin } from "../../../../src/hub.js";
31
+ import { storeCredential } from "../../../../src/credentials.js";
32
+ import { loadSettings } from "../settings/settings.js";
33
+ import { recordHubOrigin } from "../settings/provision.js";
34
+ /** Parse `<code> [--hub <origin>] [--as <account>]`, both `--flag value` and `--flag=value` forms. */
35
+ export function parseArgs(args) {
36
+ const parsed = {};
37
+ const takeValue = (a, i) => {
38
+ const eq = a.indexOf('=');
39
+ if (eq !== -1)
40
+ return { value: a.slice(eq + 1), next: i };
41
+ const v = args[i + 1];
42
+ if (v === undefined)
43
+ return { error: `missing value for ${a}` };
44
+ return { value: v, next: i + 1 };
45
+ };
46
+ for (let i = 0; i < args.length; i++) {
47
+ const a = args[i];
48
+ const name = a.startsWith('--') && a.includes('=') ? a.slice(0, a.indexOf('=')) : a;
49
+ switch (name) {
50
+ case '--hub':
51
+ case '--as': {
52
+ const r = takeValue(a, i);
53
+ if ('error' in r)
54
+ return { error: r.error };
55
+ i = r.next;
56
+ if (name === '--hub')
57
+ parsed.hub = r.value;
58
+ else
59
+ parsed.as = r.value;
60
+ break;
61
+ }
62
+ default:
63
+ if (a.startsWith('-'))
64
+ return { error: `unknown option '${a}'` };
65
+ if (parsed.code === undefined)
66
+ parsed.code = a;
67
+ else
68
+ return { error: `unexpected argument '${a}'` };
69
+ }
70
+ }
71
+ return parsed;
72
+ }
73
+ function usage(err) {
74
+ err('usage: owenloop work join <code> [--hub <origin>] [--as <account>]');
75
+ }
76
+ function errMsg(e) {
77
+ return e instanceof Error ? e.message : String(e);
78
+ }
79
+ /** Map a non-2xx redeem response onto the exact-wording exit-1 message (brief-pinned strings for 410/404). */
80
+ async function redeemErrorMessage(status, res) {
81
+ if (status === 410) {
82
+ return 'code expired or already used — ask for a fresh one (Agents page → Approve/Reconnect)';
83
+ }
84
+ if (status === 404) {
85
+ return 'invalid code — check the paste, or ask for a fresh one (Agents page → Approve/Reconnect)';
86
+ }
87
+ if (status === 409) {
88
+ const body = await safeJson(res);
89
+ const message = typeof body?.['message'] === 'string' ? body['message'] : 'redemption blocked';
90
+ return `${message} — fix it on the console and retry (the code is still valid)`;
91
+ }
92
+ if (status === 429) {
93
+ const retryAfter = res.headers.get('retry-after');
94
+ return retryAfter !== null ? `rate limited — retry in ${retryAfter}s` : 'rate limited';
95
+ }
96
+ if (status === 400) {
97
+ return 'hub rejected the request (bad request)';
98
+ }
99
+ return `hub error ${status}`;
100
+ }
101
+ async function safeJson(res) {
102
+ try {
103
+ const body = await res.json();
104
+ return typeof body === 'object' && body !== null && !Array.isArray(body) ? body : undefined;
105
+ }
106
+ catch {
107
+ return undefined;
108
+ }
109
+ }
110
+ export async function run(args, deps = {}) {
111
+ const out = deps.out ?? ((line) => void process.stdout.write(`${line}\n`));
112
+ const err = deps.err ?? ((line) => void process.stderr.write(`${line}\n`));
113
+ const env = deps.env ?? process.env;
114
+ const fetchImpl = deps.fetchImpl ?? fetch;
115
+ const parsed = parseArgs(args);
116
+ if (parsed.error !== undefined) {
117
+ err(`owenloop work join: ${parsed.error}`);
118
+ usage(err);
119
+ return 2;
120
+ }
121
+ if (parsed.code === undefined) {
122
+ err('owenloop work join: missing required <code>');
123
+ usage(err);
124
+ return 2;
125
+ }
126
+ const code = parsed.code;
127
+ let settings;
128
+ try {
129
+ settings = loadSettings(env);
130
+ }
131
+ catch (e) {
132
+ err(`owenloop work join: ${errMsg(e)}`);
133
+ return 1;
134
+ }
135
+ // Origin resolution (security-critical) — see module doc. The code plays no
136
+ // part in this decision at all.
137
+ const raw = parsed.hub ?? settings.hubOrigin;
138
+ if (raw === undefined || raw.trim() === '') {
139
+ err('owenloop work join: no hub origin — pass --hub <origin>, or set hubOrigin in settings');
140
+ return 2;
141
+ }
142
+ let origin;
143
+ try {
144
+ origin = normalizeOrigin(raw);
145
+ }
146
+ catch (e) {
147
+ err(`owenloop work join: ${errMsg(e)}`);
148
+ return 2;
149
+ }
150
+ // Redeem — unauthenticated by design (H4): no Authorization header.
151
+ let res;
152
+ try {
153
+ res = await fetchImpl(`${origin}/enroll/redeem`, {
154
+ method: 'POST',
155
+ headers: { 'content-type': 'application/json' },
156
+ body: JSON.stringify({ code, device: { hostname: hostname(), platform: process.platform } }),
157
+ });
158
+ }
159
+ catch (e) {
160
+ err(`owenloop work join: redeem failed: ${errMsg(e)}`);
161
+ return 1;
162
+ }
163
+ if (!res.ok) {
164
+ err(`owenloop work join: ${await redeemErrorMessage(res.status, res)}`);
165
+ return 1;
166
+ }
167
+ const body = await safeJson(res);
168
+ const token = body?.['token'];
169
+ const agentName = body?.['agentName'];
170
+ if (typeof token !== 'string' || typeof agentName !== 'string') {
171
+ err('owenloop work join: unexpected hub response');
172
+ return 1;
173
+ }
174
+ const crewsRaw = body?.['crews'];
175
+ const crews = Array.isArray(crewsRaw) && crewsRaw.every((p) => typeof p === 'string') ? crewsRaw : undefined;
176
+ // body.hubOrigin (if present) is deliberately never read — see module doc.
177
+ const account = parsed.as ?? agentName;
178
+ let backend;
179
+ try {
180
+ backend = await storeCredential({ env, ...(deps.keychain !== undefined ? { keychain: deps.keychain } : {}) }, origin, { principal: 'agent', account }, { kind: 'agent', accessToken: token });
181
+ }
182
+ catch (e) {
183
+ err(`owenloop work join: ${errMsg(e)}`);
184
+ return 1;
185
+ }
186
+ const recorded = recordHubOrigin(env, origin);
187
+ if (recorded.outcome === 'conflict') {
188
+ err(`owenloop work join: warning: settings hubOrigin is ${recorded.existing} (differs from ${origin}) — ` +
189
+ `left untouched; pass --hub <origin> to future commands or edit ${recorded.path}`);
190
+ }
191
+ out(`joined ${origin} as Scoped Identity '${agentName}'`);
192
+ if (crews !== undefined && crews.length > 0)
193
+ out(` crews: ${crews.join(', ')}`);
194
+ out(` credential: agent:${account} (${backend} backend)`);
195
+ // 'unchanged' and 'conflict' both leave the file byte-identical, so both
196
+ // read the same on stdout; the 'conflict' case additionally warned on
197
+ // stderr above with the differing-origin detail.
198
+ const settingsLine = recorded.outcome === 'written' ? `written -> ${recorded.path}` : `hubOrigin already set (unchanged) -> ${recorded.path}`;
199
+ out(` settings: ${settingsLine}`);
200
+ const asSuffix = account === 'default' ? '' : ` --as ${account}`;
201
+ const shiftScope = crews !== undefined && crews.length > 0 ? crews.join(' ') : '--all';
202
+ out(` next: owenloop shift start ${shiftScope}${asSuffix}`);
203
+ return 0;
204
+ }
@@ -0,0 +1,59 @@
1
+ /**
2
+ * `owenloop work lint <workflow-name | path>` — validate the `x.harness` option bags
3
+ * in a workflow def or cached bundle and report actionable, per-step/per-field
4
+ * findings.
5
+ *
6
+ * WHICH HARNESS CHECKS A STEP. Each step names its harness (`x.harness.id`, or a
7
+ * top-level `harness` key, which wins), and lint asks THAT adapter's optional
8
+ * `lintStep(bag, step)`. A step that names no harness is checked by the DEFAULT
9
+ * adapter — `defaultHarnessId()`, the registry head — because that is the adapter
10
+ * that will actually run it. A step naming an unregistered harness is an error
11
+ * finding, not silence: the def selects something this build cannot run.
12
+ *
13
+ * WHERE THE ADAPTERS COME FROM (Phase 6). This module used to be the SECOND
14
+ * composition root, carrying its own copy of the adapter imports in an order
15
+ * that had to match `src/roles/agent-run.ts` exactly — because the first id
16
+ * registered is what `defaultHarnessId()` returns, and lint must judge a
17
+ * harness-less step by the same default that will run it. Both roots are now the
18
+ * one module `src/harnesses.ts`, imported below for its side effect, so that
19
+ * order has a single owner and the two files can no longer disagree.
20
+ *
21
+ * Target resolution (D9):
22
+ * `*.yaml` / `*.yml` — a raw owenloop def, parsed with `yaml`. Only what lint
23
+ * needs is read (a `steps` list with `name` + optional
24
+ * `x`); this does NOT reimplement owenloop's validator.
25
+ * `*.json` — a cached/exported bundle (`CachedBundle` or a bare
26
+ * `FetchedDef`).
27
+ * bare name — the latest cached bundle for that workflow (error with
28
+ * "run `owenloop work prepare <name>` first" when absent).
29
+ *
30
+ * Exit codes: 0 clean or warnings-only · 1 any error finding (or a load
31
+ * failure) · 2 usage. (Exit 1 is new for lint but consistent: 0 ok / 1 real
32
+ * failure / 2 usage / 3 stub.)
33
+ */
34
+ import '../harnesses.ts';
35
+ import type { FetchedStep } from '../bundle/types.ts';
36
+ import type { LintFinding } from '../harness/types.ts';
37
+ export declare function run(args: string[]): Promise<number>;
38
+ /**
39
+ * Findings for ONE step: resolve which adapter would run it, then hand that
40
+ * adapter the step's option bag.
41
+ *
42
+ * A step with no `x.harness` bag at all is silent — an empty bag is a completely
43
+ * normal step, and lint has nothing to say about it. That is why the empty-bag
44
+ * check comes BEFORE the unregistered-harness check: a def that names no harness
45
+ * and carries no options is clean even in a build with an empty registry.
46
+ *
47
+ * ONE finding is raised HERE rather than by the adapter: the bag-`model` /
48
+ * first-class-`model` conflict. The harness contract's `lintStep(bag, step)`
49
+ * receives only the bag and the step NAME, so no adapter can see `step.model`;
50
+ * this function still holds the whole `FetchedStep`. Raising it here is also the
51
+ * neutral home for it, because the precedence it warns about is implemented by
52
+ * the NEUTRAL normalizer (`normalizeStepPermissions` in
53
+ * `src/harness/permissions.ts`: `step.model` wins over `bag.model`), not by any
54
+ * one adapter.
55
+ *
56
+ * Exported for tests: the alternative is asserting on `run()`'s stdout, which
57
+ * would test the printer instead of the resolution logic.
58
+ */
59
+ export declare function lintOneStep(step: FetchedStep): LintFinding[];
@@ -0,0 +1,200 @@
1
+ /**
2
+ * `owenloop work lint <workflow-name | path>` — validate the `x.harness` option bags
3
+ * in a workflow def or cached bundle and report actionable, per-step/per-field
4
+ * findings.
5
+ *
6
+ * WHICH HARNESS CHECKS A STEP. Each step names its harness (`x.harness.id`, or a
7
+ * top-level `harness` key, which wins), and lint asks THAT adapter's optional
8
+ * `lintStep(bag, step)`. A step that names no harness is checked by the DEFAULT
9
+ * adapter — `defaultHarnessId()`, the registry head — because that is the adapter
10
+ * that will actually run it. A step naming an unregistered harness is an error
11
+ * finding, not silence: the def selects something this build cannot run.
12
+ *
13
+ * WHERE THE ADAPTERS COME FROM (Phase 6). This module used to be the SECOND
14
+ * composition root, carrying its own copy of the adapter imports in an order
15
+ * that had to match `src/roles/agent-run.ts` exactly — because the first id
16
+ * registered is what `defaultHarnessId()` returns, and lint must judge a
17
+ * harness-less step by the same default that will run it. Both roots are now the
18
+ * one module `src/harnesses.ts`, imported below for its side effect, so that
19
+ * order has a single owner and the two files can no longer disagree.
20
+ *
21
+ * Target resolution (D9):
22
+ * `*.yaml` / `*.yml` — a raw owenloop def, parsed with `yaml`. Only what lint
23
+ * needs is read (a `steps` list with `name` + optional
24
+ * `x`); this does NOT reimplement owenloop's validator.
25
+ * `*.json` — a cached/exported bundle (`CachedBundle` or a bare
26
+ * `FetchedDef`).
27
+ * bare name — the latest cached bundle for that workflow (error with
28
+ * "run `owenloop work prepare <name>` first" when absent).
29
+ *
30
+ * Exit codes: 0 clean or warnings-only · 1 any error finding (or a load
31
+ * failure) · 2 usage. (Exit 1 is new for lint but consistent: 0 ok / 1 real
32
+ * failure / 2 usage / 3 stub.)
33
+ */
34
+ import "../harnesses.js";
35
+ import { existsSync, readFileSync } from 'node:fs';
36
+ import { parse as parseYaml } from 'yaml';
37
+ import { adapterFor, defaultHarnessId } from "../harness/registry.js";
38
+ import { parseHarnessCarrier } from "../bundle/fetch.js";
39
+ import { readLatestBundle, resolveCacheDir } from "../bundle/cache.js";
40
+ import { loadSettings } from "../settings/settings.js";
41
+ export async function run(args) {
42
+ const positional = args.filter((a) => !a.startsWith('-'));
43
+ const unknownFlag = args.find((a) => a.startsWith('-'));
44
+ if (unknownFlag !== undefined) {
45
+ process.stderr.write(`owenloop work lint: unknown option '${unknownFlag}'\n`);
46
+ process.stderr.write('usage: owenloop work lint <workflow-name | path>\n');
47
+ return 2;
48
+ }
49
+ if (positional.length === 0) {
50
+ process.stderr.write('owenloop work lint: missing required <workflow-name | path>\n');
51
+ process.stderr.write('usage: owenloop work lint <workflow-name | path>\n');
52
+ return 2;
53
+ }
54
+ if (positional.length > 1) {
55
+ process.stderr.write(`owenloop work lint: unexpected argument '${positional[1]}'\n`);
56
+ return 2;
57
+ }
58
+ const target = positional[0];
59
+ let steps;
60
+ try {
61
+ steps = loadSteps(target);
62
+ }
63
+ catch (err) {
64
+ process.stderr.write(`owenloop work lint: ${err instanceof Error ? err.message : String(err)}\n`);
65
+ return 1;
66
+ }
67
+ const findings = [];
68
+ for (const step of steps) {
69
+ findings.push(...lintOneStep(step));
70
+ }
71
+ const out = process.stdout;
72
+ let errors = 0;
73
+ let warnings = 0;
74
+ for (const f of findings) {
75
+ if (f.severity === 'error')
76
+ errors++;
77
+ else
78
+ warnings++;
79
+ const loc = f.field !== undefined ? `x.harness.${f.field}` : 'x.harness';
80
+ out.write(`${f.severity} step ${f.step}: ${loc}: ${f.message}\n`);
81
+ }
82
+ out.write(`lint: ${steps.length} step(s), ${errors} error(s), ${warnings} warning(s)\n`);
83
+ return errors > 0 ? 1 : 0;
84
+ }
85
+ /**
86
+ * Findings for ONE step: resolve which adapter would run it, then hand that
87
+ * adapter the step's option bag.
88
+ *
89
+ * A step with no `x.harness` bag at all is silent — an empty bag is a completely
90
+ * normal step, and lint has nothing to say about it. That is why the empty-bag
91
+ * check comes BEFORE the unregistered-harness check: a def that names no harness
92
+ * and carries no options is clean even in a build with an empty registry.
93
+ *
94
+ * ONE finding is raised HERE rather than by the adapter: the bag-`model` /
95
+ * first-class-`model` conflict. The harness contract's `lintStep(bag, step)`
96
+ * receives only the bag and the step NAME, so no adapter can see `step.model`;
97
+ * this function still holds the whole `FetchedStep`. Raising it here is also the
98
+ * neutral home for it, because the precedence it warns about is implemented by
99
+ * the NEUTRAL normalizer (`normalizeStepPermissions` in
100
+ * `src/harness/permissions.ts`: `step.model` wins over `bag.model`), not by any
101
+ * one adapter.
102
+ *
103
+ * Exported for tests: the alternative is asserting on `run()`'s stdout, which
104
+ * would test the printer instead of the resolution logic.
105
+ */
106
+ export function lintOneStep(step) {
107
+ const bag = step.harnessOptions;
108
+ if (bag === undefined)
109
+ return [];
110
+ const id = step.harness ?? defaultHarnessId();
111
+ if (id === undefined) {
112
+ return [{
113
+ severity: 'error',
114
+ step: step.name,
115
+ message: 'no harness is registered in this build, so nothing can check these options',
116
+ }];
117
+ }
118
+ const adapter = adapterFor(id);
119
+ if (adapter === undefined) {
120
+ return [{
121
+ severity: 'error',
122
+ step: step.name,
123
+ message: `unknown harness '${id}' — this build cannot run it`,
124
+ field: 'id',
125
+ }];
126
+ }
127
+ const findings = [...(adapter.lintStep?.(bag, step.name) ?? [])];
128
+ if (step.model !== undefined && 'model' in bag) {
129
+ findings.push({
130
+ severity: 'warning',
131
+ step: step.name,
132
+ field: 'model',
133
+ message: `bag sets model but the step's first-class model wins (step model: '${step.model}')`,
134
+ });
135
+ }
136
+ return findings;
137
+ }
138
+ /** Load the steps to lint from a yaml def, a json bundle, or a bare name. */
139
+ function loadSteps(target) {
140
+ if (target.endsWith('.yaml') || target.endsWith('.yml')) {
141
+ if (!existsSync(target))
142
+ throw new Error(`no such file: ${target}`);
143
+ const parsed = parseYaml(readFileSync(target, 'utf8'));
144
+ return stepsFromDefLike(parsed, target);
145
+ }
146
+ if (target.endsWith('.json')) {
147
+ if (!existsSync(target))
148
+ throw new Error(`no such file: ${target}`);
149
+ let parsed;
150
+ try {
151
+ parsed = JSON.parse(readFileSync(target, 'utf8'));
152
+ }
153
+ catch (err) {
154
+ throw new Error(`malformed JSON in ${target}: ${err instanceof Error ? err.message : String(err)}`);
155
+ }
156
+ // A CachedBundle wraps the def under `def`; a bare FetchedDef is the def.
157
+ const p = parsed;
158
+ const defLike = p && typeof p === 'object' && 'def' in p ? p['def'] : parsed;
159
+ return stepsFromDefLike(defLike, target);
160
+ }
161
+ // Bare workflow name — read the latest cached bundle.
162
+ const cacheDir = resolveCacheDir(process.env, loadSettings(process.env).cacheDir);
163
+ const bundle = readLatestBundle(cacheDir, target);
164
+ if (bundle === null) {
165
+ throw new Error(`no cached bundle for '${target}' — run \`owenloop work prepare ${target}\` first`);
166
+ }
167
+ return bundle.def.steps;
168
+ }
169
+ /**
170
+ * Pull a loose `FetchedStep[]` out of a def-like object (only name + model +
171
+ * executor + the harness carrier are needed).
172
+ *
173
+ * The carrier is lifted by `parseHarnessCarrier`, the SAME function the def
174
+ * parser uses, so lint and prepare cannot disagree about what `x.harness` means.
175
+ * A malformed carrier throws there and surfaces as a load failure (exit 1),
176
+ * which is right: lint cannot check options it cannot parse.
177
+ */
178
+ function stepsFromDefLike(defLike, source) {
179
+ if (typeof defLike !== 'object' || defLike === null) {
180
+ throw new Error(`${source}: not a workflow def (expected an object with a steps list)`);
181
+ }
182
+ const rawSteps = defLike['steps'];
183
+ if (!Array.isArray(rawSteps)) {
184
+ throw new Error(`${source}: missing a steps list`);
185
+ }
186
+ return rawSteps.map((raw, i) => {
187
+ if (typeof raw !== 'object' || raw === null) {
188
+ throw new Error(`${source}: step[${i}] is not an object`);
189
+ }
190
+ const s = raw;
191
+ const name = typeof s['name'] === 'string' ? s['name'] : `step[${i}]`;
192
+ return {
193
+ name,
194
+ model: typeof s['model'] === 'string' ? s['model'] : undefined,
195
+ executor: typeof s['executor'] === 'string' ? s['executor'] : undefined,
196
+ ...parseHarnessCarrier(s, source, name),
197
+ x: (typeof s['x'] === 'object' && s['x'] !== null ? s['x'] : undefined),
198
+ };
199
+ });
200
+ }
@@ -0,0 +1 @@
1
+ export declare function run(args: string[]): Promise<number>;