@aragon-agent/cli 0.6.56 → 0.6.58

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 (97) hide show
  1. package/CHANGELOG.md +94 -0
  2. package/README.md +159 -3
  3. package/dist/agent/controller.d.ts +112 -1
  4. package/dist/agent/controller.js +350 -7
  5. package/dist/agent/project-guidance-prompt.js +97 -97
  6. package/dist/agent/redteam-prompt.d.ts +29 -11
  7. package/dist/agent/redteam-prompt.js +118 -103
  8. package/dist/agent/redteam-wiring.d.ts +117 -2
  9. package/dist/agent/redteam-wiring.js +204 -1
  10. package/dist/agent/team-notices.d.ts +68 -0
  11. package/dist/agent/team-notices.js +82 -0
  12. package/dist/app/App.js +208 -5
  13. package/dist/app/use-redteam-mode.d.ts +1 -1
  14. package/dist/app/use-redteam-mode.js +14 -1
  15. package/dist/cli.js +13 -0
  16. package/dist/commands/catalog.js +6 -2
  17. package/dist/commands/redteam-command.d.ts +14 -8
  18. package/dist/commands/redteam-command.js +243 -12
  19. package/dist/commands/team-command.js +93 -2
  20. package/dist/config/app-paths.d.ts +19 -0
  21. package/dist/config/app-paths.js +23 -0
  22. package/dist/config/load.d.ts +8 -0
  23. package/dist/gene/catalog-sync.js +37 -16
  24. package/dist/gene/curator/budget.js +1 -1
  25. package/dist/gene/curator/curator.d.ts +6 -0
  26. package/dist/gene/curator/curator.js +8 -0
  27. package/dist/gene/curator/recheck.js +2 -1
  28. package/dist/gene/curator/task-runner.js +4 -1
  29. package/dist/gene/curator/tool-support.js +16 -7
  30. package/dist/gene/curator/tools-verify.js +54 -1
  31. package/dist/gene/curator/tools-write.js +41 -1
  32. package/dist/gene/curator/validate/evidence-tokens.d.ts +7 -19
  33. package/dist/gene/curator/validate/evidence-tokens.js +174 -17
  34. package/dist/gene/curator/validate/knowledge.d.ts +22 -1
  35. package/dist/gene/curator/validate/knowledge.js +108 -25
  36. package/dist/gene/curator/validate/live-check.js +7 -1
  37. package/dist/gene/curator/validate/prompts.js +7 -3
  38. package/dist/gene/curator/validate/types.d.ts +6 -1
  39. package/dist/gene/learn/learn-call.d.ts +58 -5
  40. package/dist/gene/learn/learn-call.js +38 -30
  41. package/dist/gene/learn/learn-prompt.d.ts +18 -2
  42. package/dist/gene/learn/learn-prompt.js +29 -11
  43. package/dist/gene/learn/learner.d.ts +6 -0
  44. package/dist/gene/learn/learner.js +31 -9
  45. package/dist/gene/learn/proposal-build.js +2 -6
  46. package/dist/gene/wiring-models.js +4 -1
  47. package/dist/governance/engine/lifecycle.js +1 -1
  48. package/dist/governance/store/run-lock.d.ts +9 -2
  49. package/dist/governance/store/run-lock.js +91 -7
  50. package/dist/host/controller-factory.d.ts +13 -0
  51. package/dist/host/controller-factory.js +7 -0
  52. package/dist/host/index.d.ts +1 -0
  53. package/dist/host/index.js +1 -0
  54. package/dist/host/interaction.d.ts +19 -0
  55. package/dist/host/interaction.js +75 -0
  56. package/dist/host/team-control.d.ts +83 -0
  57. package/dist/host/team-control.js +55 -0
  58. package/dist/logging/install.d.ts +32 -1
  59. package/dist/logging/install.js +21 -0
  60. package/dist/proc/output-streams.d.ts +11 -0
  61. package/dist/proc/output-streams.js +11 -0
  62. package/dist/redteam/prompt-resolve.d.ts +61 -0
  63. package/dist/redteam/prompt-resolve.js +303 -0
  64. package/dist/redteam/prompt-store.d.ts +96 -0
  65. package/dist/redteam/prompt-store.js +156 -0
  66. package/dist/redteam/prompt-template.d.ts +22 -0
  67. package/dist/redteam/prompt-template.js +72 -0
  68. package/dist/team/bus.d.ts +18 -0
  69. package/dist/team/bus.js +70 -18
  70. package/dist/team/console-tools.d.ts +54 -0
  71. package/dist/team/console-tools.js +333 -0
  72. package/dist/team/console-view.d.ts +88 -0
  73. package/dist/team/console-view.js +173 -0
  74. package/dist/team/forced-mode.d.ts +61 -1
  75. package/dist/team/forced-mode.js +75 -0
  76. package/dist/team/normalize.d.ts +31 -0
  77. package/dist/team/normalize.js +49 -5
  78. package/dist/team/notices.d.ts +95 -0
  79. package/dist/team/notices.js +121 -0
  80. package/dist/team/pause-gate.d.ts +79 -0
  81. package/dist/team/pause-gate.js +127 -0
  82. package/dist/team/prompt.d.ts +25 -9
  83. package/dist/team/prompt.js +29 -29
  84. package/dist/team/report.js +33 -0
  85. package/dist/team/runtime.d.ts +270 -5
  86. package/dist/team/runtime.js +732 -64
  87. package/dist/team/settled.d.ts +5 -2
  88. package/dist/team/settled.js +12 -2
  89. package/dist/team/subagent.d.ts +7 -0
  90. package/dist/team/subagent.js +12 -1
  91. package/dist/team/task-tool.d.ts +39 -1
  92. package/dist/team/task-tool.js +75 -18
  93. package/dist/tools/bash-tool.d.ts +11 -8
  94. package/dist/tools/bash-tool.js +37 -9
  95. package/dist/tools/index.d.ts +2 -2
  96. package/dist/tools/index.js +30 -0
  97. package/package.json +3 -3
