owenloop 0.5.7 → 0.5.9

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 (111) hide show
  1. package/CHANGELOG.md +41 -0
  2. package/README.md +7 -8
  3. package/dist/packages/work/src/agent/capability-model.d.ts +64 -82
  4. package/dist/packages/work/src/agent/capability-model.js +94 -91
  5. package/dist/packages/work/src/agent/loop.d.ts +55 -26
  6. package/dist/packages/work/src/agent/loop.js +144 -50
  7. package/dist/packages/work/src/bundle/types.d.ts +3 -3
  8. package/dist/packages/work/src/consumed-verifier.js +6 -17
  9. package/dist/packages/work/src/exec/loop.d.ts +1 -1
  10. package/dist/packages/work/src/exec/loop.js +206 -35
  11. package/dist/packages/work/src/exec/receipt.d.ts +7 -7
  12. package/dist/packages/work/src/exec/receipt.js +6 -6
  13. package/dist/packages/work/src/harness/child-env.js +4 -5
  14. package/dist/packages/work/src/harness/claude.js +100 -0
  15. package/dist/packages/work/src/harness/codex.js +3 -4
  16. package/dist/packages/work/src/harness/session-store.d.ts +63 -3
  17. package/dist/packages/work/src/harness/session-store.js +104 -9
  18. package/dist/packages/work/src/hub/client.d.ts +19 -4
  19. package/dist/packages/work/src/hub/client.js +7 -3
  20. package/dist/packages/work/src/hub/types.d.ts +87 -3
  21. package/dist/packages/work/src/main.js +1 -0
  22. package/dist/packages/work/src/roles/agent-run.js +46 -43
  23. package/dist/packages/work/src/roles/exec.js +2 -0
  24. package/dist/packages/work/src/roles/sessions.d.ts +3 -2
  25. package/dist/packages/work/src/roles/sessions.js +9 -2
  26. package/dist/packages/work/src/roles/settings.js +3 -1
  27. package/dist/packages/work/src/roles/shift.js +14 -2
  28. package/dist/packages/work/src/roles/util.d.ts +1 -0
  29. package/dist/packages/work/src/roles/util.js +10 -0
  30. package/dist/packages/work/src/settings/hub-roster-cache.d.ts +68 -0
  31. package/dist/packages/work/src/settings/hub-roster-cache.js +370 -0
  32. package/dist/packages/work/src/settings/roster.d.ts +105 -0
  33. package/dist/packages/work/src/settings/roster.js +439 -0
  34. package/dist/packages/work/src/settings/serving.d.ts +17 -0
  35. package/dist/packages/work/src/settings/serving.js +79 -0
  36. package/dist/packages/work/src/settings/settings.d.ts +25 -24
  37. package/dist/packages/work/src/settings/settings.js +29 -33
  38. package/dist/packages/work/src/shift/loop.d.ts +108 -5
  39. package/dist/packages/work/src/shift/loop.js +299 -51
  40. package/dist/packages/work/src/shift/protocol.d.ts +7 -5
  41. package/dist/packages/work/src/shift/runtime.d.ts +15 -0
  42. package/dist/packages/work/src/shift/runtime.js +95 -13
  43. package/dist/packages/work/src/shift/server.js +2 -0
  44. package/dist/packages/work/src/shift/spawn.d.ts +18 -50
  45. package/dist/packages/work/src/shift/spawn.js +30 -65
  46. package/dist/packages/work/src/shift/state.d.ts +29 -2
  47. package/dist/packages/work/src/shift/state.js +45 -15
  48. package/dist/packages/work/src/usage.d.ts +1 -1
  49. package/dist/packages/work/src/usage.js +10 -5
  50. package/dist/packages/work/src/util/modifier-init.d.ts +7 -0
  51. package/dist/packages/work/src/util/modifier-init.js +73 -0
  52. package/dist/src/bundle/tar.d.ts +9 -4
  53. package/dist/src/bundle/tar.js +9 -4
  54. package/dist/src/capabilities.d.ts +50 -0
  55. package/dist/src/capabilities.js +38 -0
  56. package/dist/src/cli.d.ts +15 -1
  57. package/dist/src/cli.js +1099 -32
  58. package/dist/src/config-dir.d.ts +14 -19
  59. package/dist/src/config-dir.js +16 -24
  60. package/dist/src/credentials.d.ts +1 -1
  61. package/dist/src/credentials.js +1 -1
  62. package/dist/src/crypto/index.d.ts +1 -1
  63. package/dist/src/crypto/index.js +1 -1
  64. package/dist/src/crypto/org-root.d.ts +30 -12
  65. package/dist/src/crypto/org-root.js +162 -14
  66. package/dist/src/crypto/records.d.ts +3 -0
  67. package/dist/src/crypto/records.js +8 -0
  68. package/dist/src/crypto/trust-roots.d.ts +2 -2
  69. package/dist/src/crypto/trust-roots.js +2 -2
  70. package/dist/src/defs.d.ts +6 -1
  71. package/dist/src/defs.js +203 -8
  72. package/dist/src/engine.d.ts +55 -6
  73. package/dist/src/engine.js +172 -22
  74. package/dist/src/global-config.d.ts +4 -7
  75. package/dist/src/global-config.js +4 -7
  76. package/dist/src/hub.d.ts +207 -5
  77. package/dist/src/hub.js +263 -3
  78. package/dist/src/index.d.ts +5 -5
  79. package/dist/src/index.js +3 -3
  80. package/dist/src/mcp/serve.d.ts +22 -0
  81. package/dist/src/mcp/serve.js +88 -8
  82. package/dist/src/model.d.ts +2 -0
  83. package/dist/src/model.js +32 -25
  84. package/dist/src/order-resolver.d.ts +1 -0
  85. package/dist/src/order-resolver.js +8 -1
  86. package/dist/src/schemas/index.d.ts +19 -0
  87. package/dist/src/schemas/order.v1.schema.json +13 -2
  88. package/dist/src/store/pre-commit-verifier.js +1 -1
  89. package/dist/src/store.d.ts +5 -0
  90. package/dist/src/store.js +43 -8
  91. package/dist/src/types.d.ts +64 -7
  92. package/dist/src/work-settings.d.ts +2 -4
  93. package/dist/src/work-settings.js +2 -4
  94. package/docs/agent-runner.md +2 -2
  95. package/docs/authoring.md +90 -2
  96. package/docs/bundles.md +29 -3
  97. package/docs/cli.md +456 -120
  98. package/docs/crypto.md +32 -16
  99. package/docs/design.md +70 -1
  100. package/docs/routing.md +762 -0
  101. package/docs/shift-logs.md +37 -10
  102. package/docs/wire-contracts.md +50 -7
  103. package/examples/workflows/delivery.yaml +31 -14
  104. package/examples/workflows/ship.yaml +10 -2
  105. package/package.json +1 -1
  106. package/plugins/claude-code/plugin/.claude-plugin/plugin.json +1 -1
  107. package/plugins/claude-code/plugin/.mcp.json +1 -1
  108. package/plugins/claude-code/plugin/skills/author/SKILL.md +1 -2
  109. package/plugins/codex/plugins/owenloop/.codex-plugin/plugin.json +1 -1
  110. package/plugins/codex/plugins/owenloop/.mcp.json +1 -1
  111. package/plugins/codex/plugins/owenloop/skills/author/SKILL.md +1 -2
