owenloop 0.4.1 → 0.5.1

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 (282) hide show
  1. package/CHANGELOG.md +71 -0
  2. package/README.md +182 -53
  3. package/bin/owenloop.mjs +50 -2
  4. package/dist/packages/work/src/agent/brief.d.ts +176 -0
  5. package/dist/packages/work/src/agent/brief.js +197 -0
  6. package/dist/packages/work/src/agent/loop.d.ts +141 -0
  7. package/dist/packages/work/src/agent/loop.js +669 -0
  8. package/dist/packages/work/src/agent/model-policy.d.ts +49 -0
  9. package/dist/packages/work/src/agent/model-policy.js +138 -0
  10. package/dist/packages/work/src/agent/workdir.d.ts +210 -0
  11. package/dist/packages/work/src/agent/workdir.js +319 -0
  12. package/dist/packages/work/src/bundle/cache.d.ts +92 -0
  13. package/dist/packages/work/src/bundle/cache.js +338 -0
  14. package/dist/packages/work/src/bundle/fetch.d.ts +87 -0
  15. package/dist/packages/work/src/bundle/fetch.js +345 -0
  16. package/dist/packages/work/src/bundle/types.d.ts +164 -0
  17. package/dist/packages/work/src/bundle/types.js +1 -0
  18. package/dist/packages/work/src/consumed-verifier.d.ts +45 -0
  19. package/dist/packages/work/src/consumed-verifier.js +205 -0
  20. package/dist/packages/work/src/credentials/owenloop.d.ts +11 -0
  21. package/dist/packages/work/src/credentials/owenloop.js +28 -0
  22. package/dist/packages/work/src/credentials/reader.d.ts +36 -0
  23. package/dist/packages/work/src/credentials/reader.js +32 -0
  24. package/dist/packages/work/src/credentials/resolve.d.ts +19 -0
  25. package/dist/packages/work/src/credentials/resolve.js +56 -0
  26. package/dist/packages/work/src/exec/instructions.d.ts +99 -0
  27. package/dist/packages/work/src/exec/instructions.js +323 -0
  28. package/dist/packages/work/src/exec/loop.d.ts +40 -0
  29. package/dist/packages/work/src/exec/loop.js +332 -0
  30. package/dist/packages/work/src/exec/payload.d.ts +29 -0
  31. package/dist/packages/work/src/exec/payload.js +54 -0
  32. package/dist/packages/work/src/exec/receipt.d.ts +41 -0
  33. package/dist/packages/work/src/exec/receipt.js +32 -0
  34. package/dist/packages/work/src/exec/runner.d.ts +71 -0
  35. package/dist/packages/work/src/exec/runner.js +256 -0
  36. package/dist/packages/work/src/harness/child-env.d.ts +100 -0
  37. package/dist/packages/work/src/harness/child-env.js +134 -0
  38. package/dist/packages/work/src/harness/claude.d.ts +140 -0
  39. package/dist/packages/work/src/harness/claude.js +837 -0
  40. package/dist/packages/work/src/harness/codex.d.ts +111 -0
  41. package/dist/packages/work/src/harness/codex.js +1024 -0
  42. package/dist/packages/work/src/harness/contract.d.ts +308 -0
  43. package/dist/packages/work/src/harness/contract.js +32 -0
  44. package/dist/packages/work/src/harness/fake.d.ts +59 -0
  45. package/dist/packages/work/src/harness/fake.js +91 -0
  46. package/dist/packages/work/src/harness/jsonrpc-stdio.d.ts +108 -0
  47. package/dist/packages/work/src/harness/jsonrpc-stdio.js +351 -0
  48. package/dist/packages/work/src/harness/permissions.d.ts +75 -0
  49. package/dist/packages/work/src/harness/permissions.js +182 -0
  50. package/dist/packages/work/src/harness/registry.d.ts +47 -0
  51. package/dist/packages/work/src/harness/registry.js +45 -0
  52. package/dist/packages/work/src/harness/session-store.d.ts +181 -0
  53. package/dist/packages/work/src/harness/session-store.js +523 -0
  54. package/dist/packages/work/src/harness/types.d.ts +29 -0
  55. package/dist/packages/work/src/harness/types.js +14 -0
  56. package/dist/packages/work/src/harnesses.d.ts +38 -0
  57. package/dist/packages/work/src/harnesses.js +38 -0
  58. package/dist/packages/work/src/hold/loop.d.ts +36 -0
  59. package/dist/packages/work/src/hold/loop.js +23 -0
  60. package/dist/packages/work/src/hold/mcp.d.ts +75 -0
  61. package/dist/packages/work/src/hold/mcp.js +264 -0
  62. package/dist/packages/work/src/hub/client.d.ts +23 -0
  63. package/dist/packages/work/src/hub/client.js +91 -0
  64. package/dist/packages/work/src/hub/types.d.ts +326 -0
  65. package/dist/packages/work/src/hub/types.js +26 -0
  66. package/dist/packages/work/src/lease/loop.d.ts +94 -0
  67. package/dist/packages/work/src/lease/loop.js +277 -0
  68. package/dist/packages/work/src/main.d.ts +1 -0
  69. package/dist/packages/work/src/main.js +48 -0
  70. package/dist/packages/work/src/mcp/server.d.ts +125 -0
  71. package/dist/packages/work/src/mcp/server.js +320 -0
  72. package/dist/packages/work/src/owenloop-bin.d.ts +1 -0
  73. package/dist/packages/work/src/owenloop-bin.js +18 -0
  74. package/dist/packages/work/src/roles/agent-run.d.ts +124 -0
  75. package/dist/packages/work/src/roles/agent-run.js +529 -0
  76. package/dist/packages/work/src/roles/exec.d.ts +48 -0
  77. package/dist/packages/work/src/roles/exec.js +228 -0
  78. package/dist/packages/work/src/roles/hold.d.ts +72 -0
  79. package/dist/packages/work/src/roles/hold.js +363 -0
  80. package/dist/packages/work/src/roles/join.d.ts +18 -0
  81. package/dist/packages/work/src/roles/join.js +204 -0
  82. package/dist/packages/work/src/roles/lint.d.ts +58 -0
  83. package/dist/packages/work/src/roles/lint.js +234 -0
  84. package/dist/packages/work/src/roles/prepare.d.ts +1 -0
  85. package/dist/packages/work/src/roles/prepare.js +249 -0
  86. package/dist/packages/work/src/roles/release.d.ts +48 -0
  87. package/dist/packages/work/src/roles/release.js +137 -0
  88. package/dist/packages/work/src/roles/sessions.d.ts +61 -0
  89. package/dist/packages/work/src/roles/sessions.js +180 -0
  90. package/dist/packages/work/src/roles/settings.d.ts +6 -0
  91. package/dist/packages/work/src/roles/settings.js +71 -0
  92. package/dist/packages/work/src/roles/shift.d.ts +13 -0
  93. package/dist/packages/work/src/roles/shift.js +250 -0
  94. package/dist/packages/work/src/roles/signals.d.ts +55 -0
  95. package/dist/packages/work/src/roles/signals.js +62 -0
  96. package/dist/packages/work/src/settings/provision.d.ts +21 -0
  97. package/dist/packages/work/src/settings/provision.js +47 -0
  98. package/dist/packages/work/src/settings/settings.d.ts +136 -0
  99. package/dist/packages/work/src/settings/settings.js +155 -0
  100. package/dist/packages/work/src/shift/client.d.ts +24 -0
  101. package/dist/packages/work/src/shift/client.js +124 -0
  102. package/dist/packages/work/src/shift/loop.d.ts +131 -0
  103. package/dist/packages/work/src/shift/loop.js +751 -0
  104. package/dist/packages/work/src/shift/protocol.d.ts +95 -0
  105. package/dist/packages/work/src/shift/protocol.js +24 -0
  106. package/dist/packages/work/src/shift/routing.d.ts +35 -0
  107. package/dist/packages/work/src/shift/routing.js +50 -0
  108. package/dist/packages/work/src/shift/runtime.d.ts +45 -0
  109. package/dist/packages/work/src/shift/runtime.js +337 -0
  110. package/dist/packages/work/src/shift/server.d.ts +23 -0
  111. package/dist/packages/work/src/shift/server.js +716 -0
  112. package/dist/packages/work/src/shift/spawn.d.ts +109 -0
  113. package/dist/packages/work/src/shift/spawn.js +158 -0
  114. package/dist/packages/work/src/shift/state.d.ts +79 -0
  115. package/dist/packages/work/src/shift/state.js +385 -0
  116. package/dist/packages/work/src/submit-proof.d.ts +36 -0
  117. package/dist/packages/work/src/submit-proof.js +93 -0
  118. package/dist/packages/work/src/usage.d.ts +6 -0
  119. package/dist/packages/work/src/usage.js +175 -0
  120. package/dist/src/add.d.ts +189 -0
  121. package/dist/src/add.js +300 -0
  122. package/dist/src/archive.d.ts +97 -0
  123. package/dist/src/archive.js +591 -0
  124. package/dist/src/bundle/index.d.ts +64 -0
  125. package/dist/src/bundle/index.js +508 -0
  126. package/dist/src/bundle/manifest.d.ts +50 -0
  127. package/dist/src/bundle/manifest.js +435 -0
  128. package/dist/src/bundle/runtime.d.ts +26 -0
  129. package/dist/src/bundle/runtime.js +64 -0
  130. package/dist/src/bundle/tar.d.ts +62 -0
  131. package/dist/src/bundle/tar.js +238 -0
  132. package/dist/src/bundle/types.d.ts +105 -0
  133. package/dist/src/bundle/types.js +21 -0
  134. package/dist/{cli.d.ts → src/cli.d.ts} +92 -7
  135. package/dist/src/cli.js +5968 -0
  136. package/dist/{credentials.d.ts → src/credentials.d.ts} +22 -15
  137. package/dist/{credentials.js → src/credentials.js} +35 -31
  138. package/dist/src/crypto/allowed-signers.d.ts +68 -0
  139. package/dist/src/crypto/allowed-signers.js +307 -0
  140. package/dist/src/crypto/canonical.d.ts +8 -0
  141. package/dist/src/crypto/canonical.js +92 -0
  142. package/dist/src/crypto/chain.d.ts +65 -0
  143. package/dist/src/crypto/chain.js +377 -0
  144. package/dist/src/crypto/dsse.d.ts +209 -0
  145. package/dist/src/crypto/dsse.js +282 -0
  146. package/dist/src/crypto/enrollment.d.ts +78 -0
  147. package/dist/src/crypto/enrollment.js +186 -0
  148. package/dist/src/crypto/index.d.ts +48 -0
  149. package/dist/src/crypto/index.js +44 -0
  150. package/dist/src/crypto/keys.d.ts +258 -0
  151. package/dist/src/crypto/keys.js +908 -0
  152. package/dist/src/crypto/org-root.d.ts +33 -0
  153. package/dist/src/crypto/org-root.js +78 -0
  154. package/dist/src/crypto/origin-rules.d.ts +56 -0
  155. package/dist/src/crypto/origin-rules.js +143 -0
  156. package/dist/src/crypto/policy-floor.d.ts +98 -0
  157. package/dist/src/crypto/policy-floor.js +353 -0
  158. package/dist/src/crypto/records.d.ts +316 -0
  159. package/dist/src/crypto/records.js +157 -0
  160. package/dist/src/crypto/scope.d.ts +49 -0
  161. package/dist/src/crypto/scope.js +83 -0
  162. package/dist/src/crypto/ssh.d.ts +171 -0
  163. package/dist/src/crypto/ssh.js +396 -0
  164. package/dist/src/crypto/submission.d.ts +33 -0
  165. package/dist/src/crypto/submission.js +47 -0
  166. package/dist/src/crypto/trust-roots.d.ts +29 -0
  167. package/dist/src/crypto/trust-roots.js +39 -0
  168. package/dist/src/crypto/verify-consumed.d.ts +67 -0
  169. package/dist/src/crypto/verify-consumed.js +259 -0
  170. package/dist/src/crypto/verify-origin.d.ts +50 -0
  171. package/dist/src/crypto/verify-origin.js +151 -0
  172. package/dist/src/crypto/verify-publication.d.ts +60 -0
  173. package/dist/src/crypto/verify-publication.js +150 -0
  174. package/dist/{defs.d.ts → src/defs.d.ts} +24 -1
  175. package/dist/{defs.js → src/defs.js} +181 -61
  176. package/dist/{engine.d.ts → src/engine.d.ts} +105 -9
  177. package/dist/{engine.js → src/engine.js} +251 -47
  178. package/dist/{factory.d.ts → src/factory.d.ts} +16 -0
  179. package/dist/{factory.js → src/factory.js} +16 -4
  180. package/dist/src/global-config.d.ts +59 -0
  181. package/dist/src/global-config.js +84 -0
  182. package/dist/{hub.d.ts → src/hub.d.ts} +280 -31
  183. package/dist/{hub.js → src/hub.js} +493 -52
  184. package/dist/src/index.d.ts +47 -0
  185. package/dist/src/index.js +41 -0
  186. package/dist/src/install.d.ts +538 -0
  187. package/dist/src/install.js +1981 -0
  188. package/dist/src/lock.d.ts +38 -0
  189. package/dist/src/lock.js +325 -0
  190. package/dist/src/mcp/serve.d.ts +109 -0
  191. package/dist/{mcp → src/mcp}/serve.js +335 -75
  192. package/dist/{mcp → src/mcp}/server.d.ts +6 -9
  193. package/dist/{mcp → src/mcp}/server.js +18 -10
  194. package/dist/{model.d.ts → src/model.d.ts} +15 -0
  195. package/dist/{model.js → src/model.js} +112 -2
  196. package/dist/src/order-resolver.d.ts +184 -0
  197. package/dist/src/order-resolver.js +252 -0
  198. package/dist/src/package-version.d.ts +10 -0
  199. package/dist/src/package-version.js +42 -0
  200. package/dist/{paths.d.ts → src/paths.d.ts} +14 -1
  201. package/dist/{paths.js → src/paths.js} +18 -0
  202. package/dist/src/schemas/enrollment-grant.v1.schema.json +90 -0
  203. package/dist/src/schemas/index.d.ts +1416 -0
  204. package/dist/src/schemas/index.js +31 -0
  205. package/dist/src/schemas/order.v1.schema.json +106 -0
  206. package/dist/src/schemas/origin.v1.schema.json +68 -0
  207. package/dist/src/schemas/policy-floor.v1.schema.json +29 -0
  208. package/dist/src/schemas/publication.v1.schema.json +31 -0
  209. package/dist/src/schemas/revocation.v1.schema.json +39 -0
  210. package/dist/src/schemas/submission.v1.schema.json +61 -0
  211. package/dist/src/store/def-source.d.ts +52 -0
  212. package/dist/src/store/def-source.js +335 -0
  213. package/dist/src/store/index-file.d.ts +69 -0
  214. package/dist/src/store/index-file.js +151 -0
  215. package/dist/src/store/index.d.ts +27 -0
  216. package/dist/src/store/index.js +22 -0
  217. package/dist/src/store/ingestor.d.ts +43 -0
  218. package/dist/src/store/ingestor.js +211 -0
  219. package/dist/src/store/install.d.ts +228 -0
  220. package/dist/src/store/install.js +555 -0
  221. package/dist/src/store/instruction-source.d.ts +49 -0
  222. package/dist/src/store/instruction-source.js +298 -0
  223. package/dist/src/store/origin-evidence.d.ts +21 -0
  224. package/dist/src/store/origin-evidence.js +66 -0
  225. package/dist/src/store/pre-commit-verifier.d.ts +68 -0
  226. package/dist/src/store/pre-commit-verifier.js +418 -0
  227. package/dist/src/store/resolve.d.ts +138 -0
  228. package/dist/src/store/resolve.js +363 -0
  229. package/dist/src/store/types.d.ts +288 -0
  230. package/dist/src/store/types.js +356 -0
  231. package/dist/{types.d.ts → src/types.d.ts} +58 -24
  232. package/dist/{untar.d.ts → src/untar.d.ts} +8 -23
  233. package/dist/src/untar.js +38 -0
  234. package/dist/{util.d.ts → src/util.d.ts} +3 -2
  235. package/dist/{util.js → src/util.js} +3 -2
  236. package/dist/{owenwork.d.ts → src/work-settings.d.ts} +22 -22
  237. package/dist/{owenwork.js → src/work-settings.js} +27 -27
  238. package/docs/agent-runner.md +86 -0
  239. package/docs/authoring.md +150 -59
  240. package/docs/bundles.md +250 -0
  241. package/docs/cli.md +1758 -163
  242. package/docs/crypto.md +816 -0
  243. package/docs/design.md +374 -52
  244. package/docs/embedding.md +135 -27
  245. package/docs/wire-contracts.md +380 -0
  246. package/examples/workflows/{command-worker.yaml → command-executor.yaml} +15 -15
  247. package/examples/workflows/compile-dev-playbook.yaml +338 -0
  248. package/examples/workflows/judges/gate-sharpness.md +39 -0
  249. package/examples/workflows/judges/security.md +34 -0
  250. package/package.json +22 -8
  251. package/plugins/claude-code/.claude-plugin/marketplace.json +14 -0
  252. package/plugins/claude-code/plugin/.claude-plugin/plugin.json +8 -0
  253. package/plugins/claude-code/plugin/.mcp.json +14 -0
  254. package/plugins/claude-code/plugin/hooks/hooks.json +26 -0
  255. package/plugins/claude-code/plugin/hooks/session-end.sh +40 -0
  256. package/plugins/claude-code/plugin/hooks/session-start.sh +52 -0
  257. package/plugins/claude-code/plugin/skills/author/SKILL.md +181 -0
  258. package/plugins/claude-code/plugin/skills/conduct/SKILL.md +106 -0
  259. package/plugins/claude-code/plugin/skills/shift/SKILL.md +105 -0
  260. package/plugins/codex/.agents/plugins/marketplace.json +21 -0
  261. package/plugins/codex/plugins/owenloop/.codex-plugin/plugin.json +7 -0
  262. package/plugins/codex/plugins/owenloop/.mcp.json +20 -0
  263. package/plugins/codex/plugins/owenloop/hooks/hooks.json +26 -0
  264. package/plugins/codex/plugins/owenloop/hooks/session-end.sh +40 -0
  265. package/plugins/codex/plugins/owenloop/hooks/session-start.sh +52 -0
  266. package/plugins/codex/plugins/owenloop/skills/author/SKILL.md +181 -0
  267. package/plugins/codex/plugins/owenloop/skills/conduct/SKILL.md +106 -0
  268. package/plugins/codex/plugins/owenloop/skills/shift/SKILL.md +105 -0
  269. package/dist/add.d.ts +0 -384
  270. package/dist/add.js +0 -834
  271. package/dist/cli.js +0 -3270
  272. package/dist/index.d.ts +0 -32
  273. package/dist/index.js +0 -23
  274. package/dist/lock.d.ts +0 -80
  275. package/dist/lock.js +0 -217
  276. package/dist/mcp/serve.d.ts +0 -84
  277. package/dist/untar.js +0 -164
  278. /package/dist/{schema.d.ts → src/schema.d.ts} +0 -0
  279. /package/dist/{schema.js → src/schema.js} +0 -0
  280. /package/dist/{store.d.ts → src/store.d.ts} +0 -0
  281. /package/dist/{store.js → src/store.js} +0 -0
  282. /package/dist/{types.js → src/types.js} +0 -0