@@ -7,20 +7,28 @@
7
7
  * K2 source >= 1 evidence; every cited ref resolves; every path / symbol / error code /
8
8
  * number of the draft appears VERBATIM in the evidence texts that were
9
9
  * snapshotted at enqueue. The live re-check against the project tree is optional
10
- * and its absence is recorded, never a failure.
10
+ * and its absence is recorded, never a failure. A miss that OUR OWN clipping
11
+ * explains does not fail the candidate: it puts it on probation (RV-13), and the
12
+ * missing tokens are handed to the curator as repair instructions (RV-17).
11
13
  * K3 scope a temporary preference only in the task scope; a specific path or a project
12
14
  * name cannot live in the user scope; environment-bound claims carry applicability
13
15
  * K4 supported model: do the evidence texts support the draft? (skipped when a user said it)
16
+ * A "no" is RECORDED, not a veto (RC-4). Everything an agent publishes
17
+ * already starts on probation - visible, double-weighted, revoked after it misleads
18
+ * twice (`probation.ts`, `plan-content.ts`). Refusing here was a second, harsher
19
+ * risk model fighting the library's own; it also made every candidate whose
20
+ * evidence was thinner than its draft unpublishable for good.
14
21
  * K5 conflict neighbour relations (see `conflicts.ts`)
15
22
  * K6 trust all-untrusted evidence waits for a person (TH-1)
16
23
  *
17
24
  * Every function returns plain data. A failing detail names fields and counts, never text.
18
25
  */
19
26
  import { promises as nodeFs } from 'node:fs';
20
- import { preferenceHorizonFitsScope } from '@aragon-agent/tui/model/gene/validate';
27
+ import { preferenceHorizonFitsScope, normalizedApplicabilityOf } from '@aragon-agent/tui/model/gene/validate';
21
28
  import { runConflictCheck } from '../conflicts.js';
29
+ import { LEARN_UNVERIFIED_HEADING } from '../../learn/learn-prompt.js';
22
30
  import { addUsage, failCheck, okCheck, skippedCheck, splitIssues, staticCheck, trustCheck, } from './common.js';
23
- import { extractVerbatimTokens, findUnsupportedTokens, summarizeMissing } from './evidence-tokens.js';
31
+ import { extractVerbatimTokens, findUnsupportedTokens, summarizeMissing, } from './evidence-tokens.js';
24
32
  import { liveCheckEvidence } from './live-check.js';
25
33
  import { askModel, buildSupportPrompt, parseSupportAnswer } from './prompts.js';
26
34
  function payloadOf(content) {
@@ -54,9 +62,45 @@ export async function resolveEvidence(ports, scope, geneId, content, snapshot) {
54
62
  }
55
63
  return { corpus: [...byRef.values()], unresolved };
56
64
  }
