@aragon-agent/cli 0.6.68 → 0.6.71

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 (48) hide show
  1. package/CHANGELOG.md +31 -0
  2. package/README.md +39 -15
  3. package/dist/agent/controller.d.ts +30 -1
  4. package/dist/agent/controller.js +91 -9
  5. package/dist/agent/project-guidance-prompt.js +97 -97
  6. package/dist/app/App.d.ts +12 -3
  7. package/dist/app/App.js +25 -2
  8. package/dist/app/use-governance-rounds.js +8 -4
  9. package/dist/cli.js +2 -2
  10. package/dist/commands/catalog.js +1 -1
  11. package/dist/config/cli-commands.d.ts +1 -1
  12. package/dist/config/cli-commands.js +4 -0
  13. package/dist/config/env.js +6 -0
  14. package/dist/config/load.js +36 -1
  15. package/dist/governance/engine/lifecycle.js +1 -1
  16. package/dist/governance/prompts/orchestrator-block.js +3 -3
  17. package/dist/host/controller-factory.d.ts +15 -0
  18. package/dist/host/controller-factory.js +10 -2
  19. package/dist/host/memory.d.ts +5 -1
  20. package/dist/host/memory.js +13 -0
  21. package/dist/memory/block.d.ts +38 -4
  22. package/dist/memory/block.js +52 -5
  23. package/dist/memory/command.js +56 -2
  24. package/dist/memory/journal.d.ts +58 -0
  25. package/dist/memory/journal.js +202 -0
  26. package/dist/memory/ledger.d.ts +54 -0
  27. package/dist/memory/ledger.js +105 -0
  28. package/dist/memory/paths.d.ts +10 -0
  29. package/dist/memory/paths.js +31 -0
  30. package/dist/memory/service.d.ts +54 -1
  31. package/dist/memory/service.js +156 -1
  32. package/dist/memory/store.d.ts +21 -3
  33. package/dist/memory/store.js +66 -6
  34. package/dist/memory/tools-batch.d.ts +27 -0
  35. package/dist/memory/tools-batch.js +462 -0
  36. package/dist/memory/tools-shared.d.ts +176 -0
  37. package/dist/memory/tools-shared.js +305 -0
  38. package/dist/memory/tools.d.ts +19 -28
  39. package/dist/memory/tools.js +148 -228
  40. package/dist/memory/undo.d.ts +53 -0
  41. package/dist/memory/undo.js +173 -0
  42. package/dist/redteam/prompt-template.js +16 -16
  43. package/dist/tools/index.d.ts +2 -2
  44. package/dist/tools/index.js +16 -1
  45. package/package.json +3 -3
  46. package/runtime/insecure-tls-warning.cjs +62 -62
  47. package/runtime/insecure-tls-warning.d.cts +5 -5
  48. package/skills/project-indexer/templates/artifact-hygiene-template.md +14 -14
