@thegitai/cli 1.3.0 → 1.4.0

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.
@@ -144,8 +144,8 @@ const HELP_MARKDOWN = [
144
144
  '- `/skills add <source>` - install a skill from GitHub (`owner/repo/path`',
145
145
  ' or a GitHub URL) or from a local folder into ~/.thegitai/skills; add',
146
146
  ' `--project` to put it in this project\'s .thegitai/skills instead',
147
- '- `/memory` - see what the agent has saved on this computer; also',
148
- ' `/memory edit <number> <text>`, `/memory delete <number>`, `/memory off`, `/memory on`',
147
+ '- `/memory` - see the topics the agent has saved on this computer; also',
148
+ ' `/memory show <number>`, `/memory delete <number>`, `/memory off`, `/memory on`',
149
149
  '- `/<skill> [what to do]` - run a skill yourself. Skills show up in the',
150
150
  ' command picker, and the agent also loads a matching skill on its own',
151
151
  '- `/about` - show version and platform info',
@@ -1,26 +1,30 @@
1
- import { deleteMemory, isMemoryEnabled, listMemories, memoryFilePaths, setMemoryEnabled, updateMemory, } from './store.js';
2
- const USAGE = 'Usage: /memory, /memory edit <number> <text>, /memory delete <number>, /memory off, /memory on';
1
+ import { deleteMemoryTopic, isMemoryEnabled, listMemoryTopics, memoryFolders, readMemoryTopicFile, setMemoryEnabled, } from './store.js';
2
+ const USAGE = 'Usage: /memory, /memory show <number>, /memory delete <number>, /memory off, /memory on';
3
3
  const shownListings = new Map();
4
- function when(entry) {
5
- return entry.updatedAt.slice(0, 16).replace('T', ' ');
4
+ function when(timestamp) {
5
+ return timestamp.slice(0, 16).replace('T', ' ');
6
6
  }
7
7
  function listing(rootDir, env) {
8
- const entries = listMemories(rootDir, env);
9
- shownListings.set(memoryFilePaths(rootDir, env).project, entries.map((entry) => entry.id));
8
+ const topics = listMemoryTopics(rootDir, env);
9
+ const folders = memoryFolders(rootDir, env);
10
+ shownListings.set(folders.project, topics.map(({ scope, name }) => ({ scope, name })));
10
11
  const status = isMemoryEnabled(env)
11
12
  ? 'Memory is on. Notes stay on this computer.'
12
13
  : 'Memory is off. Saved notes are kept but not used.';
13
- if (entries.length === 0)
14
+ if (topics.length === 0)
14
15
  return `${status}\n\nNothing saved yet.`;
15
16
  const section = (title, scope) => {
16
- const lines = entries.flatMap((entry, index) => entry.scope === scope ? [`${index + 1}. ${entry.text} (${when(entry)})`] : []);
17
- return lines.length ? [title, ...lines, ''] : [];
17
+ const lines = topics.flatMap((topic, index) => topic.scope === scope
18
+ ? [`${index + 1}. ${topic.name} - ${topic.description} (updated ${when(topic.updated)})`]
19
+ : []);
20
+ return lines.length ? [`${title}: ${folders[scope]}`, ...lines, ''] : [];
18
21
  };
19
22
  return [
20
23
  status,
21
24
  '',
22
25
  ...section('This project', 'project'),
23
26
  ...section('Everywhere', 'personal'),
27
+ 'Each topic is a Markdown file in the folder above, and can be edited in any text editor.',
24
28
  USAGE,
25
29
  ].join('\n');
26
30
  }
@@ -32,29 +36,23 @@ export function runMemoryCommand(args, rootDir, env = process.env) {
32
36
  setMemoryEnabled(trimmed === 'on', env);
33
37
  return listing(rootDir, env);
34
38
  }
35
- const match = trimmed.match(/^(edit|delete)\s+(\d+)(?:\s+([\s\S]+))?$/);
39
+ const match = trimmed.match(/^(show|delete)\s+(\d+)$/);
36
40
  if (!match)
37
41
  return USAGE;
38
- const shown = shownListings.get(memoryFilePaths(rootDir, env).project);
42
+ const shown = shownListings.get(memoryFolders(rootDir, env).project);
39
43
  if (!shown)
40
- return 'Run /memory first to see the note numbers.';
41
- const id = shown[Number(match[2]) - 1];
42
- if (!id)
43
- return `There is no memory number ${match[2]}.`;
44
- const entry = listMemories(rootDir, env).find((item) => item.id === id);
45
- if (!entry)
46
- return 'That note no longer exists. Run /memory to see the current list.';
47
- if (match[1] === 'delete') {
48
- try {
49
- deleteMemory({ rootDir, env, id });
50
- }
51
- catch (error) {
52
- return error instanceof Error ? error.message : String(error);
53
- }
54
- return `Deleted: ${entry.text}`;
44
+ return 'Run /memory first to see the topic numbers.';
45
+ const target = shown[Number(match[2]) - 1];
46
+ if (!target)
47
+ return `There is no memory topic number ${match[2]}.`;
48
+ try {
49
+ if (match[1] === 'show')
50
+ return readMemoryTopicFile({ rootDir, env, ...target }).content.trimEnd();
51
+ return deleteMemoryTopic({ rootDir, env, ...target })
52
+ ? `Deleted: ${target.name}`
53
+ : 'That topic no longer exists. Run /memory to see the current list.';
54
+ }
55
+ catch (error) {
56
+ return error instanceof Error ? error.message : String(error);
55
57
  }
56
- if (!match[3])
57
- return USAGE;
58
- const updated = updateMemory({ rootDir, env, id, text: match[3] });
59
- return updated.ok ? `Updated: ${updated.entry.text}` : updated.error;
60
58
  }
@@ -1,30 +1,33 @@
1
- import { randomBytes } from 'node:crypto';
2
- import { closeSync, mkdirSync, openSync, readFileSync, renameSync, rmSync, statSync, writeFileSync, } from 'node:fs';
1
+ import { createHash } from 'node:crypto';
2
+ import { closeSync, existsSync, mkdirSync, openSync, readdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync, } from 'node:fs';
3
3
  import path from 'node:path';
4
4
  import { getClientStateDir } from '../client-state.js';
5
5
  import { localTimestamp } from '../local-clock.js';
6
6
  import { getSessionProjectKey } from '../project-key.js';
7
- export const MEMORY_TEXT_MAX_CHARS = 400;
8
- export const MEMORY_MAX_ENTRIES_PER_SCOPE = 100;
7
+ export const MEMORY_ENTRY_MAX_CHARS = 1_000;
8
+ export const MEMORY_TOPIC_MAX_CHARS = 12_000;
9
+ export const MEMORY_MAX_TOPICS_PER_SCOPE = 100;
10
+ const DESCRIPTION_MAX_CHARS = 200;
11
+ const REQUEST_BODY_BUDGET_CHARS = 60_000;
12
+ const INDEX_FILE = 'INDEX.md';
13
+ const LEGACY_FILE = 'memories.json';
14
+ const TYPES = ['preference', 'correction', 'fact', 'decision'];
9
15
  const LOCK_WAIT_MS = 5_000;
10
16
  const LOCK_STALE_MS = 10_000;
11
17
  const LOCK_RETRY_MS = 15;
12
18
  const LOCK_BUSY_CODES = new Set(['EEXIST', 'EPERM', 'EACCES', 'EBUSY']);
13
- function memoryFile(scope, rootDir, env) {
19
+ export function memoryFolder(scope, rootDir, env = process.env) {
14
20
  const base = getClientStateDir(env);
15
21
  return scope === 'personal'
16
- ? path.join(base, 'memory', 'memories.json')
17
- : path.join(base, 'projects', getSessionProjectKey(rootDir), 'memory', 'memories.json');
22
+ ? path.join(base, 'memory')
23
+ : path.join(base, 'projects', getSessionProjectKey(rootDir), 'memory');
24
+ }
25
+ export function memoryFolders(rootDir, env = process.env) {
26
+ return { personal: memoryFolder('personal', rootDir, env), project: memoryFolder('project', rootDir, env) };
18
27
  }
19
28
  function settingsFile(env) {
20
29
  return path.join(getClientStateDir(env), 'memory', 'settings.json');
21
30
  }
22
- export function memoryFilePaths(rootDir, env = process.env) {
23
- return {
24
- personal: memoryFile('personal', rootDir, env),
25
- project: memoryFile('project', rootDir, env),
26
- };
27
- }
28
31
  function withMemoryLock(env, mutate) {
29
32
  const lockPath = path.join(getClientStateDir(env), 'memory', '.lock');
30
33
  mkdirSync(path.dirname(lockPath), { recursive: true, mode: 0o700 });
@@ -55,52 +58,179 @@ function withMemoryLock(env, mutate) {
55
58
  rmSync(lockPath, { force: true });
56
59
  }
57
60
  }
58
- function saveFailure(error) {
59
- return { ok: false, error: error instanceof Error ? error.message : String(error) };
60
- }
61
- function writeJson(filePath, value) {
61
+ function writeText(filePath, text) {
62
62
  mkdirSync(path.dirname(filePath), { recursive: true, mode: 0o700 });
63
63
  const tempPath = `${filePath}.${process.pid}.tmp`;
64
- writeFileSync(tempPath, `${JSON.stringify(value, null, 2)}\n`, { mode: 0o600 });
64
+ writeFileSync(tempPath, text, { mode: 0o600 });
65
65
  renameSync(tempPath, filePath);
66
66
  }
67
- function cleanText(value) {
68
- return String(value ?? '').replace(/\s+/g, ' ').trim();
67
+ function oneLine(value, max = DESCRIPTION_MAX_CHARS) {
68
+ return String(value ?? '').replace(/\s+/g, ' ').trim().slice(0, max);
69
+ }
70
+ function validTime(value) {
71
+ return value && !Number.isNaN(Date.parse(value)) ? value : '';
72
+ }
73
+ function entryStamp(timestamp) {
74
+ return timestamp.slice(0, 16).replace('T', ' ');
75
+ }
76
+ const TRAILING_FILLER = new Set(['a', 'an', 'and', 'as', 'at', 'be', 'by', 'for', 'from', 'in', 'is', 'it', 'of', 'on', 'or', 'that', 'the', 'this', 'to', 'with']);
77
+ function nameFromSentence(text) {
78
+ const words = text.toLowerCase().replace(/[^a-z0-9\s-]+/g, ' ').split(/\s+/).filter(Boolean).slice(0, 6);
79
+ while (words.length > 1 && TRAILING_FILLER.has(words.at(-1)))
80
+ words.pop();
81
+ return words.join(' ');
82
+ }
83
+ export function memoryBodyVersion(body) {
84
+ return createHash('sha256').update(String(body ?? '').trim()).digest('hex').slice(0, 16);
85
+ }
86
+ function entryText(block) {
87
+ return block.trim().replace(/^\d{4}-\d{2}-\d{2} \d{2}:\d{2}: /, '');
88
+ }
89
+ export function topicNameFrom(value) {
90
+ const slug = String(value ?? '')
91
+ .toLowerCase()
92
+ .replace(/[^a-z0-9]+/g, '-')
93
+ .replace(/^-+|-+$/g, '')
94
+ .slice(0, 60)
95
+ .replace(/-+$/, '');
96
+ if (!slug)
97
+ return 'note';
98
+ return slug === 'index' ? 'index-topic' : slug;
99
+ }
100
+ function parseTopic(name, scope, content, modified) {
101
+ const header = {};
102
+ let body = content;
103
+ const match = content.match(/^---\r?\n([\s\S]*?)\r?\n---[ \t]*(?:\r?\n|$)/);
104
+ if (match) {
105
+ for (const line of match[1].split(/\r?\n/)) {
106
+ const colon = line.indexOf(':');
107
+ if (colon > 0)
108
+ header[line.slice(0, colon).trim().toLowerCase()] = line.slice(colon + 1).trim();
109
+ }
110
+ body = content.slice(match[0].length);
111
+ }
112
+ body = body.trim();
113
+ const fallback = localTimestamp(modified);
114
+ const created = validTime(header.created) || fallback;
115
+ return {
116
+ name,
117
+ scope,
118
+ description: oneLine(header.description) || oneLine(body.split('\n')[0]) || name,
119
+ type: TYPES.includes(header.type) ? header.type : 'fact',
120
+ created,
121
+ updated: validTime(header.updated) || created,
122
+ body,
123
+ };
124
+ }
125
+ function renderTopic(topic) {
126
+ return [
127
+ '---',
128
+ `name: ${topic.name}`,
129
+ `description: ${topic.description}`,
130
+ `type: ${topic.type}`,
131
+ `created: ${topic.created}`,
132
+ `updated: ${topic.updated}`,
133
+ '---',
134
+ '',
135
+ topic.body ?? '',
136
+ '',
137
+ ].join('\n');
138
+ }
139
+ function topicFile(folder, name) {
140
+ return path.join(folder, `${name}.md`);
69
141
  }
70
142
  function readScope(scope, rootDir, env) {
71
- let parsed;
143
+ const folder = memoryFolder(scope, rootDir, env);
144
+ let files;
72
145
  try {
73
- parsed = JSON.parse(readFileSync(memoryFile(scope, rootDir, env), 'utf8'));
146
+ files = readdirSync(folder);
74
147
  }
75
148
  catch {
76
149
  return [];
77
150
  }
78
- if (!Array.isArray(parsed))
79
- return [];
80
- const entries = [];
81
- for (const item of parsed) {
82
- if (!item || typeof item !== 'object')
151
+ const topics = [];
152
+ for (const file of files) {
153
+ if (!file.endsWith('.md') || file === INDEX_FILE)
83
154
  continue;
84
- const record = item;
85
- const text = cleanText(record.text).slice(0, MEMORY_TEXT_MAX_CHARS);
86
- if (typeof record.id !== 'string' || !record.id || !text)
87
- continue;
88
- const createdAt = typeof record.createdAt === 'string' ? record.createdAt : '';
89
- const updatedAt = typeof record.updatedAt === 'string' ? record.updatedAt : createdAt;
90
- entries.push({ id: record.id, text, createdAt, updatedAt });
155
+ const filePath = path.join(folder, file);
156
+ try {
157
+ const stat = statSync(filePath);
158
+ if (!stat.isFile())
159
+ continue;
160
+ topics.push(parseTopic(file.slice(0, -3), scope, readFileSync(filePath, 'utf8'), stat.mtime));
161
+ }
162
+ catch {
163
+ }
91
164
  }
92
- return entries;
93
- }
94
- function writeScope(scope, rootDir, env, entries) {
95
- writeJson(memoryFile(scope, rootDir, env), entries);
165
+ return topics;
96
166
  }
97
167
  function byNewest(a, b) {
98
- return (Date.parse(b.updatedAt) || 0) - (Date.parse(a.updatedAt) || 0);
168
+ return (Date.parse(b.updated) || 0) - (Date.parse(a.updated) || 0);
169
+ }
170
+ function writeIndex(folder, topics) {
171
+ if (topics.length === 0) {
172
+ rmSync(path.join(folder, INDEX_FILE), { force: true });
173
+ return;
174
+ }
175
+ const lines = [...topics]
176
+ .sort(byNewest)
177
+ .map((topic) => `- [${topic.name}](${encodeURI(`${topic.name}.md`)}) - ${topic.description} (updated ${entryStamp(topic.updated)})`);
178
+ writeText(path.join(folder, INDEX_FILE), ['# Memory', '', ...lines, ''].join('\n'));
99
179
  }
100
- export function listMemories(rootDir, env = process.env) {
101
- const scoped = (scope) => readScope(scope, rootDir, env)
102
- .map((entry) => ({ ...entry, scope }))
103
- .sort(byNewest);
180
+ function uniqueName(base, taken) {
181
+ let name = base;
182
+ for (let n = 2; taken.has(name); n += 1)
183
+ name = `${base}-${n}`;
184
+ return name;
185
+ }
186
+ function migrateLegacyNotes(scope, rootDir, env) {
187
+ const folder = memoryFolder(scope, rootDir, env);
188
+ const legacyPath = path.join(folder, LEGACY_FILE);
189
+ if (!existsSync(legacyPath))
190
+ return;
191
+ withMemoryLock(env, () => {
192
+ let notes;
193
+ try {
194
+ notes = JSON.parse(readFileSync(legacyPath, 'utf8'));
195
+ }
196
+ catch {
197
+ return;
198
+ }
199
+ const topics = readScope(scope, rootDir, env);
200
+ const taken = new Set(topics.map((topic) => topic.name));
201
+ for (const item of Array.isArray(notes) ? notes : []) {
202
+ const record = (item ?? {});
203
+ const text = oneLine(record.text, MEMORY_ENTRY_MAX_CHARS);
204
+ if (!text)
205
+ continue;
206
+ const created = validTime(String(record.createdAt ?? '')) || localTimestamp();
207
+ const name = uniqueName(topicNameFrom(nameFromSentence(text)), taken);
208
+ taken.add(name);
209
+ const topic = {
210
+ name,
211
+ scope,
212
+ description: oneLine(text.split(/(?<=[.!?])\s/)[0]),
213
+ type: 'fact',
214
+ created,
215
+ updated: validTime(String(record.updatedAt ?? '')) || created,
216
+ body: `${entryStamp(created)}: ${text}`,
217
+ };
218
+ writeText(topicFile(folder, name), renderTopic(topic));
219
+ topics.push(topic);
220
+ }
221
+ writeIndex(folder, topics);
222
+ rmSync(legacyPath, { force: true });
223
+ });
224
+ }
225
+ export function listMemoryTopics(rootDir, env = process.env) {
226
+ const scoped = (scope) => {
227
+ try {
228
+ migrateLegacyNotes(scope, rootDir, env);
229
+ }
230
+ catch {
231
+ }
232
+ return readScope(scope, rootDir, env).sort(byNewest);
233
+ };
104
234
  return [...scoped('project'), ...scoped('personal')];
105
235
  }
106
236
  export function isMemoryEnabled(env = process.env) {
@@ -112,115 +242,140 @@ export function isMemoryEnabled(env = process.env) {
112
242
  }
113
243
  }
114
244
  export function setMemoryEnabled(enabled, env = process.env) {
115
- writeJson(settingsFile(env), { enabled });
245
+ writeText(settingsFile(env), `${JSON.stringify({ enabled }, null, 2)}\n`);
116
246
  }
117
247
  export function collectMemoryRequest(rootDir, env = process.env) {
118
- return isMemoryEnabled(env) ? { memories: listMemories(rootDir, env) } : {};
248
+ if (!isMemoryEnabled(env))
249
+ return {};
250
+ let budget = REQUEST_BODY_BUDGET_CHARS;
251
+ const topics = listMemoryTopics(rootDir, env)
252
+ .sort(byNewest)
253
+ .map((topic) => {
254
+ const body = (topic.body ?? '').slice(0, MEMORY_TOPIC_MAX_CHARS);
255
+ if (body.length > budget)
256
+ return { ...topic, body: undefined };
257
+ budget -= body.length;
258
+ return { ...topic, body };
259
+ });
260
+ return { memoryTopics: topics };
119
261
  }
120
- function validText(text) {
262
+ export function addMemoryEntry({ rootDir, env = process.env, scope: rawScope, topic: rawTopic, text: rawText, description, type, body: rewrittenBody, basedOn, }) {
263
+ const text = oneLine(rawText, Number.MAX_SAFE_INTEGER);
121
264
  if (!text)
122
- return 'A memory needs some text.';
123
- if (text.length > MEMORY_TEXT_MAX_CHARS) {
124
- return `A memory can be at most ${MEMORY_TEXT_MAX_CHARS} characters.`;
265
+ return { ok: false, error: 'A memory needs some text.' };
266
+ if (text.length > MEMORY_ENTRY_MAX_CHARS) {
267
+ return { ok: false, error: `One memory entry can be at most ${MEMORY_ENTRY_MAX_CHARS} characters.` };
125
268
  }
126
- return null;
127
- }
128
- export function saveMemory({ rootDir, env = process.env, text: rawText, scope: rawScope, replaces, }) {
129
- const text = cleanText(rawText);
130
- const invalid = validText(text);
131
- if (invalid)
132
- return { ok: false, error: invalid };
133
- const replacedId = typeof replaces === 'string' ? replaces : '';
269
+ const scope = rawScope === 'personal' ? 'personal' : 'project';
270
+ const folder = memoryFolder(scope, rootDir, env);
134
271
  try {
272
+ migrateLegacyNotes(scope, rootDir, env);
135
273
  return withMemoryLock(env, () => {
136
- let old = null;
137
- if (replacedId) {
138
- for (const candidate of ['project', 'personal']) {
139
- const entry = readScope(candidate, rootDir, env).find((item) => item.id === replacedId);
140
- if (entry)
141
- old = { scope: candidate, entry };
142
- }
143
- if (!old)
144
- return { ok: false, error: `No saved memory has the id ${replacedId}.` };
145
- }
146
- const scope = rawScope === 'personal' || rawScope === 'project' ? rawScope : (old?.scope ?? 'project');
147
- const destination = readScope(scope, rootDir, env).filter((item) => !(old?.scope === scope && item.id === old.entry.id));
148
- const duplicate = destination.find((item) => item.text === text);
149
- if (!duplicate && destination.length >= MEMORY_MAX_ENTRIES_PER_SCOPE) {
274
+ const topics = readScope(scope, rootDir, env);
275
+ const requested = String(rawTopic ?? '').trim();
276
+ const name = topics.some((topic) => topic.name === requested)
277
+ ? requested
278
+ : topicNameFrom(requested || nameFromSentence(text));
279
+ const existing = topics.find((topic) => topic.name === name);
280
+ if (!existing && topics.length >= MEMORY_MAX_TOPICS_PER_SCOPE) {
150
281
  return {
151
282
  ok: false,
152
- error: `Memory is full (${MEMORY_MAX_ENTRIES_PER_SCOPE} notes). Replace an outdated note, or ask the user to remove some with /memory.`,
283
+ error: `Memory is full (${MEMORY_MAX_TOPICS_PER_SCOPE} topics). Add to an existing topic, or ask the user to remove some with /memory.`,
153
284
  };
154
285
  }
155
286
  const now = localTimestamp();
156
- const entry = duplicate ?? {
157
- id: `m_${randomBytes(4).toString('hex')}`,
158
- text,
159
- createdAt: old?.entry.createdAt || now,
160
- updatedAt: now,
287
+ const entry = { at: entryStamp(now), text };
288
+ const base = existing ?? {
289
+ name,
290
+ scope,
291
+ description: oneLine(description) || oneLine(text.split(/(?<=[.!?])\s/)[0]),
292
+ type: TYPES.includes(type) ? type : 'fact',
293
+ created: now,
294
+ updated: now,
295
+ body: '',
161
296
  };
162
- if (!duplicate || old?.scope === scope) {
163
- writeScope(scope, rootDir, env, duplicate ? destination : [...destination, entry]);
164
- }
165
- if (old && old.scope !== scope) {
166
- const replacedEntryId = old.entry.id;
167
- writeScope(old.scope, rootDir, env, readScope(old.scope, rootDir, env).filter((item) => item.id !== replacedEntryId));
297
+ const replacement = typeof rewrittenBody === 'string' && rewrittenBody.trim() && existing && basedOn === memoryBodyVersion(existing.body)
298
+ ? rewrittenBody.trim()
299
+ : null;
300
+ const before = replacement ?? base.body ?? '';
301
+ const duplicate = before.split(/\n\s*\n/).some((block) => entryText(block) === text);
302
+ if (duplicate && replacement === null)
303
+ return { ok: true, topic: base, entry, created: false };
304
+ const body = duplicate ? before : before ? `${before}\n\n${entry.at}: ${text}` : `${entry.at}: ${text}`;
305
+ if (body.length > MEMORY_TOPIC_MAX_CHARS) {
306
+ return {
307
+ ok: false,
308
+ error: `The topic ${base.name} is full (${MEMORY_TOPIC_MAX_CHARS} characters). Ask the user to tidy it with /memory.`,
309
+ };
168
310
  }
169
- return { ok: true, entry: { ...entry, scope } };
311
+ const topic = { ...base, updated: now, body };
312
+ writeText(topicFile(folder, topic.name), renderTopic(topic));
313
+ writeIndex(folder, [...topics.filter((item) => item.name !== topic.name), topic]);
314
+ return { ok: true, topic, entry, created: !existing };
170
315
  });
171
316
  }
172
317
  catch (error) {
173
- return saveFailure(error);
318
+ return { ok: false, error: error instanceof Error ? error.message : String(error) };
174
319
  }
175
320
  }
176
- export function updateMemory({ rootDir, env = process.env, id, text: rawText, }) {
177
- const text = cleanText(rawText);
178
- const invalid = validText(text);
179
- if (invalid)
180
- return { ok: false, error: invalid };
181
- try {
182
- return withMemoryLock(env, () => {
183
- for (const scope of ['project', 'personal']) {
184
- const entries = readScope(scope, rootDir, env);
185
- const index = entries.findIndex((entry) => entry.id === id);
186
- if (index === -1)
187
- continue;
188
- const entry = { ...entries[index], text, updatedAt: localTimestamp() };
189
- entries[index] = entry;
190
- writeScope(scope, rootDir, env, entries);
191
- return { ok: true, entry: { ...entry, scope } };
192
- }
193
- return { ok: false, error: 'That memory no longer exists.' };
194
- });
195
- }
196
- catch (error) {
197
- return saveFailure(error);
198
- }
321
+ function findTopic(scope, name, rootDir, env) {
322
+ return readScope(scope, rootDir, env).find((topic) => topic.name === name);
323
+ }
324
+ export function readMemoryTopicFile({ rootDir, env = process.env, scope, name, }) {
325
+ if (!findTopic(scope, name, rootDir, env))
326
+ throw new Error('That memory topic no longer exists.');
327
+ const filePath = topicFile(memoryFolder(scope, rootDir, env), name);
328
+ return { path: filePath, content: readFileSync(filePath, 'utf8') };
199
329
  }
200
- export function deleteMemory({ rootDir, env = process.env, id, }) {
330
+ export function writeMemoryTopicFile({ rootDir, env = process.env, scope, name, content, }) {
201
331
  return withMemoryLock(env, () => {
202
- for (const scope of ['project', 'personal']) {
203
- const entries = readScope(scope, rootDir, env);
204
- if (!entries.some((entry) => entry.id === id))
205
- continue;
206
- writeScope(scope, rootDir, env, entries.filter((entry) => entry.id !== id));
207
- return true;
332
+ const folder = memoryFolder(scope, rootDir, env);
333
+ const topics = readScope(scope, rootDir, env);
334
+ const existing = topics.find((topic) => topic.name === name);
335
+ if (!existing)
336
+ throw new Error('That memory topic no longer exists.');
337
+ const parsed = parseTopic(name, scope, String(content), new Date());
338
+ if (!parsed.body)
339
+ throw new Error('A memory topic needs some text. Delete it instead.');
340
+ if ((parsed.body ?? '').length > MEMORY_TOPIC_MAX_CHARS) {
341
+ throw new Error(`A memory topic can be at most ${MEMORY_TOPIC_MAX_CHARS} characters.`);
208
342
  }
209
- return false;
343
+ const changed = parsed.body !== existing.body || parsed.description !== existing.description || parsed.type !== existing.type;
344
+ const topic = {
345
+ ...parsed,
346
+ created: existing.created,
347
+ updated: changed ? localTimestamp() : existing.updated,
348
+ };
349
+ writeText(topicFile(folder, name), renderTopic(topic));
350
+ writeIndex(folder, [...topics.filter((item) => item.name !== name), topic]);
351
+ return topic;
352
+ });
353
+ }
354
+ export function deleteMemoryTopic({ rootDir, env = process.env, scope, name, }) {
355
+ return withMemoryLock(env, () => {
356
+ const folder = memoryFolder(scope, rootDir, env);
357
+ const topics = readScope(scope, rootDir, env);
358
+ if (!topics.some((topic) => topic.name === name))
359
+ return false;
360
+ rmSync(topicFile(folder, name), { force: true });
361
+ writeIndex(folder, topics.filter((topic) => topic.name !== name));
362
+ return true;
210
363
  });
211
364
  }
212
- export function searchMemories(rootDir, env, query, limit = 10) {
213
- const entries = listMemories(rootDir, env);
214
- const terms = cleanText(query).toLowerCase().split(' ').filter((term) => term.length > 1);
365
+ export function searchMemoryTopics(rootDir, env, query, limit = 5) {
366
+ const topics = listMemoryTopics(rootDir, env);
367
+ const terms = oneLine(query, 500).toLowerCase().split(' ').filter((term) => term.length > 1);
215
368
  if (terms.length === 0)
216
- return entries.slice(0, limit);
217
- return entries
218
- .map((entry) => {
219
- const text = entry.text.toLowerCase();
220
- return { entry, score: terms.filter((term) => text.includes(term)).length };
369
+ return topics.slice(0, limit);
370
+ return topics
371
+ .map((topic) => {
372
+ const title = `${topic.name} ${topic.description}`.toLowerCase();
373
+ const body = (topic.body ?? '').toLowerCase();
374
+ const score = terms.reduce((total, term) => total + (title.includes(term) ? 2 : 0) + (body.includes(term) ? 1 : 0), 0);
375
+ return { topic, score };
221
376
  })
222
377
  .filter((match) => match.score > 0)
223
- .sort((a, b) => b.score - a.score || byNewest(a.entry, b.entry))
378
+ .sort((a, b) => b.score - a.score || byNewest(a.topic, b.topic))
224
379
  .slice(0, limit)
225
- .map((match) => match.entry);
380
+ .map((match) => match.topic);
226
381
  }
@@ -1,25 +1,79 @@
1
- import { isMemoryEnabled, saveMemory, searchMemories } from '../memory/store.js';
1
+ import { addMemoryEntry, isMemoryEnabled, searchMemoryTopics } from '../memory/store.js';
2
+ const RECALL_BODY_CHARS = 4_000;
2
3
  function memoryOff() {
3
4
  return { ok: false, error: 'Memory is turned off.', failureCategory: 'permission_denied' };
4
5
  }
5
6
  export function rememberNote(context, args) {
6
7
  if (!isMemoryEnabled(context.env))
7
8
  return memoryOff();
8
- const saved = saveMemory({
9
+ const saved = addMemoryEntry({
9
10
  rootDir: context.rootDir,
10
11
  env: context.env,
11
- text: args?.text,
12
12
  scope: args?.scope,
13
- replaces: args?.replaces,
13
+ topic: args?.topic,
14
+ text: args?.text,
15
+ description: args?.description,
16
+ type: args?.kind,
17
+ body: args?.body,
18
+ basedOn: args?.basedOn,
14
19
  });
15
20
  if (!saved.ok) {
16
21
  return { ok: false, error: saved.error, failureCategory: 'invalid_argument' };
17
22
  }
18
- return { ok: true, ...saved.entry, output: 'Saved to memory.' };
23
+ const { topic, entry } = saved;
24
+ return {
25
+ ok: true,
26
+ topic: topic.name,
27
+ scope: topic.scope,
28
+ description: topic.description,
29
+ type: topic.type,
30
+ created: topic.created,
31
+ updated: topic.updated,
32
+ at: entry.at,
33
+ text: entry.text,
34
+ newTopic: saved.created,
35
+ output: 'Saved to memory.',
36
+ };
37
+ }
38
+ function entriesFor(body, query) {
39
+ const blocks = body.split(/\n\s*\n/).filter((block) => block.trim());
40
+ if (body.length <= RECALL_BODY_CHARS)
41
+ return { body, omittedEntries: 0 };
42
+ const terms = query.toLowerCase().split(/\s+/).filter((term) => term.length > 1);
43
+ const matching = blocks.map((block, index) => ({ index, hit: terms.some((term) => block.toLowerCase().includes(term)) }));
44
+ const order = [
45
+ ...matching.filter((item) => item.hit).map((item) => item.index),
46
+ ...matching.filter((item) => !item.hit).map((item) => item.index).reverse(),
47
+ ];
48
+ const kept = new Set();
49
+ let used = 0;
50
+ for (const index of order) {
51
+ const size = blocks[index].length + 2;
52
+ if (used + size > RECALL_BODY_CHARS && kept.size > 0)
53
+ continue;
54
+ kept.add(index);
55
+ used += size;
56
+ }
57
+ return {
58
+ body: blocks.filter((_, index) => kept.has(index)).join('\n\n'),
59
+ omittedEntries: blocks.length - kept.size,
60
+ };
19
61
  }
20
62
  export function recallNotes(context, args) {
21
63
  if (!isMemoryEnabled(context.env))
22
64
  return memoryOff();
23
- const matches = searchMemories(context.rootDir, context.env ?? process.env, String(args?.query ?? ''));
65
+ const matches = searchMemoryTopics(context.rootDir, context.env ?? process.env, String(args?.query ?? '')).map((topic) => {
66
+ const { body, omittedEntries } = entriesFor(topic.body ?? '', String(args?.query ?? ''));
67
+ return {
68
+ topic: topic.name,
69
+ scope: topic.scope,
70
+ description: topic.description,
71
+ type: topic.type,
72
+ created: topic.created,
73
+ updated: topic.updated,
74
+ body,
75
+ ...(omittedEntries ? { omittedEntries } : {}),
76
+ };
77
+ });
24
78
  return { ok: true, query: String(args?.query ?? ''), matches };
25
79
  }
@@ -71,13 +71,21 @@ function sameTranscriptDraft(a, b) {
71
71
  a.filePath === b.filePath &&
72
72
  a.preformatted === b.preformatted);
73
73
  }
74
- export function buildSettledTurnTranscriptEntries(turnEntries, responseText) {
74
+ export function memoryUpdatedNote(topics) {
75
+ if (topics.length === 0)
76
+ return undefined;
77
+ const named = [...new Set(topics.filter(Boolean))];
78
+ return named.length ? `Memory updated: ${named.join(', ')}` : 'Memory updated';
79
+ }
80
+ export function buildSettledTurnTranscriptEntries(turnEntries, responseText, memoryTopics = []) {
75
81
  const responseBody = String(responseText ?? '').trim();
82
+ const note = memoryUpdatedNote(memoryTopics);
76
83
  const responseEntry = responseBody
77
84
  ? {
78
85
  body: responseBody,
79
86
  kind: 'assistant',
80
87
  title: 'Response',
88
+ ...(note ? { note } : {}),
81
89
  }
82
90
  : null;
83
91
  return [
@@ -751,13 +759,6 @@ export function buildWorkingToolEntry(event, label = event.call.name) {
751
759
  title: call.name === 'shell_job_kill' ? 'Kill job' : 'Job output',
752
760
  };
753
761
  }
754
- if (call.name === 'remember') {
755
- return {
756
- body: `${String(result?.text ?? call.args?.text ?? '').trim()}${error}`,
757
- kind,
758
- title: failed ? 'Memory' : 'Saved to memory',
759
- };
760
- }
761
762
  if (call.name === 'recall') {
762
763
  const found = Array.isArray(result?.matches) ? result.matches.length : 0;
763
764
  return {
@@ -854,6 +855,15 @@ export function buildTranscriptFromSessionHistory(history) {
854
855
  const entries = [];
855
856
  const pendingCalls = new Map();
856
857
  const pendingUserInputRequests = new Map();
858
+ let turnMemory = [];
859
+ let turnResponse = null;
860
+ const settleTurnMemory = () => {
861
+ const note = memoryUpdatedNote(turnMemory);
862
+ if (note && turnResponse)
863
+ turnResponse.note = note;
864
+ turnMemory = [];
865
+ turnResponse = null;
866
+ };
857
867
  for (const entry of history) {
858
868
  if (!entry?.parts?.length)
859
869
  continue;
@@ -903,6 +913,12 @@ export function buildTranscriptFromSessionHistory(history) {
903
913
  if (!call && responseName) {
904
914
  call = findPendingToolCallByName(pendingCalls, responseName);
905
915
  }
916
+ if (call?.name === 'remember') {
917
+ const saved = (functionResponse.response ?? {});
918
+ if (saved.ok === true)
919
+ turnMemory.push(String(saved.topic ?? call.args?.topic ?? '').trim());
920
+ continue;
921
+ }
906
922
  if (!call || !isFileChangeTool(call.name))
907
923
  continue;
908
924
  const result = (functionResponse.response ?? {});
@@ -911,6 +927,7 @@ export function buildTranscriptFromSessionHistory(history) {
911
927
  entries.push(buildFileChangeEntry({ call, result }));
912
928
  }
913
929
  if (entry.role === 'user' && entry.kind === 'turnStart') {
930
+ settleTurnMemory();
914
931
  const text = displayUserTextFromHistoryEntry(entry);
915
932
  if (text) {
916
933
  entries.push({ body: text, kind: 'user', title: 'You' });
@@ -934,9 +951,13 @@ export function buildTranscriptFromSessionHistory(history) {
934
951
  });
935
952
  continue;
936
953
  }
937
- entries.push({ body: text, kind: 'assistant', title: 'Response' });
954
+ if (turnResponse?.body === text)
955
+ continue;
956
+ turnResponse = { body: text, kind: 'assistant', title: 'Response' };
957
+ entries.push(turnResponse);
938
958
  }
939
959
  }
960
+ settleTurnMemory();
940
961
  return entries;
941
962
  }
942
963
  function createInitialTranscript() {
@@ -1512,6 +1533,7 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
1512
1533
  const blockedRows = new WeakMap();
1513
1534
  let newConversationInFlight = false;
1514
1535
  let todosTouchedThisTurn = false;
1536
+ let memoryTopicsThisTurn = [];
1515
1537
  const syncTodosState = () => {
1516
1538
  store.update((current) => ({ ...current, todos: listTodos() }));
1517
1539
  };
@@ -1660,7 +1682,8 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
1660
1682
  appendStaticEntry(entry);
1661
1683
  };
1662
1684
  const appendSettledTurnEntries = async (turnEntries, responseText, shouldContinue = () => true) => {
1663
- const entries = buildSettledTurnTranscriptEntries(turnEntries, responseText);
1685
+ const entries = buildSettledTurnTranscriptEntries(turnEntries, responseText, memoryTopicsThisTurn);
1686
+ memoryTopicsThisTurn = [];
1664
1687
  const responseEntry = entries.at(-1);
1665
1688
  if (!responseEntry ||
1666
1689
  responseEntry.kind !== 'assistant' ||
@@ -3022,6 +3045,7 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
3022
3045
  activeTurnAbort = turnAbort;
3023
3046
  lastTurnStartedAt = turnStartedAt;
3024
3047
  todosTouchedThisTurn = false;
3048
+ memoryTopicsThisTurn = [];
3025
3049
  if (!jobFollowUp)
3026
3050
  clearTodos();
3027
3051
  syncTodosState();
@@ -3300,6 +3324,12 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
3300
3324
  return;
3301
3325
  }
3302
3326
  }
3327
+ if (event.call.name === 'remember') {
3328
+ const saved = event.result;
3329
+ if (saved?.ok === true)
3330
+ memoryTopicsThisTurn.push(String(saved.topic ?? event.call.args?.topic ?? '').trim());
3331
+ return;
3332
+ }
3303
3333
  if (isFileChangeTool(event.call.name)) {
3304
3334
  const entry = buildFileChangeEntry(event);
3305
3335
  store.appendWorkingTool(entry);
@@ -9,7 +9,7 @@ export const SLASH_COMMANDS = [
9
9
  { command: '/new', description: 'start a new conversation; this session remains saved' },
10
10
  { command: '/mcp', description: 'Check MCP connections and available tools' },
11
11
  { command: '/skills', description: 'List installed skills, or add one: /skills add <source>' },
12
- { command: '/memory', description: 'See, edit or delete saved notes, or turn memory off' },
12
+ { command: '/memory', description: 'See, show or delete saved topics, or turn memory off' },
13
13
  { command: '/jobs', description: 'Background jobs: pick to view output or kill' },
14
14
  {
15
15
  command: '/notify',
@@ -349,6 +349,8 @@ export function renderTranscriptEntryLines(entry, width) {
349
349
  if (entry.todoList && entry.todoList.length > 0) {
350
350
  lines.push(...renderTodoListLines(entry.todoList, width));
351
351
  }
352
+ if (entry.note)
353
+ lines.push(plainLine(` ${entry.note}`, { color: 'gray' }));
352
354
  return lines;
353
355
  }
354
356
  const transcriptEntryLineCache = new WeakMap();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@thegitai/cli",
3
- "version": "1.3.0",
3
+ "version": "1.4.0",
4
4
  "description": "TheGitAI is an agentic AI coding tool for your terminal. It reads and searches your repository, writes and edits files, runs your tests, and verifies the change before handing it back.",
5
5
  "keywords": [
6
6
  "agentic-ai",
@@ -45,11 +45,11 @@
45
45
  "@lydell/node-pty-linux-x64": "1.1.0",
46
46
  "@lydell/node-pty-win32-arm64": "1.1.0",
47
47
  "@lydell/node-pty-win32-x64": "1.1.0",
48
- "@thegitai/tui-darwin-arm64": "1.3.0",
49
- "@thegitai/tui-darwin-x64": "1.3.0",
50
- "@thegitai/tui-linux-arm64": "1.3.0",
51
- "@thegitai/tui-linux-x64": "1.3.0",
52
- "@thegitai/tui-win32-x64": "1.3.0",
48
+ "@thegitai/tui-darwin-arm64": "1.4.0",
49
+ "@thegitai/tui-darwin-x64": "1.4.0",
50
+ "@thegitai/tui-linux-arm64": "1.4.0",
51
+ "@thegitai/tui-linux-x64": "1.4.0",
52
+ "@thegitai/tui-win32-x64": "1.4.0",
53
53
  "@vscode/ripgrep": "1.18.0"
54
54
  },
55
55
  "repository": {