@aragon-agent/cli 0.6.66 → 0.6.70

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 (36) hide show
  1. package/CHANGELOG.md +29 -0
  2. package/README.md +30 -3
  3. package/dist/agent/controller.d.ts +27 -0
  4. package/dist/agent/controller.js +41 -0
  5. package/dist/agent/governance-wiring.js +2 -0
  6. package/dist/app/App.js +31 -2
  7. package/dist/app/use-governance-rounds.d.ts +44 -0
  8. package/dist/app/use-governance-rounds.js +75 -0
  9. package/dist/commands/governance-command.js +45 -3
  10. package/dist/config/cli-commands.d.ts +1 -1
  11. package/dist/config/cli-commands.js +26 -0
  12. package/dist/gene/hub.d.ts +10 -1
  13. package/dist/gene/hub.js +25 -7
  14. package/dist/governance/copy.d.ts +8 -0
  15. package/dist/governance/copy.js +16 -1
  16. package/dist/governance/engine/cards.js +9 -1
  17. package/dist/governance/engine/digest.js +6 -2
  18. package/dist/governance/engine/engine-core.d.ts +12 -0
  19. package/dist/governance/engine/engine-core.js +29 -0
  20. package/dist/governance/engine/engine.d.ts +1 -0
  21. package/dist/governance/engine/engine.js +4 -1
  22. package/dist/governance/engine/lifecycle.d.ts +36 -1
  23. package/dist/governance/engine/lifecycle.js +185 -2
  24. package/dist/governance/engine/report.d.ts +8 -0
  25. package/dist/governance/engine/report.js +17 -0
  26. package/dist/governance/engine/stage-runner.js +48 -3
  27. package/dist/governance/engine/state-machine.d.ts +27 -2
  28. package/dist/governance/engine/state-machine.js +146 -20
  29. package/dist/governance/prompts/orchestrator-block.d.ts +2 -0
  30. package/dist/governance/prompts/orchestrator-block.js +25 -0
  31. package/dist/governance/store/events-log.d.ts +4 -2
  32. package/dist/governance/store/events-log.js +4 -2
  33. package/dist/governance/tools/inspector-tools.js +4 -0
  34. package/dist/governance/tools/lead-tools.d.ts +1 -1
  35. package/dist/governance/tools/lead-tools.js +14 -2
  36. package/package.json +3 -3