@@ -0,0 +1,439 @@
1
+ /**
2
+ * Crew-roster disk layout and layered merge.
3
+ *
4
+ * This module owns where machine roster layers come from and their
5
+ * strongest-first cascade. Shape validation and capability lookup remain in
6
+ * `agent/capability-model.ts`.
7
+ */
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';
11
+ import { validateRoster, } from "../agent/capability-model.js";
12
+ import { owenloopConfigDir } from "../../../../src/config-dir.js";
13
+ import { loadSettings } from "./settings.js";
14
+ import { hubRosterLayers, readHubRosterCache } from "./hub-roster-cache.js";
15
+ /** Merge key-by-key. `layers` is ordered STRONGEST FIRST. */
16
+ export function mergeRosterLayers(layers) {
17
+ // Capability names are arbitrary strings, including Object.prototype names.
18
+ // A null prototype keeps every own key routable and makes `__proto__` data,
19
+ // rather than a request to mutate the result's prototype.
20
+ const merged = Object.create(null);
21
+ for (const layer of layers) {
22
+ if (layer.roster === undefined)
23
+ continue;
24
+ for (const [capability, candidates] of Object.entries(layer.roster)) {
25
+ if (!Object.prototype.hasOwnProperty.call(merged, capability)) {
26
+ // Candidate arrays are atomic: a winning layer replaces every weaker
27
+ // candidate, never concatenating or element-merging with it.
28
+ merged[capability] = { candidates, source: layer.source };
29
+ }
30
+ }
31
+ }
32
+ return merged;
33
+ }
34
+ function readCrewRoster(path) {
35
+ let parsed;
36
+ try {
37
+ parsed = JSON.parse(readFileSync(path, 'utf8'));
38
+ }
39
+ catch (error) {
40
+ const message = error instanceof Error ? error.message : String(error);
41
+ throw new Error(`invalid crew roster at ${path}: ${message}`);
42
+ }
43
+ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
44
+ throw new Error(`invalid crew roster at ${path}: expected an object with a 'roster' key`);
45
+ }
46
+ const roster = parsed['roster'];
47
+ if (typeof roster !== 'object' || roster === null || Array.isArray(roster)) {
48
+ throw new Error(`invalid crew roster at ${path}: 'roster' must be a JSON object`);
49
+ }
50
+ try {
51
+ validateRoster(roster, 'roster');
52
+ }
53
+ catch (error) {
54
+ const message = error instanceof Error ? error.message : String(error);
55
+ throw new Error(`invalid crew roster at ${path}: ${message}`);
56
+ }
57
+ return roster;
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
+ }
384
+ /**
385
+ * The machine's layers for one crew, strongest first. When no crew is known,
386
+ * only the machine-global `settings.json` roster participates.
387
+ */
388
+ export function machineRosterLayers(env, crew) {
389
+ const layers = [];
390
+ if (crew !== undefined) {
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);
398
+ layers.push({
399
+ source: `machine crews/${crew}.json`,
400
+ path,
401
+ ...(existsSync(path) ? { roster: readCrewRoster(path) } : {}),
402
+ });
403
+ }
404
+ const path = join(owenloopConfigDir(env), 'settings.json');
405
+ const settings = loadSettings(env);
406
+ layers.push({
407
+ source: 'machine settings.json',
408
+ path,
409
+ ...(settings.roster !== undefined ? { roster: settings.roster } : {}),
410
+ });
411
+ return layers;
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
+ }
@@ -1,4 +1,4 @@
1
- import { type CapabilityModelRow } from '../agent/capability-model.ts';
1
+ import { type Roster } from '../agent/capability-model.ts';
2
2
  /**
3
3
  * The settings surface — every knob optional, a missing file loading as `{}`.
4
4
  * Each field is the lowest-precedence fallback for a role option (a CLI flag
@@ -16,6 +16,7 @@ import { type CapabilityModelRow } 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
  *
@@ -119,28 +132,22 @@ export interface Settings {
119
132
  */
