@aragon-agent/cli 0.6.64 → 0.6.66

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.
@@ -186,9 +186,38 @@ async function listOrSearch(run, query) {
186
186
  const rows = await collectRows(run.manager, selection, ceiling);
187
187
  if (!rows.ok)
188
188
  return failed(run.io, rows);
189
- const text = rows.value.length === 0 ? 'No genes.' : rows.value.map((row) => row.line).join('\n');
189
+ const text = rows.value.length === 0 ? await emptyText(run, selection, query) : rows.value.map(rowText).join('\n');
190
190
  return print(run, { genes: rows.value.map(rowJson), total: rows.value.length }, text);
191
191
  }
192
+ /**
193
+ * A row's text line. `line` carries the markers but not the lifecycle status, so a rejected gene
194
+ * and a published one look the same under `--status all`; any status other than published is said.
195
+ */
196
+ function rowText(row) {
197
+ return row.status === 'published' ? row.line : `${row.line} (${row.status})`;
198
+ }
199
+ /**
200
+ * "No genes." is only true when the library has none. The default selection is this project's view,
201
+ * published only, so an empty answer may just mean the genes are elsewhere or not published; one
202
+ * more look at the whole library says which, and the text names the command that shows them.
203
+ */
204
+ async function emptyText(run, selection, query) {
205
+ // A search that found nothing says so; the hint below is for a plain listing.
206
+ if (query !== undefined)
207
+ return 'No genes.';
208
+ const { type } = selection.filter;
209
+ const whole = await run.manager.list({
210
+ target: { kind: 'allProjects' },
211
+ filter: type === undefined ? {} : { type },
212
+ limit: 1,
213
+ });
214
+ if (!whole.ok || whole.value.rows.length === 0)
215
+ return 'No genes.';
216
+ return [
217
+ 'No genes match, but the library holds others (in other projects, or not published).',
218
+ 'Show everything: aragon gene list --scope all --status all',
219
+ ].join('\n');
220
+ }
192
221
  function runList(run) {
193
222
  return listOrSearch(run);
194
223
  }
@@ -11,6 +11,7 @@
11
11
  */
12
12
  import { describeGeneError, pausedReasonCopy, runEventLabel } from '@aragon-agent/tui/model/gene/copy';
13
13
  import { stripHiddenControls } from '@aragon-agent/tui/model/gene/escape';
14
+ import { isBudgetEnforced } from './curator/budget.js';
14
15
  export function clean(text) {
15
16
  return stripHiddenControls(text);
16
17
  }
