@chemx/starter-kit 26.11.14-1261 → 26.11.15-614
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/cli/commands/cmd-router.js +3 -1
- package/cli/commands-schema-commit.js +3 -2
- package/cli/commands-schema-search.js +1 -0
- package/cli/commit/commit-args.js +5 -4
- package/cli/commit/commit-hunks.js +108 -0
- package/cli/commit/commit-run.js +33 -2
- package/cli/generator-indexer.js +3 -2
- package/cli/index-seed.js +1 -0
- package/cli/search-args.js +1 -1
- package/cli/search-ast-module.js +26 -3
- package/cli/search-ast.js +4 -2
- package/cli/search-commands.js +44 -0
- package/cli/search-db.js +1 -0
- package/cli/search-index-meta.js +8 -3
- package/cli/search-index-write.js +5 -2
- package/cli/search-literal.js +24 -6
- package/cli/search-queries.js +19 -0
- package/cli/search-schema-ddl.js +11 -0
- package/cli/search-sync-rows.js +2 -2
- package/cli/search.js +8 -3
- package/cli/team/team-db-feed.js +6 -0
- package/cli/team/team-db-task-helpers.js +9 -6
- package/cli/ui-api-index.js +39 -0
- package/cli/ui-handlers.js +17 -20
- package/cli/ui-html.js +17 -4
- package/cli/ui-index.html +298 -107
- package/cli/ui-page/components/00-core.css +10 -0
- package/cli/ui-page/components/00-core.js +78 -0
- package/cli/ui-page/components/xo-agent-profile.js +6 -0
- package/cli/ui-page/components/xo-avatar.js +17 -0
- package/cli/ui-page/components/xo-composer.js +5 -0
- package/cli/ui-page/components/xo-notification-bell.js +5 -0
- package/cli/ui-page/components/xo-post-card.js +20 -0
- package/cli/ui-page/components/xo-post-permalink.js +5 -0
- package/cli/ui-page/components/xo-post-thread.js +5 -0
- package/cli/ui-page/components/xo-timeline.js +52 -0
- package/cli/ui-page/components/xo-today-card.js +5 -0
- package/cli/ui-paging-agents.js +34 -0
- package/cli/ui-paging-feed.js +14 -0
- package/cli/ui-paging-task-where.js +63 -0
- package/cli/ui-paging-tasks.js +68 -0
- package/cli/ui-paging.js +35 -0
- package/cli/ui-server-routes.js +5 -4
- package/cli/ui-server.js +12 -0
- package/cli/ui-social-digest.js +12 -0
- package/cli/ui-social-feed.js +12 -0
- package/cli/ui-social-mentions.js +12 -0
- package/cli/ui-social-notify.js +12 -0
- package/cli/ui-social-posts.js +12 -0
- package/cli/ui-social-profile.js +12 -0
- package/cli/ui-social-routes.js +21 -0
- package/cli/ui-social-threads.js +12 -0
- package/package.json +1 -1
|
@@ -402,8 +402,10 @@ export const dispatchCommand = async (firstArg, rawArgs, runAudit, getPackageVer
|
|
|
402
402
|
const hostArg = rawArgs.find((a) => a.startsWith('--host='));
|
|
403
403
|
const host = hostArg ? hostArg.split('=')[1] : undefined;
|
|
404
404
|
const isDev = rawArgs.includes('--dev') || rawArgs.includes('-d') || process.env.CHEMX_UI_DEV === '1';
|
|
405
|
+
const tokenArg = rawArgs.find((a) => a.startsWith('--token='));
|
|
406
|
+
const token = (tokenArg ? tokenArg.split('=')[1] : undefined) || process.env.CHEMX_UI_TOKEN;
|
|
405
407
|
const allowHosts = rawArgs.filter((a) => a.startsWith('--allow-host=')).flatMap((a) => a.slice('--allow-host='.length).split(',')).filter(Boolean);
|
|
406
|
-
const { server } = await startUiServer({ port, host, allowHosts, dev: isDev, isCli: true, cwd: process.cwd() });
|
|
408
|
+
const { server } = await startUiServer({ port, host, token, allowHosts, dev: isDev, isCli: true, cwd: process.cwd() });
|
|
407
409
|
await new Promise((resolve) => {
|
|
408
410
|
const shutdown = () => {
|
|
409
411
|
server.close(() => resolve());
|
|
@@ -5,7 +5,7 @@ export const COMMIT_COMMANDS = [
|
|
|
5
5
|
aliases: [],
|
|
6
6
|
group: 'wrappers',
|
|
7
7
|
brief: 'Commit only the listed files, lease-checked',
|
|
8
|
-
usage: 'chemx commit <files...> -m <subject> [-m <body>] [--task=<id> | --no-task=<reason>] [--board=<dir>] [--release] [--skip-ci | --no-skip-ci] [--json] [--as=@handle]',
|
|
8
|
+
usage: 'chemx commit <files...> [--hunks=<file>:<n,m-k>] -m <subject> [-m <body>] [--task=<id> | --no-task=<reason>] [--board=<dir>] [--release] [--skip-ci | --no-skip-ci] [--json] [--as=@handle]',
|
|
9
9
|
summary: 'Path-limited git commit that checks leases and the task id, then records the commit on the task.',
|
|
10
10
|
description: 'Stages only the listed files and commits only them; the repository pre-commit hook always runs. Refuses -a/--all, --no-verify, an empty file list, other already-staged paths, a file under another handle\'s live lease, and a commit with neither a task id (#<id> in the message or --task) nor --no-task=<reason>. The task id is checked, and the commit recorded, on the board in this order: --board=<dir>; the board where the committer claimed that task (`chemx team task claim` leaves a pointer, so a repo whose directory resolves to another board still finds it); the directory\'s own board. A refusal for an unknown id names every board it looked in. --no-task never scans the subject for a #id. Adds [skip ci] only while HEAD is the default branch (main, master or the branch origin/HEAD names) and .chemxrc has commit.skipCi; --skip-ci forces it on any branch, --no-skip-ci drops it. Adds a Co-Authored-By trailer only when CHEMX_COAUTHOR or commit.coAuthor names one. Retries a held .git/index.lock up to 6 times over about 20 s. A failed gate leaves the listed files staged. Lease checks and the task event are best effort: a lease taken after the check is not seen, and an unavailable team db skips the event.',
|
|
11
11
|
flags: [
|
|
@@ -13,12 +13,13 @@ export const COMMIT_COMMANDS = [
|
|
|
13
13
|
{ flag: '--task=<id>', desc: 'Task the commit belongs to; added to the subject as (#<id>) when missing' },
|
|
14
14
|
{ flag: '--no-task=<reason>', desc: 'Commit without a task; the reason is recorded in the body and the feed, and the subject is not scanned for #ids' },
|
|
15
15
|
{ flag: '--board=<dir>', desc: 'Check the task id and record the commit on the board of this directory, whatever the claim or cwd say' },
|
|
16
|
+
{ flag: '--hunks=<file>:<n,a-b>', desc: 'Commit only these hunks of a file (numbered as git diff -U0 HEAD -- <file> lists them, from 1); repeatable. The file is then also a listed file. The rest of it stays uncommitted, and nothing others staged rides along' },
|
|
16
17
|
{ flag: '--release', desc: 'Release your own leases on the committed files after a successful commit' },
|
|
17
18
|
{ flag: '--skip-ci', desc: 'Add [skip ci] to the subject on any branch (default: only commit.skipCi on the default branch)' },
|
|
18
19
|
{ flag: '--no-skip-ci', desc: 'Never add [skip ci], even on the default branch with commit.skipCi set' },
|
|
19
20
|
{ flag: '--as=@handle', desc: 'Committer handle (default: CHEMX_AGENT_ID, else a session handle)' },
|
|
20
21
|
{ flag: '--json', desc: 'Print the result as one object' }
|
|
21
22
|
],
|
|
22
|
-
examples: ['chemx commit src/a.js src/b.js -m "fix(a): handle empty input (#42)"', 'chemx commit docs/x.md -m "docs: x" --task=42 --release', 'chemx commit notes.txt -m "chore: notes" --no-task="one-off cleanup"', 'chemx commit plugin/a.php -m "fix: a (#42)" --board=../app']
|
|
23
|
+
examples: ['chemx commit src/shared.ts --hunks=src/shared.ts:1,3-4 -m "feat: my part of shared (#42)"', 'chemx commit src/a.js src/b.js -m "fix(a): handle empty input (#42)"', 'chemx commit docs/x.md -m "docs: x" --task=42 --release', 'chemx commit notes.txt -m "chore: notes" --no-task="one-off cleanup"', 'chemx commit plugin/a.php -m "fix: a (#42)" --board=../app']
|
|
23
24
|
}
|
|
24
25
|
];
|
|
@@ -13,6 +13,7 @@ export const SEARCH_COMMANDS = [
|
|
|
13
13
|
{ flag: '--columnar', desc: 'Token-compact columnar format (cols/rows) for agent pipelines' },
|
|
14
14
|
{ flag: '-i, --inspect', desc: 'Inspect props and hooks without full source' },
|
|
15
15
|
{ flag: '--tier=<tier>', desc: 'Filter by tier: atom, molecule, organism, hook, view' },
|
|
16
|
+
{ flag: '--uses, --usages', desc: 'Every indexed use of the name as path:line:text (grep-style, from the index; no grep)' },
|
|
16
17
|
{ flag: '--blast-radius, --blast, --impact', desc: 'Map direct consumers, transitive dependents and impacted tiers' },
|
|
17
18
|
{ flag: '--trace', desc: 'Forward call trace: downstream functions invoked by target' },
|
|
18
19
|
{ flag: '--backtrace', desc: 'Reverse backtrace: upstream callers leading to target' },
|
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
* validator can refuse it by name instead of passing it on to git.
|
|
5
5
|
*/
|
|
6
6
|
|
|
7
|
-
const VALUE_FLAGS = new Set(['-m', '--message', '--task', '--no-task', '--as', '--board']);
|
|
7
|
+
const VALUE_FLAGS = new Set(['-m', '--message', '--task', '--no-task', '--as', '--board', '--hunks']);
|
|
8
8
|
const KNOWN_FLAGS = new Set(['--release', '--json', '-a', '--all', '--no-verify', '-n', '--skip-ci', '--no-skip-ci']);
|
|
9
9
|
|
|
10
10
|
// Splits `--flag=value` into its name and value; a bare token has value undefined.
|
|
@@ -16,7 +16,7 @@ const splitToken = (token) => {
|
|
|
16
16
|
};
|
|
17
17
|
|
|
18
18
|
const emptyParsed = () => ({
|
|
19
|
-
files: [], messages: [], taskId: null, noTask: null, as: null, board: null,
|
|
19
|
+
files: [], hunks: [], messages: [], taskId: null, noTask: null, as: null, board: null,
|
|
20
20
|
release: false, json: false, all: false, skipVerify: false, skipCi: false, noSkipCi: false, unknown: [], missingValue: []
|
|
21
21
|
});
|
|
22
22
|
|
|
@@ -26,7 +26,8 @@ const VALUE_SETTERS = {
|
|
|
26
26
|
'--task': (parsed, value) => { parsed.taskId = String(value).replace(/^#/, ''); },
|
|
27
27
|
'--no-task': (parsed, value) => { parsed.noTask = value; },
|
|
28
28
|
'--as': (parsed, value) => { parsed.as = value; },
|
|
29
|
-
'--board': (parsed, value) => { parsed.board = value; }
|
|
29
|
+
'--board': (parsed, value) => { parsed.board = value; },
|
|
30
|
+
'--hunks': (parsed, value) => parsed.hunks.push(value)
|
|
30
31
|
};
|
|
31
32
|
|
|
32
33
|
const BOOLEAN_SETTERS = {
|
|
@@ -45,7 +46,7 @@ const applyBooleanFlag = (parsed, name) => BOOLEAN_SETTERS[name](parsed);
|
|
|
45
46
|
|
|
46
47
|
/**
|
|
47
48
|
* @param {string[]} args Everything after `chemx commit`.
|
|
48
|
-
* @returns {{ files: string[], messages: string[], taskId: string|null, noTask: string|null, as: string|null,
|
|
49
|
+
* @returns {{ files: string[], hunks: string[], messages: string[], taskId: string|null, noTask: string|null, as: string|null,
|
|
49
50
|
* board: string|null, release: boolean, json: boolean, all: boolean, skipVerify: boolean, skipCi: boolean,
|
|
50
51
|
* noSkipCi: boolean, unknown: string[], missingValue: string[] }}
|
|
51
52
|
*/
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Chemical X Protocol: `chemx commit --hunks=<file>:<n,m-k>` commits only some hunks of a file (#7599).
|
|
3
|
+
* A file other sessions are also editing cannot be committed whole without taking their half-finished
|
|
4
|
+
* work. The hunks are numbered as `git diff -U0 HEAD -- <file>` lists them (1-based). The commit is built on a private index
|
|
5
|
+
* that starts from HEAD, so only the listed files can differ in it and nothing another handle staged rides
|
|
6
|
+
* along. Not guaranteed: hunks are cut at zero context, so two changes on adjoining lines are one hunk;
|
|
7
|
+
* a spec that selects half of a change a later hunk depends on commits that half as written.
|
|
8
|
+
*/
|
|
9
|
+
import fs from 'node:fs';
|
|
10
|
+
import os from 'node:os';
|
|
11
|
+
import path from 'node:path';
|
|
12
|
+
import { spawnSync } from 'node:child_process';
|
|
13
|
+
import { runGit } from './commit-git.js';
|
|
14
|
+
|
|
15
|
+
const SPEC_PART = /^(\d+)(?:-(\d+))?$/;
|
|
16
|
+
|
|
17
|
+
/** `1,3-4` to [1, 3, 4]; null when any part is not a positive number or a range that runs up. */
|
|
18
|
+
export const parseRanges = (spec) => {
|
|
19
|
+
const numbers = [];
|
|
20
|
+
for (const part of spec.split(',')) {
|
|
21
|
+
const found = SPEC_PART.exec(part.trim());
|
|
22
|
+
if (!found) return null;
|
|
23
|
+
const from = Number(found[1]);
|
|
24
|
+
const to = found[2] === undefined ? from : Number(found[2]);
|
|
25
|
+
const isBackwards = from < 1 || to < from;
|
|
26
|
+
if (isBackwards) return null;
|
|
27
|
+
for (let at = from; at <= to; at += 1) numbers.push(at);
|
|
28
|
+
}
|
|
29
|
+
return numbers;
|
|
30
|
+
};
|
|
31
|
+
|
|
32
|
+
/** `--hunks` values to { file, numbers } entries and the messages for any that cannot be read. */
|
|
33
|
+
export const parseHunkSpecs = (raw) => {
|
|
34
|
+
const specs = [];
|
|
35
|
+
const errors = [];
|
|
36
|
+
for (const value of raw) {
|
|
37
|
+
const colon = value.lastIndexOf(':');
|
|
38
|
+
const file = colon > 0 ? value.slice(0, colon) : '';
|
|
39
|
+
const numbers = colon > 0 ? parseRanges(value.slice(colon + 1)) : null;
|
|
40
|
+
const isBad = file === '' || numbers === null;
|
|
41
|
+
if (isBad) errors.push(`Refused: --hunks=${value} is not <file>:<n[,n|a-b]> with hunk numbers from 1.`);
|
|
42
|
+
else specs.push({ file, numbers });
|
|
43
|
+
}
|
|
44
|
+
return { specs, errors };
|
|
45
|
+
};
|
|
46
|
+
|
|
47
|
+
/** A diff cut into its header lines and its hunks, each hunk with its own header and body. */
|
|
48
|
+
export const splitDiff = (diff) => {
|
|
49
|
+
const lines = diff.split('\n');
|
|
50
|
+
const firstHunk = lines.findIndex((line) => line.startsWith('@@'));
|
|
51
|
+
const hasNoHunks = firstHunk < 0;
|
|
52
|
+
if (hasNoHunks) return { header: lines, hunks: [] };
|
|
53
|
+
const hunks = [];
|
|
54
|
+
for (const line of lines.slice(firstHunk)) {
|
|
55
|
+
if (line.startsWith('@@')) hunks.push([line]);
|
|
56
|
+
else hunks[hunks.length - 1].push(line);
|
|
57
|
+
}
|
|
58
|
+
return { header: lines.slice(0, firstHunk), hunks };
|
|
59
|
+
};
|
|
60
|
+
|
|
61
|
+
/** The patch holding only the wanted hunks of one file, or the reasons it cannot be cut. */
|
|
62
|
+
export const patchFor = (root, spec) => {
|
|
63
|
+
const diff = runGit(root, ['diff', '-U0', '--no-color', '--no-ext-diff', 'HEAD', '--', spec.file]);
|
|
64
|
+
const { header, hunks } = splitDiff(diff.stdout);
|
|
65
|
+
const outOfRange = spec.numbers.filter((number) => number > hunks.length);
|
|
66
|
+
const isEmpty = hunks.length === 0;
|
|
67
|
+
if (isEmpty) return { errors: [`Refused: ${spec.file} has no changes against HEAD to take hunks from.`] };
|
|
68
|
+
if (outOfRange.length) return { errors: [`Refused: ${spec.file} has ${hunks.length} hunk(s) against HEAD; there is no hunk ${outOfRange.join(', ')}.`] };
|
|
69
|
+
const chosen = [...new Set(spec.numbers)].sort((a, b) => a - b).flatMap((number) => hunks[number - 1]);
|
|
70
|
+
return { patch: [...header, ...chosen].join('\n').replace(/\n*$/, '\n'), errors: [] };
|
|
71
|
+
};
|
|
72
|
+
|
|
73
|
+
const privateIndex = (root) => {
|
|
74
|
+
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'chemx-commit-index-'));
|
|
75
|
+
const hasHead = runGit(root, ['rev-parse', '--verify', '-q', 'HEAD']).status === 0;
|
|
76
|
+
return { dir, file: path.join(dir, 'index'), hasHead };
|
|
77
|
+
};
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Builds the index the commit is made from: HEAD, then the whole listed files, then the chosen hunks of
|
|
81
|
+
* the others. Returns the env to commit with and a cleanup, or the reasons it could not be built.
|
|
82
|
+
*/
|
|
83
|
+
export const buildHunkIndex = (root, files, specs, env) => {
|
|
84
|
+
const { dir, file, hasHead } = privateIndex(root);
|
|
85
|
+
const cleanup = () => fs.rmSync(dir, { recursive: true, force: true });
|
|
86
|
+
const indexEnv = { ...env, GIT_INDEX_FILE: file };
|
|
87
|
+
const fail = (errors) => { cleanup(); return { errors }; };
|
|
88
|
+
const reading = runGit(root, hasHead ? ['read-tree', 'HEAD'] : ['read-tree', '--empty'], indexEnv);
|
|
89
|
+
const isReadFailed = reading.status !== 0;
|
|
90
|
+
if (isReadFailed) return fail([`Failed: could not start a private index. ${reading.output.trim()}`]);
|
|
91
|
+
const partial = new Set(specs.map((spec) => spec.file));
|
|
92
|
+
const whole = files.filter((candidate) => !partial.has(candidate));
|
|
93
|
+
const adding = whole.length ? runGit(root, ['add', '--', ...whole], indexEnv) : { status: 0, output: '' };
|
|
94
|
+
const isAddFailed = adding.status !== 0;
|
|
95
|
+
if (isAddFailed) return fail([`Failed: git add did not complete. ${adding.output.trim()}`]);
|
|
96
|
+
for (const spec of specs) {
|
|
97
|
+
const cut = patchFor(root, spec);
|
|
98
|
+
const isCutFailed = cut.errors.length > 0;
|
|
99
|
+
if (isCutFailed) return fail(cut.errors);
|
|
100
|
+
const applied = spawnSync('git', ['apply', '--cached', '--unidiff-zero', '-'], { cwd: root, encoding: 'utf-8', env: indexEnv, input: cut.patch });
|
|
101
|
+
const isApplyFailed = applied.status !== 0;
|
|
102
|
+
if (isApplyFailed) return fail([`Failed: the chosen hunks of ${spec.file} did not apply. ${(applied.stderr ?? '').trim()}`]);
|
|
103
|
+
}
|
|
104
|
+
return { env: indexEnv, cleanup, errors: [] };
|
|
105
|
+
};
|
|
106
|
+
|
|
107
|
+
/** After the commit, the real index entries of the listed files are put level with the new HEAD. */
|
|
108
|
+
export const levelIndex = (root, files) => runGit(root, ['reset', '-q', '--', ...files]).status === 0;
|
package/cli/commit/commit-run.js
CHANGED
|
@@ -16,6 +16,7 @@ import { collectRefusals } from './commit-validate.js';
|
|
|
16
16
|
import { gatherFacts } from './commit-facts.js';
|
|
17
17
|
import { openCommitDb, recordCommit, releaseLeases } from './commit-record.js';
|
|
18
18
|
import { snapshotIndex, restoreIndex } from './commit-index.js';
|
|
19
|
+
import { buildHunkIndex, levelIndex, parseHunkSpecs } from './commit-hunks.js';
|
|
19
20
|
import {
|
|
20
21
|
gitRoot, stagedAmong, shortSha, hasPreCommitHook, gitWithRetry, compactFailure
|
|
21
22
|
} from './commit-git.js';
|
|
@@ -136,12 +137,19 @@ const routeToOwner = (parsed, cwd) => {
|
|
|
136
137
|
* @returns {Promise<{ ok: boolean, exitCode: number, lines: string[], refusals: string[], json: boolean, data?: object }>}
|
|
137
138
|
*/
|
|
138
139
|
export const runCommit = async (args, options = {}) => {
|
|
139
|
-
const
|
|
140
|
+
const parsedArgs = parseCommitArgs(args);
|
|
140
141
|
const startCwd = options.cwd ?? process.cwd();
|
|
142
|
+
const hunkParse = parseHunkSpecs(parsedArgs.hunks);
|
|
143
|
+
// A file named in --hunks is a listed file, whether or not it is also named plainly.
|
|
144
|
+
const hunkFiles = hunkParse.specs.map((spec) => spec.file);
|
|
145
|
+
const parsed = { ...parsedArgs, files: [...new Set([...parsedArgs.files, ...hunkFiles])], hunkSpecs: hunkParse.specs };
|
|
146
|
+
if (hunkParse.errors.length) return refused(hunkParse.errors, parsed);
|
|
141
147
|
const routed = parsed.files.length ? routeToOwner(parsed, startCwd) : { cwd: startCwd, files: parsed.files };
|
|
142
148
|
const isRefused = Boolean(routed.refusal);
|
|
143
149
|
if (isRefused) return refused(routed.refusal, parsed);
|
|
144
|
-
|
|
150
|
+
const moved = routed.files !== parsed.files;
|
|
151
|
+
const hunkSpecs = parsed.hunkSpecs.map((spec) => ({ ...spec, file: moved ? path.resolve(startCwd, spec.file) : spec.file }));
|
|
152
|
+
return commitInRepo({ ...parsed, files: routed.files, hunkSpecs }, routed.cwd, options);
|
|
145
153
|
};
|
|
146
154
|
|
|
147
155
|
const commitInRepo = async (parsed, cwd, options) => {
|
|
@@ -153,6 +161,8 @@ const commitInRepo = async (parsed, cwd, options) => {
|
|
|
153
161
|
const gitEnv = facts?.committer ? { ...env, CHEMX_AGENT_ID: facts.committer } : env;
|
|
154
162
|
const retry = { sleep: options.sleep, delaysMs: options.delaysMs, env: gitEnv };
|
|
155
163
|
const isPreflightClean = preflight.length === 0;
|
|
164
|
+
const hasHunks = isPreflightClean && parsed.hunkSpecs.length > 0;
|
|
165
|
+
if (hasHunks) return commitHunks({ parsed, cwd, root, facts, env, gitEnv, retry });
|
|
156
166
|
const snapshot = isPreflightClean ? snapshotIndex(root, facts.rel) : [];
|
|
157
167
|
const staging = isPreflightClean ? await stageFiles(root, facts.rel, retry) : { reasons: [], isFailure: false };
|
|
158
168
|
if (staging.isFailure) return failed(staging.reasons, parsed, { attempts: staging.added.attempts, lockHolder: staging.added.lockHolder });
|
|
@@ -167,3 +177,24 @@ const commitInRepo = async (parsed, cwd, options) => {
|
|
|
167
177
|
const data = afterCommit(root, cwd, facts, message, hasHook);
|
|
168
178
|
return { ok: true, exitCode: 0, refusals: [], json: parsed.json, lines: formatSuccessLines(data, parsed.release), data };
|
|
169
179
|
};
|
|
180
|
+
|
|
181
|
+
// A commit of chosen hunks: made on a private index that starts from HEAD, so only the listed files differ in it.
|
|
182
|
+
const commitHunks = async ({ parsed, cwd, root, facts, env, gitEnv, retry }) => {
|
|
183
|
+
const specs = parsed.hunkSpecs.map((spec) => ({ ...spec, file: path.relative(root, path.resolve(cwd, spec.file)) }));
|
|
184
|
+
const built = buildHunkIndex(root, facts.rel, specs, gitEnv);
|
|
185
|
+
const isBuildFailed = built.errors.length > 0;
|
|
186
|
+
if (isBuildFailed) return refused(built.errors, parsed);
|
|
187
|
+
const message = buildCommitMessage({ messages: parsed.messages, taskId: facts.taskId, noTask: parsed.noTask, config: facts.config, env, isSkipCi: facts.isSkipCi });
|
|
188
|
+
const hasHook = hasPreCommitHook(root);
|
|
189
|
+
const commitArgs = ['commit', '-m', message.subject, ...message.paragraphs.flatMap((paragraph) => ['-m', paragraph])];
|
|
190
|
+
const outcome = await gitWithRetry(root, commitArgs, { ...retry, env: built.env });
|
|
191
|
+
built.cleanup();
|
|
192
|
+
const isCommitFailed = outcome.status !== 0;
|
|
193
|
+
if (isCommitFailed) return failed(failureLines(outcome), parsed, { attempts: outcome.attempts, lockHolder: outcome.lockHolder });
|
|
194
|
+
const isLevel = levelIndex(root, facts.rel);
|
|
195
|
+
const data = afterCommit(root, cwd, facts, message, hasHook);
|
|
196
|
+
const lines = formatSuccessLines(data, parsed.release);
|
|
197
|
+
const hunkLines = [`hunks: ${specs.map((spec) => `${spec.file}:${spec.numbers.join(',')}`).join('; ')} (the rest of those files stays uncommitted)`];
|
|
198
|
+
const levelLines = isLevel ? [] : ['warning: could not put the index level with HEAD for the listed files (git reset -q -- <files>).'];
|
|
199
|
+
return { ok: true, exitCode: 0, refusals: [], json: parsed.json, lines: [...lines, ...hunkLines, ...levelLines], data };
|
|
200
|
+
};
|
package/cli/generator-indexer.js
CHANGED
|
@@ -10,7 +10,7 @@ export const parseFileAst = (absPath, relPath) => {
|
|
|
10
10
|
const lines = content.split('\n').length;
|
|
11
11
|
const chars = content.length;
|
|
12
12
|
const tier = resolveArchitectureTier(relPath);
|
|
13
|
-
const { symbols, props, hooks, imports } = extractAstMetadata(content, absPath);
|
|
13
|
+
const { symbols, props, hooks, imports, occurrences } = extractAstMetadata(content, absPath);
|
|
14
14
|
return {
|
|
15
15
|
path: relPath,
|
|
16
16
|
mtime: Math.floor(stat.mtimeMs),
|
|
@@ -21,7 +21,8 @@ export const parseFileAst = (absPath, relPath) => {
|
|
|
21
21
|
symbols,
|
|
22
22
|
props,
|
|
23
23
|
hooks,
|
|
24
|
-
imports
|
|
24
|
+
imports,
|
|
25
|
+
occurrences
|
|
25
26
|
};
|
|
26
27
|
};
|
|
27
28
|
|
package/cli/index-seed.js
CHANGED
|
@@ -30,6 +30,7 @@ const ROW_TABLES = [
|
|
|
30
30
|
{ table: 'props', pathColumn: 'file_path', columns: 'file_path, name, prop_type' },
|
|
31
31
|
{ table: 'hooks', pathColumn: 'file_path', columns: 'file_path, name' },
|
|
32
32
|
{ table: 'imports', pathColumn: 'importer_path', columns: 'importer_path, imported_symbol, source_module, resolved_path, line' },
|
|
33
|
+
{ table: 'occurrences', pathColumn: 'file_path', columns: 'file_path, name, line' },
|
|
33
34
|
{ table: 'embeddings', pathColumn: 'file_path', columns: 'file_path, target_type, target_name, vector, dimensions, model, updated_at' },
|
|
34
35
|
{ table: 'fts_index', pathColumn: 'file_path', columns: 'file_path, name, kind, tier, tokens' }
|
|
35
36
|
];
|
package/cli/search-args.js
CHANGED
|
@@ -13,7 +13,7 @@ const VALUE_FLAGS = new Map([
|
|
|
13
13
|
|
|
14
14
|
const BOOLEAN_FLAGS = new Set([
|
|
15
15
|
'--json', '-j', '--raw-json', '--no-columnar', '--columnar', '-g', '--literal', '-i', '--inspect',
|
|
16
|
-
'-l', '--lines', '--include-internal', '--reindex', '--blast-radius', '--blast', '--impact',
|
|
16
|
+
'-l', '--lines', '--include-internal', '--reindex', '--blast-radius', '--blast', '--impact', '--uses', '--usages',
|
|
17
17
|
'--trace', '--backtrace', '--semantic', '--hybrid', '--critical', '--progression', '--failing',
|
|
18
18
|
'--degraded', '--crystalline', '--clean', '--regex', '-F', '--fixed-strings', '--hidden',
|
|
19
19
|
'--full', '--help', '-h', '--ignore-case', '--bare', '-b', '-o', '--only-matching', '--unique', '--files-with-matches'
|
package/cli/search-ast-module.js
CHANGED
|
@@ -81,7 +81,23 @@ const collectTopLevel = (node, lineInfo, filePath, out) => {
|
|
|
81
81
|
|
|
82
82
|
const isDynamicImport = (node) => t.isCallExpression(node) && node.callee?.type === 'Import' && t.isStringLiteral(node.arguments[0]);
|
|
83
83
|
|
|
84
|
-
|
|
84
|
+
// An identifier that names a property, not a binding or a value: `a.b` (b), `{ b: 1 }` (b), `<X b="" />` (b).
|
|
85
|
+
// Shorthand `{ b }` is a real reference, so it is kept.
|
|
86
|
+
const isNonReferenceName = (node, parent) => {
|
|
87
|
+
if (!parent) return false;
|
|
88
|
+
const isMemberProperty = (t.isMemberExpression(parent) || t.isOptionalMemberExpression(parent)) && parent.property === node && !parent.computed;
|
|
89
|
+
const isObjectKey = (t.isObjectProperty(parent) || t.isObjectMethod(parent) || t.isClassProperty(parent) || t.isClassMethod(parent))
|
|
90
|
+
&& parent.key === node && !parent.computed && !parent.shorthand;
|
|
91
|
+
const isJsxAttributeName = t.isJSXAttribute(parent) && parent.name === node;
|
|
92
|
+
const isTypeMemberKey = (t.isTSPropertySignature(parent) || t.isTSMethodSignature(parent)) && parent.key === node && !parent.computed;
|
|
93
|
+
const isQualifiedRight = t.isTSQualifiedName(parent) && parent.right === node;
|
|
94
|
+
const isJsxMemberProperty = t.isJSXMemberExpression(parent) && parent.property === node;
|
|
95
|
+
return isMemberProperty || isObjectKey || isJsxAttributeName || isTypeMemberKey || isQualifiedRight || isJsxMemberProperty;
|
|
96
|
+
};
|
|
97
|
+
|
|
98
|
+
const isNameNode = (node) => t.isIdentifier(node) || t.isJSXIdentifier(node);
|
|
99
|
+
|
|
100
|
+
/** Extracts { symbols, props, hooks, imports, occurrences } from a Babel File AST. */
|
|
85
101
|
export const extractModuleMetadata = (ast, contentLines, filePath) => {
|
|
86
102
|
const signatureAt = (lineNo) => (contentLines[lineNo - 1] || '').trim();
|
|
87
103
|
const lineInfo = (node) => {
|
|
@@ -89,15 +105,22 @@ export const extractModuleMetadata = (ast, contentLines, filePath) => {
|
|
|
89
105
|
return { startLine, endLine: node.loc?.end.line || startLine, signature: signatureAt(startLine) };
|
|
90
106
|
};
|
|
91
107
|
const out = { symbols: [], props: [], imports: [], hooks: new Set() };
|
|
108
|
+
const occurrenceKeys = new Set();
|
|
92
109
|
for (const node of ast.program.body) collectTopLevel(node, lineInfo, filePath, out);
|
|
93
|
-
walkBabel(ast.program, (node) => {
|
|
110
|
+
walkBabel(ast.program, (node, parent) => {
|
|
94
111
|
if (isDynamicImport(node)) out.imports.push({ importedSymbol: 'default', sourceModule: node.arguments[0].value, line: node.loc?.start.line || 1 });
|
|
95
112
|
const isHookCall = t.isCallExpression(node) && t.isIdentifier(node.callee) && /^use[A-Z0-9]/.test(node.callee.name);
|
|
96
113
|
if (isHookCall) out.hooks.add(node.callee.name);
|
|
114
|
+
const isUse = isNameNode(node) && !isNonReferenceName(node, parent);
|
|
115
|
+
if (isUse) occurrenceKeys.add(`${node.name}\u0000${node.loc?.start.line || 1}`);
|
|
97
116
|
});
|
|
98
117
|
for (const sym of out.symbols) {
|
|
99
118
|
const isHookDefinition = /^use[A-Z0-9]/.test(sym.name);
|
|
100
119
|
if (isHookDefinition) out.hooks.add(sym.name);
|
|
101
120
|
}
|
|
102
|
-
|
|
121
|
+
const occurrences = [...occurrenceKeys].map((key) => {
|
|
122
|
+
const [name, line] = key.split('\u0000');
|
|
123
|
+
return { name, line: Number(line) };
|
|
124
|
+
});
|
|
125
|
+
return { symbols: out.symbols, props: out.props, imports: out.imports, hooks: [...out.hooks], occurrences };
|
|
103
126
|
};
|
package/cli/search-ast.js
CHANGED
|
@@ -172,7 +172,8 @@ const parseWithBlockFallback = (code, sfc, content) => {
|
|
|
172
172
|
const canSplit = inlineScripts.length > 1;
|
|
173
173
|
if (!canSplit) throw err;
|
|
174
174
|
const programs = inlineScripts.map((block) => parseModule(buildScriptOverlay(content, [block])));
|
|
175
|
-
|
|
175
|
+
// A typed Program node: walkBabel only visits nodes with a string `type`, so occurrences and hooks need it.
|
|
176
|
+
return { program: { type: 'Program', body: programs.flatMap((ast) => ast.program.body) } };
|
|
176
177
|
}
|
|
177
178
|
};
|
|
178
179
|
|
|
@@ -189,7 +190,8 @@ const extractSfcMetadata = (base, sfc, ast, filePath, contentLines) => {
|
|
|
189
190
|
symbols: [componentSymbol, ...base.symbols],
|
|
190
191
|
props: uniqueByName([...extractSfcProps(ast.program), ...base.props]),
|
|
191
192
|
hooks: base.hooks,
|
|
192
|
-
imports: [...base.imports, ...extractScriptSrcImports(sfc), ...extractTemplateComponentImports(sfc, localImportNames)]
|
|
193
|
+
imports: [...base.imports, ...extractScriptSrcImports(sfc), ...extractTemplateComponentImports(sfc, localImportNames)],
|
|
194
|
+
occurrences: base.occurrences
|
|
193
195
|
};
|
|
194
196
|
};
|
|
195
197
|
|
package/cli/search-commands.js
CHANGED
|
@@ -9,6 +9,7 @@ import { withUnsplitHint } from './args-unsplit-hint.js';
|
|
|
9
9
|
import {
|
|
10
10
|
findSymbolDefinition,
|
|
11
11
|
findSymbolReferences,
|
|
12
|
+
findOccurrences,
|
|
12
13
|
findFileDependencies,
|
|
13
14
|
findFileDependents,
|
|
14
15
|
queryViolations,
|
|
@@ -94,6 +95,49 @@ export const handleDefCommand = (db, targetSymbol, { index = null, isJson = fals
|
|
|
94
95
|
return payload;
|
|
95
96
|
};
|
|
96
97
|
|
|
98
|
+
// `chemx q <name> --uses`: every indexed use of a name, as grep-style `path:line:text` records.
|
|
99
|
+
// Records go to stdout alone (pipe-safe, same bytes shape as `grep -rn`); the summary goes to stderr.
|
|
100
|
+
const USES_LINE_CAP = 1000;
|
|
101
|
+
const readLineAt = (lines, lineNo) => {
|
|
102
|
+
const raw = lines[lineNo - 1] ?? '';
|
|
103
|
+
const clean = raw.replace(/\r$/, '');
|
|
104
|
+
return clean.length > USES_LINE_CAP ? clean.slice(0, USES_LINE_CAP) : clean;
|
|
105
|
+
};
|
|
106
|
+
|
|
107
|
+
export const handleUsesCommand = (db, name, { index = null, isJson = false, isCli = true, root = process.cwd(), limit = 50 } = {}) => {
|
|
108
|
+
const found = findOccurrences(db, name, { limit });
|
|
109
|
+
if (found.isMissing) {
|
|
110
|
+
process.stderr.write('index has no occurrences table (built before v3); run `chemx q <name> --uses --reindex` from a writable checkout\n');
|
|
111
|
+
if (isCli) process.exit(3);
|
|
112
|
+
return { symbol: name, total: 0, files: 0, shown: 0, truncated: false, records: [], isMissing: true };
|
|
113
|
+
}
|
|
114
|
+
const linesByFile = new Map();
|
|
115
|
+
const linesOf = (filePath) => {
|
|
116
|
+
if (!linesByFile.has(filePath)) {
|
|
117
|
+
let content = '';
|
|
118
|
+
try { content = fs.readFileSync(path.join(root, filePath), 'utf8'); } catch (err) { debugNote.warn('read occurrence file', err); }
|
|
119
|
+
linesByFile.set(filePath, content.split('\n'));
|
|
120
|
+
}
|
|
121
|
+
return linesByFile.get(filePath);
|
|
122
|
+
};
|
|
123
|
+
const records = found.rows.map((row) => ({ path: row.filePath, line: row.line, text: readLineAt(linesOf(row.filePath), row.line) }));
|
|
124
|
+
const payload = { symbol: name, total: found.total, files: found.files, shown: records.length, truncated: found.total > records.length, records };
|
|
125
|
+
|
|
126
|
+
if (isJson) {
|
|
127
|
+
process.stdout.write(JSON.stringify(withIndex(payload, index)) + '\n');
|
|
128
|
+
if (isCli) process.exit();
|
|
129
|
+
return payload;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
for (const rec of records) process.stdout.write(`${rec.path}:${rec.line}:${rec.text}\n`);
|
|
133
|
+
const summary = found.total === 0
|
|
134
|
+
? `no indexed uses of "${name}"`
|
|
135
|
+
: `${found.total} uses of "${name}" in ${found.files} files${payload.truncated ? ` (showing ${records.length})` : ''}`;
|
|
136
|
+
process.stderr.write(`${summary}\n`);
|
|
137
|
+
if (isCli) process.exit();
|
|
138
|
+
return payload;
|
|
139
|
+
};
|
|
140
|
+
|
|
97
141
|
export const handleRefsCommand = (db, targetSymbol, { index = null, isJson = false, isCli = true } = {}) => {
|
|
98
142
|
const refs = findSymbolReferences(db, targetSymbol);
|
|
99
143
|
const payload = {
|
package/cli/search-db.js
CHANGED
package/cli/search-index-meta.js
CHANGED
|
@@ -5,9 +5,10 @@ import { debugNote } from './search-debug.js';
|
|
|
5
5
|
|
|
6
6
|
// Bump whenever the extractor, module resolver, ignore rules or tier rules change meaning.
|
|
7
7
|
// v2: version stamping, anchored directory exclusions, root-relative module resolution.
|
|
8
|
-
|
|
8
|
+
// v3: identifier occurrences table (q --uses), filled from the same Babel pass as the symbols.
|
|
9
|
+
export const INDEX_VERSION = 3;
|
|
9
10
|
|
|
10
|
-
const INDEX_ROW_TABLES = ['symbols', 'props', 'hooks', 'imports', 'embeddings', 'fts_index', 'files'];
|
|
11
|
+
const INDEX_ROW_TABLES = ['symbols', 'props', 'hooks', 'imports', 'occurrences', 'embeddings', 'fts_index', 'files'];
|
|
11
12
|
|
|
12
13
|
export const readIndexMeta = (db) => {
|
|
13
14
|
const meta = { version: null, scope: null, syncedAt: null };
|
|
@@ -58,7 +59,11 @@ export const ensureIndexVersion = (db) => {
|
|
|
58
59
|
return isForeign ? { reset: false, foreign: true, previousVersion: meta.version, droppedFiles: 0 } : { reset: false, previousVersion: meta.version, droppedFiles: 0 };
|
|
59
60
|
}
|
|
60
61
|
const droppedFiles = countIndexedFiles(db);
|
|
61
|
-
|
|
62
|
+
// A table added in a later version may be missing from an old file until its schema runs; skip it then.
|
|
63
|
+
for (const table of INDEX_ROW_TABLES) {
|
|
64
|
+
const isPresent = Boolean(db.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = ?").get(table));
|
|
65
|
+
if (isPresent) db.exec(`DELETE FROM ${table};`);
|
|
66
|
+
}
|
|
62
67
|
db.exec("DELETE FROM index_meta WHERE key IN ('scope', 'syncedAt');");
|
|
63
68
|
writeIndexMeta(db, { version: INDEX_VERSION });
|
|
64
69
|
db.exec('COMMIT;');
|
|
@@ -19,6 +19,8 @@ const SQL = {
|
|
|
19
19
|
deleteImports: 'DELETE FROM imports WHERE importer_path = ?',
|
|
20
20
|
deleteEmbeddings: 'DELETE FROM embeddings WHERE file_path = ?',
|
|
21
21
|
deleteFts: 'DELETE FROM fts_index WHERE file_path = ?',
|
|
22
|
+
deleteOccurrences: 'DELETE FROM occurrences WHERE file_path = ?',
|
|
23
|
+
insertOccurrence: 'INSERT INTO occurrences (file_path, name, line) VALUES (?, ?, ?)',
|
|
22
24
|
insertFile: 'INSERT INTO files (path, mtime, size, tier, lines, chars, extractor_version, content_hash, synced_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)',
|
|
23
25
|
insertSymbol: 'INSERT INTO symbols (file_path, name, kind, is_export, start_line, end_line, signature) VALUES (?, ?, ?, ?, ?, ?, ?)',
|
|
24
26
|
insertProp: 'INSERT INTO props (file_path, name, prop_type) VALUES (?, ?, ?)',
|
|
@@ -46,7 +48,7 @@ export const withIndexTransaction = (db, callback, maxRetries = 5) => {
|
|
|
46
48
|
// Explicit deletes (not only ON DELETE CASCADE) so rows go even when foreign_keys is off.
|
|
47
49
|
export const deleteFileRows = (db, filePath) => {
|
|
48
50
|
const s = statementsFor(db);
|
|
49
|
-
for (const name of ['deleteSymbols', 'deleteProps', 'deleteHooks', 'deleteImports', 'deleteEmbeddings', 'deleteFts', 'deleteFile']) {
|
|
51
|
+
for (const name of ['deleteSymbols', 'deleteProps', 'deleteHooks', 'deleteImports', 'deleteOccurrences', 'deleteEmbeddings', 'deleteFts', 'deleteFile']) {
|
|
50
52
|
s[name].run(filePath);
|
|
51
53
|
}
|
|
52
54
|
};
|
|
@@ -65,7 +67,7 @@ const insertEmbeddings = (s, filePath, mainName, tier, tokensText, symbols) => {
|
|
|
65
67
|
|
|
66
68
|
const writeFileRows = (db, record) => {
|
|
67
69
|
const s = statementsFor(db);
|
|
68
|
-
const { path: filePath, mtime, size, tier, lines, chars, symbols = [], props = [], hooks = [], imports = [] } = record;
|
|
70
|
+
const { path: filePath, mtime, size, tier, lines, chars, symbols = [], props = [], hooks = [], imports = [], occurrences = [] } = record;
|
|
69
71
|
const root = record.root || process.cwd();
|
|
70
72
|
|
|
71
73
|
deleteFileRows(db, filePath);
|
|
@@ -81,6 +83,7 @@ const writeFileRows = (db, record) => {
|
|
|
81
83
|
const resolved = resolveModulePath(filePath, imp.sourceModule, root);
|
|
82
84
|
s.insertImport.run(filePath, imp.importedSymbol, imp.sourceModule, resolved, imp.line || 1);
|
|
83
85
|
}
|
|
86
|
+
for (const occ of occurrences) s.insertOccurrence.run(filePath, occ.name, occ.line || 1);
|
|
84
87
|
|
|
85
88
|
const tokensText = buildFtsTokens({ symbols, props, hooks, imports, filePath });
|
|
86
89
|
const mainName = symbols.find((sym) => sym.isExport)?.name || path.basename(filePath);
|
package/cli/search-literal.js
CHANGED
|
@@ -180,10 +180,28 @@ const searchWithRipgrep = (root, scopeDirs, options, collect) => {
|
|
|
180
180
|
return stats;
|
|
181
181
|
};
|
|
182
182
|
|
|
183
|
+
// Literal-search backends. A backend is { search(root, scopeDirs, options, collect) -> { filesSearched,
|
|
184
|
+
// skippedBinary, skippedLarge }, isAvailable(), isBacktracking }. Every backend must call collect() with the
|
|
185
|
+
// same match shape, so the report, bare, -l, -o and --json renderers work unchanged.
|
|
186
|
+
// Default pick: the first registered backend that is available (rg, then js). CHEMX_LITERAL_ENGINE or
|
|
187
|
+
// the engine option names one explicitly; an unknown or unavailable name falls back to the default.
|
|
188
|
+
const LITERAL_BACKENDS = new Map();
|
|
189
|
+
export const registerLiteralBackend = (name, { search, isAvailable = () => true, isBacktracking = false }) => {
|
|
190
|
+
LITERAL_BACKENDS.set(name, { search, isAvailable, isBacktracking });
|
|
191
|
+
};
|
|
192
|
+
export const literalBackendNames = () => [...LITERAL_BACKENDS.keys()];
|
|
193
|
+
registerLiteralBackend('rg', { search: searchWithRipgrep, isAvailable: isRipgrepAvailable, isBacktracking: false });
|
|
194
|
+
registerLiteralBackend('js', { search: searchWithJs, isBacktracking: true });
|
|
195
|
+
|
|
183
196
|
const resolveEngine = (requested) => {
|
|
184
|
-
const
|
|
185
|
-
|
|
186
|
-
|
|
197
|
+
const forced = requested || process.env.CHEMX_LITERAL_ENGINE || null;
|
|
198
|
+
const forcedBackend = forced ? LITERAL_BACKENDS.get(forced) : null;
|
|
199
|
+
const isForcedAvailable = Boolean(forcedBackend) && forcedBackend.isAvailable();
|
|
200
|
+
if (isForcedAvailable) return forced;
|
|
201
|
+
for (const [name, backend] of LITERAL_BACKENDS) {
|
|
202
|
+
if (backend.isAvailable()) return name;
|
|
203
|
+
}
|
|
204
|
+
return 'js';
|
|
187
205
|
};
|
|
188
206
|
|
|
189
207
|
// Returns { engine, filesSearched, filesMatched, files (every matched path), totalMatches, matches (<= limit),
|
|
@@ -202,9 +220,9 @@ export const runLiteralSearch = ({ root, scopeDirs = ['.'], pattern, isRegex = f
|
|
|
202
220
|
if (hasRoom) matches.push(match);
|
|
203
221
|
};
|
|
204
222
|
const chosen = resolveEngine(engine);
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
const stats = search(root, scopeDirs, options, collect);
|
|
223
|
+
const backend = LITERAL_BACKENDS.get(chosen);
|
|
224
|
+
if (isRegex) assertRegexSupported(pattern, { isBacktracking: backend.isBacktracking });
|
|
225
|
+
const stats = backend.search(root, scopeDirs, options, collect);
|
|
208
226
|
return {
|
|
209
227
|
engine: chosen, filesSearched: stats.filesSearched, filesMatched: matchedFiles.size, files: [...matchedFiles], totalMatches,
|
|
210
228
|
matches, truncated: totalMatches > matches.length, distinct: isOnlyMatching ? [...distinct].sort() : undefined,
|
package/cli/search-queries.js
CHANGED
|
@@ -29,6 +29,25 @@ export const findSymbolDefinition = (db, symbolName) => {
|
|
|
29
29
|
};
|
|
30
30
|
};
|
|
31
31
|
|
|
32
|
+
// Every indexed use of a name (identifier positions, not just import statements).
|
|
33
|
+
// Returns { total, files, rows } where rows are { filePath, line } ordered by path then line.
|
|
34
|
+
export const findOccurrences = (db, name, { limit = 50 } = {}) => {
|
|
35
|
+
const cleanName = typeof name === 'string' ? name.trim() : '';
|
|
36
|
+
const hasInput = Boolean(db) && Boolean(cleanName);
|
|
37
|
+
if (!hasInput) return { total: 0, files: 0, rows: [] };
|
|
38
|
+
// An index built before v3 has no occurrences table; a read-only handle does not create it.
|
|
39
|
+
const hasTable = Boolean(db.prepare("SELECT 1 FROM sqlite_master WHERE type = 'table' AND name = 'occurrences'").get());
|
|
40
|
+
if (!hasTable) return { total: 0, files: 0, rows: [], isMissing: true };
|
|
41
|
+
const totals = db.prepare('SELECT COUNT(*) AS total, COUNT(DISTINCT file_path) AS files FROM occurrences WHERE name = ?').get(cleanName);
|
|
42
|
+
const rows = db.prepare(`
|
|
43
|
+
SELECT file_path, line FROM occurrences
|
|
44
|
+
WHERE name = ?
|
|
45
|
+
ORDER BY file_path, line
|
|
46
|
+
LIMIT ?
|
|
47
|
+
`).all(cleanName, Math.max(1, Number(limit) || 50)).map((row) => ({ filePath: row.file_path, line: Number(row.line) }));
|
|
48
|
+
return { total: Number(totals.total), files: Number(totals.files), rows };
|
|
49
|
+
};
|
|
50
|
+
|
|
32
51
|
export const findSymbolReferences = (db, symbolName) => {
|
|
33
52
|
const hasInput = Boolean(db) && Boolean(symbolName);
|
|
34
53
|
if (!hasInput) return [];
|
package/cli/search-schema-ddl.js
CHANGED
|
@@ -54,6 +54,15 @@ const TABLES_SQL = `
|
|
|
54
54
|
FOREIGN KEY(importer_path) REFERENCES files(path) ON DELETE CASCADE
|
|
55
55
|
);
|
|
56
56
|
|
|
57
|
+
-- Identifier uses (reference positions in code). One row per distinct name per line.
|
|
58
|
+
CREATE TABLE IF NOT EXISTS occurrences (
|
|
59
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
60
|
+
file_path TEXT NOT NULL,
|
|
61
|
+
name TEXT NOT NULL,
|
|
62
|
+
line INTEGER NOT NULL DEFAULT 1,
|
|
63
|
+
FOREIGN KEY(file_path) REFERENCES files(path) ON DELETE CASCADE
|
|
64
|
+
);
|
|
65
|
+
|
|
57
66
|
CREATE TABLE IF NOT EXISTS violations (
|
|
58
67
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
59
68
|
file_path TEXT NOT NULL,
|
|
@@ -114,6 +123,8 @@ const INDEXES_SQL = `
|
|
|
114
123
|
CREATE INDEX IF NOT EXISTS idx_imports_symbol ON imports(imported_symbol);
|
|
115
124
|
CREATE INDEX IF NOT EXISTS idx_imports_path ON imports(importer_path);
|
|
116
125
|
CREATE INDEX IF NOT EXISTS idx_imports_resolved ON imports(resolved_path);
|
|
126
|
+
CREATE INDEX IF NOT EXISTS idx_occurrences_name ON occurrences(name);
|
|
127
|
+
CREATE INDEX IF NOT EXISTS idx_occurrences_file ON occurrences(file_path);
|
|
117
128
|
CREATE INDEX IF NOT EXISTS idx_embeddings_file ON embeddings(file_path);
|
|
118
129
|
CREATE INDEX IF NOT EXISTS idx_embeddings_type ON embeddings(target_type);
|
|
119
130
|
CREATE INDEX IF NOT EXISTS idx_violations_file ON violations(file_path);
|
package/cli/search-sync-rows.js
CHANGED
|
@@ -24,12 +24,12 @@ export const parseIndexRecord = (fullPath, relPath, root) => {
|
|
|
24
24
|
const stat = fs.statSync(fullPath);
|
|
25
25
|
const content = fs.readFileSync(fullPath, 'utf-8');
|
|
26
26
|
refuseConflicted(content, relPath);
|
|
27
|
-
const { symbols, props, hooks, imports } = extractAstMetadata(content, fullPath);
|
|
27
|
+
const { symbols, props, hooks, imports, occurrences } = extractAstMetadata(content, fullPath);
|
|
28
28
|
return {
|
|
29
29
|
path: relPath, root, mtime: Math.floor(stat.mtimeMs), size: stat.size,
|
|
30
30
|
tier: resolveArchitectureTier(relPath), lines: content.split('\n').length, chars: content.length,
|
|
31
31
|
contentHash: hashContent(content), syncedAt,
|
|
32
|
-
symbols, props, hooks, imports
|
|
32
|
+
symbols, props, hooks, imports, occurrences
|
|
33
33
|
};
|
|
34
34
|
};
|
|
35
35
|
|