omp-superagent 0.1.18 → 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 (63) hide show
  1. package/docs/OPERATIONS.en.md +127 -30
  2. package/docs/OPERATIONS.md +114 -27
  3. package/docs/design/execution.md +90 -23
  4. package/docs/design/messaging.md +34 -2
  5. package/docs/releases/0.1.19.md +10 -0
  6. package/gateway/bin/omp-gateway-darwin-arm64 +0 -0
  7. package/gateway/bin/omp-gateway-darwin-x64 +0 -0
  8. package/gateway/bin/omp-gateway-linux-arm64 +0 -0
  9. package/gateway/bin/omp-gateway-linux-x64 +0 -0
  10. package/host-owner/bin/omp-host-owner-darwin-arm64 +0 -0
  11. package/host-owner/bin/omp-host-owner-darwin-x64 +0 -0
  12. package/host-owner/bin/omp-host-owner-linux-arm64 +0 -0
  13. package/host-owner/bin/omp-host-owner-linux-x64 +0 -0
  14. package/package.json +1 -1
  15. package/skills/head/SKILL.md +4 -3
  16. package/skills/head/references/model-selection.md +8 -22
  17. package/skills/head/references/routing.md +19 -11
  18. package/skills/lane/SKILL.md +24 -76
  19. package/skills/lane/references/workflow.md +7 -94
  20. package/src/cli.ts +36 -16
  21. package/src/config/config.ts +6 -2
  22. package/src/contracts.ts +20 -4
  23. package/src/extension.ts +10 -5
  24. package/src/host-extension.ts +76 -8
  25. package/src/lane/lane-report.ts +1 -1
  26. package/src/lane/lane-rows.ts +2 -1
  27. package/src/lane-extension.ts +4 -21
  28. package/src/messaging/result-attachment.ts +77 -19
  29. package/src/messaging/written-directives.ts +56 -0
  30. package/src/omp/exit-record.ts +27 -0
  31. package/src/omp/host-protocol.ts +20 -0
  32. package/src/omp/host.ts +73 -20
  33. package/src/omp/installed-omp.ts +15 -12
  34. package/src/omp/managed-super.ts +135 -65
  35. package/src/routing/topic-request.ts +7 -4
  36. package/src/runtime/controller.ts +512 -165
  37. package/src/runtime/inbound-attachments.ts +70 -0
  38. package/src/runtime/local-host-fence.ts +85 -0
  39. package/src/runtime/model-journal.ts +14 -9
  40. package/src/runtime/native-frames.ts +5 -1
  41. package/src/runtime/result-attachments.ts +151 -24
  42. package/src/runtime/worker-result-download.ts +36 -0
  43. package/src/storage/store.ts +79 -26
  44. package/src/worker/worker-checkout.ts +89 -9
  45. package/src/worker/worker-destination.ts +8 -7
  46. package/src/worker/worker-doctor.ts +29 -9
  47. package/src/worker/worker-enrollment.ts +44 -12
  48. package/src/worker/worker-git-startup.ts +157 -0
  49. package/src/worker/worker-host.ts +16 -26
  50. package/src/worker/worker-ledger.ts +42 -18
  51. package/src/worker/worker-placement-intent.ts +13 -0
  52. package/src/worker/worker-placement.ts +204 -28
  53. package/src/worker/worker-profile.ts +18 -65
  54. package/src/worker/worker-project-startup.ts +106 -0
  55. package/src/worker/worker-registration.ts +85 -30
  56. package/src/worker/worker-repository.ts +55 -6
  57. package/src/worker/worker-request.ts +13 -6
  58. package/src/worker/worker-result-attachments.ts +185 -0
  59. package/src/worker/worker-result-wire.ts +12 -0
  60. package/src/worker/worker-service.ts +51 -23
  61. package/src/worker/worker-trust.ts +19 -4
  62. package/src/worker/worker-wire.ts +47 -14
  63. package/upstream/super.json +2 -3
