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
@@ -3,10 +3,11 @@ import { closeSync, constants, fstatSync, lstatSync, openSync } from "node:fs";
3
3
  import { join } from "node:path";
4
4
  import { Type, type Static } from "@sinclair/typebox/type";
5
5
  import { Value } from "@sinclair/typebox/value";
6
+ import { workerOwnerWasNotSpawned } from "../omp/host";
6
7
  import { releaseCheckout } from "./worker-checkout";
7
8
  import { workerMemoryBinding, type WorkerMemoryBinding } from "./worker-memory-storage";
8
9
  import { WorkerRefusal } from "./worker-request";
9
- import type { WorkerLaneRef, WorkerPolicy } from "./worker-wire";
10
+ import { workerCheckoutSchema, type WorkerLaneRef, type WorkerPolicy } from "./worker-wire";
10
11
 
11
12
  export const workerPid = Type.Integer({ minimum: 1, maximum: 0x7fffffff });
12
13
  const sessionId = Type.String({ minLength: 1, maxLength: 512 });
@@ -43,6 +44,7 @@ const receiptFields = {
43
44
  repoId: Type.String(),
44
45
  revision: Type.String(),
45
46
  subdir: Type.String(),
47
+ workerCheckout: Type.Optional(workerCheckoutSchema),
46
48
  repoRoot: Type.String(),
47
49
  gitDir: Type.String(),
48
50
  launchDigest: Type.String({ pattern: "^[0-9a-f]{64}$" }),
@@ -65,8 +67,11 @@ export type WorkerReceipt = Readonly<Static<typeof receipt>>;
65
67
  export type WorkerIdentity = Readonly<Static<typeof identity>>;
66
68
  type ReservedReceipt = Extract<WorkerReceipt, { phase: "reserved" }>;
67
69
  type Retirement = { readonly sessionId: string; readonly clean: boolean; readonly cleanup: () => void }
68
- | { readonly journalHeld: true; readonly cleanup: () => void };
69
- type WorkerSeal = Pick<WorkerLaneRef, "generation" | "repoId" | "revision" | "subdir"> & { readonly repoRoot: string };
70
+ | { readonly journalHeld: true; readonly cleanup: () => void }
71
+ | { readonly unspawnedError: unknown };
72
+ type WorkerSeal = Pick<WorkerLaneRef, "generation" | "repoId" | "revision" | "subdir"> & {
73
+ readonly repoRoot: string; readonly workerCheckout: string | null;
74
+ };
70
75
  const occupied = "phase NOT IN ('released', 'checkout-released')";
71
76
 
72
77
  function decode(row: { readonly data: string } | null): WorkerReceipt | null {
@@ -81,9 +86,16 @@ export class WorkerLedger {
81
86
  readonly #capacity: number;
82
87
 
83
88
  static count(policy: WorkerPolicy): number {
84
- if (!lstatSync(join(policy.stateDir, "worker.sqlite"), { throwIfNoEntry: false })) return 0;
89
+ return WorkerLedger.occupancy(policy).length;
90
+ }
91
+
92
+ static occupancy(policy: WorkerPolicy): readonly WorkerLaneRef[] {
93
+ if (!lstatSync(join(policy.stateDir, "worker.sqlite"), { throwIfNoEntry: false })) return [];
85
94
  const ledger = new WorkerLedger(policy, "read");
86
- try { return ledger.active().length; } finally { ledger.close(); }
95
+ try {
96
+ return ledger.active().map(({ laneId, generation, repoId, revision, subdir, workerCheckout }) =>
97
+ ({ laneId, generation, repoId, revision, subdir, ...(workerCheckout && { workerCheckout }) }));
98
+ } finally { ledger.close(); }
87
99
  }
88
100
 
89
101
  constructor(policy: WorkerPolicy, mode: "read" | "write" = "write") {
@@ -105,11 +117,13 @@ export class WorkerLedger {
105
117
  CREATE TABLE IF NOT EXISTS worker_lanes (id TEXT PRIMARY KEY, phase TEXT NOT NULL, data TEXT NOT NULL);
106
118
  CREATE TABLE IF NOT EXISTS worker_seals (
107
119
  id TEXT PRIMARY KEY, generation INTEGER NOT NULL, repoId TEXT NOT NULL,
108
- revision TEXT NOT NULL, subdir TEXT NOT NULL, repoRoot TEXT NOT NULL
120
+ revision TEXT NOT NULL, subdir TEXT NOT NULL, repoRoot TEXT NOT NULL, workerCheckout TEXT
109
121
  );
110
122
  `);
111
123
  if (mode === "write") this.#db.transaction(() => {
112
124
  this.#db.query("INSERT OR IGNORE INTO worker_identity VALUES (1, ?)").run(policy.workerId);
125
+ if (!this.#db.query<{ name: string }, []>("PRAGMA table_info(worker_seals)").all().some(col => col.name === "workerCheckout"))
126
+ this.#db.exec("ALTER TABLE worker_seals ADD COLUMN workerCheckout TEXT");
113
127
  }).immediate();
114
128
  const row = this.#db.query<{ worker_id: string }, []>("SELECT worker_id FROM worker_identity WHERE singleton = 1").get();
115
129
  if (row?.worker_id !== policy.workerId) throw new WorkerRefusal("Worker storage belongs to a different enrollment");
@@ -137,8 +151,9 @@ export class WorkerLedger {
137
151
 
138
152
  #sealedGeneration(ref: WorkerLaneRef, repoRoot: string): number | undefined {
139
153
  const seal = this.#db.query<WorkerSeal, [string]>(
140
- "SELECT generation, repoId, revision, subdir, repoRoot FROM worker_seals WHERE id = ?").get(ref.laneId);
141
- if (seal && (seal.repoId !== ref.repoId || seal.revision !== ref.revision || seal.subdir !== ref.subdir || seal.repoRoot !== repoRoot))
154
+ "SELECT generation, repoId, revision, subdir, repoRoot, workerCheckout FROM worker_seals WHERE id = ?").get(ref.laneId);
155
+ if (seal && (seal.repoId !== ref.repoId || seal.revision !== ref.revision || seal.subdir !== ref.subdir
156
+ || seal.repoRoot !== repoRoot || seal.workerCheckout !== (ref.workerCheckout ?? null)))
142
157
  throw new WorkerRefusal("Worker lane has a different durable checkout binding");
143
158
  return seal?.generation;
144
159
  }
@@ -157,8 +172,8 @@ export class WorkerLedger {
157
172
  // Keep any previous exit/session receipt intact. Reserve and seal use the
158
173
  // same immediate transaction: either a launch is already admitted, or
159
174
  // even an open request that arrives after this reply must refuse.
160
- this.#db.query("INSERT OR REPLACE INTO worker_seals VALUES (?, ?, ?, ?, ?, ?)")
161
- .run(ref.laneId, ref.generation, ref.repoId, ref.revision, ref.subdir, repoRoot);
175
+ this.#db.query("INSERT OR REPLACE INTO worker_seals (id, generation, repoId, revision, subdir, repoRoot, workerCheckout) VALUES (?, ?, ?, ?, ?, ?, ?)")
176
+ .run(ref.laneId, ref.generation, ref.repoId, ref.revision, ref.subdir, repoRoot, ref.workerCheckout ?? null);
162
177
  return true;
163
178
  });
164
179
  return options.reconcile ? confirm.immediate() : confirm();
@@ -185,11 +200,13 @@ export class WorkerLedger {
185
200
  }).immediate();
186
201
  }
187
202
 
188
- #replaceCurrent(current: WorkerReceipt, replacement: () => WorkerReceipt): boolean {
203
+ #replaceCurrent(current: WorkerReceipt, replacement: (actual: WorkerReceipt) => WorkerReceipt | null): boolean {
189
204
  return this.#db.transaction(() => {
190
205
  const actual = this.get(current.laneId);
191
206
  if (actual?.attempt !== current.attempt || actual.phase !== current.phase) return false;
192
- this.#write(replacement());
207
+ const next = replacement(actual);
208
+ if (!next) return false;
209
+ this.#write(next);
193
210
  return true;
194
211
  }).immediate();
195
212
  }
@@ -198,18 +215,25 @@ export class WorkerLedger {
198
215
  return this.#replaceCurrent(current, () => next);
199
216
  }
200
217
 
201
- retire(current: WorkerReceipt, exit?: Retirement): boolean {
202
- return this.#replaceCurrent(current, () => {
203
- exit?.cleanup();
218
+ retire(observed: WorkerReceipt, retirement?: Retirement): boolean {
219
+ return this.#replaceCurrent(observed, current => {
220
+ // No-owner proof is valid only in the live producer of this exact
221
+ // launch. It says nothing about the journal the SDK was allowed to prepare.
222
+ if (retirement && "unspawnedError" in retirement && (current.phase !== "launching"
223
+ || current.launcherPid !== process.pid || !current.checkoutIdentity
224
+ || !workerOwnerWasNotSpawned(retirement.unspawnedError, current.attempt)))
225
+ return null;
226
+ if (retirement && "cleanup" in retirement) retirement.cleanup();
204
227
  releaseCheckout(current);
205
- const { laneId, generation, repoId, revision, subdir, repoRoot, gitDir, attempt, launcherPid, launchDigest,
228
+ const { laneId, generation, repoId, revision, subdir, workerCheckout, repoRoot, gitDir, attempt, launcherPid, launchDigest,
206
229
  journalDirectory, checkoutIdentity, memory } = current;
207
- const verified = exit && "sessionId" in exit ? exit : undefined;
230
+ const verified = retirement && "sessionId" in retirement ? retirement : undefined;
208
231
  const sessionId = verified?.sessionId ?? current.sessionId;
209
232
  const binding = { laneId, generation, repoId, revision, subdir, repoRoot, gitDir, attempt, launcherPid, launchDigest,
233
+ ...(workerCheckout && { workerCheckout }),
210
234
  sessionId, ...(journalDirectory && { journalDirectory }), ...(checkoutIdentity && { checkoutIdentity }),
211
235
  ...(sessionId !== null && memory ? { memory } : {}) };
212
- if (exit && "journalHeld" in exit) return { ...binding, phase: "checkout-released" };
236
+ if (retirement && !verified) return { ...binding, phase: "checkout-released" };
213
237
  return { ...binding, phase: "released", ...(verified?.clean && { exitVerified: true }) };
214
238
  });
215
239
  }
@@ -0,0 +1,13 @@
1
+ import type { RemotePlacement } from "./worker-wire";
2
+
3
+ export interface WorkerCurrentIntent {
4
+ readonly worker: string;
5
+ readonly repoId: string;
6
+ readonly subdir: string;
7
+ }
8
+
9
+ /** The same promised workspace must own both the work and any result nominated there. */
10
+ export function matchesWorkerCurrentPlacement(intent: WorkerCurrentIntent, remote: RemotePlacement | null | undefined): boolean {
11
+ return !!remote?.workerCheckout && remote.workerId === intent.worker && remote.repoId === intent.repoId
12
+ && remote.subdir === intent.subdir;
13
+ }
@@ -1,50 +1,209 @@
1
+ import { lstatSync, readlinkSync } from "node:fs";
2
+ import { dirname, isAbsolute, join, resolve, sep } from "node:path";
1
3
  import type { Config } from "../config/config";
2
- import { workerRepositoryHead } from "./worker-repository";
3
- import { listWorkers } from "./worker-registration";
4
- import { workerDescribe, type RemotePlacement, type WorkerLaneRef, type WorkerRegistration, type WorkerSelector } from "./worker-wire";
4
+ import { workerRepositoryHead, workerRepositoryLocation } from "./worker-repository";
5
+ import { defaultCheckoutContains, listWorkers, matchWorkerDescription, verifyCurrentDefaultCheckout, workerPathSpelling } from "./worker-registration";
6
+ import { workerDescribe, workerDescribeCurrent, type RemotePlacement, type WorkerLaneRef, type WorkerRegistration, type WorkerSelector,
7
+ type WorkerWorkspace } from "./worker-wire";
5
8
 
6
9
  class WorkerPlacementError extends Error {}
7
- type Workspace = Pick<WorkerLaneRef, "repoId" | "revision" | "subdir">;
8
10
 
9
- async function availableSlots(registration: WorkerRegistration, { repoId, revision, subdir }: Workspace): Promise<number> {
11
+ export type WorkerAssignment = RemotePlacement & (
12
+ { readonly laneId?: never; readonly generation?: never } | Pick<WorkerLaneRef, "laneId" | "generation">
13
+ );
14
+
15
+ function matchesPathSpelling(expected: string, spelled: string): boolean {
16
+ if (spelled === expected) return true;
17
+ const names = expected.split(sep).slice(1);
18
+ const spellings = spelled.split(sep).slice(1);
19
+ if (names.length !== spellings.length) return false;
20
+ let parent: string = sep;
21
+ // Compare alternate names under the same parent before following any link.
22
+ // The final entry can be a replacement symlink: matching its spelling
23
+ // identifies which pin must be verified, not permission to use its target.
24
+ try {
25
+ for (const [index, name] of names.entries()) {
26
+ const spelling = spellings[index];
27
+ if (spelling === undefined) return false;
28
+ const path = `${parent === sep ? "" : parent}${sep}${name}`;
29
+ if (spelling !== name) {
30
+ const entry = lstatSync(`${parent === sep ? "" : parent}${sep}${spelling}`, { bigint: true, throwIfNoEntry: false });
31
+ if (!entry) return false;
32
+ const other = lstatSync(path, { bigint: true, throwIfNoEntry: false });
33
+ if (other?.dev !== entry.dev || other.ino !== entry.ino) return false;
34
+ }
35
+ parent = path;
36
+ }
37
+ } catch (error) {
38
+ if (error instanceof Error && "code" in error && error.code === "ENOTDIR") return false;
39
+ throw error;
40
+ }
41
+ return true;
42
+ }
43
+
44
+ function applicableCurrentDefault(registered: readonly WorkerRegistration[], cwd: string) {
45
+ const defaults = registered.flatMap(registration => {
46
+ const checkout = registration.defaultRepository;
47
+ if (checkout?.mode !== "current") return [];
48
+ const roots = checkout.localPath && checkout.localPath !== checkout.root ? [checkout.localPath, checkout.root] : [checkout.root];
49
+ return roots.map(root => ({ registration, checkout, root }));
50
+ });
51
+ if (!defaults.length) return undefined;
52
+ const applicable = (requested: string) => {
53
+ const inside = (match: (typeof defaults)[number], suffix: string) => {
54
+ const projected = join(match.checkout.root, suffix);
55
+ return defaultCheckoutContains(match.checkout.root, projected) ? { ...match, requested: projected } : undefined;
56
+ };
57
+ const parts = requested.split(sep);
58
+ for (const match of defaults) {
59
+ if (defaultCheckoutContains(match.root, requested)) {
60
+ const location = inside(match, requested.slice(match.root.length));
61
+ if (location) return location;
62
+ }
63
+ }
64
+ for (const match of defaults) {
65
+ const depth = match.root.split(sep).length;
66
+ const requestedRoot = parts.slice(0, depth).join(sep);
67
+ if (matchesPathSpelling(match.root, requestedRoot)) {
68
+ const location = inside(match, parts.slice(depth).join(sep));
69
+ if (location) return location;
70
+ }
71
+ }
72
+ return undefined;
73
+ };
74
+ const direct = applicable(workerPathSpelling(cwd));
75
+ if (direct) return direct;
76
+ // Follow one link at a time. Full realpath would erase a pinned path in
77
+ // the middle of an alias chain, before checking whether it was replaced.
78
+ const parts = cwd.split(sep);
79
+ let prefix = isAbsolute(cwd) ? sep : resolve(".");
80
+ let symlinks = 0;
81
+ while (parts.length) {
82
+ const part = parts.shift();
83
+ if (!part || part === ".") continue;
84
+ if (part === "..") {
85
+ prefix = dirname(prefix);
86
+ const match = applicable(workerPathSpelling([prefix, ...parts].join(sep)));
87
+ if (match) return match;
88
+ continue;
89
+ }
90
+ const path = join(prefix, part);
91
+ try {
92
+ const entry = lstatSync(path, { throwIfNoEntry: false });
93
+ if (!entry) return undefined;
94
+ if (!entry.isSymbolicLink()) {
95
+ prefix = path;
96
+ continue;
97
+ }
98
+ if (++symlinks > 40) throw new WorkerPlacementError("Cannot verify a current default through this symlink chain");
99
+ const target = readlinkSync(path);
100
+ if (isAbsolute(target)) prefix = sep;
101
+ parts.unshift(...target.split(sep));
102
+ const match = applicable(workerPathSpelling([prefix, ...parts].join(sep)));
103
+ if (match) return match;
104
+ } catch (error) {
105
+ if (error instanceof Error && "code" in error && error.code === "ENOTDIR") return undefined;
106
+ throw error;
107
+ }
108
+ }
109
+ return undefined;
110
+ }
111
+
112
+ async function verifiedCurrentPlacement(registration: WorkerRegistration, scope: NonNullable<WorkerSelector["currentWorkspace"]>): Promise<RemotePlacement> {
113
+ const { repoId, subdir } = scope;
114
+ const { workerId, stateDir } = registration.description;
115
+ if (!registration.description.repos.some(repo => repo.id === repoId && repo.currentWorkspace))
116
+ throw new WorkerPlacementError("The paired worker is not approved for current-workspace placement on this repository");
117
+ try {
118
+ const reply = await workerDescribeCurrent(registration, { repoId, subdir });
119
+ if (matchWorkerDescription(registration.description, reply)) {
120
+ const { revision, workerCheckout } = reply.workspace;
121
+ return { workerId, stateDir, repoId, subdir, revision, workerCheckout };
122
+ }
123
+ } catch (error) {
124
+ if (!(error instanceof Error)) throw error;
125
+ }
126
+ throw new WorkerPlacementError("Could not verify the named worker's current checkout; no lane was placed");
127
+ }
128
+
129
+ async function workerAvailability(registration: WorkerRegistration, { repoId, revision, subdir, workerCheckout }: WorkerWorkspace) {
10
130
  const saved = registration.description;
11
131
  const approved = saved.repos.find(repo => repo.id === repoId);
12
- if (!approved) return 0;
132
+ if (!approved || workerCheckout && !approved.currentWorkspace) return null;
13
133
  try {
14
- const live = await workerDescribe(registration, { repoId, revision, subdir });
134
+ const live = await workerDescribe(registration, { repoId, revision, subdir, ...(workerCheckout && { workerCheckout }) });
15
135
  const inventory = live.repos.filter(repo => repo.id === repoId);
16
- return live.workerId === saved.workerId && live.platform === saved.platform && live.stateDir === saved.stateDir
17
- && inventory.length === 1 && inventory[0]?.cwd === approved.cwd ? Math.max(0, Math.min(saved.capacity, live.capacity) - live.active) : 0;
136
+ const verified = workerCheckout ? matchWorkerDescription(saved, live)
137
+ : live.workerId === saved.workerId && live.platform === saved.platform && live.stateDir === saved.stateDir
138
+ && inventory.length === 1 && inventory[0]?.cwd === approved.cwd
139
+ && inventory[0].trustedCheckout === approved.trustedCheckout && inventory[0].currentWorkspace === approved.currentWorkspace;
140
+ if (!verified) return null;
141
+ const occupancy = live.occupancy && new Map(live.occupancy.map(ref => [ref.laneId, ref]));
142
+ return { free: Math.max(0, Math.min(saved.capacity, live.capacity) - live.active), checkoutBusy: live.checkoutBusy === true,
143
+ occupancy: occupancy?.size === live.active && live.occupancy?.length === live.active ? occupancy : undefined };
18
144
  } catch (error) {
19
- if (error instanceof Error) return 0; // No readiness receipt; no permission to open.
145
+ if (error instanceof Error) return null; // No readiness receipt; no permission to open.
20
146
  throw error;
21
147
  }
22
148
  }
23
149
 
24
150
  /** Observe only the enrolled worker; do not open or retarget an unavailable checkout. */
25
- export async function workerPlacementReady(registration: WorkerRegistration, workspace: Workspace): Promise<boolean> {
26
- return await availableSlots(registration, workspace) > 0;
151
+ export async function workerPlacementReady(registration: WorkerRegistration, workspace: WorkerWorkspace): Promise<boolean> {
152
+ const available = await workerAvailability(registration, workspace);
153
+ return available !== null && !available.checkoutBusy && available.free > 0;
27
154
  }
28
155
 
29
156
  /** Admission only: read approved inventory and live capacity; never start work here. */
30
157
  export async function selectWorkerPlacement(
31
158
  config: Pick<Config, "stateDir">, cwd: string, placement?: WorkerSelector,
32
- admission?: { queued(): ReadonlyMap<string, number>; reserve(workerId: string): void },
159
+ admission?: { queued(): readonly WorkerAssignment[]; reserve(assignment: WorkerAssignment): void },
33
160
  ): Promise<RemotePlacement | null> {
34
161
  if (placement?.target === "local") {
35
- if (placement.platform !== undefined || placement.worker !== undefined) {
36
- throw new WorkerPlacementError("Local placement cannot specify a remote worker or worker platform");
162
+ if (placement.platform !== undefined || placement.worker !== undefined || placement.currentWorkspace) {
163
+ throw new WorkerPlacementError("Local placement cannot specify a remote worker, worker platform, or current worker checkout");
37
164
  }
38
165
  return null;
39
166
  }
167
+ const current = placement?.currentWorkspace;
168
+ if (current && !placement?.worker) throw new WorkerPlacementError("Worker-current placement requires one exact paired worker ID");
40
169
  const required = placement?.target === "remote" || placement?.platform !== undefined || placement?.worker !== undefined;
41
170
  const registered = listWorkers(config.stateDir).filter(({ description, defaultRepository }) =>
42
171
  (required || defaultRepository !== undefined) && (placement?.worker === undefined || description.workerId === placement.worker)
43
172
  && (placement?.platform === undefined || description.platform === placement.platform));
44
- if (!registered.length) {
173
+ const [first] = registered;
174
+ if (!first) {
45
175
  if (!required) return null;
46
176
  throw new WorkerPlacementError("No paired worker matches the requested worker or platform");
47
177
  }
178
+ if (current) {
179
+ const { repoId, subdir } = current;
180
+ const source = await workerRepositoryLocation(cwd);
181
+ if (source?.repoId !== repoId || source.subdir !== subdir)
182
+ throw new WorkerPlacementError("Worker-current placement requires a local directory matching the approved repository identity and subdirectory");
183
+ const selected = await verifiedCurrentPlacement(first, current);
184
+ admission?.reserve(selected);
185
+ return selected;
186
+ }
187
+ if (placement === undefined) {
188
+ const match = applicableCurrentDefault(registered, cwd);
189
+ if (match) {
190
+ const { registration, checkout, requested } = match;
191
+ const verifyLocal = async () => {
192
+ const source = await workerRepositoryLocation(cwd);
193
+ if (!source || source.root !== checkout.root || source.repoId !== checkout.repoId || source.localCheckout !== checkout.localCheckout
194
+ || !matchesPathSpelling(join(source.root, source.subdir), requested)
195
+ || checkout.localPath && checkout.localPath !== checkout.root && !await verifyCurrentDefaultCheckout(checkout))
196
+ throw new WorkerPlacementError("The configured current default does not match the original local checkout; no lane was placed");
197
+ return source.subdir;
198
+ };
199
+ const subdir = await verifyLocal();
200
+ const selected = await verifiedCurrentPlacement(registration, { repoId: checkout.repoId, subdir });
201
+ if (await verifyLocal() !== subdir)
202
+ throw new WorkerPlacementError("The selected local workspace changed during current placement; no lane was placed");
203
+ admission?.reserve(selected);
204
+ return selected;
205
+ }
206
+ }
48
207
  const source = await workerRepositoryHead(cwd);
49
208
  if (!source) {
50
209
  if (!required) return null;
@@ -53,26 +212,43 @@ export async function selectWorkerPlacement(
53
212
  const { root, ...workspace } = source;
54
213
  const candidates = registered.filter(({ description, defaultRepository }) =>
55
214
  description.repos.some(repo => repo.id === workspace.repoId) &&
56
- (required || (defaultRepository?.root === root && defaultRepository.repoId === workspace.repoId)));
215
+ (required || (!defaultRepository?.mode && defaultRepository?.root === root && defaultRepository.repoId === workspace.repoId)));
57
216
  if (!candidates.length) {
58
217
  if (!required) return null;
59
218
  throw new WorkerPlacementError("No matching paired worker is approved for this repository identity");
60
219
  }
61
- const observed = await Promise.all(candidates.map(async worker => ({ worker, free: await availableSlots(worker, workspace) })));
220
+ const observed = await Promise.all(candidates.map(async worker => ({ worker, available: await workerAvailability(worker, workspace) })));
62
221
  // Read and reserve synchronously after the SSH round trips: concurrent
63
222
  // admissions see each other's decisions without serializing network I/O.
64
- const queued = admission?.queued();
65
- const waiting = (worker: WorkerRegistration) => queued?.get(worker.description.workerId) ?? 0;
66
- observed.sort(({ worker: left }, { worker: right }) => {
67
- const a = left.description.workerId, b = right.description.workerId;
68
- return waiting(left) - waiting(right) || Number(right.defaultRepository !== undefined) - Number(left.defaultRepository !== undefined)
223
+ const waiting = new Map<string, WorkerAssignment[]>();
224
+ for (const assignment of admission?.queued() ?? []) {
225
+ const pending = waiting.get(assignment.workerId);
226
+ if (pending) pending.push(assignment);
227
+ else waiting.set(assignment.workerId, [assignment]);
228
+ }
229
+ const ranked = observed.map(({ worker, available }) => {
230
+ const pending = waiting.get(worker.description.workerId) ?? [];
231
+ const checkoutRank = pending.some(assignment => assignment.repoId === workspace.repoId) || available?.checkoutBusy ? 2 : available ? 0 : 1;
232
+ const queued = pending.filter(assignment => {
233
+ const counted = assignment.laneId === undefined || assignment.stateDir !== worker.description.stateDir
234
+ ? undefined : available?.occupancy?.get(assignment.laneId);
235
+ return !counted || counted.generation !== assignment.generation || counted.repoId !== assignment.repoId
236
+ || counted.revision !== assignment.revision || counted.subdir !== assignment.subdir || counted.workerCheckout !== assignment.workerCheckout;
237
+ }).length;
238
+ return { worker, checkoutRank, queued, free: available?.free ?? 0 };
239
+ }).sort((left, right) => {
240
+ const a = left.worker.description.workerId, b = right.worker.description.workerId;
241
+ return left.checkoutRank - right.checkoutRank || left.queued - right.queued
242
+ || Number(right.worker.defaultRepository !== undefined) - Number(left.worker.defaultRepository !== undefined)
69
243
  || (a === b ? 0 : a < b ? -1 : 1);
70
244
  });
71
245
  // Explicit placement freezes its worker even when no candidate is ready now.
72
246
  // The runtime repeats this preflight on the selected worker before open.
73
- const selected = (observed.find(({ worker, free }) => free > waiting(worker)) ?? (required ? observed[0] : null))?.worker;
74
- if (!selected) return null;
75
- const { workerId, stateDir } = selected.description;
76
- admission?.reserve(workerId);
77
- return { workerId, stateDir, ...workspace };
247
+ const chosen = (ranked.find(({ checkoutRank, free, queued }) => checkoutRank === 0 && free > queued)
248
+ ?? (required ? ranked[0] : null))?.worker;
249
+ if (!chosen) return null;
250
+ const { workerId, stateDir } = chosen.description;
251
+ const selected = { workerId, stateDir, ...workspace };
252
+ admission?.reserve(selected);
253
+ return selected;
78
254
  }
@@ -1,25 +1,26 @@
1
1
  import { Database } from "bun:sqlite";
2
2
  import { lstatSync, realpathSync } from "node:fs";
3
- import { delimiter, dirname, isAbsolute, join } from "node:path";
3
+ import { join } from "node:path";
4
4
  import { readWorkerFile } from "./worker-registration";
5
- import { gitWorkerRepository } from "./worker-repository";
5
+ import { assertWorkerWorkspaceStartup, workerDotenvFiles } from "./worker-project-startup";
6
6
  import { WorkerRefusal } from "./worker-request";
7
- import { trustedWorkerPath, workerInstallRoot } from "./worker-trust";
8
- import type { WorkerPolicy, WorkerRepo } from "./worker-wire";
7
+ import { trustedWorkerPath, workerCommandPath, workerInstallRoot, workerPathContains } from "./worker-trust";
8
+ import type { WorkerPolicy } from "./worker-wire";
9
9
  import type { WorkerMemoryLaunch } from "./worker-memory-storage";
10
10
 
11
11
  export interface WorkerHostProfile {
12
- readonly config: Readonly<Record<string, unknown>>;
12
+ readonly config: Readonly<Record<string, unknown> & ReturnType<typeof assertWorkerWorkspaceStartup>>;
13
13
  readonly flags: readonly string[];
14
14
  readonly extensionPaths: readonly string[];
15
15
  readonly managedUlwPath: string;
16
+ readonly trustedWorkspaceRoot?: string;
16
17
  readonly memory?: WorkerMemoryLaunch;
17
18
  }
18
19
 
19
20
  const flags = ["--no-extensions", "--no-lsp"] as const;
20
21
  // --no-extensions is necessary but does not suppress all stock custom tool and
21
22
  // MCP discovery. Keep only the explicitly composed OMP extension roots and
22
- // builtin resources. Reject independent project config before the CLI starts.
23
+ // builtin resources; opting in to project data never enables executable discovery.
23
24
  const config = {
24
25
  disabledProviders: ["native", "agent-plugins", "agents", "agents-md", "claude", "claude-md", "claude-plugins",
25
26
  "cline", "codex", "cursor", "custom-context", "gemini", "github", "mcp-json", "opencode", "skillshare",
@@ -28,11 +29,6 @@ const config = {
28
29
  marketplace: { autoUpdate: false },
29
30
  skills: { customDirectories: [], enablePiProject: false, enableAgentsProject: false, enableClaudeProject: false },
30
31
  };
31
- const dotenv = [".env", ".env.local", ".env.development", ".env.development.local",
32
- ".env.production", ".env.production.local", ".env.test", ".env.test.local"];
33
- const projectInputs = [...dotenv, "bunfig.toml", ".omp", ".pi", ".claude", ".codex", ".cursor", ".gemini",
34
- ".opencode", ".agent", ".agents", ".cline", ".windsurf", ".codeium", ".omp-plugin", ".claude-plugin",
35
- "mcp.json", ".mcp.json", ".vscode/mcp.json", "opencode.json", "opencode.jsonc", "WATCHDOG.yml", "WATCHDOG.yaml"];
36
32
  const providerEnvironment = [
37
33
  "ANTHROPIC_API_KEY", "ANTHROPIC_OAUTH_TOKEN", "OPENAI_API_KEY", "GEMINI_API_KEY", "COPILOT_GITHUB_TOKEN",
38
34
  "AZURE_OPENAI_API_KEY", "GROQ_API_KEY", "CEREBRAS_API_KEY", "XAI_API_KEY", "OPENROUTER_API_KEY",
@@ -43,27 +39,7 @@ const providerEnvironment = [
43
39
  "SCW_SECRET_KEY", "OTARI_API_KEY",
44
40
  ] as const;
45
41
 
46
- const controls = /[\u0000-\u001f\u007f]/;
47
42
  const appData = ["XDG_DATA_HOME", "XDG_STATE_HOME", "XDG_CACHE_HOME"] as const;
48
- const gitSettings = [
49
- /^core\.(repositoryformatversion|filemode|bare|logallrefupdates|ignorecase|precomposeunicode|symlinks|autocrlf|eol|safecrlf)$/,
50
- /^extensions\.objectformat$/,
51
- /^remote\.[A-Za-z0-9._/-]+\.(url|pushurl|fetch|push|tagopt|prune|prunetags|mirror|followremotehead)$/,
52
- /^branch\.[A-Za-z0-9._/-]+\.(remote|merge|rebase|pushremote|description)$/,
53
- /^user\.(name|email|useconfigonly)$/,
54
- ];
55
-
56
- /** Stock sources read cwd, its Git root and, for plugin registries, ancestors above the root. */
57
- export function assertWorkerWorkspaceStartup(cwd: string, home: string): void {
58
- for (let dir = cwd; ; dir = dirname(dir)) {
59
- if (dir === home || (dir !== cwd && ["/tmp", "/private/tmp", "/var/tmp", "/private/var/tmp"].includes(dir))) break;
60
- for (const name of projectInputs) {
61
- if (lstatSync(join(dir, name), { throwIfNoEntry: false }))
62
- throw new WorkerRefusal(`Worker startup refuses project configuration (${name}); use a checkout without ambient OMP inputs`);
63
- }
64
- if (dirname(dir) === dir) break;
65
- }
66
- }
67
43
 
68
44
  function readProfileFile(path: string, mode?: number): Buffer | undefined {
69
45
  try { return readWorkerFile(path, mode); }
@@ -159,20 +135,6 @@ function workerProfileInputs(agent: string, repos: WorkerPolicy["repos"]) {
159
135
  return { disabledProviders: [...disabledProviders], extensionPaths };
160
136
  }
161
137
 
162
- function pathEnvironment(source: NodeJS.ProcessEnv, repos: WorkerPolicy["repos"]): string {
163
- const dirs = new Set<string>();
164
- for (const raw of (source.PATH ?? "").split(delimiter)) {
165
- if (!isAbsolute(raw) || controls.test(raw)) continue;
166
- try { dirs.add(trustedWorkerPath(realpathSync(raw), repos, "directory")); }
167
- catch (error) {
168
- if (!(error instanceof WorkerRefusal) && !(error instanceof Error && "code" in error && error.code === "ENOENT")) throw error;
169
- }
170
- }
171
- for (const dir of ["/usr/bin", "/bin", "/usr/sbin", "/sbin"])
172
- if (lstatSync(dir, { throwIfNoEntry: false })) dirs.add(realpathSync(dir));
173
- return [...dirs].join(delimiter);
174
- }
175
-
176
138
  /** Project checks and target profile checks run before either OMP or the SDK preparation process starts. */
177
139
  export function workerLaunchProfile(policy: WorkerPolicy, cwd: string, source: NodeJS.ProcessEnv = process.env) {
178
140
  const { repos, stateDir, command } = policy;
@@ -180,7 +142,10 @@ export function workerLaunchProfile(policy: WorkerPolicy, cwd: string, source: N
180
142
  if (command.length !== 1 || executable === undefined)
181
143
  throw new WorkerRefusal("Worker startup requires one enrolled stock OMP executable, with no extra arguments");
182
144
  const home = trustedWorkerPath(source.HOME ?? "", repos, "directory");
183
- assertWorkerWorkspaceStartup(cwd, home);
145
+ const repo = repos.filter(repo => workerPathContains(repo.cwd, cwd))
146
+ .sort((left, right) => right.cwd.length - left.cwd.length)[0];
147
+ const trustedWorkspaceRoot = repo?.trustedCheckout ? repo.cwd : undefined;
148
+ const projectSettings = assertWorkerWorkspaceStartup(cwd, home, trustedWorkspaceRoot);
184
149
  assertWorkerWorkspaceStartup(stateDir, home);
185
150
  trustedWorkerPath(executable, repos, "file");
186
151
  trustedWorkerPath(workerInstallRoot, repos, "directory");
@@ -196,14 +161,17 @@ export function workerLaunchProfile(policy: WorkerPolicy, cwd: string, source: N
196
161
  const defaultAgent = join(root, "agent");
197
162
  const agent = trustedWorkerPath((profileName ? undefined : source.PI_CODING_AGENT_DIR) || defaultAgent, repos, "profile");
198
163
  const env: Record<string, string> = {
199
- HOME: home, PATH: pathEnvironment(source, repos), PI_CODING_AGENT_DIR: agent,
164
+ HOME: home, PATH: workerCommandPath(source, repos), PI_CODING_AGENT_DIR: agent,
200
165
  ...(profileName ? { OMP_PROFILE: profileName } : {}),
201
166
  // Stock OMP can also ask Git about the current workspace during startup.
202
167
  GIT_CONFIG_NOSYSTEM: "1", GIT_CONFIG_GLOBAL: "/dev/null",
203
168
  GIT_CONFIG_COUNT: "2", GIT_CONFIG_KEY_0: "core.fsmonitor", GIT_CONFIG_VALUE_0: "false",
204
169
  GIT_CONFIG_KEY_1: "core.hooksPath", GIT_CONFIG_VALUE_1: "/dev/null",
205
170
  };
206
- for (const name of ["LANG", "LC_ALL", "LC_CTYPE", "NO_COLOR", ...providerEnvironment]) {
171
+ // An opted-in project can have local Git filters and ordinary project scripts.
172
+ // Authenticate OMP from its private stored profile, not secrets inherited by subprocesses.
173
+ const providerEnv = trustedWorkspaceRoot ? [] : providerEnvironment;
174
+ for (const name of ["LANG", "LC_ALL", "LC_CTYPE", "NO_COLOR", ...providerEnv]) {
207
175
  const value = source[name];
208
176
  if (value && !value.includes("\0")) env[name] = value;
209
177
  }
@@ -225,7 +193,7 @@ export function workerLaunchProfile(policy: WorkerPolicy, cwd: string, source: N
225
193
  }
226
194
  }
227
195
  for (const dir of new Set([home, base, root, agent])) {
228
- if ([...dotenv, ".bunfig.toml", "bunfig.toml"].some(name => lstatSync(join(dir, name), { throwIfNoEntry: false })))
196
+ if ([...workerDotenvFiles, ".bunfig.toml", "bunfig.toml"].some(name => lstatSync(join(dir, name), { throwIfNoEntry: false })))
229
197
  throw new WorkerRefusal("Worker startup does not read target dotenv or Bun preload configuration; use the target profile's stored auth");
230
198
  }
231
199
  for (const dir of pluginRoots) {
@@ -241,7 +209,7 @@ export function workerLaunchProfile(policy: WorkerPolicy, cwd: string, source: N
241
209
  }
242
210
  const { disabledProviders, extensionPaths } = workerProfileInputs(agent, repos);
243
211
  assertWorkerAuthDatabase(join(authDbRoot, "agent.db"));
244
- return { env, profile: { config: { ...config, disabledProviders }, flags, extensionPaths }, executable };
212
+ return { env, profile: { config: { ...projectSettings, ...config, disabledProviders }, flags, extensionPaths, trustedWorkspaceRoot }, executable };
245
213
  }
246
214
 
247
215
  export async function workerManagedUlwPath(repos: WorkerPolicy["repos"]): Promise<string> {
@@ -250,21 +218,6 @@ export async function workerManagedUlwPath(repos: WorkerPolicy["repos"]): Promis
250
218
  catch (cause) { throw new WorkerRefusal("Worker requires an active operator-installed managed superkit outside enrolled checkouts", { cause }); }
251
219
  }
252
220
 
253
- /** Stock Git may interpret more configuration than the read-only checkout verifier. */
254
- export async function assertWorkerGitStartup(repo: WorkerRepo): Promise<void> {
255
- const metadata = join(repo.cwd, ".git");
256
- const configFile = join(metadata, "config");
257
- const stat = lstatSync(configFile, { throwIfNoEntry: false });
258
- if (!stat?.isFile() || stat.uid !== process.getuid?.() || (stat.mode & 0o022) !== 0 ||
259
- lstatSync(join(metadata, "config.worktree"), { throwIfNoEntry: false }))
260
- throw new WorkerRefusal("Worker startup requires an owned regular Git config without worktree overrides");
261
- const values = await gitWorkerRepository(repo.cwd, ["config", "--local", "--no-includes", "--null", "--list"]);
262
- if (!values?.endsWith("\0") || values.slice(0, -1).split("\0").some(entry => {
263
- const key = entry.split("\n", 1)[0] ?? "";
264
- return !gitSettings.some(allowed => allowed.test(key));
265
- })) throw new WorkerRefusal("Worker startup refuses nonstandard local Git configuration (including hooks, filters and includes)");
266
- }
267
-
268
221
  /** Required public launch switches must be advertised by the enrolled binary, not the bundled SDK. */
269
222
  export async function requireWorkerStartupFlags(executable: string, cwd: string, env: Record<string, string>): Promise<void> {
270
223
  const child = Bun.spawn([executable, "--help"], {