@aragon-agent/cli 0.6.57 → 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 (85) hide show
  1. package/CHANGELOG.md +71 -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/task-runner.js +4 -1
  28. package/dist/gene/curator/tools-verify.js +17 -5
  29. package/dist/gene/curator/validate/evidence-tokens.js +97 -18
  30. package/dist/gene/curator/validate/knowledge.d.ts +5 -0
  31. package/dist/gene/curator/validate/knowledge.js +57 -13
  32. package/dist/gene/curator/validate/types.d.ts +6 -1
  33. package/dist/gene/learn/learn-prompt.d.ts +10 -1
  34. package/dist/gene/learn/learn-prompt.js +11 -2
  35. package/dist/governance/engine/lifecycle.js +1 -1
  36. package/dist/governance/store/run-lock.d.ts +9 -2
  37. package/dist/governance/store/run-lock.js +91 -7
  38. package/dist/host/controller-factory.d.ts +13 -0
  39. package/dist/host/controller-factory.js +7 -0
  40. package/dist/host/index.d.ts +1 -0
  41. package/dist/host/index.js +1 -0
  42. package/dist/host/interaction.d.ts +19 -0
  43. package/dist/host/interaction.js +75 -0
  44. package/dist/host/team-control.d.ts +83 -0
  45. package/dist/host/team-control.js +55 -0
  46. package/dist/logging/install.d.ts +32 -1
  47. package/dist/logging/install.js +21 -0
  48. package/dist/proc/output-streams.d.ts +11 -0
  49. package/dist/proc/output-streams.js +11 -0
  50. package/dist/redteam/prompt-resolve.d.ts +61 -0
  51. package/dist/redteam/prompt-resolve.js +303 -0
  52. package/dist/redteam/prompt-store.d.ts +96 -0
  53. package/dist/redteam/prompt-store.js +156 -0
  54. package/dist/redteam/prompt-template.d.ts +22 -0
  55. package/dist/redteam/prompt-template.js +72 -0
  56. package/dist/team/bus.d.ts +18 -0
  57. package/dist/team/bus.js +70 -18
  58. package/dist/team/console-tools.d.ts +54 -0
  59. package/dist/team/console-tools.js +333 -0
  60. package/dist/team/console-view.d.ts +88 -0
  61. package/dist/team/console-view.js +173 -0
  62. package/dist/team/forced-mode.d.ts +61 -1
  63. package/dist/team/forced-mode.js +75 -0
  64. package/dist/team/normalize.d.ts +31 -0
  65. package/dist/team/normalize.js +49 -5
  66. package/dist/team/notices.d.ts +95 -0
  67. package/dist/team/notices.js +121 -0
  68. package/dist/team/pause-gate.d.ts +79 -0
  69. package/dist/team/pause-gate.js +127 -0
  70. package/dist/team/prompt.d.ts +25 -9
  71. package/dist/team/prompt.js +29 -29
  72. package/dist/team/report.js +33 -0
  73. package/dist/team/runtime.d.ts +270 -5
  74. package/dist/team/runtime.js +732 -64
  75. package/dist/team/settled.d.ts +5 -2
  76. package/dist/team/settled.js +12 -2
  77. package/dist/team/subagent.d.ts +7 -0
  78. package/dist/team/subagent.js +12 -1
  79. package/dist/team/task-tool.d.ts +39 -1
  80. package/dist/team/task-tool.js +75 -18
  81. package/dist/tools/bash-tool.d.ts +11 -8
  82. package/dist/tools/bash-tool.js +37 -9
  83. package/dist/tools/index.d.ts +2 -2
  84. package/dist/tools/index.js +30 -0
  85. package/package.json +3 -3
@@ -124,18 +124,30 @@ async function repairsFor(env, head, content) {
124
124
  }
125
125
  }
126
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.
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.
130
133
  */
131
134
  function needsRepair(outcome) {
132
- return outcome.validation.checks.some((c) => !c.ok && c.code === 'KNOWLEDGE_EVIDENCE_UNRESOLVED');
135
+ return outcome.validation.checks.some((c) => !c.ok && (c.code === 'KNOWLEDGE_EVIDENCE_UNRESOLVED' || c.code === 'KNOWLEDGE_SCOPE_MISFIT'));
133
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';
134
140
  /** ` To fix: ...` when the failing checks can be made actionable, otherwise nothing. */
135
141
  async function fixAdvice(env, head, version, outcome) {
136
142
  if (!needsRepair(outcome))
137
143
  return '';
138
- const lines = await repairsFor(env, head, version.content);
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)));
139
151
  return lines.length === 0 ? '' : ` To fix: ${lines.join('. ')}`;
