dsh-memory-bond 0.0.0-stage → 1.0.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.
Files changed (126) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/LICENSE +21 -0
  3. package/README.md +181 -2
  4. package/README.zh-CN.md +180 -0
  5. package/SECURITY.md +29 -0
  6. package/client/memory-icon.svg +21 -0
  7. package/cordis.patch.yml +3 -0
  8. package/dist/audit.js +286 -0
  9. package/dist/automatic.js +16 -0
  10. package/dist/cache.js +40 -0
  11. package/dist/client.js +2035 -0
  12. package/dist/command-scope.js +123 -0
  13. package/dist/commands.js +156 -0
  14. package/dist/consolidation-store.js +357 -0
  15. package/dist/consolidation.js +182 -0
  16. package/dist/domain.js +245 -0
  17. package/dist/encoder.js +138 -0
  18. package/dist/export-files.js +161 -0
  19. package/dist/file-import-store.js +120 -0
  20. package/dist/file-import.js +265 -0
  21. package/dist/foreground-attempts.js +91 -0
  22. package/dist/guidance.js +242 -0
  23. package/dist/host.js +19 -0
  24. package/dist/index-policy.js +191 -0
  25. package/dist/index.js +349 -0
  26. package/dist/knowledge-hooks.js +398 -0
  27. package/dist/knowledge.js +359 -0
  28. package/dist/maintenance-episodes.js +73 -0
  29. package/dist/maintenance-import.js +92 -0
  30. package/dist/maintenance-store.js +738 -0
  31. package/dist/maintenance.js +376 -0
  32. package/dist/model-review.js +16 -0
  33. package/dist/personal.js +60 -0
  34. package/dist/policy.js +382 -0
  35. package/dist/prompt-copy.js +93 -0
  36. package/dist/proposal-receipts.js +70 -0
  37. package/dist/proposal-review.js +656 -0
  38. package/dist/propose-contract.js +38 -0
  39. package/dist/question-answers.js +176 -0
  40. package/dist/retrieval.js +126 -0
  41. package/dist/scope-narrowing.js +49 -0
  42. package/dist/search-index.js +164 -0
  43. package/dist/search-words.js +5 -0
  44. package/dist/semantic.js +157 -0
  45. package/dist/service.js +1473 -0
  46. package/dist/sharing.js +289 -0
  47. package/dist/sources.js +149 -0
  48. package/dist/store.js +1578 -0
  49. package/dist/tool-experience.js +87 -0
  50. package/dist/turn-review-store.js +159 -0
  51. package/dist/turn-review.js +459 -0
  52. package/dist/ui.js +346 -0
  53. package/dist/vector-index.js +232 -0
  54. package/docs/architecture.zh-CN.md +52 -0
  55. package/docs/benchmark.zh-CN.md +60 -0
  56. package/docs/benchmarks/repository-tasks.json +5355 -0
  57. package/docs/images/bond-memory-principle-en.svg +644 -0
  58. package/docs/images/bond-memory-principle-zh.svg +644 -0
  59. package/docs/images/bond-memory-principle.drawio +644 -0
  60. package/docs/images/memory-settings-en.png +0 -0
  61. package/docs/images/memory-settings-zh.png +0 -0
  62. package/docs/images/memory-turn-recalled-en.png +0 -0
  63. package/docs/images/memory-turn-recalled-zh.png +0 -0
  64. package/docs/images/memory-turn-saved-en.png +0 -0
  65. package/docs/images/memory-turn-saved-zh.png +0 -0
  66. package/docs/media/memory-bond-name-en.gif +0 -0
  67. package/docs/media/memory-bond-name-en.mp4 +0 -0
  68. package/docs/media/memory-bond-name-zh.gif +0 -0
  69. package/docs/media/memory-bond-name-zh.mp4 +0 -0
  70. package/locale/detail.en.md +13 -0
  71. package/locale/detail.zh.md +13 -0
  72. package/locale/en.json +345 -0
  73. package/locale/zh.json +345 -0
  74. package/native/embeddings/NOTICE.md +12 -0
  75. package/package.json +117 -4
  76. package/scripts/benchmark-bond.mjs +72 -0
  77. package/scripts/benchmark-conditions.mjs +144 -0
  78. package/scripts/benchmark-example.mjs +37 -0
  79. package/scripts/benchmark-scale.mjs +119 -0
  80. package/scripts/benchmark-scenarios.mjs +57 -0
  81. package/scripts/benchmark-tasks.mjs +244 -0
  82. package/src/audit.ts +286 -0
  83. package/src/automatic.ts +21 -0
  84. package/src/cache.ts +38 -0
  85. package/src/command-scope.ts +125 -0
  86. package/src/commands.ts +159 -0
  87. package/src/consolidation-store.ts +350 -0
  88. package/src/consolidation.ts +176 -0
  89. package/src/domain.ts +254 -0
  90. package/src/encoder.ts +142 -0
  91. package/src/export-files.ts +178 -0
  92. package/src/file-import-store.ts +139 -0
  93. package/src/file-import.ts +256 -0
  94. package/src/foreground-attempts.ts +97 -0
  95. package/src/guidance.ts +265 -0
  96. package/src/host.ts +119 -0
  97. package/src/index-policy.ts +231 -0
  98. package/src/index.ts +333 -0
  99. package/src/knowledge-hooks.ts +456 -0
  100. package/src/knowledge.ts +432 -0
  101. package/src/maintenance-episodes.ts +76 -0
  102. package/src/maintenance-import.ts +107 -0
  103. package/src/maintenance-store.ts +868 -0
  104. package/src/maintenance.ts +380 -0
  105. package/src/model-review.ts +27 -0
  106. package/src/personal.ts +68 -0
  107. package/src/policy.ts +508 -0
  108. package/src/prompt-copy.ts +99 -0
  109. package/src/proposal-receipts.ts +59 -0
  110. package/src/proposal-review.ts +614 -0
  111. package/src/propose-contract.ts +39 -0
  112. package/src/question-answers.ts +181 -0
  113. package/src/retrieval.ts +133 -0
  114. package/src/scope-narrowing.ts +58 -0
  115. package/src/search-index.ts +177 -0
  116. package/src/search-words.ts +6 -0
  117. package/src/semantic.ts +178 -0
  118. package/src/service.ts +1488 -0
  119. package/src/sharing.ts +349 -0
  120. package/src/sources.ts +150 -0
  121. package/src/store.ts +1829 -0
  122. package/src/tool-experience.ts +93 -0
  123. package/src/turn-review-store.ts +158 -0
  124. package/src/turn-review.ts +418 -0
  125. package/src/ui.ts +385 -0
  126. package/src/vector-index.ts +228 -0
