@evomap/evolver-cli 2.0.0-beta.9 → 2.0.1

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 (87) hide show
  1. package/dist/antiGeneBenchmark.js +2 -0
  2. package/dist/antiGeneRollout.js +9 -3
  3. package/dist/assetHealth.js +2 -0
  4. package/dist/assetTrust.js +14 -1
  5. package/dist/atp.d.ts +10 -5
  6. package/dist/atp.js +119 -26
  7. package/dist/atpAutoBuyer.d.ts +120 -0
  8. package/dist/atpAutoBuyer.js +814 -0
  9. package/dist/atpAutoDeliver.js +2 -2
  10. package/dist/autoDistillLlm.js +2 -1
  11. package/dist/autoDistillTranscript.js +3 -2
  12. package/dist/autoexec.d.ts +101 -13
  13. package/dist/autoexec.js +794 -91
  14. package/dist/cli.js +13 -0
  15. package/dist/cliContracts.d.ts +23 -2
  16. package/dist/cliContracts.js +504 -54
  17. package/dist/commands.d.ts +1 -0
  18. package/dist/commands.js +1 -0
  19. package/dist/curriculumCapabilityGaps.d.ts +6 -0
  20. package/dist/curriculumCapabilityGaps.js +24 -0
  21. package/dist/cycleConsumer.d.ts +13 -0
  22. package/dist/cycleConsumer.js +186 -20
  23. package/dist/dashboard.js +47 -9
  24. package/dist/dispatch.js +8 -2
  25. package/dist/distillPrimitives.d.ts +3 -2
  26. package/dist/distillPrimitives.js +80 -12
  27. package/dist/doctor.js +120 -11
  28. package/dist/identityHome.d.ts +9 -0
  29. package/dist/identityHome.js +47 -0
  30. package/dist/index.d.ts +70 -40
  31. package/dist/index.js +581 -193
  32. package/dist/learningTrace.d.ts +15 -0
  33. package/dist/learningTrace.js +73 -0
  34. package/dist/lifecycle.d.ts +67 -1
  35. package/dist/lifecycle.js +738 -44
  36. package/dist/localMemoryGraph.d.ts +90 -3
  37. package/dist/localMemoryGraph.js +2031 -231
  38. package/dist/login.d.ts +1 -1
  39. package/dist/login.js +3 -3
  40. package/dist/materialSnapshot.d.ts +9 -1
  41. package/dist/materialSnapshot.js +23 -6
  42. package/dist/memoryGraphOps.d.ts +8 -0
  43. package/dist/memoryGraphOps.js +140 -0
  44. package/dist/migrate/assetFormatMap.d.ts +61 -0
  45. package/dist/migrate/assetFormatMap.js +53 -0
  46. package/dist/migrate/envTranslate.d.ts +26 -0
  47. package/dist/migrate/envTranslate.js +147 -0
  48. package/dist/migrate/fieldMap.d.ts +4 -2
  49. package/dist/migrate/fieldMap.js +9 -5
  50. package/dist/migrate/oauthImport.d.ts +66 -0
  51. package/dist/migrate/oauthImport.js +667 -0
  52. package/dist/migrate/v1Import.d.ts +92 -1
  53. package/dist/migrate/v1Import.js +1481 -141
  54. package/dist/promptRecallHook.d.ts +24 -0
  55. package/dist/promptRecallHook.js +425 -0
  56. package/dist/recallVerifyReport.d.ts +37 -0
  57. package/dist/recallVerifyReport.js +244 -0
  58. package/dist/recipe.d.ts +7 -1
  59. package/dist/recipe.js +426 -56
  60. package/dist/requiredSandboxValidation.d.ts +5 -0
  61. package/dist/requiredSandboxValidation.js +4 -0
  62. package/dist/reuse.d.ts +9 -0
  63. package/dist/reuse.js +151 -56
  64. package/dist/runtimeCapabilities.js +15 -15
  65. package/dist/runtimeSessionSource.d.ts +3 -2
  66. package/dist/runtimeSessionSource.js +63 -11
  67. package/dist/selectionPolicyConfig.d.ts +8 -0
  68. package/dist/selectionPolicyConfig.js +18 -0
  69. package/dist/semanticIdfConfig.d.ts +2 -0
  70. package/dist/semanticIdfConfig.js +4 -0
  71. package/dist/sessionIngest.d.ts +37 -0
  72. package/dist/sessionIngest.js +156 -0
  73. package/dist/setupHooks.js +95 -1
  74. package/dist/skill2gep.d.ts +13 -9
  75. package/dist/skill2gep.js +42 -30
  76. package/dist/skillDistill.d.ts +8 -4
  77. package/dist/skillDistill.js +38 -9
  78. package/dist/solo/mode.js +1 -0
  79. package/dist/sync.d.ts +12 -0
  80. package/dist/sync.js +1246 -151
  81. package/dist/thesis.d.ts +1 -1
  82. package/dist/thesis.js +20 -3
  83. package/dist/trajectoryExport.js +21 -3
  84. package/dist/v1Compat.d.ts +1 -0
  85. package/dist/v1Compat.js +9 -0
  86. package/dist/workflowRuntime.js +24 -18
  87. package/package.json +11 -8
