praxo-cli 0.0.0-stage → 0.1.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 (82) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +159 -2
  3. package/dist/app.js +75 -0
  4. package/dist/bin.js +21 -0
  5. package/dist/cli/commands/ai.command.js +189 -0
  6. package/dist/cli/commands/cmd.command.js +265 -0
  7. package/dist/cli/commands/completion.command.js +334 -0
  8. package/dist/cli/commands/config.command.js +27 -0
  9. package/dist/cli/commands/decision.command.js +287 -0
  10. package/dist/cli/commands/doctor.command.js +45 -0
  11. package/dist/cli/commands/project.command.js +24 -0
  12. package/dist/cli/commands/search.command.js +59 -0
  13. package/dist/cli/commands/sync.command.js +122 -0
  14. package/dist/cli/commands/transfer.command.js +148 -0
  15. package/dist/cli/index.js +156 -0
  16. package/dist/cli/output.js +133 -0
  17. package/dist/cli/prompts.js +68 -0
  18. package/dist/features/ai/client.js +238 -0
  19. package/dist/features/ai/output.js +7 -0
  20. package/dist/features/ai/providers.js +52 -0
  21. package/dist/features/ai/schemas.js +43 -0
  22. package/dist/features/ai/service.js +183 -0
  23. package/dist/features/commands/executor.js +54 -0
  24. package/dist/features/commands/repository.js +61 -0
  25. package/dist/features/commands/safety.js +154 -0
  26. package/dist/features/commands/service.js +254 -0
  27. package/dist/features/commands/template.js +153 -0
  28. package/dist/features/decisions/repository.js +53 -0
  29. package/dist/features/decisions/service.js +209 -0
  30. package/dist/features/decisions/stats.js +84 -0
  31. package/dist/features/decisions/status.js +7 -0
  32. package/dist/features/projects/repository.js +51 -0
  33. package/dist/features/projects/service.js +74 -0
  34. package/dist/features/sync/git.js +207 -0
  35. package/dist/features/sync/merge.js +194 -0
  36. package/dist/features/sync/repository.js +151 -0
  37. package/dist/features/sync/sanitizer.js +21 -0
  38. package/dist/features/sync/service.js +199 -0
  39. package/dist/features/sync/snapshot.js +230 -0
  40. package/dist/infrastructure/credentials/store.js +105 -0
  41. package/dist/infrastructure/database/client.js +41 -0
  42. package/dist/infrastructure/database/migrate.js +102 -0
  43. package/dist/infrastructure/database/schema.js +138 -0
  44. package/dist/infrastructure/git/detector.js +48 -0
  45. package/dist/shared/clipboard.js +19 -0
  46. package/dist/shared/config.js +163 -0
  47. package/dist/shared/doctor.js +47 -0
  48. package/dist/shared/errors.js +19 -0
  49. package/dist/shared/global-search.js +51 -0
  50. package/dist/shared/input.js +37 -0
  51. package/dist/shared/links.js +48 -0
  52. package/dist/shared/paths.js +14 -0
  53. package/dist/shared/query.js +10 -0
  54. package/dist/shared/redaction.js +54 -0
  55. package/dist/shared/search.js +39 -0
  56. package/dist/shared/sync-metadata.js +7 -0
  57. package/dist/shared/tags.js +91 -0
  58. package/dist/shared/transfer/archive.js +197 -0
  59. package/dist/shared/transfer/markdown.js +53 -0
  60. package/dist/shared/transfer/service.js +278 -0
  61. package/dist/tui/Workspace.js +121 -0
  62. package/dist/tui/components/AiPanel.js +200 -0
  63. package/dist/tui/components/Catalog.js +47 -0
  64. package/dist/tui/components/Confirm.js +28 -0
  65. package/dist/tui/components/Form.js +113 -0
  66. package/dist/tui/components/HelpModal.js +44 -0
  67. package/dist/tui/components/Inspection.js +28 -0
  68. package/dist/tui/components/KeyHints.js +7 -0
  69. package/dist/tui/components/SearchInput.js +31 -0
  70. package/dist/tui/components/SyncPanel.js +93 -0
  71. package/dist/tui/index.js +18 -0
  72. package/dist/tui/screens/Commands.js +383 -0
  73. package/dist/tui/screens/DecisionForms.js +117 -0
  74. package/dist/tui/screens/Decisions.js +260 -0
  75. package/dist/tui/screens/Lookup.js +96 -0
  76. package/dist/tui/theme.js +47 -0
  77. package/drizzle/0000_initial.sql +105 -0
  78. package/drizzle/0001_v11_sync.sql +117 -0
  79. package/drizzle/meta/0000_snapshot.json +735 -0
  80. package/drizzle/meta/0001_snapshot.json +867 -0
  81. package/drizzle/meta/_journal.json +20 -0
  82. package/package.json +77 -4
