owenloop 0.5.0 → 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 (211) hide show
  1. package/CHANGELOG.md +45 -0
  2. package/README.md +137 -35
  3. package/bin/owenloop.mjs +49 -1
  4. package/dist/packages/work/src/agent/brief.d.ts +8 -4
  5. package/dist/packages/work/src/agent/brief.js +7 -3
  6. package/dist/packages/work/src/agent/loop.d.ts +13 -7
  7. package/dist/packages/work/src/agent/loop.js +136 -9
  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/bundle/cache.d.ts +7 -5
  11. package/dist/packages/work/src/bundle/cache.js +20 -6
  12. package/dist/packages/work/src/bundle/fetch.d.ts +7 -5
  13. package/dist/packages/work/src/bundle/fetch.js +27 -7
  14. package/dist/packages/work/src/bundle/types.d.ts +8 -4
  15. package/dist/packages/work/src/consumed-verifier.d.ts +45 -0
  16. package/dist/packages/work/src/consumed-verifier.js +205 -0
  17. package/dist/packages/work/src/exec/instructions.d.ts +99 -0
  18. package/dist/packages/work/src/exec/instructions.js +323 -0
  19. package/dist/packages/work/src/exec/loop.d.ts +12 -1
  20. package/dist/packages/work/src/exec/loop.js +137 -20
  21. package/dist/packages/work/src/exec/payload.d.ts +29 -0
  22. package/dist/packages/work/src/exec/payload.js +54 -0
  23. package/dist/packages/work/src/exec/receipt.d.ts +9 -6
  24. package/dist/packages/work/src/exec/receipt.js +12 -1
  25. package/dist/packages/work/src/exec/runner.d.ts +7 -1
  26. package/dist/packages/work/src/exec/runner.js +74 -3
  27. package/dist/packages/work/src/harness/child-env.js +7 -0
  28. package/dist/packages/work/src/harness/claude.d.ts +20 -8
  29. package/dist/packages/work/src/harness/claude.js +260 -58
  30. package/dist/packages/work/src/harness/codex.d.ts +5 -4
  31. package/dist/packages/work/src/harness/codex.js +169 -41
  32. package/dist/packages/work/src/harness/contract.d.ts +36 -11
  33. package/dist/packages/work/src/harness/fake.js +1 -0
  34. package/dist/packages/work/src/harness/jsonrpc-stdio.js +7 -0
  35. package/dist/packages/work/src/harness/permissions.d.ts +16 -3
  36. package/dist/packages/work/src/harness/permissions.js +102 -13
  37. package/dist/packages/work/src/harness/session-store.d.ts +27 -9
  38. package/dist/packages/work/src/harness/session-store.js +271 -67
  39. package/dist/packages/work/src/hold/mcp.d.ts +25 -5
  40. package/dist/packages/work/src/hold/mcp.js +126 -11
  41. package/dist/packages/work/src/hub/client.d.ts +2 -1
  42. package/dist/packages/work/src/hub/client.js +14 -1
  43. package/dist/packages/work/src/hub/types.d.ts +69 -33
  44. package/dist/packages/work/src/hub/types.js +8 -10
  45. package/dist/packages/work/src/mcp/server.js +1 -1
  46. package/dist/packages/work/src/owenloop-bin.d.ts +1 -0
  47. package/dist/packages/work/src/owenloop-bin.js +18 -0
  48. package/dist/packages/work/src/roles/agent-run.d.ts +12 -6
  49. package/dist/packages/work/src/roles/agent-run.js +116 -34
  50. package/dist/packages/work/src/roles/exec.d.ts +8 -0
  51. package/dist/packages/work/src/roles/exec.js +27 -2
  52. package/dist/packages/work/src/roles/hold.d.ts +4 -0
  53. package/dist/packages/work/src/roles/hold.js +44 -5
  54. package/dist/packages/work/src/roles/lint.d.ts +3 -4
  55. package/dist/packages/work/src/roles/lint.js +41 -7
  56. package/dist/packages/work/src/roles/settings.js +5 -0
  57. package/dist/packages/work/src/roles/shift.d.ts +1 -0
  58. package/dist/packages/work/src/roles/shift.js +23 -1
  59. package/dist/packages/work/src/settings/settings.d.ts +17 -1
  60. package/dist/packages/work/src/settings/settings.js +39 -0
  61. package/dist/packages/work/src/shift/loop.d.ts +14 -3
  62. package/dist/packages/work/src/shift/loop.js +447 -164
  63. package/dist/packages/work/src/shift/protocol.d.ts +4 -0
  64. package/dist/packages/work/src/shift/runtime.d.ts +2 -0
  65. package/dist/packages/work/src/shift/runtime.js +66 -3
  66. package/dist/packages/work/src/shift/spawn.d.ts +41 -18
  67. package/dist/packages/work/src/shift/spawn.js +89 -31
  68. package/dist/packages/work/src/shift/state.d.ts +53 -51
  69. package/dist/packages/work/src/shift/state.js +325 -102
  70. package/dist/packages/work/src/submit-proof.d.ts +36 -0
  71. package/dist/packages/work/src/submit-proof.js +93 -0
  72. package/dist/src/add.d.ts +64 -259
  73. package/dist/src/add.js +81 -615
  74. package/dist/src/archive.d.ts +97 -0
  75. package/dist/src/archive.js +591 -0
  76. package/dist/src/bundle/index.d.ts +64 -0
  77. package/dist/src/bundle/index.js +508 -0
  78. package/dist/src/bundle/manifest.d.ts +50 -0
  79. package/dist/src/bundle/manifest.js +435 -0
  80. package/dist/src/bundle/runtime.d.ts +26 -0
  81. package/dist/src/bundle/runtime.js +64 -0
  82. package/dist/src/bundle/tar.d.ts +62 -0
  83. package/dist/src/bundle/tar.js +238 -0
  84. package/dist/src/bundle/types.d.ts +105 -0
  85. package/dist/src/bundle/types.js +21 -0
  86. package/dist/src/cli.d.ts +90 -20
  87. package/dist/src/cli.js +2407 -365
  88. package/dist/src/credentials.d.ts +4 -3
  89. package/dist/src/credentials.js +21 -19
  90. package/dist/src/crypto/allowed-signers.d.ts +68 -0
  91. package/dist/src/crypto/allowed-signers.js +307 -0
  92. package/dist/src/crypto/canonical.d.ts +8 -0
  93. package/dist/src/crypto/canonical.js +92 -0
  94. package/dist/src/crypto/chain.d.ts +65 -0
  95. package/dist/src/crypto/chain.js +377 -0
  96. package/dist/src/crypto/dsse.d.ts +209 -0
  97. package/dist/src/crypto/dsse.js +282 -0
  98. package/dist/src/crypto/enrollment.d.ts +78 -0
  99. package/dist/src/crypto/enrollment.js +186 -0
  100. package/dist/src/crypto/index.d.ts +48 -0
  101. package/dist/src/crypto/index.js +44 -0
  102. package/dist/src/crypto/keys.d.ts +258 -0
  103. package/dist/src/crypto/keys.js +908 -0
  104. package/dist/src/crypto/org-root.d.ts +33 -0
  105. package/dist/src/crypto/org-root.js +78 -0
  106. package/dist/src/crypto/origin-rules.d.ts +56 -0
  107. package/dist/src/crypto/origin-rules.js +143 -0
  108. package/dist/src/crypto/policy-floor.d.ts +98 -0
  109. package/dist/src/crypto/policy-floor.js +353 -0
  110. package/dist/src/crypto/records.d.ts +316 -0
  111. package/dist/src/crypto/records.js +157 -0
  112. package/dist/src/crypto/scope.d.ts +49 -0
  113. package/dist/src/crypto/scope.js +83 -0
  114. package/dist/src/crypto/ssh.d.ts +171 -0
  115. package/dist/src/crypto/ssh.js +396 -0
  116. package/dist/src/crypto/submission.d.ts +33 -0
  117. package/dist/src/crypto/submission.js +47 -0
  118. package/dist/src/crypto/trust-roots.d.ts +29 -0
  119. package/dist/src/crypto/trust-roots.js +39 -0
  120. package/dist/src/crypto/verify-consumed.d.ts +67 -0
  121. package/dist/src/crypto/verify-consumed.js +259 -0
  122. package/dist/src/crypto/verify-origin.d.ts +50 -0
  123. package/dist/src/crypto/verify-origin.js +151 -0
  124. package/dist/src/crypto/verify-publication.d.ts +60 -0
  125. package/dist/src/crypto/verify-publication.js +150 -0
  126. package/dist/src/defs.d.ts +24 -1
  127. package/dist/src/defs.js +145 -25
  128. package/dist/src/engine.d.ts +99 -3
  129. package/dist/src/engine.js +238 -34
  130. package/dist/src/factory.d.ts +16 -0
  131. package/dist/src/factory.js +16 -4
  132. package/dist/src/global-config.d.ts +59 -0
  133. package/dist/src/global-config.js +84 -0
  134. package/dist/src/hub.d.ts +75 -21
  135. package/dist/src/hub.js +123 -40
  136. package/dist/src/index.d.ts +17 -2
  137. package/dist/src/index.js +20 -2
  138. package/dist/src/install.d.ts +538 -0
  139. package/dist/src/install.js +1981 -0
  140. package/dist/src/lock.d.ts +15 -57
  141. package/dist/src/lock.js +251 -143
  142. package/dist/src/mcp/serve.d.ts +46 -22
  143. package/dist/src/mcp/serve.js +167 -44
  144. package/dist/src/mcp/server.js +12 -1
  145. package/dist/src/model.d.ts +15 -0
  146. package/dist/src/model.js +111 -1
  147. package/dist/src/order-resolver.d.ts +184 -0
  148. package/dist/src/order-resolver.js +252 -0
  149. package/dist/src/package-version.d.ts +10 -0
  150. package/dist/src/package-version.js +42 -0
  151. package/dist/src/paths.d.ts +14 -1
  152. package/dist/src/paths.js +18 -0
  153. package/dist/src/schemas/enrollment-grant.v1.schema.json +90 -0
  154. package/dist/src/schemas/index.d.ts +1416 -0
  155. package/dist/src/schemas/index.js +31 -0
  156. package/dist/src/schemas/order.v1.schema.json +106 -0
  157. package/dist/src/schemas/origin.v1.schema.json +68 -0
  158. package/dist/src/schemas/policy-floor.v1.schema.json +29 -0
  159. package/dist/src/schemas/publication.v1.schema.json +31 -0
  160. package/dist/src/schemas/revocation.v1.schema.json +39 -0
  161. package/dist/src/schemas/submission.v1.schema.json +61 -0
  162. package/dist/src/store/def-source.d.ts +52 -0
  163. package/dist/src/store/def-source.js +335 -0
  164. package/dist/src/store/index-file.d.ts +69 -0
  165. package/dist/src/store/index-file.js +151 -0
  166. package/dist/src/store/index.d.ts +27 -0
  167. package/dist/src/store/index.js +22 -0
  168. package/dist/src/store/ingestor.d.ts +43 -0
  169. package/dist/src/store/ingestor.js +211 -0
  170. package/dist/src/store/install.d.ts +228 -0
  171. package/dist/src/store/install.js +555 -0
  172. package/dist/src/store/instruction-source.d.ts +49 -0
  173. package/dist/src/store/instruction-source.js +298 -0
  174. package/dist/src/store/origin-evidence.d.ts +21 -0
  175. package/dist/src/store/origin-evidence.js +66 -0
  176. package/dist/src/store/pre-commit-verifier.d.ts +68 -0
  177. package/dist/src/store/pre-commit-verifier.js +418 -0
  178. package/dist/src/store/resolve.d.ts +138 -0
  179. package/dist/src/store/resolve.js +363 -0
  180. package/dist/src/store/types.d.ts +288 -0
  181. package/dist/src/store/types.js +356 -0
  182. package/dist/src/types.d.ts +45 -11
  183. package/dist/src/untar.d.ts +8 -23
  184. package/dist/src/untar.js +10 -136
  185. package/docs/agent-runner.md +86 -0
  186. package/docs/authoring.md +57 -6
  187. package/docs/bundles.md +250 -0
  188. package/docs/cli.md +1171 -97
  189. package/docs/crypto.md +816 -0
  190. package/docs/design.md +342 -20
  191. package/docs/embedding.md +132 -25
  192. package/docs/wire-contracts.md +380 -0
  193. package/package.json +6 -1
  194. package/plugins/claude-code/.claude-plugin/marketplace.json +14 -0
  195. package/plugins/claude-code/plugin/.claude-plugin/plugin.json +8 -0
  196. package/plugins/claude-code/plugin/.mcp.json +14 -0
  197. package/plugins/claude-code/plugin/hooks/hooks.json +26 -0
  198. package/plugins/claude-code/plugin/hooks/session-end.sh +40 -0
  199. package/plugins/claude-code/plugin/hooks/session-start.sh +52 -0
  200. package/plugins/claude-code/plugin/skills/author/SKILL.md +181 -0
  201. package/plugins/claude-code/plugin/skills/conduct/SKILL.md +106 -0
  202. package/plugins/claude-code/plugin/skills/shift/SKILL.md +105 -0
  203. package/plugins/codex/.agents/plugins/marketplace.json +21 -0
  204. package/plugins/codex/plugins/owenloop/.codex-plugin/plugin.json +7 -0
  205. package/plugins/codex/plugins/owenloop/.mcp.json +20 -0
  206. package/plugins/codex/plugins/owenloop/hooks/hooks.json +26 -0
  207. package/plugins/codex/plugins/owenloop/hooks/session-end.sh +40 -0
  208. package/plugins/codex/plugins/owenloop/hooks/session-start.sh +52 -0
  209. package/plugins/codex/plugins/owenloop/skills/author/SKILL.md +181 -0
  210. package/plugins/codex/plugins/owenloop/skills/conduct/SKILL.md +106 -0
  211. package/plugins/codex/plugins/owenloop/skills/shift/SKILL.md +105 -0
package/dist/src/cli.js CHANGED
@@ -9,6 +9,7 @@
9
9
  *
10
10
  * owenloop defs list available workflow definitions
11
11
  * owenloop add <owner>/<repo>[@ref] fetch, validate, and install a repo's workflow defs (public repos)
12
+ * owenloop start <def> [--provide n=json] [--crew name] start a published hub workflow
12
13
  * owenloop create <def> [--provide n=json] [--title t] start an instance
13
14
  * owenloop provide <wf> <name> [--value json] supply an owed input
14
15
  * owenloop tick <wf> [--now ms] pull eligible orders
@@ -31,31 +32,55 @@
31
32
  *
32
33
  * Global: --db <path> (env OWENLOOP_DB), --defs <dir> (env OWENLOOP_DEFS).
33
34
  */
