@aragon-agent/cli 0.6.62 → 0.6.64

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 (93) hide show
  1. package/CHANGELOG.md +70 -2
  2. package/README.md +143 -27
  3. package/dist/agent/controller.d.ts +66 -14
  4. package/dist/agent/controller.js +291 -81
  5. package/dist/agent/headless.d.ts +16 -0
  6. package/dist/agent/headless.js +62 -3
  7. package/dist/agent/team-notices.d.ts +57 -7
  8. package/dist/agent/team-notices.js +93 -10
  9. package/dist/app/App.js +199 -77
  10. package/dist/cli.js +4 -1
  11. package/dist/commands/builtins.js +2 -1
  12. package/dist/commands/catalog.js +1 -1
  13. package/dist/compaction/archive.d.ts +27 -1
  14. package/dist/compaction/archive.js +8 -0
  15. package/dist/compaction/budget.d.ts +73 -0
  16. package/dist/compaction/budget.js +89 -0
  17. package/dist/compaction/child.js +6 -1
  18. package/dist/compaction/command.js +147 -1
  19. package/dist/compaction/compactor.d.ts +132 -15
  20. package/dist/compaction/compactor.js +288 -95
  21. package/dist/compaction/context-command.js +21 -0
  22. package/dist/compaction/memory-agent-prompt.d.ts +32 -0
  23. package/dist/compaction/memory-agent-prompt.js +76 -0
  24. package/dist/compaction/memory-agent-tools.d.ts +88 -0
  25. package/dist/compaction/memory-agent-tools.js +338 -0
  26. package/dist/compaction/memory-agent.d.ts +114 -0
  27. package/dist/compaction/memory-agent.js +220 -0
  28. package/dist/compaction/prune.d.ts +129 -0
  29. package/dist/compaction/prune.js +386 -0
  30. package/dist/compaction/retry-plan.d.ts +103 -0
  31. package/dist/compaction/retry-plan.js +136 -0
  32. package/dist/compaction/summarize-ladder.d.ts +149 -0
  33. package/dist/compaction/summarize-ladder.js +273 -0
  34. package/dist/compaction/wiring.d.ts +19 -0
  35. package/dist/compaction/wiring.js +65 -1
  36. package/dist/config/cli-commands.d.ts +2 -2
  37. package/dist/config/cli-commands.js +27 -0
  38. package/dist/config/env.d.ts +3 -1
  39. package/dist/config/env.js +44 -2
  40. package/dist/exec/events.d.ts +30 -0
  41. package/dist/exec/index.js +2 -0
  42. package/dist/exec/runner.js +16 -1
  43. package/dist/gene/commit-prepare.js +27 -1
  44. package/dist/gene/curator/curator.d.ts +15 -0
  45. package/dist/gene/curator/curator.js +26 -2
  46. package/dist/gene/curator/scripted-lane.d.ts +12 -0
  47. package/dist/gene/curator/scripted-lane.js +101 -0
  48. package/dist/gene/curator/task-context.d.ts +21 -0
  49. package/dist/gene/curator/task-context.js +33 -0
  50. package/dist/gene/curator/task-runner.d.ts +10 -1
  51. package/dist/gene/curator/task-runner.js +39 -4
  52. package/dist/gene/curator/tool-support.js +11 -4
  53. package/dist/gene/curator/toolkit.d.ts +13 -0
  54. package/dist/gene/curator/toolkit.js +23 -1
  55. package/dist/gene/curator/tools-verify.js +2 -2
  56. package/dist/gene/curator/tools-write.js +6 -1
  57. package/dist/gene/curator/validate/evidence-tokens.js +133 -22
  58. package/dist/gene/curator/validate/knowledge.d.ts +41 -1
  59. package/dist/gene/curator/validate/knowledge.js +74 -11
  60. package/dist/gene/curator/validate/prompts.d.ts +10 -2
  61. package/dist/gene/curator/validate/prompts.js +2 -2
  62. package/dist/gene/learn/draft-guard.d.ts +17 -0
  63. package/dist/gene/learn/draft-guard.js +113 -0
  64. package/dist/gene/learn/learn-prompt.d.ts +22 -1
  65. package/dist/gene/learn/learn-prompt.js +27 -2
  66. package/dist/gene/learn/learner.js +20 -2
  67. package/dist/gene/queue.d.ts +16 -0
  68. package/dist/gene/queue.js +44 -1
  69. package/dist/governance/store/run-store.d.ts +20 -0
  70. package/dist/governance/store/run-store.js +54 -8
  71. package/dist/host/index.d.ts +1 -0
  72. package/dist/host/index.js +1 -0
  73. package/dist/host/interaction.d.ts +8 -17
  74. package/dist/host/interaction.js +50 -72
  75. package/dist/host/team-wake-driver.d.ts +90 -0
  76. package/dist/host/team-wake-driver.js +114 -0
  77. package/dist/logging/install.d.ts +59 -1
  78. package/dist/logging/install.js +15 -0
  79. package/dist/session/validate-session.js +11 -0
  80. package/dist/team/console-tools.d.ts +12 -0
  81. package/dist/team/console-tools.js +20 -3
  82. package/dist/team/console-view.js +11 -1
  83. package/dist/team/notices.d.ts +81 -4
  84. package/dist/team/notices.js +187 -22
  85. package/dist/team/prompt.js +1 -1
  86. package/dist/team/runtime.d.ts +67 -24
  87. package/dist/team/runtime.js +250 -31
  88. package/dist/team/stall-watch.d.ts +54 -0
  89. package/dist/team/stall-watch.js +119 -0
  90. package/dist/team/task-tool.js +2 -2
  91. package/dist/team/wake.d.ts +176 -0
  92. package/dist/team/wake.js +444 -0
  93. package/package.json +81 -81
