codexmate 0.1.32 → 0.1.34
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 +18 -2
- package/README.vi.md +18 -2
- package/README.zh.md +18 -2
- package/cli/claude-proxy.js +2 -2
- package/cli/local-bridge.js +10 -6
- package/cli/openai-chat-routing.js +38 -0
- package/cli/prompt-history.js +2 -0
- package/cli/routing-bridge.js +143 -0
- package/cli/system-prompt-files.js +75 -53
- package/cli.js +325 -215
- package/lib/cli-config-engine.js +6 -1
- package/lib/cli-file-utils.js +6 -1
- package/lib/config-change-fs.js +132 -0
- package/lib/config-changes.js +293 -0
- package/lib/file-sharing-lan.js +111 -0
- package/lib/file-sharing.js +196 -0
- package/lib/handoff-mcp.js +18 -2
- package/lib/local-feature-store.js +39 -0
- package/lib/model-test-client.js +61 -0
- package/lib/model-test.js +126 -0
- package/lib/routing-groups.js +161 -0
- package/lib/session-bookmarks.js +72 -0
- package/lib/session-context-health.js +23 -3
- package/lib/session-diagnostics.js +75 -0
- package/lib/session-feature-settings.js +21 -0
- package/lib/session-features.js +63 -0
- package/lib/session-handoff-draft.js +43 -0
- package/lib/session-projects.js +76 -0
- package/lib/session-search-index.js +188 -0
- package/lib/thread-handoff.js +8 -0
- package/lib/web-server.js +216 -0
- package/package.json +1 -1
- package/plugins/file-sharing/manifest.mjs +10 -0
- package/plugins/file-sharing/methods.mjs +101 -0
- package/plugins/file-sharing/overview.mjs +3 -0
- package/plugins/file-sharing/ownership.mjs +5 -0
- package/plugins/registry.mjs +3 -0
- package/web-ui/app.js +22 -3
- package/web-ui/index.html +4 -2
- package/web-ui/logic.context-window.mjs +15 -0
- package/web-ui/modules/api.mjs +72 -39
- package/web-ui/modules/app.computed.main-tabs.mjs +3 -0
- package/web-ui/modules/app.methods.agents.mjs +17 -0
- package/web-ui/modules/app.methods.claude-config.mjs +2 -0
- package/web-ui/modules/app.methods.codex-config.mjs +9 -0
- package/web-ui/modules/app.methods.config-changes.mjs +124 -0
- package/web-ui/modules/app.methods.install.mjs +23 -3
- package/web-ui/modules/app.methods.kilocode-config.mjs +2 -0
- package/web-ui/modules/app.methods.navigation.mjs +2 -0
- package/web-ui/modules/app.methods.openclaw-persist.mjs +2 -0
- package/web-ui/modules/app.methods.opencode-config.mjs +2 -0
- package/web-ui/modules/app.methods.pi-config.mjs +12 -3
- package/web-ui/modules/app.methods.prompts-editor.mjs +7 -4
- package/web-ui/modules/app.methods.provider-cache.mjs +9 -3
- package/web-ui/modules/app.methods.providers.mjs +6 -0
- package/web-ui/modules/app.methods.session-actions.mjs +2 -2
- package/web-ui/modules/app.methods.startup-claude.mjs +8 -47
- package/web-ui/modules/app.methods.system-prompt.mjs +88 -17
- package/web-ui/modules/app.methods.theme.mjs +4 -3
- package/web-ui/modules/app.methods.web-ui-preferences.mjs +7 -0
- package/web-ui/modules/config-change-actions.mjs +9 -0
- package/web-ui/modules/i18n/locales/en.mjs +254 -8
- package/web-ui/modules/i18n/locales/ja.mjs +254 -8
- package/web-ui/modules/i18n/locales/vi.mjs +254 -8
- package/web-ui/modules/i18n/locales/zh-tw.mjs +254 -8
- package/web-ui/modules/i18n/locales/zh.mjs +254 -8
- package/web-ui/modules/model-test.mjs +82 -0
- package/web-ui/modules/plugins.methods.mjs +3 -1
- package/web-ui/modules/prompt-ecosystem.methods.mjs +4 -3
- package/web-ui/modules/request-deadline.mjs +33 -0
- package/web-ui/modules/routing.mjs +206 -0
- package/web-ui/modules/session-features.mjs +279 -0
- package/web-ui/modules/thread-handoff.mjs +1 -1
- package/web-ui/partials/index/config-changes.html +25 -0
- package/web-ui/partials/index/context-window-reference.html +17 -0
- package/web-ui/partials/index/layout-header.html +40 -42
- package/web-ui/partials/index/modal-openclaw-config.html +0 -2
- package/web-ui/partials/index/modal-skills.html +0 -1
- package/web-ui/partials/index/modals-basic.html +15 -8
- package/web-ui/partials/index/modals-pi-provider.html +0 -1
- package/web-ui/partials/index/panel-config-codex.html +0 -3
- package/web-ui/partials/index/panel-config-openclaw.html +16 -13
- package/web-ui/partials/index/panel-dashboard.html +0 -2
- package/web-ui/partials/index/panel-plugins.html +3 -10
- package/web-ui/partials/index/panel-prompts.html +13 -8
- package/web-ui/partials/index/panel-routing.html +3 -0
- package/web-ui/partials/index/panel-sessions.html +9 -0
- package/web-ui/partials/index/panel-settings.html +12 -13
- package/web-ui/partials/index/panel-trash.html +0 -1
- package/web-ui/partials/index/plugin-file-sharing.html +47 -0
- package/web-ui/partials/index/routing-model-test.html +53 -0
- package/web-ui/partials/index/session-diagnostics.html +32 -0
- package/web-ui/partials/index/session-features.html +107 -0
- package/web-ui/partials/index/thread-handoff.html +6 -3
- package/web-ui/res/web-ui-render.precompiled.js +1689 -246
- package/web-ui/styles/base-theme.css +1 -1
- package/web-ui/styles/config-changes.css +30 -0
- package/web-ui/styles/modals-core.css +6 -5
- package/web-ui/styles/navigation-panels.css +4 -0
- package/web-ui/styles/openclaw-structured.css +205 -189
- package/web-ui/styles/plugins-panel.css +40 -1
- package/web-ui/styles/responsive.css +10 -5
- package/web-ui/styles/routing.css +78 -0
- package/web-ui/styles/session-features.css +258 -0
- package/web-ui/styles/settings-panel.css +30 -0
- package/web-ui/styles/system-prompt.css +8 -7
- package/web-ui/styles/theme-violet-tokens.css +52 -0
- package/web-ui/styles/theme-violet.css +1736 -0
- package/web-ui/styles.css +5 -1
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
const path = require('path');
|
|
3
|
+
const { createLocalFeatureStore, digest } = require('./local-feature-store');
|
|
4
|
+
const MAX_NOTE_LENGTH = 4000;
|
|
5
|
+
const MAX_TAG_LENGTH = 80;
|
|
6
|
+
const MAX_TAGS = 20;
|
|
7
|
+
const MAX_EXCERPT_LENGTH = 50000;
|
|
8
|
+
|
|
9
|
+
function projectKey(cwd) {
|
|
10
|
+
if (!cwd) return '';
|
|
11
|
+
// Respect Windows path rules without merging same-named directories or worktrees.
|
|
12
|
+
return process.platform === 'win32' ? path.resolve(cwd).toLowerCase() : path.resolve(cwd);
|
|
13
|
+
}
|
|
14
|
+
function createSessionBookmarks({ root, readNode }) {
|
|
15
|
+
const store = createLocalFeatureStore(path.join(root, 'bookmarks.json'), { version: 1, items: [] });
|
|
16
|
+
function list(params = {}) {
|
|
17
|
+
const snapshot = store.read();
|
|
18
|
+
if (!Array.isArray(snapshot.value.items)) throw new Error('feature-store-invalid');
|
|
19
|
+
const query = String(params.query || '').toLowerCase();
|
|
20
|
+
const items = snapshot.value.items.filter((item) => (!params.project || item.projectKey === projectKey(params.project))
|
|
21
|
+
&& (!params.tag || item.tags.includes(params.tag))
|
|
22
|
+
&& `${item.excerpt}\n${item.note}\n${item.tags.join(' ')}`.toLowerCase().includes(query));
|
|
23
|
+
return { items, revision: snapshot.revision };
|
|
24
|
+
}
|
|
25
|
+
function edit(params) {
|
|
26
|
+
if (typeof params.note !== 'string' || params.note.length > MAX_NOTE_LENGTH || !Array.isArray(params.tags)
|
|
27
|
+
|| params.tags.length > MAX_TAGS || params.tags.some((tag) => typeof tag !== 'string' || tag.length > MAX_TAG_LENGTH)) {
|
|
28
|
+
throw new Error('bookmark-input-invalid');
|
|
29
|
+
}
|
|
30
|
+
return { note: params.note, tags: [...new Set(params.tags.map((tag) => tag.trim()).filter(Boolean))] };
|
|
31
|
+
}
|
|
32
|
+
async function save(params) {
|
|
33
|
+
const snapshot = store.read();
|
|
34
|
+
if (snapshot.revision !== params.revision) throw new Error('feature-store-conflict');
|
|
35
|
+
const fields = edit(params);
|
|
36
|
+
const existing = params.id && snapshot.value.items.find((item) => item.id === params.id);
|
|
37
|
+
if (params.id && !existing) throw new Error('bookmark-not-found');
|
|
38
|
+
let item = existing;
|
|
39
|
+
if (!item) {
|
|
40
|
+
const result = await readNode(params);
|
|
41
|
+
if (result.error) throw new Error('bookmark-source-unavailable');
|
|
42
|
+
const node = result.node;
|
|
43
|
+
const id = digest(JSON.stringify([result.source, params.sessionId || params.filePath, node.id]));
|
|
44
|
+
item = snapshot.value.items.find((entry) => entry.id === id);
|
|
45
|
+
if (item) return { ...list(), item };
|
|
46
|
+
if (node.text.length > MAX_EXCERPT_LENGTH) throw new Error('bookmark-excerpt-too-large');
|
|
47
|
+
item = { id, source: result.source, sessionId: params.sessionId || '', filePath: params.filePath || '',
|
|
48
|
+
nodeId: node.id, cwd: params.cwd || '', projectKey: projectKey(params.cwd), excerpt: node.text,
|
|
49
|
+
textHash: digest(node.text), createdAt: new Date().toISOString() };
|
|
50
|
+
snapshot.value.items.unshift(item);
|
|
51
|
+
}
|
|
52
|
+
Object.assign(item, fields, { updatedAt: new Date().toISOString() });
|
|
53
|
+
store.write(snapshot.value, snapshot.revision);
|
|
54
|
+
return { ...list(), item };
|
|
55
|
+
}
|
|
56
|
+
function remove(params) {
|
|
57
|
+
const snapshot = store.read();
|
|
58
|
+
if (snapshot.revision !== params.revision) throw new Error('feature-store-conflict');
|
|
59
|
+
snapshot.value.items = snapshot.value.items.filter((item) => item.id !== params.id);
|
|
60
|
+
store.write(snapshot.value, snapshot.revision);
|
|
61
|
+
return list();
|
|
62
|
+
}
|
|
63
|
+
async function locate(params) {
|
|
64
|
+
const item = store.read().value.items.find((entry) => entry.id === params.id);
|
|
65
|
+
if (!item) throw new Error('bookmark-not-found');
|
|
66
|
+
const result = await readNode({ ...item, nodeId: item.nodeId });
|
|
67
|
+
if (result.error || digest(result.node.text) !== item.textHash) return { item, available: false };
|
|
68
|
+
return { item, available: true, node: result.node };
|
|
69
|
+
}
|
|
70
|
+
return { list, save, remove, locate };
|
|
71
|
+
}
|
|
72
|
+
module.exports = { createSessionBookmarks, projectKey };
|
|
@@ -53,19 +53,28 @@ function createSessionContextHealthController(deps) {
|
|
|
53
53
|
const analyzer = createContextAnalyzer();
|
|
54
54
|
const reader = createContextRecordReader(target.source, params.cwd || '');
|
|
55
55
|
let index = 0;
|
|
56
|
+
const models = new Set();
|
|
57
|
+
const modelWindows = {};
|
|
56
58
|
for await (const record of records(target.source, target.filePath, target.sessionId)) {
|
|
59
|
+
const metadata = record?.payload || record?.message || record || {};
|
|
60
|
+
const model = metadata.model || metadata.modelID || metadata.info?.modelID;
|
|
61
|
+
const window = metadata.model_context_window ?? metadata.context_window ?? metadata.contextWindow;
|
|
62
|
+
if (typeof model === 'string' && model) {
|
|
63
|
+
models.add(model);
|
|
64
|
+
if (Number.isSafeInteger(window) && window > 0) modelWindows[model] = window;
|
|
65
|
+
}
|
|
57
66
|
for (const node of reader(record, index)) {
|
|
58
67
|
if (!focus) analyzer.add(node);
|
|
59
68
|
if (node.id === focus) {
|
|
60
69
|
return { source: target.source, node: { id: node.id, role: node.role,
|
|
61
70
|
recordLineIndex: node.recordLineIndex, messageIndex: node.messageIndex,
|
|
62
|
-
text: node.parts.map((part) => part.text).join('\n') } };
|
|
71
|
+
text: node.parts.map((part) => part.text).join('\n'), readPaths: node.readPaths || [] } };
|
|
63
72
|
}
|
|
64
73
|
}
|
|
65
74
|
index++;
|
|
66
75
|
}
|
|
67
76
|
if (focus) throw new Error('消息节点不存在,请刷新体检结果');
|
|
68
|
-
return { source: target.source, sessionId: target.sessionId, complete: true, scannedRecords: index, ...analyzer.finish() };
|
|
77
|
+
return { source: target.source, sessionId: target.sessionId, complete: true, scannedRecords: index, models: [...models], modelWindows, ...analyzer.finish() };
|
|
69
78
|
}
|
|
70
79
|
async function readSessionContextHealth(params = {}) {
|
|
71
80
|
try { return await scan(params); } catch (error) { return { error: error.message }; }
|
|
@@ -76,7 +85,18 @@ function createSessionContextHealthController(deps) {
|
|
|
76
85
|
}
|
|
77
86
|
try { return await scan(params, params.nodeId); } catch (error) { return { error: error.message }; }
|
|
78
87
|
}
|
|
79
|
-
|
|
88
|
+
async function* iterateSessionContextNodes(params = {}) {
|
|
89
|
+
const target = resolve(params);
|
|
90
|
+
const reader = createContextRecordReader(target.source, params.cwd || '');
|
|
91
|
+
let index = 0;
|
|
92
|
+
for await (const record of records(target.source, target.filePath, target.sessionId)) {
|
|
93
|
+
for (const node of reader(record, index)) yield { ...node,
|
|
94
|
+
text: node.parts.map((part) => part.text).join('\n'),
|
|
95
|
+
timestamp: record?.timestamp || record?.message?.timestamp || '' };
|
|
96
|
+
index++;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
return { readSessionContextHealth, readSessionContextNode, iterateSessionContextNodes };
|
|
80
100
|
}
|
|
81
101
|
|
|
82
102
|
module.exports = { createSessionContextHealthController };
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
const ITEM_TIMEOUT_MS = 15000;
|
|
3
|
+
const TOTAL_TIMEOUT_MS = 60000;
|
|
4
|
+
function redactDiagnostic(value, options = {}) {
|
|
5
|
+
const secrets = options.secrets || [];
|
|
6
|
+
function text(input) {
|
|
7
|
+
let output = String(input);
|
|
8
|
+
for (const secret of secrets.filter((item) => typeof item === 'string' && item)) output = output.split(secret).join('[redacted]');
|
|
9
|
+
if (options.home) output = output.split(options.home).join('~');
|
|
10
|
+
if (options.project) output = output.split(options.project).join('[project]');
|
|
11
|
+
return output.replace(/Bearer\s+[^\s"',;]+/gi, 'Bearer [redacted]')
|
|
12
|
+
.replace(/((?:api[_-]?key|token|password|secret|authorization)\s*[=:]\s*)[^\s,;]+/gi, '$1[redacted]')
|
|
13
|
+
.replace(/(https?:\/\/)[^\s/@]+:[^\s/@]+@/gi, '$1[redacted]@')
|
|
14
|
+
.replace(/([?&](?:api[_-]?key|token|password|secret)=)[^&\s]+/gi, '$1[redacted]');
|
|
15
|
+
}
|
|
16
|
+
function clean(input) {
|
|
17
|
+
if (typeof input === 'string') return text(input);
|
|
18
|
+
if (Array.isArray(input)) return input.map(clean);
|
|
19
|
+
if (!input || typeof input !== 'object') return input;
|
|
20
|
+
return Object.fromEntries(Object.entries(input).map(([key, item]) => [key,
|
|
21
|
+
/api[_-]?key|token|password|secret|authorization|headers|(?:^|_)env$/i.test(key) ? '[redacted]' : clean(item)]));
|
|
22
|
+
}
|
|
23
|
+
return clean(value);
|
|
24
|
+
}
|
|
25
|
+
function createSessionDiagnostics({ local, provider, mcp, mcpTargets, home, secrets }) {
|
|
26
|
+
let job = { status: 'idle', items: [], cancelled: false };
|
|
27
|
+
let running;
|
|
28
|
+
const status = () => {
|
|
29
|
+
const report = redactDiagnostic(job, { home, project: job.project, secrets: secrets ? secrets() : [] });
|
|
30
|
+
const markdown = ['# Codex Mate diagnostics', `Status: ${report.status}`, ...report.items.map((item) =>
|
|
31
|
+
`\n## ${item.id}\nStatus: ${item.status}\nChecked: ${item.checkedAt || ''}\n${JSON.stringify(item.evidence || {}, null, 2)}`)].join('\n');
|
|
32
|
+
return { report, markdown };
|
|
33
|
+
};
|
|
34
|
+
async function check(item, execute, deadline) {
|
|
35
|
+
if (job.cancelled) { item.status = 'cancelled'; return; }
|
|
36
|
+
const activeJob = job;
|
|
37
|
+
if (Date.now() >= deadline) { item.status = 'timeout'; return; }
|
|
38
|
+
const started = Date.now();
|
|
39
|
+
const timeout = Math.max(1, Math.min(ITEM_TIMEOUT_MS, deadline - started));
|
|
40
|
+
item.status = 'running'; item.checkedAt = new Date().toISOString();
|
|
41
|
+
let timer;
|
|
42
|
+
try {
|
|
43
|
+
const result = await Promise.race([execute({ timeoutMs: timeout, isCancelled: () => activeJob.cancelled }),
|
|
44
|
+
new Promise((_, reject) => { timer = setTimeout(() => reject(new Error('diagnostic-timeout')), timeout); })]);
|
|
45
|
+
item.status = activeJob.cancelled ? 'cancelled' : result.ok === false ? 'failed' : 'passed';
|
|
46
|
+
item.evidence = result;
|
|
47
|
+
} catch (error) {
|
|
48
|
+
item.status = activeJob.cancelled ? 'cancelled' : error.message === 'diagnostic-timeout' ? 'timeout' : 'failed';
|
|
49
|
+
item.errorCode = error.message === 'diagnostic-timeout' ? 'diagnostic-timeout' : 'diagnostic-check-failed';
|
|
50
|
+
} finally { clearTimeout(timer); item.durationMs = Date.now() - started; }
|
|
51
|
+
}
|
|
52
|
+
function start(params = {}) {
|
|
53
|
+
if (job.status === 'running') throw new Error('diagnostic-busy');
|
|
54
|
+
if (params.remote !== undefined && typeof params.remote !== 'boolean') throw new Error('diagnostic-input-invalid');
|
|
55
|
+
const names = params.mcpNames || [];
|
|
56
|
+
if (!Array.isArray(names) || names.some((name) => typeof name !== 'string' || !mcpTargets(params.cwd).includes(name))) throw new Error('diagnostic-input-invalid');
|
|
57
|
+
job = { status: 'running', cancelled: false, startedAt: new Date().toISOString(), project: params.cwd || '',
|
|
58
|
+
items: [{ id: 'local', status: 'pending' }, { id: 'provider', status: params.remote ? 'pending' : 'not_checked' },
|
|
59
|
+
...names.map((name) => ({ id: `mcp:${name}`, status: 'pending' }))] };
|
|
60
|
+
running = (async () => {
|
|
61
|
+
const deadline = Date.now() + TOTAL_TIMEOUT_MS;
|
|
62
|
+
await check(job.items[0], local, deadline);
|
|
63
|
+
if (params.remote) await check(job.items[1], provider, deadline);
|
|
64
|
+
for (let index = 0; index < names.length; index++) {
|
|
65
|
+
if (Date.now() >= deadline) { job.items[index + 2].status = 'timeout'; continue; }
|
|
66
|
+
await check(job.items[index + 2], (options) => mcp(names[index], { ...options, cwd: params.cwd }), deadline);
|
|
67
|
+
}
|
|
68
|
+
job.status = job.cancelled ? 'cancelled' : job.items.some((item) => ['failed', 'timeout'].includes(item.status)) ? 'partial' : 'success';
|
|
69
|
+
job.finishedAt = new Date().toISOString();
|
|
70
|
+
})().catch(() => { job.status = 'failed'; });
|
|
71
|
+
return status();
|
|
72
|
+
}
|
|
73
|
+
return { start, status, cancel() { job.cancelled = true; return status(); }, targets: (cwd) => ({ names: mcpTargets(cwd) }), wait: () => running };
|
|
74
|
+
}
|
|
75
|
+
module.exports = { createSessionDiagnostics, redactDiagnostic };
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
const path = require('path');
|
|
3
|
+
const { createLocalFeatureStore } = require('./local-feature-store');
|
|
4
|
+
function createSessionFeatureSettings(root) {
|
|
5
|
+
const store = createLocalFeatureStore(path.join(root, 'preferences.json'), { version: 1, windows: {}, dismissed: {} });
|
|
6
|
+
function get() { const snapshot = store.read(); return { settings: snapshot.value, revision: snapshot.revision }; }
|
|
7
|
+
function save(params) {
|
|
8
|
+
const snapshot = store.read();
|
|
9
|
+
if (snapshot.revision !== params.revision) throw new Error('feature-store-conflict');
|
|
10
|
+
if (typeof params.key !== 'string' || !params.key || params.key.length > 1000
|
|
11
|
+
|| (params.window !== '' && (!Number.isSafeInteger(params.window) || params.window <= 0))
|
|
12
|
+
|| typeof params.dismissed !== 'boolean') throw new Error('context-window-invalid');
|
|
13
|
+
if (params.window === '') delete snapshot.value.windows[params.key];
|
|
14
|
+
else snapshot.value.windows[params.key] = params.window;
|
|
15
|
+
snapshot.value.dismissed[params.key] = params.dismissed;
|
|
16
|
+
store.write(snapshot.value, snapshot.revision);
|
|
17
|
+
return get();
|
|
18
|
+
}
|
|
19
|
+
return { get, save };
|
|
20
|
+
}
|
|
21
|
+
module.exports = { createSessionFeatureSettings };
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
const { createSessionBookmarks } = require('./session-bookmarks');
|
|
3
|
+
const { digest } = require('./local-feature-store');
|
|
4
|
+
const { createSessionSearchIndex } = require('./session-search-index');
|
|
5
|
+
const { generateHandoffDraft } = require('./session-handoff-draft');
|
|
6
|
+
const { createSessionProjects } = require('./session-projects');
|
|
7
|
+
const { createSessionFeatureSettings } = require('./session-feature-settings');
|
|
8
|
+
const { createSessionDiagnostics } = require('./session-diagnostics');
|
|
9
|
+
|
|
10
|
+
function createSessionFeatures(deps) {
|
|
11
|
+
async function readNode(params) {
|
|
12
|
+
if (params.nodeId) return deps.readNode(params);
|
|
13
|
+
let match;
|
|
14
|
+
for await (const node of deps.nodes(params)) {
|
|
15
|
+
if (node.text !== params.messageText) continue;
|
|
16
|
+
if (match) return { error: 'bookmark-source-unavailable' };
|
|
17
|
+
match = node;
|
|
18
|
+
}
|
|
19
|
+
return match ? { source: params.source, node: match } : { error: 'bookmark-source-unavailable' };
|
|
20
|
+
}
|
|
21
|
+
const bookmarks = createSessionBookmarks({ root: deps.root, readNode });
|
|
22
|
+
const index = createSessionSearchIndex(deps);
|
|
23
|
+
const projects = createSessionProjects({ ...deps, bookmarks });
|
|
24
|
+
const settings = createSessionFeatureSettings(deps.root);
|
|
25
|
+
const diagnostics = deps.diagnostics ? createSessionDiagnostics(deps.diagnostics) : null;
|
|
26
|
+
const actions = {
|
|
27
|
+
'session-diagnostics-targets': (params) => { if (!diagnostics) throw new Error('feature-action-invalid'); return diagnostics.targets(params.cwd); },
|
|
28
|
+
'session-diagnostics-start': (params) => { if (!diagnostics) throw new Error('feature-action-invalid'); return diagnostics.start(params); },
|
|
29
|
+
'session-diagnostics-status': () => { if (!diagnostics) throw new Error('feature-action-invalid'); return diagnostics.status(); },
|
|
30
|
+
'session-diagnostics-cancel': () => { if (!diagnostics) throw new Error('feature-action-invalid'); return diagnostics.cancel(); },
|
|
31
|
+
'session-feature-settings-get': () => settings.get(),
|
|
32
|
+
'session-feature-settings-save': (params) => settings.save(params),
|
|
33
|
+
'session-projects': (params) => projects.list(params),
|
|
34
|
+
'session-project-map': (params) => projects.map(params),
|
|
35
|
+
'session-project-prompt': (params) => projects.prompt(params),
|
|
36
|
+
'session-handoff-draft': (params) => generateHandoffDraft(params, readNode),
|
|
37
|
+
'session-index-status': () => index.status(),
|
|
38
|
+
'session-index-refresh': (params) => index.start(params),
|
|
39
|
+
'session-index-cancel': () => index.cancel(),
|
|
40
|
+
'session-index-search': (params) => index.search(params),
|
|
41
|
+
'session-index-node': async (params) => {
|
|
42
|
+
const result = await readNode(params);
|
|
43
|
+
if (result.error || digest(result.node.text) !== params.textHash) throw new Error('bookmark-source-unavailable');
|
|
44
|
+
return result;
|
|
45
|
+
},
|
|
46
|
+
'session-bookmarks-list': (params) => bookmarks.list(params),
|
|
47
|
+
'session-bookmark-save': (params) => bookmarks.save(params),
|
|
48
|
+
'session-bookmark-remove': (params) => bookmarks.remove(params),
|
|
49
|
+
'session-bookmark-locate': (params) => bookmarks.locate(params)
|
|
50
|
+
};
|
|
51
|
+
async function handle(action, params = {}) {
|
|
52
|
+
try {
|
|
53
|
+
if (!actions[action]) throw new Error('feature-action-invalid');
|
|
54
|
+
return await actions[action](params);
|
|
55
|
+
} catch (error) {
|
|
56
|
+
// Keep filesystem paths and raw upstream errors out of the public contract.
|
|
57
|
+
const code = /^[a-z]+(?:-[a-z]+)+$/.test(error.message) ? error.message : 'feature-read-failed';
|
|
58
|
+
return { error: code, errorCode: code };
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
return { handle, bookmarks, readNode, index };
|
|
62
|
+
}
|
|
63
|
+
module.exports = { createSessionFeatures };
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
const { digest } = require('./local-feature-store');
|
|
3
|
+
const MAX_SELECTIONS = 100;
|
|
4
|
+
const EXCERPT_LENGTH = 800;
|
|
5
|
+
const GOAL_LENGTH = 500;
|
|
6
|
+
|
|
7
|
+
function classifyEvidence(node) {
|
|
8
|
+
const text = node.text;
|
|
9
|
+
const isTool = /tool|function_call_output/i.test(node.role);
|
|
10
|
+
if (!isTool) return 'unverified';
|
|
11
|
+
const failed = /(?:\b(?:fail(?:ed|ures?)?|errors?)\s*[:=]?\s*[1-9]\d*\b|\bexit(?:ed)?(?: with)?(?: code)?\s*[:=]?\s*[1-9]\d*\b|测试失败|验证失败|未通过)/i.test(text);
|
|
12
|
+
if (failed) return 'failed';
|
|
13
|
+
const passed = /(?:^|\n)\s*(?:All \d+ tests passed[.!]?|(?:ℹ|#)?\s*pass\s+[1-9]\d*|exit(?:ed)?(?: with)?(?: code)?\s*[:=]?\s*0)\s*(?:\n|$)/i.test(text);
|
|
14
|
+
const ambiguous = /未(?:执行|运行|验证)|尚未|not (?:run|executed|passed)|待确认/i.test(text);
|
|
15
|
+
return passed && !ambiguous ? 'passed' : 'unverified';
|
|
16
|
+
}
|
|
17
|
+
async function generateHandoffDraft(params, readNode) {
|
|
18
|
+
if (!Array.isArray(params.selections) || !params.selections.length || params.selections.length > MAX_SELECTIONS
|
|
19
|
+
|| params.selections.some((value) => typeof value !== 'string')) throw new Error('handoff-selection-invalid');
|
|
20
|
+
const card = { goal: String(params.goal || '').trim().slice(0, GOAL_LENGTH), completed: [], blockers: [], nextSteps: [], files: [] };
|
|
21
|
+
const evidence = [];
|
|
22
|
+
const unverified = [];
|
|
23
|
+
for (const selection of [...new Set(params.selections)]) {
|
|
24
|
+
const result = await readNode({ source: params.source, sessionId: params.sessionId, filePath: params.filePath,
|
|
25
|
+
cwd: params.cwd, ...(selection.startsWith('text:') ? { messageText: selection.slice(5) } : { nodeId: selection }) });
|
|
26
|
+
if (result.error) throw new Error('bookmark-source-unavailable');
|
|
27
|
+
const node = result.node;
|
|
28
|
+
const status = classifyEvidence(node);
|
|
29
|
+
const excerpt = node.text.slice(0, EXCERPT_LENGTH);
|
|
30
|
+
for (const file of node.readPaths || []) if (!card.files.includes(file)) card.files.push(file);
|
|
31
|
+
for (const line of node.text.split('\n')) {
|
|
32
|
+
if (/^(?:下一步|后续步骤|next steps?)\s*[::]/i.test(line.trim())) card.nextSteps.push(line.trim());
|
|
33
|
+
}
|
|
34
|
+
if (!card.goal && node.role === 'user') card.goal = node.text.slice(0, GOAL_LENGTH);
|
|
35
|
+
if (status === 'passed') card.completed.push(excerpt);
|
|
36
|
+
else if (status === 'failed') card.blockers.push(excerpt);
|
|
37
|
+
else unverified.push(excerpt);
|
|
38
|
+
evidence.push({ source: result.source, sessionId: params.sessionId || '', filePath: params.filePath || '',
|
|
39
|
+
cwd: params.cwd || '', nodeId: node.id, textHash: digest(node.text), excerpt, status });
|
|
40
|
+
}
|
|
41
|
+
return { card, evidence, unverified, requiresReview: true, sent: false };
|
|
42
|
+
}
|
|
43
|
+
module.exports = { generateHandoffDraft, classifyEvidence };
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
const fs = require('fs');
|
|
3
|
+
const path = require('path');
|
|
4
|
+
const { createLocalFeatureStore } = require('./local-feature-store');
|
|
5
|
+
const { projectKey } = require('./session-bookmarks');
|
|
6
|
+
const { SOURCES } = require('./session-search-index');
|
|
7
|
+
const PROJECT_DISCOVERY_LIMIT = 3000;
|
|
8
|
+
const PROJECT_SESSION_LIMIT = 100;
|
|
9
|
+
|
|
10
|
+
function createSessionProjects({ root, inventory, bookmarks, handoffs }) {
|
|
11
|
+
const store = createLocalFeatureStore(path.join(root, 'projects.json'), { version: 1, mappings: {} });
|
|
12
|
+
function resolveProject(cwd, mappings) {
|
|
13
|
+
let key = projectKey(cwd);
|
|
14
|
+
const visited = new Set();
|
|
15
|
+
while (mappings[key]) {
|
|
16
|
+
if (visited.has(key)) throw new Error('project-mapping-invalid');
|
|
17
|
+
visited.add(key); key = mappings[key];
|
|
18
|
+
}
|
|
19
|
+
return key;
|
|
20
|
+
}
|
|
21
|
+
function map(params) {
|
|
22
|
+
if (typeof params.from !== 'string' || typeof params.to !== 'string' || !path.isAbsolute(params.from)
|
|
23
|
+
|| (params.to && !path.isAbsolute(params.to))) throw new Error('project-mapping-invalid');
|
|
24
|
+
const snapshot = store.read();
|
|
25
|
+
if (snapshot.revision !== params.revision) throw new Error('feature-store-conflict');
|
|
26
|
+
const from = projectKey(params.from);
|
|
27
|
+
if (params.to) snapshot.value.mappings[from] = projectKey(params.to);
|
|
28
|
+
else delete snapshot.value.mappings[from];
|
|
29
|
+
resolveProject(from, snapshot.value.mappings);
|
|
30
|
+
return store.write(snapshot.value, snapshot.revision);
|
|
31
|
+
}
|
|
32
|
+
async function list(params = {}) {
|
|
33
|
+
const snapshot = store.read();
|
|
34
|
+
const groups = new Map();
|
|
35
|
+
const failures = [];
|
|
36
|
+
for (const source of SOURCES) {
|
|
37
|
+
let sessions;
|
|
38
|
+
try { sessions = await inventory(source, PROJECT_DISCOVERY_LIMIT); }
|
|
39
|
+
catch (_) { failures.push({ source, code: 'index-source-unavailable' }); continue; }
|
|
40
|
+
for (const session of sessions) {
|
|
41
|
+
const key = resolveProject(session.cwd || '', snapshot.value.mappings);
|
|
42
|
+
if (!groups.has(key)) groups.set(key, { key, cwd: key, sessions: [], sources: [], updatedAt: '' });
|
|
43
|
+
const group = groups.get(key);
|
|
44
|
+
const timestamp = session.updatedAt || session.timestamp || '';
|
|
45
|
+
group.sessions.push({ source, sessionId: session.sessionId || '', filePath: session.filePath || '',
|
|
46
|
+
cwd: session.cwd || '', title: session.title || '', timestamp, updatedAt: timestamp });
|
|
47
|
+
if (!group.sources.includes(source)) group.sources.push(source);
|
|
48
|
+
if (timestamp > group.updatedAt) group.updatedAt = timestamp;
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
const projects = [...groups.values()].map((group) => ({ key: group.key, cwd: group.cwd,
|
|
52
|
+
sources: group.sources, sessionCount: group.sessions.length, updatedAt: group.updatedAt }));
|
|
53
|
+
const key = params.project === undefined ? null : resolveProject(params.project, snapshot.value.mappings);
|
|
54
|
+
const group = key === null ? null : groups.get(key);
|
|
55
|
+
let detail = null;
|
|
56
|
+
if (group) {
|
|
57
|
+
const sessions = group.sessions.sort((left, right) => String(right.timestamp).localeCompare(String(left.timestamp))).slice(0, PROJECT_SESSION_LIMIT);
|
|
58
|
+
const prompts = group.cwd ? ['AGENTS.md', 'CLAUDE.md', '.claude/CLAUDE.md'].map((name) => path.join(group.cwd, name))
|
|
59
|
+
.filter((file) => { try { return fs.lstatSync(file).isFile(); } catch (error) { if (['ENOENT', 'ENOTDIR'].includes(error.code)) return false; throw error; } }) : [];
|
|
60
|
+
detail = { ...group, sessions, truncated: group.sessions.length > PROJECT_SESSION_LIMIT, prompts,
|
|
61
|
+
bookmarks: bookmarks.list().items.filter((item) => resolveProject(item.cwd, snapshot.value.mappings) === key),
|
|
62
|
+
handoffs: sessions.flatMap((session) => session.sessionId ? handoffs(session.sessionId).map((record) => ({ ...record, source: session.source })) : []) };
|
|
63
|
+
}
|
|
64
|
+
return { projects, detail, failures, mappings: snapshot.value.mappings, revision: snapshot.revision,
|
|
65
|
+
readAt: new Date().toISOString(), scope: 'discovered-candidates', discoveryLimit: PROJECT_DISCOVERY_LIMIT };
|
|
66
|
+
}
|
|
67
|
+
function prompt(params) {
|
|
68
|
+
if (!['AGENTS.md', 'CLAUDE.md', '.claude/CLAUDE.md'].includes(params.name) || !params.project) throw new Error('project-mapping-invalid');
|
|
69
|
+
const file = path.join(projectKey(params.project), params.name);
|
|
70
|
+
const stat = fs.lstatSync(file);
|
|
71
|
+
if (!stat.isFile() || stat.size > 2 * 1024 * 1024) throw new Error('feature-read-failed');
|
|
72
|
+
return { filePath: file, content: fs.readFileSync(file, 'utf8'), readOnly: true };
|
|
73
|
+
}
|
|
74
|
+
return { list, map, prompt };
|
|
75
|
+
}
|
|
76
|
+
module.exports = { createSessionProjects };
|
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
const fs = require('fs');
|
|
3
|
+
const path = require('path');
|
|
4
|
+
const readline = require('readline');
|
|
5
|
+
const crypto = require('crypto');
|
|
6
|
+
const { createLocalFeatureStore, digest } = require('./local-feature-store');
|
|
7
|
+
const { projectKey } = require('./session-bookmarks');
|
|
8
|
+
const SOURCES = ['codex', 'claude', 'gemini', 'codebuddy', 'workbuddy', 'pi', 'opencode', 'zed'];
|
|
9
|
+
const DEFAULT_DISCOVERY_LIMIT = 3000;
|
|
10
|
+
const MAX_DISCOVERY_LIMIT = 10000;
|
|
11
|
+
const MAX_RESULTS = 100;
|
|
12
|
+
const SNIPPET_LENGTH = 1200;
|
|
13
|
+
const BLOOM_BYTES = 256;
|
|
14
|
+
|
|
15
|
+
async function fileRevision(session) {
|
|
16
|
+
if (session.source === 'opencode' || session.source === 'zed') return null;
|
|
17
|
+
const hash = crypto.createHash('sha256');
|
|
18
|
+
for await (const chunk of fs.createReadStream(session.filePath)) hash.update(chunk);
|
|
19
|
+
return hash.digest('hex');
|
|
20
|
+
}
|
|
21
|
+
async function* readShard(file) {
|
|
22
|
+
const stream = fs.createReadStream(file, { encoding: 'utf8' });
|
|
23
|
+
const lines = readline.createInterface({ input: stream, crlfDelay: Infinity });
|
|
24
|
+
let failure;
|
|
25
|
+
stream.on('error', (error) => { failure = error; lines.close(); });
|
|
26
|
+
try {
|
|
27
|
+
for await (const line of lines) if (line) yield JSON.parse(line);
|
|
28
|
+
if (failure) throw failure;
|
|
29
|
+
} finally { lines.close(); stream.destroy(); }
|
|
30
|
+
}
|
|
31
|
+
function createSessionSearchIndex({ root, inventory, nodes }) {
|
|
32
|
+
const directory = path.join(root, 'index');
|
|
33
|
+
const store = createLocalFeatureStore(path.join(directory, 'catalog.json'), { version: 1, items: [], failures: [], coverage: [] });
|
|
34
|
+
let job = { status: 'idle', processed: 0, candidates: 0, failures: [] };
|
|
35
|
+
let activePromise;
|
|
36
|
+
let activeSearches = 0;
|
|
37
|
+
function status() {
|
|
38
|
+
const snapshot = store.read().value;
|
|
39
|
+
return { job: { ...job, failures: [...job.failures] }, indexed: snapshot.items.length,
|
|
40
|
+
failures: snapshot.failures, coverage: snapshot.coverage, updatedAt: snapshot.updatedAt || '' };
|
|
41
|
+
}
|
|
42
|
+
async function writeShard(session, before) {
|
|
43
|
+
fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
|
|
44
|
+
const temporary = path.join(directory, `${crypto.randomBytes(16).toString('hex')}.tmp`);
|
|
45
|
+
const output = await fs.promises.open(temporary, 'wx', 0o600);
|
|
46
|
+
const hash = crypto.createHash('sha256');
|
|
47
|
+
const bloom = Buffer.alloc(BLOOM_BYTES);
|
|
48
|
+
let count = 0;
|
|
49
|
+
let previous = '';
|
|
50
|
+
let pending;
|
|
51
|
+
async function emit(nextText) {
|
|
52
|
+
const line = JSON.stringify({ ...pending, before: previous, after: nextText.slice(0, SNIPPET_LENGTH) }) + '\n';
|
|
53
|
+
hash.update(line); await output.write(line); previous = pending.text.slice(-SNIPPET_LENGTH);
|
|
54
|
+
const text = `${session.title || ''}\n${pending.text}`.toLowerCase();
|
|
55
|
+
for (let index = 0; index + 1 < text.length; index++) {
|
|
56
|
+
const bit = (text.charCodeAt(index) * 31 + text.charCodeAt(index + 1)) % (BLOOM_BYTES * 8);
|
|
57
|
+
bloom[bit >> 3] |= 1 << (bit & 7);
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
try {
|
|
61
|
+
for await (const node of nodes(session)) {
|
|
62
|
+
if (job.cancelled) throw new Error('index-cancelled');
|
|
63
|
+
if (pending) await emit(node.text);
|
|
64
|
+
pending = { id: node.id, role: node.role, text: node.text, textHash: digest(node.text), timestamp: node.timestamp };
|
|
65
|
+
count++;
|
|
66
|
+
}
|
|
67
|
+
if (pending) await emit('');
|
|
68
|
+
if (before !== null && await fileRevision(session) !== before) throw new Error('index-source-changed');
|
|
69
|
+
await output.close();
|
|
70
|
+
const shard = `${digest(JSON.stringify([session.source, session.sessionId, session.filePath, hash.digest('hex')]))}.jsonl`;
|
|
71
|
+
await fs.promises.rename(temporary, path.join(directory, shard));
|
|
72
|
+
await fs.promises.writeFile(path.join(directory, shard + '.bloom'), bloom, { mode: 0o600 });
|
|
73
|
+
return { shard, count };
|
|
74
|
+
} finally {
|
|
75
|
+
await output.close();
|
|
76
|
+
if (fs.existsSync(temporary)) await fs.promises.unlink(temporary);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
async function refresh(params) {
|
|
80
|
+
let snapshot;
|
|
81
|
+
try { snapshot = store.read(); }
|
|
82
|
+
catch (error) {
|
|
83
|
+
if (!params.rebuild) throw error;
|
|
84
|
+
const catalog = path.join(directory, 'catalog.json');
|
|
85
|
+
if (fs.lstatSync(catalog).isSymbolicLink()) throw new Error('feature-store-invalid');
|
|
86
|
+
fs.renameSync(catalog, catalog + '.invalid-' + Date.now());
|
|
87
|
+
snapshot = store.read();
|
|
88
|
+
params = { ...params, source: 'all' };
|
|
89
|
+
}
|
|
90
|
+
const sources = !params.source || params.source === 'all' ? SOURCES : [params.source];
|
|
91
|
+
if (sources.some((source) => !SOURCES.includes(source))) throw new Error('index-source-invalid');
|
|
92
|
+
const limit = Math.min(MAX_DISCOVERY_LIMIT, Math.max(1, Number(params.limit) || DEFAULT_DISCOVERY_LIMIT));
|
|
93
|
+
const entries = snapshot.value.items.filter((item) => !sources.includes(item.source));
|
|
94
|
+
const failures = snapshot.value.failures.filter((item) => !sources.includes(item.source));
|
|
95
|
+
const coverage = snapshot.value.coverage.filter((item) => !sources.includes(item.source));
|
|
96
|
+
for (const source of sources) {
|
|
97
|
+
if (job.cancelled) throw new Error('index-cancelled');
|
|
98
|
+
let sessions;
|
|
99
|
+
try { sessions = await inventory(source, limit); }
|
|
100
|
+
catch (_) { failures.push({ source, code: 'index-source-unavailable' }); continue; }
|
|
101
|
+
job.candidates += sessions.length;
|
|
102
|
+
coverage.push({ source, candidates: sessions.length, discoveryLimit: limit, scope: 'discovered-candidates' });
|
|
103
|
+
for (const session of sessions) {
|
|
104
|
+
if (job.cancelled) throw new Error('index-cancelled');
|
|
105
|
+
try {
|
|
106
|
+
const revision = await fileRevision(session);
|
|
107
|
+
const key = digest(JSON.stringify([source, session.sessionId, session.filePath]));
|
|
108
|
+
const old = snapshot.value.items.find((item) => item.key === key);
|
|
109
|
+
const cached = params.rebuild !== true && revision !== null && /^[a-f0-9]{64}\.jsonl$/.test(old?.shard || '') && old?.revision === revision && fs.existsSync(path.join(directory, old.shard));
|
|
110
|
+
const shard = cached ? { shard: old.shard, count: old.count } : await writeShard(session, revision);
|
|
111
|
+
entries.push({ key, source, sessionId: session.sessionId || '', filePath: session.filePath || '',
|
|
112
|
+
cwd: session.cwd || '', title: session.title || '', timestamp: session.updatedAt || session.timestamp || '', updatedAt: session.updatedAt || session.timestamp || '', revision, ...shard });
|
|
113
|
+
} catch (_) { failures.push({ source, sessionId: session.sessionId || '', code: 'index-source-unavailable' }); }
|
|
114
|
+
job.processed++; job.failures = failures;
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
if (job.cancelled) throw new Error('index-cancelled');
|
|
118
|
+
store.write({ version: 1, items: entries, failures, coverage, updatedAt: new Date().toISOString() }, snapshot.revision);
|
|
119
|
+
}
|
|
120
|
+
async function pruneShards() {
|
|
121
|
+
if (activeSearches || !fs.existsSync(directory)) return;
|
|
122
|
+
const keep = new Set(store.read().value.items.flatMap((item) => [item.shard, item.shard + '.bloom']));
|
|
123
|
+
for (const name of await fs.promises.readdir(directory)) {
|
|
124
|
+
if (/^[a-f0-9]{64}\.jsonl(?:\.bloom)?$/.test(name) && !keep.has(name)) await fs.promises.unlink(path.join(directory, name));
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
function start(params = {}) {
|
|
128
|
+
if (job.status === 'running') throw new Error('index-busy');
|
|
129
|
+
if (params.rebuild !== undefined && typeof params.rebuild !== 'boolean') throw new Error('index-input-invalid');
|
|
130
|
+
if (params.source && params.source !== 'all' && !SOURCES.includes(params.source)) throw new Error('index-source-invalid');
|
|
131
|
+
if (params.limit !== undefined && (!Number.isSafeInteger(params.limit) || params.limit < 1 || params.limit > MAX_DISCOVERY_LIMIT)) throw new Error('index-input-invalid');
|
|
132
|
+
job = { status: 'running', processed: 0, candidates: 0, failures: [], cancelled: false };
|
|
133
|
+
activePromise = refresh(params).finally(pruneShards).then(() => { job.status = job.failures.length ? 'partial' : 'success'; }).catch((error) => { job.status = job.cancelled ? 'cancelled' : 'failed';
|
|
134
|
+
job.errorCode = /^index-/.test(error.message) ? error.message : 'index-refresh-failed'; });
|
|
135
|
+
return status();
|
|
136
|
+
}
|
|
137
|
+
function cancel() { if (job.status === 'running') job.cancelled = true; return status(); }
|
|
138
|
+
async function search(params = {}) {
|
|
139
|
+
const query = String(params.query || '').trim().toLowerCase();
|
|
140
|
+
if (!query) throw new Error('index-query-empty');
|
|
141
|
+
const tokens = query.split(/\s+/).filter(Boolean);
|
|
142
|
+
const snapshot = store.read().value;
|
|
143
|
+
const items = snapshot.items.filter((item) => (!params.source || params.source === 'all' || item.source === params.source)
|
|
144
|
+
&& (!params.project || projectKey(item.cwd) === projectKey(params.project)));
|
|
145
|
+
const results = [];
|
|
146
|
+
const failures = [...snapshot.failures];
|
|
147
|
+
let scanned = 0;
|
|
148
|
+
let truncated = false;
|
|
149
|
+
activeSearches++;
|
|
150
|
+
try {
|
|
151
|
+
for (const session of items) {
|
|
152
|
+
if (!/^[a-f0-9]{64}\.jsonl$/.test(session.shard)) throw new Error('feature-store-invalid');
|
|
153
|
+
try {
|
|
154
|
+
const bloomPath = path.join(directory, session.shard + '.bloom');
|
|
155
|
+
if (fs.existsSync(bloomPath)) {
|
|
156
|
+
const bloom = await fs.promises.readFile(bloomPath);
|
|
157
|
+
const absent = (token) => {
|
|
158
|
+
for (let index = 0; index + 1 < token.length; index++) {
|
|
159
|
+
const bit = (token.charCodeAt(index) * 31 + token.charCodeAt(index + 1)) % (BLOOM_BYTES * 8);
|
|
160
|
+
if (!(bloom[bit >> 3] & (1 << (bit & 7)))) return true;
|
|
161
|
+
}
|
|
162
|
+
return false;
|
|
163
|
+
};
|
|
164
|
+
const skip = params.mode === 'any' ? tokens.every(absent) : tokens.some(absent);
|
|
165
|
+
if (bloom.length === BLOOM_BYTES && skip) { scanned++; continue; }
|
|
166
|
+
}
|
|
167
|
+
for await (const node of readShard(path.join(directory, session.shard))) {
|
|
168
|
+
if (params.role && params.role !== 'all' && node.role !== params.role) continue;
|
|
169
|
+
const text = `${params.scope === 'all' ? session.title : ''}\n${node.text}`.toLowerCase();
|
|
170
|
+
const hit = params.mode === 'any' ? tokens.some((token) => text.includes(token)) : tokens.every((token) => text.includes(token));
|
|
171
|
+
if (!hit) continue;
|
|
172
|
+
if (results.length >= MAX_RESULTS) { truncated = true; break; }
|
|
173
|
+
const position = node.text.toLowerCase().indexOf(tokens[0]);
|
|
174
|
+
results.push({ session, nodeId: node.id, textHash: node.textHash, role: node.role,
|
|
175
|
+
snippet: node.text.slice(Math.max(0, position - SNIPPET_LENGTH / 4), Math.max(0, position - SNIPPET_LENGTH / 4) + SNIPPET_LENGTH),
|
|
176
|
+
before: node.before, after: node.after });
|
|
177
|
+
}
|
|
178
|
+
scanned++;
|
|
179
|
+
} catch (_) { failures.push({ source: session.source, sessionId: session.sessionId, code: 'index-shard-unavailable' }); }
|
|
180
|
+
if (truncated) break;
|
|
181
|
+
}
|
|
182
|
+
} finally { activeSearches--; }
|
|
183
|
+
return { results, truncated, scanned, candidates: items.length, failures, coverage: snapshot.coverage,
|
|
184
|
+
complete: scanned === items.length && !failures.length && !truncated, scope: 'indexed-discovered-candidates' };
|
|
185
|
+
}
|
|
186
|
+
return { status, start, cancel, search, wait: () => activePromise };
|
|
187
|
+
}
|
|
188
|
+
module.exports = { createSessionSearchIndex, SOURCES };
|
package/lib/thread-handoff.js
CHANGED
|
@@ -57,6 +57,14 @@ async function createHandoff(params, options = {}) {
|
|
|
57
57
|
const handoff = { id, threadId: params.threadId, target: params.target, createdAt, card,
|
|
58
58
|
acknowledgement: { command: `codexmate thread ack ${params.threadId} --handoff ${id} --agent ${params.target} --evidence <读取证据>`,
|
|
59
59
|
instruction: '目标 Agent 实际读取本卡后,使用原始 threadId、id、target 调用 thread ack;evidence 填写目标会话或检索记录标识。此确认为目标自报,非自动验证。' } };
|
|
60
|
+
if (params.evidence !== undefined) {
|
|
61
|
+
if (!Array.isArray(params.evidence) || params.evidence.length > 100 || params.evidence.some((item) =>
|
|
62
|
+
!item || typeof item.nodeId !== 'string' || typeof item.source !== 'string' || typeof item.excerpt !== 'string'
|
|
63
|
+
|| item.excerpt.length > 800 || !/^[a-f0-9]{64}$/.test(item.textHash || ''))) throw new Error('交接证据格式无效');
|
|
64
|
+
handoff.evidence = params.evidence.map((item) => ({ source: item.source, sessionId: item.sessionId || '',
|
|
65
|
+
nodeId: item.nodeId, textHash: item.textHash, excerpt: item.excerpt, status: item.status,
|
|
66
|
+
origin: 'user_reviewed_selection' }));
|
|
67
|
+
}
|
|
60
68
|
fs.mkdirSync(directory, { recursive: true });
|
|
61
69
|
const filePath = path.join(directory, `${id}.json`);
|
|
62
70
|
fs.writeFileSync(filePath, JSON.stringify(handoff, null, 2) + '\n', { flag: 'wx', mode: 0o600 });
|