omp-superagent 0.1.5 → 0.1.6

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 (57) hide show
  1. package/DESIGN.md +62 -8
  2. package/README.ko.md +22 -14
  3. package/README.md +36 -22
  4. package/config.example.json +1 -0
  5. package/docs/OPERATIONS.md +180 -42
  6. package/docs/design/execution.md +20 -7
  7. package/docs/design/messaging.md +131 -11
  8. package/docs/releases/0.1.6.md +21 -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 +7 -2
  19. package/skills/head/references/model-selection.md +4 -4
  20. package/skills/head/references/routing.md +9 -4
  21. package/skills/head/references/supervision.md +4 -3
  22. package/skills/lane/SKILL.md +19 -13
  23. package/skills/lane/references/workflow.md +19 -11
  24. package/src/board.ts +7 -2
  25. package/src/cli.ts +22 -6
  26. package/src/config.ts +26 -3
  27. package/src/contracts.ts +20 -2
  28. package/src/decision-tool.ts +1 -1
  29. package/src/extension.ts +40 -2
  30. package/src/gateway-client.ts +22 -1
  31. package/src/gateway-config.ts +4 -4
  32. package/src/gateway-restart-env.ts +7 -2
  33. package/src/gateway-wire.ts +8 -0
  34. package/src/group-access.ts +222 -0
  35. package/src/group-policy.ts +117 -0
  36. package/src/group-runner-extension.ts +153 -0
  37. package/src/group-runner.ts +284 -0
  38. package/src/head-rotation.ts +88 -0
  39. package/src/host-extension.ts +52 -3
  40. package/src/host-protocol.ts +1 -0
  41. package/src/host-sdk-helper.ts +7 -0
  42. package/src/host-superkit.ts +26 -0
  43. package/src/host.ts +5 -1
  44. package/src/lane-extension.ts +6 -3
  45. package/src/managed-memory-helper.ts +22 -0
  46. package/src/managed-memory.ts +100 -0
  47. package/src/managed-ulw.ts +16 -20
  48. package/src/messenger-command-catalog.json +3 -2
  49. package/src/native-launch-profile.ts +16 -0
  50. package/src/native-settings.ts +9 -3
  51. package/src/result-attachment.ts +211 -0
  52. package/src/runtime.ts +1109 -157
  53. package/src/setup-memory.ts +15 -33
  54. package/src/setup.ts +24 -22
  55. package/src/store.ts +214 -13
  56. package/src/topic-history.ts +430 -0
  57. package/src/topic-request.ts +88 -0
