owenloop 0.4.1 → 0.5.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (282) hide show
  1. package/CHANGELOG.md +71 -0
  2. package/README.md +182 -53
  3. package/bin/owenloop.mjs +50 -2
  4. package/dist/packages/work/src/agent/brief.d.ts +176 -0
  5. package/dist/packages/work/src/agent/brief.js +197 -0
  6. package/dist/packages/work/src/agent/loop.d.ts +141 -0
  7. package/dist/packages/work/src/agent/loop.js +669 -0
  8. package/dist/packages/work/src/agent/model-policy.d.ts +49 -0
  9. package/dist/packages/work/src/agent/model-policy.js +138 -0
  10. package/dist/packages/work/src/agent/workdir.d.ts +210 -0
  11. package/dist/packages/work/src/agent/workdir.js +319 -0
  12. package/dist/packages/work/src/bundle/cache.d.ts +92 -0
  13. package/dist/packages/work/src/bundle/cache.js +338 -0
  14. package/dist/packages/work/src/bundle/fetch.d.ts +87 -0
  15. package/dist/packages/work/src/bundle/fetch.js +345 -0
  16. package/dist/packages/work/src/bundle/types.d.ts +164 -0
  17. package/dist/packages/work/src/bundle/types.js +1 -0
  18. package/dist/packages/work/src/consumed-verifier.d.ts +45 -0
  19. package/dist/packages/work/src/consumed-verifier.js +205 -0
  20. package/dist/packages/work/src/credentials/owenloop.d.ts +11 -0
  21. package/dist/packages/work/src/credentials/owenloop.js +28 -0
  22. package/dist/packages/work/src/credentials/reader.d.ts +36 -0
  23. package/dist/packages/work/src/credentials/reader.js +32 -0
  24. package/dist/packages/work/src/credentials/resolve.d.ts +19 -0
  25. package/dist/packages/work/src/credentials/resolve.js +56 -0
  26. package/dist/packages/work/src/exec/instructions.d.ts +99 -0
  27. package/dist/packages/work/src/exec/instructions.js +323 -0
  28. package/dist/packages/work/src/exec/loop.d.ts +40 -0
  29. package/dist/packages/work/src/exec/loop.js +332 -0
  30. package/dist/packages/work/src/exec/payload.d.ts +29 -0
  31. package/dist/packages/work/src/exec/payload.js +54 -0
  32. package/dist/packages/work/src/exec/receipt.d.ts +41 -0
  33. package/dist/packages/work/src/exec/receipt.js +32 -0
  34. package/dist/packages/work/src/exec/runner.d.ts +71 -0
  35. package/dist/packages/work/src/exec/runner.js +256 -0
  36. package/dist/packages/work/src/harness/child-env.d.ts +100 -0
  37. package/dist/packages/work/src/harness/child-env.js +134 -0
  38. package/dist/packages/work/src/harness/claude.d.ts +140 -0
  39. package/dist/packages/work/src/harness/claude.js +837 -0
  40. package/dist/packages/work/src/harness/codex.d.ts +111 -0
  41. package/dist/packages/work/src/harness/codex.js +1024 -0
  42. package/dist/packages/work/src/harness/contract.d.ts +308 -0
  43. package/dist/packages/work/src/harness/contract.js +32 -0
  44. package/dist/packages/work/src/harness/fake.d.ts +59 -0
  45. package/dist/packages/work/src/harness/fake.js +91 -0
  46. package/dist/packages/work/src/harness/jsonrpc-stdio.d.ts +108 -0
  47. package/dist/packages/work/src/harness/jsonrpc-stdio.js +351 -0
  48. package/dist/packages/work/src/harness/permissions.d.ts +75 -0
  49. package/dist/packages/work/src/harness/permissions.js +182 -0
  50. package/dist/packages/work/src/harness/registry.d.ts +47 -0
  51. package/dist/packages/work/src/harness/registry.js +45 -0
  52. package/dist/packages/work/src/harness/session-store.d.ts +181 -0
  53. package/dist/packages/work/src/harness/session-store.js +523 -0
  54. package/dist/packages/work/src/harness/types.d.ts +29 -0
  55. package/dist/packages/work/src/harness/types.js +14 -0
  56. package/dist/packages/work/src/harnesses.d.ts +38 -0
  57. package/dist/packages/work/src/harnesses.js +38 -0
  58. package/dist/packages/work/src/hold/loop.d.ts +36 -0
  59. package/dist/packages/work/src/hold/loop.js +23 -0
  60. package/dist/packages/work/src/hold/mcp.d.ts +75 -0
  61. package/dist/packages/work/src/hold/mcp.js +264 -0
  62. package/dist/packages/work/src/hub/client.d.ts +23 -0
  63. package/dist/packages/work/src/hub/client.js +91 -0
  64. package/dist/packages/work/src/hub/types.d.ts +326 -0
  65. package/dist/packages/work/src/hub/types.js +26 -0
  66. package/dist/packages/work/src/lease/loop.d.ts +94 -0
  67. package/dist/packages/work/src/lease/loop.js +277 -0
  68. package/dist/packages/work/src/main.d.ts +1 -0
  69. package/dist/packages/work/src/main.js +48 -0
  70. package/dist/packages/work/src/mcp/server.d.ts +125 -0
  71. package/dist/packages/work/src/mcp/server.js +320 -0
  72. package/dist/packages/work/src/owenloop-bin.d.ts +1 -0
  73. package/dist/packages/work/src/owenloop-bin.js +18 -0
  74. package/dist/packages/work/src/roles/agent-run.d.ts +124 -0
  75. package/dist/packages/work/src/roles/agent-run.js +529 -0
  76. package/dist/packages/work/src/roles/exec.d.ts +48 -0
  77. package/dist/packages/work/src/roles/exec.js +228 -0
  78. package/dist/packages/work/src/roles/hold.d.ts +72 -0
  79. package/dist/packages/work/src/roles/hold.js +363 -0
  80. package/dist/packages/work/src/roles/join.d.ts +18 -0
  81. package/dist/packages/work/src/roles/join.js +204 -0
  82. package/dist/packages/work/src/roles/lint.d.ts +58 -0
  83. package/dist/packages/work/src/roles/lint.js +234 -0
  84. package/dist/packages/work/src/roles/prepare.d.ts +1 -0
  85. package/dist/packages/work/src/roles/prepare.js +249 -0
  86. package/dist/packages/work/src/roles/release.d.ts +48 -0
  87. package/dist/packages/work/src/roles/release.js +137 -0
  88. package/dist/packages/work/src/roles/sessions.d.ts +61 -0
  89. package/dist/packages/work/src/roles/sessions.js +180 -0
  90. package/dist/packages/work/src/roles/settings.d.ts +6 -0
  91. package/dist/packages/work/src/roles/settings.js +71 -0
  92. package/dist/packages/work/src/roles/shift.d.ts +13 -0
  93. package/dist/packages/work/src/roles/shift.js +250 -0
  94. package/dist/packages/work/src/roles/signals.d.ts +55 -0
  95. package/dist/packages/work/src/roles/signals.js +62 -0
  96. package/dist/packages/work/src/settings/provision.d.ts +21 -0
  97. package/dist/packages/work/src/settings/provision.js +47 -0
  98. package/dist/packages/work/src/settings/settings.d.ts +136 -0
  99. package/dist/packages/work/src/settings/settings.js +155 -0
  100. package/dist/packages/work/src/shift/client.d.ts +24 -0
  101. package/dist/packages/work/src/shift/client.js +124 -0
  102. package/dist/packages/work/src/shift/loop.d.ts +131 -0
  103. package/dist/packages/work/src/shift/loop.js +751 -0
  104. package/dist/packages/work/src/shift/protocol.d.ts +95 -0
  105. package/dist/packages/work/src/shift/protocol.js +24 -0
  106. package/dist/packages/work/src/shift/routing.d.ts +35 -0
  107. package/dist/packages/work/src/shift/routing.js +50 -0
  108. package/dist/packages/work/src/shift/runtime.d.ts +45 -0
  109. package/dist/packages/work/src/shift/runtime.js +337 -0
  110. package/dist/packages/work/src/shift/server.d.ts +23 -0
  111. package/dist/packages/work/src/shift/server.js +716 -0
  112. package/dist/packages/work/src/shift/spawn.d.ts +109 -0
  113. package/dist/packages/work/src/shift/spawn.js +158 -0
  114. package/dist/packages/work/src/shift/state.d.ts +79 -0
  115. package/dist/packages/work/src/shift/state.js +385 -0
  116. package/dist/packages/work/src/submit-proof.d.ts +36 -0
  117. package/dist/packages/work/src/submit-proof.js +93 -0
  118. package/dist/packages/work/src/usage.d.ts +6 -0
  119. package/dist/packages/work/src/usage.js +175 -0
  120. package/dist/src/add.d.ts +189 -0
  121. package/dist/src/add.js +300 -0
  122. package/dist/src/archive.d.ts +97 -0
  123. package/dist/src/archive.js +591 -0
  124. package/dist/src/bundle/index.d.ts +64 -0
  125. package/dist/src/bundle/index.js +508 -0
  126. package/dist/src/bundle/manifest.d.ts +50 -0
  127. package/dist/src/bundle/manifest.js +435 -0
  128. package/dist/src/bundle/runtime.d.ts +26 -0
  129. package/dist/src/bundle/runtime.js +64 -0
  130. package/dist/src/bundle/tar.d.ts +62 -0
  131. package/dist/src/bundle/tar.js +238 -0
  132. package/dist/src/bundle/types.d.ts +105 -0
  133. package/dist/src/bundle/types.js +21 -0
  134. package/dist/{cli.d.ts → src/cli.d.ts} +92 -7
  135. package/dist/src/cli.js +5968 -0
  136. package/dist/{credentials.d.ts → src/credentials.d.ts} +22 -15
  137. package/dist/{credentials.js → src/credentials.js} +35 -31
  138. package/dist/src/crypto/allowed-signers.d.ts +68 -0
  139. package/dist/src/crypto/allowed-signers.js +307 -0
  140. package/dist/src/crypto/canonical.d.ts +8 -0
  141. package/dist/src/crypto/canonical.js +92 -0
  142. package/dist/src/crypto/chain.d.ts +65 -0
  143. package/dist/src/crypto/chain.js +377 -0
  144. package/dist/src/crypto/dsse.d.ts +209 -0
  145. package/dist/src/crypto/dsse.js +282 -0
  146. package/dist/src/crypto/enrollment.d.ts +78 -0
  147. package/dist/src/crypto/enrollment.js +186 -0
  148. package/dist/src/crypto/index.d.ts +48 -0
  149. package/dist/src/crypto/index.js +44 -0
  150. package/dist/src/crypto/keys.d.ts +258 -0
  151. package/dist/src/crypto/keys.js +908 -0
  152. package/dist/src/crypto/org-root.d.ts +33 -0
  153. package/dist/src/crypto/org-root.js +78 -0
  154. package/dist/src/crypto/origin-rules.d.ts +56 -0
  155. package/dist/src/crypto/origin-rules.js +143 -0
  156. package/dist/src/crypto/policy-floor.d.ts +98 -0
  157. package/dist/src/crypto/policy-floor.js +353 -0
  158. package/dist/src/crypto/records.d.ts +316 -0
  159. package/dist/src/crypto/records.js +157 -0
  160. package/dist/src/crypto/scope.d.ts +49 -0
  161. package/dist/src/crypto/scope.js +83 -0
  162. package/dist/src/crypto/ssh.d.ts +171 -0
  163. package/dist/src/crypto/ssh.js +396 -0
  164. package/dist/src/crypto/submission.d.ts +33 -0
  165. package/dist/src/crypto/submission.js +47 -0
  166. package/dist/src/crypto/trust-roots.d.ts +29 -0
  167. package/dist/src/crypto/trust-roots.js +39 -0
  168. package/dist/src/crypto/verify-consumed.d.ts +67 -0
  169. package/dist/src/crypto/verify-consumed.js +259 -0
  170. package/dist/src/crypto/verify-origin.d.ts +50 -0
  171. package/dist/src/crypto/verify-origin.js +151 -0
  172. package/dist/src/crypto/verify-publication.d.ts +60 -0
  173. package/dist/src/crypto/verify-publication.js +150 -0
  174. package/dist/{defs.d.ts → src/defs.d.ts} +24 -1
  175. package/dist/{defs.js → src/defs.js} +181 -61
  176. package/dist/{engine.d.ts → src/engine.d.ts} +105 -9
  177. package/dist/{engine.js → src/engine.js} +251 -47
  178. package/dist/{factory.d.ts → src/factory.d.ts} +16 -0
  179. package/dist/{factory.js → src/factory.js} +16 -4
  180. package/dist/src/global-config.d.ts +59 -0
  181. package/dist/src/global-config.js +84 -0
  182. package/dist/{hub.d.ts → src/hub.d.ts} +280 -31
  183. package/dist/{hub.js → src/hub.js} +493 -52
  184. package/dist/src/index.d.ts +47 -0
  185. package/dist/src/index.js +41 -0
  186. package/dist/src/install.d.ts +538 -0
  187. package/dist/src/install.js +1981 -0
  188. package/dist/src/lock.d.ts +38 -0
  189. package/dist/src/lock.js +325 -0
  190. package/dist/src/mcp/serve.d.ts +109 -0
  191. package/dist/{mcp → src/mcp}/serve.js +335 -75
  192. package/dist/{mcp → src/mcp}/server.d.ts +6 -9
  193. package/dist/{mcp → src/mcp}/server.js +18 -10
  194. package/dist/{model.d.ts → src/model.d.ts} +15 -0
  195. package/dist/{model.js → src/model.js} +112 -2
  196. package/dist/src/order-resolver.d.ts +184 -0
  197. package/dist/src/order-resolver.js +252 -0
  198. package/dist/src/package-version.d.ts +10 -0
  199. package/dist/src/package-version.js +42 -0
  200. package/dist/{paths.d.ts → src/paths.d.ts} +14 -1
  201. package/dist/{paths.js → src/paths.js} +18 -0
  202. package/dist/src/schemas/enrollment-grant.v1.schema.json +90 -0
  203. package/dist/src/schemas/index.d.ts +1416 -0
  204. package/dist/src/schemas/index.js +31 -0
  205. package/dist/src/schemas/order.v1.schema.json +106 -0
  206. package/dist/src/schemas/origin.v1.schema.json +68 -0
  207. package/dist/src/schemas/policy-floor.v1.schema.json +29 -0
  208. package/dist/src/schemas/publication.v1.schema.json +31 -0
  209. package/dist/src/schemas/revocation.v1.schema.json +39 -0
  210. package/dist/src/schemas/submission.v1.schema.json +61 -0
  211. package/dist/src/store/def-source.d.ts +52 -0
  212. package/dist/src/store/def-source.js +335 -0
  213. package/dist/src/store/index-file.d.ts +69 -0
  214. package/dist/src/store/index-file.js +151 -0
  215. package/dist/src/store/index.d.ts +27 -0
  216. package/dist/src/store/index.js +22 -0
  217. package/dist/src/store/ingestor.d.ts +43 -0
  218. package/dist/src/store/ingestor.js +211 -0
  219. package/dist/src/store/install.d.ts +228 -0
  220. package/dist/src/store/install.js +555 -0
  221. package/dist/src/store/instruction-source.d.ts +49 -0
  222. package/dist/src/store/instruction-source.js +298 -0
  223. package/dist/src/store/origin-evidence.d.ts +21 -0
  224. package/dist/src/store/origin-evidence.js +66 -0
  225. package/dist/src/store/pre-commit-verifier.d.ts +68 -0
  226. package/dist/src/store/pre-commit-verifier.js +418 -0
  227. package/dist/src/store/resolve.d.ts +138 -0
  228. package/dist/src/store/resolve.js +363 -0
  229. package/dist/src/store/types.d.ts +288 -0
  230. package/dist/src/store/types.js +356 -0
  231. package/dist/{types.d.ts → src/types.d.ts} +58 -24
  232. package/dist/{untar.d.ts → src/untar.d.ts} +8 -23
  233. package/dist/src/untar.js +38 -0
  234. package/dist/{util.d.ts → src/util.d.ts} +3 -2
  235. package/dist/{util.js → src/util.js} +3 -2
  236. package/dist/{owenwork.d.ts → src/work-settings.d.ts} +22 -22
  237. package/dist/{owenwork.js → src/work-settings.js} +27 -27
  238. package/docs/agent-runner.md +86 -0
  239. package/docs/authoring.md +150 -59
  240. package/docs/bundles.md +250 -0
  241. package/docs/cli.md +1758 -163
  242. package/docs/crypto.md +816 -0
  243. package/docs/design.md +374 -52
  244. package/docs/embedding.md +135 -27
  245. package/docs/wire-contracts.md +380 -0
  246. package/examples/workflows/{command-worker.yaml → command-executor.yaml} +15 -15
  247. package/examples/workflows/compile-dev-playbook.yaml +338 -0
  248. package/examples/workflows/judges/gate-sharpness.md +39 -0
  249. package/examples/workflows/judges/security.md +34 -0
  250. package/package.json +22 -8
  251. package/plugins/claude-code/.claude-plugin/marketplace.json +14 -0
  252. package/plugins/claude-code/plugin/.claude-plugin/plugin.json +8 -0
  253. package/plugins/claude-code/plugin/.mcp.json +14 -0
  254. package/plugins/claude-code/plugin/hooks/hooks.json +26 -0
  255. package/plugins/claude-code/plugin/hooks/session-end.sh +40 -0
  256. package/plugins/claude-code/plugin/hooks/session-start.sh +52 -0
  257. package/plugins/claude-code/plugin/skills/author/SKILL.md +181 -0
  258. package/plugins/claude-code/plugin/skills/conduct/SKILL.md +106 -0
  259. package/plugins/claude-code/plugin/skills/shift/SKILL.md +105 -0
  260. package/plugins/codex/.agents/plugins/marketplace.json +21 -0
  261. package/plugins/codex/plugins/owenloop/.codex-plugin/plugin.json +7 -0
  262. package/plugins/codex/plugins/owenloop/.mcp.json +20 -0
  263. package/plugins/codex/plugins/owenloop/hooks/hooks.json +26 -0
  264. package/plugins/codex/plugins/owenloop/hooks/session-end.sh +40 -0
  265. package/plugins/codex/plugins/owenloop/hooks/session-start.sh +52 -0
  266. package/plugins/codex/plugins/owenloop/skills/author/SKILL.md +181 -0
  267. package/plugins/codex/plugins/owenloop/skills/conduct/SKILL.md +106 -0
  268. package/plugins/codex/plugins/owenloop/skills/shift/SKILL.md +105 -0
  269. package/dist/add.d.ts +0 -384
  270. package/dist/add.js +0 -834
  271. package/dist/cli.js +0 -3270
  272. package/dist/index.d.ts +0 -32
  273. package/dist/index.js +0 -23
  274. package/dist/lock.d.ts +0 -80
  275. package/dist/lock.js +0 -217
  276. package/dist/mcp/serve.d.ts +0 -84
  277. package/dist/untar.js +0 -164
  278. /package/dist/{schema.d.ts → src/schema.d.ts} +0 -0
  279. /package/dist/{schema.js → src/schema.js} +0 -0
  280. /package/dist/{store.d.ts → src/store.d.ts} +0 -0
  281. /package/dist/{store.js → src/store.js} +0 -0
  282. /package/dist/{types.js → src/types.js} +0 -0
