@aragon-agent/cli 0.6.56 → 0.6.57

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.
package/CHANGELOG.md CHANGED
@@ -436,6 +436,29 @@ were written.
436
436
  the same bytes it wrote before.
437
437
 
438
438
  ### Fixed
439
+ - **The gene bank learns again: a long session used to end with zero genes and no way to tell why.** Four
440
+ independent defects sat on the same four-stage path, and each one was enough on its own. (1) The learning
441
+ call asked for a three-proposal JSON object with a 1500-token ceiling, so 7 of 14 paid calls stopped at
442
+ exactly 1500, could not be parsed and counted as a strike - three of those disabled learning for the rest
443
+ of the session while the runs they covered were dropped for good. The call is now 4096 tokens and 60 s
444
+ (the two move together: at ~125 tokens/s a bigger ceiling under the old 25 s deadline would have turned
445
+ every truncation into a timeout, which is also a strike), the provider's stop reason reaches the learner,
446
+ and a reply cut at the ceiling that does not parse costs nothing: no strike, the watermark rolls back and
447
+ the run stays learnable. A truncated reply that STILL parses is used. (2) The curator wrote `applicability`
448
+ keys of its own invention (`platform`, `projects`), which K3 - reading only `os` - reported as "an
449
+ environment-bound statement without applicability", so every lesson that mentioned win32/cmd/powershell was
450
+ refused. One `normalizeApplicability` now serves the write boundary and the check (aliases renamed, scope
451
+ keys dropped with a warning), the tool schema declares the six keys, and K1 names an unknown key instead of
452
+ passing it. (3) Evidence reached the reviewer HTML-escaped (`&&` as `&&`) while the draft did not, and
453
+ the model was told to quote it verbatim - K2 then failed on text that matched. The learning prompt keeps its
454
+ characters (only fence tags are still defused), both sides of K2, the live check and the support check
455
+ unescape once, `ev_` refs are no longer treated as facts to find, and a backticked placeholder, wildcard or
456
+ plain word is emphasis rather than an assertion. (4) A miss that our own clipping caused now puts the gene
457
+ on probation instead of killing it, while a miss the model invented still fails. `gene_validate` also ends
458
+ with a `To fix:` line naming the tokens that were not in the evidence, so the curator can repair the draft
459
+ in the same task instead of re-proposing it until the budget runs out; the stored verdict and the manager
460
+ still carry kinds and counts only. A line longer than the prompt budget that holds `&&` used to be clipped
461
+ at its first ampersand (466 characters became 31); only an incomplete entity is dropped now.
439
462
  - **Turning team off, or lowering `maxSubagents`, now takes effect everywhere - including through Settings.** The
440
463
  forced-mode chip kept saying the mode was on after `team.enabled` was switched off, an armed count of 6 stayed 6
441
464
  in the prompt after `maxSubagents` dropped to 3, and a settings save also shipped a `<team_mode>` /