@@ -0,0 +1,430 @@
1
+ // allow: SIZE_OK — This API owns one bounded retrieval boundary; the journal provenance checks
2
+ // and task/checkpoint selection must travel together in the requested single source module.
3
+ import { createHash } from "node:crypto";
4
+ import { constants } from "node:fs";
5
+ import { lstat, open, realpath } from "node:fs/promises";
6
+ import { dirname, isAbsolute, join, normalize } from "node:path";
7
+ import { resolveSessionLeafId, type SessionEntry } from "@oh-my-pi/pi-coding-agent/session/session-entries";
8
+ import { parseSessionContent } from "@oh-my-pi/pi-coding-agent/session/session-loader";
9
+ import type { Lane } from "./contracts";
10
+ import { parseLaneReportResult } from "./lane-report";
11
+
12
+ export interface TopicMatch {
13
+ readonly laneId: string;
14
+ readonly entryId: string;
15
+ readonly at: number;
16
+ readonly evidence: string;
17
+ }
18
+
19
+ const MAX_QUERY = 4096;
20
+ const MAX_FIELD = 8192;
21
+ const MAX_ENVELOPE = 64 * 1024;
22
+ const MAX_JOURNAL = 16 * 1024 * 1024;
23
+ const MAX_SEARCH = 64 * 1024 * 1024;
24
+ const EXCERPT = 480;
25
+ const CHECKPOINT = 320;
26
+ const MAX_RECALL_ITEMS = 10;
27
+ const ALIAS_ANCHOR = [2] as const;
28
+ const SEMANTIC_ANCHOR = [5] as const;
29
+ const RECALL_ANCHORS = [...ALIAS_ANCHOR, ...SEMANTIC_ANCHOR] as const;
30
+ const DAY = 86_400_000;
31
+ const nativeId = /^[\w-]{1,128}$/;
32
+ const lastWeek = /\blast week\b|지난\s*주/giu;
33
+ const lastMonth = /\blast month\b|지난\s*달|저번\s*달/giu;
34
+ const yesterday = /\byesterday\b|어제/giu;
35
+ const timePhrases = [lastWeek, lastMonth, yesterday] as const;
36
+ const enPast = /\b(?:earlier|previously|before|last time|the other day|from before|where (?:we|you|i) left off|(?:we|you|i) (?:were|had been|worked on|started|looked at|investigated))\b/giu;
37
+ const enResume = /\b(?:resume|pick (?:back )?up|go back to|return to|carry on with|continue|pick(?= .{1,120}\bback up\b)|back up)\b/giu;
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
+ const koPast = /지난\s*(?:번|주|달)|저번(?:에|주|달)?|이전(?:에)?|예전(?:에)?|그때|아까|어제|(?:하|보|고치|잡|찾|다루|만들|살펴보|해보)던|(?:했|봤|다뤘|고쳤|만들었)던|하던\s*데서|보던\s*데서/gu;
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;
42
+ 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
+ ulw ultrawork mass jevify orchestrate workflowz ultrathink`.split(/\s+/));
45
+ const categories = new Set(["bug", "test", "feature", "migration", "change", "inspection", "review", "analysis", "incident"]);
46
+ 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
+ 결과 계속 기록 내용 대화 메시지 메모 모델 문서 변경 요약 확인 요청 자료 이전 정보 진행 설정 세션 사용자 작업 작업공간 저장소 참고 관련 기본 완료 반복 이어서 재개 워크스페이스`.split(/\s+/));
48
+ const aliases = new Map([
49
+ ["로그인", "login"], ["signin", "login"], ["로그아웃", "logout"], ["인증", "authentication"], ["auth", "authentication"],
50
+ ["버그", "bug"], ["문제", "bug"], ["오류", "bug"], ["에러", "bug"], ["issue", "bug"],
51
+ ["error", "bug"], ["failure", "bug"], ["fail", "bug"], ["broken", "bug"], ["break", "bug"], ["fix", "bug"], ["fixe", "bug"], ["fixed", "bug"],
52
+ ["regression", "bug"], ["crash", "bug"], ["debug", "bug"],
53
+ ["테스트", "test"], ["기능", "feature"], ["마이그레이션", "migration"],
54
+ ["리다이렉트", "redirect"], ["리디렉션", "redirect"], ["리다이렉션", "redirect"], ["redirection", "redirect"],
55
+ ]);
56
+
57
+ /** Exclude pasted blocks and quote lines, not inline names of the task. */
58
+ function directText(text: string): string {
59
+ let fence = "";
60
+ return text.split(/\r?\n/).filter(line => {
61
+ const marker = /^ {0,3}(`{3,}|~{3,})(.*)$/.exec(line);
62
+ if (fence) {
63
+ if (marker && marker[1].startsWith(fence) && !marker[2].trim()) fence = "";
64
+ return false;
65
+ }
66
+ if (marker) { fence = marker[1]; return false; }
67
+ return !/^ {0,3}>/.test(line);
68
+ }).join("\n");
69
+ }
70
+
71
+ function wordTokens(text: string): readonly string[] {
72
+ const tokens = text.normalize("NFKC").toLowerCase().replace(/\b(?:sign|log)[ -]in\b/g, "login")
73
+ .match(/[a-z][a-z0-9_]*|[0-9]{3,}|[\p{Script=Hangul}]+/gu) ?? [];
74
+ return tokens.flatMap(token => {
75
+ const stem = token.replace(/^([\p{Script=Hangul}]{2,})(?:에서부터|에서는|부터|에서|으로|처럼|까지|하고|이랑|만|의|은|는|이|가|을|를|에|도)$/u, "$1")
76
+ .replace(/^([a-z]{4,})(?:ing|ed|(?<![isu])s)$/, "$1");
77
+ const word = aliases.get(stem) ?? stem;
78
+ return word.length > 1 && word.length <= 64 && !ignored.has(word) ? [word] : [];
79
+ });
80
+ }
81
+
82
+ function words(text: string): Set<string> {
83
+ return new Set(wordTokens(text));
84
+ }
85
+
86
+ function matchingExcerpt(text: string, terms: ReadonlySet<string>): string {
87
+ // Match anchors in a single bounded piece of useful context, not across unrelated
88
+ // paragraphs of a transcript, and return the actual grounded detail around them.
89
+ for (const excerpt of excerptWindows(text)) {
90
+ const seen = words(excerpt);
91
+ if ([...terms].every(word => seen.has(word))) return excerpt;
92
+ }
93
+ return "";
94
+ }
95
+
96
+ function* excerptWindows(text: string): Iterable<string> {
97
+ const clean = visibleLine(text, MAX_FIELD);
98
+ for (let start = 0; start < clean.length; start += EXCERPT / 2) {
99
+ yield clean.slice(start, start + EXCERPT).trim();
100
+ if (start + EXCERPT >= clean.length) break;
101
+ }
102
+ }
103
+
104
+ function visibleLine(text: string, limit: number): string {
105
+ return directText(text.slice(0, limit)).replace(/[\s\p{Cc}\p{Cf}]+/gu, " ").trim();
106
+ }
107
+
108
+ 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, '""');
112
+ 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
+ const en = intent.match(enResume) ?? [];
114
+ const historical = [...timePhrases, enPast, koPast].some(pattern => intent.match(pattern));
115
+ const qualifiedEnglish = en.some(verb => !/^continue$/i.test(verb))
116
+ || /^(?:(?:please|can you|could you|would you)\s+)*continue\s+(?:work(?:ing)? on|the|our|that)\b/i.test(intent);
117
+ if (!(en.length && enLead.test(intent) && (qualifiedEnglish || historical)
118
+ || 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];
120
+ const terms = words([...timePhrases, enPast, enResume, koPast, koResume]
121
+ .reduce((value, pattern) => value.replace(pattern, " "), subject));
122
+ return terms.size <= 16 && [...terms].some(word => !categories.has(word)) ? { terms, intent, subject: subject.trim() } : null;
123
+ }
124
+
125
+ export function refersToPastTopic(text: string): boolean {
126
+ return request(text) !== null;
127
+ }
128
+
129
+ /** Send only the owner's historical subject to native memory, in its original language. */
130
+ export function pastTopicQuery(text: string): string | null {
131
+ return request(text)?.subject ?? null;
132
+ }
133
+
134
+ type RecallItem = { readonly content: string; readonly id?: string; readonly source?: string };
135
+
136
+ function concreteTerm(word: string): boolean {
137
+ return !categories.has(word) && !recallBoilerplate.has(word) && /^(?:[a-z]{4,}|[\p{Script=Hangul}]{2,})$/u.test(word);
138
+ }
139
+
140
+ function* concretePhrases(text: string, lengths: readonly number[]): Iterable<readonly string[]> {
141
+ for (const clause of text.split(/\n+|[.!?。;:](?:\s|$)/u)) {
142
+ // Remove identifiers as units: splitting e.g. CASE-308 into words would
143
+ // promote coincident identifiers to apparently independent anchors.
144
+ const tokens = wordTokens(clause.normalize("NFKC").replace(/\b(?:[\w-]*\d[\w-]*|[a-f]{8,})\b/gi, " ")).filter(concreteTerm);
145
+ for (const length of lengths) {
146
+ for (let start = 0; start + length <= tokens.length; start++) {
147
+ const phrase = tokens.slice(start, start + length);
148
+ if (phrase.every((word, index) => phrase.indexOf(word) === index)) yield phrase;
149
+ }
150
+ }
151
+ }
152
+ }
153
+
154
+ function recallAnchors(terms: ReadonlySet<string>, items: readonly RecallItem[]): ReadonlySet<string> {
155
+ const anchors = new Set<string>();
156
+ const subject = [...terms].filter(concreteTerm);
157
+ if (!subject.length) return anchors;
158
+ // Exact query terms can establish a nickname bridge within one memory passage.
159
+ // Otherwise native semantic search can suggest a turn only with much stronger
160
+ // corroboration: a substantial ordered phrase independently present in its journal.
161
+ for (const { content } of items) {
162
+ for (const paragraph of directText(content).split(/\n\s*\n/)) {
163
+ for (const phrase of concretePhrases(paragraph, SEMANTIC_ANCHOR)) anchors.add(phrase.join(" "));
164
+ for (const excerpt of excerptWindows(paragraph)) {
165
+ const seen = words(excerpt);
166
+ if (!subject.every(word => seen.has(word))) continue;
167
+ for (const phrase of concretePhrases(excerpt, ALIAS_ANCHOR)) {
168
+ if (phrase.some(word => !terms.has(word))) anchors.add(phrase.join(" "));
169
+ }
170
+ }
171
+ }
172
+ }
173
+ return anchors;
174
+ }
175
+
176
+ function recalledExcerpt(task: string, anchors: ReadonlySet<string>): string {
177
+ if (!anchors.size) return "";
178
+ // Check the phrase in the original owner lines as well as in the rendered
179
+ // excerpt, where line breaks are collapsed.
180
+ const grounded = new Set<string>();
181
+ for (const phrase of concretePhrases(task.replace(inlineQuotes, "\n"), RECALL_ANCHORS)) {
182
+ const key = phrase.join(" ");
183
+ if (anchors.has(key)) grounded.add(key);
184
+ }
185
+ if (!grounded.size) return "";
186
+ for (const excerpt of excerptWindows(task)) {
187
+ for (const phrase of concretePhrases(excerpt, RECALL_ANCHORS)) {
188
+ if (grounded.has(phrase.join(" "))) return excerpt;
189
+ }
190
+ }
191
+ return "";
192
+ }
193
+
194
+ /** Relative calendar phrases use UTC because a messenger route has no owner timezone. */
195
+ function dateWindow(intent: string, receivedAt: number): readonly [number, number] | null {
196
+ const now = new Date(receivedAt);
197
+ if (!Number.isFinite(now.getTime())) return null;
198
+ const today = now.getTime() - (now.getUTCHours() * 3600 + now.getUTCMinutes() * 60 + now.getUTCSeconds()) * 1000 - now.getUTCMilliseconds();
199
+ const dates: (readonly [number, number])[] = [];
200
+ if (intent.match(yesterday)) dates.push([today - DAY, today]);
201
+ if (intent.match(lastWeek)) {
202
+ const monday = today - (now.getUTCDay() + 6) % 7 * DAY;
203
+ dates.push([monday - 7 * DAY, monday]);
204
+ }
205
+ if (intent.match(lastMonth)) dates.push([
206
+ Date.UTC(now.getUTCFullYear(), now.getUTCMonth() - 1, 1), Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1),
207
+ ]);
208
+ if (dates.length > 1) return null;
209
+ return dates[0] ?? [0, receivedAt + 1];
210
+ }
211
+
212
+ function record(value: unknown): value is Record<string, unknown> {
213
+ return !!value && typeof value === "object" && !Array.isArray(value);
214
+ }
215
+
216
+ function promptText(content: unknown): string {
217
+ if (typeof content === "string") return content.length <= MAX_ENVELOPE ? content : "";
218
+ if (!Array.isArray(content)) return "";
219
+ let text = "";
220
+ for (const block of content.slice(0, 32)) {
221
+ if (!record(block) || block.type !== "text" || typeof block.text !== "string") continue;
222
+ if (text.length + block.text.length >= MAX_ENVELOPE) return "";
223
+ text += `${text ? "\n" : ""}${block.text}`;
224
+ }
225
+ return text;
226
+ }
227
+
228
+ /** 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);
232
+ 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
+ }
239
+ }
240
+
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;
243
+ 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;
248
+ }
249
+
250
+ function activeBranch(entries: readonly SessionEntry[]): readonly SessionEntry[] {
251
+ const byId = new Map(entries.map(entry => [entry.id, entry]));
252
+ if (byId.size !== entries.length) return [];
253
+ let id = resolveSessionLeafId(entries);
254
+ const path: SessionEntry[] = [];
255
+ while (id !== null) {
256
+ const entry = byId.get(id);
257
+ if (!entry) return [];
258
+ if (entry.type === "reset_boundary") break;
259
+ path.push(entry);
260
+ byId.delete(id); // A repeated active ancestor is a corrupt cycle.
261
+ id = entry.parentId;
262
+ }
263
+ return path.reverse();
264
+ }
265
+
266
+ /** Reuse OMP's title-slot aware parser and leaf replay without opening an OMP session. */
267
+ 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 [];
269
+ const root = dirname(dirname(lane.socketPath));
270
+ const parts = ["sessions", lane.id, "session.jsonl"] as const;
271
+ if (!isAbsolute(root) || lane.socketPath !== join(root, "run", `${lane.id}.sock`) || lane.sessionFile !== join(root, ...parts)) return [];
272
+ try {
273
+ const expected = join(await realpath(root), ...parts);
274
+ if (await realpath(lane.sessionFile) !== expected) return [];
275
+ const initial = await lstat(lane.sessionFile, { bigint: true });
276
+ if (!initial.isFile() || initial.nlink !== 1n) return [];
277
+ const file = await open(lane.sessionFile, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
278
+ try {
279
+ const before = await file.stat({ bigint: true });
280
+ if (!before.isFile() || before.dev !== initial.dev || before.ino !== initial.ino || before.nlink !== 1n
281
+ || (process.getuid && before.uid !== BigInt(process.getuid()))) return [];
282
+ if (before.size > MAX_JOURNAL) return null;
283
+ if (before.size === 0n) return [];
284
+ const size = Number(before.size);
285
+ if (size > budget.remaining) return null;
286
+ budget.remaining -= size;
287
+ const buffer = Buffer.alloc(size);
288
+ for (let offset = 0; offset < size;) {
289
+ const { bytesRead } = await file.read(buffer, offset, size - offset, offset);
290
+ if (!bytesRead) return [];
291
+ offset += bytesRead;
292
+ }
293
+ const after = await lstat(lane.sessionFile, { bigint: true });
294
+ if (!after.isFile() || after.dev !== before.dev || after.ino !== before.ino || after.nlink !== before.nlink
295
+ || after.size !== before.size || after.mtimeNs !== before.mtimeNs || after.ctimeNs !== before.ctimeNs
296
+ || await realpath(lane.sessionFile) !== expected || buffer.at(-1) !== 10) return [];
297
+ const { entries, invalidHeader, malformedRecords } = parseSessionContent(buffer.toString("utf8"));
298
+ const [header, ...body] = entries;
299
+ if (invalidHeader || malformedRecords || !record(header) || header.type !== "session" || header.id !== lane.sessionId
300
+ || header.cwd !== lane.cwd) return [];
301
+ const branch = body.filter((entry): entry is SessionEntry => record(entry) && typeof entry.type === "string" && entry.type !== "session"
302
+ && typeof entry.id === "string" && nativeId.test(entry.id) && (entry.parentId === null || typeof entry.parentId === "string")
303
+ && (entry.activeLeafId === undefined || entry.activeLeafId === null || typeof entry.activeLeafId === "string"));
304
+ return branch.length === body.length ? activeBranch(branch) : [];
305
+ } finally {
306
+ await file.close();
307
+ }
308
+ } catch (error) {
309
+ if (error instanceof Error && "code" in error) return []; // Missing, unreadable or replaced journal.
310
+ throw error;
311
+ }
312
+ }
313
+
314
+ type Checkpoint = { readonly id: string; readonly at: number; readonly text: string };
315
+ type MatchedTurn = {
316
+ readonly id: string;
317
+ readonly at: number;
318
+ readonly excerpts: readonly [string, ...string[]];
319
+ readonly direct: boolean;
320
+ readonly digest: string | undefined;
321
+ proposed?: Checkpoint;
322
+ checkpoint?: Checkpoint;
323
+ summaryInWindow?: boolean;
324
+ receiptSeen?: boolean;
325
+ };
326
+
327
+ type TopicQuery = {
328
+ readonly terms: ReadonlySet<string>;
329
+ readonly window: readonly [number, number];
330
+ readonly receivedAt: number;
331
+ };
332
+
333
+ type TopicSelection = { readonly anchors: ReadonlySet<string> } | { readonly entryId: string };
334
+ type JournalQuery = TopicQuery & { readonly selection: TopicSelection };
335
+
336
+ function topicQuery(text: string, receivedAt: number): TopicQuery | null {
337
+ const query = request(text);
338
+ const window = query && dateWindow(query.intent, receivedAt);
339
+ return query && window ? { terms: query.terms, window, receivedAt } : null;
340
+ }
341
+
342
+ function matchJournal(entries: readonly SessionEntry[], lane: Lane, query: JournalQuery): readonly MatchedTurn[] {
343
+ const matches: MatchedTurn[] = [];
344
+ const within = (at: number | undefined) => at !== undefined && at >= query.window[0] && at < query.window[1];
345
+ const { selection } = query;
346
+ 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;
349
+ const user = entry.type === "message" && record(entry.message) && entry.message.role === "user" ? entry.message : null;
350
+ // Any later native user turn ends the previous request's checkpoint scope,
351
+ // even when its content or date is not usable as evidence.
352
+ if (user) current = undefined;
353
+ if (!Number.isFinite(at) || at < 0 || at > query.receivedAt) continue;
354
+ if (user) {
355
+ if ("entryId" in selection && entry.id !== selection.entryId) continue;
356
+ if (user.synthetic === true || user.parentIrc || user.attribution === "agent") continue;
357
+ const raw = promptText(user.content);
358
+ const task = directText(raw).trim().slice(0, MAX_FIELD);
359
+ if (refersToPastTopic(task.slice(0, MAX_QUERY))) continue; // Prior continuation echoes are not independent task evidence.
360
+ const direct = matchingExcerpt(task, query.terms);
361
+ const [excerpt, ...alternates] = direct ? [direct] : "entryId" in selection ? [...excerptWindows(task)]
362
+ : [recalledExcerpt(task, selection.anchors)];
363
+ if (excerpt) {
364
+ current = { id: entry.id, at, excerpts: [excerpt, ...alternates], direct: !!direct, digest: requestDigest(raw, lane) };
365
+ matches.push(current);
366
+ }
367
+ } else if (current && entry.type === "custom") {
368
+ if (entry.customType === "rpc_prompt_result" && !current.receiptSeen) {
369
+ current.receiptSeen = true;
370
+ if (current.digest && current.proposed && completedRequest(entry.data, lane, current.digest)) {
371
+ current.checkpoint = current.proposed;
372
+ }
373
+ } else if (entry.customType === "superagent-lane-report" && current.digest && !current.receiptSeen) {
374
+ const event = parseLaneReportResult({ details: entry.data });
375
+ if (event?.sessionId === lane.sessionId && event.report.status !== "waiting") {
376
+ const text = visibleLine(event.report.summary, MAX_FIELD).slice(0, CHECKPOINT);
377
+ if (text) current.proposed = { id: entry.id, at, text };
378
+ }
379
+ }
380
+ } else if (current?.direct && within(at) && (entry.type === "compaction" || entry.type === "branch_summary")
381
+ && typeof entry.summary === "string" && matchingExcerpt(entry.summary, query.terms)) {
382
+ current.summaryInWindow = true;
383
+ }
384
+ }
385
+ return matches.filter(turn => within(turn.at) || within(turn.checkpoint?.at) || turn.summaryInWindow);
386
+ }
387
+
388
+ function topicMatch(lane: Lane, turn: MatchedTurn, excerpt: string): TopicMatch {
389
+ const date = new Date(turn.at).toISOString().slice(0, 10);
390
+ const checkpoint = turn.checkpoint
391
+ ? `\nVerified native checkpoint (entry ${turn.checkpoint.id}, ${new Date(turn.checkpoint.at).toISOString().slice(0, 10)} UTC): ${turn.checkpoint.text}`
392
+ : "";
393
+ const evidence = `Owner task (entry ${turn.id}, ${date} UTC): ${excerpt}${checkpoint}`;
394
+ return { laneId: lane.id, entryId: turn.id, at: turn.at, evidence };
395
+ }
396
+
397
+ /** Search only caller-scoped managed lanes. Journal evidence is data, never instructions. */
398
+ export async function findPastTopic(text: string, lanes: readonly Lane[], receivedAt: number,
399
+ recallItems: readonly RecallItem[] = []): Promise<readonly TopicMatch[]> {
400
+ const query = topicQuery(text, receivedAt);
401
+ // Do not claim uniqueness from an incomplete set of hints.
402
+ if (!query || recallItems.length > MAX_RECALL_ITEMS || recallItems.some(item => item.content.length > MAX_FIELD)) return [];
403
+ const selection = { anchors: recallAnchors(query.terms, recallItems) };
404
+ const matches = new Map<string, TopicMatch>();
405
+ const budget = { remaining: MAX_SEARCH };
406
+ for (const lane of lanes) {
407
+ const entries = await readJournal(lane, budget);
408
+ if (entries === null) return []; // Incomplete search cannot establish uniqueness.
409
+ for (const turn of matchJournal(entries, lane, { ...query, selection })) {
410
+ matches.set(JSON.stringify([lane.id, lane.sessionId, turn.id]), topicMatch(lane, turn, turn.excerpts[0]));
411
+ }
412
+ }
413
+ return [...matches.values()];
414
+ }
415
+
416
+ /** Revalidate an admitted evidence pin against its exact active journal entry, without recall. */
417
+ export async function readPastTopic(text: string, lane: Lane, receivedAt: number, entryId: string,
418
+ evidenceHash: string): Promise<TopicMatch | null> {
419
+ const query = topicQuery(text, receivedAt);
420
+ if (!query || !nativeId.test(entryId) || !/^[a-f0-9]{64}$/.test(evidenceHash)) return null;
421
+ const entries = await readJournal(lane, { remaining: MAX_SEARCH });
422
+ if (entries === null) return null;
423
+ for (const turn of matchJournal(entries, lane, { ...query, selection: { entryId } })) {
424
+ for (const excerpt of turn.excerpts) {
425
+ const match = topicMatch(lane, turn, excerpt);
426
+ if (createHash("sha256").update(match.evidence).digest("hex") === evidenceHash) return match;
427
+ }
428
+ }
429
+ return null;
430
+ }
@@ -0,0 +1,88 @@
1
+ import { realpathSync, statSync } from "node:fs";
2
+ import { basename, isAbsolute } from "node:path";
3
+ import type { Lane } from "./contracts";
4
+
5
+ export const TOPIC_CHOICE_WAIT_MS = 5 * 60_000;
6
+
7
+ /** Only owner text, never a quote, attachment path, or channel description. */
8
+ export function topicRequest(text: string) {
9
+ const request = text.replace(/^\s*\/new(?:\s+|$)/, "");
10
+ const header = /^cwd:[ \t]*([^\n]*)(?:\n|$)/i.exec(request.trimStart());
11
+ if (!header) return { text: request, cwd: null };
12
+ return { text: request.trimStart().slice(header[0].length), cwd: header[1].trim() };
13
+ }
14
+
15
+ /** Parse only the original Discord owner request body. An empty result asks for a task. */
16
+ export function discordThreadSplit(text: string): string | null {
17
+ const line = text.trim();
18
+ if (/[\r\n\u2028\u2029]/u.test(line)) return null;
19
+ const directive = /^(?:이건\s+따로\s+빼\s*줘|(?:please\s+)?split\s+this\s+into\s+a\s+new\s+thread)(?:[.!]|\s*:\s*(.*))?$/iu.exec(line);
20
+ if (directive) return directive[1]?.trim() ?? "";
21
+
22
+ // Without a colon, accept a plain task label, not an embedded sentence or quotation.
23
+ const korean = /^([\p{L}\p{M}\p{N}_ -]+?)(?:은|는|을|를)\s+새\s+스레드에서\s+해\s*줘[.!]?$/u.exec(line);
24
+ const english = /^(?:please\s+)?do\s+([\p{L}\p{M}\p{N}_ -]+?)\s+in\s+a\s+new\s+thread[.!]?$/iu.exec(line);
25
+ const task = (korean?.[1] ?? english?.[1])?.trim();
26
+ // Keep hyphenated task words, but not punctuation standing in for a word or clause boundary.
27
+ if (!task || /(?:^| )-|-(?: |$)|--|(?:^| )_+(?: |$)/u.test(task)) return null;
28
+ // The closing thread phrase can be an excluded alternative, not a destination.
29
+ if (/\b(?:no|not|never|instead|(?:rather|other)[ -]+than|as[ -]+opposed[ -]+to|but|or|nor|except|unless|without|versus|vs)\b|말고|대신|아니라|아닌/iu.test(task)) return null;
30
+ if (/\b(?:for +example|the +phrase|the +words)\b|예를\s*들어|예시로|라고\s/iu.test(task)) return null;
31
+ // “Do we ...” and similar questions need not end in a question mark.
32
+ if (english && /^(?:i|you|we|they)\b/iu.test(task)) return null;
33
+ return /^(?:this(?: task)?|it|이거|이것)$/iu.test(task) ? "" : task;
34
+ }
35
+
36
+ /** An edit can revise the task, not create a new placement or confirm a different one. */
37
+ export function editsTopicPlacement(before: string, after: string): boolean {
38
+ const boundary = /^\/(?:new|main)(?:\s|$)/;
39
+ const coordinates = /^\/head(?:\s|$)/;
40
+ if (boundary.test(before.trimStart()) || boundary.test(after.trimStart()) ||
41
+ coordinates.test(before.trimStart()) !== coordinates.test(after.trimStart())) return true;
42
+ const old = topicRequest(before), next = topicRequest(after);
43
+ return old.cwd !== next.cwd || old.cwd !== null && (!old.text.trim() || !next.text.trim());
44
+ }
45
+
46
+ export function existingWorkspace(path: string): string | null {
47
+ if (!isAbsolute(path)) return null;
48
+ try {
49
+ const canonical = realpathSync(path);
50
+ return statSync(canonical).isDirectory() ? canonical : null;
51
+ } catch (error) {
52
+ if (!(error instanceof Error)) throw error;
53
+ return null;
54
+ }
55
+ }
56
+
57
+ /** Match names of placed workspaces, not substrings of paths, filenames or longer repo names. */
58
+ export function namedWorkspaces(text: string, lanes: readonly Lane[], nameOnly = false): Set<string> {
59
+ const matches = new Set<string>();
60
+ for (const lane of lanes) {
61
+ for (const path of [lane.cwd, lane.repoRoot]) {
62
+ if (!path) continue;
63
+ const name = basename(path);
64
+ if (!name) continue;
65
+ const literal = name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
66
+ const pattern = nameOnly ? `^${literal}$`
67
+ : `(?<![\\p{L}\\p{N}_./\\\\-])${literal}(?:에서|으로|로|에|이랑|랑|하고|와|과|부터|까지|의)?(?:만|도|은|는|이|가|을|를)?(?![\\p{L}\\p{N}_/\\\\-]|\\.[\\p{L}\\p{N}])`;
68
+ if (new RegExp(pattern, "iu").test(text)) matches.add(lane.cwd);
69
+ }
70
+ }
71
+ return matches;
72
+ }
73
+
74
+ /** Choose a single existing directory; conflicting evidence or explicit exclusions need clarification. */
75
+ export function inferredWorkspace(text: string, lanes: readonly Lane[], replied: string | null, threadWorkspace: string | null): string | null {
76
+ if (/\b(?:not|avoid|except|instead of|rather than|other than)\b|n['’]t\b|말고|대신|제외|빼고|아니라|아닌|(?:쓰|사용하)지\s*마/iu.test(text)) return null;
77
+ const candidates = namedWorkspaces(text, lanes);
78
+ const lineEnd = text.indexOf("\n");
79
+ const path = lineEnd > 0 ? existingWorkspace(text.slice(0, lineEnd).trim()) : null;
80
+ if (path) candidates.add(path);
81
+ if (replied) candidates.add(replied);
82
+ if (!candidates.size && threadWorkspace) candidates.add(threadWorkspace);
83
+ if (!candidates.size && /^(?:(?:in|use) the same (?:repo(?:sitory)?|project|workspace)\b|(?:같은|이전|아까|기존|그)\s*(?:저장소|레포|프로젝트)에서\s)/iu.test(text)) {
84
+ for (const lane of lanes) candidates.add(lane.cwd);
85
+ }
86
+ const [selected] = candidates;
87
+ return candidates.size === 1 && selected && existingWorkspace(selected) === selected ? selected : null;
88
+ }