@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
@@ -261,11 +261,15 @@ export declare function attachAgentEvents(logger: Logger, controller: AgentEvent
261
261
  export interface TeamEventSource {
262
262
  subscribeTeam?(listener: (event: TeamLogEvent) => void): () => void;
263
263
  }
264
- /** The five members of the CLI-local `TeamEvent` union, as this module reads them. */
264
+ /** The seven members of the CLI-local `TeamEvent` union, as this module reads them. */
265
265
  export type TeamLogEvent = {
266
266
  type: 'dispatch_start';
267
267
  dispatchId: string;
268
268
  requested: number;
269
+ /** The turn that started it (team-detached-dispatch I-DD11). */
270
+ turnId?: number;
271
+ /** True when the dispatch outlives the `task` call that started it. */
272
+ detached?: boolean;
269
273
  specs?: Array<{
270
274
  label?: string;
271
275
  description?: string;
@@ -293,6 +297,33 @@ export type TeamLogEvent = {
293
297
  subject?: string;
294
298
  body?: string;
295
299
  };
300
+ } | {
301
+ /**
302
+ * A pause / resume / stop / spawn / message, by the lead, the user or the
303
+ * supervisor (team-detached-dispatch I-DD5). Logged because the audit trail
304
+ * is the whole reason a console tool is safe to give a model: every
305
+ * mutation of a running dispatch names its author here.
306
+ */
307
+ type: 'control';
308
+ dispatchId: string;
309
+ action?: string;
310
+ label?: string;
311
+ by?: string;
312
+ reason?: string;
313
+ at?: number;
314
+ } | {
315
+ /**
316
+ * A child's mail to the lead. Logged as a SUBJECT ONLY: the body is prose a
317
+ * child wrote for the lead, and the log is not the place a child's text
318
+ * becomes an unreadable line.
319
+ */
320
+ type: 'lead_mail';
321
+ dispatchId: string;
322
+ message?: {
323
+ from?: string;
324
+ to?: string;
325
+ subject?: string;
326
+ };
296
327
  } | {
297
328
  type: 'overseer';
298
329
  dispatchId: string;
@@ -514,6 +514,27 @@ export function attachTeamEvents(logger, controller) {
514
514
  subject: event.message?.subject,
515
515
  });
516
516
  break;
517
+ case 'control':
518
+ // WHO DID WHAT, at info: a control action is a deliberate act on a running
519
+ // dispatch, and the audit trail is what makes giving a model these tools
520
+ // defensible in the first place (I-DD5). The reason is the short one the
521
+ // caller supplied, never a child's prose.
522
+ logger.info('agent', 'team_control', {
523
+ dispatchId: event.dispatchId,
524
+ action: event.action,
525
+ label: event.label,
526
+ by: event.by,
527
+ reason: event.reason,
528
+ });
529
+ break;
530
+ case 'lead_mail':
531
+ // SUBJECT ONLY, for the same reason a `team_send` body is never recorded.
532
+ logger.debug('agent', 'team_lead_mail', {
533
+ dispatchId: event.dispatchId,
534
+ from: event.message?.from,
535
+ subject: event.message?.subject,
536
+ });
537
+ break;
517
538
  case 'overseer':
518
539
  // REASON ONLY, and at debug: interventions are routine supervision,
519
540
  // not failures; the report and the panel carry them to the user.
@@ -33,6 +33,17 @@
33
33
  * this to decide the WORDING (note or not) and, together with the `'end'`
34
34
  * events, to settle the ordinary path without waiting for `'close'` at all.
35
35
  *
36
+ * AND READ THEM TWICE, because one sample is still a clock. The SECOND release
37
+ * gate failure of the same sentence (2026-11-10) printed the note for
38
+ * `node -e "console.log('hi')"`: not a verdict-from-expiry this time, but a
39
+ * verdict from a single look taken in the milliseconds before libuv dispatched
40
+ * the EOF behind a starved loop. So `bash` keeps waiting past
41
+ * `PROC_LIMITS.drainMs` - event driven, so an ordinary command pays nothing -
42
+ * and prints the note only if the pipes are STILL open a whole
43
+ * `PROC_LIMITS.drainVerifyMs` later. A pipe that lets go in between is not a
44
+ * held pipe, it is a slow notification, and the model must not be told to
45
+ * background a command that already finished.
46
+ *
36
47
  * ASCII ONLY: `src/proc/**` is inside the glyph scanner's scope.
37
48
  */
38
49
  import type { Readable } from 'node:stream';
@@ -33,6 +33,17 @@
33
33
  * this to decide the WORDING (note or not) and, together with the `'end'`
34
34
  * events, to settle the ordinary path without waiting for `'close'` at all.
35
35
  *
36
+ * AND READ THEM TWICE, because one sample is still a clock. The SECOND release
37
+ * gate failure of the same sentence (2026-11-10) printed the note for
38
+ * `node -e "console.log('hi')"`: not a verdict-from-expiry this time, but a
39
+ * verdict from a single look taken in the milliseconds before libuv dispatched
40
+ * the EOF behind a starved loop. So `bash` keeps waiting past
41
+ * `PROC_LIMITS.drainMs` - event driven, so an ordinary command pays nothing -
42
+ * and prints the note only if the pipes are STILL open a whole
43
+ * `PROC_LIMITS.drainVerifyMs` later. A pipe that lets go in between is not a
44
+ * held pipe, it is a slow notification, and the model must not be told to
45
+ * background a command that already finished.
46
+ *
36
47
  * ASCII ONLY: `src/proc/**` is inside the glyph scanner's scope.
37
48
  */
38
49
  /**
@@ -0,0 +1,61 @@
1
+ /**
2
+ * The THREE-LAYER prompt resolution and its inheritance merge
3
+ * (redteam-prompt-profile 5.1 / 5.5).
4
+ *
5
+ * ASCII ONLY - `src/redteam/**` is inside `glyphs.test.ts::inScope`.
6
+ *
7
+ * --redteam-prompt <path> > redteam.profile > builtin
8
+ * (this session only) (persisted) (code, no I/O)
9
+ *
10
+ * TOTAL, AND TOTAL IS A SECURITY PROPERTY (D-9 / PF-9). No layer can throw and no layer can
11
+ * change whether the mode is available or armed: a profile that is missing, oversized,
12
+ * headerless or self-inheriting produces an issue and a fallback, and the mode still arms.
13
+ * The alternative - a prompt file that can disable a security posture by being broken - is
14
+ * the one failure mode this design refuses to have.
15
+ *
16
+ * THE DISPLAY NAME NEVER CONTAINS A REAL PATH (D-11 / PF-6). A slug stays a slug, an absolute
17
+ * profile path becomes `'<path>'`, and a `--redteam-prompt` file becomes `'<flag>'` - because
18
+ * a path can hold a user's real name and a profile body can hold a client's.
19
+ */
20
+ import { type EditableSlotId, type RedTeamPromptSlotId } from '@aragon-agent/tui/model/redteam/prompt-slots';
21
+ import type { RedTeamPromptIssue } from '@aragon-agent/tui/model/redteam/types';
22
+ import { type RedTeamPromptStoreDeps } from './prompt-store.js';
23
+ /** Where the resolved text came from; `profile` says what was CHOSEN. */
24
+ export type PromptSource = 'builtin' | 'file' | 'flag';
25
+ export interface ResolvedPrompt {
26
+ /** `'builtin'` | `'<slug>'` | `'<flag>'` | `'<path>'` - a display name, never a path. */
27
+ profile: string;
28
+ source: PromptSource;
29
+ /** Editable sections in effect. Locked sections never appear here (PF-2). */
30
+ sections: ReadonlyMap<RedTeamPromptSlotId, string>;
31
+ /** The editable slots a FILE actually replaced, in emission order. */
32
+ overridden: readonly EditableSlotId[];
33
+ /** At most two free-form sections, from the leaf only. */
34
+ extras: readonly {
35
+ title: string;
36
+ body: string;
37
+ }[];
38
+ /** Bytes read from disk; `0` when nothing was read. */
39
+ bytes: number;
40
+ /** Every file read was a cache hit. `false` for `builtin`, which reads nothing. */
41
+ fromCache: boolean;
42
+ issues: readonly RedTeamPromptIssue[];
43
+ }
44
+ export interface PromptResolveRequest {
45
+ /** `--redteam-prompt <path>`; absent when the flag was not given. */
46
+ flagPath?: string;
47
+ /** `redteam.profile`, in any of its three forms. */
48
+ profile: string;
49
+ /** Base directory for a relative flag path. */
50
+ cwd: string;
51
+ /** Injected filesystem / directories, for the tests and for a host that owns its own home. */
52
+ deps?: RedTeamPromptStoreDeps;
53
+ }
54
+ /**
55
+ * Resolve the prompt. NEVER THROWS (PF-5 / PF-9).
56
+ *
57
+ * The flag layer is tried first and falls THROUGH to the configured layer on failure, while
58
+ * the reported `profile` stays `'<flag>'`: a user who typed the flag needs to know that the
59
+ * file they named did not take effect, and they need the issue that says why.
60
+ */
61
+ export declare function resolveRedTeamPrompt(req: PromptResolveRequest): ResolvedPrompt;
@@ -0,0 +1,303 @@
1
+ /**
2
+ * The THREE-LAYER prompt resolution and its inheritance merge
3
+ * (redteam-prompt-profile 5.1 / 5.5).
4
+ *
5
+ * ASCII ONLY - `src/redteam/**` is inside `glyphs.test.ts::inScope`.
6
+ *
7
+ * --redteam-prompt <path> > redteam.profile > builtin
8
+ * (this session only) (persisted) (code, no I/O)
9
+ *
10
+ * TOTAL, AND TOTAL IS A SECURITY PROPERTY (D-9 / PF-9). No layer can throw and no layer can
11
+ * change whether the mode is available or armed: a profile that is missing, oversized,
12
+ * headerless or self-inheriting produces an issue and a fallback, and the mode still arms.
13
+ * The alternative - a prompt file that can disable a security posture by being broken - is
14
+ * the one failure mode this design refuses to have.
15
+ *
16
+ * THE DISPLAY NAME NEVER CONTAINS A REAL PATH (D-11 / PF-6). A slug stays a slug, an absolute
17
+ * profile path becomes `'<path>'`, and a `--redteam-prompt` file becomes `'<flag>'` - because
18
+ * a path can hold a user's real name and a profile body can hold a client's.
19
+ */
20
+ import { join, resolve } from 'node:path';
21
+ import { REDTEAM_PROMPT_LIMITS } from '@aragon-agent/tui/model/redteam/limits';
22
+ import { countFenceTags } from '@aragon-agent/tui/model/redteam/fence';
23
+ import { EDITABLE_SLOT_IDS, REDTEAM_BLOCK_EMIT_ORDER, redTeamPromptSlot, } from '@aragon-agent/tui/model/redteam/prompt-slots';
24
+ import { PROFILE_SLUG_PATTERN, parseProfile, } from '@aragon-agent/tui/model/redteam/prompt-file';
25
+ import { clampRedTeamProfile } from '@aragon-agent/tui/model/config/schema';
26
+ import { getRedTeamProfilesDir, } from '../config/app-paths.js';
27
+ import { loadProfileFile, } from './prompt-store.js';
28
+ /** The built-in editable sections: what a profile with nothing in it produces. */
29
+ function builtinSections() {
30
+ const sections = new Map();
31
+ for (const id of EDITABLE_SLOT_IDS) {
32
+ const body = redTeamPromptSlot(id).defaultBody;
33
+ if (body.length > 0)
34
+ sections.set(id, body);
35
+ }
36
+ return sections;
37
+ }
38
+ /**
39
+ * Every editable slot present with an EMPTY body - what `mode: replace` starts from (5.3).
40
+ *
41
+ * THE EMPTY STRING IS THE MECHANISM, not an absence: the assembler reads
42
+ * `sections.get(id) ?? spec.defaultBody`, so a MISSING key falls back to the built-in text and
43
+ * a present-but-empty one renders nothing at all. Without this seed, `mode: replace` was a
44
+ * no-op that produced the full default block while the scaffold told the user otherwise.
45
+ */
46
+ function emptyEditableSections() {
47
+ const sections = new Map();
48
+ for (const id of EDITABLE_SLOT_IDS)
49
+ sections.set(id, '');
50
+ return sections;
51
+ }
52
+ function builtinResult(issues) {
53
+ return {
54
+ profile: 'builtin',
55
+ source: 'builtin',
56
+ sections: builtinSections(),
57
+ overridden: [],
58
+ extras: [],
59
+ bytes: 0,
60
+ fromCache: false,
61
+ issues,
62
+ };
63
+ }
64
+ /**
65
+ * Resolve the prompt. NEVER THROWS (PF-5 / PF-9).
66
+ *
67
+ * The flag layer is tried first and falls THROUGH to the configured layer on failure, while
68
+ * the reported `profile` stays `'<flag>'`: a user who typed the flag needs to know that the
69
+ * file they named did not take effect, and they need the issue that says why.
70
+ */
71
+ export function resolveRedTeamPrompt(req) {
72
+ const issues = [];
73
+ const flagPath = req.flagPath?.trim() ?? '';
74
+ if (flagPath.length === 0)
75
+ return resolveConfigured(req, issues);
76
+ const absolute = resolve(req.cwd, flagPath);
77
+ const loaded = loadProfileFile(absolute, req.deps);
78
+ if (loaded.ok) {
79
+ return assemble({
80
+ source: 'flag',
81
+ displayProfile: '<flag>',
82
+ fileName: baseName(absolute),
83
+ loaded,
84
+ issues,
85
+ req,
86
+ });
87
+ }
88
+ issues.push({
89
+ code: 'flag_unreadable',
90
+ severity: 'warn',
91
+ detail: '--redteam-prompt could not be read; redteam.profile is used instead.',
92
+ });
93
+ const fallback = resolveConfigured(req, issues);
94
+ return { ...fallback, profile: '<flag>' };
95
+ }
96
+ /** Layer 2 and 3: the persisted `redteam.profile`, then `builtin`. */
97
+ function resolveConfigured(req, issues) {
98
+ // THE RAW VALUE IS JUDGED FIRST (PF-9 / AC-24). `clampRedTeamProfile` answers `builtin` for
99
+ // nonsense, which is the right FALLBACK but not the right SILENCE: a typo in
100
+ // `redteam.profile` would otherwise report "builtin" as if the user had asked for it, with no
101
+ // issue and no notice anywhere.
102
+ if (isInvalidProfileName(req.profile)) {
103
+ issues.push({
104
+ code: 'bad_slug',
105
+ severity: 'warn',
106
+ detail: 'redteam.profile is neither "builtin", a slug, nor a path; using builtin.',
107
+ });
108
+ return builtinResult(issues);
109
+ }
110
+ const chosen = clampRedTeamProfile(req.profile);
111
+ if (chosen === 'builtin')
112
+ return builtinResult(issues);
113
+ if (isPathForm(chosen)) {
114
+ const absolute = resolve(req.cwd, chosen);
115
+ const loaded = loadProfileFile(absolute, req.deps);
116
+ if (loaded.ok) {
117
+ return assemble({
118
+ source: 'file',
119
+ displayProfile: '<path>',
120
+ fileName: baseName(absolute),
121
+ loaded,
122
+ issues,
123
+ req,
124
+ });
125
+ }
126
+ issues.push(loaded.issue);
127
+ return { ...builtinResult(issues), profile: '<path>' };
128
+ }
129
+ const profilesDir = req.deps?.profilesDir?.() ?? getRedTeamProfilesDir();
130
+ const loaded = loadProfileFile(join(profilesDir, `${chosen}.md`), req.deps);
131
+ if (loaded.ok) {
132
+ return assemble({
133
+ source: 'file',
134
+ displayProfile: chosen,
135
+ fileName: `${chosen}.md`,
136
+ leafSlug: chosen,
137
+ loaded,
138
+ issues,
139
+ req,
140
+ });
141
+ }
142
+ issues.push(loaded.issue);
143
+ // THE MODE STILL ARMS (PF-9); the reported profile stays the slug so the user sees which
144
+ // selection is not delivering.
145
+ return { ...builtinResult(issues), profile: chosen };
146
+ }
147
+ /** The same three-form test the config clamp uses, kept in one order (D-18 rule 2). */
148
+ function isPathForm(value) {
149
+ return value.includes('/')
150
+ || value.includes('\\')
151
+ || /^[A-Za-z]:[\\/]/u.test(value)
152
+ || value.toLowerCase().endsWith('.md');
153
+ }
154
+ /**
155
+ * Would `clampRedTeamProfile` silently replace this value with `builtin`?
156
+ *
157
+ * The three forms are the ones D-18 fixes, in the same order - `builtin`, a path, a slug - and
158
+ * a slug is compared in the form the clamp would store it (trimmed, lowercased).
159
+ */
160
+ function isInvalidProfileName(raw) {
161
+ const trimmed = raw.trim();
162
+ if (trimmed.length === 0 || trimmed === 'builtin')
163
+ return false;
164
+ if (isPathForm(trimmed))
165
+ return false;
166
+ return !PROFILE_SLUG_PATTERN.test(trimmed.toLowerCase());
167
+ }
168
+ /**
169
+ * Parse the leaf, walk `extends`, and merge base-to-leaf.
170
+ *
171
+ * THE MIDDLE OF A CHAIN IS ALWAYS `merge` (5.5): a base that says `replace` and a leaf that
172
+ * says `merge` has no explainable meaning, so only the leaf's `mode` is read.
173
+ */
174
+ function assemble(input) {
175
+ const { source, displayProfile, fileName, loaded, issues, req } = input;
176
+ // THE REAL FILE NAME, not the display name: `bad_slug` has to fire for
177
+ // `--redteam-prompt "./My Engagement.md"` exactly as it does for a slug profile (AC-25).
178
+ const leaf = parseProfile(loaded.text, fileName, { nameFallback: '<path>' });
179
+ issues.push(...leaf.issues);
180
+ const chain = [leaf];
181
+ let bytes = loaded.bytes;
182
+ let fromCache = loaded.fromCache;
183
+ const chainResult = walkExtends(leaf, req, issues, input.leafSlug);
184
+ chain.unshift(...chainResult.ancestors);
185
+ bytes += chainResult.bytes;
186
+ fromCache = fromCache && chainResult.fromCache;
187
+ if (chainResult.cycle) {
188
+ return { ...builtinResult(issues), profile: displayProfile };
189
+ }
190
+ const sections = leaf.directives.mode === 'replace'
191
+ ? emptyEditableSections()
192
+ : builtinSections();
193
+ const overridden = new Set();
194
+ for (const link of chain) {
195
+ for (const [id, body] of Object.entries(link.sections)) {
196
+ sections.set(id, body);
197
+ overridden.add(id);
198
+ }
199
+ }
200
+ reportNeutralized(sections, overridden, leaf, issues);
201
+ return {
202
+ profile: displayProfile,
203
+ source,
204
+ sections,
205
+ overridden: [...REDTEAM_BLOCK_EMIT_ORDER].filter((id) => overridden.has(id)),
206
+ extras: leaf.extras,
207
+ bytes,
208
+ fromCache,
209
+ issues,
210
+ };
211
+ }
212
+ /**
213
+ * The BASE NAME of a resolved path - what the parser may look at for `name` and `bad_slug`.
214
+ *
215
+ * Only the last segment: the directory is exactly the part that can hold a person's name,
216
+ * and no code path here needs it (D-11).
217
+ */
218
+ function baseName(path) {
219
+ return path.replace(/\\/gu, '/').split('/').pop() ?? path;
220
+ }
221
+ /**
222
+ * Walk `extends` from the leaf's target down to `builtin` (or until the depth limit).
223
+ *
224
+ * A CYCLE DISCARDS THE WHOLE CHAIN rather than the cycle alone: with `a -> b -> a` there is no
225
+ * defensible "start again from here" point, and a partial answer would be a prompt nobody
226
+ * wrote. A DEPTH overrun truncates instead, because there the part that was read is sound.
227
+ */
228
+ function walkExtends(leaf, req, issues, leafSlug) {
229
+ const ancestors = [];
230
+ // THE LEAF IS SEEDED WHEN IT HAS A NAME (5.5). `a -> b -> a` never revisited `a` before: only
231
+ // loaded ancestors went into `visited`, so the loop could only be seen one hop too late - and
232
+ // with the documented depth limit the chain hit `extends_depth` first, which tells the user to
233
+ // shorten an inheritance that is really circular.
234
+ const visited = new Set(leafSlug === undefined ? [] : [leafSlug]);
235
+ const profilesDir = req.deps?.profilesDir?.() ?? getRedTeamProfilesDir();
236
+ let bytes = 0;
237
+ let fromCache = true;
238
+ let cursor = leaf.directives.extends;
239
+ while (cursor !== 'builtin') {
240
+ // CYCLE FIRST, DEPTH SECOND: `a -> b -> a` must be reported as a loop, not as "too deep".
241
+ // The two checks guard different mistakes and a user can act on only one of them.
242
+ if (visited.has(cursor)) {
243
+ issues.push({
244
+ code: 'extends_cycle',
245
+ severity: 'error',
246
+ detail: 'Profile inheritance loops; using builtin.',
247
+ });
248
+ return { ancestors: [], bytes, fromCache, cycle: true };
249
+ }
250
+ // DEPTH: `extendsDepthMax` COUNTS THE BUILT-IN LINK (5.5: `[profile, extends1, ...,
251
+ // 'builtin']`, length <= 3), so the chain may hold at most `max - 2` ancestors - one
252
+ // extension at the documented limit. The `+ 2` stands for this leaf and the trailing builtin;
253
+ // with `>` instead of `>=` the limit admitted one ancestor too many.
254
+ if (ancestors.length + 2 >= REDTEAM_PROMPT_LIMITS.extendsDepthMax) {
255
+ issues.push({
256
+ code: 'extends_depth',
257
+ severity: 'error',
258
+ detail: `Inheritance is deeper than `
259
+ + `${REDTEAM_PROMPT_LIMITS.extendsDepthMax}; the rest is ignored.`,
260
+ });
261
+ break;
262
+ }
263
+ visited.add(cursor);
264
+ const loaded = loadProfileFile(join(profilesDir, `${cursor}.md`), req.deps);
265
+ if (!loaded.ok) {
266
+ issues.push({
267
+ code: 'extends_missing',
268
+ severity: 'warn',
269
+ detail: `Base profile ${cursor} was not found; the chain ends there.`,
270
+ });
271
+ break;
272
+ }
273
+ bytes += loaded.bytes;
274
+ fromCache = fromCache && loaded.fromCache;
275
+ const parsed = parseProfile(loaded.text, `${cursor}.md`, { nameFallback: cursor });
276
+ issues.push(...parsed.issues);
277
+ ancestors.unshift(parsed);
278
+ cursor = parsed.directives.extends;
279
+ }
280
+ return { ancestors, bytes, fromCache, cycle: false };
281
+ }
282
+ /**
283
+ * Report sections whose text contains a fence tag (5.8's `fence_neutralized`, `info`).
284
+ *
285
+ * THE NEUTRALIZATION ITSELF HAPPENS IN THE ASSEMBLER, which is the only place that sees the
286
+ * final text. This pass exists so the user learns that their prose contained something that
287
+ * looked like the block's own closing tag.
288
+ */
289
+ function reportNeutralized(sections, overridden, leaf, issues) {
290
+ let count = 0;
291
+ for (const id of overridden) {
292
+ count += countFenceTags(sections.get(id) ?? '');
293
+ }
294
+ for (const extra of leaf.extras)
295
+ count += countFenceTags(extra.body);
296
+ if (count === 0)
297
+ return;
298
+ issues.push({
299
+ code: 'fence_neutralized',
300
+ severity: 'info',
301
+ detail: `${count} fence tag(s) inside the profile text were neutralized.`,
302
+ });
303
+ }
@@ -0,0 +1,96 @@
1
+ /**
2
+ * The prompt-profile STORE: the only place a red team profile touches the disk
3
+ * (redteam-prompt-profile 5.4 / 5.7 / 6.1).
4
+ *
5
+ * ASCII ONLY - `src/redteam/**` is inside `glyphs.test.ts::inScope`.
6
+ *
7
+ * NOTHING HERE THROWS, AND THAT IS THE FEATURE (D-9 / PF-9). Every failure is an issue plus a
8
+ * fallback: a profile is a convenience, so a missing, oversized or unreadable file must leave
9
+ * the mode armed and the user informed. The one case that could take a security posture down
10
+ * with it - an exception escaping into the prompt builder - is the case this file exists to
11
+ * make impossible.
12
+ *
13
+ * TWO ENTRY POINTS, ONE CACHE. `loadProfileFile` is the read path (stat, byte cap, decode,
14
+ * `(mtimeMs, size)` memo); `writeScaffold` is the only write in the whole feature, and it
15
+ * REFUSES TO OVERWRITE a profile the user already has.
16
+ *
17
+ * `builtin` NEVER REACHES THIS FILE (PF-11): the resolver returns before calling in, and the
18
+ * test that proves it injects an `fs` port whose every method throws.
19
+ */
20
+ import type { RedTeamPromptIssue } from '@aragon-agent/tui/model/redteam/types';
21
+ /**
22
+ * The filesystem, as a PORT.
23
+ *
24
+ * A port rather than direct `node:fs` calls for one concrete reason: `PF-11` asserts that
25
+ * `builtin` performs no I/O at all, and the way to prove "no I/O" is to hand the code a
26
+ * filesystem that throws on first use.
27
+ */
28
+ export interface RedTeamPromptFs {
29
+ statSync(path: string): {
30
+ mtimeMs: number;
31
+ size: number;
32
+ };
33
+ readFileSync(path: string): string;
34
+ existsSync(path: string): boolean;
35
+ writeFileSync(path: string, data: string, options: {
36
+ encoding: 'utf-8';
37
+ mode: number;
38
+ }): void;
39
+ renameSync(from: string, to: string): void;
40
+ mkdirSync(path: string, options: {
41
+ recursive: boolean;
42
+ mode: number;
43
+ }): void;
44
+ rmSync(path: string, options: {
45
+ force: boolean;
46
+ }): void;
47
+ chmodSync(path: string, mode: number): void;
48
+ }
49
+ /** The real filesystem, wired explicitly so the port's shape stays small and honest. */
50
+ export declare const NODE_REDTEAM_FS: RedTeamPromptFs;
51
+ /** Where the store reads and writes. Injectable so tests never touch a real home directory. */
52
+ export interface RedTeamPromptStoreDeps {
53
+ fs?: RedTeamPromptFs;
54
+ /** `<home>/redteam/profiles`, resolved lazily so `ARAGON_HOME` still applies. */
55
+ profilesDir?: () => string;
56
+ /** `<home>/redteam`, created by `init` with 0700 where the platform honours it. */
57
+ redTeamDir?: () => string;
58
+ }
59
+ export type ProfileReadResult = {
60
+ ok: true;
61
+ text: string;
62
+ bytes: number;
63
+ fromCache: boolean;
64
+ } | {
65
+ ok: false;
66
+ issue: RedTeamPromptIssue;
67
+ };
68
+ /** `/redteam prompt reload` and the "file was deleted" path both empty this (5.7). */
69
+ export declare function clearPromptProfileCache(): void;
70
+ /** Drop ONE path; used when the file vanished, so a re-created file is read again. */
71
+ export declare function forgetPromptProfile(path: string): void;
72
+ /** The number of memoised files - asserted by the cache tests. */
73
+ export declare function promptProfileCacheSize(): number;
74
+ /**
75
+ * Read one profile file, subject to the byte cap.
76
+ *
77
+ * THE BYTE CAP IS CHECKED ON `stat` FIRST (PF-7 / R-4): decoding a 40 MiB file into a string
78
+ * to find out it was too large would defeat the limit it is meant to enforce.
79
+ */
80
+ export declare function loadProfileFile(path: string, deps?: RedTeamPromptStoreDeps): ProfileReadResult;
81
+ export type ScaffoldResult = {
82
+ ok: true;
83
+ path: string;
84
+ } | {
85
+ ok: false;
86
+ reason: 'exists' | 'write_failed';
87
+ };
88
+ /**
89
+ * Write a starter profile, REFUSING to replace one that exists (5.3 / AC-10).
90
+ *
91
+ * The refusal is the important half: `init` is offered in a transcript as a safe first step,
92
+ * and a command that silently overwrites the file the user has been editing for an hour is
93
+ * the opposite of that. The write itself copies `prompts/store.ts`'s three steps - tmp file
94
+ * named for the pid, `rename`, `chmod` - because a half-written profile is worse than none.
95
+ */
96
+ export declare function writePromptScaffold(text: string, slug: string, deps?: RedTeamPromptStoreDeps): ScaffoldResult;