@@ -76,7 +77,10 @@ export function statusLines(view, facts) {
76
77
  const lines = [switchLine(view), ...libraryLines(view), contextLine(view), ...workerLines(view)];
77
78
  if (facts.config !== undefined) {
78
79
  const budget = facts.config.dailyTokens;
79
- lines.push(`Tokens: ${facts.tokensToday} of ${budget} used in the last 24 hours.`);
80
+ // Metering is the default; the ceiling is only worth showing when it is real (enforced, or 0 = off).
81
+ lines.push(isBudgetEnforced() || budget <= 0
82
+ ? `Tokens: ${facts.tokensToday} of ${budget} used in the last 24 hours.`
83
+ : `Tokens: ${facts.tokensToday} used in the last 24 hours (no daily limit).`);
80
84
  lines.push(`Holdout: ${facts.config.holdoutPercent}% of runs deliberately skip the library.`);
81
85
  }
82
86
  if (view.last !== undefined) {
@@ -1,4 +1,21 @@
1
1
  import type { GeneConfig } from '@aragon-agent/tui/model/config/schema';
2
+ /** The operator's switch: `1` makes `gene.dailyTokens` and `gene.curatorTaskTokens` ceilings again. */
3
+ export declare const BUDGET_ENFORCED_ENV = "ARAGON_GENE_BUDGET_ENFORCED";
4
+ /**
5
+ * A task's internal token valve while the budget is not enforced. Not a setting. A curator task that
6
+ * is making progress needs 45k-95k tokens (measured), and a loop that is not making progress is
7
+ * ended by the turn and wall-clock limits first, so this only fires when a model has gone wrong in
8
+ * a way those two cannot see (a very large prompt on every turn).
9
+ */
10
+ export declare const RUNAWAY_TASK_TOKENS = 400000;
11
+ /** Are the token ceilings (`dailyTokens`, `curatorTaskTokens`) enforced? Off unless the env var is `1`. */
12
+ export declare function isBudgetEnforced(env?: Readonly<Record<string, string | undefined>>): boolean;
13
+ /**
14
+ * The one question every daily-budget gate asks (the curator's pause, a task's admission, the
15
+ * scripted lane, the learner's call). `limit <= 0` is "do not spend" in both modes; a positive
16
+ * limit only stops anything while the budget is enforced.
17
+ */
18
+ export declare function isDailyBudgetExhausted(limit: number, used: number, enforced?: boolean): boolean;
2
19
  export interface TaskLimits {
3
20
  tokens: number;
4
21
  turns: number;
@@ -22,7 +39,13 @@ export interface BudgetDeps {
22
39
  */
23
40
  export declare const IMPORT_MIN_REMAINING_SHARE = 0.5;
24
41
  /** May a cold-start import proposal be claimed now? Pure over the day's budget state. */
25
- export declare function importClaimAllowed(daily: Pick<DailyState, 'limit' | 'used'>): boolean;
42
+ export declare function importClaimAllowed(daily: Pick<DailyState, 'limit' | 'used'>, enforced?: boolean): boolean;
43
+ /**
44
+ * How many estimated tokens one cold-start import preview may queue: half of today's remaining
45
+ * allowance while the budget is enforced, otherwise no token cap (the count and queue-room limits
46
+ * still apply). `limit <= 0` stays zero.
47
+ */
48
+ export declare function importTokenAllowance(limit: number, used: number, enforced?: boolean): number;
26
49
  export declare class CuratorBudget {
27
50
  private readonly deps;
28
51
  constructor(deps: BudgetDeps);
@@ -3,37 +3,85 @@
3
3
  *
4
4
  * ASCII ONLY - the whole `gene/` tree is in `glyphs.test.ts::inScope`.
5
5
  *
6
- * THREE LAYERS, EACH VISIBLE:
7
- * - per TASK tokens (`gene.curatorTaskTokens`), turns (20) and wall clock (240 s). A task that
8
- * crosses one is stopped and retried later; it cannot run away.
9
- * - per DAY a rolling 24 h sum of every `tokens` field in the run log (the learner's, the
10
- * curator's, the validators' and retrieval's share ONE budget). At the limit the
11
- * curator pauses and the queue keeps everything. The deterministic P0 paths
12
- * (revoke, rollback, recheck) never consult it: they spend no tokens.
6
+ * TOKENS ARE METERED, NOT RATIONED (the default). Publishing, revising and retiring genes is the
7
+ * point of the library, and the only thing a token ceiling ever did was freeze it: a nine-minute
8
+ * burst of killed attempts once parked the whole pipeline - the reviewer included - for a day, and
9
+ * the experience that happened meanwhile was never reviewed. So `gene.dailyTokens` and
10
+ * `gene.curatorTaskTokens` are no longer enforced; the run log still records every token and
11
+ * `/gene` still shows the 24 h sum. ONE predicate decides, `isBudgetEnforced()`: set
12
+ * `ARAGON_GENE_BUDGET_ENFORCED=1` to bring the old ceilings back (for a comparison or an
13
+ * emergency). Every gate that used to look at the limits asks it, in this file, so there is one
14
+ * place to flip and one place a test has to pin. `dailyTokens <= 0` keeps its older meaning,
15
+ * "do not spend at all", and is honoured in both modes.
16
+ *
17
+ * WHAT STILL STOPS A RUNAWAY, none of it a budget:
18
+ * - per TASK turns (20), wall clock (240 s) and `RUNAWAY_TASK_TOKENS`, an internal valve that is
19
+ * not a setting and sits far above any task that is making progress. A task that
20
+ * crosses one is stopped and retried later (at most twice for an overrun).
13
21
  * - per FAILURE STREAK three consecutive infrastructure failures open a breaker for 30 minutes;
14
22
  * then ONE trial request is let through (half-open) and its result decides.
23
+ * The deterministic P0 paths (revoke, rollback, recheck) never consult any of it: they spend no tokens.
15
24
  *
16
- * THE RESET TIME IS AN ESTIMATE. A rolling window has no single reset instant: spend ages out
17
- * hour by hour. `daily()` probes the window an hour at a time and reports the first instant at
18
- * which the sum is back under the limit, which is what a queued item's `notBefore` and the
19
- * "paused: daily budget" line show.
25
+ * WHEN ENFORCED (`ARAGON_GENE_BUDGET_ENFORCED=1`) the old behaviour applies in full: a rolling 24 h
26
+ * sum of every `tokens` field in the run log (the learner's, the curator's, the validators' and
27
+ * retrieval's share ONE budget) pauses the curator at the limit and the queue keeps everything, and
28
+ * each task is capped at `gene.curatorTaskTokens`. The reset time is then an estimate: a rolling
29
+ * window has no single reset instant, so `daily()` probes it an hour at a time and reports the
30
+ * first instant at which the sum is back under the limit.
20
31
  */
21
32
  import { GENE_LIMITS } from '@aragon-agent/tui/model/gene/limits';
22
33
  const HOUR_MS = 60 * 60 * 1000;
23
34
  const DAY_MS = 24 * HOUR_MS;
24
35
  /** When the limit is zero there is no instant at which more is allowed; look again in an hour. */
25
36
  const ZERO_LIMIT_RECHECK_MS = HOUR_MS;
37
+ /** The operator's switch: `1` makes `gene.dailyTokens` and `gene.curatorTaskTokens` ceilings again. */
38
+ export const BUDGET_ENFORCED_ENV = 'ARAGON_GENE_BUDGET_ENFORCED';
39
+ /**
40
+ * A task's internal token valve while the budget is not enforced. Not a setting. A curator task that
41
+ * is making progress needs 45k-95k tokens (measured), and a loop that is not making progress is
42
+ * ended by the turn and wall-clock limits first, so this only fires when a model has gone wrong in
43
+ * a way those two cannot see (a very large prompt on every turn).
44
+ */
45
+ export const RUNAWAY_TASK_TOKENS = 400_000;
46
+ /** Are the token ceilings (`dailyTokens`, `curatorTaskTokens`) enforced? Off unless the env var is `1`. */
47
+ export function isBudgetEnforced(env = process.env) {
48
+ return env[BUDGET_ENFORCED_ENV] === '1';
49
+ }
50
+ /**
51
+ * The one question every daily-budget gate asks (the curator's pause, a task's admission, the
52
+ * scripted lane, the learner's call). `limit <= 0` is "do not spend" in both modes; a positive
53
+ * limit only stops anything while the budget is enforced.
54
+ */
55
+ export function isDailyBudgetExhausted(limit, used, enforced = isBudgetEnforced()) {
56
+ if (limit <= 0)
57
+ return true;
58
+ return enforced && used >= limit;
59
+ }
26
60
  /**
27
61
  * Cold-start imports (`origin.source === 'import'`) are claimed only while at least this share of
28
62
  * the day's token allowance is still unspent: they must never starve live learning.
29
63
  */
30
64
  export const IMPORT_MIN_REMAINING_SHARE = 0.5;
31
65
  /** May a cold-start import proposal be claimed now? Pure over the day's budget state. */
32
- export function importClaimAllowed(daily) {
66
+ export function importClaimAllowed(daily, enforced = isBudgetEnforced()) {
33
67
  if (daily.limit <= 0)
34
68
  return false;
69
+ if (!enforced)
70
+ return true;
35
71
  return daily.limit - daily.used >= daily.limit * IMPORT_MIN_REMAINING_SHARE;
36
72
  }
73
+ /**
74
+ * How many estimated tokens one cold-start import preview may queue: half of today's remaining
75
+ * allowance while the budget is enforced, otherwise no token cap (the count and queue-room limits
76
+ * still apply). `limit <= 0` stays zero.
77
+ */
78
+ export function importTokenAllowance(limit, used, enforced = isBudgetEnforced()) {
79
+ if (limit <= 0)
80
+ return 0;
81
+ if (!enforced)
82
+ return Number.MAX_SAFE_INTEGER;
83
+ return Math.floor(Math.max(0, limit - used) * IMPORT_MIN_REMAINING_SHARE);
84
+ }
37
85
  export class CuratorBudget {
38
86
  deps;
39
87
  constructor(deps) {
@@ -41,7 +89,7 @@ export class CuratorBudget {
41
89
  }
42
90
  taskLimits(config) {
43
91
  return {
44
- tokens: config.curatorTaskTokens,
92
+ tokens: isBudgetEnforced() ? config.curatorTaskTokens : RUNAWAY_TASK_TOKENS,
45
93
  turns: GENE_LIMITS.curatorMaxTurns,
46
94
  wallMs: GENE_LIMITS.curatorWallClockMs,
47
95
  };
@@ -49,8 +97,13 @@ export class CuratorBudget {
49
97
  async daily(config) {
50
98
  const now = this.deps.now();
51
99
  const limit = config.dailyTokens;
100
+ if (limit > 0 && !isBudgetEnforced()) {
101
+ // Metering only: an unreadable log must not decide anything, so it reads as "nothing spent".
102
+ const used = await this.deps.tokensSince(now - DAY_MS).catch(() => 0);
103
+ return { limit, used, exhausted: false, resetAt: null };
104
+ }
52
105
  const used = await this.deps.tokensSince(now - DAY_MS);
53
- if (limit > 0 && used < limit)
106
+ if (!isDailyBudgetExhausted(limit, used, true))
54
107
  return { limit, used, exhausted: false, resetAt: null };
55
108
  return { limit, used, exhausted: true, resetAt: await this.estimateReset(now, limit) };
56
109
  }
@@ -150,6 +150,16 @@ export declare class GeneCurator {
150
150
  private notify;
151
151
  private tickOnce;
152
152
  private ensureLease;
153
+ /**
154
+ * Wake the proposals an earlier budget pause parked. `release` / a `budget` failure wrote their
155
+ * `notBefore` (up to a day out) into the queue file, and `claimNext` only reads the file, so lifting
156
+ * the budget gate does not wake them: they would sleep until the old window's reset. Done once per
157
+ * lease, never while the budget is enforced (the parking is then still true), and only for the items
158
+ * a budget pause parks: a `lastError` of `released` / `budget_exhausted` and a wait longer than the
159
+ * breaker's 30 minutes, which keeps the short, legitimate waits (no fast model, an open breaker, a
160
+ * network backoff) exactly as they were. Best effort: a failed pass is retried by the next lease.
161
+ */
162
+ private thawParkedItems;
153
163
  private every;
154
164
  private housekeeping;
155
165
  private recoverStale;
@@ -26,10 +26,11 @@
26
26
  * curator at its next checkpoint.
27
27
  *
28
28
  * PAUSING NEVER DESTROYS WORK. Forced or switch-driven pauses (red team, learning off) claim
29
- * nothing. Model-related pauses (no fast model, an open breaker, the daily budget) still let
30
- * the deterministic paths run - a revoke or a rollback spends no tokens and must not wait for a
31
- * budget - and put model items back with a `notBefore`, no attempt counted. Every pause and resume
32
- * is a run record, with the reason as the first word of its detail (the activity hub reads that).
29
+ * nothing. Model-related pauses (no fast model, an open breaker, and the daily budget when it is
30
+ * enforced - `budget.ts`, off by default) still let the deterministic paths run - a revoke or a
31
+ * rollback spends no tokens and must not wait for a budget - and put model items back with a
32
+ * `notBefore`, no attempt counted. Every pause and resume is a run record, with the reason as the
33
+ * first word of its detail (the activity hub reads that).
33
34
  *
34
35
  * LOGGING NEVER CARRIES GENE TEXT (I-19): ids, scopes, enums, counts and stable tokens only.
35
36
  */
@@ -37,7 +38,7 @@ import { agingPriority } from '@aragon-agent/tui/model/gene/proposal';
37
38
  import { scopeId } from '@aragon-agent/tui/model/gene/ids';
38
39
  import { GENE_LIMITS } from '@aragon-agent/tui/model/gene/limits';
39
40
  import { curatorLeaseFile } from '../paths.js';
40
- import { BREAKER_OPEN_MS, CircuitBreaker, CuratorBudget, importClaimAllowed, } from './budget.js';
41
+ import { BREAKER_OPEN_MS, CircuitBreaker, CuratorBudget, importClaimAllowed, isBudgetEnforced, } from './budget.js';
41
42
  import { makeSystemProposal } from './executors.js';
42
43
  import { LaneScheduler } from './lanes.js';
43
44
  import { CuratorLease } from './lease.js';
@@ -326,6 +327,10 @@ export class GeneCurator {
326
327
  if (!got.ok)
327
328
  return false;
328
329
  this.leaseErrors = 0;
330
+ // The pause the log shows belongs to whoever held the lease: the activity hub drops it at
331
+ // `lease_acquired`. A process that lost the lease and took it back would otherwise find its own
332
+ // pause "unchanged" and never say it again, leaving the chip idle while nothing is claimed.
333
+ this.paused = undefined;
329
334
  this.lastRun.clear();
330
335
  this.lastRun.set('maintenance', now - this.timing.maintenanceMs + this.timing.maintenanceFirstMs);
331
336
  if (this.timing.choresFirstRun === 'after_interval') {
@@ -333,8 +338,32 @@ export class GeneCurator {
333
338
  this.lastRun.set(chore, now);
334
339
  }
335
340
  await this.events.emit('lease_acquired', { detail: got.takenOver ? 'takeover' : 'fresh' });
341
+ await this.thawParkedItems();
336
342
  return true;
337
343
  }
344
+ /**
345
+ * Wake the proposals an earlier budget pause parked. `release` / a `budget` failure wrote their
346
+ * `notBefore` (up to a day out) into the queue file, and `claimNext` only reads the file, so lifting
347
+ * the budget gate does not wake them: they would sleep until the old window's reset. Done once per
348
+ * lease, never while the budget is enforced (the parking is then still true), and only for the items
349
+ * a budget pause parks: a `lastError` of `released` / `budget_exhausted` and a wait longer than the
350
+ * breaker's 30 minutes, which keeps the short, legitimate waits (no fast model, an open breaker, a
351
+ * network backoff) exactly as they were. Best effort: a failed pass is retried by the next lease.
352
+ */
353
+ async thawParkedItems() {
354
+ if (isBudgetEnforced())
355
+ return;
356
+ try {
357
+ const now = this.now();
358
+ const thawed = await this.deps.queue.thawPendingWhere((record) => (record.lastError === 'released' || record.lastError === 'budget_exhausted') &&
359
+ record.notBefore - now > BREAKER_OPEN_MS);
360
+ if (thawed.length > 0)
361
+ await this.events.emit('skipped', { detail: `thawed n=${thawed.length}` });
362
+ }
363
+ catch {
364
+ // The items keep their old wait; nothing is lost.
365
+ }
366
+ }
338
367
  async every(name, ms, job) {
339
368
  const last = this.lastRun.get(name);
340
369
  const now = this.now();
@@ -431,6 +460,7 @@ export class GeneCurator {
431
460
  this.modelBlock = { reason: 'curator_failing', until: view.until ?? this.now() + BREAKER_OPEN_MS };
432
461
  return 'curator_failing';
433
462
  }
463
+ // Only ever exhausted while the budget is enforced, or when `dailyTokens` is 0 ("do not spend").
434
464
  const daily = await this.budget.daily(config);
435
465
  if (daily.exhausted) {
436
466
  const resetAt = daily.resetAt ?? until;
@@ -107,6 +107,14 @@ export declare function createTaskContext(seed: ContextSeed): CuratorTaskContext
107
107
  * `detail`; empty when the task took no turn. Bounded: the log clips a detail at 240 characters.
108
108
  */
109
109
  export declare function describeTaskStats(stats: TaskStats): string;
110
+ /** Turns after which a task that has called no tool at all still counts as having worked. */
111
+ export declare const PROGRESS_MIN_TURNS = 3;
112
+ /**
113
+ * Did the task get anywhere before something ended it: one tool call, or `PROGRESS_MIN_TURNS`
114
+ * model turns? A deadline that finds a task with neither is a stalled provider; one that finds
115
+ * either is a task too big for the clock (`task-runner.ts::modelOutcome`).
116
+ */
117
+ export declare function madeProgress(stats: TaskStats): boolean;
110
118
  /** Count one finished tool call, and its refusal code when it was refused. Never throws. */
111
119
  export declare function noteToolCall(ctx: CuratorTaskContext, tool: string, result: ToolResult): void;
112
120
  /** A tool refusal, or null when the context is a live curator task. Never throws. */
@@ -69,6 +69,16 @@ export function describeTaskStats(stats) {
69
69
  const refusals = listed(stats.refusals, STATS_MAX_REFUSALS);
70
70
  return ` turns=${stats.turns}${tools === '' ? '' : ` tools=${tools}`}${refusals === '' ? '' : ` refusals=${refusals}`}`;
71
71
  }
72
+ /** Turns after which a task that has called no tool at all still counts as having worked. */
73
+ export const PROGRESS_MIN_TURNS = 3;
74
+ /**
75
+ * Did the task get anywhere before something ended it: one tool call, or `PROGRESS_MIN_TURNS`
76
+ * model turns? A deadline that finds a task with neither is a stalled provider; one that finds
77
+ * either is a task too big for the clock (`task-runner.ts::modelOutcome`).
78
+ */
79
+ export function madeProgress(stats) {
80
+ return stats.tools.size > 0 || stats.turns >= PROGRESS_MIN_TURNS;
81
+ }
72
82
  /** Count one finished tool call, and its refusal code when it was refused. Never throws. */
73
83
  export function noteToolCall(ctx, tool, result) {
74
84
  const { stats } = ctx;
@@ -18,8 +18,10 @@
18
18
  *
19
19
  * A TASK THAT ENDS WITHOUT `gene_finish` IS A RETRY (10.3). A task that ran out of tokens or turns
20
20
  * is a retry too, and counts as an attempt so a proposal that always overruns reaches `dead/`
21
- * instead of looping; a deadline or a model error is an INFRASTRUCTURE failure and is what the
22
- * circuit breaker counts. A daily-budget stop is not the item's fault and costs no attempt.
21
+ * instead of looping; a model error, or a deadline that found the task doing nothing, is an
22
+ * INFRASTRUCTURE failure and is what the circuit breaker counts. A deadline that cut off a task that
23
+ * was working is the task's own overrun (`task_wallclock`), not a sick provider. A daily-budget stop
24
+ * exists only while the budget is enforced (`budget.ts`); it is not the item's fault and costs no attempt.
23
25
  */
24
26
  import { mintEvidenceRef } from '@aragon-agent/tui/model/gene/ids';
25
27
  import { redactSecrets } from '../secrets.js';
@@ -28,7 +30,7 @@ import { planTask } from './deterministic.js';
28
30
  import { executeDirect } from './executors.js';
29
31
  import { buildTaskPrompt, CURATOR_SYSTEM_PROMPT } from './prompt.js';
30
32
  import { isScriptedLaneEnabled, isScriptedShape, writeScriptedCandidate } from './scripted-lane.js';
31
- import { createTaskContext, describeTaskStats } from './task-context.js';
33
+ import { createTaskContext, describeTaskStats, madeProgress, } from './task-context.js';
32
34
  import { createCuratorToolkit } from './tools.js';
33
35
  import { settleLeftovers } from './tools-release.js';
34
36
  // ---------------------------------------------------------------------------
@@ -171,6 +173,15 @@ async function modelOutcome(deps, env, summary) {
171
173
  return abandonOutcome(deps, ctx.proposal, ctx.abandoned);
172
174
  if (summary.stop === 'aborted')
173
175
  return { kind: 'release', reason: 'released' };
176
+ if (summary.stop === 'timeout' && madeProgress(ctx.stats)) {
177
+ // Without the per-task token valve a working task can outlast the wall clock. That is the task
178
+ // outgrowing its ceiling, like `task_tokens` did, not the provider failing: it must not trip the
179
+ // breaker (three of these would stop the curator for 30 minutes) and it gets the overrun retry limit.
180
+ deps.breaker.recordSuccess();
181
+ await settleLeftovers(env, 'reject_failed');
182
+ const stats = describeTaskStats(ctx.stats);
183
+ return { kind: 'fail', failure: { kind: 'transient', error: 'task_wallclock' }, infra: false, stats };
184
+ }
174
185
  if (summary.stop === 'error' || summary.stop === 'timeout') {
175
186
  const error = summary.stop === 'timeout' ? 'task_timeout' : (summary.error?.errorType ?? 'model_error');
176
187
  deps.breaker.recordInfraFailure(error);
@@ -241,8 +252,8 @@ async function runScriptedLane(deps, claimed, plan) {
241
252
  if (!isScriptedLaneEnabled() || !isScriptedShape(proposal) || deps.scriptedLaneAvailable?.() === false)
242
253
  return null;
243
254
  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.
255
+ // An exhausted budget (only possible while it is enforced, or when `dailyTokens` is 0) is the agent
256
+ // path's to report - a `budget` failure that waits for the reset - not the lane's to ignore.
246
257
  if ((await deps.budget.daily(config)).exhausted)
247
258
  return null;
248
259
  const ctx = newContext(deps, claimed, { basis: plan.basis, rebased: plan.rebased });
package/dist/gene/hub.js CHANGED
@@ -73,6 +73,11 @@ export function foldCuratorRecord(fold, record) {
73
73
  pause(next, record);
74
74
  else if (record.ev === 'resumed')
75
75
  next.paused = undefined;
76
+ // A new lease holder works out its own pause from scratch and says so if one applies, so a pause the
77
+ // previous holder left in the log is stale the moment it takes over (it would otherwise be shown until
78
+ // some item was claimed, even with an empty queue).
79
+ else if (record.ev === 'lease_acquired')
80
+ next.paused = undefined;
76
81
  else if (ENDS_ITEM.has(record.ev) && finishesCurrent(fold, record))
77
82
  finishItem(next);
78
83
  return next;
@@ -14,10 +14,11 @@
14
14
  * 1. COUNT `min(gene.importMaxItems, queueRoom, sources)`. `queueRoom` is the queue's cap
15
15
  * minus what is pending minus 100 held back for the reviewer's live proposals;
16
16
  * an import that filled the queue would make live `p=4` proposals get dropped.
17
- * 2. BUDGET estimated tokens must fit in half of today's remaining allowance; a source that
17
+ * 2. BUDGET while the token budget is enforced (`curator/budget.ts`, off by default),
18
+ * estimated tokens must fit in half of today's remaining allowance; a source that
18
19
  * does not fit is "left for next time", not dropped. The curator enforces the same
19
20
  * half at claim time (`importClaimAllowed`), because the budget moves after a
20
- * preview.
21
+ * preview. Unenforced, only the count and the queue room limit an import.
21
22
  * 3. IDEMPOTENCE the same source at the same content is never queued twice: its dedupe key is
22
23
  * looked for in pending, claimed, done and dead, and its reference in the ledger
23
24
  * (`import-ledger.jsonl`), which outlives the pruning of `done/`.
@@ -35,7 +36,7 @@ import { CHARS_PER_TOKEN } from '@aragon-agent/core';
35
36
  import { embedFields, encodeVec } from '@aragon-agent/tui/model/gene/hashvec';
36
37
  import { GENE_LIMITS } from '@aragon-agent/tui/model/gene/limits';
37
38
  import { fingerprintOf } from '@aragon-agent/tui/model/gene/validate';
38
- import { IMPORT_MIN_REMAINING_SHARE } from './curator/budget.js';
39
+ import { importTokenAllowance } from './curator/budget.js';
39
40
  import { appendJsonl, readText } from './fs.js';
40
41
  import { geneFail, geneOk } from './gene-errors.js';
41
42
  import { buildImportProposal, importDedupeKey, sourceRefOf } from './import-proposal.js';
@@ -148,8 +149,10 @@ export class GeneImporter {
148
149
  }
149
150
  async budgetOf() {
150
151
  const dailyTokens = this.deps.core.config().dailyTokens;
151
- const remaining = Math.max(0, dailyTokens - (await this.deps.tokensToday()));
152
- const allowed = Math.floor(remaining * IMPORT_MIN_REMAINING_SHARE);
152
+ const used = await this.deps.tokensToday();
153
+ const remaining = Math.max(0, dailyTokens - used);
154
+ // Half of what is left while the budget is enforced; otherwise no token cap (`budget.ts`).
155
+ const allowed = importTokenAllowance(dailyTokens, used);
153
156
  return { dailyTokens, remaining, allowed, exceeded: false };
154
157
  }
155
158
  /** The newest sources that fit the count, the room and the token allowance. */
@@ -32,6 +32,7 @@
32
32
  */
33
33
  import { collectSignals, shouldLearn, } from '@aragon-agent/tui/model/gene/signals';
34
34
  import { normalizeLearningOutput } from '@aragon-agent/tui/model/gene/proposal';
35
+ import { isBudgetEnforced, isDailyBudgetExhausted } from '../curator/budget.js';
35
36
  import { EvidenceLedger, } from './ledger.js';
36
37
  import { factsFromLedger } from './signals-port.js';
37
38
  import { buildLearningInput, LEARN_SKILLS_PER_REPLY, LEARN_SYSTEM_PROMPT } from './learn-prompt.js';
@@ -171,12 +172,15 @@ export class GeneLearner {
171
172
  async refreshBudget() {
172
173
  try {
173
174
  const cfg = this.deps.config();
174
- if (cfg.dailyTokens <= 0) {
175
- this.budgetExhausted = true;
175
+ // `dailyTokens <= 0` is "do not spend" in both modes. A positive limit only stops the reviewer
176
+ // while the budget is enforced (`budget.ts`): metering must never cost the library its
177
+ // experience, which cannot be reviewed later - the session it came from is gone.
178
+ if (cfg.dailyTokens <= 0 || !isBudgetEnforced()) {
179
+ this.budgetExhausted = isDailyBudgetExhausted(cfg.dailyTokens, 0);
176
180
  return;
177
181
  }
178
182
  const spent = await this.deps.runLog.tokensSince(this.deps.now() - DAY_MS);
179
- this.budgetExhausted = spent >= cfg.dailyTokens;
183
+ this.budgetExhausted = isDailyBudgetExhausted(cfg.dailyTokens, spent, true);
180
184
  }
181
185
  catch {
182
186
  // Keep the last known answer: an unreadable log must not flip learning on or off.
@@ -211,6 +211,14 @@ export declare class GeneQueue implements ProposalFence {
211
211
  * redacted: `retryDead` puts an item back. Returns the ids moved. `reasonOf` must be PURE and cheap.
212
212
  */
213
213
  quarantinePendingWhere(reasonOf: (proposal: GeneProposal) => string | null): Promise<string[]>;
214
+ /**
215
+ * Give every `pending/` item `isParked` names a clean `notBefore` (so it is claimable now) and
216
+ * return their ids. Counts nothing against the item: no attempt, no outcome, same file name. This
217
+ * is for waits that no longer have a reason (a budget window that is no longer enforced); the
218
+ * caller owns the policy, `isParked` must be PURE and cheap, and the rewrite is under the item's
219
+ * own lock like every other change to a pending file.
220
+ */
221
+ thawPendingWhere(isParked: (record: GeneQueueRecord) => boolean): Promise<string[]>;
214
222
  private settlePending;
215
223
  /** Counts per state, cached for one second (12.8); the queue's own writes drop the cache. */
216
224
  counts(): Promise<QueueCounts>;
@@ -64,8 +64,17 @@ export const QUEUE_MAX_ATTEMPTS = 4;
64
64
  * network-class errors (a timeout, a provider fault) keep all four: those are not the item's fault.
65
65
  */
66
66
  export const QUEUE_MAX_OVERRUN_ATTEMPTS = 2;
67
- /** The errors `task-runner.ts` records when a task hit a ceiling. `task_budget` is the pre-split name. */
68
- const OVERRUN_ERRORS = new Set(['task_tokens', 'task_turns', 'no_finish', 'task_budget']);
67
+ /**
68
+ * The errors `task-runner.ts` records when a task hit a ceiling (`task_wallclock`: the clock ended a task
69
+ * that was working). `task_budget` is the pre-split name. `task_timeout` is NOT here: that is a stall.
70
+ */
71
+ const OVERRUN_ERRORS = new Set([
72
+ 'task_tokens',
73
+ 'task_turns',
74
+ 'task_wallclock',
75
+ 'no_finish',
76
+ 'task_budget',
77
+ ]);
69
78
  /** Backoff after the 1st, 2nd and 3rd transient failure; the 4th goes to `dead/`. */
70
79
  export const QUEUE_BACKOFF_MS = [30_000, 120_000, 600_000];
71
80
  /** How many attempts a transient failure of this kind may use before the item is quarantined. */
@@ -540,6 +549,33 @@ export class GeneQueue {
540
549
  this.invalidateCounts();
541
550
  return moved;
542
551
  }
552
+ /**
553
+ * Give every `pending/` item `isParked` names a clean `notBefore` (so it is claimable now) and
554
+ * return their ids. Counts nothing against the item: no attempt, no outcome, same file name. This
555
+ * is for waits that no longer have a reason (a budget window that is no longer enforced); the
556
+ * caller owns the policy, `isParked` must be PURE and cheap, and the rewrite is under the item's
557
+ * own lock like every other change to a pending file.
558
+ */
559
+ async thawPendingWhere(isParked) {
560
+ const thawed = [];
561
+ for (const parsed of await this.parsedPending()) {
562
+ const path = queueFile('pending', parsed.name, this.ctx);
563
+ if (path === null)
564
+ continue;
565
+ const locked = await this.withLock(parsed.name, async () => {
566
+ const record = await this.readRecord(path);
567
+ if (record === null || !isParked(record))
568
+ return null;
569
+ await this.rewrite(path, { ...record, notBefore: 0 });
570
+ return record.proposal.id;
571
+ }, SETTLE_LOCK_ATTEMPTS);
572
+ if (locked.held && locked.value !== null)
573
+ thawed.push(locked.value);
574
+ }
575
+ if (thawed.length > 0)
576
+ this.invalidateCounts();
577
+ return thawed;
578
+ }
543
579
  async settlePending(parsed, outcome, redact = false) {
544
580
  const from = queueFile('pending', parsed.name, this.ctx);
545
581
  const to = queueFile('done', parsed.name, this.ctx);
@@ -67,6 +67,12 @@ export function makeController(flags, opts = { interactive: true }) {
67
67
  const controller = new AgentController(config, {
68
68
  version: VERSION,
69
69
  todoPanelCapable,
70
+ // THE SAME ANSWER `todoPanelCapable` GIVES, for the same reason (tiered-reconnect
71
+ // §4.4 / D-6): a headless host is headless. `-p`, `aragon exec` and every
72
+ // subcommand build with `interactive: false` and therefore get the BOUNDED
73
+ // ladder (two tiers), while the TUI keeps the full three. Derived here rather
74
+ // than threaded through five call sites, so no host can forget it.
75
+ reconnectMode: opts.interactive ? 'interactive' : 'headless',
70
76
  confirm: (req) => confirmBridge.handler ? confirmBridge.handler(req) : Promise.resolve(true),
71
77
  // THE TWO CAN NEVER BOTH BE PRESENT: `interactive: false` is the only path
72
78
  // that supplies a bridge gate, and the interactive branch is the only one that
@@ -201,6 +201,9 @@ export type AgentLogEvent = {
201
201
  errorType?: string;
202
202
  message?: unknown;
203
203
  retryAfterMs?: number;
204
+ tier?: number;
205
+ tierCount?: number;
206
+ totalAttempts?: number;
204
207
  discardedToolCallIds?: string[];
205
208
  };
206
209
  } | {
@@ -373,6 +373,14 @@ export function attachAgentEvents(logger, controller) {
373
373
  // retry line stays small; an HTTP-error body already arrives cut at 300.
374
374
  message: typeof se.message === 'string' ? se.message.slice(0, 200) : undefined,
375
375
  retryAfterMs: se.retryAfterMs,
376
+ // TIERED RECONNECT (§4.6.7). `attempt` is per-tier, so an operator
377
+ // reading one line cannot tell a 3rd fast retry from a 3rd five-minute
378
+ // hold; these three say which ladder and how long it has been going.
379
+ // Absent when the host does not escalate, so the record shape is
380
+ // unchanged there.
381
+ ...(se.tier !== undefined ? { tier: se.tier } : {}),
382
+ ...(se.tierCount !== undefined ? { tierCount: se.tierCount } : {}),
383
+ ...(se.totalAttempts !== undefined ? { totalAttempts: se.totalAttempts } : {}),
376
384
  providerId: cfg.provider,
377
385
  modelId: cfg.model,
378
386
  });
@@ -196,8 +196,15 @@ export function normalizeLoadedEntries(entries) {
196
196
  // would never advance past it and every frame for the rest of the session
197
197
  // would re-render the whole tail. `resumeAt` is dropped for the same reason
198
198
  // the phase changes: there is no attempt coming.
199
+ //
200
+ // `tierEndsAt` GOES WITH IT (tiered-reconnect P1-2). This is the load-time
201
+ // normalisation, and it is the ONLY one — the reducer's `abortMark` / `runEnd`
202
+ // paths are runtime settlement, not load. A card saved while waiting in tier 3
203
+ // would otherwise revive holding an instant that says "this tier ends at ..."
204
+ // for a ladder that no longer exists, which is exactly the stale fact the
205
+ // phase change was meant to remove.
199
206
  if (entry.kind === 'retry' && (entry.phase === 'waiting' || entry.phase === 'retrying')) {
200
- return { ...entry, phase: 'interrupted', resumeAt: undefined };
207
+ return { ...entry, phase: 'interrupted', resumeAt: undefined, tierEndsAt: undefined };
201
208
  }
202
209
  // THE FOURTH CLAUSE (fast-model-tier §5.4 / C-5 / AC-28). A review card
203
210
  // saved while its call was open resumes claiming to be running while nothing