@@ -26,22 +26,24 @@ import { isDeepStrictEqual } from "node:util";
26
26
  import {
27
27
  HEAD_MODEL_CONTROL, headRecoveryEffectsSettled, isRetiredScopeInput, laneFallbackKey, laneModelPickerRestoreKey, physicalRoute, physicalRouteKey, resolvePickerOption, routeKey, type Approval, type Inbound, type InputRecord, type Lane, type LaneModel, type ModelPreset, type LanePresetSnapshot,
28
28
  type ActiveInputState, type KickoffHold, type OutputRecord, type Route, type SettlementOutput, type StorePort, type WorkflowActivation,
29
- type HeadModelChange, type HeadRecoveryAttempt, type HeadRecoveryEffect, type LaneFallbackReceipt, type LaneRecoveryScope,
29
+ type HeadModelChange, type HeadRecoveryAttempt, type HeadRecoveryEffect, type LaneFallbackReceipt, type LaneRecoveryScope, type LocalHostIdentity,
30
30
  } from "../contracts.ts";
31
31
  import type { ApprovalResolution } from "../contracts";
32
32
  import { captureDecision, resolveDecision } from "../lane/decisions";
33
33
  import { isLaneModel, laneModelArgument, sameLaneModel } from "../lane/lane-models";
34
34
  import { laneData, readLaneRows, toLane, type LaneRow } from "../lane/lane-rows";
35
35
  import { compareMessageIds, slackOutputTimestamp, slackWorkspaceQuestionTimestamp } from "../routing/message-order";
36
+ import { hasWorkerCurrentHeader, readWorkerCurrentDirective } from "../messaging/written-directives";
36
37
  import { storedWorkflowName, workflowChoice } from "../lane/workflow";
37
38
  import { laneWaitKey, type LaneReport } from "../lane/lane-report";
38
39
  import { laneWatchReplySource } from "../lane/lane-watch";
39
40
  import { discordWorkThreadOwnerKey, recordedDiscordWorkThreadSource } from "../messaging/discord-work-thread";
40
- import { isResultAttachmentSnapshot } from "../messaging/result-attachment";
41
+ import { isOriginalAttachmentMessage, isResultAttachmentSnapshot } from "../messaging/result-attachment";
41
42
  import { existingWorkspace, matchingSlackHistoryChoice, slackWorkspaceAnswer, TOPIC_CHOICE_WAIT_MS, topicRequest } from "../routing/topic-request";
42
43
  import type { CronUpdate } from "../cron/cron-jobs";
43
44
  import { unattendedSource, hasIntakeReplyRoute, intakeThreadKey, intakeWorkId } from "../pr/pr-intake-work";
44
45
  import { isPrReviewLane, type ReviewRound } from "../pr/pr-intake-review";
46
+ import { matchesWorkerCurrentPlacement } from "../worker/worker-placement-intent";
45
47
  import { DeferredRoutingQueue, type DeferredChoiceRow } from "./deferred-routing";
46
48
 
47
49
  const ACTIVE_INPUTS = "state IN ('pending','submitted','uncertain')";