package/dist/cli.js DELETED
@@ -1,3270 +0,0 @@
1
- /**
2
- * The owenloop CLI — a thin, scriptable surface over the engine.
3
- *
4
- * Every data command prints JSON to stdout, so a *wiring* (the worker/automation
5
- * that actually runs orders) can drive the engine programmatically: `tick` to
6
- * pull orders, run them, then `green` / `emit` / `seal` / `reject` / `close` to
7
- * report outcomes. The engine itself is domain-neutral; this binary just maps
8
- * argv to engine calls.
9
- *
10
- * owenloop defs list available workflow definitions
11
- * owenloop add <owner>/<repo>[@ref] fetch, validate, and install a repo's workflow defs (public repos)
12
- * owenloop create <def> [--provide n=json] [--title t] start an instance
13
- * owenloop provide <wf> <name> [--value json] supply an owed input
14
- * owenloop tick <wf> [--now ms] pull eligible orders
15
- * owenloop reap <wf> [--now] run the reaper; --now forces every claim stale (TTL 0)
16
- * owenloop runs <wf> [--open] list this instance's runs (+ claim state for open ones)
17
- * owenloop status <wf> derive debts / eligible / blocked
18
- * owenloop status --all every instance's status in one call (fleet read)
19
- * owenloop wait <wf> --until eligible|done [--timeout <dur>] block until engine state matches
20
- * owenloop show <wf> dump raw artifacts (debugging)
21
- * owenloop list list instances
22
- * owenloop green <wf> <run> <path> [--value json] [--terminal]
23
- * owenloop emit <wf> <run> --items '[{...},{...}]'
24
- * owenloop seal <wf> <run> [--value json]
25
- * owenloop reject <wf> <path> --by <author> --text <msg>
26
- * owenloop retract <wf> <path> --by <author> --text <msg>
27
- * owenloop skip <wf> <path> --by <author> --text <msg>
28
- * owenloop retry <wf> <path> [--by <author>] [--text <guidance>] clear a stall
29
- * owenloop close <wf> <run> [--outcome ok|no_work|failed|skipped] [--summary s]
30
- * owenloop delete <wf> [--recursive]
31
- *
32
- * Global: --db <path> (env OWENLOOP_DB), --defs <dir> (env OWENLOOP_DEFS).
33
- */
34
- import { existsSync, mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';
35
- import { basename, delimiter, dirname, join, resolve } from 'node:path';
36
- import { spawn, spawnSync } from 'node:child_process';
37
- import { createServer } from 'node:http';
38
- import { createInterface } from 'node:readline/promises';
39
- import { hostname } from 'node:os';
40
- import { parse as parseYaml } from 'yaml';
41
- import { Engine } from "./engine.js";
42
- import { buildGraph, buildTrace, graphToDot, graphToMermaid, modelCheck } from "./model.js";
43
- import { openStore } from "./store.js";
44
- import { buildDef, DefError, finalizeDefs, lintDef, loadDefs, loadDefsRaw, loadDefsUnfinalized, validateDef, } from "./defs.js";
45
- import { CliError, dbPathRefusingSymlink, detId, mkdirRefusingSymlink, nowMs, parseDurationMs, randId } from "./util.js";
46
- import { authHeader, deleteCredential, discoverMetadata, ensureFreshOAuth, hubFetch, hubMaxResponseBytes, mintAgentCredential, readBodyBounded, refreshOAuth, rekeyAgentCredential, storeCredential, } from "./credentials.js";
47
- import { runMcpCommand } from "./mcp/serve.js";
48
- import { DEFAULT_TAR_LIMITS, extractTarGz } from "./untar.js";
49
- import { acquireInstallLock, ADD_JOURNAL_FILENAME, archivePathViolation, commitInstall, finalizeInstallCommit, githubShaUrl, githubTarballUrl, installFolder, parkOldNameDir, parseRepoSpec, readLockfile, recoverInterruptedInstall, releaseInstallLock, removeAddJournal, rollbackInstallCommit, RollbackFailedError, stageFiles, STAGING_DIRNAME, writeAddJournal, writeLockfile, } from "./add.js";
50
- import { asAgentIdentities, asCreateWorkflowOk, asWhoami, computeServerDiff, credentialBackend, createWorkflowError, credentialFilePath, credentialSlot, externalCredentialCommand, hashDefForHub, hubBindingPath, keychainServiceFor, listStoredHubOrigins, normalizeOrigin, parseWorkflowList, pkcePair, randomState, readCredentialFile, readHubBinding, readStoredCredential, resolveEndpoint, resolveKeychain, writeCredentialFile, writeHubBinding, } from "./hub.js";
51
- import { owenworkSettingsPath, readOwenworkSettingsRaw, writeOwenworkHubOrigin } from "./owenwork.js";
52
- function defaultIO() {
53
- return {
54
- cwd: process.cwd(),
55
- env: process.env,
56
- out: (s) => process.stdout.write(`${s}\n`),
57
- err: (s) => process.stderr.write(`${s}\n`),
58
- fetch: globalThis.fetch,
59
- openUrl: defaultOpenUrl,
60
- readStdin: defaultReadStdin,
61
- prompt: defaultPrompt,
62
- runCommand: defaultRunCommand,
63
- };
64
- }
65
- /**
66
- * The default interactive prompt: a one-shot `node:readline/promises` question
67
- * whose text and echo go to STDERR (so stdout remains the parseable JSON
68
- * document). Closed immediately after the single read.
69
- */
70
- async function defaultPrompt(question) {
71
- const rl = createInterface({ input: process.stdin, output: process.stderr });
72
- try {
73
- return await rl.question(question);
74
- }
75
- finally {
76
- rl.close();
77
- }
78
- }
79
- /**
80
- * The default local-command runner: `spawnSync` with `shell: false` (argv is
81
- * passed as a vector, never interpolated into a shell) and captured, not
82
- * inherited, stdio. Only the plugin probe uses it.
83
- */
84
- function defaultRunCommand(cmd, args) {
85
- const r = spawnSync(cmd, args, { encoding: 'utf8' });
86
- return { status: r.status, stdout: r.stdout ?? '', stderr: r.stderr ?? '' };
87
- }
88
- /** Fire-and-forget browser open — never blocks the login flow on the child. */
89
- function defaultOpenUrl(url) {
90
- const platform = process.platform;
91
- const cmd = platform === 'darwin' ? 'open' : platform === 'win32' ? 'start' : 'xdg-open';
92
- try {
93
- spawn(cmd, [url], { stdio: 'ignore', detached: true }).unref();
94
- }
95
- catch {
96
- // Non-fatal: the URL is also printed to stderr for the user to open manually.
97
- }
98
- }
99
- async function defaultReadStdin() {
100
- const chunks = [];
101
- for await (const chunk of process.stdin)
102
- chunks.push(chunk);
103
- return Buffer.concat(chunks).toString('utf8');
104
- }
105
- /**
106
- * Flags that are always boolean and must never consume the following token as
107
- * a value — `owenloop push --force foo` must force-push only `foo`, not treat
108
- * `foo` as `--force`'s value and swallow it from the positionals. Audited
109
- * against every `flag(args, ...)` call site in this file. `now` is dual-mode:
110
- * a bare boolean for `reap`, but `tick` reads it as `--now=<ms>` (the `=` form
111
- * bypasses this set entirely, handled by the `eq >= 0` branch below); the
112
- * space-separated `--now 123` form intentionally no longer binds `123` as
113
- * `now`'s value — docs/cli.md documents only `--now=<ms>`.
114
- */
115
- const BOOLEAN_FLAGS = new Set([
116
- 'assume-provided',
117
- 'strict-inputs',
118
- 'shallow',
119
- 'now',
120
- 'all',
121
- 'open',
122
- 'terminal',
123
- 'recursive',
124
- 'with-token',
125
- 'dry-run',
126
- 'force',
127
- // `add --recover` takes NO value: `add --recover acme/widgets` must keep
128
- // `acme/widgets` as a positional so the recover branch can refuse it, rather
129
- // than binding it as `--recover`'s value and silently dropping it.
130
- 'recover',
131
- ]);
132
- function parseArgs(argv) {
133
- const positionals = [];
134
- const options = new Map();
135
- for (let i = 0; i < argv.length; i++) {
136
- const a = argv[i];
137
- if (a.startsWith('--')) {
138
- let key = a.slice(2);
139
- let val;
140
- const eq = key.indexOf('=');
141
- if (eq >= 0) {
142
- val = key.slice(eq + 1);
143
- key = key.slice(0, eq);
144
- }
145
- else if (BOOLEAN_FLAGS.has(key)) {
146
- val = 'true'; // never consume the next token for a known-boolean flag
147
- }
148
- else if (i + 1 < argv.length && !argv[i + 1].startsWith('--')) {
149
- val = argv[++i];
150
- }
151
- else {
152
- val = 'true'; // boolean flag
153
- }
154
- const arr = options.get(key) ?? [];
155
- arr.push(val);
156
- options.set(key, arr);
157
- }
158
- else {
159
- positionals.push(a);
160
- }
161
- }
162
- return { positionals, options };
163
- }
164
- const last = (args, key) => {
165
- const arr = args.options.get(key);
166
- return arr ? arr[arr.length - 1] : undefined;
167
- };
168
- const all = (args, key) => args.options.get(key) ?? [];
169
- const flag = (args, key) => {
170
- const v = last(args, key);
171
- return v === 'true' || v === '' || (v !== undefined && v !== 'false');
172
- };
173
- /**
174
- * A 429 from the hub during a push batch (REL-10). Thrown from the batch loop
175
- * and handled by an explicit `instanceof` branch that halts the rest of the
176
- * batch and surfaces `Retry-After` — NOT folded into the generic per-def
177
- * failure path or matched by message regex. Keeping it a distinct class is the
178
- * fix for the shared-catch gotcha (knowledge node "CLI: split a shared
179
- * switch-case when one verb's return type changes"): branch on the type, never
180
- * on the message text.
181
- */
182
- class RateLimitError extends CliError {
183
- }
184
- function need(args, idx, label) {
185
- const v = args.positionals[idx];
186
- if (v === undefined)
187
- throw new CliError(`missing required argument: ${label}`);
188
- return v;
189
- }
190
- function needOpt(args, key) {
191
- const v = last(args, key);
192
- if (v === undefined)
193
- throw new CliError(`missing required option: --${key}`);
194
- return v;
195
- }
196
- /** Read an optional numeric flag; throw a CliError (never NaN) on a non-finite value. */
197
- function numOpt(args, key) {
198
- const raw = last(args, key);
199
- if (raw === undefined)
200
- return undefined;
201
- const n = Number(raw);
202
- if (!Number.isFinite(n)) {
203
- throw new CliError(`invalid value for --${key}: expected --${key}=<number> (got "${raw}")`);
204
- }
205
- return n;
206
- }
207
- function parseJson(s, fallback = {}) {
208
- if (s === undefined)
209
- return fallback;
210
- let v;
211
- try {
212
- v = JSON.parse(s);
213
- }
214
- catch {
215
- throw new CliError(`invalid JSON: ${s}`);
216
- }
217
- if (typeof v !== 'object' || v === null || Array.isArray(v)) {
218
- throw new CliError(`expected a JSON object, got: ${s}`);
219
- }
220
- return v;
221
- }
222
- /** Parse repeated `name=jsonvalue` pairs (for --provide / --param). */
223
- function parsePairs(entries, jsonValue) {
224
- const out = {};
225
- for (const e of entries) {
226
- const eq = e.indexOf('=');
227
- if (eq < 0)
228
- throw new CliError(`expected name=value, got: ${e}`);
229
- const name = e.slice(0, eq);
230
- const raw = e.slice(eq + 1);
231
- if (jsonValue) {
232
- try {
233
- out[name] = JSON.parse(raw);
234
- }
235
- catch {
236
- throw new CliError(`invalid JSON for '${name}': ${raw}`);
237
- }
238
- }
239
- else {
240
- out[name] = raw;
241
- }
242
- }
243
- return out;
244
- }
245
- /**
246
- * Load the DEFAULT def set, folding in the defs `owenloop add` installed under
247
- * ledger-recorded subfolders of `defsDir` so `defs`/`create`/`tick`/etc. see
248
- * them by name with NO `--defs` flag. Called ONLY when the operator did not
249
- * override the defs dir (see {@link openCtx}) — an explicit `--defs`/`OWENLOOP_DEFS`
250
- * targets a specific literal dir and keeps today's pure-scan behavior, including
251
- * `--defs workflows/<owner>-<repo>-<hash>` pointed straight at an install folder.
252
- *
253
- * The composition is ledger-DRIVEN and BOUNDED: it only folds in folders named
254
- * by fail-closed-validated `installed.json` entries (never a raw tree recurse),
255
- * and it stays in the CLI layer (where both cwd and defsDir are known) so
256
- * `loadDefs`/`loadDefsUnfinalized` in defs.ts hold no ledger knowledge.
257
- *
258
- * Two-phase discipline: it merges the RAW (unfinalized) maps of the base dir and
259
- * each install folder, then runs ONE `finalizeDefs` over the union. That single
260
- * finalize is what lets a project-local def `calls:` an installed def across the
261
- * boundary — finalizing each dir independently would throw "does not exist"
262
- * before the merge. When the ledger is empty/missing the result is exactly
263
- * `finalizeDefs(loadDefsUnfinalized(defsDir))` === today's `loadDefs(defsDir)`:
264
- * zero behavior drift on the no-installs path.
265
- *
266
- * Precedence: project-local (base) defs WIN over installed defs; among installed
267
- * entries, ledger sources are iterated in sorted order and the FIRST-loaded def
268
- * with a given name wins. Every shadowed def is surfaced as a warning on stderr,
269
- * never a silent clobber. Note the outer base scan ALREADY loads an install
270
- * folder's `workflow.yaml` via its immediate-subdir rule, while the fold-in
271
- * loads that folder's top-level `*.yaml` (excluding `workflow.yaml`) — the two
272
- * scans are disjoint per file, so no file is ever loaded twice and any name
273
- * collision is a genuine two-file collision.
274
- *
275
- * Fail-OPEN: the fold-in never breaks base loading. A corrupt/invalid ledger, a
276
- * missing install folder, or an install folder that fails to load each emits a
277
- * warning on stderr and is skipped; base defs still load. (The add-time
278
- * fail-closed validation in add.ts is untouched — we consume `readLockfile`,
279
- * discovery merely refuses to act on a bad ledger rather than crashing.)
280
- */
281
- function loadDefsWithInstalled(io, defsDir) {
282
- const merged = existsSync(defsDir) ? loadDefsUnfinalized(defsDir) : new Map();
283
- let lf;
284
- try {
285
- lf = readLockfile(join(io.cwd, '.owenloop', 'installed.json'));
286
- }
287
- catch (e) {
288
- io.err(`warning: skipping installed workflow defs: ${e.message}`);
289
- return finalizeDefs(merged);
290
- }
291
- for (const source of Object.keys(lf.installed).sort()) {
292
- const entry = lf.installed[source];
293
- if (entry === undefined)
294
- continue; // unreachable — keys come from lf.installed
295
- const entryDir = join(defsDir, entry.path);
296
- if (!existsSync(entryDir)) {
297
- io.err(`warning: installed defs folder missing for ${source}: ${entry.path}`);
298
- continue;
299
- }
300
- let entryRaw;
301
- try {
302
- entryRaw = loadDefsUnfinalized(entryDir);
303
- }
304
- catch (e) {
305
- io.err(`warning: failed to load installed defs for ${source} (${entry.path}): ${e.message}`);
306
- continue;
307
- }
308
- for (const [name, def] of entryRaw) {
309
- const winner = merged.get(name);
310
- if (winner !== undefined) {
311
- io.err(`warning: workflow '${name}' from ${def.dir ?? entryDir} is shadowed by ${winner.dir ?? 'project defs'} (project defs take precedence over installed defs)`);
312
- continue;
313
- }
314
- merged.set(name, def);
315
- }
316
- }
317
- return finalizeDefs(merged);
318
- }
319
- function openCtx(io, args) {
320
- const dbOverride = last(args, 'db') ?? io.env.OWENLOOP_DB;
321
- const dbPath = dbOverride ?? join(io.cwd, '.owenloop', 'state.db');
322
- // An explicit `--defs`/`OWENLOOP_DEFS` is the operator targeting a literal dir
323
- // (keep pure-scan behavior, no ledger fold-in); its ABSENCE means the default
324
- // dir, where `add` installs and the ledger's folders live — fold installed
325
- // defs in there. The rule is "was an override given", not path equality: even
326
- // `OWENLOOP_DEFS=<cwd>/workflows` counts as an override and stays literal.
327
- const defsOverride = last(args, 'defs') ?? io.env.OWENLOOP_DEFS;
328
- const defsDir = defsOverride ?? join(io.cwd, 'workflows');
329
- // Guard the built-in default (`cwd/.owenloop/state.db`) against a symlinked
330
- // `.owenloop` from a hostile checkout (SEC-3). Directory guard first, then the
331
- // file-level guard on `state.db` and its SQLite sidecars — a symlinked db file
332
- // inside a REAL `.owenloop` would otherwise redirect writes SQLite follows. An
333
- // explicit `--db`/`OWENLOOP_DB` comes from the operator, not the repo —
334
- // deliberately pointing state through a symlink is intent, so keep today's
335
- // behavior for overrides.
336
- if (dbOverride === undefined) {
337
- mkdirRefusingSymlink(dirname(dbPath));
338
- dbPathRefusingSymlink(dbPath);
339
- }
340
- else
341
- mkdirSync(dirname(dbPath), { recursive: true });
342
- const store = openStore(dbPath);
343
- const defs = defsOverride !== undefined
344
- ? existsSync(defsDir)
345
- ? loadDefs(defsDir)
346
- : new Map()
347
- : loadDefsWithInstalled(io, defsDir);
348
- const engine = new Engine(store, (name) => {
349
- const d = defs.get(name);
350
- if (!d)
351
- throw new CliError(`unknown workflow definition '${name}' (looked in ${defsDir})`);
352
- return d;
353
- });
354
- return { store, engine, defs, defsDir, dbPath };
355
- }
356
- function print(io, value) {
357
- io.out(JSON.stringify(value, null, 2));
358
- }
359
- /**
360
- * Synchronous blocking sleep. The whole codebase is sync end to end (no
361
- * async/Promise/setTimeout anywhere in src/*.ts), so `wait` needs a sync
362
- * sleep rather than turning `main`/`dispatch` async. `Atomics.wait` on a
363
- * value that never changes (compare 0 against 0) blocks for the full `ms`
364
- * every time — exactly the "just sleep" behavior wanted here.
365
- */
366
- function sleepMs(ms) {
367
- Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
368
- }
369
- // ---- commands ----------------------------------------------------------------
370
- export const USAGE = `owenloop — a dataflow workflow engine
371
-
372
- Usage: owenloop <command> [args] [--db <path>] [--defs <dir>]
373
-
374
- Commands:
375
- defs list available workflow definitions
376
- add <owner>/<repo>[@ref] fetch, validate, and install a repo's workflow defs (public repos)
377
- add --recover finish or undo a crash-interrupted install (offline; no network)
378
- login [--hub <url>] [--with-token] [--as <slot>] authenticate the CLI against a hub, verified via whoami (loopback OAuth, or --with-token from stdin)
379
- logout [--hub <url>] [--as <slot>] delete the stored credential for a hub in one slot
380
- connect [--hub <url>] [--as <slot>] bind this project to a hub and verify the stored credential (whoami)
381
- push [<defName>...] [--force] [--dry-run] [--as <slot>] publish local workflow defs to the bound hub (server-diffed, idempotent)
382
- --as names the credential slot: human (default), agent, or agent:<account>
383
- agent new <name> [--pools <a,b>] [--hub <url>] mint a new agent identity on the hub and store its token in slot agent:<name> (the token is never printed)
384
- setup [--hub <url>] [--new-agent <name> | --replace-agent <name>] [--pools <a,b>] converge this machine's install: human login, agent credential, owenwork settings, plugin (idempotent)
385
- doctor [--hub <url>] check this machine's owenloop install and report each piece (read-only)
386
- mcp [--hub <url>] serve the hub control plane over stdio MCP (spawned by MCP hosts, not run by humans)
387
- lint [<def-name>] check def(s) for wiring problems
388
- check <def> [--format text|json] [--max-depth N] [--max-states N] [--max-collection N] [--assume-provided] [--strict-inputs]
389
- bounded reachability check (stall states, true deadlocks, stuck, dead steps, declared invariants)
390
- create <def> [--title t] [--provide name=json ...] [--param k=v ...]
391
- provide <wf> <name> [--value json] supply an owed (seedOwed) input
392
- adopt <wf> re-pin an instance to the current def (§28); settles new debts
393
- tick <wf> [--now <ms>] [--shallow] [--label <l>]... pull eligible orders (deep: also from calls: children; --shallow for this instance only; --label filters to matching-label steps)
394
- reap <wf> [--now] run the reaper; --now forces every claim stale (TTL 0)
395
- runs <wf> [--open] list this instance's runs (+ claim state for open ones)
396
- order <wf> <run> print the order packet issued at claim time (persisted in the claim txn)
397
- status <wf> derive debts / eligible / blocked
398
- status --all every instance's status in one call (fleet read)
399
- wait <wf> --until eligible|done [--timeout <dur>] block until engine state matches
400
- show <wf> dump raw artifacts
401
- trace <wf> [--format text] causal timeline + artifact biographies
402
- graph <def-or-wf> [--format dot|mermaid|json] wiring graph (+ live overlay if wf id)
403
- list list workflow instances
404
- green <wf> <run> <path> [--value json] [--terminal]
405
- emit <wf> <run> --items '[{...}]' accrete collection elements
406
- seal <wf> <run> [--value json] signal a collection is complete
407
- reject <wf> <path> --by <author> --text <msg>
408
- retract <wf> <path> --by <author> --text <msg>
409
- skip <wf> <path> --by <author> --text <msg>
410
- retry <wf> <path> [--by <author>] [--text <guidance>] clear a §6 stall
411
- heartbeat <wf> <run> [--now <ms>] touch liveness timestamp on an open run
412
- close <wf> <run> [--outcome ok|no_work|failed|skipped] [--summary s]
413
- delete <wf> [--recursive] refuse if children exist unless --recursive (cascades)
414
-
415
- Environment: OWENLOOP_DB, OWENLOOP_DEFS`;
416
- /** Append parse failures to a "definition not found" error — the def the user asked for may be in one of the broken files. */
417
- function failureNote(failures) {
418
- if (failures.length === 0)
419
- return '';
420
- return `\n${failures.length} file(s) failed to load:\n - ${failures.map((f) => `${f.file}: ${f.error}`).join('\n - ')}`;
421
- }
422
- /**
423
- * Options accepted on EVERY command. docs/cli.md documents `--db`/`--defs` as
424
- * global ("pass both on every command"), so they are allowlisted everywhere —
425
- * even on commands that ignore them — to avoid rejecting a documented
426
- * invocation.
427
- */
428
- const GLOBAL_OPTIONS = ['db', 'defs'];
429
- /** Build a command's option allowlist: the two globals plus its own long-form flags. */
430
- const cmdOpts = (...extra) => new Set([...GLOBAL_OPTIONS, ...extra]);
431
- /**
432
- * Single source of truth for the `--options` each command accepts, consulted by
433
- * `preflight` before any side effect. Unknown-OPTION rejection AND
434
- * unknown-COMMAND detection both derive from this table: a developer who adds a
435
- * new `dispatch`/`ASYNC_COMMANDS` case without a matching entry here gets
436
- * `unknown command` on the very first invocation, so the command cannot run
437
- * until its flags are declared. That is the forcing function that stops the
438
- * silently-dropped-flag hole (a misspelled `push --dryrn` doing a real push)
439
- * from reappearing — keep this table in lockstep with the dispatch verbs and
440
- * the USAGE string. All names are long-form: this CLI has no short options
441
- * (`-h` reaches dispatch as a positional). Values are audited against every
442
- * `last/all/flag/needOpt/numOpt` call site.
443
- */
444
- export const COMMAND_OPTIONS = new Map([
445
- ['help', cmdOpts()],
446
- ['defs', cmdOpts()],
447
- ['add', cmdOpts('recover')],
448
- ['login', cmdOpts('hub', 'with-token', 'as')],
449
- ['logout', cmdOpts('hub', 'as')],
450
- ['connect', cmdOpts('hub', 'as')],
451
- ['push', cmdOpts('dry-run', 'force', 'hub', 'as')],
452
- ['agent', cmdOpts('pools', 'hub')],
453
- ['setup', cmdOpts('hub', 'new-agent', 'replace-agent', 'pools')],
454
- ['doctor', cmdOpts('hub')],
455
- ['mcp', cmdOpts('hub')],
456
- ['lint', cmdOpts()],
457
- ['check', cmdOpts('format', 'max-depth', 'max-states', 'max-collection', 'assume-provided', 'strict-inputs')],
458
- ['create', cmdOpts('title', 'provide', 'param')],
459
- ['provide', cmdOpts('value')],
460
- ['adopt', cmdOpts()],
461
- ['tick', cmdOpts('now', 'shallow', 'label')],
462
- ['reap', cmdOpts('now')],
463
- ['status', cmdOpts('all')],
464
- ['wait', cmdOpts('until', 'timeout')],
465
- ['show', cmdOpts()],
466
- ['trace', cmdOpts('format')],
467
- ['runs', cmdOpts('open')],
468
- ['order', cmdOpts()],
469
- ['list', cmdOpts()],
470
- ['green', cmdOpts('value', 'terminal')],
471
- ['emit', cmdOpts('items')],
472
- ['seal', cmdOpts('value')],
473
- ['reject', cmdOpts('by', 'text')],
474
- ['retract', cmdOpts('by', 'text')],
475
- ['skip', cmdOpts('by', 'text')],
476
- ['retry', cmdOpts('by', 'text')],
477
- ['close', cmdOpts('outcome', 'summary')],
478
- ['heartbeat', cmdOpts('now')],
479
- ['delete', cmdOpts('recursive')],
480
- ['graph', cmdOpts('format')],
481
- ]);
482
- /** Levenshtein edit distance (small DP, no deps) — used only for "did you mean" hints. */
483
- function editDistance(a, b) {
484
- const m = a.length;
485
- const n = b.length;
486
- let prev = new Array(n + 1);
487
- let curr = new Array(n + 1);
488
- for (let j = 0; j <= n; j++)
489
- prev[j] = j;
490
- for (let i = 1; i <= m; i++) {
491
- curr[0] = i;
492
- for (let j = 1; j <= n; j++) {
493
- const cost = a[i - 1] === b[j - 1] ? 0 : 1;
494
- const del = prev[j] + 1;
495
- const ins = curr[j - 1] + 1;
496
- const sub = prev[j - 1] + cost;
497
- curr[j] = Math.min(del, ins, sub);
498
- }
499
- [prev, curr] = [curr, prev];
500
- }
501
- return prev[n];
502
- }
503
- /**
504
- * Reject any `--option` the target command does not declare in
505
- * `COMMAND_OPTIONS`. Names each offender with its `--` prefix, suggests the
506
- * nearest valid option (edit distance ≤ 2), and lists the command's valid
507
- * options. Throws `CliError` (exit 1 via the entry-point catch). Runs BEFORE
508
- * any side effect — see `preflight`.
509
- */
510
- function assertKnownOptions(command, args) {
511
- const allowed = COMMAND_OPTIONS.get(command);
512
- if (!allowed)
513
- return; // unknown command is handled separately (in preflight)
514
- const unknown = [...args.options.keys()].filter((k) => !allowed.has(k));
515
- if (unknown.length === 0)
516
- return;
517
- const lines = unknown.map((k) => {
518
- const base = `unknown option --${k} for '${command}'`;
519
- const near = k.length > 0
520
- ? [...allowed]
521
- .map((o) => ({ o, d: editDistance(k, o) }))
522
- .filter((c) => c.d <= 2)
523
- .sort((a, b) => a.d - b.d)[0]
524
- : undefined;
525
- return near ? `${base} (did you mean --${near.o}?)` : base;
526
- });
527
- const validSorted = [...allowed].map((o) => `--${o}`).sort();
528
- throw new CliError(`${lines.join('\n')}\nvalid options for '${command}': ${validSorted.join(', ')}`);
529
- }
530
- /**
531
- * Pre-dispatch guard shared by both entry points (`main` and `mainAsync`) so
532
- * the sync and async paths cannot drift. In order: the help escape hatch
533
- * (`help`/`--help`/`-h`, or `--help` given anywhere e.g. `push --help`) prints
534
- * usage and short-circuits with exit 0; an unrecognized command throws the same
535
- * `unknown command` error dispatch's `default:` produces (but now before
536
- * `openCtx`, so it no longer creates `.owenloop/state.db`); then unknown
537
- * options are rejected. All of this runs ahead of any filesystem, keychain, or
538
- * network I/O. Returns an exit code to short-circuit on, or `undefined` to
539
- * proceed to dispatch. `command` is always defined here — callers own the
540
- * no-command usage branch.
541
- */
542
- function preflight(command, args, io) {
543
- if (command === 'help' || command === '--help' || command === '-h' || args.options.has('help')) {
544
- io.out(USAGE);
545
- return 0;
546
- }
547
- if (!COMMAND_OPTIONS.has(command)) {
548
- throw new CliError(`unknown command: ${command}\n\n${USAGE}`);
549
- }
550
- assertKnownOptions(command, args);
551
- return undefined;
552
- }
553
- function dispatch(command, io, args) {
554
- // help and lint need no store
555
- if (command === 'help' || command === '--help' || command === '-h') {
556
- io.out(USAGE);
557
- return 0;
558
- }
559
- if (command === 'lint') {
560
- const defsDir = last(args, 'defs') ?? io.env.OWENLOOP_DEFS ?? join(io.cwd, 'workflows');
561
- const failures = [];
562
- const defs = existsSync(defsDir) ? loadDefsRaw(defsDir, failures) : new Map();
563
- const defName = args.positionals[1];
564
- let hasErrors = false;
565
- if (defName !== undefined) {
566
- const def = defs.get(defName);
567
- if (!def)
568
- throw new CliError(`unknown workflow definition '${defName}' (looked in ${defsDir})${failureNote(failures)}`);
569
- const result = lintDef(def);
570
- if (result.errors.length)
571
- hasErrors = true;
572
- print(io, { def: def.name, errors: result.errors, warnings: result.warnings });
573
- }
574
- else {
575
- const results = [...defs.values()].map((def) => {
576
- const result = lintDef(def);
577
- if (result.errors.length)
578
- hasErrors = true;
579
- return { def: def.name, errors: result.errors, warnings: result.warnings };
580
- });
581
- // Files that never became defs (malformed YAML / bad shape) are lint errors
582
- // too — omitting them makes `lint` claim a dir is clean when `create` would die.
583
- for (const f of failures) {
584
- hasErrors = true;
585
- results.push({ file: f.file, errors: [f.error], warnings: [] });
586
- }
587
- print(io, results);
588
- }
589
- if (hasErrors)
590
- throw new CliError('one or more definitions have errors (see above)');
591
- return 0;
592
- }
593
- if (command === 'check') {
594
- const defsDir = last(args, 'defs') ?? io.env.OWENLOOP_DEFS ?? join(io.cwd, 'workflows');
595
- const failures = [];
596
- const defs = existsSync(defsDir) ? loadDefsRaw(defsDir, failures) : new Map();
597
- const defName = need(args, 1, 'def');
598
- const def = defs.get(defName);
599
- if (!def) {
600
- throw new CliError(`unknown workflow definition '${defName}' (looked in ${defsDir}).\n` +
601
- `Known definitions: ${[...defs.keys()].sort().join(', ') || '(none)'}${failureNote(failures)}`);
602
- }
603
- // loadDefsRaw uses buildDef (no semantic validation); run validateDef here so
604
- // invariant stem-reference / duplicate-name errors surface to the author.
605
- const defErrors = validateDef(def);
606
- if (defErrors.length > 0) {
607
- throw new CliError(`workflow '${def.name}' has validation errors:\n - ${defErrors.join('\n - ')}`);
608
- }
609
- const format = last(args, 'format') ?? 'text';
610
- const maxDepth = numOpt(args, 'max-depth');
611
- const maxStates = numOpt(args, 'max-states');
612
- const maxCollection = numOpt(args, 'max-collection');
613
- // `--strict-inputs` restores the pre-existing seedOwed-starts-owed behavior;
614
- // it takes precedence over `--assume-provided` when both are passed (the
615
- // newer explicit opt-out wins; `--assume-provided` is otherwise redundant
616
- // with the new default and is kept only so it never errors as unknown).
617
- const strictInputs = flag(args, 'strict-inputs');
618
- const bounds = {
619
- ...(maxDepth !== undefined ? { maxDepth } : {}),
620
- ...(maxStates !== undefined ? { maxStates } : {}),
621
- ...(maxCollection !== undefined ? { maxCollectionSize: maxCollection } : {}),
622
- };
623
- const report = modelCheck(def, { ...bounds, assumeProvided: !strictInputs });
624
- if (format === 'json') {
625
- print(io, report);
626
- }
627
- else {
628
- // text format
629
- const clean = report.deadlocks.length === 0
630
- && report.invariantViolations.length === 0 && report.structurallyDeadSteps.length === 0;
631
- const status = clean && report.completable ? 'OK' : clean ? 'INCOMPLETE' : 'DEFECTS FOUND';
632
- io.out(`=== owenloop check: ${def.name} ===`);
633
- io.out(`Status: ${status}`);
634
- io.out(`Completable: ${report.completable ? 'yes' : 'no'}`);
635
- io.out(`States explored: ${report.stats.statesExplored}, max depth: ${report.stats.depthReached}`);
636
- if (report.bounded) {
637
- io.out('');
638
- io.out(`SEARCH INCOMPLETE — bounds hit: ${report.boundsHit.join(', ')}`);
639
- io.out('Verdicts apply only within the explored region.');
640
- }
641
- if (report.stallStates.length > 0) {
642
- io.out('');
643
- io.out(`Stall states (expected — maxAttempts / human-escalation brakes) (${report.stallStates.length}):`);
644
- for (const s of report.stallStates) {
645
- io.out(` path: ${s.path.map((p) => `${p.step}/${p.outcome}`).join(' -> ') || '(initial state)'}`);
646
- }
647
- }
648
- if (report.deadlocks.length > 0) {
649
- io.out('');
650
- io.out(`True deadlocks (no path to completion at unlimited attempts) (${report.deadlocks.length}):`);
651
- for (const d of report.deadlocks) {
652
- io.out(` path: ${d.path.map((s) => `${s.step}/${s.outcome}`).join(' -> ') || '(initial state)'}`);
653
- }
654
- }
655
- if (strictInputs) {
656
- const seedOwedNames = def.inputs.filter((i) => i.seedOwed).map((i) => i.name);
657
- const initialDeadlock = report.deadlocks.some((d) => d.path.length === 0);
658
- if (seedOwedNames.length > 0 && initialDeadlock) {
659
- // precision: would treating seedOwed inputs as provided dissolve the
660
- // initial-state deadlock? If so, it's caused solely by unprovided
661
- // seedOwed inputs, not a structural defect — print a hint pointing at
662
- // the new default. This never fires for a deadlock that survives
663
- // providing the seeded inputs (a structural one).
664
- const probe = modelCheck(def, { ...bounds, assumeProvided: true });
665
- const clearedByProvide = !probe.deadlocks.some((d) => d.path.length === 0);
666
- if (clearedByProvide) {
667
- io.out('');
668
- io.out(`Hint: the initial-state deadlock is caused solely by unprovided seedOwed input(s): ${seedOwedNames.join(', ')}.`);
669
- io.out(` Seeded inputs are assumed provided by default; this appears only because --strict-inputs was passed.`);
670
- io.out(` Re-run 'owenloop check ${def.name}' without --strict-inputs to check the real reachable space.`);
671
- }
672
- }
673
- }
674
- if (report.stuck.length > 0) {
675
- io.out('');
676
- io.out(`Stuck states (brake tripped; other branches still moving — informational) (${report.stuck.length}):`);
677
- for (const s of report.stuck) {
678
- io.out(` path: ${s.path.map((p) => `${p.step}/${p.outcome}`).join(' -> ') || '(initial state)'}`);
679
- }
680
- }
681
- if (report.invariantViolations.length > 0) {
682
- io.out('');
683
- io.out(`Invariant violations (${report.invariantViolations.length}):`);
684
- for (const v of report.invariantViolations) {
685
- io.out(` invariant: ${v.invariant}`);
686
- io.out(` path: ${v.path.map((s) => `${s.step}/${s.outcome}`).join(' -> ') || '(initial state)'}`);
687
- }
688
- }
689
- if (report.structurallyDeadSteps.length > 0) {
690
- io.out('');
691
- io.out(`Structurally dead steps (can never fire — wiring defect): ${report.structurallyDeadSteps.join(', ')}`);
692
- }
693
- if (report.unreachedSteps.length > 0) {
694
- io.out('');
695
- io.out(`Unreached within bounds (raise --max-states/--max-depth): ${report.unreachedSteps.join(', ')}`);
696
- }
697
- if (report.completePath) {
698
- io.out('');
699
- io.out(`Example completion path:`);
700
- io.out(` ${report.completePath.map((s) => `${s.step}/${s.outcome}`).join(' -> ') || '(already done)'}`);
701
- }
702
- }
703
- // Exit codes:
704
- // - invariant violations → ALWAYS nonzero, regardless of bounded. A reported
705
- // counterexample path was produced by real applyOutcome/settleInMemory
706
- // transitions (pinned to the live Engine by the conformance test). The path
707
- // is a genuine executable witness; bounds only cause MISSES, never
708
- // fabrications. Contrast true deadlocks, where the maxCollectionSize cap can
709
- // manufacture a spurious "no moves" state — hence that requires !bounded.
710
- // Do NOT remove this asymmetry; it encodes a real soundness distinction.
711
- // - structurally-dead steps → ALWAYS nonzero, regardless of bounded. Unlike
712
- // true deadlocks (found by the bounded BFS, so a tighter maxCollectionSize
713
- // can manufacture a spurious one), structurally-dead is a STATIC canEverFire
714
- // finding that needs no search bounds at all — it is sound and bounds-
715
- // independent by construction (model.ts's canEverFire only ever returns
716
- // false when certain), so it belongs with invariant violations, not with
717
- // true deadlocks. unreachedSteps (the other dead-step bucket) must NEVER
718
- // affect the exit code — it is purely a bounds artifact.
719
- // - definite (true) deadlock only when EXHAUSTIVE (!bounded) → nonzero
720
- // - stall states and stuck states are by-design brakes and NEVER affect the
721
- // exit code — a stall state (report.stallStates) is EXPECTED (a human-
722
- // escalation brake whose freeze, once lifted, re-arms a producer), and a
723
- // stuck state (report.stuck) is purely informational (a brake tripped on
724
- // one branch while the line still moves on another). Neither is a defect.
725
- // - truncated with no invariant violations / structurally-dead steps / true
726
- // deadlocks → 0
727
- const hasDefiniteDefect = report.invariantViolations.length > 0 ||
728
- report.structurallyDeadSteps.length > 0 ||
729
- (!report.bounded && report.deadlocks.length > 0);
730
- if (hasDefiniteDefect) {
731
- throw new CliError(`definite defects found (${report.invariantViolations.length} invariant violation(s), ` +
732
- `${report.structurallyDeadSteps.length} structurally dead step(s), ` +
733
- `${report.deadlocks.length} true deadlock(s))`);
734
- }
735
- return 0;
736
- }
737
- const ctx = openCtx(io, args);
738
- const { engine, store } = ctx;
739
- try {
740
- switch (command) {
741
- case 'defs': {
742
- print(io, [...ctx.defs.values()].map((d) => ({
743
- name: d.name,
744
- title: d.title ?? null,
745
- inputs: d.inputs.map((i) => i.name),
746
- steps: d.steps.map((l) => l.name),
747
- })));
748
- return 0;
749
- }
750
- case 'create': {
751
- const defName = need(args, 1, 'def');
752
- const opts = {};
753
- const title = last(args, 'title');
754
- if (title !== undefined)
755
- opts.title = title;
756
- const provide = parsePairs(all(args, 'provide'), true);
757
- if (Object.keys(provide).length) {
758
- opts.provide = provide;
759
- }
760
- const params = parsePairs(all(args, 'param'), false);
761
- if (Object.keys(params).length)
762
- opts.params = params;
763
- const id = engine.createInstance(defName, opts);
764
- print(io, { workflow: id });
765
- return 0;
766
- }
767
- case 'provide': {
768
- const wf = need(args, 1, 'workflow');
769
- const name = need(args, 2, 'name');
770
- engine.provideInput(wf, name, parseJson(last(args, 'value')));
771
- print(io, { ok: true, provided: name });
772
- return 0;
773
- }
774
- case 'adopt': {
775
- const wf = need(args, 1, 'workflow');
776
- const res = engine.adopt(wf);
777
- print(io, { ok: true, ...res });
778
- return 0;
779
- }
780
- case 'tick': {
781
- const wf = need(args, 1, 'workflow');
782
- const now = numOpt(args, 'now');
783
- // §23.6.8: tick is deep by default (descends into calls: children and
784
- // returns their orders too); --shallow restores single-instance ticking.
785
- const tickOpts = {};
786
- if (now !== undefined)
787
- tickOpts.now = now;
788
- if (flag(args, 'shallow'))
789
- tickOpts.deep = false;
790
- // A2: repeatable --label narrows the claim to steps whose labels
791
- // intersect the caller's; absent = claim everything (today's behavior).
792
- const labels = all(args, 'label');
793
- if (labels.length > 0)
794
- tickOpts.labels = labels;
795
- print(io, engine.tick(wf, tickOpts));
796
- return 0;
797
- }
798
- case 'reap': {
799
- const wf = need(args, 1, 'workflow');
800
- const nowFlag = flag(args, 'now');
801
- const wfRow = store.getWorkflow(wf);
802
- if (!wfRow)
803
- throw new CliError(`workflow not found: ${wf}`);
804
- const def = ctx.defs.get(wfRow.def);
805
- if (!def)
806
- throw new CliError(`unknown workflow definition '${wfRow.def}' (looked in ${ctx.defsDir})`);
807
- const result = engine.reapWithDetails(wf, nowMs(), def, nowFlag ? { ttlOverride: 0 } : {});
808
- print(io, { reaped: result.count, details: result.details });
809
- return 0;
810
- }
811
- case 'status': {
812
- // `--all` is the fleet read: one call returns every instance's full
813
- // status plus its identity and `task` join key, so a supervisor (dev)
814
- // sees the whole project in a single invocation instead of N ticks. A
815
- // single instance whose def is unresolvable degrades to an `error`
816
- // field rather than aborting the sweep.
817
- if (flag(args, 'all')) {
818
- // `--all` is the whole-fleet read; a workflow argument is
819
- // contradictory (one or all?). Reject it in both orderings rather
820
- // than silently ignoring the caller's intent:
821
- // `status wf --all` / `status --all wf` → the wf lands in positionals[1]
822
- // (`all` is a boolean flag and never consumes the next token)
823
- // `status --all=wf` → the `=` form binds wf as `--all`'s value
824
- const v = last(args, 'all');
825
- const stray = args.positionals[1] ?? (v !== 'true' && v !== '' ? v : undefined);
826
- if (stray !== undefined) {
827
- throw new CliError(`status --all takes no workflow argument (got "${stray}")`);
828
- }
829
- print(io, store.listWorkflows().map((w) => statusEntry(engine, w)));
830
- return 0;
831
- }
832
- print(io, engine.status(need(args, 1, 'workflow')));
833
- return 0;
834
- }
835
- case 'wait': {
836
- // Blocking poll so an orchestrator/agent can wait for engine state
837
- // change without burning inference on a poll loop. Plain synchronous
838
- // poll of the local db (cheap — one process, no LLM calls). On
839
- // success, prints the exact `status()` shape (same as plain
840
- // `status <wf>`) so a caller sees WHY it returned and can pipe the
841
- // output the same way. On timeout, exits 1 with a JSON body (not
842
- // just a stderr string) naming what's still unmet.
843
- const wf = need(args, 1, 'workflow');
844
- const until = last(args, 'until');
845
- if (until !== 'eligible' && until !== 'done') {
846
- throw new CliError(`--until must be "eligible" or "done" (got: ${until ?? '(missing)'})`);
847
- }
848
- const timeoutSpec = last(args, 'timeout') ?? '10m';
849
- let timeoutMs;
850
- try {
851
- timeoutMs = parseDurationMs(timeoutSpec);
852
- }
853
- catch (e) {
854
- throw new CliError(`--timeout: ${e.message}`);
855
- }
856
- const pollMs = 250;
857
- const deadline = nowMs() + timeoutMs;
858
- for (;;) {
859
- // Unknown/unresolvable workflow throws here the same way plain
860
- // `status <wf>` does today — `wait` inherits that for free. A bad
861
- // workflow id is a hard error, not a wait condition.
862
- const st = engine.status(wf);
863
- const satisfied = until === 'done' ? st.done : st.eligible.length > 0;
864
- if (satisfied) {
865
- print(io, st);
866
- return 0;
867
- }
868
- const now = nowMs();
869
- if (now >= deadline) {
870
- print(io, {
871
- ok: false,
872
- error: 'timeout',
873
- until,
874
- timeout: timeoutSpec,
875
- status: st, // last-observed state, so the caller sees *why* it's still unmet
876
- });
877
- return 1;
878
- }
879
- // Clamped so the last iteration wakes right at the deadline
880
- // instead of sleeping past it.
881
- sleepMs(Math.min(pollMs, deadline - now));
882
- }
883
- }
884
- case 'show': {
885
- const wf = need(args, 1, 'workflow');
886
- print(io, store.listArtifacts(wf));
887
- return 0;
888
- }
889
- case 'trace': {
890
- const wf = need(args, 1, 'workflow');
891
- const format = last(args, 'format') ?? 'json';
892
- const artifacts = store.listArtifacts(wf);
893
- const runs = store.listRuns(wf);
894
- // Resolve the def — need the workflow row to get the definition name.
895
- const wfRow = store.getWorkflow(wf);
896
- if (!wfRow)
897
- throw new CliError(`workflow not found: ${wf}`);
898
- const def = ctx.defs.get(wfRow.def);
899
- if (!def)
900
- throw new CliError(`unknown workflow definition '${wfRow.def}' (looked in ${ctx.defsDir})`);
901
- const trace = buildTrace(def, artifacts, runs);
902
- if (format === 'text') {
903
- // --- compact human-readable rendering ---
904
- io.out('=== Timeline ===');
905
- for (const ev of trace.timeline) {
906
- const ts = new Date(ev.at).toISOString();
907
- const keyPart = ev.key ? `[${ev.key}]` : '';
908
- const consumed = ev.consumedInputs
909
- ? JSON.stringify(ev.consumedInputs)
910
- : '(no fingerprint)';
911
- const produced = ev.producedStems.join(', ') || '(none)';
912
- io.out(`#${ev.seq} ${ts} ${ev.step}${keyPart} ${ev.outcome ?? 'open'} — consumed ${consumed} produced [${produced}]`);
913
- if (ev.summary)
914
- io.out(` summary: ${ev.summary}`);
915
- }
916
- io.out('');
917
- io.out('=== Artifacts ===');
918
- for (const art of trace.artifacts) {
919
- io.out(`${art.path} (${art.acceptance}, v${art.version}, producer: ${art.producer})`);
920
- if (art.approvals && Object.keys(art.approvals).length > 0) {
921
- const ledger = Object.entries(art.approvals).map(([jn, v]) => `${jn}@v${v}`).join(', ');
922
- io.out(` approvals: ${ledger}`);
923
- }
924
- if (art.events.length === 0) {
925
- io.out(' (no lifecycle events)');
926
- }
927
- else {
928
- for (const ev of art.events) {
929
- const ts = new Date(ev.at).toISOString();
930
- io.out(` ${ts} ${ev.action} by:${ev.by} "${ev.text}"`);
931
- }
932
- }
933
- }
934
- io.out('');
935
- io.out(`=== Summary: ${trace.summary.totalRuns} runs, done=${trace.summary.done} ===`);
936
- }
937
- else {
938
- // default: JSON
939
- print(io, trace);
940
- }
941
- return 0;
942
- }
943
- case 'runs': {
944
- const wf = need(args, 1, 'workflow');
945
- const openOnly = flag(args, 'open');
946
- const runs = store.listRuns(wf); // src/store.ts, already workflow-scoped
947
- const tasks = store.listTasks(wf); // for the claim join
948
- const now = nowMs();
949
- const taskByKey = new Map(tasks.map((t) => [detId('taskkey', t.step, t.key), t]));
950
- const rows = runs
951
- .filter((r) => !openOnly || r.outcome === undefined)
952
- .map((r) => {
953
- const base = {
954
- run: r.id,
955
- step: r.step,
956
- key: r.key,
957
- outcome: r.outcome ?? 'open',
958
- createdAt: r.createdAt,
959
- updatedAt: r.updatedAt,
960
- };
961
- if (r.outcome !== undefined)
962
- return base; // only join claim state for OPEN runs
963
- const task = taskByKey.get(detId('taskkey', r.step, r.key ?? ''));
964
- if (!task || task.run !== r.id)
965
- return base; // superseded/reaped — no live claim to join
966
- return {
967
- ...base,
968
- claimedAt: task.claimedAt,
969
- heartbeatAt: task.heartbeatAt,
970
- attempts: task.attempts,
971
- claimAgeMs: task.claimedAt !== undefined ? now - task.claimedAt : undefined,
972
- heartbeatAgeMs: task.heartbeatAt !== undefined ? now - task.heartbeatAt : undefined,
973
- };
974
- });
975
- print(io, rows);
976
- return 0;
977
- }
978
- case 'order': {
979
- const wf = need(args, 1, 'workflow');
980
- const run = need(args, 2, 'run');
981
- const r = store.getRun(run);
982
- if (!r)
983
- throw new CliError(`run not found: ${run}`);
984
- if (r.workflow !== wf)
985
- throw new CliError(`run ${run} belongs to workflow ${r.workflow}, not ${wf}`);
986
- if (r.order === undefined)
987
- throw new CliError(`run ${run} has no persisted order (created before order persistence, schema v7)`);
988
- print(io, r.order);
989
- return 0;
990
- }
991
- case 'list': {
992
- print(io, store.listWorkflows().map((w) => {
993
- const s = safeStatus(engine, w.id);
994
- return { id: w.id, def: w.def, title: w.title ?? null, createdAt: w.createdAt, done: s };
995
- }));
996
- return 0;
997
- }
998
- case 'green': {
999
- const wf = need(args, 1, 'workflow');
1000
- // §24: a human bypass (§4.11) passes 'human' in place of a run id — no
1001
- // lease/CAS applies, see Engine.green's actor-discrimination doc comment.
1002
- const run = need(args, 2, 'run');
1003
- const path = need(args, 3, 'path');
1004
- const value = parseJson(last(args, 'value'));
1005
- const res = engine.green(wf, run, path, value, { terminal: flag(args, 'terminal') });
1006
- print(io, res);
1007
- // §24: 'submitted' (producer commit awaiting judges) and 'approved'
1008
- // (one judge signed, others still pending) are successful outcomes,
1009
- // not errors — only 'born-rejected', 'schema-rejected', and (§26)
1010
- // 'group-rejected' are failures.
1011
- if (res.outcome === 'born-rejected' || res.outcome === 'schema-rejected' || res.outcome === 'group-rejected') {
1012
- io.err(`green ${path}: ${res.outcome}${res.reason ? ' — ' + res.reason : ''}`);
1013
- return 1;
1014
- }
1015
- return 0;
1016
- }
1017
- case 'emit': {
1018
- const wf = need(args, 1, 'workflow');
1019
- const run = need(args, 2, 'run');
1020
- const itemsRaw = needOpt(args, 'items');
1021
- let parsed;
1022
- try {
1023
- parsed = JSON.parse(itemsRaw);
1024
- }
1025
- catch {
1026
- throw new CliError(`--items must be a JSON array: ${itemsRaw}`);
1027
- }
1028
- if (!Array.isArray(parsed))
1029
- throw new CliError('--items must be a JSON array');
1030
- const items = parsed.map((v) => ({ value: v }));
1031
- const emitRes = engine.emit(wf, run, items);
1032
- print(io, emitRes);
1033
- if (emitRes.outcome !== 'emitted') {
1034
- io.err(`emit: ${emitRes.outcome}${emitRes.reason ? ' — ' + emitRes.reason : ''}`);
1035
- return 1;
1036
- }
1037
- return 0;
1038
- }
1039
- case 'seal': {
1040
- const wf = need(args, 1, 'workflow');
1041
- const run = need(args, 2, 'run');
1042
- const sealRes = engine.seal(wf, run, parseJson(last(args, 'value')));
1043
- print(io, sealRes);
1044
- if (sealRes.outcome !== 'green') {
1045
- io.err(`seal ${sealRes.path}: ${sealRes.outcome}${sealRes.reason ? ' — ' + sealRes.reason : ''}`);
1046
- return 1;
1047
- }
1048
- return 0;
1049
- }
1050
- case 'reject': {
1051
- const wf = need(args, 1, 'workflow');
1052
- const path = need(args, 2, 'path');
1053
- const by = needOpt(args, 'by');
1054
- const text = needOpt(args, 'text');
1055
- const rejectRes = engine.reject(wf, path, by, text);
1056
- print(io, { ok: true, action: 'reject', path, outcome: rejectRes.outcome });
1057
- // §24.4/§4.6: a judge's reject can itself be born-rejected by the CAS
1058
- // guard (stale verdict against a submission that already moved on) —
1059
- // mirror the 'green' handler above: that is a failure, not a success,
1060
- // and callers scripting against the CLI (e.g. judged-research.yaml)
1061
- // must see it, not a silent { ok: true }.
1062
- if (rejectRes.outcome === 'born-rejected') {
1063
- io.err(`reject ${path}: ${rejectRes.outcome}${rejectRes.reason ? ' — ' + rejectRes.reason : ''}`);
1064
- return 1;
1065
- }
1066
- return 0;
1067
- }
1068
- case 'retract':
1069
- case 'skip': {
1070
- const wf = need(args, 1, 'workflow');
1071
- const path = need(args, 2, 'path');
1072
- const by = needOpt(args, 'by');
1073
- const text = needOpt(args, 'text');
1074
- engine[command](wf, path, by, text);
1075
- print(io, { ok: true, action: command, path });
1076
- return 0;
1077
- }
1078
- case 'retry': {
1079
- // text/by are optional: a retry can be a bare stall-clear or carry guidance
1080
- const wf = need(args, 1, 'workflow');
1081
- const path = need(args, 2, 'path');
1082
- engine.retry(wf, path, last(args, 'by') ?? 'human', last(args, 'text') ?? 'retry: stall cleared');
1083
- print(io, { ok: true, action: 'retry', path });
1084
- return 0;
1085
- }
1086
- case 'close': {
1087
- const wf = need(args, 1, 'workflow');
1088
- const run = need(args, 2, 'run');
1089
- const outcome = (last(args, 'outcome') ?? 'ok');
1090
- // close has no outcome discriminator: engine throws on real errors, so {ok:true} is always accurate here.
1091
- engine.close(wf, run, outcome, last(args, 'summary'));
1092
- print(io, { ok: true, run, outcome });
1093
- return 0;
1094
- }
1095
- case 'heartbeat': {
1096
- const wf = need(args, 1, 'workflow');
1097
- const run = need(args, 2, 'run');
1098
- engine.heartbeat(wf, run, numOpt(args, 'now'));
1099
- print(io, { ok: true, workflow: wf, run });
1100
- return 0;
1101
- }
1102
- case 'delete': {
1103
- const wf = need(args, 1, 'workflow');
1104
- const children = store.listChildrenByParent(wf);
1105
- // Default is refuse-with-children, not silent cascade: an operator deleting one workflow
1106
- // should not accidentally destroy an unbounded tree of spawned instances. --recursive opts in.
1107
- if (children.length > 0 && !flag(args, 'recursive')) {
1108
- throw new CliError(`workflow '${wf}' has ${children.length} child instance(s): ` +
1109
- `${children.map((c) => `${c.id} (${c.def})`).join(', ')}. ` +
1110
- `Refusing to delete without --recursive.`);
1111
- }
1112
- if (flag(args, 'recursive')) {
1113
- store.deleteWorkflowCascade(wf);
1114
- }
1115
- else {
1116
- store.deleteWorkflow(wf);
1117
- }
1118
- print(io, { ok: true, deleted: wf, ...(children.length > 0 ? { cascaded: children.length } : {}) });
1119
- return 0;
1120
- }
1121
- case 'graph': {
1122
- const arg = need(args, 1, 'def-name or workflow-id');
1123
- const format = last(args, 'format') ?? 'dot';
1124
- let def;
1125
- let artifacts;
1126
- if (ctx.defs.has(arg)) {
1127
- // static mode: arg is a def name
1128
- def = ctx.defs.get(arg);
1129
- artifacts = undefined;
1130
- }
1131
- else {
1132
- // live mode: arg is a workflow instance id
1133
- const wfRow = store.getWorkflow(arg);
1134
- if (!wfRow) {
1135
- throw new CliError(`'${arg}' is neither a known workflow definition nor a workflow instance id.\n` +
1136
- `Known definitions: ${[...ctx.defs.keys()].sort().join(', ') || '(none)'}`);
1137
- }
1138
- const defName = wfRow.def;
1139
- const resolvedDef = ctx.defs.get(defName);
1140
- if (!resolvedDef) {
1141
- throw new CliError(`workflow instance '${arg}' uses definition '${defName}' which is not available (looked in ${ctx.defsDir})`);
1142
- }
1143
- def = resolvedDef;
1144
- artifacts = store.listArtifacts(arg);
1145
- }
1146
- const graph = buildGraph(def, artifacts);
1147
- if (format === 'json') {
1148
- print(io, graph);
1149
- }
1150
- else if (format === 'mermaid') {
1151
- io.out(graphToMermaid(graph));
1152
- }
1153
- else {
1154
- // default: dot
1155
- io.out(graphToDot(graph));
1156
- }
1157
- return 0;
1158
- }
1159
- default:
1160
- throw new CliError(`unknown command: ${command}\n\n${USAGE}`);
1161
- }
1162
- }
1163
- finally {
1164
- store.close();
1165
- }
1166
- }
1167
- function safeStatus(engine, wf) {
1168
- try {
1169
- return engine.status(wf).done;
1170
- }
1171
- catch {
1172
- return null;
1173
- }
1174
- }
1175
- /** One row of the `status --all` fleet read: instance identity + join key,
1176
- * merged with its derived status (or an `error` if the def can't resolve). */
1177
- function statusEntry(engine, w) {
1178
- const base = {
1179
- workflow: w.id,
1180
- def: w.def,
1181
- title: w.title ?? null,
1182
- task: w.params?.task ?? null,
1183
- createdAt: w.createdAt,
1184
- };
1185
- try {
1186
- return { ...base, ...engine.status(w.id) };
1187
- }
1188
- catch (e) {
1189
- return { ...base, error: e.message };
1190
- }
1191
- }
1192
- /**
1193
- * `owenloop add <owner>/<repo>[@ref]` — the one network-touching CLI verb
1194
- * (workflow-distribution Stage 1). Fetches a public GitHub repo's tarball,
1195
- * validates its `workflows/**` defs with the same lint/check machinery
1196
- * `owenloop lint`/`owenloop check` use, and — only if everything passes —
1197
- * installs them under `<defsDir>/<installFolder(owner,repo)>/` and records
1198
- * provenance in `.owenloop/installed.json`. A partial install is never left
1199
- * behind: any refusal (parse/lint/validate/check failure) writes nothing, and
1200
- * even a failure of the lockfile write after the directory swap rolls the
1201
- * directory state back — the commit point is the durable lockfile write.
1202
- *
1203
- * Kept inside cli.ts (rather than add.ts) so it can reuse `Args`/`need`/
1204
- * `last`/`CliError`/`parseJson`/`print`/`failureNote` without exporting them
1205
- * from this module — the pure, unit-tested logic (spec parsing, lockfile
1206
- * I/O, file install) lives in `src/add.ts`; this function is just the async
1207
- * network + arg glue.
1208
- */
1209
- // Request deadlines for the two `add` fetches. A small JSON/text sha lookup
1210
- // should be quick; the whole-repo tarball may be large on a slow link, so it
1211
- // gets a much longer budget. Constants only — no env knob (a follow-up can add
1212
- // one if ever needed).
1213
- const ADD_SHA_TIMEOUT_MS = 30_000;
1214
- const ADD_TARBALL_TIMEOUT_MS = 300_000;
1215
- /**
1216
- * Cap on the `add` tarball download body, enforced DURING the stream by
1217
- * `readBodyBounded` — defense in depth with `extractTarGz`'s own post-hoc
1218
- * `maxCompressedBytes` check (kept intact). `OWENLOOP_TARBALL_MAX_BYTES`
1219
- * overrides it (a test-only knob, validated `Number.isFinite && > 0`,
1220
- * consistent with the project's other `OWENLOOP_*` knobs) so a mid-stream test
1221
- * need not buffer the real 256 MiB cap in CI.
1222
- */
1223
- function tarballMaxBytes(io) {
1224
- const override = Number(io.env.OWENLOOP_TARBALL_MAX_BYTES);
1225
- return Number.isFinite(override) && override > 0 ? override : DEFAULT_TAR_LIMITS.maxCompressedBytes;
1226
- }
1227
- /**
1228
- * `owenloop add <owner>/<repo>[@ref]` — fetch a repo's `workflows/**`, validate
1229
- * it, and install it under `<defsDir>/<installFolder(owner,repo)>`.
1230
- *
1231
- * The network fetch/extract/path-filter runs FIRST, unlocked (a tarball can
1232
- * take minutes and holding a lock that long would needlessly serialize
1233
- * unrelated adds). Everything that touches project state then runs under the
1234
- * per-project `.owenloop/add.lock`: crash-recovery pass → stale-staging cleanup
1235
- * → lockfile read → ownership check → stage → strict validation → atomic commit
1236
- * (backups retained) → journal write → lockfile write → journal advance →
1237
- * finalize (backups discarded) → journal remove. Deciding ownership and reading
1238
- * the lockfile INSIDE the lock is deliberate (TOCTOU discipline — see the
1239
- * store-migration knowledge node). The install is staged on the destination
1240
- * filesystem and swapped in with an atomic rename, but the displaced previous
1241
- * install and any old-name dir are kept until the lockfile write succeeds — the
1242
- * directory commit and the ledger write are one recoverable operation. Any
1243
- * failure before the lockfile is durably written rolls the directory state back
1244
- * and leaves the previous install and lockfile exactly as they were, with no
1245
- * staging debris.
1246
- *
1247
- * A `.owenloop/add.journal` intent record closes the crash-recovery gap the
1248
- * in-process rollback arms can't: it is written (phase `applying`) right before
1249
- * the destructive `commitInstall`, advanced (phase `finalizing`) right after the
1250
- * durable ledger write, and removed on clean completion. A process killed
1251
- * mid-install leaves the journal behind; the NEXT add runs
1252
- * `recoverInterruptedInstall` FIRST inside the lock — before the stale-staging
1253
- * clear, since the backups a rollback needs live under the staging root — to
1254
- * roll the interrupted install forward (past the commit point) or back (before
1255
- * it) to a consistent (defs ⇔ ledger) state. The journal is attacker-
1256
- * influenceable input, validated fail-closed with the same A1 discipline as the
1257
- * lockfile; a bad/mismatched/contradictory journal REFUSES with no fs mutation
1258
- * (and, via `preserveStagingRoot`, without the `finally` clearing the evidence).
1259
- */
1260
- async function dispatchAdd(io, args) {
1261
- // Offline crash-recovery branch. This sits at the VERY TOP — before `need`/
1262
- // `parseRepoSpec` and before either network fetch — so `--recover` is
1263
- // structurally incapable of reaching the SHA/tarball fetches. A machine that
1264
- // crashed mid-install and is now offline can finish or undo the interrupted
1265
- // install with no network (recovery is purely local filesystem work).
1266
- if (flag(args, 'recover'))
1267
- return dispatchAddRecover(io, args);
1268
- const spec = need(args, 1, 'owner/repo[@ref]');
1269
- const { owner, repo, ref } = parseRepoSpec(spec);
1270
- const source = `${owner}/${repo}`;
1271
- const defsOverride = last(args, 'defs') ?? io.env.OWENLOOP_DEFS;
1272
- const defsDir = defsOverride ?? join(io.cwd, 'workflows');
1273
- const lockfilePath = join(io.cwd, '.owenloop', 'installed.json');
1274
- const installLockPath = join(io.cwd, '.owenloop', 'add.lock');
1275
- const journalPath = join(io.cwd, '.owenloop', ADD_JOURNAL_FILENAME);
1276
- const fetchFn = io.fetch ?? globalThis.fetch;
1277
- // 1. Resolve the ref to a pinned commit sha.
1278
- let shaRes;
1279
- try {
1280
- shaRes = await fetchFn(githubShaUrl(owner, repo, ref), {
1281
- headers: { Accept: 'application/vnd.github.sha', 'User-Agent': 'owenloop' },
1282
- signal: AbortSignal.timeout(ADD_SHA_TIMEOUT_MS),
1283
- });
1284
- }
1285
- catch (e) {
1286
- const err = e;
1287
- if (err.name === 'TimeoutError' || err.name === 'AbortError') {
1288
- throw new CliError(`timed out after ${ADD_SHA_TIMEOUT_MS / 1000}s resolving ${source}@${ref}`);
1289
- }
1290
- throw e;
1291
- }
1292
- if (!shaRes.ok) {
1293
- const notFoundNote = shaRes.status === 404 ? ' (repo or ref not found)' : '';
1294
- throw new CliError(`could not resolve ${source}@${ref}: GitHub returned ${shaRes.status}${notFoundNote}`);
1295
- }
1296
- const shaBytes = await readBodyBounded(shaRes, hubMaxResponseBytes(io), `sha resolution for ${source}@${ref}`);
1297
- const shaBody = new TextDecoder().decode(shaBytes).trim();
1298
- if (!/^[0-9a-f]{40}$/i.test(shaBody)) {
1299
- throw new CliError(`unexpected response resolving ${source}@${ref}: expected a 40-char commit sha, got "${shaBody}"`);
1300
- }
1301
- const sha = shaBody;
1302
- // 2. Fetch the tarball for that pinned sha. The timeout must cover the body
1303
- // read too — undici ties the abort signal to the body stream — so the
1304
- // fetch AND the bounded read live in the same try. readBodyBounded caps the
1305
- // download DURING the stream (cancelling at the cap), so an oversized
1306
- // tarball is never fully allocated; extractTarGz still re-checks the size
1307
- // post-hoc (defense in depth).
1308
- let bytes;
1309
- try {
1310
- const tarRes = await fetchFn(githubTarballUrl(owner, repo, sha), {
1311
- headers: { 'User-Agent': 'owenloop' },
1312
- signal: AbortSignal.timeout(ADD_TARBALL_TIMEOUT_MS),
1313
- });
1314
- if (!tarRes.ok) {
1315
- throw new CliError(`could not fetch tarball for ${source}@${sha}: GitHub returned ${tarRes.status}`);
1316
- }
1317
- bytes = await readBodyBounded(tarRes, tarballMaxBytes(io), `tarball for ${source}@${sha}`);
1318
- }
1319
- catch (e) {
1320
- const err = e;
1321
- if (err.name === 'TimeoutError' || err.name === 'AbortError') {
1322
- throw new CliError(`timed out after ${ADD_TARBALL_TIMEOUT_MS / 1000}s downloading tarball for ${source}@${sha}`);
1323
- }
1324
- throw e;
1325
- }
1326
- // 3. Extract, strip the single leading '<owner>-<repo>-<sha>/' root-dir
1327
- // component GitHub tarballs always have, and keep only workflows/**
1328
- // (re-keyed relative to that dir).
1329
- let rawFiles;
1330
- try {
1331
- rawFiles = extractTarGz(bytes);
1332
- }
1333
- catch (e) {
1334
- throw new CliError(`could not extract tarball for ${source}@${sha}: ${e.message}`);
1335
- }
1336
- const files = new Map();
1337
- const pathViolations = [];
1338
- for (const [rawPath, data] of rawFiles) {
1339
- const firstSlash = rawPath.indexOf('/');
1340
- const rest = firstSlash >= 0 ? rawPath.slice(firstSlash + 1) : '';
1341
- if (rest.startsWith('workflows/')) {
1342
- const relPath = rest.slice('workflows/'.length);
1343
- if (relPath) {
1344
- // Reject any entry that would escape the staging/install dir BEFORE it
1345
- // is ever joined and written (SEC-1). Collect every offender so the
1346
- // refusal names them all.
1347
- const violation = archivePathViolation(relPath);
1348
- if (violation) {
1349
- pathViolations.push(`${rawPath}: ${violation}`);
1350
- continue;
1351
- }
1352
- files.set(relPath, data);
1353
- }
1354
- }
1355
- }
1356
- if (pathViolations.length > 0) {
1357
- throw new CliError(`refusing to install ${source}@${sha} — ${pathViolations.length} unsafe archive path(s) found; nothing written:\n - ${pathViolations.join('\n - ')}`);
1358
- }
1359
- // Note: git (and so GitHub's tarball export) never tracks a truly empty
1360
- // directory, so "no workflows/ dir at all" and "workflows/ dir exists but
1361
- // is untracked-empty" are indistinguishable from the archive's contents —
1362
- // both land here as files.size === 0. A `workflows/` dir that is tracked
1363
- // but genuinely has zero yaml defs in it (e.g. holds only a .gitkeep)
1364
- // takes the success/`installed: 0` path below instead, since it has at
1365
- // least one file under the prefix.
1366
- if (files.size === 0) {
1367
- throw new CliError(`no workflows/ directory found in ${source}@${ref}`);
1368
- }
1369
- // 4. Everything that touches project state runs under the per-project install
1370
- // lock: concurrent `add` runs serialize instead of interleaving. The lock
1371
- // is acquired only now — AFTER the (potentially slow) network fetch — so a
1372
- // tarball download never blocks an unrelated add.
1373
- const folder = installFolder(owner, repo);
1374
- const stagingRoot = join(defsDir, STAGING_DIRNAME);
1375
- const stagingId = randId('stg');
1376
- const stagingDir = join(stagingRoot, stagingId);
1377
- // SEC-3, add's half: refuse a symlinked project `.owenloop` (the parent of
1378
- // add.lock and installed.json — always cwd-derived in add, no override
1379
- // exists) and a symlinked DEFAULT defs dir before any state write. Both must
1380
- // precede acquireInstallLock: `.owenloop` is written by the lock acquire and
1381
- // the ledger; defsDir is DELETED-through by the stale-staging rmSync below and
1382
- // then written by staging/commit. An explicit --defs/OWENLOOP_DEFS is operator
1383
- // intent, not repo content — deliberately installing through a symlink keeps
1384
- // today's behavior, matching the --db/OWENLOOP_DB rule.
1385
- mkdirRefusingSymlink(join(io.cwd, '.owenloop'));
1386
- if (defsOverride === undefined)
1387
- mkdirRefusingSymlink(defsDir);
1388
- const lock = await acquireInstallLock(installLockPath);
1389
- // Set true only on a rollback double-fault, where the ONLY copy of the
1390
- // previous content ends up parked under the staging root — then the `finally`
1391
- // must NOT delete it (the error message tells the user to recover it).
1392
- let preserveStagingRoot = false;
1393
- try {
1394
- // Recover a crash-interrupted prior install FIRST — before the stale-staging
1395
- // clear, since the backups/parked dirs a rollback needs live UNDER the
1396
- // staging root, so clearing it first would destroy them. Any refusal (bad or
1397
- // mismatched or contradictory journal) must preserve the staging root and the
1398
- // journal as evidence: without this, the `finally` below would rmSync the
1399
- // staging root and take the backups a later recovery needs with it.
1400
- try {
1401
- recoverInterruptedInstall({ defsDir, journalPath, lockfilePath });
1402
- }
1403
- catch (e) {
1404
- preserveStagingRoot = true;
1405
- throw e;
1406
- }
1407
- // The lock holder is the only legitimate writer under the staging root, so
1408
- // anything already there is debris from a crashed/killed prior run — clear
1409
- // it. Keeps "no staging debris" true even across a Ctrl-C.
1410
- rmSync(stagingRoot, { recursive: true, force: true });
1411
- // Read the lockfile and decide ownership INSIDE the lock (TOCTOU: a pre-lock
1412
- // read could be stale by the time we act on it). A corrupt lockfile is a
1413
- // hard error (readLockfile), never a silent reset.
1414
- const lf = readLockfile(lockfilePath);
1415
- const dest = join(defsDir, folder);
1416
- const existing = lf.installed[source];
1417
- // Use-site exact-match (Layer 2): the entry being installed may only record
1418
- // the currently computed folder OR the exact legacy `<owner>-<repo>` name
1419
- // (the only pre-hash scheme this tool ever wrote). `readLockfile` has
1420
- // already refused any structurally unsafe `path`; this additionally refuses
1421
- // a structurally-valid-but-WRONG segment (e.g. 'not-the-right-folder')
1422
- // before any staging/commit mutation, so the later `existing.path !== folder`
1423
- // migration branch is guaranteed to see only the exact legacy name.
1424
- const legacyFolder = `${owner}-${repo}`;
1425
- if (existing && existing.path !== folder && existing.path !== legacyFolder) {
1426
- throw new CliError(`refusing to install ${source}: lockfile records install path '${existing.path}', ` +
1427
- `which is neither the expected '${folder}' nor the legacy '${legacyFolder}' — fix ${lockfilePath} manually`);
1428
- }
1429
- if (existsSync(dest) && !(existing && existing.path === folder)) {
1430
- throw new CliError(`refusing to install ${source}: destination '${folder}' already exists and is not owned by ${source} — ` +
1431
- `remove it manually or fix ${lockfilePath}`);
1432
- }
1433
- // Stage the incoming files onto the DESTINATION filesystem (under defsDir),
1434
- // so the commit is an atomic same-fs rename. Two-level layout keeps the
1435
- // staged content invisible to loadDefs(defsDir).
1436
- const written = stageFiles(stagingDir, files);
1437
- // 5. Validate the STAGED tree — the exact bytes that will be renamed into
1438
- // place, with no re-write after validation.
1439
- const failures = [];
1440
- const staged = loadDefsRaw(stagingDir, failures);
1441
- const reasons = failures.map((f) => `${f.file}: ${f.error}`);
1442
- for (const stagedDef of staged.values()) {
1443
- const lintResult = lintDef(stagedDef);
1444
- reasons.push(...lintResult.errors.map((e) => `${stagedDef.name}: ${e}`));
1445
- const validationErrors = validateDef(stagedDef);
1446
- reasons.push(...validationErrors.map((e) => `${stagedDef.name}: ${e}`));
1447
- // Mirror the `check` command's exact "definite defect" predicate — but,
1448
- // deliberately, WITH `assumeProvided: true`. Without it, a def with any
1449
- // `seedOwed` input (the norm — see e.g. `proposal` in delivery.yaml)
1450
- // deadlocks in the very first state, because the checker models "no
1451
- // `provide` has happened yet" by default (see `seedArts` in
1452
- // src/model.ts). `owenloop check <def>` behaves the same way absent
1453
- // `--assume-provided`; verified every def under examples/workflows/
1454
- // fails plain `check` for exactly this reason. Since `add` validates a
1455
- // def that a real user will `provide` into after install (that's the
1456
- // whole point of a seedOwed input), refusing every seedOwed def here
1457
- // would make `add` unable to install almost any real workflow,
1458
- // including this project's own examples — so this checks "is it
1459
- // completable once its owed inputs are supplied," the same bar a
1460
- // careful author would clear with `check --assume-provided` before
1461
- // publishing.
1462
- const report = modelCheck(stagedDef, { assumeProvided: true });
1463
- const hasDefiniteDefect = report.invariantViolations.length > 0 ||
1464
- (!report.bounded && report.deadlocks.length > 0);
1465
- if (hasDefiniteDefect) {
1466
- reasons.push(`${stagedDef.name}: definite defects found (${report.invariantViolations.length} invariant violation(s), ` +
1467
- `${report.deadlocks.length} true deadlock(s))`);
1468
- }
1469
- }
1470
- // Strict backstop: only if the aggregate pass found nothing, run the FULL
1471
- // loadDefs on the staged tree. `loadDefsRaw` is best-effort — it swallows
1472
- // include-expansion failures and cross-def `calls:` errors that strict
1473
- // `loadDefs` (via finalizeDefs) throws on. Every later command loads the
1474
- // installed dir with strict `loadDefs`, so this guarantees whatever we
1475
- // commit cannot make a subsequent `loadDefs` of that dir throw.
1476
- if (reasons.length === 0) {
1477
- try {
1478
- loadDefs(stagingDir);
1479
- }
1480
- catch (e) {
1481
- if (e instanceof DefError) {
1482
- reasons.push(`cross-definition validation failed: ${e.message}`);
1483
- }
1484
- else {
1485
- throw e;
1486
- }
1487
- }
1488
- }
1489
- if (reasons.length > 0) {
1490
- throw new CliError(`refusing to install ${source}@${sha} — ${reasons.length} problem(s) found; nothing written:\n - ${reasons.join('\n - ')}`);
1491
- }
1492
- // 6. Commit as one recoverable operation: atomically swap the validated
1493
- // staging dir into place (backups RETAINED, not dropped), park any
1494
- // old-naming dir this source used to occupy, write the lockfile, and only
1495
- // then finalize (discard the retained backups). If the lockfile write
1496
- // fails after the swap, roll the directory state back so the previous
1497
- // install and lockfile are left exactly as they were.
1498
- //
1499
- // Write the crash-recovery journal (phase `applying`) BEFORE the first
1500
- // destructive step. `hadDest` is captured here, under the lock, right before
1501
- // commitInstall reads the same fact — so recovery knows whether a backup dir
1502
- // will exist. A migration off the old `<owner>-<repo>` name records that
1503
- // path so recovery can restore the parked old-name dir. If the process is
1504
- // killed anywhere past this point, the next add's recovery pass uses this
1505
- // record to roll forward or back.
1506
- const migratingOldName = existing !== undefined && existing.path !== folder;
1507
- const journalBase = {
1508
- version: 1,
1509
- phase: 'applying',
1510
- source,
1511
- sha,
1512
- folder,
1513
- stagingId,
1514
- hadDest: existsSync(dest),
1515
- ...(migratingOldName ? { oldNamePath: existing.path } : {}),
1516
- defsDir: resolve(defsDir),
1517
- ref,
1518
- startedAt: nowMs(),
1519
- };
1520
- writeAddJournal(journalPath, journalBase);
1521
- let handle;
1522
- try {
1523
- handle = commitInstall(defsDir, folder, stagingDir);
1524
- }
1525
- catch (e) {
1526
- // commitInstall's own swap-then-rollback double-fault left the only copy
1527
- // of previous content under the staging root — keep it (see the `finally`).
1528
- if (e instanceof RollbackFailedError)
1529
- preserveStagingRoot = true;
1530
- throw e;
1531
- }
1532
- if (existing && existing.path !== folder) {
1533
- // Migrating off the old `<owner>-<repo>` scheme: park (not delete) the old
1534
- // dir so a failure below can restore it. Finalized away on success. This
1535
- // park now sits INSIDE the recoverable region — a park failure must roll
1536
- // the committed swap back too, exactly like the lockfile-write failure
1537
- // below (a bare park could otherwise strand the swap and leave the next
1538
- // `add` refusing on an ownership mismatch).
1539
- try {
1540
- parkOldNameDir(handle, defsDir, existing.path);
1541
- }
1542
- catch (e) {
1543
- try {
1544
- rollbackInstallCommit(handle);
1545
- }
1546
- catch (rollbackErr) {
1547
- // Double fault: parking the old dir failed AND rolling the committed
1548
- // swap back failed. Nothing of value sits under the staging root here —
1549
- // the staging dir was consumed by the swap, and this migration branch
1550
- // never has a backup (`dest` cannot pre-exist; see the ownership refusal
1551
- // above). The old-name dir was never moved (the park is a single atomic
1552
- // rename recorded only on success) so it stays intact at its original
1553
- // path, and the stranded item is the NEW content still at `dest`. LEAVE
1554
- // the journal (phase `applying`) so the next add's recovery rolls the
1555
- // swap back (case (c): discards `dest`) before anything clears the
1556
- // staging root, mirroring the lockfile-write double fault below.
1557
- preserveStagingRoot = true;
1558
- throw new CliError(`could not migrate ${source} off old-name directory '${existing.path}' (${e.message}) ` +
1559
- `and rolling the install back failed too (${rollbackErr.message}); ` +
1560
- `the old-name directory was never moved and is intact at ${join(defsDir, existing.path)}, ` +
1561
- `and the newly installed content is stranded at ${dest} — ` +
1562
- `the next owenloop add will recover automatically (discarding the stranded content and leaving the previous install in place)`);
1563
- }
1564
- // Directory state restored in-process — nothing left to recover, so drop
1565
- // the journal before surfacing the (single-fault) failure.
1566
- removeAddJournal(journalPath);
1567
- throw new CliError(`could not migrate ${source} off old-name directory '${existing.path}': ${e.message} — ` +
1568
- `install rolled back, previous state restored`);
1569
- }
1570
- }
1571
- const entry = { source, ref, sha, installedAt: nowMs(), path: folder, files: written };
1572
- lf.installed[source] = entry;
1573
- try {
1574
- writeLockfile(lockfilePath, lf);
1575
- }
1576
- catch (e) {
1577
- try {
1578
- rollbackInstallCommit(handle);
1579
- }
1580
- catch (rollbackErr) {
1581
- // Double fault: the ledger write failed AND restoring the directory
1582
- // failed. The previous content is now parked under the staging root —
1583
- // preserve it past the `finally` and LEAVE the journal (phase
1584
- // `applying`, ledger not committed) so the next add's recovery restores
1585
- // the previous state before anything clears the staging root.
1586
- preserveStagingRoot = true;
1587
- throw new CliError(`could not record install of ${source} in ${lockfilePath} (${e.message}) ` +
1588
- `and rolling the install back failed too (${rollbackErr.message}); ` +
1589
- `previous content preserved under ${stagingRoot} — recover it before running add again ` +
1590
- `(the next owenloop add will attempt recovery automatically; leaving it, that dir is cleared as debris)`);
1591
- }
1592
- // Directory state restored in-process — drop the journal before surfacing
1593
- // the (single-fault) failure.
1594
- removeAddJournal(journalPath);
1595
- throw new CliError(`could not record install of ${source} in ${lockfilePath}: ${e.message} — ` +
1596
- `install rolled back, previous state restored`);
1597
- }
1598
- // The ledger write is the durable commit point: past here a crash rolls
1599
- // FORWARD. Record that in the journal (phase `finalizing`) so recovery
1600
- // finishes the install rather than tearing it down, then finalize and drop
1601
- // the journal now that there is nothing left to recover.
1602
- writeAddJournal(journalPath, { ...journalBase, phase: 'finalizing' });
1603
- finalizeInstallCommit(handle);
1604
- removeAddJournal(journalPath);
1605
- // 7. Report.
1606
- print(io, {
1607
- ok: true,
1608
- source,
1609
- ref,
1610
- sha,
1611
- path: folder,
1612
- installed: written.length,
1613
- defs: [...staged.values()].map((d) => d.name).sort(),
1614
- hint: `installed workflows are now discoverable by default — run e.g. \`owenloop create ${[...staged.values()].map((d) => d.name).sort()[0] ?? '<def-name>'}\` with no --defs flag; for an explicit --defs, point it at ${folder}`,
1615
- });
1616
- return 0;
1617
- }
1618
- finally {
1619
- // On success the staging dir was renamed away and its retained backups
1620
- // finalized; on failure this clears whatever staging debris is left. The one
1621
- // exception is a rollback double-fault (`preserveStagingRoot`), where the
1622
- // only surviving copy of the previous content is parked here — leave it for
1623
- // the user to recover (the next add clears it as debris). Then release the lock.
1624
- if (!preserveStagingRoot)
1625
- rmSync(stagingRoot, { recursive: true, force: true });
1626
- releaseInstallLock(lock);
1627
- }
1628
- }
1629
- /**
1630
- * `owenloop add --recover`: an OFFLINE, network-free entry point to the same
1631
- * `recoverInterruptedInstall` the normal add path runs inline. `dispatchAdd`
1632
- * branches here at its very top, before `parseRepoSpec` and before the SHA and
1633
- * tarball fetches — so this path can never touch the network. The normal add
1634
- * path already runs recovery inline (belt-and-suspenders); this exists only so a
1635
- * machine that crashed mid-install and is now offline can finish/undo the
1636
- * interrupted install without waiting for the network to return.
1637
- *
1638
- * The lock scope here is recovery-ONLY: acquire `.owenloop/add.lock`, run
1639
- * recovery, release. There is no fetch to keep outside the lock (the reason the
1640
- * normal path acquires the lock only after the download), so the whole
1641
- * short local operation runs under it. No `--db`/store open — recovery never
1642
- * reads the store. Refusals (bad/mismatched/contradictory journal) throw and
1643
- * propagate to `mainAsync`'s catch as `error: ...`, exit 1, mutating nothing —
1644
- * and unlike the inline path there is no `preserveStagingRoot` dance, because
1645
- * this path never rmSyncs the staging root itself, so a refusal naturally leaves
1646
- * the journal, staging root, and dest untouched as evidence.
1647
- */
1648
- async function dispatchAddRecover(io, args) {
1649
- // With --recover the owner/repo positional is optional; a supplied spec is
1650
- // ambiguous ("recover then install"?), so refuse rather than guess — the
1651
- // normal add path runs recovery inline anyway, so "recover then install" is
1652
- // just `owenloop add owner/repo`.
1653
- if (args.positionals[1] !== undefined) {
1654
- throw new CliError('--recover takes no repository argument — run recovery alone, then re-run add');
1655
- }
1656
- // Resolve paths EXACTLY as dispatchAdd does — same defsDir/lock/journal
1657
- // derivation — so recovery acts on the same tree a real add would. No fetch
1658
- // reference, no store open.
1659
- const defsOverride = last(args, 'defs') ?? io.env.OWENLOOP_DEFS;
1660
- const defsDir = defsOverride ?? join(io.cwd, 'workflows');
1661
- const lockfilePath = join(io.cwd, '.owenloop', 'installed.json');
1662
- const installLockPath = join(io.cwd, '.owenloop', 'add.lock');
1663
- const journalPath = join(io.cwd, '.owenloop', ADD_JOURNAL_FILENAME);
1664
- // Mirror the SEC-3 symlink guards from the normal path (same order, same
1665
- // rationale): `.owenloop` is written by the lock acquire; the default defsDir
1666
- // is mutated-through by recovery. An explicit --defs/OWENLOOP_DEFS is operator
1667
- // intent, not repo content, so it is not symlink-guarded (matching dispatchAdd).
1668
- mkdirRefusingSymlink(join(io.cwd, '.owenloop'));
1669
- if (defsOverride === undefined)
1670
- mkdirRefusingSymlink(defsDir);
1671
- const lock = await acquireInstallLock(installLockPath);
1672
- let outcome;
1673
- try {
1674
- outcome = recoverInterruptedInstall({ defsDir, journalPath, lockfilePath });
1675
- }
1676
- finally {
1677
- releaseInstallLock(lock);
1678
- }
1679
- switch (outcome) {
1680
- case 'no-journal':
1681
- print(io, { ok: true, recovered: false, message: 'nothing to recover — no interrupted install found' });
1682
- return 0;
1683
- case 'rolled-forward':
1684
- print(io, {
1685
- ok: true,
1686
- recovered: true,
1687
- outcome: 'rolled-forward',
1688
- message: 'interrupted install completed (rolled forward)',
1689
- });
1690
- return 0;
1691
- case 'rolled-back':
1692
- print(io, {
1693
- ok: true,
1694
- recovered: true,
1695
- outcome: 'rolled-back',
1696
- message: 'interrupted install undone — previous state restored (or already consistent)',
1697
- });
1698
- return 0;
1699
- }
1700
- }
1701
- // ---- hub onboarding: login / logout / connect / push -------------------------
1702
- /**
1703
- * Resolve the target hub origin: `--hub` > `OWENLOOP_HUB` env > the default
1704
- * production hub. Normalized (scheme required, trailing slash/path stripped) so
1705
- * it can serve as a stable credential-store key and project binding value.
1706
- */
1707
- const DEFAULT_HUB = 'https://api.owenloop.com';
1708
- function resolveHub(io, args) {
1709
- const raw = last(args, 'hub') ?? io.env.OWENLOOP_HUB ?? DEFAULT_HUB;
1710
- try {
1711
- return normalizeOrigin(raw);
1712
- }
1713
- catch (e) {
1714
- throw new CliError(e.message);
1715
- }
1716
- }
1717
- /**
1718
- * Parse `--as <human | agent | agent:NAME>` into a `CredentialSlotSelector`.
1719
- * Absent `--as` means the **human** slot — the everyday interactive case.
1720
- * A malformed value (or an invalid account name, validated by `credentialSlot`)
1721
- * is a usage error, never a silent coercion to some other slot.
1722
- */
1723
- function resolveSlot(args) {
1724
- const raw = last(args, 'as');
1725
- const sel = parseSlotArg(raw);
1726
- // Validate eagerly so a bad account name fails before any network or store
1727
- // access, with the same wording every later call site would produce.
1728
- try {
1729
- credentialSlot(sel);
1730
- }
1731
- catch (e) {
1732
- throw new CliError(`--as: ${e.message}`);
1733
- }
1734
- return sel;
1735
- }
1736
- function parseSlotArg(raw) {
1737
- if (raw === undefined)
1738
- return { principal: 'human' };
1739
- if (raw === 'human')
1740
- return { principal: 'human' };
1741
- if (raw === 'agent')
1742
- return { principal: 'agent' };
1743
- if (raw.startsWith('agent:'))
1744
- return { principal: 'agent', account: raw.slice('agent:'.length) };
1745
- throw new CliError(`--as: unrecognized slot '${raw}' — expected 'human', 'agent', or 'agent:<account>'`);
1746
- }
1747
- /**
1748
- * The "nothing stored here" message for a read that missed. It names the SLOT,
1749
- * not just the origin — a credential may well exist for this hub under another
1750
- * principal, and the fix is `--as`, not another `login`.
1751
- */
1752
- function emptySlotMessage(origin, slot) {
1753
- const name = credentialSlot(slot);
1754
- return `no stored credential for ${origin} in slot \`${name}\` — run \`owenloop login\` (or pass --as agent:<name>)`;
1755
- }
1756
- /**
1757
- * Read the stored credential for `origin` in `slot`. Thin wrapper over the
1758
- * shared `readStoredCredential` in `hub.ts` (the same implementation the public
1759
- * package export uses), threading the CLI's injected `env`/`keychain`. Callers
1760
- * pass a pre-normalized origin (`resolveHub` output); the wrapper's
1761
- * normalization is idempotent, so CLI behavior is unchanged. REL-6 no-fallback
1762
- * and corrupt-entry-as-absent semantics live in `hub.ts`.
1763
- */
1764
- function readCredential(io, origin, slot) {
1765
- return readStoredCredential(origin, { ...slot, env: io.env, keychain: io.keychain });
1766
- }
1767
- /**
1768
- * GET `path` on `origin` with a bearer credential, refreshing an expiring
1769
- * oauth token first and retrying exactly once after a 401→refresh for oauth.
1770
- * Returns the raw response plus the credential actually used (possibly
1771
- * refreshed), so the caller can both persist it and apply its own hard-error
1772
- * semantics on the final status (a 401 after the retry, a non-2xx, etc. —
1773
- * left to the caller since the wording differs slightly by context).
1774
- */
1775
- async function authedGet(io, origin, slot, cred, path, persist = true) {
1776
- let current = await ensureFreshOAuth(io, origin, slot, cred, persist);
1777
- let res = await hubFetch(io, resolveEndpoint(origin, path), {
1778
- headers: { Authorization: authHeader(current), Accept: 'application/json' },
1779
- });
1780
- if (res.status === 401 && current.kind === 'oauth') {
1781
- current = await refreshOAuth(io, origin, slot, current, persist);
1782
- res = await hubFetch(io, resolveEndpoint(origin, path), {
1783
- headers: { Authorization: authHeader(current), Accept: 'application/json' },
1784
- });
1785
- }
1786
- return { res, cred: current };
1787
- }
1788
- /**
1789
- * A 401 on an agent token is a hard "revoked/invalid" error; a 401 on any
1790
- * other credential kind (after `authedGet`'s one refresh-and-retry) is a hard
1791
- * "credential rejected" error; any other non-2xx is a generic hub-rejected
1792
- * error naming the status. Shared by `verifyCredential` and `dispatchPush`'s
1793
- * server-list fetch so both surfaces the same wording for the same failure.
1794
- */
1795
- function assertAuthOk(res, cred, origin) {
1796
- if (res.status === 401) {
1797
- if (cred.kind === 'agent') {
1798
- throw new CliError('token revoked or invalid — re-mint it in the console or run `owenloop login`');
1799
- }
1800
- throw new CliError('credential rejected by the hub — run `owenloop login`');
1801
- }
1802
- if (!res.ok) {
1803
- throw new CliError(`hub ${origin} rejected the credential (HTTP ${res.status})`);
1804
- }
1805
- }
1806
- /**
1807
- * Verify a credential works against the hub's `GET /api/whoami` (any 2xx =
1808
- * authenticated) and return the identity it names. Whoami carries no RBAC
1809
- * verb, so this proves *authentication*, not any particular scope (e.g.
1810
- * `list`) — a token lacking a scope `push` later needs still fails there,
1811
- * with the hub's own 401/403, which is acceptable and honest. Refreshes an
1812
- * expiring oauth token first, and retries exactly once after a 401→refresh
1813
- * for oauth; a 401 on an agent token is a hard "revoked/invalid" error.
1814
- * Returns the credential actually used (possibly refreshed), so the caller
1815
- * can persist it, alongside the parsed identity.
1816
- *
1817
- * `persist` (default true) controls whether an in-flight refresh writes its
1818
- * new token to storage immediately (see `refreshOAuth`'s doc comment) —
1819
- * `dispatchLogin`'s OAuth branch passes `false` because the credential being
1820
- * verified here hasn't been stored yet at all; a refresh mid-verify must not
1821
- * sneak a not-yet-proven credential onto disk ahead of the pass/fail verdict.
1822
- */
1823
- async function verifyCredential(io, origin, slot, cred, persist = true) {
1824
- const { res, cred: current } = await authedGet(io, origin, slot, cred, '/api/whoami', persist);
1825
- assertAuthOk(res, current, origin);
1826
- const body = await res.json();
1827
- return { cred: current, identity: asWhoami(body) };
1828
- }
1829
- /**
1830
- * `owenloop login` — authenticate the CLI against a hub. Primary flow is a
1831
- * loopback OAuth auth-code + PKCE(S256) exchange; `--with-token` reads an
1832
- * `olp_`/`mcpat_` token from stdin instead (never argv). Either way the
1833
- * credential is verified before it is stored, and stored in the OS keychain or
1834
- * a 0600 file — never plaintext in the repo or `.env`.
1835
- *
1836
- * The SLOT the credential lands in follows the credential KIND, with `--as`
1837
- * naming the agent account: a human credential (loopback `oauth`, or a pasted
1838
- * `mcpat_`) writes `human`; a pasted `olp_` agent token writes
1839
- * `agent:<account>` (`default` unless `--as agent:NAME`). A `--as` that
1840
- * contradicts the credential kind is a usage error, not a silent coercion —
1841
- * that is what keeps the agent slot holding agent keys.
1842
- *
1843
- * Refused outright while an external credential command is configured: that
1844
- * command, not the local store, is what every read consults, so there is nothing
1845
- * for `login` to usefully write. The check is here — before the "did a
1846
- * credential already exist?" probe, which would otherwise RUN the command and
1847
- * report its failure instead of this far more actionable reason — with
1848
- * `storeCredential`'s own throw kept as the invariant backstop for any other
1849
- * write path.
1850
- */
1851
- async function dispatchLogin(io, args) {
1852
- const origin = resolveHub(io, args);
1853
- const asked = resolveSlot(args);
1854
- const asGiven = last(args, 'as') !== undefined;
1855
- if (externalCredentialCommand(io.env) !== undefined) {
1856
- throw new CliError('an external credential command is configured (OWENLOOP_CREDENTIAL_COMMAND), so it — not the ' +
1857
- 'local store — supplies credentials for this hub; unset it to use `owenloop login`');
1858
- }
1859
- if (flag(args, 'with-token')) {
1860
- const readStdin = io.readStdin ?? defaultReadStdin;
1861
- const token = (await readStdin()).trim();
1862
- if (token === '')
1863
- throw new CliError('no token on stdin (pipe the token in, e.g. `pbpaste | owenloop login --with-token`)');
1864
- let cred;
1865
- if (token.startsWith('olp_'))
1866
- cred = { kind: 'agent', accessToken: token };
1867
- else if (token.startsWith('mcpat_'))
1868
- cred = { kind: 'oauth-pasted', accessToken: token };
1869
- else
1870
- throw new CliError('unrecognized token — expected an `olp_` agent token or an `mcpat_` access token');
1871
- // Contradictions are usage errors, refused BEFORE any network call so
1872
- // nothing is verified or stored under a slot the token does not belong in.
1873
- if (cred.kind === 'agent' && asGiven && asked.principal === 'human') {
1874
- throw new CliError('an `olp_` agent token cannot be stored in the `human` slot — drop `--as human`, or pass `--as agent[:<account>]`');
1875
- }
1876
- if (cred.kind !== 'agent' && asked.principal === 'agent') {
1877
- throw new CliError(`a ${cred.kind} credential is a human credential and cannot be stored in the \`${credentialSlot(asked)}\` slot — drop \`--as\`, or paste an \`olp_\` agent token`);
1878
- }
1879
- const slot = cred.kind === 'agent' ? { principal: 'agent', ...(asked.principal === 'agent' && asked.account !== undefined ? { account: asked.account } : {}) } : { principal: 'human' };
1880
- const existed = readCredential(io, origin, slot) !== null;
1881
- const { identity } = await verifyCredential(io, origin, slot, cred); // never store an unverified token
1882
- const storage = await storeCredential(io, origin, slot, cred);
1883
- print(io, {
1884
- ok: true,
1885
- hub: origin,
1886
- kind: cred.kind,
1887
- slot: credentialSlot(slot),
1888
- storage,
1889
- replaced: existed,
1890
- org: identity.orgName,
1891
- orgId: identity.orgId,
1892
- identity: identity.actor,
1893
- ...(identity.email ? { email: identity.email } : {}),
1894
- });
1895
- return 0;
1896
- }
1897
- // Loopback OAuth always yields a HUMAN credential — `--as agent*` on this
1898
- // flow is a contradiction, refused before the browser is opened.
1899
- if (asked.principal === 'agent') {
1900
- throw new CliError(`the loopback OAuth login produces a human credential and cannot be stored in the \`${credentialSlot(asked)}\` slot — drop \`--as\`, or use \`login --with-token\` with an \`olp_\` agent token`);
1901
- }
1902
- const r = await runLoopbackOAuth(io, origin);
1903
- print(io, {
1904
- ok: true,
1905
- hub: origin,
1906
- kind: r.cred.kind,
1907
- slot: credentialSlot({ principal: 'human' }),
1908
- storage: r.storage,
1909
- replaced: r.replaced,
1910
- org: r.identity.orgName,
1911
- orgId: r.identity.orgId,
1912
- identity: r.identity.actor,
1913
- ...(r.identity.email ? { email: r.identity.email } : {}),
1914
- });
1915
- return 0;
1916
- }
1917
- /**
1918
- * The loopback OAuth auth-code + PKCE(S256) round-trip, extracted verbatim from
1919
- * `dispatchLogin` so `setup`'s human-login gate (step 2) runs the exact same
1920
- * flow — one implementation, one behavior. Always targets the **human** slot
1921
- * (the only slot loopback OAuth can produce). Binds a single-use 127.0.0.1:0
1922
- * catcher, discovers the hub's OAuth metadata, dynamically registers a client
1923
- * for the concrete redirect URI, opens the browser, waits for the callback,
1924
- * exchanges the code, verifies the resulting credential against `whoami`
1925
- * (persist=false — an unverified token must never reach storage ahead of its
1926
- * pass/fail verdict), then stores it. Returns whether a human credential was
1927
- * already present (`replaced`), the stored credential, the verified identity,
1928
- * and the storage backend actually used.
1929
- */
1930
- async function runLoopbackOAuth(io, origin) {
1931
- const slot = { principal: 'human' };
1932
- const existed = readCredential(io, origin, slot) !== null;
1933
- // Loopback OAuth: bind the port FIRST (the service matches redirect URIs by
1934
- // exact string — no RFC 8252 variable-port allowance — so the DCR must carry
1935
- // the concrete 127.0.0.1:<port> callback).
1936
- const { verifier, challenge } = pkcePair();
1937
- const state = randomState();
1938
- const timeoutOverride = Number(io.env.OWENLOOP_LOGIN_TIMEOUT_MS);
1939
- const timeoutMs = Number.isFinite(timeoutOverride) && timeoutOverride > 0 ? timeoutOverride : undefined;
1940
- const { server, port, waitForCallback, close } = await startLoopbackServer(state, timeoutMs);
1941
- try {
1942
- const redirectUri = `http://127.0.0.1:${port}/callback`;
1943
- const meta = await discoverMetadata(io, origin);
1944
- if (!meta.authorization_endpoint || !meta.token_endpoint || !meta.registration_endpoint) {
1945
- throw new CliError(`hub ${origin} does not advertise the OAuth endpoints login needs`);
1946
- }
1947
- const clientId = await registerClient(io, origin, meta.registration_endpoint, redirectUri);
1948
- const authUrl = new URL(resolveEndpoint(origin, meta.authorization_endpoint));
1949
- authUrl.searchParams.set('response_type', 'code');
1950
- authUrl.searchParams.set('client_id', clientId);
1951
- authUrl.searchParams.set('redirect_uri', redirectUri);
1952
- authUrl.searchParams.set('code_challenge', challenge);
1953
- authUrl.searchParams.set('code_challenge_method', 'S256');
1954
- authUrl.searchParams.set('state', state);
1955
- io.err(`Opening your browser to sign in. If it does not open, visit:\n ${authUrl.toString()}`);
1956
- (io.openUrl ?? defaultOpenUrl)(authUrl.toString());
1957
- const { code } = await waitForCallback;
1958
- const exchanged = await exchangeCode(io, origin, meta.token_endpoint, {
1959
- code,
1960
- clientId,
1961
- redirectUri,
1962
- verifier,
1963
- });
1964
- const { cred, identity } = await verifyCredential(io, origin, slot, exchanged, false); // never store an unverified token
1965
- const storage = await storeCredential(io, origin, slot, cred);
1966
- return { cred, identity, storage, replaced: existed };
1967
- }
1968
- finally {
1969
- void server;
1970
- close();
1971
- }
1972
- }
1973
- const LOGIN_TIMEOUT_MS = 5 * 60 * 1000;
1974
- /**
1975
- * Bind a single-use loopback catcher on 127.0.0.1:0 that resolves on the OAuth
1976
- * callback. `timeoutMs` overrides the 5-minute default (test knob, threaded
1977
- * from `OWENLOOP_LOGIN_TIMEOUT_MS` by `dispatchLogin`, consistent with the
1978
- * project's other `OWENLOOP_*` test-only env knobs).
1979
- */
1980
- async function startLoopbackServer(expectedState, timeoutMs = LOGIN_TIMEOUT_MS) {
1981
- const loginHtml = (msg) => `<!doctype html><meta charset="utf-8"><title>owenloop</title><body style="font-family:system-ui;padding:2rem"><p>${msg}</p></body>`;
1982
- let resolveCb;
1983
- let rejectCb;
1984
- const waitForCallback = new Promise((res, rej) => {
1985
- resolveCb = res;
1986
- rejectCb = rej;
1987
- });
1988
- // The timeout timer (below) can fire — and reject waitForCallback — before
1989
- // dispatchLogin reaches its `await waitForCallback` (it awaits
1990
- // discoverMetadata/registerClient first), which would otherwise surface as
1991
- // an unhandled rejection and crash the process. This no-op .catch marks the
1992
- // rejection handled without consuming it; the later real `await
1993
- // waitForCallback` in dispatchLogin still sees and throws the same error.
1994
- waitForCallback.catch(() => { });
1995
- const server = createServer((req, res) => {
1996
- const u = new URL(req.url ?? '/', 'http://127.0.0.1');
1997
- if (u.pathname !== '/callback') {
1998
- res.writeHead(404);
1999
- res.end();
2000
- return;
2001
- }
2002
- const error = u.searchParams.get('error');
2003
- const code = u.searchParams.get('code');
2004
- const gotState = u.searchParams.get('state');
2005
- if (error) {
2006
- res.writeHead(400, { 'Content-Type': 'text/html' });
2007
- res.end(loginHtml('Login failed. You can close this tab.'));
2008
- rejectCb(new CliError(`login denied by the hub: ${error}`));
2009
- return;
2010
- }
2011
- if (gotState !== expectedState) {
2012
- res.writeHead(400, { 'Content-Type': 'text/html' });
2013
- res.end(loginHtml('State mismatch. You can close this tab.'));
2014
- rejectCb(new CliError('state mismatch on the OAuth callback — possible CSRF; aborting login'));
2015
- return;
2016
- }
2017
- if (!code) {
2018
- res.writeHead(400, { 'Content-Type': 'text/html' });
2019
- res.end(loginHtml('Missing authorization code. You can close this tab.'));
2020
- rejectCb(new CliError('OAuth callback carried no authorization code'));
2021
- return;
2022
- }
2023
- res.writeHead(200, { 'Content-Type': 'text/html' });
2024
- res.end(loginHtml('Login complete — return to your terminal.'));
2025
- resolveCb({ code });
2026
- });
2027
- const timer = setTimeout(() => {
2028
- const human = timeoutMs % 60_000 === 0 ? `${timeoutMs / 60_000} minutes` : `${timeoutMs}ms`;
2029
- rejectCb(new CliError(`login timed out after ${human} waiting for the browser callback`));
2030
- }, timeoutMs);
2031
- timer.unref?.();
2032
- await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve));
2033
- const port = server.address().port;
2034
- return {
2035
- server,
2036
- port,
2037
- waitForCallback,
2038
- close: () => {
2039
- clearTimeout(timer);
2040
- server.close();
2041
- },
2042
- };
2043
- }
2044
- /** DCR a public client (no client secret) with the exact loopback redirect URI. */
2045
- async function registerClient(io, origin, registrationEndpoint, redirectUri) {
2046
- const res = await hubFetch(io, resolveEndpoint(origin, registrationEndpoint), {
2047
- method: 'POST',
2048
- headers: { 'Content-Type': 'application/json' },
2049
- body: JSON.stringify({
2050
- client_name: 'owenloop CLI',
2051
- redirect_uris: [redirectUri],
2052
- token_endpoint_auth_method: 'none',
2053
- grant_types: ['authorization_code', 'refresh_token'],
2054
- response_types: ['code'],
2055
- }),
2056
- });
2057
- if (!res.ok) {
2058
- throw new CliError(`dynamic client registration failed at ${origin} (HTTP ${res.status})`);
2059
- }
2060
- const json = (await res.json());
2061
- if (typeof json.client_id !== 'string') {
2062
- throw new CliError('dynamic client registration returned no client_id');
2063
- }
2064
- return json.client_id;
2065
- }
2066
- /** Exchange an auth code for tokens (form-encoded, with the PKCE verifier). */
2067
- async function exchangeCode(io, origin, tokenEndpoint, p) {
2068
- const body = new URLSearchParams({
2069
- grant_type: 'authorization_code',
2070
- code: p.code,
2071
- client_id: p.clientId,
2072
- redirect_uri: p.redirectUri,
2073
- code_verifier: p.verifier,
2074
- });
2075
- const res = await hubFetch(io, resolveEndpoint(origin, tokenEndpoint), {
2076
- method: 'POST',
2077
- headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
2078
- body: body.toString(),
2079
- });
2080
- if (!res.ok) {
2081
- throw new CliError(`token exchange failed at ${origin} (HTTP ${res.status})`);
2082
- }
2083
- const json = (await res.json());
2084
- if (typeof json.access_token !== 'string' || typeof json.refresh_token !== 'string') {
2085
- throw new CliError('token exchange returned an incomplete token set');
2086
- }
2087
- const expiresIn = typeof json.expires_in === 'number' ? json.expires_in : 3600;
2088
- return {
2089
- kind: 'oauth',
2090
- accessToken: json.access_token,
2091
- refreshToken: json.refresh_token,
2092
- expiresAt: nowMs() + expiresIn * 1000,
2093
- clientId: p.clientId,
2094
- };
2095
- }
2096
- /**
2097
- * `owenloop logout` — delete the stored credential for a hub, in ONE slot
2098
- * (`--as`, default `human`), from both the keychain and the file store. Cheap;
2099
- * completes the credential lifecycle. Other slots for the same origin are left
2100
- * alone: the keychain cannot enumerate its accounts, so a blanket
2101
- * clear-everything is not implementable and is not faked.
2102
- */
2103
- async function dispatchLogout(io, args) {
2104
- const origin = resolveHub(io, args);
2105
- const slot = resolveSlot(args);
2106
- const removed = await deleteCredential(io, origin, slot);
2107
- const slotName = credentialSlot(slot);
2108
- if (!removed) {
2109
- io.err(`no stored credential for ${origin} in slot \`${slotName}\` — another slot may hold one (see --as)`);
2110
- }
2111
- print(io, { ok: true, hub: origin, slot: slotName, removed });
2112
- return 0;
2113
- }
2114
- /**
2115
- * `owenloop connect` — bind the current project to a hub (writes
2116
- * `.owenloop/hub.json`) and verify the stored credential works. Requires a
2117
- * prior `owenloop login` for the resolved origin. `.owenloop/hub.json` is a
2118
- * pure binding — there's no push state to preserve or reset across a rebind
2119
- * (see `HubBinding`); `switchedFrom` is still reported when the origin
2120
- * changes so the caller notices the rebind.
2121
- */
2122
- async function dispatchConnect(io, args) {
2123
- const origin = resolveHub(io, args);
2124
- const slot = resolveSlot(args);
2125
- const cred = readCredential(io, origin, slot);
2126
- if (!cred)
2127
- throw new CliError(emptySlotMessage(origin, slot));
2128
- const { identity } = await verifyCredential(io, origin, slot, cred);
2129
- const path = hubBindingPath(io.cwd);
2130
- const existing = readHubBinding(path);
2131
- const switched = existing !== null && existing.hub !== origin;
2132
- const binding = { version: 1, hub: origin };
2133
- writeHubBinding(path, binding);
2134
- print(io, {
2135
- ok: true,
2136
- hub: origin,
2137
- ...(switched ? { switchedFrom: existing.hub } : {}),
2138
- org: identity.orgName,
2139
- orgId: identity.orgId,
2140
- identity: identity.actor,
2141
- ...(identity.email ? { email: identity.email } : {}),
2142
- });
2143
- return 0;
2144
- }
2145
- /**
2146
- * `owenloop push [<defName>...] [--force] [--dry-run]` — publish local workflow
2147
- * defs to the bound hub, diffed against the hub's own def `hash`
2148
- * (`GET /api/workflows` — see `computeServerDiff`), never a client-side
2149
- * ledger. Mirrors `add`'s all-or-nothing client-side validation gate before
2150
- * any network write; server-side failures mid-batch record what landed and
2151
- * exit 1. `POST /api/create_workflow` is itself idempotent, so even a wrong
2152
- * "changed" verdict (e.g. from engine-version drift between this CLI and the
2153
- * hub) is harmless — it just costs one extra round-trip that the server
2154
- * reports back as a no-op.
2155
- */
2156
- async function dispatchPush(io, args) {
2157
- const defsDir = last(args, 'defs') ?? io.env.OWENLOOP_DEFS ?? join(io.cwd, 'workflows');
2158
- const dryRun = flag(args, 'dry-run');
2159
- const force = flag(args, 'force');
2160
- const slot = resolveSlot(args);
2161
- // Require a project binding.
2162
- const bindingPath = hubBindingPath(io.cwd);
2163
- const binding = readHubBinding(bindingPath);
2164
- if (!binding)
2165
- throw new CliError('this project is not bound to a hub — run `owenloop connect` first');
2166
- // Defense in depth (SEC-2): a hub.json written by an older CLI could carry a
2167
- // remote-http origin that predates the transport policy, and dispatchPush uses
2168
- // it verbatim as the request origin. Validate the persisted binding at USE
2169
- // time — normalizeOrigin enforces https-except-loopback. This check lives
2170
- // here, NOT inside readHubBinding: dispatchConnect reads the existing binding
2171
- // only to report switchedFrom, and a read-time throw would deadlock rebinding
2172
- // AWAY from a bad origin. Leave readHubBinding shape-validation-only.
2173
- let origin;
2174
- try {
2175
- origin = normalizeOrigin(binding.hub);
2176
- }
2177
- catch (e) {
2178
- throw new CliError(`${e.message} — re-run \`owenloop connect\` to rebind`);
2179
- }
2180
- // A --hub that disagrees with the binding is a mistake, not a silent override.
2181
- const hubArg = last(args, 'hub');
2182
- if (hubArg !== undefined) {
2183
- const requested = normalizeOrigin(hubArg);
2184
- if (requested !== origin) {
2185
- throw new CliError(`this project is bound to ${origin}, not ${requested} — re-run \`owenloop connect\` to rebind`);
2186
- }
2187
- }
2188
- let cred = readCredential(io, origin, slot);
2189
- if (!cred)
2190
- throw new CliError(emptySlotMessage(origin, slot));
2191
- // Load defs (same machinery as lint/add).
2192
- if (!existsSync(defsDir))
2193
- throw new CliError(`defs directory not found: ${defsDir}`);
2194
- const failures = [];
2195
- const allDefs = loadDefsRaw(defsDir, failures);
2196
- // Narrow to positional names, if any (error on an unknown name).
2197
- const requested = args.positionals.slice(1);
2198
- let selected;
2199
- if (requested.length > 0) {
2200
- selected = [];
2201
- for (const name of requested) {
2202
- const def = allDefs.get(name);
2203
- if (!def) {
2204
- throw new CliError(`unknown workflow definition '${name}' (looked in ${defsDir})${failureNote(failures)}`);
2205
- }
2206
- selected.push(def);
2207
- }
2208
- }
2209
- else {
2210
- selected = [...allDefs.values()];
2211
- }
2212
- if (selected.length === 0) {
2213
- throw new CliError(`nothing to push — no workflow definitions found in ${defsDir}`);
2214
- }
2215
- // Client-side validation gate — all-or-nothing, mirroring dispatchAdd exactly.
2216
- // Any failure aborts the entire push; nothing is sent.
2217
- const reasons = failures.map((f) => `${f.file}: ${f.error}`);
2218
- for (const def of selected) {
2219
- const lintResult = lintDef(def);
2220
- reasons.push(...lintResult.errors.map((e) => `${def.name}: ${e}`));
2221
- reasons.push(...validateDef(def).map((e) => `${def.name}: ${e}`));
2222
- const report = modelCheck(def, { assumeProvided: true });
2223
- const hasDefiniteDefect = report.invariantViolations.length > 0 ||
2224
- (!report.bounded && report.deadlocks.length > 0);
2225
- if (hasDefiniteDefect) {
2226
- reasons.push(`${def.name}: definite defects found (${report.invariantViolations.length} invariant violation(s), ` +
2227
- `${report.deadlocks.length} true deadlock(s))`);
2228
- }
2229
- }
2230
- // Assemble the push candidates: verbatim source yaml + the server-canonical
2231
- // content hash (hashDefForHub). Defs whose file uses include: are not
2232
- // hub-pushable (the service's create_workflow parses without include
2233
- // expansion, and a re-serialized expanded def is not round-trippable) —
2234
- // refuse them with a clear per-def reason. Same for bodyFile: — hashDefForHub
2235
- // parses with no baseDir (matching the server's own computation), which
2236
- // throws a DefError naming bodyFile for such a def; catch that specific
2237
- // failure and refuse the def pre-push rather than letting it read as a
2238
- // generic error (the server would reject the raw-YAML push anyway).
2239
- const candidates = [];
2240
- for (const def of selected) {
2241
- if (!def.dir) {
2242
- reasons.push(`${def.name}: has no source file on disk to push`);
2243
- continue;
2244
- }
2245
- const yaml = readFileSync(def.dir, 'utf8');
2246
- let usesInclude = false;
2247
- try {
2248
- const rawDef = buildDef(parseYaml(yaml), basename(def.dir), dirname(def.dir));
2249
- usesInclude = (rawDef._includes?.length ?? 0) > 0;
2250
- }
2251
- catch {
2252
- // A shape error here would already have surfaced via the validation gate;
2253
- // treat an unexpected re-parse failure conservatively as pushable-as-is.
2254
- }
2255
- if (usesInclude) {
2256
- reasons.push(`${def.name}: uses include:, not hub-pushable yet`);
2257
- continue;
2258
- }
2259
- let hash;
2260
- try {
2261
- hash = hashDefForHub(yaml);
2262
- }
2263
- catch (e) {
2264
- if (e instanceof DefError && /bodyFile/.test(e.message)) {
2265
- reasons.push(`${def.name}: uses bodyFile:, not hub-pushable`);
2266
- continue;
2267
- }
2268
- throw e;
2269
- }
2270
- candidates.push({ name: def.name, hash, yaml });
2271
- }
2272
- if (reasons.length > 0) {
2273
- throw new CliError(`refusing to push — ${reasons.length} problem(s) found; nothing sent:\n - ${reasons.join('\n - ')}`);
2274
- }
2275
- // Fetch the server's own list once — the diff source of truth. Always
2276
- // fetched, even under --force, so the new/changed labels stay accurate.
2277
- const { res: listRes, cred: listCred } = await authedGet(io, origin, slot, cred, '/api/workflows');
2278
- assertAuthOk(listRes, listCred, origin);
2279
- cred = listCred;
2280
- let serverMap;
2281
- try {
2282
- serverMap = parseWorkflowList(await listRes.json());
2283
- }
2284
- catch (e) {
2285
- throw new CliError(e.message);
2286
- }
2287
- const { toPush, unchanged } = computeServerDiff(candidates, serverMap, force);
2288
- // Diff-style human lines go to stderr so stdout stays machine-parseable JSON.
2289
- for (const c of unchanged)
2290
- io.err(`= ${c.name} (unchanged)`);
2291
- if (dryRun) {
2292
- for (const c of toPush) {
2293
- io.err(c.status === 'new' ? `+ ${c.name} (new)` : `~ ${c.name} (changed)`);
2294
- }
2295
- print(io, {
2296
- ok: true,
2297
- dryRun: true,
2298
- hub: origin,
2299
- new: toPush.filter((c) => c.status === 'new').map((c) => c.name),
2300
- changed: toPush.filter((c) => c.status === 'changed').map((c) => c.name),
2301
- unchanged: unchanged.map((c) => c.name),
2302
- wouldPush: toPush.map((c) => c.name),
2303
- });
2304
- return 0;
2305
- }
2306
- // Refresh an expiring oauth token once up front (per-request 401 refresh below covers mid-batch expiry).
2307
- cred = await ensureFreshOAuth(io, origin, slot, cred);
2308
- const pushedNames = [];
2309
- const noopNames = [];
2310
- const failed = [];
2311
- const skipped = [];
2312
- for (let i = 0; i < toPush.length; i++) {
2313
- const c = toPush[i];
2314
- const label = c.status === 'new' ? '+' : '~';
2315
- try {
2316
- let res = await createWorkflowRequest(io, origin, cred, c.yaml);
2317
- if (res.status === 401 && cred.kind === 'oauth') {
2318
- cred = await refreshOAuth(io, origin, slot, cred);
2319
- res = await createWorkflowRequest(io, origin, cred, c.yaml);
2320
- }
2321
- if (res.status === 401) {
2322
- if (cred.kind === 'agent') {
2323
- throw new CliError('token revoked or invalid — re-mint it in the console or run `owenloop login`');
2324
- }
2325
- throw new CliError('credential rejected by the hub — run `owenloop login`');
2326
- }
2327
- if (res.status === 413)
2328
- throw new CliError('workflow yaml exceeds the hub 32MB request cap');
2329
- if (res.status === 429) {
2330
- const retryAfter = res.headers.get('retry-after');
2331
- throw new RateLimitError(`rate limited by the hub${retryAfter ? ` (retry after ${retryAfter})` : ''}`);
2332
- }
2333
- if (!res.ok)
2334
- throw new CliError(`hub returned HTTP ${res.status}`);
2335
- const bodyJson = await res.json();
2336
- const errText = createWorkflowError(bodyJson);
2337
- if (errText !== null)
2338
- throw new CliError(`hub rejected the def: ${errText}`);
2339
- const okBody = asCreateWorkflowOk(bodyJson, c.name);
2340
- if (okBody.unchanged) {
2341
- noopNames.push(c.name);
2342
- io.err(`= ${c.name} (server: unchanged, v${okBody.version})`);
2343
- }
2344
- else {
2345
- pushedNames.push(c.name);
2346
- io.err(`${label} ${c.name} (→ v${okBody.version})`);
2347
- }
2348
- }
2349
- catch (e) {
2350
- // A 429 halts the whole batch immediately (REL-10): record this def as
2351
- // failed, then stop — the not-yet-attempted remainder is reported as
2352
- // `skipped`, not silently hammered against a rate-limited server.
2353
- // Handled before the generic path because RateLimitError extends CliError.
2354
- if (e instanceof RateLimitError) {
2355
- const msg = e.message;
2356
- failed.push({ name: c.name, error: msg });
2357
- io.err(`! ${c.name} (failed: ${msg})`);
2358
- const remainder = toPush.slice(i + 1).map((r) => r.name);
2359
- skipped.push(...remainder);
2360
- if (remainder.length > 0) {
2361
- io.err(`stopping — rate limited by the hub; ${remainder.length} def(s) not attempted`);
2362
- }
2363
- break;
2364
- }
2365
- // A hard auth error aborts the whole run (re-throw); a per-def server
2366
- // failure is recorded and the batch continues (already-pushed defs stand).
2367
- if (e instanceof CliError && /run `owenloop login`|re-mint it/.test(e.message)) {
2368
- throw e;
2369
- }
2370
- const msg = e.message;
2371
- failed.push({ name: c.name, error: msg });
2372
- io.err(`! ${c.name} (failed: ${msg})`);
2373
- }
2374
- }
2375
- print(io, {
2376
- ok: failed.length === 0,
2377
- hub: origin,
2378
- pushed: pushedNames,
2379
- noop: noopNames,
2380
- unchanged: unchanged.map((c) => c.name),
2381
- skipped,
2382
- failed,
2383
- });
2384
- return failed.length === 0 ? 0 : 1;
2385
- }
2386
- /**
2387
- * `owenloop mcp` — serve the human control plane to a local MCP host over stdio.
2388
- * A thin adapter: read the optional `--hub <url>` flag and hand `io` (which
2389
- * satisfies the module's `McpIo`) to `runMcpCommand`, which resolves the origin,
2390
- * builds the tool list, and pumps stdin until EOF. All the logic lives in
2391
- * `src/mcp/serve.ts`; this stays a two-line dispatch like every other verb.
2392
- */
2393
- async function dispatchMcp(io, args) {
2394
- return runMcpCommand(io, { hubFlag: last(args, 'hub') });
2395
- }
2396
- function createWorkflowRequest(io, origin, cred, yaml) {
2397
- return hubFetch(io, resolveEndpoint(origin, '/api/create_workflow'), {
2398
- method: 'POST',
2399
- headers: {
2400
- Authorization: authHeader(cred),
2401
- 'Content-Type': 'application/json',
2402
- Accept: 'application/json',
2403
- },
2404
- body: JSON.stringify({ yaml }),
2405
- });
2406
- }
2407
- /**
2408
- * Resolve the hub `agent new` mints on: `--hub <origin>` (normalized via
2409
- * `normalizeOrigin`) → else the ONE hub the credential FILE knows → else a
2410
- * `CliError` with `exitCode: 2` naming both remedies.
2411
- *
2412
- * Deliberately NOT `resolveHub` (`--hub → OWENLOOP_HUB → DEFAULT_HUB`): silently
2413
- * defaulting a MINT to the production hub while the user is logged into a dev hub
2414
- * would mint on the wrong org, and a mint is not undone by a retry. `OWENLOOP_HUB`
2415
- * is intentionally excluded so this stays in parity with O2's `owenloop mcp`.
2416
- *
2417
- * `listStoredHubOrigins` is backend-aware (shared with O2's `owenloop mcp`): only
2418
- * the FILE backend can enumerate, so it returns `null` on a keychain- or
2419
- * external-command-backed machine — those must pass `--hub`. A file-backed store
2420
- * returns the origins with a valid `human` slot: `[]` (log in first), exactly one
2421
- * (used automatically), or more than one (the non-secret origin keys are listed
2422
- * back so the user can pick).
2423
- */
2424
- function resolveAgentHub(io, args) {
2425
- const flagVal = last(args, 'hub');
2426
- if (flagVal !== undefined) {
2427
- try {
2428
- return normalizeOrigin(flagVal);
2429
- }
2430
- catch (e) {
2431
- throw new CliError(e.message);
2432
- }
2433
- }
2434
- const origins = listStoredHubOrigins(io.env, io.keychain);
2435
- if (origins === null) {
2436
- const backend = credentialBackend(io.env, io.keychain);
2437
- const which = backend.kind === 'external' ? 'external-command' : 'keychain';
2438
- throw new CliError(`cannot determine which hub to mint on — the ${which} credential store cannot be enumerated; ` +
2439
- 'pass --hub <origin>', { exitCode: 2 });
2440
- }
2441
- if (origins.length === 1)
2442
- return origins[0];
2443
- throw new CliError('cannot determine which hub to mint on — pass --hub <origin>, or log in to exactly one hub first ' +
2444
- '(owenloop login --hub <origin>)' +
2445
- (origins.length > 1 ? `; stored hubs: ${origins.join(', ')}` : ''), { exitCode: 2 });
2446
- }
2447
- /**
2448
- * `owenloop agent new <name>` — mint a new agent identity on the hub and store
2449
- * its `olp_` token in slot `agent:<name>`.
2450
- *
2451
- * **Secret hygiene (identity model §6, "rule of gates"):** the minted token goes
2452
- * process→store ONLY — it never appears on stdout, stderr, in an error, or in a
2453
- * log. `mintAgentCredential` (credentials.ts) owns the token end to end and
2454
- * returns none of it; the confirmation printed here is built from an explicit
2455
- * WHITELIST of non-secret fields (name, pools, storage backend, revocation ids).
2456
- *
2457
- * Ordering is load-bearing (PR #69 lesson, carried by `mintAgentCredential`): the
2458
- * client-side name validation and the external-command refusal both run BEFORE
2459
- * any network call, so a refusal that would make the credential unstorable never
2460
- * mints a server-side token first — minting then failing to store would burn the
2461
- * agent name permanently.
2462
- *
2463
- * Exit codes: 0 ok; 1 generic failure (invalid name, name taken, pool/shape
2464
- * rejection, network timeout, minted-but-unstored); 2 the hub is unresolvable;
2465
- * 3 the human credential is absent or irrecoverable (remedy names
2466
- * `owenloop login --hub <origin>`).
2467
- *
2468
- * A subcommand switch (`new` only today) leaves room for `agent list`/etc. later.
2469
- */
2470
- async function dispatchAgent(io, args) {
2471
- const sub = args.positionals[1];
2472
- if (sub !== 'new') {
2473
- throw new CliError(`unknown agent subcommand '${sub ?? ''}' — expected: agent new <name>`);
2474
- }
2475
- const name = args.positionals[2];
2476
- if (name === undefined) {
2477
- throw new CliError('missing required argument: <name> (usage: owenloop agent new <name> [--pools a,b] [--hub <url>])');
2478
- }
2479
- // Validate the agent name eagerly — before any I/O — with the store's own
2480
- // wording, so a bad name never reaches the network or the store.
2481
- try {
2482
- credentialSlot({ principal: 'agent', account: name });
2483
- }
2484
- catch (e) {
2485
- throw new CliError(`agent new: invalid agent name — ${e.message}`);
2486
- }
2487
- // --pools: split on `,`, trim, drop empties. Absent → undefined (key omitted
2488
- // from the request; the server then defaults to the minter's personal pool).
2489
- // Present but empty (`--pools ""` / `--pools ,`) → usage error, before any I/O.
2490
- // No client-side pool-name validation — the server is the enforcement of record.
2491
- const poolsRaw = last(args, 'pools');
2492
- let pools;
2493
- if (poolsRaw !== undefined) {
2494
- pools = poolsRaw
2495
- .split(',')
2496
- .map((p) => p.trim())
2497
- .filter((p) => p !== '');
2498
- if (pools.length === 0) {
2499
- throw new CliError('--pools requires at least one pool name');
2500
- }
2501
- }
2502
- // Refuse an external-command setup at the TOP of the dispatcher — before the
2503
- // human-credential read (which would otherwise RUN the command) and before any
2504
- // network call (PR #69 lesson; `mintAgentCredential` carries the same guard as
2505
- // a library backstop). Refusing only at store time would mint a server-side
2506
- // token we could never store locally, permanently burning the agent name.
2507
- if (externalCredentialCommand(io.env) !== undefined) {
2508
- throw new CliError('an external credential command is configured (OWENLOOP_CREDENTIAL_COMMAND), so it — not the ' +
2509
- 'local store — supplies credentials for this hub; unset it to use `owenloop login`');
2510
- }
2511
- const origin = resolveAgentHub(io, args);
2512
- // The human bearer for the resolved origin. Absent → exit 3 with the verbatim
2513
- // remedy the brief mandates.
2514
- const cred = readCredential(io, origin, { principal: 'human' });
2515
- if (cred === null) {
2516
- throw new CliError(`no human credential for ${origin} — run: owenloop login --hub ${origin}`, { exitCode: 3 });
2517
- }
2518
- let result;
2519
- try {
2520
- result = await mintAgentCredential(io, origin, { principal: 'human' }, cred, { name, pools });
2521
- }
2522
- catch (e) {
2523
- // A refresh-failure-family error (the human oauth is irrecoverable, or a 401
2524
- // survived the refresh-and-retry) is exit 3 with the login remedy; every
2525
- // other CliError propagates as-is — a network timeout stays exit 1, because a
2526
- // flaky network is not an irrecoverable credential.
2527
- if (e instanceof CliError && /run `owenloop login`/.test(e.message)) {
2528
- throw new CliError(`${e.message} — run: owenloop login --hub ${origin}`, { exitCode: 3 });
2529
- }
2530
- throw e;
2531
- }
2532
- // Confirmation: whitelisted, non-secret fields ONLY. `text`/`token` are
2533
- // structurally absent from `result`, so there is nothing here to leak.
2534
- print(io, {
2535
- ok: true,
2536
- hub: origin,
2537
- name,
2538
- slot: `agent:${name}`,
2539
- pools: result.pools,
2540
- scopes: ['work'],
2541
- storage: result.storage,
2542
- agentId: result.agentId,
2543
- tokenId: result.id,
2544
- });
2545
- return 0;
2546
- }
2547
- /**
2548
- * The plugin check is rendered but NON-FATAL while the marketplace is not yet
2549
- * fetchably published (the brief's open question): `doctor` shows ✓/✗ but the
2550
- * plugin never flips the exit code, and `setup` PRINTS install instructions
2551
- * instead of failing. Flip to `true` once the shell-out install lands.
2552
- */
2553
- const PLUGIN_CHECK_FATAL = false;
2554
- /**
2555
- * Resolve the hub `setup`/`doctor` target. Deviates from `resolveAgentHub` in
2556
- * exactly ONE way (documented in the plan §4): a fresh machine — which is the
2557
- * Flow A mainline — has NO stored hub, so instead of `resolveAgentHub`'s exit-2
2558
- * it falls back to the production `DEFAULT_HUB` with a printed notice. The
2559
- * wrong-hub-mint risk `resolveAgentHub` guards against does not apply: the mint
2560
- * happens only AFTER the human logs in through this hub's own browser consent,
2561
- * and the target line is printed first.
2562
- *
2563
- * - `--hub <origin>` → `normalizeOrigin`.
2564
- * - else `listStoredHubOrigins`: exactly one → use it; more than one → `CliError`
2565
- * exitCode 2 listing them; zero or `null` (keychain/external cannot enumerate)
2566
- * → `DEFAULT_HUB` + notice.
2567
- *
2568
- * `OWENLOOP_HUB` stays excluded (O2/O3 parity). Shared by both commands so they
2569
- * agree on the target.
2570
- */
2571
- function resolveSetupHub(io, args) {
2572
- const flagVal = last(args, 'hub');
2573
- if (flagVal !== undefined) {
2574
- try {
2575
- return normalizeOrigin(flagVal);
2576
- }
2577
- catch (e) {
2578
- throw new CliError(e.message);
2579
- }
2580
- }
2581
- const origins = listStoredHubOrigins(io.env, io.keychain);
2582
- if (origins !== null && origins.length === 1)
2583
- return origins[0];
2584
- if (origins !== null && origins.length > 1) {
2585
- throw new CliError(`more than one hub is configured on this machine — pass --hub <origin> to pick one; stored hubs: ${origins.join(', ')}`, { exitCode: 2 });
2586
- }
2587
- io.err(`targeting ${DEFAULT_HUB} (pass --hub to override)`);
2588
- return DEFAULT_HUB;
2589
- }
2590
- /**
2591
- * Is `cmd` an executable file on `env.PATH`? A pure PATH scan (no exec), so it is
2592
- * hermetic-testable by pointing `PATH` at a fixture dir with a chmod +x stub.
2593
- * A directory entry, a non-executable file, or an unreadable dir is skipped.
2594
- */
2595
- function commandOnPath(env, cmd) {
2596
- const path = env.PATH;
2597
- if (!path)
2598
- return false;
2599
- for (const dir of path.split(delimiter)) {
2600
- if (dir === '')
2601
- continue;
2602
- const full = join(dir, cmd);
2603
- try {
2604
- const st = statSync(full);
2605
- if (st.isFile() && (st.mode & 0o111) !== 0)
2606
- return true;
2607
- }
2608
- catch {
2609
- // not here — keep scanning
2610
- }
2611
- }
2612
- return false;
2613
- }
2614
- /**
2615
- * Coerce a raw string (a hostname) into a valid agent account name, or `''` when
2616
- * nothing usable survives. Lowercase; drop every character outside the account
2617
- * body class `[a-z0-9._-]`; strip leading non-alphanumerics (the account MUST
2618
- * start alphanumeric); clamp to 64 chars. A suggestion only — never parsed or
2619
- * matched (§2); the user may accept it or type any valid label.
2620
- */
2621
- export function sanitizeAgentName(raw) {
2622
- let s = raw.toLowerCase().replace(/[^a-z0-9._-]/g, '');
2623
- s = s.replace(/^[^a-z0-9]+/, '');
2624
- if (s.length > 64)
2625
- s = s.slice(0, 64);
2626
- return s;
2627
- }
2628
- /**
2629
- * The identity's last-active instant in epoch-ms: `max` of its two non-null
2630
- * timestamps (`lastUsedAt`, the rekey-surviving token-level max; `lastContactAt`,
2631
- * the identity-level any-protocol contact), or `null` when both are absent. Both
2632
- * recording paths are monotone, so `max` is the correct "most recent activity".
2633
- */
2634
- export function lastActiveMs(identity) {
2635
- const c = identity.lastContactAt;
2636
- const u = identity.lastUsedAt;
2637
- if (c === null)
2638
- return u;
2639
- if (u === null)
2640
- return c;
2641
- return Math.max(c, u);
2642
- }
2643
- /**
2644
- * Render an elapsed-time delta (ms) as a short relative string: `just now`,
2645
- * `<n>m ago`, `<n>h ago`, `<n>d ago`. A `null` delta (no recorded activity)
2646
- * renders `never`. Negative deltas (clock skew) clamp to `just now`.
2647
- */
2648
- export function formatLastActive(deltaMs) {
2649
- if (deltaMs === null)
2650
- return 'never';
2651
- const ms = Math.max(0, deltaMs);
2652
- const min = Math.floor(ms / 60_000);
2653
- if (min < 1)
2654
- return 'just now';
2655
- if (min < 60)
2656
- return `${min}m ago`;
2657
- const hr = Math.floor(min / 60);
2658
- if (hr < 24)
2659
- return `${hr}h ago`;
2660
- return `${Math.floor(hr / 24)}d ago`;
2661
- }
2662
- /**
2663
- * File-backend agent account names stored for `origin`, or `null` when the
2664
- * backend cannot enumerate (keychain/external) — mirrors `listStoredHubOrigins`'
2665
- * backend-awareness. The keychain interface is get/set/delete only, so the real
2666
- * agent probe on a keychain machine is the identity-name-keyed reads in step 3.
2667
- */
2668
- function enumerateAgentAccounts(io, origin) {
2669
- if (credentialBackend(io.env, io.keychain).kind !== 'file')
2670
- return null;
2671
- const file = readCredentialFile(credentialFilePath(io.env));
2672
- return Object.keys(file.hubs[origin] ?? {})
2673
- .filter((k) => k.startsWith('agent:'))
2674
- .map((k) => k.slice('agent:'.length));
2675
- }
2676
- /**
2677
- * Probe local agent slots (`names`) for one that verifies live against the hub's
2678
- * `whoami`. Reads each `agent:<name>` slot; a hit is verified with `authedGet`
2679
- * (ensureFreshOAuth no-ops on the `agent` kind; a 401 = revoked → `sawRevoked`).
2680
- * Prefers a slot whose `whoami actor.id` matches a listed identity id; falls back
2681
- * to the first otherwise-verified slot (id/name mismatch is tolerated, never a
2682
- * hard fail — see plan §5). Never a write.
2683
- */
2684
- async function probeAgentSlots(io, origin, names, identities) {
2685
- let verified = null;
2686
- let sawSlot = false;
2687
- let sawRevoked = false;
2688
- for (const name of names) {
2689
- const cred = readCredential(io, origin, { principal: 'agent', account: name });
2690
- if (cred === null)
2691
- continue;
2692
- sawSlot = true;
2693
- let res;
2694
- try {
2695
- ({ res } = await authedGet(io, origin, { principal: 'agent', account: name }, cred, '/api/whoami'));
2696
- }
2697
- catch {
2698
- continue;
2699
- }
2700
- if (res.status === 401) {
2701
- sawRevoked = true;
2702
- continue;
2703
- }
2704
- if (!res.ok)
2705
- continue;
2706
- let actorId = '';
2707
- try {
2708
- actorId = asWhoami(await res.json()).actor.id;
2709
- }
2710
- catch {
2711
- continue;
2712
- }
2713
- const byId = identities.find((i) => i.id === actorId);
2714
- const byName = identities.find((i) => i.name === name);
2715
- const va = { name, actorId, identity: byId ?? byName };
2716
- if (byId)
2717
- return { verified: va, sawSlot, sawRevoked };
2718
- if (verified === null)
2719
- verified = va;
2720
- }
2721
- return { verified, sawSlot, sawRevoked };
2722
- }
2723
- /**
2724
- * The interactive prompt for setup, or the non-interactive guard. Returns
2725
- * `io.prompt` when injected; else, when stdin is a real TTY, the default
2726
- * readline prompt; else a `CliError` naming the two bypass flags — thrown BEFORE
2727
- * any mutation so a scripted/piped run never blocks or half-applies.
2728
- */
2729
- function requirePrompt(io) {
2730
- if (io.prompt)
2731
- return io.prompt;
2732
- if (process.stdin.isTTY)
2733
- return defaultPrompt;
2734
- throw new CliError('setup needs to ask which agent to use, but stdin is not interactive — pass ' +
2735
- '--new-agent <name> to create a new agent, or --replace-agent <name> to replace an existing one');
2736
- }
2737
- /**
2738
- * Prompt for an agent name (Flow A). Offers `sanitizeAgentName(hostname())` as a
2739
- * prefill an empty answer accepts; an invalid answer re-prompts once, then a
2740
- * `CliError`. The name is a SUGGESTION only — any valid label is accepted.
2741
- */
2742
- async function promptAgentName(io) {
2743
- const prompt = requirePrompt(io);
2744
- const prefill = sanitizeAgentName(hostname());
2745
- const question = prefill ? `Name this agent [${prefill}]: ` : 'Name this agent: ';
2746
- for (let attempt = 0; attempt < 2; attempt++) {
2747
- const raw = (await prompt(question)).trim();
2748
- const answer = raw === '' ? prefill : raw;
2749
- if (answer === '') {
2750
- io.err('an agent name is required');
2751
- continue;
2752
- }
2753
- try {
2754
- credentialSlot({ principal: 'agent', account: answer });
2755
- return answer;
2756
- }
2757
- catch {
2758
- io.err(`invalid agent name '${answer}' — expected 1-64 chars matching [A-Za-z0-9][A-Za-z0-9._-]*`);
2759
- }
2760
- }
2761
- throw new CliError('no valid agent name provided');
2762
- }
2763
- /**
2764
- * Render the succession question (Flow B) and read a choice. The framing
2765
- * sentences are VERBATIM from the model doc; the radio glyphs become numbered
2766
- * terminal choices (the honest line-input adaptation). `[1]` = new installation;
2767
- * `[k]` = replace the (k-2)th non-disabled identity. Each Replace line shows the
2768
- * name, `last active <relative>`, and pools. Invalid input re-prompts once, then
2769
- * a `CliError`.
2770
- */
2771
- async function promptSuccession(io, identities) {
2772
- const prompt = requirePrompt(io);
2773
- const candidates = identities.filter((i) => !i.disabled);
2774
- const now = nowMs();
2775
- const lines = [
2776
- 'Is this a new installation, or does it replace an existing one?',
2777
- '',
2778
- ' [1] New installation → create a new agent',
2779
- ];
2780
- candidates.forEach((id, i) => {
2781
- const active = lastActiveMs(id);
2782
- const rel = formatLastActive(active === null ? null : now - active);
2783
- const pools = id.pools.length ? id.pools.join(', ') : '(none)';
2784
- lines.push(` [${i + 2}] Replace: ${id.name} last active ${rel} · pools: ${pools}`);
2785
- });
2786
- lines.push('');
2787
- lines.push('⚠ "Replace" revokes that agent\'s current credential. If it is still');
2788
- lines.push(' running somewhere, it will be disconnected there.');
2789
- lines.push('');
2790
- const max = candidates.length + 1;
2791
- const question = `${lines.join('\n')}\nChoose [1-${max}]: `;
2792
- for (let attempt = 0; attempt < 2; attempt++) {
2793
- const raw = (await prompt(attempt === 0 ? question : `Choose [1-${max}]: `)).trim();
2794
- const n = Number(raw);
2795
- if (Number.isInteger(n) && n >= 1 && n <= max) {
2796
- if (n === 1)
2797
- return { kind: 'new' };
2798
- return { kind: 'replace', identity: candidates[n - 2] };
2799
- }
2800
- io.err(`please enter a number between 1 and ${max}`);
2801
- }
2802
- throw new CliError('no valid choice provided');
2803
- }
2804
- /** Probe the Claude Code plugin state: is `claude` on PATH, and does `plugin list` mention owenloop? */
2805
- function probePlugin(io) {
2806
- if (!commandOnPath(io.env, 'claude'))
2807
- return { claudeFound: false, installed: false };
2808
- const run = io.runCommand ?? defaultRunCommand;
2809
- try {
2810
- return { claudeFound: true, installed: run('claude', ['plugin', 'list']).stdout.includes('owenloop') };
2811
- }
2812
- catch {
2813
- return { claudeFound: true, installed: false };
2814
- }
2815
- }
2816
- /**
2817
- * The plugin ACT step. While the marketplace is unpublished this PRINTS the
2818
- * manual install instructions instead of shelling out — the single seam a real
2819
- * shell-out install would replace later. Never fails setup.
2820
- */
2821
- function installPluginStep(io, state) {
2822
- if (!state.claudeFound)
2823
- io.err('Claude Code (claude) not detected on PATH.');
2824
- io.err('Claude Code plugin — install manually:');
2825
- io.err(' claude plugin marketplace add owenloop');
2826
- io.err(' claude plugin install owenloop@owenloop');
2827
- }
2828
- /**
2829
- * `owenloop setup` — converge this machine's install in six probe→(skip|act)
2830
- * steps, idempotently: a second run performs ZERO writes (no store mutation, no
2831
- * settings write, no browser, no mint/rekey/register POST). Each ACT is reached
2832
- * only through its probe failing.
2833
- *
2834
- * Flags: `--hub <url>`; mutually-exclusive `--new-agent <name>` / `--replace-agent
2835
- * <name>` (bypass the interactive agent branches); `--pools <a,b>` (mint only —
2836
- * a usage error with `--replace-agent`, which preserves pools).
2837
- *
2838
- * Exit: 0 when every step ended skipped/done/noted AND doctor's core (non-plugin)
2839
- * checks pass; 1 otherwise. Any hard failure throws (mapped to an exit code by
2840
- * `mainAsync`).
2841
- */
2842
- async function dispatchSetup(io, args) {
2843
- // --- usage validation, before any I/O ---
2844
- const newAgent = last(args, 'new-agent');
2845
- const replaceAgent = last(args, 'replace-agent');
2846
- if (newAgent !== undefined && replaceAgent !== undefined) {
2847
- throw new CliError('pass at most one of --new-agent or --replace-agent, not both');
2848
- }
2849
- const poolsRaw = last(args, 'pools');
2850
- let pools;
2851
- if (poolsRaw !== undefined) {
2852
- pools = poolsRaw
2853
- .split(',')
2854
- .map((p) => p.trim())
2855
- .filter((p) => p !== '');
2856
- if (pools.length === 0)
2857
- throw new CliError('--pools requires at least one pool name');
2858
- }
2859
- if (replaceAgent !== undefined && pools !== undefined) {
2860
- throw new CliError("--pools cannot be combined with --replace-agent — re-keying preserves the agent's pools (manage pools in the console)");
2861
- }
2862
- for (const [flagName, val] of [
2863
- ['--new-agent', newAgent],
2864
- ['--replace-agent', replaceAgent],
2865
- ]) {
2866
- if (val !== undefined) {
2867
- try {
2868
- credentialSlot({ principal: 'agent', account: val });
2869
- }
2870
- catch (e) {
2871
- throw new CliError(`${flagName}: invalid agent name — ${e.message}`);
2872
- }
2873
- }
2874
- }
2875
- // Symmetric with `dispatchLogin`: when an external credential command supplies
2876
- // this hub's credentials, the local store is never consulted, so setup's
2877
- // human-login step (step 2, which opens the loopback OAuth browser) and its
2878
- // agent mint would strand keys nobody reads. Refuse BEFORE any browser opens —
2879
- // otherwise setup completes the full OAuth round-trip only to fail at
2880
- // storeCredential's backstop, wasting a browser trip on the flagship command.
2881
- if (externalCredentialCommand(io.env) !== undefined) {
2882
- throw new CliError('an external credential command is configured (OWENLOOP_CREDENTIAL_COMMAND), so it — not the ' +
2883
- 'local store — supplies credentials for this hub; unset it to use `owenloop login`');
2884
- }
2885
- const origin = resolveSetupHub(io, args);
2886
- const steps = [];
2887
- // --- [1/6] inspect: zero writes, best-effort probes ---
2888
- io.err('[1/6] inspect');
2889
- io.err(` human credential: ${readCredential(io, origin, { principal: 'human' }) !== null ? 'present' : 'none — will log in'}`);
2890
- const inspectSettingsPath = owenworkSettingsPath(io.env);
2891
- let settingsNote;
2892
- if (!existsSync(inspectSettingsPath)) {
2893
- settingsNote = 'missing — will write';
2894
- }
2895
- else {
2896
- try {
2897
- const raw = readOwenworkSettingsRaw(inspectSettingsPath);
2898
- const found = raw && typeof raw.hubOrigin === 'string' ? raw.hubOrigin : undefined;
2899
- settingsNote = found === origin ? `hubOrigin already ${origin}` : `hubOrigin ${found ?? '(unset)'} — will update`;
2900
- }
2901
- catch {
2902
- settingsNote = 'present but unreadable — step 4 will error if still corrupt';
2903
- }
2904
- }
2905
- io.err(` owenwork settings: ${settingsNote}`);
2906
- io.err(` claude on PATH: ${commandOnPath(io.env, 'claude') ? 'yes' : 'no'}`);
2907
- const inspectAccts = enumerateAgentAccounts(io, origin);
2908
- io.err(inspectAccts === null
2909
- ? ' agent slots: checked in step 3'
2910
- : ` agent slots: ${inspectAccts.length ? inspectAccts.map((a) => `agent:${a}`).join(', ') : 'none'}`);
2911
- steps.push({ step: 'inspect', action: 'done', detail: 'probed local state' });
2912
- // --- [2/6] human login: the hard gate that makes step 3's rekey legal ---
2913
- io.err('[2/6] human login');
2914
- let humanCred = readCredential(io, origin, { principal: 'human' });
2915
- let humanIdentity;
2916
- if (humanCred !== null) {
2917
- try {
2918
- const verified = await verifyCredential(io, origin, { principal: 'human' }, humanCred);
2919
- humanCred = verified.cred;
2920
- humanIdentity = verified.identity;
2921
- io.err(`✓ human: ${humanIdentity.email ?? humanIdentity.actor.id} @ ${humanIdentity.orgName}`);
2922
- steps.push({ step: 'human login', action: 'skipped', detail: `${humanIdentity.email ?? humanIdentity.actor.id} @ ${humanIdentity.orgName}` });
2923
- }
2924
- catch (e) {
2925
- if (!(e instanceof CliError))
2926
- throw e; // a genuine non-credential error is not a re-login trigger
2927
- const r = await runLoopbackOAuth(io, origin);
2928
- humanCred = r.cred;
2929
- humanIdentity = r.identity;
2930
- io.err(`✓ human: signed in as ${humanIdentity.email ?? humanIdentity.actor.id} @ ${humanIdentity.orgName}`);
2931
- steps.push({ step: 'human login', action: 'done', detail: `signed in as ${humanIdentity.email ?? humanIdentity.actor.id}` });
2932
- }
2933
- }
2934
- else {
2935
- const r = await runLoopbackOAuth(io, origin);
2936
- humanCred = r.cred;
2937
- humanIdentity = r.identity;
2938
- io.err(`✓ human: signed in as ${humanIdentity.email ?? humanIdentity.actor.id} @ ${humanIdentity.orgName}`);
2939
- steps.push({ step: 'human login', action: 'done', detail: `signed in as ${humanIdentity.email ?? humanIdentity.actor.id}` });
2940
- }
2941
- // --- [3/6] agent ---
2942
- io.err('[3/6] agent');
2943
- const { res: idRes } = await authedGet(io, origin, { principal: 'human' }, humanCred, '/api/agent_identities');
2944
- if (idRes.status === 403) {
2945
- throw new CliError('setup needs an admin credential to manage agents (hub returned 403)');
2946
- }
2947
- assertAuthOk(idRes, humanCred, origin);
2948
- const identities = asAgentIdentities(await idRes.json());
2949
- const candidateNames = new Set(identities.map((i) => i.name));
2950
- candidateNames.add('default');
2951
- const probe = await probeAgentSlots(io, origin, [...candidateNames], identities);
2952
- let agentAccount;
2953
- if (probe.verified !== null) {
2954
- agentAccount = probe.verified.name;
2955
- const poolsStr = probe.verified.identity ? ` (pools: ${probe.verified.identity.pools.join(', ') || 'none'})` : '';
2956
- io.err(`✓ agent: ${agentAccount}${poolsStr}`);
2957
- steps.push({ step: 'agent', action: 'skipped', detail: `agent:${agentAccount} verified` });
2958
- }
2959
- else {
2960
- // ACT — resolve which agent to connect, then mint or rekey.
2961
- let action;
2962
- if (newAgent !== undefined) {
2963
- action = { mode: 'mint', name: newAgent };
2964
- }
2965
- else if (replaceAgent !== undefined) {
2966
- const target = identities.find((i) => i.name === replaceAgent);
2967
- if (target === undefined) {
2968
- throw new CliError(`no agent named '${replaceAgent}' on ${origin} — available: ${identities.map((i) => i.name).join(', ') || '(none)'}`);
2969
- }
2970
- action = { mode: 'rekey', agentId: target.id, name: replaceAgent };
2971
- }
2972
- else if (identities.length === 0) {
2973
- // Flow A — fresh org, prompt for a name.
2974
- action = { mode: 'mint', name: await promptAgentName(io) };
2975
- }
2976
- else {
2977
- // Flow B — succession.
2978
- const choice = await promptSuccession(io, identities);
2979
- action =
2980
- choice.kind === 'new'
2981
- ? { mode: 'mint', name: await promptAgentName(io) }
2982
- : { mode: 'rekey', agentId: choice.identity.id, name: choice.identity.name };
2983
- }
2984
- if (action.mode === 'mint') {
2985
- const result = await mintAgentCredential(io, origin, { principal: 'human' }, humanCred, { name: action.name, pools });
2986
- agentAccount = action.name;
2987
- io.err(`✓ agent: minted agent:${agentAccount} (pools: ${result.pools.join(', ') || 'none'})`);
2988
- steps.push({ step: 'agent', action: 'done', detail: `minted agent:${agentAccount}` });
2989
- }
2990
- else {
2991
- const result = await rekeyAgentCredential(io, origin, { principal: 'human' }, humanCred, { agentId: action.agentId, name: action.name });
2992
- agentAccount = action.name;
2993
- io.err(`✓ agent: re-keyed agent:${agentAccount} (revoked ${result.revokedTokenIds.length} old token(s))`);
2994
- steps.push({ step: 'agent', action: 'done', detail: `re-keyed agent:${agentAccount}` });
2995
- }
2996
- }
2997
- // --- [4/6] owenwork settings ---
2998
- io.err('[4/6] owenwork settings');
2999
- const settingsPath = owenworkSettingsPath(io.env);
3000
- const existingSettings = readOwenworkSettingsRaw(settingsPath); // corrupt file → hard CliError (never clobber)
3001
- const currentHub = existingSettings && typeof existingSettings.hubOrigin === 'string' ? existingSettings.hubOrigin : undefined;
3002
- if (existingSettings !== null && currentHub === origin) {
3003
- io.err(`✓ owenwork settings: hubOrigin already ${origin}`);
3004
- steps.push({ step: 'owenwork settings', action: 'skipped', detail: settingsPath });
3005
- }
3006
- else {
3007
- const written = writeOwenworkHubOrigin(io.env, origin);
3008
- io.err(`✓ owenwork settings: hubOrigin ${written.previous ?? '(unset)'} → ${origin}`);
3009
- steps.push({ step: 'owenwork settings', action: 'done', detail: `${written.previous ?? '(unset)'} → ${origin}` });
3010
- }
3011
- if (agentAccount !== 'default') {
3012
- io.err(`non-default agent account — run owenwork with OWENWORK_ACCOUNT=${agentAccount}`);
3013
- }
3014
- // --- [5/6] plugin (non-fatal) ---
3015
- io.err('[5/6] plugin');
3016
- const pluginState = probePlugin(io);
3017
- if (pluginState.installed) {
3018
- io.err('✓ plugin: owenloop installed');
3019
- steps.push({ step: 'plugin', action: 'skipped', detail: 'installed' });
3020
- }
3021
- else {
3022
- installPluginStep(io, pluginState);
3023
- steps.push({
3024
- step: 'plugin',
3025
- action: 'noted',
3026
- detail: pluginState.claudeFound ? 'not installed — printed manual instructions' : 'claude not on PATH — printed manual instructions',
3027
- });
3028
- }
3029
- // --- [6/6] doctor pass ---
3030
- io.err('[6/6] doctor');
3031
- const doctor = await runDoctor(io, origin);
3032
- print(io, { ok: doctor.ok, hub: origin, steps, doctor: { ok: doctor.ok, checks: doctor.checks } });
3033
- return doctor.ok ? 0 : 1;
3034
- }
3035
- /**
3036
- * `owenloop doctor` — the read-only probe of the five install surfaces plus the
3037
- * plugin, rendering one distinct ✓/✗ line each. NO configuration writes (no
3038
- * mint, rekey, slot create/delete, settings write, or browser). The one
3039
- * carve-out: `authedGet`'s persist=true MAY rotate-and-persist an expiring human
3040
- * oauth token — as every authed verb does — because a refresh WITHOUT persisting
3041
- * would strand the rotated refresh token and corrupt the install (worse than a
3042
- * write). Tests use non-expiring tokens so the strict zero-write assertion holds.
3043
- */
3044
- async function dispatchDoctor(io, args) {
3045
- const origin = resolveSetupHub(io, args);
3046
- const doctor = await runDoctor(io, origin);
3047
- print(io, { ok: doctor.ok, hub: origin, checks: doctor.checks });
3048
- return doctor.ok ? 0 : 1;
3049
- }
3050
- /**
3051
- * Run the six doctor checks in order, printing each ✓/✗ line to stderr and
3052
- * returning the structured result. Never short-circuits — a machine with no
3053
- * working human credential still renders lines 3–6 (the agent probe degrades
3054
- * honestly). `ok` reflects checks 1–5 only; the plugin check (6) renders but,
3055
- * while `PLUGIN_CHECK_FATAL` is false, never affects `ok`.
3056
- */
3057
- async function runDoctor(io, origin) {
3058
- const checks = [];
3059
- let coreOk = true;
3060
- const record = (label, ok, detail, core) => {
3061
- io.err(`${ok ? '✓' : '✗'} ${label}: ${detail}`);
3062
- checks.push({ label, ok, detail });
3063
- if (core && !ok)
3064
- coreOk = false;
3065
- };
3066
- // 1. human slot
3067
- const humanCred = readCredential(io, origin, { principal: 'human' });
3068
- if (humanCred === null) {
3069
- record('human credential', false, `none stored for ${origin} — run owenloop setup (or owenloop login --hub ${origin})`, true);
3070
- }
3071
- else {
3072
- record('human credential', true, 'present', true);
3073
- }
3074
- // 2. human plane
3075
- let humanOk = false;
3076
- let usableHumanCred = null;
3077
- if (humanCred !== null) {
3078
- try {
3079
- const { cred, identity } = await verifyCredential(io, origin, { principal: 'human' }, humanCred);
3080
- humanOk = true;
3081
- usableHumanCred = cred;
3082
- record('human plane', true, `${identity.email ?? identity.actor.id} @ ${identity.orgName}`, true);
3083
- }
3084
- catch (e) {
3085
- const msg = e instanceof Error ? e.message : String(e);
3086
- if (/refresh/i.test(msg)) {
3087
- record('human plane', false, 'human credential present but irrecoverable (refresh failed) — run owenloop login', true);
3088
- }
3089
- else if (/rejected by the hub|revoked or invalid/.test(msg)) {
3090
- record('human plane', false, 'human credential rejected by the hub — run owenloop login', true);
3091
- }
3092
- else {
3093
- record('human plane', false, `could not reach the hub — ${msg}`, true);
3094
- }
3095
- }
3096
- }
3097
- else {
3098
- record('human plane', false, 'not checked — no human credential to verify', true);
3099
- }
3100
- // Best-effort identities listing for the agent checks (soft: a 403/failure degrades, never throws).
3101
- let identities = [];
3102
- let identitiesForbidden = false;
3103
- let identitiesAvailable = false;
3104
- if (humanOk && usableHumanCred !== null) {
3105
- try {
3106
- const { res } = await authedGet(io, origin, { principal: 'human' }, usableHumanCred, '/api/agent_identities');
3107
- if (res.status === 403) {
3108
- identitiesForbidden = true;
3109
- }
3110
- else if (res.ok) {
3111
- identities = asAgentIdentities(await res.json());
3112
- identitiesAvailable = true;
3113
- }
3114
- }
3115
- catch {
3116
- // leave degraded
3117
- }
3118
- }
3119
- // 3. agent slot (presence) + 4. agent plane (verification)
3120
- const candidateNames = new Set(identities.map((i) => i.name));
3121
- const fileAccts = enumerateAgentAccounts(io, origin);
3122
- if (fileAccts !== null)
3123
- for (const a of fileAccts)
3124
- candidateNames.add(a);
3125
- candidateNames.add('default');
3126
- const agentProbe = await probeAgentSlots(io, origin, [...candidateNames], identities);
3127
- if (!agentProbe.sawSlot) {
3128
- if (!identitiesAvailable && !humanOk && fileAccts === null) {
3129
- record('agent slot', false, 'not probeable without a working human credential', true);
3130
- }
3131
- else {
3132
- record('agent slot', false, `no agent credential stored for ${origin} — run owenloop setup`, true);
3133
- }
3134
- record('agent plane', false, 'no agent credential to verify — run owenloop setup', true);
3135
- }
3136
- else {
3137
- record('agent slot', true, 'present', true);
3138
- if (agentProbe.verified !== null) {
3139
- const va = agentProbe.verified;
3140
- const pools = va.identity
3141
- ? `pools: ${va.identity.pools.join(', ') || 'none'}`
3142
- : identitiesForbidden
3143
- ? '(pools not visible — requires an admin credential)'
3144
- : '(pools unknown)';
3145
- const idPart = va.identity ? va.identity.id : va.actorId;
3146
- record('agent plane', true, `${va.name} (agent id ${idPart}) · ${pools}`, true);
3147
- }
3148
- else if (agentProbe.sawRevoked) {
3149
- record('agent plane', false, 'agent token revoked or invalid — re-run owenloop setup (Replace) or Reconnect in the console', true);
3150
- }
3151
- else {
3152
- record('agent plane', false, 'agent credential present but could not be verified against the hub', true);
3153
- }
3154
- }
3155
- // 5. owenwork settings
3156
- const settingsPath = owenworkSettingsPath(io.env);
3157
- let settingsRaw = null;
3158
- let settingsError = null;
3159
- try {
3160
- settingsRaw = readOwenworkSettingsRaw(settingsPath);
3161
- }
3162
- catch (e) {
3163
- settingsError = e instanceof Error ? e.message : String(e);
3164
- }
3165
- if (settingsError !== null) {
3166
- record('owenwork settings', false, settingsError, true);
3167
- }
3168
- else if (settingsRaw === null) {
3169
- record('owenwork settings', false, `missing (${settingsPath})`, true);
3170
- }
3171
- else {
3172
- const found = typeof settingsRaw.hubOrigin === 'string' ? settingsRaw.hubOrigin : undefined;
3173
- if (found !== origin) {
3174
- record('owenwork settings', false, `hubOrigin is ${found ?? '(unset)'}, expected ${origin}`, true);
3175
- }
3176
- else {
3177
- record('owenwork settings', true, settingsPath, true);
3178
- }
3179
- }
3180
- // 6. plugin (rendered; non-core while PLUGIN_CHECK_FATAL is false)
3181
- const pluginState = probePlugin(io);
3182
- if (!pluginState.claudeFound) {
3183
- record('plugin', false, 'Claude Code (claude) not on PATH', PLUGIN_CHECK_FATAL);
3184
- }
3185
- else if (!pluginState.installed) {
3186
- record('plugin', false, 'plugin not installed — claude plugin marketplace add owenloop && claude plugin install owenloop@owenloop', PLUGIN_CHECK_FATAL);
3187
- }
3188
- else {
3189
- record('plugin', true, 'owenloop installed', PLUGIN_CHECK_FATAL);
3190
- }
3191
- return { ok: coreOk, checks };
3192
- }
3193
- /**
3194
- * Async entry point that adds network I/O for `add` and the hub commands on top
3195
- * of the otherwise fully-synchronous engine/CLI (see the doc comment on
3196
- * `sleepMs` above and README "sync end to end"). `main`/`dispatch` stay sync and
3197
- * unchanged — this wraps them, routing only the network-touching verbs through
3198
- * the async path, so every existing command and test keeps working exactly as
3199
- * before.
3200
- */
3201
- export const ASYNC_COMMANDS = new Set(['add', 'login', 'logout', 'connect', 'push', 'agent', 'setup', 'doctor', 'mcp']);
3202
- export async function mainAsync(argv, io = defaultIO()) {
3203
- const args = parseArgs(argv);
3204
- const command = args.positionals[0];
3205
- if (command === undefined || !ASYNC_COMMANDS.has(command)) {
3206
- return main(argv, io);
3207
- }
3208
- try {
3209
- const short = preflight(command, args, io);
3210
- if (short !== undefined)
3211
- return short;
3212
- switch (command) {
3213
- case 'add':
3214
- return await dispatchAdd(io, args);
3215
- case 'login':
3216
- return await dispatchLogin(io, args);
3217
- case 'logout':
3218
- return await dispatchLogout(io, args);
3219
- case 'connect':
3220
- return await dispatchConnect(io, args);
3221
- case 'push':
3222
- return await dispatchPush(io, args);
3223
- case 'agent':
3224
- return await dispatchAgent(io, args);
3225
- case 'setup':
3226
- return await dispatchSetup(io, args);
3227
- case 'doctor':
3228
- return await dispatchDoctor(io, args);
3229
- case 'mcp':
3230
- return await dispatchMcp(io, args);
3231
- default:
3232
- return main(argv, io); // unreachable — ASYNC_COMMANDS guards the switch
3233
- }
3234
- }
3235
- catch (e) {
3236
- if (e instanceof CliError || e instanceof DefError) {
3237
- io.err(`error: ${e.message}`);
3238
- }
3239
- else {
3240
- io.err(`error: ${e.message}`);
3241
- }
3242
- // A CliError carries its own exit code (default 1); everything else is 1.
3243
- return e instanceof CliError ? e.exitCode : 1;
3244
- }
3245
- }
3246
- /** Run the CLI. Returns a process exit code. */
3247
- export function main(argv, io = defaultIO()) {
3248
- const args = parseArgs(argv);
3249
- const command = args.positionals[0];
3250
- if (command === undefined) {
3251
- io.out(USAGE);
3252
- return 0;
3253
- }
3254
- try {
3255
- const short = preflight(command, args, io);
3256
- if (short !== undefined)
3257
- return short;
3258
- return dispatch(command, io, args);
3259
- }
3260
- catch (e) {
3261
- if (e instanceof CliError || e instanceof DefError) {
3262
- io.err(`error: ${e.message}`);
3263
- }
3264
- else {
3265
- io.err(`error: ${e.message}`);
3266
- }
3267
- // A CliError carries its own exit code (default 1); everything else is 1.
3268
- return e instanceof CliError ? e.exitCode : 1;
3269
- }
3270
- }