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
@@ -111,6 +111,16 @@ export function hashDefForHub(yaml) {
111
111
  * and cheap to widen later (a two-way door).
112
112
  */
113
113
  const LOOPBACK_HOSTS = new Set(['localhost', '127.0.0.1', '[::1]']);
114
+ /**
115
+ * The production hub. The sole fallback rung for every hub-resolution ladder
116
+ * in this package that has one (`src/cli.ts`'s `resolveHub` and
117
+ * `resolveSetupHub`, `src/mcp/serve.ts`'s `resolveMcpOrigin`) — there must be
118
+ * exactly one literal `'https://api.owenloop.com'` in `src/`, and this is it.
119
+ * `resolveAgentHub` (`src/cli.ts`) deliberately has NO fallback to this
120
+ * constant: it mints credentials, and silently minting on the wrong org is
121
+ * not undone by a retry.
122
+ */
123
+ export const DEFAULT_HUB = 'https://api.owenloop.com';
114
124
  /**
115
125
  * Normalize a hub URL to a bare origin (`scheme://host[:port]`), stripping any
116
126
  * path, query, trailing slash, and fragment. Requires an http(s) scheme. This
@@ -360,52 +370,101 @@ export function writeCredentialFile(path, file) {
360
370
  chmodSync(dir, 0o700);
361
371
  writeFileAtomic(path, `${JSON.stringify(file, null, 2)}\n`, { mode: 0o600 });
362
372
  }
373
+ const runMacosSecurity = (command) => {
374
+ if (command.captureStdout === true) {
375
+ return execFileSync('security', command.args, {
376
+ encoding: 'utf8',
377
+ stdio: ['ignore', 'pipe', 'ignore'],
378
+ });
379
+ }
380
+ execFileSync('security', command.args, {
381
+ ...(command.input === undefined ? {} : { input: command.input }),
382
+ stdio: command.input === undefined ? 'ignore' : ['pipe', 'ignore', 'ignore'],
383
+ });
384
+ return '';
385
+ };
386
+ function macosSecurityFailure(operation, error) {
387
+ const detail = error;
388
+ if (typeof detail.status === 'number') {
389
+ throw new Error(`macOS Keychain ${operation} failed: security exited with status ${detail.status}`);
390
+ }
391
+ if (typeof detail.signal === 'string') {
392
+ throw new Error(`macOS Keychain ${operation} failed: security terminated by signal ${detail.signal}`);
393
+ }
394
+ const code = typeof detail.code === 'string' ? detail.code : 'unknown error';
395
+ throw new Error(`macOS Keychain ${operation} failed: security could not be run (${code})`);
396
+ }
363
397
  /**
364
- * The default macOS keychain backend (generic passwords under service
365
- * `owenloop:<origin>`, account = the credential slot). The secret is fed through
366
- * the `security -i` command stream on stdin, never as a `-w` argv value, so it
367
- * never appears in `ps`/shell history. Returns `undefined` off macOS or when
368
- * `OWENLOOP_NO_KEYCHAIN=1`, so callers fall back to the 0600 credential file.
398
+ * Build the macOS generic-password backend around an injectable `security`
399
+ * command runner. Status 44 (`errSecItemNotFound`) alone means absence. Every
400
+ * other exit, signal, or start failure is a stable, secret-free error.
369
401
  */
370
- export function defaultKeychain(env) {
371
- if (env.OWENLOOP_NO_KEYCHAIN === '1')
372
- return undefined;
373
- if (process.platform !== 'darwin')
374
- return undefined;
402
+ export function macosKeychain(runner = runMacosSecurity) {
375
403
  return {
376
404
  get(service, account) {
377
405
  try {
378
- const out = execFileSync('security', ['find-generic-password', '-s', service, '-a', account, '-w'], {
379
- encoding: 'utf8',
380
- stdio: ['ignore', 'pipe', 'ignore'],
406
+ const out = runner({
407
+ args: ['find-generic-password', '-s', service, '-a', account, '-w'],
408
+ captureStdout: true,
381
409
  });
382
410
  return out.replace(/\n$/, '');
383
411
  }
384
- catch {
385
- return null; // not found (errSecItemNotFound) — treated as "no credential"
412
+ catch (error) {
413
+ if (error.status === 44)
414
+ return null;
415
+ return macosSecurityFailure('lookup', error);
386
416
  }
387
417
  },
388
418
  set(service, account, value) {
389
419
  // `security -i` reads newline-terminated commands from stdin; the secret
390
420
  // rides in that stdin stream (single-quoted), never on this process's argv.
391
- // The service string now carries `:` and `//` — inert for `security`, but
392
- // the single-quote escaping stays as the general guard it always was.
393
- const sq = (s) => `'${s.replace(/'/g, `'\\''`)}'`;
421
+ // `security -i` treats `\` as an escape character even inside single
422
+ // quotes, so backslashes are doubled before quote escaping.
423
+ const sq = (s) => `'${s.replace(/\\/g, '\\\\').replace(/'/g, `'\\''`)}'`;
394
424
  const cmd = `add-generic-password -U -s ${sq(service)} -a ${sq(account)} -w ${sq(value)}\n`;
395
- execFileSync('security', ['-i'], { input: cmd, stdio: ['pipe', 'ignore', 'ignore'] });
425
+ try {
426
+ runner({ args: ['-i'], input: cmd });
427
+ }
428
+ catch (error) {
429
+ return macosSecurityFailure('write', error);
430
+ }
396
431
  },
397
432
  delete(service, account) {
398
433
  try {
399
- execFileSync('security', ['delete-generic-password', '-s', service, '-a', account], {
400
- stdio: 'ignore',
401
- });
434
+ runner({ args: ['delete-generic-password', '-s', service, '-a', account] });
402
435
  }
403
- catch {
404
- // Not found — already absent; a no-op delete is success.
436
+ catch (error) {
437
+ if (error.status === 44)
438
+ return;
439
+ return macosSecurityFailure('delete', error);
405
440
  }
406
441
  },
407
442
  };
408
443
  }
444
+ /**
445
+ * Every locally available Keychain backend, independent of the ordinary-store
446
+ * override. Defensive logout uses this resolver so `OWENLOOP_NO_KEYCHAIN=1`
447
+ * cannot hide a credential that would become authoritative again when the
448
+ * override is removed. An injected backend remains available on every platform;
449
+ * otherwise only macOS has a platform backend.
450
+ */
451
+ export function resolveLocalKeychain(injected) {
452
+ if (injected !== undefined)
453
+ return injected;
454
+ if (process.platform !== 'darwin')
455
+ return undefined;
456
+ return macosKeychain();
457
+ }
458
+ /**
459
+ * The default Keychain selected for ordinary reads and writes. Returns
460
+ * `undefined` off macOS or when `OWENLOOP_NO_KEYCHAIN=1` selects the 0600 file
461
+ * store. Logout deliberately uses `resolveLocalKeychain` instead.
462
+ */
463
+ export function defaultKeychain(env) {
464
+ if (env.OWENLOOP_NO_KEYCHAIN === '1')
465
+ return undefined;
466
+ return resolveLocalKeychain();
467
+ }
409
468
  /**
410
469
  * The configured external credential command, or `undefined` when it is unset
411
470
  * or blank.
@@ -543,7 +602,7 @@ export function credentialBackend(env, injected) {
543
602
  /**
544
603
  * Read the stored hub credential for `origin` **in the named slot** from the
545
604
  * chosen backend ONLY — the supported, read-only programmatic surface
546
- * (owenwork's CredentialReader seam wires to this once released). Secret hygiene
605
+ * (owenloop's CredentialReader seam wires to this once released). Secret hygiene
547
606
  * is unchanged: this function never logs or echoes the returned credential, and
548
607
  * there is deliberately no write/delete companion on the public surface —
549
608
  * `login` / `logout` remain the only way to store or remove a credential.
@@ -575,13 +634,11 @@ export function credentialBackend(env, injected) {
575
634
  * never `process.env` directly, so a caller passing `opts.env` stays hermetic;
576
635
  * only the top-level default falls back to `process.env`.
577
636
  *
578
- * **When `OWENLOOP_CREDENTIAL_COMMAND` is configured this function can THROW
579
- * instead of returning `null`**, and it does not consult a store at all. The
580
- * command is authoritative, so a nonzero exit, a timeout, empty output, or
581
- * output that is not a well-formed credential is a loud error naming the origin
582
- * and the slot — never a silent fallthrough to a stale local entry. See
583
- * `runCredentialCommand`. When it is NOT configured, behaviour is exactly what
584
- * it has always been.
637
+ * **An authoritative backend failure throws instead of returning `null`.** For
638
+ * `OWENLOOP_CREDENTIAL_COMMAND`, a nonzero exit, timeout, empty output, or
639
+ * malformed credential is a loud error naming the origin and slot. For the
640
+ * macOS Keychain, every `security` failure except status 44 is a stable,
641
+ * secret-free error. Neither backend falls through to a stale file entry.
585
642
  */
586
643
  export function readStoredCredential(origin, opts) {
587
644
  const env = opts.env ?? process.env;
@@ -614,11 +671,37 @@ export function readStoredCredential(origin, opts) {
614
671
  * Enumerate the hub origins that have a usable `human` credential stored, or
615
672
  * `null` when the active backend cannot be enumerated.
616
673
  *
617
- * Consumer: `owenloop mcp`'s origin inference (`resolveMcpOrigin` in
618
- * `src/mcp/serve.ts`). When the host spawns the server with neither `--hub` nor
619
- * `OWENLOOP_HUB`, the server tries to infer the single hub the user is logged
620
- * in to. That inference is only sound on the FILE backend, which can list its
621
- * `hubs` map; the keychain and external-command backends cannot enumerate:
674
+ * Callers in `src/cli.ts` share a backend-aware discovery layer, while
675
+ * `src/mcp/serve.ts` consumes this fact directly. Their policies deliberately
676
+ * differ, turning the same three possible results (`null`, `[]`, length>1)
677
+ * into different outcomes:
678
+ *
679
+ * - `resolveAgentHub` (`agent new`, `capability bind|unbind|list`, and
680
+ * `crew`'s subcommands) — mutating, mint-like commands. Every non-single
681
+ * result (`null`, `[]`, or length>1) is an immediate `CliError` (exit 2)
682
+ * naming `--hub <origin>` as the fix. There is no `DEFAULT_HUB` fallback
683
+ * here at all: silently minting against the production hub while the
684
+ * operator is logged into a dev hub would mint on the wrong org, and a mint
685
+ * is not undone by a retry.
686
+ * - `resolveSetupHub` (`setup`, `doctor`) — `null` or `[]` fall back to
687
+ * `DEFAULT_HUB` with a printed notice so the operator can see what
688
+ * happened; length>1 is still a `CliError` (exit 2) naming the origins,
689
+ * because guessing among several logged-in hubs would be silently wrong for
690
+ * someone who has more than one.
691
+ * - `resolvePublishingHub` (`connect`, `push`, `publish`) — one file-backed
692
+ * origin is the global fallback; more than one or none is an exit-2 error.
693
+ * For `null`, and only for `null`, this policy may use the validated
694
+ * execution-settings `hubOrigin` after checking the requested credential
695
+ * slot. It never guesses `DEFAULT_HUB`.
696
+ * - `resolveMcpOrigin` (`owenloop mcp`'s origin ladder) — the most lenient:
697
+ * this is rung 4 of 5, tried only after `--hub`, `OWENLOOP_HUB`, and
698
+ * `~/.owenloop/config.json` have all had nothing to offer. `null`, `[]`,
699
+ * and length>1 are ALL just "this rung has nothing to offer either" and
700
+ * fall through silently to rung 5 (`DEFAULT_HUB`) — there is no error path
701
+ * left to reach from here.
702
+ *
703
+ * The backend determines whether enumeration is even possible in the first
704
+ * place, independent of which of the three callers is asking:
622
705
  *
623
706
  * - **file** → the origins in `readCredentialFile(credentialFilePath(env)).hubs`
624
707
  * whose `human` slot parses as a well-formed `Credential` (`parseCredential`).
@@ -633,10 +716,10 @@ export function readStoredCredential(origin, opts) {
633
716
  * - **external** → `null`, for the same reason: the command answers a single
634
717
  * `(origin, slot)` query; it has no listing contract.
635
718
  *
636
- * `null` (cannot enumerate), `[]` (nothing stored), and a length>1 result are
637
- * all distinct signals the caller turns into tailored exit-2 messages — this
638
- * function reports the fact, it never decides the outcome. It never logs or
639
- * echoes any credential; only the origin KEYS (never secrets) are returned.
719
+ * This function only reports the fact (and the backend-level reason behind
720
+ * it); it never decides the outcome — that is each caller's job, per the list
721
+ * above. It never logs or echoes any credential; only the origin KEYS (never
722
+ * secrets) are returned.
640
723
  *
641
724
  * `env`/`keychain` are threaded exactly as `readStoredCredential` threads them,
642
725
  * so a caller passing a fixture `env` stays hermetic.
@@ -806,7 +889,7 @@ export function asWhoami(body) {
806
889
  * FIELD only — it never echoes a field VALUE. A malformed body could still carry
807
890
  * the `olp_` plaintext (in `text`, or in a mistyped `token`), so echoing values
808
891
  * here would be the exact leak §6 forbids. `id`/`agentId` must be non-empty
809
- * strings; `token` a non-empty string starting `olp_`; `pools` an array of
892
+ * strings; `token` a non-empty string starting `olp_`; `crews` an array of
810
893
  * strings (empty allowed defensively — the server always resolves at least one,
811
894
  * but the client does not depend on that to stay leak-safe).
812
895
  */
@@ -827,17 +910,17 @@ export function asMintAgentTokenOk(body) {
827
910
  if (!b.token.startsWith('olp_')) {
828
911
  throw new Error('mint_agent_token: malformed success response — token is not an olp_ token');
829
912
  }
830
- if (!Array.isArray(b.pools) || b.pools.some((p) => typeof p !== 'string')) {
831
- throw new Error('mint_agent_token: malformed success response — pools must be an array of strings');
913
+ if (!Array.isArray(b.crews) || b.crews.some((p) => typeof p !== 'string')) {
914
+ throw new Error('mint_agent_token: malformed success response — crews must be an array of strings');
832
915
  }
833
- return { id: b.id, token: b.token, agentId: b.agentId, pools: b.pools };
916
+ return { id: b.id, token: b.token, agentId: b.agentId, crews: b.crews };
834
917
  }
835
918
  /**
836
919
  * Narrow `GET /api/agent_identities`'s 200 body (`{identities: [...]}`) to a
837
920
  * typed array. Throws on a malformed body (missing `identities` array, or a row
838
921
  * missing `id`/`name`). Non-secret shape — the rows carry no token — so errors
839
922
  * may name indices/fields freely. `lastContactAt`/`lastUsedAt` tolerate `null`
840
- * or absence (→ `null`) but reject a present non-number; `pools` defaults to an
923
+ * or absence (→ `null`) but reject a present non-number; `crews` defaults to an
841
924
  * empty array when absent, rejects a present non-array-of-strings; `disabled`
842
925
  * defaults to `false`.
843
926
  */
@@ -864,23 +947,381 @@ export function asAgentIdentities(body) {
864
947
  throw new Error(`agent_identities: malformed response — identities[${i}].${field} must be a number or null`);
865
948
  return v;
866
949
  };
867
- let pools = [];
868
- if (e.pools !== undefined) {
869
- if (!Array.isArray(e.pools) || e.pools.some((p) => typeof p !== 'string')) {
870
- throw new Error(`agent_identities: malformed response — identities[${i}].pools must be an array of strings`);
950
+ let crews = [];
951
+ if (e.crews !== undefined) {
952
+ if (!Array.isArray(e.crews) || e.crews.some((p) => typeof p !== 'string')) {
953
+ throw new Error(`agent_identities: malformed response — identities[${i}].crews must be an array of strings`);
871
954
  }
872
- pools = e.pools;
955
+ crews = e.crews;
873
956
  }
874
957
  return {
875
958
  id: e.id,
876
959
  name: e.name,
877
960
  disabled: e.disabled === true,
878
- pools,
961
+ crews,
879
962
  lastContactAt: epochOrNull(e.lastContactAt, 'lastContactAt'),
880
963
  lastUsedAt: epochOrNull(e.lastUsedAt, 'lastUsedAt'),
881
964
  };
882
965
  });
883
966
  }
967
+ /**
968
+ * Validate the five common `CapabilityRouteWire` fields on one row. `prefix` is the
969
+ * endpoint-qualified lead-in the caller wants (e.g.
970
+ * `add_capability_route: malformed success response`) and `where` names the
971
+ * offending position (`route`, or `routes[2]`) — a FIELD/INDEX name only,
972
+ * never a value.
973
+ *
974
+ * `crewName` is validated LENIENTLY here, unlike the other four fields: absent or
975
+ * `null` both yield `null`, because `null` is the hub's own answer for a dangling
976
+ * route. A caller that additionally KNOWS its crew is live (`asCapabilityRouteAdded`
977
+ * resolves by name) layers its own non-null check on top of this shared call.
978
+ */
979
+ function asCapabilityRouteRow(entry, prefix, where) {
980
+ if (typeof entry !== 'object' || entry === null) {
981
+ throw new Error(`${prefix} — ${where} is not an object`);
982
+ }
983
+ const e = entry;
984
+ for (const field of ['capability', 'crewId', 'createdBy']) {
985
+ if (typeof e[field] !== 'string' || e[field] === '') {
986
+ throw new Error(`${prefix} — ${where} missing non-empty string ${field}`);
987
+ }
988
+ }
989
+ if (typeof e.createdAt !== 'number') {
990
+ throw new Error(`${prefix} — ${where} missing number createdAt`);
991
+ }
992
+ // Lenient exactly like `asCrewRow`'s `ownerMemberId`: absent or null both mean
993
+ // "no name to report" — here, a DANGLING route whose crew row is gone.
994
+ let crewName = null;
995
+ if (e.crewName !== undefined && e.crewName !== null) {
996
+ if (typeof e.crewName !== 'string' || e.crewName === '') {
997
+ throw new Error(`${prefix} — ${where} crewName must be a non-empty string or null`);
998
+ }
999
+ crewName = e.crewName;
1000
+ }
1001
+ return {
1002
+ capability: e.capability,
1003
+ crewId: e.crewId,
1004
+ crewName,
1005
+ createdBy: e.createdBy,
1006
+ createdAt: e.createdAt,
1007
+ };
1008
+ }
1009
+ /**
1010
+ * Narrow `POST /api/add_capability_route`'s 200 body
1011
+ * (`{ text, route, alreadyRouted, routedCrewCount }`). Throws on anything
1012
+ * malformed, naming the offending FIELD only — same discipline as
1013
+ * `asAgentIdentities`, so no body value is echoed.
1014
+ *
1015
+ * `route.crewName` is required to be a NON-NULL non-empty string here, on top
1016
+ * of `asCapabilityRouteRow`'s lenient check. That is not a contradiction: an add
1017
+ * resolves its crew BY NAME, so the crew is live by construction and a `null`
1018
+ * name in THIS response is genuinely malformed — whereas a `null` name in a
1019
+ * `capability_routes` row is the legitimate dangling-route case. Layering a
1020
+ * call-site-specific check on top of the shared row call is the established
1021
+ * shape in this family, not a new pattern.
1022
+ */
1023
+ export function asCapabilityRouteAdded(body) {
1024
+ const prefix = 'add_capability_route: malformed success response';
1025
+ if (typeof body !== 'object' || body === null) {
1026
+ throw new Error(`${prefix} — not an object`);
1027
+ }
1028
+ const b = body;
1029
+ if (b.route === undefined) {
1030
+ throw new Error(`${prefix} — missing route`);
1031
+ }
1032
+ const route = asCapabilityRouteRow(b.route, prefix, 'route');
1033
+ if (route.crewName === null) {
1034
+ throw new Error(`${prefix} — route missing non-empty string crewName`);
1035
+ }
1036
+ if (typeof b.alreadyRouted !== 'boolean') {
1037
+ throw new Error(`${prefix} — missing boolean alreadyRouted`);
1038
+ }
1039
+ if (typeof b.routedCrewCount !== 'number') {
1040
+ throw new Error(`${prefix} — missing number routedCrewCount`);
1041
+ }
1042
+ return { route, alreadyRouted: b.alreadyRouted, routedCrewCount: b.routedCrewCount };
1043
+ }
1044
+ /**
1045
+ * Narrow `POST /api/remove_capability_route`'s 200 body
1046
+ * (`{ text, capability, crewId, removed, remainingCrewIds }`).
1047
+ *
1048
+ * `removed` must be a BOOLEAN — this guard is how the CLI proves the 2xx really
1049
+ * was the remove verb's answer. BOTH boolean values are valid, deliberate hub
1050
+ * responses:
1051
+ * - `true` — the `(capability, crew)` pair was bound and is now removed;
1052
+ * - `false` — the pair was never bound, so there was nothing to do. The hub
1053
+ * answers this with a 200, never a 404 (the `removeCrewMember` `{existed}`
1054
+ * house pattern), and that tolerance is what makes `capability unbind` idempotent.
1055
+ *
1056
+ * `crewId` is LENIENT (absent or `null` both yield `null`) because `null` is a
1057
+ * real hub output, not a defect: `manage-capability-routes.ts` resolves it as
1058
+ * `namedCrew?.id ?? thisCapabilityRows.find(...)?.crewId ?? null`, so it is `null`
1059
+ * on exactly the tolerant `removed: false` path where the argument matched
1060
+ * neither a live crew name nor one of this capability's own route rows. Requiring a
1061
+ * non-empty string here would throw on a normal success.
1062
+ *
1063
+ * `remainingCrewIds` is deliberately NOT lenient — it must be PRESENT and an
1064
+ * array of non-empty strings. The asymmetry is the point: for a nullable name,
1065
+ * the lenient default (`null`) is the SAFE reading, but defaulting an absent
1066
+ * `remainingCrewIds` to `[]` would assert "this capability is now PARKED" — the
1067
+ * alarming reading, and exactly the signal an operator acts on — off a malformed
1068
+ * body. It lists LIVE crews only, so `[]` genuinely means zero live routes
1069
+ * remain (which can happen while a dangling row survives, since such a row routes
1070
+ * nothing).
1071
+ *
1072
+ * The stdout shape built from this is documented in `docs/cli.md`'s
1073
+ * "Printed JSON" table under capability routes.
1074
+ */
1075
+ export function asCapabilityRouteRemoved(body) {
1076
+ const prefix = 'remove_capability_route: malformed success response';
1077
+ if (typeof body !== 'object' || body === null) {
1078
+ throw new Error(`${prefix} — not an object`);
1079
+ }
1080
+ const b = body;
1081
+ if (typeof b.removed !== 'boolean') {
1082
+ throw new Error(`${prefix} — missing boolean removed`);
1083
+ }
1084
+ if (typeof b.capability !== 'string' || b.capability === '') {
1085
+ throw new Error(`${prefix} — missing non-empty string capability`);
1086
+ }
1087
+ let crewId = null;
1088
+ if (b.crewId !== undefined && b.crewId !== null) {
1089
+ if (typeof b.crewId !== 'string' || b.crewId === '') {
1090
+ throw new Error(`${prefix} — crewId must be a non-empty string or null`);
1091
+ }
1092
+ crewId = b.crewId;
1093
+ }
1094
+ if (!Array.isArray(b.remainingCrewIds)) {
1095
+ throw new Error(`${prefix} — missing array remainingCrewIds`);
1096
+ }
1097
+ const remainingCrewIds = b.remainingCrewIds.map((entry, i) => {
1098
+ if (typeof entry !== 'string' || entry === '') {
1099
+ throw new Error(`${prefix} — remainingCrewIds[${i}] is not a non-empty string`);
1100
+ }
1101
+ return entry;
1102
+ });
1103
+ return { capability: b.capability, crewId, removed: b.removed, remainingCrewIds };
1104
+ }
1105
+ /**
1106
+ * Narrow `GET /api/capability_routes`'s 200 body (`{ text, routes: [...] }`) to a
1107
+ * typed array. An EMPTY array is valid — that is the "this org has no routes
1108
+ * yet" case, not an error.
1109
+ *
1110
+ * Rows are plain `CapabilityRouteWire`, ONE per `(capability, crew)` pair ordered by
1111
+ * `capability, crew_id`, so a capability bound to many crews yields MANY rows — the array
1112
+ * is forwarded as-is and must never be collapsed into a per-capability map. A row
1113
+ * whose `crewName` is `null` is a dangling route and is kept, not dropped.
1114
+ */
1115
+ export function asCapabilityRoutes(body) {
1116
+ if (typeof body !== 'object' || body === null || !Array.isArray(body.routes)) {
1117
+ throw new Error('capability_routes: malformed response — expected a `routes` array');
1118
+ }
1119
+ const list = body.routes;
1120
+ return list.map((entry, i) => asCapabilityRouteRow(entry, 'capability_routes: malformed response', `routes[${i}]`));
1121
+ }
1122
+ /**
1123
+ * The `orphan:` prefix the hub uses to name its reserved orphan crew
1124
+ * (`packages/hub-core/src/crews-table.ts` / `verbs/manage-crews.ts`). Mirrored
1125
+ * here as a named constant — not an invention — so a future reader can tell at
1126
+ * a glance that this string is copied from the hub's source of truth, not
1127
+ * independently chosen.
1128
+ */
1129
+ const ORPHAN_CREW_NAME_PREFIX = 'orphan:';
1130
+ /**
1131
+ * Validate the common `CrewWire` fields on one row. `prefix` is the
1132
+ * endpoint-qualified lead-in (e.g. `crews: malformed response`) and `where`
1133
+ * names the offending position (`crew`, or `crews[2]`) — a FIELD/INDEX name
1134
+ * only, never a value, mirroring `asCapabilityRouteRow`'s discipline exactly.
1135
+ */
1136
+ function asCrewRow(entry, prefix, where) {
1137
+ if (typeof entry !== 'object' || entry === null) {
1138
+ throw new Error(`${prefix} — ${where} is not an object`);
1139
+ }
1140
+ const e = entry;
1141
+ for (const field of ['id', 'name', 'kind', 'createdBy']) {
1142
+ if (typeof e[field] !== 'string' || e[field] === '') {
1143
+ throw new Error(`${prefix} — ${where} missing non-empty string ${field}`);
1144
+ }
1145
+ }
1146
+ if (typeof e.createdAt !== 'number') {
1147
+ throw new Error(`${prefix} — ${where} missing number createdAt`);
1148
+ }
1149
+ // Lenient exactly like `asCapabilityRouteRow`'s `crewName`: absent or null both
1150
+ // mean "no owner" — a serializer that drops `undefined` must not turn a valid
1151
+ // shared crew into a hard failure.
1152
+ let ownerMemberId = null;
1153
+ if (e.ownerMemberId !== undefined && e.ownerMemberId !== null) {
1154
+ if (typeof e.ownerMemberId !== 'string' || e.ownerMemberId === '') {
1155
+ throw new Error(`${prefix} — ${where} ownerMemberId must be a non-empty string or null`);
1156
+ }
1157
+ ownerMemberId = e.ownerMemberId;
1158
+ }
1159
+ return {
1160
+ id: e.id,
1161
+ name: e.name,
1162
+ kind: e.kind,
1163
+ ownerMemberId,
1164
+ createdBy: e.createdBy,
1165
+ createdAt: e.createdAt,
1166
+ };
1167
+ }
1168
+ /**
1169
+ * Validate one `CrewMemberWire` row. The wire row also carries `crewId`; it is
1170
+ * deliberately NOT validated and NOT printed here, because inside
1171
+ * `crews[i].members[j]` it is structurally the enclosing crew's `id` and
1172
+ * repeating it adds no information.
1173
+ */
1174
+ function asCrewMemberRow(entry, prefix, where) {
1175
+ if (typeof entry !== 'object' || entry === null) {
1176
+ throw new Error(`${prefix} — ${where} is not an object`);
1177
+ }
1178
+ const e = entry;
1179
+ for (const field of ['principalKind', 'principalId', 'addedBy']) {
1180
+ if (typeof e[field] !== 'string' || e[field] === '') {
1181
+ throw new Error(`${prefix} — ${where} missing non-empty string ${field}`);
1182
+ }
1183
+ }
1184
+ if (typeof e.addedAt !== 'number') {
1185
+ throw new Error(`${prefix} — ${where} missing number addedAt`);
1186
+ }
1187
+ return {
1188
+ principalKind: e.principalKind,
1189
+ principalId: e.principalId,
1190
+ addedBy: e.addedBy,
1191
+ addedAt: e.addedAt,
1192
+ };
1193
+ }
1194
+ /**
1195
+ * Narrow `GET /api/crews`'s 200 body (`{ text, crews: [...] }`) to a typed
1196
+ * array. An EMPTY array is valid (a brand-new org). `GET /api/crews`
1197
+ * deliberately returns the org's reserved orphan crew when it exists — this
1198
+ * never filters it out; instead every row gets a derived `orphan` boolean,
1199
+ * always present (`true` or `false`), so a scripted consumer never branches on
1200
+ * the key's existence.
1201
+ */
1202
+ export function asCrews(body) {
1203
+ if (typeof body !== 'object' || body === null || !Array.isArray(body.crews)) {
1204
+ throw new Error('crews: malformed response — expected a `crews` array');
1205
+ }
1206
+ const list = body.crews;
1207
+ const prefix = 'crews: malformed response';
1208
+ return list.map((entry, i) => {
1209
+ const row = asCrewRow(entry, prefix, `crews[${i}]`);
1210
+ const e = entry;
1211
+ if (!Array.isArray(e.members)) {
1212
+ throw new Error(`${prefix} — crews[${i}] missing members array`);
1213
+ }
1214
+ const members = e.members.map((m, j) => asCrewMemberRow(m, prefix, `crews[${i}].members[${j}]`));
1215
+ const orphan = row.kind === 'orphan' || row.name.startsWith(ORPHAN_CREW_NAME_PREFIX);
1216
+ return { ...row, orphan, members };
1217
+ });
1218
+ }
1219
+ /**
1220
+ * Narrow `POST /api/create_crew`'s 200 body (`{ text, crew }`) to the typed
1221
+ * row.
1222
+ */
1223
+ export function asCrewCreated(body) {
1224
+ const prefix = 'create_crew: malformed success response';
1225
+ if (typeof body !== 'object' || body === null) {
1226
+ throw new Error(`${prefix} — not an object`);
1227
+ }
1228
+ const b = body;
1229
+ if (b.crew === undefined) {
1230
+ throw new Error(`${prefix} — missing crew`);
1231
+ }
1232
+ return asCrewRow(b.crew, prefix, 'crew');
1233
+ }
1234
+ /**
1235
+ * Narrow `POST /api/delete_crew`'s 200 body. `crewId` and `deleted` are always
1236
+ * present (`deleted` is a genuine boolean — both values are valid, deliberate
1237
+ * hub answers, exactly like `asCapabilityRouteRemoved`). Each of the six transfer
1238
+ * fields is validated ONLY IF PRESENT and OMITTED from the returned object when
1239
+ * absent — never defaulted to `0`, `null`, or `[]`. Absence is the hub's way of
1240
+ * saying "nothing moved"; default-filling would assert a transfer that never
1241
+ * happened. `runsTransferred`/`runningRunsTransferred` are ARRAYS OF IDS, not
1242
+ * counts — `stampsTransferred`/`membersRemoved` are the counts.
1243
+ */
1244
+ export function asCrewDeleted(body) {
1245
+ const prefix = 'delete_crew: malformed success response';
1246
+ if (typeof body !== 'object' || body === null) {
1247
+ throw new Error(`${prefix} — not an object`);
1248
+ }
1249
+ const b = body;
1250
+ if (typeof b.crewId !== 'string' || b.crewId === '') {
1251
+ throw new Error(`${prefix} — missing non-empty string crewId`);
1252
+ }
1253
+ if (typeof b.deleted !== 'boolean') {
1254
+ throw new Error(`${prefix} — missing boolean deleted`);
1255
+ }
1256
+ const out = { crewId: b.crewId, deleted: b.deleted };
1257
+ const numberIfPresent = (field) => {
1258
+ if (b[field] === undefined)
1259
+ return;
1260
+ if (typeof b[field] !== 'number') {
1261
+ throw new Error(`${prefix} — ${field} must be a number`);
1262
+ }
1263
+ out[field] = b[field];
1264
+ };
1265
+ const stringIfPresent = (field) => {
1266
+ if (b[field] === undefined)
1267
+ return;
1268
+ if (typeof b[field] !== 'string' || b[field] === '') {
1269
+ throw new Error(`${prefix} — ${field} must be a non-empty string`);
1270
+ }
1271
+ out[field] = b[field];
1272
+ };
1273
+ const stringArrayIfPresent = (field) => {
1274
+ if (b[field] === undefined)
1275
+ return;
1276
+ const v = b[field];
1277
+ if (!Array.isArray(v) || v.some((x) => typeof x !== 'string' || x === '')) {
1278
+ throw new Error(`${prefix} — ${field} must be an array of strings`);
1279
+ }
1280
+ out[field] = v;
1281
+ };
1282
+ numberIfPresent('membersRemoved');
1283
+ stringIfPresent('orphanCrewId');
1284
+ stringIfPresent('orphanCrewName');
1285
+ numberIfPresent('stampsTransferred');
1286
+ stringArrayIfPresent('runsTransferred');
1287
+ stringArrayIfPresent('runningRunsTransferred');
1288
+ return out;
1289
+ }
1290
+ /** Narrow `POST /api/add_crew_member`'s 200 body (`{ text, member }`) to the typed row. */
1291
+ export function asCrewMemberAdded(body) {
1292
+ const prefix = 'add_crew_member: malformed success response';
1293
+ if (typeof body !== 'object' || body === null) {
1294
+ throw new Error(`${prefix} — not an object`);
1295
+ }
1296
+ const b = body;
1297
+ if (b.member === undefined) {
1298
+ throw new Error(`${prefix} — missing member`);
1299
+ }
1300
+ return asCrewMemberRow(b.member, prefix, 'member');
1301
+ }
1302
+ /**
1303
+ * Narrow `POST /api/remove_crew_member`'s 200 body (`{ text, crewId,
1304
+ * principalId, removed }`). `removed` must be a genuine boolean — both values
1305
+ * are valid, deliberate hub answers: `false` means the principal was never a
1306
+ * member (tolerant, a normal success), exactly like `asCapabilityRouteRemoved`.
1307
+ */
1308
+ export function asCrewMemberRemoved(body) {
1309
+ const prefix = 'remove_crew_member: malformed success response';
1310
+ if (typeof body !== 'object' || body === null) {
1311
+ throw new Error(`${prefix} — not an object`);
1312
+ }
1313
+ const b = body;
1314
+ if (typeof b.crewId !== 'string' || b.crewId === '') {
1315
+ throw new Error(`${prefix} — missing non-empty string crewId`);
1316
+ }
1317
+ if (typeof b.principalId !== 'string' || b.principalId === '') {
1318
+ throw new Error(`${prefix} — missing non-empty string principalId`);
1319
+ }
1320
+ if (typeof b.removed !== 'boolean') {
1321
+ throw new Error(`${prefix} — missing boolean removed`);
1322
+ }
1323
+ return { crewId: b.crewId, principalId: b.principalId, removed: b.removed };
1324
+ }
884
1325
  /**
885
1326
  * Narrow a `POST /api/rekey_agent_token` 200 body to its typed success shape.
886
1327
  * Mirrors `asMintAgentTokenOk`'s discipline exactly: STRICT validation of the