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,197 @@
1
+ import { isDeepStrictEqual } from 'node:util';
2
+ import { z } from 'zod';
3
+ import { parseTemplate } from '../../features/commands/template.js';
4
+ import { AppError, messageOf } from '../errors.js';
5
+ import { confidence, isoDate, normalize, rating, tier } from '../input.js';
6
+ export const selection = z.enum(['all', 'commands', 'decisions']);
7
+ const id = z.string().min(1);
8
+ const text = z.string();
9
+ const timestamp = z.iso.datetime({ precision: 3 });
10
+ const timestamps = { createdAt: timestamp, updatedAt: timestamp };
11
+ const decisionBody = {
12
+ title: id,
13
+ content: text,
14
+ reason: text,
15
+ alternatives: text,
16
+ expected: text,
17
+ domain: id,
18
+ confidence: confidence.nullable(),
19
+ reviewAt: isoDate,
20
+ };
21
+ export const archiveSchema = z.strictObject({
22
+ schemaVersion: z.union([z.literal(1), z.literal(2)]),
23
+ only: selection,
24
+ projects: z.array(z.strictObject({
25
+ id,
26
+ name: id,
27
+ root: id.nullable(),
28
+ aliases: z.array(id),
29
+ remote: id.nullable(),
30
+ ...timestamps,
31
+ })),
32
+ commands: z.array(z.strictObject({
33
+ id,
34
+ name: id,
35
+ template: id,
36
+ note: text,
37
+ type: id,
38
+ tier,
39
+ sos: z.boolean(),
40
+ danger: z.boolean(),
41
+ projectId: id.nullable(),
42
+ ...timestamps,
43
+ })),
44
+ commandUsages: z.array(z.strictObject({
45
+ id,
46
+ commandId: id,
47
+ kind: z.enum(['copy', 'run']),
48
+ usedAt: timestamp,
49
+ outcome: z.enum(['success', 'failed', 'interrupted']),
50
+ exitCode: z.number().int().nullable(),
51
+ })),
52
+ decisions: z.array(z.strictObject({
53
+ id,
54
+ ...decisionBody,
55
+ aiNote: text.nullable().optional(),
56
+ projectId: id.nullable(),
57
+ ...timestamps,
58
+ })),
59
+ decisionReviews: z.array(z.strictObject({
60
+ id,
61
+ decisionId: id,
62
+ reviewedAt: timestamp,
63
+ result: id,
64
+ rating,
65
+ lesson: id,
66
+ snapshot: z.strictObject(decisionBody),
67
+ })),
68
+ tags: z.array(z.strictObject({ id, name: id, normalized: id })),
69
+ entityTags: z.array(z.strictObject({ tagId: id, commandId: id.nullable(), decisionId: id.nullable() })),
70
+ entityLinks: z.array(z.strictObject({ commandId: id, decisionId: id })),
71
+ });
72
+ const rowId = (row) => row.id;
73
+ const tagKey = (row) => JSON.stringify([row.commandId, row.decisionId, row.tagId]);
74
+ const linkKey = (row) => JSON.stringify([row.commandId, row.decisionId]);
75
+ function invalid(message) {
76
+ throw new AppError(5, 'Invalid Praxo archive: ' + message);
77
+ }
78
+ function keys(rows, key, label) {
79
+ const values = new Set();
80
+ for (const row of rows) {
81
+ const value = key(row);
82
+ if (values.has(value))
83
+ invalid('duplicate ' + label + ' ' + value + '.');
84
+ values.add(value);
85
+ }
86
+ return values;
87
+ }
88
+ function reference(ids, id, label) {
89
+ if (id !== null && !ids.has(id))
90
+ invalid('missing ' + label + ' ' + id + '.');
91
+ }
92
+ /** 除字段类型外,还检查项目身份、业务引用和部分导出的边界。 */
93
+ export function validateArchive(value) {
94
+ if (typeof value !== 'object' ||
95
+ value === null ||
96
+ !('schemaVersion' in value) ||
97
+ (value.schemaVersion !== 1 && value.schemaVersion !== 2)) {
98
+ invalid('unsupported or missing schemaVersion; expected 1 or 2.');
99
+ }
100
+ const parsed = archiveSchema.safeParse(value);
101
+ if (!parsed.success) {
102
+ const problem = parsed.error.issues[0];
103
+ invalid(problem.path.join('.') + ' ' + problem.message);
104
+ }
105
+ const data = parsed.data;
106
+ if (data.projects.some((row) => row.root === null && (data.schemaVersion === 1 || row.aliases.length)))
107
+ invalid('unbound project cannot have aliases, and requires schemaVersion 2.');
108
+ if (data.schemaVersion === 1 && data.decisions.some((row) => row.aiNote !== undefined))
109
+ invalid('AI notes require schemaVersion 2.');
110
+ const projectIds = keys(data.projects, rowId, 'project ID');
111
+ const commandIds = keys(data.commands, rowId, 'command ID');
112
+ const decisionIds = keys(data.decisions, rowId, 'decision ID');
113
+ const tagIds = keys(data.tags, rowId, 'tag ID');
114
+ keys(data.commandUsages, rowId, 'usage ID');
115
+ keys(data.decisionReviews, rowId, 'review ID');
116
+ keys(data.entityTags, tagKey, 'tag association');
117
+ keys(data.entityLinks, linkKey, 'entity link');
118
+ keys(data.projects.flatMap((row) => (row.root === null ? row.aliases : [row.root, ...row.aliases])), (path) => path, 'project path');
119
+ keys(data.projects.flatMap((row) => (row.remote === null ? [] : [row.remote])), (remote) => remote, 'project Remote');
120
+ keys(data.tags, (row) => row.normalized, 'normalized tag');
121
+ for (const row of data.projects) {
122
+ if (row.remote !== null && !/^[^/@\s]+\/[^?#\r\n]+$/u.test(row.remote))
123
+ invalid('invalid project Remote ' + row.id + '.');
124
+ }
125
+ if ((data.only === 'commands' && data.decisions.length) ||
126
+ (data.only === 'decisions' && data.commands.length) ||
127
+ (data.only !== 'all' && data.entityLinks.length))
128
+ invalid('entities do not match the archive selection.');
129
+ for (const row of data.commands) {
130
+ reference(projectIds, row.projectId, 'project');
131
+ try {
132
+ parseTemplate(row.template);
133
+ }
134
+ catch (error) {
135
+ invalid('command ' + row.id + ' has an invalid template. ' + messageOf(error));
136
+ }
137
+ }
138
+ for (const row of data.decisions)
139
+ reference(projectIds, row.projectId, 'project');
140
+ for (const row of data.commandUsages) {
141
+ reference(commandIds, row.commandId, 'command');
142
+ if (row.kind === 'copy' && (row.outcome !== 'success' || row.exitCode !== null))
143
+ invalid('invalid copied usage event ' + row.id + '.');
144
+ }
145
+ for (const row of data.decisionReviews)
146
+ reference(decisionIds, row.decisionId, 'decision');
147
+ for (const row of data.tags) {
148
+ if (!row.normalized || normalize(row.name) !== row.normalized)
149
+ invalid('invalid normalized tag ' + row.id + '.');
150
+ }
151
+ for (const row of data.entityTags) {
152
+ if ((row.commandId === null) === (row.decisionId === null))
153
+ invalid('a tag must belong to exactly one entity.');
154
+ reference(commandIds, row.commandId, 'command');
155
+ reference(decisionIds, row.decisionId, 'decision');
156
+ reference(tagIds, row.tagId, 'tag');
157
+ }
158
+ for (const row of data.entityLinks) {
159
+ reference(commandIds, row.commandId, 'command');
160
+ reference(decisionIds, row.decisionId, 'decision');
161
+ }
162
+ return data;
163
+ }
164
+ function missing(label, source, current, key) {
165
+ const stored = new Map(current.map((row) => [key(row), row]));
166
+ return source.filter((row) => {
167
+ const found = stored.get(key(row));
168
+ if (found === undefined)
169
+ return true;
170
+ if (!isDeepStrictEqual(found, row)) {
171
+ throw new AppError(5, 'Import conflict for ' +
172
+ label +
173
+ ' ' +
174
+ key(row) +
175
+ '. Resolve differing data or use an interactive full replacement.');
176
+ }
177
+ return false;
178
+ });
179
+ }
180
+ export function planMerge(current, incoming) {
181
+ const added = {
182
+ schemaVersion: incoming.schemaVersion,
183
+ only: incoming.only,
184
+ projects: missing('project', incoming.projects, current.projects, rowId),
185
+ commands: missing('command', incoming.commands, current.commands, rowId),
186
+ commandUsages: missing('usage', incoming.commandUsages, current.commandUsages, rowId),
187
+ decisions: missing('decision', incoming.decisions.map((row) => ({ ...row, aiNote: row.aiNote ?? null })), current.decisions.map((row) => ({ ...row, aiNote: row.aiNote ?? null })), rowId),
188
+ decisionReviews: missing('review', incoming.decisionReviews, current.decisionReviews, rowId),
189
+ tags: missing('tag', incoming.tags, current.tags, rowId),
190
+ entityTags: missing('tag association', incoming.entityTags, current.entityTags, tagKey),
191
+ entityLinks: missing('link', incoming.entityLinks, current.entityLinks, linkKey),
192
+ };
193
+ keys([...current.projects, ...added.projects].flatMap((row) => row.root === null ? row.aliases : [row.root, ...row.aliases]), (path) => path, 'project path in merge');
194
+ keys([...current.projects, ...added.projects].flatMap((row) => row.remote === null ? [] : [row.remote]), (remote) => remote, 'project Remote in merge');
195
+ keys([...current.tags, ...added.tags], (row) => row.normalized, 'normalized tag in merge');
196
+ return added;
197
+ }
@@ -0,0 +1,53 @@
1
+ function fence(template) {
2
+ const length = Math.max(3, ...[...template.matchAll(/`+/gu)].map(([run]) => run.length + 1));
3
+ const delimiter = '`'.repeat(length);
4
+ return [delimiter, template, delimiter].join('\n');
5
+ }
6
+ function heading(label) {
7
+ return label.replace(/\r?\n/gu, ' ');
8
+ }
9
+ export function markdown(data) {
10
+ const out = ['# Praxo'];
11
+ if (data.only !== 'decisions') {
12
+ out.push('## Commands');
13
+ for (const command of data.commands) {
14
+ out.push('### ' + heading(command.name), fence(command.template));
15
+ if (command.note)
16
+ out.push(command.note);
17
+ }
18
+ }
19
+ if (data.only !== 'commands') {
20
+ const history = new Map();
21
+ for (const review of data.decisionReviews) {
22
+ const list = history.get(review.decisionId);
23
+ if (list)
24
+ list.push(review);
25
+ else
26
+ history.set(review.decisionId, [review]);
27
+ }
28
+ out.push('## Decisions');
29
+ for (const record of data.decisions) {
30
+ out.push('### ' + heading(record.title), 'Review date: ' + record.reviewAt);
31
+ if (record.content)
32
+ out.push(record.content);
33
+ if (record.reason)
34
+ out.push('**Reason**\n\n' + record.reason);
35
+ if (record.alternatives)
36
+ out.push('**Alternatives**\n\n' + record.alternatives);
37
+ if (record.expected)
38
+ out.push('**Expected**\n\n' + record.expected);
39
+ if (record.aiNote)
40
+ out.push('**AI note**\n\n' + record.aiNote);
41
+ if (record.confidence !== null)
42
+ out.push('**Confidence** ' + record.confidence + '%');
43
+ const reviews = history
44
+ .get(record.id)
45
+ ?.sort((a, b) => b.reviewedAt.localeCompare(a.reviewedAt) || b.id.localeCompare(a.id));
46
+ for (const review of reviews ?? []) {
47
+ out.push('#### Review · ' + review.reviewedAt + ' · ' + review.rating, '**Then** ' + review.snapshot.title, '**Reason at the time**\n\n' + (review.snapshot.reason || '—'), '**Alternatives at the time**\n\n' + (review.snapshot.alternatives || '—'), '**Expected at the time**\n\n' + (review.snapshot.expected || '—'), '**Confidence at the time** ' +
48
+ (review.snapshot.confidence === null ? '—' : review.snapshot.confidence + '%'), '**Actual result**\n\n' + review.result, '**Lesson**\n\n' + review.lesson);
49
+ }
50
+ }
51
+ }
52
+ return out.join('\n\n') + '\n';
53
+ }
@@ -0,0 +1,278 @@
1
+ import { chmodSync, mkdirSync, renameSync, rmSync } from 'node:fs';
2
+ import { dirname, join } from 'node:path';
3
+ import Database from 'better-sqlite3';
4
+ import { eq, isNull } from 'drizzle-orm';
5
+ import { commandUsages, commands, decisionReviews, decisions, entityLinks, entityTags, projectLocalBindings, projects, tags, } from '../../infrastructure/database/schema.js';
6
+ import { withoutSyncMetadata } from '../sync-metadata.js';
7
+ import { AppError, messageOf } from '../errors.js';
8
+ import { newId } from '../input.js';
9
+ import { planMerge, validateArchive } from './archive.js';
10
+ function counts(data) {
11
+ return {
12
+ projects: data.projects.length,
13
+ commands: data.commands.length,
14
+ commandUsages: data.commandUsages.length,
15
+ decisions: data.decisions.length,
16
+ decisionReviews: data.decisionReviews.length,
17
+ tags: data.tags.length,
18
+ entityTags: data.entityTags.length,
19
+ entityLinks: data.entityLinks.length,
20
+ };
21
+ }
22
+ /** 在替换事务持有写锁期间,用独立读连接获取包含 WAL 中数据的一致备份。 */
23
+ async function backup(path) {
24
+ const folder = join(dirname(path), 'backups');
25
+ mkdirSync(folder, { recursive: true, mode: 0o700 });
26
+ const final = join(folder, 'praxo-' + new Date().toISOString().replace(/[:.]/gu, '-') + '-' + newId() + '.sqlite');
27
+ const temporary = final + '.partial';
28
+ const reader = new Database(path, { readonly: true, fileMustExist: true, timeout: 3000 });
29
+ try {
30
+ await reader.backup(temporary);
31
+ chmodSync(temporary, 0o600);
32
+ renameSync(temporary, final);
33
+ return final;
34
+ }
35
+ finally {
36
+ reader.close();
37
+ rmSync(temporary, { force: true });
38
+ }
39
+ }
40
+ function archiveAssociation(value) {
41
+ const row = withoutSyncMetadata(value);
42
+ delete row.updatedAt;
43
+ return row;
44
+ }
45
+ export function transferService({ db, native }, path, now) {
46
+ const snapshot = (only = 'all') => native
47
+ .transaction(() => {
48
+ const commandRows = only === 'decisions'
49
+ ? []
50
+ : db
51
+ .select()
52
+ .from(commands)
53
+ .where(isNull(commands.deletedAt))
54
+ .orderBy(commands.id)
55
+ .all()
56
+ .map(withoutSyncMetadata);
57
+ const decisionRows = only === 'commands'
58
+ ? []
59
+ : db
60
+ .select()
61
+ .from(decisions)
62
+ .where(isNull(decisions.deletedAt))
63
+ .orderBy(decisions.id)
64
+ .all()
65
+ .map(withoutSyncMetadata);
66
+ const associations = db
67
+ .select()
68
+ .from(entityTags)
69
+ .where(isNull(entityTags.deletedAt))
70
+ .orderBy(entityTags.commandId, entityTags.decisionId, entityTags.tagId)
71
+ .all()
72
+ .map(archiveAssociation)
73
+ .filter((row) => only === 'all' ||
74
+ (only === 'commands' ? row.commandId !== null : row.decisionId !== null));
75
+ const decisionIds = new Set(decisionRows.map(({ id }) => id));
76
+ const projectIds = new Set([...commandRows, ...decisionRows].map((row) => row.projectId));
77
+ const tagIds = new Set(associations.map((row) => row.tagId));
78
+ return {
79
+ schemaVersion: 2,
80
+ only,
81
+ commands: commandRows,
82
+ decisions: decisionRows,
83
+ projects: db
84
+ .select({ project: projects, binding: projectLocalBindings })
85
+ .from(projects)
86
+ .leftJoin(projectLocalBindings, eq(projects.id, projectLocalBindings.projectId))
87
+ .where(isNull(projects.deletedAt))
88
+ .orderBy(projects.id)
89
+ .all()
90
+ .map(({ project, binding }) => ({
91
+ ...withoutSyncMetadata(project),
92
+ root: binding?.root ?? null,
93
+ aliases: binding?.aliases ?? [],
94
+ }))
95
+ .filter((row) => only === 'all' || projectIds.has(row.id)),
96
+ commandUsages: only === 'decisions'
97
+ ? []
98
+ : db
99
+ .select({ usage: commandUsages })
100
+ .from(commandUsages)
101
+ .innerJoin(commands, eq(commands.id, commandUsages.commandId))
102
+ .where(isNull(commands.deletedAt))
103
+ .orderBy(commandUsages.id)
104
+ .all()
105
+ .map(({ usage }) => usage),
106
+ decisionReviews: only === 'commands'
107
+ ? []
108
+ : db
109
+ .select()
110
+ .from(decisionReviews)
111
+ .where(isNull(decisionReviews.deletedAt))
112
+ .orderBy(decisionReviews.id)
113
+ .all()
114
+ .filter((row) => decisionIds.has(row.decisionId))
115
+ .map(withoutSyncMetadata),
116
+ tags: db
117
+ .select()
118
+ .from(tags)
119
+ .where(isNull(tags.deletedAt))
120
+ .orderBy(tags.id)
121
+ .all()
122
+ .filter((row) => only === 'all' || tagIds.has(row.id))
123
+ .map(archiveAssociation),
124
+ entityTags: associations,
125
+ entityLinks: only === 'all'
126
+ ? db
127
+ .select()
128
+ .from(entityLinks)
129
+ .where(isNull(entityLinks.deletedAt))
130
+ .orderBy(entityLinks.commandId, entityLinks.decisionId)
131
+ .all()
132
+ .map(archiveAssociation)
133
+ : [],
134
+ };
135
+ })
136
+ .deferred();
137
+ function summarize(incoming, mode) {
138
+ if (mode === 'replace' && incoming.only !== 'all') {
139
+ throw new AppError(5, 'Replacement requires a full archive. Export with --only all.');
140
+ }
141
+ const current = snapshot();
142
+ if (mode === 'replace')
143
+ return { added: counts(incoming), removed: counts(current) };
144
+ const added = counts(planMerge(current, incoming));
145
+ const total = counts(incoming);
146
+ const skipped = { ...total };
147
+ for (const key of Object.keys(total))
148
+ skipped[key] -= added[key];
149
+ return { added, skipped };
150
+ }
151
+ function insert(data) {
152
+ const at = now().toISOString();
153
+ for (const { root, aliases, ...row } of data.projects) {
154
+ const values = { ...row, deletedAt: null };
155
+ db.insert(projects)
156
+ .values(values)
157
+ .onConflictDoUpdate({ target: projects.id, set: values })
158
+ .run();
159
+ if (root !== null)
160
+ db.insert(projectLocalBindings)
161
+ .values({ projectId: row.id, root, aliases })
162
+ .onConflictDoUpdate({ target: projectLocalBindings.projectId, set: { root, aliases } })
163
+ .run();
164
+ }
165
+ for (const row of data.commands) {
166
+ const values = { ...row, deletedAt: null };
167
+ db.insert(commands)
168
+ .values(values)
169
+ .onConflictDoUpdate({ target: commands.id, set: values })
170
+ .run();
171
+ }
172
+ for (const row of data.decisions) {
173
+ const values = { ...row, aiNote: row.aiNote ?? null, deletedAt: null };
174
+ db.insert(decisions)
175
+ .values(values)
176
+ .onConflictDoUpdate({ target: decisions.id, set: values })
177
+ .run();
178
+ }
179
+ const tagIds = new Map();
180
+ for (const row of data.tags) {
181
+ const existing = db.select().from(tags).where(eq(tags.normalized, row.normalized)).get();
182
+ const values = { ...row, id: existing?.id ?? row.id, deletedAt: null, updatedAt: at };
183
+ tagIds.set(row.id, values.id);
184
+ db.insert(tags).values(values).onConflictDoUpdate({ target: tags.id, set: values }).run();
185
+ }
186
+ for (const row of data.commandUsages)
187
+ db.insert(commandUsages).values(row).run();
188
+ for (const row of data.decisionReviews) {
189
+ const values = { ...row, deletedAt: null };
190
+ db.insert(decisionReviews)
191
+ .values(values)
192
+ .onConflictDoUpdate({ target: decisionReviews.id, set: values })
193
+ .run();
194
+ }
195
+ for (const row of data.entityTags) {
196
+ const owner = row.commandId === null ? entityTags.decisionId : entityTags.commandId;
197
+ db.insert(entityTags)
198
+ .values({ ...row, tagId: tagIds.get(row.tagId) ?? row.tagId, updatedAt: at })
199
+ .onConflictDoUpdate({
200
+ target: [owner, entityTags.tagId],
201
+ set: { deletedAt: null, updatedAt: at },
202
+ })
203
+ .run();
204
+ }
205
+ for (const row of data.entityLinks)
206
+ db.insert(entityLinks)
207
+ .values({ ...row, updatedAt: at })
208
+ .onConflictDoUpdate({
209
+ target: [entityLinks.commandId, entityLinks.decisionId],
210
+ set: { deletedAt: null, updatedAt: at },
211
+ })
212
+ .run();
213
+ }
214
+ async function importArchive(raw, mode, confirmed = false) {
215
+ const incoming = validateArchive(raw);
216
+ if (mode === 'merge') {
217
+ return native
218
+ .transaction(() => {
219
+ const added = planMerge(snapshot(), incoming);
220
+ insert(added);
221
+ return { added: counts(added) };
222
+ })
223
+ .immediate();
224
+ }
225
+ if (incoming.only !== 'all')
226
+ throw new AppError(5, 'Replacement requires a full archive.');
227
+ if (!confirmed)
228
+ throw new AppError(4, 'Replacement requires interactive confirmation.');
229
+ let backupPath;
230
+ try {
231
+ native.exec('BEGIN IMMEDIATE');
232
+ backupPath = await backup(path);
233
+ const at = now().toISOString();
234
+ db.delete(commandUsages).run();
235
+ db.delete(projectLocalBindings).run();
236
+ db.update(entityLinks)
237
+ .set({ deletedAt: at, updatedAt: at })
238
+ .where(isNull(entityLinks.deletedAt))
239
+ .run();
240
+ db.update(entityTags)
241
+ .set({ deletedAt: at, updatedAt: at })
242
+ .where(isNull(entityTags.deletedAt))
243
+ .run();
244
+ db.update(decisionReviews)
245
+ .set({ deletedAt: at })
246
+ .where(isNull(decisionReviews.deletedAt))
247
+ .run();
248
+ db.update(commands)
249
+ .set({ deletedAt: at, updatedAt: at })
250
+ .where(isNull(commands.deletedAt))
251
+ .run();
252
+ db.update(decisions)
253
+ .set({ deletedAt: at, updatedAt: at })
254
+ .where(isNull(decisions.deletedAt))
255
+ .run();
256
+ db.update(tags).set({ deletedAt: at, updatedAt: at }).where(isNull(tags.deletedAt)).run();
257
+ db.update(projects)
258
+ .set({ deletedAt: at, updatedAt: at })
259
+ .where(isNull(projects.deletedAt))
260
+ .run();
261
+ insert(incoming);
262
+ native.exec('COMMIT');
263
+ return { added: counts(incoming), backupPath };
264
+ }
265
+ catch (error) {
266
+ if (native.inTransaction)
267
+ native.exec('ROLLBACK');
268
+ throw new AppError(5, 'Could not replace local data. ' +
269
+ messageOf(error) +
270
+ (backupPath ? ' Backup saved to ' + backupPath + '.' : ''), { cause: error });
271
+ }
272
+ }
273
+ return {
274
+ snapshot,
275
+ preview: (raw, mode) => summarize(validateArchive(raw), mode),
276
+ import: importArchive,
277
+ };
278
+ }
@@ -0,0 +1,121 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { Box, Text, useApp, useInput, useWindowSize } from 'ink';
3
+ import { useMemo, useRef, useState } from 'react';
4
+ import { AppError } from '../shared/errors.js';
5
+ import { AiSettings } from './components/AiPanel.js';
6
+ import { SyncPanel, useSyncPanel } from './components/SyncPanel.js';
7
+ import { HelpModal } from './components/HelpModal.js';
8
+ import { CommandsScreen } from './screens/Commands.js';
9
+ import { DecisionsScreen } from './screens/Decisions.js';
10
+ import { LinksScreen, LookupScreen } from './screens/Lookup.js';
11
+ import { theme } from './theme.js';
12
+ /** 顶层全屏工作台容器:遵循国际 TUI 键位规范(Tab/1/2 切模块、Ctrl+K 全局搜索、q 退出、Esc 永不误退)。 */
13
+ export function Workspace({ app, initial }) {
14
+ const { rows } = useWindowSize();
15
+ const [section, setSection] = useState(initial);
16
+ const [locked, lock] = useState(false);
17
+ const [overlay, setOverlay] = useState();
18
+ const [destination, setDestination] = useState();
19
+ const [badgeRevision, refreshBadge] = useState(0);
20
+ const [syncRevision, refreshSync] = useState(0);
21
+ const sync = useSyncPanel(app.sync, () => {
22
+ refreshSync((value) => value + 1);
23
+ refreshBadge((value) => value + 1);
24
+ });
25
+ const aiStatus = useMemo(() => {
26
+ void badgeRevision;
27
+ try {
28
+ const ai = app.ai.settings();
29
+ return ai ? `AI · ${ai.provider}` : 'AI Off';
30
+ }
31
+ catch {
32
+ return 'AI Config Error';
33
+ }
34
+ }, [app, badgeRevision]);
35
+ const showSync = Boolean(sync.panel && !locked && !overlay);
36
+ const syncStatus = useMemo(() => {
37
+ void badgeRevision;
38
+ try {
39
+ const state = app.sync.status().status;
40
+ return state === 'Unconfigured' ? undefined : state;
41
+ }
42
+ catch {
43
+ return 'Error';
44
+ }
45
+ }, [app, badgeRevision]);
46
+ const interrupt = useRef(undefined);
47
+ const { exit } = useApp();
48
+ const project = useMemo(() => {
49
+ void syncRevision;
50
+ return app.projects.current();
51
+ }, [app, syncRevision]);
52
+ const dueCount = useMemo(() => {
53
+ void badgeRevision;
54
+ try {
55
+ return app.decisions.countDue();
56
+ }
57
+ catch {
58
+ return 0;
59
+ }
60
+ }, [app, badgeRevision]);
61
+ function switchSection(next) {
62
+ if (next === section)
63
+ return;
64
+ setSection(next);
65
+ setDestination(undefined);
66
+ refreshBadge((value) => value + 1);
67
+ }
68
+ useInput((key, info) => {
69
+ if (info.ctrl && key === 'c') {
70
+ if (interrupt.current)
71
+ interrupt.current();
72
+ else if (sync.isRunning())
73
+ sync.close();
74
+ else
75
+ exit(new AppError(130, 'Interrupted.'));
76
+ return;
77
+ }
78
+ if (locked || overlay || showSync)
79
+ return;
80
+ if (key === 'S' && !info.ctrl && !info.meta) {
81
+ void sync.start();
82
+ return;
83
+ }
84
+ if (info.ctrl && (key === 'k' || key === 'p')) {
85
+ setOverlay({ kind: 'lookup' });
86
+ return;
87
+ }
88
+ if (info.ctrl && key === 'e') {
89
+ setOverlay({ kind: 'ai-settings' });
90
+ return;
91
+ }
92
+ if (key === '?' && !info.ctrl && !info.meta) {
93
+ setOverlay({ kind: 'help' });
94
+ return;
95
+ }
96
+ if (info.tab) {
97
+ switchSection(section === 'commands' ? 'decisions' : 'commands');
98
+ return;
99
+ }
100
+ if (!info.ctrl && (key === '1' || key === '2')) {
101
+ switchSection(key === '1' ? 'commands' : 'decisions');
102
+ return;
103
+ }
104
+ if (key === 'q' && !info.ctrl && !info.meta && !sync.isRunning())
105
+ exit();
106
+ });
107
+ function navigate(target) {
108
+ setOverlay(undefined);
109
+ setSection(target.kind === 'command' ? 'commands' : 'decisions');
110
+ setDestination((current) => ({ id: target.id, revision: (current?.revision ?? 0) + 1 }));
111
+ refreshBadge((value) => value + 1);
112
+ }
113
+ return (_jsxs(Box, { flexDirection: "column", height: Math.max(12, rows), width: "100%", children: [_jsxs(Box, { flexShrink: 0, paddingX: 2, justifyContent: "space-between", children: [_jsxs(Box, { gap: 3, children: [_jsx(Text, { bold: true, color: theme.brand, children: "\u25C6 Praxo" }), _jsxs(Box, { gap: 2, children: [_jsxs(Text, { bold: section === 'commands', color: section === 'commands' ? theme.accent : undefined, dimColor: section !== 'commands', children: [section === 'commands' ? '● ' : ' ', "[1] Commands"] }), _jsxs(Box, { gap: 1, children: [_jsxs(Text, { bold: section === 'decisions', color: section === 'decisions' ? theme.accent : undefined, dimColor: section !== 'decisions', children: [section === 'decisions' ? '● ' : ' ', "[2] Decisions"] }), dueCount > 0 && _jsxs(Text, { color: theme.warning, children: ["\u00B7 ", dueCount, " Due"] })] })] })] }), _jsx(Text, { dimColor: true, wrap: "truncate-end", children: [sync.status ?? syncStatus, aiStatus, project ? `⎇ ${project.name}` : 'Global']
114
+ .filter(Boolean)
115
+ .join(' · ') })] }), _jsx(Box, { flexDirection: "column", flexGrow: 1, display: overlay || showSync ? 'none' : 'flex', children: section === 'commands' ? (_jsx(CommandsScreen, { app: app, active: !overlay && !showSync, refreshToken: syncRevision, initialId: destination?.id, lock: lock, onChanged: () => refreshBadge((value) => value + 1), setInterrupt: (action) => {
116
+ interrupt.current = action;
117
+ }, onLinks: (id) => setOverlay({ kind: 'links', target: { kind: 'command', id } }) }, destination?.revision)) : (_jsx(DecisionsScreen, { app: app, active: !overlay && !showSync, refreshToken: syncRevision, initialId: destination?.id, lock: lock, onChanged: () => refreshBadge((value) => value + 1), onLinks: (id) => setOverlay({ kind: 'links', target: { kind: 'decision', id } }) }, destination?.revision)) }), showSync && _jsx(SyncPanel, { controller: sync }), overlay?.kind === 'lookup' && (_jsx(Box, { flexDirection: "column", flexGrow: 1, children: _jsx(LookupScreen, { app: app, onOpen: navigate, onClose: () => setOverlay(undefined) }) })), overlay?.kind === 'links' && (_jsx(Box, { flexDirection: "column", flexGrow: 1, children: _jsx(LinksScreen, { app: app, target: overlay.target, onOpen: navigate, onClose: () => setOverlay(undefined) }) })), overlay?.kind === 'help' && (_jsx(Box, { flexDirection: "column", flexGrow: 1, padding: 1, children: _jsx(HelpModal, { section: section, onClose: () => setOverlay(undefined) }) })), overlay?.kind === 'ai-settings' && (_jsx(Box, { flexDirection: "column", flexGrow: 1, padding: 1, children: _jsx(AiSettings, { app: app, onClose: () => setOverlay(undefined), onSaved: () => {
118
+ setOverlay(undefined);
119
+ refreshBadge((value) => value + 1);
120
+ } }) }))] }));
121
+ }