@aragon-agent/cli 0.6.64 → 0.6.68

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 (63) hide show
  1. package/CHANGELOG.md +79 -0
  2. package/README.md +79 -4
  3. package/dist/agent/controller.d.ts +75 -0
  4. package/dist/agent/controller.js +128 -1
  5. package/dist/agent/governance-wiring.js +2 -0
  6. package/dist/agent/headless.js +24 -3
  7. package/dist/agent/reconnect-memory.d.ts +68 -0
  8. package/dist/agent/reconnect-memory.js +82 -0
  9. package/dist/app/App.js +116 -3
  10. package/dist/app/use-governance-rounds.d.ts +44 -0
  11. package/dist/app/use-governance-rounds.js +71 -0
  12. package/dist/commands/builtins.js +8 -72
  13. package/dist/commands/catalog.js +1 -1
  14. package/dist/commands/governance-command.js +45 -3
  15. package/dist/commands/retry-command.d.ts +52 -0
  16. package/dist/commands/retry-command.js +225 -0
  17. package/dist/config/cli-commands.d.ts +2 -2
  18. package/dist/config/cli-commands.js +54 -0
  19. package/dist/exec/events.d.ts +12 -0
  20. package/dist/exec/runner.js +6 -0
  21. package/dist/gene/cli-commands.js +30 -1
  22. package/dist/gene/command-report.js +5 -1
  23. package/dist/gene/curator/budget.d.ts +24 -1
  24. package/dist/gene/curator/budget.js +67 -14
  25. package/dist/gene/curator/curator.d.ts +10 -0
  26. package/dist/gene/curator/curator.js +35 -5
  27. package/dist/gene/curator/task-context.d.ts +8 -0
  28. package/dist/gene/curator/task-context.js +10 -0
  29. package/dist/gene/curator/task-runner.js +16 -5
  30. package/dist/gene/hub.d.ts +10 -1
  31. package/dist/gene/hub.js +30 -7
  32. package/dist/gene/import-plan.js +8 -5
  33. package/dist/gene/learn/learner.js +7 -3
  34. package/dist/gene/queue.d.ts +8 -0
  35. package/dist/gene/queue.js +38 -2
  36. package/dist/governance/copy.d.ts +8 -0
  37. package/dist/governance/copy.js +16 -1
  38. package/dist/governance/engine/cards.js +9 -1
  39. package/dist/governance/engine/digest.js +6 -2
  40. package/dist/governance/engine/engine-core.d.ts +12 -0
  41. package/dist/governance/engine/engine-core.js +29 -0
  42. package/dist/governance/engine/engine.d.ts +1 -0
  43. package/dist/governance/engine/engine.js +4 -1
  44. package/dist/governance/engine/lifecycle.d.ts +36 -1
  45. package/dist/governance/engine/lifecycle.js +185 -2
  46. package/dist/governance/engine/report.d.ts +8 -0
  47. package/dist/governance/engine/report.js +17 -0
  48. package/dist/governance/engine/stage-runner.js +48 -3
  49. package/dist/governance/engine/state-machine.d.ts +27 -2
  50. package/dist/governance/engine/state-machine.js +146 -20
  51. package/dist/governance/prompts/orchestrator-block.d.ts +2 -0
  52. package/dist/governance/prompts/orchestrator-block.js +25 -0
  53. package/dist/governance/store/events-log.d.ts +4 -2
  54. package/dist/governance/store/events-log.js +4 -2
  55. package/dist/governance/tools/inspector-tools.js +4 -0
  56. package/dist/governance/tools/lead-tools.d.ts +1 -1
  57. package/dist/governance/tools/lead-tools.js +14 -2
  58. package/dist/host/controller-factory.js +6 -0
  59. package/dist/logging/install.d.ts +3 -0
  60. package/dist/logging/install.js +8 -0
  61. package/dist/session/persist.js +8 -1
  62. package/dist/session/validate-session.js +15 -5
  63. package/package.json +3 -3