@@ -0,0 +1,305 @@
1
+ /**
2
+ * Work the two memory write tools share: the error table, the refusal helper, the approval preview
3
+ * trimming and the per-op plumbing (memory-agent-autonomy spec 7.2 / RV-P1-10).
4
+ *
5
+ * ASCII ONLY - `src/memory/**` is inside `glyphs.test.ts::inScope`.
6
+ *
7
+ * ONE COPY OF THE ERROR TEXT, AND IT LIVES HERE. `tools.ts` was 641 lines before autonomy and
8
+ * `memory_batch` needs a file of its own; putting the batch executor there would have pushed it
9
+ * through the repo's 1000-line ceiling. Two files sharing one error table is fine; two files
10
+ * COPYING one error table is how a model starts getting two different sentences for one code.
11
+ *
12
+ * THE OP PLUMBING IS SHARED TOO - parsing, draft composition, the secret sniff, target resolution.
13
+ * A batch op is deliberately the same shape as a `memory_write` argument, so it has to go through
14
+ * the same validators; a second copy would drift on the first rule anyone adjusts.
15
+ */
16
+ import { errorResult } from '@aragon-agent/core';
17
+ import { memoryAskWhyCopy } from '@aragon-agent/tui/model/memory/copy';
18
+ import { MEMORY_LIMITS } from '@aragon-agent/tui/model/memory/limits';
19
+ import { resolveMemoryRef } from './resolve.js';
20
+ import { isMemoryLoad, validateMemoryDraft, deriveMemorySummary, clipCodePoints, codePointCount, } from '@aragon-agent/tui/model/memory/validate';
21
+ import { getLogger } from '../logging/logger.js';
22
+ import { looksLikeSecret } from './secrets.js';
23
+ import { readNote, toCatalogRow } from './store.js';
24
+ /**
25
+ * One sentence per refusal code, addressed to the MODEL (English, ASCII).
26
+ *
27
+ * The five autonomy codes at the bottom are the whole point of the feature having a vocabulary at
28
+ * all: "you are doing too much" (`rate_limited`) and "nobody can approve this"
29
+ * (`approval_unavailable`) lead to completely different next steps, so they cannot share a
30
+ * sentence.
31
+ */
32
+ export const ERROR_TEXT = {
33
+ invalid_argument: 'A parameter is missing or malformed.',
34
+ invalid_id: 'That id is not valid.',
35
+ title_required: 'title is required.',
36
+ body_required: 'body is required.',
37
+ title_too_long: `title must be at most ${MEMORY_LIMITS.titleMax} characters.`,
38
+ summary_too_long: `summary must be at most ${MEMORY_LIMITS.summaryMax} characters.`,
39
+ body_too_long: `body must be at most ${MEMORY_LIMITS.bodyMax} characters.`,
40
+ too_many_tags: `at most ${MEMORY_LIMITS.tagsMax} tags.`,
41
+ tag_too_long: `each tag must be at most ${MEMORY_LIMITS.tagMax} characters.`,
42
+ secret_detected: 'The text looks like a secret (credential or key). Do not retry with the same content; tell the user notes cannot hold secrets.',
43
+ duplicate_title: 'A note with this title already exists. Use op="update" on it instead.',
44
+ limit_reached: 'This scope is full. Ask the user which note to delete.',
45
+ not_found: 'No such note. Use memory_search to find ids.',
46
+ ambiguous: 'The id matches more than one note.',
47
+ conflict: 'The note changed since you read it. Call memory_read again, then retry with its new rev.',
48
+ declined: 'The user did not approve. Do not retry the same call; explain what you wanted to do or take another route.',
49
+ write_failed: 'The disk write failed. Tell the user; do not retry repeatedly.',
50
+ disabled: 'Memory is switched off.',
51
+ rate_limited: 'The user declined memory changes twice this turn. Stop writing memory; tell the user what you wanted to change and why.',
52
+ approval_unavailable: 'Nobody can approve this change right now. Split it into fewer writes, or ask the user to save it themselves with Ctrl+M.',
53
+ undo_unavailable: 'That change has no earlier version left to go back to; only the last 3 are kept.',
54
+ batch_too_large: `At most ${MEMORY_LIMITS.batchMaxOps} ops in one batch. Split it into several calls.`,
55
+ batch_invalid: 'The whole batch was refused because at least one op is invalid; nothing was written.',
56
+ };
57
+ /**
58
+ * The one sentence that explains WHY a human is being asked, for the card's second line.
59
+ *
60
+ * ONE CALL SITE FOR THE COUNT (spec 7.2 / RV-P1-2). `used` means something different per reason -
61
+ * how many times THIS NOTE was rewritten for `note_churn`, how many writes the turn has spent for
62
+ * `turn_budget`, how many the 24h window has spent for `day_budget` - and the two tool files used to
63
+ * each re-derive it. Both got `note_churn` wrong the same way, by reporting the turn's write count as
64
+ * the note's rewrite count; at the defaults the two numbers coincide, so nothing showed until a user
65
+ * raised `autoWritesPerTurn`, which is exactly the configuration the churn test exists for.
66
+ */
67
+ export function askWhyCopy(ports, decision, intent) {
68
+ const policy = ports.service.autonomyPolicy();
69
+ const state = ports.autonomyState();
70
+ const used = decision.reason === 'note_churn'
71
+ ? intent.churnIds.reduce((most, entry) => Math.max(most, entry.used), 0) + 1
72
+ : decision.reason === 'day_budget'
73
+ ? state.usedDay
74
+ : state.usedTurn;
75
+ const limit = decision.reason === 'day_budget' ? policy.perDay : policy.perTurn;
76
+ return memoryAskWhyCopy(decision.reason, {
77
+ opCount: intent.opCount,
78
+ threshold: policy.bulkThreshold,
79
+ protectedCount: intent.protectedCount,
80
+ used,
81
+ limit,
82
+ });
83
+ }
84
+ /** `<tool>: <code> - <detail> <sentence>`. The prefix names the tool that refused. */
85
+ export function makeWriteError(tool) {
86
+ return (code, detail) => {
87
+ const base = ERROR_TEXT[code] ?? 'The write was refused.';
88
+ return errorResult(`${tool}: ${code} - ${detail !== undefined ? `${detail} ` : ''}${base}`);
89
+ };
90
+ }
91
+ /** The preview the user approves. Bounded in lines AND characters. */
92
+ export function clipPreview(lines) {
93
+ const maxLines = MEMORY_LIMITS.approvalPreviewLines;
94
+ let text = lines.slice(0, maxLines).join('\n');
95
+ let dropped = lines.length > maxLines ? lines.slice(maxLines).join('\n').length : 0;
96
+ if (codePointCount(text) > MEMORY_LIMITS.approvalPreviewChars) {
97
+ const clipped = clipCodePoints(text, MEMORY_LIMITS.approvalPreviewChars);
98
+ dropped += text.length - clipped.length;
99
+ text = clipped;
100
+ }
101
+ return dropped > 0 ? `${text.trimEnd()}\n... (+${dropped} more chars)` : text;
102
+ }
103
+ /**
104
+ * The batch confirmation card: header and footer are NEVER trimmed, only the op rows are.
105
+ *
106
+ * A card whose reason line was cut is a card asking for a signature on something the reader cannot
107
+ * read. So the lines that explain WHY and the line that says WHAT IT ADDS UP TO are fixed, and the
108
+ * middle - the row-by-row table - gives way: rows beyond the budget collapse into `(+N more ops)`.
109
+ */
110
+ export function clipBatchCard(header, rows, footer) {
111
+ // ONE LINE IS RESERVED FOR `(+N more ops)` BEFORE THE ROWS ARE PLACED. Appending the marker to a
112
+ // full table is how the folded card came out one line over `approvalPreviewLines` - and an
113
+ // approval card that overruns its own ceiling is the one place where being one line long means
114
+ // the last line (the [y]/[n] hint) is the one that gets cut.
115
+ const room = MEMORY_LIMITS.approvalPreviewLines - header.length - footer.length;
116
+ const folded = rows.length > room;
117
+ const budget = Math.max(1, folded ? room - 1 : room);
118
+ const shown = rows.slice(0, budget);
119
+ const hidden = rows.length - shown.length;
120
+ const body = hidden > 0 ? [...shown, `(+${hidden} more ops)`] : shown;
121
+ return [...header, ...body, ...footer].join('\n');
122
+ }
123
+ /** The body of the confirmation card except its first line, trimmed like a single-write card. */
124
+ export function withWhy(summary, why) {
125
+ const [first, ...rest] = summary.split('\n');
126
+ return clipPreview([first ?? '', `Why: ${why}`, ...rest]);
127
+ }
128
+ // ---------------------------------------------------------------------------
129
+ // One op: parsed, validated, resolved (shared with memory_batch)
130
+ // ---------------------------------------------------------------------------
131
+ export const OPS = ['create', 'update', 'delete'];
132
+ export function asString(value) {
133
+ return typeof value === 'string' ? value : undefined;
134
+ }
135
+ export function asInteger(value, fallback, min, max) {
136
+ const n = typeof value === 'number' ? value : Number.parseInt(String(value ?? ''), 10);
137
+ if (!Number.isFinite(n))
138
+ return fallback;
139
+ return Math.min(max, Math.max(min, Math.floor(n)));
140
+ }
141
+ /** Enabled notes only: a disabled note is invisible to the agent (agent-memory spec 5.2). */
142
+ export function visibleNotes(service) {
143
+ return service.scanFresh().filter((note) => note.enabled);
144
+ }
145
+ export function catalogRowsOf(notes) {
146
+ return notes.map(toCatalogRow);
147
+ }
148
+ export function listCandidates(rows) {
149
+ return rows.slice(0, 5).map((row) => row.id).join(', ');
150
+ }
151
+ /**
152
+ * The one place an op's raw arguments become `WriteParams`.
153
+ *
154
+ * An ABSENT scope is the documented default (`project`); a PRESENT one must be exactly one of the
155
+ * two enum values. Guessing ("Global", "repo" -> project) would file a preference the user meant to
156
+ * be global under one repository, silently.
157
+ */
158
+ export function parseWriteParams(raw) {
159
+ const op = asString(raw.op);
160
+ if (op === undefined || !OPS.includes(op)) {
161
+ return 'op must be "create", "update" or "delete".';
162
+ }
163
+ let scope = 'project';
164
+ if (raw.scope !== undefined && raw.scope !== null) {
165
+ if (raw.scope !== 'global' && raw.scope !== 'project') {
166
+ return 'scope must be exactly "project" or "global" (lowercase), or omitted for "project".';
167
+ }
168
+ scope = raw.scope;
169
+ }
170
+ const tags = Array.isArray(raw.tags)
171
+ ? raw.tags.filter((tag) => typeof tag === 'string')
172
+ : undefined;
173
+ const loadRaw = asString(raw.load);
174
+ if (loadRaw !== undefined && !isMemoryLoad(loadRaw)) {
175
+ return 'load must be "auto", "pinned" or "manual".';
176
+ }
177
+ const out = { op: op, scope };
178
+ const id = asString(raw.id);
179
+ const title = asString(raw.title);
180
+ const summary = asString(raw.summary);
181
+ const body = asString(raw.body);
182
+ const append = asString(raw.append);
183
+ const expectedRev = asString(raw.expected_rev);
184
+ if (id !== undefined)
185
+ out.id = id.trim();
186
+ if (title !== undefined)
187
+ out.title = title;
188
+ if (summary !== undefined)
189
+ out.summary = summary;
190
+ if (body !== undefined)
191
+ out.body = body;
192
+ if (append !== undefined)
193
+ out.append = append;
194
+ if (tags !== undefined)
195
+ out.tags = tags;
196
+ if (loadRaw !== undefined)
197
+ out.load = loadRaw;
198
+ if (expectedRev !== undefined)
199
+ out.expectedRev = expectedRev.trim();
200
+ return out;
201
+ }
202
+ export function normaliseTitle(title) {
203
+ return title.replace(/\s+/g, ' ').trim().toLowerCase();
204
+ }
205
+ export function scopeLabel(service, scope) {
206
+ return scope === 'global' ? 'global' : `project: ${service.getProject().label}`;
207
+ }
208
+ export function composeCreate(params) {
209
+ const verdict = validateMemoryDraft({
210
+ title: params.title ?? '',
211
+ summary: params.summary ?? '',
212
+ body: params.body ?? '',
213
+ tags: (params.tags ?? []).join(','),
214
+ load: params.load ?? 'auto',
215
+ enabled: true,
216
+ scope: params.scope,
217
+ });
218
+ return verdict.ok ? verdict.input : verdict.code;
219
+ }
220
+ export function composeUpdate(params, current) {
221
+ let body = current.body;
222
+ if (params.body !== undefined)
223
+ body = params.body;
224
+ else if (params.append !== undefined) {
225
+ body = `${current.body.replace(/\s+$/, '')}\n\n${params.append}`;
226
+ }
227
+ const bodyChanged = body !== current.body;
228
+ // A summary the code derived at create time stays derived: re-derive from the new body instead
229
+ // of leaving a stale first sentence in the catalog.
230
+ const summaryWasDerived = current.summary === deriveMemorySummary(current.body);
231
+ const summary = params.summary !== undefined
232
+ ? params.summary
233
+ : bodyChanged && summaryWasDerived
234
+ ? ''
235
+ : current.summary;
236
+ const verdict = validateMemoryDraft({
237
+ title: params.title ?? current.title,
238
+ summary,
239
+ body,
240
+ tags: (params.tags ?? current.tags).join(','),
241
+ load: params.load ?? current.load,
242
+ enabled: current.enabled,
243
+ scope: current.scope,
244
+ });
245
+ return verdict.ok ? verdict.input : verdict.code;
246
+ }
247
+ /** The sniffer's verdict for a whole draft; `null` when it is clean. */
248
+ export function secretKind(draft) {
249
+ const text = [draft.title, draft.summary, draft.body, draft.tags.join(' ')].join('\n');
250
+ const verdict = looksLikeSecret(text);
251
+ return verdict.hit ? (verdict.kind ?? 'secret') : null;
252
+ }
253
+ /**
254
+ * `true` when this note is the USER's, which makes changing it a decision they own (D-2 / I-17).
255
+ *
256
+ * `source` is the creator and never changes after `createNote` (D-21), which is the only reason
257
+ * this predicate keeps working the second time a note is edited.
258
+ */
259
+ export function isProtectedNote(note) {
260
+ return note.source !== 'agent';
261
+ }
262
+ export function logWrite(event, fields) {
263
+ try {
264
+ getLogger().info('memory', event, fields);
265
+ }
266
+ catch {
267
+ // Logging must never fail a tool.
268
+ }
269
+ }
270
+ export function resolveTarget(service, ref) {
271
+ const notes = visibleNotes(service);
272
+ const found = resolveMemoryRef(catalogRowsOf(notes), ref, { allowIndex: false, allowTitle: false });
273
+ if (!found.ok) {
274
+ return found.code === 'ambiguous'
275
+ ? { ok: false, code: 'ambiguous', candidates: found.candidates.map((row) => row.id) }
276
+ : { ok: false, code: 'not_found' };
277
+ }
278
+ const fresh = readNote(service.targetOf(found.row.scope), found.row.id);
279
+ return fresh.ok ? { ok: true, note: fresh.value } : { ok: false, code: fresh.code };
280
+ }
281
+ /** The tool-result shape of {@link resolveTarget}: one refusal sentence instead of a code. */
282
+ export function findTarget(service, ref, fail) {
283
+ const found = resolveTarget(service, ref);
284
+ if (found.ok)
285
+ return found;
286
+ if (found.code === 'ambiguous') {
287
+ return {
288
+ ok: false,
289
+ result: fail('ambiguous', `Candidates: ${listCandidates((found.candidates ?? []).map((id) => ({ id })))}.`),
290
+ };
291
+ }
292
+ return { ok: false, result: fail(found.code) };
293
+ }
294
+ /** Ask a human, and be honest about the three possible answers (memory-agent-autonomy D-9). */
295
+ export async function requestApproval(ports, tool, summary, signal) {
296
+ // PROBE FIRST, live. When nobody can be asked the answer is NOT "yes": `confirm`'s unattached
297
+ // fallback is `true`, which is why writes never go through it. Here a missing channel is its own
298
+ // answer, so the model can be told something it can act on.
299
+ if (!ports.approval.canPrompt())
300
+ return 'unavailable';
301
+ const approved = await ports.withHumanWait(() => ports.approval.request({ tool, summary, ...(signal ? { signal } : {}) }));
302
+ if (signal?.aborted === true)
303
+ return 'declined';
304
+ return approved === true ? 'approved' : 'declined';
305
+ }
@@ -1,36 +1,27 @@
1
1
  /**
2
2
  * `memory_search`, `memory_read` and `memory_write` (agent-memory spec 7).
3
3
  *
4
- * ASCII ONLY - `src/memory/**` is inside `glyphs.test.ts::inScope`. Everything the model
5
- * reads is English (D-26); the user's notes are quoted verbatim in their own language.
4
+ * ASCII ONLY - `src/memory/**` is inside `glyphs.test.ts::inScope`. Everything the model reads is
5
+ * English (D-26); the user's notes are quoted verbatim in their own language.
6
6
  *
7
- * PROGRESSIVE DISCLOSURE, ENFORCED BY SHAPE (D-6). Search returns at most ten one-line
8
- * rows and NEVER a body; read returns at most 6,000 characters and a cursor; write returns a
9
- * one-line receipt plus the new catalog line. Together with the three short descriptions
10
- * (budget-tested), the whole tool surface costs the model a few hundred tokens until it
11
- * actually uses it.
7
+ * PROGRESSIVE DISCLOSURE, ENFORCED BY SHAPE (D-6). Search returns at most ten one-line rows and
8
+ * NEVER a body; read returns at most 6,000 characters and a cursor; write returns a one-line receipt
9
+ * plus the new catalog line. Together with the short descriptions (budget-tested), the whole tool
10
+ * surface costs the model a few hundred tokens until it actually uses it.
12
11
  *
13
- * WRITES ARE THE USER'S ACTION, DONE BY THE AGENT'S HAND (D-7 / I-1 / I-13). Under the
14
- * default policy every `memory_write` stops at a full preview and waits. The wait is on an
15
- * `ApprovalGate` - NOT on `confirm`, whose "no human attached" fallback is `true`: a
16
- * channel that approves when nobody can be asked would turn the main defence against memory
17
- * poisoning (T1) into a no-op without a single error. When nobody can be asked, the answer
18
- * is `declined` and nothing is written.
12
+ * A SMALL WRITE NO LONGER STOPS FOR A HUMAN (memory-agent-autonomy D-1 / R1). The decision moved
13
+ * out of this file into `tui/model/memory/autonomy.ts`, where it is a nine-step table a test can
14
+ * walk: a small change on a note of the agent's own making, inside both budgets, is applied and
15
+ * journalled; a large one, or one that touches a note the user wrote, is still confirmed. What did
16
+ * NOT move is the part that made the old design safe: when nobody can be asked, the answer is not
17
+ * "yes" - `approval_unavailable`, not `declined`-with-a-shrug, because the model can act on the
18
+ * difference (D-9).
19
+ *
20
+ * VALIDATION ORDER IS UNCHANGED AND DELIBERATE: shape, draft, secret, duplicate title, room, THEN
21
+ * the human. Nobody should ever be asked to approve a write that was already going to fail.
19
22
  */
20
23
  import { type AgentTool } from '@aragon-agent/core';
21
- import type { ApprovalGate } from '../skills/service.js';
22
- import type { MemoryService } from './service.js';
23
- export interface MemoryToolPorts {
24
- service: MemoryService;
25
- approval: ApprovalGate;
26
- /** Pauses the idle watchdog while a human reads the preview. */
27
- withHumanWait<T>(fn: () => Promise<T>): Promise<T>;
28
- /** `memory.enabled`, read LIVE: a session cannot unregister tools, only refuse them. */
29
- isEnabled(): boolean;
30
- /** Effective write policy, read LIVE (a session can switch `ask` <-> `auto`). */
31
- agentWrites(): 'ask' | 'auto' | 'off';
32
- /** Register `memory_write` at all (false when `memory.agentWrites` is `off`). */
33
- includeWrite: boolean;
34
- }
35
- /** The tools to register, in registration order. `memory_write` only when allowed. */
24
+ import { type MemoryToolPorts } from './tools-shared.js';
25
+ export type { MemoryToolPorts } from './tools-shared.js';
26
+ /** The tools to register, in registration order. The write pair only when allowed. */
36
27
  export declare function createMemoryTools(ports: MemoryToolPorts): AgentTool[];