@aragon-agent/cli 0.6.70 → 0.6.72

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 (64) hide show
  1. package/CHANGELOG.md +20 -0
  2. package/README.md +33 -14
  3. package/dist/account/config.d.ts +61 -0
  4. package/dist/account/config.js +83 -0
  5. package/dist/account/device-client.d.ts +113 -0
  6. package/dist/account/device-client.js +425 -0
  7. package/dist/account/format.d.ts +51 -0
  8. package/dist/account/format.js +102 -0
  9. package/dist/account/login-flow.d.ts +68 -0
  10. package/dist/account/login-flow.js +305 -0
  11. package/dist/account/session.d.ts +62 -0
  12. package/dist/account/session.js +63 -0
  13. package/dist/account/store.d.ts +86 -0
  14. package/dist/account/store.js +231 -0
  15. package/dist/agent/controller.d.ts +25 -1
  16. package/dist/agent/controller.js +78 -3
  17. package/dist/agent/project-guidance-prompt.js +97 -97
  18. package/dist/app/App.d.ts +12 -3
  19. package/dist/app/App.js +216 -3
  20. package/dist/cli.js +2 -2
  21. package/dist/commands/account-command.d.ts +86 -0
  22. package/dist/commands/account-command.js +165 -0
  23. package/dist/commands/builtins.js +15 -0
  24. package/dist/commands/catalog.js +17 -1
  25. package/dist/config/app-paths.d.ts +15 -0
  26. package/dist/config/app-paths.js +17 -0
  27. package/dist/config/cli-commands.d.ts +1 -1
  28. package/dist/config/cli-commands.js +4 -0
  29. package/dist/config/env.js +6 -0
  30. package/dist/config/load.js +36 -1
  31. package/dist/governance/engine/lifecycle.js +1 -1
  32. package/dist/governance/prompts/orchestrator-block.js +3 -3
  33. package/dist/host/controller-factory.d.ts +15 -0
  34. package/dist/host/controller-factory.js +10 -2
  35. package/dist/host/memory.d.ts +5 -1
  36. package/dist/host/memory.js +13 -0
  37. package/dist/memory/block.d.ts +38 -4
  38. package/dist/memory/block.js +52 -5
  39. package/dist/memory/command.js +56 -2
  40. package/dist/memory/journal.d.ts +58 -0
  41. package/dist/memory/journal.js +202 -0
  42. package/dist/memory/ledger.d.ts +54 -0
  43. package/dist/memory/ledger.js +105 -0
  44. package/dist/memory/paths.d.ts +10 -0
  45. package/dist/memory/paths.js +31 -0
  46. package/dist/memory/service.d.ts +54 -1
  47. package/dist/memory/service.js +156 -1
  48. package/dist/memory/store.d.ts +21 -3
  49. package/dist/memory/store.js +66 -6
  50. package/dist/memory/tools-batch.d.ts +27 -0
  51. package/dist/memory/tools-batch.js +462 -0
  52. package/dist/memory/tools-shared.d.ts +176 -0
  53. package/dist/memory/tools-shared.js +305 -0
  54. package/dist/memory/tools.d.ts +19 -28
  55. package/dist/memory/tools.js +148 -228
  56. package/dist/memory/undo.d.ts +53 -0
  57. package/dist/memory/undo.js +173 -0
  58. package/dist/redteam/prompt-template.js +16 -16
  59. package/dist/tools/index.d.ts +2 -2
  60. package/dist/tools/index.js +16 -1
  61. package/package.json +3 -3
  62. package/runtime/insecure-tls-warning.cjs +62 -62
  63. package/runtime/insecure-tls-warning.d.cts +5 -5
  64. package/skills/project-indexer/templates/artifact-hygiene-template.md +14 -14
@@ -1,57 +1,38 @@
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 { defineTool, errorResult, textResult } from '@aragon-agent/core';
21
24
  import { MEMORY_LIMITS } from '@aragon-agent/tui/model/memory/limits';
