owenloop 0.5.8 → 0.5.10

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 (131) hide show
  1. package/CHANGELOG.md +69 -0
  2. package/README.md +81 -39
  3. package/bin/owenloop.mjs +16 -1
  4. package/dist/packages/work/src/agent/loop.d.ts +23 -8
  5. package/dist/packages/work/src/agent/loop.js +55 -6
  6. package/dist/packages/work/src/bundle/pull.d.ts +21 -0
  7. package/dist/packages/work/src/bundle/pull.js +118 -0
  8. package/dist/packages/work/src/consumed-verifier.js +6 -17
  9. package/dist/packages/work/src/exec/instructions.d.ts +4 -1
  10. package/dist/packages/work/src/exec/instructions.js +3 -0
  11. package/dist/packages/work/src/exec/loop.d.ts +2 -2
  12. package/dist/packages/work/src/exec/loop.js +273 -46
  13. package/dist/packages/work/src/exec/receipt.d.ts +7 -7
  14. package/dist/packages/work/src/exec/receipt.js +6 -6
  15. package/dist/packages/work/src/harness/claude.js +116 -0
  16. package/dist/packages/work/src/harness/codex.d.ts +8 -0
  17. package/dist/packages/work/src/harness/codex.js +27 -1
  18. package/dist/packages/work/src/harness/contract.d.ts +9 -0
  19. package/dist/packages/work/src/hub/client.d.ts +19 -4
  20. package/dist/packages/work/src/hub/client.js +7 -3
  21. package/dist/packages/work/src/hub/types.d.ts +84 -0
  22. package/dist/packages/work/src/main.js +1 -0
  23. package/dist/packages/work/src/roles/agent-run.js +57 -32
  24. package/dist/packages/work/src/roles/exec.js +27 -8
  25. package/dist/packages/work/src/roles/settings.js +2 -0
  26. package/dist/packages/work/src/roles/shift.js +14 -2
  27. package/dist/packages/work/src/roles/util.d.ts +1 -0
  28. package/dist/packages/work/src/roles/util.js +10 -0
  29. package/dist/packages/work/src/settings/hub-roster-cache.d.ts +68 -0
  30. package/dist/packages/work/src/settings/hub-roster-cache.js +370 -0
  31. package/dist/packages/work/src/settings/roster.d.ts +84 -0
  32. package/dist/packages/work/src/settings/roster.js +364 -5
  33. package/dist/packages/work/src/settings/serving.d.ts +17 -0
  34. package/dist/packages/work/src/settings/serving.js +79 -0
  35. package/dist/packages/work/src/settings/settings.d.ts +14 -1
  36. package/dist/packages/work/src/settings/settings.js +14 -0
  37. package/dist/packages/work/src/shift/loop.d.ts +108 -5
  38. package/dist/packages/work/src/shift/loop.js +416 -54
  39. package/dist/packages/work/src/shift/protocol.d.ts +7 -5
  40. package/dist/packages/work/src/shift/runtime.d.ts +18 -0
  41. package/dist/packages/work/src/shift/runtime.js +104 -5
  42. package/dist/packages/work/src/shift/server.js +2 -0
  43. package/dist/packages/work/src/shift/spawn.d.ts +17 -2
  44. package/dist/packages/work/src/shift/spawn.js +16 -13
  45. package/dist/packages/work/src/shift/state.d.ts +29 -2
  46. package/dist/packages/work/src/shift/state.js +45 -15
  47. package/dist/packages/work/src/submit-proof.d.ts +11 -8
  48. package/dist/packages/work/src/submit-proof.js +11 -8
  49. package/dist/packages/work/src/usage.d.ts +1 -1
  50. package/dist/packages/work/src/usage.js +7 -1
  51. package/dist/packages/work/src/util/modifier-init.d.ts +7 -0
  52. package/dist/packages/work/src/util/modifier-init.js +73 -0
  53. package/dist/src/bundle/tar.d.ts +9 -4
  54. package/dist/src/bundle/tar.js +9 -4
  55. package/dist/src/capabilities.d.ts +76 -6
  56. package/dist/src/capabilities.js +49 -6
  57. package/dist/src/capability-mapping-client.d.ts +29 -0
  58. package/dist/src/capability-mapping-client.js +160 -0
  59. package/dist/src/cli.d.ts +16 -3
  60. package/dist/src/cli.js +1925 -281
  61. package/dist/src/config-dir.d.ts +1 -1
  62. package/dist/src/config-dir.js +1 -1
  63. package/dist/src/crypto/index.d.ts +1 -1
  64. package/dist/src/crypto/index.js +1 -1
  65. package/dist/src/crypto/org-root.d.ts +30 -12
  66. package/dist/src/crypto/org-root.js +162 -14
  67. package/dist/src/crypto/records.d.ts +2 -0
  68. package/dist/src/crypto/records.js +2 -0
  69. package/dist/src/defs.d.ts +38 -2
  70. package/dist/src/defs.js +593 -86
  71. package/dist/src/engine.d.ts +103 -25
  72. package/dist/src/engine.js +331 -79
  73. package/dist/src/hub.d.ts +77 -0
  74. package/dist/src/hub.js +162 -0
  75. package/dist/src/implements.d.ts +56 -0
  76. package/dist/src/implements.js +790 -0
  77. package/dist/src/index.d.ts +11 -9
  78. package/dist/src/index.js +6 -5
  79. package/dist/src/mcp/serve.d.ts +22 -0
  80. package/dist/src/mcp/serve.js +330 -41
  81. package/dist/src/mcp/server.d.ts +10 -7
  82. package/dist/src/mcp/server.js +53 -8
  83. package/dist/src/model.d.ts +48 -10
  84. package/dist/src/model.js +252 -99
  85. package/dist/src/order-resolver.d.ts +1 -0
  86. package/dist/src/order-resolver.js +8 -1
  87. package/dist/src/schemas/index.d.ts +11 -0
  88. package/dist/src/schemas/order.v1.schema.json +7 -1
  89. package/dist/src/store/def-source.d.ts +19 -0
  90. package/dist/src/store/def-source.js +87 -17
  91. package/dist/src/store/gc-recovery.d.ts +46 -0
  92. package/dist/src/store/gc-recovery.js +258 -0
  93. package/dist/src/store/gc.d.ts +94 -0
  94. package/dist/src/store/gc.js +562 -0
  95. package/dist/src/store/index.d.ts +3 -1
  96. package/dist/src/store/index.js +2 -0
  97. package/dist/src/store/install.d.ts +34 -5
  98. package/dist/src/store/install.js +73 -11
  99. package/dist/src/store/pre-commit-verifier.js +42 -2
  100. package/dist/src/store/snapshot-guard.d.ts +18 -0
  101. package/dist/src/store/snapshot-guard.js +94 -0
  102. package/dist/src/store.d.ts +69 -4
  103. package/dist/src/store.js +254 -16
  104. package/dist/src/types.d.ts +101 -20
  105. package/dist/src/util.js +4 -1
  106. package/docs/authoring.md +235 -10
  107. package/docs/bundles.md +45 -2
  108. package/docs/cli.md +437 -55
  109. package/docs/crypto.md +32 -10
  110. package/docs/design.md +177 -47
  111. package/docs/evals/mcp-charter-baseline.json +428 -0
  112. package/docs/mcp-charter-eval.md +124 -0
  113. package/docs/routing.md +189 -34
  114. package/docs/shift-logs.md +38 -9
  115. package/docs/wire-contracts.md +78 -14
  116. package/examples/workflows/compile-dev-playbook.yaml +1 -1
  117. package/examples/workflows/delivery.yaml +31 -14
  118. package/examples/workflows/ship.yaml +38 -4
  119. package/package.json +2 -1
  120. package/plugins/claude-code/plugin/.claude-plugin/plugin.json +1 -1
  121. package/plugins/claude-code/plugin/.mcp.json +1 -1
  122. package/plugins/claude-code/plugin/skills/author/SKILL.md +22 -0
  123. package/plugins/claude-code/plugin/skills/ephemeral/SKILL.md +95 -0
  124. package/plugins/claude-code/plugin/skills/graduate/SKILL.md +156 -0
  125. package/plugins/claude-code/plugin/skills/plan/SKILL.md +236 -0
  126. package/plugins/codex/plugins/owenloop/.codex-plugin/plugin.json +1 -1
  127. package/plugins/codex/plugins/owenloop/.mcp.json +1 -1
  128. package/plugins/codex/plugins/owenloop/skills/author/SKILL.md +22 -0
  129. package/plugins/codex/plugins/owenloop/skills/ephemeral/SKILL.md +95 -0
  130. package/plugins/codex/plugins/owenloop/skills/graduate/SKILL.md +156 -0
  131. package/plugins/codex/plugins/owenloop/skills/plan/SKILL.md +236 -0