@@ -48,13 +48,14 @@ async function recheckTool(input, at) {
48
48
  async function runRules(input, at) {
49
49
  const { head, version, ports } = input;
50
50
  if (head.type === 'knowledge') {
51
- return checkSource({
51
+ const source = await checkSource({
52
52
  ports,
53
53
  scope: head.scope,
54
54
  geneId: head.id,
55
55
  content: version.content,
56
56
  evidence: input.evidence ?? [],
57
57
  });
58
+ return source.checks;
58
59
  }
59
60
  if (head.type === 'skill') {
60
61
  return checkDependencies({ ports, scope: head.scope, geneId: head.id, content: version.content });
@@ -20,6 +20,7 @@
20
20
  import { defineTool, errorResult, textResult, } from '@aragon-agent/core';
21
21
  import { describeGeneError } from '@aragon-agent/tui/model/gene/copy';
22
22
  import { GENE_LIMITS } from '@aragon-agent/tui/model/gene/limits';
23
+ import { normalizeApplicability, } from '@aragon-agent/tui/model/gene/validate';
23
24
  import { GeneStoreError } from '../gene-errors.js';
24
25
  import { geneLooksLikeSecret } from '../secrets.js';
25
26
  import { assertCuratorContext } from './task-context.js';
@@ -165,11 +166,12 @@ function listOf(raw, key, fallback) {
165
166
  */
166
167
  export function buildContent(env, type, raw, previous) {
167
168
  const requestedClass = raw.class === 'oversight' ? 'oversight' : undefined;
169
+ const applicability = applicabilityOf(raw, previous, env.ctx.proposal.applicability);
168
170
  const base = {
169
171
  ...proseOf(raw, previous),
170
172
  tags: listOf(raw, 'tags', previous?.tags ?? []),
171
173
  localeHints: listOf(raw, 'localeHints', previous?.localeHints ?? []),
172
- applicability: applicabilityOf(env, raw, previous),
174
+ applicability: applicability.applicability,
173
175
  roles: rolesOf(raw.roles, previous?.roles ?? ALL_ROLES),
174
176
  deps: previous?.deps ?? [],
175
177
  source: sourceOf(env),
@@ -177,16 +179,23 @@ export function buildContent(env, type, raw, previous) {
177
179
  payload: payloadOf(raw, previous),
178
180
  };
179
181
  const content = type === 'skill' ? syncSkillDeps(base) : base;
180
- if (requestedClass === undefined)
181
- return { content, warnings: [] };
182
- return { content, requestedClass, warnings: ['class oversight is human-only; stored as standard'] };
182
+ const warnings = [...applicability.warnings];
183
+ if (requestedClass !== undefined)
184
+ warnings.push('class oversight is human-only; stored as standard');
185
+ return requestedClass === undefined ? { content, warnings } : { content, requestedClass, warnings };
183
186
  }
184
187
  function payloadOf(raw, previous) {
185
188
  return (asObject(raw.payload) ?? previous?.payload ?? {});
186
189
  }
187
- function applicabilityOf(env, raw, previous) {
188
- const proposed = env.ctx.proposal.applicability;
189
- return asObject(raw.applicability) ?? previous?.applicability ?? proposed ?? {};
190
+ /**
191
+ * The applicability to store, NORMALISED (RC-2). This is the one write boundary every candidate
192
+ * goes through, and the model's block is passed through it verbatim in the old code: `platform` and
193
+ * `projects` went to disk unread by the checks, so K3 saw "no applicability" and refused the gene.
194
+ * Renames and drops are reported as warnings rather than silently accepted.
195
+ */
196
+ function applicabilityOf(raw, previous, proposed) {
197
+ const block = asObject(raw.applicability) ?? previous?.applicability ?? proposed;
198
+ return normalizeApplicability(block ?? {});
190
199
  }
191
200
  /** The proposal's evidence for a commit to `geneId`: attached once per gene. */
192
201
  export function evidenceFor(ctx, geneId) {
@@ -1,6 +1,7 @@
1
1
  import { autoProbe } from './probe.js';
2
2
  import { validationKey } from './task-context.js';
3
3
  import { validateCandidateDetailed } from './validate/index.js';
4
+ import { repairLines, resolveEvidence } from './validate/knowledge.js';
4
5
  import { CURATOR_ACTOR, asString, defineCuratorTool, receipt, refuse, switchGate, } from './tool-support.js';
5
6
  function scriptRefOf(content) {
6
7
  const exec = content.payload.exec;
@@ -98,6 +99,45 @@ function conflictAdvice(outcome) {
98
99
  return ` Conflict: revise ${c.target}; use gene_revise.`;
99
100
  return ` Conflict with a person-owned gene (${c.against}); finish needs_human.`;
100
101
  }
102
+ /**
103
+ * The tokens K2 could not find, listed verbatim so the curator can fix the draft instead of
104
+ * ending the task (RV-17, B3). `symbol x8` is a verdict the model cannot act on: the same
105
+ * rejection repeats on every re-proposal and the experience is lost.
106
+ *
107
+ * THIS STRING IS THE TOOL'S ANSWER AND NOTHING ELSE. It is built from the model's own draft and
108
+ * its own evidence, and it never reaches `validation.detail` or the manager UI, which stay redacted
109
+ * to kinds and counts (I-19). The evidence is resolved the same way K2 resolved it, so a ref that
110
+ * lives on disk cannot be reported as missing.
111
+ */
112
+ async function repairsFor(env, head, content) {
113
+ if (head.type !== 'knowledge')
114
+ return [];
115
+ try {
116
+ const ports = await env.deps.validatorPorts(env.ctx);
117
+ const evidence = evidenceSnapshot(env, head.id);
118
+ const resolved = await resolveEvidence(ports, head.scope, head.id, content, evidence);
119
+ return repairLines(content, resolved.corpus.map((e) => e.text).join('\n'));
120
+ }
121
+ catch {
122
+ // A library that cannot be read must not turn a verdict into a crash; the redacted detail stays.
123
+ return [];
124
+ }
125
+ }
126
+ /**
127
+ * Only K2's miss list is actionable: it names specifics the model itself wrote. Every other code
128
+ * (`GENE_INVALID_CONTENT`, a scope misfit) already names the field to change, so paying for an
129
+ * evidence resolution to print more would be noise.
130
+ */
131
+ function needsRepair(outcome) {
132
+ return outcome.validation.checks.some((c) => !c.ok && c.code === 'KNOWLEDGE_EVIDENCE_UNRESOLVED');
133
+ }
134
+ /** ` To fix: ...` when the failing checks can be made actionable, otherwise nothing. */
135
+ async function fixAdvice(env, head, version, outcome) {
136
+ if (!needsRepair(outcome))
137
+ return '';
138
+ const lines = await repairsFor(env, head, version.content);
139
+ return lines.length === 0 ? '' : ` To fix: ${lines.join('. ')}`;
140
+ }
101
141
  /** What a verdict beyond "pass" or "fail" needs done to the library, and what to tell the model. */
102
142
  async function actOnVerdict(env, head, outcome) {
103
143
  if (outcome.verdict === 'needs_human') {
@@ -151,7 +191,8 @@ async function validateCandidate(env, params) {
151
191
  detail: `name=${head.brief.name}`,
152
192
  });
153
193
  const advice = await actOnVerdict(env, head, outcome);
154
- return receipt(`${id} v${v.n}: verdict=${outcome.verdict}. ${summariseChecks(outcome)}.${advice}`);
194
+ const fix = await fixAdvice(env, head, v, outcome);
195
+ return receipt(`${id} v${v.n}: verdict=${outcome.verdict}. ${summariseChecks(outcome)}.${advice}${fix}`);
155
196
  }
156
197
  function validateTool(env) {
157
198
  return defineCuratorTool(env, {
@@ -4,9 +4,49 @@ import { evaluatePublishGate } from './publish.js';
4
4
  import { validationKey } from './task-context.js';
5
5
  import { flagNeedsHuman, runCandidateValidation, summariseChecks } from './tools-verify.js';
6
6
  import { CURATOR_ACTOR, TYPE_NAMES, applyFailureEffects, asObject, asString, asStringList, buildContent, defineCuratorTool, evidenceFor, failureResult, noteStale, reasonOf, receipt, refuse, switchGate, } from './tool-support.js';
7
+ /**
8
+ * The `applicability` block, WITH its keys declared (RC-2). It used to be an undescribed object,
9
+ * so the model wrote whatever it remembered (`platform`, `projects`, `surfaces`) and K3 - which
10
+ * reads `os` - saw "no environment at all" and refused the gene. Declaring the six keys here stops
11
+ * the bad shape at the model side; `normalizeApplicability` catches the rest at the write boundary.
12
+ */
13
+ const APPLICABILITY_PARAM = {
14
+ type: 'object',
15
+ description: 'Environment filters, and nothing else. os plus optional requiresTools, fileGlobs, projectKinds, ' +
16
+ 'envStamp, minWindowTokens. The scope already carries the project; do not repeat it here.',
17
+ properties: {
18
+ os: {
19
+ type: 'array',
20
+ description: 'win32, darwin or linux.',
21
+ items: { type: 'string', enum: ['win32', 'darwin', 'linux'] },
22
+ },
23
+ requiresTools: { type: 'array', description: 'Tool names that must exist.', items: { type: 'string' } },
24
+ fileGlobs: { type: 'array', description: 'Files the statement is about.', items: { type: 'string' } },
25
+ projectKinds: { type: 'array', description: 'Kinds of project.', items: { type: 'string' } },
26
+ envStamp: { type: 'object', description: 'Environment values that must match.' },
27
+ minWindowTokens: { type: 'number', description: 'Smallest context window it needs.' },
28
+ },
29
+ };
7
30
  const CONTENT_PARAM = {
8
31
  type: 'object',
9
- description: 'name, purpose, trigger, body, tags, applicability, roles, payload. English prose.',
32
+ description: 'name, purpose, trigger, body, tags, localeHints, applicability, roles, payload. English prose.',
33
+ properties: {
34
+ name: { type: 'string', description: 'kebab-case, 3-60 chars of a-z, 0-9 and "-".' },
35
+ purpose: { type: 'string', description: 'One English sentence: what it is for.' },
36
+ trigger: { type: 'string', description: 'One English sentence: when to load it.' },
37
+ body: { type: 'string', description: 'The English text of the gene.' },
38
+ tags: { type: 'array', items: { type: 'string' } },
39
+ // Declared because `buildContent` reads it: a field the boundary accepts but the schema
40
+ // hides is one the model has to guess at.
41
+ localeHints: {
42
+ type: 'array',
43
+ description: 'Chinese phrases a search may arrive in, when the body is English.',
44
+ items: { type: 'string' },
45
+ },
46
+ applicability: APPLICABILITY_PARAM,
47
+ roles: { type: 'array', items: { type: 'string', enum: ['main', 'subagent', 'reviewer'] } },
48
+ payload: { type: 'object', description: 'kind, claims, exec, requires or preference.' },
49
+ },
10
50
  };
11
51
  function candidateNote(outcome, warnings) {
12
52
  const extra = warnings.length > 0 ? ` Warning: ${warnings.join('; ')}.` : '';
@@ -1,20 +1,3 @@
1
- /**
2
- * Verbatim-token extraction for the K2 source check (gene-bank spec 10.7.1 K2, RV-10).
3
- *
4
- * ASCII ONLY - the whole `gene/` tree is in `glyphs.test.ts::inScope`. PURE.
5
- *
6
- * THE RULE THIS IMPLEMENTS. Every path, symbol, error code and number that a draft states must
7
- * appear VERBATIM in the evidence the proposal carried. A model that "tidies" `src\\a.ts` into
8
- * `src/a.ts` is fine (paths compare with one separator), a model that invents `src/b.ts` or
9
- * rounds `1.7 s` to `2 s` is not. This is the deterministic backbone of K2: it needs no
10
- * filesystem and no model, so it runs even when the evidence's project is not on this machine.
11
- *
12
- * WHAT IT IS NOT. It does not decide that the draft is TRUE (that is K4's supported-by-evidence
13
- * question) and it cannot see a fact the model stated in prose without a token. It is a floor:
14
- * the specifics that are cheap to check mechanically are checked mechanically.
15
- *
16
- * NO FAILURE MESSAGE MAY CARRY A TOKEN (I-19). Callers report counts per kind only.
17
- */
18
1
  export type TokenKind = 'path' | 'symbol' | 'error_code' | 'number';
19
2
  export interface VerbatimToken {
20
3
  kind: TokenKind;
@@ -22,13 +5,18 @@ export interface VerbatimToken {
22
5
  }
23
6
  /** The checkable specifics of `text`, at most 96, in order of first appearance. */
24
7
  export declare function extractVerbatimTokens(text: string): VerbatimToken[];
25
- /** Is `token` present verbatim in the evidence `corpus`? Paths compare with one separator. */
8
+ /**
9
+ * Is `token` present verbatim in the evidence `corpus`? Both sides are entity-unescaped once: the
10
+ * model read an escaped prompt, so it quotes `&amp;&amp;` for a `&&` the evidence really has.
11
+ */
26
12
  export declare function tokenAppearsIn(token: VerbatimToken, corpus: string): boolean;
27
13
  export interface TokenReport {
28
14
  /** How many tokens the drafted texts contained. */
29
15
  checked: number;
30
- /** The tokens the evidence does not contain; callers report only `kind` counts. */
16
+ /** Tokens the evidence does not contain and our clipping does not explain: a real miss. */
31
17
  missing: VerbatimToken[];
18
+ /** Tokens the evidence only lacks because it was clipped here, not because they are wrong. */
19
+ clipped: VerbatimToken[];
32
20
  }
33
21
  /** Check every token of `drafted` against `corpus` (all evidence texts joined). */
34
22
  export declare function findUnsupportedTokens(drafted: readonly string[], corpus: string): TokenReport;
@@ -13,8 +13,25 @@
13
13
  * question) and it cannot see a fact the model stated in prose without a token. It is a floor:
14
14
  * the specifics that are cheap to check mechanically are checked mechanically.
15
15
  *
16
- * NO FAILURE MESSAGE MAY CARRY A TOKEN (I-19). Callers report counts per kind only.
16
+ * THREE CORRECTIONS LEARNED FROM REAL CANDIDATES (RC-3):
17
+ * 1. an evidence REF (`ev_1a2b3c4d`) is an id this system minted, never a fact, so it is not a
18
+ * token at all - the curator is TOLD to cite refs, so treating one as "must appear in the
19
+ * evidence" is a guaranteed miss (RV-8);
20
+ * 2. both sides of the comparison are entity-unescaped once, because the model was shown an
21
+ * escaped prompt and quotes what it was shown (RV-5, RV-19);
22
+ * 3. a backticked PLACEHOLDER (`python <file>`, `...`), a WILDCARD (`198.18.0.x`) or a plain
23
+ * lower-case word (`desktop`) is emphasis, not an assertion. Narrowing only these three
24
+ * enumerable shapes keeps an invented path or symbol caught (RV-13, B2c).
25
+ *
26
+ * A MISS WE CAUSED OURSELVES IS NOT THE DRAFT'S FAULT. Evidence is clipped with a trailing `...`
27
+ * on its way into the prompt, so a token that is a truncated PREFIX of what the draft says is
28
+ * reported as `clipped`, not `missing` (RV-13). `probation.ts` then keeps the gene out of harm's
29
+ * way instead of the candidate dying over our own truncation.
30
+ *
31
+ * NO FAILURE MESSAGE MAY CARRY A TOKEN (I-19). Callers report counts per kind only - except the
32
+ * curator's own tool answer, which lists them so the model can fix its draft (RV-17, B3).
17
33
  */
34
+ import { unescapeGeneEntities } from '@aragon-agent/tui/model/gene/escape';
18
35
  const MAX_TOKENS = 96;
19
36
  const FILE_EXTENSIONS = 'ts|tsx|js|jsx|mjs|cjs|json|md|yml|yaml|toml|lock|py|rs|go|java|cs|sh|ps1|cmd|bat|txt|log|css|' +
20
37
  'html|xml|sql|ini|cfg|conf|env|exe|dll|so|zip|tgz|gz|map|svg|png|csv';
@@ -30,6 +47,14 @@ const UPPER_SNAKE_RE = /^[A-Z][A-Z0-9]*(?:_[A-Z0-9]+)+$/;
30
47
  const COMPILER_CODE_RE = /^(?:TS|CS|CE|LNK|E|W)\d{3,5}$/;
31
48
  const LIST_MARKER_RE = /^\s*(?:[-*+]|\d+[.)])\s+/;
32
49
  const BACKTICK_RE = /`([^`\n]{2,80})`/g;
50
+ /** An evidence ref this system minted (`ids.ts`: `ev_` + 8 chars of [0-9a-z]). */
51
+ const EVIDENCE_REF_RE = /^ev_[0-9a-z]{8}$/;
52
+ /** `python <file>`, `<path>`, `...`: the model is naming a shape, not asserting a value. */
53
+ const PLACEHOLDER_RE = /<[^<>\n]{0,60}>|\.\.\./;
54
+ /** `198.18.0.x`, `src/*.ts`: a pattern, not a fact. */
55
+ const WILDCARD_SEGMENT_RE = /(?:^|[./\\])(?:x|\*|\?)(?=[./\\]|$)/i;
56
+ /** A single lower-case word in backticks (`desktop`) is emphasis. */
57
+ const PLAIN_WORD_RE = /^[a-z]+$/;
33
58
  function trimWord(word) {
34
59
  let out = word.replace(/^[("'[{<]+/, '').replace(/[)"'\]}>,;:!?]+$/, '');
35
60
  // A sentence-ending dot is not part of the token; a dot inside a name is.
@@ -55,7 +80,15 @@ function looksLikePath(word) {
55
80
  const directory = /[\\/]$/.test(word);
56
81
  return hasExtension || anchored || directory || segments.length >= 3;
57
82
  }
83
+ /** A quoted span that asserts nothing: a placeholder, a wildcard pattern, or one plain word. */
84
+ function isEmphasisOnly(span) {
85
+ return PLACEHOLDER_RE.test(span) || WILDCARD_SEGMENT_RE.test(span) || PLAIN_WORD_RE.test(span);
86
+ }
58
87
  function classify(word, quoted) {
88
+ if (EVIDENCE_REF_RE.test(word))
89
+ return null;
90
+ if (quoted && isEmphasisOnly(word))
91
+ return null;
59
92
  if (looksLikePath(word) || FILE_NAME_RE.test(word))
60
93
  return { kind: 'path', text: word };
61
94
  if (quoted)
@@ -111,13 +144,45 @@ function numberAppearsIn(text, corpus) {
111
144
  const re = new RegExp(`(?<![0-9A-Za-z_.,])${escapeRegExp(text)}(?![0-9A-Za-z_]|[.,]\\d)`);
112
145
  return re.test(corpus);
113
146
  }
114
- /** Is `token` present verbatim in the evidence `corpus`? Paths compare with one separator. */
115
- export function tokenAppearsIn(token, corpus) {
147
+ /** Does `token` appear in the (already unescaped) evidence `corpus`? Paths compare with one separator. */
148
+ function appearsIn(token, corpus) {
149
+ const needle = unescapeGeneEntities(token.text);
116
150
  if (token.kind === 'number')
117
- return numberAppearsIn(token.text, corpus);
151
+ return numberAppearsIn(needle, corpus);
118
152
  if (token.kind === 'path')
119
- return slashNormal(corpus).includes(slashNormal(token.text));
120
- return corpus.includes(token.text);
153
+ return slashNormal(corpus).includes(slashNormal(needle));
154
+ return corpus.includes(needle);
155
+ }
156
+ /**
157
+ * Is `token` present verbatim in the evidence `corpus`? Both sides are entity-unescaped once: the
158
+ * model read an escaped prompt, so it quotes `&amp;&amp;` for a `&&` the evidence really has.
159
+ */
160
+ export function tokenAppearsIn(token, corpus) {
161
+ return appearsIn(token, unescapeGeneEntities(String(corpus ?? '')));
162
+ }
163
+ /** How many characters of a clipped line's tail we are willing to match against a token. */
164
+ const MAX_CLIP_MATCH = 64;
165
+ /** The longest suffix of `head` that `text` starts with, at least 6 characters or nothing. */
166
+ function sharedSuffixLength(head, text) {
167
+ const max = Math.min(head.length, text.length, MAX_CLIP_MATCH);
168
+ for (let n = max; n >= 6; n -= 1) {
169
+ if (text.startsWith(head.slice(head.length - n)))
170
+ return n;
171
+ }
172
+ return 0;
173
+ }
174
+ /** The text each evidence LINE had before this system clipped it (a clip ends in `...`). */
175
+ function clippedHeads(corpus) {
176
+ return corpus
177
+ .split(/\r?\n/)
178
+ .map((line) => line.trimEnd())
179
+ .filter((line) => line.endsWith('...') && line.length > 6)
180
+ .map((line) => line.slice(0, -3));
181
+ }
182
+ /** Was this miss CAUSED by our own clipping? Only then may it be downgraded (RV-13). */
183
+ function looksClipped(token, heads) {
184
+ const text = unescapeGeneEntities(token);
185
+ return text.length >= 6 && heads.some((head) => sharedSuffixLength(head, text) >= 6);
121
186
  }
122
187
  /** Check every token of `drafted` against `corpus` (all evidence texts joined). */
123
188
  export function findUnsupportedTokens(drafted, corpus) {
@@ -127,8 +192,21 @@ export function findUnsupportedTokens(drafted, corpus) {
127
192
  for (const token of extractVerbatimTokens(text))
128
193
  pushUnique(tokens, seen, token);
129
194
  }
130
- const missing = tokens.filter((token) => !tokenAppearsIn(token, corpus));
131
- return { checked: tokens.length, missing };
195
+ const haystack = unescapeGeneEntities(String(corpus ?? ''));
196
+ // The heads come from the UNESCAPED text too: historical evidence holds `&amp;&amp;` where the
197
+ // draft says `&&`, and a clipped `&&`-line would otherwise never be recognised as clipped (RV-20).
198
+ const heads = clippedHeads(haystack);
199
+ const missing = [];
200
+ const clipped = [];
201
+ for (const token of tokens) {
202
+ if (appearsIn(token, haystack))
203
+ continue;
204
+ if (looksClipped(token.text, heads))
205
+ clipped.push(token);
206
+ else
207
+ missing.push(token);
208
+ }
209
+ return { checked: tokens.length, missing, clipped };
132
210
  }
133
211
  /** `path x1, number x2` - kinds and counts only, never the token text (I-19). */
134
212
  export function summarizeMissing(missing) {
@@ -1,5 +1,6 @@
1
1
  import type { GeneContent, GeneEvidence, GeneScope, GeneValidationCheck } from '@aragon-agent/tui/model/gene/types';
2
2
  import type { StaticReport } from './common.js';
3
+ import { type VerbatimToken } from './evidence-tokens.js';
3
4
  import type { ValidatorPorts } from './ports.js';
4
5
  import type { CandidateContext, TypeResult } from './types.js';
5
6
  /** The refs a draft cites: its `evidence` list and each claim's `evidence`. */
@@ -20,6 +21,21 @@ export interface SourceInput {
20
21
  /** Already-resolved evidence, so a caller that needs the corpus too reads each ref once. */
21
22
  resolved?: ResolvedEvidence;
22
23
  }
24
+ export interface SourceResult {
25
+ checks: GeneValidationCheck[];
26
+ /** Misses that OUR clipping explains. The gene may pass, but only on probation (RV-13). */
27
+ clipped: VerbatimToken[];
28
+ }
29
+ /**
30
+ * The CURATOR-ONLY repair line for a failing K2 (RV-17, B3): the missing tokens, verbatim, so the
31
+ * model can cite them or take them out of its draft in the same task.
32
+ *
33
+ * WHY IT IS NOT ON THE OUTCOME. `CandidateOutcome` is logged and stored, and a stored detail may
34
+ * never echo gene or evidence text (I-19) - the `poison-untrusted` case fails the moment a token
35
+ * leaves through it. This string is built at the tool boundary instead, from the model's own draft
36
+ * and its own evidence, and exists only in that one tool answer.
37
+ */
38
+ export declare function repairLines(content: GeneContent, corpus: string): string[];
23
39
  /** K2, reusable by `recheck` (10.9). Returns the K2 check and, when run, the live_check record. */
24
- export declare function checkSource(input: SourceInput): Promise<GeneValidationCheck[]>;
40
+ export declare function checkSource(input: SourceInput): Promise<SourceResult>;
25
41
  export declare function validateKnowledge(ctx: CandidateContext, report: StaticReport): Promise<TypeResult>;
@@ -7,7 +7,9 @@
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)
@@ -17,10 +19,10 @@
17
19
  * Every function returns plain data. A failing detail names fields and counts, never text.
18
20
  */
19
21
  import { promises as nodeFs } from 'node:fs';
20
- import { preferenceHorizonFitsScope } from '@aragon-agent/tui/model/gene/validate';
22
+ import { preferenceHorizonFitsScope, normalizedApplicabilityOf } from '@aragon-agent/tui/model/gene/validate';
21
23
  import { runConflictCheck } from '../conflicts.js';
22
24
  import { addUsage, failCheck, okCheck, skippedCheck, splitIssues, staticCheck, trustCheck, } from './common.js';
23
- import { extractVerbatimTokens, findUnsupportedTokens, summarizeMissing } from './evidence-tokens.js';
25
+ import { extractVerbatimTokens, findUnsupportedTokens, summarizeMissing, } from './evidence-tokens.js';
24
26
  import { liveCheckEvidence } from './live-check.js';
25
27
  import { askModel, buildSupportPrompt, parseSupportAnswer } from './prompts.js';
26
28
  function payloadOf(content) {
@@ -79,26 +81,53 @@ async function liveCheck(ports, scope, corpus, at) {
79
81
  const detail = result.status === 'passed' ? 'passed' : `failed: ${result.failed} of ${result.checked}`;
80
82
  return { check: okCheck('live_check', at, detail), failed: result.failed };
81
83
  }
84
+ /**
85
+ * The CURATOR-ONLY repair line for a failing K2 (RV-17, B3): the missing tokens, verbatim, so the
86
+ * model can cite them or take them out of its draft in the same task.
87
+ *
88
+ * WHY IT IS NOT ON THE OUTCOME. `CandidateOutcome` is logged and stored, and a stored detail may
89
+ * never echo gene or evidence text (I-19) - the `poison-untrusted` case fails the moment a token
90
+ * leaves through it. This string is built at the tool boundary instead, from the model's own draft
91
+ * and its own evidence, and exists only in that one tool answer.
92
+ */
93
+ export function repairLines(content, corpus) {
94
+ const report = findUnsupportedTokens(draftedTexts(content), corpus);
95
+ if (report.missing.length === 0)
96
+ return [];
97
+ const tokens = report.missing.map((t) => `${t.kind} ${t.text}`).join(', ');
98
+ return [`these tokens are not in the evidence: ${tokens} - quote them verbatim or remove them`];
99
+ }
100
+ function evidenceProblems(unresolved, report) {
101
+ const problems = [];
102
+ if (unresolved > 0)
103
+ problems.push(`${unresolved} cited ref(s) unresolved`);
104
+ if (report.missing.length > 0)
105
+ problems.push(`not in evidence: ${summarizeMissing(report.missing)}`);
106
+ return problems;
107
+ }
82
108
  /** K2, reusable by `recheck` (10.9). Returns the K2 check and, when run, the live_check record. */
83
109
  export async function checkSource(input) {
84
110
  const at = input.ports.now();
85
111
  const { corpus, unresolved } = input.resolved ??
86
112
  (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`);
113
+ if (corpus.length === 0) {
114
+ return {
115
+ checks: [failCheck('KNOWLEDGE_EVIDENCE_UNRESOLVED', at, 'K2 the proposal carries no evidence')],
116
+ clipped: [],
117
+ };
118
+ }
92
119
  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)}`);
120
+ const problems = evidenceProblems(unresolved, report);
95
121
  const live = await liveCheck(input.ports, input.scope, corpus, at);
96
122
  if (live.failed > 0)
97
123
  problems.push(`${live.failed} evidence item(s) no longer match the project`);
98
124
  const main = problems.length > 0
99
125
  ? failCheck('KNOWLEDGE_EVIDENCE_UNRESOLVED', at, `K2 ${problems.join('; ')}`)
100
126
  : okCheck('K2', at, `${report.checked} specific(s) found in evidence`);
101
- return live.check === undefined ? [main] : [main, live.check];
127
+ return {
128
+ checks: live.check === undefined ? [main] : [main, live.check],
129
+ clipped: report.clipped,
130
+ };
102
131
  }
103
132
  // ---------------------------------------------------------------------------
104
133
  // K3 - scope fit
@@ -123,7 +152,9 @@ function mentionsProject(texts, labels) {
123
152
  });
124
153
  }
125
154
  function applicabilityEmpty(content) {
126
- const a = content.applicability ?? {};
155
+ // The SAME normalisation the write path applied (RC-2, RV-16): a legacy or imported block that
156
+ // spells `platform` is an environment filter, not an absent one.
157
+ const a = normalizedApplicabilityOf(content);
127
158
  return !a.os?.length && !a.envStamp && !a.projectKinds?.length && !a.fileGlobs?.length && !a.requiresTools?.length;
128
159
  }
129
160
  function scopeProblems(ctx) {
@@ -194,7 +225,14 @@ export async function validateKnowledge(ctx, report) {
194
225
  resolved,
195
226
  ...(ctx.geneId === undefined ? {} : { geneId: ctx.geneId }),
196
227
  });
197
- checks.push(...source, ...checkScope(ctx, at));
228
+ checks.push(...source.checks);
229
+ if (source.clipped.length > 0) {
230
+ // The gene may still be right: the evidence we held was cut, not wrong. It goes in on probation
231
+ // (visible, double-weighted, revoked after it misleads twice) instead of dying here (RV-13).
232
+ const count = summarizeMissing(source.clipped);
233
+ checks.push(okCheck('KNOWLEDGE_EVIDENCE_CLIPPED', at, `K2 ${count} only missing because the evidence was clipped`));
234
+ }
235
+ checks.push(...checkScope(ctx, at));
198
236
  checks.push(await checkSupported(ctx, resolved.corpus, usage));
199
237
  const conflict = await runConflictCheck(ctx.ports, {
200
238
  type: 'knowledge',
@@ -212,5 +250,6 @@ export async function validateKnowledge(ctx, report) {
212
250
  conflict: conflict.decision,
213
251
  usage,
214
252
  ...(needsHuman === undefined ? {} : { needsHuman }),
253
+ ...(source.clipped.length > 0 ? { forceProbation: true } : {}),
215
254
  };
216
255
  }
@@ -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 `&amp;&amp;` 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
  };
@@ -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) {
@@ -13,7 +13,14 @@ export declare const LEARN_INPUT_LIMITS: {
13
13
  };
14
14
  /** The system prompt. Source constant: nothing a run or a gene says can reach it. */
15
15
  export declare const LEARN_SYSTEM_PROMPT: string;
16
- /** One line, entity-escaped, clipped: the only form untrusted text takes in the input. */
16
+ /**
17
+ * One line, fence-tag defended, clipped: the only form untrusted text takes in the input.
18
+ *
19
+ * NO ENTITY SUBSTITUTION (RV-19, RC-3). The reviewer is told to quote what it was shown, and that
20
+ * quote becomes an evidence snapshot compared verbatim against the draft. Escaping `&&` to
21
+ * `&amp;&amp;` here made every shell-command quote unmatchable. `line-noent` keeps what the fence
22
+ * needs (one line, no controls, no open tag) and leaves the characters alone.
23
+ */
17
24
  export declare function oneLine(text: string, max?: number): string;
18
25
  /**
19
26
  * 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
@@ -66,11 +68,18 @@ function clipPoints(text, max) {
66
68
  const points = Array.from(text);
67
69
  return points.length <= max ? text : `${points.slice(0, Math.max(0, max - 3)).join('')}...`;
68
70
  }
69
- /** One line, entity-escaped, clipped: the only form untrusted text takes in the input. */
71
+ /**
72
+ * One line, fence-tag defended, clipped: the only form untrusted text takes in the input.
73
+ *
74
+ * NO ENTITY SUBSTITUTION (RV-19, RC-3). The reviewer is told to quote what it was shown, and that
75
+ * quote becomes an evidence snapshot compared verbatim against the draft. Escaping `&&` to
76
+ * `&amp;&amp;` here made every shell-command quote unmatchable. `line-noent` keeps what the fence
77
+ * needs (one line, no controls, no open tag) and leaves the characters alone.
78
+ */
70
79
  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);
80
+ // Flatten and defend first, clip last: what has to fit is the line the model sees, and
81
+ // `clipEscaped` only ever drops an entity it would otherwise cut in half.
82
+ return clipEscaped(escapeGeneText(text, 'line-noent'), max);
74
83
  }
75
84
  const SIGNAL_NAMES = {
76
85
  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;
@@ -26,14 +26,16 @@
26
26
  * FAILURE POLICY. A transient provider error (rate limit, overload) costs nothing and is retried
27
27
  * at the next trigger. A real failure or a timeout is a strike; three in a row disable learning
28
28
  * for the session (`learner_failing`) and the status chip says so. A cancelled call (`/clear`,
29
- * exit) is dropped without a trace: no strike, no enqueue.
29
+ * exit) is dropped without a trace: no strike, no enqueue. A reply that stopped at the output
30
+ * ceiling and did not parse is a truncation, not a model failure: it costs no strike and rolls the
31
+ * watermark back, so the next trigger pays for that run again instead of losing the experience.
30
32
  */
31
33
  import { collectSignals, shouldLearn, } from '@aragon-agent/tui/model/gene/signals';
32
34
  import { normalizeLearningOutput } from '@aragon-agent/tui/model/gene/proposal';
33
35
  import { EvidenceLedger, } from './ledger.js';
34
36
  import { factsFromLedger } from './signals-port.js';
35
37
  import { buildLearningInput, LEARN_SYSTEM_PROMPT } from './learn-prompt.js';
36
- import { runLearnCall, } from './learn-call.js';
38
+ import { isTruncated, runLearnCall, } from './learn-call.js';
37
39
  import { guardProposal } from './proposal-guard.js';
38
40
  import { adjustAttributions, buildProposal, outcomeEvents, } from './proposal-build.js';
39
41
  export const LEARNER_STRIKES_MAX = 3;
@@ -280,8 +282,9 @@ export class GeneLearner {
280
282
  return;
281
283
  }
282
284
  this.deps.onUsage?.(result.usage);
283
- if (result.ok)
284
- await this.settleReply(result.text, { job, prepared, usage: result.usage });
285
+ if (result.ok) {
286
+ await this.settleReply(result.text, { job, prepared, usage: result.usage, truncated: isTruncated(result), replyChars: result.replyChars }, before);
287
+ }
285
288
  else
286
289
  await this.settleFailure(result, before);
287
290
  this.deps.notify?.();
@@ -300,10 +303,18 @@ export class GeneLearner {
300
303
  const used = [...snapshot.reads.keys()].map((id) => ({ id, line: this.deps.describeGene(id) ?? '' }));
301
304
  return { input: buildLearningInput({ snapshot, signals: job.signals, used, existing }), snapshot };
302
305
  }
303
- undoFire(before) {
306
+ /**
307
+ * Un-spend one attempt: the run's signals become learnable again and the session count goes
308
+ * back. The cooldown (`lastLearnAt`) is NOT part of it - a busy provider, a truncation and a
309
+ * cancellation all keep it, and only a cancellation gives it back (`undoFire`).
310
+ */
311
+ giveBack(before) {
304
312
  this.watermark = before.watermark;
305
- this.lastLearnAt = before.lastLearnAt;
306
313
  this.sessionCount = Math.max(0, this.sessionCount - 1);
314
+ }
315
+ undoFire(before) {
316
+ this.giveBack(before);
317
+ this.lastLearnAt = before.lastLearnAt;
307
318
  this.deps.notify?.();
308
319
  }
309
320
  setReviewing(value) {
@@ -311,10 +322,12 @@ export class GeneLearner {
311
322
  this.deps.notify?.();
312
323
  }
313
324
  async settleFailure(result, before) {
325
+ // The spend of a FAILED call is still spend: without this the run log said `tokens: null` for
326
+ // every truncation and the budget could never see the wasted calls (RV-14).
327
+ this.pendingTokens = { in: result.usage.inTok, out: result.usage.outTok, component: 'reviewer' };
314
328
  if (result.kind === 'transient') {
315
329
  // Busy provider: not our fault and not a strike. Keep the cooldown, forget the attempt.
316
- this.watermark = before.watermark;
317
- this.sessionCount = Math.max(0, this.sessionCount - 1);
330
+ this.giveBack(before);
318
331
  await this.record({ ev: 'skipped', detail: `transient:${result.errorType}` });
319
332
  return;
320
333
  }
@@ -327,7 +340,7 @@ export class GeneLearner {
327
340
  this.selfDisabled = true;
328
341
  }
329
342
  // ---- the reply -------------------------------------------------------------------------
330
- async settleReply(text, ctx) {
343
+ async settleReply(text, ctx, before) {
331
344
  const { snapshot, input } = ctx.prepared;
332
345
  const normalized = normalizeLearningOutput(text, {
333
346
  readGeneIds: input.usedIds,
@@ -335,6 +348,15 @@ export class GeneLearner {
335
348
  });
336
349
  this.pendingTokens = { in: ctx.usage.inTok, out: ctx.usage.outTok, component: 'reviewer' };
337
350
  if (normalized.parseFailed === true) {
351
+ // PARSE FIRST, THEN BLAME (RV-18). A reply cut at OUR ceiling is not the tier's fault and not
352
+ // the run's fault: no strike, the watermark rolls back so the next trigger tries again, and
353
+ // the cooldown stays. Without this, three truncations in a row disabled learning for the
354
+ // whole session and the signals they covered were dropped forever (RC-1).
355
+ if (ctx.truncated) {
356
+ this.giveBack(before);
357
+ await this.record({ ev: 'skipped', detail: `truncated:reply=${ctx.replyChars}` });
358
+ return;
359
+ }
338
360
  this.noteStrike();
339
361
  await this.record({ ev: 'error', detail: 'unparseable_reply' });
340
362
  return;
@@ -1,4 +1,4 @@
1
- import { escapeGeneText } from '@aragon-agent/tui/model/gene/escape';
1
+ import { escapeGeneText, unescapeGeneEntities } from '@aragon-agent/tui/model/gene/escape';
2
2
  import { isValidScope, mintProposalId, scopeId } from '@aragon-agent/tui/model/gene/ids';
3
3
  import { GENE_LIMITS, GENE_SCORE } from '@aragon-agent/tui/model/gene/limits';
4
4
  import { dedupeKeyOf, priorityOf } from '@aragon-agent/tui/model/gene/proposal';
@@ -26,10 +26,6 @@ export function resolveScope(kind, session) {
26
26
  function quoteKey(text) {
27
27
  return escapeGeneText(text, 'line');
28
28
  }
29
- /** The model read an entity-escaped prompt and may quote the entities back; undo them once. */
30
- function unescapeEntities(text) {
31
- return text.replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&quot;/g, '"').replace(/&amp;/g, '&');
32
- }
33
29
  /** Check quotes against the ledger, scrub secrets, clip. */
34
30
  export function verifyEvidence(list, snapshot, knownSecrets) {
35
31
  const users = snapshot.users.map((u) => ({ key: quoteKey(u.text), raw: u.text }));
@@ -37,7 +33,7 @@ export function verifyEvidence(list, snapshot, knownSecrets) {
37
33
  let text = entry.text;
38
34
  let trust = entry.trust;
39
35
  if (entry.kind === 'user_statement') {
40
- const keys = [quoteKey(entry.text), quoteKey(unescapeEntities(entry.text))].filter((k) => k.length > 0);
36
+ const keys = [quoteKey(entry.text), quoteKey(unescapeGeneEntities(entry.text))].filter((k) => k.length > 0);
41
37
  const hit = users.find((u) => keys.some((key) => u.key.includes(key)));
42
38
  text = hit ? hit.raw : text;
43
39
  trust = hit ? 'user' : 'untrusted';
@@ -76,6 +76,9 @@ export function createLearnComplete(deps) {
76
76
  const inTok = reply.usage?.inputTokens ?? 0;
77
77
  const outTok = reply.usage?.outputTokens ?? 0;
78
78
  deps.onSpend?.({ inTok, outTok, usd: reply.usage?.cost });
79
- return { text, usage: { inTok, outTok } };
79
+ // The stop reason is the ONLY way to tell "the model wrote a short answer" from "we cut its
80
+ // answer at our own ceiling": every provider fills it and it used to be dropped right here.
81
+ const stop = reply.stopReason === undefined ? {} : { stopReason: reply.stopReason };
82
+ return { text, usage: { inTok, outTok }, ...stop };
80
83
  };
81
84
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aragon-agent/cli",
3
- "version": "0.6.56",
3
+ "version": "0.6.57",
4
4
  "description": "AragonAgent CLI — a Claude-Code / Codex-style interactive terminal UI (TUI) on top of the @aragon-agent/core engine. Installable and runnable via npm / npx.",
5
5
  "license": "MIT",
6
6
  "author": "AragonAgent contributors",
@@ -58,8 +58,8 @@
58
58
  "prepublishOnly": "npm run build"
59
59
  },
60
60
  "dependencies": {
61
- "@aragon-agent/core": "^0.2.68",
62
- "@aragon-agent/tui": "0.0.9",
61
+ "@aragon-agent/core": "^0.2.69",
62
+ "@aragon-agent/tui": "0.0.10",
63
63
  "commander": "^12.1.0",
64
64
  "dotenv": "^16.6.1",
65
65
  "env-paths": "^3.0.0",