aismemory 0.8.8 → 0.8.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (68) hide show
  1. package/README.md +38 -7
  2. package/dist/agent-key-mode.d.ts +26 -0
  3. package/dist/agent-key-mode.js +165 -26
  4. package/dist/agent-only-pass.d.ts +41 -0
  5. package/dist/agent-only-pass.js +539 -0
  6. package/dist/ais-http.d.ts +11 -0
  7. package/dist/ais-http.js +31 -17
  8. package/dist/cli/hooks.d.ts +35 -5
  9. package/dist/cli/hooks.js +280 -66
  10. package/dist/cli/install.d.ts +8 -0
  11. package/dist/cli/install.js +15 -0
  12. package/dist/cli/orientation-load.d.ts +18 -0
  13. package/dist/cli/orientation-load.js +50 -0
  14. package/dist/cli/read-claude-memory-tree.d.ts +37 -0
  15. package/dist/cli/read-claude-memory-tree.js +247 -2
  16. package/dist/cli/setup-core.js +7 -3
  17. package/dist/cli/slack.d.ts +2 -0
  18. package/dist/cli/slack.js +263 -0
  19. package/dist/cli/sync-memory.js +13 -5
  20. package/dist/cli-info.d.ts +1 -0
  21. package/dist/cli-info.js +6 -0
  22. package/dist/decision-card.d.ts +42 -0
  23. package/dist/decision-card.js +50 -0
  24. package/dist/decision-ledger.d.ts +24 -0
  25. package/dist/decision-ledger.js +59 -0
  26. package/dist/decision-receipt.d.ts +33 -0
  27. package/dist/decision-receipt.js +72 -0
  28. package/dist/device-poll.d.ts +16 -7
  29. package/dist/device-poll.js +31 -3
  30. package/dist/handoff-doc.d.ts +9 -0
  31. package/dist/handoff-doc.js +53 -0
  32. package/dist/inbox-client.js +33 -26
  33. package/dist/index.js +298 -71
  34. package/dist/mcp/tools.d.ts +5 -0
  35. package/dist/mcp/tools.js +121 -31
  36. package/dist/operating-layer-read.d.ts +38 -0
  37. package/dist/operating-layer-read.js +164 -0
  38. package/dist/pending-device-flow.d.ts +2 -0
  39. package/dist/pending-device-flow.js +1 -0
  40. package/dist/pipeline/bulk-store.d.ts +4 -3
  41. package/dist/pipeline/bulk-store.js +45 -8
  42. package/dist/pipeline/ingestion.d.ts +1 -0
  43. package/dist/pipeline/ingestion.js +6 -1
  44. package/dist/pipeline/types.d.ts +4 -0
  45. package/dist/recall-warning.d.ts +14 -0
  46. package/dist/recall-warning.js +36 -0
  47. package/dist/request-timeout.d.ts +27 -2
  48. package/dist/request-timeout.js +92 -2
  49. package/dist/run-pass-mode.js +34 -16
  50. package/dist/session-identity.js +3 -1
  51. package/dist/session-start.d.ts +13 -3
  52. package/dist/session-start.js +53 -10
  53. package/dist/skill-fetch.d.ts +30 -0
  54. package/dist/skill-fetch.js +88 -0
  55. package/dist/slack-tools.d.ts +44 -0
  56. package/dist/slack-tools.js +156 -0
  57. package/dist/sources/local-claude.js +16 -2
  58. package/dist/sources/types.d.ts +2 -0
  59. package/dist/startup-identity.d.ts +4 -0
  60. package/dist/startup-identity.js +2 -0
  61. package/dist/tool-args.d.ts +12 -1
  62. package/dist/tool-args.js +15 -0
  63. package/dist/tool-scope-filter.d.ts +29 -0
  64. package/dist/tool-scope-filter.js +123 -0
  65. package/dist/version-check.d.ts +30 -3
  66. package/dist/version-check.js +59 -4
  67. package/dist/workspace-key-mode.js +36 -22
  68. package/package.json +4 -3