@@ -5,11 +5,13 @@
5
5
  * strongest-first cascade. Shape validation and capability lookup remain in
6
6
  * `agent/capability-model.ts`.
7
7
  */
8
- import { existsSync, readFileSync } from 'node:fs';
9
- import { join } from 'node:path';
8
+ import { existsSync, readFileSync, readdirSync } from 'node:fs';
9
+ import { createHash } from 'node:crypto';
10
+ import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
10
11
  import { validateRoster, } from "../agent/capability-model.js";
11
12
  import { owenloopConfigDir } from "../../../../src/config-dir.js";
12
13
  import { loadSettings } from "./settings.js";
14
+ import { hubRosterLayers, readHubRosterCache } from "./hub-roster-cache.js";
13
15
  /** Merge key-by-key. `layers` is ordered STRONGEST FIRST. */
14
16
  export function mergeRosterLayers(layers) {
15
17
  // Capability names are arbitrary strings, including Object.prototype names.
@@ -54,22 +56,352 @@ function readCrewRoster(path) {
54
56
  }
55
57
  return roster;
56
58
  }
59
+ /** The directory containing operator-owned strongest-layer crew files. */
60
+ export function crewRosterDir(env) {
61
+ return join(owenloopConfigDir(env), 'crews');
62
+ }
63
+ // There is exactly ONE codec generation. The only crew-file behavior any
64
+ // published release has ever shipped is origin/main's bare
65
+ // `join(configDir, 'crews', crew + '.json')` — no release ever wrote an
66
+ // encoded filename, so there are no historical codec files to migrate and no
67
+ // second generation to probe. Keep it that way: a new naming scheme replaces
68
+ // this one wholesale behind a new directory, never as an additional probe.
69
+ const CREW_ROSTER_FILENAME_PREFIX = 'crew-hex--';
70
+ const CREW_ROSTER_HASH_FILENAME_PREFIX = 'crew-hex-hash--';
71
+ // POSIX filesystems commonly cap a path component at 255 bytes. Leave margin
72
+ // below that limit so the codec cannot turn a hub-valid crew into ENAMETOOLONG.
73
+ const MAX_CREW_ROSTER_FILENAME_BYTES = 240;
74
+ // Hub crew names are at most 64 characters. The directory name is itself long
75
+ // enough that `<directory>/<basename>` can never be a hub-valid nested legacy
76
+ // crew name, so no file is ambiguously a member of both namespaces.
77
+ const CREW_ROSTER_ENCODED_DIR = '.owenloop-machine-roster-codec-namespace-reserved-v1-ownership';
78
+ const WINDOWS_RESERVED_BASENAMES = /^(?:con|prn|aux|nul|com[1-9]|lpt[1-9])(?:\..*)?$/iu;
79
+ /**
80
+ * Path-segment-safe filename codec for crews that cannot use their legacy
81
+ * literal filename. Its lowercase-hex alphabet is stable under filesystem
82
+ * case folding: distinct UTF-8 crew names therefore cannot alias after a
83
+ * case-insensitive filesystem has accepted the first spelling. Extremely large
84
+ * names use a fixed-size content-addressed form; setup writes the crew name in
85
+ * the file's note, while ordinary safe names remain literal for rollback.
86
+ */
87
+ export function encodeCrewRosterFilename(crew) {
88
+ const reversible = `${CREW_ROSTER_FILENAME_PREFIX}${Buffer.from(crew, 'utf8').toString('hex')}.json`;
89
+ if (Buffer.byteLength(reversible, 'utf8') <= MAX_CREW_ROSTER_FILENAME_BYTES)
90
+ return reversible;
91
+ return `${CREW_ROSTER_HASH_FILENAME_PREFIX}${createHash('sha256').update(crew, 'utf8').digest('hex')}.json`;
92
+ }
93
+ /** A codec file is accepted only when its recorded owner reproduces the name. */
94
+ function codecFilenameMatchesCrew(filename, crew) {
95
+ return filename === encodeCrewRosterFilename(crew);
96
+ }
97
+ /** Decode only an exact reversible codec output; ordinary legacy basenames stay literal. */
98
+ export function decodeCrewRosterFilename(filename) {
99
+ if (!filename.endsWith('.json') || !filename.startsWith(CREW_ROSTER_FILENAME_PREFIX))
100
+ return undefined;
101
+ const encoded = filename.slice(CREW_ROSTER_FILENAME_PREFIX.length, -'.json'.length);
102
+ if (!/^[0-9a-f]+$/u.test(encoded) || encoded.length % 2 !== 0)
103
+ return undefined;
104
+ try {
105
+ const crew = Buffer.from(encoded, 'hex').toString('utf8');
106
+ return encodeCrewRosterFilename(crew) === filename ? crew : undefined;
107
+ }
108
+ catch {
109
+ return undefined;
110
+ }
111
+ }
112
+ /** Map a root-level legacy filename to its literal crew name. */
113
+ export function crewNameFromRosterFilename(filename) {
114
+ return filename.endsWith('.json') ? filename.slice(0, -'.json'.length) : undefined;
115
+ }
116
+ /** Map a filename within the codec-only directory back to its crew name. */
117
+ export function crewNameFromEncodedRosterFilename(filename) {
118
+ return decodeCrewRosterFilename(filename);
119
+ }
120
+ /**
121
+ * Return the authoritative crew identity stored by a codec-only roster.
122
+ * Reversible basenames are deliberately not authority by themselves: an old
123
+ * nested legacy path can have the same basename. Every codec file therefore
124
+ * carries the crew it owns, and that identity must reproduce the basename.
125
+ */
126
+ export function crewNameFromEncodedRosterFile(path) {
127
+ const filename = basename(path);
128
+ try {
129
+ const parsed = JSON.parse(readFileSync(path, 'utf8'));
130
+ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed))
131
+ return undefined;
132
+ const crew = parsed['crew'];
133
+ return typeof crew === 'string' && codecFilenameMatchesCrew(filename, crew) ? crew : undefined;
134
+ }
135
+ catch {
136
+ return undefined;
137
+ }
138
+ }
139
+ function containedCrewPath(dir, filename) {
140
+ const root = resolve(dir);
141
+ const path = resolve(root, filename);
142
+ const fromRoot = relative(root, path);
143
+ if (fromRoot === '' || fromRoot === '..' || fromRoot.startsWith(`..${sep}`) || isAbsolute(fromRoot)) {
144
+ throw new Error(`unsafe crew roster path for ${JSON.stringify(filename)}`);
145
+ }
146
+ return path;
147
+ }
148
+ /** Directory reserved for the reversible codec; disjoint from legacy files. */
149
+ export function encodedCrewRosterDir(env) {
150
+ return containedCrewPath(crewRosterDir(env), CREW_ROSTER_ENCODED_DIR);
151
+ }
152
+ function encodedCrewRosterPath(env, crew) {
153
+ return containedCrewPath(encodedCrewRosterDir(env), encodeCrewRosterFilename(crew));
154
+ }
155
+ const LOCAL_CREW_ROSTER_FILESYSTEM = {
156
+ pathExists: existsSync,
157
+ directoryEntries: (path) => readdirSync(path),
158
+ };
159
+ /**
160
+ * `existsSync` folds case on APFS/NTFS. Before preserving an old literal file,
161
+ * walk its contained path and require every on-disk component to have exactly
162
+ * the requested spelling. This is what makes Delivery and delivery distinct
163
+ * crew identities even after either one was created first.
164
+ */
165
+ function hasExactContainedPath(root, path, filesystem) {
166
+ if (!filesystem.pathExists(path))
167
+ return false;
168
+ const fromRoot = relative(root, path);
169
+ if (fromRoot === '' || fromRoot === '..' || fromRoot.startsWith(`..${sep}`) || isAbsolute(fromRoot))
170
+ return false;
171
+ let current = root;
172
+ for (const component of fromRoot.split(sep)) {
173
+ try {
174
+ if (!filesystem.directoryEntries(current).includes(component))
175
+ return false;
176
+ }
177
+ catch {
178
+ return false;
179
+ }
180
+ current = join(current, component);
181
+ }
182
+ return true;
183
+ }
184
+ /**
185
+ * Return the owner of a codec file placed directly in the codec directory.
186
+ *
187
+ * A codec basename alone never establishes ownership; the filename's decoded
188
+ * identity must also reproduce its canonical codec path. Keeping this check
189
+ * beside resolution prevents a corrupt or hand-renamed codec file from
190
+ * aliasing another crew's strongest layer.
191
+ */
192
+ function codecOwnerAtDirectoryRoot(env, codecDir, path) {
193
+ if (!samePath(dirname(path), codecDir))
194
+ return undefined;
195
+ const crew = crewNameFromEncodedRosterFile(path);
196
+ return crew !== undefined && codecFilenameMatchesCrew(basename(path), crew) ? crew : undefined;
197
+ }
198
+ /**
199
+ * Return an owned codec target with its exact filesystem spelling. The current
200
+ * namespace is codec-only for a full codec basename, so an unowned file there
201
+ * is a corrupt/colliding strongest layer and must fail closed instead of being
202
+ * mistaken for an existing roster of the requested crew by setup or agent-run.
203
+ */
204
+ function ownedCodecRosterPath(env, crew, codecDir, filesystem) {
205
+ const root = crewRosterDir(env);
206
+ const path = containedCrewPath(codecDir, encodeCrewRosterFilename(crew));
207
+ if (!hasExactContainedPath(root, path, filesystem))
208
+ return undefined;
209
+ const owner = codecOwnerAtDirectoryRoot(env, codecDir, path);
210
+ if (owner === crew)
211
+ return path;
212
+ const found = owner === undefined ? 'no valid recorded crew' : JSON.stringify(owner);
213
+ throw new Error(`invalid crew roster at ${path}: codec file is owned by ${found}, expected ${JSON.stringify(crew)}`);
214
+ }
215
+ function isWindowsNativePathComponent(component) {
216
+ const hasControlCharacter = [...component].some((char) => char.codePointAt(0) < 0x20);
217
+ return component !== '' && component !== '.' && component !== '..' &&
218
+ !hasControlCharacter && !/[<>:"|?*]/u.test(component) && !/[. ]$/u.test(component) &&
219
+ !WINDOWS_RESERVED_BASENAMES.test(component);
220
+ }
221
+ /**
222
+ * Whether this crew can be CREATED as one literal filename. This is separate
223
+ * from legacy discovery: a pre-codec nested `crews/foo/bar.json` is a valid
224
+ * POSIX/Windows path to preserve, but a new `foo/bar` roster must use the
225
+ * codec-only directory instead of growing a hand-edited subtree.
226
+ */
227
+ export function isNativeCrewRosterFilename(crew, platform = process.platform) {
228
+ if (crew === '' || crew.includes('/') || crew.includes('\\') || crew.includes('\0') || Buffer.byteLength(`${crew}.json`, 'utf8') > MAX_CREW_ROSTER_FILENAME_BYTES)
229
+ return false;
230
+ return platform !== 'win32' || isWindowsNativePathComponent(crew);
231
+ }
232
+ /**
233
+ * A contained deployed legacy path may be preserved even when new files
234
+ * encode it. This deliberately follows the pre-codec `path.join` behavior:
235
+ * `foo/../bar`, `foo/./bar`, and `foo//bar` preserve their existing normalized
236
+ * target when it remains below `crews/`. Segment eligibility is a
237
+ * rule for creating new names (`isNativeCrewRosterFilename`), never a reason
238
+ * to stop reading an existing strongest-layer override.
239
+ */
240
+ function legacyCrewRosterPath(dir, crew) {
241
+ if (crew === '' || crew.includes('\0'))
242
+ return undefined;
243
+ try {
244
+ // Preserve the literal pre-codec construction before proving containment.
245
+ // Unlike resolve(), join() treats a leading separator in the crew as a
246
+ // nested path below `dir`, so `/bar` retains an existing `crews/bar.json`.
247
+ return containedCrewPath(dir, join(dir, `${crew}.json`));
248
+ }
249
+ catch {
250
+ // A traversal-shaped name that would leave `crews/` is never a legacy
251
+ // migration target; it receives an encoded path below.
252
+ return undefined;
253
+ }
254
+ }
255
+ function samePath(a, b) {
256
+ return resolve(a) === resolve(b);
257
+ }
258
+ function legacyCrewNameForPath(root, path) {
259
+ const relativePath = relative(root, path);
260
+ if (!relativePath.endsWith('.json'))
261
+ return undefined;
262
+ // Hub crew names use `/` even on Windows; legacy paths use the current
263
+ // platform separator. This is the only representation conversion, and the
264
+ // final round trip through `legacyCrewRosterPath` proves containment.
265
+ const crew = relativePath.slice(0, -'.json'.length).split(sep).join('/');
266
+ const resolved = legacyCrewRosterPath(root, crew);
267
+ return resolved !== undefined && samePath(resolved, path) ? crew : undefined;
268
+ }
269
+ function walkCrewRosterFiles(root, current, visit, skipDirectories) {
270
+ for (const entry of readdirSync(current, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
271
+ const path = join(current, entry.name);
272
+ if (entry.isDirectory()) {
273
+ if (current === root && skipDirectories?.has(entry.name))
274
+ continue;
275
+ walkCrewRosterFiles(root, path, visit, skipDirectories);
276
+ }
277
+ else if (entry.isFile() && entry.name.endsWith('.json')) {
278
+ visit(path);
279
+ }
280
+ }
281
+ }
282
+ /**
283
+ * Classify one file inside the codec directory. A matching JSON `crew`
284
+ * identity plus its canonical codec path is the only authority that makes it
285
+ * encoded; all other contained files remain ordinary nested legacy entries,
286
+ * which prevents the directory name from becoming an ownership claim.
287
+ */
288
+ function classifyCodecDirectoryFile(env, root, codecDir, path) {
289
+ const crew = relative(codecDir, path) === basename(path)
290
+ ? crewNameFromEncodedRosterFile(path)
291
+ : undefined;
292
+ if (crew !== undefined && codecFilenameMatchesCrew(basename(path), crew)) {
293
+ return { crew, path, kind: 'encoded' };
294
+ }
295
+ const legacyCrew = legacyCrewNameForPath(root, path);
296
+ return legacyCrew === undefined ? undefined : { crew: legacyCrew, path, kind: 'legacy' };
297
+ }
298
+ /**
299
+ * Discover crew roster files for global doctor diagnostics. Routing never calls
300
+ * this function: it directly probes only the requested crew's legacy and codec
301
+ * targets, so an unrelated unreadable or racing subtree cannot refuse an
302
+ * agent-run before settings and hub layers get a chance to participate.
303
+ */
304
+ export function discoverCrewRosterFiles(env) {
305
+ const root = crewRosterDir(env);
306
+ if (!existsSync(root))
307
+ return [];
308
+ const found = [];
309
+ const encodedDir = encodedCrewRosterDir(env);
310
+ // Literal/nested legacy files are independent of codec parsing. Keep the
311
+ // codec directory out of this pass; it is considered below, where an
312
+ // explicit owner distinguishes an encoded file from a shorter legacy entry.
313
+ walkCrewRosterFiles(root, root, (path) => {
314
+ const crew = legacyCrewNameForPath(root, path);
315
+ if (crew !== undefined)
316
+ found.push({ crew, path, kind: 'legacy' });
317
+ }, new Set([CREW_ROSTER_ENCODED_DIR]));
318
+ if (existsSync(encodedDir)) {
319
+ walkCrewRosterFiles(encodedDir, encodedDir, (path) => {
320
+ const file = classifyCodecDirectoryFile(env, root, encodedDir, path);
321
+ if (file !== undefined)
322
+ found.push(file);
323
+ });
324
+ }
325
+ return found;
326
+ }
327
+ /**
328
+ * The `crew` identity setup records in every file it materializes. A pre-codec
329
+ * operator file has no identity and keeps resolving for any crew whose
330
+ * join-normalized path lands on it — exactly the pre-codec behavior. A file
331
+ * that cannot be parsed makes no claim either way; the preserved path then
332
+ * fails closed in readCrewRoster instead of silently falling to a codec
333
+ * target.
334
+ */
335
+ function declaredCrewOwner(path) {
336
+ try {
337
+ const parsed = JSON.parse(readFileSync(path, 'utf8'));
338
+ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed))
339
+ return undefined;
340
+ const crew = parsed['crew'];
341
+ return typeof crew === 'string' ? crew : undefined;
342
+ }
343
+ catch {
344
+ return undefined;
345
+ }
346
+ }
347
+ /**
348
+ * Resolve an untrusted crew name to one file beneath `crews/`, preserving a
349
+ * pre-codec operator file when it exists. This makes an upgrade non-destructive
350
+ * for names such as spaces, colons, percent signs, and Unicode; setup uses this
351
+ * same resolver, so it cannot create an empty encoded duplicate over an existing
352
+ * strongest-layer override.
353
+ *
354
+ * A new name that is safe as a single native path component remains a literal
355
+ * root-level file for rollback compatibility. Unsafe or too-wide names use the
356
+ * codec-only subdirectory plus `encodeCrewRosterFilename`; hub names are always
357
+ * data, never path segments, and every target has an explicit containment
358
+ * proof.
359
+ */
360
+ export function crewRosterPath(env, crew, filesystem = LOCAL_CREW_ROSTER_FILESYSTEM) {
361
+ const dir = crewRosterDir(env);
362
+ const legacy = legacyCrewRosterPath(dir, crew);
363
+ // A case-folded sibling counts as occupied even when it is not an exact
364
+ // legacy match. Returning that literal spelling would make setup's later
365
+ // EEXIST look like an operator roster for this different crew.
366
+ const legacyOccupied = legacy !== undefined && filesystem.pathExists(legacy);
367
+ if (legacy !== undefined && hasExactContainedPath(dir, legacy, filesystem)) {
368
+ // Distinct hub-valid names can join-normalize onto one legacy path
369
+ // (`bar` and `foo/../bar`). Setup records the owning crew in every file
370
+ // it creates; honor that identity so the first-materialized crew cannot
371
+ // hand its strongest layer to the second. An ownerless file is a
372
+ // pre-codec operator roster and keeps the pre-codec join semantics.
373
+ const owner = declaredCrewOwner(legacy);
374
+ if (owner === undefined || owner === crew)
375
+ return legacy;
376
+ }
377
+ const encodedDir = encodedCrewRosterDir(env);
378
+ const ownedEncoded = ownedCodecRosterPath(env, crew, encodedDir, filesystem);
379
+ if (ownedEncoded !== undefined)
380
+ return ownedEncoded;
381
+ const encoded = encodedCrewRosterPath(env, crew);
382
+ return isNativeCrewRosterFilename(crew) && !legacyOccupied ? legacy : encoded;
383
+ }
57
384
  /**
58
385
  * The machine's layers for one crew, strongest first. When no crew is known,
59
386
  * only the machine-global `settings.json` roster participates.
60
387
  */