57
- function draftedTexts(content) {
65
+ /**
66
+ * The block an author writes to say what it could NOT verify (RC-2). One heading, matched
67
+ * from its first words, opened at the start of a line and closed by the next markdown heading.
68
+ *
69
+ * WHY THIS EXISTS. K2 reads a draft LEXICALLY: it cannot tell an assertion from the sentence
70
+ * "these names appear in no evidence ref, so none is recommended here", so it scored a draft
71
+ * HONESTY as fabrication - 10 of the 25 measured misses on real candidates came from such a
72
+ * paragraph. A candidate must not have to claim it verified something it did not.
73
+ *
74
+ * WHY IT IS NOT A HOLE. The block is only dropped when the rest of the draft still says something
75
+ * checkable: a draft that puts EVERYTHING under the heading keeps its full text and is checked
76
+ * exactly as before. And K1's injection screen still reads the whole body, heading included, so
77
+ * the block cannot carry an instruction either.
78
+ */
79
+ const UNVERIFIED_HEADING_RE = new RegExp(`^\\s*(?:#{1,6}\\s*)?${LEARN_UNVERIFIED_HEADING}\\b`, 'i');
80
+ const NEXT_HEADING_RE = /^\s*#{1,6}\s+\S/;
81
+ function stripUnverified(text) {
82
+ const kept = [];
83
+ let inside = false;
84
+ for (const line of text.split(/\r?\n/)) {
85
+ if (UNVERIFIED_HEADING_RE.test(line)) {
86
+ inside = true;
87
+ continue;
88
+ }
89
+ if (inside && NEXT_HEADING_RE.test(line))
90
+ inside = false;
91
+ if (!inside)
92
+ kept.push(line);
93
+ }
94
+ const out = kept.join('\n');
95
+ return out.trim().length === 0 ? text : out;
96
+ }
97
+ /**
98
+ * The texts K2 actually checks: the body and every claim, with the author's own "what I could not
99
+ * verify" block removed. Exported so a test can pin the check's surface without restating the rule.
100
+ */
101
+ export function draftedTexts(content) {
58
102
  const claims = (payloadOf(content).claims ?? []).map((c) => String(c?.text ?? ''));
59
- return [String(content.body ?? ''), ...claims];
103
+ return [String(content.body ?? ''), ...claims].map(stripUnverified);
60
104
  }
61
105
  async function rootIsDirectory(root) {
62
106
  const stat = await nodeFs.stat(root).catch(() => null);
@@ -79,26 +123,53 @@ async function liveCheck(ports, scope, corpus, at) {
79
123
  const detail = result.status === 'passed' ? 'passed' : `failed: ${result.failed} of ${result.checked}`;
80
124
  return { check: okCheck('live_check', at, detail), failed: result.failed };
81
125
  }
126
+ /**
127
+ * The CURATOR-ONLY repair line for a failing K2 (RV-17, B3): the missing tokens, verbatim, so the
128
+ * model can cite them or take them out of its draft in the same task.
129
+ *
130
+ * WHY IT IS NOT ON THE OUTCOME. `CandidateOutcome` is logged and stored, and a stored detail may
131
+ * never echo gene or evidence text (I-19) - the `poison-untrusted` case fails the moment a token
132
+ * leaves through it. This string is built at the tool boundary instead, from the model's own draft
133
+ * and its own evidence, and exists only in that one tool answer.
134
+ */
135
+ export function repairLines(content, corpus) {
136
+ const report = findUnsupportedTokens(draftedTexts(content), corpus);
137
+ if (report.missing.length === 0)
138
+ return [];
139
+ const tokens = report.missing.map((t) => `${t.kind} ${t.text}`).join(', ');
140
+ return [`these tokens are not in the evidence: ${tokens} - quote them verbatim or remove them`];
141
+ }
142
+ function evidenceProblems(unresolved, report) {
143
+ const problems = [];
144
+ if (unresolved > 0)
145
+ problems.push(`${unresolved} cited ref(s) unresolved`);
146
+ if (report.missing.length > 0)
147
+ problems.push(`not in evidence: ${summarizeMissing(report.missing)}`);
148
+ return problems;
149
+ }
82
150
  /** K2, reusable by `recheck` (10.9). Returns the K2 check and, when run, the live_check record. */
83
151
  export async function checkSource(input) {
84
152
  const at = input.ports.now();
85
153
  const { corpus, unresolved } = input.resolved ??
86
154
  (await resolveEvidence(input.ports, input.scope, input.geneId, input.content, input.evidence));
87
- if (corpus.length === 0)
88
- return [failCheck('KNOWLEDGE_EVIDENCE_UNRESOLVED', at, 'K2 the proposal carries no evidence')];
89
- const problems = [];
90
- if (unresolved > 0)
91
- problems.push(`${unresolved} cited ref(s) unresolved`);
155
+ if (corpus.length === 0) {
156
+ return {
157
+ checks: [failCheck('KNOWLEDGE_EVIDENCE_UNRESOLVED', at, 'K2 the proposal carries no evidence')],
158
+ clipped: [],
159
+ };
160
+ }
92
161
  const report = findUnsupportedTokens(draftedTexts(input.content), corpus.map((e) => e.text).join('\n'));
93
- if (report.missing.length > 0)
94
- problems.push(`not in evidence: ${summarizeMissing(report.missing)}`);
162
+ const problems = evidenceProblems(unresolved, report);
95
163
  const live = await liveCheck(input.ports, input.scope, corpus, at);
96
164
  if (live.failed > 0)
97
165
  problems.push(`${live.failed} evidence item(s) no longer match the project`);
98
166
  const main = problems.length > 0
99
167
  ? failCheck('KNOWLEDGE_EVIDENCE_UNRESOLVED', at, `K2 ${problems.join('; ')}`)
100
168
  : okCheck('K2', at, `${report.checked} specific(s) found in evidence`);
101
- return live.check === undefined ? [main] : [main, live.check];
169
+ return {
170
+ checks: live.check === undefined ? [main] : [main, live.check],
171
+ clipped: report.clipped,
172
+ };
102
173
  }
103
174
  // ---------------------------------------------------------------------------
104
175
  // K3 - scope fit
@@ -123,7 +194,9 @@ function mentionsProject(texts, labels) {
123
194
  });
124
195
  }
125
196
  function applicabilityEmpty(content) {
126
- const a = content.applicability ?? {};
197
+ // The SAME normalisation the write path applied (RC-2, RV-16): a legacy or imported block that
198
+ // spells `platform` is an environment filter, not an absent one.
199
+ const a = normalizedApplicabilityOf(content);
127
200
  return !a.os?.length && !a.envStamp && !a.projectKinds?.length && !a.fileGlobs?.length && !a.requiresTools?.length;
128
201
  }