@@ -1,6 +1,9 @@
1
- import { readFileSync, readdirSync, statSync } from 'node:fs';
2
- import { join } from 'node:path';
1
+ import { lstatSync, readFileSync, readdirSync, realpathSync, statSync } from 'node:fs';
2
+ import { isAbsolute, join, relative, sep } from 'node:path';
3
3
  /**
4
+ * Unscoped walk of every project's memory/. Sync must use
5
+ * `loadScopedClaudeMemory` instead. This remains for the walker unit test.
6
+ *
4
7
  * Walks ~/.claude/projects/<project>/memory/ subtrees only. Project dirs
5
8
  * without a memory/ subdir are skipped. Anything outside a memory/ subdir
6
9
  * (handoffs, scratch notes, etc.) is NOT read.
@@ -62,4 +65,246 @@ export function readClaudeMemoryTree(projectsRoot) {
62
65
  }
63
66
  return { rootPath: projectsRoot, files };
64
67
  }
68
+ /** Thrown when the user declines the proposed scope under `--save-scope`. */
69
+ export const SCOPE_NOT_CONFIRMED_MESSAGE = 'Scope not confirmed; aborting. Rerun without --save-scope or with --scope <project key>.';
70
+ export class ProjectScopeError extends Error {
71
+ constructor(message) {
72
+ super(message);
73
+ this.name = 'ProjectScopeError';
74
+ }
75
+ }
76
+ /**
77
+ * Claude Code's project directory name: every character outside
78
+ * [A-Za-z0-9] in the canonical path becomes "-".
79
+ */
80
+ export function claudeProjectKey(canonicalPath) {
81
+ return canonicalPath.replace(/[^A-Za-z0-9]/g, '-');
82
+ }
83
+ export function formatScopedSourceListing(projectKey, files) {
84
+ const lines = [`source project: ${projectKey}`];
85
+ if (files.length === 0) {
86
+ lines.push('(no memory files)');
87
+ }
88
+ else {
89
+ for (const file of files)
90
+ lines.push(file.path);
91
+ }
92
+ return `${lines.join('\n')}\n`;
93
+ }
94
+ export function assertFilesMatchProject(files, projectKey) {
95
+ for (const file of files) {
96
+ if (file.projectKey !== projectKey) {
97
+ const found = file.projectKey ?? 'unknown';
98
+ throw new ProjectScopeError(`Refusing to import ${file.path}: source project ${found} does not match resolved project ${projectKey}. Read nothing.`);
99
+ }
100
+ }
101
+ }
102
+ /**
103
+ * Resolve one canonical project key, then read only that project's memory
104
+ * directory. The working directory matches only its sanitized canonical key.
105
+ * A `--scope` value must equal exactly one project key; a free-text label is
106
+ * refused. A symlink project directory, or a path that escapes the resolved
107
+ * memory directory, throws before any foreign memory file is returned.
108
+ */
109
+ export function loadScopedClaudeMemory(projectsRoot, selector) {
110
+ const projectsRootReal = canonicalProjectsRoot(projectsRoot);
111
+ const projectKey = resolveProjectKey(projectsRootReal, selector);
112
+ const result = readProjectMemory(projectsRootReal, projectKey);
113
+ assertFilesMatchProject(result.files, projectKey);
114
+ return {
115
+ projectKey,
116
+ result,
117
+ listing: formatScopedSourceListing(projectKey, result.files),
118
+ };
119
+ }
120
+ function isSinglePathSegment(name) {
121
+ return (name.length > 0 &&
122
+ name !== '.' &&
123
+ name !== '..' &&
124
+ !name.includes('/') &&
125
+ !name.includes('\\') &&
126
+ !name.includes('\0'));
127
+ }
128
+ function isInside(parentReal, childReal) {
129
+ const rel = relative(parentReal, childReal);
130
+ return rel === '' || (rel !== '..' && !rel.startsWith(`..${sep}`) && !isAbsolute(rel));
131
+ }
132
+ function canonicalProjectsRoot(projectsRoot) {
133
+ try {
134
+ const resolved = realpathSync(projectsRoot);
135
+ if (!statSync(resolved).isDirectory()) {
136
+ throw new ProjectScopeError(`Refusing to sync: Claude projects path is not a directory (${projectsRoot}). Read nothing.`);
137
+ }
138
+ return resolved;
139
+ }
140
+ catch (err) {
141
+ if (err instanceof ProjectScopeError)
142
+ throw err;
143
+ throw new ProjectScopeError(`Refusing to sync: Claude projects directory does not resolve (${projectsRoot}). Read nothing.`);
144
+ }
145
+ }
146
+ function listRealProjectKeys(projectsRootReal) {
147
+ let names;
148
+ try {
149
+ names = readdirSync(projectsRootReal);
150
+ }
151
+ catch {
152
+ throw new ProjectScopeError(`Refusing to sync: Claude projects directory is not readable (${projectsRootReal}). Read nothing.`);
153
+ }
154
+ const keys = [];
155
+ for (const name of names) {
156
+ if (!isSinglePathSegment(name))
157
+ continue;
158
+ const full = join(projectsRootReal, name);
159
+ let st;
160
+ try {
161
+ st = lstatSync(full);
162
+ }
163
+ catch {
164
+ continue;
165
+ }
166
+ if (st.isSymbolicLink() || !st.isDirectory())
167
+ continue;
168
+ let resolved;
169
+ try {
170
+ resolved = realpathSync(full);
171
+ }
172
+ catch {
173
+ continue;
174
+ }
175
+ if (resolved !== full)
176
+ continue;
177
+ keys.push(name);
178
+ }
179
+ return keys;
180
+ }
181
+ function resolveProjectKey(projectsRootReal, selector) {
182
+ const hasPath = selector.projectPath !== undefined;
183
+ const hasName = selector.namedScope !== undefined;
184
+ if (hasPath === hasName) {
185
+ throw new ProjectScopeError('Refusing to sync: provide exactly one of a working directory or a named scope. Read nothing.');
186
+ }
187
+ if (hasName) {
188
+ return resolveFromNamedScope(projectsRootReal, selector.namedScope ?? '');
189
+ }
190
+ return resolveFromProjectPath(projectsRootReal, selector.projectPath ?? '');
191
+ }
192
+ function resolveFromProjectPath(projectsRootReal, projectPath) {
193
+ let canonical;
194
+ try {
195
+ canonical = realpathSync(projectPath);
196
+ }
197
+ catch {
198
+ throw new ProjectScopeError(`Refusing to sync: project path does not resolve (${projectPath}). Read nothing.`);
199
+ }
200
+ const keys = listRealProjectKeys(projectsRootReal);
201
+ const sanitized = claudeProjectKey(canonical);
202
+ if (keys.includes(sanitized))
203
+ return sanitized;
204
+ throw new ProjectScopeError(`Refusing to sync: no Claude project directory named ${sanitized} for ${canonical}. Read nothing.`);
205
+ }
206
+ function matchesNamedScope(projectKey, namedScope) {
207
+ return projectKey === namedScope;
208
+ }
209
+ function resolveFromNamedScope(projectsRootReal, namedScope) {
210
+ if (namedScope.length === 0 ||
211
+ namedScope.includes('..') ||
212
+ namedScope.includes('/') ||
213
+ namedScope.includes('\\') ||
214
+ namedScope.includes('\0')) {
215
+ throw new ProjectScopeError(`Refusing to sync: named scope "${namedScope}" is not a single project name. Read nothing.`);
216
+ }
217
+ const matches = listRealProjectKeys(projectsRootReal).filter((key) => matchesNamedScope(key, namedScope));
218
+ if (matches.length !== 1) {
219
+ const listed = [...matches].sort().join(', ');
220
+ throw new ProjectScopeError(`Refusing to sync: named scope "${namedScope}" matches ${matches.length} Claude projects (${listed || 'none'}). Expected exactly one. Read nothing.`);
221
+ }
222
+ const only = matches[0];
223
+ if (only === undefined) {
224
+ throw new ProjectScopeError(`Refusing to sync: named scope "${namedScope}" matches 0 Claude projects (none). Expected exactly one. Read nothing.`);
225
+ }
226
+ return only;
227
+ }
228
+ function readProjectMemory(projectsRootReal, projectKey) {
229
+ if (!isSinglePathSegment(projectKey)) {
230
+ throw new ProjectScopeError(`Refusing to sync: project key "${projectKey}" is not a single directory name. Read nothing.`);
231
+ }
232
+ const projectDir = join(projectsRootReal, projectKey);
233
+ const relativeKey = relative(projectsRootReal, projectDir);
234
+ if (relativeKey !== projectKey) {
235
+ throw new ProjectScopeError(`Refusing to sync: project key "${projectKey}" escapes the projects root. Read nothing.`);
236
+ }
237
+ const memoryDir = join(projectDir, 'memory');
238
+ let memoryStat;
239
+ try {
240
+ memoryStat = lstatSync(memoryDir);
241
+ }
242
+ catch {
243
+ return { rootPath: projectsRootReal, projectKey, files: [] };
244
+ }
245
+ if (memoryStat.isSymbolicLink()) {
246
+ throw new ProjectScopeError(`Refusing to sync: ${projectKey}/memory is a symlink. Read nothing.`);
247
+ }
248
+ if (!memoryStat.isDirectory()) {
249
+ return { rootPath: projectsRootReal, projectKey, files: [] };
250
+ }
251
+ const memoryReal = realpathSync(memoryDir);
252
+ if (memoryReal !== memoryDir) {
253
+ throw new ProjectScopeError(`Refusing to sync: ${projectKey}/memory resolves outside the project. Read nothing.`);
254
+ }
255
+ const files = [];
256
+ const stack = [memoryDir];
257
+ while (stack.length > 0) {
258
+ const dir = stack.pop();
259
+ if (dir === undefined)
260
+ break;
261
+ let dirReal;
262
+ try {
263
+ dirReal = realpathSync(dir);
264
+ }
265
+ catch {
266
+ continue;
267
+ }
268
+ if (!isInside(memoryReal, dirReal))
269
+ continue;
270
+ let names;
271
+ try {
272
+ names = readdirSync(dir);
273
+ }
274
+ catch {
275
+ continue;
276
+ }
277
+ for (const name of names) {
278
+ if (!isSinglePathSegment(name))
279
+ continue;
280
+ const full = join(dir, name);
281
+ let st;
282
+ try {
283
+ st = lstatSync(full);
284
+ }
285
+ catch {
286
+ continue;
287
+ }
288
+ if (st.isSymbolicLink())
289
+ continue;
290
+ if (st.isDirectory()) {
291
+ stack.push(full);
292
+ continue;
293
+ }
294
+ if (!st.isFile() || !name.endsWith('.md'))
295
+ continue;
296
+ let fileReal;
297
+ try {
298
+ fileReal = realpathSync(full);
299
+ }
300
+ catch {
301
+ continue;
302
+ }
303
+ if (!isInside(memoryReal, fileReal))
304
+ continue;
305
+ files.push({ path: full, content: readFileSync(full, 'utf8'), projectKey });
306
+ }
307
+ }
308
+ return { rootPath: projectsRootReal, projectKey, files };
309
+ }
65
310
  //# sourceMappingURL=read-claude-memory-tree.js.map
@@ -12,7 +12,7 @@ import { credentialsFilePath } from '../oauth-credentials.js';
12
12
  import { loadRunPassConfig, RunPassConfigError } from '../run-pass-mode.js';
13
13
  import { loadSessionIdentity } from '../session-identity.js';
14
14
  import { loadWorkspaceKeyConfig, WorkspaceKeyConfigError } from '../workspace-key-mode.js';
15
- import { renderEntryInstructions } from './install.js';
15
+ import { renderEntryInstructions, renderRulesFirstLineBlock } from './install.js';
16
16
  import { backupFileOnce, HookFailure, inline, NO_CREDENTIAL_HINT, resolveHookClient, stripInvisibles, writeTextFileAtomic, } from './hooks.js';
17
17
  import { readPackageVersion } from '../version-check.js';
18
18
  export const SETUP_NEW_WARNING = 'This is new and has not been checked end to end on a fresh machine yet.';
@@ -1252,6 +1252,10 @@ function setupToolPresent(home, tool, toolchain) {
1252
1252
  return toolchain.codexMcpAdd;
1253
1253
  return false;
1254
1254
  }
1255
+ /** Codex and Cursor have no session-start hook, so their rules file asks for the RULES line (CORBOT-4612D028). */
1256
+ function withRulesFirstLine(entryInstructions, harness) {
1257
+ return `${entryInstructions.trimEnd()}\n\n${renderRulesFirstLineBlock(harness)}`;
1258
+ }
1255
1259
  export async function buildSetupPlan(opts) {
1256
1260
  const version = opts.packageVersion ?? readPackageVersion();
1257
1261
  const toolchain = opts.toolchain ?? { claudeOnPath: false, codexMcpAdd: false };
@@ -1377,7 +1381,7 @@ export async function buildSetupPlan(opts) {
1377
1381
  }
1378
1382
  else {
1379
1383
  const existingInstructions = readTextFile(instructionPath);
1380
- const next = planInstructionContent(existingInstructions, opts.agentId, entryInstructions, accountRules, opts.setDate, existingInstructions === null);
1384
+ const next = planInstructionContent(existingInstructions, opts.agentId, withRulesFirstLine(entryInstructions, 'cursor'), accountRules, opts.setDate, existingInstructions === null);
1381
1385
  instructionPlan = {
1382
1386
  path: instructionPath,
1383
1387
  status: fileChangeStatus(instructionPath, next),
@@ -1419,7 +1423,7 @@ export async function buildSetupPlan(opts) {
1419
1423
  }
1420
1424
  const instructionPath = codexInstructionPath(opts.home, opts.project);
1421
1425
  const existingInstructions = readTextFile(instructionPath);
1422
- const next = planInstructionContent(existingInstructions, opts.agentId, entryInstructions, accountRules, opts.setDate, false);
1426
+ const next = planInstructionContent(existingInstructions, opts.agentId, withRulesFirstLine(entryInstructions, 'codex'), accountRules, opts.setDate, false);
1423
1427
  instructionPlan = {
1424
1428
  path: instructionPath,
1425
1429
  status: fileChangeStatus(instructionPath, next),
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
@@ -0,0 +1,263 @@
1
+ #!/usr/bin/env node
2
+ import { randomUUID } from 'node:crypto';
3
+ import { mkdirSync, mkdtempSync, readdirSync, readFileSync, renameSync, rmdirSync, rmSync, statSync, writeFileSync } from 'node:fs';
4
+ import { homedir } from 'node:os';
5
+ import { basename, dirname, join } from 'node:path';
6
+ import { setTimeout as delay } from 'node:timers/promises';
7
+ import { parseArgs } from 'node:util';
8
+ import { z } from 'zod';
9
+ import { AgentApiKeyConfigError, loadAgentApiKeyConfig } from '../agent-key-mode.js';
10
+ import { DEFAULT_AIS_REQUEST_TIMEOUT_MS } from '../request-timeout.js';
11
+ import { retryAfterOf } from '../retry-after.js';
12
+ const timestamp = z.string().regex(/^\d{9,11}\.\d{6}$/);
13
+ const channelId = z.string().regex(/^[CG][A-Z0-9]{2,}$/);
14
+ const cursorStore = z.record(z.string(), timestamp);
15
+ const posted = z.object({ ok: z.literal(true), ts: timestamp });
16
+ const page = z.object({
17
+ ok: z.literal(true),
18
+ messages: z.array(z.object({ ts: timestamp })),
19
+ has_more: z.boolean(),
20
+ next_cursor: z.string().optional(),
21
+ });
22
+ const usage = 'Usage: aismemory-slack post --channel ID --text TEXT [--thread TS] or ' +
23
+ 'aismemory-slack read --channel ID [--since TS] [--thread TS] [--limit 1-200].';
24
+ class SlackCliError extends Error {
25
+ }
26
+ function slackBaseUrl(raw) {
27
+ if (!raw?.trim())
28
+ throw new SlackCliError('Set AIS_SLACK_URL to the Slack service URL.');
29
+ const invalid = new SlackCliError('AIS_SLACK_URL must be an HTTPS service URL or loopback HTTP URL.');
30
+ let url;
31
+ try {
32
+ url = new URL(raw);
33
+ }
34
+ catch {
35
+ throw invalid;
36
+ }
37
+ const loopback = ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname);
38
+ if ((url.protocol !== 'https:' && !(loopback && url.protocol === 'http:')) ||
39
+ url.username || url.password || url.search || url.hash) {
40
+ throw invalid;
41
+ }
42
+ return url.origin + url.pathname.replace(/\/$/, '');
43
+ }
44
+ async function slackRequest(url, key, body) {
45
+ const headers = new Headers({ 'x-agent-api-key': key });
46
+ if (body)
47
+ headers.set('Content-Type', 'application/json');
48
+ const response = await fetch(url, {
49
+ headers,
50
+ method: body ? 'POST' : 'GET',
51
+ body: body ? JSON.stringify(body) : undefined,
52
+ redirect: 'error',
53
+ signal: AbortSignal.timeout(DEFAULT_AIS_REQUEST_TIMEOUT_MS),
54
+ });
55
+ const payload = await response.json().catch(() => null);
56
+ if (response.ok)
57
+ return payload;
58
+ if (response.status === 401)
59
+ throw new SlackCliError('Slack rejected the agent key.');
60
+ if (response.status === 403 && typeof payload === 'object' && payload !== null &&
61
+ 'error' in payload && payload.error === 'unknown_channel_sharing') {
62
+ throw new SlackCliError('Slack could not verify channel sharing.');
63
+ }
64
+ if (response.status === 429) {
65
+ const seconds = retryAfterOf(response);
66
+ const wait = seconds !== null && Number.isFinite(seconds) ? ` Retry after ${seconds} seconds.` : '';
67
+ throw new SlackCliError(`Slack rate limit reached.${wait}`);
68
+ }
69
+ throw new SlackCliError(`Slack request failed (HTTP ${response.status}).`);
70
+ }
71
+ function loadCursors(file) {
72
+ try {
73
+ const data = JSON.parse(readFileSync(file, 'utf8'));
74
+ return cursorStore.parse(data);
75
+ }
76
+ catch (error) {
77
+ if (error instanceof Error && 'code' in error && error.code === 'ENOENT')
78
+ return {};
79
+ throw new SlackCliError('Could not read ~/.aismemory/slack-cursor.json.');
80
+ }
81
+ }
82
+ function newerThan(candidate, current) {
83
+ return current === undefined || BigInt(candidate.replace('.', '')) > BigInt(current.replace('.', ''));
84
+ }
85
+ function releaseCursorLock(lock, owner) {
86
+ try {
87
+ if (owner !== undefined)
88
+ rmSync(join(lock, owner), { force: true });
89
+ rmdirSync(lock);
90
+ }
91
+ catch {
92
+ // Another process may already have released or replaced the lock.
93
+ }
94
+ }
95
+ async function acquireCursorLock(lock) {
96
+ const staleAfterMs = 30_000;
97
+ mkdirSync(dirname(lock), { recursive: true, mode: 0o700 });
98
+ const staging = mkdtempSync(`${lock}-`);
99
+ const owner = basename(staging);
100
+ try {
101
+ // Publish a nonempty directory atomically. A stale-lock cleanup can only
102
+ // remove its observed owner, and rmdir cannot remove a new owner's directory.
103
+ writeFileSync(join(staging, owner), '', { mode: 0o600 });
104
+ for (let attempt = 0; attempt < 20; attempt += 1) {
105
+ const current = statSync(lock, { throwIfNoEntry: false });
106
+ const stale = current !== undefined && Date.now() - current.mtimeMs >= staleAfterMs;
107
+ if (stale) {
108
+ let owners;
109
+ try {
110
+ owners = readdirSync(lock);
111
+ }
112
+ catch (error) {
113
+ if (!(error instanceof Error && 'code' in error && error.code === 'ENOENT'))
114
+ throw error;
115
+ continue;
116
+ }
117
+ const observed = statSync(lock, { throwIfNoEntry: false });
118
+ if (observed?.ino === current.ino && observed.mtimeMs === current.mtimeMs) {
119
+ if (owners.length === 0)
120
+ releaseCursorLock(lock);
121
+ else if (owners.length === 1 && owners[0]?.startsWith(basename(lock) + '-')) {
122
+ releaseCursorLock(lock, owners[0]);
123
+ }
124
+ }
125
+ }
126
+ if (!current || stale) {
127
+ try {
128
+ renameSync(staging, lock);
129
+ return owner;
130
+ }
131
+ catch (error) {
132
+ if (!(error instanceof Error && 'code' in error &&
133
+ (error.code === 'EEXIST' || error.code === 'ENOTEMPTY')))
134
+ throw error;
135
+ }
136
+ }
137
+ if (attempt < 19)
138
+ await delay(50);
139
+ }
140
+ throw new SlackCliError('Could not lock ~/.aismemory/slack-cursor.json.');
141
+ }
142
+ finally {
143
+ rmSync(staging, { recursive: true, force: true });
144
+ }
145
+ }
146
+ async function saveSlackCursor(file, scope, latest) {
147
+ const lock = `${file}.lock`;
148
+ const owner = await acquireCursorLock(lock).catch(() => {
149
+ throw new SlackCliError('Could not lock ~/.aismemory/slack-cursor.json.');
150
+ });
151
+ const temporary = `${file}.${randomUUID()}.tmp`;
152
+ try {
153
+ // Merge under the lock so concurrent reads cannot erase another checkpoint.
154
+ const cursors = loadCursors(file);
155
+ if (newerThan(latest, cursors[scope]))
156
+ cursors[scope] = latest;
157
+ writeFileSync(temporary, JSON.stringify(cursors) + '\n', { mode: 0o600, flag: 'wx' });
158
+ renameSync(temporary, file);
159
+ }
160
+ finally {
161
+ try {
162
+ rmSync(temporary, { force: true });
163
+ }
164
+ catch {
165
+ // Preserve the checkpoint write error if temporary-file cleanup fails.
166
+ }
167
+ releaseCursorLock(lock, owner);
168
+ }
169
+ }
170
+ async function readSlack(url, key, channel, query) {
171
+ const cursorFile = join(homedir(), '.aismemory', 'slack-cursor.json');
172
+ const thread = query.get('thread_ts');
173
+ // A thread scan cannot establish how far channel history was read.
174
+ const scope = thread === null ? channel : `${channel}:${thread}`;
175
+ const saved = loadCursors(cursorFile)[scope];
176
+ if (!query.has('since') && saved !== undefined)
177
+ query.set('since', saved);
178
+ let latest;
179
+ let count = 0;
180
+ const seenCursors = new Set();
181
+ for (;;) {
182
+ const result = page.safeParse(await slackRequest(`${url}/agent/channel/${channel}/messages?${query}`, key));
183
+ if (!result.success)
184
+ throw new SlackCliError('Slack returned an invalid read response.');
185
+ for (const { ts } of result.data.messages) {
186
+ if (newerThan(ts, latest))
187
+ latest = ts;
188
+ count += 1;
189
+ }
190
+ if (!result.data.has_more)
191
+ break;
192
+ const next = result.data.next_cursor;
193
+ if (!next || seenCursors.has(next))
194
+ throw new SlackCliError('Slack did not provide a usable next cursor.');
195
+ seenCursors.add(next);
196
+ query.set('cursor', next);
197
+ }
198
+ if (latest !== undefined)
199
+ await saveSlackCursor(cursorFile, scope, latest);
200
+ process.stdout.write(`Read ${count} messages\n`);
201
+ }
202
+ async function runSlackCli(args) {
203
+ const [command, ...flags] = args;
204
+ if (command !== 'post' && command !== 'read')
205
+ throw new SlackCliError(usage);
206
+ const url = slackBaseUrl(process.env.AIS_SLACK_URL);
207
+ const values = parseArgs({
208
+ args: flags,
209
+ options: {
210
+ channel: { type: 'string' },
211
+ thread: { type: 'string' },
212
+ text: { type: 'string' },
213
+ since: { type: 'string' },
214
+ limit: { type: 'string' },
215
+ },
216
+ }).values;
217
+ const channel = channelId.safeParse(values.channel);
218
+ const { thread, since, limit, text } = values;
219
+ if ((command === 'post' ? since !== undefined || limit !== undefined : text !== undefined) ||
220
+ !channel.success || (thread !== undefined && !timestamp.safeParse(thread).success) ||
221
+ (since !== undefined && !timestamp.safeParse(since).success) ||
222
+ (limit !== undefined && (!/^\d{1,3}$/.test(limit) ||
223
+ Number(limit) < 1 || Number(limit) > 200))) {
224
+ throw new SlackCliError(usage);
225
+ }
226
+ const config = loadAgentApiKeyConfig();
227
+ if (!config)
228
+ throw new SlackCliError('Set AIS_API_KEY (or AIS_AGENT_API_KEY) and AIS_AGENT_ID.');
229
+ if (!z.guid().safeParse(config.agentId).success)
230
+ throw new SlackCliError('AIS_AGENT_ID must be a UUID.');
231
+ if (command === 'post') {
232
+ if (!text?.trim() || text.length > 3000)
233
+ throw new SlackCliError(usage);
234
+ const result = posted.safeParse(await slackRequest(`${url}/agent/post`, config.apiKey, {
235
+ agent_id: config.agentId, channel: channel.data, text, thread_ts: thread,
236
+ }));
237
+ if (!result.success)
238
+ throw new SlackCliError('Slack returned an invalid post response.');
239
+ process.stdout.write(`Posted ${result.data.ts}\n`);
240
+ return;
241
+ }
242
+ const query = new URLSearchParams({ agent_id: config.agentId });
243
+ if (since !== undefined)
244
+ query.set('since', since);
245
+ if (thread !== undefined)
246
+ query.set('thread_ts', thread);
247
+ if (limit !== undefined)
248
+ query.set('limit', limit);
249
+ await readSlack(url, config.apiKey, channel.data, query);
250
+ }
251
+ runSlackCli(process.argv.slice(2)).catch((error) => {
252
+ // Parser, fetch and filesystem errors can include raw user inputs.
253
+ let message = 'Slack command failed.';
254
+ if (error instanceof SlackCliError)
255
+ message = error.message;
256
+ else if (error instanceof AgentApiKeyConfigError)
257
+ message = 'Check AIS_API_KEY (or AIS_AGENT_API_KEY) and AIS_AGENT_ID.';
258
+ else if (error instanceof Error && 'code' in error && String(error.code).startsWith('ERR_PARSE_ARGS_'))
259
+ message = usage;
260
+ process.stderr.write(`${message}\n`);
261
+ process.exitCode = 1;
262
+ });
263
+ //# sourceMappingURL=slack.js.map
@@ -12,7 +12,7 @@ import { TrustLedger } from '../trust-ledger.js';
12
12
  import { LocalMirror } from '../local-mirror.js';
13
13
  import { interactiveReview, bulkSelectAll } from '../review/cli-review.js';
14
14
  import { resolveScope } from '../pipeline/scope-resolver.js';
15
- import { readClaudeMemoryTree } from './read-claude-memory-tree.js';
15
+ import { SCOPE_NOT_CONFIRMED_MESSAGE, assertFilesMatchProject, loadScopedClaudeMemory, } from './read-claude-memory-tree.js';
16
16
  function parseArgs(argv) {
17
17
  const args = {
18
18
  source: 'claude-local',
@@ -59,7 +59,10 @@ async function main() {
59
59
  const ledger = new TrustLedger(home);
60
60
  const mirror = new LocalMirror(home, config.retentionDays);
61
61
  const claudeRoot = join(home, '.claude', 'projects');
62
- const rawSourceData = readClaudeMemoryTree(claudeRoot);
62
+ const scoped = loadScopedClaudeMemory(claudeRoot, args.scope !== undefined ? { namedScope: args.scope } : { projectPath: resolve(process.cwd()) });
63
+ assertFilesMatchProject(scoped.result.files, scoped.projectKey);
64
+ const rawSourceData = scoped.result;
65
+ process.stdout.write(scoped.listing);
63
66
  const projectPath = resolve(process.cwd());
64
67
  const scope = args.scope
65
68
  ? { kind: 'user-named', label: args.scope }
@@ -77,7 +80,7 @@ async function main() {
77
80
  .trim()
78
81
  .toLowerCase();
79
82
  if (!(answer === 'y' || answer === 'yes')) {
80
- throw new Error('Scope not confirmed; aborting. Rerun without --save-scope or with --scope LABEL.');
83
+ throw new Error(SCOPE_NOT_CONFIRMED_MESSAGE);
81
84
  }
82
85
  return p;
83
86
  }
@@ -131,10 +134,15 @@ async function main() {
131
134
  review,
132
135
  });
133
136
  process.stdout.write(`\n=== Sync complete ===\n`);
134
- process.stdout.write(`imported: ${result.imported}\n`);
137
+ process.stdout.write(`received: ${result.received}\n`);
138
+ process.stdout.write(`stored: ${result.imported}\n`);
139
+ process.stdout.write(`already stored: ${result.deduplicated}\n`);
140
+ process.stdout.write(`rejected: ${result.failed.length}\n`);
141
+ for (const { index, error } of result.failed) {
142
+ process.stdout.write(` - [${index}] ${error}\n`);
143
+ }
135
144
  process.stdout.write(`skippedExactDupes: ${result.skippedExactDupes}\n`);
136
145
  process.stdout.write(`skippedByUser: ${result.skippedByUser}\n`);
137
- process.stdout.write(`failed: ${result.failed.length}\n`);
138
146
  if (result.warnings.length > 0) {
139
147
  process.stdout.write(`\nwarnings:\n`);
140
148
  for (const w of result.warnings)
@@ -10,6 +10,7 @@
10
10
  */
11
11
  export declare const HUMAN_HOWTO_TEXT: string;
12
12
  export declare const USAGE_TEXT: string;
13
+ export declare const BOND_USAGE_LINE = "Usage: aismemory bond\n";
13
14
  /**
14
15
  * Returns the text to print for a help or version request, or null when the
15
16
  * arguments are not one. Only the first argument counts, so subcommand flags
package/dist/cli-info.js CHANGED
@@ -37,6 +37,8 @@ export const USAGE_TEXT = [
37
37
  '',
38
38
  'Usage:',
39
39
  ' aismemory Start the MCP server on stdio',
40
+ ' aismemory bond Print the bonding link and exit',
41
+ ' aismemory bond --agent-only Wait for approval and save a computer pass',
40
42
  ' aismemory install --identity <agent-id> Write a pinned MCP config for one agent\'s session',
41
43
  ' aismemory hooks install Add the session-start and pre-compact hook to Claude Code',
42
44
  ' aismemory enable-key-auth Enroll a device key for silent sign-in',
@@ -61,6 +63,7 @@ export const USAGE_TEXT = [
61
63
  ' Open it and press Bond.',
62
64
  '',
63
65
  ].join('\n');
66
+ export const BOND_USAGE_LINE = 'Usage: aismemory bond\n';
64
67
  /**
65
68
  * Returns the text to print for a help or version request, or null when the
66
69
  * arguments are not one. Only the first argument counts, so subcommand flags
@@ -72,6 +75,9 @@ export function resolveInfoRequest(args, version) {
72
75
  return USAGE_TEXT;
73
76
  if (first === '--version' || first === '-v')
74
77
  return `${version}\n`;
78
+ if (first === 'bond' && args.length === 2 && (args[1] === '--help' || args[1] === '-h')) {
79
+ return `${BOND_USAGE_LINE}\nPrint the bonding link and exit.\nUse --agent-only to wait for approval and save a computer pass.\n`;
80
+ }
75
81
  return null;
76
82
  }
77
83
  //# sourceMappingURL=cli-info.js.map