@anyswarm/core 0.5.2 → 0.6.0

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 (210) hide show
  1. package/AGENTS.md +19 -4
  2. package/README.md +68 -61
  3. package/dist/examples/README.md +134 -84
  4. package/dist/examples/autoresearch/README.md +106 -21
  5. package/dist/examples/autoresearch/REQUIREMENTS.zh.md +14 -6
  6. package/dist/examples/autoresearch/config.d.ts +48 -5
  7. package/dist/examples/autoresearch/config.js +57 -23
  8. package/dist/examples/autoresearch/demo.d.ts +12 -4
  9. package/dist/examples/autoresearch/demo.js +65 -22
  10. package/dist/examples/autoresearch/frontiercs2-config.d.ts +2 -2
  11. package/dist/examples/autoresearch/frontiercs2-config.js +13 -2
  12. package/dist/examples/autoresearch/frontiercs2.d.ts +18 -1
  13. package/dist/examples/autoresearch/frontiercs2.js +71 -14
  14. package/dist/examples/autoresearch/prepare-demo.js +34 -3
  15. package/dist/examples/autoresearch/prepare.d.ts +105 -53
  16. package/dist/examples/autoresearch/prepare.js +126 -57
  17. package/dist/examples/autoresearch/project.d.ts +6 -1
  18. package/dist/examples/autoresearch/project.js +130 -26
  19. package/dist/examples/autoresearch/research-service.d.ts +16 -1
  20. package/dist/examples/autoresearch/research-service.js +84 -44
  21. package/dist/examples/code/config.d.ts +1 -0
  22. package/dist/examples/first-harness/AGENTS.md +25 -0
  23. package/dist/examples/first-harness/README.md +136 -0
  24. package/dist/examples/first-harness/config.d.ts +9 -8
  25. package/dist/examples/first-harness/config.js +33 -26
  26. package/dist/examples/first-harness/eject.json +14 -0
  27. package/dist/examples/first-harness/handoff.js +3 -3
  28. package/dist/examples/first-harness/harness.d.ts +14 -18
  29. package/dist/examples/first-harness/harness.js +102 -77
  30. package/dist/examples/first-harness/input/README.md +7 -0
  31. package/dist/examples/first-harness/session.js +2 -1
  32. package/dist/examples/first-harness/tsconfig.json +2 -1
  33. package/dist/examples/harness-session/README.md +1 -1
  34. package/dist/examples/lead-worker/README.md +1 -1
  35. package/dist/examples/lead-worker/project-config.d.ts +1 -0
  36. package/dist/examples/messages/README.md +2 -2
  37. package/dist/examples/notes/README.md +2 -2
  38. package/dist/examples/notes/config.d.ts +1 -0
  39. package/dist/examples/parallel-swarm/AGENTS.md +32 -0
  40. package/dist/examples/parallel-swarm/README.md +136 -0
  41. package/dist/examples/parallel-swarm/board-service.js +25 -8
  42. package/dist/examples/parallel-swarm/board.d.ts +31 -1
  43. package/dist/examples/parallel-swarm/board.js +98 -13
  44. package/dist/examples/parallel-swarm/config.d.ts +11 -0
  45. package/dist/examples/parallel-swarm/config.js +39 -0
  46. package/dist/examples/parallel-swarm/eject.json +5 -0
  47. package/dist/examples/parallel-swarm/harness.d.ts +26 -20
  48. package/dist/examples/parallel-swarm/harness.js +77 -76
  49. package/dist/examples/parallel-swarm/report.d.ts +12 -0
  50. package/dist/examples/parallel-swarm/report.js +30 -0
  51. package/dist/examples/peermesh/README.md +1 -1
  52. package/dist/examples/peermesh/project-config.d.ts +1 -0
  53. package/dist/examples/services/agent-control/README.md +1 -1
  54. package/dist/examples/services/mathlib-search/README.md +1 -1
  55. package/dist/examples/services/mcp-managed/README.md +1 -1
  56. package/dist/examples/services/persistent-board/README.md +1 -1
  57. package/dist/examples/subagents/AGENTS.md +35 -0
  58. package/dist/examples/subagents/README.md +129 -93
  59. package/dist/examples/subagents/config.d.ts +2 -10
  60. package/dist/examples/subagents/config.js +8 -15
  61. package/dist/examples/subagents/eject.json +17 -0
  62. package/dist/examples/subagents/handoff-config.d.ts +41 -0
  63. package/dist/examples/subagents/handoff-config.js +13 -0
  64. package/dist/examples/subagents/model.d.ts +3 -0
  65. package/dist/examples/subagents/model.js +19 -0
  66. package/dist/examples/substrate/README.md +12 -6
  67. package/dist/examples/substrate/config.d.ts +1 -0
  68. package/dist/examples/substrate/project-config.d.ts +1 -0
  69. package/dist/examples/taskpool/README.md +1 -1
  70. package/dist/examples/taskpool/config.d.ts +1 -0
  71. package/dist/examples/taskpool/deploy/service-hosts/service-authority-snapshot.d.ts +4 -4
  72. package/dist/scripts/anyswarm-progress.js +36 -5
  73. package/dist/scripts/build-provenance.json +1 -1
  74. package/dist/scripts/generate-architecture-coverage.js +1 -1
  75. package/dist/scripts/generate-architecture-prompts.js +18 -10
  76. package/dist/scripts/local-environment.d.ts +3 -3
  77. package/dist/scripts/local-environment.js +6 -1
  78. package/dist/scripts/local-setup.js +25 -18
  79. package/dist/scripts/pack-release.js +27 -3
  80. package/dist/src/core/index.js +1 -1
  81. package/dist/src/core/sandbox/opensandbox-backend.js +10 -4
  82. package/dist/src/core/sandbox/sandbox-connection.d.ts +9 -2
  83. package/dist/src/core/sandbox/sandbox-connection.js +22 -7
  84. package/dist/src/harness/project-harness.js +3 -2
  85. package/dist/src/harness/project-rpc-client.js +19 -0
  86. package/dist/src/harness/typescript-loader.d.ts +2 -0
  87. package/dist/src/harness/typescript-loader.js +26 -8
  88. package/dist/src/trace-viewer/command.mjs +6 -3
  89. package/dist/src/trace-viewer/public/app.js +239 -59
  90. package/dist/src/trace-viewer/public/index.html +5 -0
  91. package/dist/src/trace-viewer/public/style.css +22 -0
  92. package/dist/src/trace-viewer/reader.mjs +242 -26
  93. package/dist/src/trace-viewer/run-root.d.mts +1 -0
  94. package/dist/src/trace-viewer/run-root.mjs +7 -0
  95. package/dist/src/trace-viewer/server.mjs +3 -1
  96. package/docs/INDEX.md +9 -8
  97. package/docs/architecture/06-observability-experiments.md +21 -7
  98. package/docs/architecture/07-run-configuration.md +97 -12
  99. package/docs/architecture/08-prompts.md +21 -2
  100. package/docs/architecture/10-service-api-reference.md +12 -5
  101. package/docs/architecture/12-code-coverage.md +129 -86
  102. package/docs/architecture/15-core-runtime.md +1 -1
  103. package/docs/architecture/16-pi-opensandbox-backend.md +2 -0
  104. package/docs/architecture/17-harness-reporting.md +78 -0
  105. package/docs/architecture/22-website.md +53 -18
  106. package/docs/architecture/23-project-harness.md +63 -16
  107. package/docs/architecture/28-autoresearch.md +16 -22
  108. package/docs/architecture/prompts/11-first-sdk-harness.md +9 -9
  109. package/docs/architecture/prompts/16-parallel-swarm.md +46 -13
  110. package/docs/architecture/prompts/22-autoresearch.md +9 -2
  111. package/docs/architecture/prompts/source-manifest.json +78 -54
  112. package/docs/architecture/source-map.json +396 -36
  113. package/docs/designs/core-harness/06-project-harness.md +1 -1
  114. package/docs/en/autoresearch.md +41 -0
  115. package/docs/en/blog/100b-tokens.md +157 -0
  116. package/docs/en/build-your-harness.md +47 -22
  117. package/docs/en/changelog.md +22 -1
  118. package/docs/en/first-harness.md +40 -32
  119. package/docs/en/harnesses/index.md +23 -23
  120. package/docs/en/harnesses/subagents.md +8 -29
  121. package/docs/en/latest.md +26 -5
  122. package/docs/en/overview.md +22 -22
  123. package/docs/en/quickstart.md +55 -21
  124. package/docs/en/reference/api.md +1 -1
  125. package/docs/en/trace-viewer.md +32 -12
  126. package/docs/operations/trace-viewer.md +25 -10
  127. package/docs/workflows/development.md +160 -120
  128. package/docs/workflows/release-and-docs-versioning.md +207 -55
  129. package/docs/workflows/release-cli-acceptance.md +124 -47
  130. package/docs/zh/autoresearch.md +41 -0
  131. package/docs/zh/blog/100b-tokens.md +102 -0
  132. package/docs/zh/build-your-harness.md +48 -23
  133. package/docs/zh/changelog.md +22 -1
  134. package/docs/zh/first-harness.md +43 -35
  135. package/docs/zh/harnesses/index.md +23 -23
  136. package/docs/zh/harnesses/subagents.md +8 -29
  137. package/docs/zh/latest.md +26 -5
  138. package/docs/zh/overview.md +23 -23
  139. package/docs/zh/quickstart.md +51 -21
  140. package/docs/zh/reference/api.md +1 -1
  141. package/docs/zh/trace-viewer.md +32 -12
  142. package/examples/README.md +134 -84
  143. package/examples/autoresearch/README.md +106 -21
  144. package/examples/autoresearch/REQUIREMENTS.zh.md +14 -6
  145. package/examples/autoresearch/config.ts +64 -25
  146. package/examples/autoresearch/demo.ts +75 -22
  147. package/examples/autoresearch/frontiercs2-config.ts +13 -2
  148. package/examples/autoresearch/frontiercs2.ts +64 -11
  149. package/examples/autoresearch/prepare-demo.ts +32 -3
  150. package/examples/autoresearch/prepare.ts +134 -60
  151. package/examples/autoresearch/project.ts +119 -26
  152. package/examples/autoresearch/research-service.ts +91 -41
  153. package/examples/first-harness/AGENTS.md +25 -0
  154. package/examples/first-harness/README.md +136 -0
  155. package/examples/first-harness/config.ts +41 -27
  156. package/examples/first-harness/eject.json +14 -0
  157. package/examples/first-harness/handoff.ts +3 -3
  158. package/examples/first-harness/harness.ts +104 -72
  159. package/examples/first-harness/input/README.md +7 -0
  160. package/examples/first-harness/session.ts +2 -1
  161. package/examples/first-harness/tsconfig.json +2 -1
  162. package/examples/harness-session/README.md +1 -1
  163. package/examples/lead-worker/README.md +1 -1
  164. package/examples/messages/README.md +2 -2
  165. package/examples/notes/README.md +2 -2
  166. package/examples/parallel-swarm/AGENTS.md +32 -0
  167. package/examples/parallel-swarm/README.md +136 -0
  168. package/examples/parallel-swarm/board-service.ts +28 -9
  169. package/examples/parallel-swarm/board.ts +107 -13
  170. package/examples/parallel-swarm/config.ts +47 -0
  171. package/examples/parallel-swarm/eject.json +5 -0
  172. package/examples/parallel-swarm/harness.ts +83 -71
  173. package/examples/parallel-swarm/report.ts +33 -0
  174. package/examples/peermesh/README.md +1 -1
  175. package/examples/services/agent-control/README.md +1 -1
  176. package/examples/services/mathlib-search/README.md +1 -1
  177. package/examples/services/mcp-managed/README.md +1 -1
  178. package/examples/services/persistent-board/README.md +1 -1
  179. package/examples/subagents/AGENTS.md +35 -0
  180. package/examples/subagents/README.md +129 -93
  181. package/examples/subagents/config.ts +8 -15
  182. package/examples/subagents/eject.json +17 -0
  183. package/examples/subagents/handoff-config.ts +14 -0
  184. package/examples/subagents/model.ts +20 -0
  185. package/examples/substrate/README.md +12 -6
  186. package/examples/taskpool/README.md +1 -1
  187. package/npm-shrinkwrap.development.json +9 -2
  188. package/npm-shrinkwrap.json +9 -2
  189. package/package.development.json +2 -1
  190. package/package.json +2 -1
  191. package/scripts/anyswarm-progress.ts +36 -6
  192. package/scripts/generate-architecture-coverage.ts +1 -1
  193. package/scripts/generate-architecture-prompts.ts +21 -10
  194. package/scripts/local-environment.ts +8 -1
  195. package/scripts/local-setup.ts +22 -17
  196. package/scripts/pack-release.ts +24 -3
  197. package/src/core/index.ts +1 -1
  198. package/src/core/sandbox/opensandbox-backend.ts +10 -4
  199. package/src/core/sandbox/sandbox-connection.ts +22 -7
  200. package/src/harness/project-harness.ts +3 -2
  201. package/src/harness/project-rpc-client.ts +23 -0
  202. package/src/harness/typescript-loader.ts +28 -8
  203. package/src/trace-viewer/command.mjs +6 -3
  204. package/src/trace-viewer/public/app.js +239 -59
  205. package/src/trace-viewer/public/index.html +5 -0
  206. package/src/trace-viewer/public/style.css +22 -0
  207. package/src/trace-viewer/reader.mjs +242 -26
  208. package/src/trace-viewer/run-root.d.mts +1 -0
  209. package/src/trace-viewer/run-root.mjs +7 -0
  210. package/src/trace-viewer/server.mjs +3 -1
