@aragon-agent/cli 0.6.48 → 0.6.49

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 (70) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/dist/agent/controller.d.ts +21 -0
  3. package/dist/agent/controller.js +35 -8
  4. package/dist/agent/governance-wiring.d.ts +2 -0
  5. package/dist/agent/governance-wiring.js +4 -0
  6. package/dist/app/App.d.ts +2 -4
  7. package/dist/app/App.js +207 -511
  8. package/dist/cli.js +2 -150
  9. package/dist/commands/catalog.d.ts +17 -0
  10. package/dist/commands/catalog.js +52 -0
  11. package/dist/commands/create-registry.d.ts +13 -0
  12. package/dist/commands/create-registry.js +19 -0
  13. package/dist/commands/governance-command.js +5 -1
  14. package/dist/commands/skills.js +18 -67
  15. package/dist/config/env.d.ts +2 -0
  16. package/dist/config/env.js +1 -1
  17. package/dist/fast/review-call.d.ts +6 -0
  18. package/dist/fast/review-call.js +10 -0
  19. package/dist/governance/engine/budget.d.ts +18 -6
  20. package/dist/governance/engine/budget.js +61 -19
  21. package/dist/governance/engine/engine-core.d.ts +8 -0
  22. package/dist/governance/engine/engine-core.js +29 -9
  23. package/dist/governance/engine/engine.d.ts +1 -0
  24. package/dist/governance/engine/engine.js +9 -10
  25. package/dist/governance/engine/inspector.js +4 -3
  26. package/dist/governance/engine/lifecycle.js +4 -2
  27. package/dist/governance/engine/report.js +7 -1
  28. package/dist/governance/engine/run-digest.js +2 -1
  29. package/dist/governance/engine/stage-runner.js +1 -1
  30. package/dist/governance/engine/submissions.d.ts +2 -0
  31. package/dist/governance/engine/submissions.js +22 -3
  32. package/dist/governance/engine/visibility.d.ts +10 -0
  33. package/dist/governance/engine/visibility.js +28 -0
  34. package/dist/governance/rules/settlement.d.ts +7 -0
  35. package/dist/governance/rules/settlement.js +24 -0
  36. package/dist/governance/tools/shared-tools.d.ts +2 -0
  37. package/dist/governance/tools/shared-tools.js +15 -1
  38. package/dist/governance/tools/submit-tools.js +14 -7
  39. package/dist/host/commands.d.ts +18 -0
  40. package/dist/host/commands.js +30 -0
  41. package/dist/host/controller-factory.d.ts +109 -0
  42. package/dist/host/controller-factory.js +159 -0
  43. package/dist/host/controller-feed.d.ts +122 -0
  44. package/dist/host/controller-feed.js +356 -0
  45. package/dist/host/index-build.d.ts +23 -0
  46. package/dist/host/index-build.js +35 -0
  47. package/dist/host/index.d.ts +21 -0
  48. package/dist/host/index.js +21 -0
  49. package/dist/host/interaction.d.ts +58 -0
  50. package/dist/host/interaction.js +165 -0
  51. package/dist/host/logging.d.ts +7 -0
  52. package/dist/host/logging.js +7 -0
  53. package/dist/host/prompts.d.ts +10 -0
  54. package/dist/host/prompts.js +9 -0
  55. package/dist/host/sessions.d.ts +87 -0
  56. package/dist/host/sessions.js +234 -0
  57. package/dist/host/settings.d.ts +104 -0
  58. package/dist/host/settings.js +235 -0
  59. package/dist/host/skills.d.ts +19 -0
  60. package/dist/host/skills.js +38 -0
  61. package/dist/skills/command-names.d.ts +19 -0
  62. package/dist/skills/command-names.js +28 -0
  63. package/dist/skills/invoke.d.ts +38 -0
  64. package/dist/skills/invoke.js +65 -0
  65. package/dist/team/overseer.d.ts +25 -1
  66. package/dist/team/overseer.js +38 -1
  67. package/dist/team/runtime.d.ts +2 -0
  68. package/dist/team/runtime.js +10 -7
  69. package/dist/team/subagent.js +2 -4
  70. 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. */