129
202
  function scopeProblems(ctx) {
@@ -152,26 +225,26 @@ function checkScope(ctx, at) {
152
225
  out.push(failCheck('KNOWLEDGE_SCOPE_MISFIT', at, `K3 ${problems.join('; ')}`));
153
226
  return out.length > 0 ? out : [okCheck('K3', at)];
154
227
  }
155
- // ---------------------------------------------------------------------------
156
- // K4 - supported by the evidence
157
- // ---------------------------------------------------------------------------
158
228
  async function checkSupported(ctx, corpus, usage) {
159
229
  const at = ctx.ports.now();
160
230
  if (corpus.some((e) => e.kind === 'user_statement' && e.trust !== 'untrusted')) {
161
- return okCheck('K4', at, 'a user statement is sufficient');
231
+ return { check: okCheck('K4', at, 'a user statement is sufficient'), forceProbation: false };
162
232
  }
163
233
  const prompt = buildSupportPrompt(draftedTexts(ctx.content).join('\n'), corpus.map((e) => e.text));
164
234
  const answer = await askModel(ctx.ports, prompt.system, prompt.user);
165
235
  if (!answer.ok)
166
- return skippedCheck('K4', at, answer.reason);
236
+ return { check: skippedCheck('K4', at, answer.reason), forceProbation: false };
167
237
  addUsage(usage, answer.usage);
168
238
  const supported = parseSupportAnswer(answer.json);
239
+ // A model output we could not read is NOT a "no": it is recorded as skipped, never as support.
169
240
  if (supported === null)
170
- return skippedCheck('K4', at, 'bad_model_output');
241
+ return { check: skippedCheck('K4', at, 'bad_model_output'), forceProbation: false };
171
242
  const extras = { by: 'model', ...(answer.model ? { model: answer.model } : {}), durationMs: answer.durationMs };
172
- return supported
173
- ? okCheck('K4', at, undefined, extras)
174
- : failCheck('KNOWLEDGE_UNSUPPORTED', at, 'K4 the evidence does not support the draft', extras);
243
+ if (supported)
244
+ return { check: okCheck('K4', at, undefined, extras), forceProbation: false };
245
+ // The answer is kept verbatim in the version file, so a reviewer can still find every gene whose
246
+ // support was doubted. What it no longer does is outrank the library's own probation rules.
247
+ return { check: okCheck('K4', at, 'not supported by the evidence', extras), forceProbation: true };
175
248
  }
176
249
  // ---------------------------------------------------------------------------
177
250
  // Entry point
@@ -194,8 +267,16 @@ export async function validateKnowledge(ctx, report) {
194
267
  resolved,
195
268
  ...(ctx.geneId === undefined ? {} : { geneId: ctx.geneId }),
196
269
  });