@@ -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 ?? [],
@@ -161,6 +161,18 @@ export declare class EngineCore {
161
161
  constructor(deps: EngineDeps);
162
162
  now(): number;
163
163
  config(): GovernanceConfig;
164
+ /**
165
+ * The run's effective round limit, read from the LIVE config every call: `/gov rounds 6`
166
+ * and the escalation card's `retry` therefore take effect on the very next dispatch, with
167
+ * no "refresh the frozen limits" step - which is exactly why no copy of the policy value
168
+ * is stored on the run (governance-round-budget RV-P1-2).
169
+ */
170
+ roundsLimit(): number;
171
+ /** The options every stage check and every `NEXT` build is given, from one read. */
172
+ stageOptions(): {
173
+ teamCeiling: number;
174
+ roundsLimit: number;
175
+ };
164
176
  requireRun(): RunState;
165
177
  wp(id: string): WorkPackage | undefined;
166
178
  /** Public queue entry for modules that persist their own files in order with the rest. */
@@ -19,6 +19,7 @@
19
19
  * else in the tree touches `core.ledger`.
20
20
  */
21
21
  import { GOV_LIMITS, GOV_SCHEMA_VERSION } from '@aragon-agent/tui/model/governance/limits';
22
+ import { ensureRunRounds, roundsLimit } from '@aragon-agent/tui/model/governance/rounds';
22
23
  import { applyOp, replay } from '../rules/ledger-replay.js';
23
24
  import { createLedger, standings, teamHealth } from '../rules/ledger-state.js';
24
25
  import { budgetLevel } from './budget.js';
@@ -142,6 +143,22 @@ export class EngineCore {
142
143
  config() {
143
144
  return this.deps.getConfig();
144
145
  }
146
+ /**
147
+ * The run's effective round limit, read from the LIVE config every call: `/gov rounds 6`
148
+ * and the escalation card's `retry` therefore take effect on the very next dispatch, with
149
+ * no "refresh the frozen limits" step - which is exactly why no copy of the policy value
150
+ * is stored on the run (governance-round-budget RV-P1-2).
151
+ */
152
+ roundsLimit() {
153
+ const run = this.run;
154
+ if (run === null)
155
+ return GOV_LIMITS.hardMaxRounds;
156
+ return roundsLimit(run, this.config().rounds);
157
+ }
158
+ /** The options every stage check and every `NEXT` build is given, from one read. */
159
+ stageOptions() {
160
+ return { teamCeiling: this.deps.getTeamCeiling(), roundsLimit: this.roundsLimit() };
161
+ }
145
162
  requireRun() {
146
163
  if (this.run === null)
147
164
  throw new Error('governance: no active run');
@@ -442,6 +459,10 @@ export class EngineCore {
442
459
  .map((id) => run.workPackages[id])
443
460
  .find((w) => w !== undefined && w.reworkCount > 0);
444
461
  const phaseIndex = currentDisplayPhase(run);
462
+ // ONE live-config read for both fields: the limit and the mode cannot disagree with each
463
+ // other or with the policy in force (governance-round-budget 7.4).
464
+ const budget = this.config().rounds;
465
+ const rounds = ensureRunRounds(run);
445
466
  return {
446
467
  runId: run.runId,
447
468
  goal: run.goal,
@@ -461,6 +482,7 @@ export class EngineCore {
461
482
  reworkNote: reworkWp
462
483
  ? `rework ${reworkWp.reworkCount}/${run.limits.maxRework} (${reworkWp.id})`
463
484
  : null,
485
+ rounds: { ...rounds, limit: roundsLimit(run, budget), auto: budget === null },
464
486
  // Present only when true, so a snapshot without a pending pause is byte-identical
465
487
  // to what it was before the field existed.
466
488
  ...(this.pauseRequested ? { pauseRequested: true } : {}),
@@ -552,6 +574,13 @@ export class EngineCore {
552
574
  const health = this.health();
553
575
  if (health !== null && health < GOV_LIMITS.healthWarnThreshold)
554
576
  out.push('team health low');
577
+ // LAST: a budget warning and an open escalation must keep the panel's single alert row
578
+ // (governance-panel.ts) - the round cap is the slower fuse of the three.
579
+ const rounds = ensureRunRounds(run);
580
+ const limit = roundsLimit(run, this.config().rounds);
581
+ if (rounds.used >= limit) {
582
+ out.push(`rounds spent (${rounds.used}/${limit}) - the engine escalates instead of retrying`);
583
+ }
555
584
  return out;
556
585
  }
557
586
  static schemaVersion() {
@@ -31,6 +31,7 @@ export declare class GovernanceEngine implements GovernanceEngineApi {
31
31
  close(summary?: string): Promise<ToolText>;
32
32
  abandon(reason: string): Promise<ToolText>;
33
33
  resolve(input: unknown): Promise<ToolText>;
34
+ rounds(input: unknown): Promise<ToolText>;
34
35
  private guard;
35
36
  snapshot(): GovernanceSnapshot | null;
36
37
  isStageRunning(): boolean;
@@ -24,7 +24,7 @@ import { parseArtifactId } from '../store/artifacts.js';
24
24
  import { EngineCore } from './engine-core.js';
25
25
  import { currentDisplayPhase } from './engine-core.js';
26
26
  import { handleInspectorApply, handleInspectorRule, handleInspectorSettle } from './inspector.js';
27
- import { abandonRun, closeRun, resolveEscalation, resumeRun, startRun, statusText, } from './lifecycle.js';
27
+ import { abandonRun, closeRun, resolveEscalation, resumeRun, roundsGrant, startRun, statusText, } from './lifecycle.js';
28
28
  import { cancelPause, requestPause } from './pause.js';
29
29
  import { renderStandings } from './report.js';
30
30
  import { runStage } from './stage-runner.js';
@@ -103,6 +103,9 @@ export class GovernanceEngine {
103
103
  async resolve(input) {
104
104
  return this.guard('resolve', () => resolveEscalation(this.core, input));
105
105
  }
106
+ async rounds(input) {
107
+ return this.guard('rounds', () => roundsGrant(this.core, input));
108
+ }
106
109
  async guard(where, fn) {
107
110
  try {
108
111
  return await fn();
@@ -8,9 +8,10 @@
8
8
  * an error: an error result invites an identical retry, a result that says what to do
9
9
  * instead does not.
10
10
  */
11
- import type { Escalation } from '@aragon-agent/tui/model/governance/types';
11
+ import type { Escalation, StageKind } from '@aragon-agent/tui/model/governance/types';
12
12
  import type { EngineCore } from './engine-core.js';
13
13
  export declare const BUDGET_TOPIC_PREFIX = "Team token budget";
14
+ export declare const ROUNDS_TOPIC_PREFIX = "The round budget is spent";
14
15
  /** `gov_run start`. Creates nothing unless every check passes (7.2). */
15
16
  export declare function startRun(core: EngineCore, raw: unknown, signal?: AbortSignal): Promise<string>;
16
17
  /** Retention prune, once per engine instance, never blocking and never throwing. */
@@ -27,3 +28,37 @@ export declare function abandonRun(core: EngineCore, reason: string): Promise<st
27
28
  export declare function openBudgetEscalation(core: EngineCore): Escalation;
28
29
  /** `gov_run resolve`: the user's L3 ruling, optionally with a disposition (7.2). */
29
30
  export declare function resolveEscalation(core: EngineCore, raw: unknown): Promise<string>;
31
+ /** What the refusal was about: the stage it named and the packages it listed. */
32
+ export interface RoundsSubjectHint {
33
+ stage: StageKind;
34
+ wpIds: readonly string[];
35
+ }
36
+ /**
37
+ * Open the `rounds_exhausted` escalation (called by the stage runner when the cap is hit).
38
+ *
39
+ * IDEMPOTENT, and the dedupe is defence in depth: opening it sets `status = 'escalated'`,
40
+ * and `runLevelRefusal` refuses an escalated run before `roundsGate` is ever reached, so a
41
+ * second dispatch of the same stage cannot produce a second card. The find() here covers the
42
+ * one window that ordering does not (a resolve that immediately re-opens the same cap).
43
+ */
44
+ export declare function openRoundsEscalation(core: EngineCore, hint?: RoundsSubjectHint): Escalation;
45
+ /**
46
+ * Close an open `rounds_exhausted` escalation whose complaint is no longer true.
47
+ *
48
+ * WHY THIS EXISTS (a gap found while implementing): the card says "the round budget is
49
+ * spent", and then the user raises the budget with `/gov rounds 6`. Leaving the card open
50
+ * would make the card LIE and would block every dispatch behind `runLevelRefusal`, so the
51
+ * run could only be rescued by ruling `retry` - a second, redundant step for a problem the
52
+ * user has already fixed. Called from the dispatch path, before the gate reads the limit.
53
+ */
54
+ export declare function reconcileRoundsEscalation(core: EngineCore): boolean;
55
+ /** What `gov_run {action:"rounds"}` answers: the facts, and what is still available. */
56
+ export declare function roundsStatusText(core: EngineCore): string;
57
+ /**
58
+ * `gov_run {action:"rounds", reason}`: the orchestrator asks for one more round.
59
+ *
60
+ * NOT routed through `runLevelRefusal` (6.3): the whole point is that this call works while
61
+ * the run IS escalated on the round cap - that is the self-rescue path S5. Only a finished
62
+ * run is refused here; every other rule belongs to `grantRound`.
63
+ */
64
+ export declare function roundsGrant(core: EngineCore, raw: unknown): Promise<string>;
@@ -11,6 +11,7 @@
11
11
  import { readFile } from 'node:fs/promises';
12
12
  import { join } from 'node:path';
13
13
  import { GOV_LIMITS, GOV_SCHEMA_VERSION } from '@aragon-agent/tui/model/governance/limits';
14
+ import { deriveAutoRounds, emptyRunRounds, ensureRunRounds, grantRound, roundGrantRefusal, roundsLimit, } from '@aragon-agent/tui/model/governance/rounds';
14
15
  import { formatDispatchEstimate, formatDispatchPlanForAgent } from '../copy.js';
15
16
  import { rosterIds, rosterSizes } from '../roles.js';
16
17
  import { createLedger } from '../rules/ledger-state.js';
@@ -22,9 +23,10 @@ import { estimateDispatches, estimateForRun } from './estimate.js';
22
23
  import { planPhases } from './phase-planner.js';
23
24
  import { recoverInterruptedStage, replayCheckpoints } from './rebuild.js';
24
25
  import { buildBoardMarkdown, buildFinalReport, renderPhases, renderWpTable, } from './report.js';
25
- import { applyResolveDisposition, canClose, closeEscalation, nextEscalationId, } from './state-machine.js';
26
+ import { applyResolveDisposition, canClose, closeEscalation, currentPhaseIndex, nextEscalationId, } from './state-machine.js';
26
27
  import { normalizeStartInput } from './start-input.js';
27
28
  export const BUDGET_TOPIC_PREFIX = 'Team token budget';
29
+ export const ROUNDS_TOPIC_PREFIX = 'The round budget is spent';
28
30
  const LIVE_STATUSES = new Set([
29
31
  'executing',
30
32
  'escalated',
@@ -247,10 +249,19 @@ function buildRunState(core, c, runId, plan) {
247
249
  maxFixCycles: Math.min(cfg.maxFixCycles, GOV_LIMITS.hardMaxFixCycles),
248
250
  budgetTokens: cfg.budgetTokens,
249
251
  },
252
+ // FACTS ONLY (RV-P1-2). The POLICY value is read live by `roundsLimit()`, so `/gov rounds 6`
253
+ // and a card `retry` both take effect on the very next dispatch, with no refresh step.
254
+ rounds: emptyRunRounds(deriveAutoRounds({
255
+ phaseCount: c.planned.length,
256
+ wpCount: input.workPackages.length,
257
+ })),
250
258
  };
251
259
  }
252
260
  /** Reset every per-run field of the core and wire it to the new run. */
253
261
  function adoptRun(core, run) {
262
+ // Normalise BEFORE the run enters the engine, so every later read path (snapshot, digest,
263
+ // cards, `status`) sees the same facts without a second fallback (7.1: `rounds` optional).
264
+ run.rounds = ensureRunRounds(run);
254
265
  core.run = run;
255
266
  core.seq = 0;
256
267
  core.pauseRequested = false;
@@ -350,6 +361,10 @@ async function loadForResume(core, runId) {
350
361
  return release(`run ${runId} is already ${loaded.run.status}; start a new run.`);
351
362
  }
352
363
  core.run = loaded.run;
364
+ // An older `run.json` has no `rounds`: derive the budget from the phase shape and start the
365
+ // counters at 0. The rounds a previous version ran are unknowable, and `n/a` in the report
366
+ // is the honest answer (R-10) - not an invented zero in the other direction.
367
+ core.run.rounds = ensureRunRounds(core.run);
353
368
  core.pauseRequested = false;
354
369
  core.userPaused = false;
355
370
  core.ledger = loaded.ledger ?? createLedger([]);
@@ -479,6 +494,7 @@ function finalize(core, summary, abandoned) {
479
494
  ...board,
480
495
  ...(summary !== undefined ? { summary } : {}),
481
496
  wallMs: core.now() - run.createdAt,
497
+ roundsLimit: core.roundsLimit(),
482
498
  });
483
499
  core.writeFile('reports/final.md', report);
484
500
  core.exportScoreboard();
@@ -524,6 +540,7 @@ export async function closeRun(core, summary) {
524
540
  recent: [],
525
541
  ...(summary !== undefined ? { summary } : {}),
526
542
  wallMs: core.now() - run.createdAt,
543
+ roundsLimit: core.roundsLimit(),
527
544
  });
528
545
  return composeDigest(core, {
529
546
  headline: `OK: run ${run.runId} closed.`,
@@ -633,7 +650,7 @@ export async function resolveEscalation(core, raw) {
633
650
  return refusal(core, 'the team-token budget is still exhausted. Ask the user to raise it (/gov budget <n>), ' +
634
651
  'then resolve again, or abandon the run.');
635
652
  }
636
- const applied = applyResolveDisposition(run, escalation, input.disposition);
653
+ const applied = applyResolveDisposition(run, escalation, input.disposition, core.config().rounds);
637
654
  if (!applied.ok)
638
655
  return composeDigest(core, { headline: applied.message });
639
656
  closeEscalation(run, escalation, input.ruling);
@@ -656,3 +673,169 @@ export async function resolveEscalation(core, raw) {
656
673
  });
657
674
  return flushNote === null ? text : `${text}\n${flushNote}`;
658
675
  }
676
+ /**
677
+ * Open the `rounds_exhausted` escalation (called by the stage runner when the cap is hit).
678
+ *
679
+ * IDEMPOTENT, and the dedupe is defence in depth: opening it sets `status = 'escalated'`,
680
+ * and `runLevelRefusal` refuses an escalated run before `roundsGate` is ever reached, so a
681
+ * second dispatch of the same stage cannot produce a second card. The find() here covers the
682
+ * one window that ordering does not (a resolve that immediately re-opens the same cap).
683
+ */
684
+ export function openRoundsEscalation(core, hint) {
685
+ const run = core.requireRun();
686
+ const existing = run.escalations.find((e) => e.status === 'open' && e.kind === 'rounds_exhausted');
687
+ if (existing !== undefined)
688
+ return existing;
689
+ const rounds = ensureRunRounds(run);
690
+ const budget = core.config().rounds;
691
+ const limit = roundsLimit(run, budget);
692
+ const escalation = {
693
+ id: nextEscalationId(run),
694
+ level: 'L3',
695
+ kind: 'rounds_exhausted',
696
+ ...roundsSubject(run, hint),
697
+ topic: `${ROUNDS_TOPIC_PREFIX} after ${rounds.used} round(s) ` +
698
+ `(limit ${limit}, ${budget === null ? 'auto' : 'fixed'}). ` +
699
+ 'The work is not converged; the run needs a ruling.',
700
+ positions: [],
701
+ status: 'open',
702
+ };
703
+ run.escalations.push(escalation);
704
+ run.status = 'escalated';
705
+ core.log('escalation', 'engine', { id: escalation.id, kind: 'rounds_exhausted' });
706
+ core.checkpoint();
707
+ core.emit((snapshot) => ({
708
+ type: 'escalation',
709
+ snapshot,
710
+ escalation,
711
+ card: escalationCard(core, escalation),
712
+ }));
713
+ return escalation;
714
+ }
715
+ /**
716
+ * WHICH object the ruling is about: a work package when it is a rework that ran out of
717
+ * rounds (`retry` puts it back into `rework`), otherwise the phase whose fix loop is out of
718
+ * rounds (`retry` buys one more round for that phase).
719
+ *
720
+ * The hint decides WHOSE question it is. A `fix` refusal is a PHASE question even when some
721
+ * other package happens to sit in `rework`: naming that one would offer `accept_as_is` /
722
+ * `drop` for a package the ruling is not about, and `drop` would discard it. A `dev` refusal
723
+ * only considers the packages the call listed, and only those the gate itself counts
724
+ * (`rework`, or `blocked@dev` - exactly `wouldStartRound`'s predicate, so a package merely
725
+ * blocked at review is never named).
726
+ */
727
+ function roundsSubject(run, hint) {
728
+ if (hint?.stage !== 'fix') {
729
+ const asked = hint !== undefined && hint.wpIds.length > 0 ? hint.wpIds : run.wpOrder;
730
+ const wp = asked
731
+ .map((id) => run.workPackages[id])
732
+ .find((w) => w !== undefined &&
733
+ (w.status === 'rework' || (w.status === 'blocked' && w.blockedAt === 'dev')));
734
+ if (wp !== undefined)
735
+ return { wpId: wp.id, phase: wp.phase };
736
+ }
737
+ const index = currentPhaseIndex(run);
738
+ return index === null ? {} : { phase: index };
739
+ }
740
+ /**
741
+ * Close an open `rounds_exhausted` escalation whose complaint is no longer true.
742
+ *
743
+ * WHY THIS EXISTS (a gap found while implementing): the card says "the round budget is
744
+ * spent", and then the user raises the budget with `/gov rounds 6`. Leaving the card open
745
+ * would make the card LIE and would block every dispatch behind `runLevelRefusal`, so the
746
+ * run could only be rescued by ruling `retry` - a second, redundant step for a problem the
747
+ * user has already fixed. Called from the dispatch path, before the gate reads the limit.
748
+ */
749
+ export function reconcileRoundsEscalation(core) {
750
+ const run = core.run;
751
+ if (run === null)
752
+ return false;
753
+ const open = run.escalations.filter((e) => e.status === 'open' && e.kind === 'rounds_exhausted');
754
+ if (open.length === 0)
755
+ return false;
756
+ const rounds = ensureRunRounds(run);
757
+ const limit = roundsLimit(run, core.config().rounds);
758
+ if (rounds.used >= limit)
759
+ return false;
760
+ for (const escalation of open) {
761
+ closeEscalation(run, escalation, `the round budget was raised (${rounds.used}/${limit})`);
762
+ }
763
+ core.log('resolution', 'engine', { kind: 'rounds_exhausted', limit, used: rounds.used });
764
+ core.checkpoint();
765
+ return true;
766
+ }
767
+ /** What `gov_run {action:"rounds"}` answers: the facts, and what is still available. */
768
+ export function roundsStatusText(core) {
769
+ const run = core.run;
770
+ if (run === null)
771
+ return 'NOT ACCEPTED: no governance run is active.';
772
+ const rounds = ensureRunRounds(run);
773
+ const budget = core.config().rounds;
774
+ const limit = roundsLimit(run, budget);
775
+ const agentLeft = Math.max(0, GOV_LIMITS.autoRoundExtensionsPerRun - rounds.agentGrants);
776
+ const userLeft = Math.max(0, GOV_LIMITS.maxRoundGrantsPerRun - rounds.grants);
777
+ return (`OK: round budget ${budget === null ? 'auto' : 'fixed'} - used ${rounds.used}/${limit}, ` +
778
+ `${agentLeft} engine grant(s) and ${userLeft} user grant(s) left; ` +
779
+ `this plan's auto budget is ${rounds.autoBudget}.`);
780
+ }
781
+ /**
782
+ * `gov_run {action:"rounds", reason}`: the orchestrator asks for one more round.
783
+ *
784
+ * NOT routed through `runLevelRefusal` (6.3): the whole point is that this call works while
785
+ * the run IS escalated on the round cap - that is the self-rescue path S5. Only a finished
786
+ * run is refused here; every other rule belongs to `grantRound`.
787
+ */
788
+ export async function roundsGrant(core, raw) {
789
+ const run = core.run;
790
+ if (run === null)
791
+ return refusal(core, 'no governance run is active; call gov_run start first.');
792
+ const args = isRecord(raw) ? raw : {};
793
+ const reason = typeof args.reason === 'string' ? args.reason.trim() : '';
794
+ // The read-only form: any state, any time - it is how the model learns whether it may ask.
795
+ if (reason === '')
796
+ return composeDigest(core, { headline: roundsStatusText(core) });
797
+ if (run.status === 'closed' || run.status === 'abandoned') {
798
+ return refusal(core, `run ${run.runId} is ${run.status}; a round cannot be granted to it.`);
799
+ }
800
+ if (reason.length < GOV_LIMITS.roundsReasonMinChars) {
801
+ return refusal(core, `a round grant needs a reason of at least ${GOV_LIMITS.roundsReasonMinChars} characters ` +
802
+ '(why the run cannot converge without one more round).');
803
+ }
804
+ if (reason.length > GOV_LIMITS.reasonChars) {
805
+ return refusal(core, `the reason is longer than ${GOV_LIMITS.reasonChars} characters.`);
806
+ }
807
+ const budget = core.config().rounds;
808
+ const rounds = ensureRunRounds(run);
809
+ const granted = grantRound(rounds, 'agent', budget);
810
+ if (!granted.ok)
811
+ return refusal(core, roundGrantRefusal(granted.reason, rounds, budget));
812
+ run.rounds = granted.rounds;
813
+ core.log('rounds_granted', 'engine', {
814
+ reason: reason.slice(0, GOV_LIMITS.reasonChars),
815
+ by: 'agent',
816
+ limit: granted.limit,
817
+ used: rounds.used,
818
+ });
819
+ closeRoundsEscalation(run);
820
+ core.checkpoint();
821
+ core.emit((snapshot) => ({ type: 'agent_state', snapshot }));
822
+ const flush = await core.flush();
823
+ const text = composeDigest(core, {
824
+ headline: `OK: one more round granted (limit now ${granted.limit}). Reason recorded: ${reason}`,
825
+ standings: false,
826
+ });
827
+ return flush === null ? text : `${text}\n${flush}`;
828
+ }
829
+ /**
830
+ * Mark the round escalation this grant just answered as resolved, through the ONE close path
831
+ * every kind uses. The run leaves `escalated` only when nothing ELSE is open: the token
832
+ * budget may still be what blocks it.
833
+ */
834
+ function closeRoundsEscalation(run) {
835
+ const ruling = 'the orchestrator asked for one more round and recorded a reason';
836
+ for (const escalation of run.escalations) {
837
+ if (escalation.status !== 'open' || escalation.kind !== 'rounds_exhausted')
838
+ continue;
839
+ closeEscalation(run, escalation, ruling);
840
+ }
841
+ }
@@ -58,7 +58,15 @@ export declare function renderEscalation(e: Escalation): string;
58
58
  export interface FinalReportInput extends BoardInput {
59
59
  summary?: string;
60
60
  wallMs: number;
61
+ /** The run's effective round limit (`core.roundsLimit()`), for the accounting line. */
62
+ roundsLimit?: number;
61
63
  }
64
+ /**
65
+ * The round accounting for a human document. `n/a` for a run written before the budget
66
+ * existed: the rounds it actually ran cannot be recovered, and a fabricated 0 would be the
67
+ * same lie as "$0.00" for an unpriced run (R-10).
68
+ */
69
+ export declare function roundsReportLine(run: RunState, limit?: number): string;
62
70
  /**
63
71
  * The closing report: what was delivered, what was accepted with known issues, what was
64
72
  * dropped, final standings. Bounded by `finalReportMaxBytes`.
@@ -165,6 +165,8 @@ export function buildBoardMarkdown(input) {
165
165
  renderWpTable(run),
166
166
  '',
167
167
  renderStandings(input.standings, input.health),
168
+ '',
169
+ roundsReportLine(run),
168
170
  '```',
169
171
  ];
170
172
  if (run.escalations.length > 0) {
@@ -192,6 +194,20 @@ export function renderEscalation(e) {
192
194
  const ruling = e.ruling ? ` - ruling: ${e.ruling}` : '';
193
195
  return `- ${e.id} [${e.kind}] ${e.topic}: ${e.status}${ruling}`;
194
196
  }
197
+ /**
198
+ * The round accounting for a human document. `n/a` for a run written before the budget
199
+ * existed: the rounds it actually ran cannot be recovered, and a fabricated 0 would be the
200
+ * same lie as "$0.00" for an unpriced run (R-10).
201
+ */
202
+ export function roundsReportLine(run, limit) {
203
+ const rounds = run.rounds;
204
+ if (rounds === undefined)
205
+ return 'Rounds: n/a (this run predates the round budget)';
206
+ const cap = limit ?? rounds.autoBudget + rounds.grants;
207
+ return (`Rounds: ${rounds.used}/${cap} ` +
208
+ `(auto ${rounds.autoBudget} + ${rounds.grants} granted; ` +
209
+ `${rounds.rework} rework, ${rounds.fix} fix)`);
210
+ }
195
211
  /**
196
212
  * The closing report: what was delivered, what was accepted with known issues, what was
197
213
  * dropped, final standings. Bounded by `finalReportMaxBytes`.
@@ -221,6 +237,7 @@ export function buildFinalReport(input) {
221
237
  .join(', ')}`);
222
238
  }
223
239
  lines.push('', renderStandings(input.standings, input.health), '');
240
+ lines.push(roundsReportLine(run, input.roundsLimit));
224
241
  lines.push(`Team tokens: input ${run.usage.inputTokens}, ${cacheClause(run.usage)}output ${run.usage.outputTokens}, cost ${run.usage.costUsd === null ? 'pricing unknown' : `$${run.usage.costUsd.toFixed(4)}`}; wall ${Math.round(input.wallMs / 1000)}s`);
225
242
  return clipBytes(`${lines.join('\n')}\n`, GOV_LIMITS.finalReportMaxBytes);
226
243
  }