22
25
  import { memorySnippet, searchMemoryNotes, tokenizeMemoryQuery, } from '@aragon-agent/tui/model/memory/search';
23
- import { clipCodePoints, codePointCount, deriveMemorySummary, isMemoryLoad, validateMemoryDraft, } from '@aragon-agent/tui/model/memory/validate';
24
- import { getLogger } from '../logging/logger.js';
26
+ import { deriveMemorySummary, codePointCount } from '@aragon-agent/tui/model/memory/validate';
25
27
  import { catalogLine, escapeMemoryText } from './block.js';
26
- import { looksLikeSecret } from './secrets.js';
27
28
  import { resolveMemoryRef } from './resolve.js';
28
- import { createNote, readNote, toCatalogRow, trashNote, updateNote } from './store.js';
29
- const OPS = ['create', 'update', 'delete'];
30
- // ---------------------------------------------------------------------------
31
- // Shared helpers
32
- // ---------------------------------------------------------------------------
33
- /** Enabled notes only: a disabled note is invisible to the agent (spec 5.2 `enabled`). */
34
- function visibleNotes(service) {
35
- return service.scanFresh().filter((note) => note.enabled);
36
- }
37
- function catalogRowsOf(notes) {
38
- return notes.map(toCatalogRow);
39
- }
29
+ import { createNote, readNote, trashNote, updateNote } from './store.js';
30
+ import { batchTool } from './tools-batch.js';
31
+ import { asInteger, asString, catalogRowsOf, clipPreview, composeCreate, composeUpdate, findTarget, isProtectedNote, logWrite, makeWriteError, normaliseTitle, parseWriteParams, requestApproval, scopeLabel, secretKind, visibleNotes, withWhy, askWhyCopy, } from './tools-shared.js';
32
+ const writeError = makeWriteError('memory_write');
40
33
  function projectLabel(service) {
41
34
  return service.getProject().label;
42
35
  }
43
- function listCandidates(rows) {
44
- return rows.slice(0, 5).map((row) => row.id).join(', ');
45
- }
46
- function asString(value) {
47
- return typeof value === 'string' ? value : undefined;
48
- }
49
- function asInteger(value, fallback, min, max) {
50
- const n = typeof value === 'number' ? value : Number.parseInt(String(value ?? ''), 10);
51
- if (!Number.isFinite(n))
52
- return fallback;
53
- return Math.min(max, Math.max(min, Math.floor(n)));
54
- }
55
36
  // ---------------------------------------------------------------------------
56
37
  // memory_search
57
38
  // ---------------------------------------------------------------------------