@@ -175,6 +177,12 @@ export declare class EngineCore {
175
177
  /** Append ledger lines for a digest (call after `ledgerOp`). */
176
178
  noteBooked(booked: readonly BookedEntry[]): void;
177
179
  resetStageScratch(): void;
180
+ /**
181
+ * Everything a run leaves behind that is NOT persisted state: roster chips, agent states,
182
+ * the activity line and the gov_view log. A new or resumed run starts from a clean board
183
+ * instead of inheriting the previous run's `+5` chips and "submitted" markers.
184
+ */
185
+ resetRunScratch(): void;
178
186
  private entriesAt;
179
187
  private noteDelta;
180
188
  standingRows(): StandingRow[];
@@ -20,7 +20,8 @@
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';
@@ -230,6 +231,22 @@ export class EngineCore {
230
231
  this.inspectorOutcome = null;
231
232
  this.stageEndedEmitted = false;
232
233
  this.touchedFiles.clear();
234
+ // The 3-strikes rule is per STAGE (spec 8.4): a lifetime counter would leave a
235
+ // (identity, WP) pair permanently "not submitted" after three refusals spread over a
236
+ // whole session. A stage-internal auto-redispatch does not pass through here.
237
+ this.validationFailures.clear();
238
+ }
239
+ /**
240
+ * Everything a run leaves behind that is NOT persisted state: roster chips, agent states,
241
+ * the activity line and the gov_view log. A new or resumed run starts from a clean board
242
+ * instead of inheriting the previous run's `+5` chips and "submitted" markers.
243
+ */
244
+ resetRunScratch() {
245
+ this.agentStates.clear();
246
+ this.activity.clear();
247
+ this.lastDelta.clear();
248
+ this.viewLog.clear();
249
+ this.validationFailures.clear();
233
250
  }
234
251
  entriesAt(seq) {
235
252
  const out = [];
@@ -414,7 +431,7 @@ export class EngineCore {
414
431
  health: this.health(),
415
432
  recent: this.recent(),
416
433
  usage: { ...run.usage },
417
- budgetTokens: run.limits.budgetTokens,
434
+ budgetTokens: this.config().budgetTokens,
418
435
  alerts: this.alerts(run),
419
436
  reworkNote: reworkWp
420
437
  ? `rework ${reworkWp.reworkCount}/${run.limits.maxRework} (${reworkWp.id})`
@@ -435,7 +452,9 @@ export class EngineCore {
435
452
  activity: r.status === 'eliminated' ? '' : (this.activity.get(r.id) ?? ''),
436
453
  confirmed: r.confirmed,
437
454
  provisional: r.provisional,
438
- label: labelFor(r.confirmed),
455
+ // The standings row already decided: an eliminated agent is KILLED even when a tail
456
+ // elimination left `confirmed` in the DANGER band.
457
+ label: r.label,
439
458
  lastDelta: this.lastDelta.get(r.id) ?? null,
440
459
  replacedBy: r.replacedBy,
441
460
  }));
@@ -496,12 +515,13 @@ export class EngineCore {
496
515
  out.push(`${open.length} escalation(s) need the user`);
497
516
  if (run.status === 'paused')
498
517
  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
- }
518
+ // The LIVE config, not the value frozen at run start: `/gov budget` must show at once, and
519
+ // it is usually typed precisely because the run is escalated on an exhausted budget.
520
+ const level = budgetLevel(run.usage, this.config().budgetTokens);
521
+ if (level === 'exhausted')
522
+ out.push('team token budget exhausted - new stages blocked');
523
+ else if (level === 'warning')
524
+ out.push('team token budget nearly used');
505
525
  const health = this.health();
506
526
  if (health !== null && health < GOV_LIMITS.healthWarnThreshold)
507
527
  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.
@@ -59,7 +59,16 @@ export function normalizeViewRequest(raw) {
59
59
  issues.fail(`reason must explain why you need it, at least ${GOV_LIMITS.viewReasonMinChars} ` +
60
60
  `characters (got ${reason.length}).`);
61
61
  }
62
- return issues.result({ target, reason });
62
+ const kind = issues.oneOf(args.kind, 'kind', ['review', 'work', 'test', 'inspector'], {
63
+ aliases: {
64
+ findings: 'review',
65
+ reviews: 'review',
66
+ tests: 'test',
67
+ dev: 'work',
68
+ developer: 'work',
69
+ },
70
+ });
71
+ return issues.result({ target, reason, ...(kind ? { kind } : {}) });
63
72
  }
64
73
  function runRequest(tool, normalized, forward) {
65
74
  if (!normalized.ok)
@@ -114,6 +123,11 @@ export function makeViewTool(engine, identity) {
114
123
  type: 'object',
115
124
  properties: {
116
125
  target: { type: 'string', description: 'What you want to see.' },
126
+ kind: {
127
+ type: 'string',
128
+ description: 'Which material the target is: review | work | test | inspector. Default review ' +
129
+ '(the review findings for a file).',
130
+ },
117
131
  reason: { type: 'string', description: 'Why you need it.' },
118
132
  },
119
133
  required: ['target', 'reason'],