@@ -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 });
@@ -124,8 +124,17 @@ export declare class GeneActivityHub {
124
124
  isPolling(): boolean;
125
125
  /** A local synchronous event happened (search started, learner state changed). */
126
126
  notify(): void;
127
- /** Re-read the file facts now and emit if anything changed. Never rejects. */
127
+ /**
128
+ * Re-read the file facts now and emit if anything changed. Never rejects.
129
+ *
130
+ * A caller that arrives while a read is already running does not settle for that read: it asks
131
+ * for one more pass and shares the promise of the WHOLE chain, so `await refresh()` always means
132
+ * "a read that started after my call has finished". Resolving with the earlier read instead would
133
+ * hand back facts read before the caller's own append landed, and the caller cannot tell.
134
+ */
128
135
  refresh(): Promise<void>;
136
+ /** Read until no caller asked for one more pass while a pass was running. */
137
+ private refreshUntilQuiet;
129
138
  dispose(): void;
130
139
  private startPolling;
131
140
  private stopAll;
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;
@@ -206,7 +211,14 @@ export class GeneActivityHub {
206
211
  notify() {
207
212
  this.requestEmit();
208
213
  }
209
- /** Re-read the file facts now and emit if anything changed. Never rejects. */
214
+ /**
215
+ * Re-read the file facts now and emit if anything changed. Never rejects.
216
+ *
217
+ * A caller that arrives while a read is already running does not settle for that read: it asks
218
+ * for one more pass and shares the promise of the WHOLE chain, so `await refresh()` always means
219
+ * "a read that started after my call has finished". Resolving with the earlier read instead would
220
+ * hand back facts read before the caller's own append landed, and the caller cannot tell.
221
+ */
210
222
  refresh() {
211
223
  if (this.disposed)
212
224
  return Promise.resolve();
@@ -214,14 +226,25 @@ export class GeneActivityHub {
214
226
  this.refreshAgain = true;
215
227
  return this.refreshing;
216
228
  }
217
- this.refreshing = this.refreshOnce().finally(() => {
218
- this.refreshing = null;
219
- if (this.refreshAgain && !this.disposed) {
229
+ const run = this.refreshUntilQuiet();
230
+ this.refreshing = run;
231
+ return run;
232
+ }
233
+ /** Read until no caller asked for one more pass while a pass was running. */
234
+ async refreshUntilQuiet() {
235
+ try {
236
+ for (;;) {
220
237
  this.refreshAgain = false;
221
- void this.refresh();
238
+ await this.refreshOnce();
239
+ // The flag is read and the state cleared with no await in between (the finally
240
+ // runs synchronously with this return), so a later caller starts a pass of its own.
241
+ if (!this.refreshAgain || this.disposed)
242
+ return;
222
243
  }
223
- });
224
- return this.refreshing;
244
+ }
245
+ finally {
246
+ this.refreshing = null;
247
+ }
225
248
  }
226
249
  dispose() {
227
250
  this.disposed = true;
@@ -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);
@@ -75,6 +75,14 @@ export declare function govUnavailableNotice(reason: GovernanceUnavailableReason
75
75
  export declare function govBudgetSetNotice(tokens: number): string;
76
76
  export declare const GOV_BUDGET_OFF_NOTICE = "Team token budget removed (unlimited).";
77
77
  export declare const GOV_BUDGET_USAGE = "Usage: /gov budget <tokens>|off";
78
+ /**
79
+ * The upper bound is INTERPOLATED from `GOV_LIMITS.hardMaxRounds`, never written as a literal:
80
+ * the config layer keeps that discipline (it never repeats a `hardMax*`), and a sentence has
81
+ * no reason to be the one place that goes stale when the constant moves.
82
+ */
83
+ export declare const GOV_ROUNDS_USAGE: string;
84
+ /** `/gov rounds <n>`: what was WRITTEN (the clamp runs before this sentence is built). */
85
+ export declare function govRoundsSetNotice(rounds: number | null): string;
78
86
  export interface GovStatusRun {
79
87
  runId: string;
80
88
  /** 1-based. */
@@ -122,6 +122,21 @@ export function govBudgetSetNotice(tokens) {
122
122
  }
123
123
  export const GOV_BUDGET_OFF_NOTICE = 'Team token budget removed (unlimited).';
124
124
  export const GOV_BUDGET_USAGE = 'Usage: /gov budget <tokens>|off';
125
+ // --- round budget (governance-round-budget 4.6 / 6.2) ------------------------------------
126
+ /**
127
+ * The upper bound is INTERPOLATED from `GOV_LIMITS.hardMaxRounds`, never written as a literal:
128
+ * the config layer keeps that discipline (it never repeats a `hardMax*`), and a sentence has
129
+ * no reason to be the one place that goes stale when the constant moves.
130
+ */
131
+ export const GOV_ROUNDS_USAGE = `Usage: /gov rounds <n|auto> (0-${GOV_LIMITS.hardMaxRounds}, auto = the engine decides)`;
132
+ /** `/gov rounds <n>`: what was WRITTEN (the clamp runs before this sentence is built). */
133
+ export function govRoundsSetNotice(rounds) {
134
+ if (rounds === null)
135
+ return 'Round budget set to auto: the engine decides per plan.';
136
+ if (rounds === 0)
137
+ return 'Round budget set to 0: the first rejection comes straight to you.';
138
+ return `Round budget set to ${rounds} round${rounds === 1 ? '' : 's'} per run.`;
139
+ }
125
140
  /** The `/gov` and `/gov status` notice. */
126
141
  export function formatGovStatus(input) {
127
142
  const lines = [`Posture: ${POSTURE_LABEL[input.posture]}`];
@@ -184,7 +199,7 @@ export function buildGovHelpText(minAskRounds = 2) {
184
199
  '',
185
200
  'Commands',
186
201
  ' /gov status | on | plan | off | board | runs | resume [id] | abort | budget <n|off> | help',
187
- ' /gov pause [cancel] | report [id]',
202
+ ' /gov rounds <n|auto> | pause [cancel] | report [id]',
188
203
  '',
189
204
  'Team fan-out versus governance',
190
205
  ' /team and the task tool fan out independent subtasks in parallel and the lead',
@@ -7,6 +7,7 @@
7
7
  * per-stage chatter belongs to the panel, not the transcript.
8
8
  */
9
9
  import { formatDispatchEstimate } from '../copy.js';
10
+ import { ensureRunRounds } from '@aragon-agent/tui/model/governance/rounds';
10
11
  import { formatCost } from './budget.js';
11
12
  import { estimateForRun } from './estimate.js';
12
13
  import { teamHealthStatus } from '../rules/elimination.js';
@@ -73,7 +74,8 @@ export function charterCard(core) {
73
74
  if (run.contracts.length > 0) {
74
75
  notes.push(`contracts: ${run.contracts.map((c) => c.name).join(', ')}`);
75
76
  }
76
- notes.push(`limits: rework ${run.limits.maxRework}, fix cycles ${run.limits.maxFixCycles}` +
77
+ notes.push(`limits: rework ${run.limits.maxRework}, fix cycles ${run.limits.maxFixCycles}, ` +
78
+ `rounds used ${ensureRunRounds(run).used}/${core.roundsLimit()}` +
77
79
  (run.limits.budgetTokens > 0 ? `, budget ${run.limits.budgetTokens} tokens` : ''));
78
80
  const plan = formatDispatchEstimate(estimateForRun(run, core.deps.getTeamCeiling()));
79
81
  if (plan !== '')
@@ -146,6 +148,12 @@ function options(escalation) {
146
148
  return 'ruling needed: retry, accept as is, or drop the work package';
147
149
  case 'integration_exhausted':
148
150
  return 'ruling needed: retry once more or accept the failing integration';
151
+ // Exhaustive switch WITHOUT a default: the compiler is the sentinel that catches a new
152
+ // `Escalation['kind']` everywhere a card is described (governance-round-budget RV-P1-3).
153
+ case 'rounds_exhausted':
154
+ return escalation.wpId
155
+ ? 'ruling needed: grant one more round, accept as is, or drop the work package'
156
+ : 'ruling needed: grant one more round or accept the failing integration';
149
157
  case 'dispute':
150
158
  return 'ruling needed: the user decides';
151
159
  }
@@ -9,6 +9,7 @@
9
9
  * one place that guarantees the prefix, the byte budget and the footer wording.
10
10
  */
11
11
  import { GOV_LIMITS } from '@aragon-agent/tui/model/governance/limits';
12
+ import { ensureRunRounds, roundsStatusLine } from '@aragon-agent/tui/model/governance/rounds';
12
13
  import { nextActions } from './state-machine.js';
13
14
  import { budgetLine, budgetNotice } from './budget.js';
14
15
  import { buildDigest, renderStandings } from './report.js';
@@ -18,9 +19,12 @@ export function footerLines(core) {
18
19
  if (run === null)
19
20
  return [];
20
21
  const budget = core.config().budgetTokens;
22
+ const rounds = ensureRunRounds(run);
23
+ const mode = core.config().rounds;
21
24
  const lines = [
22
25
  `Limits: rework <= ${run.limits.maxRework} per WP, fix cycles <= ${run.limits.maxFixCycles} ` +
23
- `per phase, stage width <= ${core.deps.getTeamCeiling()}, ` +
26
+ `per phase, ${roundsStatusLine(rounds, mode)}, ` +
27
+ `stage width <= ${core.deps.getTeamCeiling()}, ` +
24
28
  `dispatch ${run.dispatches}/${GOV_LIMITS.hardMaxDispatches}.`,
25
29
  budgetLine(run.usage, budget),
26
30
  ];
@@ -44,7 +48,7 @@ export function composeDigest(core, parts) {
44
48
  ? []
45
49
  : waitingOnUser
46
50
  ? [USER_PAUSED_NEXT]
47
- : nextActions(run, { teamCeiling: core.deps.getTeamCeiling() });
51
+ : nextActions(run, core.stageOptions());
48
52
  return buildDigest({
49
53
  headline: parts.headline,
50
54
  results: parts.results ?? [],