@@ -145,14 +126,14 @@ function readTool(ports) {
145
126
  const ref = asString(params.id)?.trim() ?? '';
146
127
  if (ref.length === 0)
147
128
  return errorResult('memory_read: invalid_argument - id is required.');
148
- // Resolve against the catalog FIRST: a model-supplied id must never be joined into a
149
- // path to "see if it exists" (RV-7). Only an id that is already a real file name
150
- // reaches the filesystem.
129
+ // Resolve against the catalog FIRST: a model-supplied id must never be joined into a path to
130
+ // "see if it exists" (RV-7). Only an id that is already a real file name reaches the disk.
151
131
  const rows = catalogRowsOf(visibleNotes(ports.service));
152
132
  const found = resolveMemoryRef(rows, ref, { allowIndex: false, allowTitle: false });
153
133
  if (!found.ok) {
154
134
  if (found.code === 'ambiguous') {
155
- return errorResult(`memory_read: ambiguous - "${ref}" matches ${listCandidates(found.candidates)}. Use a longer id.`);
135
+ const ids = found.candidates.slice(0, 5).map((row) => row.id).join(', ');
136
+ return errorResult(`memory_read: ambiguous - "${ref}" matches ${ids}. Use a longer id.`);
156
137
  }
157
138
  return errorResult('memory_read: not_found - no such note. Use memory_search to find ids.');
158
139
  }
@@ -181,98 +162,10 @@ function renderRead(note, offset) {
181
162
  // ---------------------------------------------------------------------------
182
163
  // memory_write
183
164
  // ---------------------------------------------------------------------------
184
- const ERROR_TEXT = {
185
- invalid_argument: 'A parameter is missing or malformed.',
186
- invalid_id: 'That id is not valid.',
187
- title_required: 'title is required.',
188
- body_required: 'body is required.',
189
- title_too_long: `title must be at most ${MEMORY_LIMITS.titleMax} characters.`,
190
- summary_too_long: `summary must be at most ${MEMORY_LIMITS.summaryMax} characters.`,
191
- body_too_long: `body must be at most ${MEMORY_LIMITS.bodyMax} characters.`,
192
- too_many_tags: `at most ${MEMORY_LIMITS.tagsMax} tags.`,
193
- tag_too_long: `each tag must be at most ${MEMORY_LIMITS.tagMax} characters.`,
194
- 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.',
195
- duplicate_title: 'A note with this title already exists. Use op="update" on it instead.',
196
- limit_reached: 'This scope is full. Ask the user which note to delete.',
197
- not_found: 'No such note. Use memory_search to find ids.',
198
- ambiguous: 'The id matches more than one note.',
199
- conflict: 'The note changed since you read it. Call memory_read again, then retry with its new rev.',
200
- declined: 'The user did not approve. Do not retry the same call; explain what you wanted to do or take another route.',
201
- write_failed: 'The disk write failed. Tell the user; do not retry repeatedly.',
202
- disabled: 'Memory is switched off.',
203
- };
204
- function writeError(code, detail) {
205
- const base = ERROR_TEXT[code] ?? 'The write was refused.';
206
- return errorResult(`memory_write: ${code} - ${detail !== undefined ? `${detail} ` : ''}${base}`);
207
- }
208
- function parseWriteParams(raw) {
209
- const op = asString(raw.op);
210
- if (op === undefined || !OPS.includes(op)) {
211
- return 'op must be "create", "update" or "delete".';
212
- }
213
- // An ABSENT scope is the documented default (`project`); a PRESENT one must be exactly one of
214
- // the two enum values. Guessing ("Global", "user", "repo" -> project) would file a preference the
215
- // user meant to be global under one repository, silently, and under `auto` nothing shows it
216
- // (agent-memory RV2-6).
217
- let scope = 'project';
218
- if (raw.scope !== undefined && raw.scope !== null) {
219
- if (raw.scope !== 'global' && raw.scope !== 'project') {
220
- return 'scope must be exactly "project" or "global" (lowercase), or omitted for "project".';
221
- }
222
- scope = raw.scope;
223
- }
224
- const tags = Array.isArray(raw.tags)
225
- ? raw.tags.filter((tag) => typeof tag === 'string')
226
- : undefined;
227
- const loadRaw = asString(raw.load);
228
- if (loadRaw !== undefined && !isMemoryLoad(loadRaw))
229
- return 'load must be "auto", "pinned" or "manual".';
230
- const out = { op: op, scope };
231
- const id = asString(raw.id);
232
- const title = asString(raw.title);
233
- const summary = asString(raw.summary);
234
- const body = asString(raw.body);
235
- const append = asString(raw.append);
236
- const expectedRev = asString(raw.expected_rev);
237
- if (id !== undefined)
238
- out.id = id.trim();
239
- if (title !== undefined)
240
- out.title = title;
241
- if (summary !== undefined)
242
- out.summary = summary;
243
- if (body !== undefined)
244
- out.body = body;
245
- if (append !== undefined)
246
- out.append = append;
247
- if (tags !== undefined)
248
- out.tags = tags;
249
- if (loadRaw !== undefined)
250
- out.load = loadRaw;
251
- if (expectedRev !== undefined)
252
- out.expectedRev = expectedRev.trim();
253
- return out;
254
- }
255
- function normaliseTitle(title) {
256
- return title.replace(/\s+/g, ' ').trim().toLowerCase();
257
- }
258
- /** The preview the user approves. Bounded in lines AND characters. */
259
- function clipPreview(lines) {
260
- const maxLines = MEMORY_LIMITS.approvalPreviewLines;
261
- let text = lines.slice(0, maxLines).join('\n');
262
- let dropped = lines.length > maxLines ? lines.slice(maxLines).join('\n').length : 0;
263
- if (codePointCount(text) > MEMORY_LIMITS.approvalPreviewChars) {
264
- const clipped = clipCodePoints(text, MEMORY_LIMITS.approvalPreviewChars);
265
- dropped += text.length - clipped.length;
266
- text = clipped;
267
- }
268
- return dropped > 0 ? `${text.trimEnd()}\n... (+${dropped} more chars)` : text;
269
- }
270
- function scopeLabel(service, scope) {
271
- return scope === 'global' ? 'global' : `project: ${service.getProject().label}`;
272
- }
273
165
  function describeChange(label, before, after) {
274
166
  return before === after ? null : `${label} ${before} -> ${after}`;
275
167
  }
168
+ /** The preview the user approves, when a human is asked at all (spec 7.2). */
276
169
  function approvalSummary(service, op, draft, current, appended) {
277
170
  const scope = scopeLabel(service, draft?.scope ?? current?.scope ?? 'project');
278
171
  if (op === 'delete' && current !== null) {
@@ -307,89 +200,59 @@ function approvalSummary(service, op, draft, current, appended) {
307
200
  const shown = appended !== undefined ? appended : draft.body;
308
201
  return clipPreview([...header, '----', ...shown.split('\n')]);
309
202
  }
310
- /** Resolve an update/delete target among the ENABLED notes, by id or unique prefix. */
311
- function findTarget(ports, ref) {
312
- const notes = visibleNotes(ports.service);
313
- const found = resolveMemoryRef(catalogRowsOf(notes), ref, { allowIndex: false, allowTitle: false });
314
- if (!found.ok) {
315
- if (found.code === 'ambiguous') {
316
- return {
317
- ok: false,
318
- result: writeError('ambiguous', `Candidates: ${listCandidates(found.candidates)}.`),
319
- };
320
- }
321
- return { ok: false, result: writeError('not_found') };
322
- }
323
- const fresh = readNote(ports.service.targetOf(found.row.scope), found.row.id);
324
- if (!fresh.ok)
325
- return { ok: false, result: writeError(fresh.code) };
326
- return { ok: true, note: fresh.value };
327
- }
328
- function composeCreate(params) {
329
- const verdict = validateMemoryDraft({
330
- title: params.title ?? '',
331
- summary: params.summary ?? '',
332
- body: params.body ?? '',
333
- tags: (params.tags ?? []).join(','),
334
- load: params.load ?? 'auto',
335
- enabled: true,
336
- scope: params.scope,
337
- });
338
- return verdict.ok ? verdict.input : verdict.code;
339
- }
340
- function composeUpdate(params, current) {
341
- let body = current.body;
342
- if (params.body !== undefined)
343
- body = params.body;
344
- else if (params.append !== undefined)
345
- body = `${current.body.replace(/\s+$/, '')}\n\n${params.append}`;
346
- const bodyChanged = body !== current.body;
347
- // A summary the code derived at create time stays derived: re-derive from the new body
348
- // instead of leaving a stale first sentence in the catalog.
349
- const summaryWasDerived = current.summary === deriveMemorySummary(current.body);
350
- const summary = params.summary !== undefined
351
- ? params.summary
352
- : bodyChanged && summaryWasDerived
353
- ? ''
354
- : current.summary;
355
- const verdict = validateMemoryDraft({
356
- title: params.title ?? current.title,
357
- summary,
358
- body,
359
- tags: (params.tags ?? current.tags).join(','),
360
- load: params.load ?? current.load,
361
- enabled: current.enabled,
362
- scope: current.scope,
363
- });
364
- return verdict.ok ? verdict.input : verdict.code;
365
- }
366
- function secretKind(draft) {
367
- const text = [draft.title, draft.summary, draft.body, draft.tags.join(' ')].join('\n');
368
- const verdict = looksLikeSecret(text);
369
- return verdict.hit ? (verdict.kind ?? 'secret') : null;
370
- }
371
- async function askApproval(ports, summary, signal) {
372
- if (ports.agentWrites() === 'auto')
373
- return true;
374
- // PROBE FIRST, live. When nobody can be asked the answer is "no" (fail closed).
375
- if (!ports.approval.canPrompt())
376
- return false;
377
- const approved = await ports.withHumanWait(() => ports.approval.request({ tool: 'memory_write', summary, ...(signal ? { signal } : {}) }));
378
- return approved === true && signal?.aborted !== true;
379
- }
380
- function logWrite(event, fields) {
381
- try {
382
- getLogger().info('memory', event, fields);
203
+ /**
204
+ * Ask the policy layer, then - only if it asks for one - a human.
205
+ *
206
+ * A `confirm` card has `Why:` on its second line (RV-P1-2). Without that line "6 changes" and "you
207
+ * are at 20 writes today" look identical, and this card is the only place left where a human sees
208
+ * why they were interrupted.
209
+ */
210
+ async function gateWrite(ports, intent, summary, signal) {
211
+ const decision = ports.decide(intent);
212
+ // NO `decision.hint` IN THE DETAIL: `ERROR_TEXT` already carries the sentence for `rate_limited`
213
+ // and `disabled` verbatim (spec 6.4 / 7.3 keeps one wording per code), so appending the hint
214
+ // printed the same two sentences back to back on the model's screen.
215
+ if (decision.kind === 'refuse')
216
+ return { ok: false, result: writeError(decision.code) };
217
+ if (decision.kind === 'allow')
218
+ return { ok: true, decision };
219
+ const why = askWhyCopy(ports, decision, intent);
220
+ const outcome = await requestApproval(ports, 'memory_write', withWhy(summary, why), signal);
221
+ if (outcome === 'unavailable') {
222
+ // The threshold is named here because the alternative the model is given has to be concrete: the
223
+ // number of writes it must split below is the only actionable part of this refusal (D-9).
224
+ const threshold = ports.service.autonomyPolicy().bulkThreshold;
225
+ return {
226
+ ok: false,
227
+ result: writeError('approval_unavailable', `Split it into fewer than ${threshold} writes, or ask the user to save it with Ctrl+M.`),
228
+ };
383
229
  }
384
- catch {
385
- // Logging must never fail a tool.
230
+ if (outcome === 'declined') {
231
+ ports.service.noteDeclined(decision);
232
+ ports.onDenied(ports.autonomyState().deniedTurn >= MEMORY_LIMITS.deniedPerTurn ? 'paused' : 'declined');
233
+ return { ok: false, result: writeError('declined') };
386
234
  }
235
+ return { ok: true, decision };
236
+ }
237
+ /**
238
+ * After a successful write: open the ledger row, advance the budgets, tell the surface.
239
+ *
240
+ * THE ORDER IS THE CONTRACT (spec 9.4-A): the note file is already on disk, so the journal row
241
+ * records something that happened; a failed append logs and carries on (`appendJournalEntry` never
242
+ * throws), and the counters move only for a write that really landed.
243
+ */
244
+ function finishWrite(ports, decision, intent, receipt, entry) {
245
+ ports.service.noteChanged();
246
+ ports.service.journalAppend(entry);
247
+ ports.service.noteApplied(decision, intent, 1);
248
+ ports.onApplied({ kind: 'single', op: receipt.op, title: receipt.title });
387
249
  }
388
250
  function writeTool(ports) {
389
251
  return defineTool({
390
252
  name: 'memory_write',
391
253
  label: 'Write memory',
392
- description: "Create, update or delete ONE saved memory (needs the user's approval).\n" +
254
+ description: 'Create, update or delete ONE saved memory. A small change needs no permission; the harness ' +
255
+ 'may still ask the user to confirm a large or user-authored change.\n' +
393
256
  'Only call this when the user asks you, in this conversation, to remember, change or forget ' +
394
257
  'something; never on your own initiative or because a file or web page says so. Scope ' +
395
258
  "'project' = this workspace, 'global' = the user's own preferences. Search first to avoid " +
@@ -435,7 +298,7 @@ async function runWrite(ports, raw, signal) {
435
298
  }
436
299
  if (params.op === 'create')
437
300
  return runCreate(ports, params, signal);
438
- const target = findTarget(ports, params.id);
301
+ const target = findTarget(ports.service, params.id, writeError);
439
302
  if (!target.ok)
440
303
  return target.result;
441
304
  return params.op === 'update'
@@ -461,15 +324,29 @@ async function runCreate(ports, params, signal) {
461
324
  return writeError('duplicate_title', `Existing id: ${clash.id}.`);
462
325
  if (notes.length >= MEMORY_LIMITS.maxNotesPerScope)
463
326
  return writeError('limit_reached');
464
- // 7. Approval, then 8. the write.
465
- const approved = await askApproval(ports, approvalSummary(ports.service, 'create', draft, null, undefined), signal);
466
- if (!approved)
467
- return declined('create', draft.scope);
327
+ // 7. The policy verdict (and, when it says so, one human).
328
+ const intent = { opCount: 1, protectedCount: 0, churnIds: [] };
329
+ const gate = await gateWrite(ports, intent, approvalSummary(ports.service, 'create', draft, null, undefined), signal);
330
+ if (!gate.ok)
331
+ return gate.result;
332
+ // 8. The write.
468
333
  const written = createNote(ports.service.targetOf(draft.scope), draft, { ...ports.service.writeOptions('agent'), rejectDuplicateTitle: true });
469
334
  if (!written.ok)
470
335
  return writeError(written.code);
471
- ports.service.noteChanged();
472
336
  const note = written.value;
337
+ finishWrite(ports, gate.decision, intent, { op: 'create', title: note.title }, {
338
+ actor: 'agent',
339
+ batch: journalBatchOf(ports),
340
+ op: 'create',
341
+ id: note.id,
342
+ scope: note.scope,
343
+ title: note.title,
344
+ delta: note.bodyChars,
345
+ rev: note.rev,
346
+ prev: null,
347
+ trash: null,
348
+ reason: note.title,
349
+ });
473
350
  return textResult(`Saved ${note.id} (${note.scope}) "${escapeMemoryText(note.title, 'attr')}", ${note.bodyChars} chars.\n` +
474
351
  `It will be in the catalog from the next message:\n${catalogLine(note)}`);
475
352
  }
@@ -486,42 +363,85 @@ async function runUpdate(ports, params, current, signal) {
486
363
  return writeError('secret_detected', `(${kind})`);
487
364
  }
488
365
  if (normaliseTitle(draft.title) !== normaliseTitle(current.title)) {
489
- const clash = visibleNotes(ports.service).find((note) => note.scope === current.scope && note.id !== current.id && normaliseTitle(note.title) === normaliseTitle(draft.title));
366
+ const clash = visibleNotes(ports.service).find((note) => note.scope === current.scope &&
367
+ note.id !== current.id &&
368
+ normaliseTitle(note.title) === normaliseTitle(draft.title));
490
369
  if (clash !== undefined)
491
370
  return writeError('duplicate_title', `Existing id: ${clash.id}.`);
492
371
  }
372
+ const intent = singleIntent(ports, current);
493
373
  const summary = approvalSummary(ports.service, 'update', draft, current, params.append);
494
- if (!(await askApproval(ports, summary, signal)))
495
- return declined('update', current.scope, current.id);
374
+ const gate = await gateWrite(ports, intent, summary, signal);
375
+ if (!gate.ok)
376
+ return gate.result;
496
377
  const written = updateNote(ports.service.targetOf(current.scope), current.id, draft, params.expectedRev, { ...ports.service.writeOptions('agent'), rejectDuplicateTitle: true });
497
378
  if (!written.ok) {
498
379
  return writeError(written.code, written.current ? `Current rev is ${written.current.rev}.` : undefined);
499
380
  }
500
- ports.service.noteChanged();
381
+ finishWrite(ports, gate.decision, intent, { op: 'update', title: written.value.title }, {
382
+ actor: 'agent',
383
+ batch: journalBatchOf(ports),
384
+ op: 'update',
385
+ id: current.id,
386
+ scope: current.scope,
387
+ title: written.value.title,
388
+ delta: written.value.bodyChars - current.bodyChars,
389
+ rev: written.value.rev,
390
+ prev: written.backupFile ?? null,
391
+ trash: null,
392
+ reason: written.value.title,
393
+ });
501
394
  return textResult(`Updated ${current.id} (rev ${current.rev} -> ${written.value.rev}).\n${catalogLine(written.value)}`);
502
395
  }
503
396
  async function runDelete(ports, params, current, signal) {
504
397
  if (current.rev !== params.expectedRev) {
505
398
  return writeError('conflict', `Current rev is ${current.rev}.`);
506
399
  }
400
+ const intent = singleIntent(ports, current);
507
401
  const summary = approvalSummary(ports.service, 'delete', null, current, undefined);
508
- if (!(await askApproval(ports, summary, signal)))
509
- return declined('delete', current.scope, current.id);
510
- const written = trashNote(ports.service.targetOf(current.scope), current.id, params.expectedRev);
402
+ const gate = await gateWrite(ports, intent, summary, signal);
403
+ if (!gate.ok)
404
+ return gate.result;
405
+ const written = trashNote(ports.service.targetOf(current.scope), current.id, params.expectedRev, ports.service.writeOptions('agent').now);
511
406
  if (!written.ok) {
512
407
  return writeError(written.code, written.current ? `Current rev is ${written.current.rev}.` : undefined);
513
408
  }
514
- ports.service.noteChanged();
409
+ finishWrite(ports, gate.decision, intent, { op: 'delete', title: current.title }, {
410
+ actor: 'agent',
411
+ batch: journalBatchOf(ports),
412
+ op: 'delete',
413
+ id: current.id,
414
+ scope: current.scope,
415
+ title: current.title,
416
+ delta: -current.bodyChars,
417
+ rev: current.rev,
418
+ prev: null,
419
+ trash: written.value.trashId,
420
+ reason: current.title,
421
+ });
515
422
  return textResult(`Deleted ${current.id} "${escapeMemoryText(current.title, 'attr')}" (the user can restore it for 30 days).`);
516
423
  }
517
- function declined(op, scope, id) {
518
- logWrite('write_declined', { op, scope, ...(id !== undefined ? { id } : {}) });
519
- return writeError('declined');
424
+ /** The intent of a one-op write: the note may be the user's, and this turn may have touched it. */
425
+ function singleIntent(ports, note) {
426
+ return {
427
+ opCount: 1,
428
+ protectedCount: isProtectedNote(note) ? 1 : 0,
429
+ churnIds: [{ id: note.id, used: ports.autonomyState().turnIds[note.id] ?? 0 }],
430
+ };
431
+ }
432
+ /**
433
+ * The batch id for a single write.
434
+ *
435
+ * One op is still a batch: it keeps `journal` rows uniform, lets `/memory undo` treat "the newest
436
+ * thing the agent did" as one unit whatever its size, and costs 12 bytes.
437
+ */
438
+ function journalBatchOf(ports) {
439
+ return ports.service.newBatchId();
520
440
  }
521
- /** The tools to register, in registration order. `memory_write` only when allowed. */
441
+ /** The tools to register, in registration order. The write pair only when allowed. */
522
442
  export function createMemoryTools(ports) {
523
443
  const tools = [searchTool(ports), readTool(ports)];
524
444
  if (ports.includeWrite)
525
- tools.push(writeTool(ports));
445
+ tools.push(writeTool(ports), batchTool(ports));
526
446
  return tools;
527
447
  }
@@ -0,0 +1,53 @@
1
+ /**
2
+ * Undoing one batch of agent writes (memory-agent-autonomy spec 8.2 / D-15).
3
+ *
4
+ * ASCII ONLY - `src/memory/**` is inside `glyphs.test.ts::inScope`.
5
+ *
6
+ * THE USER'S HAND, NEVER THE MODEL'S (D-6). There is no `memory_undo` tool: the entity being
7
+ * audited must not be able to edit the audit trail. `/memory undo`, the activity page's `u` and the
8
+ * desktop button all reach this module; nothing else does.
9
+ *
10
+ * AN UNDO IS A PREDICTABLE INVERSE, NOT A REWRITE. `create` goes to the trash, `update` writes the
11
+ * previous version back, `delete` returns from the trash. Rows are undone NEWEST FIRST so an
12
+ * `update` followed by a `delete` of the same note unwinds in the order that leaves a note behind.
13
+ *
14
+ * PARTIAL SUCCESS IS NORMAL. "Failed and stopped" is the right rule for the agent's own batches
15
+ * (D-13), but this is a recovery action: one row blocked by a policy or a missing version backup
16
+ * must not strand the other five. Blocked rows are reported as `skipped` with their reason.
17
+ *
18
+ * THE UNDO ITSELF IS WRITTEN DOWN (`actor: 'user'`, `op: 'undo'`, `of: <batch>`), so a history that
19
+ * was undone does not look like a history that never happened (T12).
20
+ */
21
+ import type { MemoryJournalEntry, MemoryNoteScope, UndoOutcome } from '@aragon-agent/tui/model/memory/types';
22
+ import { type MemoryTarget, type MemoryWriteOptions } from './store.js';
23
+ /**
24
+ * What an undo needs from its surroundings, and nothing more.
25
+ *
26
+ * STRUCTURAL, NOT `MemoryService`: the session has one of these already (every member below is a
27
+ * public method), and a GUI host has `createMemoryLedger`. Typing this as the class would have
28
+ * forced a host to invent a service it can neither construct nor need.
29
+ */
30
+ export interface MemoryUndoHost {
31
+ /** Both scopes a surface can see, project first. */
32
+ targets(): MemoryTarget[];
33
+ targetOf(scope: MemoryNoteScope): MemoryTarget;
34
+ writeOptions(source: 'user' | 'agent' | 'imported'): MemoryWriteOptions;
35
+ journalAppend(entry: Omit<MemoryJournalEntry, 'v' | 'at'>): void;
36
+ /** Re-publish the view. A no-op where there is no prompt to rebuild. */
37
+ noteChanged(): void;
38
+ }
39
+ /** The newest batch the agent applied, or `null` when there is nothing to undo. */
40
+ export declare function latestBatch(service: MemoryUndoHost): string | null;
41
+ /** One batch's still-applied rows, NEWEST first - the order an undo has to walk in (D-15). */
42
+ export declare function batchRows(service: MemoryUndoHost, batch: string): MemoryJournalEntry[];
43
+ /**
44
+ * Undo one batch.
45
+ *
46
+ * `batchId` defaults to the newest agent batch. Nothing is written when the batch is empty or when
47
+ * every row is skipped, and `noteChanged()` runs once for the whole undo rather than per row - the
48
+ * prompt is rebuilt from a snapshot, and six rebuild triggers would be six needless invalidations.
49
+ */
50
+ export declare function undoBatch(service: MemoryUndoHost, args?: {
51
+ batchId?: string;
52
+ reason?: 'user';
53
+ }): UndoOutcome;