@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
@@ -24,12 +24,13 @@
24
24
  * posture change produces no `AgentEvent`, so without one the badge would wait for an
25
25
  * unrelated state change to repaint (the lesson of team-command-forced-dispatch P1-6).
26
26
  */
27
- import { GOV_ABORTED_NOTICE, GOV_BUDGET_OFF_NOTICE, GOV_BUDGET_USAGE, GOV_COMMAND_SUMMARY, GOV_NO_RUN_NOTICE, GOV_NO_RUNS_NOTICE, GOV_NO_STAGE_NOTICE, GOV_OFF_NOTICE, GOV_OFF_WITH_RUN_NOTICE, GOV_PAUSE_ALREADY_NOTICE, GOV_PAUSE_CANCELLED_TOAST, GOV_PAUSE_ESCALATED_NOTICE, GOV_PAUSE_NONE_PENDING_NOTICE, GOV_PAUSE_NO_RUN_NOTICE, GOV_REPORT_NO_RUN_NOTICE, GOV_STAGE_BUSY_NOTICE, buildGovHelpText, formatGovStatus, govBudgetSetNotice, govPausePendingToast, govPausedNowToast, govReportBadIdNotice, govReportMissingNotice, govUnavailableNotice, posturePendingToast, postureAppliedToast, stageRunningToast, RESTART_REQUIRED_TEXT, } from '../governance/copy.js';
28
- import { RUN_ID_PATTERN } from '@aragon-agent/tui/model/governance/limits';
27
+ import { GOV_ABORTED_NOTICE, GOV_BUDGET_OFF_NOTICE, GOV_BUDGET_USAGE, GOV_COMMAND_SUMMARY, GOV_NO_RUN_NOTICE, GOV_NO_RUNS_NOTICE, GOV_NO_STAGE_NOTICE, GOV_OFF_NOTICE, GOV_OFF_WITH_RUN_NOTICE, GOV_PAUSE_ALREADY_NOTICE, GOV_PAUSE_CANCELLED_TOAST, GOV_PAUSE_ESCALATED_NOTICE, GOV_PAUSE_NONE_PENDING_NOTICE, GOV_PAUSE_NO_RUN_NOTICE, GOV_REPORT_NO_RUN_NOTICE, GOV_ROUNDS_USAGE, GOV_STAGE_BUSY_NOTICE, buildGovHelpText, formatGovStatus, govBudgetSetNotice, govRoundsSetNotice, govPausePendingToast, govPausedNowToast, govReportBadIdNotice, govReportMissingNotice, govUnavailableNotice, posturePendingToast, postureAppliedToast, stageRunningToast, RESTART_REQUIRED_TEXT, } from '../governance/copy.js';
28
+ import { GOV_LIMITS, RUN_ID_PATTERN } from '@aragon-agent/tui/model/governance/limits';
29
+ import { formatRoundBudget, parseRoundBudget } from '@aragon-agent/tui/model/governance/rounds';
29
30
  import { isGovernancePosture } from '@aragon-agent/tui/model/governance/posture';
30
31
  import { formatReportNotice, formatRunsTable } from './governance-runs-table.js';
31
32
  const USAGE = 'Usage: /gov [status|on|plan|off|board|runs|report [runId]|resume [runId]|pause [cancel]' +
32
- '|abort|budget <n|off>|help]';
33
+ '|abort|budget <n|off>|rounds <n|auto>|help]';
33
34
  /** The fixed English turn that makes the orchestrator call `gov_run resume` (11.3). */