197
- checks.push(...source, ...checkScope(ctx, at));
198
- checks.push(await checkSupported(ctx, resolved.corpus, usage));
270
+ checks.push(...source.checks);
271
+ if (source.clipped.length > 0) {
272
+ // The gene may still be right: the evidence we held was cut, not wrong. It goes in on probation
273
+ // (visible, double-weighted, revoked after it misleads twice) instead of dying here (RV-13).
274
+ const count = summarizeMissing(source.clipped);
275
+ checks.push(okCheck('KNOWLEDGE_EVIDENCE_CLIPPED', at, `K2 ${count} only missing because the evidence was clipped`));
276
+ }
277
+ checks.push(...checkScope(ctx, at));
278
+ const support = await checkSupported(ctx, resolved.corpus, usage);
279
+ checks.push(support.check);
199
280
  const conflict = await runConflictCheck(ctx.ports, {
200
281
  type: 'knowledge',
201
282
  scope: ctx.scope,
@@ -207,10 +288,12 @@ export async function validateKnowledge(ctx, report) {
207
288
  const trust = trustCheck(ctx.evidence, at);
208
289
  checks.push(trust.check);
209
290
  const needsHuman = trust.needsHuman ?? (conflict.decision.action === 'needs_human' ? conflict.decision.reason : undefined);
291
+ const probation = source.clipped.length > 0 || support.forceProbation;
210
292
  return {
211
293
  checks,
212
294
  conflict: conflict.decision,
213
295
  usage,
214
296
  ...(needsHuman === undefined ? {} : { needsHuman }),
297
+ ...(probation ? { forceProbation: true } : {}),
215
298
  };
216
299
  }
@@ -20,6 +20,7 @@
20
20
  import { createHash } from 'node:crypto';
21
21
  import { promises as nodeFs } from 'node:fs';
22
22
  import { isAbsolute, join } from 'node:path';
23
+ import { unescapeGeneEntities } from '@aragon-agent/tui/model/gene/escape';
23
24
  import { isInsideRoot } from '../../paths.js';
24
25
  const MAX_FILE_BYTES = 2 * 1024 * 1024;
25
26
  const GREP_FILE_BYTES = 512 * 1024;
@@ -67,7 +68,12 @@ async function checkFileEvidence(root, evidence) {
67
68
  const needle = quoteNeedle(evidence.text);
68
69
  if (needle.length === 0)
69
70
  return 'ok';
70
- return bytes.toString('utf8').replace(/\r\n/g, '\n').includes(needle) ? 'ok' : 'failed';
71
+ const text = bytes.toString('utf8').replace(/\r\n/g, '\n');
72
+ if (text.includes(needle))
73
+ return 'ok';
74
+ // A quote captured from an escaped prompt holds entities the file never had: compare the
75
+ // unescaped forms too, so "the file still says it" means the same thing in every check (RV-20).
76
+ return unescapeGeneEntities(text).includes(unescapeGeneEntities(needle)) ? 'ok' : 'failed';
71
77
  }
72
78
  async function grepFile(path, symbol, state) {
73
79
  if (!TEXT_FILE_RE.test(path))
@@ -15,7 +15,7 @@
15
15
  * A MODEL ANSWER NEVER OVERRIDES A CODE CHECK. These checks are additions to the deterministic
16
16
  * ones; they can only make a candidate fail, not make a failed deterministic check pass.
17
17
  */
18
- import { clipEscaped, escapeGeneText } from '@aragon-agent/tui/model/gene/escape';
18
+ import { clipEscaped, escapeGeneText, unescapeGeneEntities, } from '@aragon-agent/tui/model/gene/escape';
19
19
  export const MODEL_CALL = { maxTokens: 600, timeoutMs: 20_000 };
20
20
  /** Ask the validator model; absent port, a null answer or a thrown call all mean "skipped". */
21
21
  export async function askModel(ports, system, user) {
@@ -65,13 +65,17 @@ function entryIndex(entry, count) {
65
65
  // K4 - is the draft supported by its evidence?
66
66
  // ---------------------------------------------------------------------------
67
67
  export function buildSupportPrompt(draft, evidence) {
68
- const blocks = evidence.slice(0, 12).map((text, i) => fence(`evidence ${i + 1}`, text, 1500));
68
+ // ONE ROUND OF ENTITY-UNESCAPING ON BOTH SIDES (RV-20). Evidence captured from an escaped
69
+ // learning prompt carries `&&` while the draft says `&&`; a validator asked whether the
70
+ // first supports the second would answer "no" about text that is character-for-character the
71
+ // same. K2 compares the unescaped forms, so this prompt must show the unescaped forms too.
72
+ const blocks = evidence.slice(0, 12).map((text, i) => fence(`evidence ${i + 1}`, unescapeGeneEntities(text), 1500));
69
73
  return {
70
74
  system: `${SYSTEM_BASE} Judge only whether the EVIDENCE supports every statement in the DRAFT.`,
71
75
  user: [
72
76
  'Question: does the evidence support every statement in the draft, without adding facts?',
73
77
  'Answer {"supported": true} or {"supported": false}.',
74
- fence('draft', draft, 2400),
78
+ fence('draft', unescapeGeneEntities(draft), 2400),
75
79
  ...blocks,
76
80
  ].join('\n'),
77
81
  };
@@ -76,7 +76,12 @@ export interface CandidateOutcome {
76
76
  needsHuman?: GeneNeedsHuman['reason'];
77
77
  conflict?: ConflictDecision;
78
78
  probation?: GeneProbation;
79
- /** A model check could not run for lack of positives / a model: the gene must be on probation. */
79
+ /**
80
+ * A model check could not run for lack of positives / a model, or answered "not supported": the
81
+ * gene must be on probation. RECORDED, not enforced here - an agent's publish is stamped with
82
+ * probation unconditionally (`plan-content.ts` -> `startProbation`), and this flag is what tells
83
+ * the manager UI and the run log that the support was doubted (RC-4).
84
+ */
80
85
  forceProbation: boolean;
81
86
  /** The class the gene will be stored with (an agent draft of `oversight` is demoted). */
82
87
  class: GeneClass;
@@ -1,6 +1,45 @@
1
+ /**
2
+ * The learning model call (gene-bank spec 10.1.3, 10.6).
3
+ *
4
+ * ASCII ONLY - the whole `gene/` tree is in `glyphs.test.ts::inScope`.
5
+ *
6
+ * ONE BOUNDED CALL, NO TOOLS. `maxTokens 4096`, `temperature 0`, 60 s for the whole thing
7
+ * INCLUDING the retry. The transport is an injected `complete` function: the controller wires it
8
+ * to `FastWiring.completeViaFastRegistry` (or to a main-model, fail-fast registry when
9
+ * `gene.reviewerModel` is `main`, RV-22). It must be a FAIL-FAST transport - a background
10
+ * learning call that inherits the foreground's long retry backoff would sit on a rate limit and
11
+ * compete with the user's turn.
12
+ *
13
+ * FOUR OUTCOMES, because the caller reacts to each differently:
14
+ * - `transient` the provider is busy (`rate_limit` / `overloaded`). Not the tier's fault, so it
15
+ * never counts as a strike (same rule as `classifyReviewFailure`, D-24).
16
+ * - `failure` anything else that went wrong. A strike; three in a row disable learning for
17
+ * the session so a misconfigured tier cannot burn tokens forever.
18
+ * - `timeout` the deadline passed. A strike.
19
+ * - `cancelled` the caller aborted (`/clear`, exit). Never a strike and never enqueued.
20
+ *
21
+ * THE TIMEOUT AND THE CANCEL ARE TOLD APART HERE, by a variable set BEFORE the abort. After
22
+ * the retry layer both arrive as the same bare abort error, so they cannot be told apart at the
23
+ * catch (the lesson of `fast/review-call.ts`, where the same mistake once made a Esc press count
24
+ * as a model failure). The deadline is also enforced by a race, not only by the signal, so a
25
+ * transport that ignores its signal still cannot hold the single-flight slot.
26
+ *
27
+ * WHY 4096 TOKENS AND 60 s (RC-1). The reply is one JSON object holding up to three proposals with
28
+ * a body of up to 6000 characters each, so a compliant answer does not fit in 1500 tokens: every
29
+ * paid call on the machine this fix was written for stopped at exactly 1500 and 7 of 14 were
30
+ * unparseable. The two numbers move TOGETHER: at the measured ~125 tokens/second, 4096 tokens
31
+ * needs ~33 s, so a 1500 -> 4096 change alone would turn every truncation into a timeout, and a
32
+ * timeout is a strike. `minRetryWindowMs` still leaves room for one retry inside the deadline.
33
+ *
34
+ * A REPLY THAT HIT THE CEILING IS NOT A FAILURE OF THE TIER. `stopReason` comes back from the
35
+ * provider through the transport; `isTruncated` below is the only place that reads it. Whether a
36
+ * truncated reply is unusable depends on whether it PARSES, which is the learner's call - a reply
37
+ * cut after its final `}` is still a good answer (RV-18).
38
+ */
39
+ import type { StopReason } from '@aragon-agent/core';
1
40
  export declare const LEARN_CALL: {
2
- readonly maxTokens: 1500;
3
- readonly timeoutMs: 25000;
41
+ readonly maxTokens: 4096;
42
+ readonly timeoutMs: 60000;
4
43
  /** One extra attempt, and only for a transient failure with time left. */
5
44
  readonly retries: 1;
6
45
  readonly retryDelayMs: 500;
@@ -20,6 +59,8 @@ export interface LearnCompletion {
20
59
  inTok: number;
21
60
  outTok: number;
22
61
  };
62
+ /** The provider's stop reason (`max_tokens` means "cut off at the ceiling"), when it has one. */
63
+ stopReason?: StopReason;
23
64
  }
24
65
  /** The transport port. Throws on failure; the thrown value may carry `errorType`. */
25
66
  export type LearnComplete = (request: LearnRequest) => Promise<LearnCompletion>;
@@ -44,20 +85,32 @@ export interface LearnUsage {
44
85
  inTok: number;
45
86
  outTok: number;
46
87
  }
47
- export type LearnCallResult = {
88
+ export type LearnCallResult = LearnReply | LearnFailure;
89
+ /** A usable reply. `replyChars` is the only size the run log may record (I-19: never the text). */
90
+ export interface LearnReply {
48
91
  ok: true;
49
92
  text: string;
50
93
  usage: LearnUsage;
51
94
  attempts: number;
52
- } | {
95
+ /** The provider's stop reason, when it reported one. */
96
+ stopReason?: StopReason;
97
+ replyChars: number;
98
+ }
99
+ export interface LearnFailure {
53
100
  ok: false;
54
101
  kind: 'transient' | 'failure' | 'timeout' | 'cancelled';
55
102
  errorType: string;
56
103
  message: string;
57
104
  usage: LearnUsage;
58
105
  attempts: number;
59
- };
106
+ replyChars?: number;
107
+ }
60
108
  /** True for the kinds that count toward self-disabling. */
61
109
  export declare function countsAsStrike(result: LearnCallResult): boolean;
110
+ /**
111
+ * Did the provider cut the reply off at the output ceiling? The learner pairs this with "and it
112
+ * did not parse" before treating the call as a wasted (transient) one (RV-18).
113
+ */
114
+ export declare function isTruncated(result: LearnCallResult): boolean;
62
115
  /** Run the call with a deadline and at most one retry of a transient failure. Never throws. */
63
116
  export declare function runLearnCall(options: LearnCallOptions): Promise<LearnCallResult>;
@@ -1,33 +1,7 @@
1
- /**
2
- * The learning model call (gene-bank spec 10.1.3, 10.6).
3
- *
4
- * ASCII ONLY - the whole `gene/` tree is in `glyphs.test.ts::inScope`.
5
- *
6
- * ONE BOUNDED CALL, NO TOOLS. `maxTokens 1500`, `temperature 0`, 25 s for the whole thing
7
- * INCLUDING the retry. The transport is an injected `complete` function: the controller wires it
8
- * to `FastWiring.completeViaFastRegistry` (or to a main-model, fail-fast registry when
9
- * `gene.reviewerModel` is `main`, RV-22). It must be a FAIL-FAST transport - a background
10
- * learning call that inherits the foreground's long retry backoff would sit on a rate limit and
11
- * compete with the user's turn.
12
- *
13
- * FOUR OUTCOMES, because the caller reacts to each differently:
14
- * - `transient` the provider is busy (`rate_limit` / `overloaded`). Not the tier's fault, so it
15
- * never counts as a strike (same rule as `classifyReviewFailure`, D-24).
16
- * - `failure` anything else that went wrong. A strike; three in a row disable learning for
17
- * the session so a misconfigured tier cannot burn tokens forever.
18
- * - `timeout` the deadline passed. A strike.
19
- * - `cancelled` the caller aborted (`/clear`, exit). Never a strike and never enqueued.
20
- *
21
- * THE TIMEOUT AND THE CANCEL ARE TOLD APART HERE, by a variable set BEFORE the abort. After
22
- * the retry layer both arrive as the same bare abort error, so they cannot be told apart at the
23
- * catch (the lesson of `fast/review-call.ts`, where the same mistake once made a Esc press count
24
- * as a model failure). The deadline is also enforced by a race, not only by the signal, so a
25
- * transport that ignores its signal still cannot hold the single-flight slot.
26
- */
27
1
  import { classifyReviewFailure, errorText } from '../../fast/review-call.js';
28
2
  export const LEARN_CALL = {
29
- maxTokens: 1500,
30
- timeoutMs: 25_000,
3
+ maxTokens: 4096,
4
+ timeoutMs: 60_000,
31
5
  /** One extra attempt, and only for a transient failure with time left. */
32
6
  retries: 1,
33
7
  retryDelayMs: 500,
@@ -45,6 +19,13 @@ export const realLearnTimers = {
45
19
  export function countsAsStrike(result) {
46
20
  return !result.ok && (result.kind === 'failure' || result.kind === 'timeout');
47
21
  }
22
+ /**
23
+ * Did the provider cut the reply off at the output ceiling? The learner pairs this with "and it
24
+ * did not parse" before treating the call as a wasted (transient) one (RV-18).
25
+ */
26
+ export function isTruncated(result) {
27
+ return result.ok && result.stopReason === 'max_tokens';
28
+ }
48
29
  function realSleep(ms, signal) {
49
30
  return new Promise((resolve) => {
50
31
  const timer = setTimeout(resolve, ms);
@@ -120,10 +101,37 @@ function settle(completion, t) {
120
101
  t.usage.inTok += completion.usage?.inTok ?? 0;
121
102
  t.usage.outTok += completion.usage?.outTok ?? 0;
122
103
  const text = typeof completion.text === 'string' ? completion.text.trim() : '';
104
+ const stop = completion.stopReason;
123
105
  if (text.length === 0) {
124
- return failure({ kind: 'failure', errorType: 'empty_response', message: 'empty reply', usage: t.usage, attempts: t.attempt });
106
+ // An EMPTY reply that stopped at the ceiling is a truncation, not a model that had nothing to
107
+ // say: charging it as a strike would disable learning for the session (RC-1 / RV-14).
108
+ if (stop === 'max_tokens') {
109
+ return failure({
110
+ kind: 'transient',
111
+ errorType: 'truncated',
112
+ message: 'truncated to nothing',
113
+ usage: t.usage,
114
+ attempts: t.attempt,
115
+ replyChars: 0,
116
+ });
117
+ }
118
+ return failure({
119
+ kind: 'failure',
120
+ errorType: 'empty_response',
121
+ message: 'empty reply',
122
+ usage: t.usage,
123
+ attempts: t.attempt,
124
+ replyChars: 0,
125
+ });
125
126
  }
126
- return { ok: true, text, usage: t.usage, attempts: t.attempt };
127
+ return {
128
+ ok: true,
129
+ text,
130
+ usage: t.usage,
131
+ attempts: t.attempt,
132
+ ...(stop === undefined ? {} : { stopReason: stop }),
133
+ replyChars: text.length,
134
+ };
127
135
  }
128
136
  /** A thrown error: an abort wins, a busy provider may be retried, anything else ends the call. */
129
137
  function afterError(error, t) {
@@ -1,6 +1,15 @@
1
1
  import type { LearningSignal } from '@aragon-agent/tui/model/gene/signals';
2
2
  import type { LedgerSnapshot } from './ledger.js';
3
- export declare const GENE_LEARN_PROMPT_VERSION = "v1-2026-11";
3
+ export declare const GENE_LEARN_PROMPT_VERSION = "v2-2026-11";
4
+ /**
5
+ * The ONE heading under which a draft states what it could NOT verify (RC-2).
6
+ *
7
+ * It lives here, next to the rules that ask the model to write it, and the validator imports this
8
+ * same constant - two spellings of one convention is how a prompt and a check drift apart. The
9
+ * block is exempt from the verbatim-token check (`curator/validate/knowledge.ts`), so the reviewer
10
+ * no longer has to claim it verified something the evidence never showed it.
11
+ */
12
+ export declare const LEARN_UNVERIFIED_HEADING = "Not established";
4
13
  export declare const LEARN_INPUT_LIMITS: {
5
14
  readonly sectionsMaxBytes: number;
6
15
  readonly totalMaxBytes: number;
@@ -13,7 +22,14 @@ export declare const LEARN_INPUT_LIMITS: {
13
22
  };
14
23
  /** The system prompt. Source constant: nothing a run or a gene says can reach it. */
15
24
  export declare const LEARN_SYSTEM_PROMPT: string;
16
- /** One line, entity-escaped, clipped: the only form untrusted text takes in the input. */
25
+ /**
26
+ * One line, fence-tag defended, clipped: the only form untrusted text takes in the input.
27
+ *
28
+ * NO ENTITY SUBSTITUTION (RV-19, RC-3). The reviewer is told to quote what it was shown, and that
29
+ * quote becomes an evidence snapshot compared verbatim against the draft. Escaping `&&` to
30
+ * `&amp;&amp;` here made every shell-command quote unmatchable. `line-noent` keeps what the fence
31
+ * needs (one line, no controls, no open tag) and leaves the characters alone.
32
+ */
17
33
  export declare function oneLine(text: string, max?: number): string;
18
34
  /**
19
35
  * The LEDGER section within `maxBytes`: unsignalled and oldest frames are dropped first, the
@@ -10,11 +10,13 @@
10
10
  * rules the reviewer was given.
11
11
  *
12
12
  * THE INPUT IS DATA, NOT INSTRUCTION. Everything from the run (user text, tool output, gene
13
- * lines) is flattened to ONE line with angle brackets entity-escaped and given a short tag
14
- * prefix (`U3`, `C7`, `G12`). A fragment therefore can never start a line of its own, so it
15
- * cannot forge a `=== SECTION ===` marker or impersonate this prompt's structure, and the system
16
- * text tells the model so. This is hygiene, not a security boundary: the reply is normalised,
17
- * guarded and validated downstream, and nothing it says can write to the library by itself.
13
+ * lines) is flattened to ONE line and given a short tag prefix (`U3`, `C7`, `G12`). A fragment
14
+ * therefore can never start a line of its own, so it cannot forge a `=== SECTION ===` marker or
15
+ * impersonate this prompt's structure, and the system text tells the model so. The one line keeps
16
+ * its characters (no entity substitution: the model is told to quote them verbatim and the quote is
17
+ * compared against this text, RC-3 / RV-19); only the fence tags are defused. This is hygiene, not
18
+ * a security boundary: the reply is normalised, guarded and validated downstream, and nothing it
19
+ * says can write to the library by itself.
18
20
  *
19
21
  * BOUNDS (10.1.3, RV-9): GOAL + SIGNALS + LEDGER + GENES_USED together <= 14 KB, the whole input
20
22
  * <= 48 KB. The 14 KB sections are filled in priority order - GENES_USED is capped first, then
@@ -22,7 +24,16 @@
22
24
  * whatever the 48 KB total allows, in WHOLE lines (a clipped tier-1 line is a different gene).
23
25
  */
24
26
  import { clipEscaped, escapeGeneText } from '@aragon-agent/tui/model/gene/escape';
25
- export const GENE_LEARN_PROMPT_VERSION = 'v1-2026-11';
27
+ export const GENE_LEARN_PROMPT_VERSION = 'v2-2026-11';
28
+ /**
29
+ * The ONE heading under which a draft states what it could NOT verify (RC-2).
30
+ *
31
+ * It lives here, next to the rules that ask the model to write it, and the validator imports this
32
+ * same constant - two spellings of one convention is how a prompt and a check drift apart. The
33
+ * block is exempt from the verbatim-token check (`curator/validate/knowledge.ts`), so the reviewer
34
+ * no longer has to claim it verified something the evidence never showed it.
35
+ */
36
+ export const LEARN_UNVERIFIED_HEADING = 'Not established';
26
37
  export const LEARN_INPUT_LIMITS = {
27
38
  sectionsMaxBytes: 14 * 1024,
28
39
  totalMaxBytes: 48 * 1024,
@@ -51,7 +62,7 @@ export const LEARN_SYSTEM_PROMPT = [
51
62
  '1. attributions: give exactly one entry for EVERY gene listed in GENES_USED, using its id. Say "helped" or "harmed" ONLY when the text that followed the read shows clear evidence caused by following that entry, and put that evidence in "ev". Never judge an entry by whether the whole task succeeded or failed. When unsure write "unknown".',
52
63
  '2. When "decision" is "none", "proposals" must be empty. Make at most 3 proposals. Prefer none: a run with nothing new is the common, correct answer.',
53
64
  '3. A "create" proposal needs type, scope and title. Every other kind needs "target", an id taken from EXISTING or GENES_USED; "merge" also lists "mergeFrom". Never invent an id.',
54
- '4. Write title, why, expectedBenefit and everything under draft in English. Keep file paths, code symbols, error codes and numbers exactly as they appear. Quote evidence verbatim in its original language and never paraphrase it.',
65
+ '4. Write title, why, expectedBenefit and everything under draft in English. Keep file paths, code symbols, error codes and numbers exactly as they appear. Quote evidence verbatim in its original language and never paraphrase it. Write in draft.body only what the LEDGER shows you: a fact you cannot point at in the ledger does not belong in the body. When part of the lesson rests on something the run did not show, put it under ONE final section whose heading line starts with the words "Not established" (a "## " prefix is allowed) and say there what you could not confirm - that section is never treated as a claim.',
55
66
  '5. scope "user" is for standing preferences and facts about this person, "project" for facts about this codebase, "task" for what only matters to this session.',
56
67
  '6. A user statement about how things should be done is a preference; mark it with payload.kind "preference". Never state a preference the user did not express.',
57
68
  '7. Do not include secrets, tokens, personal data, or long code listings. Do not include instructions that tell a reader to ignore rules or reveal anything.',
@@ -66,11 +77,18 @@ function clipPoints(text, max) {
66
77
  const points = Array.from(text);
67
78
  return points.length <= max ? text : `${points.slice(0, Math.max(0, max - 3)).join('')}...`;
68
79
  }
69
- /** One line, entity-escaped, clipped: the only form untrusted text takes in the input. */
80
+ /**
81
+ * One line, fence-tag defended, clipped: the only form untrusted text takes in the input.
82
+ *
83
+ * NO ENTITY SUBSTITUTION (RV-19, RC-3). The reviewer is told to quote what it was shown, and that
84
+ * quote becomes an evidence snapshot compared verbatim against the draft. Escaping `&&` to
85
+ * `&amp;&amp;` here made every shell-command quote unmatchable. `line-noent` keeps what the fence
86
+ * needs (one line, no controls, no open tag) and leaves the characters alone.
87
+ */
70
88
  export function oneLine(text, max = LEARN_INPUT_LIMITS.lineMax) {
71
- // Escape first, clip last: the escaped form is what must fit, and `clipEscaped` never cuts an
72
- // entity in half.
73
- return clipEscaped(escapeGeneText(text, 'line'), max);
89
+ // Flatten and defend first, clip last: what has to fit is the line the model sees, and
90
+ // `clipEscaped` only ever drops an entity it would otherwise cut in half.
91
+ return clipEscaped(escapeGeneText(text, 'line-noent'), max);
74
92
  }
75
93
  const SIGNAL_NAMES = {
76
94
  L1: 'user_correction',
@@ -167,6 +167,12 @@ export declare class GeneLearner implements LearnerFeed {
167
167
  private projectMayLearn;
168
168
  private learn;
169
169
  private prepare;
170
+ /**
171
+ * Un-spend one attempt: the run's signals become learnable again and the session count goes
172
+ * back. The cooldown (`lastLearnAt`) is NOT part of it - a busy provider, a truncation and a
173
+ * cancellation all keep it, and only a cancellation gives it back (`undoFire`).
174
+ */
175
+ private giveBack;
170
176
  private undoFire;
171
177
  private setReviewing;
172
178
  private settleFailure;