code60-transmission-server 0.1.0-staging.13 → 0.1.0-staging.18

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 (104) hide show
  1. package/INTENT.md +47 -0
  2. package/README.md +54 -340
  3. package/dist/src/acp.js +115 -0
  4. package/dist/src/contract.js +103 -0
  5. package/dist/src/engine.js +506 -0
  6. package/dist/src/main.js +72 -25
  7. package/dist/src/repository.js +94 -0
  8. package/dist/src/service.js +184 -0
  9. package/package.json +16 -35
  10. package/reference/openapi.json +728 -0
  11. package/README.engine.md +0 -463
  12. package/dist/src/broker/filesystem.js +0 -385
  13. package/dist/src/broker/index.js +0 -777
  14. package/dist/src/broker/native/README.md +0 -207
  15. package/dist/src/broker/native/build.js +0 -46
  16. package/dist/src/broker/native/command-helper.c +0 -93
  17. package/dist/src/broker/native/fs-helper.c +0 -529
  18. package/dist/src/broker/native/git-helper.c +0 -205
  19. package/dist/src/broker/policy.js +0 -149
  20. package/dist/src/broker/startup-lock.js +0 -14
  21. package/dist/src/broker/types.js +0 -11
  22. package/dist/src/cli/configure.js +0 -208
  23. package/dist/src/cli/daemon.js +0 -369
  24. package/dist/src/cli/helpers.js +0 -112
  25. package/dist/src/cli/main.js +0 -189
  26. package/dist/src/cli/runtime-build.js +0 -38
  27. package/dist/src/config/coding-policy.js +0 -4
  28. package/dist/src/config/deployment.js +0 -183
  29. package/dist/src/config/documents.js +0 -29
  30. package/dist/src/config/profile-validation.js +0 -129
  31. package/dist/src/config/schema-graph.js +0 -237
  32. package/dist/src/config/schema-loader.js +0 -185
  33. package/dist/src/config/validation-pool.js +0 -105
  34. package/dist/src/config/validation-protocol.js +0 -1
  35. package/dist/src/config/validation-worker.js +0 -106
  36. package/dist/src/config/workflow-language.js +0 -9
  37. package/dist/src/config/workflow-schema.json +0 -545
  38. package/dist/src/config/workflow-types.js +0 -1
  39. package/dist/src/config/workflow-validation.js +0 -95
  40. package/dist/src/engine/budgets.js +0 -50
  41. package/dist/src/engine/clocks.js +0 -27
  42. package/dist/src/engine/commands.js +0 -477
  43. package/dist/src/engine/contracts.js +0 -11
  44. package/dist/src/engine/drain-state.js +0 -31
  45. package/dist/src/engine/effective-permissions.js +0 -120
  46. package/dist/src/engine/instruction-pins.js +0 -205
  47. package/dist/src/engine/retries.js +0 -50
  48. package/dist/src/engine/state.js +0 -1
  49. package/dist/src/engine/timing.js +0 -23
  50. package/dist/src/engine/tool-observations.js +0 -87
  51. package/dist/src/engine/workflow-engine.js +0 -1864
  52. package/dist/src/mcp/catalog.js +0 -71
  53. package/dist/src/mcp/main.js +0 -26
  54. package/dist/src/mcp/server.js +0 -177
  55. package/dist/src/runtime/codex-app-server.js +0 -91
  56. package/dist/src/runtime/codex-executable.js +0 -50
  57. package/dist/src/runtime/containment.js +0 -82
  58. package/dist/src/runtime/engine-driver.js +0 -221
  59. package/dist/src/runtime/json-line-writer.js +0 -192
  60. package/dist/src/runtime/pinned-instruction-sources.js +0 -24
  61. package/dist/src/runtime/protocol-client.js +0 -264
  62. package/dist/src/runtime/protocol-pool.js +0 -183
  63. package/dist/src/runtime/protocol-projection.js +0 -393
  64. package/dist/src/runtime/protocol-types.js +0 -1
  65. package/dist/src/runtime/protocol-worker.js +0 -18
  66. package/dist/src/runtime/provider-bridge.js +0 -290
  67. package/dist/src/runtime/provider-credentials.js +0 -41
  68. package/dist/src/runtime/provider-transport.js +0 -406
  69. package/dist/src/runtime/runtime-broker.js +0 -213
  70. package/dist/src/runtime/workspace-instructions.js +0 -120
  71. package/dist/src/runtime/workspace-view.js +0 -74
  72. package/dist/src/server/api-contract.json +0 -11637
  73. package/dist/src/server/api-types.js +0 -1
  74. package/dist/src/server/application.js +0 -44
  75. package/dist/src/server/auth.js +0 -67
  76. package/dist/src/server/broker-handlers.js +0 -242
  77. package/dist/src/server/coding.js +0 -281
  78. package/dist/src/server/control-plane.js +0 -50
  79. package/dist/src/server/deployment.js +0 -249
  80. package/dist/src/server/errors.js +0 -22
  81. package/dist/src/server/history-handlers.js +0 -130
  82. package/dist/src/server/http.js +0 -124
  83. package/dist/src/server/paging.js +0 -56
  84. package/dist/src/server/publication.js +0 -119
  85. package/dist/src/server/tool-event-handler.js +0 -77
  86. package/dist/src/server/workspace-handlers.js +0 -34
  87. package/dist/src/storage/coordinator.js +0 -224
  88. package/dist/src/storage/startup-lock.js +0 -71
  89. package/dist/src/storage/store.js +0 -167
  90. package/dist/src/tools/check-worker.js +0 -81
  91. package/dist/src/tools/checks.js +0 -117
  92. package/dist/src/tools/command-check.js +0 -34
  93. package/dist/src/tools/commands.js +0 -312
  94. package/dist/src/tools/developer.js +0 -355
  95. package/dist/src/tools/dns.js +0 -248
  96. package/dist/src/tools/http-contract.js +0 -38
  97. package/dist/src/tools/http.js +0 -358
  98. package/dist/src/tools/index.js +0 -194
  99. package/dist/src/tools/worker-check.js +0 -73
  100. package/dist/src/workspaces/git.js +0 -227
  101. package/dist/src/workspaces/index.js +0 -937
  102. package/dist/src/workspaces/source.js +0 -295
  103. package/examples/deployment.local.json +0 -22
  104. package/scripts/postinstall.mjs +0 -26