34
35
  export function resumeTurnText(runId) {
35
36
  return `Resume governance run ${runId}.`;
@@ -251,6 +252,44 @@ function setBudget(ctx) {
251
252
  ctx.persistConfig({ governance: adopted });
252
253
  ctx.notify('info', adopted.budgetTokens === 0 ? GOV_BUDGET_OFF_NOTICE : govBudgetSetNotice(adopted.budgetTokens));
253
254
  }
255
+ /**
256
+ * `/gov rounds` - read without an argument, write with one.
257
+ *
258
+ * The read branch is answerable in ANY session (it is a question, like `status`), and it
259
+ * names what a LIVE run can still do: the user's own `retry` ruling can grant a round even
260
+ * on a fixed budget, which is the fact a user is most likely to be missing (R-11).
261
+ */
262
+ function roundsCommand(ctx) {
263
+ const raw = ctx.args.trim().split(/\s+/)[1];
264
+ if (raw === undefined) {
265
+ ctx.notify('info', describeRounds(ctx));
266
+ return;
267
+ }
268
+ const parsed = parseRoundBudget(raw);
269
+ if (!parsed.ok && parsed.reason !== 'out_of_range') {
270
+ ctx.notify('warn', GOV_ROUNDS_USAGE);
271
+ return;
272
+ }
273
+ // An out-of-range NUMBER is clamped by `clampGovernanceConfig` rather than rejected, which
274
+ // is the same rule every other numeric setting follows; a word that is not a number is not
275
+ // an answer at all. The notice echoes what was WRITTEN.
276
+ const requested = parsed.ok ? parsed.value : Number(raw);
277
+ const adopted = ctx.controller.setGovernanceConfig({ rounds: requested });
278
+ ctx.persistConfig({ governance: adopted });
279
+ ctx.notify('info', govRoundsSetNotice(adopted.rounds));
280
+ }
281
+ /** The read-only answer: the setting in force plus this run's used/limit when there is one. */
282
+ function describeRounds(ctx) {
283
+ const budget = ctx.controller.getGovernanceConfig().rounds;
284
+ const snapshot = ctx.controller.getGovernanceSnapshot();
285
+ const head = `Round budget: ${formatRoundBudget(budget)}`;
286
+ if (snapshot === null)
287
+ return head;
288
+ const { used, limit, grants, rework, fix } = snapshot.rounds;
289
+ const left = Math.max(0, GOV_LIMITS.maxRoundGrantsPerRun - grants);
290
+ return (`${head}; this run has used ${used}/${limit} (${rework} rework, ${fix} fix). ` +
291
+ `${left} grant(s) left - a "retry" ruling on an escalation card spends one.`);
292
+ }
254
293
  /** The command body; `registerGovernanceCommand` is the only registration site. */
255
294
  export async function runGovernanceCommand(ctx) {
256
295
  const verb = (ctx.args.trim().split(/\s+/)[0] ?? '').toLowerCase();
@@ -292,6 +331,9 @@ export async function runGovernanceCommand(ctx) {
292
331
  case 'budget':
293
332
  setBudget(ctx);
294
333
  return;
334
+ case 'rounds':
335
+ roundsCommand(ctx);
336
+ return;
295
337
  default:
296
338
  ctx.notify('warn', `Unknown argument "${verb}". ${USAGE}`);
297
339
  }
@@ -0,0 +1,52 @@
1
+ /**
2
+ * `/retry` — the command BODY (tiered-reconnect §5.3 / P1-5).
3
+ *
4
+ * WHY THIS IS NOT IN `builtins.ts`: that file is ~1 600 lines, well past
5
+ * `CLAUDE.md`'s 1 000-line ceiling and already recorded as an exception, while its
6
+ * own `/compact` registration carries the sentence "the body lives in
7
+ * `compaction/command.ts` because this file is already past the 1000-line
8
+ * guideline". The six tier keys would have added ~90 lines there; they add none.
9
+ *
10
+ * TWO CALLS FOR EVERY MUTATION, IN THIS ORDER, and neither is optional:
11
+ *
12
+ * `setRetryConfig` replaces the policy on the live `ProviderRegistry`, so the
13
+ * change takes effect in THIS session — and, because
14
+ * `TeamRuntime` holds the same registry instance, for every
15
+ * child too. Without it `/retry off` reports success and
16
+ * changes nothing until the next launch.
17
+ * `persistConfig` is what survives the session.
18
+ *
19
+ * THE TIER KEYS DO NOT NEED THE FIRST CALL, and that asymmetry is worth knowing:
20
+ * the escalation policy is delivered by a CLOSURE the engine calls once per run
21
+ * (`AgentConfig.resolveEscalation`), so it is already live. `setRetryConfig` is
22
+ * still called for uniformity where the key overlaps with the fast policy, and the
23
+ * user-visible effect is the same either way: the next request uses the new shape.
24
+ */
25
+ import { type RetryConfig } from '@aragon-agent/tui/model/config/schema';
26
+ import type { CommandRegistry, CommandContext } from './registry.js';
27
+ /**
28
+ * The ladder summary line for `/retry show`.
29
+ *
30
+ * EVERY NUMBER IS READ FROM `cfg` (P2-6). A hardcoded `budget 240s` would become a
31
+ * lie the moment someone ran `/retry max 3`, and this line exists precisely to tell
32
+ * a user what their CURRENT configuration will do.
33
+ */
34
+ export declare function reconnectSummary(cfg: RetryConfig, opts: {
35
+ headless: boolean;
36
+ }): string;
37
+ /**
38
+ * The one-line ladder shape for a READ-ONLY surface (`10 + 10x1m + every 5m`).
39
+ *
40
+ * `reconnectSummary` is a sentence for `/retry show`, where a user asked how the
41
+ * ladder works and has room to read it. The settings screen prints this next to
42
+ * `API retries:` on a single truncated row, so it has to be a FORM, not prose - and
43
+ * it still reads every number from `cfg`, for the reason `reconnectSummary` does
44
+ * (P2-6, and AC-17's own wording).
45
+ */
46
+ export declare function retryLadderShape(cfg: RetryConfig, opts: {
47
+ headless: boolean;
48
+ }): string;
49
+ /** The `/retry` command body. Registered by `builtins.ts` with one line. */
50
+ export declare function runRetryCommand(ctx: CommandContext): void;
51
+ /** One-line registration, the `/compact` shape. */
52
+ export declare function registerRetryCommand(registry: CommandRegistry): void;
@@ -0,0 +1,225 @@
1
+ /**
2
+ * `/retry` — the command BODY (tiered-reconnect §5.3 / P1-5).
3
+ *
4
+ * WHY THIS IS NOT IN `builtins.ts`: that file is ~1 600 lines, well past
5
+ * `CLAUDE.md`'s 1 000-line ceiling and already recorded as an exception, while its
6
+ * own `/compact` registration carries the sentence "the body lives in
7
+ * `compaction/command.ts` because this file is already past the 1000-line
8
+ * guideline". The six tier keys would have added ~90 lines there; they add none.
9
+ *
10
+ * TWO CALLS FOR EVERY MUTATION, IN THIS ORDER, and neither is optional:
11
+ *
12
+ * `setRetryConfig` replaces the policy on the live `ProviderRegistry`, so the
13
+ * change takes effect in THIS session — and, because
14
+ * `TeamRuntime` holds the same registry instance, for every
15
+ * child too. Without it `/retry off` reports success and
16
+ * changes nothing until the next launch.
17
+ * `persistConfig` is what survives the session.
18
+ *
19
+ * THE TIER KEYS DO NOT NEED THE FIRST CALL, and that asymmetry is worth knowing:
20
+ * the escalation policy is delivered by a CLOSURE the engine calls once per run
21
+ * (`AgentConfig.resolveEscalation`), so it is already live. `setRetryConfig` is
22
+ * still called for uniformity where the key overlaps with the fast policy, and the
23
+ * user-visible effect is the same either way: the next request uses the new shape.
24
+ */
25
+ import { clampRetryConfig, HARD_MAX_RETRIES, } from '@aragon-agent/tui/model/config/schema';
26
+ import { RECONNECT_MODES, isReconnectMode, resolveEscalationPolicy, } from '@aragon-agent/tui/model/config/reconnect';
27
+ /** `1s` / `30s` / `5m`: short, ASCII, and honest about the unit it dropped. */
28
+ function shortWait(ms) {
29
+ const seconds = Math.round(ms / 1000);
30
+ if (seconds < 60)
31
+ return `${seconds}s`;
32
+ const minutes = Math.floor(seconds / 60);
33
+ const rest = seconds % 60;
34
+ return rest === 0 ? `${minutes}m` : `${minutes}m${String(rest).padStart(2, '0')}s`;
35
+ }
36
+ /**
37
+ * The ladder summary line for `/retry show`.
38
+ *
39
+ * EVERY NUMBER IS READ FROM `cfg` (P2-6). A hardcoded `budget 240s` would become a
40
+ * lie the moment someone ran `/retry max 3`, and this line exists precisely to tell
41
+ * a user what their CURRENT configuration will do.
42
+ */
43
+ export function reconnectSummary(cfg, opts) {
44
+ const safe = clampRetryConfig(cfg);
45
+ if (!safe.enabled || safe.maxRetries <= 0)
46
+ return 'Reconnect: off (no fast retries configured).';
47
+ if (safe.reconnect === 'off') {
48
+ return `Reconnect: off (fast tier only).`;
49
+ }
50
+ const policy = resolveEscalationPolicy(safe, { headless: opts.headless });
51
+ if (!policy) {
52
+ return safe.slowAttempts === 0
53
+ ? 'Reconnect: off (slowAttempts 0).'
54
+ : 'Reconnect: off (no fast retries configured).';
55
+ }
56
+ const fast = `fast ${safe.maxRetries} (${shortWait(safe.initialDelayMs)}->${shortWait(safe.maxDelayMs)}, ` +
57
+ `budget ${shortWait(safe.maxElapsedMs)})`;
58
+ const slow = `then every ${shortWait(policy.slow.initialDelayMs)} x ${policy.slow.attempts}`;
59
+ // `bounded` has no hold tier, and saying "then every 5 minutes" there would be the
60
+ // same class of lie the notice avoids (P1-4).
61
+ const hold = policy.hold
62
+ ? `then every ${shortWait(policy.hold.initialDelayMs)} until it works`
63
+ : 'then it gives up';
64
+ const cap = policy.totalBudgetMs === undefined
65
+ ? 'no overall cap'
66
+ : `gives up entirely after ${shortWait(policy.totalBudgetMs)}`;
67
+ return `API reconnect: ${fast}, ${slow}, ${hold} (${cap}).`;
68
+ }
69
+ /**
70
+ * The one-line ladder shape for a READ-ONLY surface (`10 + 10x1m + every 5m`).
71
+ *
72
+ * `reconnectSummary` is a sentence for `/retry show`, where a user asked how the
73
+ * ladder works and has room to read it. The settings screen prints this next to
74
+ * `API retries:` on a single truncated row, so it has to be a FORM, not prose - and
75
+ * it still reads every number from `cfg`, for the reason `reconnectSummary` does
76
+ * (P2-6, and AC-17's own wording).
77
+ */
78
+ export function retryLadderShape(cfg, opts) {
79
+ const safe = clampRetryConfig(cfg);
80
+ if (!safe.enabled || safe.maxRetries <= 0)
81
+ return 'off';
82
+ const fast = String(safe.maxRetries);
83
+ const policy = resolveEscalationPolicy(safe, { headless: opts.headless });
84
+ if (!policy)
85
+ return `${fast} (no reconnect ladder)`;
86
+ const slow = `${policy.slow.attempts}x${shortWait(policy.slow.initialDelayMs)}`;
87
+ const hold = policy.hold
88
+ ? `every ${shortWait(policy.hold.initialDelayMs)}`
89
+ : 'stop';
90
+ const cap = policy.totalBudgetMs === undefined ? '' : `, cap ${shortWait(policy.totalBudgetMs)}`;
91
+ return `${fast} + ${slow} + ${hold}${cap}`;
92
+ }
93
+ function showReconnect(ctx) {
94
+ const cfg = ctx.controller.getRetryConfig();
95
+ ctx.notify('info', reconnectSummary(cfg, { headless: false }));
96
+ // The cost of an endless ladder is the one thing a user cannot infer from the
97
+ // shape, so it is said once, here, rather than only in the README (Q-5).
98
+ const policy = resolveEscalationPolicy(cfg, { headless: false });
99
+ if (policy?.hold) {
100
+ ctx.notify('info', 'Every attempt re-sends the request and is billed again; a long outage is charged ' +
101
+ 'close to full price (do not count on prompt caching). Set /retry hold 0 to cap it.');
102
+ }
103
+ }
104
+ /** `/retry hold <minutes>`; `0` = no cap, which is the documented "keep trying". */
105
+ function setHold(ctx, raw, cfg) {
106
+ const minutes = Number.parseInt(raw ?? '', 10);
107
+ if (!Number.isFinite(minutes) || minutes < 0) {
108
+ ctx.notify('warn', 'Usage: /retry hold <0-1440> (minutes; 0 = keep trying, no cap)');
109
+ return;
110
+ }
111
+ const applied = clampRetryConfig({ ...cfg, holdMaxMinutes: minutes });
112
+ ctx.controller.setRetryConfig({ holdMaxMinutes: applied.holdMaxMinutes });
113
+ ctx.persistConfig({ retry: { holdMaxMinutes: applied.holdMaxMinutes } });
114
+ ctx.toast('success', applied.holdMaxMinutes === 0
115
+ ? 'Reconnect: no overall cap - it keeps trying every 5 minutes.'
116
+ : `Reconnect: gives up entirely after ${applied.holdMaxMinutes} minutes ` +
117
+ '(including the first two tiers).');
118
+ }
119
+ /** `/retry slow <seconds>` and `/retry every <seconds>`: tier 2's interval. */
120
+ function setSlow(ctx, raw, cfg) {
121
+ const seconds = Number.parseInt(raw ?? '', 10);
122
+ if (!Number.isFinite(seconds) || seconds <= 0) {
123
+ ctx.notify('warn', 'Usage: /retry slow <15-900> (seconds between tier-2 attempts)');
124
+ return;
125
+ }
126
+ const applied = clampRetryConfig({ ...cfg, slowIntervalMs: seconds * 1000 });
127
+ ctx.controller.setRetryConfig({ slowIntervalMs: applied.slowIntervalMs });
128
+ ctx.persistConfig({ retry: { slowIntervalMs: applied.slowIntervalMs } });
129
+ ctx.toast('success', `Reconnect: one try every ${shortWait(applied.slowIntervalMs)}.`);
130
+ }
131
+ /** `/retry reconnect <auto|full|bounded|off>`. */
132
+ function setMode(ctx, raw, cfg) {
133
+ const value = (raw ?? '').toLowerCase();
134
+ if (!isReconnectMode(value)) {
135
+ ctx.notify('warn', `Usage: /retry reconnect <${RECONNECT_MODES.join('|')}>`);
136
+ return;
137
+ }
138
+ const applied = clampRetryConfig({ ...cfg, reconnect: value });
139
+ ctx.controller.setRetryConfig({ reconnect: applied.reconnect });
140
+ ctx.persistConfig({ retry: { reconnect: applied.reconnect } });
141
+ // `auto` is worth explaining rather than echoing: it is the only value whose
142
+ // meaning depends on who is running.
143
+ ctx.toast('success', applied.reconnect === 'auto'
144
+ ? 'Reconnect: auto (full ladder here, two tiers in -p / exec).'
145
+ : applied.reconnect === 'full'
146
+ ? 'Reconnect: full - fast, then every minute, then every 5 minutes until it works.'
147
+ : applied.reconnect === 'bounded'
148
+ ? 'Reconnect: bounded - fast, then every minute, then it stops.'
149
+ : 'Reconnect: off - fast retries only.');
150
+ }
151
+ /** The `/retry` command body. Registered by `builtins.ts` with one line. */
152
+ export function runRetryCommand(ctx) {
153
+ const arg = ctx.args.trim().toLowerCase();
154
+ const [verb, value] = arg.split(/\s+/, 2);
155
+ const controller = ctx.controller;
156
+ if (!verb || verb === 'show' || verb === 'status') {
157
+ const cfg = controller.getRetryConfig();
158
+ if (!cfg.enabled || cfg.maxRetries <= 0) {
159
+ ctx.notify('info', `API retry: off (maxRetries ${cfg.maxRetries}). Use /retry on or /retry max <n>.`);
160
+ return;
161
+ }
162
+ ctx.notify('info', `API retry: on. Up to ${cfg.maxRetries} retries, ${cfg.initialDelayMs}ms doubling to ` +
163
+ `${cfg.maxDelayMs}ms${cfg.jitter ? ' with jitter' : ''}, ` +
164
+ `giving up after ${Math.round(cfg.maxElapsedMs / 1000)}s. ` +
165
+ `Retry-After ${cfg.respectRetryAfter ? 'honoured' : 'ignored'}.`);
166
+ showReconnect(ctx);
167
+ return;
168
+ }
169
+ if (verb === 'on' || verb === 'off') {
170
+ const enabled = verb === 'on';
171
+ const applied = controller.setRetryConfig({ enabled });
172
+ // A PARTIAL `retry` section, safe only because `updatePersistedConfig`
173
+ // deep-merges it — the same contract `/team on` relies on.
174
+ ctx.persistConfig({ retry: { enabled } });
175
+ if (enabled && applied.maxRetries <= 0) {
176
+ // Honest rather than cheerful: `enabled` is on but the count is the
177
+ // kill switch, so nothing will actually retry.
178
+ ctx.notify('warn', 'API retry enabled, but maxRetries is 0 - use /retry max <n>.');
179
+ return;
180
+ }
181
+ ctx.toast('success', `API retry ${enabled ? 'on' : 'off'}.`);
182
+ return;
183
+ }
184
+ if (verb === 'max') {
185
+ // `Number.isFinite` and `>= 0`, NOT `> 0`: `0` is this key's documented floor
186
+ // and its kill switch, and rejecting it here would make `/retry max 0` the one
187
+ // documented control that does not work (R-16).
188
+ const n = Number.parseInt(value ?? '', 10);
189
+ if (!Number.isFinite(n) || n < 0) {
190
+ ctx.notify('warn', `Usage: /retry max <0-${HARD_MAX_RETRIES}> (0 turns retry off)`);
191
+ return;
192
+ }
193
+ const applied = controller.setRetryConfig({ maxRetries: n });
194
+ ctx.persistConfig({
195
+ retry: { maxRetries: applied.maxRetries },
196
+ });
197
+ ctx.toast('success', applied.maxRetries === 0
198
+ ? 'API retry off (maxRetries 0).'
199
+ : `API retry: up to ${applied.maxRetries} retries.`);
200
+ return;
201
+ }
202
+ const cfg = controller.getRetryConfig();
203
+ if (verb === 'reconnect') {
204
+ setMode(ctx, value, cfg);
205
+ return;
206
+ }
207
+ if (verb === 'slow' || verb === 'every') {
208
+ setSlow(ctx, value, cfg);
209
+ return;
210
+ }
211
+ if (verb === 'hold') {
212
+ setHold(ctx, value, cfg);
213
+ return;
214
+ }
215
+ ctx.notify('warn', `Unknown argument "${verb}" - use /retry [show|on|off|max <n>|` +
216
+ 'reconnect <auto|full|bounded|off>|slow <secs>|hold <minutes>].');
217
+ }
218
+ /** One-line registration, the `/compact` shape. */
219
+ export function registerRetryCommand(registry) {
220
+ registry.register({
221
+ name: 'retry',
222
+ description: 'API retry: show | on | off | max <n> | reconnect <mode> | slow <secs> | hold <minutes>',
223
+ run: (ctx) => runRetryCommand(ctx),
224
+ });
225
+ }
@@ -55,7 +55,7 @@ export declare const TASK_SUMMARY_CONFIG_SET_KEYS: readonly ["taskSummary.enable
55
55
  * switch falls through every case, writes nothing, and still prints
56
56
  * `Set retry.maxRetries = 0`.
57
57
  */
58
- export declare const RETRY_CONFIG_SET_KEYS: readonly ["retry.enabled", "retry.maxRetries", "retry.initialDelayMs", "retry.maxDelayMs", "retry.multiplier", "retry.jitter", "retry.respectRetryAfter", "retry.maxElapsedMs", "retry.onPartialStream", "retry.resumeRun", "retry.maxRunResumes", "retry.maxRunResumesPerPrompt"];
58
+ export declare const RETRY_CONFIG_SET_KEYS: readonly ["retry.enabled", "retry.maxRetries", "retry.initialDelayMs", "retry.maxDelayMs", "retry.multiplier", "retry.jitter", "retry.respectRetryAfter", "retry.maxElapsedMs", "retry.onPartialStream", "retry.resumeRun", "retry.maxRunResumes", "retry.maxRunResumesPerPrompt", "retry.reconnect", "retry.slowIntervalMs", "retry.slowAttempts", "retry.holdIntervalMs", "retry.holdMaxMinutes", "retry.stickyRung"];
59
59
  /**
60
60
  * Config keys under `fast.` that `aragon config set` accepts (fast-model-tier
61
61
  * §4.2).
@@ -100,7 +100,7 @@ export declare const COMPACTION_CONFIG_SET_KEYS: readonly ["compaction.enabled",
100
100
  * Config keys under `governance.` that `aragon config set` accepts (governance-mode 11.1).
101
101
  * Every key is writable and ONE level deep, so `runConfigGet`'s single-dot split resolves it.
102
102
  */
103
- export declare const GOVERNANCE_CONFIG_SET_KEYS: readonly ["governance.enabled", "governance.shiftTab", "governance.panel", "governance.profile", "governance.maxWorkPackages", "governance.maxPhases", "governance.maxRework", "governance.maxFixCycles", "governance.minAskRounds", "governance.budgetTokens", "governance.confirmCharter"];
103
+ export declare const GOVERNANCE_CONFIG_SET_KEYS: readonly ["governance.enabled", "governance.shiftTab", "governance.panel", "governance.profile", "governance.maxWorkPackages", "governance.maxPhases", "governance.maxRework", "governance.maxFixCycles", "governance.minAskRounds", "governance.budgetTokens", "governance.confirmCharter", "governance.rounds", "governance.arrowRounds"];
104
104
  /**
105
105
  * Config keys under `memory.` that `aragon config set` accepts (agent-memory spec 5.6).
106
106
  * Every key is writable and ONE level deep, so `runConfigGet`'s single-dot split resolves it.
@@ -16,6 +16,7 @@ import { loadPersistedConfig, updatePersistedConfig } from './store.js';
16
16
  import { normalizeModelProfiles, validateModelProfiles } from '@aragon-agent/tui/model/config/model-profiles';
17
17
  import { clampFastConfig, clampRetryConfig, clampCompactionConfig, clampTeamConfig, parseThresholdInput, clampUpdateConfig, coercePositiveInt, maskSecret, DEFAULT_FAST_CONFIG, DEFAULT_RETRY_CONFIG, DEFAULT_TEAM_CONFIG, DEFAULT_COMPACTION_CONFIG, DEFAULT_UPDATE_CONFIG, DEFAULT_JOBS_CONFIG, clampJobsConfig, clampGovernanceConfig, clampMemoryConfig, clampGeneConfig, DEFAULT_GOVERNANCE_CONFIG, DEFAULT_MEMORY_CONFIG, DEFAULT_GENE_CONFIG, } from '@aragon-agent/tui/model/config/schema';
18
18
  import { clampLogLevel } from '@aragon-agent/tui/model/logging/levels';
19
+ import { parseRoundBudget } from '@aragon-agent/tui/model/governance/rounds';
19
20
  /** Config keys under `log.` that `aragon config set` accepts. */
20
21
  export const LOG_CONFIG_SET_KEYS = [
21
22
  'log.level',
@@ -104,6 +105,16 @@ export const RETRY_CONFIG_SET_KEYS = [
104
105
  'retry.resumeRun',
105
106
  'retry.maxRunResumes',
106
107
  'retry.maxRunResumesPerPrompt',
108
+ // TIERED RECONNECT (tiered-reconnect §5.2). Six keys, and §8.5's rule applies to
109
+ // all six: `retry-config.test.ts` asserts that EVERY key listed here can actually
110
+ // be patched into something non-empty, so declaring one without a `case` below is
111
+ // a red test rather than a key that silently writes nothing.
112
+ 'retry.reconnect',
113
+ 'retry.slowIntervalMs',
114
+ 'retry.slowAttempts',
115
+ 'retry.holdIntervalMs',
116
+ 'retry.holdMaxMinutes',
117
+ 'retry.stickyRung',
107
118
  ];
108
119
  /**
109
120
  * Config keys under `fast.` that `aragon config set` accepts (fast-model-tier
@@ -194,6 +205,8 @@ export const GOVERNANCE_CONFIG_SET_KEYS = [
194
205
  'governance.minAskRounds',
195
206
  'governance.budgetTokens',
196
207
  'governance.confirmCharter',
208
+ 'governance.rounds',
209
+ 'governance.arrowRounds',
197
210
  ];
198
211
  /**
199
212
  * Config keys under `memory.` that `aragon config set` accepts (agent-memory spec 5.6).
@@ -409,7 +422,25 @@ export function applyGeneConfigSet(key, value) {
409
422
  });
410
423
  return { gene: { [field]: clamped[field] } };
411
424
  }
425
+ /**
426
+ * `rounds` is the one TRI-STATE key in this section, so the default's runtime type (`object`
427
+ * for `null`) cannot decide how to parse it: a typed `auto` would become the string
428
+ * `"auto"`, which `clampGovernanceConfig` repairs to `null` only by luck, and `banana`
429
+ * would look like a deliberate value. `parseRoundBudget` says what happened instead.
430
+ */
431
+ function parseRoundArgument(value) {
432
+ const parsed = parseRoundBudget(value);
433
+ if (parsed.ok)
434
+ return parsed.value;
435
+ // `99` is a NUMBER, just too large: the clamp caps it at `hardMaxRounds`, exactly like
436
+ // `maxRework 99` becomes 5. Only text that is not a number at all becomes NaN, which the
437
+ // clamp repairs to AUTO - the "typo changes nothing" rule every other key here follows.
438
+ const text = value.trim();
439
+ return /^\d+$/.test(text) ? Number(text) : Number.NaN;
440
+ }
412
441
  function parseGovernanceArgument(field, value) {
442
+ if (field === 'rounds')
443
+ return parseRoundArgument(value);
413
444
  const kind = typeof DEFAULT_GOVERNANCE_CONFIG[field];
414
445
  const trimmed = value.trim();
415
446
  if (kind === 'boolean')
@@ -520,6 +551,24 @@ export function applyRetryConfigSet(key, value) {
520
551
  return patch(clampOne('maxRunResumes'));
521
552
  case 'retry.maxRunResumesPerPrompt':
522
553
  return patch(clampOne('maxRunResumesPerPrompt'));
554
+ // ---- tiered reconnect (§5.2) -----------------------------------------
555
+ // Every one of the six goes through `clampRetryConfig` for the reason this
556
+ // function's header records, and the two keys whose floor is 0 (`slowAttempts`,
557
+ // `holdMaxMinutes`) are exactly why `clampIntAllowingZero` exists: a plain
558
+ // `coercePositiveInt` would store "ten tries" for `slowAttempts 0` and "no cap"
559
+ // would become a cap.
560
+ case 'retry.reconnect':
561
+ return patch(clampOne('reconnect'));
562
+ case 'retry.slowIntervalMs':
563
+ return patch(clampOne('slowIntervalMs'));
564
+ case 'retry.slowAttempts':
565
+ return patch(clampOne('slowAttempts'));
566
+ case 'retry.holdIntervalMs':
567
+ return patch(clampOne('holdIntervalMs'));
568
+ case 'retry.holdMaxMinutes':
569
+ return patch(clampOne('holdMaxMinutes'));
570
+ case 'retry.stickyRung':
571
+ return patch({ stickyRung: isTrue(value) });
523
572
  default:
524
573
  return null;
525
574
  }
@@ -709,6 +758,11 @@ function displayOverride(key, value) {
709
758
  // bare `null` sends the user looking for a bug that is not there.
710
759
  if (key === 'contextWindow' && value === null)
711
760
  return 'auto';
761
+ // `governance.rounds: null` is AUTO too. `config view` keeps printing the raw `null` (it
762
+ // mirrors the file); `get` and `list` are the human forms, and two presentations of one
763
+ // value are still one value (governance-round-budget 6.1).
764
+ if (key === 'governance.rounds' && value === null)
765
+ return 'auto';
712
766
  return undefined;
713
767
  }
714
768
  /** Resolve a flat or one-level-dotted key against the persisted config. */
@@ -450,6 +450,18 @@ export interface ExecRetryEvent {
450
450
  maxRetries: number;
451
451
  errorType: string;
452
452
  delayMs: number;
453
+ /**
454
+ * Tiered reconnect (tiered-reconnect §5.4). THREE OPTIONAL FIELDS, and
455
+ * `EXEC_SCHEMA_VERSION` does not move: this file's rule is that adding a field or
456
+ * an event type never bumps it, and a consumer that ignores them sees exactly the
457
+ * payload it always saw.
458
+ *
459
+ * `attempt` keeps its PER-TIER meaning; `totalAttempts` is the cumulative one, so
460
+ * a machine consumer can report "13 retries" without knowing the ladder exists.
461
+ */
462
+ tier?: 1 | 2 | 3;
463
+ tierCount?: number;
464
+ totalAttempts?: number;
453
465
  }
454
466
  /**
455
467
  * The bridge control channel (headless-host-bridge §4.2.2).
@@ -1621,6 +1621,12 @@ export class ExecRunner {
1621
1621
  maxRetries: se.maxRetries,
1622
1622
  errorType: String(se.errorType),
1623
1623
  delayMs: se.delayMs,
1624
+ // Tiered reconnect (§5.4): pure pass-through, and absent when this host is
1625
+ // not escalating. `-p` / `exec` are bounded by default, so a machine
1626
+ // consumer here normally sees tiers 1 and 2 and never a 3.
1627
+ ...(se.tier !== undefined ? { tier: se.tier } : {}),
1628
+ ...(se.tierCount !== undefined ? { tierCount: se.tierCount } : {}),
1629
+ ...(se.totalAttempts !== undefined ? { totalAttempts: se.totalAttempts } : {}),
1624
1630
  });
1625
1631
  }
1626
1632
  }
@@ -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);