140
152
  }
141
153
  /** What a verdict beyond "pass" or "fail" needs done to the library, and what to tell the model. */
@@ -13,7 +13,7 @@
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
- * THREE CORRECTIONS LEARNED FROM REAL CANDIDATES (RC-3):
16
+ * THREE CORRECTIONS LEARNED FROM REAL CANDIDATES (RC-3; four more below):
17
17
  * 1. an evidence REF (`ev_1a2b3c4d`) is an id this system minted, never a fact, so it is not a
18
18
  * token at all - the curator is TOLD to cite refs, so treating one as "must appear in the
19
19
  * evidence" is a guaranteed miss (RV-8);
@@ -23,15 +23,31 @@
23
23
  * lower-case word (`desktop`) is emphasis, not an assertion. Narrowing only these three
24
24
  * enumerable shapes keeps an invented path or symbol caught (RV-13, B2c).
25
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
+ *
26
40
  * 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.
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.
30
45
  *
31
46
  * NO FAILURE MESSAGE MAY CARRY A TOKEN (I-19). Callers report counts per kind only - except the
32
47
  * curator's own tool answer, which lists them so the model can fix its draft (RV-17, B3).
33
48
  */
34
49
  import { unescapeGeneEntities } from '@aragon-agent/tui/model/gene/escape';
50
+ import { SYSTEM_MINTED_ID_RE } from '@aragon-agent/tui/model/gene/ids';
35
51
  const MAX_TOKENS = 96;
36
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|' +
37
53
  'html|xml|sql|ini|cfg|conf|env|exe|dll|so|zip|tgz|gz|map|svg|png|csv';
@@ -46,17 +62,34 @@ const ERRNO_RE = /^E[A-Z]{2,15}$/;
46
62
  const UPPER_SNAKE_RE = /^[A-Z][A-Z0-9]*(?:_[A-Z0-9]+)+$/;
47
63
  const COMPILER_CODE_RE = /^(?:TS|CS|CE|LNK|E|W)\d{3,5}$/;
48
64
  const LIST_MARKER_RE = /^\s*(?:[-*+]|\d+[.)])\s+/;
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}$/;
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;
52
69
  /** `python <file>`, `<path>`, `...`: the model is naming a shape, not asserting a value. */
53
70
  const PLACEHOLDER_RE = /<[^<>\n]{0,60}>|\.\.\./;
54
71
  /** `198.18.0.x`, `src/*.ts`: a pattern, not a fact. */
55
72
  const WILDCARD_SEGMENT_RE = /(?:^|[./\\])(?:x|\*|\?)(?=[./\\]|$)/i;
56
73
  /** A single lower-case word in backticks (`desktop`) is emphasis. */
57
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_%.\\/:-]*$/;
58
91
  function trimWord(word) {
59
- let out = word.replace(/^[("'[{<]+/, '').replace(/[)"'\]}>,;:!?]+$/, '');
92
+ let out = word.replace(/^[("'[{<`]+/, '').replace(/[)"'\]}>,;:!?`]+$/, '');
60
93
  // A sentence-ending dot is not part of the token; a dot inside a name is.
61
94
  while (out.endsWith('.') && out.length > 1)
62
95
  out = out.slice(0, -1);
@@ -84,11 +117,23 @@ function looksLikePath(word) {
84
117
  function isEmphasisOnly(span) {
85
118
  return PLACEHOLDER_RE.test(span) || WILDCARD_SEGMENT_RE.test(span) || PLAIN_WORD_RE.test(span);
86
119
  }
87
- function classify(word, quoted) {
88
- if (EVIDENCE_REF_RE.test(word))
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))
89
130
  return null;
90
131
  if (quoted && isEmphasisOnly(word))
91
132
  return null;
133
+ if (isShellSyntax(word))
134
+ return null;
135
+ if (isBareCount(word, unitAdjacent))
136
+ return null;
92
137
  if (looksLikePath(word) || FILE_NAME_RE.test(word))
93
138
  return { kind: 'path', text: word };
94
139
  if (quoted)
@@ -103,14 +148,38 @@ function classify(word, quoted) {
103
148
  }
104
149
  return null;
105
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
+ */
106
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);
107
164
  const spans = [];
108
- const rest = line.replace(BACKTICK_RE, (_whole, inner) => {
109
- spans.push(inner.trim());
110
- return ' ';
111
- });
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);
112
177
  return { rest, spans };
113
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
+ }
114
183
  function pushUnique(out, seen, token) {
115
184
  if (token === null || token.text.length === 0 || out.length >= MAX_TOKENS)
116
185
  return;
@@ -128,8 +197,8 @@ export function extractVerbatimTokens(text) {
128
197
  const { rest, spans } = quotedSpans(rawLine.replace(LIST_MARKER_RE, ''));
129
198
  for (const span of spans)
130
199
  pushUnique(out, seen, classify(span, true));
131
- for (const raw of rest.split(/\s+/))
132
- 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]))));
133
202
  }
