omp-superagent 0.1.17 → 0.1.19

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 (82) hide show
  1. package/DESIGN.md +15 -12
  2. package/config.example.json +4 -1
  3. package/docs/OPERATIONS.en.md +205 -59
  4. package/docs/OPERATIONS.md +173 -47
  5. package/docs/design/execution.md +119 -37
  6. package/docs/design/messaging.md +160 -45
  7. package/docs/releases/0.1.18.md +10 -0
  8. package/docs/releases/0.1.19.md +10 -0
  9. package/gateway/bin/omp-gateway-darwin-arm64 +0 -0
  10. package/gateway/bin/omp-gateway-darwin-x64 +0 -0
  11. package/gateway/bin/omp-gateway-linux-arm64 +0 -0
  12. package/gateway/bin/omp-gateway-linux-x64 +0 -0
  13. package/host-owner/bin/omp-host-owner-darwin-arm64 +0 -0
  14. package/host-owner/bin/omp-host-owner-darwin-x64 +0 -0
  15. package/host-owner/bin/omp-host-owner-linux-arm64 +0 -0
  16. package/host-owner/bin/omp-host-owner-linux-x64 +0 -0
  17. package/package.json +1 -1
  18. package/skills/head/SKILL.md +6 -5
  19. package/skills/head/references/model-selection.md +8 -22
  20. package/skills/head/references/routing.md +36 -17
  21. package/skills/lane/SKILL.md +24 -76
  22. package/skills/lane/references/workflow.md +7 -94
  23. package/src/cli.ts +36 -16
  24. package/src/config/config.ts +21 -2
  25. package/src/contracts.ts +66 -7
  26. package/src/cron/cron-jobs.ts +135 -92
  27. package/src/cron/cron-pr-intake.ts +18 -11
  28. package/src/extension.ts +25 -10
  29. package/src/gateway/gateway-client.ts +3 -1
  30. package/src/host-extension.ts +76 -8
  31. package/src/lane/lane-report.ts +1 -1
  32. package/src/lane/lane-rows.ts +2 -1
  33. package/src/lane/workflow.ts +12 -6
  34. package/src/lane-extension.ts +4 -21
  35. package/src/managed-super-probe.ts +21 -15
  36. package/src/messaging/messenger-command-catalog.json +1 -1
  37. package/src/messaging/messenger-commands.ts +8 -3
  38. package/src/messaging/result-attachment.ts +77 -19
  39. package/src/messaging/slack-context.ts +50 -0
  40. package/src/messaging/written-directives.ts +56 -0
  41. package/src/omp/exit-record.ts +27 -0
  42. package/src/omp/host-protocol.ts +20 -0
  43. package/src/omp/host.ts +73 -20
  44. package/src/omp/installed-omp.ts +15 -12
  45. package/src/omp/managed-super.ts +135 -65
  46. package/src/omp/superkit-skills.ts +15 -2
  47. package/src/pr/pr-intake-order.ts +62 -0
  48. package/src/pr/pr-intake-review.ts +49 -31
  49. package/src/pr/pr-intake-work.ts +3 -2
  50. package/src/routing/message-order.ts +22 -1
  51. package/src/routing/topic-request.ts +48 -4
  52. package/src/runtime/controller.ts +968 -338
  53. package/src/runtime/deferred-routing.ts +12 -4
  54. package/src/runtime/dm-timeline.ts +3 -3
  55. package/src/runtime/inbound-attachments.ts +70 -0
  56. package/src/runtime/local-host-fence.ts +85 -0
  57. package/src/runtime/model-journal.ts +14 -9
  58. package/src/runtime/native-frames.ts +5 -1
  59. package/src/runtime/result-attachments.ts +151 -24
  60. package/src/runtime/worker-result-download.ts +36 -0
  61. package/src/storage/deferred-routing.ts +25 -4
  62. package/src/storage/store.ts +445 -75
  63. package/src/worker/worker-checkout.ts +89 -9
  64. package/src/worker/worker-destination.ts +8 -7
  65. package/src/worker/worker-doctor.ts +29 -9
  66. package/src/worker/worker-enrollment.ts +44 -12
  67. package/src/worker/worker-git-startup.ts +157 -0
  68. package/src/worker/worker-host.ts +16 -26
  69. package/src/worker/worker-ledger.ts +42 -18
  70. package/src/worker/worker-placement-intent.ts +13 -0
  71. package/src/worker/worker-placement.ts +204 -28
  72. package/src/worker/worker-profile.ts +18 -65
  73. package/src/worker/worker-project-startup.ts +106 -0
  74. package/src/worker/worker-registration.ts +85 -30
  75. package/src/worker/worker-repository.ts +55 -6
  76. package/src/worker/worker-request.ts +13 -6
  77. package/src/worker/worker-result-attachments.ts +185 -0
  78. package/src/worker/worker-result-wire.ts +12 -0
  79. package/src/worker/worker-service.ts +51 -23
  80. package/src/worker/worker-trust.ts +19 -4
  81. package/src/worker/worker-wire.ts +47 -14
  82. package/upstream/super.json +2 -3