@@ -0,0 +1,161 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { closeSync, constants, existsSync, fstatSync, fsyncSync, linkSync, lstatSync, mkdirSync, openSync, readFileSync, renameSync, statSync, unlinkSync, writeFileSync, } from 'node:fs';
3
+ import { tmpdir } from 'node:os';
4
+ import { basename, dirname, join } from 'node:path';
5
+ import { DatabaseSync } from 'node:sqlite';
6
+ import { digest } from "./domain.js";
7
+ import { StoreError } from "./store.js";
8
+ export const snapshotHash = (s) => digest(JSON.stringify(s));
9
+ const missing = (error) => error?.code === 'ENOENT';
10
+ function unlink(path) {
11
+ try {
12
+ unlinkSync(path);
13
+ }
14
+ catch (error) {
15
+ if (!missing(error))
16
+ throw error;
17
+ }
18
+ }
19
+ function create(path, text, mode) {
20
+ const fd = openSync(path, 'wx', mode);
21
+ try {
22
+ writeFileSync(fd, text);
23
+ fsyncSync(fd);
24
+ }
25
+ finally {
26
+ closeSync(fd);
27
+ }
28
+ }
29
+ function hashFile(path) {
30
+ const fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
31
+ try {
32
+ const stat = fstatSync(fd);
33
+ if (!stat.isFile() || stat.size > 2_000_000)
34
+ return undefined;
35
+ return snapshotHash(readFileSync(fd, 'utf8'));
36
+ }
37
+ finally {
38
+ closeSync(fd);
39
+ }
40
+ }
41
+ function identity(path) {
42
+ try {
43
+ const s = lstatSync(path, { bigint: true });
44
+ return String(s.dev) + '/' + s.ino;
45
+ }
46
+ catch (error) {
47
+ if (!missing(error))
48
+ throw error;
49
+ }
50
+ }
51
+ function siblings(target, nonce) {
52
+ const base = join(dirname(target), '.' + basename(target) + '.dsh-export-' + nonce);
53
+ return { next: base + '.next', previous: base + '.previous' };
54
+ }
55
+ function recover(target, journal) {
56
+ // Preparing the intent precedes all changes to the checkout. Only a complete atomic record counts.
57
+ unlink(journal + '.prepare');
58
+ if (!existsSync(journal))
59
+ return;
60
+ const record = JSON.parse(readFileSync(journal, 'utf8'));
61
+ if (!/^[a-f0-9-]{36}$/u.test(record.nonce) || !/^[a-f0-9]{64}$/u.test(record.before))
62
+ throw new StoreError('invalid_export_journal');
63
+ const { next, previous } = siblings(target, record.nonce);
64
+ let preserved = false;
65
+ if (identity(previous)) {
66
+ if (!identity(target)) {
67
+ try {
68
+ linkSync(previous, target);
69
+ }
70
+ catch (error) {
71
+ if (error.code !== 'EEXIST')
72
+ throw error;
73
+ }
74
+ }
75
+ // Editors may replace a path, or keep writing the inode they had open. Preserve both versions on divergence.
76
+ if (identity(previous) === identity(target) || hashFile(previous) === record.before)
77
+ unlink(previous);
78
+ else
79
+ preserved = true;
80
+ }
81
+ unlink(next);
82
+ unlink(journal);
83
+ if (preserved)
84
+ throw new StoreError('export_conflict', '并发修改已保留在 ' + basename(previous) + ',当前目标文件也已保留。');
85
+ }
86
+ /** A SQLite writer lock is released by the kernel on process exit, without a racy PID/age-based unlock. */
87
+ export function withExportTarget(path, work, authorize) {
88
+ // macOS and Linux can run separate DSH profiles with separate HOME and TMPDIR against the same checkout.
89
+ const folder = process.getuid
90
+ ? join('/tmp', 'dsh-export-' + process.getuid())
91
+ : join(tmpdir(), 'dsh-project-memory-exports');
92
+ try {
93
+ mkdirSync(folder, { mode: 0o700 });
94
+ }
95
+ catch (error) {
96
+ if (error.code !== 'EEXIST')
97
+ throw error;
98
+ }
99
+ const owner = lstatSync(folder);
100
+ if (!owner.isDirectory() || (process.getuid && (owner.uid !== process.getuid() || !!(owner.mode & 0o077))))
101
+ throw new StoreError('invalid_export_lock');
102
+ const key = join(folder, digest(path));
103
+ const lock = new DatabaseSync(key + '.sqlite');
104
+ try {
105
+ lock.exec('PRAGMA busy_timeout=3000; BEGIN IMMEDIATE');
106
+ authorize?.();
107
+ recover(path, key + '.json');
108
+ return work(key + '.json');
109
+ }
110
+ finally {
111
+ lock.close();
112
+ }
113
+ }
114
+ export function publishExport(path, before, after, journal, append) {
115
+ if (before !== null && append && lstatSync(path).nlink === 1) {
116
+ // An append never replaces the bytes of an uncoordinated editor, even if it races the final comparison.
117
+ const fd = openSync(path, constants.O_RDWR | constants.O_APPEND | constants.O_NOFOLLOW | constants.O_NONBLOCK);
118
+ try {
119
+ const stat = fstatSync(fd, { bigint: true });
120
+ if (!stat.isFile() ||
121
+ stat.nlink !== 1n ||
122
+ stat.size > 2000000n ||
123
+ readFileSync(fd, 'utf8') !== before)
124
+ throw new StoreError('stale_preview');
125
+ writeFileSync(fd, after.slice(before.length));
126
+ fsyncSync(fd);
127
+ if (identity(path) !== String(stat.dev) + '/' + stat.ino || hashFile(path) !== snapshotHash(after))
128
+ throw new StoreError('stale_preview');
129
+ }
130
+ finally {
131
+ closeSync(fd);
132
+ }
133
+ return;
134
+ }
135
+ const record = { nonce: randomUUID(), before: snapshotHash(before), after: snapshotHash(after) };
136
+ const { next, previous } = siblings(path, record.nonce);
137
+ create(journal + '.prepare', JSON.stringify(record), 0o600);
138
+ renameSync(journal + '.prepare', journal);
139
+ try {
140
+ const mode = before === null ? 0o644 : statSync(path).mode & 0o777;
141
+ create(next, after, mode);
142
+ if (before !== null) {
143
+ // Claim exactly the version being replaced. A normal rename onto the destination could silently
144
+ // overwrite an editor's newer inode between checking its hash and publishing the replacement.
145
+ renameSync(path, previous);
146
+ if (hashFile(previous) !== record.before)
147
+ throw new StoreError('stale_preview');
148
+ }
149
+ try {
150
+ linkSync(next, path);
151
+ }
152
+ catch (error) {
153
+ if (error.code === 'EEXIST')
154
+ throw new StoreError('stale_preview');
155
+ throw error;
156
+ }
157
+ }
158
+ finally {
159
+ recover(path, journal);
160
+ }
161
+ }
@@ -0,0 +1,120 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { digest } from "./domain.js";
3
+ import { StoreError } from "./store.js";
4
+ export const fileImportSchema = `
5
+ CREATE TABLE file_import_batches (
6
+ domain TEXT NOT NULL, id TEXT NOT NULL, request TEXT NOT NULL, created INTEGER NOT NULL,
7
+ summary TEXT NOT NULL, undo TEXT, PRIMARY KEY(domain,id), UNIQUE(domain,request)
8
+ );
9
+ CREATE TABLE file_import_entries (
10
+ domain TEXT NOT NULL, batch TEXT NOT NULL, proposal TEXT NOT NULL, fingerprint TEXT NOT NULL,
11
+ PRIMARY KEY(domain,proposal), FOREIGN KEY(domain,batch) REFERENCES file_import_batches(domain,id),
12
+ FOREIGN KEY(domain,proposal) REFERENCES proposals(domain,id)
13
+ );
14
+ CREATE INDEX file_import_by_batch ON file_import_entries(domain,batch);
15
+ `;
16
+ export class FileImportStore {
17
+ db;
18
+ operations;
19
+ constructor(db, operations) {
20
+ this.db = db;
21
+ this.operations = operations;
22
+ }
23
+ list(domain) {
24
+ return this.db.prepare('SELECT id,created,summary,undo FROM file_import_batches WHERE domain=? ORDER BY created DESC,id')
25
+ .all(domain).map(row => ({ batchId: String(row.id), created: Number(row.created),
26
+ proposals: JSON.parse(String(row.summary)).proposals.length, undone: row.undo !== null }));
27
+ }
28
+ stage(domain, source, selection, files, skipped, entries, next, staleImports = new Set()) {
29
+ const request = digest(JSON.stringify([source.storeId, source.sessionId, source.seq, selection]));
30
+ return this.operations.tx(() => {
31
+ const previous = this.db.prepare('SELECT summary FROM file_import_batches WHERE domain=? AND request=?').get(domain, request);
32
+ if (previous)
33
+ return JSON.parse(String(previous.summary));
34
+ this.operations.expire(domain);
35
+ const batchId = 'import-' + randomUUID();
36
+ const result = { batchId, proposals: [], files, skipped, duplicates: 0, ...(next ? { next } : {}) };
37
+ const key = (r) => digest(JSON.stringify([r.action.normalize('NFC').trim(),
38
+ r.when.normalize('NFC').trim(), r.exceptions, [...r.paths].sort()]));
39
+ const current = this.operations.list(domain);
40
+ const stale = new Set(current.filter(rule => rule.source.fileImport).map(rule => rule.id + '@' + rule.rev)
41
+ .filter(ref => staleImports.has(ref)));
42
+ const existing = new Set(current.filter(rule => !stale.has(rule.id + '@' + rule.rev)).map(key));
43
+ const previousEntries = this.db.prepare(`SELECT i.fingerprint,p.id,p.source,p.state,p.receipt FROM file_import_entries i
44
+ JOIN file_import_batches b ON b.domain=i.domain AND b.id=i.batch
45
+ JOIN proposals p ON p.domain=i.domain AND p.id=i.proposal WHERE i.domain=? AND b.undo IS NULL`).all(domain);
46
+ for (const row of previousEntries) {
47
+ const file = JSON.parse(String(row.source)).fileImport;
48
+ if (row.state === 'pending' && file && files[file.path] && files[file.path] !== file.sha256) {
49
+ this.cancel(domain, String(row.id));
50
+ continue;
51
+ }
52
+ if (row.state === 'confirmed' && row.receipt) {
53
+ const refs = JSON.parse(String(row.receipt)).entries;
54
+ // An approved import whose repository guidance changed needs a fresh human review.
55
+ // The original batch continues to own only the original revision.
56
+ if (refs.length && refs.every(ref => stale.has(ref.id + '@' + ref.rev)))
57
+ continue;
58
+ }
59
+ if (row.state !== 'expired' && row.state !== 'cancelled')
60
+ existing.add(String(row.fingerprint));
61
+ }
62
+ this.db.prepare('INSERT INTO file_import_batches(domain,id,request,created,summary) VALUES(?,?,?,?,?)')
63
+ .run(domain, batchId, request, Date.now(), '{}');
64
+ for (const { file, item } of entries) {
65
+ const fingerprint = key(item);
66
+ if (existing.has(fingerprint)) {
67
+ result.duplicates++;
68
+ continue;
69
+ }
70
+ const p = this.operations.create(domain, source.sessionId, { ...source, origin: 'manual', fileImport: file }, item, batchId + '/' + fingerprint);
71
+ result.proposals.push(p.id);
72
+ this.db.prepare('INSERT INTO file_import_entries(domain,batch,proposal,fingerprint) VALUES(?,?,?,?)')
73
+ .run(domain, batchId, p.id, fingerprint);
74
+ existing.add(fingerprint);
75
+ }
76
+ this.db.prepare('UPDATE file_import_batches SET summary=? WHERE domain=? AND id=?')
77
+ .run(JSON.stringify(result), domain, batchId);
78
+ return result;
79
+ });
80
+ }
81
+ cancel(domain, id) {
82
+ this.db.prepare("UPDATE proposals SET state='cancelled',items='[]' WHERE domain=? AND id=? AND state='pending'").run(domain, id);
83
+ }
84
+ undo(domain, session, id) {
85
+ return this.operations.tx(() => {
86
+ const batch = this.db.prepare('SELECT undo FROM file_import_batches WHERE domain=? AND id=?').get(domain, id);
87
+ if (!batch)
88
+ throw new StoreError('not_found');
89
+ if (batch.undo)
90
+ return JSON.parse(String(batch.undo));
91
+ this.operations.expire(domain);
92
+ const rows = this.db.prepare(`SELECT p.id,p.state,p.receipt FROM file_import_entries i JOIN proposals p
93
+ ON p.domain=i.domain AND p.id=i.proposal WHERE i.domain=? AND i.batch=?`).all(domain, id);
94
+ const current = new Map(this.operations.list(domain).map(r => [r.id, r]));
95
+ const result = { batchId: id, cancelled: 0, revoked: 0, preserved: [] };
96
+ for (const row of rows) {
97
+ if (row.state === 'pending') {
98
+ this.cancel(domain, String(row.id));
99
+ result.cancelled++;
100
+ continue;
101
+ }
102
+ if (row.state !== 'confirmed' || !row.receipt)
103
+ continue;
104
+ for (const ref of JSON.parse(String(row.receipt)).entries) {
105
+ const head = current.get(ref.id);
106
+ if (!head)
107
+ continue;
108
+ if (head.rev !== ref.rev || head.pinned) {
109
+ result.preserved.push({ id: head.id, rev: head.rev });
110
+ continue;
111
+ }
112
+ this.operations.revoke(domain, head.id, head.rev, session);
113
+ result.revoked++;
114
+ }
115
+ }
116
+ this.db.prepare('UPDATE file_import_batches SET undo=? WHERE domain=? AND id=?').run(JSON.stringify(result), domain, id);
117
+ return result;
118
+ });
119
+ }
120
+ }
@@ -0,0 +1,265 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { closeSync, constants, fstatSync, lstatSync, openSync, readdirSync, readSync, realpathSync } from 'node:fs';
3
+ import { homedir } from 'node:os';
4
+ import { isAbsolute, join, resolve } from 'node:path';
5
+ import { skipsAutomaticMemory } from "./automatic.js";
6
+ const maxFileBytes = 128 * 1024;
7
+ const maxFiles = 32;
8
+ const maxEntries = 128;
9
+ function validTopic(name) {
10
+ return !name.startsWith('.') && !/[\\/\p{Cc}]/u.test(name) && name.endsWith('.md') && !skipsAutomaticMemory(name);
11
+ }
12
+ function memoryDirectory(root) {
13
+ const config = process.env.CLAUDE_CONFIG_DIR || join(homedir(), '.claude');
14
+ if (!isAbsolute(config))
15
+ throw new Error('unsafe_source');
16
+ // Claude Code keys its default per-project directory by the sanitized checkout path.
17
+ let project = root.replace(/[^a-zA-Z0-9]/g, '-');
18
+ if (project.length > 200) {
19
+ let hash = 0;
20
+ for (let i = 0; i < root.length; i++)
21
+ hash = (Math.imul(hash, 31) + root.charCodeAt(i)) | 0;
22
+ project = project.slice(0, 200) + '-' + Math.abs(hash).toString(36);
23
+ }
24
+ return join(config, 'projects', project, 'memory');
25
+ }
26
+ function dirExists(dir) {
27
+ try {
28
+ return realpathSync(dir) === resolve(dir) && lstatSync(dir).isDirectory();
29
+ }
30
+ catch {
31
+ return false;
32
+ }
33
+ }
34
+ function fileBytes(dir, name) {
35
+ if (realpathSync(dir) !== dir)
36
+ throw new Error('unsafe_source');
37
+ const path = join(dir, name);
38
+ const fd = openSync(path, constants.O_RDONLY | constants.O_NOFOLLOW | constants.O_NONBLOCK);
39
+ try {
40
+ const stat = fstatSync(fd);
41
+ if (!stat.isFile() || stat.size > maxFileBytes || realpathSync(path) !== path)
42
+ throw new Error('unsafe_source');
43
+ const linked = lstatSync(path);
44
+ if (stat.dev !== linked.dev || stat.ino !== linked.ino)
45
+ throw new Error('unsafe_source');
46
+ const buffer = Buffer.alloc(stat.size + 1);
47
+ let length = 0;
48
+ while (length < buffer.length) {
49
+ const n = readSync(fd, buffer, length, buffer.length - length, null);
50
+ if (!n)
51
+ break;
52
+ length += n;
53
+ }
54
+ if (length !== stat.size)
55
+ throw new Error('source_changed');
56
+ return buffer.subarray(0, length);
57
+ }
58
+ finally {
59
+ closeSync(fd);
60
+ }
61
+ }
62
+ function location(root, label) {
63
+ if (label === 'AGENTS.md' || label === 'CLAUDE.md')
64
+ return [root, label];
65
+ if (label === '.claude/CLAUDE.md') {
66
+ const dir = join(root, '.claude');
67
+ if (dirExists(dir) && lstatSync(join(dir, '.git'), { throwIfNoEntry: false }))
68
+ throw new Error('unsafe_source');
69
+ return [dir, 'CLAUDE.md'];
70
+ }
71
+ const prefix = 'claude-memory/';
72
+ const name = label.slice(prefix.length);
73
+ if (label.startsWith(prefix) && validTopic(name))
74
+ return [memoryDirectory(root), name];
75
+ throw new Error('unsafe_source');
76
+ }
77
+ const sha = (bytes) => createHash('sha256').update(bytes).digest('hex');
78
+ export function currentImport(root, file) {
79
+ try {
80
+ return sha(fileBytes(...location(root, file.path))) === file.sha256;
81
+ }
82
+ catch {
83
+ return false;
84
+ }
85
+ }
86
+ // Claude topic files often label the reason separately from the instruction to apply.
87
+ // Match the label itself so a rule that gives a reason or uses an inline link is retained.
88
+ function sectionLabel(text) {
89
+ return text.split(/[::]/u, 1)[0].trim().replace(/^[*_]+|[*_]+$/gu, '').trim();
90
+ }
91
+ const rationaleLabel = /^(?:why|rationale|reasons?|为什么|原因|理由)$/iu;
92
+ const actionLabels = ['how to apply', 'action', 'actions', '如何应用', '如何运用', '做法', '操作'];
93
+ const actionField = new RegExp('(?:^|\\s)[*_]*(?:' + actionLabels.join('|') + ')[*_]*\\s*[::]', 'iu');
94
+ const indexLabel = /^(?:index|contents|table of contents|目录|索引)$/iu;
95
+ export function isImportScaffolding(action, context, path) {
96
+ if (/^(?:!?\[[^\]]*\]\([^)]*\)\s*)+$/u.test(action) || /^@\S+$/u.test(action))
97
+ return true;
98
+ const label = sectionLabel(action);
99
+ // Previously imported paragraphs can contain both a reason and a "How to apply" field.
100
+ if (rationaleLabel.test(label))
101
+ return !actionField.test(action);
102
+ const sections = context.split(' / ').map(sectionLabel);
103
+ const enclosing = sections.findLast(s => rationaleLabel.test(s) || actionLabels.includes(s.toLowerCase()));
104
+ if (enclosing && rationaleLabel.test(enclosing) && !actionField.test(action))
105
+ return true;
106
+ const index = /(?:^|\/)(?:memory|index)\.md$/iu.test(path) || sections.some(s => indexLabel.test(s));
107
+ return index && /^\[[^\]]+\]\([^)]*\)\s*(?:[—–::]|-\s)/u.test(action);
108
+ }
109
+ // Markdown list items and paragraphs are the units a person approves. Keep wrapped lines together;
110
+ // fences, headings, frontmatter and link-only index entries are not standalone instructions.
111
+ function markdownEntries(body, path, sha256, add) {
112
+ const lines = body.split(/\r?\n/u);
113
+ let parts = [];
114
+ let line = 0, endLine = 0, skipped = 0;
115
+ let fence = '', front = false, comment = false;
116
+ const headings = [], ancestors = [];
117
+ let lead;
118
+ let indent;
119
+ let context = '', contextLines = [];
120
+ const flush = () => {
121
+ if (!parts.length)
122
+ return;
123
+ const action = parts.join(' ').trim();
124
+ parts = [];
125
+ if (action.length > 480 || context.length > 480 || skipsAutomaticMemory(context + ' ' + action) || /[\p{Cc}\u202a-\u202e\u2066-\u2069]/u.test(action) ||
126
+ isImportScaffolding(action, context, path)) {
127
+ skipped++;
128
+ return;
129
+ }
130
+ add({ action, context, file: { path, sha256, line, endLine, ...(contextLines.length ? { contextLines } : {}) } });
131
+ };
132
+ for (const [index, raw] of lines.entries()) {
133
+ const text = raw.trim();
134
+ if (index === 0 && text === '---') {
135
+ front = true;
136
+ continue;
137
+ }
138
+ if (front) {
139
+ if (/^(?:---|\.\.\.)$/u.test(text))
140
+ front = false;
141
+ continue;
142
+ }
143
+ if (fence) {
144
+ if (text.startsWith(fence) && /^(`+|~+)\s*$/u.test(text))
145
+ fence = '';
146
+ continue;
147
+ }
148
+ const start = /^(`{3,}|~{3,})/u.exec(text);
149
+ if (start) {
150
+ flush();
151
+ fence = start[1];
152
+ continue;
153
+ }
154
+ if (comment || text.includes('<!--')) {
155
+ flush();
156
+ comment = !text.includes('-->');
157
+ continue;
158
+ }
159
+ const heading = /^(#{1,6})\s+(.+)$/u.exec(text);
160
+ if (heading) {
161
+ flush();
162
+ headings.length = heading[1].length - 1;
163
+ headings.push({ text: heading[2].replace(/\s+#+$/u, ''), span: [index + 1, index + 1] });
164
+ ancestors.length = 0;
165
+ lead = undefined;
166
+ continue;
167
+ }
168
+ if (!text || /^(?:>|---+$|\*\*\*+$)/u.test(text)) {
169
+ flush();
170
+ continue;
171
+ }
172
+ const bullet = /^\s*(?:[-+*]|\d+[.)])\s+(?:\[[ xX]\]\s+)?(.*)$/u.exec(raw);
173
+ if (!bullet && parts.length && /[::]/u.test(text)) {
174
+ const label = sectionLabel(text);
175
+ if (rationaleLabel.test(label) || actionLabels.includes(label.toLowerCase()))
176
+ flush();
177
+ }
178
+ if (bullet) {
179
+ const depth = raw.length - raw.trimStart().length;
180
+ if (parts.length && indent === undefined && /[::][*_]*$/u.test(parts.at(-1))) {
181
+ lead = { text: parts.join(' '), span: [line, endLine] };
182
+ parts = [];
183
+ }
184
+ else if (parts.length && indent !== undefined && depth > indent) {
185
+ ancestors.push({ indent, text: parts.join(' '), span: [line, endLine] });
186
+ // The parent can be a qualifier that is incomplete on its own.
187
+ parts = [];
188
+ }
189
+ else
190
+ flush();
191
+ while (ancestors.length && ancestors.at(-1).indent >= depth)
192
+ ancestors.pop();
193
+ indent = depth;
194
+ }
195
+ else if (!parts.length) {
196
+ ancestors.length = 0;
197
+ indent = undefined;
198
+ lead = undefined;
199
+ }
200
+ if (!parts.length) {
201
+ line = index + 1;
202
+ const sections = [...headings, lead, ...ancestors].filter((section) => Boolean(section));
203
+ context = sections.map(section => section.text).join(' / ');
204
+ contextLines = sections.map(section => section.span);
205
+ }
206
+ endLine = index + 1;
207
+ parts.push(bullet ? bullet[1] : text);
208
+ }
209
+ flush();
210
+ return skipped;
211
+ }
212
+ export function scanImport(root, selection, fileIndex = 0, startLine = 1) {
213
+ const labels = [];
214
+ let skipped = 0;
215
+ if (selection === 'all' || selection === 'agents')
216
+ labels.push('AGENTS.md');
217
+ if (selection === 'all' || selection === 'claude')
218
+ labels.push('CLAUDE.md', '.claude/CLAUDE.md');
219
+ if (selection === 'all' || selection === 'claude-memory') {
220
+ const dir = memoryDirectory(root);
221
+ if (dirExists(dir)) {
222
+ try {
223
+ for (const name of readdirSync(dir).filter(validTopic).sort())
224
+ labels.push('claude-memory/' + name);
225
+ }
226
+ catch {
227
+ skipped++;
228
+ }
229
+ }
230
+ }
231
+ const entries = [], files = {};
232
+ let next;
233
+ for (let index = fileIndex; index < labels.length; index++) {
234
+ if (index - fileIndex >= maxFiles) {
235
+ next = index + ':1';
236
+ break;
237
+ }
238
+ const path = labels[index];
239
+ try {
240
+ const bytes = fileBytes(...location(root, path));
241
+ const body = new TextDecoder('utf-8', { fatal: true }).decode(bytes);
242
+ if (body.includes('\0') || /-----BEGIN [^\n]*PRIVATE KEY-----/iu.test(body)) {
243
+ skipped++;
244
+ continue;
245
+ }
246
+ const hash = sha(bytes);
247
+ files[path] = hash;
248
+ skipped += markdownEntries(body, path, hash, entry => {
249
+ if (index === fileIndex && entry.file.line < startLine)
250
+ return;
251
+ if (entries.length < maxEntries)
252
+ entries.push(entry);
253
+ else
254
+ next ??= index + ':' + entry.file.line;
255
+ });
256
+ if (next)
257
+ break;
258
+ }
259
+ catch (error) {
260
+ if (error.code !== 'ENOENT')
261
+ skipped++;
262
+ }
263
+ }
264
+ return { entries, files, skipped, next };
265
+ }
@@ -0,0 +1,91 @@
1
+ import { digest } from "./domain.js";
2
+ import { standingRequest } from "./question-answers.js";
3
+ import { foregroundAttemptLimit } from "./turn-review-store.js";
4
+ const sentences = new Intl.Segmenter(undefined, { granularity: 'sentence' });
5
+ export const foregroundTurnKey = (store, session, turn, domain, generation) => digest(JSON.stringify([store, session, turn, domain, generation]));
6
+ // Use the native source coordinates, never a model-supplied topic, target or scope.
7
+ // Citing a smaller part of a sentence still consumes the same allowance. Explicit
8
+ // list separators let independent instructions on one line be cited separately.
9
+ export function foregroundEvidence(event, turnKey, start = 0, end = event.text.length) {
10
+ const ranges = [];
11
+ const segments = sentences.segment(event.text);
12
+ let sentence = segments.containing(start);
13
+ while (sentence && sentence.index < end) {
14
+ const selections = standingRequest(sentence.segment)
15
+ ? event.formSelections?.map(option => [option.resultSeq, option.questionId, option.label]) : undefined;
16
+ for (const clause of sentence.segment.matchAll(/[^,,;;\r\n]+/gu)) {
17
+ const offset = sentence.index + clause.index;
18
+ if (offset >= end || offset + clause[0].length <= start || !clause[0].trim())
19
+ continue;
20
+ const key = digest(JSON.stringify([turnKey, event.seq, event.block, offset, clause[0], event.question, selections]));
21
+ ranges.push({ key, start: offset, end: offset + clause[0].length });
22
+ }
23
+ sentence = segments.containing(sentence.index + sentence.segment.length);
24
+ }
25
+ return ranges;
26
+ }
27
+ /** One instance per foreground submission. SQLite shares the actual allowance across callers. */
28
+ export class ForegroundAttempts {
29
+ ledger;
30
+ turnKey;
31
+ keys = new Map();
32
+ batches = [];
33
+ constructor(ledger, turnKey) {
34
+ this.ledger = ledger;
35
+ this.turnKey = turnKey;
36
+ }
37
+ bind(index, event, quote) {
38
+ const start = event.text.indexOf(quote);
39
+ this.keys.set(index, foregroundEvidence(event, this.turnKey, start, start + quote.length).map(range => range.key));
40
+ }
41
+ evidence(index) {
42
+ const keys = this.keys.get(index);
43
+ // Malformed or unlocatable proposals have their own allowance. They cannot use
44
+ // up an authentic source's attempts, even when submitted together in one tool call.
45
+ return keys?.length ? keys : [this.turnKey];
46
+ }
47
+ exhausted(index) {
48
+ return this.ledger.foregroundExhausted(this.evidence(index));
49
+ }
50
+ batch() {
51
+ const batch = new Map();
52
+ this.batches.push(batch);
53
+ return batch;
54
+ }
55
+ admit(index, batch) {
56
+ const keys = this.evidence(index);
57
+ const fresh = keys.filter(key => !batch.has(key));
58
+ if (fresh.length) {
59
+ const attempt = this.ledger.reserveForeground(fresh);
60
+ if (!attempt)
61
+ return false;
62
+ for (const key of fresh)
63
+ batch.set(key, { indices: [], attempt });
64
+ }
65
+ for (const key of keys)
66
+ batch.get(key).indices.push(index);
67
+ return true;
68
+ }
69
+ finish(saved) {
70
+ const lastAttempts = new Set();
71
+ for (const batch of this.batches) {
72
+ const refund = [];
73
+ for (const [key, reservation] of batch) {
74
+ if (reservation.indices.every(saved))
75
+ refund.push(key);
76
+ else if (reservation.attempt === foregroundAttemptLimit)
77
+ for (const index of reservation.indices)
78
+ if (!saved(index))
79
+ lastAttempts.add(index);
80
+ }
81
+ if (refund.length)
82
+ this.ledger.releaseForeground(refund);
83
+ }
84
+ // A multi-clause reservation reports the largest counter. A sibling that cites
85
+ // just one clause may still have credit, including after a concurrent refund.
86
+ for (const index of lastAttempts)
87
+ if (!this.exhausted(index))
88
+ lastAttempts.delete(index);
89
+ return lastAttempts;
90
+ }
91
+ }