@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
@@ -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,57 @@ 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
+ * The failing checks whose reason the curator can act on in the same task, one line each.
128
+ *
129
+ * ONLY K2 AND K3 (RV-17, B3, RC-5). `symbol x8` is a verdict the model cannot act on, and a scope
130
+ * misfit used to arrive with no advice at all - the task ended, the candidate was rejected, and the
131
+ * next attempt rewrote the same draft. K4's answer is deliberately absent: it is recorded on the
132
+ * version and no longer fails the candidate (RC-4), so there is nothing to repair.
133
+ */
134
+ function needsRepair(outcome) {
135
+ return outcome.validation.checks.some((c) => !c.ok && (c.code === 'KNOWLEDGE_EVIDENCE_UNRESOLVED' || c.code === 'KNOWLEDGE_SCOPE_MISFIT'));
136
+ }
137
+ /** What to do about a scope misfit, in words the model can apply to its own draft. */
138
+ const SCOPE_ADVICE = 'the scope does not fit this draft - a specific path or a project name cannot live in the user ' +
139
+ 'scope: move the candidate to a project scope or take the specific path out';
140
+ /** ` To fix: ...` when the failing checks can be made actionable, otherwise nothing. */
141
+ async function fixAdvice(env, head, version, outcome) {
142
+ if (!needsRepair(outcome))
143
+ return '';
144
+ const failing = (code) => outcome.validation.checks.some((c) => !c.ok && c.code === code);
145
+ const lines = [];
146
+ if (failing('KNOWLEDGE_SCOPE_MISFIT'))
147
+ lines.push(SCOPE_ADVICE);
148
+ // The evidence resolution behind the token list is paid work: only K2 needs it.
149
+ if (failing('KNOWLEDGE_EVIDENCE_UNRESOLVED'))
150
+ lines.push(...(await repairsFor(env, head, version.content)));
151
+ return lines.length === 0 ? '' : ` To fix: ${lines.join('. ')}`;
152
+ }
101
153
  /** What a verdict beyond "pass" or "fail" needs done to the library, and what to tell the model. */
102
154
  async function actOnVerdict(env, head, outcome) {
103
155
  if (outcome.verdict === 'needs_human') {
@@ -151,7 +203,8 @@ async function validateCandidate(env, params) {
151
203
  detail: `name=${head.brief.name}`,
152
204
  });
153
205
  const advice = await actOnVerdict(env, head, outcome);
154
- return receipt(`${id} v${v.n}: verdict=${outcome.verdict}. ${summariseChecks(outcome)}.${advice}`);
206
+ const fix = await fixAdvice(env, head, v, outcome);
207
+ return receipt(`${id} v${v.n}: verdict=${outcome.verdict}. ${summariseChecks(outcome)}.${advice}${fix}`);
155
208
  }
156
209
  function validateTool(env) {
157
210
  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 `&&` 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,41 @@
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; four more below):
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
+ * FOUR MORE, LEARNED FROM 25 MEASURED MISSES ON REAL CANDIDATES (RC-3). Each is a shape
27
+ * that cannot be a fact about the run, so checking it only ever produced a false positive:
28
+ * 4. every id this system mints (`gk_`, `gt_`, `gs_`, `pr_`, `ev_`) - "related gene gk_..." is a
29
+ * cross-reference the library asked for, not a claim about the evidence;
30
+ * 5. ONE bare digit with no decimal and no unit word next to it (`step 2`, `exit code 1`). NOT
31
+ * any other number: `1500`, `1.7` and `2 s` (a digit followed by its unit) stay checked, so
32
+ * this file's own control - rounding `1.7 s` to `2 s` must still be caught - still holds;
33
+ * 6. shell syntax: a flag (`--help`, `-x`, `/d`), an operator (`&&`, `||`), a batch variable
34
+ * (`!errorlevel!`, `%errorlevel%`) or an environment assignment (`EXITCODE=0`). Grammar, not
35
+ * values; `encoding='utf-8'` is deliberately NOT one of them - it is a real run fact;
36
+ * 7. a backtick span longer than `MAX_QUOTED_SPAN`: prose wearing quotes. The span is dropped
37
+ * AND the words inside it are never re-scanned - re-pairing the marks is what turned one
38
+ * over-long span into three invented "symbols" on a real candidate.
39
+ *
40
+ * A MISS WE CAUSED OURSELVES IS NOT THE DRAFT'S FAULT. Evidence is clipped with a trailing `...`
41
+ * on its way into the prompt, so a token our own clip explains is reported as `clipped`, not
42
+ * `missing` (RV-13): both when the evidence cut the token's tail and (RC-7) when the draft says
43
+ * MORE than the clipped evidence line did. `probation.ts` then keeps the gene out of harm's way
44
+ * instead of the candidate dying over our own truncation.
45
+ *
46
+ * NO FAILURE MESSAGE MAY CARRY A TOKEN (I-19). Callers report counts per kind only - except the
47
+ * curator's own tool answer, which lists them so the model can fix its draft (RV-17, B3).
17
48
  */