120
133
  allowedWorkdirRoots?: string[];
121
134
  /**
122
- * How THIS machine serves each capability: a flat map from capability to
123
- * `{model, effort}`, keyed by the composed capability (`wise:deep`) or by the
124
- * bare name (`wise`). See `src/agent/capability-model.ts` for the lookup rule
125
- * and for why this replaced `tierMap`/`tierProfiles` outright.
126
- *
127
- * Carry a bare row per capability the shift's crews serve. The bare row is
128
- * what makes a hub name-match fallback order resolvable — the hub can stamp
129
- * `wise:deep` on an order claimed by a crew bound only to `wise:standard`,
130
- * and that shift has no `wise:deep` row by construction.
135
+ * Machine-global crew roster: each capability maps to an ordered list of
136
+ * `{harness, model, effort}` candidates. A crew-specific roster file can
137
+ * replace individual capability rows above this layer.
131
138
  */
132
- capabilityModels?: Record<string, CapabilityModelRow>;
139
+ roster?: Roster;
133
140
  }
134
141
  /** The known settings keys, in the order `owenloop work settings` prints them. */
135
- export declare const KNOWN_SETTINGS_KEYS: readonly ["hubOrigin", "cacheDir", "stateDir", "dispatchCap", "shiftLogDir", "shiftLogMaxAgeMs", "commandRouting", "defPolicy", "artifactPolicy", "maxConcurrentAgents", "workRoot", "workRepo", "allowedWorkdirRoots", "capabilityModels"];
142
+ export declare const KNOWN_SETTINGS_KEYS: readonly ["hubOrigin", "cacheDir", "stateDir", "dispatchCap", "shiftLogDir", "shiftLogMaxAgeMs", "commandRouting", "defPolicy", "artifactPolicy", "maxConcurrentAgents", "execReserve", "localQueueHoldMs", "workRoot", "workRepo", "allowedWorkdirRoots", "roster"];
136
143
  /**
137
144
  * Keys owenloop still RECOGNIZES but no longer acts on. Each one produces a
138
145
  * warning naming what replaced it, and is excluded from `unrecognized` so the
139
146
  * same key is not also reported as a likely typo.
140
147
  *
141
- * Distinct from `tierMap`/`tierProfiles`, which are a hard error: ignoring
142
- * those would leave the shift with no capability map and refuse every order,
143
- * whereas ignoring these changes nothing about how a shift runs.
148
+ * Distinct from unrecognized keys, which are surfaced as likely typos. These
149
+ * are recognized legacy settings whose removal leaves current shift behavior
150
+ * unchanged, so they remain a warning rather than a load failure.
144
151
  */
