@aragon-agent/cli 0.6.48 → 0.6.50

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 (72) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/README.md +1 -0
  3. package/dist/agent/controller.d.ts +21 -0
  4. package/dist/agent/controller.js +35 -8
  5. package/dist/agent/governance-wiring.d.ts +2 -0
  6. package/dist/agent/governance-wiring.js +4 -0
  7. package/dist/app/App.d.ts +2 -4
  8. package/dist/app/App.js +279 -522
  9. package/dist/cli.js +8 -150
  10. package/dist/commands/catalog.d.ts +17 -0
  11. package/dist/commands/catalog.js +52 -0
  12. package/dist/commands/create-registry.d.ts +13 -0
  13. package/dist/commands/create-registry.js +19 -0
  14. package/dist/commands/governance-command.js +5 -1
  15. package/dist/commands/skills.js +18 -67
  16. package/dist/config/env.d.ts +2 -0
  17. package/dist/config/env.js +11 -1
  18. package/dist/config/load.js +4 -0
  19. package/dist/fast/review-call.d.ts +6 -0
  20. package/dist/fast/review-call.js +10 -0
  21. package/dist/governance/engine/budget.d.ts +18 -6
  22. package/dist/governance/engine/budget.js +61 -19
  23. package/dist/governance/engine/engine-core.d.ts +10 -0
  24. package/dist/governance/engine/engine-core.js +56 -9
  25. package/dist/governance/engine/engine.d.ts +1 -0
  26. package/dist/governance/engine/engine.js +9 -10
  27. package/dist/governance/engine/inspector.js +4 -3
  28. package/dist/governance/engine/lifecycle.js +4 -2
  29. package/dist/governance/engine/report.js +7 -1
  30. package/dist/governance/engine/run-digest.js +2 -1
  31. package/dist/governance/engine/stage-runner.js +1 -1
  32. package/dist/governance/engine/submissions.d.ts +2 -0
  33. package/dist/governance/engine/submissions.js +22 -3
  34. package/dist/governance/engine/visibility.d.ts +10 -0
  35. package/dist/governance/engine/visibility.js +28 -0
  36. package/dist/governance/rules/settlement.d.ts +7 -0
  37. package/dist/governance/rules/settlement.js +24 -0
  38. package/dist/governance/tools/shared-tools.d.ts +2 -0
  39. package/dist/governance/tools/shared-tools.js +15 -1
  40. package/dist/governance/tools/submit-tools.js +14 -7
  41. package/dist/host/commands.d.ts +18 -0
  42. package/dist/host/commands.js +30 -0
  43. package/dist/host/controller-factory.d.ts +109 -0
  44. package/dist/host/controller-factory.js +159 -0
  45. package/dist/host/controller-feed.d.ts +122 -0
  46. package/dist/host/controller-feed.js +356 -0
  47. package/dist/host/index-build.d.ts +23 -0
  48. package/dist/host/index-build.js +35 -0
  49. package/dist/host/index.d.ts +21 -0
  50. package/dist/host/index.js +21 -0
  51. package/dist/host/interaction.d.ts +58 -0
  52. package/dist/host/interaction.js +165 -0
  53. package/dist/host/logging.d.ts +7 -0
  54. package/dist/host/logging.js +7 -0
  55. package/dist/host/prompts.d.ts +10 -0
  56. package/dist/host/prompts.js +9 -0
  57. package/dist/host/sessions.d.ts +87 -0
  58. package/dist/host/sessions.js +234 -0
  59. package/dist/host/settings.d.ts +104 -0
  60. package/dist/host/settings.js +235 -0
  61. package/dist/host/skills.d.ts +19 -0
  62. package/dist/host/skills.js +38 -0
  63. package/dist/skills/command-names.d.ts +19 -0
  64. package/dist/skills/command-names.js +28 -0
  65. package/dist/skills/invoke.d.ts +38 -0
  66. package/dist/skills/invoke.js +65 -0
  67. package/dist/team/overseer.d.ts +25 -1
  68. package/dist/team/overseer.js +38 -1
  69. package/dist/team/runtime.d.ts +2 -0
  70. package/dist/team/runtime.js +10 -7
  71. package/dist/team/subagent.js +6 -4
  72. package/package.json +3 -3
@@ -5,9 +5,14 @@
5
5
  *
6
6
  * WHAT IS COUNTED. `run.usage` and `governance.budgetTokens` cover the governed TEAM's
7
7
  * spend only: every dispatch's `outcome.usage` plus `outcome.overseerUsage` (the
8
- * supervisor's fast-tier spend). The orchestrator's own turns are already in the
9
- * session total on the status bar, and labelling this figure "team tokens" everywhere
10
- * keeps a user from reading it as the session total.
8
+ * supervisor's fast-tier spend). The unit is input + cacheRead + cacheWrite + output (the
9
+ * same formula as the status bar's context occupancy): Anthropic reports `input_tokens`
10
+ * EXCLUDING cached tokens, and on a long cached run the cache traffic is most of the spend,
11
+ * so an input+output budget would not bound spend at all. This is a deliberate deviation
12
+ * from the literal wording of the spec (8.5), which was amended alongside. The
13
+ * orchestrator's own turns are already in the session total on the status bar, and
14
+ * labelling this figure "team tokens" everywhere keeps a user from reading it as the
15
+ * session total.
11
16
  *
