omp-superagent 0.1.6 → 0.1.8

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 (90) hide show
  1. package/DESIGN.md +36 -20
  2. package/README.ko.md +140 -33
  3. package/README.md +165 -41
  4. package/THIRD_PARTY_NOTICES.md +9 -7
  5. package/config.example.json +3 -1
  6. package/docs/OPERATIONS.md +395 -157
  7. package/docs/design/execution.md +156 -22
  8. package/docs/design/messaging.md +258 -52
  9. package/docs/discord-voice.md +8 -4
  10. package/docs/releases/0.1.7.md +25 -0
  11. package/docs/releases/0.1.8.md +21 -0
  12. package/gateway/bin/omp-gateway-darwin-arm64 +0 -0
  13. package/gateway/bin/omp-gateway-darwin-x64 +0 -0
  14. package/gateway/bin/omp-gateway-linux-arm64 +0 -0
  15. package/gateway/bin/omp-gateway-linux-x64 +0 -0
  16. package/host-owner/bin/omp-host-owner-darwin-arm64 +0 -0
  17. package/host-owner/bin/omp-host-owner-darwin-x64 +0 -0
  18. package/host-owner/bin/omp-host-owner-linux-arm64 +0 -0
  19. package/host-owner/bin/omp-host-owner-linux-x64 +0 -0
  20. package/package.json +9 -9
  21. package/scripts/ci.ts +4 -4
  22. package/scripts/test-omp.sh +2 -1
  23. package/skills/head/SKILL.md +26 -5
  24. package/skills/head/references/routing.md +68 -33
  25. package/skills/head/references/supervision.md +20 -4
  26. package/skills/lane/references/workflow.md +16 -7
  27. package/src/board.ts +5 -3
  28. package/src/cli.ts +161 -19
  29. package/src/config.ts +21 -1
  30. package/src/contracts.ts +63 -8
  31. package/src/cron-jobs.ts +443 -19
  32. package/src/cron-pr-intake.ts +257 -0
  33. package/src/discord-markdown.ts +350 -123
  34. package/src/extension.ts +78 -13
  35. package/src/gateway-client.ts +8 -2
  36. package/src/head-quota.ts +80 -0
  37. package/src/head-recovery.ts +40 -1
  38. package/src/host-extension.ts +122 -4
  39. package/src/host-inventory-manifest.ts +2 -2
  40. package/src/host-protocol.ts +11 -0
  41. package/src/host-sdk-helper.ts +121 -12
  42. package/src/host.ts +175 -57
  43. package/src/installed-omp.ts +116 -4
  44. package/src/lane-rows.ts +44 -4
  45. package/src/lane-watch.ts +339 -0
  46. package/src/managed-memory-helper.ts +13 -10
  47. package/src/managed-memory.ts +62 -27
  48. package/src/managed-ulw-probe.ts +75 -20
  49. package/src/managed-ulw.ts +174 -21
  50. package/src/messenger-command-catalog.json +2 -2
  51. package/src/native-launch-profile.ts +4 -2
  52. package/src/native-presets.ts +32 -5
  53. package/src/native-sessions.ts +3 -1
  54. package/src/native-settings.ts +47 -9
  55. package/src/observation-request.ts +23 -0
  56. package/src/omp-usage.ts +254 -36
  57. package/src/pr-github-schema.ts +5 -1
  58. package/src/pr-github.ts +68 -19
  59. package/src/pr-intake-automation.ts +316 -0
  60. package/src/pr-intake-comment.ts +226 -0
  61. package/src/pr-intake-fix.ts +233 -0
  62. package/src/pr-intake-github.ts +480 -0
  63. package/src/pr-intake-material.ts +230 -0
  64. package/src/pr-intake-mode.ts +59 -0
  65. package/src/pr-intake-review.ts +397 -0
  66. package/src/pr-intake-tree.ts +69 -0
  67. package/src/pr-intake-work.ts +29 -0
  68. package/src/pr-watch.ts +91 -32
  69. package/src/runtime.ts +2702 -391
  70. package/src/setup-judge.ts +1 -1
  71. package/src/setup.ts +12 -16
  72. package/src/store.ts +429 -86
  73. package/src/topic-history.ts +243 -47
  74. package/src/worker-checkout.ts +106 -0
  75. package/src/worker-destination.ts +10 -0
  76. package/src/worker-doctor.ts +66 -0
  77. package/src/worker-enrollment.ts +165 -0
  78. package/src/worker-host.ts +180 -0
  79. package/src/worker-ledger.ts +188 -0
  80. package/src/worker-placement.ts +78 -0
  81. package/src/worker-profile.ts +274 -0
  82. package/src/worker-registration.ts +288 -0
  83. package/src/worker-repository.ts +233 -0
  84. package/src/worker-request.ts +74 -0
  85. package/src/worker-service.ts +230 -0
  86. package/src/worker-stdio.ts +61 -0
  87. package/src/worker-trust.ts +36 -0
  88. package/src/worker-wire.ts +204 -0
  89. package/src/workflow.ts +81 -32
  90. package/src/setup-memory.ts +0 -21
@@ -6,7 +6,7 @@ import { lstat, open, realpath } from "node:fs/promises";
6
6
  import { dirname, isAbsolute, join, normalize } from "node:path";
7
7
  import { resolveSessionLeafId, type SessionEntry } from "@oh-my-pi/pi-coding-agent/session/session-entries";
8
8
  import { parseSessionContent } from "@oh-my-pi/pi-coding-agent/session/session-loader";
9
- import type { Lane } from "./contracts";
9
+ import type { Inbound, Lane } from "./contracts";
10
10
  import { parseLaneReportResult } from "./lane-report";
11
11
 
