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,194 @@
1
+ import { stripVTControlCharacters } from 'node:util';
2
+ import { inspectText } from '../../shared/redaction.js';
3
+ import { canonical, content, entryKey, hash, references } from './snapshot.js';
4
+ function timestamp(entry) {
5
+ const row = entry.row;
6
+ if (row.deletedAt)
7
+ return row.deletedAt;
8
+ if ('updatedAt' in row)
9
+ return row.updatedAt;
10
+ return 'reviewedAt' in row ? row.reviewedAt : null;
11
+ }
12
+ function describe(entry, other) {
13
+ if (!entry)
14
+ return 'Absent';
15
+ if (entry.row.deletedAt)
16
+ return 'Deleted';
17
+ const fields = entry.row;
18
+ const alternate = other?.row;
19
+ const different = Object.keys(fields)
20
+ .sort()
21
+ .filter((key) => !['id', 'createdAt', 'updatedAt', 'deletedAt', 'deviceId', 'revision'].includes(key) &&
22
+ (!alternate || canonical(fields[key]) !== canonical(alternate[key])));
23
+ const short = (value) => inspectText(stripVTControlCharacters(typeof value === 'string' ? value : String(canonical(value))))
24
+ .value.replace(/\s+/gu, ' ')
25
+ .slice(0, 100);
26
+ return (different
27
+ .slice(0, 4)
28
+ .map((key) => key + '=' + short(fields[key]))
29
+ .join(' · ') || 'Present');
30
+ }
31
+ function remapTags(snapshots) {
32
+ const byName = new Map();
33
+ for (const snapshot of snapshots)
34
+ for (const entry of snapshot.values()) {
35
+ if (entry.table !== 'tags')
36
+ continue;
37
+ const { id, normalized } = entry.row;
38
+ const current = byName.get(normalized);
39
+ if (!current || id < current)
40
+ byName.set(normalized, id);
41
+ }
42
+ // 同名标签在三侧使用相同键,再进行内容比较和关联去重。
43
+ const aligned = snapshots.map((snapshot) => {
44
+ const tags = new Map();
45
+ for (const entry of snapshot.values())
46
+ if (entry.table === 'tags') {
47
+ tags.set(entry.row.id, byName.get(entry.row.normalized));
48
+ }
49
+ const result = new Map();
50
+ for (const original of snapshot.values()) {
51
+ let entry = original;
52
+ if (entry.table === 'tags')
53
+ entry = { ...entry, row: { ...entry.row, id: tags.get(entry.row.id) } };
54
+ if (entry.table === 'entity_tags')
55
+ entry = {
56
+ ...entry,
57
+ row: { ...entry.row, tagId: tags.get(entry.row.tagId) ?? entry.row.tagId },
58
+ };
59
+ result.set(entryKey(entry), entry);
60
+ }
61
+ return result;
62
+ });
63
+ // 同时新建不同大小写标签时采用规范 ID 对应的展示名称。
64
+ for (const [key, remote] of aligned[2]) {
65
+ const local = aligned[1].get(key);
66
+ if (remote.table !== 'tags' ||
67
+ local?.table !== 'tags' ||
68
+ aligned[0].has(key) ||
69
+ remote.row.deletedAt ||
70
+ local.row.deletedAt ||
71
+ content(local) === content(remote))
72
+ continue;
73
+ const canonical = snapshots[1].has(key) ? local : remote;
74
+ aligned[1].set(key, canonical);
75
+ aligned[2].set(key, canonical);
76
+ }
77
+ return aligned;
78
+ }
79
+ /** 合并只计算结果和冲突,SQLite 和 Git 都由调用方管理。 */
80
+ export function mergeSnapshots(base, local, remote, strategy = 'safe', choices = {}) {
81
+ const original = [base, local, remote];
82
+ [base, local, remote] = remapTags(original);
83
+ const result = new Map();
84
+ const missingRemote = [...base.keys()].some((key) => !remote.has(key));
85
+ const conflicts = new Map();
86
+ const projectAliases = new Map();
87
+ const assign = (key, entry) => entry ? result.set(key, entry) : result.delete(key);
88
+ function choice(record, kind, keys) {
89
+ const versions = [base, local, remote].map((snapshot) => keys.map((key) => content(snapshot.get(key))));
90
+ const id = hash([record, kind, versions]).slice(0, 24);
91
+ const selected = choices[id];
92
+ conflicts.set(id, {
93
+ id,
94
+ record,
95
+ kind,
96
+ ...(selected ? { choice: selected } : {}),
97
+ local: keys.map((key) => describe(local.get(key), remote.get(key))).join(' / '),
98
+ remote: keys.map((key) => describe(remote.get(key), local.get(key))).join(' / '),
99
+ });
100
+ return selected;
101
+ }
102
+ for (const key of new Set([...base.keys(), ...local.keys(), ...remote.keys()])) {
103
+ const previous = base.get(key), here = local.get(key), there = remote.get(key);
104
+ const signatures = [previous, here, there].map(content);
105
+ const [b, l, r] = signatures;
106
+ if (l === r || l === b) {
107
+ assign(key, there);
108
+ continue;
109
+ }
110
+ if (r === b) {
111
+ assign(key, here);
112
+ continue;
113
+ }
114
+ if (strategy === 'lww' && here && there) {
115
+ const left = timestamp(here), right = timestamp(there);
116
+ if (left && right && left !== right) {
117
+ assign(key, left > right ? here : there);
118
+ continue;
119
+ }
120
+ }
121
+ assign(key, choice(key, 'changed', [key]) === 'remote' ? there : here);
122
+ }
123
+ const destinations = new Map();
124
+ for (const entry of result.values()) {
125
+ if (entry.table !== 'projects' || !entry.row.remote || entry.row.deletedAt)
126
+ continue;
127
+ const other = destinations.get(entry.row.remote);
128
+ if (!other) {
129
+ destinations.set(entry.row.remote, entry);
130
+ continue;
131
+ }
132
+ const keys = [entryKey(other), entryKey(entry)].sort();
133
+ const selected = choice(keys.join(' / '), 'project', keys);
134
+ const preferred = selected === 'remote' ? remote : local;
135
+ const winner = preferred.get(entryKey(entry))?.row.deletedAt === null ? entry : other;
136
+ const loser = winner === other ? entry : other;
137
+ destinations.set(entry.row.remote, winner);
138
+ projectAliases.set(loser.row.id, winner.row.id);
139
+ result.set(entryKey(loser), {
140
+ ...loser,
141
+ row: { ...loser.row, deletedAt: winner.row.updatedAt },
142
+ });
143
+ }
144
+ for (const entry of result.values()) {
145
+ if (entry.table !== 'projects' || !entry.row.deletedAt || !entry.row.remote)
146
+ continue;
147
+ const winner = destinations.get(entry.row.remote);
148
+ if (winner)
149
+ projectAliases.set(entry.row.id, winner.row.id);
150
+ }
151
+ for (const [key, entry] of result) {
152
+ if ((entry.table === 'commands' || entry.table === 'decisions') && entry.row.projectId) {
153
+ const replacement = projectAliases.get(entry.row.projectId);
154
+ if (replacement)
155
+ result.set(key, { ...entry, row: { ...entry.row, projectId: replacement } });
156
+ }
157
+ }
158
+ // 后代的并发新增或修改不能被父级 Tombstone 静默覆盖。
159
+ for (let pass = 0; pass < 3; pass++) {
160
+ let applied = false;
161
+ for (const [key, entry] of [...result])
162
+ for (const reference of references(entry)) {
163
+ const parent = result.get(reference);
164
+ if (parent && (!parent.row.deletedAt || entry.row.deletedAt))
165
+ continue;
166
+ const selected = choice(key + ' → ' + reference, 'reference', [key, reference]);
167
+ if (!selected)
168
+ continue;
169
+ const source = selected === 'local' ? local : remote;
170
+ if (content(result.get(key)) !== content(source.get(key)) ||
171
+ content(result.get(reference)) !== content(source.get(reference)))
172
+ applied = true;
173
+ assign(key, source.get(key));
174
+ assign(reference, source.get(reference));
175
+ }
176
+ if (!applied)
177
+ break;
178
+ }
179
+ const invalidReferences = [...result.values()].some((entry) => references(entry).some((ref) => {
180
+ const parent = result.get(ref);
181
+ return !parent || (parent.row.deletedAt !== null && entry.row.deletedAt === null);
182
+ }));
183
+ for (const entry of result.values()) {
184
+ if (entry.table === 'projects' && entry.row.deletedAt === null)
185
+ projectAliases.delete(entry.row.id);
186
+ }
187
+ return {
188
+ snapshot: result,
189
+ conflicts: [...conflicts.values()],
190
+ invalidReferences,
191
+ missingRemote,
192
+ projectAliases,
193
+ };
194
+ }
@@ -0,0 +1,151 @@
1
+ import { content, parseSnapshot, portable, snapshotData, tables } from './snapshot.js';
2
+ import { AppError } from '../../shared/errors.js';
3
+ const primary = (entry) => entry.table === 'entity_tags'
4
+ ? [entry.row.commandId === null ? 'decisionId' : 'commandId', 'tagId']
5
+ : entry.table === 'entity_links'
6
+ ? ['commandId', 'decisionId']
7
+ : ['id'];
8
+ export function syncRepository({ native }) {
9
+ const read = native.prepare('SELECT value FROM sync_state WHERE key = ?').pluck();
10
+ const write = native.prepare('INSERT INTO sync_state VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value=excluded.value');
11
+ const remove = native.prepare('DELETE FROM sync_state WHERE key = ?');
12
+ function get(key) {
13
+ const value = read.get(key);
14
+ return typeof value === 'string' ? JSON.parse(value) : undefined;
15
+ }
16
+ function set(key, value) {
17
+ write.run(key, JSON.stringify(value));
18
+ }
19
+ function snapshot() {
20
+ return native
21
+ .transaction(() => {
22
+ const data = Object.fromEntries(tables.map((table) => [
23
+ table,
24
+ native.prepare('SELECT * FROM ' + table).all().map((row) => {
25
+ if (table === 'commands')
26
+ return { ...row, danger: row.danger === 1, sos: row.sos === 1 };
27
+ if (table === 'decision_reviews')
28
+ return { ...row, snapshot: JSON.parse(String(row.snapshot)) };
29
+ return row;
30
+ }),
31
+ ]));
32
+ return parseSnapshot(data);
33
+ })
34
+ .deferred();
35
+ }
36
+ /** 在持锁事务中维护外键和本机绑定,仅写入发生变化的记录。 */
37
+ function apply(current, merged, aliases) {
38
+ for (const [key, entry] of [...current].reverse()) {
39
+ if (merged.has(key))
40
+ continue;
41
+ const fields = primary(entry);
42
+ const row = entry.row;
43
+ native
44
+ .prepare('DELETE FROM ' +
45
+ entry.table +
46
+ ' WHERE ' +
47
+ fields.map((field) => field + ' = ?').join(' AND '))
48
+ .run(...fields.map((field) => row[field]));
49
+ }
50
+ for (const table of tables) {
51
+ const changes = [...merged].filter(([key, entry]) => entry.table === table && content(current.get(key)) !== content(entry));
52
+ // 同一个远程身份下,先标记落选项目为删除,再写入保留的项目。
53
+ if (table === 'projects')
54
+ changes.sort(([, a], [, b]) => Number(b.row.deletedAt !== null) - Number(a.row.deletedAt !== null));
55
+ for (const [key, item] of changes) {
56
+ const entry = portable(item);
57
+ const keys = primary(entry);
58
+ const row = { ...entry.row };
59
+ const before = current.get(key)?.row;
60
+ if (typeof row.revision === 'number') {
61
+ row.revision = typeof before?.revision === 'number' ? before.revision + 1 : 1;
62
+ }
63
+ const fields = Object.keys(row);
64
+ const values = fields.map((name) => {
65
+ const value = row[name];
66
+ return typeof value === 'boolean'
67
+ ? Number(value)
68
+ : typeof value === 'object' && value !== null
69
+ ? JSON.stringify(value)
70
+ : value;
71
+ });
72
+ native
73
+ .prepare('INSERT INTO ' +
74
+ table +
75
+ '(' +
76
+ fields.join(',') +
77
+ ') VALUES (' +
78
+ fields.map(() => '?').join(',') +
79
+ ')' +
80
+ ' ON CONFLICT(' +
81
+ keys.join(',') +
82
+ ') DO UPDATE SET ' +
83
+ fields
84
+ .filter((field) => !keys.includes(field))
85
+ .map((field) => field + '=excluded.' + field)
86
+ .join(','))
87
+ .run(...values);
88
+ if (entry.table === 'commands' && entry.row.deletedAt) {
89
+ native.prepare('DELETE FROM command_usages WHERE commandId = ?').run(entry.row.id);
90
+ }
91
+ }
92
+ }
93
+ const readBinding = native.prepare('SELECT root, aliases FROM project_local_bindings WHERE projectId = ?');
94
+ for (const [from, to] of aliases) {
95
+ const source = readBinding.get(from);
96
+ if (!source)
97
+ continue;
98
+ const target = readBinding.get(to);
99
+ if (!target) {
100
+ native
101
+ .prepare('UPDATE project_local_bindings SET projectId = ? WHERE projectId = ?')
102
+ .run(to, from);
103
+ continue;
104
+ }
105
+ const paths = new Set([
106
+ ...JSON.parse(target.aliases),
107
+ source.root,
108
+ ...JSON.parse(source.aliases),
109
+ ]);
110
+ paths.delete(target.root);
111
+ native
112
+ .prepare('UPDATE project_local_bindings SET aliases = ? WHERE projectId = ?')
113
+ .run(JSON.stringify([...paths]), to);
114
+ native.prepare('DELETE FROM project_local_bindings WHERE projectId = ?').run(from);
115
+ }
116
+ native
117
+ .prepare('DELETE FROM project_local_bindings WHERE projectId IN (SELECT id FROM projects WHERE deletedAt IS NOT NULL)')
118
+ .run();
119
+ }
120
+ // SQLite 锁记录与 PID 检查让意外退出后的下一次同步可直接恢复。
121
+ function acquire() {
122
+ native
123
+ .transaction(() => {
124
+ const pid = get('lock');
125
+ if (pid) {
126
+ let running = true;
127
+ try {
128
+ process.kill(pid, 0);
129
+ }
130
+ catch (error) {
131
+ running = error.code !== 'ESRCH';
132
+ }
133
+ if (running)
134
+ throw new AppError(5, 'Sync is already running in a Praxo process. Wait and retry.');
135
+ }
136
+ set('lock', process.pid);
137
+ })
138
+ .immediate();
139
+ return () => {
140
+ remove.run('lock');
141
+ };
142
+ }
143
+ return {
144
+ snapshot,
145
+ apply,
146
+ acquire,
147
+ transaction: (operation) => native.transaction(operation).immediate(),
148
+ load: (key) => get(key) ?? { sha: null, base: snapshotData(new Map()) },
149
+ save: (key, state) => set(key, state),
150
+ };
151
+ }
@@ -0,0 +1,21 @@
1
+ import { inspectText } from '../../shared/redaction.js';
2
+ import { portable } from './snapshot.js';
3
+ export function inspectSnapshot(snapshot) {
4
+ const findings = [];
5
+ function inspect(record, path, data) {
6
+ if (typeof data === 'string') {
7
+ const result = inspectText(data);
8
+ if (result.blocked || result.suspicious)
9
+ findings.push({ record, field: path, level: result.blocked ? 'blocked' : 'suspicious' });
10
+ }
11
+ else if (typeof data === 'object' && data !== null) {
12
+ for (const [name, value] of Object.entries(data))
13
+ inspect(record, path ? path + '.' + name : name, value);
14
+ }
15
+ }
16
+ for (const [record, entry] of snapshot) {
17
+ // 记录键由标识符构成,回显位置前仍须脱敏。
18
+ inspect(inspectText(record).value, '', portable(entry).row);
19
+ }
20
+ return findings;
21
+ }
@@ -0,0 +1,199 @@
1
+ import { mkdtemp, rm } from 'node:fs/promises';
2
+ import { tmpdir } from 'node:os';
3
+ import { join } from 'node:path';
4
+ import { AppError } from '../../shared/errors.js';
5
+ import { syncConfigSchema } from '../../shared/config.js';
6
+ import { gitHistory, gitTransport } from './git.js';
7
+ import { mergeSnapshots } from './merge.js';
8
+ import { inspectSnapshot } from './sanitizer.js';
9
+ import { content, parseSnapshot, snapshotData, snapshotHash } from './snapshot.js';
10
+ import { inspectText } from '../../shared/redaction.js';
11
+ export function syncService(repo, config, clock, onApplied, override) {
12
+ const identity = (settings) => config.identity('git:' + settings.repository.toLowerCase());
13
+ const storageKey = (settings) => identity(settings) + ':' + settings.branch;
14
+ const cache = (settings) => join(config.paths.cache, 'git', config.identity(storageKey(settings)).slice(-24));
15
+ const transport = override ?? ((settings, path) => gitTransport(path, settings.repository, settings.branch));
16
+ function settings() {
17
+ const data = config.read().sync;
18
+ if (!data)
19
+ throw new AppError(2, 'Sync is unconfigured. Run pxo sync init <repo>.');
20
+ return data;
21
+ }
22
+ /** 链接远端 Git SSH 仓库并验证本机 SSH 连通性。 */
23
+ async function initialize(raw) {
24
+ const parsed = syncConfigSchema.safeParse(raw);
25
+ if (!parsed.success)
26
+ throw new AppError(2, 'Enter a GitHub repository (owner/name) or SSH Git URL (for example git@github.com:owner/name.git), plus a valid branch.');
27
+ const next = parsed.data;
28
+ const unlock = repo.acquire();
29
+ try {
30
+ const git = await transport(next, cache(next));
31
+ const remote = await git.fetch();
32
+ const records = repo.snapshot().size;
33
+ config.set('sync', next);
34
+ return { repository: next.repository, branch: next.branch, records, remote: remote.sha };
35
+ }
36
+ finally {
37
+ unlock();
38
+ }
39
+ }
40
+ function status() {
41
+ const selected = config.read().sync;
42
+ if (!selected)
43
+ return { status: 'Unconfigured' };
44
+ const state = repo.load(storageKey(selected));
45
+ const dirty = snapshotHash(repo.snapshot()) !== snapshotHash(parseSnapshot(state.base));
46
+ const conflicts = state.conflicts?.filter(({ choice }) => !choice).length ?? 0;
47
+ return {
48
+ status: conflicts ? 'Conflict' : dirty || state.pending ? 'Pending' : 'Synced',
49
+ repository: selected.repository,
50
+ branch: selected.branch,
51
+ sha: state.sha,
52
+ lastSuccess: state.lastSuccess,
53
+ conflicts,
54
+ };
55
+ }
56
+ async function history() {
57
+ const selected = settings();
58
+ const { sha } = repo.load(storageKey(selected));
59
+ return sha ? gitHistory(cache(selected), sha) : [];
60
+ }
61
+ function conflicts() {
62
+ return (repo.load(storageKey(settings())).conflicts ?? []).map((item) => ({
63
+ ...item,
64
+ record: inspectText(item.record).value,
65
+ }));
66
+ }
67
+ function resolve(id, side) {
68
+ const unlock = repo.acquire();
69
+ try {
70
+ const key = storageKey(settings());
71
+ const state = repo.load(key);
72
+ const target = state.conflicts?.find((item) => item.id === id);
73
+ if (!target)
74
+ throw new AppError(3, 'Conflict not found. Run pxo sync conflicts.');
75
+ repo.save(key, {
76
+ ...state,
77
+ choices: { ...state.choices, [id]: side },
78
+ conflicts: state.conflicts?.map((item) => item.id === id ? { ...item, choice: side } : item),
79
+ });
80
+ }
81
+ finally {
82
+ unlock();
83
+ }
84
+ }
85
+ /** 先持久化已合入的远端基线及待发布提交,再跨越网络边界。 */
86
+ async function run(options = {}) {
87
+ const selected = settings();
88
+ const direction = options.direction ?? 'both';
89
+ const key = storageKey(selected);
90
+ const unlock = options.dryRun ? () => { } : repo.acquire();
91
+ let temporary;
92
+ try {
93
+ temporary = options.dryRun ? await mkdtemp(join(tmpdir(), 'praxo-sync-preview-')) : undefined;
94
+ const git = await transport(selected, temporary ?? cache(selected));
95
+ for (let attempt = 0; attempt < 3; attempt++) {
96
+ let state = repo.load(key);
97
+ const local = repo.snapshot();
98
+ const remote = await git.fetch();
99
+ if (state.pending && remote.sha && (await git.hasAncestor(state.pending.sha, remote.sha))) {
100
+ state = {
101
+ ...state,
102
+ sha: state.pending.sha,
103
+ base: state.pending.snapshot,
104
+ pending: undefined,
105
+ lastSuccess: clock().toISOString(),
106
+ };
107
+ if (!options.dryRun)
108
+ repo.save(key, state);
109
+ }
110
+ if (state.sha && (!remote.sha || !(await git.hasAncestor(state.sha, remote.sha)))) {
111
+ throw new AppError(5, 'The sync branch history changed. Restore the previous history before retrying.');
112
+ }
113
+ if (direction === 'push' && remote.sha !== state.sha) {
114
+ throw new AppError(5, 'The remote branch has changed. Run pxo sync pull first.');
115
+ }
116
+ const merged = mergeSnapshots(parseSnapshot(state.base), local, remote.snapshot, options.strategy, state.choices);
117
+ if (merged.missingRemote)
118
+ throw new AppError(5, 'The remote snapshot removed tracked records without tombstones. Restore the last valid sync snapshot and retry.');
119
+ const findings = inspectSnapshot(merged.snapshot);
120
+ const unresolved = merged.conflicts.some(({ choice }) => !choice) || merged.invalidReferences;
121
+ const report = {
122
+ status: unresolved ? 'Conflict' : 'Synced',
123
+ changes: [...new Set([...local.keys(), ...merged.snapshot.keys()])].filter((id) => content(local.get(id)) !== content(merged.snapshot.get(id))).length,
124
+ outgoing: [...new Set([...remote.snapshot.keys(), ...merged.snapshot.keys()])].filter((id) => content(remote.snapshot.get(id)) !== content(merged.snapshot.get(id))).length,
125
+ conflicts: merged.conflicts.map((item) => ({
126
+ ...item,
127
+ record: inspectText(item.record).value,
128
+ })),
129
+ findings,
130
+ sha: remote.sha,
131
+ };
132
+ if (options.dryRun)
133
+ return {
134
+ ...report,
135
+ status: unresolved ? 'Conflict' : findings.length ? 'Blocked' : 'Preview',
136
+ };
137
+ if (unresolved) {
138
+ repo.save(key, {
139
+ ...state,
140
+ conflicts: merged.conflicts,
141
+ choices: Object.fromEntries(merged.conflicts.filter((item) => item.choice).map((item) => [item.id, item.choice])),
142
+ });
143
+ return report;
144
+ }
145
+ if (findings.some((item) => item.level === 'blocked') ||
146
+ (findings.length > 0 && !(await options.approve?.(findings)))) {
147
+ return { ...report, status: 'Blocked' };
148
+ }
149
+ parseSnapshot(snapshotData(merged.snapshot));
150
+ const timestamp = clock().toISOString();
151
+ const noPush = direction === 'pull' ||
152
+ (remote.sha !== null && report.outgoing === 0) ||
153
+ (remote.sha === null && merged.snapshot.size === 0);
154
+ const commit = noPush
155
+ ? undefined
156
+ : await git.commit(merged.snapshot, remote.sha, timestamp);
157
+ const integrated = {
158
+ sha: remote.sha,
159
+ base: snapshotData(remote.snapshot),
160
+ lastSuccess: commit ? state.lastSuccess : timestamp,
161
+ pending: commit ? { sha: commit, snapshot: snapshotData(merged.snapshot) } : undefined,
162
+ };
163
+ const applied = repo.transaction(() => {
164
+ if (snapshotHash(repo.snapshot()) !== snapshotHash(local))
165
+ return false;
166
+ repo.apply(local, merged.snapshot, merged.projectAliases);
167
+ repo.save(key, integrated);
168
+ return true;
169
+ });
170
+ if (!applied)
171
+ continue;
172
+ onApplied();
173
+ if (!commit)
174
+ return {
175
+ ...report,
176
+ status: direction === 'pull' && report.outgoing ? 'Pending' : 'Synced',
177
+ };
178
+ if (!(await git.push(commit))) {
179
+ if (direction === 'push')
180
+ throw new AppError(5, 'The remote branch moved. Run pxo sync pull, then retry push.');
181
+ continue;
182
+ }
183
+ repo.save(key, {
184
+ sha: commit,
185
+ base: snapshotData(merged.snapshot),
186
+ lastSuccess: timestamp,
187
+ });
188
+ return { ...report, sha: commit };
189
+ }
190
+ throw new AppError(5, 'Sync changed repeatedly while running. Local data is safe. Retry sync.');
191
+ }
192
+ finally {
193
+ unlock();
194
+ if (temporary)
195
+ await rm(temporary, { recursive: true, force: true });
196
+ }
197
+ }
198
+ return { initialize, status, history, conflicts, resolve, run };
199
+ }