@aragon-agent/cli 0.6.53 → 0.6.55
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 +64 -0
- package/README.md +135 -6
- package/dist/agent/controller.d.ts +98 -0
- package/dist/agent/controller.js +341 -1
- package/dist/agent/redteam-prompt.d.ts +47 -0
- package/dist/agent/redteam-prompt.js +161 -0
- package/dist/agent/redteam-wiring.d.ts +159 -0
- package/dist/agent/redteam-wiring.js +349 -0
- package/dist/agent/system-prompt.d.ts +27 -0
- package/dist/agent/system-prompt.js +10 -0
- package/dist/app/App.d.ts +17 -1
- package/dist/app/App.js +266 -26
- package/dist/app/use-redteam-mode.d.ts +56 -0
- package/dist/app/use-redteam-mode.js +121 -0
- package/dist/cli.js +78 -4
- package/dist/commands/builtins.js +49 -1
- package/dist/commands/catalog.js +5 -0
- package/dist/commands/index-build.js +2 -1
- package/dist/commands/redteam-command.d.ts +22 -0
- package/dist/commands/redteam-command.js +141 -0
- package/dist/commands/registry.d.ts +7 -0
- package/dist/compaction/compactor.d.ts +26 -0
- package/dist/compaction/compactor.js +81 -8
- package/dist/compaction/summarize-call.d.ts +22 -0
- package/dist/compaction/summarize-call.js +29 -0
- package/dist/compaction/wiring.js +22 -3
- package/dist/config/app-paths.d.ts +13 -0
- package/dist/config/app-paths.js +15 -0
- package/dist/config/cli-commands.d.ts +15 -0
- package/dist/config/cli-commands.js +32 -1
- package/dist/config/env.d.ts +3 -1
- package/dist/config/env.js +23 -1
- package/dist/config/load.d.ts +18 -0
- package/dist/config/load.js +19 -1
- package/dist/config/redteam-launch.d.ts +77 -0
- package/dist/config/redteam-launch.js +58 -0
- package/dist/config/store.js +20 -1
- package/dist/config/ui-state.d.ts +44 -0
- package/dist/config/ui-state.js +38 -0
- package/dist/exec/bridge/server.js +9 -2
- package/dist/exec/options.js +16 -2
- package/dist/governance/prompts/orchestrator-block.js +2 -2
- package/dist/host/controller-factory.d.ts +33 -0
- package/dist/host/controller-factory.js +14 -0
- package/dist/host/follow-up-seed.d.ts +109 -0
- package/dist/host/follow-up-seed.js +196 -0
- package/dist/host/follow-up.d.ts +73 -0
- package/dist/host/follow-up.js +123 -0
- package/dist/host/index.d.ts +3 -0
- package/dist/host/index.js +3 -0
- package/dist/host/memory.d.ts +21 -0
- package/dist/host/memory.js +17 -0
- package/dist/host/sessions.d.ts +32 -2
- package/dist/host/sessions.js +40 -2
- package/dist/logging/install.d.ts +1 -0
- package/dist/logging/install.js +4 -0
- package/dist/logging/logger.d.ts +1 -1
- package/dist/memory/block.d.ts +24 -0
- package/dist/memory/block.js +54 -0
- package/dist/memory/command.d.ts +31 -0
- package/dist/memory/command.js +350 -0
- package/dist/memory/format.d.ts +51 -0
- package/dist/memory/format.js +308 -0
- package/dist/memory/paths.d.ts +68 -0
- package/dist/memory/paths.js +172 -0
- package/dist/memory/plan.d.ts +37 -0
- package/dist/memory/plan.js +184 -0
- package/dist/memory/resolve.d.ts +45 -0
- package/dist/memory/resolve.js +54 -0
- package/dist/memory/secrets.d.ts +30 -0
- package/dist/memory/secrets.js +73 -0
- package/dist/memory/service.d.ts +175 -0
- package/dist/memory/service.js +576 -0
- package/dist/memory/store.d.ts +133 -0
- package/dist/memory/store.js +694 -0
- package/dist/memory/tools.d.ts +36 -0
- package/dist/memory/tools.js +527 -0
- package/dist/memory/transfer.d.ts +53 -0
- package/dist/memory/transfer.js +93 -0
- package/dist/session/checkpoint.d.ts +33 -0
- package/dist/session/checkpoint.js +52 -0
- package/dist/session/limits.d.ts +16 -0
- package/dist/session/limits.js +16 -0
- package/dist/session/persist.d.ts +68 -0
- package/dist/session/persist.js +11 -0
- package/dist/session/startup-session.d.ts +17 -2
- package/dist/session/startup-session.js +15 -2
- package/dist/session/store.d.ts +14 -0
- package/dist/session/store.js +18 -0
- package/dist/session/validate-session.js +129 -0
- package/dist/team/runtime.d.ts +11 -0
- package/dist/team/runtime.js +6 -0
- package/dist/team/subagent.d.ts +21 -0
- package/dist/team/subagent.js +7 -0
- package/dist/tools/index.d.ts +45 -2
- package/dist/tools/index.js +53 -3
- package/package.json +3 -3
- package/skills/project-indexer/SKILL.md +275 -147
- package/skills/project-indexer/templates/artifact-hygiene-template.md +14 -0
- package/skills/project-indexer/templates/config-template.md +12 -0
- package/skills/project-indexer/templates/index-template.md +4 -0
|
@@ -0,0 +1,308 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* One note file <-> a `MemoryNote` (agent-memory spec 5.2).
|
|
3
|
+
*
|
|
4
|
+
* ASCII ONLY - `src/memory/**` is inside `glyphs.test.ts::inScope`.
|
|
5
|
+
*
|
|
6
|
+
* STRICT OUT, TOLERANT IN. A note is written in one fixed shape (field order, JSON-quoted
|
|
7
|
+
* strings, LF endings), but READ from whatever a person or a sync tool left behind: no
|
|
8
|
+
* frontmatter, unknown keys, a half-quoted title, CRLF, a BOM, a bad date. Every
|
|
9
|
+
* deviation degrades to a usable note flagged `repaired`; it never throws and it never
|
|
10
|
+
* discards the file (I-3). Reading never rewrites the file either (I-14): normalising is
|
|
11
|
+
* something a SAVE does, not something opening the manager does behind the user's back.
|
|
12
|
+
*
|
|
13
|
+
* The frontmatter is a deliberately tiny YAML subset (scalars, a flat list, quoted
|
|
14
|
+
* strings). `skills/manifest.ts` is a `.aragon-skill.json` reader, not a frontmatter
|
|
15
|
+
* parser, so there is nothing to reuse and no dependency worth adding for six keys.
|
|
16
|
+
*/
|
|
17
|
+
import { createHash } from 'node:crypto';
|
|
18
|
+
import { clipCodePoints, codePointCount, deriveMemorySummary, isMemoryLoad, parseMemoryTags, stripMemoryControl, toSingleLine, } from '@aragon-agent/tui/model/memory/validate';
|
|
19
|
+
import { MEMORY_LIMITS } from '@aragon-agent/tui/model/memory/limits';
|
|
20
|
+
export { deriveMemorySummary };
|
|
21
|
+
/** The `schema:` value this build writes. A larger value found on disk is preserved. */
|
|
22
|
+
export const MEMORY_FILE_SCHEMA = 1;
|
|
23
|
+
const SOURCES = ['user', 'agent', 'imported', 'hand'];
|
|
24
|
+
/** First 10 hex chars of the sha1 of the file's bytes (D-16). */
|
|
25
|
+
export function computeRev(bytes) {
|
|
26
|
+
return createHash('sha1').update(bytes).digest('hex').slice(0, 10);
|
|
27
|
+
}
|
|
28
|
+
// ---------------------------------------------------------------------------
|
|
29
|
+
// Reading
|
|
30
|
+
// ---------------------------------------------------------------------------
|
|
31
|
+
/** Decode strictly; `null` for bytes that are not valid UTF-8 (the file is skipped). */
|
|
32
|
+
export function decodeNoteBytes(bytes) {
|
|
33
|
+
try {
|
|
34
|
+
const text = new TextDecoder('utf-8', { fatal: true }).decode(bytes);
|
|
35
|
+
return text.charCodeAt(0) === 0xfeff ? text.slice(1) : text;
|
|
36
|
+
}
|
|
37
|
+
catch {
|
|
38
|
+
return null;
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
const FENCE = /^---[ \t]*$/;
|
|
42
|
+
const KEY_LINE = /^([A-Za-z_][A-Za-z0-9_-]*)[ \t]*:[ \t]*(.*)$/;
|
|
43
|
+
/** Split `---` frontmatter from the body; `null` when the file has none. */
|
|
44
|
+
function splitFrontmatter(text) {
|
|
45
|
+
const lines = text.split('\n');
|
|
46
|
+
if (lines.length === 0 || !FENCE.test(lines[0]))
|
|
47
|
+
return null;
|
|
48
|
+
let close = -1;
|
|
49
|
+
for (let i = 1; i < lines.length; i += 1) {
|
|
50
|
+
if (FENCE.test(lines[i])) {
|
|
51
|
+
close = i;
|
|
52
|
+
break;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
if (close === -1)
|
|
56
|
+
return null;
|
|
57
|
+
const values = new Map();
|
|
58
|
+
const order = [];
|
|
59
|
+
let repaired = false;
|
|
60
|
+
for (let i = 1; i < close; i += 1) {
|
|
61
|
+
const line = lines[i];
|
|
62
|
+
if (line.trim().length === 0 || line.trimStart().startsWith('#'))
|
|
63
|
+
continue;
|
|
64
|
+
const match = KEY_LINE.exec(line);
|
|
65
|
+
if (match === null) {
|
|
66
|
+
// A continuation line or junk. We cannot place it, so say the file was repaired.
|
|
67
|
+
repaired = true;
|
|
68
|
+
continue;
|
|
69
|
+
}
|
|
70
|
+
const key = match[1];
|
|
71
|
+
if (!values.has(key))
|
|
72
|
+
order.push(key);
|
|
73
|
+
values.set(key, match[2].trim());
|
|
74
|
+
}
|
|
75
|
+
let body = lines.slice(close + 1).join('\n');
|
|
76
|
+
if (body.startsWith('\n'))
|
|
77
|
+
body = body.slice(1);
|
|
78
|
+
if (body.endsWith('\n'))
|
|
79
|
+
body = body.slice(0, -1);
|
|
80
|
+
return { values, order, repaired, body };
|
|
81
|
+
}
|
|
82
|
+
/** Parse a YAML-ish scalar: `"json"`, `'single'`, or bare text. */
|
|
83
|
+
function parseScalar(raw) {
|
|
84
|
+
const value = raw.trim();
|
|
85
|
+
if (value.startsWith('"')) {
|
|
86
|
+
// A well-formed JSON string first; otherwise take the rest of the line.
|
|
87
|
+
try {
|
|
88
|
+
const parsed = JSON.parse(value);
|
|
89
|
+
if (typeof parsed === 'string')
|
|
90
|
+
return { text: parsed, repaired: false };
|
|
91
|
+
}
|
|
92
|
+
catch {
|
|
93
|
+
// Fall through to the repair path.
|
|
94
|
+
}
|
|
95
|
+
const inner = value.slice(1).replace(/"\s*$/, '');
|
|
96
|
+
return { text: inner, repaired: true };
|
|
97
|
+
}
|
|
98
|
+
if (value.startsWith("'")) {
|
|
99
|
+
const closed = value.length >= 2 && value.endsWith("'");
|
|
100
|
+
const inner = closed ? value.slice(1, -1).replace(/''/g, "'") : value.slice(1);
|
|
101
|
+
return { text: inner, repaired: !closed };
|
|
102
|
+
}
|
|
103
|
+
return { text: value, repaired: false };
|
|
104
|
+
}
|
|
105
|
+
function parseTagList(raw) {
|
|
106
|
+
const value = raw.trim();
|
|
107
|
+
const inner = value.startsWith('[') && value.endsWith(']') ? value.slice(1, -1) : value;
|
|
108
|
+
const tags = [];
|
|
109
|
+
// Quoted items first (they may contain commas), the rest split on commas.
|
|
110
|
+
const re = /"((?:[^"\\]|\\.)*)"|'([^']*)'|([^,\s][^,]*)/g;
|
|
111
|
+
for (const match of inner.matchAll(re)) {
|
|
112
|
+
const item = match[1] !== undefined ? safeJsonString(match[1]) : (match[2] ?? match[3] ?? '');
|
|
113
|
+
const tag = toSingleLine(item);
|
|
114
|
+
if (tag.length > 0)
|
|
115
|
+
tags.push(tag);
|
|
116
|
+
}
|
|
117
|
+
return parseMemoryTags(tags.join(' '));
|
|
118
|
+
}
|
|
119
|
+
function safeJsonString(inner) {
|
|
120
|
+
try {
|
|
121
|
+
const parsed = JSON.parse(`"${inner}"`);
|
|
122
|
+
return typeof parsed === 'string' ? parsed : inner;
|
|
123
|
+
}
|
|
124
|
+
catch {
|
|
125
|
+
return inner;
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
function parseBoolean(raw, fallback) {
|
|
129
|
+
if (raw === undefined)
|
|
130
|
+
return { value: fallback, ok: true };
|
|
131
|
+
const text = raw.trim().toLowerCase();
|
|
132
|
+
if (text === 'true')
|
|
133
|
+
return { value: true, ok: true };
|
|
134
|
+
if (text === 'false')
|
|
135
|
+
return { value: false, ok: true };
|
|
136
|
+
return { value: fallback, ok: false };
|
|
137
|
+
}
|
|
138
|
+
function parseDate(raw, fallback) {
|
|
139
|
+
if (raw === undefined)
|
|
140
|
+
return { ms: fallback, ok: false };
|
|
141
|
+
const ms = Date.parse(parseScalar(raw).text);
|
|
142
|
+
return Number.isFinite(ms) ? { ms, ok: true } : { ms: fallback, ok: false };
|
|
143
|
+
}
|
|
144
|
+
const KNOWN_KEYS = new Set([
|
|
145
|
+
'schema', 'title', 'summary', 'tags', 'load', 'enabled', 'created', 'updated', 'source',
|
|
146
|
+
]);
|
|
147
|
+
/** First `# ` heading of a headerless file, for its title. */
|
|
148
|
+
function firstHeading(text) {
|
|
149
|
+
for (const line of text.split('\n')) {
|
|
150
|
+
const match = /^#{1}\s+(.+?)\s*#*\s*$/.exec(line);
|
|
151
|
+
if (match !== null)
|
|
152
|
+
return match[1];
|
|
153
|
+
if (line.trim().length > 0 && !line.startsWith('#'))
|
|
154
|
+
return null;
|
|
155
|
+
}
|
|
156
|
+
return null;
|
|
157
|
+
}
|
|
158
|
+
/**
|
|
159
|
+
* Parse one file's bytes into a note. `null` ONLY when the bytes are not UTF-8 (the
|
|
160
|
+
* caller counts that as skipped); every other oddity becomes a repaired note.
|
|
161
|
+
*/
|
|
162
|
+
export function parseNoteBytes(bytes, ctx) {
|
|
163
|
+
const decoded = decodeNoteBytes(bytes);
|
|
164
|
+
if (decoded === null)
|
|
165
|
+
return null;
|
|
166
|
+
const text = decoded.replace(/\r\n?/g, '\n');
|
|
167
|
+
const rev = computeRev(bytes);
|
|
168
|
+
const front = splitFrontmatter(text);
|
|
169
|
+
if (front === null)
|
|
170
|
+
return parseHeaderless(text, ctx, rev, bytes.byteLength);
|
|
171
|
+
return parseWithFrontmatter(front, ctx, rev, bytes.byteLength);
|
|
172
|
+
}
|
|
173
|
+
function finishNote(partial, rev, bytes, repairedBefore) {
|
|
174
|
+
let repaired = repairedBefore;
|
|
175
|
+
let title = toSingleLine(partial.title);
|
|
176
|
+
if (title.length === 0) {
|
|
177
|
+
title = partial.id;
|
|
178
|
+
repaired = true;
|
|
179
|
+
}
|
|
180
|
+
if (codePointCount(title) > MEMORY_LIMITS.titleMax) {
|
|
181
|
+
title = clipCodePoints(title, MEMORY_LIMITS.titleMax);
|
|
182
|
+
repaired = true;
|
|
183
|
+
}
|
|
184
|
+
let body = stripMemoryControl(partial.body);
|
|
185
|
+
if (codePointCount(body) > MEMORY_LIMITS.bodyMax) {
|
|
186
|
+
body = clipCodePoints(body, MEMORY_LIMITS.bodyMax);
|
|
187
|
+
repaired = true;
|
|
188
|
+
}
|
|
189
|
+
let summary = toSingleLine(partial.rawSummary);
|
|
190
|
+
if (codePointCount(summary) > MEMORY_LIMITS.summaryMax) {
|
|
191
|
+
summary = clipCodePoints(summary, MEMORY_LIMITS.summaryMax);
|
|
192
|
+
repaired = true;
|
|
193
|
+
}
|
|
194
|
+
const summaryDerived = summary.length === 0;
|
|
195
|
+
if (summaryDerived)
|
|
196
|
+
summary = deriveMemorySummary(body);
|
|
197
|
+
const { rawSummary: _unused, ...rest } = partial;
|
|
198
|
+
return {
|
|
199
|
+
...rest,
|
|
200
|
+
title,
|
|
201
|
+
summary,
|
|
202
|
+
summaryDerived,
|
|
203
|
+
body,
|
|
204
|
+
repaired,
|
|
205
|
+
rev,
|
|
206
|
+
bytes,
|
|
207
|
+
bodyChars: codePointCount(body),
|
|
208
|
+
};
|
|
209
|
+
}
|
|
210
|
+
function parseHeaderless(text, ctx, rev, bytes) {
|
|
211
|
+
const heading = firstHeading(text);
|
|
212
|
+
return finishNote({
|
|
213
|
+
id: ctx.id,
|
|
214
|
+
scope: ctx.scope,
|
|
215
|
+
title: heading ?? ctx.id,
|
|
216
|
+
rawSummary: '',
|
|
217
|
+
body: text.replace(/\n+$/, ''),
|
|
218
|
+
tags: [],
|
|
219
|
+
load: 'auto',
|
|
220
|
+
enabled: true,
|
|
221
|
+
createdAt: ctx.mtimeMs,
|
|
222
|
+
updatedAt: ctx.mtimeMs,
|
|
223
|
+
source: 'hand',
|
|
224
|
+
schema: MEMORY_FILE_SCHEMA,
|
|
225
|
+
repaired: true,
|
|
226
|
+
}, rev, bytes, true);
|
|
227
|
+
}
|
|
228
|
+
function parseWithFrontmatter(front, ctx, rev, bytes) {
|
|
229
|
+
let repaired = front.repaired;
|
|
230
|
+
const get = (key) => front.values.get(key);
|
|
231
|
+
const title = parseScalar(get('title') ?? '');
|
|
232
|
+
const summary = parseScalar(get('summary') ?? '');
|
|
233
|
+
repaired = repaired || title.repaired || summary.repaired;
|
|
234
|
+
const rawLoad = parseScalar(get('load') ?? '').text.toLowerCase();
|
|
235
|
+
const load = isMemoryLoad(rawLoad) ? rawLoad : 'auto';
|
|
236
|
+
if (get('load') !== undefined && !isMemoryLoad(rawLoad))
|
|
237
|
+
repaired = true;
|
|
238
|
+
const enabled = parseBoolean(get('enabled'), true);
|
|
239
|
+
if (!enabled.ok)
|
|
240
|
+
repaired = true;
|
|
241
|
+
const created = parseDate(get('created'), ctx.mtimeMs);
|
|
242
|
+
const updated = parseDate(get('updated'), ctx.mtimeMs);
|
|
243
|
+
if (!created.ok || !updated.ok)
|
|
244
|
+
repaired = true;
|
|
245
|
+
const rawSource = parseScalar(get('source') ?? '').text.toLowerCase();
|
|
246
|
+
const source = SOURCES.includes(rawSource)
|
|
247
|
+
? rawSource
|
|
248
|
+
: 'hand';
|
|
249
|
+
const schemaNum = Number.parseInt(parseScalar(get('schema') ?? '').text, 10);
|
|
250
|
+
const schema = Number.isFinite(schemaNum) && schemaNum >= 1 ? schemaNum : MEMORY_FILE_SCHEMA;
|
|
251
|
+
const extra = {};
|
|
252
|
+
let extraCount = 0;
|
|
253
|
+
for (const key of front.order) {
|
|
254
|
+
if (KNOWN_KEYS.has(key))
|
|
255
|
+
continue;
|
|
256
|
+
if (extraCount >= MEMORY_LIMITS.extraKeysMax) {
|
|
257
|
+
repaired = true;
|
|
258
|
+
break;
|
|
259
|
+
}
|
|
260
|
+
const value = toSingleLine(parseScalar(front.values.get(key) ?? '').text);
|
|
261
|
+
extra[key] = clipCodePoints(value, MEMORY_LIMITS.extraValueMax);
|
|
262
|
+
extraCount += 1;
|
|
263
|
+
}
|
|
264
|
+
const note = finishNote({
|
|
265
|
+
id: ctx.id,
|
|
266
|
+
scope: ctx.scope,
|
|
267
|
+
title: title.text,
|
|
268
|
+
rawSummary: summary.text,
|
|
269
|
+
body: front.body,
|
|
270
|
+
tags: get('tags') === undefined ? [] : parseTagList(get('tags')),
|
|
271
|
+
load,
|
|
272
|
+
enabled: enabled.value,
|
|
273
|
+
createdAt: created.ms,
|
|
274
|
+
updatedAt: updated.ms,
|
|
275
|
+
source,
|
|
276
|
+
schema,
|
|
277
|
+
repaired,
|
|
278
|
+
...(extraCount > 0 ? { extra } : {}),
|
|
279
|
+
}, rev, bytes, repaired);
|
|
280
|
+
return note;
|
|
281
|
+
}
|
|
282
|
+
const BARE_TAG = /^[^\s,[\]"'#:]+$/;
|
|
283
|
+
function formatTag(tag) {
|
|
284
|
+
return BARE_TAG.test(tag) ? tag : JSON.stringify(tag);
|
|
285
|
+
}
|
|
286
|
+
/** The exact bytes (as text) a note is stored as. Always LF; always ends in a newline. */
|
|
287
|
+
export function serializeNote(note) {
|
|
288
|
+
const lines = [
|
|
289
|
+
'---',
|
|
290
|
+
`schema: ${Math.max(MEMORY_FILE_SCHEMA, note.schema)}`,
|
|
291
|
+
`title: ${JSON.stringify(note.title)}`,
|
|
292
|
+
`summary: ${JSON.stringify(note.summary)}`,
|
|
293
|
+
`tags: [${note.tags.map(formatTag).join(', ')}]`,
|
|
294
|
+
`load: ${note.load}`,
|
|
295
|
+
`enabled: ${note.enabled ? 'true' : 'false'}`,
|
|
296
|
+
`created: ${new Date(note.createdAt).toISOString()}`,
|
|
297
|
+
`updated: ${new Date(note.updatedAt).toISOString()}`,
|
|
298
|
+
`source: ${note.source}`,
|
|
299
|
+
];
|
|
300
|
+
for (const [key, value] of Object.entries(note.extra ?? {})) {
|
|
301
|
+
if (!/^[A-Za-z_][A-Za-z0-9_-]*$/.test(key) || KNOWN_KEYS.has(key))
|
|
302
|
+
continue;
|
|
303
|
+
lines.push(`${key}: ${JSON.stringify(value)}`);
|
|
304
|
+
}
|
|
305
|
+
lines.push('---', '');
|
|
306
|
+
const body = stripMemoryControl(note.body).replace(/^\n+/, '').replace(/\s+$/, '');
|
|
307
|
+
return `${lines.join('\n')}\n${body}\n`;
|
|
308
|
+
}
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Where agent memory lives on disk, and the rules that keep a caller-supplied name
|
|
3
|
+
* from escaping it (agent-memory spec 5.1 / 5.3 / 8.2, T5 / T6, I-9).
|
|
4
|
+
*
|
|
5
|
+
* ASCII ONLY - `src/memory/**` is inside `glyphs.test.ts::inScope`.
|
|
6
|
+
*
|
|
7
|
+
* NO CALLER-SUPPLIED STRING IS EVER JOINED INTO A PATH BEFORE IT IS VALIDATED. An id
|
|
8
|
+
* reaches this module from three untrusted places: a tool argument the model chose, an
|
|
9
|
+
* IPC argument the renderer sent, and a file name the user (or a sync tool) dropped into
|
|
10
|
+
* the directory. `noteFile()` checks the id FIRST, builds the path SECOND, and then
|
|
11
|
+
* proves the result is still inside the scope directory.
|
|
12
|
+
*/
|
|
13
|
+
import { getMemoryDir } from '../config/app-paths.js';
|
|
14
|
+
import type { MemoryNoteScope } from '@aragon-agent/tui/model/memory/types';
|
|
15
|
+
export { getMemoryDir };
|
|
16
|
+
/** Which directory a store call is about. `projectKey` is required for `project`. */
|
|
17
|
+
export type MemoryTarget = {
|
|
18
|
+
scope: 'global';
|
|
19
|
+
} | {
|
|
20
|
+
scope: 'project';
|
|
21
|
+
projectKey: string;
|
|
22
|
+
};
|
|
23
|
+
/** Whether `id` may name a note file. Pure; no filesystem access. */
|
|
24
|
+
export declare function isValidNoteId(id: unknown): id is string;
|
|
25
|
+
/** Whether `key` has the shape `resolveProjectKey` produces. */
|
|
26
|
+
export declare function isValidProjectKey(key: unknown): key is string;
|
|
27
|
+
/** Mint `mem_` + six lowercase alphanumerics (D-23). */
|
|
28
|
+
export declare function mintNoteId(random?: (size: number) => Buffer): string;
|
|
29
|
+
/** `path` is `root` or lies below it. Compares path SEGMENTS, never string prefixes. */
|
|
30
|
+
export declare function isInside(root: string, path: string): boolean;
|
|
31
|
+
export interface ProjectIdentity {
|
|
32
|
+
/** `<slug>-<8 hex>`; the directory name under `memory/projects/`. */
|
|
33
|
+
key: string;
|
|
34
|
+
/** The display path (as the user knows it), not the normalised one. */
|
|
35
|
+
root: string;
|
|
36
|
+
/** Last path segment, for humans. */
|
|
37
|
+
label: string;
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* Which project a working directory belongs to (spec 5.3).
|
|
41
|
+
*
|
|
42
|
+
* The key is a hash of the NORMALISED real path, so nothing inside a repository can
|
|
43
|
+
* influence it (T2: a cloned repo cannot pre-seed memory), and two spellings of one
|
|
44
|
+
* directory agree. Different git worktrees of one repository are different projects on
|
|
45
|
+
* purpose - the trade-off is documented in the CHANGELOG.
|
|
46
|
+
*/
|
|
47
|
+
export declare function resolveProjectKey(cwd: string): ProjectIdentity;
|
|
48
|
+
/** `global` or `projects/<key>`: the segment shared by notes, trash and versions. */
|
|
49
|
+
export declare function scopeSegment(target: MemoryTarget): string;
|
|
50
|
+
/** The directory holding a scope's live notes, or `null` when the target is malformed. */
|
|
51
|
+
export declare function scopeDir(target: MemoryTarget): string | null;
|
|
52
|
+
/** `.trash/<scope segment>` for deleted notes. */
|
|
53
|
+
export declare function trashDir(target: MemoryTarget): string | null;
|
|
54
|
+
/** `.trash/versions/<scope segment>/<id>` for overwritten versions. */
|
|
55
|
+
export declare function versionsDir(target: MemoryTarget, id: string): string | null;
|
|
56
|
+
/**
|
|
57
|
+
* The file for one note, or `null` when the id is not acceptable.
|
|
58
|
+
*
|
|
59
|
+
* Validates BEFORE joining and checks containment AFTER (I-9): a traversal string, an
|
|
60
|
+
* absolute path, a reserved device name or an over-long id never produces a path.
|
|
61
|
+
*/
|
|
62
|
+
export declare function noteFile(target: MemoryTarget, id: string): string | null;
|
|
63
|
+
/** The stem of a `*.md` directory entry, or `null` for anything else. */
|
|
64
|
+
export declare function stemOfNoteFile(name: string): string | null;
|
|
65
|
+
/** The sidecar that remembers a project's display root (spec 5.1). */
|
|
66
|
+
export declare function projectMetaFile(projectKey: string): string | null;
|
|
67
|
+
/** Scope of a target as stored in a note. */
|
|
68
|
+
export declare function scopeOf(target: MemoryTarget): MemoryNoteScope;
|
|
@@ -0,0 +1,172 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Where agent memory lives on disk, and the rules that keep a caller-supplied name
|
|
3
|
+
* from escaping it (agent-memory spec 5.1 / 5.3 / 8.2, T5 / T6, I-9).
|
|
4
|
+
*
|
|
5
|
+
* ASCII ONLY - `src/memory/**` is inside `glyphs.test.ts::inScope`.
|
|
6
|
+
*
|
|
7
|
+
* NO CALLER-SUPPLIED STRING IS EVER JOINED INTO A PATH BEFORE IT IS VALIDATED. An id
|
|
8
|
+
* reaches this module from three untrusted places: a tool argument the model chose, an
|
|
9
|
+
* IPC argument the renderer sent, and a file name the user (or a sync tool) dropped into
|
|
10
|
+
* the directory. `noteFile()` checks the id FIRST, builds the path SECOND, and then
|
|
11
|
+
* proves the result is still inside the scope directory.
|
|
12
|
+
*/
|
|
13
|
+
import { createHash, randomBytes } from 'node:crypto';
|
|
14
|
+
import { existsSync, realpathSync } from 'node:fs';
|
|
15
|
+
import { basename, dirname, join, parse, relative, resolve, sep } from 'node:path';
|
|
16
|
+
import process from 'node:process';
|
|
17
|
+
import { getMemoryDir } from '../config/app-paths.js';
|
|
18
|
+
import { MEMORY_LIMITS } from '@aragon-agent/tui/model/memory/limits';
|
|
19
|
+
export { getMemoryDir };
|
|
20
|
+
const ID_PATTERN = /^[a-z0-9][a-z0-9_-]*$/;
|
|
21
|
+
/**
|
|
22
|
+
* Names Win32 resolves to a DEVICE no matter the extension or directory. `con.md` is the
|
|
23
|
+
* console, and reading it blocks waiting for input. The rule is the same on every
|
|
24
|
+
* platform: a `nul.md` created on macOS and synced to Windows would hang there.
|
|
25
|
+
*/
|
|
26
|
+
const WINDOWS_DEVICE = /^(con|prn|aux|nul|com[0-9]|lpt[0-9])$/i;
|
|
27
|
+
/** Whether `id` may name a note file. Pure; no filesystem access. */
|
|
28
|
+
export function isValidNoteId(id) {
|
|
29
|
+
if (typeof id !== 'string')
|
|
30
|
+
return false;
|
|
31
|
+
if (id.length === 0 || id.length > MEMORY_LIMITS.idMax)
|
|
32
|
+
return false;
|
|
33
|
+
if (!ID_PATTERN.test(id))
|
|
34
|
+
return false;
|
|
35
|
+
// The pattern has no `.`, so `con.md` and `con.txt` forms cannot reach here as an id; the
|
|
36
|
+
// bare stem (`con`, `com1`) is the only spelling left to reject. `con-1` is a normal name.
|
|
37
|
+
return !WINDOWS_DEVICE.test(id);
|
|
38
|
+
}
|
|
39
|
+
const PROJECT_KEY_PATTERN = /^[a-z0-9][a-z0-9-]*-[0-9a-f]{8}$/;
|
|
40
|
+
/** Whether `key` has the shape `resolveProjectKey` produces. */
|
|
41
|
+
export function isValidProjectKey(key) {
|
|
42
|
+
return typeof key === 'string' && key.length <= 64 && PROJECT_KEY_PATTERN.test(key);
|
|
43
|
+
}
|
|
44
|
+
/** Mint `mem_` + six lowercase alphanumerics (D-23). */
|
|
45
|
+
export function mintNoteId(random = randomBytes) {
|
|
46
|
+
const alphabet = '0123456789abcdefghijklmnopqrstuvwxyz';
|
|
47
|
+
const bytes = random(6);
|
|
48
|
+
let out = 'mem_';
|
|
49
|
+
for (let i = 0; i < 6; i += 1)
|
|
50
|
+
out += alphabet[bytes[i] % alphabet.length];
|
|
51
|
+
return out;
|
|
52
|
+
}
|
|
53
|
+
/** `path` is `root` or lies below it. Compares path SEGMENTS, never string prefixes. */
|
|
54
|
+
export function isInside(root, path) {
|
|
55
|
+
const rel = relative(root, path);
|
|
56
|
+
if (rel === '')
|
|
57
|
+
return true;
|
|
58
|
+
return !rel.startsWith('..') && !rel.includes(`..${sep}`) && rel !== '..' && !parse(rel).root;
|
|
59
|
+
}
|
|
60
|
+
function safeRealpath(path) {
|
|
61
|
+
try {
|
|
62
|
+
return realpathSync.native(path);
|
|
63
|
+
}
|
|
64
|
+
catch {
|
|
65
|
+
return resolve(path);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
/** Nearest ancestor (self included) holding `.git` (a directory OR a worktree file). */
|
|
69
|
+
function findGitRoot(start) {
|
|
70
|
+
let dir = start;
|
|
71
|
+
for (let depth = 0; depth < 40; depth += 1) {
|
|
72
|
+
if (existsSync(join(dir, '.git')))
|
|
73
|
+
return dir;
|
|
74
|
+
const parent = dirname(dir);
|
|
75
|
+
if (parent === dir)
|
|
76
|
+
return null;
|
|
77
|
+
dir = parent;
|
|
78
|
+
}
|
|
79
|
+
return null;
|
|
80
|
+
}
|
|
81
|
+
function slugOf(name) {
|
|
82
|
+
const slug = name
|
|
83
|
+
.toLowerCase()
|
|
84
|
+
.replace(/[^a-z0-9]+/g, '-')
|
|
85
|
+
.replace(/^-+|-+$/g, '')
|
|
86
|
+
.slice(0, 24)
|
|
87
|
+
.replace(/-+$/g, '');
|
|
88
|
+
return slug.length > 0 ? slug : 'project';
|
|
89
|
+
}
|
|
90
|
+
/**
|
|
91
|
+
* Which project a working directory belongs to (spec 5.3).
|
|
92
|
+
*
|
|
93
|
+
* The key is a hash of the NORMALISED real path, so nothing inside a repository can
|
|
94
|
+
* influence it (T2: a cloned repo cannot pre-seed memory), and two spellings of one
|
|
95
|
+
* directory agree. Different git worktrees of one repository are different projects on
|
|
96
|
+
* purpose - the trade-off is documented in the CHANGELOG.
|
|
97
|
+
*/
|
|
98
|
+
export function resolveProjectKey(cwd) {
|
|
99
|
+
const real = safeRealpath(cwd);
|
|
100
|
+
const root = findGitRoot(real) ?? real;
|
|
101
|
+
let normalised = root.replace(/\\/g, '/');
|
|
102
|
+
if (process.platform === 'win32' || process.platform === 'darwin') {
|
|
103
|
+
normalised = normalised.toLowerCase();
|
|
104
|
+
}
|
|
105
|
+
normalised = normalised.replace(/\/+$/, '');
|
|
106
|
+
const label = basename(root) || 'project';
|
|
107
|
+
const hash = createHash('sha1').update(normalised).digest('hex').slice(0, 8);
|
|
108
|
+
return { key: `${slugOf(label)}-${hash}`, root, label };
|
|
109
|
+
}
|
|
110
|
+
/** `global` or `projects/<key>`: the segment shared by notes, trash and versions. */
|
|
111
|
+
export function scopeSegment(target) {
|
|
112
|
+
return target.scope === 'global' ? 'global' : join('projects', target.projectKey);
|
|
113
|
+
}
|
|
114
|
+
/** The directory holding a scope's live notes, or `null` when the target is malformed. */
|
|
115
|
+
export function scopeDir(target) {
|
|
116
|
+
if (target.scope === 'project' && !isValidProjectKey(target.projectKey))
|
|
117
|
+
return null;
|
|
118
|
+
const root = getMemoryDir();
|
|
119
|
+
const dir = join(root, scopeSegment(target));
|
|
120
|
+
return isInside(root, dir) ? dir : null;
|
|
121
|
+
}
|
|
122
|
+
/** `.trash/<scope segment>` for deleted notes. */
|
|
123
|
+
export function trashDir(target) {
|
|
124
|
+
if (target.scope === 'project' && !isValidProjectKey(target.projectKey))
|
|
125
|
+
return null;
|
|
126
|
+
const root = join(getMemoryDir(), '.trash');
|
|
127
|
+
const dir = join(root, scopeSegment(target));
|
|
128
|
+
return isInside(root, dir) ? dir : null;
|
|
129
|
+
}
|
|
130
|
+
/** `.trash/versions/<scope segment>/<id>` for overwritten versions. */
|
|
131
|
+
export function versionsDir(target, id) {
|
|
132
|
+
if (!isValidNoteId(id))
|
|
133
|
+
return null;
|
|
134
|
+
if (target.scope === 'project' && !isValidProjectKey(target.projectKey))
|
|
135
|
+
return null;
|
|
136
|
+
const root = join(getMemoryDir(), '.trash', 'versions');
|
|
137
|
+
const dir = join(root, scopeSegment(target), id);
|
|
138
|
+
return isInside(root, dir) ? dir : null;
|
|
139
|
+
}
|
|
140
|
+
/**
|
|
141
|
+
* The file for one note, or `null` when the id is not acceptable.
|
|
142
|
+
*
|
|
143
|
+
* Validates BEFORE joining and checks containment AFTER (I-9): a traversal string, an
|
|
144
|
+
* absolute path, a reserved device name or an over-long id never produces a path.
|
|
145
|
+
*/
|
|
146
|
+
export function noteFile(target, id) {
|
|
147
|
+
if (!isValidNoteId(id))
|
|
148
|
+
return null;
|
|
149
|
+
const dir = scopeDir(target);
|
|
150
|
+
if (dir === null)
|
|
151
|
+
return null;
|
|
152
|
+
const file = join(dir, `${id}.md`);
|
|
153
|
+
return isInside(dir, file) && dirname(file) === dir ? file : null;
|
|
154
|
+
}
|
|
155
|
+
/** The stem of a `*.md` directory entry, or `null` for anything else. */
|
|
156
|
+
export function stemOfNoteFile(name) {
|
|
157
|
+
if (!name.endsWith('.md'))
|
|
158
|
+
return null;
|
|
159
|
+
const stem = name.slice(0, -3);
|
|
160
|
+
return isValidNoteId(stem) ? stem : null;
|
|
161
|
+
}
|
|
162
|
+
/** The sidecar that remembers a project's display root (spec 5.1). */
|
|
163
|
+
export function projectMetaFile(projectKey) {
|
|
164
|
+
if (!isValidProjectKey(projectKey))
|
|
165
|
+
return null;
|
|
166
|
+
const dir = scopeDir({ scope: 'project', projectKey });
|
|
167
|
+
return dir === null ? null : join(dir, '_project.json');
|
|
168
|
+
}
|
|
169
|
+
/** Scope of a target as stored in a note. */
|
|
170
|
+
export function scopeOf(target) {
|
|
171
|
+
return target.scope;
|
|
172
|
+
}
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Budget resolution and the context plan (agent-memory spec 6.2 / 6.3, D-14, D-17).
|
|
3
|
+
*
|
|
4
|
+
* ASCII ONLY - `src/memory/**` is inside `glyphs.test.ts::inScope`.
|
|
5
|
+
*
|
|
6
|
+
* BOTH FUNCTIONS ARE PURE: no clock, no random, no filesystem. Same input, same output -
|
|
7
|
+
* which is what lets the whole decision table be tested by enumeration, and what keeps
|
|
8
|
+
* the system-prompt block stable across turns so the provider's prefix cache survives
|
|
9
|
+
* (I-4). Nothing here reads a use count or a "last read" time (D-14): reading a note must
|
|
10
|
+
* never reshuffle the catalog.
|
|
11
|
+
*
|
|
12
|
+
* ALL LENGTHS ARE BUDGET UNITS (spec 5.8): an ASCII code point weighs 1, anything else
|
|
13
|
+
* weighs `nonAsciiUnits`. That is what stops a Chinese note from costing three times the
|
|
14
|
+
* window share its character count suggests.
|
|
15
|
+
*/
|
|
16
|
+
import type { MemoryBudgetInput, MemoryBudgets, MemoryContextPlan, MemoryMountOverride, MemoryPlanNote } from '@aragon-agent/tui/model/memory/types';
|
|
17
|
+
/**
|
|
18
|
+
* Resolve the budgets for a model window.
|
|
19
|
+
*
|
|
20
|
+
* `windowTokens` is the window of the model the prompt is being BUILT FOR - read from the
|
|
21
|
+
* config passed to `composeSystemPrompt`, never from `this.config` (I-5) - because a model
|
|
22
|
+
* switch pre-builds the next prompt and must not use the old model's window.
|
|
23
|
+
*
|
|
24
|
+
* The cap is taken from the CONFIG SUM last, so `total` can never exceed what the user
|
|
25
|
+
* configured, even when the floor would otherwise lift it (RV-8).
|
|
26
|
+
*/
|
|
27
|
+
export declare function resolveMemoryBudgets(cfg: MemoryBudgetInput, windowTokens: number | undefined): MemoryBudgets;
|
|
28
|
+
export interface PlanMemoryInput {
|
|
29
|
+
/** Every note visible in this workspace; disabled ones are ignored. */
|
|
30
|
+
notes: readonly MemoryPlanNote[];
|
|
31
|
+
overrides: Readonly<Record<string, MemoryMountOverride>>;
|
|
32
|
+
/** The RESOLVED switch (session ?? config); the planner also ANDs `autoloadActive`. */
|
|
33
|
+
autoload: boolean;
|
|
34
|
+
budgets: MemoryBudgets;
|
|
35
|
+
}
|
|
36
|
+
/** Decide, deterministically, which notes ride in the prompt and at what level (6.3). */
|
|
37
|
+
export declare function planMemoryContext(input: PlanMemoryInput): MemoryContextPlan;
|