@@ -0,0 +1,163 @@
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import { mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
3
+ import { homedir } from 'node:os';
4
+ import { dirname, isAbsolute, join } from 'node:path';
5
+ import { z } from 'zod';
6
+ import { AppError } from './errors.js';
7
+ const githubShorthand = /^([a-z\d][a-z\d-]*)\/([a-z\d_.-]+)$/iu;
8
+ const scpSshRemote = /^(?:[a-z\d._-]+@)?([a-z\d][a-z\d._-]*):([a-z\d._-]+(?:\/[a-z\d._-]+)*)$/iu;
9
+ const forbiddenSchemes = new Set(['http', 'https', 'file', 'ext', 'ftp']);
10
+ /** 将 GitHub 简写或 SSH 地址规范化为本地 Git 可直接访问的 SSH 远端地址。 */
11
+ export function normalizeSyncRepository(input) {
12
+ const trimmed = input.trim();
13
+ if (!trimmed || trimmed.startsWith('-') || /\s/u.test(trimmed))
14
+ return null;
15
+ const short = githubShorthand.exec(trimmed);
16
+ if (short) {
17
+ const [, owner, rawRepo] = short;
18
+ const repo = rawRepo.replace(/\.git$/iu, '');
19
+ if (!repo || repo === '.' || repo === '..' || repo.endsWith('.'))
20
+ return null;
21
+ return `git@github.com:${owner}/${repo}.git`;
22
+ }
23
+ if (trimmed.toLowerCase().startsWith('ssh://')) {
24
+ try {
25
+ const url = new URL(trimmed);
26
+ const segments = url.pathname.split('/').filter(Boolean);
27
+ if (url.protocol !== 'ssh:' ||
28
+ !url.hostname ||
29
+ url.hostname.startsWith('-') ||
30
+ url.password ||
31
+ url.search ||
32
+ url.hash ||
33
+ segments.length === 0 ||
34
+ segments.some((segment) => segment === '.' || segment === '..')) {
35
+ return null;
36
+ }
37
+ return trimmed;
38
+ }
39
+ catch {
40
+ return null;
41
+ }
42
+ }
43
+ const scp = scpSshRemote.exec(trimmed);
44
+ if (scp) {
45
+ const [, host, path] = scp;
46
+ if (forbiddenSchemes.has(host.toLowerCase()))
47
+ return null;
48
+ const segments = path.split('/');
49
+ if (segments.some((segment) => !segment || segment === '.' || segment === '..'))
50
+ return null;
51
+ return trimmed;
52
+ }
53
+ return null;
54
+ }
55
+ const syncRepository = z
56
+ .string()
57
+ .trim()
58
+ .transform((value, ctx) => {
59
+ const normalized = normalizeSyncRepository(value);
60
+ if (!normalized) {
61
+ ctx.addIssue({
62
+ code: 'custom',
63
+ message: 'Enter a GitHub repository (owner/name) or SSH Git URL (for example git@github.com:owner/name.git).',
64
+ });
65
+ return z.NEVER;
66
+ }
67
+ return normalized;
68
+ });
69
+ export const syncConfigSchema = z
70
+ .object({
71
+ repository: syncRepository,
72
+ branch: z.string().trim().min(1).default('praxo-sync'),
73
+ })
74
+ .strip();
75
+ export const providerName = z.enum(['deepseek', 'gemini']);
76
+ const retiredProviders = new Set(['openai', 'ollama', 'custom']);
77
+ /** 兼容旧版配置:移除已下线的 AI 服务商配置节,保留其余有效配置并允许直接重新配置。 */
78
+ function normalizeLegacyConfig(raw) {
79
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw))
80
+ return raw;
81
+ const record = raw;
82
+ const ai = record.ai;
83
+ if (ai &&
84
+ typeof ai === 'object' &&
85
+ !Array.isArray(ai) &&
86
+ typeof ai.provider === 'string' &&
87
+ retiredProviders.has(ai.provider)) {
88
+ const rest = { ...record };
89
+ delete rest.ai;
90
+ return rest;
91
+ }
92
+ return raw;
93
+ }
94
+ export const aiConfigSchema = z
95
+ .object({
96
+ provider: providerName,
97
+ model: z.string().trim().min(1),
98
+ timeoutMs: z.number().int().min(100).max(300_000).default(30_000),
99
+ })
100
+ .strip();
101
+ const configSchema = z.strictObject({
102
+ sync: syncConfigSchema.optional(),
103
+ ai: aiConfigSchema.optional(),
104
+ });
105
+ export function instancePaths(path, isolated = Boolean(process.env.PRAXO_DATA_DIR)) {
106
+ const data = dirname(path);
107
+ const home = homedir();
108
+ const xdg = (value, fallback) => value && isAbsolute(value) ? value : fallback;
109
+ const config = isolated || process.platform !== 'linux'
110
+ ? join(data, 'config')
111
+ : join(xdg(process.env.XDG_CONFIG_HOME, join(home, '.config')), 'praxo');
112
+ const cache = isolated || process.platform === 'win32'
113
+ ? join(data, 'cache')
114
+ : process.platform === 'darwin'
115
+ ? join(home, 'Library', 'Caches', 'praxo')
116
+ : join(xdg(process.env.XDG_CACHE_HOME, join(home, '.cache')), 'praxo');
117
+ return { database: path, config: join(config, 'config.json'), cache };
118
+ }
119
+ export function configService(paths, serialize = (action) => action()) {
120
+ function read() {
121
+ let raw;
122
+ try {
123
+ raw = readFileSync(paths.config, 'utf8');
124
+ }
125
+ catch (error) {
126
+ if (error.code === 'ENOENT')
127
+ return {};
128
+ throw new AppError(5, 'Cannot read configuration at ' + paths.config + '.');
129
+ }
130
+ try {
131
+ return configSchema.parse(normalizeLegacyConfig(JSON.parse(raw)));
132
+ }
133
+ catch {
134
+ throw new AppError(5, 'Invalid configuration. Check ' + paths.config + '.');
135
+ }
136
+ }
137
+ function set(section, value) {
138
+ return serialize(() => {
139
+ const data = configSchema.parse({ ...read(), [section]: value });
140
+ const temp = paths.config + '.' + randomUUID() + '.tmp';
141
+ mkdirSync(dirname(temp), { recursive: true, mode: 0o700 });
142
+ try {
143
+ writeFileSync(temp, JSON.stringify(data, null, 2) + '\n', {
144
+ flag: 'wx',
145
+ mode: 0o600,
146
+ flush: true,
147
+ });
148
+ renameSync(temp, paths.config);
149
+ }
150
+ finally {
151
+ rmSync(temp, { force: true });
152
+ }
153
+ return data;
154
+ });
155
+ }
156
+ function identity(scope) {
157
+ return ('praxo-' +
158
+ createHash('sha256')
159
+ .update(paths.config + '\0' + scope)
160
+ .digest('hex'));
161
+ }
162
+ return { paths, read, set, identity };
163
+ }
@@ -0,0 +1,47 @@
1
+ import { existsSync } from 'node:fs';
2
+ import Database from 'better-sqlite3';
3
+ import { migrationState } from '../infrastructure/database/migrate.js';
4
+ import { detectGit, gitVersion } from '../infrastructure/git/detector.js';
5
+ import { checkClipboard } from './clipboard.js';
6
+ import { messageOf } from './errors.js';
7
+ import { databasePath } from './paths.js';
8
+ function inspectDatabase(path) {
9
+ if (!existsSync(path))
10
+ return { status: 'uninitialized' };
11
+ let db;
12
+ try {
13
+ db = new Database(path, { readonly: true, fileMustExist: true, timeout: 3000 });
14
+ db.pragma('foreign_keys = ON');
15
+ const migrations = migrationState(db);
16
+ const wal = db.pragma('journal_mode', { simple: true }) === 'wal';
17
+ const foreignKeys = db.pragma('foreign_keys', { simple: true }) === 1;
18
+ const integrity = db.pragma('quick_check(1)', { simple: true }) === 'ok';
19
+ const validReferences = db.pragma('foreign_key_check').length === 0;
20
+ return {
21
+ status: integrity && validReferences && wal && foreignKeys && migrations.current
22
+ ? 'ok'
23
+ : 'error',
24
+ migrations,
25
+ wal,
26
+ foreignKeys,
27
+ integrity,
28
+ validReferences,
29
+ };
30
+ }
31
+ catch (error) {
32
+ return { status: 'error', message: messageOf(error) };
33
+ }
34
+ finally {
35
+ db?.close();
36
+ }
37
+ }
38
+ export async function doctor(cwd = process.cwd()) {
39
+ const path = databasePath();
40
+ const [major, minor] = process.versions.node.split('.').map(Number);
41
+ return {
42
+ node: { version: process.versions.node, supported: major === 24 && (minor ?? 0) >= 22 },
43
+ database: { path, ...inspectDatabase(path) },
44
+ git: { version: gitVersion(cwd) ?? null, current: detectGit(cwd) },
45
+ clipboard: { available: await checkClipboard() },
46
+ };
47
+ }
@@ -0,0 +1,19 @@
1
+ export class AppError extends Error {
2
+ code;
3
+ constructor(code, message, options) {
4
+ super(message, options);
5
+ this.code = code;
6
+ this.name = 'AppError';
7
+ }
8
+ }
9
+ export function messageOf(error) {
10
+ return error instanceof Error ? error.message : String(error);
11
+ }
12
+ export function exitCodeOf(error) {
13
+ if (error instanceof AppError)
14
+ return error.code;
15
+ if (error instanceof Error && 'code' in error && String(error.code).startsWith('SQLITE_')) {
16
+ return 5;
17
+ }
18
+ return 1;
19
+ }
@@ -0,0 +1,51 @@
1
+ import { z } from 'zod';
2
+ import { commandFields } from '../features/commands/service.js';
3
+ import { decisionFields } from '../features/decisions/service.js';
4
+ import { defaultLimit, nonempty, validate } from './input.js';
5
+ import { search } from './search.js';
6
+ const options = z.object({
7
+ only: z.enum(['all', 'commands', 'decisions']).default('all'),
8
+ project: nonempty.optional(),
9
+ tags: z.array(nonempty).optional(),
10
+ limit: z.number().int().positive().default(defaultLimit),
11
+ });
12
+ export function globalSearch(commands, decisions) {
13
+ return (query, rawOptions = {}) => {
14
+ const filters = validate(options, rawOptions);
15
+ const criteria = { project: filters.project, tags: filters.tags };
16
+ const entries = [];
17
+ if (filters.only !== 'decisions') {
18
+ for (const item of commands.candidates(criteria)) {
19
+ entries.push({
20
+ result: {
21
+ id: item.id,
22
+ type: 'command',
23
+ title: item.name,
24
+ description: item.template,
25
+ projectName: item.projectName,
26
+ tags: item.tags,
27
+ },
28
+ fields: commandFields(item),
29
+ });
30
+ }
31
+ }
32
+ if (filters.only !== 'commands') {
33
+ for (const item of decisions.candidates(criteria)) {
34
+ entries.push({
35
+ result: {
36
+ id: item.id,
37
+ type: 'decision',
38
+ title: item.title,
39
+ description: item.reason || item.content,
40
+ projectName: item.projectName,
41
+ tags: item.tags,
42
+ },
43
+ fields: decisionFields(item),
44
+ });
45
+ }
46
+ }
47
+ return search(entries, query, (entry) => entry.fields)
48
+ .slice(0, filters.limit)
49
+ .map(({ item }) => item.result);
50
+ };
51
+ }
@@ -0,0 +1,37 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { z } from 'zod';
3
+ import { AppError } from './errors.js';
4
+ export const nonempty = z.string().trim().min(1, 'must not be empty');
5
+ export const scope = z.enum(['auto', 'global', 'project']);
6
+ export const tier = z.enum(['hot', 'normal']);
7
+ export const rating = z.enum(['accurate', 'partial', 'failed']);
8
+ export const status = z.enum(['open', 'due', 'reviewed', 'all']);
9
+ export const confidence = z.number().int().min(0).max(100);
10
+ export const isoDate = z.iso.date();
11
+ export const defaultLimit = 50;
12
+ export function validate(schema, value) {
13
+ const result = schema.safeParse(value);
14
+ if (!result.success) {
15
+ throw new AppError(2, result.error.issues
16
+ .map((issue) => [issue.path.join('.'), issue.message].filter(Boolean).join(': '))
17
+ .join('; '));
18
+ }
19
+ return result.data;
20
+ }
21
+ export function normalize(value) {
22
+ return value.normalize('NFKC').trim().toLowerCase();
23
+ }
24
+ export function newId() {
25
+ return randomUUID();
26
+ }
27
+ export function localDay(date = new Date()) {
28
+ const year = String(date.getFullYear()).padStart(4, '0');
29
+ const month = String(date.getMonth() + 1).padStart(2, '0');
30
+ const day = String(date.getDate()).padStart(2, '0');
31
+ return `${year}-${month}-${day}`;
32
+ }
33
+ export function daysFrom(date, days) {
34
+ const result = new Date(date);
35
+ result.setDate(result.getDate() + days);
36
+ return validate(isoDate, localDay(result));
37
+ }
@@ -0,0 +1,48 @@
1
+ import { and, eq, isNotNull, isNull } from 'drizzle-orm';
2
+ import { commands, decisions, entityLinks } from '../infrastructure/database/schema.js';
3
+ export function linkService(db, commandApi, decisionApi, write, now) {
4
+ function list(kind, id) {
5
+ if (kind === 'command') {
6
+ commandApi.show(id);
7
+ return db
8
+ .select({ id: decisions.id, title: decisions.title })
9
+ .from(entityLinks)
10
+ .innerJoin(decisions, eq(entityLinks.decisionId, decisions.id))
11
+ .where(and(eq(entityLinks.commandId, id), isNull(entityLinks.deletedAt), isNull(decisions.deletedAt)))
12
+ .orderBy(decisions.title, decisions.id)
13
+ .all();
14
+ }
15
+ decisionApi.show(id);
16
+ return db
17
+ .select({ id: commands.id, title: commands.name })
18
+ .from(entityLinks)
19
+ .innerJoin(commands, eq(entityLinks.commandId, commands.id))
20
+ .where(and(eq(entityLinks.decisionId, id), isNull(entityLinks.deletedAt), isNull(commands.deletedAt)))
21
+ .orderBy(commands.name, commands.id)
22
+ .all();
23
+ }
24
+ function change(kind, id, target, action) {
25
+ const commandId = kind === 'command' ? id : target;
26
+ const decisionId = kind === 'decision' ? id : target;
27
+ write(() => {
28
+ commandApi.show(commandId);
29
+ decisionApi.show(decisionId);
30
+ const at = now().toISOString();
31
+ if (action === 'link')
32
+ db.insert(entityLinks)
33
+ .values({ commandId, decisionId, updatedAt: at })
34
+ .onConflictDoUpdate({
35
+ target: [entityLinks.commandId, entityLinks.decisionId],
36
+ set: { deletedAt: null, updatedAt: at },
37
+ setWhere: isNotNull(entityLinks.deletedAt),
38
+ })
39
+ .run();
40
+ else
41
+ db.update(entityLinks)
42
+ .set({ deletedAt: at, updatedAt: at })
43
+ .where(and(eq(entityLinks.commandId, commandId), eq(entityLinks.decisionId, decisionId), isNull(entityLinks.deletedAt)))
44
+ .run();
45
+ });
46
+ }
47
+ return { list, change };
48
+ }
@@ -0,0 +1,14 @@
1
+ import { homedir } from 'node:os';
2
+ import { isAbsolute, join, resolve } from 'node:path';
3
+ export function databasePath() {
4
+ const home = homedir();
5
+ const xdg = process.env.XDG_DATA_HOME;
6
+ const base = process.platform === 'win32'
7
+ ? process.env.LOCALAPPDATA || join(home, 'AppData', 'Local')
8
+ : process.platform === 'darwin'
9
+ ? join(home, 'Library', 'Application Support')
10
+ : xdg && isAbsolute(xdg)
11
+ ? xdg
12
+ : join(home, '.local', 'share');
13
+ return resolve(process.env.PRAXO_DATA_DIR || join(base, 'praxo'), 'praxo.sqlite');
14
+ }
@@ -0,0 +1,10 @@
1
+ import { eq, isNull, or, sql } from 'drizzle-orm';
2
+ export function inScope(column, projectId, scope) {
3
+ if (scope === 'all')
4
+ return undefined;
5
+ if (scope === 'global' || (!projectId && scope === undefined))
6
+ return isNull(column);
7
+ if (scope === 'project')
8
+ return projectId ? eq(column, projectId) : sql `0 = 1`;
9
+ return or(eq(column, projectId), isNull(column));
10
+ }
@@ -0,0 +1,54 @@
1
+ const known = [
2
+ /-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?(?:-----END [A-Z ]*PRIVATE KEY-----|$)/gu,
3
+ /\b(?:github_pat_[\w]{20,}|gh[pousr]_[\w]{20,}|sk-[\w-]{16,}|AIza[0-9A-Za-z_-]{35}|AKIA[A-Z0-9]{16})\b/gu,
4
+ /\bBearer[ \t]+[\w./+=-]{12,}/giu,
5
+ /\b(?:postgres(?:ql)?|mysql|mongodb(?:\+srv)?|redis|amqp):\/\/[^\s:@/]+:[^\s@/]+@/giu,
6
+ ];
7
+ const assignment = /\b((?:api[_-]?key|password|secret|access[_-]?token)\b["']?\s*[:=]\s*)("(?:\\[^\r\n]|[^"\\\r\n])*"|'[^'\r\n]*'|\{\{[^}\r\n]+\}\}|\$\{[\w]+\}|[^\s,;|&<>"'{}]+)/giu;
8
+ const templateVariable = /^\{\{[ \t]*[a-z_]\w*[ \t]*\}\}$/iu;
9
+ const shellVariable = /^\$(?:[a-z_]\w*|\{[a-z_]\w*\})$/iu;
10
+ const candidate = /\b[A-Za-z0-9_/.+=-]{32,}\b/gu;
11
+ function entropy(value) {
12
+ const counts = new Map();
13
+ for (const char of value)
14
+ counts.set(char, (counts.get(char) ?? 0) + 1);
15
+ return [...counts.values()].reduce((sum, count) => {
16
+ const p = count / value.length;
17
+ return sum - p * Math.log2(p);
18
+ }, 0);
19
+ }
20
+ function highEntropy(value) {
21
+ return (value.length <= 512 &&
22
+ /[a-z]/u.test(value) &&
23
+ /[A-Z]/u.test(value) &&
24
+ /[0-9]/u.test(value) &&
25
+ entropy(value) > 4.2);
26
+ }
27
+ export function inspectText(value) {
28
+ let blocked = false;
29
+ let suspicious = false;
30
+ // 已标明用途的字面凭据不受长度限制,保留无默认值的模板变量和 Shell 变量引用。
31
+ value = value.replace(assignment, (match, label, raw) => {
32
+ const quote = raw[0] === '"' || raw[0] === "'" ? raw[0] : '';
33
+ const token = quote ? raw.slice(1, -1) : raw;
34
+ if (!token ||
35
+ token === '[REDACTED]' ||
36
+ templateVariable.test(token) ||
37
+ (quote !== "'" && shellVariable.test(token)))
38
+ return match;
39
+ blocked = true;
40
+ return label + quote + '[REDACTED]' + quote;
41
+ });
42
+ for (const pattern of known)
43
+ value = value.replace(pattern, () => {
44
+ blocked = true;
45
+ return '[REDACTED]';
46
+ });
47
+ value = value.replace(candidate, (token) => {
48
+ if (!highEntropy(token))
49
+ return token;
50
+ suspicious = true;
51
+ return '[REDACTED]';
52
+ });
53
+ return { value, blocked, suspicious };
54
+ }
@@ -0,0 +1,39 @@
1
+ import Fuse from 'fuse.js';
2
+ import { nonempty, normalize, validate } from './input.js';
3
+ /** 先规范化字符和大小写,再将完整子串与 Fuse 模糊匹配合并。 */
4
+ export function search(items, raw, fields) {
5
+ const query = normalize(validate(nonempty, raw));
6
+ const documents = items.map((item) => {
7
+ const value = fields(item);
8
+ return {
9
+ item,
10
+ title: normalize(value.title),
11
+ body: normalize(value.body),
12
+ tags: value.tags.map(normalize),
13
+ project: normalize(value.project),
14
+ };
15
+ });
16
+ const fuse = new Fuse(documents, {
17
+ includeScore: true,
18
+ ignoreLocation: true,
19
+ threshold: 0.35,
20
+ keys: [
21
+ { name: 'title', weight: 0.44 },
22
+ { name: 'body', weight: 0.31 },
23
+ { name: 'tags', weight: 0.15 },
24
+ { name: 'project', weight: 0.1 },
25
+ ],
26
+ });
27
+ const fuzzy = new Map(fuse.search(query).map((hit) => [hit.refIndex, hit.score ?? 1]));
28
+ const ranked = documents.flatMap((doc, index) => {
29
+ const score = doc.title === query
30
+ ? 0
31
+ : doc.title.includes(query)
32
+ ? 0.01
33
+ : [doc.body, doc.project, ...doc.tags].some((field) => field.includes(query))
34
+ ? 0.1
35
+ : fuzzy.get(index);
36
+ return score === undefined ? [] : [{ item: doc.item, score }];
37
+ });
38
+ return ranked.sort((left, right) => left.score - right.score);
39
+ }
@@ -0,0 +1,7 @@
1
+ export function withoutSyncMetadata(value) {
2
+ const row = { ...value };
3
+ delete row.deletedAt;
4
+ delete row.revision;
5
+ delete row.deviceId;
6
+ return row;
7
+ }
@@ -0,0 +1,91 @@
1
+ import { and, eq, gt, isNotNull, isNull, sql } from 'drizzle-orm';
2
+ import { entityTags, tags } from '../infrastructure/database/schema.js';
3
+ import { newId, nonempty, normalize, validate } from './input.js';
4
+ export function matchesTags(names, required = []) {
5
+ const normalized = new Set(names.map(normalize));
6
+ return required.every((name) => normalized.has(normalize(name)));
7
+ }
8
+ export function tagService(db, now) {
9
+ function tagMap(kind) {
10
+ const owner = kind === 'command' ? entityTags.commandId : entityTags.decisionId;
11
+ const grouped = new Map();
12
+ const rows = db
13
+ .select({ id: owner, name: tags.name })
14
+ .from(entityTags)
15
+ .innerJoin(tags, eq(entityTags.tagId, tags.id))
16
+ .where(and(isNotNull(owner), isNull(entityTags.deletedAt), isNull(tags.deletedAt)))
17
+ .orderBy(tags.normalized)
18
+ .all();
19
+ for (const row of rows) {
20
+ if (row.id === null)
21
+ continue;
22
+ const existing = grouped.get(row.id);
23
+ if (existing)
24
+ existing.push(row.name);
25
+ else
26
+ grouped.set(row.id, [row.name]);
27
+ }
28
+ return grouped;
29
+ }
30
+ function forEntity(kind, id) {
31
+ const owner = kind === 'command' ? entityTags.commandId : entityTags.decisionId;
32
+ return db
33
+ .select({ name: tags.name })
34
+ .from(entityTags)
35
+ .innerJoin(tags, eq(entityTags.tagId, tags.id))
36
+ .where(and(eq(owner, id), isNull(entityTags.deletedAt), isNull(tags.deletedAt)))
37
+ .orderBy(tags.normalized)
38
+ .all()
39
+ .map((row) => row.name);
40
+ }
41
+ function attach(kind, id, name) {
42
+ const owner = kind === 'command' ? entityTags.commandId : entityTags.decisionId;
43
+ const clean = validate(nonempty, name);
44
+ const normalized = normalize(clean);
45
+ const at = now().toISOString();
46
+ const existing = db.select().from(tags).where(eq(tags.normalized, normalized)).get();
47
+ const tag = existing ??
48
+ db
49
+ .insert(tags)
50
+ .values({ id: newId(), name: clean, normalized, updatedAt: at })
51
+ .returning()
52
+ .get();
53
+ if (tag.deletedAt)
54
+ db.update(tags).set({ deletedAt: null, updatedAt: at }).where(eq(tags.id, tag.id)).run();
55
+ db.insert(entityTags)
56
+ .values({
57
+ tagId: tag.id,
58
+ commandId: kind === 'command' ? id : null,
59
+ decisionId: kind === 'decision' ? id : null,
60
+ updatedAt: at,
61
+ })
62
+ .onConflictDoUpdate({
63
+ target: [owner, entityTags.tagId],
64
+ set: { deletedAt: null, updatedAt: at },
65
+ setWhere: isNotNull(entityTags.deletedAt),
66
+ })
67
+ .run();
68
+ }
69
+ function detach(kind, id, name) {
70
+ const owner = kind === 'command' ? entityTags.commandId : entityTags.decisionId;
71
+ const key = normalize(validate(nonempty, name));
72
+ const at = now().toISOString();
73
+ db.update(entityTags)
74
+ .set({ deletedAt: at, updatedAt: at })
75
+ .where(and(eq(owner, id), isNull(entityTags.deletedAt), sql `${entityTags.tagId} in (select ${tags.id} from ${tags} where ${tags.normalized} = ${key})`))
76
+ .run();
77
+ }
78
+ function list(sort = 'name') {
79
+ const tally = sql `count(${entityTags.tagId})`;
80
+ return db
81
+ .select({ id: tags.id, name: tags.name, normalized: tags.normalized, count: tally })
82
+ .from(tags)
83
+ .leftJoin(entityTags, and(eq(entityTags.tagId, tags.id), isNull(entityTags.deletedAt)))
84
+ .where(isNull(tags.deletedAt))
85
+ .groupBy(tags.id)
86
+ .having(gt(tally, 0))
87
+ .orderBy(...(sort === 'usage' ? [sql `${tally} desc`, tags.normalized] : [tags.normalized]))
88
+ .all();
89
+ }
90
+ return { tagMap, forEntity, attach, detach, list };
91
+ }