@aragon-agent/cli 0.6.57 → 0.6.61

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 +20 -0
  49. package/dist/proc/output-streams.js +20 -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 +44 -9
  83. package/dist/tools/index.d.ts +2 -2
  84. package/dist/tools/index.js +30 -0
  85. package/package.json +3 -3
@@ -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;
@@ -0,0 +1,156 @@
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 { chmodSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync, } from 'node:fs';
21
+ import { join } from 'node:path';
22
+ import process from 'node:process';
23
+ import { getRedTeamProfilesDir } from '../config/app-paths.js';
24
+ import { REDTEAM_PROMPT_LIMITS } from '@aragon-agent/tui/model/redteam/limits';
25
+ import { PROFILE_SLUG_PATTERN } from '@aragon-agent/tui/model/redteam/prompt-file';
26
+ /** The real filesystem, wired explicitly so the port's shape stays small and honest. */
27
+ export const NODE_REDTEAM_FS = {
28
+ statSync: (path) => statSync(path),
29
+ readFileSync: (path) => readFileSync(path, 'utf-8'),
30
+ existsSync: (path) => existsSync(path),
31
+ writeFileSync: (path, data, options) => writeFileSync(path, data, options),
32
+ renameSync: (from, to) => renameSync(from, to),
33
+ mkdirSync: (path, options) => { mkdirSync(path, options); },
34
+ rmSync: (path, options) => { rmSync(path, options); },
35
+ chmodSync: (path, mode) => { chmodSync(path, mode); },
36
+ };
37
+ /**
38
+ * `(mtimeMs, size)` memo, keyed by absolute path.
39
+ *
40
+ * NO "hot reload" SWITCH EXISTS AND NONE IS NEEDED (D-10): the key changes when the file
41
+ * changes, so the next assembly picks the new text up. A switch that could leave a file
42
+ * unread is worse than no switch at all.
43
+ */
44
+ const cache = new Map();
45
+ /** `/redteam prompt reload` and the "file was deleted" path both empty this (5.7). */
46
+ export function clearPromptProfileCache() {
47
+ cache.clear();
48
+ }
49
+ /** Drop ONE path; used when the file vanished, so a re-created file is read again. */
50
+ export function forgetPromptProfile(path) {
51
+ cache.delete(path);
52
+ }
53
+ /** The number of memoised files - asserted by the cache tests. */
54
+ export function promptProfileCacheSize() {
55
+ return cache.size;
56
+ }
57
+ /**
58
+ * Read one profile file, subject to the byte cap.
59
+ *
60
+ * THE BYTE CAP IS CHECKED ON `stat` FIRST (PF-7 / R-4): decoding a 40 MiB file into a string
61
+ * to find out it was too large would defeat the limit it is meant to enforce.
62
+ */
63
+ export function loadProfileFile(path, deps = {}) {
64
+ const fs = deps.fs ?? NODE_REDTEAM_FS;
65
+ let stat;
66
+ try {
67
+ stat = fs.statSync(path);
68
+ }
69
+ catch {
70
+ forgetPromptProfile(path);
71
+ return {
72
+ ok: false,
73
+ issue: {
74
+ code: 'file_missing',
75
+ severity: 'warn',
76
+ detail: 'The selected profile file does not exist; the built-in text is used.',
77
+ },
78
+ };
79
+ }
80
+ if (stat.size > REDTEAM_PROMPT_LIMITS.fileMaxBytes) {
81
+ forgetPromptProfile(path);
82
+ return {
83
+ ok: false,
84
+ issue: {
85
+ code: 'too_large',
86
+ severity: 'error',
87
+ detail: `The profile is ${stat.size} bytes; the limit is `
88
+ + `${REDTEAM_PROMPT_LIMITS.fileMaxBytes}.`,
89
+ },
90
+ };
91
+ }
92
+ const cached = cache.get(path);
93
+ if (cached !== undefined && cached.mtimeMs === stat.mtimeMs && cached.size === stat.size) {
94
+ return { ok: true, text: cached.text, bytes: cached.bytes, fromCache: true };
95
+ }
96
+ let text;
97
+ try {
98
+ text = fs.readFileSync(path);
99
+ }
100
+ catch {
101
+ forgetPromptProfile(path);
102
+ return {
103
+ ok: false,
104
+ issue: {
105
+ code: 'file_missing',
106
+ severity: 'warn',
107
+ detail: 'The selected profile could not be read; the built-in text is used.',
108
+ },
109
+ };
110
+ }
111
+ const entry = { mtimeMs: stat.mtimeMs, size: stat.size, text, bytes: stat.size };
112
+ cache.set(path, entry);
113
+ return { ok: true, text, bytes: entry.bytes, fromCache: false };
114
+ }
115
+ /**
116
+ * Write a starter profile, REFUSING to replace one that exists (5.3 / AC-10).
117
+ *
118
+ * The refusal is the important half: `init` is offered in a transcript as a safe first step,
119
+ * and a command that silently overwrites the file the user has been editing for an hour is
120
+ * the opposite of that. The write itself copies `prompts/store.ts`'s three steps - tmp file
121
+ * named for the pid, `rename`, `chmod` - because a half-written profile is worse than none.
122
+ */
123
+ export function writePromptScaffold(text, slug, deps = {}) {
124
+ const fs = deps.fs ?? NODE_REDTEAM_FS;
125
+ const dir = deps.profilesDir?.() ?? getRedTeamProfilesDir();
126
+ if (!PROFILE_SLUG_PATTERN.test(slug))
127
+ return { ok: false, reason: 'write_failed' };
128
+ const path = join(dir, `${slug}.md`);
129
+ try {
130
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
131
+ }
132
+ catch {
133
+ return { ok: false, reason: 'write_failed' };
134
+ }
135
+ if (fs.existsSync(path))
136
+ return { ok: false, reason: 'exists' };
137
+ const tmp = `${path}.tmp-${process.pid}`;
138
+ try {
139
+ fs.writeFileSync(tmp, text, { encoding: 'utf-8', mode: 0o600 });
140
+ fs.renameSync(tmp, path);
141
+ // BEST EFFORT, and a no-op on Windows (RV-P2-7): this is not a defence against another
142
+ // local user, it is the conventional "not world-readable" bit.
143
+ if (process.platform !== 'win32')
144
+ fs.chmodSync(path, 0o600);
145
+ return { ok: true, path };
146
+ }
147
+ catch {
148
+ try {
149
+ fs.rmSync(tmp, { force: true });
150
+ }
151
+ catch {
152
+ // Nothing further to try: the scaffold simply was not written, and the caller says so.
153
+ }
154
+ return { ok: false, reason: 'write_failed' };
155
+ }
156
+ }
@@ -0,0 +1,22 @@
1
+ /**
2
+ * The `/redteam prompt init` scaffold (redteam-prompt-profile 5.3 / 7.1).
3
+ *
4
+ * ASCII ONLY - `src/redteam/**` is inside `glyphs.test.ts::inScope`.
5
+ *
6
+ * AN EMPTY SKELETON IS THE RIGHT STARTER, not a filled-in example. Every section body in this
7
+ * file is EMPTY, so a user who runs `init` and changes nothing gets the built-in behaviour:
8
+ * the scaffold can never become a silently different prompt. The instructions live in the
9
+ * PREAMBLE, before the first `##` heading, which the parser ignores - so the explanation is
10
+ * for the human and never reaches the model.
11
+ *
12
+ * The seven headings use the natural spelling ("## Rules of engagement"), which is the form
13
+ * `HEADING_ALIASES` exists to bind (RV-P1-2).
14
+ */
15
+ /**
16
+ * The scaffold for `slug`.
17
+ *
18
+ * The header keys are the minimal set a reader needs: `schema` (required), `name`, `title`,
19
+ * `extends` and `mode`. `title` is left as a visible prompt rather than an empty value,
20
+ * because a human editing this file wants to know what the line is for.
21
+ */
22
+ export declare function promptProfileScaffold(slug: string): string;
@@ -0,0 +1,72 @@
1
+ /**
2
+ * The `/redteam prompt init` scaffold (redteam-prompt-profile 5.3 / 7.1).
3
+ *
4
+ * ASCII ONLY - `src/redteam/**` is inside `glyphs.test.ts::inScope`.
5
+ *
6
+ * AN EMPTY SKELETON IS THE RIGHT STARTER, not a filled-in example. Every section body in this
7
+ * file is EMPTY, so a user who runs `init` and changes nothing gets the built-in behaviour:
8
+ * the scaffold can never become a silently different prompt. The instructions live in the
9
+ * PREAMBLE, before the first `##` heading, which the parser ignores - so the explanation is
10
+ * for the human and never reaches the model.
11
+ *
12
+ * The seven headings use the natural spelling ("## Rules of engagement"), which is the form
13
+ * `HEADING_ALIASES` exists to bind (RV-P1-2).
14
+ */
15
+ import { REDTEAM_PROMPT_LIMITS } from '@aragon-agent/tui/model/redteam/limits';
16
+ const PREAMBLE = `<!--
17
+ One file, one profile. Rename nothing here unless you also change "name:" below.
18
+
19
+ How this file is used
20
+ - Every "## <heading>" section REPLACES the built-in text of that section.
21
+ - A section you leave empty keeps the built-in text, so an untouched file behaves
22
+ exactly like the default mode.
23
+ - The sections Authorization, What this mode changes and the closing sentence are NOT
24
+ editable: a profile cannot restate what this session is allowed to do. Writing one of
25
+ those headings is ignored and reported.
26
+ - "mode: replace" drops every SECTION YOU DO NOT WRITE. Leave it as "merge".
27
+ - "extends: <slug>" starts from another profile instead of the built-in text.
28
+
29
+ Validate before you rely on it: /redteam prompt validate <path>
30
+ Switch this session to it: /redteam prompt <slug>
31
+ Go back to the default: /redteam prompt builtin
32
+ -->`;
33
+ /** The section list, in the order a reader expects them (not the emission order). */
34
+ const SECTIONS = [
35
+ '## Role and engagement framing',
36
+ '',
37
+ '## Execution',
38
+ '',
39
+ '## Rules of engagement',
40
+ '',
41
+ '## Method',
42
+ '',
43
+ '## Routing and vocabulary',
44
+ '',
45
+ '## Deliverable',
46
+ '',
47
+ '## House rules',
48
+ '',
49
+ ];
50
+ /**
51
+ * The scaffold for `slug`.
52
+ *
53
+ * The header keys are the minimal set a reader needs: `schema` (required), `name`, `title`,
54
+ * `extends` and `mode`. `title` is left as a visible prompt rather than an empty value,
55
+ * because a human editing this file wants to know what the line is for.
56
+ */
57
+ export function promptProfileScaffold(slug) {
58
+ const name = slug.length > 0 ? slug : REDTEAM_PROMPT_LIMITS.scaffoldSlugFallback;
59
+ return [
60
+ '---',
61
+ 'schema: 1',
62
+ `name: ${name}`,
63
+ 'title: ',
64
+ 'extends: builtin',
65
+ 'mode: merge',
66
+ '---',
67
+ '',
68
+ PREAMBLE,
69
+ '',
70
+ ...SECTIONS,
71
+ ].join('\n');
72
+ }
@@ -109,6 +109,24 @@ export declare class TeamBus {
109
109
  messageCount(): number;
110
110
  lastMessage(): TeamMessage | undefined;
111
111
  sentCount(label: string): number;
112
+ /**
113
+ * Add a participant mid-dispatch (team-detached-dispatch section 5.2.6).
114
+ *
115
+ * `team_spawn` creates children after the first batch, and a late child that
116
+ * cannot be addressed would be a subagent its own siblings cannot message and
117
+ * whose mail nobody can send - a silent half-participant. `participants()` keeps
118
+ * the lead LAST, which is the order every bus consumer already assumes.
119
+ */
120
+ addParticipant(label: string): void;
121
+ /**
122
+ * Messages addressed to `lead` from `cursor` onward, for the live reminder path
123
+ * (section 5.2.3). `leadMail()` returns everything, which is what the REPORT
124
+ * wants; a relay that re-reported every message on every event would repeat
125
+ * itself once per notice.
126
+ */
127
+ leadMailSince(cursor: number): TeamMessage[];
128
+ /** How many messages have been addressed to `lead` so far (the relay's cursor). */
129
+ leadMailCount(): number;
112
130
  /**
113
131
  * Canonical label for a model-supplied `from`, or `undefined` (P1-3).
114
132
  *