61
388
  export function machineRosterLayers(env, crew) {
62
- const configDir = owenloopConfigDir(env);
63
389
  const layers = [];
64
390
  if (crew !== undefined) {
65
- const path = join(configDir, 'crews', `${crew}.json`);
391
+ // Do not use discovery as the read gate. Bounded hash filenames need the
392
+ // JSON's `crew` field for doctor to associate them with their intended
393
+ // name, but that field is unavailable precisely when a truncated/corrupt
394
+ // strongest-layer file must fail closed. The requested crew resolves its
395
+ // own deterministic target, and any existing target is always parsed by
396
+ // readCrewRoster.
397
+ const path = crewRosterPath(env, crew);
66
398
  layers.push({
67
399
  source: `machine crews/${crew}.json`,
68
400
  path,
69
401
  ...(existsSync(path) ? { roster: readCrewRoster(path) } : {}),
70
402
  });
71
403
  }
72
- const path = join(configDir, 'settings.json');
404
+ const path = join(owenloopConfigDir(env), 'settings.json');
73
405
  const settings = loadSettings(env);
74
406
  layers.push({
75
407
  source: 'machine settings.json',
@@ -78,3 +410,30 @@ export function machineRosterLayers(env, crew) {
78
410
  });
79
411
  return layers;
80
412
  }
413
+ /** One composition point shared by the offline child and CLI diagnostics. */
414
+ export function effectiveRosterLayers(env, crew, hub) {
415
+ const machine = machineRosterLayers(env, crew);
416
+ if (hub.origin === undefined || hub.origin.trim() === '') {
417
+ const unavailable = (source) => ({ source: `${source} (unavailable: no hub origin configured)` });
418
+ return crew === undefined
419
+ ? [...machine, unavailable('hub org-global')]
420
+ : [...machine, unavailable(`hub crew ${crew}`), unavailable('hub org-global')];
421
+ }
422
+ return [...machine, ...hubRosterLayers(readHubRosterCache(env, hub.origin, hub.account), crew)];
423
+ }
424
+ /** Explain all weaker rows hidden by a stronger layer, without changing merge. */
425
+ export function explainRosterShadows(layers) {
426
+ const result = Object.create(null);
427
+ for (const layer of layers) {
428
+ if (layer.roster === undefined)
429
+ continue;
430
+ for (const [capability, candidates] of Object.entries(layer.roster)) {
431
+ const existing = result[capability];
432
+ if (existing === undefined)
433
+ result[capability] = { winner: layer.source, shadowed: [] };
434
+ else
435
+ existing.shadowed.push({ source: layer.source, candidateCount: candidates.length });
436
+ }
437
+ }
438
+ return result;
439
+ }
@@ -0,0 +1,17 @@
1
+ type Env = NodeJS.ProcessEnv;
2
+ type Hub = {
3
+ origin: string | undefined;
4
+ account: string;
5
+ };
6
+ /** The capability keys one crew's effective merged roster serves. Never throws. */
7
+ export declare function servingSetForCrew(env: Env, crew: string | undefined, hub: Hub): string[];
8
+ /** The union across every crew the shift serves. Never throws. */
9
+ export declare function computeServeCapabilities(opts: {
10
+ env: Env;
11
+ /** The shift's live serve crews. EMPTY MEANS ALL CREWS, never none. */
12
+ crews: readonly string[];
13
+ hub: Hub;
14
+ /** One line per unreadable crew. Optional; default no-op. */
15
+ warn?: (message: string) => void;
16
+ }): string[];
17
+ export {};
@@ -0,0 +1,79 @@
1
+ /**
2
+ * The capability keys a shift can advertise from its effective roster layers.
3
+ *
4
+ * This is deliberately advisory: roster resolution and authorization remain
5
+ * with the worker. A broken local roster must never stop a shift's poll loop.
6
+ */
7
+ import { discoverCrewRosterFiles, effectiveRosterLayers, mergeRosterLayers } from "./roster.js";
8
+ import { readHubRosterCache } from "./hub-roster-cache.js";
9
+ function errorMessage(error) {
10
+ try {
11
+ return error instanceof Error ? error.message : String(error);
12
+ }
13
+ catch {
14
+ return 'unknown error';
15
+ }
16
+ }
17
+ function reportWarning(warn, message) {
18
+ try {
19
+ warn?.(message);
20
+ }
21
+ catch {
22
+ // A diagnostic callback must not violate this module's totality contract.
23
+ }
24
+ }
25
+ function servingSetForCrewUnsafe(env, crew, hub) {
26
+ return Object.keys(mergeRosterLayers(effectiveRosterLayers(env, crew, hub)));
27
+ }
28
+ /** The capability keys one crew's effective merged roster serves. Never throws. */
29
+ export function servingSetForCrew(env, crew, hub) {
30
+ try {
31
+ return servingSetForCrewUnsafe(env, crew, hub).sort();
32
+ }
33
+ catch {
34
+ return [];
35
+ }
36
+ }
37
+ /** The union across every crew the shift serves. Never throws. */
38
+ export function computeServeCapabilities(opts) {
39
+ const scopes = new Set();
40
+ if (opts.crews.length > 0) {
41
+ for (const crew of opts.crews)
42
+ scopes.add(crew);
43
+ }
44
+ else {
45
+ try {
46
+ for (const file of discoverCrewRosterFiles(opts.env))
47
+ scopes.add(file.crew);
48
+ }
49
+ catch (error) {
50
+ reportWarning(opts.warn, `could not discover local crew rosters: ${errorMessage(error)}`);
51
+ }
52
+ if (opts.hub.origin !== undefined && opts.hub.origin.trim() !== '') {
53
+ try {
54
+ const cached = readHubRosterCache(opts.env, opts.hub.origin, opts.hub.account);
55
+ if (cached.kind === 'hit') {
56
+ for (const crew of cached.data.crews) {
57
+ if (crew.crewName !== null)
58
+ scopes.add(crew.crewName);
59
+ }
60
+ }
61
+ }
62
+ catch (error) {
63
+ reportWarning(opts.warn, `could not read cached hub rosters: ${errorMessage(error)}`);
64
+ }
65
+ }
66
+ }
67
+ const result = new Set();
68
+ const targets = scopes.size === 0 ? [undefined] : [...scopes];
69
+ for (const crew of targets) {
70
+ try {
71
+ for (const capability of servingSetForCrewUnsafe(opts.env, crew, opts.hub))
72
+ result.add(capability);
73
+ }
74
+ catch (error) {
75
+ reportWarning(opts.warn, `could not compute serving capabilities for ${crew === undefined ? 'crew-independent layers' : JSON.stringify(crew)}: ${errorMessage(error)}`);
76
+ }
77
+ }
78
+ return [...result].sort();
79
+ }
@@ -16,6 +16,7 @@ import { type Roster } from '../agent/capability-model.ts';
16
16
  * - `shiftLogMaxAgeMs` — worker-log retention in ms; below `--log-max-age`
17
17
  * and `OWENLOOP_SHIFT_LOG_MAX_AGE_MS`, above the 14-day default.
18
18
  * - `commandRouting` — who runs `executor: 'command'` steps this machine sees.
19
+ * - `execReserve` — slots within dispatch cap reserved from agent work.
19
20
  * - `defPolicy` — local publication trust policy (`warn` by default).
20
21
  */
21
22
  export interface Settings {
@@ -70,6 +71,18 @@ export interface Settings {
70
71
  * both. Fallback below `--max-agents`.
71
72
  */
72
73
  maxConcurrentAgents?: number;
74
+ /**
75
+ * Slots inside `dispatchCap` that `agent-run` children may not occupy, so
76
+ * an exec/command order always has room. A non-negative integer: `0`
77
+ * disables the reserve and restores the pre-reserve behavior. Fallback below
78
+ * `--exec-reserve`; default 1.
79
+ */
80
+ execReserve?: number;
81
+ /**
82
+ * How long a shift may retain an undispatchable claim locally before
83
+ * returning it to the hub. Default 0: never retain it locally.
84
+ */
85
+ localQueueHoldMs?: number;
73
86
  /**
74
87
  * Phase 4 — the root under which per-RUN agent working directories live.
75
88
  *
@@ -126,7 +139,7 @@ export interface Settings {
126
139
  roster?: Roster;
127
140
  }
128
141
  /** The known settings keys, in the order `owenloop work settings` prints them. */
129
- export declare const KNOWN_SETTINGS_KEYS: readonly ["hubOrigin", "cacheDir", "stateDir", "dispatchCap", "shiftLogDir", "shiftLogMaxAgeMs", "commandRouting", "defPolicy", "artifactPolicy", "maxConcurrentAgents", "workRoot", "workRepo", "allowedWorkdirRoots", "roster"];
142
+ export declare const KNOWN_SETTINGS_KEYS: readonly ["hubOrigin", "cacheDir", "stateDir", "dispatchCap", "shiftLogDir", "shiftLogMaxAgeMs", "commandRouting", "defPolicy", "artifactPolicy", "maxConcurrentAgents", "execReserve", "localQueueHoldMs", "workRoot", "workRepo", "allowedWorkdirRoots", "roster"];
130
143
  /**
131
144
  * Keys owenloop still RECOGNIZES but no longer acts on. Each one produces a
132
145
  * warning naming what replaced it, and is excluded from `unrecognized` so the
@@ -28,6 +28,8 @@ export const KNOWN_SETTINGS_KEYS = [
28
28
  'defPolicy',
29
29
  'artifactPolicy',
30
30
  'maxConcurrentAgents',
31
+ 'execReserve',
32
+ 'localQueueHoldMs',
31
33
  'workRoot',
32
34
  'workRepo',
33
35
  'allowedWorkdirRoots',
@@ -96,6 +98,18 @@ export function validateSettings(raw, path) {
96
98
  throw bad('maxConcurrentAgents', 'a positive integer', v);
97
99
  }
98
100
  }
101
+ if ('execReserve' in obj) {
102
+ const v = obj['execReserve'];
103
+ if (typeof v !== 'number' || !Number.isInteger(v) || v < 0) {
104
+ throw bad('execReserve', 'a non-negative integer', v);
105
+ }
106
+ }
107
+ if ('localQueueHoldMs' in obj) {
108
+ const v = obj['localQueueHoldMs'];
109
+ if (typeof v !== 'number' || !Number.isInteger(v) || v < 0) {
110
+ throw bad('localQueueHoldMs', 'a non-negative integer', v);
111
+ }
112
+ }
99
113
  if ('allowedWorkdirRoots' in obj) {
100
114
  // ABSOLUTE PATHS ONLY, and that is the one rule worth a hard error rather
101
115
  // than a warning. A relative entry would resolve against whatever directory