@@ -1,10 +1,12 @@
1
- import { mkdir, readFile, readdir, writeFile } from 'node:fs/promises';
1
+ import { createReadStream } from 'node:fs';
2
+ import { createInterface } from 'node:readline';
3
+ import { mkdir, readFile, readdir, rename, writeFile } from 'node:fs/promises';
2
4
  import { join, resolve } from 'node:path';
3
5
  import { setTimeout as delay } from 'node:timers/promises';
4
6
  import { createRuntime, createSandbox, getExecutorCapabilities, observeProjectRuntime, ProjectPreflightError, runInput, ServiceRegistry,
5
7
  type CloseReceipt, type Harness, type Profile, type HarnessContext, type HarnessJson, type InterruptReceipt, type JsonValue, type Runtime } from '@anyswarm/core';
6
- import { checkBudget, type ResearchConfiguration } from './config.js';
7
- import { appendResearchEvent, candidatePath, createResearch, researchOperations, withDeadline } from './research-service.js';
8
+ import { checkBudget, modelConfigurationError, type ResearchConfiguration } from './config.js';
9
+ import { appendResearchEvent, candidatePath, createResearch, readFinalEvaluation, researchOperations, withDeadline } from './research-service.js';
8
10
 
9
11
  const instructions = `You are one of several equal research peers exploring the same goal. Choose your own concrete direction and coordinate directly with peers.
10
12
  Use the following CLI directly in your private project. The host already provides this Service.
@@ -46,6 +48,8 @@ function configuration(value: unknown): ResearchConfiguration {
46
48
  throw new ProjectPreflightError('AUTORESEARCH_CONFIG_INVALID', 'Evaluator timeouts must be positive millisecond values.');
47
49
  }
48
50
  }
51
+ const problem = modelConfigurationError(config.model, config.executor);
52
+ if (problem) throw new ProjectPreflightError('AUTORESEARCH_MODEL_REQUIRED', problem);
49
53
  return { ...config, budget: checkBudget(config.budget) };
50
54
  }
51
55
 
@@ -73,6 +77,8 @@ async function modelUsage(directory: string, peers: { agentId: string; label: st
73
77
  let outputTokens = 0;
74
78
  let attemptsWithUsage = 0;
75
79
  const intervals: { agentId: string; start: number; end: number }[] = [];
80
+ const upstreamModels = new Map<string, number>();
81
+ const requestIntervals: { from: number; to: number; peers: number }[] = [];
76
82
  const summarized = new Map(peers.map(peer => [peer.agentId, { ...peer, dispatched: 0, succeeded: 0 }]));
77
83
  for (const id of attempts) {
78
84
  const attempt = (file: string) => readFile(join(trace, id, file), 'utf8').then(text => JSON.parse(text)).catch(() => null);
@@ -87,14 +93,36 @@ async function modelUsage(directory: string, peers: { agentId: string; label: st
87
93
  }
88
94
  if (result?.state !== 'completed' || result?.upstreamStatus !== 200) continue;
89
95
  peer.succeeded++;
96
+ const models = new Set<string>();
97
+ const stream = createReadStream(join(trace, id, 'response.txt'));
98
+ try {
99
+ for await (const line of createInterface({ input: stream, crlfDelay: Infinity })) {
100
+ if (!line.startsWith('data:')) continue;
101
+ try {
102
+ const event = JSON.parse(line.slice(5));
103
+ const model = event.type === 'response.completed' ? event.response?.model : event.model;
104
+ if (typeof model === 'string') models.add(model.slice(0, 160));
105
+ } catch { /* Incomplete or non-JSON SSE fields carry no model identity. */ }
106
+ }
107
+ } catch { /* The gateway can record the attempt even if the upstream bytes are unavailable. */ }
108
+ finally { stream.destroy(); }
109
+ if (models.size === 1) {
110
+ const model = [...models][0];
111
+ upstreamModels.set(model, (upstreamModels.get(model) ?? 0) + 1);
112
+ }
90
113
  const start = Date.parse(request.startedAt);
91
114
  const end = Date.parse(result.endedAt);
92
115
  if (start < end) intervals.push({ agentId: peer.agentId, start, end });
93
116
  }
94
117
  const current = new Map<string, number>();
95
118
  let peakConcurrentPeers = 0;
119
+ let lastAt: number | undefined;
96
120
  for (const point of intervals.flatMap(({ agentId, start, end }) =>
97
121
  [{ agentId, at: start, delta: 1 }, { agentId, at: end, delta: -1 }]).sort((a, b) => a.at - b.at || a.delta - b.delta)) {
122
+ if (lastAt !== undefined && lastAt < point.at && current.size > 1) {
123
+ requestIntervals.push({ from: lastAt, to: point.at, peers: current.size });
124
+ }
125
+ lastAt = point.at;
98
126
  const next = (current.get(point.agentId) ?? 0) + point.delta;
99
127
  if (next) current.set(point.agentId, next);
100
128
  else current.delete(point.agentId);
@@ -104,6 +132,13 @@ async function modelUsage(directory: string, peers: { agentId: string; label: st
104
132
  dispatched: attempts.length, attemptsWithUsage, attemptsWithoutUsage: attempts.length - attemptsWithUsage,
105
133
  inputTokens: attemptsWithUsage ? inputTokens : null, outputTokens: attemptsWithUsage ? outputTokens : null,
106
134
  peers: [...summarized.values()], peakConcurrentPeers,
135
+ upstreamModels: Object.fromEntries(upstreamModels),
136
+ requestsWithoutUpstreamModel: [...summarized.values()].reduce((sum, peer) => sum + peer.succeeded, 0) -
137
+ [...upstreamModels.values()].reduce((sum, count) => sum + count, 0),
138
+ peerOverlapMs: requestIntervals.reduce<Record<string, number>>((summary, { from, to, peers }) => {
139
+ summary[peers] = (summary[peers] ?? 0) + to - from;
140
+ return summary;
141
+ }, {}),
107
142
  };
108
143
  }
109
144
 
@@ -115,6 +150,7 @@ export default {
115
150
  async run(context: HarnessContext) {
116
151
  const config = configuration(context.configuration);
117
152
  const { budget } = config;
153
+ await config.validateStarter?.(context.initial);
118
154
  if (config.requiredFiles?.some(path => !Object.hasOwn(context.initial.files, path))) {
119
155
  throw new ProjectPreflightError('AUTORESEARCH_STARTER_INCOMPLETE', 'Project capture missed required starter files. Verify the prepared Git checkout and retry.');
120
156
  }
@@ -125,6 +161,11 @@ export default {
125
161
  : Promise.resolve('complete' as const);
126
162
  const registry = new ServiceRegistry();
127
163
  let deadlineAt = 0;
164
+ let workStartedAt: number | null = null;
165
+ let workEndedAt: number | null = null;
166
+ const startingAt = Date.now();
167
+ let runtimeAttempted = false;
168
+ let initFailure: { runtimeId?: string; reportPath?: string; cleanup?: CloseReceipt['cleanup']; details?: JsonValue } | undefined;
128
169
  let runtime: Runtime;
129
170
  const peerLabels = Array.from({ length: budget.workers }, (_, index) => `peer-${index + 1}`);
130
171
  const profile: Profile = { model: 'research', image: config.image, writable: true, services: { research: researchOperations }, addedSystemPrompt: instructions, ...(config.restrictNetwork ? { network: { allow: [] } } : {}) };
@@ -150,7 +191,7 @@ export default {
150
191
  }
151
192
  }
152
193
  const research = createResearch({
153
- outputDir: context.outputDir, direction: config.direction, maxEvaluations: budget.maxEvaluations, targetScore: config.targetScore,
194
+ get outputDir() { return join(context.outputDir, runtime.id); }, direction: config.direction, maxEvaluations: budget.maxEvaluations, targetScore: config.targetScore,
154
195
  get deadlineAt() { return deadlineAt; }, signal, trainSignal: context.signal, evaluator: config.evaluator, evaluationTimeoutMs: config.evaluationTimeoutMs ?? 190_000,
155
196
  stopWork: reason => controller.abort(reason),
156
197
  statusChanged: () => {
@@ -192,6 +233,9 @@ export default {
192
233
  let final: JsonValue | null = null;
193
234
  let judgeCleanup: 'complete' | 'pending' = 'complete';
194
235
  let error: string | null = null;
236
+ let finalStartedAt: number | null = null;
237
+ let finalEndedAt: number | null = null;
238
+ let cleanupStartedAt: number | null = null;
195
239
  let searchEnd = 'workers-settled';
196
240
  let selected: ReturnType<typeof research.selection>;
197
241
  try {
@@ -199,8 +243,7 @@ export default {
199
243
  const startSignal = AbortSignal.any([context.signal, AbortSignal.timeout(360_000)]);
200
244
  await withDeadline(startSignal, () => config.evaluator.start!(context.outputDir, startSignal));
201
245
  }
202
- deadlineAt = Date.now() + budget.workMs;
203
- deadline = setTimeout(() => controller.abort('work-deadline'), budget.workMs);
246
+ runtimeAttempted = true;
204
247
  runtime = await createRuntime({
205
248
  sandbox: createSandbox(config.sandbox), connection: { ...config.connection, modelGateway: {
206
249
  ...config.connection.modelGateway,
@@ -281,6 +324,9 @@ export default {
281
324
  }
282
325
  signal.throwIfAborted();
283
326
  status = 'researching';
327
+ workStartedAt = Date.now();
328
+ deadlineAt = workStartedAt + budget.workMs;
329
+ deadline = setTimeout(() => controller.abort('work-deadline'), budget.workMs);
284
330
  context.markRunning();
285
331
  research.event('team.ready');
286
332
  await Promise.all(peers.map(async ({ peer, label, member }) => {
@@ -296,10 +342,14 @@ export default {
296
342
  const remaining = deadlineAt - Date.now();
297
343
  if (remaining <= 0) break;
298
344
  const review = member.reviewOfferedInTurn ? undefined : member.review;
299
- if (turn > 0 && !review && research.state().budget.evaluations >= budget.maxEvaluations) break;
345
+ const trainExhausted = research.state().budget.evaluations >= budget.maxEvaluations;
346
+ if (turn > 0 && !review && trainExhausted && !config.continueAfterTrainBudget) break;
347
+ const remainingWork = trainExhausted
348
+ ? 'Train capacity is exhausted. Review another peer’s candidate, run local checks and publish concrete findings.'
349
+ : 'Check updates, review or build on promising peers’ work, and propose the next evidence-backed improvement.';
300
350
  const prompt = turn === 0
301
351
  ? `You are ${label}. Team objective: ${config.goal}\n${context.input.prompt}\nRead the project task statement and the board, claim an open direction and work toward a first testable patch promptly.`
302
- : 'Check updates, review or build on promising peers’ work, and propose the next evidence-backed improvement.';
352
+ : remainingWork;
303
353
  const interrupting = new Error('Peer interrupt pending before dispatch.');
304
354
  try {
305
355
  await runInput(runtime, peer.id, review ? `${prompt}\n\n${reviewNotice(review)}` : prompt, {
@@ -318,8 +368,15 @@ export default {
318
368
  if (!peerSignal.aborted) research.event('peer.turn-ended', { agentId: peer.id, detail: (error as Error).message.slice(0, 250) });
319
369
  }
320
370
  }));
371
+ workEndedAt = Date.now();
321
372
  searchEnd = research.stopReason() ?? (context.signal.aborted ? 'stopped' : controller.signal.aborted ? 'deadline' :
322
- research.state().budget.evaluations >= budget.maxEvaluations ? 'evaluation-budget' : 'workers-settled');
373
+ !config.continueAfterTrainBudget && research.state().budget.evaluations >= budget.maxEvaluations ? 'evaluation-budget' : 'workers-settled');
374
+ if (searchEnd === 'workers-settled' && budget.maxModelRequests !== undefined) {
375
+ const attempts = await readdir(join(context.outputDir, runtime.id, 'model-trace')).catch(() => []);
376
+ if (attempts.length >= budget.maxModelRequests) searchEnd = 'model-request-budget';
377
+ }
378
+ if (!controller.signal.aborted) controller.abort(searchEnd);
379
+ research.event('research.stopped', { detail: searchEnd });
323
380
  // The host owns the judge independently of the Runtime. Stop native work
324
381
  // while the last admitted train call settles under its own deadline.
325
382
  [close] = await Promise.all([
@@ -334,14 +391,29 @@ export default {
334
391
  selected = research.selection();
335
392
  if (selected && !context.signal.aborted) {
336
393
  status = 'final evaluation';
394
+ finalStartedAt = Date.now();
337
395
  research.event('final.selected', { agentId: selected.agentId, candidate: selected.id });
338
396
  const finalSignal = AbortSignal.any([context.signal, AbortSignal.timeout(config.closeTimeoutMs ?? 240_000)]);
339
397
  final = await withDeadline(finalSignal, () => config.evaluator.final(research.patch(selected!), finalSignal));
340
- research.event('final.returned', { agentId: selected.agentId, candidate: selected.id });
398
+ finalEndedAt = Date.now();
399
+ const verdict = readFinalEvaluation(final);
400
+ const evidence = verdict?.evidence as { payload?: { digest?: string }; summary?: string } | undefined;
401
+ research.event('final.returned', { agentId: selected.agentId, candidate: selected.id,
402
+ score: verdict?.score, payloadDigest: evidence?.payload?.digest,
403
+ detail: evidence?.summary ?? verdict?.status ?? 'unverified evaluator result' });
341
404
  }
342
405
  } catch (failure) {
343
- error = (failure as Error).message?.slice(0, 500) ?? 'Research failed';
406
+ error = failure instanceof Error ? failure.message.slice(0, 500) : 'Research failed';
407
+ if (!runtime! && runtimeAttempted && failure instanceof Error && failure.name === 'ResourceError') {
408
+ initFailure = failure as typeof initFailure;
409
+ }
410
+ if (runtime!) research.event(finalStartedAt === null ? 'run.failed' : 'final.failed', {
411
+ ...(selected ? { agentId: selected.agentId, candidate: selected.id } : {}), detail: error,
412
+ });
344
413
  } finally {
414
+ cleanupStartedAt = Date.now();
415
+ workEndedAt ??= workStartedAt === null ? null : cleanupStartedAt;
416
+ finalEndedAt ??= finalStartedAt === null ? null : cleanupStartedAt;
345
417
  clearTimeout(deadline);
346
418
  controller.abort('closing');
347
419
  research.close();
@@ -352,29 +424,50 @@ export default {
352
424
  }
353
425
  observation?.close();
354
426
  judgeCleanup = await cleanupJudge();
427
+ if (runtime!) research.event('run.cleanup', {
428
+ detail: `Runtime ${close?.cleanup ?? 'pending'}; evaluator ${judgeCleanup}`,
429
+ });
355
430
  }
356
431
  const best = research.best();
357
432
  const peers = research.state().peers;
358
433
  const traceDirectory = runtime! ? join(context.outputDir, runtime.id) : null;
359
- const runtimeReport = close?.reportPath ? await readFile(close.reportPath, 'utf8').then(text => JSON.parse(text)).catch(() => null) : null;
434
+ const runtimeReceipt = close?.reportPath ?? initFailure?.reportPath ?? null;
435
+ const runtimeReport = runtimeReceipt ? await readFile(runtimeReceipt, 'utf8').then(text => JSON.parse(text)).catch(() => null) : null;
436
+ const usage = traceDirectory ? await modelUsage(traceDirectory, peers) : null;
437
+ const finalEvaluation = readFinalEvaluation(final);
438
+ const accepted = finalEvaluation?.status === 'valid' && finalEvaluation.meetsObjective !== false;
439
+ const reason = context.signal.aborted ? 'stopped'
440
+ : error ? searchEnd === 'train-outcome-unknown' ? searchEnd : finalStartedAt === null ? 'research-error' : 'final-error'
441
+ : !best ? 'no-valid-candidate'
442
+ : journalError ? 'trace-write-failed'
443
+ : !finalEvaluation || finalEvaluation.status === 'unknown' ? 'final-unconfirmed'
444
+ : finalEvaluation.status === 'rejected' ? 'final-rejected'
445
+ : !accepted ? 'objective-unmet'
446
+ : searchEnd;
447
+ const runtimeCleanup = close?.cleanup ?? initFailure?.cleanup ?? (runtimeAttempted ? 'pending' : 'complete');
448
+ const record = join(context.outputDir, 'research-result.json');
360
449
  const result = {
361
- runtimeId: runtime!?.id ?? null, budget, searchEnd,
362
- model: { provider: config.model.provider, id: config.model.model, usage: traceDirectory ? await modelUsage(traceDirectory, peers) : null, trace: runtimeReport?.modelTrace ?? null, cost: 'unknown' },
363
- peers,
364
- candidates: research.candidates(), best: best ?? null, selected: selected ?? null, final, journalError, error,
365
- record: join(context.outputDir, 'research-result.json'), judge: config.evaluator.evidence?.() ?? null,
366
- traceDirectory,
367
- cleanup: { runtime: close?.cleanup ?? 'pending', judge: judgeCleanup },
450
+ schemaVersion: 1, runId: context.runId, runtimeId: runtime!?.id ?? initFailure?.runtimeId ?? null, goal: config.goal, budget, searchEnd,
451
+ timing: { startingAt, workStartedAt, workEndedAt, finalStartedAt, finalEndedAt, cleanupStartedAt, completedAt: Date.now() },
452
+ executor: typeof config.executor === 'string' ? config.executor : config.executor.kind,
453
+ initial: { digest: context.initial.digest, files: context.initial.fileCount },
454
+ model: { provider: config.model.provider, id: config.model.model, usage, trace: runtimeReport?.modelTrace ?? null, cost: 'unknown' },
455
+ peers, candidates: research.candidates(), best: best ?? null, selected: selected ?? null, final, finalEvaluation: finalEvaluation ?? null, journalError, error,
456
+ record, judge: config.evaluator.evidence?.() ?? null, traceDirectory,
457
+ cleanup: { runtime: runtimeCleanup, judge: judgeCleanup, runtimePending: close?.pending ?? runtimeReport?.pending ?? [],
458
+ runtimeReceipt, runtimeInitializationDetails: initFailure?.details ?? null },
368
459
  };
369
460
  await mkdir(context.outputDir, { recursive: true, mode: 0o700 });
370
- await writeFile(result.record, JSON.stringify(result, null, 2) + '\n', { mode: 0o600 });
461
+ await writeFile(record + '.next', JSON.stringify(result, null, 2) + '\n', { mode: 0o600, flag: 'wx' });
462
+ await rename(record + '.next', record);
463
+ const outcome = context.signal.aborted ? 'cancelled' : error || !best || !accepted || journalError ? 'failed' : 'completed';
371
464
  return {
372
- outcome: context.signal.aborted ? 'cancelled' : error || !best || final === null || journalError ? 'failed' : 'completed',
373
- reason: error ? 'research-error' : !best ? 'no-valid-candidate' : journalError ? 'trace-write-failed' : searchEnd,
374
- result: encode(result),
375
- acceptance: encode({ status: best && final !== null && !error ? 'verified' : 'unverified', final }),
376
- artifacts: [...(selected ? [{ path: selected.path, sha256: selected.sha256 }] : []), { path: result.record } as HarnessJson],
377
- cleanup: { status: close?.cleanup === 'complete' && judgeCleanup === 'complete' ? 'complete' : 'pending', ...(close?.pending.length ? { pending: encode(close.pending) } : {}) },
465
+ outcome, reason, result: encode(result),
466
+ acceptance: encode({ status: outcome === 'completed' ? 'verified' : finalEvaluation?.status === 'rejected' || finalEvaluation?.meetsObjective === false
467
+ ? 'rejected' : 'unverified', final: finalEvaluation ?? null }),
468
+ artifacts: [...research.candidates().map(candidate => ({ path: candidate.path, sha256: candidate.sha256 })), { path: record }],
469
+ cleanup: { status: runtimeCleanup === 'complete' && judgeCleanup === 'complete' ? 'complete' : 'pending',
470
+ ...(close?.pending.length ? { pending: encode(close.pending) } : {}) },
378
471
  };
379
472
  },
380
473
  } satisfies Harness;
@@ -1,18 +1,35 @@
1
1
  import { createHash } from 'node:crypto';
2
2
  import { appendFileSync } from 'node:fs';
3
- import { mkdir, writeFile } from 'node:fs/promises';
3
+ import { mkdir, unlink, writeFile } from 'node:fs/promises';
4
4
  import { join } from 'node:path';
5
5
  import { inProcessService, type JsonValue, type Runtime, type ServiceInterface } from '@anyswarm/core';
6
6
 
7
7
  export const candidatePath = '.anyswarm-candidate.patch';
8
8
  const maxPatch = 1024 * 1024 - 1536;
9
9
  const patchChunk = 24 * 1024;
10
- const maxNotes = 512;
10
+ const maxMutations = 16_384;
11
11
 
12
12
  export interface Evaluation {
13
13
  valid: boolean;
14
14
  score: number | null;
15
15
  feedback: JsonValue;
16
+ payload?: { digest: string; size: number };
17
+ }
18
+
19
+ export type FinalEvaluation = {
20
+ status: 'valid' | 'rejected' | 'unknown';
21
+ score: number | null;
22
+ meetsObjective: boolean | null;
23
+ evidence: JsonValue;
24
+ };
25
+
26
+ export function readFinalEvaluation(value: JsonValue): FinalEvaluation | undefined {
27
+ if (!value || typeof value !== 'object' || Array.isArray(value) ||
28
+ !['valid', 'rejected', 'unknown'].includes(value.status as string) ||
29
+ (value.score !== null && (typeof value.score !== 'number' || !Number.isFinite(value.score))) ||
30
+ (value.meetsObjective !== null && typeof value.meetsObjective !== 'boolean') ||
31
+ value.evidence === undefined) return undefined;
32
+ return value as FinalEvaluation;
16
33
  }
17
34
 
18
35
  export interface Evaluator {
@@ -20,7 +37,7 @@ export interface Evaluator {
20
37
  close?(): Promise<'complete' | 'pending'>;
21
38
  evidence?(): JsonValue;
22
39
  train(candidate: Buffer, signal: AbortSignal, admitted: (reference: string | number) => void): Promise<Evaluation>;
23
- final(candidate: Buffer, signal: AbortSignal): Promise<JsonValue>;
40
+ final(candidate: Buffer, signal: AbortSignal): Promise<FinalEvaluation | JsonValue>;
24
41
  }
25
42
 
26
43
  export interface Candidate {
@@ -50,6 +67,8 @@ interface ResearchEvent {
50
67
  basedOnSha256?: string;
51
68
  score?: number | null;
52
69
  officialJob?: string | number;
70
+ payloadDigest?: string;
71
+ bytes?: number;
53
72
  label?: string;
54
73
  }
55
74
 
@@ -105,19 +124,41 @@ export function createResearch(options: {
105
124
  const claims = new Map<string, string>();
106
125
  let best: Candidate | undefined;
107
126
  let reserved = 0;
127
+ let nextCandidate = 0;
128
+ let storing = Promise.resolve();
129
+ const mutations = new Map<string, { fingerprint: string; receipt: Promise<JsonValue> }>();
108
130
  let closed = false;
109
131
  let stopReason: string | undefined;
110
132
  let queue = Promise.resolve();
111
133
  const project = (record: unknown) => record as JsonValue;
112
134
  const reached = (score: number, target: number) => options.direction === 'max' ? score >= target : score <= target;
113
135
  function event(operation: string, data: Omit<ResearchEvent, 'operation' | 'seq' | 'at' | 'type'> = {}) {
114
- const entry = { ...data, seq: events.length + 1, at: new Date().toISOString(), type: 'research' as const, operation };
136
+ const candidate = data.candidate && candidates.get(data.candidate);
137
+ const entry = { ...(candidate ? { sha256: candidate.sha256 } : {}), ...data, seq: events.length + 1, at: new Date().toISOString(), type: 'research' as const, operation };
115
138
  events.push(entry);
116
139
  options.traceEvent(entry);
117
140
  options.statusChanged();
118
141
  }
119
142
  function admit() {
120
- if (closed || stopReason || options.signal.aborted || events.length >= maxNotes) throw new Error('Research admissions are closed');
143
+ if (closed || stopReason || options.signal.aborted) throw new Error('Research admissions are closed');
144
+ }
145
+ type Handler = Parameters<typeof inProcessService>[1][string];
146
+ function mutation(operation: string, handler: Handler): Handler {
147
+ return (input, context) => {
148
+ context.assertAuthorized();
149
+ const key = JSON.stringify([context.caller.agentId, context.envelope.operation_id]);
150
+ const payload = input as Record<string, JsonValue>;
151
+ const fingerprint = JSON.stringify([operation, Object.entries(payload).sort(([left], [right]) => left.localeCompare(right))]);
152
+ const entry = mutations.get(key);
153
+ if (entry) {
154
+ if (entry.fingerprint !== fingerprint) throw new Error('Operation ID already identifies a different research action');
155
+ return entry.receipt;
156
+ }
157
+ if (mutations.size >= maxMutations) throw new Error('Research mutation receipt limit reached');
158
+ const receipt = Promise.resolve().then(() => handler(input, context));
159
+ mutations.set(key, { fingerprint, receipt });
160
+ return receipt;
161
+ };
121
162
  }
122
163
  function state() {
123
164
  return {
@@ -148,7 +189,8 @@ export function createResearch(options: {
148
189
  }));
149
190
  candidate.evaluation = evaluation;
150
191
  candidate.state = validScore(evaluation) ? 'scored' : 'invalid';
151
- event('train.returned', { agentId: candidate.agentId, candidate: candidate.id, score: evaluation.score });
192
+ event('train.returned', { agentId: candidate.agentId, candidate: candidate.id, score: evaluation.score,
193
+ officialJob: candidate.officialJob, payloadDigest: evaluation.payload?.digest });
152
194
  if (validScore(evaluation) && (!best || (evaluation.score !== best.evaluation!.score && reached(evaluation.score!, best.evaluation!.score!)))) {
153
195
  best = candidate;
154
196
  event('candidate.best', { agentId: candidate.agentId, candidate: candidate.id, score: evaluation.score });
@@ -173,7 +215,7 @@ export function createResearch(options: {
173
215
  candidates: [...candidates.values()].slice(-8).map(({ path: _, ...candidate }) => candidate),
174
216
  });
175
217
  },
176
- claim: (input, { caller, assertAuthorized }) => {
218
+ claim: mutation('claim', (input, { caller, assertAuthorized }) => {
177
219
  assertAuthorized();
178
220
  admit();
179
221
  const direction = (input as { direction: string }).direction.trim();
@@ -184,8 +226,8 @@ export function createResearch(options: {
184
226
  claims.set(key, caller.agentId);
185
227
  event('peer.claim', { agentId: caller.agentId, detail: direction });
186
228
  return { claimed: true, agentId: caller.agentId };
187
- },
188
- publish: (input, { caller, assertAuthorized }) => {
229
+ }),
230
+ publish: mutation('publish', (input, { caller, assertAuthorized }) => {
189
231
  assertAuthorized();
190
232
  admit();
191
233
  const { kind, summary, candidate } = input as { kind: 'finding' | 'review'; summary: string; candidate?: string };
@@ -197,15 +239,15 @@ export function createResearch(options: {
197
239
  event(`peer.${kind}`, { agentId: caller.agentId, detail: summary,
198
240
  ...(reviewed ? { candidate: reviewed.id, sha256: reviewed.sha256 } : {}) });
199
241
  return { published: true };
200
- },
201
- message: (input, { caller, assertAuthorized }) => {
242
+ }),
243
+ message: mutation('message', (input, { caller, assertAuthorized }) => {
202
244
  assertAuthorized();
203
245
  admit();
204
246
  const { peer, summary } = input as { peer: string; summary: string };
205
247
  if (peer === caller.agentId || !peers.has(peer)) throw new Error('Peer does not belong to this Run');
206
248
  event('peer.message', { agentId: caller.agentId, to: peer, detail: summary });
207
249
  return { sent: true };
208
- },
250
+ }),
209
251
  read_patch: (input, { caller, assertAuthorized }) => {
210
252
  assertAuthorized();
211
253
  admit();
@@ -225,42 +267,50 @@ export function createResearch(options: {
225
267
  }
226
268
  return { candidate, sha256, data: bytes.subarray(start, end).toString('base64'), nextOffset: end < bytes.length ? end : null };
227
269
  },
228
- submit: async (input, { caller, envelope, assertAuthorized }) => {
270
+ submit: mutation('submit', async (input, { caller, envelope, assertAuthorized }) => {
229
271
  assertAuthorized();
230
272
  admit();
231
273
  const { summary, basedOn } = input as { summary: string; basedOn?: string };
232
- if (basedOn && !readEntirePatch(caller.agentId, basedOn)) throw new Error('Read the referenced candidate before building on it');
274
+ const parent = basedOn ? candidates.get(basedOn) : undefined;
275
+ if (basedOn && (!parent || parent.agentId === caller.agentId || !readEntirePatch(caller.agentId, basedOn))) {
276
+ throw new Error('Read the referenced peer candidate before building on it');
277
+ }
233
278
  const bytes = await options.readPatch(caller.agentId, envelope.operation_id);
234
- assertAuthorized();
235
- admit();
236
279
  if (!bytes.length || bytes.length > maxPatch) throw new Error('Candidate patch is empty or exceeds the size limit');
237
280
  const sha256 = createHash('sha256').update(bytes).digest('hex');
238
- const previous = known.get(sha256);
239
- if (previous) return { candidate: previous.id, status: previous.state, duplicate: true, sha256 };
240
- if (reserved >= options.maxEvaluations) throw new Error('Shared evaluation budget is exhausted');
241
- reserved++;
242
- const id = `candidate-${reserved}`;
243
- const path = join(options.outputDir, 'candidates', `${id}.patch`);
244
- const candidate: Candidate = { id, agentId: caller.agentId, summary, basedOn: basedOn ?? null, path,
245
- sha256, bytes: bytes.length, state: 'queued' };
246
- known.set(sha256, candidate);
247
- try {
248
- await mkdir(join(options.outputDir, 'candidates'), { recursive: true, mode: 0o700 });
249
- await writeFile(path, bytes, { mode: 0o600, flag: 'wx' });
281
+ // Serialize the host file commit and quota admission, once the private
282
+ // workspace snapshot is available. No duplicate can observe a half write.
283
+ const result = storing.then(async () => {
250
284
  assertAuthorized();
251
285
  admit();
252
- } catch (error) {
253
- candidate.state = 'cancelled';
286
+ const previous = known.get(sha256);
287
+ if (previous) return { candidate: previous.id, status: previous.state, duplicate: true, sha256 };
288
+ if (reserved >= options.maxEvaluations) throw new Error('Shared evaluation budget is exhausted');
289
+ const id = `candidate-${++nextCandidate}`;
290
+ const path = join(options.outputDir, 'candidates', `${id}.patch`);
291
+ const candidate: Candidate = { id, agentId: caller.agentId, summary, basedOn: basedOn ?? null, path,
292
+ sha256, bytes: bytes.length, state: 'queued' };
293
+ await mkdir(join(options.outputDir, 'candidates'), { recursive: true, mode: 0o700 });
294
+ await writeFile(path, bytes, { mode: 0o600, flag: 'wx' });
295
+ try {
296
+ assertAuthorized();
297
+ admit();
298
+ } catch (error) {
299
+ await unlink(path);
300
+ throw error;
301
+ }
302
+ reserved++;
303
+ known.set(sha256, candidate);
304
+ patches.set(id, bytes);
254
305
  candidates.set(id, candidate);
255
- throw error;
256
- }
257
- patches.set(id, bytes);
258
- candidates.set(id, candidate);
259
- event(basedOn ? 'candidate.built-on' : 'candidate.queued', { agentId: caller.agentId, candidate: id, sha256, detail: summary,
260
- ...(basedOn ? { basedOn, basedOnSha256: candidates.get(basedOn)!.sha256 } : {}) });
261
- queue = queue.then(() => evaluate(candidate, bytes));
262
- return { candidate: id, status: candidate.state, duplicate: false, sha256 };
263
- },
306
+ event(parent ? 'candidate.built-on' : 'candidate.queued', { agentId: caller.agentId, candidate: id, sha256, bytes: bytes.length, detail: summary,
307
+ ...(parent ? { basedOn, basedOnSha256: parent.sha256 } : {}) });
308
+ queue = queue.then(() => evaluate(candidate, bytes));
309
+ return { candidate: id, status: 'queued', duplicate: false, sha256 };
310
+ });
311
+ storing = result.then(() => {}, () => {});
312
+ return result;
313
+ }),
264
314
  }, {
265
315
  readState: () => ({
266
316
  state: project(state()), capturedAt: new Date().toISOString(), revision: String(events.length),
@@ -277,10 +327,10 @@ export function createResearch(options: {
277
327
  addPeer: (id: string, label: string) => { peers.set(id, label); event('peer.ready', { agentId: id, label }); },
278
328
  close: () => { closed = true; },
279
329
  stopReason: () => stopReason,
280
- drained: () => queue,
330
+ drained: async () => { await storing; await queue; },
281
331
  best: () => best,
282
332
  peerLabel: (agentId: string) => peers.get(agentId),
283
- selection: () => best ?? [...candidates.values()].find(candidate => candidate.state === 'invalid'),
333
+ selection: () => best,
284
334
  patch: (candidate: Candidate) => Buffer.from(patches.get(candidate.id)!),
285
335
  candidates: () => [...candidates.values()],
286
336
  };
@@ -0,0 +1,25 @@
1
+ # Editing this Harness
2
+
3
+ This is consumer-owned source exported from AnySwarm. Use the public
4
+ `@anyswarm/core` entry and the SDK recorded in `anyswarm-source.json`; run `npm
5
+ install` here and use `npm run start` or `npm exec -- anyswarm`. Keep imports local
6
+ to this project or to declared dependencies.
7
+
8
+ - `config.ts` owns the connection, selected executor/model, shared model-request
9
+ limit and foreground channel. Explicit `--config ./custom.ts` replaces this
10
+ configuration; start from its exported defaults when changing one setting.
11
+ - `harness.ts` owns the two Profiles, turn order and completion checks.
12
+ `context.runWithRuntime` owns close/report classification; `runInput` waits for
13
+ each exclusive Agent turn. Keep business verification outside `afterClose`.
14
+ - `handoff.ts` owns the Service contract and authenticated caller evidence.
15
+ The publisher may publish; the writer may take. Preserve request IDs and the
16
+ fresh publisher-only reference when changing the exercise.
17
+ - Default foreground execution must finish without a question. `session.ts`
18
+ deliberately enables questions for the SDK/RPC extension.
19
+ - Check both sandbox and exported `delivery.txt` bytes, including final newlines.
20
+ Keep business acceptance, artifact export and cleanup separate. Preserve the
21
+ original pending resources and receipts instead of inventing success after a
22
+ timeout or missing export.
23
+
24
+ Make the smallest change needed for the user's task, keep credentials in trusted
25
+ configuration, and update this project's README when its commands or checks change.