@@ -2,6 +2,7 @@ import { mkdtempSync, readFileSync } from 'node:fs';
2
2
  import { tmpdir } from 'node:os';
3
3
  import { join, resolve } from 'node:path';
4
4
  import { assetstore, benchmark, events } from '@evomap/evolver-core';
5
+ import { semanticIdfEnabled } from './semanticIdfConfig.js';
5
6
  const usage = '用法: evolver anti-gene-benchmark --suite <file> [--assets <dir>] [--review-dir <dir>] [--events <file>] [--json] [--min-samples N] [--min-failure-delta D]\n'
6
7
  + ' 或: evolver anti-gene-benchmark --report <events-file> [--json]\n';
7
8
  function parseFlags(argv) {
@@ -172,6 +173,7 @@ export async function runAntiGeneBenchmarkCommand(argv, deps = {}) {
172
173
  const report = await benchmark.runAntiGeneBenchmark(suite, { store, review }, {
173
174
  eventsPath,
174
175
  now: deps.now,
176
+ ...(!semanticIdfEnabled() ? { disableSemanticIdf: true } : {}),
175
177
  ...(flags.minSamples !== undefined ? { minSamples: flags.minSamples } : {}),
176
178
  ...(flags.minFailureDelta !== undefined ? { minFailureDelta: flags.minFailureDelta } : {}),
177
179
  });
@@ -3,7 +3,8 @@ import { tmpdir } from 'node:os';
3
3
  import { join, resolve } from 'node:path';
4
4
  import { spawn } from 'node:child_process';
5
5
  import { assetstore, benchmark, events, exec } from '@evomap/evolver-core';
6
- const usage = '用法: evolver anti-gene-rollout --suite <file> --repo <path> [--assets <dir>] [--review-dir <dir>] [--events <file>] [--runner claude|codex] [--json] [--min-samples N] [--min-failure-delta D]\n'
6
+ import { semanticIdfEnabled } from './semanticIdfConfig.js';
7
+ const usage = '用法: evolver anti-gene-rollout --suite <file> --repo <path> [--assets <dir>] [--review-dir <dir>] [--events <file>] [--runner claude|codex|gemini] [--json] [--min-samples N] [--min-failure-delta D]\n'
7
8
  + ' 或: evolver anti-gene-rollout --report <events-file> [--json]\n';
8
9
  function parseFlags(argv) {
9
10
  const out = { json: false };
@@ -247,8 +248,8 @@ export async function runAntiGeneRolloutCommand(argv, deps = {}) {
247
248
  process.stderr.write('anti-gene-rollout: --min-failure-delta must be >= 0\n');
248
249
  return 1;
249
250
  }
250
- if (flags.runner !== undefined && flags.runner !== 'claude' && flags.runner !== 'codex') {
251
- process.stderr.write('anti-gene-rollout: --runner must be claude or codex\n');
251
+ if (flags.runner !== undefined && flags.runner !== 'claude' && flags.runner !== 'codex' && flags.runner !== 'gemini') {
252
+ process.stderr.write('anti-gene-rollout: --runner must be claude, codex, or gemini\n');
252
253
  return 1;
253
254
  }
254
255
  let suite;
@@ -268,6 +269,10 @@ export async function runAntiGeneRolloutCommand(argv, deps = {}) {
268
269
  process.stderr.write('anti-gene-rollout: live rollout requires a non-empty suite.validation[] external verifier; refusing to trust agent self-report\n');
269
270
  return 1;
270
271
  }
272
+ if (!injected && !deps.agent && flags.runner !== 'gemini') {
273
+ process.stderr.write('anti-gene-rollout: execute capability is unsupported for built-in Claude/Codex; select --runner gemini or inject an externally sandboxed agent\n');
274
+ return 1;
275
+ }
271
276
  const assetsDir = flags.assets ? resolve(flags.assets) : events.assetsDir();
272
277
  const reviewDir = flags.reviewDir ? resolve(flags.reviewDir) : assetsDir;
273
278
  const store = deps.store ?? new assetstore.LocalJsonlProvider(assetsDir);
@@ -277,6 +282,7 @@ export async function runAntiGeneRolloutCommand(argv, deps = {}) {
277
282
  const report = await benchmark.runAntiGeneRollout(suite, { store, review, makeExecute }, {
278
283
  eventsPath,
279
284
  now: deps.now,
285
+ ...(!semanticIdfEnabled() ? { disableSemanticIdf: true } : {}),
280
286
  ...(flags.minSamples !== undefined ? { minSamples: flags.minSamples } : {}),
281
287
  ...(flags.minFailureDelta !== undefined ? { minFailureDelta: flags.minFailureDelta } : {}),
282
288
  });
@@ -18,6 +18,7 @@ function renderText(report, stdout) {
18
18
  `corrupt=${report.totals.corruptRows}`,
19
19
  `duplicate=${report.totals.duplicateRows}`,
20
20
  `hash_mismatch=${report.totals.hashMismatchRows}`,
21
+ `unverified=${report.totals.unverifiedRows}`,
21
22
  `schema_invalid=${report.totals.schemaInvalidRows}`,
22
23
  `unsafe=${report.totals.unsafeFiles}`,
23
24
  `unavailable=${report.totals.unavailableFiles}`,
@@ -32,6 +33,7 @@ function renderText(report, stdout) {
32
33
  `corrupt=${file.corruptRows}`,
33
34
  `duplicate=${file.duplicateRows}`,
34
35
  `hash_mismatch=${file.hashMismatchRows}`,
36
+ `unverified=${file.unverifiedRows}`,
35
37
  `schema_invalid=${file.schemaInvalidRows}`,
36
38
  ...(file.unterminated ? ['unterminated=true'] : []),
37
39
  ...(file.reason ? [`reason=${file.reason}`] : []),
@@ -194,7 +194,20 @@ export async function runAssetTrustCommand(argv, deps = {}) {
194
194
  return parseFailure('unsafe_reason', parsed.json, stdout, stderr);
195
195
  const actorId = safeActorId(env);
196
196
  const desiredTrust = parsed.action === 'promote';
197
- const change = provenance.changeTrust(asset.asset_id, desiredTrust, actorId, reason);
197
+ let change;
198
+ try {
199
+ change = provenance.changeTrust(asset.asset_id, desiredTrust, actorId, reason);
200
+ }
201
+ catch (error) {
202
+ if (error instanceof assetstore.ProvenanceWritePendingError) {
203
+ if (parsed.json)
204
+ writeJson(stdout, { ok: false, group: GROUP, reason: 'asset_write_pending' });
205
+ else
206
+ stderr('[asset-trust] asset_write_pending\n');
207
+ return 1;
208
+ }
209
+ throw error;
210
+ }
198
211
  const view = viewFor(asset, change.record, env);
199
212
  const ingestor = deps.ingestor ?? new events.Ingestor({ path: events.rootEventsPath() });
200
213
  const auditEventRecorded = change.changed
package/dist/atp.d.ts CHANGED
@@ -28,9 +28,13 @@ export interface VerifyOptions {
28
28
  orderId: string;
29
29
  action: AtpVerifyAction;
30
30
  }
31
- export interface AtpOptions {
31
+ export type AtpOptions = {
32
32
  sub: 'enable' | 'disable' | 'status';
33
- }
33
+ } | {
34
+ sub: 'resolve';
35
+ reservationId: string;
36
+ outcome: 'success' | 'failure';
37
+ };
34
38
  export interface AtpCliDeps {
35
39
  client?: AtpCliClient;
36
40
  env?: NodeJS.ProcessEnv;
@@ -38,6 +42,7 @@ export interface AtpCliDeps {
38
42
  err?: LogFn;
39
43
  sleep?: (ms: number) => Promise<void>;
40
44
  consentPath?: string;
45
+ autoBuyerLedgerPath?: string;
41
46
  now?: () => Date;
42
47
  }
43
48
  export interface AtpCliClient {
@@ -81,6 +86,7 @@ export declare function runOrdersCommand(argv: readonly string[]): Promise<numbe
81
86
  export declare function runVerifyCommand(argv: readonly string[]): Promise<number>;
82
87
  export declare function runAtpCommand(argv: readonly string[]): Promise<number>;
83
88
  export declare function createAtpClientFromEnv(env?: NodeJS.ProcessEnv): AtpHubClient;
89
+ export { resolveIdentityHome as resolveAtpIdentityHome } from './identityHome.js';
84
90
  export declare function resolveAtpHome(env?: NodeJS.ProcessEnv): string;
85
91
  export declare function atpConsentPath(env?: NodeJS.ProcessEnv): string;
86
92
  export declare function getAtpConsent(env?: NodeJS.ProcessEnv, ackPath?: string): AtpConsent;
@@ -92,7 +98,7 @@ export declare class AtpSpendConsentError extends Error {
92
98
  /**
93
99
  * THE single enforced consent gate every ATP spend path MUST pass through (#177). One door, two callers:
94
100
  * - explicit (a human ran `evolver buy`) → the invocation IS the consent, allowed through.
95
- * - autonomous (future auto-buy / autoexec auto-order / swarm purchase) → must have getAtpConsent().enabled,
101
+ * - autonomous (auto-buy / autoexec auto-order / swarm purchase) → must have getAtpConsent().enabled,
96
102
  * else refused. This keeps consent enforcement UPSTREAM of money movement instead of a read-only status bit
97
103
  * each caller might forget to check (the latent money-safety hole autogame-17 flagged). Any new autonomous
98
104
  * spending path is required to call this (NOT client.placeOrder directly) — see placeAtpOrderWithConsent.
@@ -118,5 +124,4 @@ export declare function setAtpConsent(enabled: boolean, ackPath?: string, now?:
118
124
  version: 1;
119
125
  };
120
126
  export declare function resolveAtpSenderId(env?: NodeJS.ProcessEnv): string | undefined;
121
- export declare function printAtpUsage(): string;
122
- export {};
127
+ export declare function printAtpUsage(): string;
package/dist/atp.js CHANGED
@@ -1,8 +1,10 @@
1
- import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
1
+ import { randomUUID } from 'node:crypto';
2
+ import { existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
2
3
  import { homedir } from 'node:os';
3
- import { dirname, join } from 'node:path';
4
- import { events, mailbox } from '@evomap/evolver-core';
4
+ import { dirname, join, resolve } from 'node:path';
5
+ import { mailbox } from '@evomap/evolver-core';
5
6
  import { loadEnvFileFromEnv } from '@evomap/evolver-mcp';
7
+ import { resolveExplicitNodeCredentials, resolveIdentityHome } from './identityHome.js';
6
8
  import { AtpHubClient, ATP_PROOF_STATUSES, ATP_ROLES, ATP_ROUTING_MODES, ATP_VERIFY_ACTIONS, ATP_VERIFY_MODES, connectPublicHub, globalFetchLike, resolveHubUrl, } from '@evomap/evolver-adapter-public';
7
9
  export function parseBuyArgs(args) {
8
10
  if (args.length === 0)
@@ -60,8 +62,19 @@ export function parseVerifyArgs(args) {
60
62
  }
61
63
  export function parseAtpArgs(args) {
62
64
  const sub = firstPositional(args)?.toLowerCase();
65
+ if (sub === 'resolve') {
66
+ const positionals = args.filter((arg) => !arg.startsWith('--'));
67
+ const reservationId = positionals[1];
68
+ const outcome = parseNamed(args, '--outcome');
69
+ if (!reservationId)
70
+ return { ok: false, error: 'atp resolve requires <reservationId>' };
71
+ if (outcome !== 'success' && outcome !== 'failure') {
72
+ return { ok: false, error: 'atp resolve requires --outcome=success|failure' };
73
+ }
74
+ return { ok: true, opts: { sub, reservationId, outcome } };
75
+ }
63
76
  if (sub !== 'enable' && sub !== 'disable' && sub !== 'status') {
64
- return { ok: false, error: `atp subcommand must be enable|disable|status (got: ${sub ?? '-'})` };
77
+ return { ok: false, error: `atp subcommand must be enable|disable|status|resolve (got: ${sub ?? '-'})` };
65
78
  }
66
79
  return { ok: true, opts: { sub } };
67
80
  }
@@ -175,18 +188,61 @@ export async function runAtp(opts, deps = {}) {
175
188
  const env = deps.env ?? process.env;
176
189
  const log = deps.log ?? ((s) => process.stdout.write(`${s}\n`));
177
190
  const err = deps.err ?? ((s) => process.stderr.write(`${s}\n`));
178
- const ackPath = deps.consentPath ?? atpConsentPath(env);
179
191
  try {
192
+ const envFile = loadEnvFileFromEnv(env);
193
+ if (envFile.error && opts.sub !== 'disable') {
194
+ err('[ATP] atp command error: env_file_unavailable');
195
+ return { exitCode: 1, error: 'env_file_unavailable' };
196
+ }
197
+ if (envFile.error) {
198
+ err('[ATP] WARNING: env_file_unavailable; applying fail-safe local disable.');
199
+ }
200
+ const ackPath = deps.consentPath ?? atpConsentPath(env);
201
+ const dailyCap = boundedAtpCap(env['ATP_AUTOBUY_DAILY_CAP_CREDITS'], 50);
202
+ const perOrderCap = boundedAtpCap(env['ATP_AUTOBUY_PER_ORDER_CAP_CREDITS'], 10);
180
203
  if (opts.sub === 'status') {
181
204
  const consent = getAtpConsent(env, ackPath);
205
+ const autoBuyer = await import('./atpAutoBuyer.js');
206
+ const ledgerPath = deps.autoBuyerLedgerPath ?? autoBuyer.resolveAtpAutoBuyerLedgerPath(env, ackPath);
207
+ const ledger = existsSync(ledgerPath) ? autoBuyer.readAtpAutoBuyerLedger(ledgerPath) : undefined;
208
+ const reservations = ledger ? Object.values(ledger.reservations) : [];
182
209
  log(`[ATP] auto-spend: ${consent.enabled ? 'ENABLED' : 'DISABLED'} (source: ${consent.source})`);
183
210
  log(` ack file: ${consent.ackPath}`);
184
- return { exitCode: 0, data: consent };
211
+ log(` Caps: daily=${dailyCap}, per-order=${perOrderCap} credits`);
212
+ log(` Unresolved reservations: ${reservations.length}`);
213
+ for (const reservation of reservations) {
214
+ const recoveryDeadline = reservation.resolveAfter === undefined
215
+ ? ''
216
+ : ` resolve-after=${new Date(reservation.resolveAfter).toISOString()}`;
217
+ log(` ${reservation.id} state=${reservation.state} budget=${reservation.budget} hash=${reservation.hash} created=${new Date(reservation.createdAt).toISOString()}${recoveryDeadline}`);
218
+ }
219
+ return { exitCode: 0, data: { ...consent, reservations } };
220
+ }
221
+ if (opts.sub === 'resolve') {
222
+ const autoBuyer = await import('./atpAutoBuyer.js');
223
+ const ledgerPath = deps.autoBuyerLedgerPath ?? autoBuyer.resolveAtpAutoBuyerLedgerPath(env, ackPath);
224
+ const buyer = new autoBuyer.AtpAutoBuyer({
225
+ client: { placeOrder: async () => ({ ok: false, error: 'operator_only_client' }) },
226
+ ledgerPath,
227
+ env,
228
+ consentPath: ackPath,
229
+ now: () => (deps.now ?? (() => new Date()))().getTime(),
230
+ });
231
+ if (!buyer.resolveReservation(opts.reservationId, opts.outcome)) {
232
+ err('[ATP] reservation not found or its recovery/transport-settle deadline is still active. No ledger state changed.');
233
+ return { exitCode: 1, error: 'reservation_not_found' };
234
+ }
235
+ const capNote = opts.outcome === 'failure'
236
+ ? ' Ambiguous budget remains charged against the original day cap.'
237
+ : '';
238
+ log(`[ATP] reservation ${opts.reservationId} resolved as ${opts.outcome}; operator decision recorded in the bounded ledger audit.${capNote}`);
239
+ return { exitCode: 0, data: { reservationId: opts.reservationId, outcome: opts.outcome } };
185
240
  }
186
241
  const enabled = opts.sub === 'enable';
187
242
  const body = setAtpConsent(enabled, ackPath, deps.now ?? (() => new Date()));
188
243
  log(`[ATP] auto-spend ${enabled ? 'ENABLED' : 'DISABLED'} (consent recorded ${body.acknowledged_at}).`);
189
- log(' Manual `evolver buy` orders are unaffected; this ack is for future auto-buyer wiring.');
244
+ log(` Caps: daily=${dailyCap}, per-order=${perOrderCap} credits`);
245
+ log(' Manual `evolver buy` orders are unaffected; this consent gates the autoexec capability-gap auto-buyer.');
190
246
  const override = envOverride(env);
191
247
  if (override !== null && override !== enabled) {
192
248
  const label = override ? 'on' : 'off';
@@ -202,6 +258,12 @@ export async function runAtp(opts, deps = {}) {
202
258
  return { exitCode: 1, error: msg };
203
259
  }
204
260
  }
261
+ function boundedAtpCap(value, fallback) {
262
+ const parsed = typeof value === 'string' && value.trim().length > 0 ? Number(value) : undefined;
263
+ return typeof parsed === 'number' && Number.isSafeInteger(Math.floor(parsed)) && parsed >= 0
264
+ ? Math.floor(parsed)
265
+ : fallback;
266
+ }
205
267
  export async function runBuyCommand(argv) {
206
268
  const parsed = parseBuyArgs(argv);
207
269
  if (!parsed.ok)
@@ -229,17 +291,25 @@ export async function runAtpCommand(argv) {
229
291
  export function createAtpClientFromEnv(env = process.env) {
230
292
  loadEnvFileFromEnv(env);
231
293
  const hubUrl = resolveHubUrl(env);
232
- const evomapDir = resolveAtpHome(env);
233
- const resolvedSenderId = resolveAtpSenderId(env);
294
+ const evomapDir = resolveIdentityHome(env);
295
+ const explicitCredentials = resolveExplicitNodeCredentials(env);
296
+ const { nodeSecret } = explicitCredentials;
297
+ const resolvedSenderId = nodeSecret
298
+ ? explicitCredentials.senderId ?? resolveAtpSenderId(env)
299
+ : resolveAtpSenderId(env);
234
300
  const senderId = () => resolvedSenderId;
235
- const nodeSecret = env['EVOMAP_NODE_SECRET']?.trim();
236
301
  const connected = nodeSecret
237
302
  ? connectPublicHub({ hubUrl, authMode: 'legacy', evomapDir, nodeSecret, senderId })
238
303
  : connectPublicHub({ hubUrl, authMode: 'oauth', evomapDir, senderId });
239
304
  return new AtpHubClient({ baseUrl: hubUrl, auth: connected.auth, fetchFn: globalFetchLike, senderId });
240
305
  }
306
+ export { resolveIdentityHome as resolveAtpIdentityHome } from './identityHome.js';
241
307
  export function resolveAtpHome(env = process.env) {
242
- return env['EVOMAP_DIR'] ?? env['EVOLVER_HOME'] ?? env['EVOMAP_HOME'] ?? events.evomapHome();
308
+ const configured = [env['EVOMAP_DIR'], env['EVOLVER_HOME'], env['EVOMAP_HOME']]
309
+ .map((value) => value?.trim())
310
+ .find((value) => Boolean(value));
311
+ const home = env['HOME']?.trim();
312
+ return configured ?? join(home || homedir(), '.evomap');
243
313
  }
244
314
  export function atpConsentPath(env = process.env) {
245
315
  return join(resolveAtpHome(env), 'evolution', 'atp-autobuy-ack.json');
@@ -265,7 +335,7 @@ export class AtpSpendConsentError extends Error {
265
335
  /**
266
336
  * THE single enforced consent gate every ATP spend path MUST pass through (#177). One door, two callers:
267
337
  * - explicit (a human ran `evolver buy`) → the invocation IS the consent, allowed through.
268
- * - autonomous (future auto-buy / autoexec auto-order / swarm purchase) → must have getAtpConsent().enabled,
338
+ * - autonomous (auto-buy / autoexec auto-order / swarm purchase) → must have getAtpConsent().enabled,
269
339
  * else refused. This keeps consent enforcement UPSTREAM of money movement instead of a read-only status bit
270
340
  * each caller might forget to check (the latent money-safety hole autogame-17 flagged). Any new autonomous
271
341
  * spending path is required to call this (NOT client.placeOrder directly) — see placeAtpOrderWithConsent.
@@ -290,15 +360,37 @@ export async function placeAtpOrderWithConsent(client, order, consent = {}) {
290
360
  export function setAtpConsent(enabled, ackPath = atpConsentPath(), now = () => new Date()) {
291
361
  const body = { enabled, acknowledged_at: now().toISOString(), version: 1 };
292
362
  mkdirSync(dirname(ackPath), { recursive: true });
293
- const tmp = `${ackPath}.tmp`;
294
- writeFileSync(tmp, JSON.stringify(body, null, 2));
295
- renameSync(tmp, ackPath);
363
+ const tmp = `${ackPath}.${randomUUID()}.tmp`;
364
+ try {
365
+ writeFileSync(tmp, JSON.stringify(body, null, 2), { encoding: 'utf8', flag: 'wx', mode: 0o600 });
366
+ renameSync(tmp, ackPath);
367
+ }
368
+ finally {
369
+ rmSync(tmp, { force: true });
370
+ }
296
371
  return body;
297
372
  }
298
373
  export function resolveAtpSenderId(env = process.env) {
299
- const direct = env['EVOMAP_NODE_ID']?.trim();
300
- if (direct)
301
- return direct;
374
+ const evomapNodeId = env['EVOMAP_NODE_ID']?.trim();
375
+ if (evomapNodeId)
376
+ return evomapNodeId;
377
+ const explicitCredentials = resolveExplicitNodeCredentials(env);
378
+ if (explicitCredentials.nodeSecret && explicitCredentials.senderId)
379
+ return explicitCredentials.senderId;
380
+ try {
381
+ const nodeId = readFileSync(join(resolveIdentityHome(env), 'node_id'), 'utf8').trim();
382
+ if (/^node_[a-f0-9]{12,32}$/.test(nodeId))
383
+ return nodeId;
384
+ }
385
+ catch {
386
+ // Best effort only: missing or unreadable legacy identity files are optional.
387
+ }
388
+ const a2aNodeId = env['A2A_NODE_ID']?.trim();
389
+ if (a2aNodeId)
390
+ return a2aNodeId;
391
+ return resolveStoredAtpSenderId(env);
392
+ }
393
+ function resolveStoredAtpSenderId(env) {
302
394
  for (const p of proxyStoreCandidates(env)) {
303
395
  if (!existsSync(p))
304
396
  continue;
@@ -323,7 +415,8 @@ export function printAtpUsage() {
323
415
  ` evolver orders [--role=${ATP_ROLES.join('|')}] [--status=${ATP_PROOF_STATUSES.join('|')}]`,
324
416
  ' [--limit=N] [--json]',
325
417
  ` evolver verify <orderId> [--action=${ATP_VERIFY_ACTIONS.join('|')}]`,
326
- ' evolver atp <enable|disable|status> -- manage auto-spend consent',
418
+ ' evolver atp <enable|disable|status> -- manage consent and inspect unresolved reservations',
419
+ ' evolver atp resolve <reservationId> --outcome=success|failure -- reconcile spend (ambiguous failure remains cap-charged)',
327
420
  ].join('\n');
328
421
  }
329
422
  function parseNamed(args, longFlag, shortFlag) {
@@ -405,11 +498,11 @@ function envOverride(env) {
405
498
  return false; // ambiguous value on a spend gate → fail closed (never auto-enable spending on an unexpected/typo value)
406
499
  }
407
500
  function proxyStoreCandidates(env) {
408
- const home = resolveAtpHome(env);
409
- const candidates = [
410
- env['EVOLVER_PROXY_STORE'],
411
- join(home, 'proxy', 'mailbox.db'),
412
- join(env['HOME'] ?? homedir(), '.evomap', 'proxy', 'mailbox.db'),
413
- ].filter((x) => typeof x === 'string' && x.length > 0);
414
- return [...new Set(candidates)];
501
+ const explicit = env['EVOLVER_PROXY_STORE']?.trim();
502
+ if (explicit)
503
+ return [explicit];
504
+ const stateHome = resolveAtpHome(env);
505
+ return resolve(stateHome) === resolve(resolveIdentityHome(env))
506
+ ? [join(stateHome, 'proxy', 'mailbox.db')]
507
+ : [];
415
508
  }
@@ -0,0 +1,120 @@
1
+ import { type AtpOrderOptions, type AtpResult } from '@evomap/evolver-adapter-public';
2
+ import type { AtpCliClient } from './atp.js';
3
+ export declare const ATP_AUTOBUY_DEFAULT_DAILY_CAP = 50;
4
+ export declare const ATP_AUTOBUY_DEFAULT_PER_ORDER_CAP = 10;
5
+ export declare const ATP_AUTOBUY_DEFAULT_TIMEOUT_MS = 3000;
6
+ export declare const ATP_AUTOBUY_COLD_START_MS: number;
7
+ export declare const ATP_AUTOBUY_SUCCESS_DEDUP_MS: number;
8
+ export declare const ATP_AUTOBUY_FAILURE_DEDUP_MS: number;
9
+ export declare const ATP_AUTOBUY_LEDGER_FILENAME = "atp-autobuyer-ledger.json";
10
+ export declare const ATP_AUTOBUY_LEDGER_MAX_BYTES: number;
11
+ export type AtpAutoBuyerClient = Pick<AtpCliClient, 'placeOrder'>;
12
+ export interface AtpAutoBuyerRequest extends AtpOrderOptions {
13
+ kind: 'capability_gap';
14
+ /** Public-safe signals are mandatory for this specialized request, even though generic ATP orders allow omission. */
15
+ signals: string[];
16
+ }
17
+ export interface AtpAutoBuyerTimer {
18
+ setTimeout(callback: () => void, delayMs: number): unknown;
19
+ clearTimeout(handle: unknown): void;
20
+ }
21
+ export interface AtpAutoBuyerOptions {
22
+ client: AtpAutoBuyerClient;
23
+ ledgerPath?: string;
24
+ lockPath?: string;
25
+ consentPath?: string;
26
+ env?: NodeJS.ProcessEnv;
27
+ now?: () => number;
28
+ timer?: AtpAutoBuyerTimer;
29
+ reservationId?: () => string;
30
+ dailyCap?: number;
31
+ perOrderCap?: number;
32
+ timeoutMs?: number;
33
+ coldStartMs?: number;
34
+ successDedupMs?: number;
35
+ failureDedupMs?: number;
36
+ transportSettleMs?: number;
37
+ lockMaxTries?: number;
38
+ lockWaitMs?: number;
39
+ }
40
+ export type AtpAutoBuyerReason = 'not_capability_gap' | 'no_capabilities' | 'consent_disabled' | 'dedup_hit' | 'daily_cap_reached' | 'budget_clamped_to_zero' | 'ledger_corrupt' | 'ledger_busy' | 'ledger_unavailable' | 'order_timeout' | 'order_ambiguous';
41
+ export interface AtpAutoBuyerResult {
42
+ ok: boolean;
43
+ skipped: boolean;
44
+ reason?: AtpAutoBuyerReason;
45
+ data?: unknown;
46
+ error?: string;
47
+ status?: number;
48
+ hash?: string;
49
+ reservationId?: string;
50
+ spent?: number;
51
+ reserved?: number;
52
+ cap?: number;
53
+ }
54
+ export interface AtpAutoBuyerDedupEntry {
55
+ ts: number;
56
+ state: 'success' | 'failure' | 'reserved';
57
+ reservationId?: string;
58
+ }
59
+ export interface AtpAutoBuyerReservation {
60
+ id: string;
61
+ hash: string;
62
+ budget: number;
63
+ dayKey: string;
64
+ createdAt: number;
65
+ updatedAt: number;
66
+ /** Earliest time an operator may reconcile a pending reservation left by a crashed process. */
67
+ resolveAfter?: number;
68
+ state: 'pending' | 'ambiguous';
69
+ error?: string;
70
+ }
71
+ export interface AtpAutoBuyerResolution {
72
+ reservationId: string;
73
+ hash: string;
74
+ budget: number;
75
+ outcome: 'success' | 'failure';
76
+ resolvedAt: number;
77
+ source: 'operator' | 'late_result';
78
+ }
79
+ export interface AtpAutoBuyerLedger {
80
+ version: 2;
81
+ dayKey: string;
82
+ spent: number;
83
+ dedup: Record<string, AtpAutoBuyerDedupEntry>;
84
+ reservations: Record<string, AtpAutoBuyerReservation>;
85
+ resolutions: AtpAutoBuyerResolution[];
86
+ }
87
+ export declare class AtpAutoBuyerLedgerError extends Error {
88
+ readonly code: 'CORRUPT_LEDGER' | 'LEDGER_UNAVAILABLE';
89
+ constructor(message: string, code: 'CORRUPT_LEDGER' | 'LEDGER_UNAVAILABLE', options?: ErrorOptions);
90
+ }
91
+ export declare function readAtpAutoBuyerLedger(path: string): AtpAutoBuyerLedger;
92
+ export declare function resolveAtpAutoBuyerLedgerPath(env?: NodeJS.ProcessEnv, consentPath?: string): string;
93
+ export declare function hashAtpCapabilityGap(request: Pick<AtpAutoBuyerRequest, 'capabilities' | 'question'>): string;
94
+ export declare class AtpAutoBuyer {
95
+ readonly ledgerPath: string;
96
+ readonly lockPath: string;
97
+ private readonly client;
98
+ private readonly consentPath;
99
+ private readonly env;
100
+ private readonly now;
101
+ private readonly timer;
102
+ private readonly reservationId;
103
+ private readonly config;
104
+ private queue;
105
+ private startedAt;
106
+ constructor(options: AtpAutoBuyerOptions);
107
+ consider(request: AtpAutoBuyerRequest): Promise<AtpAutoBuyerResult>;
108
+ reconcileReservation(reservationId: string, result: AtpResult): boolean;
109
+ resolveReservation(reservationId: string, outcome: 'success' | 'failure'): boolean;
110
+ private considerSerialized;
111
+ private reserve;
112
+ private awaitOrder;
113
+ private reconcileLate;
114
+ private markAmbiguous;
115
+ private releaseReservation;
116
+ private pendingResolveAfter;
117
+ private loadLedger;
118
+ private withLedgerLock;
119
+ private ledgerFailure;
120
+ }