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,230 @@
1
+ import { stripVTControlCharacters } from 'node:util';
2
+ import { inspectText } from '../../shared/redaction.js';
3
+ import { createHash } from 'node:crypto';
4
+ import { z } from 'zod';
5
+ import { parseTemplate } from '../commands/template.js';
6
+ import { AppError } from '../../shared/errors.js';
7
+ import { normalize } from '../../shared/input.js';
8
+ import { archiveSchema } from '../../shared/transfer/archive.js';
9
+ const date = z.iso.datetime({ precision: 3 });
10
+ const deleted = { deletedAt: date.nullable() };
11
+ const tracked = {
12
+ ...deleted,
13
+ revision: z.number().int().nonnegative().optional(),
14
+ deviceId: z
15
+ .string()
16
+ .regex(/^[a-f0-9]{32}$/u)
17
+ .nullable()
18
+ .optional(),
19
+ };
20
+ const archived = archiveSchema.shape;
21
+ export const tables = [
22
+ 'projects',
23
+ 'commands',
24
+ 'decisions',
25
+ 'decision_reviews',
26
+ 'tags',
27
+ 'entity_tags',
28
+ 'entity_links',
29
+ ];
30
+ const schemas = {
31
+ projects: archived.projects.element.omit({ root: true, aliases: true }).extend(tracked),
32
+ commands: archived.commands.element.extend(tracked),
33
+ decisions: archived.decisions.element.extend({ ...tracked, aiNote: z.string().nullable() }),
34
+ decision_reviews: archived.decisionReviews.element.extend(tracked),
35
+ tags: archived.tags.element.extend({ ...tracked, updatedAt: date.nullable() }),
36
+ entity_tags: archived.entityTags.element.extend({ ...deleted, updatedAt: date.nullable() }),
37
+ entity_links: archived.entityLinks.element.extend({ ...deleted, updatedAt: date.nullable() }),
38
+ };
39
+ export const manifest = z.strictObject({
40
+ format: z.literal('praxo-sync'),
41
+ schemaVersion: z.literal(1),
42
+ exportedAt: date,
43
+ });
44
+ const compare = (left, right) => (left < right ? -1 : left === right ? 0 : 1);
45
+ export function canonical(value) {
46
+ return JSON.stringify(value, (_key, item) => typeof item === 'object' && item !== null && !Array.isArray(item)
47
+ ? Object.fromEntries(Object.entries(item).sort(([left], [right]) => compare(left, right)))
48
+ : item);
49
+ }
50
+ export const hash = (value) => createHash('sha256').update(canonical(value)).digest('hex');
51
+ export function content(entry) {
52
+ if (!entry)
53
+ return '';
54
+ const { deletedAt, ...row } = portable(entry).row;
55
+ const data = row;
56
+ delete data.updatedAt;
57
+ delete data.revision;
58
+ delete data.deviceId;
59
+ return canonical({ ...data, deleted: deletedAt !== null });
60
+ }
61
+ export const keyOf = (table, ...parts) => table + ':' + JSON.stringify(parts);
62
+ export function entryKey(entry) {
63
+ const { table, row } = entry;
64
+ if (table === 'entity_tags')
65
+ return keyOf(table, row.commandId, row.decisionId, row.tagId);
66
+ if (table === 'entity_links')
67
+ return keyOf(table, row.commandId, row.decisionId);
68
+ return keyOf(table, row.id);
69
+ }
70
+ export function references(entry) {
71
+ const { table, row } = entry;
72
+ switch (table) {
73
+ case 'decision_reviews':
74
+ return [keyOf('decisions', row.decisionId)];
75
+ case 'entity_links':
76
+ return [keyOf('commands', row.commandId), keyOf('decisions', row.decisionId)];
77
+ case 'entity_tags':
78
+ return [
79
+ row.commandId ? keyOf('commands', row.commandId) : keyOf('decisions', row.decisionId),
80
+ keyOf('tags', row.tagId),
81
+ ];
82
+ case 'commands':
83
+ case 'decisions':
84
+ return row.projectId ? [keyOf('projects', row.projectId)] : [];
85
+ default:
86
+ return [];
87
+ }
88
+ }
89
+ function invalid(where) {
90
+ throw new AppError(5, 'Invalid Praxo sync snapshot at ' +
91
+ inspectText(stripVTControlCharacters(where)).value +
92
+ '. Review the sync branch and retry.');
93
+ }
94
+ /** 同步协议通过明确字段白名单校验来自远端的每一行。 */
95
+ export function parseSnapshot(input, checkReferences = true) {
96
+ if (input === null || typeof input !== 'object' || Object.keys(input).length !== tables.length)
97
+ invalid('data');
98
+ const snapshot = new Map();
99
+ const projectRemotes = new Set();
100
+ const tagNames = new Set();
101
+ for (const table of tables) {
102
+ const data = input[table];
103
+ const result = schemas[table].array().safeParse(data);
104
+ if (!result.success)
105
+ invalid(table + '.' + result.error.issues[0]?.path.join('.'));
106
+ for (const row of result.data) {
107
+ const entry = { table, row };
108
+ const key = entryKey(entry);
109
+ if (snapshot.has(key))
110
+ invalid(key + ' (duplicate key)');
111
+ if (entry.table === 'commands') {
112
+ try {
113
+ parseTemplate(entry.row.template);
114
+ }
115
+ catch {
116
+ invalid(key + ' (template)');
117
+ }
118
+ }
119
+ else if (entry.table === 'tags') {
120
+ if (tagNames.has(entry.row.normalized) ||
121
+ normalize(entry.row.name) !== entry.row.normalized)
122
+ invalid(key + ' (tag identity)');
123
+ tagNames.add(entry.row.normalized);
124
+ }
125
+ else if (entry.table === 'projects' && entry.row.remote !== null) {
126
+ if (!/^[^/@\s]+\/[^?#\r\n]+$/u.test(entry.row.remote))
127
+ invalid(key + ' (remote)');
128
+ if (entry.row.deletedAt === null) {
129
+ if (projectRemotes.has(entry.row.remote))
130
+ invalid(key + ' (project identity)');
131
+ projectRemotes.add(entry.row.remote);
132
+ }
133
+ }
134
+ else if (entry.table === 'entity_tags' &&
135
+ (entry.row.commandId === null) === (entry.row.decisionId === null)) {
136
+ invalid(key + ' (owner)');
137
+ }
138
+ snapshot.set(key, entry);
139
+ }
140
+ }
141
+ if (checkReferences)
142
+ for (const [key, entry] of snapshot) {
143
+ for (const ref of references(entry)) {
144
+ const parent = snapshot.get(ref);
145
+ if (!parent || (parent.row.deletedAt !== null && entry.row.deletedAt === null))
146
+ invalid(key + ' (reference)');
147
+ }
148
+ }
149
+ return snapshot;
150
+ }
151
+ /** Tombstone 保留身份与引用,删除的自由文本不会被提交到 Git。 */
152
+ export function portable(entry) {
153
+ if (!entry.row.deletedAt)
154
+ return entry;
155
+ switch (entry.table) {
156
+ case 'commands':
157
+ return {
158
+ ...entry,
159
+ row: {
160
+ ...entry.row,
161
+ name: 'Deleted command',
162
+ template: 'echo',
163
+ note: '',
164
+ type: 'custom',
165
+ danger: false,
166
+ sos: false,
167
+ tier: 'normal',
168
+ },
169
+ };
170
+ case 'decisions':
171
+ return {
172
+ ...entry,
173
+ row: {
174
+ ...entry.row,
175
+ title: 'Deleted decision',
176
+ content: '',
177
+ reason: '',
178
+ alternatives: '',
179
+ expected: '',
180
+ aiNote: null,
181
+ domain: 'architecture',
182
+ confidence: null,
183
+ },
184
+ };
185
+ case 'decision_reviews':
186
+ return {
187
+ ...entry,
188
+ row: {
189
+ ...entry.row,
190
+ result: 'Deleted',
191
+ lesson: 'Deleted',
192
+ rating: 'partial',
193
+ snapshot: {
194
+ title: 'Deleted decision',
195
+ content: '',
196
+ reason: '',
197
+ alternatives: '',
198
+ expected: '',
199
+ domain: 'architecture',
200
+ confidence: null,
201
+ reviewAt: entry.row.snapshot.reviewAt,
202
+ },
203
+ },
204
+ };
205
+ case 'projects':
206
+ return { ...entry, row: { ...entry.row, name: 'Deleted project' } };
207
+ default:
208
+ return entry;
209
+ }
210
+ }
211
+ export function snapshotData(snapshot) {
212
+ const groups = {
213
+ projects: [],
214
+ commands: [],
215
+ decisions: [],
216
+ decision_reviews: [],
217
+ tags: [],
218
+ entity_tags: [],
219
+ entity_links: [],
220
+ };
221
+ for (const [, entry] of [...snapshot].sort(([a], [b]) => compare(a, b)))
222
+ groups[entry.table].push(portable(entry).row);
223
+ return groups;
224
+ }
225
+ export function snapshotHash(snapshot) {
226
+ return hash([...snapshot].sort(([a], [b]) => compare(a, b)).map(([key, entry]) => [key, content(entry)]));
227
+ }
228
+ export function serialize(value) {
229
+ return JSON.stringify(JSON.parse(canonical(value)), null, 2) + '\n';
230
+ }
@@ -0,0 +1,105 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { AppError } from '../../shared/errors.js';
3
+ function invoke(program, args, input) {
4
+ return new Promise((resolve) => {
5
+ const child = spawn(program, args, { windowsHide: true, timeout: 8000 });
6
+ let value = '';
7
+ child.stdout.setEncoding('utf8').on('data', (chunk) => {
8
+ value += chunk;
9
+ });
10
+ child.stderr.resume();
11
+ child.stdin.on('error', () => { });
12
+ child.stdin.end(input);
13
+ child.once('error', () => resolve({ code: null, value: '' }));
14
+ child.once('close', (code) => resolve({ code, value: value.trim() }));
15
+ });
16
+ }
17
+ // Windows 平台通过标准输入向 Credential Manager 写入密钥,进程参数只携带操作和目标。
18
+ const win32 = `
19
+ using System;
20
+ using System.Runtime.InteropServices;
21
+ public static class PraxoCredential {
22
+ [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)]
23
+ public struct Entry {
24
+ public uint Flags, Type;
25
+ public string Target, Comment;
26
+ public long LastWritten;
27
+ public uint Size;
28
+ public IntPtr Blob;
29
+ public uint Persist, Count;
30
+ public IntPtr Attributes;
31
+ public string Alias, User;
32
+ }
33
+ [DllImport("advapi32.dll", EntryPoint="CredReadW", CharSet=CharSet.Unicode)]
34
+ static extern bool Read(string target, uint type, uint flags, out IntPtr cred);
35
+ [DllImport("advapi32.dll", EntryPoint="CredWriteW", CharSet=CharSet.Unicode)]
36
+ static extern bool Write(ref Entry cred, uint flags);
37
+ [DllImport("advapi32.dll")] static extern void CredFree(IntPtr ptr);
38
+ public static string Get(string key) {
39
+ IntPtr ptr;
40
+ if (!Read(key, 1, 0, out ptr)) return null;
41
+ try {
42
+ var entry = (Entry)Marshal.PtrToStructure(ptr, typeof(Entry));
43
+ return Marshal.PtrToStringUni(entry.Blob, (int)entry.Size / 2);
44
+ } finally { CredFree(ptr); }
45
+ }
46
+ public static bool Set(string key, string value) {
47
+ var entry = new Entry { Type=1, Target=key, User="Praxo", Persist=2,
48
+ Size=(uint)value.Length * 2, Blob=Marshal.StringToCoTaskMemUni(value) };
49
+ try { return Write(ref entry, 0); }
50
+ finally { Marshal.ZeroFreeCoTaskMemUnicode(entry.Blob); }
51
+ }
52
+ }`;
53
+ function systemCredential(key, value) {
54
+ if (process.platform === 'win32') {
55
+ const command = "$ErrorActionPreference='Stop'; [Console]::InputEncoding=[Text.Encoding]::UTF8; [Console]::OutputEncoding=[Text.Encoding]::UTF8; " +
56
+ "Add-Type -TypeDefinition @'\n" +
57
+ win32 +
58
+ "\n'@\n" +
59
+ (value === undefined
60
+ ? "[Console]::Write([PraxoCredential]::Get('" + key + "'))"
61
+ : "if (-not [PraxoCredential]::Set('" + key + "', [Console]::In.ReadToEnd())) { exit 1 }");
62
+ return invoke('powershell.exe', [
63
+ '-NoLogo',
64
+ '-NoProfile',
65
+ '-NonInteractive',
66
+ '-EncodedCommand',
67
+ Buffer.from(command, 'utf16le').toString('base64'),
68
+ ], value);
69
+ }
70
+ if (process.platform === 'darwin') {
71
+ return value === undefined
72
+ ? invoke('/usr/bin/security', ['find-generic-password', '-s', key, '-a', 'praxo', '-w'])
73
+ : invoke('/usr/bin/security', ['-i'], 'add-generic-password -U -s ' +
74
+ key +
75
+ ' -a praxo -w "' +
76
+ value.replace(/[\\"]/gu, '\\$&') +
77
+ '"\n');
78
+ }
79
+ return value === undefined
80
+ ? invoke('secret-tool', ['lookup', 'service', 'praxo', 'account', key])
81
+ : invoke('secret-tool', ['store', '--label=Praxo', 'service', 'praxo', 'account', key], value);
82
+ }
83
+ export function credentials() {
84
+ return {
85
+ async get(key, variable) {
86
+ const environment = variable ? process.env[variable]?.trim() : undefined;
87
+ if (environment)
88
+ return environment;
89
+ const result = await systemCredential(key);
90
+ return result.code === 0 ? result.value || undefined : undefined;
91
+ },
92
+ async set(key, value, variable) {
93
+ if (!value.trim() || /[\u0000-\u0020\u007f]/u.test(value) || value.length > 1024) {
94
+ throw new AppError(2, 'Enter a nonempty API token without whitespace.');
95
+ }
96
+ const result = await systemCredential(key, value);
97
+ // macOS 的交互子命令可能吞掉错误,因此写后再读确认。
98
+ const read = result.code === 0 ? await systemCredential(key) : undefined;
99
+ if (read?.code !== 0 || read.value !== value) {
100
+ throw new AppError(5, 'System credential storage is unavailable.' +
101
+ (variable ? ' Set ' + variable + ' instead.' : ''));
102
+ }
103
+ },
104
+ };
105
+ }
@@ -0,0 +1,41 @@
1
+ import { existsSync, mkdirSync } from 'node:fs';
2
+ import { dirname } from 'node:path';
3
+ import Database from 'better-sqlite3';
4
+ import { drizzle } from 'drizzle-orm/better-sqlite3';
5
+ import { AppError, messageOf } from '../../shared/errors.js';
6
+ import { migrate, migrationState } from './migrate.js';
7
+ import * as schema from './schema.js';
8
+ export function openStore(path, mode = 'write') {
9
+ const preview = mode === 'preview';
10
+ const memory = path === ':memory:' || (preview && !existsSync(path));
11
+ let connection;
12
+ try {
13
+ if (!preview && !memory)
14
+ mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
15
+ connection = new Database(memory ? ':memory:' : path, {
16
+ readonly: preview && !memory,
17
+ fileMustExist: preview && !memory,
18
+ timeout: 3000,
19
+ });
20
+ connection.pragma('foreign_keys = ON');
21
+ if (!memory &&
22
+ !preview &&
23
+ connection.pragma('journal_mode = WAL', { simple: true }) !== 'wal') {
24
+ throw new Error('SQLite could not enable WAL');
25
+ }
26
+ if (!preview || memory) {
27
+ migrate(connection);
28
+ }
29
+ else if (!migrationState(connection).current) {
30
+ throw new Error('Run a regular pxo command to migrate the database before previewing');
31
+ }
32
+ const native = connection;
33
+ return { db: drizzle(native, { schema }), native, close: () => native.close() };
34
+ }
35
+ catch (error) {
36
+ connection?.close();
37
+ throw new AppError(5, `Cannot open Praxo data at ${path}: ${messageOf(error)}`, {
38
+ cause: error,
39
+ });
40
+ }
41
+ }
@@ -0,0 +1,102 @@
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ import { mkdirSync, writeFileSync } from 'node:fs';
3
+ import { dirname, join } from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+ import { readMigrationFiles } from 'drizzle-orm/migrator';
6
+ const migrationsFolder = fileURLToPath(new URL('../../../drizzle/', import.meta.url));
7
+ const ledger = '__drizzle_migrations';
8
+ const breakpoint = '--> statement-breakpoint';
9
+ function checksum(sql) {
10
+ return createHash('sha256').update(sql).digest('hex');
11
+ }
12
+ /** 新迁移使用 LF 校验和,同时接受旧发布包记录的 CRLF 校验和。 */
13
+ function readMigrations(folder) {
14
+ return readMigrationFiles({ migrationsFolder: folder }).map((entry) => {
15
+ const sql = entry.sql.map((statement) => statement.replaceAll('\r\n', '\n'));
16
+ const source = sql.join(breakpoint);
17
+ return {
18
+ ...entry,
19
+ sql,
20
+ hash: checksum(source),
21
+ compatibleHashes: new Set([entry.hash, checksum(source.replaceAll('\n', '\r\n'))]),
22
+ };
23
+ });
24
+ }
25
+ function applied(connection) {
26
+ const exists = connection
27
+ .prepare('select 1 from sqlite_master where type = ? and name = ?')
28
+ .get('table', ledger);
29
+ return exists
30
+ ? connection
31
+ .prepare(`select hash, created_at from ${ledger} order by created_at`)
32
+ .all()
33
+ : [];
34
+ }
35
+ function validateHistory(history, disk) {
36
+ if (history.some((row, index) => {
37
+ const migration = disk[index];
38
+ return (!migration ||
39
+ row.created_at !== migration.folderMillis ||
40
+ (row.hash !== migration.hash && !migration.compatibleHashes.has(row.hash)));
41
+ })) {
42
+ throw new Error('Migration history differs from this package. Open the database with its matching or newer Praxo version.');
43
+ }
44
+ }
45
+ export function migrationState(connection, folder = migrationsFolder) {
46
+ const disk = readMigrations(folder);
47
+ const history = applied(connection);
48
+ validateHistory(history, disk);
49
+ return {
50
+ applied: history.length,
51
+ available: disk.length,
52
+ current: history.length === disk.length,
53
+ };
54
+ }
55
+ /** 先取得写锁,再读取版本记录,避免两个 pxo 进程同时执行同一迁移。 */
56
+ export function migrate(connection, folder = migrationsFolder) {
57
+ const disk = readMigrations(folder);
58
+ const existing = applied(connection);
59
+ validateHistory(existing, disk);
60
+ if (existing.length === disk.length)
61
+ return;
62
+ let backup;
63
+ try {
64
+ connection
65
+ .transaction(() => {
66
+ const history = applied(connection);
67
+ validateHistory(history, disk);
68
+ if (history.length === disk.length)
69
+ return;
70
+ if (history.length && connection.name !== ':memory:') {
71
+ const folder = join(dirname(connection.name), 'backups');
72
+ mkdirSync(folder, { recursive: true, mode: 0o700 });
73
+ const path = join(folder, 'migration-' + randomUUID() + '.sqlite');
74
+ // 当前连接已持有写锁,序列化包括已经提交到 WAL 的页面。
75
+ const image = connection.serialize();
76
+ image[18] = 1;
77
+ image[19] = 1;
78
+ writeFileSync(path, image, { flag: 'wx', mode: 0o600, flush: true });
79
+ backup = path;
80
+ }
81
+ connection.exec(`create table if not exists ${ledger} (hash text not null, created_at integer primary key)`);
82
+ const record = connection.prepare(`insert into ${ledger} (hash, created_at) values (?, ?)`);
83
+ for (const migration of disk.slice(history.length)) {
84
+ for (const statement of migration.sql) {
85
+ if (statement.trim())
86
+ connection.exec(statement);
87
+ }
88
+ record.run(migration.hash, migration.folderMillis);
89
+ }
90
+ const violations = connection.pragma('foreign_key_check');
91
+ if (violations.length > 0) {
92
+ throw new Error('Migration would leave invalid database references');
93
+ }
94
+ })
95
+ .immediate();
96
+ }
97
+ catch (error) {
98
+ if (!backup)
99
+ throw error;
100
+ throw new Error(String(error) + ' Migration backup saved to ' + backup + '.', { cause: error });
101
+ }
102
+ }
@@ -0,0 +1,138 @@
1
+ import { sql } from 'drizzle-orm';
2
+ import { check, index, integer, primaryKey, sqliteTable, text, uniqueIndex, } from 'drizzle-orm/sqlite-core';
3
+ const syncColumns = () => ({
4
+ deletedAt: text(),
5
+ revision: integer().notNull().default(0),
6
+ deviceId: text(),
7
+ });
8
+ export const projects = sqliteTable('projects', {
9
+ id: text().primaryKey().notNull(),
10
+ name: text().notNull(),
11
+ remote: text(),
12
+ createdAt: text().notNull(),
13
+ updatedAt: text().notNull(),
14
+ ...syncColumns(),
15
+ }, (t) => [
16
+ uniqueIndex('projects_remote')
17
+ .on(t.remote)
18
+ .where(sql `${t.remote} is not null and ${t.deletedAt} is null`),
19
+ ]);
20
+ export const projectLocalBindings = sqliteTable('project_local_bindings', {
21
+ projectId: text()
22
+ .primaryKey()
23
+ .notNull()
24
+ .references(() => projects.id, { onDelete: 'cascade' }),
25
+ root: text().notNull().unique('project_local_bindings_root'),
26
+ aliases: text({ mode: 'json' })
27
+ .$type()
28
+ .notNull()
29
+ .default(sql `'[]'`),
30
+ });
31
+ export const commands = sqliteTable('commands', {
32
+ id: text().primaryKey().notNull(),
33
+ name: text().notNull(),
34
+ template: text().notNull(),
35
+ note: text().notNull().default(''),
36
+ type: text().notNull().default('custom'),
37
+ tier: text({ enum: ['hot', 'normal'] })
38
+ .notNull()
39
+ .default('normal'),
40
+ sos: integer({ mode: 'boolean' }).notNull().default(false),
41
+ danger: integer({ mode: 'boolean' }).notNull().default(false),
42
+ projectId: text().references(() => projects.id, { onDelete: 'set null' }),
43
+ createdAt: text().notNull(),
44
+ updatedAt: text().notNull(),
45
+ ...syncColumns(),
46
+ }, (t) => [
47
+ index('commands_project_tier').on(t.projectId, t.tier),
48
+ check('command_tier', sql `${t.tier} in ('hot', 'normal')`),
49
+ check('command_flags', sql `${t.sos} in (0, 1) and ${t.danger} in (0, 1)`),
50
+ ]);
51
+ export const commandUsages = sqliteTable('command_usages', {
52
+ id: text().primaryKey().notNull(),
53
+ commandId: text()
54
+ .notNull()
55
+ .references(() => commands.id, { onDelete: 'cascade' }),
56
+ kind: text({ enum: ['copy', 'run'] }).notNull(),
57
+ usedAt: text().notNull(),
58
+ outcome: text({ enum: ['success', 'failed', 'interrupted'] }).notNull(),
59
+ exitCode: integer(),
60
+ }, (t) => [
61
+ index('usage_command_date').on(t.commandId, t.usedAt),
62
+ index('usage_kind_date').on(t.kind, t.usedAt),
63
+ check('usage_kind', sql `${t.kind} in ('copy', 'run')`),
64
+ check('usage_outcome', sql `${t.outcome} in ('success', 'failed', 'interrupted')`),
65
+ check('copy_outcome', sql `${t.kind} != 'copy' or (${t.outcome} = 'success' and ${t.exitCode} is null)`),
66
+ ]);
67
+ export const decisions = sqliteTable('decisions', {
68
+ id: text().primaryKey().notNull(),
69
+ title: text().notNull(),
70
+ content: text().notNull().default(''),
71
+ reason: text().notNull().default(''),
72
+ alternatives: text().notNull().default(''),
73
+ expected: text().notNull().default(''),
74
+ aiNote: text(),
75
+ domain: text().notNull().default('architecture'),
76
+ confidence: integer(),
77
+ reviewAt: text().notNull(),
78
+ projectId: text().references(() => projects.id, { onDelete: 'set null' }),
79
+ createdAt: text().notNull(),
80
+ updatedAt: text().notNull(),
81
+ ...syncColumns(),
82
+ }, (t) => [
83
+ index('decisions_project_review').on(t.projectId, t.reviewAt),
84
+ check('decision_confidence', sql `${t.confidence} is null or (typeof(${t.confidence}) = 'integer' and ${t.confidence} between 0 and 100)`),
85
+ ]);
86
+ export const decisionReviews = sqliteTable('decision_reviews', {
87
+ id: text().primaryKey().notNull(),
88
+ decisionId: text()
89
+ .notNull()
90
+ .references(() => decisions.id, { onDelete: 'cascade' }),
91
+ reviewedAt: text().notNull(),
92
+ result: text().notNull(),
93
+ rating: text({ enum: ['accurate', 'partial', 'failed'] }).notNull(),
94
+ lesson: text().notNull(),
95
+ snapshot: text({ mode: 'json' }).$type().notNull(),
96
+ ...syncColumns(),
97
+ }, (t) => [
98
+ index('reviews_decision_date').on(t.decisionId, t.reviewedAt, t.id),
99
+ check('review_rating', sql `${t.rating} in ('accurate', 'partial', 'failed')`),
100
+ ]);
101
+ export const tags = sqliteTable('tags', {
102
+ id: text().primaryKey().notNull(),
103
+ name: text().notNull(),
104
+ normalized: text().notNull().unique(),
105
+ updatedAt: text(),
106
+ ...syncColumns(),
107
+ });
108
+ export const entityTags = sqliteTable('entity_tags', {
109
+ tagId: text()
110
+ .notNull()
111
+ .references(() => tags.id, { onDelete: 'cascade' }),
112
+ commandId: text().references(() => commands.id, { onDelete: 'cascade' }),
113
+ decisionId: text().references(() => decisions.id, { onDelete: 'cascade' }),
114
+ deletedAt: text(),
115
+ updatedAt: text(),
116
+ }, (t) => [
117
+ check('entity_tags_owner', sql `(${t.commandId} is null) != (${t.decisionId} is null)`),
118
+ uniqueIndex('entity_tags_command').on(t.commandId, t.tagId),
119
+ uniqueIndex('entity_tags_decision').on(t.decisionId, t.tagId),
120
+ index('entity_tags_tag').on(t.tagId),
121
+ ]);
122
+ export const entityLinks = sqliteTable('entity_links', {
123
+ commandId: text()
124
+ .notNull()
125
+ .references(() => commands.id, { onDelete: 'cascade' }),
126
+ decisionId: text()
127
+ .notNull()
128
+ .references(() => decisions.id, { onDelete: 'cascade' }),
129
+ deletedAt: text(),
130
+ updatedAt: text(),
131
+ }, (t) => [
132
+ primaryKey({ columns: [t.commandId, t.decisionId] }),
133
+ index('entity_links_decision').on(t.decisionId),
134
+ ]);
135
+ export const syncState = sqliteTable('sync_state', {
136
+ key: text().primaryKey().notNull(),
137
+ value: text({ mode: 'json' }).$type().notNull(),
138
+ });
@@ -0,0 +1,48 @@
1
+ import { spawnSync } from 'node:child_process';
2
+ import { realpathSync } from 'node:fs';
3
+ import { resolve } from 'node:path';
4
+ function git(cwd, args) {
5
+ const result = spawnSync('git', args, {
6
+ cwd,
7
+ encoding: 'utf8',
8
+ windowsHide: true,
9
+ timeout: 1500,
10
+ });
11
+ return result.status === 0 ? result.stdout.trimEnd() : undefined;
12
+ }
13
+ export function normalizeRoot(path) {
14
+ let absolute = resolve(path);
15
+ try {
16
+ absolute = realpathSync.native(absolute);
17
+ }
18
+ catch {
19
+ // 导入的历史路径在这台机器上可能不存在。
20
+ }
21
+ return process.platform === 'win32' ? absolute.toLowerCase() : absolute;
22
+ }
23
+ export function normalizeRemote(value) {
24
+ if (!value)
25
+ return null;
26
+ const url = URL.canParse(value) && value.includes('://') ? new URL(value) : undefined;
27
+ const scp = value.match(/^(?:[^@/:]+@)?([^/:]+\.[^/:]+|[^@/:]+):([^/].+|\/[^/].*)$/u);
28
+ if (url?.protocol === 'file:' || (!url && (!scp || /^[A-Za-z]:[\\/]/u.test(value)))) {
29
+ return null;
30
+ }
31
+ const host = url?.host || scp?.[1];
32
+ const path = (url?.pathname || scp?.[2]?.split(/[?#]/u, 1)[0] || '')
33
+ .replace(/^\/+|\/+$/gu, '')
34
+ .replace(/\.git$/u, '');
35
+ return host && path ? `${host.toLowerCase()}/${path}` : null;
36
+ }
37
+ export function detectGit(cwd) {
38
+ const root = git(cwd, ['rev-parse', '--show-toplevel']);
39
+ if (!root)
40
+ return null;
41
+ return {
42
+ root: normalizeRoot(root),
43
+ remote: normalizeRemote(git(root, ['remote', 'get-url', 'origin'])),
44
+ };
45
+ }
46
+ export function gitVersion(cwd) {
47
+ return git(cwd, ['--version']);
48
+ }
@@ -0,0 +1,19 @@
1
+ import clipboardy from 'clipboardy';
2
+ import { AppError } from './errors.js';
3
+ export async function copyToClipboard(text) {
4
+ try {
5
+ await clipboardy.write(text);
6
+ }
7
+ catch (error) {
8
+ throw new AppError(1, 'Clipboard unavailable. Use pxo command render to print the command instead.', { cause: error });
9
+ }
10
+ }
11
+ export async function checkClipboard() {
12
+ try {
13
+ await clipboardy.read();
14
+ return true;
15
+ }
16
+ catch {
17
+ return false;
18
+ }
19
+ }