@@ -18,7 +18,9 @@
18
18
  * ARAGON_UPDATE,
19
19
  * ARAGON_COMPACTION, ARAGON_COMPACTION_THRESHOLD,
20
20
  * ARAGON_COMPACTION_KEEP_TURNS, ARAGON_COMPACTION_SUBAGENTS,
21
- * ARAGON_COMPACTION_ARCHIVE,
21
+ * ARAGON_COMPACTION_ARCHIVE, ARAGON_COMPACTION_AGENTIC,
22
+ * ARAGON_COMPACTION_PRUNE, ARAGON_COMPACTION_BUDGET_TOKENS,
23
+ * ARAGON_COMPACTION_BUDGET_USD,
22
24
  * ARAGON_JOBS_ENABLED, ARAGON_JOBS_WAIT_SECONDS, ARAGON_JOBS_STALL_SECONDS,
23
25
  * ARAGON_JOBS_PERSIST_LOG, ARAGON_JOBS_NOTICE_STEER,
24
26
  * ARAGON_PROMPTS (the quick-prompt library's `enabled` switch, and only that),
@@ -434,12 +436,23 @@ export function readEnvConfig() {
434
436
  // disk in an environment that may not permit it.
435
437
  const compactionSubagents = process.env.ARAGON_COMPACTION_SUBAGENTS?.trim().toLowerCase();
436
438
  const compactionArchive = process.env.ARAGON_COMPACTION_ARCHIVE?.trim().toLowerCase();
439
+ // THE FOUR v3 KEYS (context-compaction-v3 W6). Same contract as the five above:
440
+ // a bad value is left ABSENT rather than resolved to a default, so the config
441
+ // layer underneath - and `clampCompactionConfig` - still owns the fallback.
442
+ const compactionAgentic = process.env.ARAGON_COMPACTION_AGENTIC?.trim().toLowerCase();
443
+ const compactionPrune = process.env.ARAGON_COMPACTION_PRUNE?.trim().toLowerCase();
444
+ const compactionBudgetTokens = process.env.ARAGON_COMPACTION_BUDGET_TOKENS?.trim();
445
+ const compactionBudgetUsd = process.env.ARAGON_COMPACTION_BUDGET_USD?.trim();
437
446
  const positive = (v) => v === '1' || v === 'true' || v === 'on' || v === 'yes';
438
447
  if ((compaction !== undefined && compaction.length > 0) ||
439
448
  (compactionThreshold !== undefined && compactionThreshold.length > 0) ||
440
449
  (compactionKeepTurns !== undefined && compactionKeepTurns.length > 0) ||
441
450
  (compactionSubagents !== undefined && compactionSubagents.length > 0) ||
442
- (compactionArchive !== undefined && compactionArchive.length > 0)) {
451
+ (compactionArchive !== undefined && compactionArchive.length > 0) ||
452
+ (compactionAgentic !== undefined && compactionAgentic.length > 0) ||
453
+ (compactionPrune !== undefined && compactionPrune.length > 0) ||
454
+ (compactionBudgetTokens !== undefined && compactionBudgetTokens.length > 0) ||
455
+ (compactionBudgetUsd !== undefined && compactionBudgetUsd.length > 0)) {
443
456
  const section = {};
444
457
  if (compaction !== undefined && compaction.length > 0) {
445
458
  section.enabled = positive(compaction);
@@ -450,6 +463,22 @@ export function readEnvConfig() {
450
463
  if (compactionArchive !== undefined && compactionArchive.length > 0) {
451
464
  section.archive = positive(compactionArchive);
452
465
  }
466
+ if (compactionAgentic !== undefined && compactionAgentic.length > 0) {
467
+ section.agentic = positive(compactionAgentic);
468
+ }
469
+ if (compactionPrune !== undefined && compactionPrune.length > 0) {
470
+ section.prune = positive(compactionPrune);
471
+ }
472
+ if (compactionBudgetTokens !== undefined && compactionBudgetTokens.length > 0) {
473
+ const n = parseBudgetNumber(compactionBudgetTokens);
474
+ if (n !== null)
475
+ section.budgetTokens = Math.round(n);
476
+ }
477
+ if (compactionBudgetUsd !== undefined && compactionBudgetUsd.length > 0) {
478
+ const n = parseBudgetNumber(compactionBudgetUsd);
479
+ if (n !== null)
480
+ section.budgetUsd = n;
481
+ }
453
482
  if (compactionThreshold !== undefined && compactionThreshold.length > 0) {
454
483
  // Left ABSENT on a bad value rather than clamped to a default, so a typo
455
484
  // falls through to the config layer instead of masking it for the session.
@@ -548,6 +577,19 @@ function envBool(value) {
548
577
  const v = value.trim().toLowerCase();
549
578
  return !(v === '0' || v === 'false' || v === 'off' || v === 'no');
550
579
  }
580
+ /**
581
+ * A budget number from the environment, or `null` when it is not one.
582
+ *
583
+ * `off`/`unlimited`/`0` all mean "no ceiling" (D-8), and a typo returns `null`
584
+ * so the key stays ABSENT - the rule `ARAGON_COMPACTION_THRESHOLD` states three
585
+ * lines above. Never throws, never clamps: the clamp is `clampCompactionConfig`.
586
+ */
587
+ function parseBudgetNumber(raw) {
588
+ if (/^(off|none|unlimited)$/i.test(raw))
589
+ return 0;
590
+ const n = Number(raw.replace(/[$,]/g, ''));
591
+ return Number.isFinite(n) && n >= 0 ? n : null;
592
+ }
551
593
  /**
552
594
  * Assemble the `log` section from the environment, or `undefined` when the user
553
595
  * said nothing about it. Same shape as the `partial.skills` assembly above: a
@@ -411,6 +411,36 @@ export interface ExecCompactionEvent {
411
411
  messages: number;
412
412
  charsRemoved: number;
413
413
  };
414
+ /**
415
+ * The three v3 sections (context-compaction-v3 §6.2), all optional.
416
+ *
417
+ * `EXEC_SCHEMA_VERSION` DOES NOT MOVE: adding a field never does, and the README
418
+ * already promises that a consumer ignores what it does not know. A wrapper that
419
+ * wants to enforce a spend ceiling needs `budget` here, and one that wants to
420
+ * explain a slow compaction needs `agent`.
421
+ */
422
+ prune?: {
423
+ actions: number;
424
+ removedChars: number;
425
+ removedTokens: number;
426
+ inspected: number;
427
+ kinds: Record<string, number>;
428
+ };
429
+ budget?: {
430
+ limitTokens: number;
431
+ spentTokens: number;
432
+ limitUsd: number;
433
+ spentUsd: number;
434
+ priceUnknown: boolean;
435
+ stop?: 'budget_tokens' | 'budget_usd';
436
+ };
437
+ agent?: {
438
+ turns: number;
439
+ toolCalls: number;
440
+ submissions: number;
441
+ fallback?: 'single-shot';
442
+ };
443
+ stoppedBy?: 'budget_tokens' | 'budget_usd' | 'turn_limit' | 'timeout' | 'cancel';
414
444
  durationMs?: number;
415
445
  }
416
446
  export interface ExecRetryEvent {
@@ -22,6 +22,7 @@ import { randomUUID } from 'node:crypto';
22
22
  import process from 'node:process';
23
23
  import { runHeadless } from '../agent/headless.js';
24
24
  import { computeCost } from '@aragon-agent/tui/model/agent/usage';
25
+ import { toRunResumePolicy } from '@aragon-agent/tui/model/config/schema';
25
26
  import { loadConfig } from '../config/load.js';
26
27
  import { latestSessionForCwd, readSessionFile, resolveSessionRef, resumedSessionId, sessionPathFor, tryAcquireSessionLock, writeSession, } from '../session/store.js';
27
28
  import { createEmitter } from './emitter.js';
@@ -689,6 +690,7 @@ async function drive(input, controller, runner) {
689
690
  const code = await runHeadless(controller, first, {
690
691
  quiet: options.quiet,
691
692
  followThrough: controller.getTodoConfig().followThrough,
693
+ resume: toRunResumePolicy(controller.getConfig().retry, { headless: true }),
692
694
  stdout: out,
693
695
  stderr: err,
694
696
  });
@@ -306,6 +306,12 @@ export class ExecRunner {
306
306
  tokensBefore: r.tokensBefore,
307
307
  tokensAfter: r.tokensAfter,
308
308
  ...(r.tailRelief ? { tailRelief: r.tailRelief } : {}),
309
+ // THE v3 SECTIONS (context-compaction-v3 §6.2). Passed straight through:
310
+ // this runner is a projection of the record, never a second truth.
311
+ ...(r.prune ? { prune: r.prune } : {}),
312
+ ...(r.budget ? { budget: r.budget } : {}),
313
+ ...(r.agent ? { agent: r.agent } : {}),
314
+ ...(r.stoppedBy ? { stoppedBy: r.stoppedBy } : {}),
309
315
  ...(r.decision ? { decision: r.decision } : {}),
310
316
  ...(r.memoryVersion ? { memoryVersion: r.memoryVersion } : {}),
311
317
  durationMs: r.durationMs,
@@ -1159,7 +1165,16 @@ export class ExecRunner {
1159
1165
  budget,
1160
1166
  interactive: false,
1161
1167
  });
1162
- if (decision.kind === 'none')
1168
+ // `resume` IS NEVER REQUESTED HERE: this call passes no `resume` input, so the
1169
+ // table cannot return it. It is NOT wired on purpose
1170
+ // (team-idle-watchdog-dead-run, "issues found during implementation"): a death
1171
+ // with no assistant turn has already set `stopReason = 'error'` through
1172
+ // `recordError`, and the early `stopReason !== 'end_turn'` return above ends the
1173
+ // chain before this table is read - which also means the plan-driven recovery
1174
+ // below has never been reachable for such a death. Re-running from here would
1175
+ // first have to un-send the fatal `error` frame a failed stream has already
1176
+ // written, which is a change to the wire contract and not a host policy.
1177
+ if (decision.kind === 'none' || decision.kind === 'resume')
1163
1178
  return false;
1164
1179
  if (decision.kind === 'notify') {
1165
1180
  this.note(`[todo] ${decision.text}`);
@@ -12,6 +12,30 @@ export function validateActorOf(actor) {
12
12
  return 'user';
13
13
  return actor.kind === 'curator' ? 'agent' : 'import';
14
14
  }
15
+ /** How many content issues one refusal lists, and how long the list may get. */
16
+ const MAX_LISTED_ISSUES = 6;
17
+ const MAX_LISTED_ISSUES_CHARS = 600;
18
+ /**
19
+ * Every content issue a draft has, as `path: reason; path: reason` (gene-bank-never-publishes-3, R-1).
20
+ *
21
+ * WHY ALL OF THEM. The refusal used to carry only the FIRST issue's category, so a skill draft
22
+ * missing four things was told "a required section is missing" four times in a row, one fix per
23
+ * round trip, and a curator task that spends a 9-call loop per attempt ran out of budget before it
24
+ * ran out of fixes. Listing them lets one rewrite satisfy the whole contract.
25
+ *
26
+ * WHAT IT MAY CARRY. Only `path` and the validators' own closed vocabulary: limits, section names,
27
+ * rule ids and gene ids. No `bad(...)` in `validate-*.ts` interpolates gene or evidence text, so
28
+ * the list is as safe as the single message it replaces (I-19); `no-body-in-logs.test.ts` and the
29
+ * `poison-untrusted` case keep it so.
30
+ */
31
+ function listContentIssues(issues) {
32
+ const lines = issues
33
+ .filter((i) => i.code === 'GENE_INVALID_CONTENT')
34
+ .slice(0, MAX_LISTED_ISSUES)
35
+ .map((i) => `${i.path}: ${i.message}`);
36
+ const joined = lines.join('; ');
37
+ return joined.length <= MAX_LISTED_ISSUES_CHARS ? joined : `${joined.slice(0, MAX_LISTED_ISSUES_CHARS - 3)}...`;
38
+ }
15
39
  /** A violation of the issue list that outranks the rest, then the first issue (11.3, 11.5). */
16
40
  export function issuesToFailure(issues) {
17
41
  const order = [
@@ -23,7 +47,9 @@ export function issuesToFailure(issues) {
23
47
  const chosen = outranking.find((i) => i !== undefined) ?? issues[0];
24
48
  if (chosen === undefined)
25
49
  return geneFail('GENE_INVALID_CONTENT', 'The content is not valid.');
26
- return geneFail(chosen.code, `${chosen.path}: ${chosen.message}`, chosen.detail);
50
+ // `code:detail` stays the FIRST issue's (every consumer keys on it); only the prose grows.
51
+ const message = chosen.code === 'GENE_INVALID_CONTENT' ? listContentIssues(issues) : `${chosen.path}: ${chosen.message}`;
52
+ return geneFail(chosen.code, message, chosen.detail);
27
53
  }
28
54
  /** Trimmed, English, length-bounded, secret-free (the `reason` of a version). */
29
55
  export function cleanReason(reason, knownSecrets) {
@@ -70,6 +70,13 @@ export interface CuratorDeps {
70
70
  housekeeping?(): Promise<void>;
71
71
  probeDeps?: ProbeDeps;
72
72
  timing?: Partial<CuratorTiming>;
73
+ /**
74
+ * The scripted create lane (`scripted-lane.ts`). Absent = on, which is what production wants; a
75
+ * test that scripts the agent loop turns it off so its proposals reach the model, and a test of
76
+ * the lane turns it on. `ARAGON_GENE_SCRIPTED_LANE=0` is the operator's kill switch and applies
77
+ * either way.
78
+ */
79
+ scriptedLane?(): boolean;
73
80
  }
74
81
  export interface CuratorStatus {
75
82
  started: boolean;
@@ -146,6 +153,14 @@ export declare class GeneCurator {
146
153
  private every;
147
154
  private housekeeping;
148
155
  private recoverStale;
156
+ /**
157
+ * Move the queued reviewer proposals whose draft the curator can never turn into a candidate to
158
+ * `dead/`, once an hour and logged (R-3'). They were queued before the enqueue guard existed (a
159
+ * skill draft alone cost 145k-205k tokens and ended in nothing), and nothing else would ever
160
+ * stop them: this is a sweep with an event per proposal, not a hand edit of `queue/**`, and
161
+ * `retryDead` puts any of them back.
162
+ */
163
+ private sweepUncreatableDrafts;
149
164
  private enqueueMaintenance;
150
165
  /** Returns whether to claim at all; sets the model block that only blocks model work. */
151
166
  private evaluatePause;
@@ -47,6 +47,7 @@ import { SwitchGuard } from './switches.js';
47
47
  import { runClaimedTask } from './task-runner.js';
48
48
  import { createValidatorPortsFactory } from './validator-ports.js';
49
49
  import { realScheduler } from '../hub.js';
50
+ import { checkDraftCreatable, draftRefusalDetail, isDraftGuardEnabled } from '../learn/draft-guard.js';
50
51
  const MINUTE_MS = 60_000;
51
52
  export const DEFAULT_TIMING = {
52
53
  pollMs: 5000,
@@ -162,6 +163,8 @@ export class GeneCurator {
162
163
  random: this.random,
163
164
  scheduler: this.scheduler,
164
165
  modelBlocked: () => this.modelBlockedNow(),
166
+ // Peeks: unlike `modelBlockedNow`, it never takes the half-open trial.
167
+ scriptedLaneAvailable: () => (this.deps.scriptedLane?.() ?? true) && this.modelBlock === null && this.breaker.view().state === 'closed',
165
168
  };
166
169
  }
167
170
  // ---- public surface ---------------------------------------------------------
@@ -350,6 +353,7 @@ export class GeneCurator {
350
353
  await this.every('recover', t.recoverMs, () => this.recoverStale());
351
354
  await this.every('probation', t.probationMs, () => sweepProbation({ service: this.deps.service, library: this.deps.library, now: this.now }));
352
355
  await this.every('maintenance', t.maintenanceMs, () => this.enqueueMaintenance());
356
+ await this.every('draft_sweep', t.pruneMs, () => this.sweepUncreatableDrafts());
353
357
  await this.every('prune', t.pruneMs, async () => {
354
358
  await this.deps.queue.prune();
355
359
  await this.deps.runLog.prune();
@@ -365,6 +369,25 @@ export class GeneCurator {
365
369
  await this.events.emit(ev, { proposalId: item.proposalId, detail: `claim_expired attempt=${item.attempt}` });
366
370
  }
367
371
  }
372
+ /**
373
+ * Move the queued reviewer proposals whose draft the curator can never turn into a candidate to
374
+ * `dead/`, once an hour and logged (R-3'). They were queued before the enqueue guard existed (a
375
+ * skill draft alone cost 145k-205k tokens and ended in nothing), and nothing else would ever
376
+ * stop them: this is a sweep with an event per proposal, not a hand edit of `queue/**`, and
377
+ * `retryDead` puts any of them back.
378
+ */
379
+ async sweepUncreatableDrafts() {
380
+ if (!isDraftGuardEnabled())
381
+ return;
382
+ const secrets = this.deps.knownSecrets?.() ?? [];
383
+ const now = this.now();
384
+ const moved = await this.deps.queue.quarantinePendingWhere((proposal) => {
385
+ const verdict = checkDraftCreatable(proposal, secrets, now);
386
+ return verdict.creatable ? null : draftRefusalDetail(verdict);
387
+ });
388
+ for (const proposalId of moved)
389
+ await this.events.emit('dead', { proposalId, detail: 'draft_not_creatable' });
390
+ }
368
391
  async enqueueMaintenance() {
369
392
  const proposal = makeSystemProposal({ now: this.now, random: this.random }, {
370
393
  kind: 'maintenance',
@@ -555,10 +578,11 @@ export class GeneCurator {
555
578
  return;
556
579
  }
557
580
  const error = outcome.failure.kind === 'transient' ? outcome.failure.error : 'validation';
581
+ const stats = outcome.stats ?? '';
558
582
  if (result.state === 'dead')
559
- await this.events.emit('dead', { proposalId, detail: `${error} attempts=${result.attempt}` });
583
+ await this.events.emit('dead', { proposalId, detail: `${error} attempts=${result.attempt}${stats}` });
560
584
  else
561
- await this.events.emit('retry_scheduled', { proposalId, detail: `${error} attempt=${result.attempt}` });
585
+ await this.events.emit('retry_scheduled', { proposalId, detail: `${error} attempt=${result.attempt}${stats}` });
562
586
  }
563
587
  async settleRelease(claimed, outcome) {
564
588
  const proposalId = claimed.item.proposal.id;
@@ -0,0 +1,12 @@
1
+ import type { GeneProposal } from '@aragon-agent/tui/model/gene/types';
2
+ import type { CandidateRef } from './task-context.js';
3
+ import { type ToolEnv } from './tool-support.js';
4
+ export declare function isScriptedLaneEnabled(env?: NodeJS.ProcessEnv): boolean;
5
+ /** The only shape the lane takes: a reviewer's knowledge create that names no existing gene. */
6
+ export declare function isScriptedShape(proposal: GeneProposal): boolean;
7
+ /**
8
+ * Write the candidate when every deterministic check would pass, and return its reference for
9
+ * `resume_validation`. `null` = decline (nothing was written); `'abandoned'` = a switch or a
10
+ * cancellation stopped the task and `ctx.abandoned` says why.
11
+ */
12
+ export declare function writeScriptedCandidate(env: ToolEnv): Promise<CandidateRef | 'abandoned' | null>;
@@ -0,0 +1,101 @@
1
+ /**
2
+ * The scripted create lane (gene-bank-never-publishes-3, F2 / beta').
3
+ *
4
+ * ASCII ONLY - the whole `gene/` tree is in `glyphs.test.ts::inScope`.
5
+ *
6
+ * WHAT IT IS. For a reviewer's `create` proposal whose knowledge draft is already COMPLETE and
7
+ * already passes the two checks that need no model (K1 static, K2 source, K3 scope), the CODE writes
8
+ * the candidate - through the same `buildContent` and the same `service.commit` that
9
+ * `gene_create_candidate` uses - and hands it to `resume_validation`, the executor that already
10
+ * validates and publishes a candidate a killed task left behind. No agent is created.
11
+ *
12
+ * WHY. A curator task is a 9-call loop whose cost is the model's behaviour: 26k-70k tokens to reach
13
+ * the validator, against a validator that costs about 1-2k. 12 of the 15 validations ever produced,
14
+ * and the only published gene, came out of `resume_validation` after a cap kill. This lane makes
15
+ * that path the first resort for the proposals that can take it, so the cost no longer depends on
16
+ * whether the model happens to be tidy.
17
+ *
18
+ * WHAT IT DOES NOT TOUCH. Every gate stays where it was: the switches are re-read right before the
19
+ * write (`switchGate`), the write is `service.commit` as the curator actor, validation is
20
+ * `runCandidateValidation` (K4 and K5 still call a model; a conflict still converts or waits for a
21
+ * person; a K6 untrusted-only candidate still waits), and publishing is `publishCandidate`, so
22
+ * probation, the publish gate and the leftover cleanup are the ones the agent path uses.
23
+ *
24
+ * WHEN IT DECLINES. Any doubt returns `null` and the proposal takes the agent loop exactly as it
25
+ * did before: not a knowledge create, not from the reviewer, not complete, K1/K2/K3 would fail, the
26
+ * switch is off, the model is blocked, or the write itself was refused. The decision is made BEFORE
27
+ * the candidate exists, because once it does a failed validation is final.
28
+ *
29
+ * KILL SWITCH. `ARAGON_GENE_SCRIPTED_LANE=0` turns it off and nothing turns it on.
30
+ */
31
+ import process from 'node:process';
32
+ import { validateGeneContent } from '@aragon-agent/tui/model/gene/validate';
33
+ import { geneLooksLikeSecret } from '../secrets.js';
34
+ import { CURATOR_ACTOR, buildContent, evidenceFor, switchGate, } from './tool-support.js';
35
+ import { passesDeterministicChecks } from './validate/knowledge.js';
36
+ const KILL_SWITCH = 'ARAGON_GENE_SCRIPTED_LANE';
37
+ const REASON = 'Written by the curator from a reviewer proposal after the deterministic checks passed.';
38
+ export function isScriptedLaneEnabled(env = process.env) {
39
+ return env[KILL_SWITCH]?.trim() !== '0';
40
+ }
41
+ /** The only shape the lane takes: a reviewer's knowledge create that names no existing gene. */
42
+ export function isScriptedShape(proposal) {
43
+ return (proposal.kind === 'create' &&
44
+ (proposal.type ?? 'knowledge') === 'knowledge' &&
45
+ proposal.target === undefined &&
46
+ proposal.origin.source === 'reviewer' &&
47
+ proposal.draft !== undefined);
48
+ }
49
+ /** The draft as the fields `gene_create_candidate` would receive from a model. */
50
+ function rawFromDraft(draft) {
51
+ return { ...draft };
52
+ }
53
+ /** The content the lane would write, or null when the draft is not complete and valid as it stands. */
54
+ async function completeContent(env) {
55
+ const { ctx } = env;
56
+ const draft = ctx.proposal.draft;
57
+ if (draft === undefined)
58
+ return null;
59
+ const built = buildContent(env, 'knowledge', rawFromDraft(draft));
60
+ const verdict = validateGeneContent('knowledge', built.content, {
61
+ scope: ctx.scope,
62
+ actor: 'agent',
63
+ secretCheck: (text) => geneLooksLikeSecret(text, env.deps.knownSecrets()),
64
+ });
65
+ return verdict.ok && built.requestedClass === undefined ? built.content : null;
66
+ }
67
+ /** Would K2 and K3 pass on the content as drafted? Uses the validator's own functions. */
68
+ async function passesPrecheck(env, content) {
69
+ const { ctx } = env;
70
+ const ports = await env.deps.validatorPorts(ctx);
71
+ return passesDeterministicChecks({ ports, type: 'knowledge', scope: ctx.scope, content, evidence: ctx.evidence });
72
+ }
73
+ /**
74
+ * Write the candidate when every deterministic check would pass, and return its reference for
75
+ * `resume_validation`. `null` = decline (nothing was written); `'abandoned'` = a switch or a
76
+ * cancellation stopped the task and `ctx.abandoned` says why.
77
+ */
78
+ export async function writeScriptedCandidate(env) {
79
+ const { ctx } = env;
80
+ const content = await completeContent(env);
81
+ if (content === null || !(await passesPrecheck(env, content)))
82
+ return null;
83
+ // The same checkpoint every write tool passes: a person may have switched learning off meanwhile.
84
+ if ((await switchGate(env, 'scripted_create')) !== null)
85
+ return 'abandoned';
86
+ const done = await env.deps.service.commit({
87
+ op: 'create',
88
+ type: 'knowledge',
89
+ scope: ctx.scope,
90
+ content,
91
+ reason: REASON,
92
+ class: 'standard',
93
+ proposalId: ctx.proposal.id,
94
+ evidence: evidenceFor(ctx, null),
95
+ }, CURATOR_ACTOR);
96
+ if (!done.ok)
97
+ return null;
98
+ ctx.wrote = true;
99
+ ctx.evidenceAttached.add(done.value.id);
100
+ return { id: done.value.id, scope: ctx.scope, type: 'knowledge', version: done.value.version ?? 1 };
101
+ }
@@ -49,6 +49,19 @@ export interface TaskUsage {
49
49
  };
50
50
  }
51
51
  export declare const CURATOR_CONTEXT_BRAND: unique symbol;
52
+ /**
53
+ * What one task did, as numbers and our own names (gene-bank-never-publishes-3, R-6'). The run log
54
+ * had a token total per attempt and nothing else, so "80k went where?" was unanswerable: a skill
55
+ * that was refused five times and a knowledge task that spent its turns searching looked the same.
56
+ * Only tool NAMES (a source constant) and refusal CODES (`GENE_*`) are counted - never an argument,
57
+ * a draft or a receipt (I-19).
58
+ */
59
+ export interface TaskStats {
60
+ /** Model turns, written by the runner when the agent loop ends. */
61
+ turns: number;
62
+ tools: Map<string, number>;
63
+ refusals: Map<string, number>;
64
+ }
52
65
  export interface CuratorTaskContext {
53
66
  readonly brand: typeof CURATOR_CONTEXT_BRAND;
54
67
  /** False once the task has ended: every tool then refuses. */
@@ -78,6 +91,7 @@ export interface CuratorTaskContext {
78
91
  needsHuman: GeneNeedsHuman['reason'] | null;
79
92
  /** Whether a gene-writing call already took place (a retry needs to know). */
80
93
  wrote: boolean;
94
+ stats: TaskStats;
81
95
  }
82
96
  export interface ContextSeed {
83
97
  proposal: GeneProposal;
@@ -88,6 +102,13 @@ export interface ContextSeed {
88
102
  rebased: boolean;
89
103
  }
90
104
  export declare function createTaskContext(seed: ContextSeed): CuratorTaskContext;
105
+ /**
106
+ * ` turns=9 tools=gene_create_candidate:5,gene_toolkit:3 refusals=GENE_INVALID_CONTENT:4` for a run-log
107
+ * `detail`; empty when the task took no turn. Bounded: the log clips a detail at 240 characters.
108
+ */
109
+ export declare function describeTaskStats(stats: TaskStats): string;
110
+ /** Count one finished tool call, and its refusal code when it was refused. Never throws. */
111
+ export declare function noteToolCall(ctx: CuratorTaskContext, tool: string, result: ToolResult): void;
91
112
  /** A tool refusal, or null when the context is a live curator task. Never throws. */
92
113
  export declare function assertCuratorContext(ctx: CuratorTaskContext | undefined): ToolResult | null;
93
114
  export declare function validationKey(id: string, version: number): string;
@@ -46,8 +46,41 @@ export function createTaskContext(seed) {
46
46
  merged: [],
47
47
  needsHuman: null,
48
48
  wrote: false,
49
+ stats: { turns: 0, tools: new Map(), refusals: new Map() },
49
50
  };
50
51
  }
52
+ const STATS_MAX_TOOLS = 6;
53
+ const STATS_MAX_REFUSALS = 4;
54
+ function listed(counts, max) {
55
+ return [...counts.entries()]
56
+ .sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))
57
+ .slice(0, max)
58
+ .map(([name, n]) => `${name}:${n}`)
59
+ .join(',');
60
+ }
61
+ /**
62
+ * ` turns=9 tools=gene_create_candidate:5,gene_toolkit:3 refusals=GENE_INVALID_CONTENT:4` for a run-log
63
+ * `detail`; empty when the task took no turn. Bounded: the log clips a detail at 240 characters.
64
+ */
65
+ export function describeTaskStats(stats) {
66
+ if (stats.turns === 0 && stats.tools.size === 0)
67
+ return '';
68
+ const tools = listed(stats.tools, STATS_MAX_TOOLS);
69
+ const refusals = listed(stats.refusals, STATS_MAX_REFUSALS);
70
+ return ` turns=${stats.turns}${tools === '' ? '' : ` tools=${tools}`}${refusals === '' ? '' : ` refusals=${refusals}`}`;
71
+ }
72
+ /** Count one finished tool call, and its refusal code when it was refused. Never throws. */
73
+ export function noteToolCall(ctx, tool, result) {
74
+ const { stats } = ctx;
75
+ stats.tools.set(tool, (stats.tools.get(tool) ?? 0) + 1);
76
+ if (result.isError !== true)
77
+ return;
78
+ const first = result.content.find((block) => block.type === 'text');
79
+ // `errorResult` prefixes `Error: `; the refusal itself is `<tool>: <CODE>[:<detail>] - <message>`.
80
+ const code = /^(?:Error: )?[a-z_]+: ([A-Z][A-Z_]*)/.exec(first?.text ?? '')?.[1];
81
+ if (code !== undefined)
82
+ stats.refusals.set(code, (stats.refusals.get(code) ?? 0) + 1);
83
+ }
51
84
  /** A tool refusal, or null when the context is a live curator task. Never throws. */
52
85
  export function assertCuratorContext(ctx) {
53
86
  if (ctx === undefined || ctx.brand !== CURATOR_CONTEXT_BRAND) {
@@ -10,10 +10,13 @@ export type TaskOutcome = {
10
10
  kind: 'complete';
11
11
  result: QueueResult;
12
12
  detail: string;
13
- } | {
13
+ }
14
+ /** `stats`: ` turns=9 tools=... refusals=...` for the run-log record of the failed attempt (R-6'). */
15
+ | {
14
16
  kind: 'fail';
15
17
  failure: QueueFailure;
16
18
  infra: boolean;
19
+ stats?: string;
17
20
  } | {
18
21
  kind: 'release';
19
22
  reason: string;
@@ -38,6 +41,12 @@ export interface TaskRunnerDeps {
38
41
  scheduler?: Pick<HubScheduler, 'after'>;
39
42
  /** Why model work cannot start right now, or null. Deterministic work is never blocked. */
40
43
  modelBlocked(): ModelBlock | null;
44
+ /**
45
+ * May the scripted create lane run? It needs a model for K4/K5 and must NOT consume the breaker's
46
+ * single half-open trial, which `modelBlocked()` does: ask that question twice and the agent task
47
+ * the trial was meant for is released as `curator_failing`. Absent = yes.
48
+ */
49
+ scriptedLaneAvailable?(): boolean;
41
50
  }
42
51
  /**
43
52
  * The proposal's evidence with refs minted ONCE: the validators' corpus (redacted exactly as the
@@ -27,7 +27,8 @@ import { assembleCuratorAgent, runCuratorAgent } from './agent.js';
27
27
  import { planTask } from './deterministic.js';
28
28
  import { executeDirect } from './executors.js';
29
29
  import { buildTaskPrompt, CURATOR_SYSTEM_PROMPT } from './prompt.js';
30
- import { createTaskContext } from './task-context.js';
30
+ import { isScriptedLaneEnabled, isScriptedShape, writeScriptedCandidate } from './scripted-lane.js';
31
+ import { createTaskContext, describeTaskStats } from './task-context.js';
31
32
  import { createCuratorToolkit } from './tools.js';
32
33
  import { settleLeftovers } from './tools-release.js';
33
34
  // ---------------------------------------------------------------------------
@@ -165,6 +166,7 @@ async function finishedOutcome(deps, env, finish) {
165
166
  // ---------------------------------------------------------------------------
166
167
  async function modelOutcome(deps, env, summary) {
167
168
  const { ctx } = env;
169
+ ctx.stats.turns = summary.turns;
168
170
  if (ctx.abandoned !== null)
169
171
  return abandonOutcome(deps, ctx.proposal, ctx.abandoned);
170
172
  if (summary.stop === 'aborted')
@@ -173,7 +175,7 @@ async function modelOutcome(deps, env, summary) {
173
175
  const error = summary.stop === 'timeout' ? 'task_timeout' : (summary.error?.errorType ?? 'model_error');
174
176
  deps.breaker.recordInfraFailure(error);
175
177
  await settleLeftovers(env, 'reject_failed');
176
- return { kind: 'fail', failure: { kind: 'transient', error }, infra: true };
178
+ return { kind: 'fail', failure: { kind: 'transient', error }, infra: true, stats: describeTaskStats(ctx.stats) };
177
179
  }
178
180
  deps.breaker.recordSuccess();
179
181
  if (ctx.finish !== null)
@@ -183,7 +185,7 @@ async function modelOutcome(deps, env, summary) {
183
185
  // `task_tokens` means raise `gene.curatorTaskTokens`, `task_turns` means the task is doing too
184
186
  // many small steps (RC-6). One `task_budget` name used to hide that from the run log.
185
187
  const error = summary.stop === 'tokens' ? 'task_tokens' : summary.stop === 'turns' ? 'task_turns' : 'no_finish';
186
- return { kind: 'fail', failure: { kind: 'transient', error }, infra: false };
188
+ return { kind: 'fail', failure: { kind: 'transient', error }, infra: false, stats: describeTaskStats(ctx.stats) };
187
189
  }
188
190
  async function runModelTask(deps, claimed, plan, signal) {
189
191
  const proposal = claimed.item.proposal;
@@ -227,6 +229,39 @@ async function runModelTask(deps, claimed, plan, signal) {
227
229
  }
228
230
  }
229
231
  // ---------------------------------------------------------------------------
232
+ // The scripted create lane (F2)
233
+ // ---------------------------------------------------------------------------
234
+ /**
235
+ * A reviewer's complete knowledge draft that K1-K3 would accept is written and validated by code,
236
+ * with no agent (`scripted-lane.ts` has the why). `null` hands the proposal to the agent loop
237
+ * untouched; the decision to decline is always made BEFORE a candidate exists.
238
+ */
239
+ async function runScriptedLane(deps, claimed, plan) {
240
+ const proposal = claimed.item.proposal;
241
+ if (!isScriptedLaneEnabled() || !isScriptedShape(proposal) || deps.scriptedLaneAvailable?.() === false)
242
+ return null;
243
+ const config = await deps.toolDeps.switches.effective();
244
+ // The daily budget stays a hard limit: the validators spend a little, and an exhausted window is the
245
+ // agent path's to report (a `budget` failure that waits for the reset), not the lane's to ignore.
246
+ if ((await deps.budget.daily(config)).exhausted)
247
+ return null;
248
+ const ctx = newContext(deps, claimed, { basis: plan.basis, rebased: plan.rebased });
249
+ const env = { ctx, deps: deps.toolDeps };
250
+ try {
251
+ const written = await writeScriptedCandidate(env);
252
+ if (written === 'abandoned')
253
+ return ctx.abandoned === null ? null : await abandonOutcome(deps, proposal, ctx.abandoned);
254
+ if (written === null)
255
+ return null;
256
+ await deps.toolDeps.events.emit('distilling', { ...scopeFields(proposal), type: 'knowledge', detail: 'scripted' });
257
+ const result = await executeDirect({ env, queue: deps.queue, random: deps.random, capPerType: config.capPerType }, { kind: 'resume_validation', candidate: written });
258
+ return await directOutcome(deps, proposal, result);
259
+ }
260
+ finally {
261
+ ctx.active = false;
262
+ }
263
+ }
264
+ // ---------------------------------------------------------------------------
230
265
  // Entry point
231
266
  // ---------------------------------------------------------------------------
232
267
  /** Decide one claimed item. Never throws; the host turns an unexpected failure into a retry. */
@@ -246,7 +281,7 @@ export async function runClaimedTask(deps, claimed, signal) {
246
281
  if (plan.mode === 'release')
247
282
  return { kind: 'release', reason: plan.reason };
248
283
  if (plan.mode === 'model')
249
- return runModelTask(deps, claimed, plan, signal);
284
+ return (await runScriptedLane(deps, claimed, plan)) ?? runModelTask(deps, claimed, plan, signal);
250
285
  const ctx = newContext(deps, claimed, { basis: new Map(), rebased: false });
251
286
  const env = { ctx, deps: deps.toolDeps };
252
287
  const config = await switches.effective();
@@ -23,7 +23,7 @@ import { GENE_LIMITS } from '@aragon-agent/tui/model/gene/limits';
23
23
  import { normalizeApplicability, } from '@aragon-agent/tui/model/gene/validate';
24
24
  import { GeneStoreError } from '../gene-errors.js';
25
25
  import { geneLooksLikeSecret } from '../secrets.js';
26
- import { assertCuratorContext } from './task-context.js';
26
+ import { assertCuratorContext, noteToolCall } from './task-context.js';
27
27
  import { syncSkillDeps } from './validate/skill.js';
28
28
  export const CURATOR_ACTOR = { kind: 'curator', label: 'gene-curator' };
29
29
  export function paramsOf(raw) {
@@ -54,7 +54,11 @@ export function refuse(tool, code, message) {
54
54
  }
55
55
  export function failureResult(tool, failure) {
56
56
  const code = failure.detail === undefined ? failure.code : `${failure.code}:${failure.detail}`;
57
- return refuse(tool, code, describeGeneError(failure.code, failure.detail));
57
+ const copy = describeGeneError(failure.code, failure.detail);
58
+ // Only a content refusal carries its own explanation: `issuesToFailure` builds it from the
59
+ // validators' closed vocabulary. Every other code's `message` is unaudited prose, so it stays out.
60
+ const fix = failure.code === 'GENE_INVALID_CONTENT' && failure.message.length > 0 ? ` To fix: ${failure.message}` : '';
61
+ return refuse(tool, code, `${copy}${fix}`);
58
62
  }
59
63
  /** A refusal that ends the task is recorded on the context; the answer still reaches the model. */
60
64
  export function applyFailureEffects(ctx, failure) {
@@ -120,13 +124,16 @@ export function defineCuratorTool(env, spec) {
120
124
  const denied = assertCuratorContext(env.ctx);
121
125
  if (denied !== null)
122
126
  return denied;
127
+ let result;
123
128
  try {
124
- return await spec.run(paramsOf(raw), callId);
129
+ result = await spec.run(paramsOf(raw), callId);
125
130
  }
126
131
  catch (error) {
127
132
  const detail = error instanceof GeneStoreError ? error.code : 'GENE_UNAVAILABLE';
128
- return refuse(spec.name, detail, 'The library could not complete that. Try once more or finish retry.');
133
+ result = refuse(spec.name, detail, 'The library could not complete that. Try once more or finish retry.');
129
134
  }
135
+ noteToolCall(env.ctx, spec.name, result);
136
+ return result;
130
137
  },
131
138
  });
132
139
  }