34
- import { existsSync, mkdirSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';
35
- import { basename, delimiter, dirname, join, resolve } from 'node:path';
35
+ import { chmodSync, existsSync, lstatSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, renameSync, rmSync, statSync, unlinkSync, writeFileSync } from 'node:fs';
36
+ import { basename, delimiter, dirname, isAbsolute, join, resolve, sep } from 'node:path';
36
37
  import { spawn, spawnSync } from 'node:child_process';
37
38
  import { createServer } from 'node:http';
38
39
  import { createInterface } from 'node:readline/promises';
39
- import { hostname } from 'node:os';
40
+ import { hostname, tmpdir } from 'node:os';
41
+ import { fileURLToPath } from 'node:url';
40
42
  import { parse as parseYaml } from 'yaml';
41
43
  import { Engine } from "./engine.js";
42
- import { buildGraph, buildTrace, graphToDot, graphToMermaid, modelCheck } from "./model.js";
44
+ import { buildGraph, buildTrace, graphToDot, graphToMermaid, hasDefiniteCheckDefect, modelCheck } from "./model.js";
43
45
  import { openStore } from "./store.js";
44
- import { buildDef, DefError, finalizeDefs, lintDef, loadDefs, loadDefsRaw, loadDefsUnfinalized, validateDef, } from "./defs.js";
46
+ import { buildDef, DefError, finalizeDefs, lintDef, loadDefFile, loadDefs, loadDefsRaw, loadDefsUnfinalized, resolveCallsTarget, validateDef, } from "./defs.js";
47
+ import { createDefInstructionSource } from "./order-resolver.js";
45
48
  import { CliError, dbPathRefusingSymlink, detId, mkdirRefusingSymlink, nowMs, parseDurationMs, randId } from "./util.js";
49
+ import { packageVersion } from "./package-version.js";
46
50
  import { authHeader, deleteCredential, discoverMetadata, ensureFreshOAuth, hubFetch, hubMaxResponseBytes, mintAgentCredential, readBodyBounded, refreshOAuth, rekeyAgentCredential, storeCredential, } from "./credentials.js";
51
+ import { PrincipalKeyManager } from "./crypto/keys.js";
52
+ import { createHash } from 'node:crypto';
53
+ import { DSSE_SSH_NAMESPACE, decodeBase64Strict, dsseSignEnrollmentGrant, dsseSignOrigin, dsseSignPublication, dsseSignRevocation, PAYLOAD_TYPE_ORIGIN, PAYLOAD_TYPE_PUBLICATION, } from "./crypto/dsse.js";
54
+ import { assertEd25519PubText, createSshSigner, SshSignerError } from "./crypto/ssh.js";
55
+ import { publicKeyDescriptor } from "./crypto/keys.js";
56
+ import { DEFAULT_MACHINE_SCOPE, buildEnrollmentGrant, verifyRosterEntry } from "./crypto/enrollment.js";
57
+ import { resolveAllowedSigners } from "./crypto/trust-roots.js";
58
+ import { orgRootPrivateKeyPath, orgRootPublicKeyPath, resolveOrgRoot, revocationsDir, rosterDir, } from "./crypto/org-root.js";
47
59
  import { runMcpCommand } from "./mcp/serve.js";
48
60
  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, asCapabilityRouteAdded, asCapabilityRouteRemoved, asCapabilityRoutes, asCrewCreated, asCrewDeleted, asCrewMemberAdded, asCrewMemberRemoved, asCrews, 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";
61
+ import { BundleError, digestBundle, inspectBundle, packBundle, unpackBundle } from "./bundle/index.js";
62
+ import { acquireInstallLock, ADD_JOURNAL_FILENAME, archivePathViolation, commitInstall, finalizeInstallCommit, githubShaUrl, githubTarballUrl, installFolder, parkOldNameDir, parseRepoSpec, readLockfile, recoverInterruptedInstall, releaseInstallLock, removeAddJournal, rmRecursiveForce, rollbackInstallCommit, RollbackFailedError, stageFiles, STAGING_DIRNAME, writeAddJournal, writeLockfile, } from "./add.js";
63
+ import { BundleIngestorUnavailableError, globalStoreRoot, installWorkflowBundle, inspectCasDefs, loadCasDefs, PreCommitVerifierUnavailableError, projectStoreRoot, createBundleIngestor, createPreCommitVerifier, recoverWorkflowStore, storeIndexPath, workflowStoreReplacementRecovery, workflowStoreStatePaths, } from "./store/index.js";
64
+ import { asAgentIdentities, asCreateWorkflowOk, asCapabilityRouteAdded, asCapabilityRouteRemoved, asCapabilityRoutes, asCrewCreated, asCrewDeleted, asCrewMemberAdded, asCrewMemberRemoved, asCrews, asWhoami, computeServerDiff, credentialBackend, createWorkflowError, credentialFilePath, credentialSlot, DEFAULT_HUB, externalCredentialCommand, hashDefForHub, hubBindingPath, keychainServiceFor, listStoredHubOrigins, normalizeOrigin, parseWorkflowList, pkcePair, randomState, readCredentialFile, readHubBinding, readStoredCredential, resolveEndpoint, resolveKeychain, writeCredentialFile, writeHubBinding, } from "./hub.js";
65
+ import { loadSettings, settingsPath as executionSettingsPath } from "../packages/work/src/settings/settings.js";
51
66
  import { owenloopSettingsPath, readOwenloopSettingsRaw, writeOwenloopHubOrigin } from "./work-settings.js";
52
- function defaultIO() {
67
+ import { globalConfigPath, writeGlobalConfig } from "./global-config.js";
68
+ import { canonicalJsonBytes, defaultRecoveryMarkerDir, ensureDirectoryPathNoSymlink, guardStateFile } from "./install.js";
69
+ import { summarizeIssues, validateValue } from "./schema.js";
70
+ import { originSchema } from "./schemas/index.js";
71
+ export function defaultIO() {
53
72
  return {
54
73
  cwd: process.cwd(),
55
74
  env: process.env,
56
75
  out: (s) => process.stdout.write(`${s}\n`),
57
76
  err: (s) => process.stderr.write(`${s}\n`),
58
77
  fetch: globalThis.fetch,
78
+ bundleIngestor: createBundleIngestor(),
79
+ preCommitVerifier: createPreCommitVerifier({
80
+ cwd: process.cwd(),
81
+ env: process.env,
82
+ warn: (line) => process.stderr.write(`${line}\n`),
83
+ }),
59
84
  openUrl: defaultOpenUrl,
60
85
  readStdin: defaultReadStdin,
61
86
  prompt: defaultPrompt,
@@ -79,7 +104,7 @@ async function defaultPrompt(question) {
79
104
  /**
80
105
  * The default local-command runner: `spawnSync` with `shell: false` (argv is
81
106
  * passed as a vector, never interpolated into a shell) and captured, not
82
- * inherited, stdio. Only the plugin probe uses it.
107
+ * inherited, stdio. Plugin probes and convergers use it.
83
108
  */
84
109
  function defaultRunCommand(cmd, args) {
85
110
  const r = spawnSync(cmd, args, { encoding: 'utf8' });
@@ -128,10 +153,15 @@ const BOOLEAN_FLAGS = new Set([
128
153
  // `acme/widgets` as a positional so the recover branch can refuse it, rather
129
154
  // than binding it as `--recover`'s value and silently dropping it.
130
155
  'recover',
156
+ // `add --global` (and `add --global --recover`) is likewise value-less: the
157
+ // bundle path/URL must stay a positional.
158
+ 'global',
159
+ 'unsigned',
131
160
  ]);
132
161
  function parseArgs(argv) {
133
162
  const positionals = [];
134
163
  const options = new Map();
164
+ const missingOptionValues = new Set();
135
165
  for (let i = 0; i < argv.length; i++) {
136
166
  const a = argv[i];
137
167
  if (a.startsWith('--')) {
@@ -149,7 +179,8 @@ function parseArgs(argv) {
149
179
  val = argv[++i];
150
180
  }
151
181
  else {
152
- val = 'true'; // boolean flag
182
+ val = 'true'; // legacy representation for a valueless non-boolean option
183
+ missingOptionValues.add(key);
153
184
  }
154
185
  const arr = options.get(key) ?? [];
155
186
  arr.push(val);
@@ -159,7 +190,7 @@ function parseArgs(argv) {
159
190
  positionals.push(a);
160
191
  }
161
192
  }
162
- return { positionals, options };
193
+ return { positionals, options, missingOptionValues };
163
194
  }
164
195
  const last = (args, key) => {
165
196
  const arr = args.options.get(key);
@@ -242,6 +273,13 @@ function parsePairs(entries, jsonValue) {
242
273
  }
243
274
  return out;
244
275
  }
276
+ function finalizeDiscoveredDefs(merged, tolerantCasInspection, definitionDiscoveryComplete) {
277
+ if (!tolerantCasInspection || definitionDiscoveryComplete)
278
+ return finalizeDefs(merged);
279
+ // Only `status` requests tolerant CAS inspection. Its partial map is read-only:
280
+ // unresolved calls into skipped corrupt objects must not abort the fleet read.
281
+ return finalizeDefs(merged, { allowUnresolvedCalls: true });
282
+ }
245
283
  /**
246
284
  * Load the DEFAULT def set, folding in the defs `owenloop add` installed under
247
285
  * ledger-recorded subfolders of `defsDir` so `defs`/`create`/`tick`/etc. see
@@ -278,7 +316,7 @@ function parsePairs(entries, jsonValue) {
278
316
  * fail-closed validation in add.ts is untouched — we consume `readLockfile`,
279
317
  * discovery merely refuses to act on a bad ledger rather than crashing.)
280
318
  */
281
- function loadDefsWithInstalled(io, defsDir) {
319
+ function loadDefsWithInstalled(io, defsDir, tolerantCasInspection = false) {
282
320
  const merged = existsSync(defsDir) ? loadDefsUnfinalized(defsDir) : new Map();
283
321
  let lf;
284
322
  try {
@@ -286,7 +324,11 @@ function loadDefsWithInstalled(io, defsDir) {
286
324
  }
287
325
  catch (e) {
288
326
  io.err(`warning: skipping installed workflow defs: ${e.message}`);
289
- return finalizeDefs(merged);
327
+ const definitionDiscoveryComplete = foldCasDefs(io, defsDir, merged, tolerantCasInspection);
328
+ return {
329
+ defs: finalizeDiscoveredDefs(merged, tolerantCasInspection, definitionDiscoveryComplete),
330
+ definitionDiscoveryComplete,
331
+ };
290
332
  }
291
333
  for (const source of Object.keys(lf.installed).sort()) {
292
334
  const entry = lf.installed[source];
@@ -314,9 +356,67 @@ function loadDefsWithInstalled(io, defsDir) {
314
356
  merged.set(name, def);
315
357
  }
316
358
  }
317
- return finalizeDefs(merged);
359
+ const definitionDiscoveryComplete = foldCasDefs(io, defsDir, merged, tolerantCasInspection);
360
+ return {
361
+ defs: finalizeDiscoveredDefs(merged, tolerantCasInspection, definitionDiscoveryComplete),
362
+ definitionDiscoveryComplete,
363
+ };
364
+ }
365
+ /**
366
+ * WS-6: fold the CONTENT-ADDRESSED store's defs into the same raw map, under
367
+ * their QUALIFIED keys only.
368
+ *
369
+ * Precedence, level 3 of 4 (see `loadDefsWithInstalled` above for 1 and 2):
370
+ * this runs LAST, after the base scan and after the `add`-ledger fold, so a
371
+ * project-local def and an `add`-installed def both keep the precedence they
372
+ * have today. Nothing here can shadow either of them regardless of ordering,
373
+ * because the key a CAS def is registered under always contains `/` and a def
374
+ * name may not (`/^[a-z0-9][a-z0-9_-]*$/i`) — a CAS registration is unforgeable
375
+ * as a filesystem name.
376
+ *
377
+ * Precedence level 4 — a BARE `calls:` reaching a CAS workflow — is deliberately
378
+ * NOT a map entry. Bare sibling resolution happens in `resolveCallsTarget`
379
+ * (defs.ts), scoped by the calling def's own `bundleDigest`, so bundle A's
380
+ * `calls: build` can never bind to bundle B's `build`.
381
+ *
382
+ * Executable discovery is fail-closed. Only the explicit status inspection path
383
+ * uses `inspectCasDefs`, which warns, returns `complete: false`, and is never
384
+ * reused by a mutating command's resolver.
385
+ *
386
+ * When no store exists (no `index.json` at either root) this is a no-op and the
387
+ * merged map is byte-identical to what it was before WS-6.
388
+ */
389
+ function foldCasDefs(io, defsDir, merged, tolerantInspection = false) {
390
+ // Without HOME/USERPROFILE, retain project discovery and consult a guaranteed
391
+ // absent synthetic global root instead of silently dropping the project store.
392
+ let globalRoot;
393
+ try {
394
+ globalRoot = globalStoreRoot(workflowHome(io));
395
+ }
396
+ catch {
397
+ globalRoot = join(defsDir, '.owenloop-global-store-unavailable');
398
+ }
399
+ const discoveryArgs = {
400
+ projectRoot: projectStoreRoot(defsDir),
401
+ globalRoot,
402
+ warn: (line) => io.err(line),
403
+ };
404
+ const discovery = tolerantInspection
405
+ ? inspectCasDefs(discoveryArgs)
406
+ : { registrations: loadCasDefs(discoveryArgs), complete: true };
407
+ const registrations = discovery.registrations;
408
+ for (const registration of registrations) {
409
+ const winner = merged.get(registration.key);
410
+ if (winner !== undefined) {
411
+ io.err(`warning: workflow '${registration.key}' from bundle ${registration.bundleDigest} is shadowed by ` +
412
+ `${winner.dir ?? 'an already-registered definition'}`);
413
+ continue;
414
+ }
415
+ merged.set(registration.key, registration.def);
416
+ }
417
+ return discovery.complete;
318
418
  }
319
- function openCtx(io, args) {
419
+ function openCtx(io, args, tolerantCasInspection = false) {
320
420
  const dbOverride = last(args, 'db') ?? io.env.OWENLOOP_DB;
321
421
  const dbPath = dbOverride ?? join(io.cwd, '.owenloop', 'state.db');
322
422
  // An explicit `--defs`/`OWENLOOP_DEFS` is the operator targeting a literal dir
@@ -326,6 +426,16 @@ function openCtx(io, args) {
326
426
  // `OWENLOOP_DEFS=<cwd>/workflows` counts as an override and stays literal.
327
427
  const defsOverride = last(args, 'defs') ?? io.env.OWENLOOP_DEFS;
328
428
  const defsDir = defsOverride ?? join(io.cwd, 'workflows');
429
+ // Discover and validate executable definitions before creating or opening the
430
+ // runtime database. Corrupt workflow-store state therefore cannot mutate local
431
+ // runtime state before the command fails closed.
432
+ const loaded = defsOverride !== undefined
433
+ ? {
434
+ defs: existsSync(defsDir) ? loadDefs(defsDir) : new Map(),
435
+ definitionDiscoveryComplete: true,
436
+ }
437
+ : loadDefsWithInstalled(io, defsDir, tolerantCasInspection);
438
+ const { defs, definitionDiscoveryComplete } = loaded;
329
439
  // Guard the built-in default (`cwd/.owenloop/state.db`) against a symlinked
330
440
  // `.owenloop` from a hostile checkout (SEC-3). Directory guard first, then the
331
441
  // file-level guard on `state.db` and its SQLite sidecars — a symlinked db file
@@ -340,22 +450,637 @@ function openCtx(io, args) {
340
450
  else
341
451
  mkdirSync(dirname(dbPath), { recursive: true });
342
452
  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);
453
+ // WP-B1: the CLI ticks reference-mode orders exactly like the embedded
454
+ // path — one loaded-definition resolver seeds the instruction boundary
455
+ // (emission digests + instruction resolution), never a second local path.
456
+ const instructionSource = createDefInstructionSource(defs.values());
457
+ // WS-6: the resolver is SCOPE-AWARE. `from` is supplied only by the engine's
458
+ // `calls:` spawn path; when it is present and carries CAS provenance, a bare
459
+ // target resolves sibling-first inside that def's own bundle (the exact rule
460
+ // `finalizeDefs` validated against at load time, so load-time and run-time
461
+ // agree). With `from` absent — every other resolver caller — this is the plain
462
+ // flat-map lookup it has always been.
463
+ const engine = new Engine(store, (name, from) => {
464
+ const d = from === undefined ? defs.get(name) : resolveCallsTarget(defs, name, from);
350
465
  if (!d)
351
466
  throw new CliError(`unknown workflow definition '${name}' (looked in ${defsDir})`);
352
467
  return d;
353
- });
354
- return { store, engine, defs, defsDir, dbPath };
468
+ }, { instructionSource });
469
+ return { store, engine, defs, defsDir, dbPath, definitionDiscoveryComplete };
355
470
  }
356
471
  function print(io, value) {
357
472
  io.out(JSON.stringify(value, null, 2));
358
473
  }
474
+ /** Validate the exact positional shape of one bundle subcommand. */
475
+ function assertBundlePositionals(args, count, usage) {
476
+ if (args.positionals.length !== count) {
477
+ throw new CliError(`invalid bundle arguments; usage: ${usage}`);
478
+ }
479
+ }
480
+ /** `--output` requires a following value; parseArgs represents a bare flag as `true`. */
481
+ function bundleOutput(args) {
482
+ const value = last(args, 'output');
483
+ if (value === 'true') {
484
+ throw new CliError('owenloop bundle pack: --output requires a path value');
485
+ }
486
+ return value;
487
+ }
488
+ function printBundlePackResult(io, outputAbs, packed) {
489
+ print(io, {
490
+ path: outputAbs,
491
+ digest: packed.digest,
492
+ name: packed.manifest.package.name,
493
+ version: packed.manifest.package.version,
494
+ ...(packed.manifest.runtime === undefined ? {} : { runtime: packed.manifest.runtime }),
495
+ files: packed.entries.length,
496
+ });
497
+ }
498
+ function printBundleUnpackResult(io, result) {
499
+ print(io, {
500
+ path: result.path,
501
+ digest: result.digest,
502
+ name: result.manifest.package.name,
503
+ version: result.manifest.package.version,
504
+ files: result.entries.length,
505
+ });
506
+ }
507
+ function printBundleInspectResult(io, result) {
508
+ print(io, {
509
+ digest: result.digest,
510
+ manifest: result.manifest,
511
+ entries: result.entries.map((e) => ({ path: e.path, size: e.size, executable: e.executable, sha256: e.sha256 })),
512
+ });
513
+ }
514
+ /**
515
+ * `owenloop bundle pack|unpack|inspect|digest` — the `.wnlp` package-format
516
+ * verbs (WP-A1; format contract in `docs/bundles.md`). Purely filesystem
517
+ * work on the bytes the user points at: these commands NEVER open the store
518
+ * (dispatched before `openCtx`), NEVER touch the network, and NEVER write
519
+ * `.owenloop/` state. Every `BundleError` carries a stable `code`, kept in
520
+ * the stderr message so scripts can match on it.
521
+ */
522
+ function dispatchBundle(io, args) {
523
+ const sub = need(args, 1, 'pack|unpack|inspect|digest');
524
+ if (sub !== 'pack' && args.options.has('output')) {
525
+ throw new CliError(`owenloop bundle ${sub}: --output is only valid for pack`);
526
+ }
527
+ switch (sub) {
528
+ case 'pack': {
529
+ assertBundlePositionals(args, 3, 'owenloop bundle pack <source-dir> [--output <bundle.wnlp>]');
530
+ const outputOpt = bundleOutput(args);
531
+ const source = need(args, 2, 'source-dir');
532
+ const sourceAbs = resolve(io.cwd, source);
533
+ // Check an explicit output before reading the source. The output cannot
534
+ // become one of the source files during a pack operation.
535
+ if (outputOpt !== undefined)
536
+ assertOutputOutsideSource(resolve(io.cwd, outputOpt), sourceAbs);
537
+ const packed = runBundle(() => packBundle(sourceAbs));
538
+ const outputAbs = resolve(io.cwd, outputOpt ?? defaultPackOutput(sourceAbs, packed.manifest.package.name, packed.manifest.package.version));
539
+ // The default output is derived from the manifest, so it is checked after
540
+ // packing; an explicit output was checked before the source walk above.
541
+ assertOutputOutsideSource(outputAbs, sourceAbs);
542
+ // Reject an existing non-file output (a directory); replace a regular file.
543
+ const existing = lstatSync(outputAbs, { throwIfNoEntry: false });
544
+ if (existing && !existing.isFile())
545
+ throw new CliError(`owenloop bundle pack: output '${outputOpt ?? defaultPackOutput(sourceAbs, packed.manifest.package.name, packed.manifest.package.version)}' exists and is not a regular file`);
546
+ writeBundleFileAtomic(outputAbs, packed.bytes);
547
+ printBundlePackResult(io, outputAbs, packed);
548
+ return 0;
549
+ }
550
+ case 'unpack': {
551
+ assertBundlePositionals(args, 4, 'owenloop bundle unpack <bundle.wnlp> <destination-dir>');
552
+ const bundlePath = need(args, 2, 'bundle.wnlp');
553
+ const destination = need(args, 3, 'destination-dir');
554
+ const bytes = readBundleCommandFile(io, bundlePath);
555
+ const result = runBundle(() => unpackBundle(bytes, resolve(io.cwd, destination)));
556
+ printBundleUnpackResult(io, result);
557
+ return 0;
558
+ }
559
+ case 'inspect': {
560
+ assertBundlePositionals(args, 3, 'owenloop bundle inspect <bundle.wnlp>');
561
+ const bundlePath = need(args, 2, 'bundle.wnlp');
562
+ const bytes = readBundleCommandFile(io, bundlePath);
563
+ const result = runBundle(() => inspectBundle(bytes));
564
+ printBundleInspectResult(io, result);
565
+ return 0;
566
+ }
567
+ case 'digest': {
568
+ assertBundlePositionals(args, 3, 'owenloop bundle digest <bundle.wnlp>');
569
+ const bundlePath = need(args, 2, 'bundle.wnlp');
570
+ const bytes = readBundleCommandFile(io, bundlePath);
571
+ const result = runBundle(() => digestBundle(bytes));
572
+ print(io, { digest: result.digest });
573
+ return 0;
574
+ }
575
+ default:
576
+ throw new CliError(`owenloop bundle: unknown subcommand '${sub}' (expected pack, unpack, inspect, or digest)`);
577
+ }
578
+ }
579
+ /** `--output` requires a following value; a bare flag is not a default path. */
580
+ function publishOutput(args) {
581
+ const value = last(args, 'output');
582
+ if (value === 'true')
583
+ throw new CliError('owenloop publish: --output requires a path value');
584
+ return value;
585
+ }
586
+ /** Parse and validate the signer-supplied provenance object before key work. */
587
+ function publishSource(args) {
588
+ const raw = last(args, 'source');
589
+ if (raw === undefined)
590
+ return undefined;
591
+ const value = parseJson(raw);
592
+ const properties = originSchema.properties;
593
+ const sourceSchema = properties?.source;
594
+ if (sourceSchema === undefined)
595
+ throw new CliError('owenloop publish: origin schema has no source property');
596
+ const shape = validateValue(sourceSchema, value);
597
+ if (!shape.valid) {
598
+ throw new CliError(`owenloop publish: --source does not match origin source schema: ${summarizeIssues(shape.issues)}`);
599
+ }
600
+ if (value.kind === 'console') {
601
+ throw new CliError('owenloop publish: --source kind "console" requires a client-side signing ceremony');
602
+ }
603
+ return value;
604
+ }
605
+ /** Refuse an output or sidecar path that is not absent or a regular file. */
606
+ function assertPublishOutputPath(path, label) {
607
+ const existing = lstatSync(path, { throwIfNoEntry: false });
608
+ if (existing !== undefined && !existing.isFile()) {
609
+ throw new CliError(`owenloop publish: ${label} '${path}' exists and is not a regular file`);
610
+ }
611
+ }
612
+ /** Remove one regular publication sidecar after its replacement is durable. */
613
+ function removePublicationSidecar(path) {
614
+ if (lstatSync(path, { throwIfNoEntry: false }) === undefined)
615
+ return;
616
+ try {
617
+ unlinkSync(path);
618
+ }
619
+ catch (e) {
620
+ throw new CliError(`owenloop publish: cannot remove stale sidecar '${path}': ${e.message}`);
621
+ }
622
+ }
623
+ /**
624
+ * `owenloop publish <source-dir>` — pack one canonical workflow bundle and
625
+ * publish a signed DSSE statement beside it. Signed publication is the default;
626
+ * `--unsigned` writes an unauthenticated intent marker instead. The signed path
627
+ * resolves and probes the author key before `packBundle`, so key or signer
628
+ * failures leave no bundle or sidecar behind. This command is deliberately
629
+ * separate from `bundle pack` and `push`: it is asynchronous only because local
630
+ * key material is materialized through the signing-key manager.
631
+ */
632
+ async function dispatchPublish(io, args) {
633
+ if (args.positionals.length !== 2) {
634
+ throw new CliError('invalid publish arguments; usage: owenloop publish <source-dir> [--output <bundle.wnlp>] [--source <json>] [--unsigned] [--hub <origin>]');
635
+ }
636
+ const source = need(args, 1, 'source-dir');
637
+ const sourceAbs = resolve(io.cwd, source);
638
+ const outputOpt = publishOutput(args);
639
+ if (outputOpt !== undefined)
640
+ assertOutputOutsideSource(resolve(io.cwd, outputOpt), sourceAbs);
641
+ const originSource = publishSource(args);
642
+ const unsigned = flag(args, 'unsigned');
643
+ if (originSource !== undefined && unsigned) {
644
+ throw new CliError('owenloop publish: --source cannot be combined with --unsigned');
645
+ }
646
+ const { origin } = resolvePublishingHub(io, args, { principal: 'human' });
647
+ const keys = io.principalKeys ?? new PrincipalKeyManager({ env: io.env });
648
+ let packed;
649
+ let envelope;
650
+ let originEnvelope;
651
+ if (unsigned) {
652
+ packed = runBundle(() => packBundle(sourceAbs));
653
+ }
654
+ else {
655
+ const ref = keys.resolveRef(origin, 'human');
656
+ if (ref === null) {
657
+ throw new CliError(`no author signing key for ${origin} — run \`owenloop setup\` or pass --unsigned`);
658
+ }
659
+ // `inspect` is read-only: publish must confirm that setup already stored
660
+ // this key, never create or repair one. `withSigningKey` remains the only
661
+ // API that materializes private bytes.
662
+ const inspected = await keys.inspect(ref);
663
+ if (!inspected.exists || inspected.publicKey === undefined) {
664
+ throw new CliError(`no author signing key for ${origin} — run \`owenloop setup\` or pass --unsigned`);
665
+ }
666
+ const publicKey = inspected.publicKey;
667
+ const signed = await keys.withSigningKey(ref, async (keyPath) => {
668
+ // Constructing the signer probes ssh-keygen -Y before packBundle runs.
669
+ const signer = createSshSigner({ namespace: DSSE_SSH_NAMESPACE, signKeyPath: keyPath });
670
+ const nextPacked = runBundle(() => packBundle(sourceAbs));
671
+ const timestamp = nowMs();
672
+ const record = {
673
+ digest: nextPacked.digest,
674
+ name: nextPacked.manifest.package.name,
675
+ version: nextPacked.manifest.package.version,
676
+ publisherKeyId: publicKey.keyid,
677
+ timestamp,
678
+ };
679
+ const payloadBytes = Buffer.from(canonicalJsonBytes(record));
680
+ const result = await dsseSignPublication(payloadBytes, signer);
681
+ let signedOrigin;
682
+ if (originSource !== undefined) {
683
+ const originRecord = {
684
+ digest: nextPacked.digest,
685
+ name: nextPacked.manifest.package.name,
686
+ version: nextPacked.manifest.package.version,
687
+ source: originSource,
688
+ attesterKeyId: publicKey.keyid,
689
+ timestamp,
690
+ };
691
+ const originResult = await dsseSignOrigin(Buffer.from(canonicalJsonBytes(originRecord)), signer);
692
+ signedOrigin = originResult.envelope;
693
+ }
694
+ return { envelope: result.envelope, originEnvelope: signedOrigin, packed: nextPacked };
695
+ });
696
+ packed = signed.packed;
697
+ envelope = signed.envelope;
698
+ originEnvelope = signed.originEnvelope;
699
+ }
700
+ const outputAbs = resolve(io.cwd, outputOpt ?? defaultPackOutput(sourceAbs, packed.manifest.package.name, packed.manifest.package.version));
701
+ assertOutputOutsideSource(outputAbs, sourceAbs);
702
+ const envelopePath = `${outputAbs}.dsse`;
703
+ const originPath = `${outputAbs}.origin.dsse`;
704
+ const markerPath = `${outputAbs}.unsigned`;
705
+ assertPublishOutputPath(outputAbs, 'output');
706
+ assertPublishOutputPath(envelopePath, 'sidecar');
707
+ assertPublishOutputPath(originPath, 'sidecar');
708
+ assertPublishOutputPath(markerPath, 'sidecar');
709
+ writeBundleFileAtomic(outputAbs, packed.bytes, 'owenloop publish');
710
+ if (unsigned) {
711
+ const marker = { formatVersion: 1, digest: packed.digest, signed: false };
712
+ writeBundleFileAtomic(markerPath, canonicalJsonBytes(marker), 'owenloop publish');
713
+ removePublicationSidecar(envelopePath);
714
+ removePublicationSidecar(originPath);
715
+ print(io, {
716
+ ok: true,
717
+ bundle: outputAbs,
718
+ digest: packed.digest,
719
+ name: packed.manifest.package.name,
720
+ version: packed.manifest.package.version,
721
+ signed: false,
722
+ marker: markerPath,
723
+ });
724
+ }
725
+ else {
726
+ writeBundleFileAtomic(envelopePath, canonicalJsonBytes(envelope), 'owenloop publish');
727
+ removePublicationSidecar(markerPath);
728
+ if (originSource !== undefined && originEnvelope !== undefined) {
729
+ writeBundleFileAtomic(originPath, canonicalJsonBytes(originEnvelope), 'owenloop publish');
730
+ }
731
+ else {
732
+ removePublicationSidecar(originPath);
733
+ }
734
+ print(io, {
735
+ ok: true,
736
+ bundle: outputAbs,
737
+ digest: packed.digest,
738
+ name: packed.manifest.package.name,
739
+ version: packed.manifest.package.version,
740
+ signed: true,
741
+ envelope: envelopePath,
742
+ ...(originSource !== undefined ? { origin: originPath } : {}),
743
+ });
744
+ }
745
+ return 0;
746
+ }
747
+ const TRUST_USAGE = 'usage: owenloop trust init [--force] | ' +
748
+ 'owenloop trust grant --key <pubkey-path> --principal <human|machine|agent>:<id> ' +
749
+ '[--pools a,b|*] [--labels a,b|*] [--namespaces a,b|*] [--delegate no|<n>|unbounded] ' +
750
+ '[--signing-key <path>] [--output <file>] | ' +
751
+ 'owenloop trust revoke --key <SHA256:…> --principal <kind>:<id> ' +
752
+ '[--reason <text>] [--effective-from <epochMs>] [--signing-key <path>] [--output <file>]';
753
+ function trustRequiredOption(args, key) {
754
+ const value = last(args, key);
755
+ if (value === undefined || value === '' || value === 'true') {
756
+ throw new CliError(`missing required option: --${key} (${TRUST_USAGE})`);
757
+ }
758
+ return value;
759
+ }
760
+ function trustOptionalOption(args, key) {
761
+ const value = last(args, key);
762
+ if (value === 'true')
763
+ throw new CliError(`--${key} requires a value (${TRUST_USAGE})`);
764
+ return value;
765
+ }
766
+ function parseTrustPrincipal(raw) {
767
+ const match = /^(human|machine|agent):(.+)$/.exec(raw);
768
+ const kind = match?.[1];
769
+ const id = match?.[2];
770
+ if (kind === undefined || id === undefined || id === '') {
771
+ throw new CliError(`invalid --principal '${raw}': expected human|machine|agent:<id> (${TRUST_USAGE})`);
772
+ }
773
+ return { kind: kind, id };
774
+ }
775
+ function parseTrustAxis(args, key) {
776
+ const raw = trustOptionalOption(args, key);
777
+ if (raw === undefined)
778
+ return [];
779
+ if (raw === '*')
780
+ return '*';
781
+ const values = raw.split(',').map((value) => value.trim());
782
+ if (values.length === 0 || values.some((value) => value === '')) {
783
+ throw new CliError(`invalid --${key} '${raw}': expected a comma-separated list or * (${TRUST_USAGE})`);
784
+ }
785
+ return values;
786
+ }
787
+ function parseTrustDelegation(args) {
788
+ const raw = trustOptionalOption(args, 'delegate') ?? 'no';
789
+ if (raw === 'no')
790
+ return { allowed: false };
791
+ if (raw === 'unbounded')
792
+ return { allowed: true, maxDepth: 'unbounded' };
793
+ if (!/^\d+$/.test(raw)) {
794
+ throw new CliError(`invalid --delegate '${raw}': expected no, a non-negative integer, or unbounded (${TRUST_USAGE})`);
795
+ }
796
+ const maxDepth = Number(raw);
797
+ if (!Number.isSafeInteger(maxDepth)) {
798
+ throw new CliError(`invalid --delegate '${raw}': integer is too large (${TRUST_USAGE})`);
799
+ }
800
+ return { allowed: true, maxDepth };
801
+ }
802
+ function parseTrustKeyId(raw) {
803
+ if (!/^SHA256:[A-Za-z0-9+/]{43}$/.test(raw)) {
804
+ throw new CliError(`invalid --key '${raw}': expected SHA256:<base64 fingerprint> (${TRUST_USAGE})`);
805
+ }
806
+ return raw;
807
+ }
808
+ function trustKeyHash(keyid) {
809
+ return createHash('sha256').update(keyid).digest('hex');
810
+ }
811
+ function assertTrustPath(path, label) {
812
+ const stat = lstatSync(path, { throwIfNoEntry: false });
813
+ if (stat?.isSymbolicLink())
814
+ throw new CliError(`owenloop trust: ${label} '${path}' is a symlink`);
815
+ if (stat !== undefined && !stat.isFile()) {
816
+ throw new CliError(`owenloop trust: ${label} '${path}' is not a regular file`);
817
+ }
818
+ }
819
+ function writeTrustEnvelope(path, envelope) {
820
+ const parent = dirname(path);
821
+ mkdirRefusingSymlink(parent);
822
+ assertTrustPath(path, 'output');
823
+ let tempDir;
824
+ try {
825
+ tempDir = mkdtempSync(join(parent, '.owenloop-trust-'));
826
+ chmodSync(tempDir, 0o700);
827
+ const temp = join(tempDir, basename(path));
828
+ writeFileSync(temp, canonicalJsonBytes(envelope), { mode: 0o644, flag: 'wx' });
829
+ renameSync(temp, path);
830
+ }
831
+ catch (error) {
832
+ throw new CliError(`owenloop trust: cannot write '${path}': ${error.message}`);
833
+ }
834
+ finally {
835
+ if (tempDir !== undefined)
836
+ rmSync(tempDir, { recursive: true, force: true });
837
+ }
838
+ }
839
+ function publicKeyForSigningPath(path) {
840
+ const stat = lstatSync(path, { throwIfNoEntry: false });
841
+ if (stat === undefined)
842
+ throw new CliError(`owenloop trust: signing key '${path}' does not exist`);
843
+ if (stat.isSymbolicLink())
844
+ throw new CliError(`owenloop trust: signing key '${path}' is a symlink`);
845
+ if (!stat.isFile())
846
+ throw new CliError(`owenloop trust: signing key '${path}' is not a regular file`);
847
+ try {
848
+ const text = readFileSync(path, 'utf8');
849
+ const first = text.split(/\r?\n/).find((line) => line.trim() !== '')?.trim() ?? '';
850
+ if (/^(ssh-|ecdsa-|sk-)/.test(first))
851
+ return text;
852
+ }
853
+ catch {
854
+ // ssh-keygen below supplies the stable failure classification.
855
+ }
856
+ const result = spawnSync('ssh-keygen', ['-y', '-f', path], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] });
857
+ if (result.error !== undefined || result.status !== 0 || typeof result.stdout !== 'string') {
858
+ throw new CliError(`owenloop trust: cannot derive public key from signing key '${path}'`);
859
+ }
860
+ return result.stdout;
861
+ }
862
+ function signingKeyInfo(io, explicitPath) {
863
+ const path = explicitPath ?? orgRootPrivateKeyPath(io.env);
864
+ let publicKey;
865
+ if (explicitPath === undefined) {
866
+ const root = resolveOrgRoot(io.env);
867
+ if (root.kind === 'absent') {
868
+ throw new CliError(`owenloop trust: org root is absent at '${root.path}' — run \`owenloop trust init\``);
869
+ }
870
+ publicKey = root.publicKey;
871
+ }
872
+ else {
873
+ publicKey = publicKeyForSigningPath(path);
874
+ }
875
+ try {
876
+ assertEd25519PubText(publicKey, 'signing key');
877
+ const descriptor = publicKeyDescriptor(publicKey);
878
+ return { path, publicKey: descriptor.openSshPublicKey, keyid: descriptor.keyid };
879
+ }
880
+ catch (error) {
881
+ throw new CliError(`owenloop trust: ${error instanceof Error ? error.message : String(error)}`);
882
+ }
883
+ }
884
+ function trustEnvelopeOutput(args, cwd, explicitDefault) {
885
+ const output = trustOptionalOption(args, 'output');
886
+ return resolve(cwd, output ?? explicitDefault);
887
+ }
888
+ function ensureTrustRootDirectory(env) {
889
+ const privatePath = orgRootPrivateKeyPath(env);
890
+ const directory = dirname(privatePath);
891
+ mkdirRefusingSymlink(directory);
892
+ chmodSync(directory, 0o700);
893
+ return directory;
894
+ }
895
+ function generateTrustRoot(io, force) {
896
+ const directory = ensureTrustRootDirectory(io.env);
897
+ const privatePath = orgRootPrivateKeyPath(io.env);
898
+ const publicPath = orgRootPublicKeyPath(io.env);
899
+ const privateStat = lstatSync(privatePath, { throwIfNoEntry: false });
900
+ const publicStat = lstatSync(publicPath, { throwIfNoEntry: false });
901
+ if (!force && (privateStat !== undefined || publicStat !== undefined)) {
902
+ throw new CliError(`owenloop trust init: org root already exists under '${directory}' — pass --force to replace it`);
903
+ }
904
+ for (const [path, label] of [[privatePath, 'private key'], [publicPath, 'public key']]) {
905
+ if (lstatSync(path, { throwIfNoEntry: false })?.isSymbolicLink()) {
906
+ throw new CliError(`owenloop trust init: existing ${label} '${path}' is a symlink`);
907
+ }
908
+ if (lstatSync(path, { throwIfNoEntry: false }) !== undefined)
909
+ unlinkSync(path);
910
+ }
911
+ const result = spawnSync('ssh-keygen', ['-q', '-t', 'ed25519', '-N', '', '-C', 'owenloop org root', '-f', privatePath], { stdio: 'ignore' });
912
+ if (result.error !== undefined || result.status !== 0) {
913
+ throw new CliError('owenloop trust init: ssh-keygen could not create the Ed25519 org root');
914
+ }
915
+ chmodSync(privatePath, 0o600);
916
+ chmodSync(publicPath, 0o644);
917
+ print(io, { ok: true, privateKey: privatePath, publicKey: publicPath });
918
+ return 0;
919
+ }
920
+ /** `owenloop trust init|grant|revoke` — offline enrollment-record minting. */
921
+ async function dispatchTrust(io, args) {
922
+ const sub = args.positionals[1];
923
+ if (sub !== 'init' && sub !== 'grant' && sub !== 'revoke') {
924
+ throw new CliError(`unknown trust subcommand '${sub ?? ''}' — ${TRUST_USAGE}`);
925
+ }
926
+ if (sub === 'init') {
927
+ if (args.positionals.length !== 2)
928
+ throw new CliError(`invalid trust init arguments — ${TRUST_USAGE}`);
929
+ return generateTrustRoot(io, flag(args, 'force'));
930
+ }
931
+ if (args.positionals.length !== 2)
932
+ throw new CliError(`invalid trust ${sub} arguments — ${TRUST_USAGE}`);
933
+ const keyOption = trustRequiredOption(args, 'key');
934
+ const principal = parseTrustPrincipal(trustRequiredOption(args, 'principal'));
935
+ const signingPath = trustOptionalOption(args, 'signing-key');
936
+ if (sub === 'grant') {
937
+ const pools = parseTrustAxis(args, 'pools');
938
+ const labels = parseTrustAxis(args, 'labels');
939
+ const namespaces = parseTrustAxis(args, 'namespaces');
940
+ const delegation = parseTrustDelegation(args);
941
+ const publicKeyPath = resolve(io.cwd, keyOption);
942
+ assertTrustPath(publicKeyPath, 'enrollment key');
943
+ const keyText = (() => {
944
+ try {
945
+ return readFileSync(publicKeyPath, 'utf8');
946
+ }
947
+ catch (error) {
948
+ throw new CliError(`owenloop trust grant: cannot read --key '${keyOption}': ${error.message}`);
949
+ }
950
+ })();
951
+ let newKey;
952
+ try {
953
+ assertEd25519PubText(keyText, 'enrollment key');
954
+ newKey = publicKeyDescriptor(keyText);
955
+ }
956
+ catch (error) {
957
+ throw new CliError(`owenloop trust grant: ${error instanceof Error ? error.message : String(error)}`);
958
+ }
959
+ const signer = signingKeyInfo(io, signingPath);
960
+ const record = {
961
+ newKey: {
962
+ keyid: newKey.keyid,
963
+ keyType: newKey.keyType,
964
+ openSshPublicKey: newKey.openSshPublicKey,
965
+ ...(newKey.comment !== '' ? { comment: newKey.comment } : {}),
966
+ },
967
+ principal,
968
+ scope: { pools, labels, namespaces, delegation },
969
+ grantedBy: signer.keyid,
970
+ validFrom: nowMs(),
971
+ };
972
+ const sshSigner = createSshSigner({ namespace: DSSE_SSH_NAMESPACE, signKeyPath: signer.path });
973
+ try {
974
+ const signed = await dsseSignEnrollmentGrant(Buffer.from(canonicalJsonBytes(record)), sshSigner);
975
+ const output = trustEnvelopeOutput(args, io.cwd, join(rosterDir(io.env), `${trustKeyHash(newKey.keyid)}.grant.dsse`));
976
+ writeTrustEnvelope(output, signed.envelope);
977
+ print(io, { ok: true, path: output, keyid: newKey.keyid, grantedBy: signer.keyid, principal, validFrom: record.validFrom });
978
+ }
979
+ finally {
980
+ sshSigner.dispose();
981
+ }
982
+ return 0;
983
+ }
984
+ const revokedKey = parseTrustKeyId(keyOption);
985
+ const reason = trustOptionalOption(args, 'reason');
986
+ const rawEffective = trustOptionalOption(args, 'effective-from');
987
+ let effectiveFrom;
988
+ if (rawEffective !== undefined) {
989
+ if (!/^\d+$/.test(rawEffective)) {
990
+ throw new CliError(`invalid --effective-from '${rawEffective}': expected a non-negative epoch millisecond (${TRUST_USAGE})`);
991
+ }
992
+ effectiveFrom = Number(rawEffective);
993
+ if (!Number.isSafeInteger(effectiveFrom)) {
994
+ throw new CliError(`invalid --effective-from '${rawEffective}': integer is too large (${TRUST_USAGE})`);
995
+ }
996
+ }
997
+ const signer = signingKeyInfo(io, signingPath);
998
+ const issuedAt = nowMs();
999
+ const cut = effectiveFrom ?? issuedAt;
1000
+ const record = {
1001
+ revokedKey,
1002
+ principal,
1003
+ revokedBy: signer.keyid,
1004
+ issuedAt,
1005
+ effectiveFrom: cut,
1006
+ backdated: cut < issuedAt,
1007
+ ...(reason !== undefined ? { reason } : {}),
1008
+ };
1009
+ const sshSigner = createSshSigner({ namespace: DSSE_SSH_NAMESPACE, signKeyPath: signer.path });
1010
+ try {
1011
+ const signed = await dsseSignRevocation(Buffer.from(canonicalJsonBytes(record)), sshSigner);
1012
+ const output = trustEnvelopeOutput(args, io.cwd, join(revocationsDir(io.env), `${trustKeyHash(revokedKey)}.revocation.dsse`));
1013
+ writeTrustEnvelope(output, signed.envelope);
1014
+ print(io, {
1015
+ ok: true,
1016
+ path: output,
1017
+ revokedKey,
1018
+ revokedBy: signer.keyid,
1019
+ principal,
1020
+ issuedAt,
1021
+ effectiveFrom: cut,
1022
+ backdated: record.backdated,
1023
+ });
1024
+ }
1025
+ finally {
1026
+ sshSigner.dispose();
1027
+ }
1028
+ return 0;
1029
+ }
1030
+ /** Default pack output: `<package-name>-<version>.wnlp` next to the source directory. */
1031
+ function defaultPackOutput(sourceAbs, name, version) {
1032
+ return join(dirname(sourceAbs), `${name}-${version}.wnlp`);
1033
+ }
1034
+ /** Refuse an output path located inside the source tree (or equal to it). */
1035
+ function assertOutputOutsideSource(outputAbs, sourceAbs) {
1036
+ const sourcePrefix = sourceAbs.endsWith(sep) ? sourceAbs : sourceAbs + sep;
1037
+ if (outputAbs === sourceAbs || outputAbs.startsWith(sourcePrefix)) {
1038
+ throw new CliError(`owenloop bundle pack: output '${outputAbs}' is inside the source directory '${sourceAbs}'`);
1039
+ }
1040
+ }
1041
+ /** Read a `.wnlp` file from disk, converting fs failures into CliErrors. */
1042
+ function readBundleCommandFile(io, bundlePath) {
1043
+ const abs = resolve(io.cwd, bundlePath);
1044
+ try {
1045
+ return readFileSync(abs);
1046
+ }
1047
+ catch (e) {
1048
+ throw new CliError(`owenloop bundle: cannot read '${bundlePath}': ${e.message}`);
1049
+ }
1050
+ }
1051
+ /** Run a bundle API call, converting a BundleError into a CliError that keeps the stable code. */
1052
+ function runBundle(fn) {
1053
+ try {
1054
+ return fn();
1055
+ }
1056
+ catch (e) {
1057
+ if (e instanceof BundleError) {
1058
+ throw new CliError(`owenloop bundle [${e.code}]: ${e.message}`);
1059
+ }
1060
+ throw e;
1061
+ }
1062
+ }
1063
+ /**
1064
+ * Write `bytes` to `outputAbs` atomically: a collision-safe sibling temporary
1065
+ * directory, then rename the temporary file over the destination. Temporary
1066
+ * state is cleaned on every failure and after success.
1067
+ */
1068
+ function writeBundleFileAtomic(outputAbs, bytes, operation = 'owenloop bundle pack') {
1069
+ let tempDir;
1070
+ try {
1071
+ tempDir = mkdtempSync(join(dirname(outputAbs), '.owenloop-pack-'));
1072
+ const tmp = join(tempDir, basename(outputAbs));
1073
+ writeFileSync(tmp, bytes, { mode: 0o644, flag: 'wx' });
1074
+ renameSync(tmp, outputAbs);
1075
+ }
1076
+ catch (e) {
1077
+ throw new CliError(`${operation}: cannot write output: ${e.message}`);
1078
+ }
1079
+ finally {
1080
+ if (tempDir !== undefined)
1081
+ rmSync(tempDir, { recursive: true, force: true });
1082
+ }
1083
+ }
359
1084
  /**
360
1085
  * Synchronous blocking sleep. The whole codebase is sync end to end (no
361
1086
  * async/Promise/setTimeout anywhere in src/*.ts), so `wait` needs a sync
@@ -374,12 +1099,29 @@ Usage: owenloop <command> [args] [--db <path>] [--defs <dir>]
374
1099
  Commands:
375
1100
  defs list available workflow definitions
376
1101
  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)
1102
+ add <bundle.wnlp | https://url> [--global]
1103
+ install a workflow BUNDLE into the content-addressed store
1104
+ (default: project store under the defs dir; --global: ~/.owenloop/workflows)
1105
+ add --recover [--global] finish or undo a crash-interrupted install (offline; no network)
1106
+ bundle pack <source-dir> [--output <bundle.wnlp>] pack a source directory into a deterministic .wnlp bundle
1107
+ bundle unpack <bundle.wnlp> <destination-dir> unpack a .wnlp bundle into a new directory
1108
+ bundle inspect <bundle.wnlp> strictly validate a .wnlp bundle and print its manifest/entries
1109
+ bundle digest <bundle.wnlp> print the bundle's def digest (SHA-256 of the canonical tar)
1110
+ publish <source-dir> [--output <bundle.wnlp>] [--source <json>] [--unsigned] [--hub <origin>]
1111
+ pack a bundle and sign its canonical digest (signed by default)
1112
+ trust init [--force] create the local Ed25519 enrollment root
1113
+ trust grant --key <pubkey-path> --principal <kind>:<id> [--pools a,b|*] [--labels a,b|*] [--namespaces a,b|*] [--delegate no|<n>|unbounded] [--signing-key <path>] [--output <file>]
1114
+ mint an offline signed enrollment grant
1115
+ trust revoke --key <SHA256:…> --principal <kind>:<id> [--reason <text>] [--effective-from <epochMs>] [--signing-key <path>] [--output <file>]
1116
+ mint an offline signed revocation
378
1117
  login [--hub <url>] [--with-token] [--as <slot>] authenticate the CLI against a hub, verified via whoami (loopback OAuth, or --with-token from stdin)
379
1118
  logout [--hub <url>] [--as <slot>] delete the stored credential for a hub in one slot
380
1119
  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)
1120
+ push [<defName>...] [--bundle <bundle.wnlp>] [--force] [--dry-run] [--hub <origin>] [--as <slot>]
1121
+ publish local workflow defs, or exact bundle-backed defs, to the safely resolved hub (server-diffed, idempotent)
382
1122
  --as names the credential slot: human (default), agent, or agent:<account>
1123
+ start <defName> [--provide name=json ...] [--crew <name>] [--title <text>] [--hub <url>]
1124
+ ${' '.repeat(41)}start a published workflow on the bound hub (human credential)
383
1125
  agent new <name> [--crews <a,b>] [--scopes <a,b>] [--shift] [--hub <url>] mint a new Scoped Identity on the hub and store its token in slot agent:<name> (the token is never printed; --shift = --scopes work,run)
384
1126
  capability bind <capability> <crew> [--hub <url>] add a crew to a workflow capability on the hub org — a capability may bind many crews (admin; human credential)
385
1127
  capability unbind <capability> <crew> [--hub <url>] remove one (capability, crew) route
@@ -389,8 +1131,9 @@ Commands:
389
1131
  crew rm <crewId> [--hub <url>] delete a crew; work stamped to it moves to the org's orphan crew
390
1132
  crew member add <crewId> <principalKind> <principalId> [--hub <url>] add a member or agent to a crew
391
1133
  crew member rm <crewId> <principalId> [--hub <url>] remove a principal from a crew
392
- setup [--hub <url>] [--new-agent <name> | --replace-agent <name>] [--crews <a,b>] [--scopes <a,b>] converge this machine's install: human login, agent credential, owenloop settings, plugin (idempotent)
1134
+ setup [--hub <url>] [--new-agent <name> | --replace-agent <name>] [--crews <a,b>] [--scopes <a,b>] [--reuse-ssh-key <path>] converge this machine's install: human login, agent credential, signing keys, owenloop settings, plugins (idempotent)
393
1135
  doctor [--hub <url>] check this machine's owenloop install and report each piece (read-only)
1136
+ enrollments [--hub <url>] list the hub's relayed machine enrollment grants (read-only)
394
1137
  mcp [--hub <url>] serve the hub control plane over stdio MCP (spawned by MCP hosts, not run by humans)
395
1138
  work <subcommand> [args] run execution-side shift/hold/exec/agent-run/... commands
396
1139
  shift start|next|status|end [args] run and attend a local Unix-socket shift daemon
@@ -429,24 +1172,11 @@ function failureNote(failures) {
429
1172
  return '';
430
1173
  return `\n${failures.length} file(s) failed to load:\n - ${failures.map((f) => `${f.file}: ${f.error}`).join('\n - ')}`;
431
1174
  }
432
- /**
433
- * The single "definite defect" predicate over a modelCheck `report`, shared by
434
- * `check`, `add` (dispatchAdd) and `push` (dispatchPush) so all three
435
- * accept-or-reject a def identically. A pure function of the report object — it
436
- * does NOT read or change how any caller seeded its modelCheck (add/push seed
437
- * `assumeProvided: true`; check seeds `assumeProvided: !strictInputs`).
438
- *
439
- * invariant violations and structurally-dead steps are ALWAYS definite (sound
440
- * regardless of bounds); a true deadlock counts ONLY when the search was
441
- * exhaustive (`!bounded`) because a tight maxCollectionSize cap can manufacture
442
- * a spurious one. `unreachedSteps` is deliberately EXCLUDED — it is a bounds
443
- * artifact ("raise --max-states/--max-depth"), never a definite defect.
444
- */
445
- export function hasDefiniteCheckDefect(report) {
446
- return (report.invariantViolations.length > 0 ||
447
- report.structurallyDeadSteps.length > 0 ||
448
- (!report.bounded && report.deadlocks.length > 0));
449
- }
1175
+ // The shared definite-defect predicate now lives in the engine core (model.ts)
1176
+ // so the workflow-store installer (src/store/install.ts — engine core, no CLI
1177
+ // imports) can run the identical acceptance gate without coupling to this
1178
+ // module. Re-exported here to keep the existing CLI/test import surface.
1179
+ export { hasDefiniteCheckDefect };
450
1180
  /**
451
1181
  * Options accepted on EVERY command. docs/cli.md documents `--db`/`--defs` as
452
1182
  * global ("pass both on every command"), so they are allowlisted everywhere —
@@ -472,16 +1202,21 @@ const cmdOpts = (...extra) => new Set([...GLOBAL_OPTIONS, ...extra]);
472
1202
  export const COMMAND_OPTIONS = new Map([
473
1203
  ['help', cmdOpts()],
474
1204
  ['defs', cmdOpts()],
475
- ['add', cmdOpts('recover')],
1205
+ ['add', cmdOpts('recover', 'global')],
1206
+ ['bundle', cmdOpts('output')],
476
1207
  ['login', cmdOpts('hub', 'with-token', 'as')],
477
1208
  ['logout', cmdOpts('hub', 'as')],
478
1209
  ['connect', cmdOpts('hub', 'as')],
479
- ['push', cmdOpts('dry-run', 'force', 'hub', 'as')],
1210
+ ['publish', cmdOpts('unsigned', 'output', 'source', 'hub')],
1211
+ ['trust', cmdOpts('force', 'key', 'principal', 'pools', 'labels', 'namespaces', 'delegate', 'signing-key', 'output', 'reason', 'effective-from')],
1212
+ ['push', cmdOpts('dry-run', 'force', 'hub', 'as', 'bundle')],
1213
+ ['start', cmdOpts('hub', 'crew', 'title', 'provide')],
480
1214
  ['agent', cmdOpts('crews', 'hub', 'scopes', 'shift')],
481
1215
  ['capability', cmdOpts('hub')],
482
1216
  ['crew', cmdOpts('hub', 'kind', 'owner')],
483
- ['setup', cmdOpts('hub', 'new-agent', 'replace-agent', 'crews', 'scopes')],
1217
+ ['setup', cmdOpts('hub', 'new-agent', 'replace-agent', 'crews', 'scopes', 'reuse-ssh-key')],
484
1218
  ['doctor', cmdOpts('hub')],
1219
+ ['enrollments', cmdOpts('hub')],
485
1220
  ['mcp', cmdOpts('hub')],
486
1221
  ['work', cmdOpts()],
487
1222
  ['shift', cmdOpts('all', 'origin', 'as', 'name', 'cap', 'max-agents', 'poll-interval', 'once', 'cache-dir', 'state-dir', 'wait')],
@@ -764,8 +1499,18 @@ function dispatch(command, io, args) {
764
1499
  }
765
1500
  return 0;
766
1501
  }
767
- const ctx = openCtx(io, args);
1502
+ // The bundle namespace is pure filesystem work on the bytes the user
1503
+ // points at — dispatched BEFORE openCtx so pack/inspect/digest neither
1504
+ // open/create `.owenloop/state.db` nor touch a remote (same reasoning as
1505
+ // lint/check above; see docs/cli.md).
1506
+ if (command === 'bundle') {
1507
+ return dispatchBundle(io, args);
1508
+ }
1509
+ const ctx = openCtx(io, args, command === 'status');
768
1510
  const { engine, store } = ctx;
1511
+ if (command === 'status' && !ctx.definitionDiscoveryComplete) {
1512
+ io.err('warning: status is incomplete because workflow definition discovery skipped corrupt store state');
1513
+ }
769
1514
  try {
770
1515
  switch (command) {
771
1516
  case 'defs': {
@@ -1254,6 +1999,275 @@ function tarballMaxBytes(io) {
1254
1999
  const override = Number(io.env.OWENLOOP_TARBALL_MAX_BYTES);
1255
2000
  return Number.isFinite(override) && override > 0 ? override : DEFAULT_TAR_LIMITS.maxCompressedBytes;
1256
2001
  }
2002
+ // ---- `add` source classification (GitHub repo vs `.wnlp` bundle) ------------------
2003
+ /** The byte budget for a local `.wnlp` bundle file — same 256 MiB default as the GitHub tarball cap. */
2004
+ function bundleFileMaxBytes(io) {
2005
+ return tarballMaxBytes(io);
2006
+ }
2007
+ /** The byte budget for a `.wnlp` bundle fetched over `http:`/`https:` — same cap as the GitHub tarball. */
2008
+ function bundleUrlMaxBytes(io) {
2009
+ return tarballMaxBytes(io);
2010
+ }
2011
+ /** The `--global` + `--defs` refusal — the global store has a fixed home-directory location, so `--defs` would only create ambiguity. */
2012
+ const GLOBAL_DEFS_CONFLICT_MSG = '--global cannot be combined with --defs: the global store lives in the home directory';
2013
+ /**
2014
+ * Classify one `add` positional WITHOUT changing GitHub behavior: the GitHub
2015
+ * shape (`owner/repo[@ref]`, no scheme, not a `.wnlp` path) returns
2016
+ * `{ kind: 'github' }` for exactly the same inputs `parseRepoSpec` accepts,
2017
+ * and the GitHub route keeps parsing it — so every error message for a
2018
+ * malformed repo spec is unchanged. `.wnlp` file paths and http/https URLs
2019
+ * take the bundle route; everything else is a specific usage refusal.
2020
+ *
2021
+ * The classifier never inspects the filesystem: a `.wnlp` path that does not
2022
+ * exist is still classified as a file (the reader refuses it afterward with
2023
+ * the reason), and a URL is classified by scheme alone.
2024
+ */
2025
+ export function classifyAddSource(spec) {
2026
+ const schemeMatch = /^[a-zA-Z][a-zA-Z0-9+.-]*:/.exec(spec);
2027
+ if (schemeMatch !== null) {
2028
+ if (spec.startsWith('http:') || spec.startsWith('https:')) {
2029
+ return { kind: 'url', url: spec };
2030
+ }
2031
+ throw new CliError(`unsupported source scheme '${spec.slice(0, schemeMatch[0].length)}' — supported sources: ` +
2032
+ `owner/repo[@ref] (GitHub), a local .wnlp file, or an http(s) URL`);
2033
+ }
2034
+ if (spec.endsWith('.wnlp')) {
2035
+ return { kind: 'file', path: spec };
2036
+ }
2037
+ return { kind: 'github', spec };
2038
+ }
2039
+ /**
2040
+ * Read a local `.wnlp` bundle: it must be a BOUNDED REGULAR FILE. Refusals
2041
+ * name the user-supplied path exactly as given (origin data for messages only
2042
+ * — identity always comes from the bundle's manifest, never from the path).
2043
+ * The size cap is enforced BEFORE and AFTER the read so an oversized file is
2044
+ * never fully allocated.
2045
+ */
2046
+ function readBundleFile(io, path) {
2047
+ const filesystemPath = isAbsolute(path) ? path : join(io.cwd, path);
2048
+ let st;
2049
+ try {
2050
+ st = lstatSync(filesystemPath);
2051
+ }
2052
+ catch {
2053
+ throw new CliError(`could not read bundle at ${path}: file not found`);
2054
+ }
2055
+ if (st.isSymbolicLink()) {
2056
+ throw new CliError(`refusing bundle at ${path}: it is a symlink`);
2057
+ }
2058
+ if (!st.isFile()) {
2059
+ throw new CliError(`refusing bundle at ${path}: not a regular file`);
2060
+ }
2061
+ const cap = bundleFileMaxBytes(io);
2062
+ if (st.size > cap) {
2063
+ throw new CliError(`refusing bundle at ${path}: file is ${st.size} bytes, over the ${cap}-byte cap`);
2064
+ }
2065
+ let bytes;
2066
+ try {
2067
+ bytes = readFileSync(filesystemPath);
2068
+ }
2069
+ catch (e) {
2070
+ throw new CliError(`could not read bundle at ${path}: ${e.message}`);
2071
+ }
2072
+ if (bytes.length > cap) {
2073
+ throw new CliError(`refusing bundle at ${path}: file grew to ${bytes.length} bytes while reading (cap ${cap})`);
2074
+ }
2075
+ return bytes;
2076
+ }
2077
+ /**
2078
+ * Fetch a `.wnlp` bundle over `http:`/`https:`. Mirrors the GitHub tarball
2079
+ * fetch discipline: the timeout covers the fetch AND the body read (undici
2080
+ * ties the abort signal to the stream), `readBodyBounded` cancels an
2081
+ * oversized body DURING the stream, and redirects are refused
2082
+ * (`redirect: 'error'`) rather than followed silently. The A1 adapter remains
2083
+ * the authority for bundle size/archive limits once bytes arrive.
2084
+ */
2085
+ async function fetchBundleUrl(io, url) {
2086
+ const fetchFn = io.fetch ?? globalThis.fetch;
2087
+ let res;
2088
+ try {
2089
+ res = await fetchFn(url, {
2090
+ headers: { 'User-Agent': 'owenloop' },
2091
+ signal: AbortSignal.timeout(ADD_TARBALL_TIMEOUT_MS),
2092
+ redirect: 'error',
2093
+ });
2094
+ }
2095
+ catch (e) {
2096
+ const err = e;
2097
+ if (err.name === 'TimeoutError' || err.name === 'AbortError') {
2098
+ throw new CliError(`timed out after ${ADD_TARBALL_TIMEOUT_MS / 1000}s downloading bundle from ${url}`);
2099
+ }
2100
+ throw new CliError(`could not fetch bundle from ${url}: ${err.message}`);
2101
+ }
2102
+ if (!res.ok) {
2103
+ throw new CliError(`could not fetch bundle from ${url}: server returned ${res.status}`);
2104
+ }
2105
+ try {
2106
+ return await readBodyBounded(res, bundleUrlMaxBytes(io), `bundle from ${url}`);
2107
+ }
2108
+ catch (e) {
2109
+ const err = e;
2110
+ if (err.name === 'TimeoutError' || err.name === 'AbortError') {
2111
+ throw new CliError(`timed out after ${ADD_TARBALL_TIMEOUT_MS / 1000}s downloading bundle from ${url}`);
2112
+ }
2113
+ throw e;
2114
+ }
2115
+ }
2116
+ /** Return the caller-injected home, rejecting empty values instead of defaulting to process state. */
2117
+ function workflowHome(io) {
2118
+ const home = [io.env.HOME, io.env.USERPROFILE].find((value) => value !== undefined && value.trim() !== '');
2119
+ if (home === undefined)
2120
+ throw new CliError('cannot locate the global workflow store: set HOME or USERPROFILE');
2121
+ return home;
2122
+ }
2123
+ /**
2124
+ * Resolve the external install/repair marker directory from injected CLI state.
2125
+ * A bundle install always needs a concrete directory; no marker API may consult
2126
+ * the ambient process home.
2127
+ */
2128
+ function workflowRecoveryMarkerDir(io) {
2129
+ return io.recoveryMarkerDir ?? defaultRecoveryMarkerDir(workflowHome(io));
2130
+ }
2131
+ /** Recovery keeps the legacy GitHub path usable when no v2 marker is involved. */
2132
+ function optionalWorkflowRecoveryMarkerDir(io) {
2133
+ if (io.recoveryMarkerDir !== undefined)
2134
+ return io.recoveryMarkerDir;
2135
+ const home = [io.env.HOME, io.env.USERPROFILE].find((value) => value !== undefined && value.trim() !== '');
2136
+ return home === undefined ? undefined : defaultRecoveryMarkerDir(home);
2137
+ }
2138
+ /**
2139
+ * The `.wnlp` bundle route of `owenloop add` — the content-addressed store
2140
+ * counterpart of the GitHub route. `dispatchAdd` classifies the positional
2141
+ * (pure {@link classifyAddSource}), reads/fetches the bytes unlocked (same as
2142
+ * the GitHub download — a slow fetch must not hold a lock), then hands
2143
+ * everything that touches store state to `installWorkflowBundle`: lock →
2144
+ * recovery → index reread → A1 stage → strict engine validation → A2 verify →
2145
+ * harden → journal → swap → atomic index commit → finalize → unlock.
2146
+ *
2147
+ * Fail-closed adapters: with no A1/A2 module bound to `io`, the installer
2148
+ * throws its named adapter-unavailable error BEFORE any journal/object/index
2149
+ * commit — there is no default accepting parser, digest algorithm, or
2150
+ * verifier. Recovery (`add --recover`) is unaffected by adapter availability:
2151
+ * it is pure local journal/object/index work.
2152
+ */
2153
+ async function dispatchAddBundle(io, args, source) {
2154
+ const globalFlag = flag(args, 'global');
2155
+ const defsOverride = last(args, 'defs') ?? io.env.OWENLOOP_DEFS;
2156
+ if (globalFlag && defsOverride !== undefined) {
2157
+ throw new CliError(GLOBAL_DEFS_CONFLICT_MSG);
2158
+ }
2159
+ // Store roots: the global store is `~/.owenloop/workflows` (HOME injected
2160
+ // via env so tests never touch the real one); the project store is the
2161
+ // resolved defs dir. Lock/journal paths live per root; the PROJECT route
2162
+ // shares the existing project add lock + journal (its recovery ordering).
2163
+ // A fresh bundle install also needs an external marker directory, so derive
2164
+ // that path from the same injected home and never from process state.
2165
+ const recoveryMarkerDir = workflowRecoveryMarkerDir(io);
2166
+ const root = globalFlag
2167
+ ? globalStoreRoot(workflowHome(io))
2168
+ : projectStoreRoot(defsOverride ?? join(io.cwd, 'workflows'));
2169
+ const statePaths = workflowStoreStatePaths(root);
2170
+ const lockPath = statePaths.lockPath;
2171
+ const journalPath = statePaths.journalPath;
2172
+ // Bytes first, lock later (same as the GitHub route). Origin data only —
2173
+ // the bundle's manifest is the identity authority.
2174
+ let bytes;
2175
+ let bundleSource;
2176
+ if (source.kind === 'file') {
2177
+ bytes = readBundleFile(io, source.path);
2178
+ bundleSource = { kind: 'file', path: source.path };
2179
+ }
2180
+ else if (source.kind === 'url') {
2181
+ bytes = await fetchBundleUrl(io, source.url);
2182
+ bundleSource = { kind: 'url', url: source.url };
2183
+ }
2184
+ else {
2185
+ // Unreachable: `dispatchAdd` routes only file/url sources here.
2186
+ throw new CliError('internal error: a GitHub repo spec cannot reach the bundle route');
2187
+ }
2188
+ // Fail-closed adapter gate, explicit at the dispatch site: with no A1/A2
2189
+ // module bound to `io`, dispatch refuses with the named adapter-unavailable
2190
+ // error BEFORE any journal/object/index commit (the installer enforces the
2191
+ // same rule too — belt and suspenders).
2192
+ if (io.bundleIngestor === undefined)
2193
+ throw new BundleIngestorUnavailableError();
2194
+ if (io.preCommitVerifier === undefined)
2195
+ throw new PreCommitVerifierUnavailableError();
2196
+ // The project route shares the project add lock/recovery ordering — hand
2197
+ // the recovery pass the installed.json ledger lookup so a legacy v1
2198
+ // (GitHub) journal at the shared project journal path can still be
2199
+ // recovered. The global route has no ledger: v1 journals there are refused.
2200
+ const readLedger = globalFlag
2201
+ ? undefined
2202
+ : () => {
2203
+ const lf = readLockfile(join(io.cwd, '.owenloop', 'installed.json'));
2204
+ return (src) => {
2205
+ const entry = lf.installed[src];
2206
+ if (entry === undefined)
2207
+ return undefined;
2208
+ return { sha: entry.sha, path: entry.path };
2209
+ };
2210
+ };
2211
+ const result = await installWorkflowBundle({
2212
+ bytes,
2213
+ source: bundleSource,
2214
+ root,
2215
+ level: globalFlag ? 'global' : 'project',
2216
+ lockPath,
2217
+ journalPath,
2218
+ recoveryMarkerDir,
2219
+ ingestor: io.bundleIngestor,
2220
+ verifier: io.preCommitVerifier,
2221
+ readLedger,
2222
+ });
2223
+ print(io, {
2224
+ ok: true,
2225
+ source: bundleSource.kind === 'file' ? bundleSource.path : bundleSource.url,
2226
+ level: result.level,
2227
+ coordinate: result.coordinate,
2228
+ digest: result.digest,
2229
+ workflows: result.workflows,
2230
+ objectPath: result.objectPath,
2231
+ installed: result.installed,
2232
+ });
2233
+ return 0;
2234
+ }
2235
+ /**
2236
+ * `owenloop add --recover [--global]`: the global variant runs the store's
2237
+ * offline recovery on the global root; the plain variant keeps the current
2238
+ * project/GitHub recovery. Never touches the network, and adapter
2239
+ * availability is irrelevant — recovery is pure local journal/object/index
2240
+ * work.
2241
+ */
2242
+ async function dispatchAddRecoverGlobal(io) {
2243
+ const home = workflowHome(io);
2244
+ const root = globalStoreRoot(home);
2245
+ const lockPath = join(root, '.owenloop', 'add.lock');
2246
+ const journalPath = join(root, '.owenloop', ADD_JOURNAL_FILENAME);
2247
+ const recoveryMarkerDir = workflowRecoveryMarkerDir(io);
2248
+ const outcome = await recoverWorkflowStore({ root, lockPath, journalPath, recoveryMarkerDir });
2249
+ switch (outcome) {
2250
+ case 'no-journal':
2251
+ print(io, { ok: true, recovered: false, message: 'nothing to recover — no interrupted install found' });
2252
+ return 0;
2253
+ case 'rolled-forward':
2254
+ print(io, {
2255
+ ok: true,
2256
+ recovered: true,
2257
+ outcome: 'rolled-forward',
2258
+ message: 'interrupted install completed (rolled forward)',
2259
+ });
2260
+ return 0;
2261
+ case 'rolled-back':
2262
+ print(io, {
2263
+ ok: true,
2264
+ recovered: true,
2265
+ outcome: 'rolled-back',
2266
+ message: 'interrupted install undone — previous state restored (or already consistent)',
2267
+ });
2268
+ return 0;
2269
+ }
2270
+ }
1257
2271
  /**
1258
2272
  * `owenloop add <owner>/<repo>[@ref]` — fetch a repo's `workflows/**`, validate
1259
2273
  * it, and install it under `<defsDir>/<installFolder(owner,repo)>`.
@@ -1295,7 +2309,17 @@ async function dispatchAdd(io, args) {
1295
2309
  // install with no network (recovery is purely local filesystem work).
1296
2310
  if (flag(args, 'recover'))
1297
2311
  return dispatchAddRecover(io, args);
1298
- const spec = need(args, 1, 'owner/repo[@ref]');
2312
+ // Classify the source BEFORE the GitHub parse: `owner/repo[@ref]` keeps the
2313
+ // byte-for-byte preserved GitHub route (same inputs reach `parseRepoSpec`,
2314
+ // so every existing error is unchanged); `.wnlp` file paths and http(s)
2315
+ // URLs take the content-addressed bundle store route.
2316
+ const spec = need(args, 1, '<source>');
2317
+ const classified = classifyAddSource(spec);
2318
+ if (classified.kind !== 'github')
2319
+ return dispatchAddBundle(io, args, classified);
2320
+ if (flag(args, 'global')) {
2321
+ throw new CliError('--global is only supported for .wnlp bundle sources');
2322
+ }
1299
2323
  const { owner, repo, ref } = parseRepoSpec(spec);
1300
2324
  const source = `${owner}/${repo}`;
1301
2325
  const defsOverride = last(args, 'defs') ?? io.env.OWENLOOP_DEFS;
@@ -1303,6 +2327,8 @@ async function dispatchAdd(io, args) {
1303
2327
  const lockfilePath = join(io.cwd, '.owenloop', 'installed.json');
1304
2328
  const installLockPath = join(io.cwd, '.owenloop', 'add.lock');
1305
2329
  const journalPath = join(io.cwd, '.owenloop', ADD_JOURNAL_FILENAME);
2330
+ const canonicalState = workflowStoreStatePaths(projectStoreRoot(defsDir));
2331
+ const recoveryMarkerDir = optionalWorkflowRecoveryMarkerDir(io);
1306
2332
  const fetchFn = io.fetch ?? globalThis.fetch;
1307
2333
  // 1. Resolve the ref to a pinned commit sha.
1308
2334
  let shaRes;
@@ -1413,9 +2439,25 @@ async function dispatchAdd(io, args) {
1413
2439
  // intent, not repo content — deliberately installing through a symlink keeps
1414
2440
  // today's behavior, matching the --db/OWENLOOP_DB rule.
1415
2441
  mkdirRefusingSymlink(join(io.cwd, '.owenloop'));
2442
+ guardStateFile(installLockPath, 'install lock');
2443
+ guardStateFile(journalPath, 'crash-recovery journal');
2444
+ guardStateFile(lockfilePath, 'installed ledger');
1416
2445
  if (defsOverride === undefined)
1417
2446
  mkdirRefusingSymlink(defsDir);
1418
- const lock = await acquireInstallLock(installLockPath);
2447
+ mkdirRefusingSymlink(canonicalState.stateDir);
2448
+ guardStateFile(canonicalState.lockPath, 'canonical install lock');
2449
+ guardStateFile(canonicalState.journalPath, 'canonical crash-recovery journal');
2450
+ const lockPaths = [...new Set([installLockPath, canonicalState.lockPath])].sort();
2451
+ const locks = [];
2452
+ try {
2453
+ for (const path of lockPaths)
2454
+ locks.push(await acquireInstallLock(path));
2455
+ }
2456
+ catch (e) {
2457
+ for (const handle of locks.reverse())
2458
+ releaseInstallLock(handle);
2459
+ throw e;
2460
+ }
1419
2461
  // Set true only on a rollback double-fault, where the ONLY copy of the
1420
2462
  // previous content ends up parked under the staging root — then the `finally`
1421
2463
  // must NOT delete it (the error message tells the user to recover it).
@@ -1428,7 +2470,20 @@ async function dispatchAdd(io, args) {
1428
2470
  // journal as evidence: without this, the `finally` below would rmSync the
1429
2471
  // staging root and take the backups a later recovery needs with it.
1430
2472
  try {
1431
- recoverInterruptedInstall({ defsDir, journalPath, lockfilePath });
2473
+ recoverInterruptedInstall({
2474
+ defsDir,
2475
+ journalPath: canonicalState.journalPath,
2476
+ lockfilePath: storeIndexPath(defsDir),
2477
+ recoveryMarkerDir,
2478
+ v2Replacement: workflowStoreReplacementRecovery,
2479
+ });
2480
+ recoverInterruptedInstall({
2481
+ defsDir,
2482
+ journalPath,
2483
+ lockfilePath,
2484
+ recoveryMarkerDir,
2485
+ v2Replacement: workflowStoreReplacementRecovery,
2486
+ });
1432
2487
  }
1433
2488
  catch (e) {
1434
2489
  preserveStagingRoot = true;
@@ -1436,8 +2491,10 @@ async function dispatchAdd(io, args) {
1436
2491
  }
1437
2492
  // The lock holder is the only legitimate writer under the staging root, so
1438
2493
  // anything already there is debris from a crashed/killed prior run — clear
1439
- // it. Keeps "no staging debris" true even across a Ctrl-C.
1440
- rmSync(stagingRoot, { recursive: true, force: true });
2494
+ // it. Keeps "no staging debris" true even across a Ctrl-C. The shared
2495
+ // project staging root may hold a hardened CAS object from a crashed
2496
+ // bundle install, so remove without requiring write permission inside it.
2497
+ rmRecursiveForce(stagingRoot);
1441
2498
  // Read the lockfile and decide ownership INSIDE the lock (TOCTOU: a pre-lock
1442
2499
  // read could be stale by the time we act on it). A corrupt lockfile is a
1443
2500
  // hard error (readLockfile), never a silent reset.
@@ -1649,10 +2706,12 @@ async function dispatchAdd(io, args) {
1649
2706
  // finalized; on failure this clears whatever staging debris is left. The one
1650
2707
  // exception is a rollback double-fault (`preserveStagingRoot`), where the
1651
2708
  // only surviving copy of the previous content is parked here — leave it for
1652
- // the user to recover (the next add clears it as debris). Then release the lock.
2709
+ // the user to recover (the next add clears it as debris). Then release the
2710
+ // lock. rmRecursiveForce: the debris may hold a hardened CAS object.
1653
2711
  if (!preserveStagingRoot)
1654
- rmSync(stagingRoot, { recursive: true, force: true });
1655
- releaseInstallLock(lock);
2712
+ rmRecursiveForce(stagingRoot);
2713
+ for (const handle of locks.reverse())
2714
+ releaseInstallLock(handle);
1656
2715
  }
1657
2716
  }
1658
2717
  /**
@@ -1682,6 +2741,15 @@ async function dispatchAddRecover(io, args) {
1682
2741
  if (args.positionals[1] !== undefined) {
1683
2742
  throw new CliError('--recover takes no repository argument — run recovery alone, then re-run add');
1684
2743
  }
2744
+ // --global selects the GLOBAL STORE's offline recovery; plain --recover
2745
+ // keeps this project/GitHub path exactly as before. The --defs conflict
2746
+ // applies here too (the global root never reads a defs override).
2747
+ if (flag(args, 'global')) {
2748
+ if (last(args, 'defs') !== undefined || io.env.OWENLOOP_DEFS !== undefined) {
2749
+ throw new CliError(GLOBAL_DEFS_CONFLICT_MSG);
2750
+ }
2751
+ return dispatchAddRecoverGlobal(io);
2752
+ }
1685
2753
  // Resolve paths EXACTLY as dispatchAdd does — same defsDir/lock/journal
1686
2754
  // derivation — so recovery acts on the same tree a real add would. No fetch
1687
2755
  // reference, no store open.
@@ -1690,20 +2758,56 @@ async function dispatchAddRecover(io, args) {
1690
2758
  const lockfilePath = join(io.cwd, '.owenloop', 'installed.json');
1691
2759
  const installLockPath = join(io.cwd, '.owenloop', 'add.lock');
1692
2760
  const journalPath = join(io.cwd, '.owenloop', ADD_JOURNAL_FILENAME);
2761
+ const canonicalState = workflowStoreStatePaths(projectStoreRoot(defsDir));
2762
+ const recoveryMarkerDir = optionalWorkflowRecoveryMarkerDir(io);
1693
2763
  // Mirror the SEC-3 symlink guards from the normal path (same order, same
1694
2764
  // rationale): `.owenloop` is written by the lock acquire; the default defsDir
1695
2765
  // is mutated-through by recovery. An explicit --defs/OWENLOOP_DEFS is operator
1696
2766
  // intent, not repo content, so it is not symlink-guarded (matching dispatchAdd).
1697
2767
  mkdirRefusingSymlink(join(io.cwd, '.owenloop'));
2768
+ guardStateFile(installLockPath, 'install lock');
2769
+ guardStateFile(journalPath, 'crash-recovery journal');
2770
+ guardStateFile(lockfilePath, 'installed ledger');
1698
2771
  if (defsOverride === undefined)
1699
2772
  mkdirRefusingSymlink(defsDir);
1700
- const lock = await acquireInstallLock(installLockPath);
1701
- let outcome;
2773
+ const canonicalStateExists = lstatSync(canonicalState.stateDir, { throwIfNoEntry: false }) !== undefined;
2774
+ if (canonicalStateExists) {
2775
+ mkdirRefusingSymlink(canonicalState.stateDir);
2776
+ guardStateFile(canonicalState.lockPath, 'canonical install lock');
2777
+ guardStateFile(canonicalState.journalPath, 'canonical crash-recovery journal');
2778
+ }
2779
+ const lockPaths = [...new Set([installLockPath, ...(canonicalStateExists ? [canonicalState.lockPath] : [])])].sort();
2780
+ const locks = [];
1702
2781
  try {
1703
- outcome = recoverInterruptedInstall({ defsDir, journalPath, lockfilePath });
2782
+ for (const path of lockPaths)
2783
+ locks.push(await acquireInstallLock(path));
2784
+ }
2785
+ catch (e) {
2786
+ for (const handle of locks.reverse())
2787
+ releaseInstallLock(handle);
2788
+ throw e;
2789
+ }
2790
+ let outcome = 'no-journal';
2791
+ try {
2792
+ const canonicalOutcome = recoverInterruptedInstall({
2793
+ defsDir,
2794
+ journalPath: canonicalState.journalPath,
2795
+ lockfilePath: storeIndexPath(defsDir),
2796
+ recoveryMarkerDir,
2797
+ v2Replacement: workflowStoreReplacementRecovery,
2798
+ });
2799
+ const legacyOutcome = recoverInterruptedInstall({
2800
+ defsDir,
2801
+ journalPath,
2802
+ lockfilePath,
2803
+ recoveryMarkerDir,
2804
+ v2Replacement: workflowStoreReplacementRecovery,
2805
+ });
2806
+ outcome = legacyOutcome !== 'no-journal' ? legacyOutcome : canonicalOutcome;
1704
2807
  }
1705
2808
  finally {
1706
- releaseInstallLock(lock);
2809
+ for (const handle of locks.reverse())
2810
+ releaseInstallLock(handle);
1707
2811
  }
1708
2812
  switch (outcome) {
1709
2813
  case 'no-journal':
@@ -1729,11 +2833,11 @@ async function dispatchAddRecover(io, args) {
1729
2833
  }
1730
2834
  // ---- hub onboarding: login / logout / connect / push -------------------------
1731
2835
  /**
1732
- * Resolve the target hub origin: `--hub` > `OWENLOOP_HUB` env > the default
1733
- * production hub. Normalized (scheme required, trailing slash/path stripped) so
1734
- * it can serve as a stable credential-store key and project binding value.
2836
+ * Resolve the target hub origin: `--hub` > `OWENLOOP_HUB` env > `DEFAULT_HUB`
2837
+ * (`src/hub.ts` — the production hub). Normalized (scheme required, trailing
2838
+ * slash/path stripped) so it can serve as a stable credential-store key and
2839
+ * project binding value.
1735
2840
  */
1736
- const DEFAULT_HUB = 'https://api.owenloop.com';
1737
2841
  function resolveHub(io, args) {
1738
2842
  const raw = last(args, 'hub') ?? io.env.OWENLOOP_HUB ?? DEFAULT_HUB;
1739
2843
  try {
@@ -1743,6 +2847,89 @@ function resolveHub(io, args) {
1743
2847
  throw new CliError(e.message);
1744
2848
  }
1745
2849
  }
2850
+ /**
2851
+ * Inspect the active credential backend once and return only the facts every
2852
+ * hub-policy resolver needs. Policy stays with the caller: agent commands are
2853
+ * strict, setup may choose DEFAULT_HUB, and publishing commands may consult
2854
+ * execution settings only when the selected backend cannot enumerate.
2855
+ */
2856
+ function discoverStoredHubs(io) {
2857
+ const stored = listStoredHubOrigins(io.env, io.keychain);
2858
+ if (stored === null) {
2859
+ const backend = credentialBackend(io.env, io.keychain);
2860
+ return { kind: 'non-enumerable', backend: backend.kind === 'external' ? 'external-command' : 'keychain' };
2861
+ }
2862
+ let origins;
2863
+ try {
2864
+ origins = stored.map((origin) => normalizeOrigin(origin));
2865
+ }
2866
+ catch (e) {
2867
+ throw new CliError(e.message);
2868
+ }
2869
+ if (origins.length === 0)
2870
+ return { kind: 'empty' };
2871
+ if (origins.length === 1)
2872
+ return { kind: 'one', origin: origins[0] };
2873
+ return { kind: 'multiple', origins: [...origins].sort() };
2874
+ }
2875
+ /**
2876
+ * Resolve the safe publication target shared by connect, push, and publish:
2877
+ * explicit flag > project override > unambiguous global state. OWENLOOP_HUB
2878
+ * and DEFAULT_HUB are intentionally absent from this ladder.
2879
+ */
2880
+ function resolvePublishingHub(io, args, slot) {
2881
+ const flagValue = last(args, 'hub');
2882
+ if (flagValue !== undefined) {
2883
+ try {
2884
+ return { origin: normalizeOrigin(flagValue), source: 'flag' };
2885
+ }
2886
+ catch (e) {
2887
+ throw new CliError(e.message);
2888
+ }
2889
+ }
2890
+ const binding = readHubBinding(hubBindingPath(io.cwd));
2891
+ if (binding !== null) {
2892
+ try {
2893
+ return { origin: normalizeOrigin(binding.hub), source: 'project' };
2894
+ }
2895
+ catch (e) {
2896
+ throw new CliError(`${e.message} — re-run \`owenloop connect --hub <origin>\` to rebind`);
2897
+ }
2898
+ }
2899
+ const discovered = discoverStoredHubs(io);
2900
+ if (discovered.kind === 'one') {
2901
+ return { origin: discovered.origin, source: 'stored' };
2902
+ }
2903
+ if (discovered.kind === 'multiple') {
2904
+ throw new CliError('cannot determine which hub to use — more than one hub has a stored human credential; ' +
2905
+ `stored hubs: ${discovered.origins.join(', ')}; pass --hub <origin> or run ` +
2906
+ '`owenloop connect --hub <origin>`', { exitCode: 2 });
2907
+ }
2908
+ if (discovered.kind === 'empty') {
2909
+ throw new CliError('cannot determine which hub to use — no stored human hub credential was found; ' +
2910
+ 'pass --hub <origin>, run `owenloop connect --hub <origin>`, or log in to exactly one hub first ' +
2911
+ '(`owenloop login --hub <origin>`)', { exitCode: 2 });
2912
+ }
2913
+ const path = executionSettingsPath(io.env);
2914
+ const settings = loadSettings(io.env);
2915
+ const raw = settings.hubOrigin;
2916
+ if (raw === undefined || raw.trim() === '') {
2917
+ throw new CliError(`cannot determine which hub to use — the ${discovered.backend} credential store cannot be enumerated ` +
2918
+ `and ${path} has no non-empty hubOrigin; pass --hub <origin> or run ` +
2919
+ '`owenloop connect --hub <origin>` (owenloop setup populates hubOrigin)', { exitCode: 2 });
2920
+ }
2921
+ let origin;
2922
+ try {
2923
+ origin = normalizeOrigin(raw);
2924
+ }
2925
+ catch (e) {
2926
+ throw new CliError(`invalid hubOrigin in ${path}: ${e.message}`);
2927
+ }
2928
+ const credential = readCredential(io, origin, slot);
2929
+ if (credential === null)
2930
+ throw new CliError(emptySlotMessage(origin, slot));
2931
+ return { origin, source: 'settings', credential };
2932
+ }
1746
2933
  /**
1747
2934
  * Parse `--as <human | agent | agent:NAME>` into a `CredentialSlotSelector`.
1748
2935
  * Absent `--as` means the **human** slot — the everyday interactive case.
@@ -1786,7 +2973,7 @@ function emptySlotMessage(origin, slot) {
1786
2973
  * Read the stored credential for `origin` in `slot`. Thin wrapper over the
1787
2974
  * shared `readStoredCredential` in `hub.ts` (the same implementation the public
1788
2975
  * package export uses), threading the CLI's injected `env`/`keychain`. Callers
1789
- * pass a pre-normalized origin (`resolveHub` output); the wrapper's
2976
+ * pass a pre-normalized origin from the command's applicable resolver; the wrapper's
1790
2977
  * normalization is idempotent, so CLI behavior is unchanged. REL-6 no-fallback
1791
2978
  * and corrupt-entry-as-absent semantics live in `hub.ts`.
1792
2979
  */
@@ -1941,6 +3128,12 @@ async function dispatchLogin(io, args) {
1941
3128
  const existed = readCredential(io, origin, slot) !== null;
1942
3129
  const { identity } = await verifyCredential(io, origin, slot, cred); // never store an unverified token
1943
3130
  const storage = await storeCredential(io, origin, slot, cred);
3131
+ try {
3132
+ writeGlobalConfig(globalConfigPath(workflowHome(io)), { version: 1, hub: origin });
3133
+ }
3134
+ catch (e) {
3135
+ io.err(`warning: could not write ~/.owenloop/config.json (${e.message}) — \`owenloop mcp\` will fall back to other origin sources`);
3136
+ }
1944
3137
  print(io, {
1945
3138
  ok: true,
1946
3139
  hub: origin,
@@ -1961,6 +3154,12 @@ async function dispatchLogin(io, args) {
1961
3154
  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`);
1962
3155
  }
1963
3156
  const r = await runLoopbackOAuth(io, origin);
3157
+ try {
3158
+ writeGlobalConfig(globalConfigPath(workflowHome(io)), { version: 1, hub: origin });
3159
+ }
3160
+ catch (e) {
3161
+ io.err(`warning: could not write ~/.owenloop/config.json (${e.message}) — \`owenloop mcp\` will fall back to other origin sources`);
3162
+ }
1964
3163
  print(io, {
1965
3164
  ok: true,
1966
3165
  hub: origin,
@@ -2181,9 +3380,10 @@ async function dispatchLogout(io, args) {
2181
3380
  * changes so the caller notices the rebind.
2182
3381
  */
2183
3382
  async function dispatchConnect(io, args) {
2184
- const origin = resolveHub(io, args);
2185
3383
  const slot = resolveSlot(args);
2186
- const cred = readCredential(io, origin, slot);
3384
+ const resolved = resolvePublishingHub(io, args, slot);
3385
+ const { origin } = resolved;
3386
+ const cred = resolved.credential ?? readCredential(io, origin, slot);
2187
3387
  if (!cred)
2188
3388
  throw new CliError(emptySlotMessage(origin, slot));
2189
3389
  const { identity } = await verifyCredential(io, origin, slot, cred);
@@ -2203,246 +3403,601 @@ async function dispatchConnect(io, args) {
2203
3403
  });
2204
3404
  return 0;
2205
3405
  }
3406
+ /** Read a publication/origin sidecar without following a symlink. */
3407
+ function readPushSidecar(path, label) {
3408
+ const stat = lstatSync(path, { throwIfNoEntry: false });
3409
+ if (stat === undefined)
3410
+ throw new CliError(`owenloop push --bundle: missing ${label} '${path}'`);
3411
+ if (stat.isSymbolicLink() || !stat.isFile()) {
3412
+ throw new CliError(`owenloop push --bundle: ${label} '${path}' must be a regular file, not a symlink`);
3413
+ }
3414
+ if (stat.size > 32 * 1024 * 1024) {
3415
+ throw new CliError(`owenloop push --bundle: ${label} '${path}' exceeds the hub 32MB request cap`);
3416
+ }
3417
+ let bytes;
3418
+ try {
3419
+ bytes = readFileSync(path);
3420
+ }
3421
+ catch (e) {
3422
+ throw new CliError(`owenloop push --bundle: cannot read ${label} '${path}': ${e.message}`);
3423
+ }
3424
+ let value;
3425
+ try {
3426
+ value = JSON.parse(bytes.toString('utf8'));
3427
+ }
3428
+ catch {
3429
+ throw new CliError(`owenloop push --bundle: ${label} '${path}' is not valid JSON`);
3430
+ }
3431
+ return { bytes, value };
3432
+ }
3433
+ /**
3434
+ * Validate the relay-level DSSE shape and its digest/package binding locally.
3435
+ * Signature authorization remains the execution host's responsibility; this
3436
+ * mirrors the hub's transport boundary and prevents a mismatched sidecar from
3437
+ * landing after the content-addressed bundle upload.
3438
+ */
3439
+ function assertPushDsse(value, expected, payloadType, label) {
3440
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) {
3441
+ throw new CliError(`owenloop push --bundle: ${label} must be a DSSE JSON object`);
3442
+ }
3443
+ const envelope = value;
3444
+ if (envelope.payloadType !== payloadType || typeof envelope.payload !== 'string') {
3445
+ throw new CliError(`owenloop push --bundle: ${label} has the wrong payload type or no string payload`);
3446
+ }
3447
+ if (!Array.isArray(envelope.signatures) || envelope.signatures.length === 0) {
3448
+ throw new CliError(`owenloop push --bundle: ${label} has no signatures`);
3449
+ }
3450
+ for (const signature of envelope.signatures) {
3451
+ if (typeof signature !== 'object' ||
3452
+ signature === null ||
3453
+ Array.isArray(signature) ||
3454
+ typeof signature.keyid !== 'string' ||
3455
+ typeof signature.sig !== 'string') {
3456
+ throw new CliError(`owenloop push --bundle: ${label} contains a malformed signature`);
3457
+ }
3458
+ }
3459
+ let record;
3460
+ try {
3461
+ record = JSON.parse(decodeBase64Strict(envelope.payload, { allowEmpty: false }).toString('utf8'));
3462
+ }
3463
+ catch (e) {
3464
+ throw new CliError(`owenloop push --bundle: ${label} payload is invalid: ${e.message}`);
3465
+ }
3466
+ if (typeof record !== 'object' || record === null || Array.isArray(record)) {
3467
+ throw new CliError(`owenloop push --bundle: ${label} payload is not a JSON object`);
3468
+ }
3469
+ const bound = record;
3470
+ if (bound.digest !== expected.digest || bound.name !== expected.name || bound.version !== expected.version) {
3471
+ throw new CliError(`owenloop push --bundle: ${label} does not bind the selected bundle digest and package identity`);
3472
+ }
3473
+ }
3474
+ /**
3475
+ * Inspect one exact archive, require exactly one adjacent publication sidecar,
3476
+ * and materialize its manifest-declared workflow files into a private temp
3477
+ * directory. The archive, not the caller's checkout, is the source of truth.
3478
+ */
3479
+ function preparePushBundle(io, bundleArg) {
3480
+ if (bundleArg === '' || bundleArg === 'true') {
3481
+ throw new CliError('owenloop push: --bundle requires a .wnlp path value');
3482
+ }
3483
+ const bundlePath = resolve(io.cwd, bundleArg);
3484
+ const bytes = readBundleCommandFile(io, bundleArg);
3485
+ const inspected = runBundle(() => inspectBundle(bytes));
3486
+ const signedPath = `${bundlePath}.dsse`;
3487
+ const unsignedPath = `${bundlePath}.unsigned`;
3488
+ const originPath = `${bundlePath}.origin.dsse`;
3489
+ const hasSigned = lstatSync(signedPath, { throwIfNoEntry: false }) !== undefined;
3490
+ const hasUnsigned = lstatSync(unsignedPath, { throwIfNoEntry: false }) !== undefined;
3491
+ if (hasSigned === hasUnsigned) {
3492
+ throw new CliError(`owenloop push --bundle: expected exactly one publication sidecar: '${signedPath}' or '${unsignedPath}'`);
3493
+ }
3494
+ const expected = {
3495
+ digest: inspected.digest,
3496
+ name: inspected.manifest.package.name,
3497
+ version: inspected.manifest.package.version,
3498
+ };
3499
+ let publication;
3500
+ let publicationState;
3501
+ if (hasSigned) {
3502
+ const sidecar = readPushSidecar(signedPath, 'signed publication sidecar');
3503
+ assertPushDsse(sidecar.value, expected, PAYLOAD_TYPE_PUBLICATION, 'signed publication sidecar');
3504
+ publication = sidecar.bytes;
3505
+ publicationState = 'signed';
3506
+ }
3507
+ else {
3508
+ const sidecar = readPushSidecar(unsignedPath, 'unsigned publication marker');
3509
+ const marker = sidecar.value;
3510
+ if (typeof marker !== 'object' ||
3511
+ marker === null ||
3512
+ Array.isArray(marker) ||
3513
+ marker.formatVersion !== 1 ||
3514
+ marker.digest !== inspected.digest ||
3515
+ marker.signed !== false) {
3516
+ throw new CliError('owenloop push --bundle: unsigned publication marker does not bind the selected bundle digest');
3517
+ }
3518
+ publication = sidecar.bytes;
3519
+ publicationState = 'unsigned';
3520
+ }
3521
+ let origin;
3522
+ if (lstatSync(originPath, { throwIfNoEntry: false }) !== undefined) {
3523
+ const sidecar = readPushSidecar(originPath, 'origin sidecar');
3524
+ assertPushDsse(sidecar.value, expected, PAYLOAD_TYPE_ORIGIN, 'origin sidecar');
3525
+ origin = sidecar.bytes;
3526
+ }
3527
+ const cleanupRoot = mkdtempSync(join(tmpdir(), 'owenloop-push-'));
3528
+ const defsDir = join(cleanupRoot, 'bundle');
3529
+ try {
3530
+ runBundle(() => unpackBundle(bytes, defsDir));
3531
+ }
3532
+ catch (e) {
3533
+ rmSync(cleanupRoot, { recursive: true, force: true });
3534
+ throw e;
3535
+ }
3536
+ return { bytes, digest: inspected.digest, manifest: inspected.manifest, publication, publicationState, origin, defsDir, cleanupRoot };
3537
+ }
3538
+ /** Bundle-backed orders identify a step by bundle digest plus step name. */
3539
+ function assertUniqueBundleStepNames(defs) {
3540
+ const ownerByStep = new Map();
3541
+ const orderedDefs = [...defs.entries()].sort(([left], [right]) => left.localeCompare(right));
3542
+ for (const [definitionName, def] of orderedDefs) {
3543
+ for (const step of def.steps) {
3544
+ const firstOwner = ownerByStep.get(step.name);
3545
+ if (firstOwner !== undefined && firstOwner !== definitionName) {
3546
+ throw new CliError(`owenloop push --bundle: duplicate step name '${step.name}' in workflow definitions ` +
3547
+ `'${firstOwner}' and '${definitionName}'; step names must be unique across the complete archive`);
3548
+ }
3549
+ ownerByStep.set(step.name, definitionName);
3550
+ }
3551
+ }
3552
+ }
3553
+ /**
3554
+ * Order only the explicitly selected definitions by their selected local
3555
+ * `calls:` dependencies. A child is published before each selected parent.
3556
+ * `<currentPackage>/<workflow>` is local in bundle mode; excluded local and
3557
+ * external-package targets add no edge, so selection never pulls another
3558
+ * workflow into the push.
3559
+ */
3560
+ function orderSelectedDefsByCalls(selected, currentPackage) {
3561
+ const selectedByName = new Map(selected.map((def) => [def.name, def]));
3562
+ const state = new Map();
3563
+ const stack = [];
3564
+ const ordered = [];
3565
+ const dependencies = new Map();
3566
+ const localPrefix = currentPackage === undefined ? undefined : `${currentPackage}/`;
3567
+ const localTarget = (target) => {
3568
+ if (target === undefined)
3569
+ return undefined;
3570
+ if (!target.includes('/'))
3571
+ return selectedByName.has(target) ? target : undefined;
3572
+ if (localPrefix === undefined || !target.startsWith(localPrefix))
3573
+ return undefined;
3574
+ const name = target.slice(localPrefix.length);
3575
+ return selectedByName.has(name) ? name : undefined;
3576
+ };
3577
+ const visit = (def) => {
3578
+ const prior = state.get(def.name);
3579
+ if (prior === 'done')
3580
+ return;
3581
+ if (prior === 'visiting') {
3582
+ const cycleStart = stack.indexOf(def.name);
3583
+ const cycle = [...stack.slice(cycleStart), def.name];
3584
+ throw new CliError(`owenloop push: selected calls cycle: ${cycle.join(' -> ')}`);
3585
+ }
3586
+ state.set(def.name, 'visiting');
3587
+ stack.push(def.name);
3588
+ const targets = new Set(def.steps
3589
+ .map((step) => localTarget(step.calls))
3590
+ .filter((target) => target !== undefined));
3591
+ dependencies.set(def.name, targets);
3592
+ for (const target of targets)
3593
+ visit(selectedByName.get(target));
3594
+ stack.pop();
3595
+ state.set(def.name, 'done');
3596
+ ordered.push(def);
3597
+ };
3598
+ for (const def of selected)
3599
+ visit(def);
3600
+ return { ordered, dependencies };
3601
+ }
3602
+ /**
3603
+ * `owenloop push [<defName>...] [--bundle <bundle.wnlp>] [--force]
3604
+ * [--dry-run] [--hub <origin>]` — publish local workflow defs, or exact
3605
+ * bundle-backed defs, to the safely resolved hub, diffed against the hub's own
3606
+ * def `hash` (`GET /api/workflows` — see `computeServerDiff`), never a
3607
+ * client-side ledger. Mirrors `add`'s all-or-nothing client-side validation
3608
+ * gate before any network write; server-side failures mid-batch record what
3609
+ * landed and exit 1. `POST /api/create_workflow` is itself idempotent, so even
3610
+ * a wrong "changed" verdict (e.g. from engine-version drift between this CLI
3611
+ * and the hub) is harmless — it just costs one extra round-trip that the
3612
+ * server reports back as a no-op.
3613
+ */
3614
+ async function dispatchPush(io, args) {
3615
+ const configuredDefsDir = last(args, 'defs') ?? io.env.OWENLOOP_DEFS ?? join(io.cwd, 'workflows');
3616
+ const bundleArg = last(args, 'bundle');
3617
+ if (bundleArg !== undefined && args.options.has('defs')) {
3618
+ throw new CliError('owenloop push: --bundle cannot be combined with --defs; the archive is the definition source');
3619
+ }
3620
+ const dryRun = flag(args, 'dry-run');
3621
+ const force = flag(args, 'force');
3622
+ const slot = resolveSlot(args);
3623
+ const resolved = resolvePublishingHub(io, args, slot);
3624
+ const { origin } = resolved;
3625
+ let cred = resolved.credential ?? readCredential(io, origin, slot);
3626
+ if (!cred)
3627
+ throw new CliError(emptySlotMessage(origin, slot));
3628
+ let bundle;
3629
+ try {
3630
+ bundle = bundleArg === undefined ? undefined : preparePushBundle(io, bundleArg);
3631
+ const defsDir = bundle?.defsDir ?? configuredDefsDir;
3632
+ // Load defs (same machinery as lint/add). Bundle mode reads only the
3633
+ // manifest-declared workflow paths from the materialized exact archive;
3634
+ // bundle.yaml and unrelated YAML assets are never mistaken for defs.
3635
+ if (!existsSync(defsDir))
3636
+ throw new CliError(`defs directory not found: ${defsDir}`);
3637
+ const failures = [];
3638
+ let allDefs;
3639
+ if (bundle !== undefined) {
3640
+ allDefs = new Map();
3641
+ for (const [name, workflowPath] of Object.entries(bundle.manifest.workflows)) {
3642
+ try {
3643
+ const def = loadDefFile(join(defsDir, workflowPath));
3644
+ if (def.name !== name) {
3645
+ throw new CliError(`manifest workflow '${name}' loads as '${def.name}'`);
3646
+ }
3647
+ allDefs.set(name, def);
3648
+ }
3649
+ catch (e) {
3650
+ throw new CliError(`owenloop push --bundle: cannot load workflow '${name}': ${e.message}`);
3651
+ }
3652
+ }
3653
+ }
3654
+ else {
3655
+ allDefs = loadDefsRaw(defsDir, failures);
3656
+ }
3657
+ if (bundle !== undefined)
3658
+ assertUniqueBundleStepNames(allDefs);
3659
+ // Narrow to positional names, if any (error on an unknown name).
3660
+ const requested = args.positionals.slice(1);
3661
+ let selected;
3662
+ if (requested.length > 0) {
3663
+ selected = [];
3664
+ for (const name of requested) {
3665
+ const def = allDefs.get(name);
3666
+ if (!def) {
3667
+ throw new CliError(`unknown workflow definition '${name}' (looked in ${defsDir})${failureNote(failures)}`);
3668
+ }
3669
+ selected.push(def);
3670
+ }
3671
+ }
3672
+ else {
3673
+ selected = [...allDefs.values()];
3674
+ }
3675
+ if (selected.length === 0) {
3676
+ throw new CliError(`nothing to push — no workflow definitions found in ${defsDir}`);
3677
+ }
3678
+ const selectedOrder = orderSelectedDefsByCalls(selected, bundle?.manifest.package.name);
3679
+ selected = selectedOrder.ordered;
3680
+ const selectedDependencies = selectedOrder.dependencies;
3681
+ // Client-side validation gate — all-or-nothing, mirroring dispatchAdd exactly.
3682
+ // Any failure aborts the entire push; nothing is sent.
3683
+ const reasons = failures.map((f) => `${f.file}: ${f.error}`);
3684
+ for (const def of selected) {
3685
+ const lintResult = lintDef(def);
3686
+ reasons.push(...lintResult.errors.map((e) => `${def.name}: ${e}`));
3687
+ reasons.push(...validateDef(def).map((e) => `${def.name}: ${e}`));
3688
+ const report = modelCheck(def, { assumeProvided: true });
3689
+ const hasDefiniteDefect = hasDefiniteCheckDefect(report);
3690
+ if (hasDefiniteDefect) {
3691
+ reasons.push(`${def.name}: definite defects found (${report.invariantViolations.length} invariant violation(s), ` +
3692
+ `${report.structurallyDeadSteps.length} structurally dead step(s), ` +
3693
+ `${report.deadlocks.length} true deadlock(s))`);
3694
+ }
3695
+ }
3696
+ // Assemble the push candidates: verbatim source yaml + the server-canonical
3697
+ // content hash (hashDefForHub). Defs whose file uses include: are not
3698
+ // hub-pushable (the service's create_workflow parses without include
3699
+ // expansion, and a re-serialized expanded def is not round-trippable) —
3700
+ // refuse them with a clear per-def reason. Same for bodyFile: — hashDefForHub
3701
+ // parses with no baseDir (matching the server's own computation), which
3702
+ // throws a DefError naming bodyFile for such a def; catch that specific
3703
+ // failure and refuse the def pre-push rather than letting it read as a
3704
+ // generic error (the server would reject the raw-YAML push anyway).
3705
+ const candidates = [];
3706
+ for (const def of selected) {
3707
+ if (!def.dir) {
3708
+ reasons.push(`${def.name}: has no source file on disk to push`);
3709
+ continue;
3710
+ }
3711
+ const yaml = readFileSync(def.dir, 'utf8');
3712
+ let usesInclude = false;
3713
+ try {
3714
+ const rawDef = buildDef(parseYaml(yaml), basename(def.dir), dirname(def.dir));
3715
+ usesInclude = (rawDef._includes?.length ?? 0) > 0;
3716
+ }
3717
+ catch {
3718
+ // A shape error here would already have surfaced via the validation gate;
3719
+ // treat an unexpected re-parse failure conservatively as pushable-as-is.
3720
+ }
3721
+ if (usesInclude) {
3722
+ reasons.push(`${def.name}: uses include:, not hub-pushable yet`);
3723
+ continue;
3724
+ }
3725
+ let hash;
3726
+ try {
3727
+ hash = hashDefForHub(yaml);
3728
+ }
3729
+ catch (e) {
3730
+ if (e instanceof DefError && /bodyFile/.test(e.message)) {
3731
+ reasons.push(`${def.name}: uses bodyFile:, not hub-pushable`);
3732
+ continue;
3733
+ }
3734
+ throw e;
3735
+ }
3736
+ candidates.push({ name: def.name, hash, yaml });
3737
+ }
3738
+ if (reasons.length > 0) {
3739
+ throw new CliError(`refusing to push — ${reasons.length} problem(s) found; nothing sent:\n - ${reasons.join('\n - ')}`);
3740
+ }
3741
+ // Fetch the server's own list once — the diff source of truth. Always
3742
+ // fetched, even under --force, so the new/changed capabilities stay accurate.
3743
+ const { res: listRes, cred: listCred } = await authedGet(io, origin, slot, cred, '/api/workflows');
3744
+ assertAuthOk(listRes, listCred, origin);
3745
+ cred = listCred;
3746
+ let serverMap;
3747
+ try {
3748
+ serverMap = parseWorkflowList(await listRes.json());
3749
+ }
3750
+ catch (e) {
3751
+ throw new CliError(e.message);
3752
+ }
3753
+ // A bundle-backed push must always send create_workflow: GET /api/workflows
3754
+ // exposes the YAML hash but intentionally not the latest bundle identity.
3755
+ // The server's (yaml,bundleDigest) idempotency decides whether this is a new
3756
+ // version or an exact no-op.
3757
+ const { toPush, unchanged } = computeServerDiff(candidates, serverMap, force || bundle !== undefined);
3758
+ // Diff-style human lines go to stderr so stdout stays machine-parseable JSON.
3759
+ for (const c of unchanged)
3760
+ io.err(`= ${c.name} (unchanged)`);
3761
+ if (dryRun) {
3762
+ for (const c of toPush) {
3763
+ io.err(c.status === 'new' ? `+ ${c.name} (new)` : `~ ${c.name} (changed)`);
3764
+ }
3765
+ print(io, {
3766
+ ok: true,
3767
+ dryRun: true,
3768
+ hub: origin,
3769
+ ...(bundle === undefined ? {} : { bundleDigest: bundle.digest, publication: bundle.publicationState }),
3770
+ new: toPush.filter((c) => c.status === 'new').map((c) => c.name),
3771
+ changed: toPush.filter((c) => c.status === 'changed').map((c) => c.name),
3772
+ unchanged: unchanged.map((c) => c.name),
3773
+ wouldPush: toPush.map((c) => c.name),
3774
+ });
3775
+ return 0;
3776
+ }
3777
+ // Refresh an expiring oauth token once up front (per-request 401 refresh below covers mid-batch expiry).
3778
+ cred = await ensureFreshOAuth(io, origin, slot, cred);
3779
+ if (bundle !== undefined) {
3780
+ cred = await uploadPushBundle(io, origin, slot, cred, bundle);
3781
+ }
3782
+ const pushedNames = [];
3783
+ const noopNames = [];
3784
+ const failed = [];
3785
+ const skipped = [];
3786
+ const unsuccessful = new Set();
3787
+ for (let i = 0; i < toPush.length; i++) {
3788
+ const c = toPush[i];
3789
+ const label = c.status === 'new' ? '+' : '~';
3790
+ const blockedBy = [...(selectedDependencies.get(c.name) ?? [])]
3791
+ .filter((dependency) => unsuccessful.has(dependency))
3792
+ .sort();
3793
+ if (blockedBy.length > 0) {
3794
+ skipped.push(c.name);
3795
+ unsuccessful.add(c.name);
3796
+ io.err(`- ${c.name} (skipped: selected dependency ${blockedBy.map((name) => `'${name}'`).join(', ')} failed or was skipped)`);
3797
+ continue;
3798
+ }
3799
+ try {
3800
+ let res = await createWorkflowRequest(io, origin, cred, c.yaml, bundle?.digest);
3801
+ if (res.status === 401 && cred.kind === 'oauth') {
3802
+ cred = await refreshOAuth(io, origin, slot, cred);
3803
+ res = await createWorkflowRequest(io, origin, cred, c.yaml, bundle?.digest);
3804
+ }
3805
+ if (res.status === 401) {
3806
+ if (cred.kind === 'agent') {
3807
+ throw new CliError('token revoked or invalid — re-mint it in the console or run `owenloop login`');
3808
+ }
3809
+ throw new CliError('credential rejected by the hub — run `owenloop login`');
3810
+ }
3811
+ if (res.status === 413)
3812
+ throw new CliError('workflow yaml exceeds the hub 32MB request cap');
3813
+ if (res.status === 429) {
3814
+ const retryAfter = res.headers.get('retry-after');
3815
+ throw new RateLimitError(`rate limited by the hub${retryAfter ? ` (retry after ${retryAfter})` : ''}`);
3816
+ }
3817
+ if (!res.ok)
3818
+ throw new CliError(`hub returned HTTP ${res.status}`);
3819
+ const bodyJson = await res.json();
3820
+ const errText = createWorkflowError(bodyJson);
3821
+ if (errText !== null)
3822
+ throw new CliError(`hub rejected the def: ${errText}`);
3823
+ const okBody = asCreateWorkflowOk(bodyJson, c.name);
3824
+ if (okBody.unchanged) {
3825
+ noopNames.push(c.name);
3826
+ io.err(`= ${c.name} (server: unchanged, v${okBody.version})`);
3827
+ }
3828
+ else {
3829
+ pushedNames.push(c.name);
3830
+ io.err(`${label} ${c.name} (→ v${okBody.version})`);
3831
+ }
3832
+ }
3833
+ catch (e) {
3834
+ // A 429 halts the whole batch immediately (REL-10): record this def as
3835
+ // failed, then stop — the not-yet-attempted remainder is reported as
3836
+ // `skipped`, not silently hammered against a rate-limited server.
3837
+ // Handled before the generic path because RateLimitError extends CliError.
3838
+ if (e instanceof RateLimitError) {
3839
+ const msg = e.message;
3840
+ failed.push({ name: c.name, error: msg });
3841
+ unsuccessful.add(c.name);
3842
+ io.err(`! ${c.name} (failed: ${msg})`);
3843
+ const remainder = toPush.slice(i + 1).map((r) => r.name);
3844
+ skipped.push(...remainder);
3845
+ for (const name of remainder)
3846
+ unsuccessful.add(name);
3847
+ if (remainder.length > 0) {
3848
+ io.err(`stopping — rate limited by the hub; ${remainder.length} def(s) not attempted`);
3849
+ }
3850
+ break;
3851
+ }
3852
+ // A hard auth error aborts the whole run (re-throw); a per-def server
3853
+ // failure is recorded and the batch continues (already-pushed defs stand).
3854
+ if (e instanceof CliError && /run `owenloop login`|re-mint it/.test(e.message)) {
3855
+ throw e;
3856
+ }
3857
+ const msg = e.message;
3858
+ failed.push({ name: c.name, error: msg });
3859
+ unsuccessful.add(c.name);
3860
+ io.err(`! ${c.name} (failed: ${msg})`);
3861
+ }
3862
+ }
3863
+ print(io, {
3864
+ ok: failed.length === 0,
3865
+ hub: origin,
3866
+ ...(bundle === undefined ? {} : { bundleDigest: bundle.digest, publication: bundle.publicationState }),
3867
+ pushed: pushedNames,
3868
+ noop: noopNames,
3869
+ unchanged: unchanged.map((c) => c.name),
3870
+ skipped,
3871
+ failed,
3872
+ });
3873
+ return failed.length === 0 ? 0 : 1;
3874
+ }
3875
+ finally {
3876
+ if (bundle !== undefined)
3877
+ rmSync(bundle.cleanupRoot, { recursive: true, force: true });
3878
+ }
3879
+ }
2206
3880
  /**
2207
- * `owenloop push [<defName>...] [--force] [--dry-run]` — publish local workflow
2208
- * defs to the bound hub, diffed against the hub's own def `hash`
2209
- * (`GET /api/workflows` — see `computeServerDiff`), never a client-side
2210
- * ledger. Mirrors `add`'s all-or-nothing client-side validation gate before
2211
- * any network write; server-side failures mid-batch record what landed and
2212
- * exit 1. `POST /api/create_workflow` is itself idempotent, so even a wrong
2213
- * "changed" verdict (e.g. from engine-version drift between this CLI and the
2214
- * hub) is harmless — it just costs one extra round-trip that the server
2215
- * reports back as a no-op.
3881
+ * Resolve the hub for `start` without ever falling through to the production
3882
+ * default or an ambient `OWENLOOP_HUB`. A connected project supplies the
3883
+ * durable default. `--hub` is allowed for an unbound directory, but must agree
3884
+ * with an existing binding so a copied command cannot silently start a run on
3885
+ * the wrong control plane.
2216
3886
  */
2217
- async function dispatchPush(io, args) {
2218
- const defsDir = last(args, 'defs') ?? io.env.OWENLOOP_DEFS ?? join(io.cwd, 'workflows');
2219
- const dryRun = flag(args, 'dry-run');
2220
- const force = flag(args, 'force');
2221
- const slot = resolveSlot(args);
2222
- // Require a project binding.
2223
- const bindingPath = hubBindingPath(io.cwd);
2224
- const binding = readHubBinding(bindingPath);
2225
- if (!binding)
2226
- throw new CliError('this project is not bound to a hub — run `owenloop connect` first');
2227
- // Defense in depth (SEC-2): a hub.json written by an older CLI could carry a
2228
- // remote-http origin that predates the transport policy, and dispatchPush uses
2229
- // it verbatim as the request origin. Validate the persisted binding at USE
2230
- // time — normalizeOrigin enforces https-except-loopback. This check lives
2231
- // here, NOT inside readHubBinding: dispatchConnect reads the existing binding
2232
- // only to report switchedFrom, and a read-time throw would deadlock rebinding
2233
- // AWAY from a bad origin. Leave readHubBinding shape-validation-only.
2234
- let origin;
2235
- try {
2236
- origin = normalizeOrigin(binding.hub);
2237
- }
2238
- catch (e) {
2239
- throw new CliError(`${e.message} — re-run \`owenloop connect\` to rebind`);
2240
- }
2241
- // A --hub that disagrees with the binding is a mistake, not a silent override.
2242
- const hubArg = last(args, 'hub');
2243
- if (hubArg !== undefined) {
2244
- const requested = normalizeOrigin(hubArg);
2245
- if (requested !== origin) {
2246
- throw new CliError(`this project is bound to ${origin}, not ${requested} — re-run \`owenloop connect\` to rebind`);
2247
- }
2248
- }
2249
- let cred = readCredential(io, origin, slot);
2250
- if (!cred)
2251
- throw new CliError(emptySlotMessage(origin, slot));
2252
- // Load defs (same machinery as lint/add).
2253
- if (!existsSync(defsDir))
2254
- throw new CliError(`defs directory not found: ${defsDir}`);
2255
- const failures = [];
2256
- const allDefs = loadDefsRaw(defsDir, failures);
2257
- // Narrow to positional names, if any (error on an unknown name).
2258
- const requested = args.positionals.slice(1);
2259
- let selected;
2260
- if (requested.length > 0) {
2261
- selected = [];
2262
- for (const name of requested) {
2263
- const def = allDefs.get(name);
2264
- if (!def) {
2265
- throw new CliError(`unknown workflow definition '${name}' (looked in ${defsDir})${failureNote(failures)}`);
2266
- }
2267
- selected.push(def);
3887
+ function resolveStartHub(io, args) {
3888
+ const binding = readHubBinding(hubBindingPath(io.cwd));
3889
+ let bound;
3890
+ if (binding !== null) {
3891
+ try {
3892
+ bound = normalizeOrigin(binding.hub);
2268
3893
  }
2269
- }
2270
- else {
2271
- selected = [...allDefs.values()];
2272
- }
2273
- if (selected.length === 0) {
2274
- throw new CliError(`nothing to push — no workflow definitions found in ${defsDir}`);
2275
- }
2276
- // Client-side validation gate — all-or-nothing, mirroring dispatchAdd exactly.
2277
- // Any failure aborts the entire push; nothing is sent.
2278
- const reasons = failures.map((f) => `${f.file}: ${f.error}`);
2279
- for (const def of selected) {
2280
- const lintResult = lintDef(def);
2281
- reasons.push(...lintResult.errors.map((e) => `${def.name}: ${e}`));
2282
- reasons.push(...validateDef(def).map((e) => `${def.name}: ${e}`));
2283
- const report = modelCheck(def, { assumeProvided: true });
2284
- const hasDefiniteDefect = hasDefiniteCheckDefect(report);
2285
- if (hasDefiniteDefect) {
2286
- reasons.push(`${def.name}: definite defects found (${report.invariantViolations.length} invariant violation(s), ` +
2287
- `${report.structurallyDeadSteps.length} structurally dead step(s), ` +
2288
- `${report.deadlocks.length} true deadlock(s))`);
3894
+ catch (e) {
3895
+ throw new CliError(`${e.message} — re-run \`owenloop connect\` to rebind`);
2289
3896
  }
2290
3897
  }
2291
- // Assemble the push candidates: verbatim source yaml + the server-canonical
2292
- // content hash (hashDefForHub). Defs whose file uses include: are not
2293
- // hub-pushable (the service's create_workflow parses without include
2294
- // expansion, and a re-serialized expanded def is not round-trippable) —
2295
- // refuse them with a clear per-def reason. Same for bodyFile: — hashDefForHub
2296
- // parses with no baseDir (matching the server's own computation), which
2297
- // throws a DefError naming bodyFile for such a def; catch that specific
2298
- // failure and refuse the def pre-push rather than letting it read as a
2299
- // generic error (the server would reject the raw-YAML push anyway).
2300
- const candidates = [];
2301
- for (const def of selected) {
2302
- if (!def.dir) {
2303
- reasons.push(`${def.name}: has no source file on disk to push`);
2304
- continue;
2305
- }
2306
- const yaml = readFileSync(def.dir, 'utf8');
2307
- let usesInclude = false;
3898
+ const hubArg = last(args, 'hub');
3899
+ if (hubArg !== undefined) {
3900
+ let requested;
2308
3901
  try {
2309
- const rawDef = buildDef(parseYaml(yaml), basename(def.dir), dirname(def.dir));
2310
- usesInclude = (rawDef._includes?.length ?? 0) > 0;
3902
+ requested = normalizeOrigin(hubArg);
2311
3903
  }
2312
- catch {
2313
- // A shape error here would already have surfaced via the validation gate;
2314
- // treat an unexpected re-parse failure conservatively as pushable-as-is.
3904
+ catch (e) {
3905
+ throw new CliError(e.message);
2315
3906
  }
2316
- if (usesInclude) {
2317
- reasons.push(`${def.name}: uses include:, not hub-pushable yet`);
2318
- continue;
3907
+ if (bound !== undefined && requested !== bound) {
3908
+ throw new CliError(`this project is bound to ${bound}, not ${requested} — re-run \`owenloop connect\` to rebind`);
2319
3909
  }
2320
- let hash;
2321
- try {
2322
- hash = hashDefForHub(yaml);
3910
+ return requested;
3911
+ }
3912
+ if (bound !== undefined)
3913
+ return bound;
3914
+ throw new CliError('this project is not bound to a hub — run `owenloop connect`, or pass --hub <url>');
3915
+ }
3916
+ /** Extract the stable hub message without ever echoing an untyped raw body. */
3917
+ async function hubRequestMessage(res) {
3918
+ try {
3919
+ const body = (await res.json());
3920
+ if (typeof body !== 'object' || body === null)
3921
+ return undefined;
3922
+ const message = body.message;
3923
+ return typeof message === 'string' && message !== '' ? message : undefined;
3924
+ }
3925
+ catch {
3926
+ return undefined;
3927
+ }
3928
+ }
3929
+ /**
3930
+ * `owenloop start` — the small, public per-run control-plane command.
3931
+ * Durable setup (login/connect/push/prepare and a standing Shift) remains
3932
+ * separate; starting another instance is one authenticated POST using the
3933
+ * human credential and the same repeated `--provide name=json` grammar as the
3934
+ * local `create` command.
3935
+ */
3936
+ async function dispatchStart(io, args) {
3937
+ const defName = need(args, 1, 'defName');
3938
+ const requiredTextOption = (key, label) => {
3939
+ if (args.missingOptionValues.has(key)) {
3940
+ throw new CliError(`missing value for --${key}: expected --${key} <${label}>`);
2323
3941
  }
2324
- catch (e) {
2325
- if (e instanceof DefError && /bodyFile/.test(e.message)) {
2326
- reasons.push(`${def.name}: uses bodyFile:, not hub-pushable`);
2327
- continue;
2328
- }
2329
- throw e;
3942
+ const value = last(args, key);
3943
+ if (value !== undefined && value.trim() === '') {
3944
+ throw new CliError(`invalid empty value for --${key}: expected --${key} <${label}>`);
2330
3945
  }
2331
- candidates.push({ name: def.name, hash, yaml });
3946
+ return value;
3947
+ };
3948
+ // Validate request-only options before project binding, Keychain, or network access.
3949
+ const crew = requiredTextOption('crew', 'name');
3950
+ const title = requiredTextOption('title', 'text');
3951
+ const origin = resolveStartHub(io, args);
3952
+ const slot = { principal: 'human' };
3953
+ const cred = readCredential(io, origin, slot);
3954
+ if (cred === null) {
3955
+ throw new CliError(`no human credential for ${origin} — run: owenloop login --hub ${origin}`, { exitCode: 3 });
2332
3956
  }
2333
- if (reasons.length > 0) {
2334
- throw new CliError(`refusing to push — ${reasons.length} problem(s) found; nothing sent:\n - ${reasons.join('\n - ')}`);
3957
+ const provide = parsePairs(all(args, 'provide'), true);
3958
+ const request = {
3959
+ workflow_name: defName,
3960
+ ...(Object.keys(provide).length > 0 ? { provide } : {}),
3961
+ ...(crew !== undefined ? { default_crew: crew } : {}),
3962
+ ...(title !== undefined ? { title } : {}),
3963
+ };
3964
+ const { res, cred: used } = await authedPost(io, origin, slot, cred, '/api/start_run', request);
3965
+ if (res.status === 401)
3966
+ assertAuthOk(res, used, origin);
3967
+ if (!res.ok) {
3968
+ const message = await hubRequestMessage(res);
3969
+ throw new CliError(message ?? `hub ${origin} rejected the request (HTTP ${res.status})`);
2335
3970
  }
2336
- // Fetch the server's own list once — the diff source of truth. Always
2337
- // fetched, even under --force, so the new/changed capabilities stay accurate.
2338
- const { res: listRes, cred: listCred } = await authedGet(io, origin, slot, cred, '/api/workflows');
2339
- assertAuthOk(listRes, listCred, origin);
2340
- cred = listCred;
2341
- let serverMap;
3971
+ let body;
2342
3972
  try {
2343
- serverMap = parseWorkflowList(await listRes.json());
3973
+ body = (await res.json());
2344
3974
  }
2345
- catch (e) {
2346
- throw new CliError(e.message);
3975
+ catch {
3976
+ throw new CliError('start_run: malformed success response — body is not valid JSON');
2347
3977
  }
2348
- const { toPush, unchanged } = computeServerDiff(candidates, serverMap, force);
2349
- // Diff-style human lines go to stderr so stdout stays machine-parseable JSON.
2350
- for (const c of unchanged)
2351
- io.err(`= ${c.name} (unchanged)`);
2352
- if (dryRun) {
2353
- for (const c of toPush) {
2354
- io.err(c.status === 'new' ? `+ ${c.name} (new)` : `~ ${c.name} (changed)`);
2355
- }
2356
- print(io, {
2357
- ok: true,
2358
- dryRun: true,
2359
- hub: origin,
2360
- new: toPush.filter((c) => c.status === 'new').map((c) => c.name),
2361
- changed: toPush.filter((c) => c.status === 'changed').map((c) => c.name),
2362
- unchanged: unchanged.map((c) => c.name),
2363
- wouldPush: toPush.map((c) => c.name),
2364
- });
2365
- return 0;
3978
+ if (typeof body !== 'object' || body === null) {
3979
+ throw new CliError('start_run: malformed success response — body is not an object');
2366
3980
  }
2367
- // Refresh an expiring oauth token once up front (per-request 401 refresh below covers mid-batch expiry).
2368
- cred = await ensureFreshOAuth(io, origin, slot, cred);
2369
- const pushedNames = [];
2370
- const noopNames = [];
2371
- const failed = [];
2372
- const skipped = [];
2373
- for (let i = 0; i < toPush.length; i++) {
2374
- const c = toPush[i];
2375
- const label = c.status === 'new' ? '+' : '~';
2376
- try {
2377
- let res = await createWorkflowRequest(io, origin, cred, c.yaml);
2378
- if (res.status === 401 && cred.kind === 'oauth') {
2379
- cred = await refreshOAuth(io, origin, slot, cred);
2380
- res = await createWorkflowRequest(io, origin, cred, c.yaml);
2381
- }
2382
- if (res.status === 401) {
2383
- if (cred.kind === 'agent') {
2384
- throw new CliError('token revoked or invalid — re-mint it in the console or run `owenloop login`');
2385
- }
2386
- throw new CliError('credential rejected by the hub — run `owenloop login`');
2387
- }
2388
- if (res.status === 413)
2389
- throw new CliError('workflow yaml exceeds the hub 32MB request cap');
2390
- if (res.status === 429) {
2391
- const retryAfter = res.headers.get('retry-after');
2392
- throw new RateLimitError(`rate limited by the hub${retryAfter ? ` (retry after ${retryAfter})` : ''}`);
2393
- }
2394
- if (!res.ok)
2395
- throw new CliError(`hub returned HTTP ${res.status}`);
2396
- const bodyJson = await res.json();
2397
- const errText = createWorkflowError(bodyJson);
2398
- if (errText !== null)
2399
- throw new CliError(`hub rejected the def: ${errText}`);
2400
- const okBody = asCreateWorkflowOk(bodyJson, c.name);
2401
- if (okBody.unchanged) {
2402
- noopNames.push(c.name);
2403
- io.err(`= ${c.name} (server: unchanged, v${okBody.version})`);
2404
- }
2405
- else {
2406
- pushedNames.push(c.name);
2407
- io.err(`${label} ${c.name} (→ v${okBody.version})`);
2408
- }
2409
- }
2410
- catch (e) {
2411
- // A 429 halts the whole batch immediately (REL-10): record this def as
2412
- // failed, then stop — the not-yet-attempted remainder is reported as
2413
- // `skipped`, not silently hammered against a rate-limited server.
2414
- // Handled before the generic path because RateLimitError extends CliError.
2415
- if (e instanceof RateLimitError) {
2416
- const msg = e.message;
2417
- failed.push({ name: c.name, error: msg });
2418
- io.err(`! ${c.name} (failed: ${msg})`);
2419
- const remainder = toPush.slice(i + 1).map((r) => r.name);
2420
- skipped.push(...remainder);
2421
- if (remainder.length > 0) {
2422
- io.err(`stopping — rate limited by the hub; ${remainder.length} def(s) not attempted`);
2423
- }
2424
- break;
2425
- }
2426
- // A hard auth error aborts the whole run (re-throw); a per-def server
2427
- // failure is recorded and the batch continues (already-pushed defs stand).
2428
- if (e instanceof CliError && /run `owenloop login`|re-mint it/.test(e.message)) {
2429
- throw e;
2430
- }
2431
- const msg = e.message;
2432
- failed.push({ name: c.name, error: msg });
2433
- io.err(`! ${c.name} (failed: ${msg})`);
2434
- }
3981
+ const wire = body;
3982
+ if (typeof wire.workflow !== 'string' || wire.workflow === '') {
3983
+ throw new CliError('start_run: malformed success response — missing workflow id');
3984
+ }
3985
+ if (wire.def !== defName) {
3986
+ throw new CliError('start_run: malformed success response — definition does not match the request');
3987
+ }
3988
+ if (typeof wire.status !== 'object' || wire.status === null || Array.isArray(wire.status)) {
3989
+ throw new CliError('start_run: malformed success response — missing status object');
2435
3990
  }
2436
3991
  print(io, {
2437
- ok: failed.length === 0,
3992
+ ok: true,
2438
3993
  hub: origin,
2439
- pushed: pushedNames,
2440
- noop: noopNames,
2441
- unchanged: unchanged.map((c) => c.name),
2442
- skipped,
2443
- failed,
3994
+ workflow: wire.workflow,
3995
+ def: wire.def,
3996
+ status: wire.status,
3997
+ ...(Array.isArray(wire.stampedCrews) ? { stampedCrews: wire.stampedCrews } : {}),
3998
+ ...(Array.isArray(wire.validatedCrews) ? { validatedCrews: wire.validatedCrews } : {}),
2444
3999
  });
2445
- return failed.length === 0 ? 0 : 1;
4000
+ return 0;
2446
4001
  }
2447
4002
  /**
2448
4003
  * `owenloop mcp` — serve the human control plane to a local MCP host over stdio.
@@ -2454,7 +4009,55 @@ async function dispatchPush(io, args) {
2454
4009
  async function dispatchMcp(io, args) {
2455
4010
  return runMcpCommand(io, { hubFlag: last(args, 'hub') });
2456
4011
  }
2457
- function createWorkflowRequest(io, origin, cred, yaml) {
4012
+ /** POST opaque bundle/sidecar bytes with the same one-refresh auth contract as JSON hub calls. */
4013
+ async function authedPushBytes(io, origin, slot, cred, path, bytes, headers) {
4014
+ let current = await ensureFreshOAuth(io, origin, slot, cred);
4015
+ const send = (bearer) => hubFetch(io, resolveEndpoint(origin, path), {
4016
+ method: 'POST',
4017
+ headers: { Authorization: authHeader(bearer), Accept: 'application/json', ...headers },
4018
+ body: Buffer.from(bytes),
4019
+ });
4020
+ let res = await send(current);
4021
+ if (res.status === 401 && current.kind === 'oauth') {
4022
+ current = await refreshOAuth(io, origin, slot, current);
4023
+ res = await send(current);
4024
+ }
4025
+ return { res, cred: current };
4026
+ }
4027
+ async function assertPushArtifactOk(res, cred, origin, label) {
4028
+ if (res.status === 401)
4029
+ assertAuthOk(res, cred, origin);
4030
+ if (res.status === 413)
4031
+ throw new CliError(`${label} exceeds the hub request cap`);
4032
+ if (res.status === 429) {
4033
+ const retryAfter = res.headers.get('retry-after');
4034
+ throw new CliError(`rate limited while uploading ${label}${retryAfter ? ` (retry after ${retryAfter})` : ''}`);
4035
+ }
4036
+ if (!res.ok) {
4037
+ const message = await hubRequestMessage(res);
4038
+ throw new CliError(message === undefined ? `hub returned HTTP ${res.status} while uploading ${label}` : `${label}: ${message}`);
4039
+ }
4040
+ }
4041
+ /** Upload the exact archive and adjacent publication/origin records before any definition version is created. */
4042
+ async function uploadPushBundle(io, origin, slot, initial, bundle) {
4043
+ let cred = initial;
4044
+ let sent = await authedPushBytes(io, origin, slot, cred, '/api/bundles', bundle.bytes, {
4045
+ 'Content-Type': 'application/gzip',
4046
+ 'X-Bundle-Digest': bundle.digest,
4047
+ });
4048
+ cred = sent.cred;
4049
+ await assertPushArtifactOk(sent.res, cred, origin, 'bundle');
4050
+ sent = await authedPushBytes(io, origin, slot, cred, `/api/publications/${bundle.digest}?state=${bundle.publicationState}`, bundle.publication, { 'Content-Type': 'application/json' });
4051
+ cred = sent.cred;
4052
+ await assertPushArtifactOk(sent.res, cred, origin, 'publication sidecar');
4053
+ if (bundle.origin !== undefined) {
4054
+ sent = await authedPushBytes(io, origin, slot, cred, `/api/origins/${bundle.digest}`, bundle.origin, { 'Content-Type': 'application/json' });
4055
+ cred = sent.cred;
4056
+ await assertPushArtifactOk(sent.res, cred, origin, 'origin sidecar');
4057
+ }
4058
+ return cred;
4059
+ }
4060
+ function createWorkflowRequest(io, origin, cred, yaml, bundleDigest) {
2458
4061
  return hubFetch(io, resolveEndpoint(origin, '/api/create_workflow'), {
2459
4062
  method: 'POST',
2460
4063
  headers: {
@@ -2462,7 +4065,7 @@ function createWorkflowRequest(io, origin, cred, yaml) {
2462
4065
  'Content-Type': 'application/json',
2463
4066
  Accept: 'application/json',
2464
4067
  },
2465
- body: JSON.stringify({ yaml }),
4068
+ body: JSON.stringify({ yaml, ...(bundleDigest === undefined ? {} : { bundle_digest: bundleDigest }) }),
2466
4069
  });
2467
4070
  }
2468
4071
  /**
@@ -2502,18 +4105,16 @@ function resolveAgentHub(io, args, purpose = 'mint on') {
2502
4105
  throw new CliError(e.message);
2503
4106
  }
2504
4107
  }
2505
- const origins = listStoredHubOrigins(io.env, io.keychain);
2506
- if (origins === null) {
2507
- const backend = credentialBackend(io.env, io.keychain);
2508
- const which = backend.kind === 'external' ? 'external-command' : 'keychain';
2509
- throw new CliError(`cannot determine which hub to ${purpose} — the ${which} credential store cannot be enumerated; ` +
4108
+ const discovered = discoverStoredHubs(io);
4109
+ if (discovered.kind === 'non-enumerable') {
4110
+ throw new CliError(`cannot determine which hub to ${purpose} — the ${discovered.backend} credential store cannot be enumerated; ` +
2510
4111
  'pass --hub <origin>', { exitCode: 2 });
2511
4112
  }
2512
- if (origins.length === 1)
2513
- return origins[0];
4113
+ if (discovered.kind === 'one')
4114
+ return discovered.origin;
2514
4115
  throw new CliError(`cannot determine which hub to ${purpose} — pass --hub <origin>, or log in to exactly one hub first ` +
2515
4116
  '(owenloop login --hub <origin>)' +
2516
- (origins.length > 1 ? `; stored hubs: ${origins.join(', ')}` : ''), { exitCode: 2 });
4117
+ (discovered.kind === 'multiple' ? `; stored hubs: ${discovered.origins.join(', ')}` : ''), { exitCode: 2 });
2517
4118
  }
2518
4119
  /**
2519
4120
  * `owenloop agent new <name>` — mint a new Scoped Identity on the hub and store
@@ -3157,10 +4758,10 @@ async function dispatchCrew(io, args) {
3157
4758
  }
3158
4759
  }
3159
4760
  /**
3160
- * The plugin check is rendered but NON-FATAL while the marketplace is not yet
3161
- * fetchably published (the brief's open question): `doctor` shows ✓/✗ but the
3162
- * plugin never flips the exit code, and `setup` PRINTS install instructions
3163
- * instead of failing. Flip to `true` once the shell-out install lands.
4761
+ * The plugin checks are rendered but NON-FATAL: a developer may use either
4762
+ * Claude Code or Codex, and a missing harness or failed plugin convergence must
4763
+ * not make the core setup/doctor result fail. The setup ACT reports each issue as
4764
+ * `noted` and continues with the other harness.
3164
4765
  */
3165
4766
  const PLUGIN_CHECK_FATAL = false;
3166
4767
  /**
@@ -3190,11 +4791,11 @@ function resolveSetupHub(io, args) {
3190
4791
  throw new CliError(e.message);
3191
4792
  }
3192
4793
  }
3193
- const origins = listStoredHubOrigins(io.env, io.keychain);
3194
- if (origins !== null && origins.length === 1)
3195
- return origins[0];
3196
- if (origins !== null && origins.length > 1) {
3197
- throw new CliError(`more than one hub is configured on this machine — pass --hub <origin> to pick one; stored hubs: ${origins.join(', ')}`, { exitCode: 2 });
4794
+ const discovered = discoverStoredHubs(io);
4795
+ if (discovered.kind === 'one')
4796
+ return discovered.origin;
4797
+ if (discovered.kind === 'multiple') {
4798
+ throw new CliError(`more than one hub is configured on this machine — pass --hub <origin> to pick one; stored hubs: ${discovered.origins.join(', ')}`, { exitCode: 2 });
3198
4799
  }
3199
4800
  io.err(`targeting ${DEFAULT_HUB} (pass --hub to override)`);
3200
4801
  return DEFAULT_HUB;
@@ -3414,41 +5015,384 @@ async function promptSuccession(io, identities) {
3414
5015
  }
3415
5016
  throw new CliError('no valid choice provided');
3416
5017
  }
3417
- /** Probe the Claude Code plugin state: is `claude` on PATH, and does `plugin list` mention owenloop? */
5018
+ const HARNESS_CONFIGS = {
5019
+ 'claude-code': {
5020
+ id: 'claude-code',
5021
+ cliName: 'claude',
5022
+ displayName: 'Claude Code',
5023
+ marketplaceDir: 'claude-code',
5024
+ marketplaceManifest: '.claude-plugin/marketplace.json',
5025
+ },
5026
+ codex: {
5027
+ id: 'codex',
5028
+ cliName: 'codex',
5029
+ displayName: 'Codex',
5030
+ marketplaceDir: 'codex',
5031
+ marketplaceManifest: '.agents/plugins/marketplace.json',
5032
+ },
5033
+ };
5034
+ const HARNESS_IDS = ['claude-code', 'codex'];
5035
+ const PLUGIN_SELECTOR = 'owenloop@owenloop';
5036
+ /**
5037
+ * Resolve a bundled marketplace root from either the source tree (`src/cli.ts`)
5038
+ * or the shipped tree (`dist/src/cli.js`). The manifest check prevents a partial
5039
+ * package from producing a path that the harness cannot consume.
5040
+ */
5041
+ export function resolveBundledMarketplaceRoot(harness) {
5042
+ const config = HARNESS_CONFIGS[harness];
5043
+ try {
5044
+ const candidates = [
5045
+ new URL(`../plugins/${config.marketplaceDir}/`, import.meta.url),
5046
+ new URL(`../../plugins/${config.marketplaceDir}/`, import.meta.url),
5047
+ ];
5048
+ for (const candidate of candidates) {
5049
+ const root = fileURLToPath(candidate);
5050
+ if (existsSync(join(root, config.marketplaceManifest)))
5051
+ return root;
5052
+ }
5053
+ }
5054
+ catch {
5055
+ // A missing or malformed bundle must degrade to manual instructions.
5056
+ }
5057
+ return null;
5058
+ }
5059
+ function recordOf(value) {
5060
+ return value !== null && typeof value === 'object' ? value : null;
5061
+ }
5062
+ function normalizedPluginVersion(value) {
5063
+ if (typeof value !== 'string')
5064
+ return null;
5065
+ const version = value.trim();
5066
+ return version === '' ? null : version;
5067
+ }
5068
+ function firstOutputLine(value) {
5069
+ const line = value.split(/\r?\n/, 1)[0]?.trim() ?? '';
5070
+ return line === '' ? null : line;
5071
+ }
5072
+ function parsePluginList(stdout, harness) {
5073
+ let parsed;
5074
+ try {
5075
+ parsed = JSON.parse(stdout);
5076
+ }
5077
+ catch {
5078
+ return { known: false, installed: false, installedVersion: null };
5079
+ }
5080
+ if (harness === 'claude-code') {
5081
+ if (!Array.isArray(parsed))
5082
+ return { known: false, installed: false, installedVersion: null };
5083
+ const entry = parsed.find((item) => {
5084
+ const row = recordOf(item);
5085
+ if (row === null)
5086
+ return false;
5087
+ const id = typeof row.id === 'string' ? row.id : '';
5088
+ return id === PLUGIN_SELECTOR || id.split('@', 1)[0] === 'owenloop';
5089
+ });
5090
+ return entry === undefined
5091
+ ? { known: true, installed: false, installedVersion: null }
5092
+ : { known: true, installed: true, installedVersion: normalizedPluginVersion(entry.version) };
5093
+ }
5094
+ const root = recordOf(parsed);
5095
+ if (root === null || !Array.isArray(root.installed))
5096
+ return { known: false, installed: false, installedVersion: null };
5097
+ const entry = root.installed.find((item) => {
5098
+ const row = recordOf(item);
5099
+ if (row === null || row.installed !== true)
5100
+ return false;
5101
+ return (row.pluginId === PLUGIN_SELECTOR ||
5102
+ (row.name === 'owenloop' && row.marketplaceName === 'owenloop'));
5103
+ });
5104
+ return entry === undefined
5105
+ ? { known: true, installed: false, installedVersion: null }
5106
+ : { known: true, installed: true, installedVersion: normalizedPluginVersion(entry.version) };
5107
+ }
5108
+ function probeCliVersion(run, cliName) {
5109
+ try {
5110
+ const result = run(cliName, ['--version']);
5111
+ return result.status === 0 ? firstOutputLine(result.stdout) : null;
5112
+ }
5113
+ catch {
5114
+ return null;
5115
+ }
5116
+ }
5117
+ /** Probe both harnesses using their structured installed-plugin JSON channels. */
3418
5118
  function probePlugin(io) {
3419
- if (!commandOnPath(io.env, 'claude'))
3420
- return { claudeFound: false, installed: false };
3421
5119
  const run = io.runCommand ?? defaultRunCommand;
5120
+ return HARNESS_IDS.map((id) => {
5121
+ const config = HARNESS_CONFIGS[id];
5122
+ const cliFound = commandOnPath(io.env, config.cliName);
5123
+ if (!cliFound) {
5124
+ return { id, cliName: config.cliName, cliFound: false, installed: false, installedVersion: null, cliVersion: null };
5125
+ }
5126
+ let installed = false;
5127
+ let installedVersion = null;
5128
+ try {
5129
+ const result = run(config.cliName, ['plugin', 'list', '--json']);
5130
+ if (result.status === 0) {
5131
+ const parsed = parsePluginList(result.stdout, id);
5132
+ // A successful command with malformed output cannot establish presence.
5133
+ // Treat it as not installed, matching the non-zero-exit path below.
5134
+ installed = parsed.known ? parsed.installed : false;
5135
+ installedVersion = parsed.installedVersion;
5136
+ }
5137
+ }
5138
+ catch {
5139
+ // A failed probe cannot establish presence; the ACT remains PATH-gated.
5140
+ installed = false;
5141
+ installedVersion = null;
5142
+ }
5143
+ return {
5144
+ id,
5145
+ cliName: config.cliName,
5146
+ cliFound,
5147
+ installed,
5148
+ installedVersion,
5149
+ cliVersion: probeCliVersion(run, config.cliName),
5150
+ };
5151
+ });
5152
+ }
5153
+ function canonicalPath(path) {
5154
+ try {
5155
+ return realpathSync(path);
5156
+ }
5157
+ catch {
5158
+ return resolve(path);
5159
+ }
5160
+ }
5161
+ function resolvedMarketplaceRoot(io, harness) {
5162
+ const resolver = io.resolveBundledMarketplaceRoot ?? resolveBundledMarketplaceRoot;
5163
+ try {
5164
+ return resolver(harness);
5165
+ }
5166
+ catch {
5167
+ return null;
5168
+ }
5169
+ }
5170
+ function pluginRemedy(harness, root) {
5171
+ const config = HARNESS_CONFIGS[harness];
5172
+ const source = root ?? '<bundled marketplace root>';
5173
+ return harness === 'claude-code'
5174
+ ? `${config.cliName} plugin marketplace add ${source} && ${config.cliName} plugin install ${PLUGIN_SELECTOR}`
5175
+ : `${config.cliName} plugin marketplace add ${source} && ${config.cliName} plugin add ${PLUGIN_SELECTOR}`;
5176
+ }
5177
+ function printManualPluginInstructions(io, harness) {
5178
+ const config = HARNESS_CONFIGS[harness];
5179
+ io.err(`${config.displayName} plugin — install manually:`);
5180
+ io.err(` ${config.cliName} plugin marketplace add <bundled marketplace root>`);
5181
+ io.err(` ${config.cliName} plugin ${harness === 'claude-code' ? 'install' : 'add'} ${PLUGIN_SELECTOR}`);
5182
+ }
5183
+ function reportPluginCommandFailure(io, cmd, args, result, error = undefined) {
5184
+ io.err(`plugin command failed: ${cmd} ${args.join(' ')}`);
5185
+ const childOutput = result === null ? '' : [result.stderr.trim(), result.stdout.trim()].filter(Boolean).join('\n');
5186
+ if (childOutput !== '')
5187
+ io.err(childOutput);
5188
+ if (error !== undefined) {
5189
+ const message = error instanceof Error ? error.message : String(error);
5190
+ if (message !== '')
5191
+ io.err(message);
5192
+ }
5193
+ }
5194
+ function runPluginCommand(io, cmd, args) {
5195
+ const run = io.runCommand ?? defaultRunCommand;
5196
+ try {
5197
+ const result = run(cmd, args);
5198
+ if (result.status === 0)
5199
+ return true;
5200
+ reportPluginCommandFailure(io, cmd, args, result);
5201
+ }
5202
+ catch (error) {
5203
+ reportPluginCommandFailure(io, cmd, args, null, error);
5204
+ }
5205
+ return false;
5206
+ }
5207
+ function codexMarketplaceGate(io, root) {
5208
+ const run = io.runCommand ?? defaultRunCommand;
5209
+ let result;
5210
+ try {
5211
+ result = run('codex', ['plugin', 'marketplace', 'list', '--json']);
5212
+ }
5213
+ catch {
5214
+ return 'absent';
5215
+ }
5216
+ if (result.status !== 0)
5217
+ return 'absent';
5218
+ try {
5219
+ const parsed = recordOf(JSON.parse(result.stdout));
5220
+ if (parsed === null || !Array.isArray(parsed.marketplaces))
5221
+ return 'absent';
5222
+ const entry = parsed.marketplaces.find((item) => recordOf(item)?.name === 'owenloop');
5223
+ if (entry === undefined)
5224
+ return 'absent';
5225
+ const row = recordOf(entry);
5226
+ const source = recordOf(row?.marketplaceSource)?.source;
5227
+ if (typeof source !== 'string' || source.trim() === '')
5228
+ return 'unknown';
5229
+ return canonicalPath(source) === canonicalPath(root) ? 'same' : 'different';
5230
+ }
5231
+ catch {
5232
+ return 'absent';
5233
+ }
5234
+ }
5235
+ /** Converge one harness without making plugin failures fatal to setup. */
5236
+ function installPluginStep(io, state) {
5237
+ const config = HARNESS_CONFIGS[state.id];
5238
+ if (!state.cliFound)
5239
+ return { action: 'noted', detail: `${config.cliName} not on PATH` };
5240
+ if (state.installed && state.installedVersion === null) {
5241
+ return { action: 'skipped', detail: 'installed (version unknown)' };
5242
+ }
5243
+ const expectedVersion = packageVersion().trim();
5244
+ const currentVersion = state.installedVersion?.trim() ?? null;
5245
+ if (state.installed && currentVersion === expectedVersion) {
5246
+ return { action: 'skipped', detail: `owenloop ${currentVersion} already current` };
5247
+ }
5248
+ const root = resolvedMarketplaceRoot(io, state.id);
5249
+ if (root === null) {
5250
+ printManualPluginInstructions(io, state.id);
5251
+ return { action: 'noted', detail: 'bundled marketplace root unavailable — printed manual instructions' };
5252
+ }
5253
+ const upgrading = state.installed && currentVersion !== null;
5254
+ if (state.id === 'claude-code') {
5255
+ if (!runPluginCommand(io, 'claude', ['plugin', 'marketplace', 'add', root])) {
5256
+ return { action: 'noted', detail: 'marketplace add failed' };
5257
+ }
5258
+ const verb = upgrading ? 'update' : 'install';
5259
+ if (!runPluginCommand(io, 'claude', ['plugin', verb, PLUGIN_SELECTOR])) {
5260
+ return { action: 'noted', detail: `${verb} failed` };
5261
+ }
5262
+ return { action: 'done', detail: upgrading ? `updated to ${expectedVersion}` : `installed ${expectedVersion}` };
5263
+ }
5264
+ const marketplace = codexMarketplaceGate(io, root);
5265
+ if (marketplace === 'different') {
5266
+ return {
5267
+ action: 'noted',
5268
+ detail: "marketplace 'owenloop' is already added from a different source; remove it before adding this source",
5269
+ };
5270
+ }
5271
+ if (marketplace === 'unknown') {
5272
+ return { action: 'noted', detail: 'could not determine the existing Codex marketplace source' };
5273
+ }
5274
+ if (marketplace === 'absent' && !runPluginCommand(io, 'codex', ['plugin', 'marketplace', 'add', root])) {
5275
+ return { action: 'noted', detail: 'marketplace add failed' };
5276
+ }
5277
+ if (!runPluginCommand(io, 'codex', ['plugin', 'add', PLUGIN_SELECTOR])) {
5278
+ return { action: 'noted', detail: 'plugin add failed' };
5279
+ }
5280
+ return { action: 'done', detail: upgrading ? `updated to ${expectedVersion}` : `installed ${expectedVersion}` };
5281
+ }
5282
+ function enrollmentEnvelopeNewKeyId(value) {
5283
+ const envelope = recordOf(value);
5284
+ if (envelope === null || typeof envelope.payload !== 'string')
5285
+ return undefined;
3422
5286
  try {
3423
- return { claudeFound: true, installed: run('claude', ['plugin', 'list']).stdout.includes('owenloop') };
5287
+ const payload = JSON.parse(decodeBase64Strict(envelope.payload, { allowEmpty: true }).toString('utf8'));
5288
+ const record = recordOf(payload);
5289
+ const newKey = recordOf(record?.newKey);
5290
+ return typeof newKey?.keyid === 'string' ? newKey.keyid : undefined;
3424
5291
  }
3425
5292
  catch {
3426
- return { claudeFound: true, installed: false };
5293
+ return undefined;
3427
5294
  }
3428
5295
  }
5296
+ function enrollmentEnvelopesFromResponse(body) {
5297
+ if (Array.isArray(body))
5298
+ return body.map((row) => recordOf(row)?.envelope ?? row);
5299
+ const record = recordOf(body);
5300
+ if (record === null)
5301
+ throw new CliError('enrollments: malformed response — expected an array of entries');
5302
+ for (const key of ['enrollments', 'entries', 'envelopes', 'items']) {
5303
+ const rows = record[key];
5304
+ if (Array.isArray(rows))
5305
+ return rows.map((row) => recordOf(row)?.envelope ?? row);
5306
+ }
5307
+ if (record.envelope !== undefined)
5308
+ return [record.envelope];
5309
+ throw new CliError('enrollments: malformed response — expected an array of entries');
5310
+ }
3429
5311
  /**
3430
- * The plugin ACT step. While the marketplace is unpublished this PRINTS the
3431
- * manual install instructions instead of shelling out — the single seam a real
3432
- * shell-out install would replace later. Never fails setup.
5312
+ * Register the already-created machine key as a signed enrollment grant. This
5313
+ * helper owns only the D1 relay action: the hub stores the DSSE envelope, while
5314
+ * the human signing key signs locally and the machine private key never enters
5315
+ * the request body.
3433
5316
  */
3434
- function installPluginStep(io, state) {
3435
- if (!state.claudeFound)
3436
- io.err('Claude Code (claude) not detected on PATH.');
3437
- io.err('Claude Code plugin — install manually:');
3438
- io.err(' claude plugin marketplace add owenloop');
3439
- io.err(' claude plugin install owenloop@owenloop');
5317
+ async function registerMachineEnrollment(io, origin, humanCred, keys, humanRef, machinePublicKey) {
5318
+ const noted = (detail) => ({ step: 'enrollment', action: 'noted', detail });
5319
+ const skipped = (detail) => ({ step: 'enrollment', action: 'skipped', detail });
5320
+ const done = (detail) => ({ step: 'enrollment', action: 'done', detail });
5321
+ let human;
5322
+ try {
5323
+ human = await keys.inspect(humanRef);
5324
+ }
5325
+ catch {
5326
+ return skipped('human signing key could not be inspected');
5327
+ }
5328
+ if (!human.exists || human.publicKey === undefined) {
5329
+ return skipped('no human signing key is stored');
5330
+ }
5331
+ let list;
5332
+ try {
5333
+ list = await authedGet(io, origin, { principal: 'human' }, humanCred, '/api/enrollments');
5334
+ }
5335
+ catch {
5336
+ return noted('hub enrollment listing unavailable');
5337
+ }
5338
+ if (!list.res.ok)
5339
+ return noted(`hub enrollment listing rejected (HTTP ${list.res.status})`);
5340
+ let existing;
5341
+ try {
5342
+ existing = enrollmentEnvelopesFromResponse(await list.res.json());
5343
+ }
5344
+ catch (error) {
5345
+ return noted(error instanceof CliError ? error.message : 'hub enrollment listing was not valid JSON');
5346
+ }
5347
+ if (existing.some((entry) => enrollmentEnvelopeNewKeyId(entry) === machinePublicKey.keyid)) {
5348
+ return skipped('machine key already registered');
5349
+ }
5350
+ const grant = buildEnrollmentGrant({
5351
+ newKey: machinePublicKey,
5352
+ principal: { kind: 'machine', id: 'local' },
5353
+ scope: DEFAULT_MACHINE_SCOPE,
5354
+ grantedBy: human.publicKey.keyid,
5355
+ validFrom: nowMs(),
5356
+ });
5357
+ let envelope;
5358
+ try {
5359
+ envelope = await keys.withSigningKey(humanRef, async (signKeyPath) => {
5360
+ const signer = createSshSigner({ namespace: DSSE_SSH_NAMESPACE, signKeyPath });
5361
+ const signed = await dsseSignEnrollmentGrant(Buffer.from(canonicalJsonBytes(grant)), signer);
5362
+ return signed.envelope;
5363
+ });
5364
+ }
5365
+ catch (error) {
5366
+ if (error instanceof SshSignerError)
5367
+ return noted(`enrollment signing unavailable: ${error.message}`);
5368
+ return noted('could not sign enrollment grant');
5369
+ }
5370
+ let posted;
5371
+ try {
5372
+ posted = await authedPost(io, origin, { principal: 'human' }, list.cred, '/api/enrollments', { envelope });
5373
+ }
5374
+ catch {
5375
+ return noted('hub enrollment registration unavailable');
5376
+ }
5377
+ if (posted.res.status === 409)
5378
+ return skipped('machine key already registered');
5379
+ if (!posted.res.ok)
5380
+ return noted(`hub enrollment registration rejected (HTTP ${posted.res.status})`);
5381
+ return done('machine key registered');
3440
5382
  }
3441
5383
  /**
3442
- * `owenloop setup` — converge this machine's install in six probe→(skip|act)
5384
+ * `owenloop setup` — converge this machine's install in seven probe→(skip|act)
3443
5385
  * steps, idempotently: a second run performs ZERO writes (no store mutation, no
3444
- * settings write, no browser, no mint/rekey/register POST). Each ACT is reached
3445
- * only through its probe failing.
5386
+ * key generation, no settings write, no browser, no mint/rekey/register POST).
5387
+ * Each ACT is reached only through its probe failing.
3446
5388
  *
3447
5389
  * Flags: `--hub <url>`; mutually-exclusive `--new-agent <name>` / `--replace-agent
3448
5390
  * <name>` (bypass the interactive agent branches); `--crews <a,b>` (mint only —
3449
5391
  * a usage error with `--replace-agent`, which preserves crews); `--scopes <a,b>`
3450
5392
  * (mint only — the minted token's scopes, default `work`; a usage error with
3451
- * `--replace-agent`, which preserves scopes).
5393
+ * `--replace-agent`, which preserves scopes); `--reuse-ssh-key <path>` (human
5394
+ * signing key only — validate an existing Ed25519 SSH key and record it instead
5395
+ * of generating the human key; a conflict with an existing key is a hard error).
3452
5396
  *
3453
5397
  * Exit: 0 when every step ended skipped/done/noted AND doctor's core (non-plugin)
3454
5398
  * checks pass; 1 otherwise. Any hard failure throws (mapped to an exit code by
@@ -3512,10 +5456,20 @@ async function dispatchSetup(io, args) {
3512
5456
  throw new CliError('an external credential command is configured (OWENLOOP_CREDENTIAL_COMMAND), so it — not the ' +
3513
5457
  'local store — supplies credentials for this hub; unset it to use `owenloop login`');
3514
5458
  }
5459
+ // --reuse-ssh-key: explicit SSH-key reuse for the HUMAN key only. The key
5460
+ // itself is validated (and challenged) inside the signing-keys step; here
5461
+ // only the path shape is checked, so a typo fails BEFORE any browser opens.
5462
+ const reuseSshKey = last(args, 'reuse-ssh-key');
5463
+ if (reuseSshKey !== undefined && reuseSshKey.trim() === '') {
5464
+ throw new CliError('--reuse-ssh-key requires a key file path');
5465
+ }
5466
+ if (reuseSshKey !== undefined && !existsSync(reuseSshKey)) {
5467
+ throw new CliError('--reuse-ssh-key: no such file');
5468
+ }
3515
5469
  const origin = resolveSetupHub(io, args);
3516
5470
  const steps = [];
3517
- // --- [1/6] inspect: zero writes, best-effort probes ---
3518
- io.err('[1/6] inspect');
5471
+ // --- [1/7] inspect: zero writes, best-effort probes ---
5472
+ io.err('[1/7] inspect');
3519
5473
  io.err(` human credential: ${readCredential(io, origin, { principal: 'human' }) !== null ? 'present' : 'none — will log in'}`);
3520
5474
  const inspectSettingsPath = owenloopSettingsPath(io.env);
3521
5475
  let settingsNote;
@@ -3529,18 +5483,19 @@ async function dispatchSetup(io, args) {
3529
5483
  settingsNote = found === origin ? `hubOrigin already ${origin}` : `hubOrigin ${found ?? '(unset)'} — will update`;
3530
5484
  }
3531
5485
  catch {
3532
- settingsNote = 'present but unreadable — step 4 will error if still corrupt';
5486
+ settingsNote = 'present but unreadable — the settings step will error if still corrupt';
3533
5487
  }
3534
5488
  }
3535
5489
  io.err(` owenloop settings: ${settingsNote}`);
3536
5490
  io.err(` claude on PATH: ${commandOnPath(io.env, 'claude') ? 'yes' : 'no'}`);
5491
+ io.err(` codex on PATH: ${commandOnPath(io.env, 'codex') ? 'yes' : 'no'}`);
3537
5492
  const inspectAccts = enumerateAgentAccounts(io, origin);
3538
5493
  io.err(inspectAccts === null
3539
5494
  ? ' agent slots: checked in step 3'
3540
5495
  : ` agent slots: ${inspectAccts.length ? inspectAccts.map((a) => `agent:${a}`).join(', ') : 'none'}`);
3541
5496
  steps.push({ step: 'inspect', action: 'done', detail: 'probed local state' });
3542
- // --- [2/6] human login: the hard gate that makes step 3's rekey legal ---
3543
- io.err('[2/6] human login');
5497
+ // --- [2/7] human login: the hard gate that makes step 3's rekey legal ---
5498
+ io.err('[2/7] human login');
3544
5499
  let humanCred = readCredential(io, origin, { principal: 'human' });
3545
5500
  let humanIdentity;
3546
5501
  if (humanCred !== null) {
@@ -3568,8 +5523,8 @@ async function dispatchSetup(io, args) {
3568
5523
  io.err(`✓ human: signed in as ${humanIdentity.email ?? humanIdentity.actor.id} @ ${humanIdentity.orgName}`);
3569
5524
  steps.push({ step: 'human login', action: 'done', detail: `signed in as ${humanIdentity.email ?? humanIdentity.actor.id}` });
3570
5525
  }
3571
- // --- [3/6] agent ---
3572
- io.err('[3/6] agent');
5526
+ // --- [3/7] agent ---
5527
+ io.err('[3/7] agent');
3573
5528
  const { res: idRes } = await authedGet(io, origin, { principal: 'human' }, humanCred, '/api/agent_identities');
3574
5529
  if (idRes.status === 403) {
3575
5530
  throw new CliError('setup needs an admin credential to manage Scoped Identities (hub returned 403)');
@@ -3580,8 +5535,12 @@ async function dispatchSetup(io, args) {
3580
5535
  candidateNames.add('default');
3581
5536
  const probe = await probeAgentSlots(io, origin, [...candidateNames], identities);
3582
5537
  let agentAccount;
5538
+ // The stable principal id for the agent signing key: the hub's agent actor
5539
+ // id (`agentId`), which rekey preserves and mint mints fresh.
5540
+ let agentPrincipalId;
3583
5541
  if (probe.verified !== null) {
3584
5542
  agentAccount = probe.verified.name;
5543
+ agentPrincipalId = probe.verified.actorId;
3585
5544
  const crewsStr = probe.verified.identity ? ` (crews: ${probe.verified.identity.crews.join(', ') || 'none'})` : '';
3586
5545
  io.err(`✓ agent: ${agentAccount}${crewsStr}`);
3587
5546
  steps.push({ step: 'agent', action: 'skipped', detail: `agent:${agentAccount} verified` });
@@ -3614,18 +5573,46 @@ async function dispatchSetup(io, args) {
3614
5573
  if (action.mode === 'mint') {
3615
5574
  const result = await mintAgentCredential(io, origin, { principal: 'human' }, humanCred, { name: action.name, crews, scopes });
3616
5575
  agentAccount = action.name;
5576
+ agentPrincipalId = result.agentId;
3617
5577
  io.err(`✓ agent: minted agent:${agentAccount} (crews: ${result.crews.join(', ') || 'none'}; scopes: ${result.scopes.join(', ')})`);
3618
5578
  steps.push({ step: 'agent', action: 'done', detail: `minted agent:${agentAccount}` });
3619
5579
  }
3620
5580
  else {
3621
5581
  const result = await rekeyAgentCredential(io, origin, { principal: 'human' }, humanCred, { agentId: action.agentId, name: action.name });
3622
5582
  agentAccount = action.name;
5583
+ agentPrincipalId = result.agentId;
3623
5584
  io.err(`✓ agent: re-keyed agent:${agentAccount} (revoked ${result.revokedTokenIds.length} old token(s))`);
3624
5585
  steps.push({ step: 'agent', action: 'done', detail: `re-keyed agent:${agentAccount}` });
3625
5586
  }
3626
5587
  }
3627
- // --- [4/6] owenloop settings ---
3628
- io.err('[4/6] owenloop settings');
5588
+ // --- [4/7] signing keys: human → machine → agent, idempotently ---
5589
+ // Prints kind + state + backend ONLY. Never key bytes, fingerprints,
5590
+ // secret-store values, or reused private-key paths.
5591
+ io.err('[4/7] signing keys');
5592
+ const keys = io.principalKeys ?? new PrincipalKeyManager({ env: io.env });
5593
+ const humanRef = { origin, kind: 'human', id: humanIdentity.actor.id };
5594
+ const machineRef = { origin, kind: 'machine', id: 'local' };
5595
+ const agentRef = { origin, kind: 'agent', id: agentPrincipalId };
5596
+ const ensured = [];
5597
+ let machine;
5598
+ {
5599
+ const human = await keys.ensure(humanRef, reuseSshKey !== undefined ? { reuse: { path: reuseSshKey } } : undefined);
5600
+ ensured.push(`human ${human.state} (${human.backend})`);
5601
+ machine = await keys.ensure(machineRef);
5602
+ ensured.push(`machine ${machine.state} (${machine.backend})`);
5603
+ const agent = await keys.ensure(agentRef);
5604
+ ensured.push(`agent ${agent.state} (${agent.backend})`);
5605
+ }
5606
+ io.err(`✓ signing keys: ${ensured.join(', ')}`);
5607
+ steps.push({ step: 'signing keys', action: 'done', detail: ensured.join(', ') });
5608
+ // Registration is deliberately subordinate to key convergence: a missing
5609
+ // SSHSIG tool, absent human key, or unavailable hub is a noted convergence
5610
+ // result, never a reason to undo the three silent key ensures above.
5611
+ const enrollment = await registerMachineEnrollment(io, origin, humanCred, keys, humanRef, machine.publicKey);
5612
+ io.err(`${enrollment.action === 'noted' ? '!' : '✓'} enrollment: ${enrollment.detail}`);
5613
+ steps.push(enrollment);
5614
+ // --- [5/7] owenloop settings ---
5615
+ io.err('[5/7] owenloop settings');
3629
5616
  const settingsPath = owenloopSettingsPath(io.env);
3630
5617
  const existingSettings = readOwenloopSettingsRaw(settingsPath); // corrupt file → hard CliError (never clobber)
3631
5618
  const currentHub = existingSettings && typeof existingSettings.hubOrigin === 'string' ? existingSettings.hubOrigin : undefined;
@@ -3641,30 +5628,67 @@ async function dispatchSetup(io, args) {
3641
5628
  if (agentAccount !== 'default') {
3642
5629
  io.err(`non-default agent account — run owenloop work with OWENLOOP_ACCOUNT=${agentAccount}`);
3643
5630
  }
3644
- // --- [5/6] plugin (non-fatal) ---
3645
- io.err('[5/6] plugin');
3646
- const pluginState = probePlugin(io);
3647
- if (pluginState.installed) {
3648
- io.err('✓ plugin: owenloop installed');
3649
- steps.push({ step: 'plugin', action: 'skipped', detail: 'installed' });
3650
- }
3651
- else {
3652
- installPluginStep(io, pluginState);
3653
- steps.push({
3654
- step: 'plugin',
3655
- action: 'noted',
3656
- detail: pluginState.claudeFound ? 'not installed — printed manual instructions' : 'claude not on PATH — printed manual instructions',
3657
- });
5631
+ // --- [6/7] plugin (non-fatal) ---
5632
+ io.err('[6/7] plugin');
5633
+ for (const pluginState of probePlugin(io)) {
5634
+ const outcome = installPluginStep(io, pluginState);
5635
+ const marker = outcome.action === 'noted' ? '!' : '✓';
5636
+ io.err(`${marker} plugin (${pluginState.id}): ${outcome.detail}`);
5637
+ steps.push({ step: `plugin (${pluginState.id})`, ...outcome });
3658
5638
  }
3659
- // --- [6/6] doctor pass ---
3660
- io.err('[6/6] doctor');
5639
+ // --- [7/7] doctor pass ---
5640
+ io.err('[7/7] doctor');
3661
5641
  const doctor = await runDoctor(io, origin);
3662
5642
  print(io, { ok: doctor.ok, hub: origin, steps, doctor: { ok: doctor.ok, checks: doctor.checks } });
3663
5643
  return doctor.ok ? 0 : 1;
3664
5644
  }
5645
+ /**
5646
+ * `owenloop enrollments` — read the hub's relayed DSSE envelopes and classify
5647
+ * each roster entry locally. This command never creates keys and never writes a
5648
+ * roster entry. D1 intentionally installs no chain validator, so a valid signed
5649
+ * grant is visible as `unverifiable` until WP-D4 supplies that validator.
5650
+ */
5651
+ async function dispatchEnrollments(io, args) {
5652
+ const origin = resolveSetupHub(io, args);
5653
+ const slot = { principal: 'human' };
5654
+ const cred = readCredential(io, origin, slot);
5655
+ if (cred === null) {
5656
+ throw new CliError(`no human credential for ${origin} — run: owenloop login --hub ${origin}`, { exitCode: 3 });
5657
+ }
5658
+ const { res, cred: used } = await authedGet(io, origin, slot, cred, '/api/enrollments');
5659
+ assertAuthOk(res, used, origin);
5660
+ let body;
5661
+ try {
5662
+ body = await res.json();
5663
+ }
5664
+ catch {
5665
+ throw new CliError('enrollments: malformed response — body is not valid JSON');
5666
+ }
5667
+ let envelopes;
5668
+ try {
5669
+ envelopes = enrollmentEnvelopesFromResponse(body);
5670
+ }
5671
+ catch (error) {
5672
+ throw new CliError(error instanceof Error ? error.message : 'enrollments: malformed response');
5673
+ }
5674
+ let allowedSignersText;
5675
+ try {
5676
+ const roots = resolveAllowedSigners(io.env);
5677
+ allowedSignersText = roots.kind === 'present' ? roots.text : undefined;
5678
+ }
5679
+ catch {
5680
+ allowedSignersText = undefined;
5681
+ }
5682
+ const verdicts = [];
5683
+ for (const envelope of envelopes) {
5684
+ verdicts.push(await verifyRosterEntry({ envelope, allowedSignersText }));
5685
+ }
5686
+ print(io, { ok: true, hub: origin, enrollments: verdicts });
5687
+ return 0;
5688
+ }
3665
5689
  /**
3666
5690
  * `owenloop doctor` — the read-only probe of the five install surfaces plus the
3667
- * plugin, rendering one distinct ✓/✗ line each. NO configuration writes (no
5691
+ * two harness plugin checks, rendering one distinct ✓/✗ line each. NO configuration writes (no
3668
5692
  * mint, rekey, slot create/delete, settings write, or browser). The one
3669
5693
  * carve-out: `authedGet`'s persist=true MAY rotate-and-persist an expiring human
3670
5694
  * oauth token — as every authed verb does — because a refresh WITHOUT persisting
@@ -3678,11 +5702,11 @@ async function dispatchDoctor(io, args) {
3678
5702
  return doctor.ok ? 0 : 1;
3679
5703
  }
3680
5704
  /**
3681
- * Run the six doctor checks in order, printing each ✓/✗ line to stderr and
5705
+ * Run the doctor checks in order, printing each ✓/✗ line to stderr and
3682
5706
  * returning the structured result. Never short-circuits — a machine with no
3683
- * working human credential still renders lines 3–6 (the agent probe degrades
3684
- * honestly). `ok` reflects checks 1–5 only; the plugin check (6) renders but,
3685
- * while `PLUGIN_CHECK_FATAL` is false, never affects `ok`.
5707
+ * working human credential still renders the later checks (the agent probe
5708
+ * degrades honestly). `ok` reflects the five core checks only; both plugin checks
5709
+ * render but, while `PLUGIN_CHECK_FATAL` is false, never affect `ok`.
3686
5710
  */
3687
5711
  async function runDoctor(io, origin) {
3688
5712
  const checks = [];
@@ -3807,16 +5831,26 @@ async function runDoctor(io, origin) {
3807
5831
  record('owenloop settings', true, settingsPath, true);
3808
5832
  }
3809
5833
  }
3810
- // 6. plugin (rendered; non-core while PLUGIN_CHECK_FATAL is false)
3811
- const pluginState = probePlugin(io);
3812
- if (!pluginState.claudeFound) {
3813
- record('plugin', false, 'Claude Code (claude) not on PATH', PLUGIN_CHECK_FATAL);
3814
- }
3815
- else if (!pluginState.installed) {
3816
- record('plugin', false, 'plugin not installed — claude plugin marketplace add owenloop && claude plugin install owenloop@owenloop', PLUGIN_CHECK_FATAL);
3817
- }
3818
- else {
3819
- record('plugin', true, 'owenloop installed', PLUGIN_CHECK_FATAL);
5834
+ // 6–7. plugins (rendered; non-core while PLUGIN_CHECK_FATAL is false)
5835
+ for (const pluginState of probePlugin(io)) {
5836
+ const config = HARNESS_CONFIGS[pluginState.id];
5837
+ if (!pluginState.cliFound) {
5838
+ record(`plugin (${pluginState.id})`, false, `${config.displayName} (${config.cliName}) not on PATH`, PLUGIN_CHECK_FATAL);
5839
+ }
5840
+ else if (!pluginState.installed) {
5841
+ const root = resolvedMarketplaceRoot(io, pluginState.id);
5842
+ const cliVersion = pluginState.cliVersion ?? 'unknown';
5843
+ record(`plugin (${pluginState.id})`, false, `not installed — ${pluginRemedy(pluginState.id, root)} · ${config.cliName} ${cliVersion}`, PLUGIN_CHECK_FATAL);
5844
+ }
5845
+ else if (pluginState.installedVersion === null) {
5846
+ record(`plugin (${pluginState.id})`, true, `owenloop version unknown · ${config.cliName} ${pluginState.cliVersion ?? 'unknown'}`, PLUGIN_CHECK_FATAL);
5847
+ }
5848
+ else if (pluginState.installedVersion === packageVersion().trim()) {
5849
+ record(`plugin (${pluginState.id})`, true, `owenloop ${pluginState.installedVersion} · ${config.cliName} ${pluginState.cliVersion ?? 'unknown'}`, PLUGIN_CHECK_FATAL);
5850
+ }
5851
+ else {
5852
+ record(`plugin (${pluginState.id})`, false, `owenloop ${pluginState.installedVersion} but CLI is ${packageVersion().trim()} — run owenloop setup · ${config.cliName} ${pluginState.cliVersion ?? 'unknown'}`, PLUGIN_CHECK_FATAL);
5853
+ }
3820
5854
  }
3821
5855
  return { ok: coreOk, checks };
3822
5856
  }
@@ -3828,7 +5862,7 @@ async function runDoctor(io, origin) {
3828
5862
  * the async path, so every existing command and test keeps working exactly as
3829
5863
  * before.
3830
5864
  */
3831
- export const ASYNC_COMMANDS = new Set(['add', 'login', 'logout', 'connect', 'push', 'agent', 'capability', 'crew', 'setup', 'doctor', 'mcp', 'shift']);
5865
+ export const ASYNC_COMMANDS = new Set(['add', 'login', 'logout', 'connect', 'publish', 'trust', 'push', 'start', 'agent', 'capability', 'crew', 'setup', 'doctor', 'enrollments', 'mcp', 'shift']);
3832
5866
  export async function mainAsync(argv, io = defaultIO()) {
3833
5867
  // Delegate execution-side and shift argv tails before root parsing. Their
3834
5868
  // roles own their option grammars, including repeated/value forms that the
@@ -3866,8 +5900,14 @@ export async function mainAsync(argv, io = defaultIO()) {
3866
5900
  return await dispatchLogout(io, args);
3867
5901
  case 'connect':
3868
5902
  return await dispatchConnect(io, args);
5903
+ case 'publish':
5904
+ return await dispatchPublish(io, args);
5905
+ case 'trust':
5906
+ return await dispatchTrust(io, args);
3869
5907
  case 'push':
3870
5908
  return await dispatchPush(io, args);
5909
+ case 'start':
5910
+ return await dispatchStart(io, args);
3871
5911
  case 'agent':
3872
5912
  return await dispatchAgent(io, args);
3873
5913
  case 'capability':
@@ -3878,6 +5918,8 @@ export async function mainAsync(argv, io = defaultIO()) {
3878
5918
  return await dispatchSetup(io, args);
3879
5919
  case 'doctor':
3880
5920
  return await dispatchDoctor(io, args);
5921
+ case 'enrollments':
5922
+ return await dispatchEnrollments(io, args);
3881
5923
  case 'mcp':
3882
5924
  return await dispatchMcp(io, args);
3883
5925
  default: