@thegitai/cli 1.2.2 → 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.
package/README.md CHANGED
@@ -295,6 +295,14 @@ repositories) or a local folder after showing what it contains; add `--project`
295
295
  to install it into the current project. Ask the agent to "create a skill that
296
296
  ..." or run `/skill-creator` to make one.
297
297
 
298
+ ## Memory
299
+
300
+ TheGitAI saves short notes when you correct it, state a lasting preference, or
301
+ make a decision the code does not show, and shows you when it does. Notes are
302
+ files on your computer, per project or personal, each with the time it was saved.
303
+ They are sent with a request only so the agent can use them for that turn.
304
+ `/memory` lists, edits and deletes them; `/memory off` turns the feature off.
305
+
298
306
  ## Chrome browser control
299
307
 
300
308
  The TheGitAI Chrome extension is separately installed. After installing it,
@@ -9,6 +9,8 @@ const PLAN_MODE_TOOL_NAMES = new Set([
9
9
  'shell_job_output',
10
10
  'update_todos',
11
11
  'use_skill',
12
+ 'remember',
13
+ 'recall',
12
14
  'browser',
13
15
  'browser_tabs',
14
16
  'browser_read_page',
@@ -15,6 +15,8 @@ import { collectClientEnvironment } from '../client-environment.js';
15
15
  import { collectProjectOrientation } from '../project-orientation.js';
16
16
  import { collectProjectInstructionFiles } from '../project-instructions.js';
17
17
  import { collectSkillRequest } from '../skills/discovery.js';
18
+ import { collectMemoryRequest } from '../memory/store.js';
19
+ import { collectLocalClock } from '../local-clock.js';
18
20
  import { describeSessionImageStore } from '../core/session-image-store.js';
19
21
  import { autoAttachImages } from '../core/image-path-extractor.js';
20
22
  import { formatTurnFailureMarker } from '../turn-failure-marker.js';
@@ -767,6 +769,8 @@ async function sendServerUserMessageInner({ config, session, input, jobFollowUp
767
769
  clientTurnId: randomUUID(),
768
770
  mcpTools: await sessionMcp(session).discover(signal),
769
771
  ...collectSkillRequest(session.rootDir, session.env, jobFollowUp ? '' : requestInputBase),
772
+ ...collectMemoryRequest(session.rootDir, session.env),
773
+ localClock: collectLocalClock(),
770
774
  modelId: session.modelId,
771
775
  reasoningEffort: projectModelEffort(readProjectModelEfforts(session.rootDir, config.serverUrl, session.env), session.modelId),
772
776
  session: snapshotForServer(session),
@@ -144,6 +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 the topics the agent has saved on this computer; also',
148
+ ' `/memory show <number>`, `/memory delete <number>`, `/memory off`, `/memory on`',
147
149
  '- `/<skill> [what to do]` - run a skill yourself. Skills show up in the',
148
150
  ' command picker, and the agent also loads a matching skill on its own',
149
151
  '- `/about` - show version and platform info',
@@ -0,0 +1,14 @@
1
+ function pad(value) {
2
+ return String(Math.abs(Math.trunc(value))).padStart(2, '0');
3
+ }
4
+ export function localTimestamp(now = new Date()) {
5
+ const offset = -now.getTimezoneOffset();
6
+ const sign = offset >= 0 ? '+' : '-';
7
+ const date = `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}`;
8
+ const time = `${pad(now.getHours())}:${pad(now.getMinutes())}:${pad(now.getSeconds())}`;
9
+ return `${date}T${time}${sign}${pad(offset / 60)}:${pad(offset % 60)}`;
10
+ }
11
+ export function collectLocalClock(now = new Date()) {
12
+ const timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone;
13
+ return { localTime: localTimestamp(now), ...(timeZone ? { timeZone } : {}) };
14
+ }
@@ -0,0 +1,58 @@
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
+ const shownListings = new Map();
4
+ function when(timestamp) {
5
+ return timestamp.slice(0, 16).replace('T', ' ');
6
+ }
7
+ function listing(rootDir, env) {
8
+ const topics = listMemoryTopics(rootDir, env);
9
+ const folders = memoryFolders(rootDir, env);
10
+ shownListings.set(folders.project, topics.map(({ scope, name }) => ({ scope, name })));
11
+ const status = isMemoryEnabled(env)
12
+ ? 'Memory is on. Notes stay on this computer.'
13
+ : 'Memory is off. Saved notes are kept but not used.';
14
+ if (topics.length === 0)
15
+ return `${status}\n\nNothing saved yet.`;
16
+ const section = (title, scope) => {
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, ''] : [];
21
+ };
22
+ return [
23
+ status,
24
+ '',
25
+ ...section('This project', 'project'),
26
+ ...section('Everywhere', 'personal'),
27
+ 'Each topic is a Markdown file in the folder above, and can be edited in any text editor.',
28
+ USAGE,
29
+ ].join('\n');
30
+ }
31
+ export function runMemoryCommand(args, rootDir, env = process.env) {
32
+ const trimmed = args.trim();
33
+ if (!trimmed || trimmed === 'list')
34
+ return listing(rootDir, env);
35
+ if (trimmed === 'off' || trimmed === 'on') {
36
+ setMemoryEnabled(trimmed === 'on', env);
37
+ return listing(rootDir, env);
38
+ }
39
+ const match = trimmed.match(/^(show|delete)\s+(\d+)$/);
40
+ if (!match)
41
+ return USAGE;
42
+ const shown = shownListings.get(memoryFolders(rootDir, env).project);
43
+ if (!shown)
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);
57
+ }
58
+ }
@@ -0,0 +1,381 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { closeSync, existsSync, mkdirSync, openSync, readdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync, } from 'node:fs';
3
+ import path from 'node:path';
4
+ import { getClientStateDir } from '../client-state.js';
5
+ import { localTimestamp } from '../local-clock.js';
6
+ import { getSessionProjectKey } from '../project-key.js';
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'];
15
+ const LOCK_WAIT_MS = 5_000;
16
+ const LOCK_STALE_MS = 10_000;
17
+ const LOCK_RETRY_MS = 15;
18
+ const LOCK_BUSY_CODES = new Set(['EEXIST', 'EPERM', 'EACCES', 'EBUSY']);
19
+ export function memoryFolder(scope, rootDir, env = process.env) {
20
+ const base = getClientStateDir(env);
21
+ return scope === 'personal'
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) };
27
+ }
28
+ function settingsFile(env) {
29
+ return path.join(getClientStateDir(env), 'memory', 'settings.json');
30
+ }
31
+ function withMemoryLock(env, mutate) {
32
+ const lockPath = path.join(getClientStateDir(env), 'memory', '.lock');
33
+ mkdirSync(path.dirname(lockPath), { recursive: true, mode: 0o700 });
34
+ const deadline = Date.now() + LOCK_WAIT_MS;
35
+ for (;;) {
36
+ try {
37
+ closeSync(openSync(lockPath, 'wx', 0o600));
38
+ break;
39
+ }
40
+ catch (error) {
41
+ if (!LOCK_BUSY_CODES.has(error?.code))
42
+ throw error;
43
+ try {
44
+ if (Date.now() - statSync(lockPath).mtimeMs > LOCK_STALE_MS)
45
+ rmSync(lockPath, { force: true });
46
+ }
47
+ catch {
48
+ }
49
+ if (Date.now() > deadline)
50
+ throw new Error('Memory is busy. Try again in a moment.');
51
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, LOCK_RETRY_MS);
52
+ }
53
+ }
54
+ try {
55
+ return mutate();
56
+ }
57
+ finally {
58
+ rmSync(lockPath, { force: true });
59
+ }
60
+ }
61
+ function writeText(filePath, text) {
62
+ mkdirSync(path.dirname(filePath), { recursive: true, mode: 0o700 });
63
+ const tempPath = `${filePath}.${process.pid}.tmp`;
64
+ writeFileSync(tempPath, text, { mode: 0o600 });
65
+ renameSync(tempPath, filePath);
66
+ }
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`);
141
+ }
142
+ function readScope(scope, rootDir, env) {
143
+ const folder = memoryFolder(scope, rootDir, env);
144
+ let files;
145
+ try {
146
+ files = readdirSync(folder);
147
+ }
148
+ catch {
149
+ return [];
150
+ }
151
+ const topics = [];
152
+ for (const file of files) {
153
+ if (!file.endsWith('.md') || file === INDEX_FILE)
154
+ continue;
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
+ }
164
+ }
165
+ return topics;
166
+ }
167
+ function byNewest(a, b) {
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'));
179
+ }
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
+ };
234
+ return [...scoped('project'), ...scoped('personal')];
235
+ }
236
+ export function isMemoryEnabled(env = process.env) {
237
+ try {
238
+ return JSON.parse(readFileSync(settingsFile(env), 'utf8'))?.enabled !== false;
239
+ }
240
+ catch {
241
+ return true;
242
+ }
243
+ }
244
+ export function setMemoryEnabled(enabled, env = process.env) {
245
+ writeText(settingsFile(env), `${JSON.stringify({ enabled }, null, 2)}\n`);
246
+ }
247
+ export function collectMemoryRequest(rootDir, env = process.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 };
261
+ }
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);
264
+ if (!text)
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.` };
268
+ }
269
+ const scope = rawScope === 'personal' ? 'personal' : 'project';
270
+ const folder = memoryFolder(scope, rootDir, env);
271
+ try {
272
+ migrateLegacyNotes(scope, rootDir, env);
273
+ return withMemoryLock(env, () => {
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) {
281
+ return {
282
+ ok: false,
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.`,
284
+ };
285
+ }
286
+ const now = localTimestamp();
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: '',
296
+ };
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
+ };
310
+ }
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 };
315
+ });
316
+ }
317
+ catch (error) {
318
+ return { ok: false, error: error instanceof Error ? error.message : String(error) };
319
+ }
320
+ }
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') };
329
+ }
330
+ export function writeMemoryTopicFile({ rootDir, env = process.env, scope, name, content, }) {
331
+ return withMemoryLock(env, () => {
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.`);
342
+ }
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;
363
+ });
364
+ }
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);
368
+ if (terms.length === 0)
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 };
376
+ })
377
+ .filter((match) => match.score > 0)
378
+ .sort((a, b) => b.score - a.score || byNewest(a.topic, b.topic))
379
+ .slice(0, limit)
380
+ .map((match) => match.topic);
381
+ }
@@ -20,6 +20,7 @@ import { strReplace } from './str-replace.js';
20
20
  import { undoEdit } from './undo-edit.js';
21
21
  import { updateTodos } from './update-todos.js';
22
22
  import { useSkill } from './use-skill.js';
23
+ import { recallNotes, rememberNote } from './memory.js';
23
24
  import { saveGeneratedImage } from './save-generated-image.js';
24
25
  import { writeFile } from './write-file.js';
25
26
  export const TOOL_MAP = {
@@ -45,6 +46,8 @@ export const TOOL_MAP = {
45
46
  shell_job_kill: shellJobKill,
46
47
  update_todos: updateTodos,
47
48
  use_skill: (context, args) => useSkill(context, args),
49
+ remember: (context, args) => rememberNote(context, args),
50
+ recall: (context, args) => recallNotes(context, args),
48
51
  browser: (context, args) => browserGateway(context, args),
49
52
  browser_tabs: browserTabs,
50
53
  browser_tab_new: (context, args) => browserTabNew(context, args),
@@ -0,0 +1,79 @@
1
+ import { addMemoryEntry, isMemoryEnabled, searchMemoryTopics } from '../memory/store.js';
2
+ const RECALL_BODY_CHARS = 4_000;
3
+ function memoryOff() {
4
+ return { ok: false, error: 'Memory is turned off.', failureCategory: 'permission_denied' };
5
+ }
6
+ export function rememberNote(context, args) {
7
+ if (!isMemoryEnabled(context.env))
8
+ return memoryOff();
9
+ const saved = addMemoryEntry({
10
+ rootDir: context.rootDir,
11
+ env: context.env,
12
+ scope: args?.scope,
13
+ topic: args?.topic,
14
+ text: args?.text,
15
+ description: args?.description,
16
+ type: args?.kind,
17
+ body: args?.body,
18
+ basedOn: args?.basedOn,
19
+ });
20
+ if (!saved.ok) {
21
+ return { ok: false, error: saved.error, failureCategory: 'invalid_argument' };
22
+ }
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
+ };
61
+ }
62
+ export function recallNotes(context, args) {
63
+ if (!isMemoryEnabled(context.env))
64
+ return memoryOff();
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
+ });
78
+ return { ok: true, query: String(args?.query ?? ''), matches };
79
+ }
@@ -26,6 +26,7 @@ import { getJobBufferedOutput, getJobOutputPreview, hasRunningBackgroundJobs, ki
26
26
  import { clearTodos, listTodos, setTodoSession } from '../todo-list.js';
27
27
  import { setScratchSession } from '../scratch-dir.js';
28
28
  import { setImageStoreSession } from '../core/session-image-store.js';
29
+ import { runMemoryCommand } from '../memory/command.js';
29
30
  import { cancelActiveCommand } from '../executor.js';
30
31
  import { isTurnFailureMarker } from '../turn-failure-marker.js';
31
32
  import { clearCliAuthConfig, logoutFromServer, } from '../api/auth.js';
@@ -70,13 +71,21 @@ function sameTranscriptDraft(a, b) {
70
71
  a.filePath === b.filePath &&
71
72
  a.preformatted === b.preformatted);
72
73
  }
73
- 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 = []) {
74
81
  const responseBody = String(responseText ?? '').trim();
82
+ const note = memoryUpdatedNote(memoryTopics);
75
83
  const responseEntry = responseBody
76
84
  ? {
77
85
  body: responseBody,
78
86
  kind: 'assistant',
79
87
  title: 'Response',
88
+ ...(note ? { note } : {}),
80
89
  }
81
90
  : null;
82
91
  return [
@@ -750,6 +759,14 @@ export function buildWorkingToolEntry(event, label = event.call.name) {
750
759
  title: call.name === 'shell_job_kill' ? 'Kill job' : 'Job output',
751
760
  };
752
761
  }
762
+ if (call.name === 'recall') {
763
+ const found = Array.isArray(result?.matches) ? result.matches.length : 0;
764
+ return {
765
+ body: `${String(call.args?.query ?? '').trim()}${state(` · ${found} found`)}${error}`,
766
+ kind,
767
+ title: 'Searched memory',
768
+ };
769
+ }
753
770
  if (call.name === 'use_skill') {
754
771
  const name = String(result?.name ?? call.args?.name ?? '').trim().replace(/^\//, '');
755
772
  return {
@@ -838,6 +855,15 @@ export function buildTranscriptFromSessionHistory(history) {
838
855
  const entries = [];
839
856
  const pendingCalls = new Map();
840
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
+ };
841
867
  for (const entry of history) {
842
868
  if (!entry?.parts?.length)
843
869
  continue;
@@ -887,6 +913,12 @@ export function buildTranscriptFromSessionHistory(history) {
887
913
  if (!call && responseName) {
888
914
  call = findPendingToolCallByName(pendingCalls, responseName);
889
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
+ }
890
922
  if (!call || !isFileChangeTool(call.name))
891
923
  continue;
892
924
  const result = (functionResponse.response ?? {});
@@ -895,6 +927,7 @@ export function buildTranscriptFromSessionHistory(history) {
895
927
  entries.push(buildFileChangeEntry({ call, result }));
896
928
  }
897
929
  if (entry.role === 'user' && entry.kind === 'turnStart') {
930
+ settleTurnMemory();
898
931
  const text = displayUserTextFromHistoryEntry(entry);
899
932
  if (text) {
900
933
  entries.push({ body: text, kind: 'user', title: 'You' });
@@ -918,9 +951,13 @@ export function buildTranscriptFromSessionHistory(history) {
918
951
  });
919
952
  continue;
920
953
  }
921
- 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);
922
958
  }
923
959
  }
960
+ settleTurnMemory();
924
961
  return entries;
925
962
  }
926
963
  function createInitialTranscript() {
@@ -1496,6 +1533,7 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
1496
1533
  const blockedRows = new WeakMap();
1497
1534
  let newConversationInFlight = false;
1498
1535
  let todosTouchedThisTurn = false;
1536
+ let memoryTopicsThisTurn = [];
1499
1537
  const syncTodosState = () => {
1500
1538
  store.update((current) => ({ ...current, todos: listTodos() }));
1501
1539
  };
@@ -1644,7 +1682,8 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
1644
1682
  appendStaticEntry(entry);
1645
1683
  };
1646
1684
  const appendSettledTurnEntries = async (turnEntries, responseText, shouldContinue = () => true) => {
1647
- const entries = buildSettledTurnTranscriptEntries(turnEntries, responseText);
1685
+ const entries = buildSettledTurnTranscriptEntries(turnEntries, responseText, memoryTopicsThisTurn);
1686
+ memoryTopicsThisTurn = [];
1648
1687
  const responseEntry = entries.at(-1);
1649
1688
  if (!responseEntry ||
1650
1689
  responseEntry.kind !== 'assistant' ||
@@ -2761,6 +2800,14 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
2761
2800
  requestExit();
2762
2801
  return;
2763
2802
  }
2803
+ if (input === '/memory' || input.startsWith('/memory ')) {
2804
+ appendStaticEntry({
2805
+ body: runMemoryCommand(input.slice('/memory'.length), session.rootDir, session.env),
2806
+ kind: 'system',
2807
+ title: 'Memory',
2808
+ });
2809
+ return;
2810
+ }
2764
2811
  if (input === '/skills' || input.startsWith('/skills ')) {
2765
2812
  await runSkillsCommand(input.slice('/skills'.length).trim());
2766
2813
  return;
@@ -2998,6 +3045,7 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
2998
3045
  activeTurnAbort = turnAbort;
2999
3046
  lastTurnStartedAt = turnStartedAt;
3000
3047
  todosTouchedThisTurn = false;
3048
+ memoryTopicsThisTurn = [];
3001
3049
  if (!jobFollowUp)
3002
3050
  clearTodos();
3003
3051
  syncTodosState();
@@ -3276,6 +3324,12 @@ export async function runClientInteractive({ appendPromptHistory, authConfig, de
3276
3324
  return;
3277
3325
  }
3278
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
+ }
3279
3333
  if (isFileChangeTool(event.call.name)) {
3280
3334
  const entry = buildFileChangeEntry(event);
3281
3335
  store.appendWorkingTool(entry);
@@ -9,6 +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, show or delete saved topics, or turn memory off' },
12
13
  { command: '/jobs', description: 'Background jobs: pick to view output or kill' },
13
14
  {
14
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.2.2",
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.2.2",
49
- "@thegitai/tui-darwin-x64": "1.2.2",
50
- "@thegitai/tui-linux-arm64": "1.2.2",
51
- "@thegitai/tui-linux-x64": "1.2.2",
52
- "@thegitai/tui-win32-x64": "1.2.2",
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": {