49
+ import { unescapeGeneEntities } from '@aragon-agent/tui/model/gene/escape';
50
+ import { SYSTEM_MINTED_ID_RE } from '@aragon-agent/tui/model/gene/ids';
18
51
  const MAX_TOKENS = 96;
19
52
  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
53
  'html|xml|sql|ini|cfg|conf|env|exe|dll|so|zip|tgz|gz|map|svg|png|csv';
@@ -29,9 +62,34 @@ const ERRNO_RE = /^E[A-Z]{2,15}$/;
29
62
  const UPPER_SNAKE_RE = /^[A-Z][A-Z0-9]*(?:_[A-Z0-9]+)+$/;
30
63
  const COMPILER_CODE_RE = /^(?:TS|CS|CE|LNK|E|W)\d{3,5}$/;
31
64
  const LIST_MARKER_RE = /^\s*(?:[-*+]|\d+[.)])\s+/;
32
- const BACKTICK_RE = /`([^`\n]{2,80})`/g;
65
+ /** A backtick span longer than this is not a citation: it is prose (RC-3 item 7). */
66
+ const MAX_QUOTED_SPAN = 80;
67
+ /** A backtick span shorter than this is punctuation, not a citation. */
68
+ const MIN_QUOTED_SPAN = 2;
69
+ /** `python <file>`, `<path>`, `...`: the model is naming a shape, not asserting a value. */
70
+ const PLACEHOLDER_RE = /<[^<>\n]{0,60}>|\.\.\./;
71
+ /** `198.18.0.x`, `src/*.ts`: a pattern, not a fact. */
72
+ const WILDCARD_SEGMENT_RE = /(?:^|[./\\])(?:x|\*|\?)(?=[./\\]|$)/i;
73
+ /** A single lower-case word in backticks (`desktop`) is emphasis. */
74
+ const PLAIN_WORD_RE = /^[a-z]+$/;
75
+ /** ONE digit on its own: an ordinal or an exit code, not a measurement (RC-3 item 5). */
76
+ const BARE_DIGIT_RE = /^\d$/;
77
+ /** Words that make the number before them a measurement (`2 s`, `1500 ms`). */
78
+ const UNIT_WORDS = new Set([
79
+ 'ms', 's', 'sec', 'secs', 'second', 'seconds', 'min', 'mins', 'minute', 'minutes',
80
+ 'h', 'hr', 'hrs', 'hour', 'hours', 'day', 'days', 'week', 'weeks', 'month', 'months',
81
+ 'kb', 'mb', 'gb', 'tb', 'px', '%',
82
+ ]);
83
+ /** `--help`, `-x`, `/d`: a command switch, which is neither a path nor a value. */
84
+ const FLAG_RE = /^(?:--?[A-Za-z][\w-]*|\/[A-Za-z0-9])$/;
85
+ /** `&&`, `||`, `|`, `>`, `>>`, `<`, `;`: shell grammar. */
86
+ const SHELL_OPERATOR_RE = /^(?:&&|\|\||[|&;<>]|>>|<<|\$\(|\$\?)$/;
87
+ /** `!errorlevel!`, `%errorlevel%`: a batch variable the shell expands. */
88
+ const BATCH_VAR_RE = /^(?:![A-Za-z_]\w*!?|%[A-Za-z_]\w*%?)$/;
89
+ /** `EXITCODE=0`: an assignment whose right-hand side is whatever the run happened to print. */
90
+ const ENV_ASSIGN_RE = /^[A-Z][A-Z0-9_]*=[A-Za-z0-9_%.\\/:-]*$/;
33
91
  function trimWord(word) {
34
- let out = word.replace(/^[("'[{<]+/, '').replace(/[)"'\]}>,;:!?]+$/, '');
92
+ let out = word.replace(/^[("'[{<`]+/, '').replace(/[)"'\]}>,;:!?`]+$/, '');
35
93
  // A sentence-ending dot is not part of the token; a dot inside a name is.
36
94
  while (out.endsWith('.') && out.length > 1)
37
95
  out = out.slice(0, -1);
@@ -55,7 +113,27 @@ function looksLikePath(word) {
55
113
  const directory = /[\\/]$/.test(word);
56
114
  return hasExtension || anchored || directory || segments.length >= 3;
57
115
  }
58
- function classify(word, quoted) {
116
+ /** A quoted span that asserts nothing: a placeholder, a wildcard pattern, or one plain word. */
117
+ function isEmphasisOnly(span) {
118
+ return PLACEHOLDER_RE.test(span) || WILDCARD_SEGMENT_RE.test(span) || PLAIN_WORD_RE.test(span);
119
+ }
120
+ /** Shell grammar rather than a fact the run produced (RC-3 item 6). */
121
+ function isShellSyntax(word) {
122
+ return FLAG_RE.test(word) || SHELL_OPERATOR_RE.test(word) || BATCH_VAR_RE.test(word) || ENV_ASSIGN_RE.test(word);
123
+ }
124
+ /** One digit with no unit beside it is a count ("step 2"), not a measurement ("2 s"). */
125
+ function isBareCount(word, unitAdjacent) {
126
+ return !unitAdjacent && BARE_DIGIT_RE.test(word);
127
+ }
128
+ function classify(word, quoted, unitAdjacent = false) {
129
+ if (SYSTEM_MINTED_ID_RE.test(word))
130
+ return null;
131
+ if (quoted && isEmphasisOnly(word))
132
+ return null;
133
+ if (isShellSyntax(word))
134
+ return null;
135
+ if (isBareCount(word, unitAdjacent))
136
+ return null;
59
137
  if (looksLikePath(word) || FILE_NAME_RE.test(word))
60
138
  return { kind: 'path', text: word };
61
139
  if (quoted)
@@ -70,14 +148,38 @@ function classify(word, quoted) {
70
148
  }
71
149
  return null;
72
150
  }
151
+ /**
152
+ * Split a line into its backticked spans and the text between them. Pairing is POSITIONAL - the
153
+ * leftmost mark with the next one - so a span's LENGTH can never move a mark into a different
154
+ * pair. That is what turned one over-long span into three invented tokens on a real candidate:
155
+ * the old regex simply skipped a span it could not fit and re-paired from the next mark (RC-3
156
+ * item 7). A span is a citation only inside [MIN_QUOTED_SPAN, MAX_QUOTED_SPAN]; outside that
157
+ * range it is dropped AND the text inside it is never re-scanned as individual words.
158
+ */
73
159
  function quotedSpans(line) {
160
+ const marks = [];
161
+ for (let i = 0; i < line.length; i += 1)
162
+ if (line[i] === '`')
163
+ marks.push(i);
74
164
  const spans = [];
75
- const rest = line.replace(BACKTICK_RE, (_whole, inner) => {
76
- spans.push(inner.trim());
77
- return ' ';
78
- });
165
+ let rest = '';
166
+ let at = 0;
167
+ for (let k = 0; k + 1 < marks.length; k += 2) {
168
+ const from = marks[k];
169
+ const to = marks[k + 1];
170
+ const inner = line.slice(from + 1, to).trim();
171
+ if (inner.length >= MIN_QUOTED_SPAN && inner.length <= MAX_QUOTED_SPAN)
172
+ spans.push(inner);
173
+ rest += `${line.slice(at, from)} `;
174
+ at = to + 1;
175
+ }
176
+ rest += line.slice(at);
79
177
  return { rest, spans };
80
178
  }
179
+ /** `2 s`: the digit before a unit word is a measurement, and stays checked. */
180
+ function unitNeighbour(next) {
181
+ return next !== undefined && UNIT_WORDS.has(next.toLowerCase());
182
+ }
81
183
  function pushUnique(out, seen, token) {
82
184
  if (token === null || token.text.length === 0 || out.length >= MAX_TOKENS)
83
185
  return;
@@ -95,8 +197,8 @@ export function extractVerbatimTokens(text) {
95
197
  const { rest, spans } = quotedSpans(rawLine.replace(LIST_MARKER_RE, ''));
96
198
  for (const span of spans)
97
199
  pushUnique(out, seen, classify(span, true));
98
- for (const raw of rest.split(/\s+/))
99
- pushUnique(out, seen, classify(trimWord(raw), false));
200
+ const words = rest.split(/\s+/).map(trimWord);
201
+ words.forEach((word, i) => pushUnique(out, seen, classify(word, false, unitNeighbour(words[i + 1]))));
100
202
  }
101
203
  return out;
102
204
  }
@@ -111,13 +213,55 @@ function numberAppearsIn(text, corpus) {
111
213
  const re = new RegExp(`(?<![0-9A-Za-z_.,])${escapeRegExp(text)}(?![0-9A-Za-z_]|[.,]\\d)`);
112
214
  return re.test(corpus);
113
215
  }
114
- /** Is `token` present verbatim in the evidence `corpus`? Paths compare with one separator. */
115
- export function tokenAppearsIn(token, corpus) {
216
+ /** Does `token` appear in the (already unescaped) evidence `corpus`? Paths compare with one separator. */
217
+ function appearsIn(token, corpus) {
218
+ const needle = unescapeGeneEntities(token.text);
116
219
  if (token.kind === 'number')
117
- return numberAppearsIn(token.text, corpus);
220
+ return numberAppearsIn(needle, corpus);
118
221
  if (token.kind === 'path')
119
- return slashNormal(corpus).includes(slashNormal(token.text));
120
- return corpus.includes(token.text);
222
+ return slashNormal(corpus).includes(slashNormal(needle));
223
+ return corpus.includes(needle);
224
+ }
225
+ /**
226
+ * Is `token` present verbatim in the evidence `corpus`? Both sides are entity-unescaped once: the
227
+ * model read an escaped prompt, so it quotes `&amp;&amp;` for a `&&` the evidence really has.
228
+ */
229
+ export function tokenAppearsIn(token, corpus) {
230
+ return appearsIn(token, unescapeGeneEntities(String(corpus ?? '')));
231
+ }
232
+ /** How many characters of a clipped line's tail we are willing to match against a token. */
233
+ const MAX_CLIP_MATCH = 64;
234
+ /** The longest suffix of `head` that `text` starts with, at least 6 characters or nothing. */
235
+ function sharedSuffixLength(head, text) {
236
+ const max = Math.min(head.length, text.length, MAX_CLIP_MATCH);
237
+ for (let n = max; n >= 6; n -= 1) {
238
+ if (text.startsWith(head.slice(head.length - n)))
239
+ return n;
240
+ }
241
+ return 0;
242
+ }
243
+ /** The text each evidence LINE had before this system clipped it (a clip ends in `...`). */
244
+ function clippedHeads(corpus) {
245
+ return corpus
246
+ .split(/\r?\n/)
247
+ .map((line) => line.trimEnd())
248
+ .filter((line) => line.endsWith('...') && line.length > 6)
249
+ .map((line) => line.slice(0, -3));
250
+ }
251
+ /**
252
+ * Was this miss CAUSED by our own clipping? Only then may it be downgraded (RV-13).
253
+ *
254
+ * BOTH DIRECTIONS, because a clip can lose either end. The evidence side may have ticked off the
255
+ * token's TAIL (`198.18.0.` where the draft says `198.18.0.0/15`), or - RC-7 - the DRAFT may say
256
+ * more than the clipped evidence line ever did (`assert len(body) >= 8, f'expected ...` against a
257
+ * 69-character evidence line that stops at `{len(bod...`). The second direction is not the
258
+ * draft's fault either: `proposal-build.ts` clipped the quote, not the author.
259
+ */
260
+ function looksClipped(token, heads) {
261
+ const text = unescapeGeneEntities(token);
262
+ if (text.length < 6)
263
+ return false;
264
+ return heads.some((head) => sharedSuffixLength(head, text) >= 6 || (head.length >= 6 && text.startsWith(head)));
121
265
  }
122
266
  /** Check every token of `drafted` against `corpus` (all evidence texts joined). */
123
267
  export function findUnsupportedTokens(drafted, corpus) {
@@ -127,8 +271,21 @@ export function findUnsupportedTokens(drafted, corpus) {
127
271
  for (const token of extractVerbatimTokens(text))
128
272
  pushUnique(tokens, seen, token);
129
273
  }
130
- const missing = tokens.filter((token) => !tokenAppearsIn(token, corpus));
131
- return { checked: tokens.length, missing };
274
+ const haystack = unescapeGeneEntities(String(corpus ?? ''));
275
+ // The heads come from the UNESCAPED text too: historical evidence holds `&amp;&amp;` where the
276
+ // draft says `&&`, and a clipped `&&`-line would otherwise never be recognised as clipped (RV-20).
277
+ const heads = clippedHeads(haystack);
278
+ const missing = [];
279
+ const clipped = [];
280
+ for (const token of tokens) {
281
+ if (appearsIn(token, haystack))
282
+ continue;
283
+ if (looksClipped(token.text, heads))
284
+ clipped.push(token);
285
+ else
286
+ missing.push(token);
287
+ }
288
+ return { checked: tokens.length, missing, clipped };
132
289
  }
133
290
  /** `path x1, number x2` - kinds and counts only, never the token text (I-19). */
134
291
  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`. */
@@ -11,6 +12,11 @@ export interface ResolvedEvidence {
11
12
  }
12
13
  /** Resolve cited refs from the snapshot first, then through `readEvidence` (a revise cites old ones). */
13
14
  export declare function resolveEvidence(ports: ValidatorPorts, scope: GeneScope, geneId: string | undefined, content: GeneContent, snapshot: readonly GeneEvidence[]): Promise<ResolvedEvidence>;
15
+ /**
16
+ * The texts K2 actually checks: the body and every claim, with the author's own "what I could not
17
+ * verify" block removed. Exported so a test can pin the check's surface without restating the rule.
18
+ */
19
+ export declare function draftedTexts(content: GeneContent): string[];
14
20
  export interface SourceInput {
15
21
  ports: ValidatorPorts;
16
22
  scope: GeneScope;
@@ -20,6 +26,21 @@ export interface SourceInput {
20
26
  /** Already-resolved evidence, so a caller that needs the corpus too reads each ref once. */
21
27
  resolved?: ResolvedEvidence;
22
28
  }
29
+ export interface SourceResult {
30
+ checks: GeneValidationCheck[];
31
+ /** Misses that OUR clipping explains. The gene may pass, but only on probation (RV-13). */
32
+ clipped: VerbatimToken[];
33
+ }
34
+ /**
35
+ * The CURATOR-ONLY repair line for a failing K2 (RV-17, B3): the missing tokens, verbatim, so the
36
+ * model can cite them or take them out of its draft in the same task.
37
+ *
38
+ * WHY IT IS NOT ON THE OUTCOME. `CandidateOutcome` is logged and stored, and a stored detail may
39
+ * never echo gene or evidence text (I-19) - the `poison-untrusted` case fails the moment a token
40
+ * leaves through it. This string is built at the tool boundary instead, from the model's own draft
41
+ * and its own evidence, and exists only in that one tool answer.
42
+ */
43
+ export declare function repairLines(content: GeneContent, corpus: string): string[];
23
44
  /** 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[]>;
45
+ export declare function checkSource(input: SourceInput): Promise<SourceResult>;
25
46
  export declare function validateKnowledge(ctx: CandidateContext, report: StaticReport): Promise<TypeResult>;