12
17
  * COST IS NEVER FABRICATED. `costUsd` stays `null` until a price table is supplied; once
13
18
  * it is `null` it is only replaced by a number when a price arrives, and a run that had
@@ -32,34 +37,58 @@ function costOf(usage, price) {
32
37
  perMillion(usage.cacheReadTokens, price.cacheRead) +
33
38
  perMillion(usage.cacheWriteTokens, price.cacheWrite));
34
39
  }
35
- function parts(outcome) {
36
- return [outcome.usage, outcome.overseerUsage].filter((u) => u !== undefined);
37
- }
38
40
  /**
39
41
  * Fold one dispatch into the run usage. Returns a NEW object. If any non-empty part of
40
- * the dispatch cannot be priced (`price` absent) the running cost becomes `null`.
42
+ * the dispatch cannot be priced the running cost becomes `null`. The children's usage is
43
+ * priced with `price`; the supervisor runs on the FAST tier and is priced with
44
+ * `overseerPrice` ONLY - never with the children's table (a wrong price reads as complete).
41
45
  */
42
- export function accumulateUsage(previous, outcome, price) {
46
+ export function accumulateUsage(previous, outcome, price, overseerPrice) {
43
47
  let inputTokens = previous.inputTokens;
44
48
  let outputTokens = previous.outputTokens;
49
+ let cacheReadTokens = previous.cacheReadTokens ?? 0;
50
+ let cacheWriteTokens = previous.cacheWriteTokens ?? 0;
45
51
  let costUsd = previous.costUsd;
46
- for (const usage of parts(outcome)) {
52
+ const parts = [
53
+ [outcome.usage, price],
54
+ [outcome.overseerUsage, overseerPrice],
55
+ ];
56
+ for (const [usage, table] of parts) {
57
+ if (usage === undefined)
58
+ continue;
47
59
  inputTokens += usage.inputTokens;
48
60
  outputTokens += usage.outputTokens;
61
+ cacheReadTokens += usage.cacheReadTokens ?? 0;
62
+ cacheWriteTokens += usage.cacheWriteTokens ?? 0;
49
63
  if (costUsd === null)
50
64
  continue;
51
- if (price)
52
- costUsd += usage.cost ?? costOf(usage, price);
65
+ if (table)
66
+ costUsd += usage.cost ?? costOf(usage, table);
53
67
  else if (usage.cost !== undefined)
54
68
  costUsd += usage.cost;
55
- else if (usage.inputTokens + usage.outputTokens > 0)
69
+ else if (spentTokens(usage) > 0)
56
70
  costUsd = null;
57
71
  }
58
- return { inputTokens, outputTokens, costUsd };
72
+ return {
73
+ inputTokens,
74
+ outputTokens,
75
+ ...(cacheReadTokens > 0 ? { cacheReadTokens } : {}),
76
+ ...(cacheWriteTokens > 0 ? { cacheWriteTokens } : {}),
77
+ costUsd,
78
+ };
79
+ }
80
+ function spentTokens(usage) {
81
+ return (usage.inputTokens +
82
+ usage.outputTokens +
83
+ (usage.cacheReadTokens ?? 0) +
84
+ (usage.cacheWriteTokens ?? 0));
59
85
  }
60
- /** Total team tokens (input + output) - the budget's unit. */
86
+ /** Total team tokens (input + cache read + cache write + output) - the budget's unit. */
61
87
  export function totalTokens(usage) {
62
- return usage.inputTokens + usage.outputTokens;
88
+ return (usage.inputTokens +
89
+ usage.outputTokens +
90
+ (usage.cacheReadTokens ?? 0) +
91
+ (usage.cacheWriteTokens ?? 0));
63
92
  }
64
93
  /** `budgetTokens <= 0` means unlimited. */
65
94
  export function budgetLevel(usage, budgetTokens) {
@@ -86,14 +115,27 @@ export function formatTokens(count) {
86
115
  export function formatCost(costUsd) {
87
116
  return costUsd === null ? 'pricing unknown' : `$${costUsd.toFixed(2)}`;
88
117
  }
118
+ /**
119
+ * Whole-number percent of the budget used. It agrees with `budgetLevel`: "100%" only once the
120
+ * budget is exhausted (the 99.5% case used to print 100% while a new stage was still allowed).
121
+ */
122
+ export function budgetPercent(usage, budgetTokens) {
123
+ const rounded = Math.round((totalTokens(usage) / budgetTokens) * 100);
124
+ return budgetLevel(usage, budgetTokens) === 'exhausted'
125
+ ? Math.max(100, rounded)
126
+ : Math.min(99, rounded);
127
+ }
89
128
  /** One line for digests and `gov_run status`. Always says "team tokens". */
90
129
  export function budgetLine(usage, budgetTokens) {
91
- const used = `team tokens: ${formatTokens(totalTokens(usage))} ` +
92
- `(in ${formatTokens(usage.inputTokens)} / out ${formatTokens(usage.outputTokens)}), ` +
130
+ const cache = (usage.cacheReadTokens ?? 0) + (usage.cacheWriteTokens ?? 0);
131
+ const split = `in ${formatTokens(usage.inputTokens)} / ` +
132
+ (cache > 0 ? `cache ${formatTokens(cache)} / ` : '') +
133
+ `out ${formatTokens(usage.outputTokens)}`;
134
+ const used = `team tokens: ${formatTokens(totalTokens(usage))} (${split}), ` +
93
135
  `cost ${formatCost(usage.costUsd)}`;
94
136
  if (!(budgetTokens > 0))
95
137
  return `${used}; no team-token budget set`;
96
- const pct = Math.round((totalTokens(usage) / budgetTokens) * 100);
138
+ const pct = budgetPercent(usage, budgetTokens);
97
139
  return `${used}; ${pct}% of the ${formatTokens(budgetTokens)} team-token budget ` +
98
140
  '(the budget covers team spend only, not the orchestrator)';
99
141
  }
@@ -101,7 +143,7 @@ export function budgetLine(usage, budgetTokens) {
101
143
  export function budgetNotice(usage, budgetTokens) {
102
144
  const level = budgetLevel(usage, budgetTokens);
103
145
  if (level === 'warning') {
104
- const pct = Math.round((totalTokens(usage) / budgetTokens) * 100);
146
+ const pct = budgetPercent(usage, budgetTokens);
105
147
  return `BUDGET WARNING: ${pct}% of the team-token budget is used; new stages stop at 100%.`;
106
148
  }
107
149
  if (level === 'exhausted') {
@@ -47,6 +47,8 @@ export interface EngineDeps {
47
47
  withPausedWatchdog: <T>(fn: () => Promise<T>) => Promise<T>;
48
48
  hasApiKey: () => boolean;
49
49
  modelCost?: () => ModelCost | undefined;
50
+ /** Price of the supervisor's fast tier; absent/undefined makes its share of cost unknown. */
51
+ fastModelCost?: () => ModelCost | undefined;
50
52
  /** PLAN+GOVERN: take (and clear) the approved plan snapshot, if one is pending. */
51
53
  takeApprovedPlan?: () => string | null;
52
54
  /** Non-consuming read of the same snapshot, so a refused `start` does not lose the plan. */
@@ -150,6 +152,8 @@ export declare class EngineCore {
150
152
  private emitTimer;
151
153
  private readonly agentStates;
152
154
  private readonly activity;
155
+ /** Structured twin of `activity` (see `RosterRow.activityPhase`); cleared with it. */
156
+ private readonly activityView;
153
157
  private readonly lastDelta;
154
158
  private stageAbort;
155
159
  private teamUnsubscribe;
@@ -175,6 +179,12 @@ export declare class EngineCore {
175
179
  /** Append ledger lines for a digest (call after `ledgerOp`). */
176
180
  noteBooked(booked: readonly BookedEntry[]): void;
177
181
  resetStageScratch(): void;
182
+ /**
183
+ * Everything a run leaves behind that is NOT persisted state: roster chips, agent states,
184
+ * the activity line and the gov_view log. A new or resumed run starts from a clean board
185
+ * instead of inheriting the previous run's `+5` chips and "submitted" markers.
186
+ */
187
+ resetRunScratch(): void;
178
188
  private entriesAt;
179
189
  private noteDelta;
180
190
  standingRows(): StandingRow[];
@@ -20,11 +20,24 @@
20
20
  */
21
21
  import { GOV_LIMITS, GOV_SCHEMA_VERSION } from '@aragon-agent/tui/model/governance/limits';
22
22
  import { applyOp, replay } from '../rules/ledger-replay.js';
23
- import { createLedger, labelFor, standings, teamHealth } from '../rules/ledger-state.js';
23
+ import { createLedger, standings, teamHealth } from '../rules/ledger-state.js';
24
+ import { budgetLevel } from './budget.js';
24
25
  import { INSPECTOR_ID } from '../rules/ledger-state.js';
25
26
  import { renderLedgerLine } from './report.js';
26
27
  import { buildRunDigest } from './run-digest.js';
27
28
  const EMIT_MIN_INTERVAL_MS = 250;
29
+ /** The optional `RosterRow` fields for one child; `{}` when nothing was observed. */
30
+ function activityFields(view) {
31
+ if (view === undefined)
32
+ return {};
33
+ return {
34
+ activityPhase: view.phase,
35
+ ...(view.tool !== undefined ? { activityTool: view.tool } : {}),
36
+ ...(view.args !== undefined ? { activityArgs: view.args } : {}),
37
+ ...(view.text !== undefined ? { activityText: view.text } : {}),
38
+ activityCalls: view.calls,
39
+ };
40
+ }
28
41
  /** Give an op the stored-event seq so replay stamps exactly what the live path stamped. */
29
42
  export function stampOp(op, seq) {
30
43
  switch (op.op) {
@@ -114,6 +127,8 @@ export class EngineCore {
114
127
  emitTimer = null;
115
128
  agentStates = new Map();
116
129
  activity = new Map();
130
+ /** Structured twin of `activity` (see `RosterRow.activityPhase`); cleared with it. */
131
+ activityView = new Map();
117
132
  lastDelta = new Map();
118
133
  stageAbort = null;
119
134
  teamUnsubscribe = null;
@@ -230,6 +245,23 @@ export class EngineCore {
230
245
  this.inspectorOutcome = null;
231
246
  this.stageEndedEmitted = false;
232
247
  this.touchedFiles.clear();
248
+ // The 3-strikes rule is per STAGE (spec 8.4): a lifetime counter would leave a
249
+ // (identity, WP) pair permanently "not submitted" after three refusals spread over a
250
+ // whole session. A stage-internal auto-redispatch does not pass through here.
251
+ this.validationFailures.clear();
252
+ }
253
+ /**
254
+ * Everything a run leaves behind that is NOT persisted state: roster chips, agent states,
255
+ * the activity line and the gov_view log. A new or resumed run starts from a clean board
256
+ * instead of inheriting the previous run's `+5` chips and "submitted" markers.
257
+ */
258
+ resetRunScratch() {
259
+ this.agentStates.clear();
260
+ this.activity.clear();
261
+ this.activityView.clear();
262
+ this.lastDelta.clear();
263
+ this.viewLog.clear();
264
+ this.validationFailures.clear();
233
265
  }
234
266
  entriesAt(seq) {
235
267
  const out = [];
@@ -284,6 +316,15 @@ export class EngineCore {
284
316
  if (this.run === null)
285
317
  return;
286
318
  this.activity.set(run.label, run.activity ?? run.lastTool ?? '');
319
+ // The structured twin: only what the friendly voice may print. `args` is the
320
+ // already-picked subset (path / pattern / command head), never the raw tool args.
321
+ this.activityView.set(run.label, {
322
+ phase: run.phase,
323
+ ...(run.phase === 'tool' && run.lastTool !== undefined ? { tool: run.lastTool } : {}),
324
+ ...(run.phase === 'tool' && run.activityArgs !== undefined ? { args: run.activityArgs } : {}),
325
+ ...(run.activity !== undefined ? { text: run.activity } : {}),
326
+ calls: run.toolCalls,
327
+ });
287
328
  if (run.filesTouched.length > 0)
288
329
  this.touchedFiles.set(run.label, [...run.filesTouched]);
289
330
  const phase = run.phase;
@@ -306,6 +347,7 @@ export class EngineCore {
306
347
  }
307
348
  clearActivity() {
308
349
  this.activity.clear();
350
+ this.activityView.clear();
309
351
  }
310
352
  // -------------------------------------------------------------------------
311
353
  // Stage abort
@@ -414,7 +456,7 @@ export class EngineCore {
414
456
  health: this.health(),
415
457
  recent: this.recent(),
416
458
  usage: { ...run.usage },
417
- budgetTokens: run.limits.budgetTokens,
459
+ budgetTokens: this.config().budgetTokens,
418
460
  alerts: this.alerts(run),
419
461
  reworkNote: reworkWp
420
462
  ? `rework ${reworkWp.reworkCount}/${run.limits.maxRework} (${reworkWp.id})`
@@ -433,9 +475,12 @@ export class EngineCore {
433
475
  state: r.status === 'eliminated' ? 'eliminated' : (this.agentStates.get(r.id) ?? 'idle'),
434
476
  wpId: this.wpOf(r.id),
435
477
  activity: r.status === 'eliminated' ? '' : (this.activity.get(r.id) ?? ''),
478
+ ...(r.status === 'eliminated' ? {} : activityFields(this.activityView.get(r.id))),
436
479
  confirmed: r.confirmed,
437
480
  provisional: r.provisional,
438
- label: labelFor(r.confirmed),
481
+ // The standings row already decided: an eliminated agent is KILLED even when a tail
482
+ // elimination left `confirmed` in the DANGER band.
483
+ label: r.label,
439
484
  lastDelta: this.lastDelta.get(r.id) ?? null,
440
485
  replacedBy: r.replacedBy,
441
486
  }));
@@ -446,6 +491,7 @@ export class EngineCore {
446
491
  state: this.agentStates.get(INSPECTOR_ID) ?? 'idle',
447
492
  wpId: null,
448
493
  activity: this.activity.get(INSPECTOR_ID) ?? '',
494
+ ...activityFields(this.activityView.get(INSPECTOR_ID)),
449
495
  confirmed: null,
450
496
  provisional: 0,
451
497
  label: 'NOT_SCORED',
@@ -496,12 +542,13 @@ export class EngineCore {
496
542
  out.push(`${open.length} escalation(s) need the user`);
497
543
  if (run.status === 'paused')
498
544
  out.push('run paused - gov_run resume');
499
- const budget = run.limits.budgetTokens;
500
- if (budget > 0) {
501
- const used = run.usage.inputTokens + run.usage.outputTokens;
502
- if (used >= budget * GOV_LIMITS.budgetWarnFraction)
503
- out.push('team token budget nearly used');
504
- }
545
+ // The LIVE config, not the value frozen at run start: `/gov budget` must show at once, and
546
+ // it is usually typed precisely because the run is escalated on an exhausted budget.
547
+ const level = budgetLevel(run.usage, this.config().budgetTokens);
548
+ if (level === 'exhausted')
549
+ out.push('team token budget exhausted - new stages blocked');
550
+ else if (level === 'warning')
551
+ out.push('team token budget nearly used');
505
552
  const health = this.health();
506
553
  if (health !== null && health < GOV_LIMITS.healthWarnThreshold)
507
554
  out.push('team health low');
@@ -47,6 +47,7 @@ export declare class GovernanceEngine implements GovernanceEngineApi {
47
47
  * the run resumable (D-12), exactly as an Esc does.
48
48
  */
49
49
  dispose(): void;
50
+ rejectInvalid(identity: Identity, input: unknown, text: string): ToolText;
50
51
  submitWork(identity: Identity, input: unknown): ToolText;
51
52
  submitReview(identity: Identity, input: unknown): ToolText;
52
53
  submitTest(identity: Identity, input: unknown): ToolText;
@@ -18,7 +18,7 @@
18
18
  import { getLogger } from '../../logging/logger.js';
19
19
  import { scanPaths, formatScanReport } from '../tools/scan-incomplete.js';
20
20
  import { GOV_LIMITS } from '@aragon-agent/tui/model/governance/limits';
21
- import { findingsForFile } from './visibility.js';
21
+ import { classifyViewTarget, findingsForFile, VIEW_KINDS } from './visibility.js';
22
22
  import { accessFor, decideView, formatPage, formatReadableList, listReadable, pageText, } from './visibility.js';
23
23
  import { parseArtifactId } from '../store/artifacts.js';
24
24
  import { EngineCore } from './engine-core.js';
@@ -28,7 +28,7 @@ import { abandonRun, closeRun, resolveEscalation, resumeRun, startRun, statusTex
28
28
  import { cancelPause, requestPause } from './pause.js';
29
29
  import { renderStandings } from './report.js';
30
30
  import { runStage } from './stage-runner.js';
31
- import { handleSubmitReview, handleSubmitTest, handleSubmitWork } from './submissions.js';
31
+ import { handleRejectInvalid, handleSubmitReview, handleSubmitTest, handleSubmitWork, } from './submissions.js';
32
32
  import { isRecord } from '../tools/normalize-util.js';
33
33
  const FILE_LIKE = /[\w./\\-]+\.[A-Za-z0-9]{1,8}/g;
34
34
  function internalError(where, error) {
@@ -153,6 +153,9 @@ export class GovernanceEngine {
153
153
  // ---------------------------------------------------------------------------
154
154
  // Child entry points (synchronous: a tool call cannot wait on the disk)
155
155
  // ---------------------------------------------------------------------------
156
+ rejectInvalid(identity, input, text) {
157
+ return this.child('reject_invalid', () => handleRejectInvalid(this.core, identity, input, text));
158
+ }
156
159
  submitWork(identity, input) {
157
160
  return this.child('gov_submit_work', () => handleSubmitWork(this.core, identity, input));
158
161
  }
@@ -238,14 +241,10 @@ export class GovernanceEngine {
238
241
  const request = isRecord(input) ? input : {};
239
242
  const target = typeof request.target === 'string' ? request.target : '';
240
243
  const reason = typeof request.reason === 'string' ? request.reason : '';
241
- const lower = target.toLowerCase();
242
- const kind = lower.includes('test')
243
- ? 'test'
244
- : lower.includes('work') || lower.includes('dev')
245
- ? 'work'
246
- : lower.includes('inspector')
247
- ? 'inspector'
248
- : 'review';
244
+ // An explicit `kind` is authoritative; the free text is only a fallback for callers that
245
+ // omit it (and is classified by whole words - see `classifyViewTarget`).
246
+ const explicit = VIEW_KINDS.find((k) => k === request.kind);
247
+ const kind = explicit ?? classifyViewTarget(target);
249
248
  const file = target.match(FILE_LIKE)?.[0];
250
249
  const used = this.core.viewRequests.get(identity.id) ?? 0;
251
250
  const decision = decideView({
@@ -204,10 +204,11 @@ function rejectionRecords(core, wps) {
204
204
  reviews.forEach((review, index) => {
205
205
  if (review.verdict !== 'NEEDS_REWORK')
206
206
  return;
207
+ // Finding ids restart at F1 in every review, so a withdrawal can only be matched against
208
+ // the review it answers: the NEXT one (an appeal targets the latest review, and the
209
+ // reply must come in the review after it).
207
210
  const ids = new Set(review.findings.map((f) => f.id));
208
- const withdrawn = reviews
209
- .slice(index + 1)
210
- .some((later) => later.appealResponses.some((a) => a.decision === 'withdraw' && ids.has(a.findingId)));
211
+ const withdrawn = reviews[index + 1]?.appealResponses.some((a) => a.decision === 'withdraw' && ids.has(a.findingId)) ?? false;
211
212
  out.push({
212
213
  id: review.id,
213
214
  wpId: wp.id,
@@ -15,7 +15,7 @@ import { formatDispatchEstimate, formatDispatchPlanForAgent } from '../copy.js';
15
15
  import { rosterIds, rosterSizes } from '../roles.js';
16
16
  import { createLedger } from '../rules/ledger-state.js';
17
17
  import { formatNotAccepted, isRecord, Issues } from '../tools/normalize-util.js';
18
- import { newRunUsage, shouldStopNewStages } from './budget.js';
18
+ import { newRunUsage, shouldStopNewStages, totalTokens } from './budget.js';
19
19
  import { charterCard, escalationCard, finalCard } from './cards.js';
20
20
  import { composeDigest, refusal } from './digest.js';
21
21
  import { estimateDispatches, estimateForRun } from './estimate.js';
@@ -259,6 +259,7 @@ function adoptRun(core, run) {
259
259
  core.submissionCache.clear();
260
260
  core.phaseFlags.clear();
261
261
  core.viewRequests.clear();
262
+ core.resetRunScratch();
262
263
  core.resetStageScratch();
263
264
  core.attachTeam();
264
265
  }
@@ -355,6 +356,7 @@ async function loadForResume(core, runId) {
355
356
  core.seq = Math.max(loaded.tailSeq, loaded.run.seq);
356
357
  core.phaseFlags.clear();
357
358
  core.viewRequests.clear();
359
+ core.resetRunScratch();
358
360
  core.resetStageScratch();
359
361
  await cacheSubmissions(core, runId);
360
362
  if (loaded.problems.length > 0) {
@@ -591,7 +593,7 @@ export function openBudgetEscalation(core) {
591
593
  id: nextEscalationId(run),
592
594
  level: 'L3',
593
595
  kind: 'dispute',
594
- topic: `${BUDGET_TOPIC_PREFIX} is exhausted (${run.usage.inputTokens + run.usage.outputTokens} ` +
596
+ topic: `${BUDGET_TOPIC_PREFIX} is exhausted (${totalTokens(run.usage)} ` +
595
597
  `of ${core.config().budgetTokens}). Raise the budget (/gov budget <n>) or abandon the run.`,
596
598
  positions: [],
597
599
  status: 'open',
@@ -16,6 +16,7 @@
16
16
  * tail (`NEXT:`) are the two parts the reader cannot do without.
17
17
  */
18
18
  import { GOV_LIMITS } from '@aragon-agent/tui/model/governance/limits';
19
+ import { formatTokens } from './budget.js';
19
20
  const WP_STATUS_WORD = {
20
21
  pending: 'pending',
21
22
  dev_running: 'developing',
@@ -29,6 +30,11 @@ const WP_STATUS_WORD = {
29
30
  blocked: 'BLOCKED',
30
31
  dropped: 'dropped',
31
32
  };
33
+ /** "cache N, " when the run spent prompt-cache tokens (they count toward the budget). */
34
+ function cacheClause(usage) {
35
+ const cache = (usage.cacheReadTokens ?? 0) + (usage.cacheWriteTokens ?? 0);
36
+ return cache > 0 ? `cache ${formatTokens(cache)}, ` : '';
37
+ }
32
38
  export function wpStatusWord(status) {
33
39
  return WP_STATUS_WORD[status];
34
40
  }
@@ -215,6 +221,6 @@ export function buildFinalReport(input) {
215
221
  .join(', ')}`);
216
222
  }
217
223
  lines.push('', renderStandings(input.standings, input.health), '');
218
- lines.push(`Team tokens: input ${run.usage.inputTokens}, output ${run.usage.outputTokens}, cost ${run.usage.costUsd === null ? 'pricing unknown' : `$${run.usage.costUsd.toFixed(4)}`}; wall ${Math.round(input.wallMs / 1000)}s`);
224
+ 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`);
219
225
  return clipBytes(`${lines.join('\n')}\n`, GOV_LIMITS.finalReportMaxBytes);
220
226
  }
@@ -16,6 +16,7 @@
16
16
  * changed on every fraction would append an index row per booking instead of per stage.
17
17
  */
18
18
  import { teamHealth } from '../rules/ledger-state.js';
19
+ import { totalTokens } from './budget.js';
19
20
  /** The phase to show: the first not-integrated one, else the last (mirrors the panel). */
20
21
  function displayPhase(run) {
21
22
  if (run.phases.length === 0)
@@ -34,7 +35,7 @@ export function buildRunDigest(run, ledger) {
34
35
  phaseCount: run.phases.length,
35
36
  agents: records.length,
36
37
  health: health === null ? null : Math.round(health),
37
- tokens: run.usage.inputTokens + run.usage.outputTokens,
38
+ tokens: totalTokens(run.usage),
38
39
  costUsd: finiteOrNull(run.usage.costUsd),
39
40
  dispatches: run.dispatches,
40
41
  eliminations: records.filter((a) => a.status === 'eliminated').length,
@@ -435,7 +435,7 @@ async function dispatchGroups(core, run, ctx, groups, options) {
435
435
  for (const g of groups)
436
436
  core.setAgentState(g.identity, 'queued');
437
437
  const outcome = await core.deps.withPausedWatchdog(() => core.deps.runtime.dispatch(specs, specs.length, options.controller.signal));
438
- run.usage = accumulateUsage(run.usage, outcome, core.deps.modelCost?.());
438
+ run.usage = accumulateUsage(run.usage, outcome, core.deps.modelCost?.(), core.deps.fastModelCost?.());
439
439
  noteOwnership(core, run, ctx, outcome);
440
440
  noteChildFailures(core, outcome);
441
441
  return outcome;
@@ -20,6 +20,8 @@
20
20
  */
21
21
  import type { Identity } from '@aragon-agent/tui/model/governance/types';
22
22
  import type { EngineCore } from './engine-core.js';
23
+ /** Count a tool-layer schema refusal against the (identity, WP) pair and answer with `text`. */
24
+ export declare function handleRejectInvalid(core: EngineCore, identity: Identity, input: unknown, text: string): string;
23
25
  export declare function handleSubmitWork(core: EngineCore, identity: Identity, input: unknown): string;
24
26
  export declare function handleSubmitReview(core: EngineCore, identity: Identity, input: unknown): string;
25
27
  export declare function handleSubmitTest(core: EngineCore, identity: Identity, input: unknown): string;
@@ -20,7 +20,7 @@
20
20
  */
21
21
  import { getLogger } from '../../logging/logger.js';
22
22
  import { GOV_LIMITS } from '@aragon-agent/tui/model/governance/limits';
23
- import { settleReview, settleTest, settleWork } from '../rules/settlement.js';
23
+ import { effectiveRejections, settleReview, settleTest, settleWork } from '../rules/settlement.js';
24
24
  import { detectOwnershipViolations } from '../rules/suspicion.js';
25
25
  import { formatNotAccepted } from '../tools/normalize-util.js';
26
26
  import { normalizeReviewSubmission, normalizeTestSubmission, normalizeWorkSubmission, } from '../tools/submit-normalizers.js';
@@ -160,15 +160,21 @@ function bookedFor(booked, agentId) {
160
160
  /** Apply a settlement's side effects that are common to all three kinds. */
161
161
  function applySettlement(core, wp, result, at) {
162
162
  const run = core.requireRun();
163
- const booked = applyEvents(core, result.events, { phase: wp.phase });
163
+ // REVERSALS FIRST: a reversal strikes the newest un-reversed entry of its code, and a
164
+ // review that withdraws an old finding while raising a new one books a NEW D5 in the same
165
+ // settlement - applied first, that new D5 would be the one struck instead of the appealed one.
166
+ // `booked` keeps the events-then-reversals order the digest lines are written in.
167
+ const reversed = [];
164
168
  for (const r of result.reversals) {
165
169
  const op = core.ledgerOp({
166
170
  op: 'reverse',
167
171
  request: { agentId: r.agentId, code: r.code, wpId: r.wpId, at, reason: r.reason },
168
172
  });
169
173
  core.noteBooked(op.booked);
170
- booked.push(...op.booked);
174
+ reversed.push(...op.booked);
171
175
  }
176
+ const booked = applyEvents(core, result.events, { phase: wp.phase });
177
+ booked.push(...reversed);
172
178
  for (const fp of result.newRejections) {
173
179
  if (!wp.rejections.includes(fp))
174
180
  wp.rejections.push(fp);
@@ -209,6 +215,8 @@ function checkOwnership(core, identity, wp) {
209
215
  }
210
216
  function finish(core, kind, identity, wpId) {
211
217
  core.stageSubmitted.add(wpId);
218
+ // A valid submission closes the correction window of this (identity, WP) pair.
219
+ core.validationFailures.delete(failureKey(identity, wpId));
212
220
  core.log('submission', identity.id, { kind, wpId });
213
221
  core.checkpoint();
214
222
  core.emit((snapshot) => ({ type: 'submission', snapshot, identity: identity.id, wpId, kind }));
@@ -246,6 +254,10 @@ function intake(core, identity, kind, input, normalized) {
246
254
  }
247
255
  return { value, ...admitted };
248
256
  }
257
+ /** Count a tool-layer schema refusal against the (identity, WP) pair and answer with `text`. */
258
+ export function handleRejectInvalid(core, identity, input, text) {
259
+ return guarded('reject_invalid', () => refuse(core, identity, rawWpId(input), text));
260
+ }
249
261
  function rawWpId(input) {
250
262
  if (input !== null && typeof input === 'object') {
251
263
  const v = input.wpId;
@@ -388,6 +400,13 @@ export function handleSubmitReview(core, identity, input) {
388
400
  persistArtifact(core, target, sub.id, sub, renderReviewMarkdown(sub));
389
401
  wp.submissions.review.push(sub.id);
390
402
  const booked = applySettlement(core, wp, result, at);
403
+ if (sub.appealResponses.some((a) => a.decision === 'withdraw')) {
404
+ // A withdrawn rejection is the reviewer's mistake: it must not keep arming D8.
405
+ wp.rejections = effectiveRejections([
406
+ ...submissionsOf(core, wp.id, 'review').filter((r) => r.id !== sub.id),
407
+ sub,
408
+ ]);
409
+ }
391
410
  let routed = 'to test';
392
411
  if (result.route?.to === 'dev')
393
412
  routed = openRework(core, run, wp);
@@ -46,6 +46,16 @@ export declare function listReadable(input: {
46
46
  ref: ArtifactRef;
47
47
  access: Access;
48
48
  }>;
49
+ /** The material kinds a `gov_view` target can name (the tool's `kind` enum). */
50
+ export declare const VIEW_KINDS: readonly ["review", "work", "test", "inspector"];
51
+ /**
52
+ * Free-text fallback for a `gov_view` target that carries no explicit `kind`. WHOLE WORDS only
53
+ * (`latest`, `contest`, `development` must not match `test` / `dev`), and review wins: it is
54
+ * the one kind that can ever be granted (a TEST asking for the findings of its own failing
55
+ * file), and that caller will write "test" in nearly every sentence. Unclassifiable text is
56
+ * `review`, the permissive reading.
57
+ */
58
+ export declare function classifyViewTarget(target: string): (typeof VIEW_KINDS)[number];
49
59
  export interface ViewTarget {
50
60
  kind: ArtifactKind;
51
61
  relation: Relation;
@@ -139,6 +139,34 @@ export function listReadable(input) {
139
139
  }
140
140
  return out;
141
141
  }
142
+ // ---------------------------------------------------------------------------
143
+ // gov_view: deterministic exception policy (D-9)
144
+ // ---------------------------------------------------------------------------
145
+ /** The material kinds a `gov_view` target can name (the tool's `kind` enum). */
146
+ export const VIEW_KINDS = ['review', 'work', 'test', 'inspector'];
147
+ const REVIEW_WORDS = /\b(?:reviews?|reviewers?|findings?)\b/;
148
+ const INSPECTOR_WORDS = /\binspector\b/;
149
+ const TEST_WORDS = /\b(?:tests?|testers?)\b/;
150
+ const WORK_WORDS = /\b(?:work|dev\d*|developers?)\b/;
151
+ /**
152
+ * Free-text fallback for a `gov_view` target that carries no explicit `kind`. WHOLE WORDS only
153
+ * (`latest`, `contest`, `development` must not match `test` / `dev`), and review wins: it is
154
+ * the one kind that can ever be granted (a TEST asking for the findings of its own failing
155
+ * file), and that caller will write "test" in nearly every sentence. Unclassifiable text is
156
+ * `review`, the permissive reading.
157
+ */
158
+ export function classifyViewTarget(target) {
159
+ const lower = target.toLowerCase();
160
+ if (REVIEW_WORDS.test(lower))
161
+ return 'review';
162
+ if (INSPECTOR_WORDS.test(lower))
163
+ return 'inspector';
164
+ if (TEST_WORDS.test(lower))
165
+ return 'test';
166
+ if (WORK_WORDS.test(lower))
167
+ return 'work';
168
+ return 'review';
169
+ }
142
170
  function normalizeFile(file) {
143
171
  return file.trim().replace(/\\/g, '/').replace(/^\.\//, '').toLowerCase();
144
172
  }
@@ -80,6 +80,13 @@ export declare function deriveRequiredChanges(findings: readonly ReviewFinding[]
80
80
  * D17 is appealable once; the booking carries that in its reason.
81
81
  */
82
82
  export declare function settleWork(ctx: SettlementContext, submission: WorkSubmission): SettlementResult;
83
+ /**
84
+ * The rejection fingerprints that still stand, recomputed from the review history (oldest
85
+ * first): every blocking finding of every NEEDS_REWORK review, except the ones the NEXT
86
+ * review withdrew on appeal. Recomputing (instead of deleting a withdrawn fingerprint from
87
+ * `wp.rejections`) keeps an earlier, still-valid rejection of the same problem alive. Pure.
88
+ */
89
+ export declare function effectiveRejections(reviews: readonly ReviewSubmission[]): string[];
83
90
  /**
84
91
  * A REVIEW submission. PASS -> D1 (+15 P) -> test; PASS_WITH_FIXES -> D2 (+5 P) -> test;
85
92
  * NEEDS_REWORK -> D5 (-20) -> dev, plus D8 (-30) when a blocking finding repeats an
@@ -132,6 +132,30 @@ function appealEffects(ctx, sub, out) {
132
132
  }
133
133
  out.notes.push(`Appeal succeeded for ${ids}: R5 booked and the earlier D5 struck.`);
134
134
  }
135
+ /**
136
+ * The rejection fingerprints that still stand, recomputed from the review history (oldest
137
+ * first): every blocking finding of every NEEDS_REWORK review, except the ones the NEXT
138
+ * review withdrew on appeal. Recomputing (instead of deleting a withdrawn fingerprint from
139
+ * `wp.rejections`) keeps an earlier, still-valid rejection of the same problem alive. Pure.
140
+ */
141
+ export function effectiveRejections(reviews) {
142
+ const out = [];
143
+ reviews.forEach((review, index) => {
144
+ if (review.verdict !== 'NEEDS_REWORK')
145
+ return;
146
+ const withdrawn = new Set((reviews[index + 1]?.appealResponses ?? [])
147
+ .filter((a) => a.decision === 'withdraw')
148
+ .map((a) => a.findingId));
149
+ for (const finding of blockingFindings(review.findings)) {
150
+ if (withdrawn.has(finding.id))
151
+ continue;
152
+ const fp = fingerprintFinding(finding);
153
+ if (!out.includes(fp))
154
+ out.push(fp);
155
+ }
156
+ });
157
+ return out;
158
+ }
135
159
  function reworkOutcome(ctx, sub, out) {
136
160
  const developer = ctx.wp.assignee;
137
161
  const required = sub.requiredChanges.length > 0 ? sub.requiredChanges : deriveRequiredChanges(sub.findings);
@@ -26,6 +26,8 @@ export interface ReadRequest {
26
26
  export interface ViewRequest {
27
27
  target: string;
28
28
  reason: string;
29
+ /** Which material is meant; omitted = classified from the target text. */
30
+ kind?: 'review' | 'work' | 'test' | 'inspector';
29
31
  }
30
32
  /**
31
33
  * Validate a `gov_read` request. Pure.