12
12
  export interface TopicMatch {
@@ -38,13 +38,24 @@ const enResume = /\b(?:resume|pick (?:back )?up|go back to|return to|carry on wi
38
38
  const enLead = /(?:^|[.!?,]\s+)(?:(?:please|can you|could you|would you|let['’]s)\s+)*(?:resume|pick|go back to|return to|carry on with|continue)\b/iu;
39
39
  const koPast = /지난\s*(?:번|주|달)|저번(?:에|주|달)?|이전(?:에)?|예전(?:에)?|그때|아까|어제|(?:하|보|고치|잡|찾|다루|만들|살펴보|해보)던|(?:했|봤|다뤘|고쳤|만들었)던|하던\s*데서|보던\s*데서/gu;
40
40
  const koResume = /계속(?:해서|해\s*줘|해줘|해|하|봐\s*줘|봐줘|봐)?|이어서|이어\s*(?:서|가|해\s*줘|해줘|해|봐\s*줘|봐줘|봐)|재개(?:해\s*줘|해줘|해|하)?|마저/gu;
41
- const inlineQuotes = /"[^"\r\n]*"|“[^”\r\n]*”|‘[^’\r\n]*’|(?<![\p{L}\p{N}])'[^'\r\n]*'|`[^`\r\n]*`/gu;
41
+ const inlineQuotes = /"(?:\\[^\r\n]|[^"\\\r\n])*"|“[^”\r\n]*”|‘[^’\r\n]*’|(?<![\p{L}\p{N}])'(?:\\[^\r\n]|[^'\\\r\n]|'(?=[\p{L}\p{N}]))*'(?![\p{L}\p{N}])/gu;
42
+ const inlineCode = /(?<!`)(`+)(?!`)[^\r\n]*?(?<!`)\1(?!`)/gu;
42
43
  const ignored = new Set(`a about again also an and as at back be by can could current day did do for from had have how i in is it last left let me month my of off old on original or our please prior previous same so stuff task that the then there thing this time to topic up us was we were what when where which will with work worked working would you your look looking investigation investigate check track tracking handle tell thanks
43
44
  거 걸 것 그 그거 그거를 거기 거기서 거기부터 이거 저거 나 네 다시 다음 데 데서 도 좀 뒤 때 에서 요 여기 이 일 일단 작업 저 제 중 지금 처음 해 하던 해줘 해주세요 봐 봐줘 봐주세요 주세요 처리 처리해 처리해줘 처리해주세요 진행해 진행해줘 진행해주세요 확인해줘 확인해주세요 확인 진행 검토 조사 부탁 과제 관련 부터 까지 보던 봤던 들던 했던 계속 이어서 이어 재개 마저
44
- ulw ultrawork mass jevify orchestrate workflowz ultrathink`.split(/\s+/));
45
+ super ulw ultrawork mass jevify orchestrate workflowz ultrathink`.split(/\s+/));
45
46
  const categories = new Set(["bug", "test", "feature", "migration", "change", "inspection", "review", "analysis", "incident"]);
46
47
  const recallBoilerplate = new Set(`action agent app assistant authorized build call change code complete confirm context continue conversation current data default detail discuss docs evidence execute file follow help history implement information input journal label lane latest mean memory message model native need nickname note output owner past pending private proceed project prompt record recall recent remember repetition report repo repository request result resume route run search session source standard start status step summary superagent support update use user verify workspace
47
48
  결과 계속 기록 내용 대화 메시지 메모 모델 문서 변경 요약 확인 요청 자료 이전 정보 진행 설정 세션 사용자 작업 작업공간 저장소 참고 관련 기본 완료 반복 이어서 재개 워크스페이스`.split(/\s+/));
49
+ const routingBoilerplate = new Set(`action add apply attached build call change compare complete confirm current deploy diagnose discuss examine execute explain find first follow give help implement inspect introduce latest make migrate need new output quick read refactor remove repair replace report reproduce resolve restore review revise run search see set show solve something source specific start step take think troubleshoot try update use verify want write
50
+ 검사해줘 고쳐줘 넣어줘 돼 도와줘 봐줄래 수정 수정해줘 알려줘 적용 적용해줘 점검 점검해줘 해결 해결해줘 해줄래`.split(/\s+/));
51
+ const routingCommand = /^(?:![a-z][\w-]*(?:\s|$)|cwd\s*:|[$%❯]\s|(?:\.\.?)?\/\S|go\s+(?:build|run|test|vet)(?:\s|$)|(?:adb|bash|bunx?|cargo|cd|chmod|cp|curl|docker|git|kubectl|ls|node|npx?|npm|pnpm|pwd|python[23]?|rg|rm|sh|sudo|uvx?|yarn|zsh)(?:\s|$))/u;
52
+ const pastedCode = /^(?: {4}| {0,3}(?:\t|(?:const|let|var)\s+\S+\s*=|(?:import|export)\s+(?:\{|["'])|(?:async\s+)?function\s+\w+\s*\(|[\w$.]+\([^)]*\)\s*;?\s*$))/u;
53
+ const shellMultilineCommand = /^(?:cat|echo|env|printf|tee)(?:\s|$)/u;
54
+ const shellEscape = /(?<!\\)(?:\\\\)*\\[ \t]*$/u;
55
+ const shellHereDoc = /^<<(-?)[ \t]*(?:'([^'\r\n]+)'|"([^"\r\n]+)"|\\?([\w.-]+))(?=\s|[;&|<>]|$)/u;
56
+ const shellPrompt = /^[ \t]*[$%❯][ \t]+/u;
57
+ const shellSecondaryPrompt = /^ {0,3}>[ \t]/u;
58
+ const routingHeader = /^\s*\/(?:new|head)(?:[ \t]+|$)/u;
48
59
  const aliases = new Map([
49
60
  ["로그인", "login"], ["signin", "login"], ["로그아웃", "logout"], ["인증", "authentication"], ["auth", "authentication"],
50
61
  ["버그", "bug"], ["문제", "bug"], ["오류", "bug"], ["에러", "bug"], ["issue", "bug"],
@@ -54,18 +65,110 @@ const aliases = new Map([
54
65
  ["리다이렉트", "redirect"], ["리디렉션", "redirect"], ["리다이렉션", "redirect"], ["redirection", "redirect"],
55
66
  ]);
56
67
 
57
- /** Exclude pasted blocks and quote lines, not inline names of the task. */
58
- function directText(text: string): string {
68
+ type ShellQuote = "" | "'" | '"' | "`";
69
+ type HereDoc = { readonly delimiter: string; readonly stripTabs: boolean };
70
+ type ShellLine = { readonly quote: ShellQuote; readonly continued: boolean; readonly documents: readonly HereDoc[] };
71
+
72
+ // Scan only lines already identified as shell. An open string, pipe or heredoc
73
+ // can carry with it arbitrary unindented payload lines that look like requests.
74
+ function shellLine(line: string, opener: ShellQuote): ShellLine {
75
+ const text = line.trimEnd();
76
+ const documents: HereDoc[] = [];
77
+ let quote = opener;
78
+ let escape = false;
79
+ let operator = "";
80
+ for (let i = 0; i < text.length; i++) {
81
+ const ch = text.charAt(i);
82
+ if (escape) { escape = false; continue; }
83
+ if (ch === "\\" && quote !== "'") { operator = ""; escape = true; continue; }
84
+ if (quote) { if (ch === quote) quote = ""; continue; }
85
+ if (ch === "#" && (i === 0 || /[ \t]/u.test(text.charAt(i - 1)))) break;
86
+ if (ch === "'" || ch === '"' || ch === "`") { operator = ""; quote = ch; continue; }
87
+ if (ch === "<" && text.charAt(i - 1) !== "<" && text.charAt(i + 1) === "<") {
88
+ const match = shellHereDoc.exec(text.slice(i));
89
+ const delimiter = match?.[2] ?? match?.[3] ?? match?.[4];
90
+ if (match && delimiter) {
91
+ documents.push({ delimiter, stripTabs: match[1] === "-" });
92
+ i += match[0].length - 1;
93
+ }
94
+ }
95
+ if (ch === "|" || ch === "&") operator += ch;
96
+ else if (ch !== " " && ch !== "\t") operator = "";
97
+ }
98
+ return { quote, continued: !!quote || escape || ["|", "|&", "||", "&&"].includes(operator), documents };
99
+ }
100
+
101
+ function filterOwnerProse(text: string, syntax: string, preserveHeader: boolean): string {
102
+ const projected = text.split(/\r\n?|\n/u);
103
+ const source = text === syntax ? projected : syntax.split(/\r\n?|\n/u);
104
+ if (projected.length !== source.length) return "";
105
+ const lines: string[] = [];
106
+ const documents: HereDoc[] = [];
59
107
  let fence = "";
60
- return text.split(/\r?\n/).filter(line => {
108
+ let quote: ShellQuote = "";
109
+ let shellContinued = false;
110
+ let interactiveShell = false;
111
+ for (const [index, line] of source.entries()) {
112
+ const document = documents[0];
113
+ if (document && !shellContinued) {
114
+ const value = interactiveShell ? line.replace(shellSecondaryPrompt, "") : line;
115
+ if ((document.stripTabs ? value.replace(/^\t+/u, "") : value) === document.delimiter) documents.shift();
116
+ continue;
117
+ }
61
118
  const marker = /^ {0,3}(`{3,}|~{3,})(.*)$/.exec(line);
62
119
  if (fence) {
63
120
  if (marker && marker[1].startsWith(fence) && !marker[2].trim()) fence = "";
64
- return false;
121
+ continue;
122
+ }
123
+ if (marker && !shellContinued) { fence = marker[1]; continue; }
124
+ if (/^ {0,3}>>>(?:\s|$)/u.test(line)) break;
125
+ const visible = projected[index] ?? "";
126
+ // Preserve the placement grammar for the controller, but still scan for
127
+ // shell pasted after an intact /new or /head prefix on this line.
128
+ const header = preserveHeader && !shellContinued ? routingHeader.exec(visible)?.[0] : undefined;
129
+ if (preserveHeader && !shellContinued && /^\s*cwd:/u.test(visible)) {
130
+ lines.push(visible);
131
+ continue;
132
+ }
133
+ const body = header === undefined ? line : line.replace(routingHeader, "");
134
+ const stripped = body.replace(inlineCode, " ").replace(inlineQuotes, " ");
135
+ if (!shellContinued && /^ {0,3}>/u.test(line)) continue;
136
+ const start = stripped.trimStart().normalize("NFKC");
137
+ const command = routingCommand.test(start);
138
+ const escaped = shellEscape.test(stripped);
139
+ if (shellContinued || command || escaped || shellMultilineCommand.test(start)) {
140
+ // An interactive paste can contain PS2 prompts before continuation lines.
141
+ if (!shellContinued) interactiveShell = shellPrompt.test(body);
142
+ const shell = shellLine(interactiveShell ? body.replace(shellContinued ? shellSecondaryPrompt : shellPrompt, "") : body, quote);
143
+ if (shellContinued || command || escaped || shell.continued || shell.documents.length) {
144
+ ({ quote, continued: shellContinued } = shell);
145
+ documents.push(...shell.documents);
146
+ if (header !== undefined) lines.push(header.trimEnd());
147
+ continue;
148
+ }
149
+ }
150
+ if (!pastedCode.test(body)) {
151
+ lines.push(header !== undefined ? visible : text === syntax ? stripped : visible.replace(inlineCode, " ").replace(inlineQuotes, " "));
65
152
  }
66
- if (marker) { fence = marker[1]; return false; }
67
- return !/^ {0,3}>/.test(line);
68
- }).join("\n");
153
+ }
154
+ return lines.join("\n").trim();
155
+ }
156
+
157
+ /** Recover only owner prose, never quoted text, pasted code or shell input. */
158
+ export function ownerRoutingProse(text: string): string {
159
+ return filterOwnerProse(text, text, false);
160
+ }
161
+
162
+ /**
163
+ * Preserve transport entity exclusions while recognizing a shell continuation
164
+ * whose opener itself was hidden. Raw bytes may discard lines, never add text.
165
+ */
166
+ export function transportRoutingProse(input: Inbound): string {
167
+ if (input.route.platform !== "telegram") return input.text;
168
+ const filtered = input.routingText;
169
+ if (filtered === undefined) return ""; // Pre-upgrade Telegram formatting is not recoverable.
170
+ if (!filtered || filtered === input.text) return filtered;
171
+ return filterOwnerProse(filtered, input.text, true);
69
172
  }
70
173
 
71
174
  function wordTokens(text: string): readonly string[] {
@@ -102,13 +205,12 @@ function* excerptWindows(text: string): Iterable<string> {
102
205
  }
103
206
 
104
207
  function visibleLine(text: string, limit: number): string {
105
- return directText(text.slice(0, limit)).replace(/[\s\p{Cc}\p{Cf}]+/gu, " ").trim();
208
+ return ownerRoutingProse(text).slice(0, limit).replace(/[\s\p{Cc}\p{Cf}]+/gu, " ").trim();
106
209
  }
107
210
 
108
211
  function request(text: string) {
109
- if (text.length > MAX_QUERY) return null;
110
- const clean = directText(text).normalize("NFKC").trim();
111
- const intent = clean.replace(inlineQuotes, '""');
212
+ if (text.length > MAX_QUERY || text.trimStart().startsWith("/")) return null;
213
+ const intent = ownerRoutingProse(text).normalize("NFKC").trim();
112
214
  if (!intent || intent.startsWith("/") || /\b(?:do not|don['’]t|never|not)\s+(?:resume|continue|go back|pick up)\b|(?:계속하|재개하|이어서 하)지\s*마|(?:말고|대신)\s*(?:새|다른)/iu.test(intent)) return null;
113
215
  const en = intent.match(enResume) ?? [];
114
216
  const historical = [...timePhrases, enPast, koPast].some(pattern => intent.match(pattern));
@@ -116,7 +218,7 @@ function request(text: string) {
116
218
  || /^(?:(?:please|can you|could you|would you)\s+)*continue\s+(?:work(?:ing)? on|the|our|that)\b/i.test(intent);
117
219
  if (!(en.length && enLead.test(intent) && (qualifiedEnglish || historical)
118
220
  || intent.match(koResume) && (historical || /이어서|이어\s*(?:가|해|봐)|재개|마저/u.test(intent)))) return null;
119
- const subject = clean.split(/(?:\b(?:and (?:then|also|add|check|fix|verify|run)|then)\b|[.!?]\s+|\n{2,})/iu, 1)[0];
221
+ const subject = intent.split(/(?:\b(?:and (?:then|also|add|check|fix|verify|run)|then)\b|[.!?]\s+|\n{2,})/iu, 1)[0];
120
222
  const terms = words([...timePhrases, enPast, enResume, koPast, koResume]
121
223
  .reduce((value, pattern) => value.replace(pattern, " "), subject));
122
224
  return terms.size <= 16 && [...terms].some(word => !categories.has(word)) ? { terms, intent, subject: subject.trim() } : null;
@@ -131,6 +233,25 @@ export function pastTopicQuery(text: string): string | null {
131
233
  return request(text)?.subject ?? null;
132
234
  }
133
235
 
236
+ function routingRequest(text: string) {
237
+ if (text.length > MAX_QUERY) return null;
238
+ const subject = ownerRoutingProse(text).replace(/[\s\p{Cc}\p{Cf}]+/gu, " ").trim();
239
+ // Past-topic aliases treat "fix" as a bug descriptor. In ordinary text an
240
+ // action alone should not make one otherwise ambiguous term a direct match.
241
+ const terms = new Set(wordTokens(subject.replace(/\b(?:fix(?:es|ed|ing)?|debug(?:s|ged|ging)?)\b/giu, " "))
242
+ .filter(word => !routingBoilerplate.has(word)));
243
+ return terms.size >= 2 && terms.size <= 16 && [...terms].some(concreteTerm) ? { subject, terms } : null;
244
+ }
245
+
246
+ export function routingSubject(text: string): string | null {
247
+ return routingRequest(text)?.subject ?? null;
248
+ }
249
+
250
+ /** An exact, same-conversation owner source need not pass a search relevance threshold. */
251
+ export function routingExcerpt(text: string): string {
252
+ return ownerRoutingProse(text).slice(0, EXCERPT);
253
+ }
254
+
134
255
  type RecallItem = { readonly content: string; readonly id?: string; readonly source?: string };
135
256
 
136
257
  function concreteTerm(word: string): boolean {
@@ -159,7 +280,7 @@ function recallAnchors(terms: ReadonlySet<string>, items: readonly RecallItem[])
159
280
  // Otherwise native semantic search can suggest a turn only with much stronger
160
281
  // corroboration: a substantial ordered phrase independently present in its journal.
161
282
  for (const { content } of items) {
162
- for (const paragraph of directText(content).split(/\n\s*\n/)) {
283
+ for (const paragraph of ownerRoutingProse(content).split(/\n\s*\n/)) {
163
284
  for (const phrase of concretePhrases(paragraph, SEMANTIC_ANCHOR)) anchors.add(phrase.join(" "));
164
285
  for (const excerpt of excerptWindows(paragraph)) {
165
286
  const seen = words(excerpt);
@@ -178,7 +299,7 @@ function recalledExcerpt(task: string, anchors: ReadonlySet<string>): string {
178
299
  // Check the phrase in the original owner lines as well as in the rendered
179
300
  // excerpt, where line breaks are collapsed.
180
301
  const grounded = new Set<string>();
181
- for (const phrase of concretePhrases(task.replace(inlineQuotes, "\n"), RECALL_ANCHORS)) {
302
+ for (const phrase of concretePhrases(ownerRoutingProse(task), RECALL_ANCHORS)) {
182
303
  const key = phrase.join(" ");
183
304
  if (anchors.has(key)) grounded.add(key);
184
305
  }
@@ -225,26 +346,44 @@ function promptText(content: unknown): string {
225
346
  return text;
226
347
  }
227
348
 
349
+ export const joinedTopicProvenance = "Input provenance: bound owner topic reply.";
350
+
228
351
  /** OMP journals the RPC completion ID; the fenced request identifies its input. */
229
- function requestDigest(raw: string, lane: Lane): string | undefined {
230
- const headers = [...raw.matchAll(/^(`{3,})superagent-runtime-context\nRequest ID: ([^\r\n]{1,512})\n/gm)]
231
- .sort((a, b) => b[1].length - a[1].length);
352
+ function journalRequest(raw: string, lane: Lane) {
353
+ const headers = [...raw.matchAll(/^(`{3,})superagent-runtime-context\nRequest ID: ([^\r\n]{1,512})\n/gm)];
354
+ if (!headers.length) return;
355
+ // Ordinary prompts start with the controller header. Pasted task text after
356
+ // its closing fence cannot replace it or make it ambiguous.
357
+ const leading = headers[0]?.index === 0;
358
+ if (!leading) headers.sort((a, b) => b[1].length - a[1].length);
232
359
  const header = headers[0];
233
- if (!header || headers[1]?.[1].length === header[1].length) return;
234
- const scope = raw.slice(header.index + header[0].length, header.index + header[0].length + 4096).split("\n", 12);
235
- if (scope.includes(`Independent lane ${lane.id}; cwd: ${lane.cwd}`)) {
236
- // Same request identity used by runtime's prompt submission, excluding generation.
237
- return createHash("sha256").update(header[2]).digest("hex").slice(0, 24);
238
- }
360
+ if (!header || !leading && headers[1]?.[1].length === header[1].length) return false;
361
+ const body = raw.slice(header.index + header[0].length);
362
+ const closing = `\n${header[1]}`;
363
+ const closeBeforeText = body.indexOf(`${closing}\n`);
364
+ const end = closeBeforeText >= 0 ? closeBeforeText : body.endsWith(closing) ? body.length - closing.length : -1;
365
+ if (end < 0) return false;
366
+ const scope = body.slice(0, Math.min(end, 4096)).split("\n", 12);
367
+ const laneIndex = scope.indexOf(`Independent lane ${lane.id}; cwd: ${lane.cwd}`);
368
+ if (laneIndex < 0) return false;
369
+ // Same request identity used by runtime's prompt submission, excluding generation.
370
+ const inputId = header[2];
371
+ const delivery = scope[laneIndex + 1];
372
+ const manager = delivery === "Delivery mode: manager handoff.";
373
+ const topicReply = delivery === "Delivery mode: topic reply.";
374
+ if (!manager && !topicReply) return false;
375
+ const fencedManager = manager && leading && closeBeforeText < 0 && !body.slice(0, end).includes(header[1]);
376
+ const joinedTopic = manager && scope[laneIndex + 2] === joinedTopicProvenance && scope[laneIndex + 3]?.startsWith("Brief: ");
377
+ return { inputId, digest: createHash("sha256").update(inputId).digest("hex").slice(0, 24), manager, fencedManager, topicReply, joinedTopic };
239
378
  }
240
379
 
241
- function completedRequest(data: unknown, lane: Lane, digest: string): boolean {
242
- if (!record(data) || data.sessionId !== lane.sessionId || data.sessionFile !== lane.sessionFile || !record(data.frame)) return false;
380
+ function journalReceipt(data: unknown, lane: Lane) {
381
+ if (!record(data) || data.sessionId !== lane.sessionId || data.sessionFile !== lane.sessionFile || !record(data.frame)) return;
243
382
  const { id, type, status, agentInvoked } = data.frame;
244
- if (typeof id !== "string" || !id.startsWith(`sg-${digest}-`)) return false;
245
- const generation = id.slice(digest.length + 4);
246
- return /^[1-9]\d{0,9}$/.test(generation) && Number(generation) <= lane.generation
247
- && type === "prompt_result" && status === "completed" && agentInvoked === true;
383
+ if (typeof id !== "string" || type !== "prompt_result") return;
384
+ const match = /^sg-([a-f0-9]{24})-([1-9]\d{0,9})$/.exec(id);
385
+ if (!match || Number(match[2]) > lane.generation) return;
386
+ return { id, digest: match[1], completed: status === "completed" && agentInvoked === true };
248
387
  }
249
388
 
250
389
  function activeBranch(entries: readonly SessionEntry[]): readonly SessionEntry[] {
@@ -265,7 +404,7 @@ function activeBranch(entries: readonly SessionEntry[]): readonly SessionEntry[]
265
404
 
266
405
  /** Reuse OMP's title-slot aware parser and leaf replay without opening an OMP session. */
267
406
  async function readJournal(lane: Lane, budget: { remaining: number }): Promise<readonly SessionEntry[] | null> {
268
- if (!lane.sessionId || !/^[\w-]+$/.test(lane.id) || lane.id === "main" || !isAbsolute(lane.cwd) || normalize(lane.cwd) !== lane.cwd) return [];
407
+ if (lane.remote || !lane.sessionId || !/^[\w-]+$/.test(lane.id) || lane.id === "main" || !isAbsolute(lane.cwd) || normalize(lane.cwd) !== lane.cwd) return [];
269
408
  const root = dirname(dirname(lane.socketPath));
270
409
  const parts = ["sessions", lane.id, "session.jsonl"] as const;
271
410
  if (!isAbsolute(root) || lane.socketPath !== join(root, "run", `${lane.id}.sock`) || lane.sessionFile !== join(root, ...parts)) return [];
@@ -318,6 +457,7 @@ type MatchedTurn = {
318
457
  readonly excerpts: readonly [string, ...string[]];
319
458
  readonly direct: boolean;
320
459
  readonly digest: string | undefined;
460
+ readonly ownerRequestId: string | undefined;
321
461
  proposed?: Checkpoint;
322
462
  checkpoint?: Checkpoint;
323
463
  summaryInWindow?: boolean;
@@ -332,6 +472,9 @@ type TopicQuery = {
332
472
 
333
473
  type TopicSelection = { readonly anchors: ReadonlySet<string> } | { readonly entryId: string };
334
474
  type JournalQuery = TopicQuery & { readonly selection: TopicSelection };
475
+ /** Resolve durable owner prose only after verifying its route and the exact completion. */
476
+ type OwnerOpening = (lane: Lane, inputId: string, mode: "manager" | "topic" | "joined-topic",
477
+ hasCompletion: (requestId: string) => boolean) => Promise<{ readonly text: string; readonly requestId: string } | null>;
335
478
 
336
479
  function topicQuery(text: string, receivedAt: number): TopicQuery | null {
337
480
  const query = request(text);
@@ -339,37 +482,77 @@ function topicQuery(text: string, receivedAt: number): TopicQuery | null {
339
482
  return query && window ? { terms: query.terms, window, receivedAt } : null;
340
483
  }
341
484
 
342
- function matchJournal(entries: readonly SessionEntry[], lane: Lane, query: JournalQuery): readonly MatchedTurn[] {
485
+ async function matchJournal(entries: readonly SessionEntry[], lane: Lane, query: JournalQuery,
486
+ ownerOpening?: OwnerOpening): Promise<readonly MatchedTurn[]> {
343
487
  const matches: MatchedTurn[] = [];
344
488
  const within = (at: number | undefined) => at !== undefined && at >= query.window[0] && at < query.window[1];
489
+ const entryTime = (entry: SessionEntry) => typeof entry.timestamp === "string" && entry.timestamp.length <= 40
490
+ ? Date.parse(entry.timestamp) : NaN;
491
+ const eligible = (at: number) => Number.isFinite(at) && at >= 0 && at <= query.receivedAt;
492
+ // A steered input can be written before the original completion. Index the
493
+ // active branch by exact RPC ID instead of letting another turn or receipt
494
+ // consume the opener's proof. Reports have no such ID; keep their narrower scope.
495
+ const receipts = new Map<string, { readonly index: number; readonly completed: boolean }>();
496
+ if (ownerOpening) {
497
+ for (const [index, entry] of entries.entries()) {
498
+ if (entry.type !== "custom" || entry.customType !== "rpc_prompt_result" || !eligible(entryTime(entry))) continue;
499
+ const receipt = journalReceipt(entry.data, lane);
500
+ if (receipt && !receipts.has(receipt.id)) receipts.set(receipt.id, { index, completed: receipt.completed });
501
+ }
502
+ }
345
503
  const { selection } = query;
346
504
  let current: MatchedTurn | undefined;
347
- for (const entry of entries) {
348
- const at = typeof entry.timestamp === "string" && entry.timestamp.length <= 40 ? Date.parse(entry.timestamp) : NaN;
505
+ for (const [index, entry] of entries.entries()) {
506
+ const at = entryTime(entry);
349
507
  const user = entry.type === "message" && record(entry.message) && entry.message.role === "user" ? entry.message : null;
350
508
  // Any later native user turn ends the previous request's checkpoint scope,
351
509
  // even when its content or date is not usable as evidence.
352
510
  if (user) current = undefined;
353
- if (!Number.isFinite(at) || at < 0 || at > query.receivedAt) continue;
511
+ if (!eligible(at)) continue;
354
512
  if (user) {
355
513
  if ("entryId" in selection && entry.id !== selection.entryId) continue;
356
514
  if (user.synthetic === true || user.parentIrc || user.attribution === "agent") continue;
357
515
  const raw = promptText(user.content);
358
- const task = directText(raw).trim().slice(0, MAX_FIELD);
516
+ const request = journalRequest(raw, lane);
517
+ if (request === false) continue;
518
+ // A manager fence can contain generated instructions and quotes. Use
519
+ // only the independent original source, never the fenced task bytes.
520
+ // Telegram's formatting entities are not recoverable from native text.
521
+ // Workflow envelopes may put raw instructions before or after the fence;
522
+ // recognizing manager delivery must not depend on the entire turn being fenced.
523
+ if (request?.manager && !request.fencedManager && !request.joinedTopic) continue;
524
+ const mode = request?.joinedTopic ? "joined-topic" : request?.manager ? "manager" : lane.route.platform === "telegram" ? "topic" : null;
525
+ let ownerText: string;
526
+ let ownerRequestId: string | undefined;
527
+ if (mode !== null) {
528
+ if (!ownerOpening || !request || mode === "topic" && !request.topicReply) continue;
529
+ const hasCompletion = (id: string) => {
530
+ const receipt = receipts.get(id);
531
+ return id.startsWith(`sg-${request.digest}-`) && receipt?.completed === true && receipt.index > index;
532
+ };
533
+ const opening = await ownerOpening(lane, request.inputId, mode, hasCompletion);
534
+ if (opening === null || !hasCompletion(opening.requestId)) continue;
535
+ ownerRequestId = opening.requestId;
536
+ ownerText = opening.text;
537
+ } else {
538
+ ownerText = raw;
539
+ }
540
+ const task = ownerRoutingProse(ownerText).slice(0, MAX_FIELD);
359
541
  if (refersToPastTopic(task.slice(0, MAX_QUERY))) continue; // Prior continuation echoes are not independent task evidence.
360
542
  const direct = matchingExcerpt(task, query.terms);
361
543
  const [excerpt, ...alternates] = direct ? [direct] : "entryId" in selection ? [...excerptWindows(task)]
362
544
  : [recalledExcerpt(task, selection.anchors)];
363
545
  if (excerpt) {
364
- current = { id: entry.id, at, excerpts: [excerpt, ...alternates], direct: !!direct, digest: requestDigest(raw, lane) };
546
+ current = { id: entry.id, at, excerpts: [excerpt, ...alternates], direct: !!direct, digest: request?.digest, ownerRequestId };
365
547
  matches.push(current);
366
548
  }
367
549
  } else if (current && entry.type === "custom") {
368
550
  if (entry.customType === "rpc_prompt_result" && !current.receiptSeen) {
369
551
  current.receiptSeen = true;
370
- if (current.digest && current.proposed && completedRequest(entry.data, lane, current.digest)) {
371
- current.checkpoint = current.proposed;
372
- }
552
+ const receipt = journalReceipt(entry.data, lane);
553
+ if (receipt?.completed && receipt.digest === current.digest
554
+ && (current.ownerRequestId === undefined || receipt.id === current.ownerRequestId)
555
+ && current.proposed) current.checkpoint = current.proposed;
373
556
  } else if (entry.customType === "superagent-lane-report" && current.digest && !current.receiptSeen) {
374
557
  const event = parseLaneReportResult({ details: entry.data });
375
558
  if (event?.sessionId === lane.sessionId && event.report.status !== "waiting") {
@@ -396,8 +579,21 @@ function topicMatch(lane: Lane, turn: MatchedTurn, excerpt: string): TopicMatch
396
579
 
397
580
  /** Search only caller-scoped managed lanes. Journal evidence is data, never instructions. */
398
581
  export async function findPastTopic(text: string, lanes: readonly Lane[], receivedAt: number,
399
- recallItems: readonly RecallItem[] = []): Promise<readonly TopicMatch[]> {
400
- const query = topicQuery(text, receivedAt);
582
+ recallItems: readonly RecallItem[] = [], ownerOpening?: OwnerOpening): Promise<readonly TopicMatch[]> {
583
+ return findTopics(topicQuery(text, receivedAt), lanes, recallItems, ownerOpening);
584
+ }
585
+
586
+ /** Advisory candidates for an ordinary request; never choose a destination here. */
587
+ export async function findRoutingTopics(text: string, lanes: readonly Lane[], receivedAt: number,
588
+ recallItems: readonly RecallItem[] = [], ownerOpening?: OwnerOpening): Promise<readonly TopicMatch[]> {
589
+ const request = routingRequest(text);
590
+ const window = dateWindow("", receivedAt);
591
+ if (!request || !window) return [];
592
+ return findTopics({ terms: request.terms, window, receivedAt }, lanes, recallItems, ownerOpening);
593
+ }
594
+
595
+ async function findTopics(query: TopicQuery | null, lanes: readonly Lane[], recallItems: readonly RecallItem[],
596
+ ownerOpening?: OwnerOpening): Promise<readonly TopicMatch[]> {
401
597
  // Do not claim uniqueness from an incomplete set of hints.
402
598
  if (!query || recallItems.length > MAX_RECALL_ITEMS || recallItems.some(item => item.content.length > MAX_FIELD)) return [];
403
599
  const selection = { anchors: recallAnchors(query.terms, recallItems) };
@@ -406,7 +602,7 @@ export async function findPastTopic(text: string, lanes: readonly Lane[], receiv
406
602
  for (const lane of lanes) {
407
603
  const entries = await readJournal(lane, budget);
408
604
  if (entries === null) return []; // Incomplete search cannot establish uniqueness.
409
- for (const turn of matchJournal(entries, lane, { ...query, selection })) {
605
+ for (const turn of await matchJournal(entries, lane, { ...query, selection }, ownerOpening)) {
410
606
  matches.set(JSON.stringify([lane.id, lane.sessionId, turn.id]), topicMatch(lane, turn, turn.excerpts[0]));
411
607
  }
412
608
  }
@@ -415,12 +611,12 @@ export async function findPastTopic(text: string, lanes: readonly Lane[], receiv
415
611
 
416
612
  /** Revalidate an admitted evidence pin against its exact active journal entry, without recall. */
417
613
  export async function readPastTopic(text: string, lane: Lane, receivedAt: number, entryId: string,
418
- evidenceHash: string): Promise<TopicMatch | null> {
614
+ evidenceHash: string, ownerOpening?: OwnerOpening): Promise<TopicMatch | null> {
419
615
  const query = topicQuery(text, receivedAt);
420
616
  if (!query || !nativeId.test(entryId) || !/^[a-f0-9]{64}$/.test(evidenceHash)) return null;
421
617
  const entries = await readJournal(lane, { remaining: MAX_SEARCH });
422
618
  if (entries === null) return null;
423
- for (const turn of matchJournal(entries, lane, { ...query, selection: { entryId } })) {
619
+ for (const turn of await matchJournal(entries, lane, { ...query, selection: { entryId } }, ownerOpening)) {
424
620
  for (const excerpt of turn.excerpts) {
425
621
  const match = topicMatch(lane, turn, excerpt);
426
622
  if (createHash("sha256").update(match.evidence).digest("hex") === evidenceHash) return match;
@@ -0,0 +1,106 @@
1
+ import { closeSync, constants, fstatSync, fsyncSync, linkSync, lstatSync, mkdirSync, openSync, readFileSync, realpathSync, unlinkSync, writeFileSync } from "node:fs";
2
+ import { isAbsolute, join, relative, sep } from "node:path";
3
+ import { gitWorkerRepository, workerRepositoryHead, workerRepositoryIdentity } from "./worker-repository";
4
+ import { WorkerRefusal } from "./worker-request";
5
+ import type { WorkerLaneRef, WorkerPolicy, WorkerRepo } from "./worker-wire";
6
+
7
+ export function privateWorkerDirectory(directory: string, create = false): boolean {
8
+ if (create) mkdirSync(directory, { mode: 0o700, recursive: true });
9
+ const info = lstatSync(directory, { throwIfNoEntry: false });
10
+ if (!info) return false;
11
+ if (!info.isDirectory() || info.uid !== process.getuid?.() || (info.mode & 0o777) !== 0o700
12
+ || realpathSync(directory) !== directory) throw new WorkerRefusal("Worker storage must be canonical and private (0700)");
13
+ return true;
14
+ }
15
+
16
+ function within(root: string, candidate: string): boolean {
17
+ const suffix = relative(root, candidate);
18
+ return !isAbsolute(suffix) && suffix !== ".." && !suffix.startsWith(`..${sep}`);
19
+ }
20
+
21
+ export async function enrolledRepo(policy: WorkerPolicy, repo: WorkerRepo): Promise<string> {
22
+ const root = lstatSync(repo.cwd, { throwIfNoEntry: false });
23
+ const uid = process.getuid?.();
24
+ if (!root?.isDirectory() || root.uid !== uid || (root.mode & 0o022) !== 0 || realpathSync(repo.cwd) !== repo.cwd
25
+ || within(policy.stateDir, repo.cwd) || within(repo.cwd, policy.stateDir))
26
+ throw new WorkerRefusal("Enrolled repository must be a canonical checkout separate from worker storage");
27
+ const [top, id, gitDir] = await Promise.all([
28
+ gitWorkerRepository(repo.cwd, ["rev-parse", "--show-toplevel"]),
29
+ workerRepositoryIdentity(repo.cwd),
30
+ gitWorkerRepository(repo.cwd, ["rev-parse", "--absolute-git-dir"]),
31
+ ]);
32
+ const gitPath = gitDir?.replace(/\n$/, "");
33
+ const stat = gitPath && lstatSync(gitPath, { throwIfNoEntry: false });
34
+ if (top !== `${repo.cwd}\n` || id !== repo.id || !gitPath || !isAbsolute(gitPath)
35
+ || !stat || !stat.isDirectory() || stat.uid !== uid || (stat.mode & 0o022) !== 0 || realpathSync(gitPath) !== gitPath)
36
+ throw new WorkerRefusal("Configured checkout does not match its enrolled Git identity");
37
+ return gitPath;
38
+ }
39
+
40
+ export async function boundWorkspace(repo: WorkerRepo, ref: Pick<WorkerLaneRef, "revision" | "subdir">): Promise<string> {
41
+ const cwd = join(repo.cwd, ref.subdir);
42
+ if (!lstatSync(cwd, { throwIfNoEntry: false })?.isDirectory() || realpathSync(cwd) !== cwd || !within(repo.cwd, cwd))
43
+ throw new WorkerRefusal("Worker subdirectory is not a canonical directory inside its enrolled checkout");
44
+ const observed = await workerRepositoryHead(cwd);
45
+ if (!observed || observed.repoId !== repo.id || observed.revision !== ref.revision || observed.subdir !== ref.subdir)
46
+ throw new WorkerRefusal("Worker checkout must be clean at the exact requested Git revision and subdirectory");
47
+ return cwd;
48
+ }
49
+
50
+ const claimName = "omp-sa-checkout.lock";
51
+ type CheckoutClaim = { readonly gitDir: string; readonly attempt: string };
52
+
53
+ function readClaim(gitDir: string) {
54
+ const path = join(gitDir, claimName);
55
+ const info = lstatSync(path, { throwIfNoEntry: false });
56
+ if (!info) return null;
57
+ if (!info.isFile() || info.uid !== process.getuid?.() || (info.mode & 0o777) !== 0o600 || info.size > 128)
58
+ throw new WorkerRefusal("Checkout reservation is not a private worker claim");
59
+ const fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW);
60
+ try {
61
+ const opened = fstatSync(fd);
62
+ if (opened.dev !== info.dev || opened.ino !== info.ino || opened.size !== info.size)
63
+ throw new WorkerRefusal("Checkout reservation changed during verification");
64
+ return { value: readFileSync(fd, "utf8"), info };
65
+ } finally { closeSync(fd); }
66
+ }
67
+
68
+ function syncDirectory(path: string): void {
69
+ const fd = openSync(path, constants.O_RDONLY | constants.O_DIRECTORY | constants.O_NOFOLLOW);
70
+ try { fsyncSync(fd); } finally { closeSync(fd); }
71
+ }
72
+
73
+ /** One physical checkout can be used by only one resident lane, even across enrolled keys. */
74
+ export function reserveCheckout({ gitDir, attempt }: CheckoutClaim): void {
75
+ const temporary = join(gitDir, `.omp-sa-${attempt}.tmp`);
76
+ const fd = openSync(temporary, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600);
77
+ try {
78
+ try {
79
+ writeFileSync(fd, attempt);
80
+ fsyncSync(fd);
81
+ } finally { closeSync(fd); }
82
+ linkSync(temporary, join(gitDir, claimName));
83
+ syncDirectory(gitDir);
84
+ } catch (error) {
85
+ if (error instanceof Error && "code" in error && error.code === "EEXIST")
86
+ throw new WorkerRefusal("An independent worker lane already reserves this checkout");
87
+ throw error;
88
+ } finally { unlinkSync(temporary); }
89
+ }
90
+
91
+ export function ownsCheckout({ gitDir, attempt }: CheckoutClaim): boolean {
92
+ return realpathSync(gitDir) === gitDir && readClaim(gitDir)?.value === attempt;
93
+ }
94
+
95
+ /** Never remove another attempt's claim. The lane ledger serializes release of our own claim. */
96
+ export function releaseCheckout({ gitDir, attempt }: CheckoutClaim): void {
97
+ if (realpathSync(gitDir) !== gitDir) throw new WorkerRefusal("Checkout reservation directory changed");
98
+ const claim = readClaim(gitDir);
99
+ if (claim?.value !== attempt) return;
100
+ const path = join(gitDir, claimName);
101
+ const current = lstatSync(path, { throwIfNoEntry: false });
102
+ if (!current || claim.info.dev !== current.dev || claim.info.ino !== current.ino)
103
+ throw new WorkerRefusal("Checkout reservation changed before release");
104
+ unlinkSync(path);
105
+ syncDirectory(gitDir);
106
+ }
@@ -0,0 +1,10 @@
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. */
3
+ export function parseWorkerDestination(value: string) {
4
+ 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 };
10
+ }
@@ -0,0 +1,66 @@
1
+ import { listWorkers, matchWorkerDescription, WorkerRegistrationError } from "./worker-registration";
2
+ import { workerRepositoryHead } from "./worker-repository";
3
+ import { workerDescribe, type WorkerDescription, type WorkerLaneRef, type WorkerRegistration } from "./worker-wire";
4
+
5
+ type Workspace = Pick<WorkerLaneRef, "repoId" | "revision" | "subdir">;
6
+
7
+ function verifiedWorker({ destination, description, defaultRepository }: WorkerRegistration) {
8
+ const { active: _enrollmentSnapshot, ...verified } = description;
9
+ return { destination, ...verified, default: defaultRepository !== undefined, ...(defaultRepository && { defaultRepository }) };
10
+ }
11
+
12
+ /** Local inventory only: never expose a private key path or stale activity as live. */
13
+ export function workerInventory(stateDir: string) {
14
+ return { source: "verified-inventory", workers: listWorkers(stateDir).map(verifiedWorker) };
15
+ }
16
+
17
+ async function describeEnrollment(registration: WorkerRegistration, workspace?: Workspace) {
18
+ let reply: WorkerDescription;
19
+ try { reply = await workerDescribe(registration, workspace); }
20
+ catch (error) {
21
+ if (error instanceof WorkerRegistrationError)
22
+ return { reason: "identity-unavailable", detail: "The dedicated SSH identity is missing or unsafe." } as const;
23
+ if (error instanceof Error) {
24
+ // Do not surface peer-supplied refusal messages or raw SSH output.
25
+ return { reason: "describe-unverified", detail: workspace
26
+ ? "The worker did not verify the requested checkout revision through the enrolled connection."
27
+ : "No verified describe receipt. Check the enrolled OpenSSH endpoint, independently verified host key and target policy." } as const;
28
+ }
29
+ throw error;
30
+ }
31
+ try {
32
+ const description = matchWorkerDescription(registration.description, reply);
33
+ if (!description)
34
+ 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;
36
+ } catch (error) {
37
+ if (error instanceof WorkerRegistrationError)
38
+ return { reason: "invalid-description", detail: "The worker returned an invalid description." } as const;
39
+ throw error;
40
+ }
41
+ }
42
+
43
+ /** Observes the verified endpoint but never refreshes enrollment, allocates capacity or starts a Host. */
44
+ export async function workerDoctor(stateDir: string, destination: string) {
45
+ const registration = listWorkers(stateDir).find(worker => worker.destination === destination);
46
+ if (!registration) return { status: "blocked", destination, reason: "unregistered",
47
+ detail: "No verified registration for this destination. Complete worker add, target worker init and worker add again." } as const;
48
+
49
+ const worker = verifiedWorker(registration);
50
+ const observed = await describeEnrollment(registration);
51
+ if (!observed.live) return { status: "blocked", worker, check: "worker", ...observed } as const;
52
+
53
+ const { defaultRepository } = registration;
54
+ if (!defaultRepository) return { status: "ok", worker, live: observed.live } as const;
55
+
56
+ const source = await workerRepositoryHead(defaultRepository.root);
57
+ if (!source || source.root !== defaultRepository.root || source.repoId !== defaultRepository.repoId || source.subdir !== "")
58
+ return { status: "blocked", worker, live: observed.live, check: "default-workspace", reason: "local-checkout-unverified",
59
+ detail: "The enrolled default requires the same clean local checkout root and Git repository identity." } as const;
60
+
61
+ // Send only the authorized repository binding, never the head-side path.
62
+ const { root: _root, ...workspace } = source;
63
+ const scoped = await describeEnrollment(registration, workspace);
64
+ if (!scoped.live) return { status: "blocked", worker, live: observed.live, check: "default-workspace", workspace, ...scoped } as const;
65
+ return { status: "ok", worker, live: scoped.live, workspace } as const;
66
+ }