@@ -192,6 +194,7 @@ const inboundData = (input: Inbound): Inbound => ({
192
194
  ...(input.slackVerifiedRoutingBody === true ? { slackVerifiedRoutingBody: true } : {}),
193
195
  ...(input.telegramProtectedCommand === undefined ? {} : { telegramProtectedCommand: input.telegramProtectedCommand }),
194
196
  ...(input.telegramOriginalText === undefined ? {} : { telegramOriginalText: input.telegramOriginalText }),
197
+ ...(input.ownerWrittenPrefix === undefined ? {} : { ownerWrittenPrefix: input.ownerWrittenPrefix }),
195
198
  ...(input.interactionId === undefined ? {} : { interactionId: input.interactionId }),
196
199
  ...(input.invocationId === undefined ? {} : { invocationId: input.invocationId }),
197
200
  ...(input.pickerSelection === undefined ? {} : { pickerSelection: input.pickerSelection }),
@@ -204,7 +207,7 @@ function inboundIdentity(input: Inbound) {
204
207
  // Derived routing text and independently edited references do not change the
205
208
  // event identity. Keep the first snapshot, including on pre-upgrade replay.
206
209
  const { reply: _reply, unresolvedReply: _unresolvedReply, discordContext: _context, routingText: _routingText,
207
- slackVerifiedRoutingBody: _slackVerifiedRoutingBody, ...data } = inboundData(input);
210
+ slackVerifiedRoutingBody: _slackVerifiedRoutingBody, ownerWrittenPrefix: _ownerWrittenPrefix, ...data } = inboundData(input);
208
211
  return {
209
212
  ...data,
210
213
  // Slack supplies no command timestamp. A transport redelivery has a fresh
@@ -590,6 +593,45 @@ export class Store implements StorePort {
590
593
  return { source, route, outputSourceId };
591
594
  }
592
595
 
596
+ resultAttachmentDelivery(id: string): ReturnType<StorePort["topicDelivery"]> {
597
+ const topic = this.topicDelivery(id);
598
+ const input = this.input(id);
599
+ const lane = input?.target && input.target !== "main" ? this.lane(input.target) : null;
600
+ const linked = this.getMeta(`handoff-source:${id}`);
601
+ const source = topic?.source ?? (linked === null ? null : this.input(linked));
602
+ if (!input || !source) return null;
603
+ const current = hasWorkerCurrentHeader(source.text);
604
+ if (!lane?.remote) return current ? null : topic;
605
+ if (this.getMeta(`user-source:${source.id}`) !== "true" || !isOriginalAttachmentMessage(source)
606
+ || source.state === "cancelled" || source.state === "uncertain") return null;
607
+
608
+ const destination = topic?.route ?? lane.route;
609
+ const sourceKey = routeKey(source.route);
610
+ const sameRoute = sourceKey === routeKey(destination);
611
+ const opening = (current || !topic || !sameRoute) && this.confirmedOpening(source, input, lane);
612
+ if (current || !topic) {
613
+ const continuation = current && id === `handoff:${source.id}:${lane.id}` && linked === source.id
614
+ && sourceKey === routeKey(lane.route) && routeKey(input.route) === sourceKey;
615
+ if (source.target !== "main" || !opening && !continuation) return null;
616
+ if (current) {
617
+ const directive = readWorkerCurrentDirective(source);
618
+ if (!directive || !matchesWorkerCurrentPlacement(directive, lane.remote)) return null;
619
+ }
620
+ }
621
+
622
+ // Text can follow a selected or reconciled work topic. File consent extends
623
+ // only to the exact native child created and confirmed for this parent input.
624
+ if (!sameRoute && opening && source.route.threadId === null && source.route.topicId === undefined
625
+ && destination.threadId !== null && sourceKey === routeKey({ ...destination, threadId: null })) {
626
+ const created = this.getMeta(`handoff-route-result:${source.id}`);
627
+ if (created !== null && isDeepStrictEqual(JSON.parse(created), destination))
628
+ return { source, route: destination, outputSourceId: id };
629
+ }
630
+ // An explicit worker-current source is tied to its selected same-context
631
+ // opening or continuation. Ordinary files can return to their own topic.
632
+ return current && !sameRoute ? null : { source, route: source.route, outputSourceId: source.id };
633
+ }
634
+
593
635
  hasTopicAdmission(target: string, generation: number): boolean {
594
636
  const rows = this.db.query<InputRow, [string, number]>(
595
637
  "SELECT * FROM inputs WHERE target = ? AND generation = ? AND request_id IS NOT NULL",
@@ -964,22 +1006,26 @@ export class Store implements StorePort {
964
1006
  if (!origin || origin.target !== "main") return null;
965
1007
  const handoff = this.input(`handoff:${sourceId}:lane`);
966
1008
  if (!handoff && this.getMeta(`handoff-intent:${sourceId}`) === null) return null;
967
- if (this.getMeta(`user-source:${origin.id}`) !== "true" || !handoff
968
- || this.getMeta(`handoff-source:${handoff.id}`) !== origin.id) return "unverified";
1009
+ const lane = handoff?.target ? this.lane(handoff.target) : null;
1010
+ if (!lane || !handoff || this.getMeta(`user-source:${origin.id}`) !== "true" || !this.confirmedOpening(origin, handoff, lane)
1011
+ || (lane.route.topicId ? physicalRouteKey(origin.route) !== physicalRouteKey(lane.route)
1012
+ : physicalRouteKey({ ...origin.route, threadId: null }) !== physicalRouteKey({ ...lane.route, threadId: null }))) return "unverified";
1013
+ return lane;
1014
+ }
1015
+
1016
+ private confirmedOpening(origin: InputRecord, handoff: InputRecord, lane: Lane): boolean {
1017
+ if (handoff.id !== `handoff:${origin.id}:lane` || this.getMeta(`handoff-source:${handoff.id}`) !== origin.id
1018
+ || handoff.target !== lane.id || routeKey(handoff.route) !== routeKey(lane.route)) return false;
969
1019
  // lane_start registers its exact creation source here; lane_message only
970
1020
  // enqueues another input. The deterministic handoff ID alone is not proof.
971
1021
  const binding = this.db.query<{ lane_id: string }, [string]>(
972
1022
  "SELECT lane_id FROM lane_sources WHERE source_id = ?",
973
1023
  ).get(handoff.id);
974
- const lane = binding && this.lane(binding.lane_id);
975
- if (!lane || handoff.target !== lane.id || routeKey(handoff.route) !== routeKey(lane.route)
976
- || (lane.route.topicId ? physicalRouteKey(origin.route) !== physicalRouteKey(lane.route)
977
- : physicalRouteKey({ ...origin.route, threadId: null }) !== physicalRouteKey({ ...lane.route, threadId: null }))) return "unverified";
1024
+ if (binding?.lane_id !== lane.id) return false;
978
1025
  const kickoffId = `${origin.id}:kickoff`;
979
1026
  const kickoff = this.output(kickoffId);
980
- if (this.getMeta(`kickoff-output:${handoff.id}`) !== kickoffId || kickoff?.state !== "sent" || !kickoff.remoteId
981
- || kickoff.sourceId !== handoff.id || routeKey(kickoff.route) !== routeKey(lane.route)) return "unverified";
982
- return lane;
1027
+ return this.getMeta(`kickoff-output:${handoff.id}`) === kickoffId && kickoff?.state === "sent" && !!kickoff.remoteId
1028
+ && kickoff.sourceId === handoff.id && routeKey(kickoff.route) === routeKey(lane.route);
983
1029
  }
984
1030
 
985
1031
  *admittedMessageIds(route: Route): Iterable<string> {
@@ -1576,7 +1622,7 @@ export class Store implements StorePort {
1576
1622
  if (!isResultAttachmentSnapshot(attachment.payload))
1577
1623
  throw new Error(`A new result attachment requires a native snapshot receipt: ${output.id}`);
1578
1624
  const native = this.input(attachment.inputId);
1579
- const topic = native && this.topicDelivery(native.id);
1625
+ const topic = native && this.resultAttachmentDelivery(native.id);
1580
1626
  const runId = native && this.getMeta(`steering-owner:${native.id}`);
1581
1627
  const run = runId && this.input(runId);
1582
1628
  const ownership = run && this.getMeta(`${native?.target === "main" ? "head-native-owner" : "lane-observation-owner"}:${run.id}`);
@@ -1588,7 +1634,7 @@ export class Store implements StorePort {
1588
1634
  || owner.generation !== attachment.generation || owner.sessionId !== attachment.sessionId
1589
1635
  || owner.sessionFile !== attachment.sessionFile
1590
1636
  || (topic ? topic.source.id !== original.id || topic.outputSourceId !== output.sourceId || routeKey(topic.route) !== routeKey(output.route)
1591
- : native.target !== "main" || native.id !== original.id || native.id !== output.sourceId)) {
1637
+ : native.target !== "main" || native.id !== original.id || native.id !== output.sourceId || hasWorkerCurrentHeader(original.text))) {
1592
1638
  throw new Error(`Result attachment does not match its original native request: ${output.id}`);
1593
1639
  }
1594
1640
  }
@@ -1920,11 +1966,11 @@ export class Store implements StorePort {
1920
1966
  this.db.query("DELETE FROM metadata WHERE key = ?").run(key);
1921
1967
  }
1922
1968
 
1923
- createLane(lane: Lane & { model: LaneModel; modelReason: string }, sourceId: string): Lane {
1924
- if (!isLaneModel(lane.model) || typeof lane.modelReason !== "string" || !lane.modelReason.trim()
1969
+ createLane(lane: Lane & { model: LaneModel }, sourceId: string): Lane {
1970
+ if (!isLaneModel(lane.model)
1925
1971
  || (lane.modelPreset !== null && (typeof lane.modelPreset !== "string" || !lane.modelPreset.trim() || !lane.modelPresetSnapshot))
1926
1972
  || (lane.modelPreset === null && lane.modelPresetSnapshot !== null)) {
1927
- throw new Error("A new lane requires an exact model and a nonempty model reason");
1973
+ throw new Error("A new lane requires an exact model and a matching preset snapshot when using a preset");
1928
1974
  }
1929
1975
  return this.db.transaction(() => {
1930
1976
  const source = this.requireInput(sourceId);
@@ -1955,7 +2001,7 @@ export class Store implements StorePort {
1955
2001
  if (!existing) {
1956
2002
  this.db.query("INSERT INTO lanes(id, route_key, generation, data, remote) VALUES (?, ?, ?, ?, ?)")
1957
2003
  .run(lane.id, routeKey(lane.route), lane.generation, laneData({
1958
- ...lane, model: { provider: lane.model.provider, id: lane.model.id },
2004
+ ...lane, model: { provider: lane.model.provider, id: lane.model.id }, modelReason: lane.modelReason?.trim() || null,
1959
2005
  }), lane.remote ? JSON.stringify(lane.remote) : null);
1960
2006
  }
1961
2007
  this.db.query("INSERT INTO lane_sources(source_id, lane_id) VALUES (?, ?)").run(sourceId, selected.id);
@@ -1979,13 +2025,13 @@ export class Store implements StorePort {
1979
2025
  }
1980
2026
 
1981
2027
  updateLane(id: string, generation: number, patch: Partial<Pick<Lane,
1982
- "workState" | "runtimeState" | "sessionId" | "pid" | "lastActivityAt" | "result"
2028
+ "workState" | "runtimeState" | "sessionId" | "pid" | "lastActivityAt" | "result" | "localOwner"
1983
2029
  >>): boolean {
1984
2030
  return this.db.transaction(() => {
1985
2031
  const lane = this.lane(id);
1986
2032
  if (!lane || lane.generation !== generation) return false;
1987
2033
  // Explicitly copy the contract whitelist; runtime callers cannot change identity.
1988
- for (const key of ["workState", "runtimeState", "sessionId", "pid", "lastActivityAt", "result"] as const) {
2034
+ for (const key of ["workState", "runtimeState", "sessionId", "pid", "lastActivityAt", "result", "localOwner"] as const) {
1989
2035
  if (patch[key] !== undefined) Object.assign(lane, { [key]: patch[key] });
1990
2036
  }
1991
2037
  return this.db.query("UPDATE lanes SET data = ? WHERE id = ? AND generation = ?")
@@ -1993,13 +2039,18 @@ export class Store implements StorePort {
1993
2039
  }).immediate();
1994
2040
  }
1995
2041
 
1996
- retireLocalLaneHost(expected: Pick<Lane, "id" | "generation" | "pid" | "sessionId" | "socketPath">): boolean {
2042
+ retireLocalLaneHost(expected: Pick<Lane, "id" | "generation" | "pid" | "sessionId" | "socketPath" | "localOwner">, orphan?: LocalHostIdentity): boolean {
1997
2043
  return this.db.transaction(() => {
1998
2044
  const lane = this.lane(expected.id);
1999
2045
  if (!lane || lane.remote || expected.pid === null || lane.generation !== expected.generation
2000
- || lane.pid !== expected.pid || lane.sessionId !== expected.sessionId || lane.socketPath !== expected.socketPath) return false;
2046
+ || lane.pid !== expected.pid || lane.sessionId !== expected.sessionId || lane.socketPath !== expected.socketPath
2047
+ || lane.localOwner?.journalHeld || !isDeepStrictEqual(lane.localOwner, expected.localOwner)) return false;
2048
+ if (orphan) {
2049
+ if (orphan.pid !== lane.pid || orphan.sessionId !== lane.sessionId || orphan.sessionFile !== lane.sessionFile) return false;
2050
+ lane.localOwner = { ...orphan, journalHeld: true };
2051
+ } else delete lane.localOwner;
2001
2052
  lane.pid = null;
2002
- if (lane.runtimeState !== "unloaded") lane.runtimeState = "interrupted";
2053
+ if (orphan || lane.runtimeState !== "unloaded") lane.runtimeState = "interrupted";
2003
2054
  return this.db.query("UPDATE lanes SET data = ? WHERE id = ? AND generation = ?")
2004
2055
  .run(laneData(lane), lane.id, lane.generation).changes === 1;
2005
2056
  }).immediate();
@@ -2023,6 +2074,8 @@ export class Store implements StorePort {
2023
2074
  nextGeneration(id: string, pickerRestoreSourceId?: string): Lane {
2024
2075
  return this.db.transaction(() => {
2025
2076
  const lane = this.requireLane(id);
2077
+ if (lane.localOwner?.journalHeld) throw new Error("The original local Host journal is unverified; refusing relaunch");
2078
+ delete lane.localOwner;
2026
2079
  const restoreKey = pickerRestoreSourceId === undefined ? null : laneModelPickerRestoreKey(pickerRestoreSourceId);
2027
2080
  if (pickerRestoreSourceId !== undefined && restoreKey) {
2028
2081
  const source = this.input(pickerRestoreSourceId);
@@ -2077,11 +2130,11 @@ export class Store implements StorePort {
2077
2130
  }).immediate();
2078
2131
  }
2079
2132
 
2080
- changeLaneModel(id: string, generation: number, expected: LaneModel | null, model: LaneModel, reason: string,
2133
+ changeLaneModel(id: string, generation: number, expected: LaneModel | null, model: LaneModel, reason: Lane["modelReason"],
2081
2134
  preset: ModelPreset | null, snapshot: LanePresetSnapshot | null, metadata: Readonly<Record<string, string>> = {}, operatorSourceId?: string): boolean {
2082
- if (!isLaneModel(model) || typeof reason !== "string" || !reason.trim()
2135
+ if (!isLaneModel(model) || (reason !== null && (typeof reason !== "string" || !reason.trim()))
2083
2136
  || (preset !== null && (typeof preset !== "string" || !preset.trim() || !snapshot)) || (preset === null && snapshot !== null)) {
2084
- throw new Error("Explicit model changes require an exact model, nonempty reason, and valid native preset");
2137
+ throw new Error("Invalid lane model selection or preset snapshot");
2085
2138
  }
2086
2139
  return this.db.transaction(() => {
2087
2140
  const lane = this.lane(id);
@@ -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); }