@@ -0,0 +1,106 @@
1
+ import { lstatSync, readdirSync } from "node:fs";
2
+ import { dirname, join } from "node:path";
3
+ import { checkWorkerFile, readWorkerFile } from "./worker-registration";
4
+ import { WorkerRefusal } from "./worker-request";
5
+ import { workerPathContains } from "./worker-trust";
6
+
7
+ export const workerDotenvFiles = [".env", ".env.local", ".env.development", ".env.development.local",
8
+ ".env.production", ".env.production.local", ".env.test", ".env.test.local"];
9
+ const projectInputs = [...workerDotenvFiles, ".bunfig.toml", "bunfig.toml", ".omp", ".pi", ".claude", ".codex", ".cursor", ".gemini",
10
+ ".opencode", ".agent", ".agents", ".cline", ".windsurf", ".codeium", ".omp-plugin", ".claude-plugin",
11
+ "mcp.json", ".mcp.json", ".vscode/mcp.json", "opencode.json", "opencode.jsonc", "WATCHDOG.yml", "WATCHDOG.yaml"];
12
+ const thinkingLevels = new Set(["auto", "minimal", "low", "medium", "high", "xhigh", "max"]);
13
+ const rolePattern = /^[a-zA-Z][a-zA-Z0-9_-]{0,127}(?![\s\S])/u;
14
+ const modelPattern = /^[a-zA-Z0-9][a-zA-Z0-9_.-]*\/[^\s\u0000-\u001f\u007f]+(?![\s\S])/u;
15
+
16
+ type ProjectSettings<Role extends string | null = string> = { defaultThinkingLevel?: string; modelRoles?: Record<string, Role> };
17
+
18
+ function inputRefusal(name: string) {
19
+ return new WorkerRefusal(`Worker startup refuses project configuration (${name}); only supported data in an operator-trusted checkout is allowed`);
20
+ }
21
+
22
+ function plainObject(value: unknown): value is Record<string, unknown> {
23
+ if (value === null || typeof value !== "object") return false;
24
+ const prototype = Object.getPrototypeOf(value);
25
+ return prototype === Object.prototype || prototype === null;
26
+ }
27
+
28
+ /** Keep the native provider disabled: allow only these typed values into the private launch overlay. */
29
+ function readProjectSettings(path: string, json: boolean): ProjectSettings<string | null> {
30
+ const bytes = readWorkerFile(path, 0o644);
31
+ if (!bytes) throw inputRefusal(".omp");
32
+ const content = bytes.toString("utf8");
33
+ const settings: unknown = !content.trim() ? {} : json ? JSON.parse(content) : Bun.YAML.parse(content);
34
+ if (!plainObject(settings)) throw inputRefusal(".omp");
35
+ const result: ProjectSettings<string | null> = {};
36
+ for (const [key, value] of Object.entries(settings)) {
37
+ if (key === "defaultThinkingLevel" && typeof value === "string" && thinkingLevels.has(value)) {
38
+ result.defaultThinkingLevel = value;
39
+ } else if (key === "modelRoles" && plainObject(value)) {
40
+ const roles: Record<string, string | null> = {};
41
+ for (const [role, model] of Object.entries(value)) {
42
+ if (!rolePattern.test(role) || model !== null && !(typeof model === "string" && modelPattern.test(model)))
43
+ throw inputRefusal(".omp");
44
+ roles[role] = model;
45
+ }
46
+ result.modelRoles = roles;
47
+ } else throw inputRefusal(".omp");
48
+ }
49
+ return result;
50
+ }
51
+
52
+ function readProjectOmp(path: string): ProjectSettings {
53
+ const info = lstatSync(path);
54
+ if (!info.isDirectory() || info.uid !== process.getuid?.() || (info.mode & 0o022) !== 0) throw inputRefusal(".omp");
55
+ let yaml: ProjectSettings<string | null> = {}, json: ProjectSettings<string | null> = {};
56
+ for (const name of readdirSync(path)) {
57
+ const file = join(path, name);
58
+ if (name === "config.yml") yaml = readProjectSettings(file, false);
59
+ else if (name === "settings.json") json = readProjectSettings(file, true);
60
+ else if (["AGENTS.md", "RULES.md", "README.md", ".gitignore"].includes(name)) checkWorkerFile(lstatSync(file), 0o644);
61
+ else throw inputRefusal(".omp");
62
+ }
63
+ const { modelRoles: jsonRoles, ...jsonSettings } = json;
64
+ const { modelRoles: yamlRoles, ...yamlSettings } = yaml;
65
+ const settings: ProjectSettings = { ...jsonSettings, ...yamlSettings };
66
+ if (jsonRoles || yamlRoles) {
67
+ // Stock OMP clears a project role back to the profile. A null in --config
68
+ // would instead mask that profile role. Resolve the project layer first.
69
+ const roles: Record<string, string> = {};
70
+ for (const [name, model] of Object.entries({ ...jsonRoles, ...yamlRoles })) {
71
+ if (model !== null) roles[name] = model;
72
+ }
73
+ settings.modelRoles = roles;
74
+ }
75
+ return settings;
76
+ }
77
+
78
+ /** Stock discovery can read ancestors; the opt-in extends no higher than the exact enrolled root. */
79
+ export function assertWorkerWorkspaceStartup(cwd: string, home: string, trustedRoot?: string): ProjectSettings {
80
+ let settings: ProjectSettings = {};
81
+ for (let dir = cwd; ; dir = dirname(dir)) {
82
+ if (dir === home || (dir !== cwd && ["/tmp", "/private/tmp", "/var/tmp", "/private/var/tmp"].includes(dir))) break;
83
+ const trusted = trustedRoot !== undefined && workerPathContains(trustedRoot, dir);
84
+ for (const name of projectInputs) {
85
+ const path = join(dir, name);
86
+ const info = lstatSync(path, { throwIfNoEntry: false });
87
+ if (!info) continue;
88
+ if (!trusted) throw inputRefusal(name);
89
+ try {
90
+ if (name === ".omp") {
91
+ const project = readProjectOmp(path);
92
+ if (dir === cwd) settings = project; // Stock settings scope is exactly the selected cwd.
93
+ } else if (workerDotenvFiles.includes(name)) {
94
+ // The CLI/SDK bootstrap outside the checkout. Do not copy, evaluate, or
95
+ // load dotenv values into the worker environment; project tools can read them.
96
+ checkWorkerFile(info, 0o644);
97
+ } else throw inputRefusal(name);
98
+ } catch {
99
+ // Parser/OS messages can contain settings values or dotenv paths.
100
+ throw inputRefusal(name);
101
+ }
102
+ }
103
+ if (dirname(dir) === dir) break;
104
+ }
105
+ return settings;
106
+ }
@@ -10,23 +10,26 @@ import { Value } from "@sinclair/typebox/value";
10
10
  import { privateDirectory } from "../config/config";
