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,287 @@
1
+ import { Option } from 'commander';
2
+ import { AppError } from '../../shared/errors.js';
3
+ import { collect, formatTable, limit, output, outputList } from '../output.js';
4
+ import { confirmRemoval, field, prompt, requirePrompt } from '../prompts.js';
5
+ function integer(value, name) {
6
+ if (value === undefined)
7
+ return undefined;
8
+ if (!/^\d+$/u.test(value) || !Number.isSafeInteger(Number(value))) {
9
+ throw new AppError(2, name + ' must be an integer.');
10
+ }
11
+ return Number(value);
12
+ }
13
+ function duration(value) {
14
+ if (value === undefined)
15
+ return undefined;
16
+ if (!/^[1-9]\d*d$/u.test(value)) {
17
+ throw new AppError(2, 'Use --in with a positive number of days, for example 90d.');
18
+ }
19
+ return integer(value.slice(0, -1), '--in');
20
+ }
21
+ function rowCells(item) {
22
+ return [
23
+ item.id,
24
+ item.title,
25
+ item.status,
26
+ item.reviewAt,
27
+ item.domain,
28
+ item.projectName ?? 'Global',
29
+ ];
30
+ }
31
+ function line(item) {
32
+ return rowCells(item).join('\t');
33
+ }
34
+ function detail(item) {
35
+ return [
36
+ line(item),
37
+ item.content,
38
+ item.reason && 'Reason: ' + item.reason,
39
+ item.alternatives && 'Alternatives: ' + item.alternatives,
40
+ item.expected && 'Expected: ' + item.expected,
41
+ 'Confidence: ' + (item.confidence === null ? '—' : item.confidence + '%'),
42
+ 'Tags: ' + (item.tags.join(', ') || '—'),
43
+ ]
44
+ .filter(Boolean)
45
+ .join('\n');
46
+ }
47
+ /** 注册决策列表、搜索与待复盘共用的筛选选项。 */
48
+ function queryOptions(command, includeStatus) {
49
+ const configured = command
50
+ .option('--domain <domain>', 'Filter by decision domain')
51
+ .addOption(new Option('--scope <scope>', 'Filter by visibility scope').choices([
52
+ 'global',
53
+ 'project',
54
+ 'all',
55
+ ]))
56
+ .option('-p, --project <id>', 'Filter by project ID or "current"')
57
+ .option('--tag <tag>', 'Filter by tag (repeatable)', collect, [])
58
+ .addOption(new Option('--sort <mode>', 'Sort order').choices(['recent', 'review-at', 'confidence']))
59
+ .option('-L, --limit <n>', 'Maximum number of results to return')
60
+ .option('--json', 'Output JSON');
61
+ if (includeStatus) {
62
+ configured.addOption(new Option('--status <status>', 'Filter by review status').choices([
63
+ 'open',
64
+ 'due',
65
+ 'reviewed',
66
+ 'all',
67
+ ]));
68
+ }
69
+ return configured;
70
+ }
71
+ function list(app, options, due = false, query) {
72
+ const { json, tag, limit: count, ...filters } = options;
73
+ const rows = app.decisions.list({
74
+ ...filters,
75
+ status: due ? 'due' : filters.status,
76
+ tags: tag,
77
+ limit: limit(count),
78
+ }, query);
79
+ outputList(rows, json, () => formatTable(['ID', 'Title', 'Status', 'Review', 'Domain', 'Scope'], rows.map(rowCells)), 'No matching decisions.');
80
+ }
81
+ /** 注册决策新增与编辑共用的字段选项。 */
82
+ function decisionFields(command, edit = false) {
83
+ const fields = command
84
+ .option('--content <text>', 'Background context or decision details')
85
+ .option('--reason <text>', 'Rationale behind the decision')
86
+ .option('--alternatives <text>', 'Alternatives considered')
87
+ .option('--expected <text>', 'Expected outcome or success criteria')
88
+ .option('--confidence <percent>', 'Confidence level (0-100)')
89
+ .option('--domain <domain>', 'Decision domain (e.g. architecture, product)')
90
+ .option('--review-at <date>', 'Scheduled review date (YYYY-MM-DD)')
91
+ .addOption(new Option('--scope <scope>', 'Visibility scope').choices(edit ? ['global', 'project'] : ['auto', 'global', 'project']))
92
+ .option('-p, --project <id>', 'Bind to a project ID or "current"');
93
+ const extended = edit
94
+ ? fields.option('--title <title>', 'Updated decision title')
95
+ : fields
96
+ .addOption(new Option('--in <days>', 'Schedule review N days from today (e.g. 90d)').conflicts('reviewAt'))
97
+ .option('--tag <tag>', 'Attach a tag (repeatable)', collect, []);
98
+ return extended.option('--json', 'Output JSON');
99
+ }
100
+ async function add(app, title, options) {
101
+ const { tag, in: days, confidence, json, ...fields } = options;
102
+ if (title === undefined) {
103
+ requirePrompt('Supply a title, for example: pxo decide "Use SQLite".');
104
+ const answers = await prompt(async (ask) => {
105
+ const answeredTitle = await ask('Decision title: ');
106
+ const reason = fields.reason ?? (await field(ask, 'Reason (optional)', ''));
107
+ const reviewAt = fields.reviewAt ??
108
+ (days === undefined
109
+ ? await field(ask, 'Review date (optional)', '90 days from now')
110
+ : undefined);
111
+ return { title: answeredTitle, reason, reviewAt };
112
+ });
113
+ title = answers.title;
114
+ fields.reason = answers.reason;
115
+ fields.reviewAt = answers.reviewAt;
116
+ }
117
+ const row = app.decisions.create({
118
+ ...fields,
119
+ title,
120
+ tags: tag,
121
+ inDays: duration(days),
122
+ confidence: integer(confidence, '--confidence'),
123
+ });
124
+ output(row, json, () => 'Added ' + line(row));
125
+ }
126
+ async function edit(app, id, options) {
127
+ const { json, ...patch } = options;
128
+ const record = app.decisions.show(id);
129
+ let updates = patch;
130
+ if (!Object.values(updates).some((value) => value !== undefined)) {
131
+ requirePrompt('Pass at least one field to update, for example --reason.');
132
+ updates = await prompt(async (ask) => ({
133
+ title: await field(ask, 'Title', record.title),
134
+ reason: await field(ask, 'Reason', record.reason),
135
+ alternatives: await field(ask, 'Alternatives', record.alternatives),
136
+ expected: await field(ask, 'Expected', record.expected),
137
+ confidence: await field(ask, 'Confidence', String(record.confidence ?? '')),
138
+ domain: await field(ask, 'Domain', record.domain),
139
+ reviewAt: await field(ask, 'Review date (YYYY-MM-DD)', record.reviewAt),
140
+ }));
141
+ if (Object.values(updates).every((value) => value === undefined)) {
142
+ output({ id, updated: false, record }, json, () => 'No changes.');
143
+ return;
144
+ }
145
+ }
146
+ const row = app.decisions.edit(id, {
147
+ ...updates,
148
+ confidence: integer(updates.confidence, '--confidence'),
149
+ });
150
+ output(row, json, () => 'Updated ' + line(row));
151
+ }
152
+ async function addReview(app, id, options) {
153
+ const { json, ...input } = options;
154
+ const item = app.decisions.show(id);
155
+ let reviewData = input;
156
+ if (reviewData.result === undefined ||
157
+ reviewData.rating === undefined ||
158
+ reviewData.lesson === undefined) {
159
+ requirePrompt('Provide --result, --rating and --lesson to review without a terminal.');
160
+ process.stderr.write(detail(item) + '\n');
161
+ reviewData = await prompt(async (ask) => ({
162
+ result: reviewData.result ?? (await ask('Actual result: ')),
163
+ rating: reviewData.rating ??
164
+ (await ask('Rating (accurate/partial/failed): ')).trim(),
165
+ lesson: reviewData.lesson ?? (await ask('Lesson: ')),
166
+ }));
167
+ }
168
+ const result = app.decisions.review(id, reviewData);
169
+ output(result, json, () => 'Recorded review ' + result.id + ' (' + result.rating + ').');
170
+ }
171
+ function renderStats(result) {
172
+ const grade = result.highConfidence;
173
+ const accuracy = grade.accuracy === null ? 'No data' : (grade.accuracy * 100).toFixed(1) + '%';
174
+ return [
175
+ 'Decisions: ' +
176
+ result.total +
177
+ ' · Open ' +
178
+ result.open +
179
+ ' · Due ' +
180
+ result.due +
181
+ ' · Reviewed ' +
182
+ result.reviewed,
183
+ 'Reviews in last six calendar months: ' + result.reviewsLastSixMonths,
184
+ 'High-confidence accuracy (≥' + grade.threshold + ', n=' + grade.samples + '): ' + accuracy,
185
+ 'Domains: ' +
186
+ (Object.entries(result.domains)
187
+ .map(([name, count]) => name + ' ' + count)
188
+ .join(', ') || '—'),
189
+ 'Command usage: ' + result.usage.copy + ' copied · ' + result.usage.run + ' executed',
190
+ ].join('\n');
191
+ }
192
+ /** 注册 `pxo decision`(别名 `d`)命令组。 */
193
+ export function registerDecisions(program, withApp) {
194
+ const decisions = program
195
+ .command('decision')
196
+ .alias('d')
197
+ .description('Manage decisions and reviews');
198
+ queryOptions(decisions.command('list').alias('ls').description('List decisions'), true).action((options) => withApp((app) => list(app, options, false)));
199
+ queryOptions(decisions.command('search <query>').alias('s').description('Search decisions'), true).action((query, options) => withApp((app) => list(app, options, false, query)));
200
+ queryOptions(decisions.command('due').description('List decisions due for review'), false).action((options) => withApp((app) => list(app, options, true)));
201
+ decisions
202
+ .command('show <id>')
203
+ .description('Show decision details')
204
+ .option('--json', 'Output JSON')
205
+ .action((id, options) => withApp((app) => {
206
+ const row = app.decisions.show(id);
207
+ output(row, options.json, () => detail(row));
208
+ }));
209
+ decisionFields(decisions.command('add [title]').description('Record a new decision')).action((title, options) => withApp((app) => add(app, title, options)));
210
+ decisionFields(decisions.command('edit <id>').description('Edit a decision'), true).action((id, options) => withApp((app) => edit(app, id, options)));
211
+ decisions
212
+ .command('remove <id>')
213
+ .alias('rm')
214
+ .description('Delete a decision and its reviews')
215
+ .option('-y, --yes', 'Skip deletion confirmation')
216
+ .option('--json', 'Output JSON')
217
+ .action((id, options) => withApp(async (app) => {
218
+ await confirmRemoval(app.decisions.show(id).title, options.yes);
219
+ app.decisions.remove(id);
220
+ output({ id, deleted: true }, options.json, () => 'Deleted decision ' + id + '.');
221
+ }));
222
+ const reviewGroup = decisions.command('review').description('Manage decision reviews');
223
+ reviewGroup
224
+ .command('add <id>')
225
+ .description('Append a review to a decision')
226
+ .option('--result <text>', 'Observed actual outcome')
227
+ .addOption(new Option('--rating <rating>', 'Outcome accuracy rating').choices([
228
+ 'accurate',
229
+ 'partial',
230
+ 'failed',
231
+ ]))
232
+ .option('--lesson <text>', 'Key takeaway or lesson learned')
233
+ .option('--json', 'Output JSON')
234
+ .action((id, options) => withApp((app) => addReview(app, id, options)));
235
+ reviewGroup
236
+ .command('list <id>')
237
+ .alias('ls')
238
+ .description('Show review history for a decision')
239
+ .option('--json', 'Output JSON')
240
+ .action((id, options) => withApp((app) => {
241
+ const rows = app.decisions.history(id);
242
+ outputList(rows, options.json, () => rows
243
+ .map((row) => [
244
+ row.reviewedAt + ' · ' + row.rating,
245
+ 'Then: ' + row.snapshot.title,
246
+ row.snapshot.reason && 'Reason: ' + row.snapshot.reason,
247
+ 'Result: ' + row.result,
248
+ 'Lesson: ' + row.lesson,
249
+ ]
250
+ .filter(Boolean)
251
+ .join('\n'))
252
+ .join('\n\n'), 'No reviews yet.');
253
+ }));
254
+ const tags = decisions.command('tag').description('Manage decision tags');
255
+ for (const action of ['add', 'remove']) {
256
+ const sub = tags
257
+ .command(action + ' <id> <tag>')
258
+ .description(action === 'add' ? 'Attach a tag to a decision' : 'Detach a tag from a decision')
259
+ .option('--json', 'Output JSON');
260
+ if (action === 'remove')
261
+ sub.alias('rm');
262
+ sub.action((id, tag, options) => withApp((app) => {
263
+ const row = app.decisions.tag(id, action, tag);
264
+ output({ id, tags: row.tags }, options.json, () => row.tags.join(', '));
265
+ }));
266
+ }
267
+ return decisions;
268
+ }
269
+ /** 注册顶层快捷命令 `pxo decide`(等价 `pxo decision add`)。 */
270
+ export function registerDecideShortcut(program, withApp) {
271
+ return decisionFields(program
272
+ .command('decide [title]')
273
+ .description('Quickly record a decision (shortcut for decision add)')).action((title, options) => withApp((app) => add(app, title, options)));
274
+ }
275
+ /** 注册顶层 `pxo stats` 命令。 */
276
+ export function registerStats(program, withApp) {
277
+ return program
278
+ .command('stats')
279
+ .description('Show decision and command usage statistics')
280
+ .addOption(new Option('--period <period>', 'Statistics window').choices(['30d', '90d', '180d', 'all']))
281
+ .option('-p, --project <id>', 'Filter by project ID or "current"')
282
+ .option('--json', 'Output JSON')
283
+ .action((options) => withApp((app) => {
284
+ const result = app.stats(options.period, options.project);
285
+ output(result, options.json, () => renderStats(result));
286
+ }));
287
+ }
@@ -0,0 +1,45 @@
1
+ import { AppError } from '../../shared/errors.js';
2
+ import { output } from '../output.js';
3
+ /** 注册 `pxo doctor` 环境与数据库诊断命令。 */
4
+ export function registerDoctor(program) {
5
+ return program
6
+ .command('doctor')
7
+ .description('Diagnose the local environment, Git, and database')
8
+ .option('--json', 'Output JSON')
9
+ .action(async (options) => {
10
+ const { doctor } = await import('../../shared/doctor.js');
11
+ const report = await doctor();
12
+ output(report, options.json, () => [
13
+ 'Node ' +
14
+ report.node.version +
15
+ (report.node.supported
16
+ ? ' · supported'
17
+ : ' · install Node 24.22 or newer within Node 24'),
18
+ 'SQLite ' + report.database.status + ' · ' + report.database.path,
19
+ ...('message' in report.database ? [String(report.database.message)] : []),
20
+ ...('migrations' in report.database && report.database.migrations
21
+ ? [
22
+ 'Migrations ' +
23
+ report.database.migrations.applied +
24
+ '/' +
25
+ report.database.migrations.available,
26
+ 'WAL ' +
27
+ (report.database.wal ? 'enabled' : 'disabled') +
28
+ ' · Foreign keys ' +
29
+ (report.database.foreignKeys ? 'enabled' : 'disabled'),
30
+ ]
31
+ : []),
32
+ (report.git.version ?? 'Git unavailable') +
33
+ ' · ' +
34
+ (report.git.current?.root ?? 'Global'),
35
+ 'Clipboard ' +
36
+ (report.clipboard.available ? 'available' : 'unavailable; use pxo command render'),
37
+ ].join('\n'));
38
+ if (report.database.status === 'error') {
39
+ throw new AppError(5, 'Database diagnostics found an issue.');
40
+ }
41
+ if (!report.node.supported) {
42
+ throw new AppError(1, 'Use a supported Node.js 24 release.');
43
+ }
44
+ });
45
+ }
@@ -0,0 +1,24 @@
1
+ import { formatTable, limit, output, outputList } from '../output.js';
2
+ /** 注册 `pxo project`(别名 `p`)项目上下文命令组。 */
3
+ export function registerProjects(program, withApp) {
4
+ const project = program.command('project').alias('p').description('Inspect the project context');
5
+ project
6
+ .command('current')
7
+ .description('Show the detected project for the current directory')
8
+ .option('--json', 'Output JSON')
9
+ .action((options) => withApp((app) => {
10
+ const current = app.projects.current();
11
+ output(current, options.json, () => current ? [current.id, current.name, current.root].join('\t') : 'Global (no Git project)');
12
+ }));
13
+ project
14
+ .command('list')
15
+ .alias('ls')
16
+ .description('List registered projects')
17
+ .option('-L, --limit <n>', 'Maximum number of results to return')
18
+ .option('--json', 'Output JSON')
19
+ .action((options) => withApp((app) => {
20
+ const rows = app.projects.list(limit(options.limit));
21
+ outputList(rows, options.json, () => formatTable(['ID', 'Name', 'Root'], rows.map((r) => [r.id, r.name, r.root ?? '—'])), 'No registered projects.');
22
+ }));
23
+ return project;
24
+ }
@@ -0,0 +1,59 @@
1
+ import { Option } from 'commander';
2
+ import { collect, formatTable, limit, output, outputList } from '../output.js';
3
+ /** 注册跨模块全局搜索 `pxo search`(别名 `s`)。 */
4
+ export function registerSearch(program, withApp) {
5
+ return program
6
+ .command('search <query>')
7
+ .alias('s')
8
+ .description('Search commands and decisions')
9
+ .addOption(new Option('--only <kind>', 'Restrict search scope').choices([
10
+ 'all',
11
+ 'commands',
12
+ 'decisions',
13
+ ]))
14
+ .option('-p, --project <id>', 'Filter by project ID or "current"')
15
+ .option('--tag <tag>', 'Filter by tag (repeatable)', collect, [])
16
+ .option('-L, --limit <n>', 'Maximum number of results to return')
17
+ .option('--json', 'Output JSON')
18
+ .action((query, options) => withApp((app) => {
19
+ const rows = app.search(query, {
20
+ only: options.only,
21
+ project: options.project,
22
+ tags: options.tag,
23
+ limit: limit(options.limit),
24
+ });
25
+ outputList(rows, options.json, () => formatTable(['Type', 'ID', 'Title', 'Scope'], rows.map((row) => [row.type, row.id, row.title, row.projectName ?? 'Global'])), 'No matches.');
26
+ }));
27
+ }
28
+ /** 为 command / decision 统一注册 `link list|add|remove` 子命令组。 */
29
+ export function registerLinks(parent, kind, withApp) {
30
+ const other = kind === 'command' ? 'decision' : 'command';
31
+ const group = parent.command('link').description('Manage links to ' + other + ' records');
32
+ group
33
+ .command('list <id>')
34
+ .alias('ls')
35
+ .description('List linked ' + other + ' records')
36
+ .option('--json', 'Output JSON')
37
+ .action((id, options) => withApp((app) => {
38
+ const rows = app.links.list(kind, id);
39
+ outputList(rows, options.json, () => formatTable(['ID', 'Title'], rows.map((row) => [row.id, row.title])), 'No related records.');
40
+ }));
41
+ group
42
+ .command('add <id> <' + other + 'Id>')
43
+ .description('Link a ' + other + ' record')
44
+ .option('--json', 'Output JSON')
45
+ .action((id, target, options) => withApp((app) => {
46
+ app.links.change(kind, id, target, 'link');
47
+ output({ id, target, linked: true }, options.json, () => 'Link saved.');
48
+ }));
49
+ group
50
+ .command('remove <id> <' + other + 'Id>')
51
+ .alias('rm')
52
+ .description('Unlink a ' + other + ' record')
53
+ .option('--json', 'Output JSON')
54
+ .action((id, target, options) => withApp((app) => {
55
+ app.links.change(kind, id, target, 'unlink');
56
+ output({ id, target, linked: false }, options.json, () => 'Link removed.');
57
+ }));
58
+ return group;
59
+ }
@@ -0,0 +1,122 @@
1
+ import { Option } from 'commander';
2
+ import { AppError } from '../../shared/errors.js';
3
+ import { canPrompt, formatTable, output, outputList } from '../output.js';
4
+ import { prompt, requirePrompt } from '../prompts.js';
5
+ /** 注册 `pxo sync` 跨设备同步命令组。 */
6
+ export function registerSync(program, withApp) {
7
+ function execute(direction, options) {
8
+ return withApp(async (app) => {
9
+ const report = await app.sync.run({
10
+ direction,
11
+ strategy: options.strategy,
12
+ dryRun: options.dryRun,
13
+ approve: canPrompt() && !options.json
14
+ ? (findings) => prompt(async (ask) => {
15
+ for (const item of findings) {
16
+ process.stderr.write(item.record + ' · ' + item.field + '\n');
17
+ }
18
+ return /^y(?:es)?$/iu.test(await ask('Continue with these suspicious values? [y/N] '));
19
+ })
20
+ : undefined,
21
+ });
22
+ output(report, options.json, () => [
23
+ report.status +
24
+ ' · ' +
25
+ report.changes +
26
+ ' local change(s), ' +
27
+ report.outgoing +
28
+ ' outgoing',
29
+ ...report.conflicts.map((item) => item.id + ' · ' + item.kind + ' · ' + item.record),
30
+ ...report.findings.map((item) => item.level + ' · ' + item.record + ' · ' + item.field),
31
+ ].join('\n'));
32
+ if (!options.dryRun && report.status === 'Conflict') {
33
+ throw new AppError(5, 'Resolve conflicts with pxo sync resolve, then retry.');
34
+ }
35
+ if (!options.dryRun && report.status === 'Blocked') {
36
+ throw new AppError(4, 'Replace sensitive values with variables, then retry.');
37
+ }
38
+ }, options.dryRun ? 'preview' : 'write');
39
+ }
40
+ const syncFlags = (command) => command
41
+ .option('--json', 'Output JSON')
42
+ .option('--dry-run', 'Preview sync changes without pushing or modifying local state')
43
+ .addOption(new Option('--strategy <strategy>', 'Conflict merge strategy').choices(['safe', 'lww']));
44
+ const sync = syncFlags(program.command('sync').description('Synchronize with a private Git repository over local SSH'));
45
+ sync.action((options) => execute('both', options));
46
+ sync
47
+ .command('init [repo]')
48
+ .description('Link a private Git repository for sync using local SSH')
49
+ .option('--repo <repo>', 'GitHub repository (owner/name) or SSH Git URL')
50
+ .option('--branch <name>', 'Git branch dedicated to Praxo snapshots', 'praxo-sync')
51
+ .option('--json', 'Output JSON')
52
+ .action(async (positional, options) => {
53
+ if (positional && options.repo && positional.trim() !== options.repo.trim()) {
54
+ throw new AppError(2, 'Specify the repository once, either as an argument or with --repo.');
55
+ }
56
+ let repo = positional ?? options.repo;
57
+ let branch = options.branch;
58
+ if (!repo) {
59
+ requirePrompt('Pass <repo> (owner/name or SSH URL) to link a sync repository.');
60
+ [repo, branch] = await prompt(async (ask) => [
61
+ (await ask('GitHub repository (owner/name) or SSH URL: ')).trim(),
62
+ (await ask('Branch [' + branch + ']: ')).trim() || branch,
63
+ ]);
64
+ }
65
+ await withApp(async (app) => {
66
+ const result = await app.sync.initialize({ repository: repo, branch });
67
+ output(result, options.json, () => 'Linked ' +
68
+ result.repository +
69
+ ' (' +
70
+ result.branch +
71
+ ', ' +
72
+ result.records +
73
+ ' local records). Using local SSH; ensure the repository is private. Run pxo sync to begin.');
74
+ });
75
+ });
76
+ syncFlags(sync.command('pull').description('Pull and merge the remote snapshot')).action((options) => execute('pull', options));
77
+ syncFlags(sync.command('push').description('Push the merged local snapshot')).action((options) => execute('push', options));
78
+ sync
79
+ .command('status')
80
+ .description('Show current synchronization status')
81
+ .option('--json', 'Output JSON')
82
+ .action((options) => withApp((app) => {
83
+ const report = app.sync.status();
84
+ output(report, options.json, () => report.status === 'Unconfigured'
85
+ ? report.status
86
+ : report.status + ' · ' + report.repository + ' (' + report.branch + ')');
87
+ }, 'preview'));
88
+ sync
89
+ .command('history')
90
+ .description('Show recent remote sync commits')
91
+ .option('--json', 'Output JSON')
92
+ .action((options) => withApp(async (app) => {
93
+ const entries = await app.sync.history();
94
+ outputList(entries, options.json, () => formatTable(['Commit', 'Timestamp'], entries.map(({ sha, at }) => [sha, at])), 'No sync history.');
95
+ }, 'preview'));
96
+ sync
97
+ .command('conflicts')
98
+ .description('List unresolved sync conflicts')
99
+ .option('--json', 'Output JSON')
100
+ .action((options) => withApp((app) => {
101
+ const report = app.sync.conflicts();
102
+ outputList(report, options.json, () => report
103
+ .map(({ id, kind, record, choice, local, remote }) => [
104
+ [id, kind, record, choice ?? 'unresolved'].join('\t'),
105
+ ' Local ' + local,
106
+ ' Remote ' + remote,
107
+ ].join('\n'))
108
+ .join('\n'), 'No conflicts.');
109
+ }, 'preview'));
110
+ sync
111
+ .command('resolve <id>')
112
+ .description('Choose which version to keep for a sync conflict')
113
+ .addOption(new Option('--keep <side>', 'Version to keep')
114
+ .choices(['local', 'remote'])
115
+ .makeOptionMandatory())
116
+ .option('--json', 'Output JSON')
117
+ .action((id, options) => withApp((app) => {
118
+ app.sync.resolve(id, options.keep);
119
+ output({ id, keep: options.keep, resolved: true }, options.json, () => 'Conflict choice saved. Run pxo sync to apply it.');
120
+ }));
121
+ return sync;
122
+ }