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
@@ -1,9 +1,19 @@
1
1
  import { closeSync, constants, fstatSync, fsyncSync, linkSync, lstatSync, mkdirSync, openSync, readFileSync, realpathSync, unlinkSync, writeFileSync } from "node:fs";
2
2
  import { dirname, isAbsolute, join, relative, sep } from "node:path";
3
- import { gitWorkerRepository, workerIndexHasOrdinaryFiles, workerMemoryRepositoryMatches, workerRepositoryHead, workerRepositoryIdentity } from "./worker-repository";
3
+ import { Type, type Static } from "@sinclair/typebox/type";
4
+ import { assertWorkerGitRead, assertWorkerGitStartup } from "./worker-git-startup";
5
+ import { gitWorkerRepository, workerCurrentRevision, workerIndexHasOrdinaryFiles, workerMemoryRepositoryMatches,
6
+ workerRepositoryHead, workerRepositoryIdentity } from "./worker-repository";
4
7
  import { WorkerRefusal } from "./worker-request";
5
8
  import { trustedWorkerPath } from "./worker-trust";
6
- import type { WorkerLaneRef, WorkerPolicy, WorkerRepo } from "./worker-wire";
9
+ import { workerCheckoutSchema, workerRevisionSchema, type WorkerPolicy, type WorkerRepo, type WorkerWorkspace } from "./worker-wire";
10
+
11
+ export const workerCheckoutPinSchema = Type.Object({
12
+ repoRoot: Type.String(), gitDir: Type.String(), subdir: Type.String(), repoId: Type.String(),
13
+ checkoutIdentity: workerCheckoutSchema, revision: workerRevisionSchema,
14
+ }, { additionalProperties: false });
15
+ export type WorkerCheckoutPin = Readonly<Static<typeof workerCheckoutPinSchema>>;
16
+ export type WorkerCheckoutProof = Pick<WorkerCheckoutPin, "checkoutIdentity" | "revision">;
7
17
 
8
18
  export function privateWorkerDirectory(directory: string, create = false): boolean {
9
19
  if (create) mkdirSync(directory, { mode: 0o700, recursive: true });
@@ -61,16 +71,74 @@ export function workerCheckoutIdentity(repoRoot: string, gitDir: string, cwd: st
61
71
  }
62
72
  }
63
73
 