11
11
  import { stagePrivateFile } from "../config/credentials";
12
12
  import { parseWorkerDestination } from "./worker-destination";
13
- import { workerRepositoryHead } from "./worker-repository";
13
+ import { workerRepositoryHead, workerRepositoryLocation } from "./worker-repository";
14
14
  import { trustedWorkerPath } from "./worker-trust";
15
- import { WorkerDescriptionSchema, type WorkerDescription, type WorkerLaneRef, type WorkerRegistration } from "./worker-wire";
15
+ import { WorkerDescriptionSchema, workerDescribeCurrent, type WorkerDefaultRepository, type WorkerDescription,
16
+ type WorkerLaneRef, type WorkerRegistration } from "./worker-wire";
16
17
 
17
18
  export class WorkerRegistrationError extends Error {
18
19
  override readonly name = "WorkerRegistrationError";
19
20
  }
20
21
 
22
+ const repoBinding = { root: Type.String(), repoId: Type.String({ pattern: "^[0-9a-f]{64}$" }) };
21
23
  const inventory = Type.Array(Type.Object({
22
24
  destination: Type.String(),
23
25
  identityFile: Type.String(),
24
26
  description: WorkerDescriptionSchema,
25
27
  default: Type.Optional(Type.Boolean()),
26
- defaultRepository: Type.Optional(Type.Object({
27
- root: Type.String(),
28
- repoId: Type.String({ pattern: "^[0-9a-f]{64}$" }),
29
- }, { additionalProperties: false })),
28
+ defaultRepository: Type.Optional(Type.Union([
29
+ Type.Object(repoBinding, { additionalProperties: false }),
30
+ Type.Object({ ...repoBinding, mode: Type.Literal("current"),
31
+ localCheckout: Type.String({ pattern: "^[0-9a-f]{64}$" }), localPath: Type.Optional(Type.String()) }, { additionalProperties: false }),
32
+ ])),
30
33
  }));
31
34
  const fileLimit = 1024 * 1024;
32
35
  const controls = /[\u0000-\u001f\u007f]/;