134
203
  return out;
135
204
  }
@@ -179,10 +248,20 @@ function clippedHeads(corpus) {
179
248
  .filter((line) => line.endsWith('...') && line.length > 6)
180
249
  .map((line) => line.slice(0, -3));
181
250
  }
182
- /** Was this miss CAUSED by our own clipping? Only then may it be downgraded (RV-13). */
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
+ */
183
260
  function looksClipped(token, heads) {
184
261
  const text = unescapeGeneEntities(token);
185
- return text.length >= 6 && heads.some((head) => sharedSuffixLength(head, text) >= 6);
262
+ if (text.length < 6)
263
+ return false;
264
+ return heads.some((head) => sharedSuffixLength(head, text) >= 6 || (head.length >= 6 && text.startsWith(head)));
186
265
  }
187
266
  /** Check every token of `drafted` against `corpus` (all evidence texts joined). */
188
267
  export function findUnsupportedTokens(drafted, corpus) {
@@ -12,6 +12,11 @@ export interface ResolvedEvidence {
12
12
  }
13
13
  /** Resolve cited refs from the snapshot first, then through `readEvidence` (a revise cites old ones). */
14
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[];
15
20
  export interface SourceInput {
16
21
  ports: ValidatorPorts;
17
22
  scope: GeneScope;
@@ -13,6 +13,11 @@
13
13
  * K3 scope a temporary preference only in the task scope; a specific path or a project
14
14
  * name cannot live in the user scope; environment-bound claims carry applicability
15
15
  * K4 supported model: do the evidence texts support the draft? (skipped when a user said it)
16
+ * A "no" is RECORDED, not a veto (RC-4). Everything an agent publishes
17
+ * already starts on probation - visible, double-weighted, revoked after it misleads
18
+ * twice (`probation.ts`, `plan-content.ts`). Refusing here was a second, harsher
19
+ * risk model fighting the library's own; it also made every candidate whose
20
+ * evidence was thinner than its draft unpublishable for good.
16
21
  * K5 conflict neighbour relations (see `conflicts.ts`)
17
22
  * K6 trust all-untrusted evidence waits for a person (TH-1)
18
23
  *
@@ -21,6 +26,7 @@
21
26
  import { promises as nodeFs } from 'node:fs';
22
27
  import { preferenceHorizonFitsScope, normalizedApplicabilityOf } from '@aragon-agent/tui/model/gene/validate';
23
28
  import { runConflictCheck } from '../conflicts.js';
29
+ import { LEARN_UNVERIFIED_HEADING } from '../../learn/learn-prompt.js';
24
30
  import { addUsage, failCheck, okCheck, skippedCheck, splitIssues, staticCheck, trustCheck, } from './common.js';
25
31
  import { extractVerbatimTokens, findUnsupportedTokens, summarizeMissing, } from './evidence-tokens.js';
26
32
  import { liveCheckEvidence } from './live-check.js';
@@ -56,9 +62,45 @@ export async function resolveEvidence(ports, scope, geneId, content, snapshot) {
56
62
  }
57
63
  return { corpus: [...byRef.values()], unresolved };
58
64
  }
59
- function draftedTexts(content) {
65
+ /**
66
+ * The block an author writes to say what it could NOT verify (RC-2). One heading, matched
67
+ * from its first words, opened at the start of a line and closed by the next markdown heading.
68
+ *
69
+ * WHY THIS EXISTS. K2 reads a draft LEXICALLY: it cannot tell an assertion from the sentence
70
+ * "these names appear in no evidence ref, so none is recommended here", so it scored a draft
71
+ * HONESTY as fabrication - 10 of the 25 measured misses on real candidates came from such a
72
+ * paragraph. A candidate must not have to claim it verified something it did not.
73
+ *
74
+ * WHY IT IS NOT A HOLE. The block is only dropped when the rest of the draft still says something
75
+ * checkable: a draft that puts EVERYTHING under the heading keeps its full text and is checked
76
+ * exactly as before. And K1's injection screen still reads the whole body, heading included, so
77
+ * the block cannot carry an instruction either.
78
+ */
79
+ const UNVERIFIED_HEADING_RE = new RegExp(`^\\s*(?:#{1,6}\\s*)?${LEARN_UNVERIFIED_HEADING}\\b`, 'i');
80
+ const NEXT_HEADING_RE = /^\s*#{1,6}\s+\S/;
81
+ function stripUnverified(text) {
82
+ const kept = [];
83
+ let inside = false;
84
+ for (const line of text.split(/\r?\n/)) {
85
+ if (UNVERIFIED_HEADING_RE.test(line)) {
86
+ inside = true;
87
+ continue;
88
+ }
89
+ if (inside && NEXT_HEADING_RE.test(line))
90
+ inside = false;
91
+ if (!inside)
92
+ kept.push(line);
93
+ }
94
+ const out = kept.join('\n');
95
+ return out.trim().length === 0 ? text : out;
96
+ }
97
+ /**
98
+ * The texts K2 actually checks: the body and every claim, with the author's own "what I could not
99
+ * verify" block removed. Exported so a test can pin the check's surface without restating the rule.
100
+ */
101
+ export function draftedTexts(content) {
60
102
  const claims = (payloadOf(content).claims ?? []).map((c) => String(c?.text ?? ''));
61
- return [String(content.body ?? ''), ...claims];
103
+ return [String(content.body ?? ''), ...claims].map(stripUnverified);
62
104
  }
63
105
  async function rootIsDirectory(root) {
64
106
  const stat = await nodeFs.stat(root).catch(() => null);
@@ -183,26 +225,26 @@ function checkScope(ctx, at) {
183
225
  out.push(failCheck('KNOWLEDGE_SCOPE_MISFIT', at, `K3 ${problems.join('; ')}`));
184
226
  return out.length > 0 ? out : [okCheck('K3', at)];
185
227
  }
186
- // ---------------------------------------------------------------------------
187
- // K4 - supported by the evidence
188
- // ---------------------------------------------------------------------------
189
228
  async function checkSupported(ctx, corpus, usage) {
190
229
  const at = ctx.ports.now();
191
230
  if (corpus.some((e) => e.kind === 'user_statement' && e.trust !== 'untrusted')) {
192
- return okCheck('K4', at, 'a user statement is sufficient');
231
+ return { check: okCheck('K4', at, 'a user statement is sufficient'), forceProbation: false };
193
232
  }
194
233
  const prompt = buildSupportPrompt(draftedTexts(ctx.content).join('\n'), corpus.map((e) => e.text));
195
234
  const answer = await askModel(ctx.ports, prompt.system, prompt.user);
196
235
  if (!answer.ok)
197
- return skippedCheck('K4', at, answer.reason);
236
+ return { check: skippedCheck('K4', at, answer.reason), forceProbation: false };
198
237
  addUsage(usage, answer.usage);
199
238
  const supported = parseSupportAnswer(answer.json);
239
+ // A model output we could not read is NOT a "no": it is recorded as skipped, never as support.
200
240
  if (supported === null)
201
- return skippedCheck('K4', at, 'bad_model_output');
241
+ return { check: skippedCheck('K4', at, 'bad_model_output'), forceProbation: false };
202
242
  const extras = { by: 'model', ...(answer.model ? { model: answer.model } : {}), durationMs: answer.durationMs };
203
- return supported
204
- ? okCheck('K4', at, undefined, extras)
205
- : failCheck('KNOWLEDGE_UNSUPPORTED', at, 'K4 the evidence does not support the draft', extras);
243
+ if (supported)
244
+ return { check: okCheck('K4', at, undefined, extras), forceProbation: false };
245
+ // The answer is kept verbatim in the version file, so a reviewer can still find every gene whose
246
+ // support was doubted. What it no longer does is outrank the library's own probation rules.
247
+ return { check: okCheck('K4', at, 'not supported by the evidence', extras), forceProbation: true };
206
248
  }
207
249
  // ---------------------------------------------------------------------------
208
250
  // Entry point
@@ -233,7 +275,8 @@ export async function validateKnowledge(ctx, report) {
233
275
  checks.push(okCheck('KNOWLEDGE_EVIDENCE_CLIPPED', at, `K2 ${count} only missing because the evidence was clipped`));
234
276
  }
235
277
  checks.push(...checkScope(ctx, at));
236
- checks.push(await checkSupported(ctx, resolved.corpus, usage));
278
+ const support = await checkSupported(ctx, resolved.corpus, usage);
279
+ checks.push(support.check);
237
280
  const conflict = await runConflictCheck(ctx.ports, {
238
281
  type: 'knowledge',
239
282
  scope: ctx.scope,
@@ -245,11 +288,12 @@ export async function validateKnowledge(ctx, report) {
245
288
  const trust = trustCheck(ctx.evidence, at);
246
289
  checks.push(trust.check);
247
290
  const needsHuman = trust.needsHuman ?? (conflict.decision.action === 'needs_human' ? conflict.decision.reason : undefined);
291
+ const probation = source.clipped.length > 0 || support.forceProbation;
248
292
  return {
249
293
  checks,
250
294
  conflict: conflict.decision,
251
295
  usage,
252
296
  ...(needsHuman === undefined ? {} : { needsHuman }),
253
- ...(source.clipped.length > 0 ? { forceProbation: true } : {}),
297
+ ...(probation ? { forceProbation: true } : {}),
254
298
  };
255
299
  }
@@ -76,7 +76,12 @@ export interface CandidateOutcome {
76
76
  needsHuman?: GeneNeedsHuman['reason'];
77
77
  conflict?: ConflictDecision;
78
78
  probation?: GeneProbation;
79
- /** A model check could not run for lack of positives / a model: the gene must be on probation. */
79
+ /**
80
+ * A model check could not run for lack of positives / a model, or answered "not supported": the
81
+ * gene must be on probation. RECORDED, not enforced here - an agent's publish is stamped with
82
+ * probation unconditionally (`plan-content.ts` -> `startProbation`), and this flag is what tells
83
+ * the manager UI and the run log that the support was doubted (RC-4).
84
+ */
80
85
  forceProbation: boolean;
81
86
  /** The class the gene will be stored with (an agent draft of `oversight` is demoted). */
82
87
  class: GeneClass;
@@ -1,6 +1,15 @@
1
1
  import type { LearningSignal } from '@aragon-agent/tui/model/gene/signals';
2
2
  import type { LedgerSnapshot } from './ledger.js';
3
- export declare const GENE_LEARN_PROMPT_VERSION = "v1-2026-11";
3
+ export declare const GENE_LEARN_PROMPT_VERSION = "v2-2026-11";
4
+ /**
5
+ * The ONE heading under which a draft states what it could NOT verify (RC-2).
6
+ *
7
+ * It lives here, next to the rules that ask the model to write it, and the validator imports this
8
+ * same constant - two spellings of one convention is how a prompt and a check drift apart. The
9
+ * block is exempt from the verbatim-token check (`curator/validate/knowledge.ts`), so the reviewer
10
+ * no longer has to claim it verified something the evidence never showed it.
11
+ */
12
+ export declare const LEARN_UNVERIFIED_HEADING = "Not established";
4
13
  export declare const LEARN_INPUT_LIMITS: {
5
14
  readonly sectionsMaxBytes: number;
6
15
  readonly totalMaxBytes: number;
@@ -24,7 +24,16 @@
24
24
  * whatever the 48 KB total allows, in WHOLE lines (a clipped tier-1 line is a different gene).
25
25
  */
26
26
  import { clipEscaped, escapeGeneText } from '@aragon-agent/tui/model/gene/escape';
27
- export const GENE_LEARN_PROMPT_VERSION = 'v1-2026-11';
27
+ export const GENE_LEARN_PROMPT_VERSION = 'v2-2026-11';
28
+ /**
29
+ * The ONE heading under which a draft states what it could NOT verify (RC-2).
30
+ *
31
+ * It lives here, next to the rules that ask the model to write it, and the validator imports this
32
+ * same constant - two spellings of one convention is how a prompt and a check drift apart. The
33
+ * block is exempt from the verbatim-token check (`curator/validate/knowledge.ts`), so the reviewer
34
+ * no longer has to claim it verified something the evidence never showed it.
35
+ */
36
+ export const LEARN_UNVERIFIED_HEADING = 'Not established';
28
37
  export const LEARN_INPUT_LIMITS = {
29
38
  sectionsMaxBytes: 14 * 1024,
30
39
  totalMaxBytes: 48 * 1024,
@@ -53,7 +62,7 @@ export const LEARN_SYSTEM_PROMPT = [
53
62
  '1. attributions: give exactly one entry for EVERY gene listed in GENES_USED, using its id. Say "helped" or "harmed" ONLY when the text that followed the read shows clear evidence caused by following that entry, and put that evidence in "ev". Never judge an entry by whether the whole task succeeded or failed. When unsure write "unknown".',
54
63
  '2. When "decision" is "none", "proposals" must be empty. Make at most 3 proposals. Prefer none: a run with nothing new is the common, correct answer.',
55
64
  '3. A "create" proposal needs type, scope and title. Every other kind needs "target", an id taken from EXISTING or GENES_USED; "merge" also lists "mergeFrom". Never invent an id.',
56
- '4. Write title, why, expectedBenefit and everything under draft in English. Keep file paths, code symbols, error codes and numbers exactly as they appear. Quote evidence verbatim in its original language and never paraphrase it.',
65
+ '4. Write title, why, expectedBenefit and everything under draft in English. Keep file paths, code symbols, error codes and numbers exactly as they appear. Quote evidence verbatim in its original language and never paraphrase it. Write in draft.body only what the LEDGER shows you: a fact you cannot point at in the ledger does not belong in the body. When part of the lesson rests on something the run did not show, put it under ONE final section whose heading line starts with the words "Not established" (a "## " prefix is allowed) and say there what you could not confirm - that section is never treated as a claim.',
57
66
  '5. scope "user" is for standing preferences and facts about this person, "project" for facts about this codebase, "task" for what only matters to this session.',
58
67
  '6. A user statement about how things should be done is a preference; mark it with payload.kind "preference". Never state a preference the user did not express.',
59
68
  '7. Do not include secrets, tokens, personal data, or long code listings. Do not include instructions that tell a reader to ignore rules or reveal anything.',
@@ -291,7 +291,7 @@ async function createRun(core, c) {
291
291
  : null;
292
292
  const flushNote = await core.flush();
293
293
  const digest = startDigest(core, c.notes, chunkNote);
294
- return flushNote === null ? digest : `${digest}
294
+ return flushNote === null ? digest : `${digest}
295
295
  ${flushNote}`;
296
296
  }
297
297
  /** DEV per WP in WP order, REV / TEST by `rosterSizes` (5.2). Logged as ledger ops. */
@@ -47,9 +47,16 @@ export declare function defaultIsPidAlive(pid: number): boolean;
47
47
  export declare function readLock(path: string, fs?: GovFs): Promise<LockInfo | null>;
48
48
  /** True when a lock must be honoured: fresh heartbeat AND a living holder. */
49
49
  export declare function isLockLive(info: LockInfo | null, deps: LockDeps): boolean;
50
- /** Take the lock, or explain who holds it. Never throws for contention. */
50
+ /**
51
+ * Take the lock, or explain who holds it. Never throws for contention.
52
+ *
53
+ * THE WINNER IS THE ONE WHO CREATES, NOT THE ONE WHO READS LAST. Between `open(wx)` and the
54
+ * `write` that follows it the file exists and is empty, and that empty file must not be readable
55
+ * as "nobody has it": `readLockState` distinguishes it, and `TORN_LOCK_GRACE_MS` bounds how long
56
+ * a genuinely abandoned one may block a takeover.
57
+ */
51
58
  export declare function acquireLock(path: string, deps: LockDeps): Promise<AcquireResult>;
52
59
  /** Refresh `heartbeatAt`. Returns false when the lock is no longer ours (lost or removed). */
53
60
  export declare function refreshLock(path: string, deps: LockDeps): Promise<boolean>;
54
- /** Remove the lock only if it is ours; a foreign lock is left untouched. */
61
+ /** Remove the lock only if it is ours; a foreign - or not-yet-written - lock is left untouched. */
55
62
  export declare function removeLock(path: string, deps: LockDeps): Promise<void>;
@@ -45,6 +45,64 @@ export async function readLock(path, fs = nodeGovFs) {
45
45
  return null;
46
46
  }
47
47
  }
48
+ /**
49
+ * Longest a lock file may stay UNPARSABLE before it is judged a crash rather than a write
50
+ * already in progress.
51
+ *
52
+ * A lock is born empty: `tryExclusiveCreate` succeeds on `open(wx)` and the JSON arrives a
53
+ * moment later with `write` + `sync`. Any process that reads the file inside that window gets
54
+ * `JSON.parse('')`. Calling that "no lock" is how TWO processes end up holding one lock - the
55
+ * second overwrites the file on Windows (POSIX replaces it even while the handle is open) and
56
+ * both enter the critical section, which is a lost update rather than an error
57
+ * (`policy.test.ts` AC-59: 11 of 12 exclusions survived, only under load).
58
+ *
59
+ * 2 s is ~1000x the cost of the write it is waiting for, and still short enough that a process
60
+ * that crashed between create and write cannot wedge a lock forever.
61
+ */
62
+ const TORN_LOCK_GRACE_MS = 2_000;
63
+ async function readLockState(path, fs) {
64
+ let text;
65
+ try {
66
+ text = await fs.readFile(path);
67
+ }
68
+ catch {
69
+ return { state: 'absent' };
70
+ }
71
+ try {
72
+ const parsed = JSON.parse(text);
73
+ if (isLockInfo(parsed))
74
+ return { state: 'held', info: parsed };
75
+ }
76
+ catch {
77
+ // Fall through: the file is there but holds no record.
78
+ }
79
+ const state = text.trim().length === 0 ? 'empty' : 'corrupt';
80
+ try {
81
+ return { state, mtimeMs: (await fs.stat(path)).mtimeMs };
82
+ }
83
+ catch {
84
+ return { state, mtimeMs: null };
85
+ }
86
+ }
87
+ /**
88
+ * True when an unparsable lock file has been that way long enough to be a crash. An
89
+ * unreadable `mtimeMs` is treated as recent: we cannot prove it is old, and taking over a
90
+ * lock somebody is writing is the failure this whole check exists to prevent.
91
+ */
92
+ function tornLockIsAbandoned(mtimeMs, deps) {
93
+ if (mtimeMs === null)
94
+ return false;
95
+ return deps.now() - mtimeMs >= TORN_LOCK_GRACE_MS;
96
+ }
97
+ function tornRefusal() {
98
+ return {
99
+ ok: false,
100
+ // No process can be named: the file does not hold a record yet. Callers that display the
101
+ // holder treat 0 as "unknown", and every caller already handles `ok: false` by waiting.
102
+ holderPid: 0,
103
+ message: 'NOT ACCEPTED: another process is taking this lock right now. Try again in a moment.',
104
+ };
105
+ }
48
106
  /** True when a lock must be honoured: fresh heartbeat AND a living holder. */
49
107
  export function isLockLive(info, deps) {
50
108
  if (!info)
@@ -91,19 +149,40 @@ async function tryExclusiveCreate(path, deps) {
91
149
  }
92
150
  return true;
93
151
  }
94
- /** Take the lock, or explain who holds it. Never throws for contention. */
152
+ /**
153
+ * Take the lock, or explain who holds it. Never throws for contention.
154
+ *
155
+ * THE WINNER IS THE ONE WHO CREATES, NOT THE ONE WHO READS LAST. Between `open(wx)` and the
156
+ * `write` that follows it the file exists and is empty, and that empty file must not be readable
157
+ * as "nobody has it": `readLockState` distinguishes it, and `TORN_LOCK_GRACE_MS` bounds how long
158
+ * a genuinely abandoned one may block a takeover.
159
+ */
95
160
  export async function acquireLock(path, deps) {
96
161
  const fs = deps.fs ?? nodeGovFs;
97
162
  if (await tryExclusiveCreate(path, deps))
98
163
  return { ok: true, takenOver: false };
99
- const existing = await readLock(path, fs);
164
+ const read = await readLockState(path, fs);
165
+ if (read.state === 'empty' && !tornLockIsAbandoned(read.mtimeMs, deps)) {
166
+ return tornRefusal();
167
+ }
168
+ const existing = read.state === 'held' ? read.info : null;
100
169
  if (isLockLive(existing, deps))
101
170
  return refusal(existing, deps);
102
- await atomicWriteFile(path, freshLockText(deps), { fs });
171
+ try {
172
+ await atomicWriteFile(path, freshLockText(deps), { fs });
173
+ }
174
+ catch {
175
+ // A replace that the platform refuses (Windows reports EPERM while the winner still holds
176
+ // its `wx` handle open) is contention, not a failure: the caller's contract is `ok: false`,
177
+ // and a thrown EPERM out of here reads as an application bug to every caller.
178
+ return tornRefusal();
179
+ }
103
180
  const confirmed = await readLock(path, fs);
104
181
  if (confirmed && confirmed.pid !== deps.pid)
105
182
  return refusal(confirmed, deps);
106
- return { ok: true, takenOver: existing !== null };
183
+ // A file we found `held` - or an empty one we waited out - was replaced, which is a takeover
184
+ // even when it held no record to read (the crashed-writer case).
185
+ return { ok: true, takenOver: read.state !== 'absent' };
107
186
  }
108
187
  /** Refresh `heartbeatAt`. Returns false when the lock is no longer ours (lost or removed). */
109
188
  export async function refreshLock(path, deps) {
@@ -114,11 +193,16 @@ export async function refreshLock(path, deps) {
114
193
  await atomicWriteFile(path, freshLockText(deps, existing.startedAt), { fs });
115
194
  return true;
116
195
  }
117
- /** Remove the lock only if it is ours; a foreign lock is left untouched. */
196
+ /** Remove the lock only if it is ours; a foreign - or not-yet-written - lock is left untouched. */
118
197
  export async function removeLock(path, deps) {
119
198
  const fs = deps.fs ?? nodeGovFs;
120
- const existing = await readLock(path, fs);
121
- if (existing && existing.pid !== deps.pid)
199
+ // `absent` is nothing to remove and `empty` is a lock being born by somebody else: unlinking
200
+ // it would delete a lock we do not own - the same double-owner window `acquireLock` refuses.
201
+ // `corrupt` is unowned garbage and has always been removable.
202
+ const read = await readLockState(path, fs);
203
+ if (read.state === 'held' && read.info.pid !== deps.pid)
204
+ return;
205
+ if (read.state === 'absent' || read.state === 'empty')
122
206
  return;
123
207
  await fs.unlink(path).catch(() => undefined);
124
208
  }
@@ -95,6 +95,19 @@ export declare function makeController(flags: CliFlags, opts?: {
95
95
  * sessions' prompts and tools byte-identical (I-1).
96
96
  */
97
97
  redTeamArmed?: boolean;
98
+ /**
99
+ * `--redteam-prompt <path>`: this session's prompt profile (redteam-prompt-profile S-12).
100
+ *
101
+ * THE SAME CHANNEL AS `redTeamArmed`, and for the same reason: the flag has to reach
102
+ * `RedTeamWiring`, and `validateRedTeamLaunch`'s `decision` is discarded at its only call
103
+ * site, so a field added there would never be read. An unreadable path is a WARNING at the
104
+ * first assembly, never a launch refusal (AC-22).
105
+ *
106
+ * THIS BAG IS SPREAD, NOT PASSED WHOLE (see the note above the deps literal): a key that is
107
+ * declared here but not spread below is dropped in silence, which is what made this flag
108
+ * inert once already.
109
+ */
110
+ redTeamPromptPath?: string;
98
111
  }): {
99
112
  controller: AgentController;
100
113
  confirmBridge: ConfirmBridge;
@@ -124,6 +124,13 @@ export function makeController(flags, opts = { interactive: true }) {
124
124
  // deps bag it always did; the value is already the output of `validateRedTeamLaunch`, which
125
125
  // is the only place allowed to refuse it.
126
126
  ...(opts.redTeamArmed === true ? { redTeamArmed: true } : {}),
127
+ // `--redteam-prompt` (redteam-prompt-profile S-12 / IF-4). THE SAME TRAP AS THE R3 PAIR
128
+ // ABOVE: this factory forwards only what is named here, so the flag's only route to
129
+ // `RedTeamWiring.promptPath` is this spread. Absent stays absent, keeping a launch without
130
+ // the flag byte-identical to the pre-feature build.
131
+ ...(opts.redTeamPromptPath === undefined
132
+ ? {}
133
+ : { redTeamPromptPath: opts.redTeamPromptPath }),
127
134
  });
128
135
  return { controller, confirmBridge, humanInputBridge };
129
136
  }
@@ -23,3 +23,4 @@ export * from './settings.js';
23
23
  export * from './commands.js';
24
24
  export * from './skills.js';
25
25
  export * from './index-build.js';
26
+ export * from './team-control.js';
@@ -23,3 +23,4 @@ export * from './settings.js';
23
23
  export * from './commands.js';
24
24
  export * from './skills.js';
25
25
  export * from './index-build.js';
26
+ export * from './team-control.js';