owenloop 0.5.8 → 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.
- package/CHANGELOG.md +25 -0
- package/README.md +4 -2
- package/dist/packages/work/src/agent/loop.d.ts +23 -8
- package/dist/packages/work/src/agent/loop.js +48 -6
- package/dist/packages/work/src/consumed-verifier.js +6 -17
- package/dist/packages/work/src/exec/loop.d.ts +1 -1
- package/dist/packages/work/src/exec/loop.js +181 -32
- package/dist/packages/work/src/exec/receipt.d.ts +7 -7
- package/dist/packages/work/src/exec/receipt.js +6 -6
- package/dist/packages/work/src/harness/claude.js +100 -0
- package/dist/packages/work/src/hub/client.d.ts +19 -4
- package/dist/packages/work/src/hub/client.js +7 -3
- package/dist/packages/work/src/hub/types.d.ts +84 -0
- package/dist/packages/work/src/main.js +1 -0
- package/dist/packages/work/src/roles/agent-run.js +19 -22
- package/dist/packages/work/src/roles/exec.js +2 -0
- package/dist/packages/work/src/roles/settings.js +2 -0
- package/dist/packages/work/src/roles/shift.js +14 -2
- package/dist/packages/work/src/roles/util.d.ts +1 -0
- package/dist/packages/work/src/roles/util.js +10 -0
- package/dist/packages/work/src/settings/hub-roster-cache.d.ts +68 -0
- package/dist/packages/work/src/settings/hub-roster-cache.js +370 -0
- package/dist/packages/work/src/settings/roster.d.ts +84 -0
- package/dist/packages/work/src/settings/roster.js +364 -5
- package/dist/packages/work/src/settings/serving.d.ts +17 -0
- package/dist/packages/work/src/settings/serving.js +79 -0
- package/dist/packages/work/src/settings/settings.d.ts +14 -1
- package/dist/packages/work/src/settings/settings.js +14 -0
- package/dist/packages/work/src/shift/loop.d.ts +108 -5
- package/dist/packages/work/src/shift/loop.js +299 -51
- package/dist/packages/work/src/shift/protocol.d.ts +7 -5
- package/dist/packages/work/src/shift/runtime.d.ts +15 -0
- package/dist/packages/work/src/shift/runtime.js +94 -4
- package/dist/packages/work/src/shift/server.js +2 -0
- package/dist/packages/work/src/shift/spawn.d.ts +17 -2
- package/dist/packages/work/src/shift/spawn.js +16 -13
- package/dist/packages/work/src/shift/state.d.ts +29 -2
- package/dist/packages/work/src/shift/state.js +45 -15
- package/dist/packages/work/src/usage.d.ts +1 -1
- package/dist/packages/work/src/usage.js +7 -1
- package/dist/packages/work/src/util/modifier-init.d.ts +7 -0
- package/dist/packages/work/src/util/modifier-init.js +73 -0
- package/dist/src/bundle/tar.d.ts +9 -4
- package/dist/src/bundle/tar.js +9 -4
- package/dist/src/capabilities.d.ts +6 -0
- package/dist/src/cli.d.ts +14 -1
- package/dist/src/cli.js +687 -75
- package/dist/src/config-dir.d.ts +1 -1
- package/dist/src/config-dir.js +1 -1
- package/dist/src/crypto/index.d.ts +1 -1
- package/dist/src/crypto/index.js +1 -1
- package/dist/src/crypto/org-root.d.ts +30 -12
- package/dist/src/crypto/org-root.js +162 -14
- package/dist/src/crypto/records.d.ts +2 -0
- package/dist/src/crypto/records.js +2 -0
- package/dist/src/defs.d.ts +6 -1
- package/dist/src/defs.js +203 -8
- package/dist/src/engine.d.ts +42 -7
- package/dist/src/engine.js +158 -16
- package/dist/src/index.d.ts +4 -4
- package/dist/src/index.js +2 -2
- package/dist/src/mcp/serve.d.ts +22 -0
- package/dist/src/mcp/serve.js +88 -8
- package/dist/src/model.d.ts +2 -0
- package/dist/src/model.js +32 -25
- package/dist/src/order-resolver.d.ts +1 -0
- package/dist/src/order-resolver.js +8 -1
- package/dist/src/schemas/index.d.ts +11 -0
- package/dist/src/schemas/order.v1.schema.json +7 -1
- package/dist/src/store.d.ts +5 -0
- package/dist/src/store.js +43 -8
- package/dist/src/types.d.ts +40 -3
- package/docs/authoring.md +90 -2
- package/docs/bundles.md +26 -2
- package/docs/cli.md +170 -28
- package/docs/crypto.md +19 -3
- package/docs/design.md +70 -1
- package/docs/routing.md +189 -34
- package/docs/shift-logs.md +20 -9
- package/docs/wire-contracts.md +50 -7
- package/examples/workflows/delivery.yaml +31 -14
- package/examples/workflows/ship.yaml +10 -2
- package/package.json +1 -1
- package/plugins/claude-code/plugin/.claude-plugin/plugin.json +1 -1
- package/plugins/claude-code/plugin/.mcp.json +1 -1
- package/plugins/codex/plugins/owenloop/.codex-plugin/plugin.json +1 -1
- package/plugins/codex/plugins/owenloop/.mcp.json +1 -1
|
@@ -0,0 +1,370 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Disk cache for the hub-owned (therefore weakest) roster layers.
|
|
3
|
+
*
|
|
4
|
+
* A shift daemon refreshes this file, while the short-lived `agent-run` child
|
|
5
|
+
* reads it without contacting the hub. The cache intentionally has no TTL:
|
|
6
|
+
* stale hub rows still lose to every machine-owned row, while rejecting an old
|
|
7
|
+
* cache would turn an ordinary hub outage into an order refusal.
|
|
8
|
+
*/
|
|
9
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
10
|
+
import { closeSync, existsSync, mkdirSync, openSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
|
|
11
|
+
import { isAbsolute, join, relative, resolve, sep } from 'node:path';
|
|
12
|
+
import { validateRoster } from "../agent/capability-model.js";
|
|
13
|
+
import { owenloopConfigDir } from "../../../../src/config-dir.js";
|
|
14
|
+
import { normalizeOrigin } from "../../../../src/hub.js";
|
|
15
|
+
export const DEFAULT_HUB_ROSTER_SYNC_TIMEOUT_MS = 10_000;
|
|
16
|
+
const MAX_HUB_IDENTIFIER_LENGTH = 200;
|
|
17
|
+
const MAX_HUB_CAPABILITY_LENGTH = 64;
|
|
18
|
+
const MAX_HUB_CREW_LENGTH = 64;
|
|
19
|
+
const MAX_HUB_CANDIDATES = 32;
|
|
20
|
+
const HUB_EFFORTS = new Set(['low', 'medium', 'high', 'xhigh', 'max']);
|
|
21
|
+
function isHubIdentifier(value) {
|
|
22
|
+
return typeof value === 'string' && value.length > 0 && value.length <= MAX_HUB_IDENTIFIER_LENGTH && value.trim() === value;
|
|
23
|
+
}
|
|
24
|
+
function isHubCapability(value) {
|
|
25
|
+
return value.length > 0 && value.length <= MAX_HUB_CAPABILITY_LENGTH && value.trim() === value && !value.startsWith('personal:');
|
|
26
|
+
}
|
|
27
|
+
function isHubCrewName(value) {
|
|
28
|
+
// Slash, backslash, and dot segments are valid hub data. The filesystem
|
|
29
|
+
// resolver handles them later; this wire validator only mirrors the hub's
|
|
30
|
+
// trimmed/non-empty/max-length crew rule.
|
|
31
|
+
return typeof value === 'string' && value.length > 0 && value.length <= MAX_HUB_CREW_LENGTH && value.trim() === value;
|
|
32
|
+
}
|
|
33
|
+
function validateHubRoster(roster, context) {
|
|
34
|
+
validateRoster(roster, context);
|
|
35
|
+
for (const [capability, candidates] of Object.entries(roster)) {
|
|
36
|
+
if (!isHubCapability(capability))
|
|
37
|
+
throw new Error(`${context}: invalid capability`);
|
|
38
|
+
if (!Array.isArray(candidates) || candidates.length > MAX_HUB_CANDIDATES) {
|
|
39
|
+
throw new Error(`${context}: invalid candidate count`);
|
|
40
|
+
}
|
|
41
|
+
const seen = new Set();
|
|
42
|
+
for (const candidate of candidates) {
|
|
43
|
+
const row = candidate;
|
|
44
|
+
if (!isHubIdentifier(row['harness']) || !isHubIdentifier(row['model']) || !HUB_EFFORTS.has(row['effort'])) {
|
|
45
|
+
throw new Error(`${context}: invalid candidate`);
|
|
46
|
+
}
|
|
47
|
+
const key = JSON.stringify([row['harness'], row['model'], row['effort']]);
|
|
48
|
+
if (seen.has(key))
|
|
49
|
+
throw new Error(`${context}: duplicate candidate`);
|
|
50
|
+
seen.add(key);
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
return roster;
|
|
54
|
+
}
|
|
55
|
+
/** Bound a refresh even when a test seam or non-fetch client ignores abort. */
|
|
56
|
+
export async function withHubRosterSyncTimeout(run, timeoutMs = DEFAULT_HUB_ROSTER_SYNC_TIMEOUT_MS) {
|
|
57
|
+
const controller = new AbortController();
|
|
58
|
+
let timer;
|
|
59
|
+
const timeout = new Promise((_resolve, reject) => {
|
|
60
|
+
timer = setTimeout(() => {
|
|
61
|
+
const error = new Error(`hub roster sync timed out after ${timeoutMs}ms`);
|
|
62
|
+
// Abort carries the same terminal error so an abort-aware transport and
|
|
63
|
+
// the explicit race report one stable, useful timeout outcome.
|
|
64
|
+
controller.abort(error);
|
|
65
|
+
reject(error);
|
|
66
|
+
}, timeoutMs);
|
|
67
|
+
});
|
|
68
|
+
try {
|
|
69
|
+
return await Promise.race([run(controller.signal), timeout]);
|
|
70
|
+
}
|
|
71
|
+
finally {
|
|
72
|
+
if (timer !== undefined)
|
|
73
|
+
clearTimeout(timer);
|
|
74
|
+
// A composite refresh can reject as soon as one request fails while a
|
|
75
|
+
// sibling fetch is still waiting. Always cancel on settlement so that
|
|
76
|
+
// sibling cannot outlive this refresh (and accumulate across polls).
|
|
77
|
+
if (!controller.signal.aborted)
|
|
78
|
+
controller.abort(new Error('hub roster sync finished'));
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
export function hubRosterCacheDir(env) {
|
|
82
|
+
return join(owenloopConfigDir(env), 'hub-rosters');
|
|
83
|
+
}
|
|
84
|
+
/** A filename is an index only; readers always verify the fields inside it. */
|
|
85
|
+
export function sanitizeOriginForFilename(origin) {
|
|
86
|
+
return origin.toLowerCase().replace(/[^a-z0-9.-]/g, '-');
|
|
87
|
+
}
|
|
88
|
+
/** Org ids are hub data, so they are filename-encoded rather than interpolated. */
|
|
89
|
+
export function sanitizeOrgIdForFilename(orgId) {
|
|
90
|
+
return encodeURIComponent(orgId);
|
|
91
|
+
}
|
|
92
|
+
/**
|
|
93
|
+
* An on-disk cache key must be injective, not merely path-safe. The historical
|
|
94
|
+
* origin sanitizer remains exported for diagnostics/backward compatibility,
|
|
95
|
+
* but it deliberately cannot be the key: distinct origins can sanitize to the
|
|
96
|
+
* same string. A fixed-size digest avoids both those collisions and a
|
|
97
|
+
* filesystem component overflow for a valid long origin. The file body is
|
|
98
|
+
* still fully parsed and matched, so the digest is only an index.
|
|
99
|
+
*/
|
|
100
|
+
function cacheKey(origin, orgId, account) {
|
|
101
|
+
return createHash('sha256')
|
|
102
|
+
.update(origin, 'utf8')
|
|
103
|
+
.update('\0', 'utf8')
|
|
104
|
+
.update(orgId, 'utf8')
|
|
105
|
+
.update('\0', 'utf8')
|
|
106
|
+
.update(account, 'utf8')
|
|
107
|
+
.digest('base64url');
|
|
108
|
+
}
|
|
109
|
+
function containedChildPath(dir, filename) {
|
|
110
|
+
const root = resolve(dir);
|
|
111
|
+
const path = resolve(root, filename);
|
|
112
|
+
const fromRoot = relative(root, path);
|
|
113
|
+
if (fromRoot === '' || fromRoot === '..' || fromRoot.startsWith(`..${sep}`) || isAbsolute(fromRoot)) {
|
|
114
|
+
throw new Error(`unsafe hub roster cache path for ${JSON.stringify(filename)}`);
|
|
115
|
+
}
|
|
116
|
+
return path;
|
|
117
|
+
}
|
|
118
|
+
export function hubRosterCachePath(env, origin, orgId, account = 'default') {
|
|
119
|
+
const canonicalOrigin = normalizeOrigin(origin);
|
|
120
|
+
return containedChildPath(hubRosterCacheDir(env), `cache-v1--${cacheKey(canonicalOrigin, orgId, account)}.json`);
|
|
121
|
+
}
|
|
122
|
+
function message(error) {
|
|
123
|
+
return error instanceof Error ? error.message : String(error);
|
|
124
|
+
}
|
|
125
|
+
function asRecord(value) {
|
|
126
|
+
return typeof value === 'object' && value !== null && !Array.isArray(value)
|
|
127
|
+
? value
|
|
128
|
+
: undefined;
|
|
129
|
+
}
|
|
130
|
+
/** Decode and validate every field readers rely on. It deliberately throws so
|
|
131
|
+
* `readHubRosterCache` can turn each failure into a non-throwing miss. */
|
|
132
|
+
function parseEntry(value) {
|
|
133
|
+
const row = asRecord(value);
|
|
134
|
+
if (row === undefined)
|
|
135
|
+
throw new Error('cache root must be an object');
|
|
136
|
+
if (row['version'] !== 1)
|
|
137
|
+
throw new Error(`unsupported cache version ${String(row['version'])}`);
|
|
138
|
+
for (const key of ['origin', 'orgId', 'account']) {
|
|
139
|
+
if (typeof row[key] !== 'string' || row[key].trim() === '')
|
|
140
|
+
throw new Error(`invalid cache ${key}`);
|
|
141
|
+
}
|
|
142
|
+
// The deployed whoami/roster contract permits an unnamed organization. Do
|
|
143
|
+
// not turn its deliberate empty display name into a failed cache refresh.
|
|
144
|
+
if (typeof row['orgName'] !== 'string')
|
|
145
|
+
throw new Error('invalid cache orgName');
|
|
146
|
+
let origin;
|
|
147
|
+
try {
|
|
148
|
+
origin = normalizeOrigin(row['origin']);
|
|
149
|
+
}
|
|
150
|
+
catch (error) {
|
|
151
|
+
throw new Error(`invalid cache origin: ${message(error)}`);
|
|
152
|
+
}
|
|
153
|
+
if (typeof row['fetchedAt'] !== 'number' || !Number.isFinite(row['fetchedAt'])) {
|
|
154
|
+
throw new Error('invalid cache fetchedAt');
|
|
155
|
+
}
|
|
156
|
+
// `Date` accepts finite values outside its TimeClip range, but `toISOString`
|
|
157
|
+
// then throws. The timestamp is displayed while constructing hub layers, so
|
|
158
|
+
// make that display operation part of cache validation rather than letting a
|
|
159
|
+
// corrupt disk cache escape the deliberately non-throwing reader.
|
|
160
|
+
try {
|
|
161
|
+
new Date(row['fetchedAt']).toISOString();
|
|
162
|
+
}
|
|
163
|
+
catch {
|
|
164
|
+
throw new Error('invalid cache fetchedAt');
|
|
165
|
+
}
|
|
166
|
+
const global = asRecord(row['global']);
|
|
167
|
+
if (global === undefined)
|
|
168
|
+
throw new Error('invalid roster shape: global must be an object');
|
|
169
|
+
const crews = row['crews'];
|
|
170
|
+
if (!Array.isArray(crews))
|
|
171
|
+
throw new Error('invalid roster shape: crews must be an array');
|
|
172
|
+
try {
|
|
173
|
+
validateHubRoster(global, 'global');
|
|
174
|
+
for (const [index, rawCrew] of crews.entries()) {
|
|
175
|
+
const crew = asRecord(rawCrew);
|
|
176
|
+
if (crew === undefined || typeof crew['crewId'] !== 'string' || crew['crewId'] === '' ||
|
|
177
|
+
!(isHubCrewName(crew['crewName']) || crew['crewName'] === null)) {
|
|
178
|
+
throw new Error(`crews[${index}] must have crewId and crewName`);
|
|
179
|
+
}
|
|
180
|
+
const roster = asRecord(crew['roster']);
|
|
181
|
+
if (roster === undefined)
|
|
182
|
+
throw new Error(`crews[${index}].roster must be an object`);
|
|
183
|
+
validateHubRoster(roster, `crews[${index}].roster`);
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
catch (error) {
|
|
187
|
+
throw new Error(`invalid roster shape: ${message(error)}`);
|
|
188
|
+
}
|
|
189
|
+
return {
|
|
190
|
+
version: 1,
|
|
191
|
+
origin,
|
|
192
|
+
orgId: row['orgId'],
|
|
193
|
+
orgName: row['orgName'],
|
|
194
|
+
account: row['account'],
|
|
195
|
+
fetchedAt: row['fetchedAt'],
|
|
196
|
+
global: global,
|
|
197
|
+
crews: crews.map((raw) => {
|
|
198
|
+
const crew = raw;
|
|
199
|
+
return { crewId: crew['crewId'], crewName: crew['crewName'], roster: crew['roster'] };
|
|
200
|
+
}),
|
|
201
|
+
};
|
|
202
|
+
}
|
|
203
|
+
/** Atomically write a verified snapshot, then drop a prior org snapshot for
|
|
204
|
+
* the same origin/account pair so a re-pointed token cannot be served stale. */
|
|
205
|
+
export function writeHubRosterCache(env, entry, options = {}) {
|
|
206
|
+
const verified = parseEntry(entry);
|
|
207
|
+
const dir = hubRosterCacheDir(env);
|
|
208
|
+
mkdirSync(dir, { recursive: true });
|
|
209
|
+
// Account is part of the key as well as the reader's validity predicate:
|
|
210
|
+
// two agent accounts can be attached to the same hub org concurrently.
|
|
211
|
+
const path = hubRosterCachePath(env, verified.origin, verified.orgId, verified.account);
|
|
212
|
+
const temp = `${path}.${(options.tempSuffix ?? randomUUID)()}.tmp`;
|
|
213
|
+
const contents = `${JSON.stringify(verified, null, 2)}\n`;
|
|
214
|
+
let tempOwned = false;
|
|
215
|
+
let fd;
|
|
216
|
+
try {
|
|
217
|
+
// Exclusive creation establishes ownership before a cleanup path can touch
|
|
218
|
+
// the name. A UUID collision must leave the other writer's temp intact.
|
|
219
|
+
fd = openSync(temp, 'wx', 0o600);
|
|
220
|
+
tempOwned = true;
|
|
221
|
+
(options.writeTemp ?? ((openFd, text) => writeFileSync(openFd, text, 'utf8')))(fd, contents);
|
|
222
|
+
closeSync(fd);
|
|
223
|
+
fd = undefined;
|
|
224
|
+
(options.rename ?? renameSync)(temp, path);
|
|
225
|
+
}
|
|
226
|
+
catch (error) {
|
|
227
|
+
if (fd !== undefined) {
|
|
228
|
+
try {
|
|
229
|
+
closeSync(fd);
|
|
230
|
+
}
|
|
231
|
+
catch {
|
|
232
|
+
// Preserve the original write/rename failure; cleanup below still runs.
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
if (tempOwned) {
|
|
236
|
+
try {
|
|
237
|
+
rmSync(temp, { force: true });
|
|
238
|
+
}
|
|
239
|
+
catch {
|
|
240
|
+
// A later refresh can retry. Never replace the I/O failure that caused
|
|
241
|
+
// this owned-temp cleanup with a less useful cleanup failure.
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
throw error;
|
|
245
|
+
}
|
|
246
|
+
for (const name of readdirSync(dir)) {
|
|
247
|
+
const sibling = join(dir, name);
|
|
248
|
+
if (sibling === path || !name.endsWith('.json'))
|
|
249
|
+
continue;
|
|
250
|
+
let other;
|
|
251
|
+
try {
|
|
252
|
+
other = parseEntry(JSON.parse(readFileSync(sibling, 'utf8')));
|
|
253
|
+
}
|
|
254
|
+
catch {
|
|
255
|
+
// A malformed unrelated file stays visible to an operator; it cannot make
|
|
256
|
+
// a successful new snapshot fail.
|
|
257
|
+
continue;
|
|
258
|
+
}
|
|
259
|
+
if (other.origin === verified.origin && other.account === verified.account && other.orgId !== verified.orgId) {
|
|
260
|
+
// Deliberately outside the parse catch. Once the new snapshot has landed,
|
|
261
|
+
// a failed prune must surface to the caller rather than masquerading as a
|
|
262
|
+
// completed repoint; readers still select the newer valid file below.
|
|
263
|
+
(options.remove ?? ((candidate) => rmSync(candidate)))(sibling);
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
/**
|
|
268
|
+
* Find a cache by the information an offline child actually has (origin plus
|
|
269
|
+
* account), never by trusting its filename. Every bad cache state degrades to
|
|
270
|
+
* a miss; this is deliberately the opposite of `readCrewRoster`.
|
|
271
|
+
*/
|
|
272
|
+
export function readHubRosterCache(env, origin, account) {
|
|
273
|
+
const dir = hubRosterCacheDir(env);
|
|
274
|
+
if (!existsSync(dir))
|
|
275
|
+
return { kind: 'miss', path: dir, reason: `no cache file at ${dir}` };
|
|
276
|
+
let expectedOrigin;
|
|
277
|
+
try {
|
|
278
|
+
expectedOrigin = normalizeOrigin(origin);
|
|
279
|
+
}
|
|
280
|
+
catch (error) {
|
|
281
|
+
return { kind: 'miss', path: dir, reason: `invalid cache origin: ${message(error)}` };
|
|
282
|
+
}
|
|
283
|
+
let firstReason;
|
|
284
|
+
let names;
|
|
285
|
+
try {
|
|
286
|
+
names = readdirSync(dir).filter((name) => name.endsWith('.json')).sort();
|
|
287
|
+
}
|
|
288
|
+
catch (error) {
|
|
289
|
+
return { kind: 'miss', path: dir, reason: `unreadable cache directory: ${message(error)}` };
|
|
290
|
+
}
|
|
291
|
+
if (names.length === 0)
|
|
292
|
+
return { kind: 'miss', path: dir, reason: `no cache file at ${dir}` };
|
|
293
|
+
let newest;
|
|
294
|
+
for (const name of names) {
|
|
295
|
+
const path = join(dir, name);
|
|
296
|
+
let raw;
|
|
297
|
+
try {
|
|
298
|
+
raw = JSON.parse(readFileSync(path, 'utf8'));
|
|
299
|
+
}
|
|
300
|
+
catch (error) {
|
|
301
|
+
firstReason ??= `unreadable JSON: ${message(error)}`;
|
|
302
|
+
continue;
|
|
303
|
+
}
|
|
304
|
+
let entry;
|
|
305
|
+
try {
|
|
306
|
+
entry = parseEntry(raw);
|
|
307
|
+
}
|
|
308
|
+
catch (error) {
|
|
309
|
+
const detail = message(error);
|
|
310
|
+
firstReason ??= detail.startsWith('unsupported cache version') || detail.startsWith('invalid roster shape:')
|
|
311
|
+
? detail
|
|
312
|
+
: `invalid roster shape: ${detail}`;
|
|
313
|
+
continue;
|
|
314
|
+
}
|
|
315
|
+
if (entry.origin !== expectedOrigin) {
|
|
316
|
+
firstReason ??= `cache is for origin ${entry.origin}, expected ${expectedOrigin}`;
|
|
317
|
+
continue;
|
|
318
|
+
}
|
|
319
|
+
if (entry.account !== account) {
|
|
320
|
+
firstReason ??= `cache is for account ${entry.account}, expected ${account}`;
|
|
321
|
+
continue;
|
|
322
|
+
}
|
|
323
|
+
if (newest === undefined ||
|
|
324
|
+
entry.fetchedAt > newest.data.fetchedAt ||
|
|
325
|
+
(entry.fetchedAt === newest.data.fetchedAt && path < newest.path)) {
|
|
326
|
+
newest = { kind: 'hit', path, data: entry };
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
if (newest !== undefined)
|
|
330
|
+
return newest;
|
|
331
|
+
return { kind: 'miss', path: dir, reason: firstReason ?? `no cache file at ${dir}` };
|
|
332
|
+
}
|
|
333
|
+
function sourceWithFetch(prefix, entry) {
|
|
334
|
+
return `${prefix} (org ${entry.orgName}, fetched ${new Date(entry.fetchedAt).toISOString()})`;
|
|
335
|
+
}
|
|
336
|
+
/** The hub's two layers, strongest first. Missing cache remains visible as
|
|
337
|
+
* absent layers, so `roster show` can explain an offline child's routing. */
|
|
338
|
+
export function hubRosterLayers(read, crew) {
|
|
339
|
+
if (read.kind === 'miss') {
|
|
340
|
+
const unavailable = (label) => ({ source: `${label} (unavailable: ${read.reason})`, path: read.path });
|
|
341
|
+
return crew === undefined
|
|
342
|
+
? [unavailable('hub org-global')]
|
|
343
|
+
: [unavailable(`hub crew ${crew}`), unavailable('hub org-global')];
|
|
344
|
+
}
|
|
345
|
+
const layers = [];
|
|
346
|
+
if (crew !== undefined) {
|
|
347
|
+
const match = read.data.crews.find((candidate) => candidate.crewName === crew);
|
|
348
|
+
layers.push(match === undefined
|
|
349
|
+
? { source: `hub crew ${crew} — no hub roster for this crew (org ${read.data.orgName}, fetched ${new Date(read.data.fetchedAt).toISOString()})`, path: read.path }
|
|
350
|
+
: { source: sourceWithFetch(`hub crew ${crew}`, read.data), path: read.path, roster: match.roster });
|
|
351
|
+
}
|
|
352
|
+
layers.push({ source: sourceWithFetch('hub org-global', read.data), path: read.path, roster: read.data.global });
|
|
353
|
+
return layers;
|
|
354
|
+
}
|
|
355
|
+
/** Refresh the disk snapshot with the same agent credential a shift uses. */
|
|
356
|
+
export async function syncHubRosterCache(deps) {
|
|
357
|
+
if (deps.client.getRosters === undefined)
|
|
358
|
+
throw new Error('hub client does not support get_rosters');
|
|
359
|
+
const [identity, rosters] = await Promise.all([deps.client.whoami(deps.signal), deps.client.getRosters(deps.signal)]);
|
|
360
|
+
writeHubRosterCache(deps.env, {
|
|
361
|
+
version: 1,
|
|
362
|
+
origin: deps.origin,
|
|
363
|
+
orgId: identity.orgId,
|
|
364
|
+
orgName: identity.orgName,
|
|
365
|
+
account: deps.account,
|
|
366
|
+
fetchedAt: Date.now(),
|
|
367
|
+
global: rosters.global,
|
|
368
|
+
crews: rosters.crews,
|
|
369
|
+
});
|
|
370
|
+
}
|
|
@@ -7,6 +7,14 @@ export interface RosterLayer {
|
|
|
7
7
|
/** Absent when the layer does not exist on this machine. */
|
|
8
8
|
roster?: Roster;
|
|
9
9
|
}
|
|
10
|
+
/** One on-disk strongest-layer roster the resolver can actually select. */
|
|
11
|
+
export interface CrewRosterFile {
|
|
12
|
+
/** The exact hub crew name represented by this file. */
|
|
13
|
+
crew: string;
|
|
14
|
+
path: string;
|
|
15
|
+
/** Literal/nested legacy path, or the dedicated codec namespace. */
|
|
16
|
+
kind: 'legacy' | 'encoded';
|
|
17
|
+
}
|
|
10
18
|
export interface MergedRosterEntry {
|
|
11
19
|
candidates: readonly RosterCandidate[];
|
|
12
20
|
source: string;
|
|
@@ -14,8 +22,84 @@ export interface MergedRosterEntry {
|
|
|
14
22
|
export type MergedRoster = Readonly<Record<string, MergedRosterEntry>>;
|
|
15
23
|
/** Merge key-by-key. `layers` is ordered STRONGEST FIRST. */
|
|
16
24
|
export declare function mergeRosterLayers(layers: readonly RosterLayer[]): MergedRoster;
|
|
25
|
+
/** The directory containing operator-owned strongest-layer crew files. */
|
|
26
|
+
export declare function crewRosterDir(env: Record<string, string | undefined>): string;
|
|
27
|
+
/**
|
|
28
|
+
* Path-segment-safe filename codec for crews that cannot use their legacy
|
|
29
|
+
* literal filename. Its lowercase-hex alphabet is stable under filesystem
|
|
30
|
+
* case folding: distinct UTF-8 crew names therefore cannot alias after a
|
|
31
|
+
* case-insensitive filesystem has accepted the first spelling. Extremely large
|
|
32
|
+
* names use a fixed-size content-addressed form; setup writes the crew name in
|
|
33
|
+
* the file's note, while ordinary safe names remain literal for rollback.
|
|
34
|
+
*/
|
|
35
|
+
export declare function encodeCrewRosterFilename(crew: string): string;
|
|
36
|
+
/** Decode only an exact reversible codec output; ordinary legacy basenames stay literal. */
|
|
37
|
+
export declare function decodeCrewRosterFilename(filename: string): string | undefined;
|
|
38
|
+
/** Map a root-level legacy filename to its literal crew name. */
|
|
39
|
+
export declare function crewNameFromRosterFilename(filename: string): string | undefined;
|
|
40
|
+
/** Map a filename within the codec-only directory back to its crew name. */
|
|
41
|
+
export declare function crewNameFromEncodedRosterFilename(filename: string): string | undefined;
|
|
42
|
+
/**
|
|
43
|
+
* Return the authoritative crew identity stored by a codec-only roster.
|
|
44
|
+
* Reversible basenames are deliberately not authority by themselves: an old
|
|
45
|
+
* nested legacy path can have the same basename. Every codec file therefore
|
|
46
|
+
* carries the crew it owns, and that identity must reproduce the basename.
|
|
47
|
+
*/
|
|
48
|
+
export declare function crewNameFromEncodedRosterFile(path: string): string | undefined;
|
|
49
|
+
/** Directory reserved for the reversible codec; disjoint from legacy files. */
|
|
50
|
+
export declare function encodedCrewRosterDir(env: Record<string, string | undefined>): string;
|
|
51
|
+
/**
|
|
52
|
+
* The filesystem operations needed to prove a legacy spelling is exact.
|
|
53
|
+
* The optional seam lets regression tests emulate an exists() lookup on a
|
|
54
|
+
* case-insensitive filesystem while retaining the directory's actual spelling.
|
|
55
|
+
*/
|
|
56
|
+
export interface CrewRosterFilesystem {
|
|
57
|
+
pathExists(path: string): boolean;
|
|
58
|
+
directoryEntries(path: string): readonly string[];
|
|
59
|
+
}
|
|
60
|
+
/**
|
|
61
|
+
* Whether this crew can be CREATED as one literal filename. This is separate
|
|
62
|
+
* from legacy discovery: a pre-codec nested `crews/foo/bar.json` is a valid
|
|
63
|
+
* POSIX/Windows path to preserve, but a new `foo/bar` roster must use the
|
|
64
|
+
* codec-only directory instead of growing a hand-edited subtree.
|
|
65
|
+
*/
|
|
66
|
+
export declare function isNativeCrewRosterFilename(crew: string, platform?: NodeJS.Platform): boolean;
|
|
67
|
+
/**
|
|
68
|
+
* Discover crew roster files for global doctor diagnostics. Routing never calls
|
|
69
|
+
* this function: it directly probes only the requested crew's legacy and codec
|
|
70
|
+
* targets, so an unrelated unreadable or racing subtree cannot refuse an
|
|
71
|
+
* agent-run before settings and hub layers get a chance to participate.
|
|
72
|
+
*/
|
|
73
|
+
export declare function discoverCrewRosterFiles(env: Record<string, string | undefined>): CrewRosterFile[];
|
|
74
|
+
/**
|
|
75
|
+
* Resolve an untrusted crew name to one file beneath `crews/`, preserving a
|
|
76
|
+
* pre-codec operator file when it exists. This makes an upgrade non-destructive
|
|
77
|
+
* for names such as spaces, colons, percent signs, and Unicode; setup uses this
|
|
78
|
+
* same resolver, so it cannot create an empty encoded duplicate over an existing
|
|
79
|
+
* strongest-layer override.
|
|
80
|
+
*
|
|
81
|
+
* A new name that is safe as a single native path component remains a literal
|
|
82
|
+
* root-level file for rollback compatibility. Unsafe or too-wide names use the
|
|
83
|
+
* codec-only subdirectory plus `encodeCrewRosterFilename`; hub names are always
|
|
84
|
+
* data, never path segments, and every target has an explicit containment
|
|
85
|
+
* proof.
|
|
86
|
+
*/
|
|
87
|
+
export declare function crewRosterPath(env: Record<string, string | undefined>, crew: string, filesystem?: CrewRosterFilesystem): string;
|
|
17
88
|
/**
|
|
18
89
|
* The machine's layers for one crew, strongest first. When no crew is known,
|
|
19
90
|
* only the machine-global `settings.json` roster participates.
|
|
20
91
|
*/
|
|
21
92
|
export declare function machineRosterLayers(env: Record<string, string | undefined>, crew: string | undefined): RosterLayer[];
|
|
93
|
+
/** One composition point shared by the offline child and CLI diagnostics. */
|
|
94
|
+
export declare function effectiveRosterLayers(env: Record<string, string | undefined>, crew: string | undefined, hub: {
|
|
95
|
+
origin: string | undefined;
|
|
96
|
+
account: string;
|
|
97
|
+
}): RosterLayer[];
|
|
98
|
+
/** Explain all weaker rows hidden by a stronger layer, without changing merge. */
|
|
99
|
+
export declare function explainRosterShadows(layers: readonly RosterLayer[]): Record<string, {
|
|
100
|
+
winner: string;
|
|
101
|
+
shadowed: Array<{
|
|
102
|
+
source: string;
|
|
103
|
+
candidateCount: number;
|
|
104
|
+
}>;
|
|
105
|
+
}>;
|