@@ -131,7 +134,9 @@ function validateDescription(value: unknown): WorkerDescription {
131
134
  throw new WorkerRegistrationError("Invalid worker description");
132
135
  return {
133
136
  workerId: value.workerId, platform: value.platform, stateDir: value.stateDir,
134
- repos: value.repos.map(({ id, cwd }) => ({ id, cwd })).sort((left, right) => left.id.localeCompare(right.id)),
137
+ repos: value.repos.map(({ id, cwd, currentWorkspace, trustedCheckout }) => ({
138
+ id, cwd, ...(currentWorkspace && { currentWorkspace }), ...(trustedCheckout && { trustedCheckout }),
139
+ })).sort((left, right) => left.id.localeCompare(right.id)),
135
140
  capacity: value.capacity, active: value.active,
136
141
  };
137
142
  }
@@ -140,6 +145,29 @@ function canonicalPath(path: string): boolean {
140
145
  return isAbsolute(path) && normalize(path) === path && !controls.test(path);
141
146
  }
142
147
 
148
+ export function defaultCheckoutContains(root: string, path: string): boolean {
149
+ return path === root || path.startsWith(root === "/" ? "/" : `${root}/`);
150
+ }
151
+
152
+ /** Preserve traversal through an explicitly selected pathname, including symlink ancestors. */
153
+ export function workerPathSpelling(path: string): string {
154
+ const absolute = isAbsolute(path) ? path : `${process.cwd()}/${path}`;
155
+ return `/${absolute.split("/").filter(part => part && part !== ".").join("/")}`;
156
+ }
157
+
158
+ export async function verifyCurrentDefaultCheckout(checkout: Extract<WorkerDefaultRepository, { mode: "current" }>): Promise<boolean> {
159
+ const source = await workerRepositoryLocation(checkout.localPath ?? checkout.root);
160
+ return source !== null && source.root === checkout.root && source.repoId === checkout.repoId
161
+ && source.subdir === "" && source.localCheckout === checkout.localCheckout;
162
+ }
163
+
164
+ function conflictingDefault(left: WorkerDefaultRepository, right: WorkerDefaultRepository): boolean {
165
+ if (!left.mode && !right.mode) return true;
166
+ const paths = (checkout: WorkerDefaultRepository) => checkout.mode && checkout.localPath
167
+ ? [checkout.root, checkout.localPath] : [checkout.root];
168
+ return paths(left).some(a => paths(right).some(b => defaultCheckoutContains(a, b) || defaultCheckoutContains(b, a)));
169
+ }
170
+
143
171
  /** Last verified inventory, not endpoint readiness. Pending keys are not listed. */
144
172
  export function listWorkers(stateDir: string): WorkerRegistration[] {
145
173
  const directory = join(stateDir, "workers");
@@ -151,18 +179,22 @@ export function listWorkers(stateDir: string): WorkerRegistration[] {
151
179
  if (!Value.Check(inventory, parsed)) throw new WorkerRegistrationError("Invalid verified worker inventory");
152
180
  const ids = new Set<string>();
153
181
  const destinations = new Set<string>();
154
- let defaultSeen = false;
182
+ const defaults: WorkerDefaultRepository[] = [];
155
183
  return parsed.map(({ destination, identityFile, description, default: preferred, defaultRepository }) => {
156
184
  const verified = validateDescription(description);
157
185
  if (!parseWorkerDestination(destination) || identityFile !== endpointFor(stateDir, destination).identityFile ||
158
186
  ids.has(verified.workerId) || destinations.has(destination) ||
159
- (defaultRepository && (!preferred || defaultSeen || !canonicalPath(defaultRepository.root)
160
- || !verified.repos.some(repo => repo.id === defaultRepository.repoId))))
187
+ (defaultRepository && (!preferred || !canonicalPath(defaultRepository.root)
188
+ || ("localPath" in defaultRepository && defaultRepository.localPath !== undefined
189
+ && (!isAbsolute(defaultRepository.localPath) || controls.test(defaultRepository.localPath)
190
+ || workerPathSpelling(defaultRepository.localPath) !== defaultRepository.localPath))
191
+ || defaults.some(other => conflictingDefault(other, defaultRepository))
192
+ || !verified.repos.some(repo => repo.id === defaultRepository.repoId && (!("mode" in defaultRepository) || repo.currentWorkspace)))))
161
193
  throw new WorkerRegistrationError("Conflicting verified worker inventory");
162
194
  ids.add(verified.workerId);
163
195
  destinations.add(destination);
164
196
  // Legacy boolean-only entries never authorized disclosure from any local checkout.
165
- defaultSeen ||= defaultRepository !== undefined;
197
+ if (defaultRepository) defaults.push(defaultRepository);
166
198
  return { destination, identityFile, description: verified, ...(defaultRepository && { default: true, defaultRepository }) };
167
199
  });
168
200
  }