@@ -0,0 +1,103 @@
1
+ import { z } from 'zod';
2
+ const text = z.string().trim().min(1).max(65536);
3
+ export const task = z.strictObject({
4
+ name: text,
5
+ instructions: text,
6
+ verify: text,
7
+ checks: z.array(text).max(30).optional(),
8
+ });
9
+ export const start = z.strictObject({
10
+ repository: text,
11
+ tasks: z.array(task).min(1).max(100),
12
+ confirmed: z.literal(true),
13
+ idempotencyKey: z.string().min(1).max(256),
14
+ repairs: z.number().int().min(0).max(30).default(2),
15
+ retries: z.number().int().min(0).max(30).default(2),
16
+ autoApprove: z.boolean().default(true),
17
+ });
18
+ export const runId = z.uuid();
19
+ const id = z.strictObject({ runId });
20
+ export const operations = {
21
+ start_workflow: start,
22
+ get_workflow: id,
23
+ get_workflow_events: id.extend({
24
+ after: z.number().int().nonnegative().default(0),
25
+ }),
26
+ get_workflow_diff: id.extend({
27
+ offset: z.number().int().nonnegative().default(0),
28
+ }),
29
+ answer_workflow_question: id.extend({ questionId: z.uuid(), answer: text }),
30
+ send_workflow_message: id.extend({ message: text }),
31
+ cancel_workflow: id,
32
+ };
33
+ export const descriptions = {
34
+ start_workflow: 'Run the exact workflow confirmed by the user. Design ordered tasks, each with implementation instructions and an independent verification prompt. Show the project, tasks and criteria to the user and obtain confirmation before calling. Reuse the same key on reconnect.',
35
+ get_workflow: 'Read an ordered task snapshot by run ID, including the active task index, decision, accepted results, and event cursor. Pass eventCursor as after to get_workflow_events for subsequent activity.',
36
+ get_workflow_events: 'Read the next page of progress, sessions, native tools and verifier feedback. Use the last sequence number as after.',
37
+ get_workflow_diff: 'Read a page of the accepted patch relative to the initial working tree. Offset is in bytes; content is base64.',
38
+ answer_workflow_question: 'Answer the outstanding decision by ID. For a permission question select an offered option ID.',
39
+ send_workflow_message: 'Deliver new guidance before the current task is accepted.',
40
+ cancel_workflow: 'Stop the workflow and its active agent sessions. Leave working files available for review.',
41
+ };
42
+ export const terminal = (status) => ['completed', 'failed', 'cancelled'].includes(status);
43
+ const status = z.enum(['running', 'completed', 'needs_input', 'failed', 'cancelled']);
44
+ const checkEvidence = z.object({
45
+ command: text,
46
+ passed: z.boolean(),
47
+ evidence: text,
48
+ });
49
+ const verdict = z.object({
50
+ decision: z.enum(['accept', 'reject']),
51
+ reason: z.string(),
52
+ checks: z.array(checkEvidence).optional(),
53
+ });
54
+ const accepted = z.object({
55
+ name: z.string(),
56
+ result: z.string(),
57
+ verdict,
58
+ worker: z.string(),
59
+ verifier: z.string(),
60
+ revision: z.string(),
61
+ });
62
+ const question = z.object({
63
+ id: z.uuid(),
64
+ text: z.string(),
65
+ options: z.array(z.object({ id: z.string(), name: z.string() })).optional(),
66
+ });
67
+ const taskState = z.enum([
68
+ 'pending', 'implementing', 'verifying', 'repairing',
69
+ 'needs_input', 'accepted', 'failed', 'cancelled',
70
+ ]);
71
+ const nonnegativeInteger = z.int().nonnegative();
72
+ export const workflowSnapshot = z.object({
73
+ runId,
74
+ status,
75
+ tasks: z.array(z.object({ index: nonnegativeInteger, name: z.string(), state: taskState })),
76
+ activeTaskIndex: nonnegativeInteger.nullable(),
77
+ eventCursor: nonnegativeInteger,
78
+ task: z.string().optional(),
79
+ phase: z.enum(['worker', 'verifier']).optional(),
80
+ decision: question.optional(),
81
+ reason: z.string().optional(),
82
+ attempts: z.array(z.string()),
83
+ accepted: z.array(accepted),
84
+ result: z.string().optional(),
85
+ verdict: verdict.optional(),
86
+ });
87
+ export const snapshotOperations = new Set([
88
+ 'start_workflow', 'get_workflow', 'answer_workflow_question',
89
+ 'send_workflow_message', 'cancel_workflow',
90
+ ]);
91
+ export const workerReply = z.discriminatedUnion('kind', [
92
+ z.object({ kind: z.literal('result'), summary: text }),
93
+ z.object({ kind: z.literal('question'), question: text }),
94
+ ]);
95
+ export const verifierReply = z.discriminatedUnion('kind', [
96
+ z.object({
97
+ kind: z.literal('verdict'),
98
+ decision: z.enum(['accept', 'reject']),
99
+ reason: text,
100
+ checks: z.array(checkEvidence).optional(),
101
+ }),
102
+ z.object({ kind: z.literal('question'), question: text }),
103
+ ]);
@@ -0,0 +1,506 @@
1
+ import { DatabaseSync } from 'node:sqlite';
2
+ import { randomUUID } from 'node:crypto';
3
+ import { closeSync, mkdirSync, openSync, readSync, realpathSync, renameSync, rmSync, statSync, } from 'node:fs';
4
+ import { join, sep } from 'node:path';
5
+ import { AcpHarness } from './acp.js';
6
+ import { terminal, verifierReply, workerReply, } from './contract.js';
7
+ import { repository, snapshot, writePatch } from './repository.js';
8
+ const diagnostic = (error) => error instanceof Error ? error.message : String(error);
9
+ function taskState(run, index) {
10
+ if (index < run.index)
11
+ return 'accepted';
12
+ if (index > run.index)
13
+ return 'pending';
14
+ switch (run.status) {
15
+ case 'running':
16
+ if (run.phase === 'verifier')
17
+ return 'verifying';
18
+ return run.repairsUsed > 0 ? 'repairing' : 'implementing';
19
+ case 'completed':
20
+ return 'accepted';
21
+ default:
22
+ return run.status;
23
+ }
24
+ }
25
+ export class Engine {
26
+ state;
27
+ factory;
28
+ db;
29
+ runs = new Map();
30
+ pumps = new Map();
31
+ agents = new Map();
32
+ pending = new Map();
33
+ closing = false;
34
+ settling = new Set();
35
+ constructor(state, factory = (hooks, cwd) => new AcpHarness(hooks, cwd)) {
36
+ this.state = state;
37
+ this.factory = factory;
38
+ mkdirSync(state, { recursive: true, mode: 0o700 });
39
+ this.db = new DatabaseSync(join(state, 'workflows.sqlite'));
40
+ this.db.exec(`PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL;
41
+ CREATE TABLE IF NOT EXISTS runs(id TEXT PRIMARY KEY, caller_key TEXT UNIQUE NOT NULL, body TEXT NOT NULL);
42
+ CREATE TABLE IF NOT EXISTS events(sequence INTEGER PRIMARY KEY, run TEXT NOT NULL, time TEXT NOT NULL, kind TEXT NOT NULL, detail TEXT NOT NULL);
43
+ CREATE INDEX IF NOT EXISTS by_run ON events(run,sequence);`);
44
+ for (const row of this.db.prepare('SELECT body FROM runs').all()) {
45
+ const r = JSON.parse(String(row.body));
46
+ this.runs.set(r.id, r);
47
+ if (terminal(r.status))
48
+ continue;
49
+ if (r.worker || r.verifier) {
50
+ this.retireSessions(r);
51
+ r.feedback +=
52
+ '\nTransmission restarted. Inspect existing work and the outcome of consequential actions before repeating them. Ask if their outcome cannot be determined.';
53
+ this.save(r, 'task_resumed', { task: r.plan.tasks[r.index].name });
54
+ }
55
+ this.wake(r);
56
+ }
57
+ }
58
+ dir(r) {
59
+ return join(this.state, r.id);
60
+ }
61
+ save(r, kind, detail = {}) {
62
+ this.db.exec('BEGIN IMMEDIATE');
63
+ try {
64
+ this.db
65
+ .prepare('INSERT INTO runs VALUES(?,?,?) ON CONFLICT(id) DO UPDATE SET body=excluded.body')
66
+ .run(r.id, r.plan.idempotencyKey, JSON.stringify(r));
67
+ this.event(r, kind, detail);
68
+ this.db.exec('COMMIT');
69
+ }
70
+ catch (error) {
71
+ this.db.exec('ROLLBACK');
72
+ throw error;
73
+ }
74
+ }
75
+ event(r, kind, detail) {
76
+ this.db
77
+ .prepare('INSERT INTO events(run,time,kind,detail) VALUES(?,?,?,?)')
78
+ .run(r.id, new Date().toISOString(), kind, JSON.stringify(detail));
79
+ }
80
+ get(id) {
81
+ const r = this.runs.get(id);
82
+ if (!r)
83
+ throw new Error('Unknown workflow.');
84
+ return r;
85
+ }
86
+ start(plan) {
87
+ const prior = this.db
88
+ .prepare('SELECT id FROM runs WHERE caller_key=?')
89
+ .get(plan.idempotencyKey);
90
+ if (prior) {
91
+ const r = this.get(String(prior.id));
92
+ if (JSON.stringify(r.plan) !==
93
+ JSON.stringify({ ...plan, repository: repository(plan.repository) }))
94
+ throw new Error('This key belongs to a different workflow.');
95
+ return this.status(r.id);
96
+ }
97
+ const root = repository(plan.repository);
98
+ const state = realpathSync(this.state);
99
+ if (state === root || state.startsWith(root + sep))
100
+ throw new Error('Keep Transmission state outside the target repository.');
101
+ if ([...this.runs.values()].some((r) => (!terminal(r.status) || this.settling.has(r.id)) &&
102
+ r.plan.repository === root))
103
+ throw new Error('A workflow is already active in this project.');
104
+ const id = randomUUID();
105
+ const r = {
106
+ id,
107
+ plan: { ...plan, repository: root },
108
+ baseline: snapshot(root, join(this.state, id)),
109
+ index: 0,
110
+ status: 'running',
111
+ phase: 'worker',
112
+ generation: 0,
113
+ repairsUsed: 0,
114
+ feedback: '',
115
+ messages: [],
116
+ guidance: [],
117
+ formatErrors: 0,
118
+ accepted: [],
119
+ attempts: [],
120
+ };
121
+ this.save(r, 'started');
122
+ this.runs.set(id, r);
123
+ this.wake(r);
124
+ return this.status(id);
125
+ }
126
+ status(id) {
127
+ const row = this.db.prepare(`
128
+ SELECT body, (SELECT MAX(sequence) FROM events WHERE run = runs.id) AS cursor
129
+ FROM runs WHERE id = ?
130
+ `).get(id);
131
+ if (!row)
132
+ throw new Error('Unknown workflow.');
133
+ const r = JSON.parse(String(row.body));
134
+ return {
135
+ runId: id,
136
+ status: r.status,
137
+ tasks: r.plan.tasks.map(({ name }, index) => ({ index, name, state: taskState(r, index) })),
138
+ activeTaskIndex: terminal(r.status) ? null : r.index,
139
+ eventCursor: Number(row.cursor),
140
+ task: r.plan.tasks[r.index]?.name,
141
+ phase: terminal(r.status) ? undefined : r.phase,
142
+ accepted: r.accepted,
143
+ decision: r.question,
144
+ reason: r.failure,
145
+ attempts: r.attempts,
146
+ ...(r.status === 'completed'
147
+ ? {
148
+ result: r.accepted.at(-1).result,
149
+ verdict: r.accepted.at(-1).verdict,
150
+ }
151
+ : {}),
152
+ };
153
+ }
154
+ events(id, after) {
155
+ this.get(id);
156
+ return this.db
157
+ .prepare('SELECT sequence,time,kind,detail FROM events WHERE run=? AND sequence>? ORDER BY sequence LIMIT 100')
158
+ .all(id, after)
159
+ .map((e) => ({
160
+ sequence: Number(e.sequence),
161
+ time: String(e.time),
162
+ kind: String(e.kind),
163
+ detail: JSON.parse(String(e.detail)),
164
+ }));
165
+ }
166
+ diff(id, offset) {
167
+ const r = this.get(id), rev = r.accepted.at(-1)?.revision;
168
+ if (!rev)
169
+ return { content: '', nextOffset: null };
170
+ const path = join(this.dir(r), rev + '.patch'), size = statSync(path).size, fd = openSync(path, 'r');
171
+ try {
172
+ const b = Buffer.alloc(Math.max(0, Math.min(size - offset, 65536)));
173
+ const n = readSync(fd, b, 0, b.length, offset);
174
+ return {
175
+ content: b.subarray(0, n).toString('base64'),
176
+ nextOffset: offset + n < size ? offset + n : null,
177
+ revision: rev,
178
+ };
179
+ }
180
+ finally {
181
+ closeSync(fd);
182
+ }
183
+ }
184
+ answer(id, questionId, answer) {
185
+ const r = this.get(id);
186
+ if (r.lastAnswer?.id === questionId && r.lastAnswer.answer === answer)
187
+ return this.status(id);
188
+ if (r.status !== 'needs_input' || r.question?.id !== questionId)
189
+ throw new Error('This decision is no longer pending.');
190
+ if (r.question.options &&
191
+ !r.question.options.some((opt) => opt.id === answer))
192
+ throw new Error('Select one of the offered option IDs.');
193
+ const q = r.question, p = this.pending.get(id);
194
+ delete r.question;
195
+ r.lastAnswer = { id: questionId, answer };
196
+ r.status = 'running';
197
+ if (!p || p.id !== q.id)
198
+ r.guidance.push('Decision: ' + q.text + '\nUser answer: ' + answer);
199
+ this.save(r, 'answered', { question: q, answer });
200
+ this.pending.delete(id);
201
+ p?.resolve(answer);
202
+ this.wake(r);
203
+ return this.status(id);
204
+ }
205
+ message(id, message) {
206
+ const r = this.get(id);
207
+ if (terminal(r.status))
208
+ throw new Error('Workflow has ended.');
209
+ r.messages.push(message);
210
+ r.guidance.push(message);
211
+ this.save(r, 'message', { message });
212
+ return this.status(id);
213
+ }
214
+ async cancel(id) {
215
+ const r = this.get(id);
216
+ if (!terminal(r.status)) {
217
+ this.settling.add(id);
218
+ r.status = 'cancelled';
219
+ delete r.question;
220
+ this.save(r, 'cancelled');
221
+ try {
222
+ await this.dispose(r);
223
+ await this.pumps.get(id);
224
+ }
225
+ finally {
226
+ this.settling.delete(id);
227
+ }
228
+ }
229
+ return this.status(id);
230
+ }
231
+ async dispose(r) {
232
+ this.pending.get(r.id)?.resolve(undefined);
233
+ this.pending.delete(r.id);
234
+ const agent = this.agents.get(r.id);
235
+ this.agents.delete(r.id);
236
+ await agent?.close();
237
+ }
238
+ async close() {
239
+ this.closing = true;
240
+ await Promise.all([...this.runs.values()].map((r) => this.dispose(r)));
241
+ await Promise.all(this.pumps.values());
242
+ this.db.close();
243
+ }
244
+ wake(r) {
245
+ if (this.closing || r.status !== 'running' || this.pumps.has(r.id))
246
+ return;
247
+ const work = Promise.resolve()
248
+ .then(() => this.drive(r))
249
+ .finally(() => {
250
+ this.pumps.delete(r.id);
251
+ this.wake(r);
252
+ });
253
+ this.pumps.set(r.id, work);
254
+ }
255
+ retireSessions(r) {
256
+ delete r.worker;
257
+ delete r.verifier;
258
+ delete r.candidate;
259
+ r.phase = 'worker';
260
+ r.formatErrors = 0;
261
+ }
262
+ restart(r, reason) {
263
+ r.attempts.push(reason);
264
+ this.retireSessions(r);
265
+ r.repairsUsed = 0;
266
+ if (r.generation >= r.plan.retries) {
267
+ r.failure = reason + ' Fresh-session retry limit reached.';
268
+ r.status = 'failed';
269
+ delete r.question;
270
+ }
271
+ else {
272
+ r.generation++;
273
+ r.feedback = reason + ' Inspect existing work before continuing.';
274
+ r.status = 'running';
275
+ delete r.question;
276
+ }
277
+ this.save(r, 'attempt_ended', {
278
+ reason,
279
+ next: r.status,
280
+ retriesUsed: r.generation,
281
+ });
282
+ }
283
+ ask(r, question) {
284
+ r.question = question;
285
+ r.status = 'needs_input';
286
+ this.save(r, 'needs_input', question);
287
+ }
288
+ client(r) {
289
+ let agent = this.agents.get(r.id);
290
+ if (agent)
291
+ return agent;
292
+ agent = this.factory({
293
+ tool: (session, detail) => this.event(r, 'tool', { session, detail }),
294
+ permission: async (request) => {
295
+ if (r.status !== 'running' || this.closing)
296
+ return undefined;
297
+ const once = request.options.find((o) => o.kind === 'allow_once');
298
+ if (r.plan.autoApprove && once) {
299
+ this.event(r, 'permission', {
300
+ session: request.sessionId,
301
+ selected: once.optionId,
302
+ });
303
+ return once.optionId;
304
+ }
305
+ const question = {
306
+ id: randomUUID(),
307
+ text: request.toolCall.title ?? 'Choose an agent permission.',
308
+ options: request.options.map((o) => ({
309
+ id: o.optionId,
310
+ name: o.name,
311
+ })),
312
+ };
313
+ this.ask(r, question);
314
+ return new Promise((resolve) => this.pending.set(r.id, { id: question.id, resolve }));
315
+ },
316
+ }, r.plan.repository);
317
+ this.agents.set(r.id, agent);
318
+ return agent;
319
+ }
320
+ async drive(r) {
321
+ try {
322
+ while (!this.closing && r.status === 'running') {
323
+ const harness = this.client(r), role = r.phase, task = r.plan.tasks[r.index];
324
+ if (!r[role]) {
325
+ const session = await harness.session(r.plan.repository);
326
+ if (this.closing || r.status !== 'running')
327
+ return;
328
+ r[role] = session;
329
+ this.save(r, 'session_started', {
330
+ role,
331
+ session,
332
+ task: task.name,
333
+ generation: r.generation,
334
+ });
335
+ }
336
+ const session = r[role], messages = [...r.messages];
337
+ const data = {
338
+ task: role === 'verifier'
339
+ ? task
340
+ : {
341
+ name: task.name,
342
+ instructions: task.instructions,
343
+ checks: task.checks,
344
+ },
345
+ incoming: messages,
346
+ priorTasks: r.accepted.slice(-8).map((a) => ({
347
+ name: a.name,
348
+ result: a.result.slice(0, 4096),
349
+ })),
350
+ feedback: r.feedback,
351
+ operatorGuidance: r.guidance.join('\n').slice(-65536),
352
+ ...(role === 'verifier' ? { candidate: r.candidate } : {}),
353
+ };
354
+ const instructions = role === 'worker'
355
+ ? 'Implement the assigned task using your normal tools in this project. Preserve prior edits, HEAD and staging. Install dependencies and run the relevant checks. Finish commands and stop temporary background services before submitting. Act on feedback from independent review. End with one line of JSON: {"kind":"result","summary":"result and executed checks"}.'
356
+ : 'Independently verify the candidate in the current repository against the verification prompt. Inspect and test it yourself. Leave the source unchanged. If task.checks are specified, run each command with your own harness and include a checks array in the final JSON with command (exact), passed (boolean), and evidence (observed output) for each. End with one line of JSON: {"kind":"verdict","decision":"accept" or "reject","reason":"specific evidence or actionable repair instructions"}.';
357
+ this.save(r, 'turn_started', { role, session, task: task.name });
358
+ const raw = await harness.prompt(session, instructions +
359
+ ' Only for a genuine decision about intent or scope, end with {"kind":"question","question":"decision needed"}.\n' +
360
+ JSON.stringify(data));
361
+ if (this.closing || terminal(r.status))
362
+ return;
363
+ // Retain messages until a turn consumes them successfully.
364
+ r.messages.splice(0, messages.length);
365
+ const line = raw
366
+ .trim()
367
+ .replace(/^```(?:json)?\s*|\s*```$/g, '')
368
+ .trim();
369
+ let value;
370
+ try {
371
+ value = JSON.parse(line);
372
+ }
373
+ catch {
374
+ try {
375
+ value = JSON.parse(line.split('\n').at(-1));
376
+ }
377
+ catch { }
378
+ }
379
+ const reply = role === 'worker'
380
+ ? workerReply.safeParse(value)
381
+ : verifierReply.safeParse(value);
382
+ if (!reply.success &&
383
+ role === 'verifier' &&
384
+ r.formatErrors < r.plan.repairs) {
385
+ r.formatErrors++;
386
+ r.feedback =
387
+ 'Your verdict could not be parsed. Return the specified JSON verdict and evidence.';
388
+ this.save(r, 'invalid_verdict', { session });
389
+ continue;
390
+ }
391
+ if (!reply.success && role === 'verifier') {
392
+ this.restart(r, 'The verifier did not return a valid verdict.');
393
+ await this.dispose(r);
394
+ return;
395
+ }
396
+ if (!reply.success) {
397
+ await this.repair(r, 'Invalid ' +
398
+ role +
399
+ ' response. Return the requested final JSON object.');
400
+ continue;
401
+ }
402
+ r.formatErrors = 0;
403
+ const v = reply.data;
404
+ if (v.kind === 'question') {
405
+ this.ask(r, { id: randomUUID(), text: v.question });
406
+ return;
407
+ }
408
+ const revision = snapshot(r.plan.repository, this.dir(r));
409
+ if (v.kind === 'result') {
410
+ r.candidate = { summary: v.summary, revision };
411
+ delete r.verifier;
412
+ r.phase = 'verifier';
413
+ r.feedback = '';
414
+ this.save(r, 'submitted', { session, revision, summary: v.summary });
415
+ continue;
416
+ }
417
+ const candidate = r.candidate;
418
+ const missing = task.checks?.filter((command) => !v.checks?.some((c) => c.command === command && c.passed));
419
+ if (v.decision === 'accept' && missing?.length) {
420
+ v.decision = 'reject';
421
+ v.reason =
422
+ 'Missing passing verifier evidence for ' +
423
+ missing.join(', ') +
424
+ '. ' +
425
+ v.reason;
426
+ }
427
+ this.save(r, 'verdict', {
428
+ worker: r.worker,
429
+ verifier: session,
430
+ revision: candidate.revision,
431
+ ...v,
432
+ });
433
+ if (v.decision === 'reject' ||
434
+ candidate.revision !== revision ||
435
+ r.messages.length ||
436
+ messages.length) {
437
+ await this.repair(r, v.decision === 'reject'
438
+ ? v.reason
439
+ : candidate.revision !== revision
440
+ ? 'Source changed during verification. Submit the current candidate.'
441
+ : 'Address user guidance before resubmitting: ' +
442
+ [...messages, ...r.messages].join('\n'));
443
+ continue;
444
+ }
445
+ const accepted = {
446
+ name: task.name,
447
+ result: candidate.summary,
448
+ revision,
449
+ worker: r.worker,
450
+ verifier: session,
451
+ verdict: {
452
+ decision: v.decision,
453
+ reason: v.reason,
454
+ ...(v.checks ? { checks: v.checks } : {}),
455
+ },
456
+ };
457
+ const patch = join(this.dir(r), revision + '.patch'), tmp = patch + '.tmp', fd = openSync(tmp, 'w', 0o600);
458
+ try {
459
+ try {
460
+ writePatch(r.plan.repository, this.dir(r), r.baseline, revision, fd);
461
+ }
462
+ finally {
463
+ closeSync(fd);
464
+ }
465
+ renameSync(tmp, patch);
466
+ }
467
+ finally {
468
+ rmSync(tmp, { force: true });
469
+ }
470
+ r.accepted.push(accepted);
471
+ r.guidance = [];
472
+ r.index++;
473
+ r.phase = 'worker';
474
+ r.feedback = '';
475
+ r.repairsUsed = 0;
476
+ r.generation = 0;
477
+ delete r.worker;
478
+ delete r.verifier;
479
+ delete r.candidate;
480
+ if (r.index === r.plan.tasks.length)
481
+ r.status = 'completed';
482
+ this.save(r, 'task_accepted', accepted);
483
+ await this.dispose(r);
484
+ }
485
+ }
486
+ catch (error) {
487
+ if (this.closing || terminal(r.status))
488
+ return;
489
+ this.restart(r, diagnostic(error));
490
+ await this.dispose(r);
491
+ }
492
+ }
493
+ async repair(r, reason) {
494
+ if (r.repairsUsed >= r.plan.repairs) {
495
+ this.restart(r, reason);
496
+ await this.dispose(r);
497
+ return;
498
+ }
499
+ r.repairsUsed++;
500
+ r.attempts.push(reason);
501
+ r.feedback = reason;
502
+ r.phase = 'worker';
503
+ delete r.verifier;
504
+ this.save(r, 'repair_requested', { worker: r.worker, reason });
505
+ }
506
+ }