@a-t-h-i/bot-lobby 0.6.60 → 0.6.62

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 (100) hide show
  1. package/README.md +3 -7
  2. package/package.json +2 -1
  3. package/prompts/designer.md +25 -15
  4. package/prompts/master.md +284 -491
  5. package/prompts/panel.md +7 -0
  6. package/prompts/planner.md +15 -4
  7. package/prompts/qa.md +5 -1
  8. package/prompts/worker.md +0 -7
  9. package/scripts/builtin/affected_packages.mjs +106 -0
  10. package/scripts/builtin/check_changed.mjs +51 -0
  11. package/scripts/builtin/check_contract_breakage.mjs +118 -0
  12. package/scripts/builtin/circular_dependency_check.mjs +79 -0
  13. package/scripts/builtin/code_duplication_check.mjs +86 -0
  14. package/scripts/builtin/diff_summary.mjs +62 -0
  15. package/scripts/builtin/failure_digest.mjs +107 -0
  16. package/scripts/builtin/find_generated_files.mjs +79 -0
  17. package/scripts/builtin/find_symbol.mjs +81 -0
  18. package/scripts/builtin/find_test_fixtures.mjs +73 -0
  19. package/scripts/builtin/find_tests_for.mjs +12 -0
  20. package/scripts/builtin/lib/common.mjs +267 -0
  21. package/scripts/builtin/outline_file.mjs +77 -0
  22. package/scripts/builtin/project_commands.mjs +49 -0
  23. package/scripts/builtin/recent_changes.mjs +14 -0
  24. package/scripts/builtin/repo_map.mjs +65 -0
  25. package/scripts/builtin/run_changed_tests.mjs +48 -0
  26. package/src/delivery/transport.ts +1 -1
  27. package/src/desk/client-extension.ts +1 -31
  28. package/src/desk/ipc.ts +1 -11
  29. package/src/desk/session.ts +4 -101
  30. package/src/execution/agent-runner.ts +50 -8
  31. package/src/execution/assigned-session.ts +263 -0
  32. package/src/execution/assignment-discovery.ts +128 -0
  33. package/src/execution/assignment-policy.ts +46 -0
  34. package/src/execution/assignment.ts +175 -0
  35. package/src/execution/delegation.ts +9 -94
  36. package/src/execution/pi-runner.ts +99 -9
  37. package/src/harness/instructions.ts +1 -1
  38. package/src/index.ts +3 -0
  39. package/src/knowledge/design-record.ts +394 -0
  40. package/src/knowledge/file-notes.ts +36 -8
  41. package/src/lobby/ask.ts +6 -0
  42. package/src/lobby/exec.ts +28 -0
  43. package/src/lobby/host.ts +1 -11
  44. package/src/lobby/planner.ts +50 -124
  45. package/src/lobby/prompts.ts +1 -7
  46. package/src/lobby/runtime.ts +2 -26
  47. package/src/lobby/service.ts +25 -23
  48. package/src/lobby/topics.ts +0 -2
  49. package/src/master/evidence-freshness.ts +96 -0
  50. package/src/master/master.ts +248 -74
  51. package/src/master/scout-cache.ts +1 -1
  52. package/src/master/scout-lock.ts +44 -0
  53. package/src/master/scout-prefetch.ts +78 -0
  54. package/src/pi/activity.ts +2 -0
  55. package/src/pi/assignment-guard.ts +157 -0
  56. package/src/pi/delegation.ts +2 -21
  57. package/src/pi/model-support.ts +0 -6
  58. package/src/pi/start-task.ts +18 -7
  59. package/src/pi/tools.ts +41 -8
  60. package/src/roles/scout.ts +3 -1
  61. package/src/roles/worker.ts +107 -5
  62. package/src/schemas/configuration.ts +11 -45
  63. package/src/schemas/findings.ts +3 -0
  64. package/src/schemas/task.ts +30 -12
  65. package/src/scripts/library.ts +31 -1
  66. package/src/scripts/pick.ts +31 -15
  67. package/src/state/archive.ts +10 -0
  68. package/src/state/checkpoint.ts +0 -1
  69. package/src/state/gitignore.ts +39 -0
  70. package/src/state/persistence.ts +56 -0
  71. package/src/state/recovery.ts +33 -1
  72. package/src/webui/api/index.ts +6 -35
  73. package/src/webui/api/retention.ts +44 -0
  74. package/src/webui/api/status.ts +4 -6
  75. package/src/webui/dev/fake-service.ts +0 -117
  76. package/src/webui/dev/fixtures.ts +2 -16
  77. package/src/webui/protocol.ts +2 -142
  78. package/src/workflow/draft-assignments.ts +118 -0
  79. package/src/workflow/workflow.ts +271 -214
  80. package/webui/dist/assets/{CodeSurface-BtzJOVyH.js → CodeSurface-D3c12DBE.js} +1 -1
  81. package/webui/dist/assets/{TerminalView-Cz-KNWsq.js → TerminalView-DG4X3Yyr.js} +1 -1
  82. package/webui/dist/assets/index-BDmgr1OS.js +112 -0
  83. package/webui/dist/assets/index-BTyu99rI.css +2 -0
  84. package/webui/dist/build.json +29 -65
  85. package/webui/dist/index.html +2 -2
  86. package/prompts/expert.md +0 -17
  87. package/prompts/goal-check.md +0 -44
  88. package/prompts/pr-review.md +0 -62
  89. package/prompts/splitter.md +0 -58
  90. package/src/execution/worker-trees.ts +0 -396
  91. package/src/lobby/issues.ts +0 -219
  92. package/src/lobby/pr-review.ts +0 -366
  93. package/src/lobby/pulls.ts +0 -250
  94. package/src/lobby/split.ts +0 -262
  95. package/src/master/goal-check.ts +0 -115
  96. package/src/webui/api/gh-error.ts +0 -17
  97. package/src/webui/api/git.ts +0 -98
  98. package/src/webui/api/issues.ts +0 -50
  99. package/webui/dist/assets/index-D5fvY8f8.js +0 -112
  100. package/webui/dist/assets/index-DFvk8ADr.css +0 -2