145
152
  export declare const RETIRED_IGNORED_KEYS: readonly ["escalateAt", "escalationExtensionKey"];
146
153
  /**
@@ -176,15 +183,9 @@ export interface SettingsInspection extends ValidatedSettings {
176
183
  * Resolve the settings file path from the caller's env, through the one shared
177
184
  * ladder in `src/config-dir.ts`: `$OWENLOOP_CONFIG_DIR/settings.json` when
178
185
  * `OWENLOOP_CONFIG_DIR` is set and non-blank (it must be absolute), else
179
- * `$XDG_CONFIG_HOME/owenloop/settings.json`, else
180
- * `$HOME/.config/owenloop/settings.json`. Throws when no rung yields a value
181
- * rather than guessing a home directory.
182
- *
183
- * `OWENLOOP_CONFIG_DIR` is the variable an operator running SEVERAL shifts on
184
- * one machine should reach for. Setting `XDG_CONFIG_HOME` per shift also works,
185
- * but a shift spreads its whole environment into every worker and every command
186
- * step's child, so relocating `XDG_CONFIG_HOME` relocates the config of `gh`,
187
- * `git`, `gcloud`, and everything else those steps shell out to.
186
+ * `$HOME/.owenloop/settings.json`. Throws when no rung yields a value rather
187
+ * than guessing a home directory. `OWENLOOP_CONFIG_DIR` remains for tests and
188
+ * throwaway isolation, not normal operator configuration.
188
189
  */
189
190
  export declare function settingsPath(env: Record<string, string | undefined>): string;
190
191
  /**