@aragon-agent/cli 0.6.70 → 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.
- package/CHANGELOG.md +20 -0
- package/README.md +33 -14
- package/dist/agent/controller.d.ts +25 -1
- package/dist/agent/controller.js +78 -3
- package/dist/agent/project-guidance-prompt.js +97 -97
- package/dist/app/App.d.ts +12 -3
- package/dist/app/App.js +25 -2
- package/dist/cli.js +2 -2
- package/dist/commands/catalog.js +1 -1
- package/dist/config/cli-commands.d.ts +1 -1
- package/dist/config/cli-commands.js +4 -0
- package/dist/config/env.js +6 -0
- package/dist/config/load.js +36 -1
- package/dist/governance/engine/lifecycle.js +1 -1
- package/dist/governance/prompts/orchestrator-block.js +3 -3
- package/dist/host/controller-factory.d.ts +15 -0
- package/dist/host/controller-factory.js +10 -2
- package/dist/host/memory.d.ts +5 -1
- package/dist/host/memory.js +13 -0
- package/dist/memory/block.d.ts +38 -4
- package/dist/memory/block.js +52 -5
- package/dist/memory/command.js +56 -2
- package/dist/memory/journal.d.ts +58 -0
- package/dist/memory/journal.js +202 -0
- package/dist/memory/ledger.d.ts +54 -0
- package/dist/memory/ledger.js +105 -0
- package/dist/memory/paths.d.ts +10 -0
- package/dist/memory/paths.js +31 -0
- package/dist/memory/service.d.ts +54 -1
- package/dist/memory/service.js +156 -1
- package/dist/memory/store.d.ts +21 -3
- package/dist/memory/store.js +66 -6
- package/dist/memory/tools-batch.d.ts +27 -0
- package/dist/memory/tools-batch.js +462 -0
- package/dist/memory/tools-shared.d.ts +176 -0
- package/dist/memory/tools-shared.js +305 -0
- package/dist/memory/tools.d.ts +19 -28
- package/dist/memory/tools.js +148 -228
- package/dist/memory/undo.d.ts +53 -0
- package/dist/memory/undo.js +173 -0
- package/dist/redteam/prompt-template.js +16 -16
- package/dist/tools/index.d.ts +2 -2
- package/dist/tools/index.js +16 -1
- package/package.json +3 -3
- package/runtime/insecure-tls-warning.cjs +62 -62
- package/runtime/insecure-tls-warning.d.cts +5 -5
- package/skills/project-indexer/templates/artifact-hygiene-template.md +14 -14
|
@@ -0,0 +1,462 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `memory_batch`: several memory changes in one request, one approval for the whole plan
|
|
3
|
+
* (memory-agent-autonomy spec 7.2).
|
|
4
|
+
*
|
|
5
|
+
* ASCII ONLY - `src/memory/**` is inside `glyphs.test.ts::inScope`. Everything the model reads is
|
|
6
|
+
* English (agent-memory D-26); the user's own words appear only inside quoted titles.
|
|
7
|
+
*
|
|
8
|
+
* WHY A SECOND TOOL AND NOT A LOOP OF `memory_write`. A sweep that merges duplicates or retags ten
|
|
9
|
+
* notes is one decision for the user, not ten; asking ten times is how approval degrades into a
|
|
10
|
+
* reflex (D-3). And the whole batch has to be validated BEFORE anyone is asked, or the confirmation
|
|
11
|
+
* card and the execution disagree (D-11 / D-12).
|
|
12
|
+
*
|
|
13
|
+
* THREE RULES THAT ARE NOT NEGOTIABLE:
|
|
14
|
+
* - ALL OR NOTHING AT VALIDATION: one bad op refuses the batch, with the first few failing
|
|
15
|
+
* indexes, and not a byte is written.
|
|
16
|
+
* - A SECRET REFUSES THE WHOLE BATCH, before the card: half a batch is not a state anyone can
|
|
17
|
+
* reason about afterwards.
|
|
18
|
+
* - EXECUTION STOPS AT THE FIRST `conflict` / `write_failed` (D-13), and reports "applied N of
|
|
19
|
+
* M" plus the batch id, so what landed can still be undone as one unit.
|
|
20
|
+
*
|
|
21
|
+
* THIS FILE EXISTS FOR THE 1000-LINE CEILING (RV-P1-10): `tools.ts` was already 641 lines, and the
|
|
22
|
+
* shape -> validate -> secret -> decide -> card -> execute -> journal -> receipt chain below is
|
|
23
|
+
* roughly 220 of them.
|
|
24
|
+
*/
|
|
25
|
+
import { defineTool, textResult } from '@aragon-agent/core';
|
|
26
|
+
import { mintBatchId } from '@aragon-agent/tui/model/memory/activity';
|
|
27
|
+
import { MEMORY_LIMITS } from '@aragon-agent/tui/model/memory/limits';
|
|
28
|
+
import { codePointCount } from '@aragon-agent/tui/model/memory/validate';
|
|
29
|
+
import { catalogLine } from './block.js';
|
|
30
|
+
import { createNote, trashNote, updateNote } from './store.js';
|
|
31
|
+
import { clipBatchCard, composeCreate, composeUpdate, isProtectedNote, logWrite, makeWriteError, normaliseTitle, parseWriteParams, requestApproval, resolveTarget, scopeLabel, secretKind, visibleNotes, askWhyCopy, } from './tools-shared.js';
|
|
32
|
+
const writeError = makeWriteError('memory_batch');
|
|
33
|
+
/** Step 1: the argument's own shape. */
|
|
34
|
+
function parseBatchArgs(raw) {
|
|
35
|
+
const rawOps = raw.ops;
|
|
36
|
+
if (!Array.isArray(rawOps))
|
|
37
|
+
return 'ops must be an array of change objects.';
|
|
38
|
+
if (rawOps.length === 0) {
|
|
39
|
+
return 'ops is empty: say nothing changed instead of sending an empty batch.';
|
|
40
|
+
}
|
|
41
|
+
if (rawOps.length > MEMORY_LIMITS.batchMaxOps) {
|
|
42
|
+
// ITS OWN CODE, not `invalid_argument` (spec 7.3): "your batch is too big" is a limit the model
|
|
43
|
+
// can do something about (split it), while "a parameter is malformed" reads as a bug in its
|
|
44
|
+
// own call. The two sentences are already different in the error table.
|
|
45
|
+
return `batch_too_large: ${rawOps.length} entries; at most ` +
|
|
46
|
+
`${MEMORY_LIMITS.batchMaxOps} fit in one batch.`;
|
|
47
|
+
}
|
|
48
|
+
const reason = typeof raw.reason === 'string' ? raw.reason.trim() : '';
|
|
49
|
+
if (reason.length === 0)
|
|
50
|
+
return 'reason is required: one line for the user about why this batch.';
|
|
51
|
+
if (codePointCount(reason) > 120)
|
|
52
|
+
return 'reason must be at most 120 characters.';
|
|
53
|
+
const ops = [];
|
|
54
|
+
for (const entry of rawOps) {
|
|
55
|
+
if (entry === null || typeof entry !== 'object' || Array.isArray(entry)) {
|
|
56
|
+
return 'every entry of ops must be an object.';
|
|
57
|
+
}
|
|
58
|
+
ops.push(entry);
|
|
59
|
+
}
|
|
60
|
+
return { ops, reason };
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* Step 2: validate every op against the directory as it is NOW, and collect what the card shows.
|
|
64
|
+
*
|
|
65
|
+
* Nothing is written here. A missing `expected_rev`, an id that does not resolve, a title that
|
|
66
|
+
* clashes, a full scope: each becomes a failure with its index, and one failure refuses the batch.
|
|
67
|
+
*/
|
|
68
|
+
function planBatch(ports, ops) {
|
|
69
|
+
const planned = [];
|
|
70
|
+
const failures = [];
|
|
71
|
+
const secrets = [];
|
|
72
|
+
const createdTitles = new Set();
|
|
73
|
+
ops.forEach((raw, index) => {
|
|
74
|
+
const one = planOne(ports, raw, index, createdTitles);
|
|
75
|
+
if (one.code !== null) {
|
|
76
|
+
failures.push({ index, code: one.code });
|
|
77
|
+
return;
|
|
78
|
+
}
|
|
79
|
+
if (one.secret)
|
|
80
|
+
secrets.push(index);
|
|
81
|
+
if (one.op !== null)
|
|
82
|
+
planned.push(one.op);
|
|
83
|
+
});
|
|
84
|
+
if (failures.length > 0)
|
|
85
|
+
return { ok: false, failures: failures.slice(0, 5) };
|
|
86
|
+
return { ok: true, ops: planned, secrets };
|
|
87
|
+
}
|
|
88
|
+
function planOne(ports, raw, index, createdTitles) {
|
|
89
|
+
const params = parseWriteParams(raw);
|
|
90
|
+
if (typeof params === 'string')
|
|
91
|
+
return { op: null, code: 'invalid_argument', secret: false };
|
|
92
|
+
if (params.body !== undefined && params.append !== undefined) {
|
|
93
|
+
return { op: null, code: 'invalid_argument', secret: false };
|
|
94
|
+
}
|
|
95
|
+
if (params.op !== 'create') {
|
|
96
|
+
if (params.id === undefined || params.id.length === 0) {
|
|
97
|
+
return { op: null, code: 'invalid_argument', secret: false };
|
|
98
|
+
}
|
|
99
|
+
if (params.expectedRev === undefined || params.expectedRev.length === 0) {
|
|
100
|
+
return { op: null, code: 'invalid_argument', secret: false };
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
return params.op === 'create'
|
|
104
|
+
? planCreate(ports, params, index, createdTitles)
|
|
105
|
+
: planChange(ports, params, index);
|
|
106
|
+
}
|
|
107
|
+
function planCreate(ports, params, index, createdTitles) {
|
|
108
|
+
const draft = composeCreate(params);
|
|
109
|
+
if (typeof draft === 'string')
|
|
110
|
+
return { op: null, code: draft, secret: false };
|
|
111
|
+
const inScope = visibleNotes(ports.service).filter((note) => note.scope === draft.scope);
|
|
112
|
+
const wanted = normaliseTitle(draft.title);
|
|
113
|
+
if (createdTitles.has(`${draft.scope}:${wanted}`))
|
|
114
|
+
return { op: null, code: 'duplicate_title', secret: false };
|
|
115
|
+
if (inScope.some((note) => normaliseTitle(note.title) === wanted)) {
|
|
116
|
+
return { op: null, code: 'duplicate_title', secret: false };
|
|
117
|
+
}
|
|
118
|
+
if (inScope.length >= MEMORY_LIMITS.maxNotesPerScope)
|
|
119
|
+
return { op: null, code: 'limit_reached', secret: false };
|
|
120
|
+
createdTitles.add(`${draft.scope}:${wanted}`);
|
|
121
|
+
return {
|
|
122
|
+
op: {
|
|
123
|
+
index,
|
|
124
|
+
op: 'create',
|
|
125
|
+
scope: draft.scope,
|
|
126
|
+
id: null,
|
|
127
|
+
title: draft.title,
|
|
128
|
+
delta: codePointCount(draft.body),
|
|
129
|
+
protected: false,
|
|
130
|
+
current: null,
|
|
131
|
+
draft,
|
|
132
|
+
expectedRev: null,
|
|
133
|
+
append: undefined,
|
|
134
|
+
},
|
|
135
|
+
code: null,
|
|
136
|
+
secret: secretKind(draft) !== null,
|
|
137
|
+
};
|
|
138
|
+
}
|
|
139
|
+
function planChange(ports, params, index) {
|
|
140
|
+
const found = resolveTarget(ports.service, params.id);
|
|
141
|
+
if (!found.ok)
|
|
142
|
+
return { op: null, code: found.code, secret: false };
|
|
143
|
+
const current = found.note;
|
|
144
|
+
if (params.op === 'delete') {
|
|
145
|
+
return {
|
|
146
|
+
op: {
|
|
147
|
+
index,
|
|
148
|
+
op: 'delete',
|
|
149
|
+
scope: current.scope,
|
|
150
|
+
id: current.id,
|
|
151
|
+
title: current.title,
|
|
152
|
+
delta: -current.bodyChars,
|
|
153
|
+
protected: isProtectedNote(current),
|
|
154
|
+
current,
|
|
155
|
+
draft: null,
|
|
156
|
+
expectedRev: params.expectedRev,
|
|
157
|
+
append: undefined,
|
|
158
|
+
},
|
|
159
|
+
code: null,
|
|
160
|
+
secret: false,
|
|
161
|
+
};
|
|
162
|
+
}
|
|
163
|
+
const draft = composeUpdate(params, current);
|
|
164
|
+
if (typeof draft === 'string')
|
|
165
|
+
return { op: null, code: draft, secret: false };
|
|
166
|
+
const clash = visibleNotes(ports.service).find((note) => note.scope === current.scope &&
|
|
167
|
+
note.id !== current.id &&
|
|
168
|
+
normaliseTitle(note.title) === normaliseTitle(draft.title));
|
|
169
|
+
if (clash !== undefined)
|
|
170
|
+
return { op: null, code: 'duplicate_title', secret: false };
|
|
171
|
+
return {
|
|
172
|
+
op: {
|
|
173
|
+
index,
|
|
174
|
+
op: 'update',
|
|
175
|
+
scope: current.scope,
|
|
176
|
+
id: current.id,
|
|
177
|
+
title: draft.title,
|
|
178
|
+
delta: codePointCount(draft.body) - current.bodyChars,
|
|
179
|
+
protected: isProtectedNote(current),
|
|
180
|
+
current,
|
|
181
|
+
draft,
|
|
182
|
+
expectedRev: params.expectedRev,
|
|
183
|
+
append: params.append,
|
|
184
|
+
},
|
|
185
|
+
code: null,
|
|
186
|
+
secret: secretKind(draft) !== null,
|
|
187
|
+
};
|
|
188
|
+
}
|
|
189
|
+
/** The intent the policy layer reads: size, protected targets and per-note churn (spec 6.1). */
|
|
190
|
+
function intentOf(ports, ops) {
|
|
191
|
+
const state = ports.autonomyState();
|
|
192
|
+
const churnIds = ops
|
|
193
|
+
.filter((op) => op.id !== null)
|
|
194
|
+
.map((op) => ({ id: op.id, used: state.turnIds[op.id] ?? 0 }));
|
|
195
|
+
return {
|
|
196
|
+
opCount: ops.length,
|
|
197
|
+
protectedCount: ops.filter((op) => op.protected).length,
|
|
198
|
+
churnIds,
|
|
199
|
+
};
|
|
200
|
+
}
|
|
201
|
+
function deltaText(delta) {
|
|
202
|
+
if (delta === null || delta === 0)
|
|
203
|
+
return '0';
|
|
204
|
+
return `${delta > 0 ? '+' : ''}${delta}`;
|
|
205
|
+
}
|
|
206
|
+
/** The card. `Why:` is its second line and is never trimmed (RV-P1-2 / RV-P2-7). */
|
|
207
|
+
function batchCard(ports, ops, reason, why) {
|
|
208
|
+
const scope = scopeLabel(ports.service, ops[0]?.scope ?? 'project');
|
|
209
|
+
const header = [
|
|
210
|
+
`Memory batch: ${ops.length} changes (${scope})`,
|
|
211
|
+
`Why: ${why}`,
|
|
212
|
+
`reason: ${reason}`,
|
|
213
|
+
'# op id title delta',
|
|
214
|
+
];
|
|
215
|
+
const rows = ops.map((op, offset) => {
|
|
216
|
+
const id = op.id ?? '-';
|
|
217
|
+
return `${offset + 1} ${op.op.padEnd(7)} ${id.padEnd(11)} ${op.title.slice(0, 28).padEnd(29)} ${deltaText(op.delta)}`;
|
|
218
|
+
});
|
|
219
|
+
const counts = countOps(ops);
|
|
220
|
+
const mine = ops.filter((op) => op.protected).length;
|
|
221
|
+
// LABELLED `Total:`, BECAUSE THE ONE LINE THAT IS NEVER TRIMMED HAS TO BE NAMED (spec 7.2 /
|
|
222
|
+
// appendix B). An unlabelled aggregate reads as another row of the table, and "the total was not
|
|
223
|
+
// cut away" is unverifiable when nothing says which line the total is.
|
|
224
|
+
const total = `Total: ${counts.create} new, ${counts.update} edits, ${counts.delete} deletes.` +
|
|
225
|
+
(mine > 0 ? ` ${mine} of them are yours (yours need your OK).` : '');
|
|
226
|
+
const footer = ['------------', total, 'Undo is available for 30 days: /memory undo', '[y] approve all [n] decline [Esc] decline'];
|
|
227
|
+
return clipBatchCard(header, rows, footer);
|
|
228
|
+
}
|
|
229
|
+
function countOps(ops) {
|
|
230
|
+
const counts = { create: 0, update: 0, delete: 0 };
|
|
231
|
+
for (const op of ops)
|
|
232
|
+
counts[op.op] += 1;
|
|
233
|
+
return counts;
|
|
234
|
+
}
|
|
235
|
+
/** What the model is told after a batch: what landed, what did not, and the id that ties it. */
|
|
236
|
+
function batchReceipt(input) {
|
|
237
|
+
const head = input.applied === input.total
|
|
238
|
+
? `Applied ${input.applied} of ${input.total} (batch ${input.batch}). ` +
|
|
239
|
+
`${input.counts.create} created, ${input.counts.update} updated, ${input.counts.delete} deleted.`
|
|
240
|
+
: `Applied ${input.applied} of ${input.total} (batch ${input.batch}); ` +
|
|
241
|
+
`${input.total - input.applied} not attempted: ${input.stoppedAt?.code ?? 'stopped'} on ` +
|
|
242
|
+
`${input.stoppedAt?.id ?? 'a note'}.`;
|
|
243
|
+
const tail = input.applied > 0
|
|
244
|
+
? 'The user can undo the whole batch with /memory undo; you cannot. ' +
|
|
245
|
+
'Applied notes appear in the catalog from the next message.'
|
|
246
|
+
: 'Nothing was written.';
|
|
247
|
+
// FIVE LINES, THEN A COUNT (spec 7.2 step 8). Every applied op used to be listed, so a 20-op
|
|
248
|
+
// batch put twenty lines into the model's context to say what one line already said.
|
|
249
|
+
const shown = input.lines.slice(0, MEMORY_LIMITS.batchReceiptLines);
|
|
250
|
+
const more = input.lines.length > shown.length ? [`... +${input.lines.length - shown.length} more`] : [];
|
|
251
|
+
return [head, ...shown, ...more, tail].join('\n');
|
|
252
|
+
}
|
|
253
|
+
export function batchTool(ports) {
|
|
254
|
+
return defineTool({
|
|
255
|
+
name: 'memory_batch',
|
|
256
|
+
label: 'Batch memory',
|
|
257
|
+
description: 'Change several saved memories in one request - one approval covers the whole plan.\n' +
|
|
258
|
+
'Use it to merge duplicates, retag or prune: prefer this over repeated memory_write when one ' +
|
|
259
|
+
'request would touch several notes. Every op is validated first; nothing is written unless ' +
|
|
260
|
+
'the whole plan is valid. Nothing to change? Say so instead of sending an empty batch.',
|
|
261
|
+
parameters: {
|
|
262
|
+
type: 'object',
|
|
263
|
+
properties: {
|
|
264
|
+
ops: {
|
|
265
|
+
type: 'array',
|
|
266
|
+
maxItems: MEMORY_LIMITS.batchMaxOps,
|
|
267
|
+
description: `Up to ${MEMORY_LIMITS.batchMaxOps} ops; each takes the same fields as memory_write.`,
|
|
268
|
+
items: {
|
|
269
|
+
type: 'object',
|
|
270
|
+
properties: {
|
|
271
|
+
op: { type: 'string', enum: ['create', 'update', 'delete'] },
|
|
272
|
+
id: { type: 'string', description: 'update/delete: note id.' },
|
|
273
|
+
scope: { type: 'string', enum: ['project', 'global'], description: 'create only.' },
|
|
274
|
+
title: { type: 'string', description: 'Up to 80 chars.' },
|
|
275
|
+
summary: { type: 'string', description: 'Up to 200 chars.' },
|
|
276
|
+
body: { type: 'string', description: 'Up to 8000 chars.' },
|
|
277
|
+
append: { type: 'string', description: 'update only: added after a blank line.' },
|
|
278
|
+
tags: { type: 'array', items: { type: 'string' }, description: 'Up to 6 tags.' },
|
|
279
|
+
load: { type: 'string', enum: ['auto', 'pinned', 'manual'] },
|
|
280
|
+
expected_rev: { type: 'string', description: 'update/delete: rev from memory_read.' },
|
|
281
|
+
},
|
|
282
|
+
required: ['op'],
|
|
283
|
+
},
|
|
284
|
+
},
|
|
285
|
+
reason: { type: 'string', description: 'One line for the user: why this batch.' },
|
|
286
|
+
},
|
|
287
|
+
required: ['ops', 'reason'],
|
|
288
|
+
},
|
|
289
|
+
async execute(_id, rawParams, ctx) {
|
|
290
|
+
return runBatch(ports, rawParams, ctx?.signal);
|
|
291
|
+
},
|
|
292
|
+
});
|
|
293
|
+
}
|
|
294
|
+
async function runBatch(ports, raw, signal) {
|
|
295
|
+
// 1. Policy and shape. Same gate as `memory_write`: a disabled feature refuses, it cannot
|
|
296
|
+
// unregister itself at run time.
|
|
297
|
+
if (!ports.isEnabled() || ports.agentWrites() === 'off')
|
|
298
|
+
return writeError('disabled');
|
|
299
|
+
const args = parseBatchArgs(raw);
|
|
300
|
+
if (typeof args === 'string') {
|
|
301
|
+
// `parseBatchArgs` prefixes the one code it raises itself; everything else it returns is a
|
|
302
|
+
// malformed argument.
|
|
303
|
+
if (args.startsWith('batch_too_large:'))
|
|
304
|
+
return writeError('batch_too_large', args.slice(16).trim());
|
|
305
|
+
return writeError('invalid_argument', args);
|
|
306
|
+
}
|
|
307
|
+
// 2. Validate every op; all or nothing (D-12).
|
|
308
|
+
const plan = planBatch(ports, args.ops);
|
|
309
|
+
if (!plan.ok) {
|
|
310
|
+
const detail = plan.failures.map((failure) => `index ${failure.index}: ${failure.code}`).join('; ');
|
|
311
|
+
logWrite('batch_refused', { code: 'batch_invalid', count: args.ops.length });
|
|
312
|
+
return writeError('batch_invalid', detail);
|
|
313
|
+
}
|
|
314
|
+
// 3. Secrets before the human is asked, exactly like a single write: never ask about a write that
|
|
315
|
+
// is already doomed, and never half-apply one (D-11).
|
|
316
|
+
if (plan.secrets.length > 0) {
|
|
317
|
+
logWrite('batch_refused', { code: 'secret_detected', indexes: plan.secrets.join(',') });
|
|
318
|
+
return writeError('secret_detected', `indexes ${plan.secrets.join(', ')}.`);
|
|
319
|
+
}
|
|
320
|
+
// 4. The policy verdict.
|
|
321
|
+
const intent = intentOf(ports, plan.ops);
|
|
322
|
+
const decision = ports.decide(intent);
|
|
323
|
+
if (decision.kind === 'refuse') {
|
|
324
|
+
logWrite('batch_refused', { code: decision.code, count: plan.ops.length });
|
|
325
|
+
// No `decision.hint` here: `ERROR_TEXT` already carries the same sentence for these codes.
|
|
326
|
+
return writeError(decision.code);
|
|
327
|
+
}
|
|
328
|
+
// 5. One approval for the whole plan.
|
|
329
|
+
if (decision.kind === 'confirm') {
|
|
330
|
+
const policy = ports.service.autonomyPolicy();
|
|
331
|
+
const why = askWhyCopy(ports, decision, intent);
|
|
332
|
+
const outcome = await requestApproval(ports, 'memory_batch', batchCard(ports, plan.ops, args.reason, why), signal);
|
|
333
|
+
if (outcome === 'unavailable') {
|
|
334
|
+
logWrite('batch_refused', { code: 'approval_unavailable', count: plan.ops.length });
|
|
335
|
+
return writeError('approval_unavailable', `Split it into fewer than ${policy.bulkThreshold} writes.`);
|
|
336
|
+
}
|
|
337
|
+
if (outcome === 'declined') {
|
|
338
|
+
ports.service.noteDeclined(decision);
|
|
339
|
+
// THE SECOND DECLINE IS THE ONE THE USER HAS TO HEAR ABOUT, batch or not (spec 7.4): the
|
|
340
|
+
// counter is shared with `memory_write`, so a batch decline can be what silences the turn and
|
|
341
|
+
// staying quiet here would leave that without a word.
|
|
342
|
+
ports.onDenied(ports.autonomyState().deniedTurn >= MEMORY_LIMITS.deniedPerTurn ? 'paused' : 'declined');
|
|
343
|
+
return declined(decision.reason);
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
// 6-8. Execute, journal, report.
|
|
347
|
+
return executeBatch(ports, plan.ops, args.reason, decision.kind === 'confirm' ? decision : { kind: 'allow' });
|
|
348
|
+
}
|
|
349
|
+
function declined(reason) {
|
|
350
|
+
logWrite('batch_declined', { reason });
|
|
351
|
+
return writeError('declined');
|
|
352
|
+
}
|
|
353
|
+
function executeBatch(ports, ops, reason, decision) {
|
|
354
|
+
const batch = mintBatchId();
|
|
355
|
+
const counts = { create: 0, update: 0, delete: 0 };
|
|
356
|
+
const lines = [];
|
|
357
|
+
let applied = 0;
|
|
358
|
+
let stoppedAt = null;
|
|
359
|
+
for (const op of ops) {
|
|
360
|
+
const outcome = executeOne(ports, op, { batch, reason, plan: ops.length }, counts);
|
|
361
|
+
if (!outcome.ok) {
|
|
362
|
+
stoppedAt = { id: op.id ?? op.title, code: outcome.code };
|
|
363
|
+
break;
|
|
364
|
+
}
|
|
365
|
+
applied += 1;
|
|
366
|
+
lines.push(`${applied}. ${outcome.op} ${outcome.id} - ${outcome.note}`);
|
|
367
|
+
}
|
|
368
|
+
// NOTHING LANDED: leave the session exactly as it was. D-13 stops at the first conflict, and a
|
|
369
|
+
// rebuild of the prompt for a batch that wrote zero bytes is a re-scan that reports a change.
|
|
370
|
+
if (applied > 0)
|
|
371
|
+
ports.service.noteChanged();
|
|
372
|
+
ports.service.noteApplied(decision, intentOf(ports, ops), applied);
|
|
373
|
+
notify(ports, applied, ops.length, counts, stoppedAt);
|
|
374
|
+
if (applied === 0) {
|
|
375
|
+
return writeError(stoppedAt?.code ?? 'write_failed', `${stoppedAt?.id ?? 'a note'} was not written.`);
|
|
376
|
+
}
|
|
377
|
+
return textResult(batchReceipt({ batch, applied, total: ops.length, counts, stoppedAt, lines }));
|
|
378
|
+
}
|
|
379
|
+
function executeOne(ports, op, ctx, counts) {
|
|
380
|
+
const service = ports.service;
|
|
381
|
+
const target = service.targetOf(op.scope);
|
|
382
|
+
const opts = { ...service.writeOptions('agent'), rejectDuplicateTitle: true };
|
|
383
|
+
if (op.op === 'create' && op.draft !== null) {
|
|
384
|
+
const created = createNote(target, op.draft, opts);
|
|
385
|
+
if (!created.ok)
|
|
386
|
+
return { ok: false, code: created.code };
|
|
387
|
+
counts.create += 1;
|
|
388
|
+
service.journalAppend({
|
|
389
|
+
actor: 'agent',
|
|
390
|
+
batch: ctx.batch,
|
|
391
|
+
op: 'create',
|
|
392
|
+
id: created.value.id,
|
|
393
|
+
scope: created.value.scope,
|
|
394
|
+
title: created.value.title,
|
|
395
|
+
delta: created.value.bodyChars,
|
|
396
|
+
rev: created.value.rev,
|
|
397
|
+
prev: null,
|
|
398
|
+
trash: null,
|
|
399
|
+
reason: ctx.reason,
|
|
400
|
+
plan: ctx.plan,
|
|
401
|
+
});
|
|
402
|
+
return { ok: true, op: 'create', id: created.value.id, note: catalogLine(created.value) };
|
|
403
|
+
}
|
|
404
|
+
if (op.id === null || op.expectedRev === null)
|
|
405
|
+
return { ok: false, code: 'invalid_argument' };
|
|
406
|
+
if (op.op === 'update' && op.draft !== null) {
|
|
407
|
+
const updated = updateNote(target, op.id, op.draft, op.expectedRev, opts);
|
|
408
|
+
if (!updated.ok)
|
|
409
|
+
return { ok: false, code: updated.code };
|
|
410
|
+
counts.update += 1;
|
|
411
|
+
service.journalAppend({
|
|
412
|
+
actor: 'agent',
|
|
413
|
+
batch: ctx.batch,
|
|
414
|
+
op: 'update',
|
|
415
|
+
id: op.id,
|
|
416
|
+
scope: op.scope,
|
|
417
|
+
title: updated.value.title,
|
|
418
|
+
delta: updated.value.bodyChars - (op.current?.bodyChars ?? updated.value.bodyChars),
|
|
419
|
+
rev: updated.value.rev,
|
|
420
|
+
prev: updated.backupFile ?? null,
|
|
421
|
+
trash: null,
|
|
422
|
+
reason: ctx.reason,
|
|
423
|
+
plan: ctx.plan,
|
|
424
|
+
});
|
|
425
|
+
return { ok: true, op: 'update', id: op.id, note: `rev ${updated.value.rev}` };
|
|
426
|
+
}
|
|
427
|
+
// EXPLICIT, NOT A FALL-THROUGH. The two branches above are `create` and `update`; anything that is
|
|
428
|
+
// neither is refused here rather than silently executed as a delete. Today `planBatch` always pairs
|
|
429
|
+
// an `update` with a draft, but the day it stops doing that is the day this branch would otherwise
|
|
430
|
+
// delete the note it was asked to edit.
|
|
431
|
+
if (op.op !== 'delete')
|
|
432
|
+
return { ok: false, code: 'invalid_argument' };
|
|
433
|
+
const trashed = trashNote(target, op.id, op.expectedRev, opts.now ?? Date.now());
|
|
434
|
+
if (!trashed.ok)
|
|
435
|
+
return { ok: false, code: trashed.code };
|
|
436
|
+
counts.delete += 1;
|
|
437
|
+
service.journalAppend({
|
|
438
|
+
actor: 'agent',
|
|
439
|
+
batch: ctx.batch,
|
|
440
|
+
op: 'delete',
|
|
441
|
+
id: op.id,
|
|
442
|
+
scope: op.scope,
|
|
443
|
+
title: op.title,
|
|
444
|
+
delta: -(op.current?.bodyChars ?? 0),
|
|
445
|
+
rev: op.expectedRev,
|
|
446
|
+
prev: null,
|
|
447
|
+
trash: trashed.value.trashId,
|
|
448
|
+
reason: ctx.reason,
|
|
449
|
+
plan: ctx.plan,
|
|
450
|
+
});
|
|
451
|
+
return { ok: true, op: 'delete', id: op.id, note: 'moved to the trash' };
|
|
452
|
+
}
|
|
453
|
+
/** The one-line receipt a surface shows, in words from `copy.ts` (never here). */
|
|
454
|
+
function notify(ports, applied, total, counts, stoppedAt) {
|
|
455
|
+
if (applied === 0)
|
|
456
|
+
return;
|
|
457
|
+
if (applied === total) {
|
|
458
|
+
ports.onApplied({ kind: 'batch', counts });
|
|
459
|
+
return;
|
|
460
|
+
}
|
|
461
|
+
ports.onApplied({ kind: 'partial', applied, total, id: stoppedAt?.id ?? '' });
|
|
462
|
+
}
|
|
@@ -0,0 +1,176 @@
|
|
|
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 { type ToolResult } from '@aragon-agent/core';
|
|
17
|
+
import type { MemoryCatalogRow, MemoryDraftInput, MemoryNote, MemoryNoteLoad, MemoryNoteScope, MemoryWriteError } from '@aragon-agent/tui/model/memory/types';
|
|
18
|
+
import type { ApprovalGate } from '../skills/service.js';
|
|
19
|
+
import type { MemoryService } from './service.js';
|
|
20
|
+
import type { MemoryAutonomyState, MemoryWriteDecision, MemoryWriteIntent } from '@aragon-agent/tui/model/memory/types';
|
|
21
|
+
/**
|
|
22
|
+
* What one applied write tells the session, so a surface can say it in the user's language.
|
|
23
|
+
*
|
|
24
|
+
* The tools speak English to the model; the receipt is the SHAPE, and `copy.ts` picks the words
|
|
25
|
+
* (D-18: no new event stream, one shape, two audiences).
|
|
26
|
+
*/
|
|
27
|
+
export type MemoryAppliedReceipt = {
|
|
28
|
+
kind: 'single';
|
|
29
|
+
op: 'create' | 'update' | 'delete';
|
|
30
|
+
title: string;
|
|
31
|
+
} | {
|
|
32
|
+
kind: 'batch';
|
|
33
|
+
counts: {
|
|
34
|
+
create: number;
|
|
35
|
+
update: number;
|
|
36
|
+
delete: number;
|
|
37
|
+
};
|
|
38
|
+
} | {
|
|
39
|
+
kind: 'partial';
|
|
40
|
+
applied: number;
|
|
41
|
+
total: number;
|
|
42
|
+
id: string;
|
|
43
|
+
};
|
|
44
|
+
/**
|
|
45
|
+
* Everything the two write tools need from the process around them.
|
|
46
|
+
*
|
|
47
|
+
* `decide` / `autonomyState` are the autonomy layer; `onApplied` / `onDenied` are the one-line
|
|
48
|
+
* receipts (D-7). Nothing here writes a note: that is `store.ts`, through the service.
|
|
49
|
+
*/
|
|
50
|
+
export interface MemoryToolPorts {
|
|
51
|
+
service: MemoryService;
|
|
52
|
+
approval: ApprovalGate;
|
|
53
|
+
/** Pauses the idle watchdog while a human reads the preview. */
|
|
54
|
+
withHumanWait<T>(fn: () => Promise<T>): Promise<T>;
|
|
55
|
+
/** `memory.enabled`, read LIVE: a session cannot unregister tools, only refuse them. */
|
|
56
|
+
isEnabled(): boolean;
|
|
57
|
+
/** Effective write policy, read LIVE (a session can switch `ask` <-> `auto`). */
|
|
58
|
+
agentWrites(): 'ask' | 'auto' | 'off';
|
|
59
|
+
/** Register the write tools at all (false when `memory.agentWrites` is `off`). */
|
|
60
|
+
includeWrite: boolean;
|
|
61
|
+
/** The nine-step policy verdict for one request (spec 6.2). */
|
|
62
|
+
decide(intent: MemoryWriteIntent): MemoryWriteDecision;
|
|
63
|
+
/** This turn's counters, read-only (oscillation guard input). */
|
|
64
|
+
autonomyState(): Readonly<MemoryAutonomyState>;
|
|
65
|
+
/** A write landed: the surface gets its one line. */
|
|
66
|
+
onApplied(receipt: MemoryAppliedReceipt): void;
|
|
67
|
+
/** A write was refused by a human: `paused` only when this was the second decline of the turn. */
|
|
68
|
+
onDenied(reason: 'declined' | 'paused'): void;
|
|
69
|
+
}
|
|
70
|
+
/** What asking a human came to. `unavailable` is NOT `declined` (D-9): nobody was asked. */
|
|
71
|
+
export type ApprovalOutcome = 'approved' | 'declined' | 'unavailable';
|
|
72
|
+
/**
|
|
73
|
+
* One sentence per refusal code, addressed to the MODEL (English, ASCII).
|
|
74
|
+
*
|
|
75
|
+
* The five autonomy codes at the bottom are the whole point of the feature having a vocabulary at
|
|
76
|
+
* all: "you are doing too much" (`rate_limited`) and "nobody can approve this"
|
|
77
|
+
* (`approval_unavailable`) lead to completely different next steps, so they cannot share a
|
|
78
|
+
* sentence.
|
|
79
|
+
*/
|
|
80
|
+
export declare const ERROR_TEXT: Record<string, string>;
|
|
81
|
+
/**
|
|
82
|
+
* The one sentence that explains WHY a human is being asked, for the card's second line.
|
|
83
|
+
*
|
|
84
|
+
* ONE CALL SITE FOR THE COUNT (spec 7.2 / RV-P1-2). `used` means something different per reason -
|
|
85
|
+
* how many times THIS NOTE was rewritten for `note_churn`, how many writes the turn has spent for
|
|
86
|
+
* `turn_budget`, how many the 24h window has spent for `day_budget` - and the two tool files used to
|
|
87
|
+
* each re-derive it. Both got `note_churn` wrong the same way, by reporting the turn's write count as
|
|
88
|
+
* the note's rewrite count; at the defaults the two numbers coincide, so nothing showed until a user
|
|
89
|
+
* raised `autoWritesPerTurn`, which is exactly the configuration the churn test exists for.
|
|
90
|
+
*/
|
|
91
|
+
export declare function askWhyCopy(ports: MemoryToolPorts, decision: Extract<MemoryWriteDecision, {
|
|
92
|
+
kind: 'confirm';
|
|
93
|
+
}>, intent: MemoryWriteIntent): string;
|
|
94
|
+
/** `<tool>: <code> - <detail> <sentence>`. The prefix names the tool that refused. */
|
|
95
|
+
export declare function makeWriteError(tool: string): (code: string, detail?: string) => ToolResult;
|
|
96
|
+
/** The preview the user approves. Bounded in lines AND characters. */
|
|
97
|
+
export declare function clipPreview(lines: string[]): string;
|
|
98
|
+
/**
|
|
99
|
+
* The batch confirmation card: header and footer are NEVER trimmed, only the op rows are.
|
|
100
|
+
*
|
|
101
|
+
* A card whose reason line was cut is a card asking for a signature on something the reader cannot
|
|
102
|
+
* read. So the lines that explain WHY and the line that says WHAT IT ADDS UP TO are fixed, and the
|
|
103
|
+
* middle - the row-by-row table - gives way: rows beyond the budget collapse into `(+N more ops)`.
|
|
104
|
+
*/
|
|
105
|
+
export declare function clipBatchCard(header: string[], rows: string[], footer: string[]): string;
|
|
106
|
+
/** The body of the confirmation card except its first line, trimmed like a single-write card. */
|
|
107
|
+
export declare function withWhy(summary: string, why: string): string;
|
|
108
|
+
export declare const OPS: readonly ["create", "update", "delete"];
|
|
109
|
+
export type Op = (typeof OPS)[number];
|
|
110
|
+
export interface WriteParams {
|
|
111
|
+
op: Op;
|
|
112
|
+
id?: string;
|
|
113
|
+
scope: MemoryNoteScope;
|
|
114
|
+
title?: string;
|
|
115
|
+
summary?: string;
|
|
116
|
+
body?: string;
|
|
117
|
+
append?: string;
|
|
118
|
+
tags?: string[];
|
|
119
|
+
load?: MemoryNoteLoad;
|
|
120
|
+
expectedRev?: string;
|
|
121
|
+
}
|
|
122
|
+
export declare function asString(value: unknown): string | undefined;
|
|
123
|
+
export declare function asInteger(value: unknown, fallback: number, min: number, max: number): number;
|
|
124
|
+
/** Enabled notes only: a disabled note is invisible to the agent (agent-memory spec 5.2). */
|
|
125
|
+
export declare function visibleNotes(service: MemoryService): MemoryNote[];
|
|
126
|
+
export declare function catalogRowsOf(notes: readonly MemoryNote[]): MemoryCatalogRow[];
|
|
127
|
+
export declare function listCandidates(rows: readonly {
|
|
128
|
+
id: string;
|
|
129
|
+
}[]): string;
|
|
130
|
+
/**
|
|
131
|
+
* The one place an op's raw arguments become `WriteParams`.
|
|
132
|
+
*
|
|
133
|
+
* An ABSENT scope is the documented default (`project`); a PRESENT one must be exactly one of the
|
|
134
|
+
* two enum values. Guessing ("Global", "repo" -> project) would file a preference the user meant to
|
|
135
|
+
* be global under one repository, silently.
|
|
136
|
+
*/
|
|
137
|
+
export declare function parseWriteParams(raw: Record<string, unknown>): WriteParams | string;
|
|
138
|
+
export declare function normaliseTitle(title: string): string;
|
|
139
|
+
export declare function scopeLabel(service: MemoryService, scope: MemoryNoteScope): string;
|
|
140
|
+
export declare function composeCreate(params: WriteParams): MemoryDraftInput | MemoryWriteError;
|
|
141
|
+
export declare function composeUpdate(params: WriteParams, current: MemoryNote): MemoryDraftInput | MemoryWriteError;
|
|
142
|
+
/** The sniffer's verdict for a whole draft; `null` when it is clean. */
|
|
143
|
+
export declare function secretKind(draft: MemoryDraftInput): string | null;
|
|
144
|
+
/**
|
|
145
|
+
* `true` when this note is the USER's, which makes changing it a decision they own (D-2 / I-17).
|
|
146
|
+
*
|
|
147
|
+
* `source` is the creator and never changes after `createNote` (D-21), which is the only reason
|
|
148
|
+
* this predicate keeps working the second time a note is edited.
|
|
149
|
+
*/
|
|
150
|
+
export declare function isProtectedNote(note: MemoryNote): boolean;
|
|
151
|
+
export declare function logWrite(event: string, fields: Record<string, unknown>): void;
|
|
152
|
+
/**
|
|
153
|
+
* Resolve an update/delete target among the ENABLED notes, by id or unique prefix.
|
|
154
|
+
*
|
|
155
|
+
* A fresh read, never the catalog's cached copy: this note's `rev` is what the CAS write compares,
|
|
156
|
+
* and an out-of-date rev would turn a legitimate write into a conflict.
|
|
157
|
+
*/
|
|
158
|
+
export type TargetLookup = {
|
|
159
|
+
ok: true;
|
|
160
|
+
note: MemoryNote;
|
|
161
|
+
} | {
|
|
162
|
+
ok: false;
|
|
163
|
+
code: string;
|
|
164
|
+
candidates?: string[];
|
|
165
|
+
};
|
|
166
|
+
export declare function resolveTarget(service: MemoryService, ref: string): TargetLookup;
|
|
167
|
+
/** The tool-result shape of {@link resolveTarget}: one refusal sentence instead of a code. */
|
|
168
|
+
export declare function findTarget(service: MemoryService, ref: string, fail: (code: string, detail?: string) => ToolResult): {
|
|
169
|
+
ok: true;
|
|
170
|
+
note: MemoryNote;
|
|
171
|
+
} | {
|
|
172
|
+
ok: false;
|
|
173
|
+
result: ToolResult;
|
|
174
|
+
};
|
|
175
|
+
/** Ask a human, and be honest about the three possible answers (memory-agent-autonomy D-9). */
|
|
176
|
+
export declare function requestApproval(ports: MemoryToolPorts, tool: 'memory_write' | 'memory_batch', summary: string, signal: AbortSignal | undefined): Promise<ApprovalOutcome>;
|