@@ -0,0 +1,263 @@
1
+ import { closeSync, existsSync, fsyncSync, lstatSync, mkdirSync, openSync, readdirSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
2
+ import { hostname } from "node:os";
3
+ import { createHash, randomUUID } from "node:crypto";
4
+ import { join, resolve } from "node:path";
5
+
6
+ /** Host-authored identity; never populate this from model tool arguments. */
7
+ export interface AssignedSession {
8
+ taskDir: string;
9
+ assignmentId: string;
10
+ revision: number;
11
+ evidence?: string[];
12
+ completedWork?: string[];
13
+ needs?: unknown[];
14
+ consumedDiscovery?: number;
15
+ /** The assignment's files and verification, for the worker's in-process guard. */
16
+ files?: { path: string; access: "reference" | "edit" | "create" }[];
17
+ verification?: string[];
18
+ }
19
+ export interface AssignedSessionState {
20
+ version: 1;
21
+ assignmentId: string;
22
+ revision: number;
23
+ sessionFile: string;
24
+ evidence: string[];
25
+ completedWork: string[];
26
+ needs: unknown[];
27
+ consumedDiscovery: number;
28
+ terminal?: boolean;
29
+ }
30
+ export class SessionRecoveryError extends Error {
31
+ constructor(message: string) { super(`Assigned session recovery: ${message}`); this.name = "SessionRecoveryError"; }
32
+ }
33
+
34
+ type Entry = Record<string, unknown>;
35
+ function object(value: unknown): Entry {
36
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new SessionRecoveryError("expected an object");
37
+ return value as Entry;
38
+ }
39
+ const ENTRY_TYPES = new Set(["message", "model_change", "thinking_level_change", "usage", "compaction", "context_edit", "branch_summary", "custom", "custom_message", "label", "session_info"]);
40
+ const ROLES = new Set(["system", "user", "assistant", "toolResult", "custom", "bashExecution", "compactionSummary", "branchSummary"]);
41
+ const TOOL_LISTING = /<tools>[\s\S]*?<\/tools>\n?/g;
42
+ function sanitizeSystem(value: unknown): Entry {
43
+ const message = object(value);
44
+ if (message.role !== "system") throw new SessionRecoveryError("invalid system checkpoint role");
45
+ if (typeof message.content !== "string") throw new SessionRecoveryError("unsupported system content; cannot separate declarations from unrelated instructions without losing history");
46
+ // A compaction checkpoint carries the composed prompt as text: only its tool listing is a declaration.
47
+ const clean: Entry = { ...message, content: message.content.replace(TOOL_LISTING, "") };
48
+ delete clean.toolsAdded;
49
+ delete clean.toolsRemoved;
50
+ if (message.sections !== undefined) {
51
+ const sections = { ...object(message.sections) };
52
+ delete sections.tools;
53
+ clean.sections = sections;
54
+ }
55
+ return clean;
56
+ }
57
+ function ancestors(entry: Entry, entries: Map<string, Entry>): Set<string> {
58
+ const ids = new Set<string>();
59
+ let parent = entry.parentId;
60
+ while (typeof parent === "string") {
61
+ if (ids.has(parent)) throw new SessionRecoveryError("cyclic parent chain");
62
+ ids.add(parent);
63
+ parent = entries.get(parent)?.parentId;
64
+ }
65
+ return ids;
66
+ }
67
+ function validateReferences(entry: Entry, entries: Map<string, Entry>): void {
68
+ for (const key of ["parentId", "targetId", "fromId", "firstKeptEntryId"]) {
69
+ const ref = entry[key];
70
+ if (ref !== undefined && ref !== null && (typeof ref !== "string" || !entries.has(ref))) throw new SessionRecoveryError(`invalid ${key} at ${entry.id}`);
71
+ }
72
+ const path = ancestors(entry, entries);
73
+ if (entry.type === "compaction" && entry.firstKeptEntryId !== entry.id && !path.has(String(entry.firstKeptEntryId))) throw new SessionRecoveryError(`invalid compaction retention at ${entry.id}`);
74
+ if (entry.type === "context_edit" && !path.has(String(entry.targetId))) throw new SessionRecoveryError(`invalid context edit target at ${entry.id}`);
75
+ }
76
+
77
+ function sessionRows(source: string): Entry[] {
78
+ let rows: Entry[];
79
+ try { rows = source.trimEnd().split("\n").map((line) => object(JSON.parse(line))); }
80
+ catch (error) { throw new SessionRecoveryError(`malformed JSONL (${error instanceof Error ? error.message : "parse failure"})`); }
81
+ const header = rows[0];
82
+ if (header?.type !== "session" || header.version !== 3 || typeof header.id !== "string" || typeof header.cwd !== "string") throw new SessionRecoveryError("unsupported or corrupt session header; version 3 required");
83
+ return rows;
84
+ }
85
+ function indexedEntries(rows: Entry[]): Map<string, Entry> {
86
+ const entries = new Map<string, Entry>();
87
+ for (const entry of rows.slice(1)) {
88
+ if (!ENTRY_TYPES.has(String(entry.type)) || typeof entry.id !== "string" || entries.has(entry.id) || !(entry.parentId === null || typeof entry.parentId === "string")) throw new SessionRecoveryError("unsupported or malformed entry");
89
+ entries.set(entry.id, entry);
90
+ }
91
+ return entries;
92
+ }
93
+
94
+ /** Only declaration-bearing system payloads change; graph and conversation stay intact. */
95
+ export function sanitizeSession(source: string): string {
96
+ const rows = sessionRows(source);
97
+ const entries = indexedEntries(rows);
98
+ for (const entry of entries.values()) {
99
+ validateReferences(entry, entries);
100
+ if (entry.type === "message") {
101
+ const message = object(entry.message);
102
+ if (!ROLES.has(String(message.role))) throw new SessionRecoveryError("unsupported message role");
103
+ if (message.role === "system") entry.message = sanitizeSystem(message);
104
+ }
105
+ if (entry.type === "compaction" && entry.systemMessage !== undefined) entry.systemMessage = sanitizeSystem(entry.systemMessage);
106
+ if (entry.type === "context_edit") {
107
+ const target = entries.get(String(entry.targetId));
108
+ if (target?.type === "message" && object(target.message).role === "system") throw new SessionRecoveryError("unsupported context edit of system payload; history retained");
109
+ }
110
+ }
111
+ return `${rows.map((entry) => JSON.stringify(entry)).join("\n")}\n`;
112
+ }
113
+
114
+ function atomicWrite(path: string, contents: string): void {
115
+ const temporary = `${path}.rewrite`;
116
+ if (existsSync(temporary) && (!lstatSync(temporary).isFile() || lstatSync(temporary).isSymbolicLink())) throw new SessionRecoveryError("invalid owned rewrite file");
117
+ const fd = openSync(temporary, "w", 0o600);
118
+ try { writeFileSync(fd, contents, "utf8"); fsyncSync(fd); } finally { closeSync(fd); }
119
+ renameSync(temporary, path);
120
+ }
121
+ function sessionPaths(assignment: Pick<AssignedSession, "taskDir" | "assignmentId">) {
122
+ if (!assignment.assignmentId.trim()) throw new SessionRecoveryError("assignment identity is required");
123
+ const key = createHash("sha256").update(assignment.assignmentId).digest("hex");
124
+ const dir = join(resolve(assignment.taskDir), "sessions", key);
125
+ return { dir, file: join(dir, "conversation.jsonl"), state: join(dir, "state.json"), lock: join(dir, "lock") };
126
+ }
127
+ /** Explicit deterministic path; never Pi's interactive session lookup. */
128
+ export function assignedSessionFile(assignment: Pick<AssignedSession, "taskDir" | "assignmentId">): string {
129
+ return sessionPaths(assignment).file;
130
+ }
131
+ function readState(path: string): AssignedSessionState {
132
+ try {
133
+ if (lstatSync(path).isSymbolicLink() || !lstatSync(path).isFile()) throw new Error("invalid metadata file");
134
+ const state = object(JSON.parse(readFileSync(path, "utf8")));
135
+ if (state.version !== 1 || typeof state.assignmentId !== "string" || !state.assignmentId.trim() || typeof state.sessionFile !== "string" || !Number.isSafeInteger(state.revision) || Number(state.revision) < 1 || !Number.isSafeInteger(state.consumedDiscovery) || Number(state.consumedDiscovery) < 0 || !Array.isArray(state.evidence) || !state.evidence.every(value => typeof value === "string") || !Array.isArray(state.completedWork) || !state.completedWork.every(value => typeof value === "string") || !Array.isArray(state.needs) || (state.terminal !== undefined && typeof state.terminal !== "boolean")) throw new Error("invalid metadata");
136
+ return state as unknown as AssignedSessionState;
137
+ } catch { throw new SessionRecoveryError("missing or corrupt state.json; restore task-owned metadata, do not start fresh"); }
138
+ }
139
+
140
+ type SessionPaths = ReturnType<typeof sessionPaths>;
141
+ function ownerRecord(path: string): { token: string; pid: number; host: string } {
142
+ try {
143
+ const owner = object(JSON.parse(readFileSync(join(path, "owner.json"), "utf8")));
144
+ if (typeof owner.token !== "string" || !owner.token || !Number.isSafeInteger(owner.pid) || Number(owner.pid) <= 0 || owner.host !== hostname()) throw new Error("ambiguous owner");
145
+ return owner as { token: string; pid: number; host: string };
146
+ } catch { throw new SessionRecoveryError("locked conversation has missing/corrupt/foreign owner metadata; explicit repair required"); }
147
+ }
148
+ function ownerDead(pid: number): boolean {
149
+ try { process.kill(pid, 0); return false; }
150
+ catch (error) { return (error as NodeJS.ErrnoException).code === "ESRCH"; }
151
+ }
152
+ /** All lock mutations share a guard, including release, so stale reclamation cannot delete a successor. */
153
+ function guarded<T>(paths: SessionPaths, action: () => T): T {
154
+ const guard = `${paths.lock}.guard`;
155
+ try { mkdirSync(guard); }
156
+ catch { throw new SessionRecoveryError("conversation lock recovery is busy or interrupted; retry or explicitly repair its guard"); }
157
+ try { return action(); } finally { rmSync(guard, { recursive: true }); }
158
+ }
159
+ function sessionLock(paths: SessionPaths) {
160
+ const token = randomUUID();
161
+ guarded(paths, () => {
162
+ if (existsSync(paths.lock)) {
163
+ if (!lstatSync(paths.lock).isDirectory() || lstatSync(paths.lock).isSymbolicLink()) throw new SessionRecoveryError("invalid conversation lock");
164
+ const owner = ownerRecord(paths.lock);
165
+ if (!ownerDead(owner.pid)) throw new SessionRecoveryError("conversation is locked by a live or unverifiable owner");
166
+ rmSync(paths.lock, { recursive: true });
167
+ }
168
+ mkdirSync(paths.lock);
169
+ writeFileSync(join(paths.lock, "owner.json"), JSON.stringify({ token, pid: process.pid, host: hostname() }), { mode: 0o600 });
170
+ });
171
+ let released = false;
172
+ return {
173
+ active: () => !released,
174
+ release: () => {
175
+ if (released) return;
176
+ guarded(paths, () => {
177
+ if (ownerRecord(paths.lock).token !== token) throw new SessionRecoveryError("conversation lock ownership changed");
178
+ rmSync(paths.lock, { recursive: true });
179
+ released = true;
180
+ });
181
+ },
182
+ };
183
+ }
184
+ function initialState(paths: SessionPaths, assignment: AssignedSession, cwd: string): AssignedSessionState {
185
+ if ([paths.file, `${paths.file}.rewrite`, `${paths.state}.rewrite`].some(existsSync)) throw new SessionRecoveryError("conversation or interrupted creation exists without metadata; explicit repair required");
186
+ const state: AssignedSessionState = { version: 1, assignmentId: assignment.assignmentId, revision: assignment.revision, sessionFile: paths.file, evidence: [], completedWork: [], needs: [], consumedDiscovery: 0 };
187
+ // Metadata first: an interrupted creation must not silently become a fresh session.
188
+ atomicWrite(paths.state, JSON.stringify(state));
189
+ atomicWrite(paths.file, `${JSON.stringify({ type: "session", version: 3, id: randomUUID(), timestamp: new Date().toISOString(), cwd: resolve(cwd) })}\n`);
190
+ return state;
191
+ }
192
+ function restoredState(paths: SessionPaths, assignment: AssignedSession, cwd: string, fresh: boolean): AssignedSessionState {
193
+ if (fresh) return initialState(paths, assignment, cwd);
194
+ const state = readState(paths.state);
195
+ if (state.assignmentId !== assignment.assignmentId || state.sessionFile !== paths.file || state.revision > assignment.revision) throw new SessionRecoveryError("identity/path mismatch or superseded revision");
196
+ if (state.terminal) { cleanupBodies(paths); throw new SessionRecoveryError("assignment is terminal; cleanup retried"); }
197
+ if (!existsSync(paths.file)) throw new SessionRecoveryError("conversation is missing; restore it, do not start fresh");
198
+ if (lstatSync(paths.file).isSymbolicLink() || !lstatSync(paths.file).isFile()) throw new SessionRecoveryError("invalid owned conversation file");
199
+ const source = readFileSync(paths.file, "utf8");
200
+ if (sessionRows(source)[0]!.cwd !== resolve(cwd)) throw new SessionRecoveryError("conversation project scope changed; restore its original worktree");
201
+ atomicWrite(paths.file, sanitizeSession(source));
202
+ return state;
203
+ }
204
+ function revisedState(state: AssignedSessionState, assignment: AssignedSession): AssignedSessionState {
205
+ return { ...state, revision: assignment.revision, evidence: assignment.evidence ?? state.evidence, completedWork: assignment.completedWork ?? state.completedWork, needs: assignment.needs ?? state.needs, consumedDiscovery: Math.max(state.consumedDiscovery, assignment.consumedDiscovery ?? 0) };
206
+ }
207
+
208
+ /** Lock spans sanitation and subprocess lifetime; only demonstrated owner death permits reclamation. */
209
+ export function openAssignedSession(assignment: AssignedSession, cwd: string) {
210
+ if (!Number.isSafeInteger(assignment.revision) || assignment.revision < 1) throw new SessionRecoveryError("revision must be a positive integer");
211
+ if (assignment.consumedDiscovery !== undefined && (!Number.isSafeInteger(assignment.consumedDiscovery) || assignment.consumedDiscovery < 0)) throw new SessionRecoveryError("consumed discovery must be a nonnegative integer");
212
+ const paths = sessionPaths(assignment);
213
+ const sessions = join(paths.dir, "..");
214
+ mkdirSync(sessions, { recursive: true, mode: 0o700 });
215
+ if (lstatSync(sessions).isSymbolicLink() || !lstatSync(sessions).isDirectory()) throw new SessionRecoveryError("invalid owned sessions directory");
216
+ let fresh = false;
217
+ try { mkdirSync(paths.dir, { mode: 0o700 }); fresh = true; }
218
+ catch (error) { if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error; }
219
+ if (lstatSync(paths.dir).isSymbolicLink() || !lstatSync(paths.dir).isDirectory()) throw new SessionRecoveryError("invalid session directory");
220
+ const lock = sessionLock(paths);
221
+ try {
222
+ const state = revisedState(restoredState(paths, assignment, cwd, fresh), assignment);
223
+ atomicWrite(paths.state, JSON.stringify(state));
224
+ const save = () => {
225
+ if (!lock.active()) throw new SessionRecoveryError("cannot save metadata after releasing the conversation lock");
226
+ atomicWrite(paths.state, JSON.stringify(state));
227
+ };
228
+ return { file: paths.file, state, release: lock.release, save };
229
+ } catch (error) { lock.release(); throw error; }
230
+ }
231
+ function cleanupBodies(paths: ReturnType<typeof sessionPaths>): void {
232
+ for (const path of [paths.file, `${paths.file}.rewrite`, `${paths.state}.rewrite`]) rmSync(path, { force: true });
233
+ }
234
+ /** Terminal cleanup does not parse or recreate conversation bodies. Metadata survives every retry. */
235
+ export function cleanupAssignedSession(assignment: AssignedSession, _cwd?: string): void {
236
+ const paths = sessionPaths(assignment);
237
+ if (lstatSync(paths.dir).isSymbolicLink() || !lstatSync(paths.dir).isDirectory()) throw new SessionRecoveryError("invalid owned session directory");
238
+ const lock = sessionLock(paths);
239
+ try {
240
+ const state = readState(paths.state);
241
+ if (state.assignmentId !== assignment.assignmentId) throw new SessionRecoveryError("cleanup assignment identity mismatch");
242
+ state.terminal = true;
243
+ atomicWrite(paths.state, JSON.stringify(state));
244
+ cleanupBodies(paths);
245
+ } finally { lock.release(); }
246
+ }
247
+ /** Host calls only after persisting terminal task state. No cancellation or crash cleanup. */
248
+ export function cleanupTaskAssignedSessions(taskDir: string): void {
249
+ const sessions = join(resolve(taskDir), "sessions");
250
+ if (!existsSync(sessions)) return;
251
+ if (lstatSync(sessions).isSymbolicLink() || !lstatSync(sessions).isDirectory()) throw new SessionRecoveryError("invalid owned sessions directory");
252
+ const issues: string[] = [];
253
+ for (const entry of readdirSync(sessions, { withFileTypes: true })) {
254
+ try {
255
+ if (!entry.isDirectory() || !/^[a-f0-9]{64}$/.test(entry.name)) throw new SessionRecoveryError(`unexpected session entry ${entry.name}`);
256
+ const state = readState(join(sessions, entry.name, "state.json"));
257
+ const assignment = { taskDir, assignmentId: state.assignmentId, revision: state.revision };
258
+ if (sessionPaths(assignment).dir !== join(sessions, entry.name)) throw new SessionRecoveryError("session directory identity mismatch");
259
+ cleanupAssignedSession(assignment);
260
+ } catch (error) { issues.push(error instanceof Error ? error.message : String(error)); }
261
+ }
262
+ if (issues.length) throw new SessionRecoveryError(`terminal cleanup incomplete: ${issues.join("; ")}`);
263
+ }
@@ -0,0 +1,128 @@
1
+ import { createHash, randomUUID } from "node:crypto";
2
+ import { closeSync, fsyncSync, mkdirSync, openSync, readFileSync, renameSync, unlinkSync, writeFileSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { setTimeout } from "node:timers/promises";
5
+ import { assignmentCallDiscovery, type AssignmentToolCall } from "./assignment-policy.ts";
6
+
7
+ export interface DiscoveryDecision { decisionId: string; reason: string; limit: number }
8
+ export interface AssignmentDiscoveryState {
9
+ version: 1;
10
+ assignmentId: string;
11
+ revision: number;
12
+ consumed: number;
13
+ limit: number;
14
+ effectiveLimit: number;
15
+ decisions: DiscoveryDecision[];
16
+ }
17
+
18
+ export class AssignmentDiscoveryError extends Error {
19
+ constructor(message: string) { super(`Assignment discovery: ${message}`); this.name = "AssignmentDiscoveryError"; }
20
+ }
21
+
22
+ function integer(value: unknown, minimum: number): value is number {
23
+ return Number.isSafeInteger(value) && Number(value) >= minimum;
24
+ }
25
+ function paths(taskDir: string, id: string) {
26
+ if (!id.trim()) throw new AssignmentDiscoveryError("assignment identity is required");
27
+ const dir = join(taskDir, "assignment-discovery");
28
+ mkdirSync(dir, { recursive: true });
29
+ const file = join(dir, `${createHash("sha256").update(id).digest("hex")}.json`);
30
+ return { file, lock: `${file}.lock` };
31
+ }
32
+ function load(file: string, id: string): AssignmentDiscoveryState | undefined {
33
+ try {
34
+ const state: AssignmentDiscoveryState = JSON.parse(readFileSync(file, "utf8"));
35
+ if (state.version !== 1 || state.assignmentId !== id || !integer(state.revision, 1) || !integer(state.consumed, 0) || !integer(state.limit, 0) || !integer(state.effectiveLimit, 0) || state.effectiveLimit > state.limit || state.consumed > state.limit || !Array.isArray(state.decisions)) throw new Error("invalid ledger schema");
36
+ if (state.decisions.some((d) => !d || typeof d.decisionId !== "string" || !d.decisionId.trim() || typeof d.reason !== "string" || !d.reason.trim() || !integer(d.limit, 0))) throw new Error("invalid decision schema");
37
+ if (new Set(state.decisions.map((d) => d.decisionId)).size !== state.decisions.length || (state.limit > 2 && !state.decisions.some((d) => d.limit === state.limit))) throw new Error("allowance lacks a unique persisted master decision");
38
+ return state;
39
+ } catch (error) {
40
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return undefined;
41
+ throw new AssignmentDiscoveryError(`cannot recover ledger ${file}: ${error instanceof Error ? error.message : String(error)}; restore it, do not reset consumption`);
42
+ }
43
+ }
44
+ function save(file: string, state: AssignmentDiscoveryState): void {
45
+ const temporary = `${file}.${randomUUID()}.tmp`;
46
+ const fd = openSync(temporary, "wx", 0o600);
47
+ try {
48
+ try { writeFileSync(fd, `${JSON.stringify(state)}\n`); fsyncSync(fd); }
49
+ finally { closeSync(fd); }
50
+ renameSync(temporary, file);
51
+ } finally { try { unlinkSync(temporary); } catch (error) { if ((error as NodeJS.ErrnoException).code !== "ENOENT") throw error; } }
52
+ }
53
+ async function acquire(lock: string): Promise<number> {
54
+ for (let attempt = 0; attempt < 200; attempt++) {
55
+ try {
56
+ const fd = openSync(lock, "wx", 0o600);
57
+ try { writeFileSync(fd, JSON.stringify({ pid: process.pid })); }
58
+ catch (error) { closeSync(fd); unlinkSync(lock); throw error; }
59
+ return fd;
60
+ }
61
+ catch (error) {
62
+ if ((error as NodeJS.ErrnoException).code !== "EEXIST") throw error;
63
+ await setTimeout(10);
64
+ }
65
+ }
66
+ throw new AssignmentDiscoveryError(`ledger busy at ${lock}; retry, or confirm the owner stopped before explicit lock recovery`);
67
+ }
68
+ async function update(taskDir: string, id: string, revision: number, change: (state: AssignmentDiscoveryState | undefined) => AssignmentDiscoveryState): Promise<AssignmentDiscoveryState> {
69
+ if (!integer(revision, 1)) throw new AssignmentDiscoveryError("revision must be a positive integer");
70
+ const { file, lock } = paths(taskDir, id);
71
+ const fd = await acquire(lock);
72
+ try {
73
+ const state = load(file, id);
74
+ if (state && revision < state.revision) throw new AssignmentDiscoveryError(`stale revision ${revision}; current revision is ${state.revision}`);
75
+ const next = change(state);
76
+ save(file, next);
77
+ return structuredClone(next);
78
+ } finally { closeSync(fd); unlinkSync(lock); }
79
+ }
80
+
81
+ /** Revision advancement never replenishes allowance, even after process recovery. */
82
+ export function prepareAssignmentDiscovery(taskDir: string, id: string, revision: number, requestedLimit = 2): Promise<AssignmentDiscoveryState> {
83
+ if (!integer(requestedLimit, 0)) throw new AssignmentDiscoveryError("limit must be a non-negative integer");
84
+ return update(taskDir, id, revision, (previous) => {
85
+ const state = previous ?? { version: 1 as const, assignmentId: id, revision, consumed: 0, limit: Math.min(requestedLimit, 2), effectiveLimit: Math.min(requestedLimit, 2), decisions: [] };
86
+ if (requestedLimit > state.limit) throw new AssignmentDiscoveryError(`requested limit ${requestedLimit} exceeds approved ${state.limit}; record an explicit master allowance decision first`);
87
+ return { ...state, revision, effectiveLimit: requestedLimit };
88
+ });
89
+ }
90
+ function current(state: AssignmentDiscoveryState | undefined, revision: number): AssignmentDiscoveryState {
91
+ if (!state) throw new AssignmentDiscoveryError("ledger missing; prepare the persisted assignment before dispatch");
92
+ if (state.revision !== revision) throw new AssignmentDiscoveryError(`revision ${revision} is not prepared; current revision is ${state.revision}`);
93
+ return state;
94
+ }
95
+
96
+ /** Host reads under the same lock; missing/corrupt state is not a fresh allowance. */
97
+ export function readAssignmentDiscovery(taskDir: string, id: string, revision: number): Promise<AssignmentDiscoveryState> {
98
+ return update(taskDir, id, revision, (state) => current(state, revision));
99
+ }
100
+
101
+ /** Host/master only: never expose this operation as a worker tool or infer approval from a brief. */
102
+ export function approveAssignmentDiscovery(taskDir: string, id: string, revision: number, decision: DiscoveryDecision): Promise<AssignmentDiscoveryState> {
103
+ if (!decision.decisionId.trim() || !decision.reason.trim() || !integer(decision.limit, 0)) throw new AssignmentDiscoveryError("an explicit master decision id, reason and integer limit are required");
104
+ return update(taskDir, id, revision, (previous) => {
105
+ const state = current(previous, revision);
106
+ const old = state.decisions.find((entry) => entry.decisionId === decision.decisionId);
107
+ if (old && (old.limit !== decision.limit || old.reason !== decision.reason)) throw new AssignmentDiscoveryError("decision id already records a different allowance");
108
+ if (old) return state;
109
+ if (decision.limit <= state.limit) throw new AssignmentDiscoveryError("allowance decision must increase the existing total limit");
110
+ return { ...state, limit: decision.limit, decisions: [...state.decisions, { decisionId: decision.decisionId, reason: decision.reason, limit: decision.limit }] };
111
+ });
112
+ }
113
+
114
+ /** Charge before dispatch; failed attempts do not refund discovery. */
115
+ export function consumeAssignmentDiscovery(taskDir: string, id: string, revision: number, count = 1): Promise<AssignmentDiscoveryState> {
116
+ if (!integer(count, 0)) throw new AssignmentDiscoveryError("lookup count must be a non-negative integer");
117
+ return update(taskDir, id, revision, (previous) => {
118
+ const state = current(previous, revision);
119
+ if (count === 0) return state;
120
+ if (!Number.isSafeInteger(state.consumed + count) || state.consumed + count > state.effectiveLimit) throw new AssignmentDiscoveryError(`allowance exhausted (${state.consumed}/${state.effectiveLimit}); request a master discovery expansion`);
121
+ return { ...state, consumed: state.consumed + count };
122
+ });
123
+ }
124
+
125
+ /** Future verified runtime boundary: validate the whole batch and atomically charge its leaves. */
126
+ export function authorizeAssignmentCalls(taskDir: string, id: string, revision: number, selected: readonly string[], calls: readonly AssignmentToolCall[]): Promise<AssignmentDiscoveryState> {
127
+ return consumeAssignmentDiscovery(taskDir, id, revision, assignmentCallDiscovery(selected, calls));
128
+ }
@@ -0,0 +1,46 @@
1
+ import type { WorkerAssignment } from "./assignment.ts";
2
+
3
+ export interface AssignmentToolInventory {
4
+ /** Full combined role, coordination, knowledge, ask and configured MCP grants. */
5
+ granted: readonly string[];
6
+ /** Known names may include configured tools which are currently disconnected. */
7
+ known: readonly string[];
8
+ available: readonly string[];
9
+ }
10
+
11
+ export class AssignmentPolicyError extends Error {
12
+ constructor(message: string) { super(`Assignment tool policy: ${message}`); this.name = "AssignmentPolicyError"; }
13
+ }
14
+
15
+ function names(values: readonly string[]): string[] { return [...new Set(values)].sort(); }
16
+
17
+ /** Replacement, never an additive loadout; codemode confers no implicit nested grants. */
18
+ export function selectAssignmentTools(assignment: Pick<WorkerAssignment, "tools">, inventory: AssignmentToolInventory): string[] {
19
+ const selected = names(assignment.tools.map((tool) => tool.name));
20
+ for (const name of selected) {
21
+ if (!inventory.known.includes(name)) throw new AssignmentPolicyError(`unknown tool ${name}; request a valid exact tool name`);
22
+ if (!inventory.granted.includes(name)) throw new AssignmentPolicyError(`ungranted tool ${name}; request a master tool expansion and existing role/configuration grant`);
23
+ if (!inventory.available.includes(name)) throw new AssignmentPolicyError(`unavailable tool ${name}; reconnect its provider before dispatch`);
24
+ }
25
+ return selected;
26
+ }
27
+
28
+ export interface AssignmentToolCall {
29
+ name: string;
30
+ /** Host-decoded calls, not untrusted model classifications or arbitrary source code. */
31
+ children?: readonly AssignmentToolCall[];
32
+ purpose?: "discovery" | "assigned-read" | "assigned-verification" | "work";
33
+ }
34
+
35
+ const DISCOVERY_TOOLS = new Set(["read", "bash", "grep", "find", "ls", "find_relevant_files", "tool_search", "search_knowledge"]);
36
+
37
+ /** Validate every decoded direct/discovered/nested leaf before any batch dispatch. */
38
+ export function assignmentCallDiscovery(selected: readonly string[], calls: readonly AssignmentToolCall[]): number {
39
+ let count = 0;
40
+ for (const call of calls) {
41
+ if (!selected.includes(call.name)) throw new AssignmentPolicyError(`unselected call ${call.name}; request a tool expansion before execution`);
42
+ if (call.purpose !== "assigned-read" && call.purpose !== "assigned-verification" && call.purpose !== "work" && (call.purpose === "discovery" || DISCOVERY_TOOLS.has(call.name))) count++;
43
+ count += assignmentCallDiscovery(selected, call.children ?? []);
44
+ }
45
+ return count;
46
+ }
@@ -0,0 +1,175 @@
1
+ import { lstat, realpath, stat } from "node:fs/promises";
2
+ import { dirname, isAbsolute, relative, resolve, sep } from "node:path";
3
+
4
+ export interface AssignmentFile {
5
+ path: string;
6
+ access: "reference" | "edit" | "create";
7
+ purpose: string;
8
+ }
9
+
10
+ export interface AssignmentExpansionRequest {
11
+ kind: "files" | "tools" | "discovery" | "decision";
12
+ reason: string;
13
+ requested: string[];
14
+ }
15
+
16
+ export interface WorkerAssignment {
17
+ id: string;
18
+ revision: number;
19
+ objective: string;
20
+ actions: { step: number; instruction: string }[];
21
+ files: AssignmentFile[];
22
+ contracts: string[];
23
+ constraints: string[];
24
+ exclusions: string[];
25
+ tools: { name: string; purpose: string }[];
26
+ verification: string[];
27
+ evidence: string[];
28
+ completedWork: string[];
29
+ needs: AssignmentExpansionRequest[];
30
+ /** Total allowance, not a fresh allowance on retry or revision. */
31
+ discoveryLimit?: number;
32
+ }
33
+
34
+ export class AssignmentValidationError extends Error {
35
+ constructor(message: string) {
36
+ super(`Invalid worker assignment: ${message}`);
37
+ this.name = "AssignmentValidationError";
38
+ }
39
+ }
40
+
41
+ function requireValue(condition: unknown, message: string): asserts condition {
42
+ if (!condition) throw new AssignmentValidationError(message);
43
+ }
44
+
45
+ function object(value: unknown, fields: string[], label: string): Record<string, unknown> {
46
+ requireValue(value !== null && typeof value === "object" && !Array.isArray(value), `${label} must be an object`);
47
+ const record = value as Record<string, unknown>;
48
+ for (const key of Object.keys(record)) requireValue(fields.includes(key), `${label}.${key} is unknown; remove it`);
49
+ return record;
50
+ }
51
+
52
+ function text(value: unknown, label: string): asserts value is string {
53
+ requireValue(typeof value === "string" && value.trim().length > 0, `${label} must be non-empty text`);
54
+ }
55
+
56
+ function list(value: unknown, label: string, required = false): unknown[] {
57
+ requireValue(Array.isArray(value), `${label} must be an array`);
58
+ requireValue(!required || value.length > 0, `${label} must contain at least one entry`);
59
+ return value;
60
+ }
61
+
62
+ function texts(value: unknown, label: string, required = false): void {
63
+ list(value, label, required).forEach((entry, i) => text(entry, `${label}[${i}]`));
64
+ }
65
+
66
+ function validateShape(input: unknown): WorkerAssignment {
67
+ const a = object(input, ["id", "revision", "objective", "actions", "files", "contracts", "constraints", "exclusions", "tools", "verification", "evidence", "completedWork", "needs", "discoveryLimit"], "assignment");
68
+ text(a.id, "id");
69
+ text(a.objective, "objective");
70
+ requireValue(Number.isSafeInteger(a.revision) && Number(a.revision) > 0, "revision must be a positive integer");
71
+ requireValue(a.discoveryLimit === undefined || (Number.isSafeInteger(a.discoveryLimit) && Number(a.discoveryLimit) >= 0), "discoveryLimit must be a non-negative integer");
72
+ validateActions(a.actions);
73
+ validateFiles(a.files);
74
+ validateTools(a.tools);
75
+ for (const key of ["contracts", "constraints", "exclusions", "verification", "evidence", "completedWork"]) texts(a[key], key, key === "verification");
76
+ validateNeeds(a.needs);
77
+ return structuredClone(input) as WorkerAssignment;
78
+ }
79
+
80
+ function validateActions(value: unknown): void {
81
+ list(value, "actions", true).forEach((value, i) => {
82
+ const action = object(value, ["step", "instruction"], `actions[${i}]`);
83
+ requireValue(action.step === i + 1, `actions[${i}].step must be ${i + 1}`);
84
+ text(action.instruction, `actions[${i}].instruction`);
85
+ });
86
+ }
87
+
88
+ function validateFiles(value: unknown): void {
89
+ list(value, "files", true).forEach((entry, i) => {
90
+ const file = object(entry, ["path", "access", "purpose"], `files[${i}]`);
91
+ text(file.path, `files[${i}].path`);
92
+ text(file.purpose, `files[${i}].purpose`);
93
+ requireValue(["reference", "edit", "create"].includes(String(file.access)), `files[${i}].access must be reference, edit or create`);
94
+ requireValue(!/[\0*?\[\]{}]/.test(file.path), `files[${i}].path must be an exact path, not a pattern`);
95
+ });
96
+ }
97
+
98
+ function validateTools(value: unknown): void {
99
+ list(value, "tools").forEach((entry, i) => {
100
+ const tool = object(entry, ["name", "purpose"], `tools[${i}]`);
101
+ text(tool.name, `tools[${i}].name`);
102
+ text(tool.purpose, `tools[${i}].purpose`);
103
+ });
104
+ }
105
+
106
+ function validateNeeds(value: unknown): void {
107
+ list(value, "needs").forEach((entry, i) => {
108
+ const need = object(entry, ["kind", "reason", "requested"], `needs[${i}]`);
109
+ requireValue(["files", "tools", "discovery", "decision"].includes(String(need.kind)), `needs[${i}].kind must be files, tools, discovery or decision`);
110
+ text(need.reason, `needs[${i}].reason`);
111
+ texts(need.requested, `needs[${i}].requested`, true);
112
+ });
113
+ }
114
+
115
+ function inside(root: string, path: string): boolean {
116
+ const rel = relative(root, path);
117
+ return rel === "" || (!isAbsolute(rel) && rel !== ".." && !rel.startsWith(`..${sep}`));
118
+ }
119
+
120
+ /** Resolve absent create paths through their nearest existing ancestor, including symlinks. */
121
+ async function resolvedPath(path: string, mayCreate: boolean): Promise<string> {
122
+ try {
123
+ await lstat(path);
124
+ return await realpath(path);
125
+ } catch (error) {
126
+ if ((error as NodeJS.ErrnoException).code !== "ENOENT" || !mayCreate) throw error;
127
+ return resolveCreatePath(path);
128
+ }
129
+ }
130
+
131
+ async function resolveCreatePath(path: string): Promise<string> {
132
+ // A dangling symlink must not be mistaken for an absent create target.
133
+ const entry = await lstat(path).catch((cause: NodeJS.ErrnoException) => {
134
+ if (cause.code !== "ENOENT") throw cause;
135
+ return undefined;
136
+ });
137
+ if (entry) throw new Error("dangling symlink cannot be resolved");
138
+ const parent = dirname(path);
139
+ if (parent === path) throw new Error("create target has no existing ancestor");
140
+ const resolved = await resolvedPath(parent, true);
141
+ const parentEntry = await stat(resolved).catch((cause: NodeJS.ErrnoException) => {
142
+ if (cause.code !== "ENOENT") throw cause;
143
+ return undefined;
144
+ });
145
+ requireValue(!parentEntry || parentEntry.isDirectory(), `create parent ${parent} must be a directory`);
146
+ return resolve(resolved, relative(parent, path));
147
+ }
148
+
149
+ async function validateFile(file: AssignmentFile, root: string, seen: Set<string>): Promise<void> {
150
+ const path = resolve(root, file.path);
151
+ requireValue(inside(root, path), `${file.path} is outside project scope ${root}`);
152
+ try {
153
+ const target = await resolvedPath(path, file.access === "create");
154
+ requireValue(inside(root, target), `${file.path} resolves outside project scope ${root}`);
155
+ const entry = await stat(target).catch((error: NodeJS.ErrnoException) => {
156
+ if (error.code !== "ENOENT" || file.access !== "create") throw error;
157
+ return undefined;
158
+ });
159
+ requireValue(!entry || entry.isFile(), `${file.path} must identify a file, not a directory`);
160
+ requireValue(!seen.has(target), `${file.path} duplicates another assigned path`);
161
+ seen.add(target);
162
+ } catch (error) {
163
+ if (error instanceof AssignmentValidationError) throw error;
164
+ throw new AssignmentValidationError(`${file.access} path ${file.path}: ${error instanceof Error ? error.message : String(error)}; correct the path or request expansion`);
165
+ }
166
+ }
167
+
168
+ /** Validate before dispatch; failure must never fall back to an unrestricted run. */
169
+ export async function validateAssignment(input: unknown, projectRoot: string): Promise<WorkerAssignment> {
170
+ const assignment = validateShape(input);
171
+ const root = await realpath(projectRoot);
172
+ const seen = new Set<string>();
173
+ for (const file of assignment.files) await validateFile(file, root, seen);
174
+ return { ...assignment, discoveryLimit: assignment.discoveryLimit ?? 2 };
175
+ }