64
- export async function boundWorkspace(repo: WorkerRepo, ref: Pick<WorkerLaneRef, "revision" | "subdir">,
65
- continuation?: { readonly gitDir: string; readonly checkoutIdentity: string }): Promise<string> {
66
- const cwd = join(repo.cwd, ref.subdir);
74
+ export function matchesWorkerCheckoutDirectory(cwd: string, pin: WorkerCheckoutPin): boolean {
75
+ return join(pin.repoRoot, pin.subdir) === cwd && join(pin.repoRoot, ".git") === pin.gitDir
76
+ && workerCheckoutIdentity(pin.repoRoot, pin.gitDir, cwd) === pin.checkoutIdentity;
77
+ }
78
+
79
+ /** Re-attest the physical checkout and base commit for the exact native session. */
80
+ export async function attestWorkerCheckout(cwd: string, pin: WorkerCheckoutPin): Promise<WorkerCheckoutProof> {
81
+ const observe = () => {
82
+ // "." denotes the directory stock OMP actually entered, even if its
83
+ // former pathname (still in session metadata) now names another inode.
84
+ const { dev, ino } = lstatSync(".", { bigint: true });
85
+ const observed = workerCheckoutIdentity(pin.repoRoot, pin.gitDir, cwd);
86
+ return observed?.endsWith(`/${dev}:${ino}`) && join(pin.repoRoot, pin.subdir) === cwd ? observed : null;
87
+ };
88
+ const checkoutIdentity = observe();
89
+ if (checkoutIdentity !== pin.checkoutIdentity)
90
+ throw new WorkerRefusal("Worker-current checkout directories changed during native attestation");
91
+ await assertWorkerGitRead(pin.repoRoot, pin.gitDir);
92
+ const revision = await workerCurrentRevision(pin.repoRoot, pin.gitDir, cwd, pin.repoId);
93
+ if (revision !== pin.revision || observe() !== checkoutIdentity)
94
+ throw new WorkerRefusal("Worker-current checkout identity or Git revision changed during native attestation");
95
+ return { checkoutIdentity, revision };
96
+ }
97
+
98
+ function workspaceDirectory(repo: WorkerRepo, subdir: string): string {
99
+ const cwd = join(repo.cwd, subdir);
67
100
  if (!lstatSync(cwd, { throwIfNoEntry: false })?.isDirectory() || realpathSync(cwd) !== cwd || !within(repo.cwd, cwd))
68
101
  throw new WorkerRefusal("Worker subdirectory is not a canonical directory inside its enrolled checkout");
102
+ return cwd;
103
+ }
104
+
105
+ /** First placement only reads the worker's physical binding and base commit, not its changed files. */
106
+ export async function workerCurrentCheckout(repo: WorkerRepo, subdir: string, gitDir = join(repo.cwd, ".git")) {
107
+ if (!repo.currentWorkspace) throw new WorkerRefusal("Worker-current placement is not approved for this repository");
108
+ const cwd = workspaceDirectory(repo, subdir);
109
+ const workerCheckout = workerCheckoutIdentity(repo.cwd, gitDir, cwd);
110
+ if (!workerCheckout) throw new WorkerRefusal("Worker-current requires an owned physical checkout");
111
+ for (let dir = cwd; dir !== repo.cwd; dir = dirname(dir)) {
112
+ if (lstatSync(join(dir, ".git"), { throwIfNoEntry: false }))
113
+ throw new WorkerRefusal("Worker-current placement cannot select a nested Git checkout");
114
+ }
115
+ await assertWorkerGitStartup(repo);
116
+ if (!repo.trustedCheckout && !await workerIndexHasOrdinaryFiles(repo.cwd, gitDir))
117
+ throw new WorkerRefusal("Worker-current placement requires a verifiable index without submodules");
118
+ const revision = await workerCurrentRevision(repo.cwd, gitDir, cwd, repo.id);
119
+ if (!revision || workerCheckout !== workerCheckoutIdentity(repo.cwd, gitDir, cwd))
120
+ throw new WorkerRefusal("Worker-current checkout identity or Git base could not be verified");
121
+ return { revision, workerCheckout };
122
+ }
123
+
124
+ export async function boundWorkspace(repo: WorkerRepo, ref: Pick<WorkerWorkspace, "revision" | "subdir" | "workerCheckout">,
125
+ continuation?: { readonly gitDir: string; readonly checkoutIdentity: string }): Promise<string> {
126
+ const cwd = workspaceDirectory(repo, ref.subdir);
127
+ if (ref.workerCheckout) {
128
+ const observed = await workerCurrentCheckout(repo, ref.subdir, continuation?.gitDir);
129
+ if (observed.workerCheckout !== ref.workerCheckout || observed.revision !== ref.revision
130
+ || continuation && observed.workerCheckout !== continuation.checkoutIdentity)
131
+ throw new WorkerRefusal("Worker-current placement no longer matches the original checkout and Git revision");
132
+ return cwd;
133
+ }
69
134
  if (continuation) {
70
135
  const { gitDir, checkoutIdentity } = continuation;
71
136
  const unchanged = () => workerCheckoutIdentity(repo.cwd, gitDir, cwd) === checkoutIdentity;
72
- // Like the clean preflight, check the exact Git binding after the asynchronous index scan.
73
- if (!unchanged() || !await workerIndexHasOrdinaryFiles(repo.cwd, gitDir)
137
+ if (!unchanged()) throw new WorkerRefusal("Worker continuation no longer matches the original checkout and Git revision");
138
+ // Trusted startup already verifies the index, including approved submodules.
139
+ // In either mode, check the exact Git binding after the asynchronous scan.
140
+ await assertWorkerGitStartup(repo);
141
+ if ((!repo.trustedCheckout && !await workerIndexHasOrdinaryFiles(repo.cwd, gitDir))
74
142
  || !await workerMemoryRepositoryMatches(cwd, { ...ref, repoId: repo.id, repoRoot: repo.cwd, gitDir }) || !unchanged())
75
143
  throw new WorkerRefusal("Worker continuation no longer matches the original checkout and Git revision");
76
144
  return cwd;
@@ -82,7 +150,12 @@ export async function boundWorkspace(repo: WorkerRepo, ref: Pick<WorkerLaneRef,
82
150
  }
83
151
 
84
152
  const claimName = "omp-sa-checkout.lock";
85
- type CheckoutClaim = { readonly gitDir: string; readonly attempt: string };
153
+ type CheckoutClaim = { readonly gitDir: string; readonly attempt: string; readonly checkoutIdentity?: string };
154
+
155
+ /** Occupancy is only a readiness hint; an exclusive claim still arbitrates simultaneous opens. */
156
+ export function checkoutClaimed(gitDir: string): boolean {
157
+ return !!lstatSync(join(gitDir, claimName), { throwIfNoEntry: false });
158
+ }
86
159
 
87
160
  function readClaim(gitDir: string) {
88
161
  const path = join(gitDir, claimName);
@@ -127,10 +200,17 @@ export function ownsCheckout({ gitDir, attempt }: CheckoutClaim): boolean {
127
200
  }
128
201
 
129
202
  /** Never remove another attempt's claim. The lane ledger serializes release of our own claim. */
130
- export function releaseCheckout({ gitDir, attempt }: CheckoutClaim): void {
203
+ export function releaseCheckout({ gitDir, attempt, checkoutIdentity }: CheckoutClaim): void {
131
204
  if (realpathSync(gitDir) !== gitDir) throw new WorkerRefusal("Checkout reservation directory changed");
132
205
  const claim = readClaim(gitDir);
133
206
  if (claim?.value !== attempt) return;
207
+ if (checkoutIdentity) {
208
+ // A replaced work directory can cause launch to fail without moving the
209
+ // claim. Match the metadata directory that actually holds the lock.
210
+ const git = lstatSync(gitDir, { bigint: true });
211
+ if (`${git.dev}:${git.ino}` !== checkoutIdentity.split("/")[1])
212
+ throw new WorkerRefusal("Checkout reservation directory changed");
213
+ }
134
214
  const path = join(gitDir, claimName);
135
215
  const current = lstatSync(path, { throwIfNoEntry: false });
136
216
  if (!current || claim.info.dev !== current.dev || claim.info.ino !== current.ino)
@@ -1,10 +1,11 @@
1
- /** Enrollment pins the full destination, including a non-default OpenSSH port.
2
- * SSH config aliases and arbitrary client options are not part of this syntax. */
1
+ import { isIPv6 } from "node:net";
2
+
3
+ /** Pin the byte transport as part of the enrollment; never interpret SSH options or shell words. */
3
4
  export function parseWorkerDestination(value: string) {
4
5
  if (value.length > 320) return;
5
- const match = /^([A-Za-z0-9_][\w.-]*@[A-Za-z0-9][\w.-]*)(?::([1-9][0-9]{0,4}))?(?![\s\S])/.exec(value);
6
- if (!match?.[1]) return;
7
- const port = match[2];
8
- if (port && Number(port) > 65535) return;
9
- return { login: match[1], port };
6
+ const match = /^(tailscale:\/\/)?([A-Za-z0-9_][\w.-]*)@(?:([A-Za-z0-9][\w.-]*)|\[([A-Fa-f0-9:.]+)\])(?::([1-9][0-9]{0,4}))?(?![\s\S])/.exec(value);
7
+ if (!match) return;
8
+ const [, tailnet, user, hostname, ipv6, port] = match;
9
+ if ((ipv6 && !isIPv6(ipv6)) || (port && Number(port) > 65535)) return;
10
+ return { login: `${user}@${hostname ?? ipv6}`, port, tailnet: !!tailnet };
10
11
  }
@@ -1,8 +1,8 @@
1
- import { listWorkers, matchWorkerDescription, WorkerRegistrationError } from "./worker-registration";
1
+ import { listWorkers, matchWorkerDescription, verifyCurrentDefaultCheckout, WorkerRegistrationError } from "./worker-registration";
2
2
  import { workerRepositoryHead } from "./worker-repository";
3
- import { workerDescribe, type WorkerDescription, type WorkerLaneRef, type WorkerRegistration } from "./worker-wire";
3
+ import { workerDescribe, workerDescribeCurrent, type WorkerRegistration, type WorkerWorkspace } from "./worker-wire";
4
4
 
5
- type Workspace = Pick<WorkerLaneRef, "repoId" | "revision" | "subdir">;
5
+ type Workspace = WorkerWorkspace | Pick<WorkerWorkspace, "repoId" | "subdir">;
6
6
 
7
7
  function verifiedWorker({ destination, description, defaultRepository }: WorkerRegistration) {
8
8
  const { active: _enrollmentSnapshot, ...verified } = description;
@@ -15,15 +15,23 @@ export function workerInventory(stateDir: string) {
15
15
  }
16
16
 
17
17
  async function describeEnrollment(registration: WorkerRegistration, workspace?: Workspace) {
18
- let reply: WorkerDescription;
19
- try { reply = await workerDescribe(registration, workspace); }
18
+ let reply: Awaited<ReturnType<typeof workerDescribe>>;
19
+ let current: Awaited<ReturnType<typeof workerDescribeCurrent>>["workspace"] | undefined;
20
+ try {
21
+ if (workspace && !("revision" in workspace)) {
22
+ const observation = await workerDescribeCurrent(registration, workspace);
23
+ current = observation.workspace;
24
+ reply = observation;
25
+ } else reply = await workerDescribe(registration, workspace);
26
+ }
20
27
  catch (error) {
21
28
  if (error instanceof WorkerRegistrationError)
22
29
  return { reason: "identity-unavailable", detail: "The dedicated SSH identity is missing or unsafe." } as const;
23
30
  if (error instanceof Error) {
24
31
  // Do not surface peer-supplied refusal messages or raw SSH output.
25
- return { reason: "describe-unverified", detail: workspace
32
+ return { reason: "describe-unverified", detail: workspace ? "revision" in workspace
26
33
  ? "The worker did not verify the requested checkout revision through the enrolled connection."
34
+ : "The worker did not verify its enrolled current checkout through the approved connection."
27
35
  : "No verified describe receipt. Check the enrolled OpenSSH endpoint, independently verified host key and target policy." } as const;
28
36
  }
29
37
  throw error;
@@ -32,7 +40,8 @@ async function describeEnrollment(registration: WorkerRegistration, workspace?:
32
40
  const description = matchWorkerDescription(registration.description, reply);
33
41
  if (!description)
34
42
  return { reason: "enrollment-mismatch", detail: "The live description differs from the verified enrollment." } as const;
35
- return { live: { active: description.active, available: description.capacity - description.active } } as const;
43
+ return { live: { active: description.active, available: workspace && reply.checkoutBusy ? 0 : description.capacity - description.active },
44
+ ...(current && { current }) } as const;
36
45
  } catch (error) {
37
46
  if (error instanceof WorkerRegistrationError)
38
47
  return { reason: "invalid-description", detail: "The worker returned an invalid description." } as const;
@@ -48,11 +57,22 @@ export async function workerDoctor(stateDir: string, destination: string) {
48
57
 
49
58
  const worker = verifiedWorker(registration);
50
59
  const observed = await describeEnrollment(registration);
51
- if (!observed.live) return { status: "blocked", worker, check: "worker", ...observed } as const;
60
+ if (!("live" in observed)) return { status: "blocked", worker, check: "worker", ...observed } as const;
52
61
 
53
62
  const { defaultRepository } = registration;
54
63
  if (!defaultRepository) return { status: "ok", worker, live: observed.live } as const;
55
64
 
65
+ if (defaultRepository.mode === "current") {
66
+ const localDrift = { status: "blocked", worker, live: observed.live, check: "default-workspace", reason: "local-checkout-unverified",
67
+ detail: "The enrolled current default path must still resolve to the original physical local checkout and Git repository identity." } as const;
68
+ if (!await verifyCurrentDefaultCheckout(defaultRepository)) return localDrift;
69
+ const workspace = { repoId: defaultRepository.repoId, subdir: "" };
70
+ const scoped = await describeEnrollment(registration, workspace);
71
+ if (!("live" in scoped)) return { status: "blocked", worker, live: observed.live, check: "default-workspace", workspace, ...scoped } as const;
72
+ if (!await verifyCurrentDefaultCheckout(defaultRepository)) return localDrift;
73
+ return { status: "ok", worker, live: scoped.live, workspace: { ...workspace, ...scoped.current } } as const;
74
+ }
75
+
56
76
  const source = await workerRepositoryHead(defaultRepository.root);
57
77
  if (!source || source.root !== defaultRepository.root || source.repoId !== defaultRepository.repoId || source.subdir !== "")
58
78
  return { status: "blocked", worker, live: observed.live, check: "default-workspace", reason: "local-checkout-unverified",
@@ -61,6 +81,6 @@ export async function workerDoctor(stateDir: string, destination: string) {
61
81
  // Send only the authorized repository binding, never the head-side path.
62
82
  const { root: _root, ...workspace } = source;
63
83
  const scoped = await describeEnrollment(registration, workspace);
64
- if (!scoped.live) return { status: "blocked", worker, live: observed.live, check: "default-workspace", workspace, ...scoped } as const;
84
+ if (!("live" in scoped)) return { status: "blocked", worker, live: observed.live, check: "default-workspace", workspace, ...scoped } as const;
65
85
  return { status: "ok", worker, live: scoped.live, workspace } as const;
66
86
  }
@@ -14,7 +14,7 @@ import {
14
14
  workerHash, workerPublicKey, WorkerRegistrationError,
15
15
  } from "./worker-registration";
16
16
  import { gitWorkerRepository, workerRepositoryIdentity } from "./worker-repository";
17
- import { trustedWorkerPath, workerInstallRoot } from "./worker-trust";
17
+ import { trustedWorkerPath, workerCommandPath, workerInstallRoot } from "./worker-trust";
18
18
  import type { WorkerPolicy, WorkerRepo } from "./worker-wire";
19
19
 
20
20
  const policyRoot = ".omp-sa-worker";
@@ -26,9 +26,12 @@ const policySchema = Type.Object({
26
26
  fingerprint: Type.String({ pattern: hashPattern }),
27
27
  workerId: Type.String({ pattern: "^worker-[0-9a-f-]{36}$" }),
28
28
  stateDir: Type.String(),
29
- repos: Type.Array(Type.Object({ id: Type.String({ pattern: hashPattern }), cwd: Type.String() }, { additionalProperties: false }),
30
- { minItems: 1, maxItems: maxRepositories }),
31
- capacity: Type.Literal(1),
29
+ repos: Type.Array(Type.Object({
30
+ id: Type.String({ pattern: hashPattern }), cwd: Type.String(),
31
+ currentWorkspace: Type.Optional(Type.Literal(true)),
32
+ trustedCheckout: Type.Optional(Type.Literal(true)),
33
+ }, { additionalProperties: false }), { minItems: 1, maxItems: maxRepositories }),
34
+ capacity: Type.Integer({ minimum: 1, maximum: maxRepositories }),
32
35
  command: Type.Tuple([Type.String()]),
33
36
  }, { additionalProperties: false });
34
37
 
@@ -40,6 +43,7 @@ function policyAt(path: string) {
40
43
  basename(stored.stateDir) !== stored.fingerprint.slice(0, 16) ||
41
44
  controls.test(stored.stateDir) || controls.test(stored.workerId) ||
42
45
  !isAbsolute(stored.command[0]) || controls.test(stored.command[0]) ||
46
+ stored.capacity > stored.repos.length ||
43
47
  stored.repos.some(repo => !isAbsolute(repo.cwd) || controls.test(repo.cwd) || controls.test(repo.id)) ||
44
48
  new Set(stored.repos.map(repo => repo.id)).size !== stored.repos.length)
45
49
  throw new WorkerRegistrationError("Invalid target worker policy");
@@ -89,20 +93,27 @@ function appendAuthorization(path: string, expected: string, baseline: Buffer |
89
93
  } finally { closeSync(fd); }
90
94
  }
91
95
 
92
- async function targetRepositories(paths: readonly string[], directory: string): Promise<WorkerRepo[]> {
96
+ type EnrollmentCheckout = { readonly path: string; readonly mode: "exact" | "current" | "trusted" };
97
+
98
+ async function targetRepositories(checkouts: readonly EnrollmentCheckout[], directory: string): Promise<WorkerRepo[]> {
93
99
  const repos: WorkerRepo[] = [];
94
100
  const inside = (root: string, path: string) => root === path || path.startsWith(root === "/" ? "/" : `${root}/`);
95
- for (const path of paths) {
101
+ for (const { path, mode } of checkouts) {
96
102
  const cwd = realpathSync(path);
97
103
  if (controls.test(cwd) || !lstatSync(cwd).isDirectory() ||
98
104
  await gitWorkerRepository(cwd, ["rev-parse", "--show-toplevel"]) !== `${cwd}\n`)
99
- throw new WorkerRegistrationError("Each --repo must be the root of an existing non-bare Git checkout");
105
+ throw new WorkerRegistrationError("Each enrolled path must be the root of an existing non-bare Git checkout");
100
106
  if (inside(cwd, directory) || inside(directory, cwd))
101
107
  throw new WorkerRegistrationError("Worker state and enrolled Git checkouts must not overlap");
102
108
  const id = await workerRepositoryIdentity(cwd);
103
109
  if (!id || repos.some(repo => repo.id === id))
104
110
  throw new WorkerRegistrationError("Each enrolled Git checkout needs a distinct verifiable network origin");
105
- repos.push({ id, cwd });
111
+ if (mode === "trusted") trustedWorkerPath(cwd, [], "directory");
112
+ repos.push({
113
+ id, cwd,
114
+ ...(mode !== "exact" && { currentWorkspace: true as const }),
115
+ ...(mode === "trusted" && { trustedCheckout: true as const }),
116
+ });
106
117
  }
107
118
  return repos.sort((left, right) => left.id.localeCompare(right.id));
108
119
  }
@@ -110,6 +121,10 @@ async function targetRepositories(paths: readonly string[], directory: string):
110
121
  /** Explicit target-side authorization; the CLI separately checks native prerequisites. */
111
122
  export async function enrollWorker(options: {
112
123
  readonly home: string; readonly headKey: string; readonly repositories: readonly string[]; readonly executable: string;
124
+ readonly capacity?: number;
125
+ readonly currentRepositories?: readonly string[];
126
+ readonly trustedRepositories?: readonly string[];
127
+ readonly checkExecutable?: (executable: string, environment: Record<string, string>) => Promise<unknown>;
113
128
  }): Promise<WorkerPolicy> {
114
129
  const key = workerPublicKey(options.headKey);
115
130
  const fingerprint = workerHash(key);
@@ -121,26 +136,43 @@ export async function enrollWorker(options: {
121
136
  const ssh = join(home, ".ssh");
122
137
  if (controls.test(stateDir) || Buffer.byteLength(join(stateDir, "run", `lane-${"0".repeat(24)}.sock`)) > 100)
123
138
  throw new WorkerRegistrationError("Target account home cannot be used for worker Unix sockets");
124
- if (!options.repositories.length || options.repositories.length > maxRepositories)
139
+ const checkouts: EnrollmentCheckout[] = [
140
+ ...options.repositories.map(path => ({ path, mode: "exact" as const })),
141
+ ...(options.currentRepositories ?? []).map(path => ({ path, mode: "current" as const })),
142
+ ...(options.trustedRepositories ?? []).map(path => ({ path, mode: "trusted" as const })),
143
+ ];
144
+ if (!checkouts.length || checkouts.length > maxRepositories)
125
145
  throw new WorkerRegistrationError(`Target enrollment requires 1–${maxRepositories} Git checkouts`);
126
- const repos = await targetRepositories(options.repositories, stateDir);
146
+ const capacity = options.capacity ?? 1;
147
+ if (!Number.isSafeInteger(capacity) || capacity < 1 || capacity > checkouts.length)
148
+ throw new WorkerRegistrationError("Worker capacity must be between one and the number of independent enrolled checkouts");
149
+ const repos = await targetRepositories(checkouts, stateDir);
150
+ if (capacity > 1) {
151
+ // Independent slots must not authorize two writers in overlapping directory trees.
152
+ for (const repo of repos) trustedWorkerPath(repo.cwd, repos.filter(other => other !== repo), "directory");
153
+ }
127
154
  const executable = trustedWorkerPath(realpathSync(options.executable), repos, "file");
128
155
  const command = [executable];
129
156
  const line = enrollmentAuthorization(path, key, repos);
130
157
  // Run every trust check before making policy, lock, or SSH directories.
131
158
  trustedWorkerPath(stateDir, repos, "profile");
132
159
  trustedWorkerPath(ssh, repos, "profile");
160
+ if (options.checkExecutable) {
161
+ const { assertWorkerWorkspaceStartup } = await import("./worker-project-startup");
162
+ assertWorkerWorkspaceStartup("/", home);
163
+ await options.checkExecutable(executable, { HOME: home, PATH: workerCommandPath(process.env, repos) });
164
+ }
133
165
  workerDirectory(root, 0o700, true);
134
166
  return await withWorkerWriteLock(join(root, "init.lock"), () => {
135
167
  workerDirectory(stateDir, 0o700, true);
136
168
  workerDirectory(ssh, 0o755, true);
137
169
  const previous = policyAt(path);
138
- if (previous && (previous.fingerprint !== fingerprint ||
170
+ if (previous && (previous.fingerprint !== fingerprint || previous.capacity !== capacity ||
139
171
  !Bun.deepEquals(previous.repos, repos) || !Bun.deepEquals(previous.command, command)))
140
172
  throw new WorkerRegistrationError("Enrollment already has a different policy; no policy or authorization was overwritten");
141
173
  const auth = join(ssh, "authorized_keys");
142
174
  const snapshot = authorizationSnapshot(auth, key, line, previous !== undefined);
143
- const policy: WorkerPolicy = { workerId: previous?.workerId ?? `worker-${randomUUID()}`, stateDir, repos, capacity: 1, command };
175
+ const policy: WorkerPolicy = { workerId: previous?.workerId ?? `worker-${randomUUID()}`, stateDir, repos, capacity, command };
144
176
  if (!previous) {
145
177
  const temporary = stagePrivateFile(path, `${JSON.stringify({ fingerprint, ...policy }, null, 2)}\n`);
146
178
  try { linkSync(temporary, path); }
@@ -0,0 +1,157 @@
1
+ import { lstatSync, readdirSync, realpathSync } from "node:fs";
2
+ import { isAbsolute, join, resolve } from "node:path";
3
+ import { checkWorkerFile, readWorkerFile } from "./worker-registration";
4
+ import { gitWorkerRepository, workerIndexHasOrdinaryFiles } from "./worker-repository";
5
+ import { WorkerRefusal } from "./worker-request";
6
+ import { trustedWorkerPath } from "./worker-trust";
7
+ import type { WorkerRepo } from "./worker-wire";
8
+
9
+ const gitSettings = [
10
+ /^core\.(repositoryformatversion|filemode|bare|logallrefupdates|ignorecase|precomposeunicode|symlinks|autocrlf|eol|safecrlf)$/,
11
+ /^extensions\.objectformat$/,
12
+ /^remote\.[A-Za-z0-9._/-]+\.(url|pushurl|fetch|push|tagopt|prune|prunetags|mirror|followremotehead)$/,
13
+ /^branch\.[A-Za-z0-9._/-]+\.(remote|merge|rebase|pushremote|description)$/,
14
+ /^user\.(name|email|useconfigonly)$/,
15
+ ];
16
+ // These preferences choose behavior for explicit Git operations, not startup executables.
17
+ const trustedGitPreferences = /^(?:fetch\.prune|pull\.(?:ff|rebase)|push\.default)$/u;
18
+ const filterKey = /^filter\.[A-Za-z0-9._/-]+\.(clean|smudge|process|required)$/u;
19
+ const moduleKey = /^submodule\.(.+)\.(path|url|update|branch|ignore|active|fetchrecursesubmodules|shallow)$/u;
20
+ const moduleUpdates = new Set(["checkout", "rebase", "merge", "none"]);
21
+ const controls = /[\u0000-\u001f\u007f\\]/u;
22
+
23
+ type ConfigEntry = readonly [key: string, value: string];
24
+ type GitCheckout = { readonly cwd: string; readonly gitDir: string; readonly submodule?: true };
25
+
26
+ function safeRelative(path: string): boolean {
27
+ return !!path && !isAbsolute(path) && !controls.test(path) &&
28
+ path.split("/").every(part => part && part !== "." && part !== ".." && part.toLowerCase() !== ".git");
29
+ }
30
+
31
+ function moduleValue(key: string, value: string): boolean {
32
+ if (key === "update") return moduleUpdates.has(value);
33
+ if (key !== "url") return true;
34
+ // Known Git network protocols, scp-style SSH and ordinary local/relative paths.
35
+ // No external remote-helper transport selectors (name::payload).
36
+ return !!value && !controls.test(value) && !value.startsWith("-") && !value.includes("::") &&
37
+ (!value.includes("://") || /^(?:https?|ssh|git|file):\/\//u.test(value));
38
+ }
39
+
40
+ async function configEntries(cwd: string, path: string): Promise<ConfigEntry[]> {
41
+ const values = await gitWorkerRepository(cwd, ["config", "--file", path, "--no-includes", "--null", "--list"]);
42
+ if (values === "") return [];
43
+ if (!values?.endsWith("\0")) throw new WorkerRefusal("Worker startup could not read bounded local Git configuration");
44
+ return values.slice(0, -1).split("\0").map(entry => {
45
+ const newline = entry.indexOf("\n");
46
+ return newline < 0 ? [entry, ""] : [entry.slice(0, newline), entry.slice(newline + 1)];
47
+ });
48
+ }
49
+
50
+ async function assertConfig(checkout: GitCheckout, trusted: boolean): Promise<void> {
51
+ const { cwd, gitDir, submodule } = checkout;
52
+ const configFile = join(gitDir, "config");
53
+ try {
54
+ checkWorkerFile(lstatSync(configFile), 0o644);
55
+ if (lstatSync(join(gitDir, "config.worktree"), { throwIfNoEntry: false })) throw new Error();
56
+ } catch {
57
+ throw new WorkerRefusal("Worker startup requires an owned regular Git config without worktree overrides");
58
+ }
59
+ const values = await configEntries(cwd, configFile);
60
+ const worktrees = values.filter(([key]) => key === "core.worktree");
61
+ if (values.some(([key, value]) => {
62
+ if (gitSettings.some(allowed => allowed.test(key)))
63
+ return trusted && /^remote\..+\.(url|pushurl)$/u.test(key) && !moduleValue("url", value);
64
+ if (!trusted) return true;
65
+ if (trustedGitPreferences.test(key) || filterKey.test(key) || key === "submodule.active") return false;
66
+ if (submodule && key === "core.worktree")
67
+ return worktrees.length !== 1 || !value || controls.test(value) || resolve(gitDir, value) !== cwd;
68
+ const [, name, field] = moduleKey.exec(key) ?? [];
69
+ return !name || !field || !safeRelative(name) || field === "path" || !moduleValue(field, value);
70
+ })) throw new WorkerRefusal("Worker startup refuses nonstandard local Git configuration (including hooks and includes; filters require checkout opt-in)");
71
+ }
72
+
73
+ /** Read-only Git plumbing does not run configured filters or inspect submodules. */
74
+ export async function assertWorkerGitRead(cwd: string, gitDir: string): Promise<void> {
75
+ if (lstatSync(join(gitDir, "commondir"), { throwIfNoEntry: false }))
76
+ throw new WorkerRefusal("Worker-current checkout cannot use a shared Git metadata directory");
77
+ await assertConfig({ cwd, gitDir }, true);
78
+ }
79
+
80
+ async function moduleNames(cwd: string): Promise<Map<string, string>> {
81
+ const path = join(cwd, ".gitmodules");
82
+ const modules = new Map<string, string>();
83
+ const info = lstatSync(path, { throwIfNoEntry: false });
84
+ if (!info) return modules;
85
+ checkWorkerFile(info, 0o644);
86
+ const names = new Set<string>();
87
+ for (const [key, value] of await configEntries(cwd, path)) {
88
+ const [, name, field] = moduleKey.exec(key) ?? [];
89
+ if (!name || !field || !safeRelative(name) || !moduleValue(field, value))
90
+ throw new WorkerRefusal("Worker startup refuses nonstandard submodule declarations");
91
+ if (field !== "path") continue;
92
+ if (!safeRelative(value) || names.has(name) || modules.has(value))
93
+ throw new WorkerRefusal("Worker startup requires uniquely bound submodule paths");
94
+ names.add(name);
95
+ modules.set(value, name);
96
+ }
97
+ return modules;
98
+ }
99
+
100
+ function initializedModule(parent: GitCheckout, path: string, name: string): GitCheckout | undefined {
101
+ const cwd = join(parent.cwd, path);
102
+ const info = lstatSync(cwd, { throwIfNoEntry: false });
103
+ if (!info) return;
104
+ trustedWorkerPath(cwd, [], "directory");
105
+ const marker = join(cwd, ".git");
106
+ const metadata = lstatSync(marker, { throwIfNoEntry: false });
107
+ if (!metadata) {
108
+ if (readdirSync(cwd).length) throw new WorkerRefusal("Worker submodule has no verified Git metadata");
109
+ return;
110
+ }
111
+ let gitDir = marker;
112
+ if (!metadata.isDirectory()) {
113
+ const text = readWorkerFile(marker, 0o644)?.toString("utf8");
114
+ const gitfile = /^gitdir: ([^\r\n]+)\r?\n?$/u.exec(text ?? "")?.[1];
115
+ if (!gitfile || controls.test(gitfile)) throw new WorkerRefusal("Worker submodule has an invalid Git marker");
116
+ gitDir = resolve(cwd, gitfile);
117
+ if (gitDir !== join(parent.gitDir, "modules", name))
118
+ throw new WorkerRefusal("Worker submodule Git metadata is outside its parent checkout binding");
119
+ }
120
+ trustedWorkerPath(gitDir, [], "directory");
121
+ if (realpathSync(gitDir) !== gitDir || lstatSync(join(gitDir, "commondir"), { throwIfNoEntry: false }))
122
+ throw new WorkerRefusal("Worker submodule does not have independent local Git metadata");
123
+ return { cwd, gitDir, submodule: true };
124
+ }
125
+
126
+ async function assertTrustedModules(checkout: GitCheckout, budget: { left: number }, depth: number): Promise<void> {
127
+ const names = await moduleNames(checkout.cwd);
128
+ if (!await workerIndexHasOrdinaryFiles(checkout.cwd, checkout.gitDir, async path => {
129
+ const name = names.get(path);
130
+ if (!name || depth >= 8 || --budget.left < 0) return false;
131
+ const module = initializedModule(checkout, path, name);
132
+ if (module) {
133
+ await assertConfig(module, true);
134
+ const layout = await gitWorkerRepository(module.cwd, ["rev-parse", "--path-format=absolute",
135
+ "--show-toplevel", "--absolute-git-dir", "--git-common-dir"]);
136
+ if (layout !== `${module.cwd}\n${module.gitDir}\n${module.gitDir}\n`)
137
+ throw new WorkerRefusal("Worker submodule layout no longer matches its validated Git metadata");
138
+ await assertTrustedModules(module, budget, depth + 1);
139
+ }
140
+ return true;
141
+ })) throw new WorkerRefusal("Worker startup could not verify the enrolled submodule layout");
142
+ }
143
+
144
+ /** The admission helpers use Git plumbing only. Explicit native lane work may use enrolled local filters. */
145
+ export async function assertWorkerGitStartup(repo: WorkerRepo): Promise<void> {
146
+ const checkout: GitCheckout = { cwd: repo.cwd, gitDir: join(repo.cwd, ".git") };
147
+ await assertConfig(checkout, repo.trustedCheckout === true);
148
+ if (!repo.trustedCheckout) return;
149
+ try {
150
+ trustedWorkerPath(checkout.cwd, [], "directory");
151
+ trustedWorkerPath(checkout.gitDir, [], "directory");
152
+ await assertTrustedModules(checkout, { left: 128 }, 0);
153
+ } catch (error) {
154
+ if (error instanceof WorkerRefusal) throw error;
155
+ throw new WorkerRefusal("Worker startup could not verify local submodule configuration");
156
+ }
157
+ }
@@ -1,9 +1,11 @@
1
- import { constants, closeSync, fstatSync, lstatSync, mkdirSync, openSync, readSync, unlinkSync, type Stats } from "node:fs";
1
+ import { lstatSync, mkdirSync, unlinkSync, type Stats } from "node:fs";
2
2
  import { dirname, join } from "node:path";
3
3
  import { Value } from "@sinclair/typebox/value";
4
4
  import { HostConnection } from "../omp/host";
5
+ import { readExitRecord } from "../omp/exit-record";
5
6
  import { NativeJournalFormatError, readNativeSessionId } from "../omp/native-journal";
6
- import { ownsCheckout, privateWorkerDirectory, syncDirectory } from "./worker-checkout";
7
+ import { matchesWorkerCheckoutDirectory, ownsCheckout, privateWorkerDirectory, syncDirectory,
8
+ type WorkerCheckoutPin } from "./worker-checkout";
7
9
  import { workerExit, workerReaped, type WorkerIdentity, type WorkerJournalDirectory, type WorkerLedger, type WorkerReceipt } from "./worker-ledger";
8
10
  import { WorkerRefusal } from "./worker-request";
9
11
  import { trustedWorkerPath } from "./worker-trust";
@@ -106,29 +108,6 @@ export async function readWorkerFiles(paths: WorkerPaths, directory?: WorkerJour
106
108
  return { socket, exit, session, sessionId };
107
109
  }
108
110
 
109
- function readExitRecord(path: string, expected: Stats | undefined): unknown {
110
- if (!expected || expected.size > 4096 || (expected.mode & 0o477) !== 0o400) return null;
111
- let fd: number;
112
- try { fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK); }
113
- catch (error) {
114
- if (permissionDenied(error)) return null;
115
- throw error;
116
- }
117
- try {
118
- const stat = fstatSync(fd);
119
- if (!sameFile(expected, stat) || stat.size !== expected.size || stat.mode !== expected.mode) return null;
120
- const bytes = Buffer.alloc(stat.size);
121
- if (readSync(fd, bytes) !== bytes.length) return null;
122
- const after = fstatSync(fd);
123
- if (after.size !== stat.size || after.mtimeMs !== stat.mtimeMs || after.ctimeMs !== stat.ctimeMs) return null;
124
- try { return JSON.parse(bytes.toString("utf8")); }
125
- catch (error) {
126
- if (error instanceof SyntaxError) return null;
127
- throw error;
128
- }
129
- } finally { closeSync(fd); }
130
- }
131
-
132
111
  function matchesExit(paths: WorkerPaths, receipt: WorkerReceipt, proof: {
133
112
  readonly workerAttempt: string; readonly sessionFile: string; readonly pid: number; readonly ownerPid: number;
134
113
  }): boolean {
@@ -143,7 +122,7 @@ function readVerifiedExit(paths: WorkerPaths, receipt: WorkerReceipt, stat: Stat
143
122
  }
144
123
 
145
124
  function journalHeld() {
146
- return new WorkerRefusal("Worker checkout was released after verified process exit; the original journal remains unverified and cannot reopen");
125
+ return new WorkerRefusal("Worker checkout was released; the original journal remains unverified and cannot reopen");
147
126
  }
148
127
 
149
128
  /** The private owner's receipt, not the damaged journal, decides checkout-only retirement. */
@@ -176,11 +155,22 @@ export function absentWorkerHost(files: WorkerFiles, receipt: WorkerReceipt | nu
176
155
  ...(!uncertain && receipt?.phase === "released" && receipt.exitVerified && { exitGeneration: receipt.generation }) };
177
156
  }
178
157
 
158
+ export function workerCheckoutPin(receipt: WorkerReceipt): WorkerCheckoutPin | undefined {
159
+ const { workerCheckout, checkoutIdentity, repoRoot, gitDir, subdir, repoId, revision } = receipt;
160
+ if (!workerCheckout) return;
161
+ if (workerCheckout !== checkoutIdentity) throw new WorkerRefusal("Worker-current launch has no verified checkout pin");
162
+ return { checkoutIdentity, repoRoot, gitDir, subdir, repoId, revision };
163
+ }
164
+
179
165
  export async function attestWorkerHost(paths: WorkerPaths, files: WorkerFiles, receipt: WorkerReceipt): Promise<WorkerIdentity> {
180
166
  if (!files.socket || !files.sessionId || !ownsCheckout(receipt)) throw new WorkerRefusal("No owned worker socket/journal/checkout");
167
+ const checkoutPin = workerCheckoutPin(receipt);
181
168
  const { connection, identity, state } = await HostConnection.open(paths.socketPath);
182
169
  try {
183
170
  if (!("workerAttempt" in state) || state.workerAttempt !== receipt.attempt ||
171
+ checkoutPin && (state.workerCheckoutProof?.checkoutIdentity !== checkoutPin.checkoutIdentity ||
172
+ state.workerCheckoutProof.revision !== checkoutPin.revision ||
173
+ !matchesWorkerCheckoutDirectory(join(checkoutPin.repoRoot, checkoutPin.subdir), checkoutPin)) ||
184
174
  typeof state.loadedSuperkitPath !== "string" || !state.loadedSuperkitPath.startsWith("/") || identity.pid === identity.ownerPid ||
185
175
  identity.sessionFile !== paths.sessionFile || identity.sessionId !== files.sessionId ||
186
176
  receipt.sessionId !== null && identity.sessionId !== receipt.sessionId || !sameFile(identity, files.socket) ||