@@ -174,11 +206,12 @@ type VerifyWorker = (
174
206
  type EnrollmentResult =
175
207
  | { readonly status: "pending"; readonly destination: string; readonly publicKey: string; readonly initCommand: string;
176
208
  readonly verificationError?: string }
177
- | { readonly status: "verified"; readonly destination: string; readonly description: WorkerDescription; readonly default: boolean };
209
+ | { readonly status: "verified"; readonly destination: string; readonly description: WorkerDescription; readonly default: boolean;
210
+ readonly defaultCurrent?: true };
178
211
 
179
- function pendingEnrollment(destination: string, publicKey: string, verificationError?: string): EnrollmentResult {
212
+ function pendingEnrollment(destination: string, publicKey: string, current: boolean, verificationError?: string): EnrollmentResult {
180
213
  return { status: "pending", destination, publicKey,
181
- initCommand: `omp-sa worker init --head-key ${shellWord(publicKey)} --repo /absolute/path/to/repo`, verificationError };
214
+ initCommand: `omp-sa worker init --head-key ${shellWord(publicKey)} ${current ? "--current-repo" : "--repo"} /absolute/path/to/repo`, verificationError };
182
215
  }
183
216
 
184
217
  function sameEnrollment(before: WorkerDescription, after: WorkerDescription): boolean {
@@ -195,15 +228,27 @@ export function matchWorkerDescription(verified: WorkerDescription, reply: unkno
195
228
 
196
229
  /** Begin without network I/O; a separate invocation verifies the restricted SSH endpoint. */
197
230
  export async function addWorker(
198
- options: { readonly stateDir: string; readonly destination: string; readonly defaultRepositoryRoot?: string },
231
+ options: { readonly stateDir: string; readonly destination: string; readonly defaultRepositoryRoot?: string;
232
+ readonly defaultCurrentRepositoryRoot?: string },
199
233
  describe: VerifyWorker,
234
+ describeCurrent = workerDescribeCurrent,
200
235
  ): Promise<EnrollmentResult> {
201
- const { stateDir, destination, defaultRepositoryRoot } = options;
236
+ const { stateDir, destination, defaultRepositoryRoot, defaultCurrentRepositoryRoot } = options;
202
237
  if (!parseWorkerDestination(destination))
203
- throw new WorkerRegistrationError("Worker destination must be an explicit user@host with an optional numeric port (user@host:port)");
238
+ throw new WorkerRegistrationError("Use user@host[:port] or tailscale://user@host[:port]; enclose an IPv6 address in brackets");
239
+ if (defaultRepositoryRoot !== undefined && defaultCurrentRepositoryRoot !== undefined)
240
+ throw new WorkerRegistrationError("Choose either an exact or a current default repository");
204
241
  const source = defaultRepositoryRoot === undefined ? null : await workerRepositoryHead(defaultRepositoryRoot);
205
242
  if (defaultRepositoryRoot !== undefined && (!source || source.subdir !== ""))
206
243
  throw new WorkerRegistrationError("A default worker requires the root of a clean head-side Git checkout with a verifiable network origin");
244
+ const localPath = defaultCurrentRepositoryRoot === undefined ? undefined : workerPathSpelling(defaultCurrentRepositoryRoot);
245
+ const current = localPath === undefined ? null : await workerRepositoryLocation(localPath);
246
+ if (localPath !== undefined && (controls.test(localPath) || !current || current.subdir !== "" || !canonicalPath(current.root)))
247
+ throw new WorkerRegistrationError("A current default worker requires a head-side Git checkout root with a verifiable network origin");
248
+ const proposed: WorkerDefaultRepository | null = current && localPath !== undefined
249
+ ? { mode: "current", root: current.root, repoId: current.repoId, localCheckout: current.localCheckout,
250
+ ...(localPath !== current.root && { localPath }) }
251
+ : source ? { root: source.root, repoId: source.repoId } : null;
207
252
  trustedWorkerPath(stateDir, [], "profile");
208
253
  privateDirectory(stateDir);
209
254
  const directory = join(stateDir, "workers");
@@ -211,11 +256,12 @@ export async function addWorker(
211
256
  return await withWorkerWriteLock(join(directory, "write.lock"), async () => {
212
257
  const registrations = listWorkers(stateDir);
213
258
  const previous = registrations.find(worker => worker.destination === destination);
214
- if (source && registrations.some(worker => worker.defaultRepository && worker !== previous))
215
- throw new WorkerRegistrationError("A different verified worker is already the default");
259
+ if (proposed && registrations.some(worker => worker.defaultRepository && worker !== previous
260
+ && conflictingDefault(worker.defaultRepository, proposed)))
261
+ throw new WorkerRegistrationError("A different verified worker is already the default for this checkout or placement mode");
216
262
  const endpoint = endpointFor(stateDir, destination);
217
263
  if (!previous && !lstatSync(endpoint.identityFile, { throwIfNoEntry: false }))
218
- return pendingEnrollment(destination, await createIdentity(endpoint.identityFile, directory));
264
+ return pendingEnrollment(destination, await createIdentity(endpoint.identityFile, directory), current !== null);
219
265
  checkWorkerIdentity(endpoint.identityFile);
220
266
 
221
267
  let observed: WorkerDescription;
@@ -223,7 +269,7 @@ export async function addWorker(
223
269
  catch (cause) {
224
270
  const message = "Worker could not be verified using its dedicated key and a known SSH host key";
225
271
  if (previous) throw new WorkerRegistrationError(message, { cause });
226
- return pendingEnrollment(destination, await identityPublicKey(endpoint.identityFile), message);
272
+ return pendingEnrollment(destination, await identityPublicKey(endpoint.identityFile), current !== null, message);
227
273
  }
228
274
  const description = validateDescription(observed);
229
275
  if (previous) {
@@ -232,22 +278,30 @@ export async function addWorker(
232
278
  } else if (registrations.some(worker => worker.description.workerId === description.workerId)) {
233
279
  throw new WorkerRegistrationError("Worker identity is already verified at a different SSH destination");
234
280
  }
235
- let defaultRepository = previous?.defaultRepository;
236
- if (source) {
237
- const { root, ...workspace } = source;
238
- if (!description.repos.some(repo => repo.id === workspace.repoId))
239
- throw new WorkerRegistrationError("Worker is not approved for the default repository identity");
281
+ if (proposed) {
282
+ if (!description.repos.some(repo => repo.id === proposed.repoId && (!proposed.mode || repo.currentWorkspace)))
283
+ throw new WorkerRegistrationError(proposed.mode
284
+ ? "Worker is not approved for a current default on this repository"
285
+ : "Worker is not approved for the default repository identity");
240
286
  // Do not send the head-side path (or a revision for an unapproved repo).
241
287
  let scoped: WorkerDescription;
242
288
  checkWorkerIdentity(endpoint.identityFile);
243
- try { scoped = validateDescription(await describe(endpoint, workspace)); }
289
+ try {
290
+ scoped = validateDescription(source
291
+ ? await describe(endpoint, { repoId: proposed.repoId, subdir: "", revision: source.revision })
292
+ : await describeCurrent(endpoint, { repoId: proposed.repoId, subdir: "" }));
293
+ }
244
294
  catch (cause) {
245
- throw new WorkerRegistrationError("Worker could not verify the default repository at the requested Git revision", { cause });
295
+ throw new WorkerRegistrationError(proposed.mode
296
+ ? "Worker could not verify the current default checkout"
297
+ : "Worker could not verify the default repository at the requested Git revision", { cause });
246
298
  }
247
299
  if (!sameEnrollment(description, scoped))
248
300
  throw new WorkerRegistrationError("Worker description no longer matches the verified enrollment");
249
- defaultRepository = { root, repoId: workspace.repoId };
301
+ if (proposed.mode === "current" && !await verifyCurrentDefaultCheckout(proposed))
302
+ throw new WorkerRegistrationError("The selected local checkout changed during current default enrollment");
250
303
  }
304
+ const defaultRepository = proposed ?? previous?.defaultRepository;
251
305
  const registration = { ...endpoint, description, ...(defaultRepository && { default: true, defaultRepository }) };
252
306
  if (!Bun.deepEquals(registration, previous)) {
253
307
  const updated = previous ? registrations.map(worker => worker === previous ? registration : worker)
@@ -260,7 +314,8 @@ export async function addWorker(
260
314
  catch (error) { if (!isMissing(error)) throw error; }
261
315
  }
262
316
  }
263
- return { status: "verified", destination, description, default: defaultRepository !== undefined };
317
+ return { status: "verified", destination, description, default: defaultRepository !== undefined,
318
+ ...(defaultRepository?.mode === "current" && { defaultCurrent: true }) };
264
319
  });
265
320
  }
266
321
 
@@ -2,7 +2,7 @@ import { createHash } from "node:crypto";
2
2
  import { closeSync, constants, fstatSync, lstatSync, openSync, readSync, realpathSync } from "node:fs";
3
3
  import { lstat, open, readlink, realpath } from "node:fs/promises";
4
4
  import { dirname, isAbsolute, join, relative, sep } from "node:path";
5
- import type { WorkerLaneRef } from "./worker-wire";
5
+ import type { WorkerWorkspace } from "./worker-wire";
6
6
 
7
7
  const gitOid = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/;
8
8
  const controls = /[\u0000-\u001f\u007f]/;
@@ -120,8 +120,48 @@ function withinTree(path: string): boolean {
120
120
  part && part !== ".." && part !== "." && part.toLowerCase() !== ".git"));
121
121
  }
122
122
 
123
+ /** Match a real local directory to an enrolled repository without reading its changes. */
124
+ export async function workerRepositoryLocation(cwd: string): Promise<(Pick<WorkerWorkspace, "repoId" | "subdir"> & {
125
+ readonly root: string; readonly localCheckout: string;
126
+ }) | null> {
127
+ try {
128
+ const canonical = await realpath(cwd);
129
+ const root = await checkoutRoot(canonical);
130
+ if (!root) return null;
131
+ const subdir = relative(root, canonical);
132
+ if (subdir.length > 2048 || !withinTree(subdir) || controls.test(subdir) || subdir.includes("\\")) return null;
133
+ const stamp = async () => {
134
+ const dirs = await Promise.all([lstat(root, { bigint: true }), lstat(join(root, ".git"), { bigint: true })]);
135
+ if (dirs.some(stat => !stat.isDirectory())) return null;
136
+ return createHash("sha256").update(dirs.map(stat => `${stat.dev}:${stat.ino}:${stat.birthtimeNs}`).join("/")).digest("hex");
137
+ };
138
+ const localCheckout = await stamp();
139
+ const repoId = await repositoryIdentity(root);
140
+ return localCheckout && repoId && await stamp() === localCheckout ? { root, localCheckout, repoId, subdir } : null;
141
+ } catch (error) {
142
+ if (unavailablePath(error)) return null;
143
+ throw error;
144
+ }
145
+ }
146
+
147
+ /** Resolve the selected worker's base commit without comparing or reading worktree bytes. */
148
+ export async function workerCurrentRevision(root: string, gitDir: string, cwd: string, repoId: string): Promise<string | null> {
149
+ try {
150
+ if (await checkoutRoot(cwd) !== root || join(root, ".git") !== gitDir) return null;
151
+ const head = [`--git-dir=${gitDir}`, `--work-tree=${root}`, "rev-parse", "--verify", "HEAD^{commit}"];
152
+ const [origin, output] = await Promise.all([repositoryIdentity(root), gitWorkerRepository(root, head)]);
153
+ const revision = output?.slice(0, -1);
154
+ if (origin !== repoId || !revision || !gitOid.test(revision) || output !== `${revision}\n`) return null;
155
+ const [stableOrigin, stableHead] = await Promise.all([repositoryIdentity(root), gitWorkerRepository(root, head)]);
156
+ return stableOrigin === origin && stableHead === output ? revision : null;
157
+ } catch (error) {
158
+ if (unavailablePath(error)) return null;
159
+ throw error;
160
+ }
161
+ }
162
+
123
163
  /** Re-attest only the workspace's identity, without scanning the index or tracked bytes. */
124
- export async function workerMemoryRepositoryMatches(cwd: string, expected: Pick<WorkerLaneRef, "repoId" | "revision" | "subdir"> & {
164
+ export async function workerMemoryRepositoryMatches(cwd: string, expected: Pick<WorkerWorkspace, "repoId" | "revision" | "subdir"> & {
125
165
  readonly repoRoot: string; readonly gitDir: string;
126
166
  }): Promise<boolean> {
127
167
  try {
@@ -272,15 +312,24 @@ async function* gitRecords(root: string, args: readonly string[]): AsyncGenerato
272
312
  }
273
313
  }
274
314
 
275
- /** Keep the existing non-submodule boundary without comparing worktree or index contents to HEAD. */
276
- export async function workerIndexHasOrdinaryFiles(root: string, gitDir: string): Promise<boolean> {
315
+ /** Validate an index without invoking worktree filters; Gitlinks require a separate verifier. */
316
+ export async function workerIndexHasOrdinaryFiles(
317
+ root: string, gitDir: string, onGitlink?: (path: string) => Promise<boolean>,
318
+ ): Promise<boolean> {
277
319
  const records = gitRecords(root, [`--git-dir=${gitDir}`, `--work-tree=${root}`, "ls-files", "--stage", "-z"]);
278
320
  try {
279
321
  for (;;) {
280
322
  const record = await records.next();
281
323
  if (record.done) return record.value;
282
324
  const tab = record.value.indexOf(9);
283
- if (tab < 0 || !/^(100644|100755|120000) [0-9a-f]+ [0-3]$/.test(record.value.toString("latin1", 0, tab))) return false;
325
+ if (tab < 0) return false;
326
+ const header = record.value.toString("latin1", 0, tab);
327
+ if (/^(100644|100755|120000) [0-9a-f]+ [0-3]$/.test(header)) continue;
328
+ if (!onGitlink || !/^160000 (?:[0-9a-f]{40}|[0-9a-f]{64}) 0$/.test(header)) return false;
329
+ const name = record.value.subarray(tab + 1);
330
+ const path = name.toString("utf8");
331
+ if (!path || !withinTree(path) || controls.test(path) || path.includes("\\") || !Buffer.from(path).equals(name)
332
+ || !await onGitlink(path)) return false;
284
333
  }
285
334
  } finally { await records.return(false); }
286
335
  }
@@ -302,7 +351,7 @@ async function matchesCommit(root: string, gitArgs: readonly string[], revision:
302
351
  }
303
352
 
304
353
  /** Inspect metadata through Git, and read tracked bytes without Git's content converters. */
305
- export async function workerRepositoryHead(cwd: string): Promise<(Pick<WorkerLaneRef, "repoId" | "revision" | "subdir">
354
+ export async function workerRepositoryHead(cwd: string): Promise<(Pick<WorkerWorkspace, "repoId" | "revision" | "subdir">
306
355
  & { readonly root: string }) | null> {
307
356
  try {
308
357
  const canonical = await realpath(cwd);
@@ -1,7 +1,7 @@
1
1
  import { Type, type Static } from "@sinclair/typebox/type";
2
2
  import { Value } from "@sinclair/typebox/value";
3
3
  import type { LanePresetSnapshot } from "../contracts";
4
- import type { WorkerPolicy } from "./worker-wire";
4
+ import { workerCheckoutSchema, workerLaneIdSchema, workerRevisionSchema, type WorkerPolicy } from "./worker-wire";
5
5
 
6
6
  export class WorkerRefusal extends Error {}
7
7
 
@@ -12,15 +12,18 @@ const absolute = Type.String({ maxLength: 4096, pattern: `^/[^\\u0000-\\u001f\\u
12
12
  const id = Type.String({ minLength: 1, maxLength: 128, pattern: `^[a-zA-Z0-9][a-zA-Z0-9_-]*${end}` });
13
13
  const repoId = Type.String({ pattern: `^[0-9a-f]{64}${end}` });
14
14
  const generation = Type.Integer({ minimum: 0, maximum: Number.MAX_SAFE_INTEGER });
15
+ const subdir = Type.String({ maxLength: 2048, pattern: `^[^\\\\\\u0000-\\u001f\\u007f]*${end}` });
15
16
  const workspaceFields = {
16
17
  repoId,
17
- revision: Type.String({ pattern: `^(?:[0-9a-f]{40}|[0-9a-f]{64})${end}` }),
18
- subdir: Type.String({ maxLength: 2048, pattern: `^[^\\\\\\u0000-\\u001f\\u007f]*${end}` }),
18
+ revision: workerRevisionSchema,
19
+ subdir,
20
+ workerCheckout: Type.Optional(workerCheckoutSchema),
19
21
  };
20
22
  const workspace = Type.Object(workspaceFields, strict);
23
+ const currentWorkspace = Type.Object({ repoId, subdir, current: Type.Literal(true) }, strict);
21
24
  const laneRefSchema = Type.Object({
22
25
  ...workspaceFields, generation,
23
- laneId: Type.String({ pattern: `^lane-[A-Za-z0-9_-]{1,48}${end}` }),
26
+ laneId: workerLaneIdSchema,
24
27
  }, strict);
25
28
  const role = Type.String({ pattern: `^[a-zA-Z][a-zA-Z0-9_-]{0,127}${end}` });
26
29
  type NativeLevel = NonNullable<LanePresetSnapshot["defaultThinkingLevel"]>;
@@ -41,14 +44,18 @@ const launch = Type.Object({
41
44
  const envelope = { version: Type.Literal(1) };
42
45
  const bound = { ...envelope, workerId: id, ref: laneRefSchema };
43
46
  const request = Type.Union([
44
- Type.Object({ ...envelope, op: Type.Literal("describe"), workspace: Type.Optional(workspace) }, strict),
47
+ Type.Object({ ...envelope, op: Type.Literal("describe"), workspace: Type.Optional(Type.Union([workspace, currentWorkspace])) }, strict),
45
48
  Type.Object({ ...bound, op: Type.Literal("probe"), reconcile: Type.Optional(Type.Literal(true)) }, strict),
46
49
  Type.Object({ ...bound, op: Type.Literal("open"), launch }, strict),
47
50
  Type.Object({ ...bound, op: Type.Literal("attach") }, strict),
48
51
  ]);
49
52
  const policySchema = Type.Object({
50
53
  workerId: id, stateDir: absolute,
51
- repos: Type.Array(Type.Object({ id: repoId, cwd: absolute }, strict), { minItems: 1, maxItems: 128 }),
54
+ repos: Type.Array(Type.Object({
55
+ id: repoId, cwd: absolute,
56
+ currentWorkspace: Type.Optional(Type.Literal(true)),
57
+ trustedCheckout: Type.Optional(Type.Literal(true)),
58
+ }, strict), { minItems: 1, maxItems: 128 }),
52
59
  capacity: Type.Integer({ minimum: 1, maximum: Number.MAX_SAFE_INTEGER }),
53
60
  command: Type.Array(text, { minItems: 1, maxItems: 64 }),
54
61
  }, strict);