@@ -0,0 +1,155 @@
1
+ /**
2
+ * Settings locate, load, and validate. This is the machine-level config
3
+ * surface for owenloop's roles, mirroring owenloop's convention (D12): a
4
+ * single JSON file at an XDG/HOME path supplying the fallback values every
5
+ * role resolves (CLI flag > env var > settings file > built-in default).
6
+ *
7
+ * C1 pinned where the file lives and how it loads; C2 added the first two
8
+ * fields; C6 fills in the full surface (dispatch cap + agents/state dirs),
9
+ * adds type validation with actionable errors, and surfaces unrecognized keys
10
+ * so typos are visible via `owenloop work settings`.
11
+ *
12
+ * HARD RULE: NO secrets ever live in this file. Credentials stay in owenloop's
13
+ * own store (the CredentialReader seam) — there is deliberately no token knob.
14
+ */
15
+ import { existsSync, readFileSync } from 'node:fs';
16
+ import { join } from 'node:path';
17
+ /** The known settings keys, in the order `owenloop work settings` prints them. */
18
+ export const KNOWN_SETTINGS_KEYS = [
19
+ 'hubOrigin',
20
+ 'cacheDir',
21
+ 'stateDir',
22
+ 'dispatchCap',
23
+ 'commandRouting',
24
+ 'defPolicy',
25
+ 'artifactPolicy',
26
+ 'maxConcurrentAgents',
27
+ 'workRoot',
28
+ 'workRepo',
29
+ 'tierMap',
30
+ 'escalateAt',
31
+ 'escalationExtensionKey',
32
+ ];
33
+ /**
34
+ * Resolve the settings file path from the caller's env:
35
+ * `$XDG_CONFIG_HOME/owenloop/settings.json` when `XDG_CONFIG_HOME` is set and
36
+ * non-empty, else `$HOME/.config/owenloop/settings.json`. Throws when neither
37
+ * is available rather than guessing a home directory.
38
+ */
39
+ export function settingsPath(env) {
40
+ const xdg = env.XDG_CONFIG_HOME;
41
+ if (xdg !== undefined && xdg.trim() !== '')
42
+ return join(xdg, 'owenloop', 'settings.json');
43
+ const home = env.HOME;
44
+ if (home !== undefined && home.trim() !== '')
45
+ return join(home, '.config', 'owenloop', 'settings.json');
46
+ throw new Error('cannot locate a settings directory: set HOME or XDG_CONFIG_HOME');
47
+ }
48
+ /**
49
+ * Validate a parsed settings object. Checks the TYPE of every known key
50
+ * (throwing an actionable error naming the key, expected type, received value,
51
+ * and file path on a mismatch) and collects any unrecognized keys. Unknown
52
+ * keys are retained on the returned `settings` (forward compatible) — only
53
+ * their names are reported, never fatal.
54
+ *
55
+ * `dispatchCap` must be a positive integer; `commandRouting` must be one of the
56
+ * two literals. Any other type on a known key is a hard error.
57
+ */
58
+ export function validateSettings(raw, path) {
59
+ if (typeof raw !== 'object' || raw === null || Array.isArray(raw)) {
60
+ const got = Array.isArray(raw) ? 'array' : raw === null ? 'null' : typeof raw;
61
+ throw new Error(`invalid settings file at ${path}: expected a JSON object, got ${got}`);
62
+ }
63
+ const obj = raw;
64
+ const bad = (key, expected, value) => new Error(`invalid settings file at ${path}: '${key}' must be ${expected}, got ${JSON.stringify(value)}`);
65
+ for (const key of ['hubOrigin', 'cacheDir', 'stateDir', 'workRoot', 'workRepo']) {
66
+ if (key in obj && typeof obj[key] !== 'string')
67
+ throw bad(key, 'a string', obj[key]);
68
+ }
69
+ if ('dispatchCap' in obj) {
70
+ const v = obj['dispatchCap'];
71
+ if (typeof v !== 'number' || !Number.isInteger(v) || v <= 0) {
72
+ throw bad('dispatchCap', 'a positive integer', v);
73
+ }
74
+ }
75
+ if ('maxConcurrentAgents' in obj) {
76
+ const v = obj['maxConcurrentAgents'];
77
+ if (typeof v !== 'number' || !Number.isInteger(v) || v <= 0) {
78
+ throw bad('maxConcurrentAgents', 'a positive integer', v);
79
+ }
80
+ }
81
+ if ('tierMap' in obj) {
82
+ const v = obj['tierMap'];
83
+ if (typeof v !== 'object' || v === null || Array.isArray(v)) {
84
+ throw bad('tierMap', 'an object whose values are non-empty strings', v);
85
+ }
86
+ for (const value of Object.values(v)) {
87
+ if (typeof value !== 'string' || value.trim() === '')
88
+ throw bad('tierMap', 'an object whose values are non-empty strings', v);
89
+ }
90
+ }
91
+ if ('escalateAt' in obj) {
92
+ const v = obj['escalateAt'];
93
+ if (typeof v !== 'number' || !Number.isInteger(v) || v <= 0) {
94
+ throw bad('escalateAt', 'a positive integer', v);
95
+ }
96
+ }
97
+ if ('escalationExtensionKey' in obj) {
98
+ const v = obj['escalationExtensionKey'];
99
+ if (typeof v !== 'string' || v.trim() === '') {
100
+ throw bad('escalationExtensionKey', 'a non-empty string', v);
101
+ }
102
+ }
103
+ if ('commandRouting' in obj) {
104
+ const v = obj['commandRouting'];
105
+ if (v !== 'shift' && v !== 'manual')
106
+ throw bad('commandRouting', "'shift' or 'manual'", v);
107
+ }
108
+ if ('defPolicy' in obj) {
109
+ const v = obj['defPolicy'];
110
+ if (v !== 'enforce' && v !== 'warn' && v !== 'off') {
111
+ throw bad('defPolicy', "'enforce', 'warn', or 'off'", v);
112
+ }
113
+ }
114
+ if ('artifactPolicy' in obj) {
115
+ const v = obj['artifactPolicy'];
116
+ if (v !== 'enforce' && v !== 'warn' && v !== 'off') {
117
+ throw bad('artifactPolicy', "'enforce', 'warn', or 'off'", v);
118
+ }
119
+ }
120
+ const known = new Set(KNOWN_SETTINGS_KEYS);
121
+ const unrecognized = Object.keys(obj).filter((k) => !known.has(k));
122
+ return { settings: obj, unrecognized };
123
+ }
124
+ /**
125
+ * Inspect the settings file: resolve its path, whether it exists, and its
126
+ * validated contents. A missing file is not an error (`exists: false`,
127
+ * settings `{}`). Malformed JSON or an invalid known-key type throws a clear,
128
+ * path-named error. This is the single read+validate path that `loadSettings`
129
+ * and the `settings` print role share.
130
+ */
131
+ export function inspectSettings(env) {
132
+ const path = settingsPath(env);
133
+ if (!existsSync(path))
134
+ return { path, exists: false, settings: {}, unrecognized: [] };
135
+ const raw = readFileSync(path, 'utf8');
136
+ let parsed;
137
+ try {
138
+ parsed = JSON.parse(raw);
139
+ }
140
+ catch (err) {
141
+ const reason = err instanceof Error ? err.message : String(err);
142
+ throw new Error(`malformed settings file at ${path}: ${reason}`);
143
+ }
144
+ return { path, exists: true, ...validateSettings(parsed, path) };
145
+ }
146
+ /**
147
+ * Load, parse, and validate the settings file. A missing file yields `{}` (not
148
+ * an error). Malformed JSON or an invalid known-key type throws a clear error
149
+ * rather than silently defaulting — a silent default would mask config bugs.
150
+ * Every consumer that calls `loadSettings` gets known-key type validation for
151
+ * free; unknown keys pass through untouched.
152
+ */
153
+ export function loadSettings(env) {
154
+ return inspectSettings(env).settings;
155
+ }
@@ -0,0 +1,24 @@
1
+ import { type ShiftRequest, type ShiftResponse } from './protocol.ts';
2
+ export interface ShiftClientErrorOptions {
3
+ absent?: boolean;
4
+ code?: string;
5
+ }
6
+ export declare class ShiftClientError extends Error {
7
+ readonly absent: boolean;
8
+ readonly code: string | undefined;
9
+ constructor(message: string, opts?: ShiftClientErrorOptions);
10
+ }
11
+ export declare function shiftSocketPath(stateDir: string): string;
12
+ export declare function noDaemonMessage(socketPath: string): string;
13
+ /** Send one request and parse the daemon's one-line response. */
14
+ export declare function requestShift(socketPath: string, request: ShiftRequest): Promise<ShiftResponse>;
15
+ export interface ParsedNextArgs {
16
+ waitMs: number;
17
+ stateDir?: string;
18
+ error?: string;
19
+ }
20
+ export declare function parseNextArgs(args: string[]): ParsedNextArgs;
21
+ export declare function parseStateDirArgs(args: string[]): {
22
+ stateDir?: string;
23
+ error?: string;
24
+ };
@@ -0,0 +1,124 @@
1
+ /**
2
+ * Thin client for the local shift daemon's one-request-per-connection socket.
3
+ */
4
+ import { createConnection } from 'node:net';
5
+ import { join } from 'node:path';
6
+ import { DEFAULT_NEXT_WAIT_MS, MAX_REQUEST_LINE_BYTES, MAX_RESPONSE_LINE_BYTES, NO_DAEMON_SUFFIX, SHIFT_SOCKET_NAME, } from "./protocol.js";
7
+ export class ShiftClientError extends Error {
8
+ absent;
9
+ code;
10
+ constructor(message, opts = {}) {
11
+ super(message);
12
+ this.name = 'ShiftClientError';
13
+ this.absent = opts.absent ?? false;
14
+ this.code = opts.code;
15
+ }
16
+ }
17
+ export function shiftSocketPath(stateDir) {
18
+ return join(stateDir, SHIFT_SOCKET_NAME);
19
+ }
20
+ export function noDaemonMessage(socketPath) {
21
+ return `no shift daemon at ${socketPath}${NO_DAEMON_SUFFIX}`;
22
+ }
23
+ /** Send one request and parse the daemon's one-line response. */
24
+ export function requestShift(socketPath, request) {
25
+ return new Promise((resolve, reject) => {
26
+ const socket = createConnection(socketPath);
27
+ let settled = false;
28
+ let buffer = Buffer.alloc(0);
29
+ const fail = (error) => {
30
+ if (settled)
31
+ return;
32
+ settled = true;
33
+ socket.destroy();
34
+ reject(error);
35
+ };
36
+ socket.once('connect', () => {
37
+ const line = Buffer.from(`${JSON.stringify(request)}\n`, 'utf8');
38
+ if (line.length > MAX_REQUEST_LINE_BYTES) {
39
+ fail(new ShiftClientError('request is too large', { code: 'EMSGSIZE' }));
40
+ return;
41
+ }
42
+ socket.write(line);
43
+ });
44
+ socket.on('data', (chunk) => {
45
+ if (settled)
46
+ return;
47
+ buffer = Buffer.concat([buffer, chunk]);
48
+ if (buffer.length > MAX_RESPONSE_LINE_BYTES) {
49
+ fail(new ShiftClientError('daemon response is too large', { code: 'EMSGSIZE' }));
50
+ return;
51
+ }
52
+ const newline = buffer.indexOf(0x0a);
53
+ if (newline === -1)
54
+ return;
55
+ const raw = buffer.subarray(0, newline).toString('utf8');
56
+ settled = true;
57
+ socket.destroy();
58
+ try {
59
+ resolve(JSON.parse(raw));
60
+ }
61
+ catch {
62
+ reject(new ShiftClientError('daemon returned malformed JSON'));
63
+ }
64
+ });
65
+ socket.once('error', (error) => {
66
+ const code = error.code;
67
+ const absent = code === 'ENOENT' || code === 'ECONNREFUSED' || code === 'ENOTSOCK' || code === 'EPIPE';
68
+ fail(new ShiftClientError(absent ? noDaemonMessage(socketPath) : error.message, { absent, code }));
69
+ });
70
+ socket.once('close', () => {
71
+ if (!settled)
72
+ fail(new ShiftClientError('shift daemon closed the connection before replying'));
73
+ });
74
+ });
75
+ }
76
+ export function parseNextArgs(args) {
77
+ let waitMs = DEFAULT_NEXT_WAIT_MS;
78
+ let stateDir;
79
+ for (let i = 0; i < args.length; i++) {
80
+ const raw = args[i];
81
+ const name = raw.startsWith('--') && raw.includes('=') ? raw.slice(0, raw.indexOf('=')) : raw;
82
+ const readValue = () => {
83
+ const eq = raw.indexOf('=');
84
+ if (eq !== -1)
85
+ return raw.slice(eq + 1);
86
+ i++;
87
+ return args[i];
88
+ };
89
+ if (name === '--wait') {
90
+ const value = readValue();
91
+ if (value === undefined || value.trim() === '')
92
+ return { waitMs, error: 'missing value for --wait' };
93
+ const seconds = Number(value);
94
+ if (!Number.isFinite(seconds) || seconds < 0)
95
+ return { waitMs, error: `--wait must be a finite non-negative number of seconds, got '${value}'` };
96
+ waitMs = seconds * 1000;
97
+ }
98
+ else if (name === '--state-dir') {
99
+ const value = readValue();
100
+ if (value === undefined || value.trim() === '')
101
+ return { waitMs, error: 'missing value for --state-dir' };
102
+ stateDir = value;
103
+ }
104
+ else {
105
+ return { waitMs, error: `unknown option '${raw}'` };
106
+ }
107
+ }
108
+ return { waitMs, ...(stateDir !== undefined ? { stateDir } : {}) };
109
+ }
110
+ export function parseStateDirArgs(args) {
111
+ let stateDir;
112
+ for (let i = 0; i < args.length; i++) {
113
+ const raw = args[i];
114
+ const name = raw.startsWith('--') && raw.includes('=') ? raw.slice(0, raw.indexOf('=')) : raw;
115
+ if (name !== '--state-dir')
116
+ return { error: `unknown option '${raw}'` };
117
+ const eq = raw.indexOf('=');
118
+ const value = eq !== -1 ? raw.slice(eq + 1) : args[++i];
119
+ if (value === undefined || value.trim() === '')
120
+ return { error: 'missing value for --state-dir' };
121
+ stateDir = value;
122
+ }
123
+ return { ...(stateDir !== undefined ? { stateDir } : {}) };
124
+ }
@@ -0,0 +1,131 @@
1
+ import type { HubClient } from '../hub/client.ts';
2
+ import { type WorkOrder } from '../hub/types.ts';
3
+ import type { FetchedStep } from '../bundle/types.ts';
4
+ import { type Liveness } from './state.ts';
5
+ import { sweepWorkDirs as sweepWorkDirsImpl } from '../agent/workdir.ts';
6
+ import type { Spawner } from './spawn.ts';
7
+ import type { ShiftEvent } from './protocol.ts';
8
+ export interface ShiftLoopOptions {
9
+ hub: HubClient;
10
+ spawner: Spawner;
11
+ /** Injected sleep — tests pass an instant/scriptable stub (no real timers). */
12
+ sleep: (ms: number) => Promise<void>;
13
+ /** Injected wall clock for persisted and externally meaningful timestamps. */
14
+ now: () => number;
15
+ /** Injected monotonic clock for elapsed-time decisions. Default `performance.now`. */
16
+ monotonicNow?: () => number;
17
+ /** stdout sink (one line per call; newline appended). */
18
+ out: (line: string) => void;
19
+ /** stderr sink (one line per call; newline appended). */
20
+ err: (line: string) => void;
21
+ /** Local dispatch/reap observations consumed by the shift socket wrapper. */
22
+ onEvent?: (event: ShiftEvent) => void;
23
+ cacheDir: string;
24
+ stateDir: string;
25
+ /** Max concurrent in-flight orders (exec + agent-run children). */
26
+ cap: number;
27
+ /** Serve crews this shift accepts (sent to presence + whats_next). INITIAL
28
+ * value only — live-mutable via the `ShiftLoop.setShift` (MCP `clock_in`). */
29
+ serveCrews: string[];
30
+ /** Shift name for presence. INITIAL value only — live-mutable via
31
+ * `ShiftLoop.setShift` (MCP `clock_in`). */
32
+ name: string;
33
+ /**
34
+ * W7: this Shift process incarnation's self-declared id (`shf_<uuid>`)
35
+ * and process start time — carried on presence pings (attribution/
36
+ * observability only, D8/INV-82) and carried into dispatched holders/orders
37
+ * so submissions can be traced back to the Shift that produced them.
38
+ * Regenerated every restart, never persisted (D1).
39
+ */
40
+ shiftId?: string;
41
+ startedAt?: number;
42
+ /** When set, poll only this instance; else inbox-mode across all servable. */
43
+ workflow?: string;
44
+ /** Machine-level command routing (raw — validated in routing.ts). */
45
+ commandRouting?: unknown;
46
+ /** Resolve exact order-pinned step metadata by `defDigest`; modern command orders fail closed without it. */
47
+ resolveOrderStep?: (order: WorkOrder) => Promise<FetchedStep | undefined>;
48
+ pollIntervalMs: number;
49
+ presenceIntervalMs: number;
50
+ /**
51
+ * Max concurrent `agent-run` children (default 4). A SECOND budget, applied
52
+ * ON TOP OF `cap` — never a replacement for it. An agent turn is long and
53
+ * memory-heavy where a command is short, so the two cannot share one number.
54
+ */
55
+ maxConcurrentAgents?: number;
56
+ /**
57
+ * PHASE 4 — the root under which per-RUN agent work directories live
58
+ * (`<workRoot>/<workflow>/<run>/`). ABSENT DISABLES THE REAPER entirely: with
59
+ * no root there is no set of directories this shift can claim to own, and a
60
+ * remover with no ownership claim is exactly what must not exist.
61
+ */
62
+ workRoot?: string;
63
+ /** PHASE 4 — when set, work dirs are git worktrees of this repo and are
64
+ * removed with `git worktree remove` rather than a plain `rm -rf`. */
65
+ workRepo?: string;
66
+ /** PHASE 4 — grace window before an idle work dir may be removed. Default
67
+ * `DEFAULT_WORK_DIR_TTL_MS` (1h), owned by `src/agent/workdir.ts`. */
68
+ workDirTtlMs?: number;
69
+ /** Bootstrap wake + exactly one sweep, then return (the e2e/demo hook). */
70
+ once?: boolean;
71
+ /** Injectable liveness probe (tests). */
72
+ isAlive?: Liveness;
73
+ /** PHASE 4 — injected in tests so the reaper can be exercised without a
74
+ * filesystem. Defaults to `sweepWorkDirs` from `src/agent/workdir.ts`. */
75
+ sweepWorkDirs?: typeof sweepWorkDirsImpl;
76
+ }
77
+ export interface ShiftLoop {
78
+ run(): Promise<number>;
79
+ stop(): void;
80
+ /**
81
+ * Run exactly one park iteration (presence → reconcile/queued dispatch → wake
82
+ * → required sweep → reap) and return how many children it spawned. The shift daemon
83
+ * uses this seam for its loop core; the standing `run()` loop ignores the
84
+ * count. Cursor/presence state is held in the closure and persists across calls.
85
+ */
86
+ iterate(): Promise<number>;
87
+ /** Free capacity right now (cap − live in-flight). ≤ 0 ⇒ at capacity. */
88
+ freeCapacity(): number;
89
+ /** Live dispatch-cap used by status and next responses. */
90
+ getCap(): number;
91
+ /** Adjust the live dispatch cap for internal callers and tests. */
92
+ setCap(cap: number): void;
93
+ /** The shift's live identity: the presence name and the crew scope (`serve_crews`)
94
+ * the next ping and the next sweep will carry. Empty `serveCrews` means ALL of
95
+ * this identity's crews, never none. */
96
+ getShift(): {
97
+ name: string;
98
+ serveCrews: string[];
99
+ };
100
+ /** Set the live shift identity (the socket `clock_in` operation). A field left ABSENT is
101
+ * left unchanged; `serveCrews: []` explicitly means "all crews". Also makes the
102
+ * next presence ping due immediately, so the new identity reaches the hub on the
103
+ * next iterate() rather than up to presenceIntervalMs later. Returns the result. */
104
+ setShift(next: {
105
+ name?: string;
106
+ serveCrews?: string[];
107
+ }): {
108
+ name: string;
109
+ serveCrews: string[];
110
+ };
111
+ /** Record local client attendance and make the next presence ping due. */
112
+ noteAttended(at: number): void;
113
+ /** Return the last accepted attendance timestamp, if any. */
114
+ getAttendedAt(): number | undefined;
115
+ /**
116
+ * Run-ended reap (metering condition (a)): drop the in-flight record for
117
+ * `run` NOW, so its slot frees immediately instead of waiting for the next
118
+ * reconcile to notice the child exited. The shift's MCP `submit` tool calls
119
+ * an internal caller may use this when the hub reports a submit CLOSED the
120
+ * run — the one in-process end-of-run signal the shift sees. A run whose closing submit went through
121
+ * the child's own mount instead is not a problem: that child exits, and the
122
+ * next reconcile's pid probe frees the slot anyway.
123
+ */
124
+ noteRunEnded(run: string): void;
125
+ }
126
+ /**
127
+ * The hub reaps a never-contacted claim after 120 seconds. Stop local queueing
128
+ * after 90 seconds so a detached child retains 30 seconds to make first contact.
129
+ */
130
+ export declare const MAX_PENDING_CANDIDATE_AGE_MS = 90000;
131
+ export declare function createShiftLoop(opts: ShiftLoopOptions): ShiftLoop;