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.
- package/LICENSE +21 -0
- package/README.md +159 -2
- package/dist/app.js +75 -0
- package/dist/bin.js +21 -0
- package/dist/cli/commands/ai.command.js +189 -0
- package/dist/cli/commands/cmd.command.js +265 -0
- package/dist/cli/commands/completion.command.js +334 -0
- package/dist/cli/commands/config.command.js +27 -0
- package/dist/cli/commands/decision.command.js +287 -0
- package/dist/cli/commands/doctor.command.js +45 -0
- package/dist/cli/commands/project.command.js +24 -0
- package/dist/cli/commands/search.command.js +59 -0
- package/dist/cli/commands/sync.command.js +122 -0
- package/dist/cli/commands/transfer.command.js +148 -0
- package/dist/cli/index.js +156 -0
- package/dist/cli/output.js +133 -0
- package/dist/cli/prompts.js +68 -0
- package/dist/features/ai/client.js +238 -0
- package/dist/features/ai/output.js +7 -0
- package/dist/features/ai/providers.js +52 -0
- package/dist/features/ai/schemas.js +43 -0
- package/dist/features/ai/service.js +183 -0
- package/dist/features/commands/executor.js +54 -0
- package/dist/features/commands/repository.js +61 -0
- package/dist/features/commands/safety.js +154 -0
- package/dist/features/commands/service.js +254 -0
- package/dist/features/commands/template.js +153 -0
- package/dist/features/decisions/repository.js +53 -0
- package/dist/features/decisions/service.js +209 -0
- package/dist/features/decisions/stats.js +84 -0
- package/dist/features/decisions/status.js +7 -0
- package/dist/features/projects/repository.js +51 -0
- package/dist/features/projects/service.js +74 -0
- package/dist/features/sync/git.js +207 -0
- package/dist/features/sync/merge.js +194 -0
- package/dist/features/sync/repository.js +151 -0
- package/dist/features/sync/sanitizer.js +21 -0
- package/dist/features/sync/service.js +199 -0
- package/dist/features/sync/snapshot.js +230 -0
- package/dist/infrastructure/credentials/store.js +105 -0
- package/dist/infrastructure/database/client.js +41 -0
- package/dist/infrastructure/database/migrate.js +102 -0
- package/dist/infrastructure/database/schema.js +138 -0
- package/dist/infrastructure/git/detector.js +48 -0
- package/dist/shared/clipboard.js +19 -0
- package/dist/shared/config.js +163 -0
- package/dist/shared/doctor.js +47 -0
- package/dist/shared/errors.js +19 -0
- package/dist/shared/global-search.js +51 -0
- package/dist/shared/input.js +37 -0
- package/dist/shared/links.js +48 -0
- package/dist/shared/paths.js +14 -0
- package/dist/shared/query.js +10 -0
- package/dist/shared/redaction.js +54 -0
- package/dist/shared/search.js +39 -0
- package/dist/shared/sync-metadata.js +7 -0
- package/dist/shared/tags.js +91 -0
- package/dist/shared/transfer/archive.js +197 -0
- package/dist/shared/transfer/markdown.js +53 -0
- package/dist/shared/transfer/service.js +278 -0
- package/dist/tui/Workspace.js +121 -0
- package/dist/tui/components/AiPanel.js +200 -0
- package/dist/tui/components/Catalog.js +47 -0
- package/dist/tui/components/Confirm.js +28 -0
- package/dist/tui/components/Form.js +113 -0
- package/dist/tui/components/HelpModal.js +44 -0
- package/dist/tui/components/Inspection.js +28 -0
- package/dist/tui/components/KeyHints.js +7 -0
- package/dist/tui/components/SearchInput.js +31 -0
- package/dist/tui/components/SyncPanel.js +93 -0
- package/dist/tui/index.js +18 -0
- package/dist/tui/screens/Commands.js +383 -0
- package/dist/tui/screens/DecisionForms.js +117 -0
- package/dist/tui/screens/Decisions.js +260 -0
- package/dist/tui/screens/Lookup.js +96 -0
- package/dist/tui/theme.js +47 -0
- package/drizzle/0000_initial.sql +105 -0
- package/drizzle/0001_v11_sync.sql +117 -0
- package/drizzle/meta/0000_snapshot.json +735 -0
- package/drizzle/meta/0001_snapshot.json +867 -0
- package/drizzle/meta/_journal.json +20 -0
- package/package.json +77 -4
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
import { z } from 'zod';
|
|
2
|
+
import { matchesTags } from '../../shared/tags.js';
|
|
3
|
+
import { withoutSyncMetadata } from '../../shared/sync-metadata.js';
|
|
4
|
+
import { AppError } from '../../shared/errors.js';
|
|
5
|
+
import { confidence, daysFrom, defaultLimit, isoDate, localDay, newId, nonempty, normalize, rating, scope, status, validate, } from '../../shared/input.js';
|
|
6
|
+
import { search } from '../../shared/search.js';
|
|
7
|
+
import { decisionStatus } from './status.js';
|
|
8
|
+
const fields = z.object({
|
|
9
|
+
title: nonempty,
|
|
10
|
+
content: z.string(),
|
|
11
|
+
reason: z.string(),
|
|
12
|
+
alternatives: z.string(),
|
|
13
|
+
expected: z.string(),
|
|
14
|
+
domain: nonempty,
|
|
15
|
+
confidence: confidence.nullable(),
|
|
16
|
+
reviewAt: isoDate.optional(),
|
|
17
|
+
project: nonempty.optional(),
|
|
18
|
+
});
|
|
19
|
+
const createSchema = fields.extend({
|
|
20
|
+
content: z.string().default(''),
|
|
21
|
+
reason: z.string().default(''),
|
|
22
|
+
alternatives: z.string().default(''),
|
|
23
|
+
expected: z.string().default(''),
|
|
24
|
+
domain: nonempty.default('architecture'),
|
|
25
|
+
confidence: confidence.nullable().default(null),
|
|
26
|
+
scope: scope.default('auto'),
|
|
27
|
+
tags: z.array(nonempty).default([]),
|
|
28
|
+
inDays: z.number().int().positive().optional(),
|
|
29
|
+
});
|
|
30
|
+
const editSchema = fields.partial().extend({ scope: z.enum(['global', 'project']).optional() });
|
|
31
|
+
const reviewSchema = z.object({ result: nonempty, rating, lesson: nonempty });
|
|
32
|
+
const querySchema = z.object({
|
|
33
|
+
project: nonempty.optional(),
|
|
34
|
+
domain: nonempty.optional(),
|
|
35
|
+
status: status.default('all'),
|
|
36
|
+
scope: z.enum(['global', 'project', 'all']).optional(),
|
|
37
|
+
tags: z.array(nonempty).optional(),
|
|
38
|
+
sort: z.enum(['recent', 'review-at', 'confidence']).default('recent'),
|
|
39
|
+
limit: z.number().int().positive().optional(),
|
|
40
|
+
});
|
|
41
|
+
export function decisionFields(item) {
|
|
42
|
+
return {
|
|
43
|
+
title: item.title,
|
|
44
|
+
body: [item.content, item.reason, item.alternatives, item.expected, item.domain].join(' '),
|
|
45
|
+
tags: item.tags,
|
|
46
|
+
project: item.projectName ?? '',
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
export function decisionService({ repository, projects, tags, write, now }) {
|
|
50
|
+
function load(id) {
|
|
51
|
+
const result = repository.byId(id);
|
|
52
|
+
if (!result)
|
|
53
|
+
throw new AppError(3, 'Decision ' + id + ' was not found. Run pxo decision list.');
|
|
54
|
+
return result;
|
|
55
|
+
}
|
|
56
|
+
function summary(row, names, today) {
|
|
57
|
+
return {
|
|
58
|
+
...withoutSyncMetadata(row.decision),
|
|
59
|
+
projectName: row.projectName,
|
|
60
|
+
tags: names,
|
|
61
|
+
status: decisionStatus(row.decision.reviewAt, row.reviewed === 1, today),
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
function show(id) {
|
|
65
|
+
const row = repository.detail(id);
|
|
66
|
+
if (!row)
|
|
67
|
+
throw new AppError(3, 'Decision ' + id + ' was not found. Run pxo decision list.');
|
|
68
|
+
return summary(row, tags.forEntity('decision', id), localDay(now()));
|
|
69
|
+
}
|
|
70
|
+
function candidates(input = {}, keyword) {
|
|
71
|
+
const filter = validate(querySchema, input);
|
|
72
|
+
const projectId = projects.resolve(filter.project)?.id ?? null;
|
|
73
|
+
const today = localDay(now());
|
|
74
|
+
const names = tags.tagMap('decision');
|
|
75
|
+
const domain = filter.domain && normalize(filter.domain);
|
|
76
|
+
const rows = repository
|
|
77
|
+
.list(projectId, filter.scope)
|
|
78
|
+
.map((row) => summary(row, names.get(row.decision.id) ?? [], today))
|
|
79
|
+
.filter((item) => (filter.status === 'all' || item.status === filter.status) &&
|
|
80
|
+
(!domain || item.domain === domain) &&
|
|
81
|
+
matchesTags(item.tags, filter.tags));
|
|
82
|
+
const ranked = keyword === undefined
|
|
83
|
+
? rows.map((item) => ({ item, score: 0 }))
|
|
84
|
+
: search(rows, keyword, decisionFields);
|
|
85
|
+
return ranked
|
|
86
|
+
.sort((left, right) => {
|
|
87
|
+
const a = left.item, b = right.item;
|
|
88
|
+
const difference = filter.sort === 'review-at'
|
|
89
|
+
? a.reviewAt.localeCompare(b.reviewAt)
|
|
90
|
+
: filter.sort === 'confidence'
|
|
91
|
+
? (b.confidence ?? -1) - (a.confidence ?? -1)
|
|
92
|
+
: 0;
|
|
93
|
+
return (left.score - right.score ||
|
|
94
|
+
difference ||
|
|
95
|
+
Number(b.projectId === projectId) - Number(a.projectId === projectId) ||
|
|
96
|
+
b.createdAt.localeCompare(a.createdAt) ||
|
|
97
|
+
a.id.localeCompare(b.id));
|
|
98
|
+
})
|
|
99
|
+
.map(({ item }) => item);
|
|
100
|
+
}
|
|
101
|
+
function list(input = {}, keyword) {
|
|
102
|
+
return candidates(input, keyword).slice(0, input.limit ?? defaultLimit);
|
|
103
|
+
}
|
|
104
|
+
/** 统计当前范围内待复盘决策的完整数量,与列表和统计口径保持一致。 */
|
|
105
|
+
function countDue(input = {}) {
|
|
106
|
+
const filter = validate(querySchema.pick({ project: true, scope: true }), input);
|
|
107
|
+
const projectId = projects.resolve(filter.project)?.id ?? null;
|
|
108
|
+
const today = localDay(now());
|
|
109
|
+
return repository
|
|
110
|
+
.list(projectId, filter.scope)
|
|
111
|
+
.filter((row) => decisionStatus(row.decision.reviewAt, row.reviewed === 1, today) === 'due')
|
|
112
|
+
.length;
|
|
113
|
+
}
|
|
114
|
+
function create(input) {
|
|
115
|
+
const { scope, project, tags: names, inDays, reviewAt, ...data } = validate(createSchema, input);
|
|
116
|
+
if (inDays !== undefined && reviewAt !== undefined)
|
|
117
|
+
throw new AppError(2, 'Choose either --in or --review-at.');
|
|
118
|
+
const date = now();
|
|
119
|
+
const id = newId();
|
|
120
|
+
const projectId = projects.scopeProject(scope, project);
|
|
121
|
+
const dueDate = reviewAt ?? daysFrom(date, inDays ?? 90);
|
|
122
|
+
write(() => {
|
|
123
|
+
repository.create({
|
|
124
|
+
...data,
|
|
125
|
+
domain: normalize(data.domain),
|
|
126
|
+
id,
|
|
127
|
+
projectId,
|
|
128
|
+
reviewAt: dueDate,
|
|
129
|
+
createdAt: date.toISOString(),
|
|
130
|
+
updatedAt: date.toISOString(),
|
|
131
|
+
});
|
|
132
|
+
for (const tag of names)
|
|
133
|
+
tags.attach('decision', id, tag);
|
|
134
|
+
});
|
|
135
|
+
return show(id);
|
|
136
|
+
}
|
|
137
|
+
function edit(id, input) {
|
|
138
|
+
const { scope, project, domain, ...data } = validate(editSchema, input);
|
|
139
|
+
const projectId = scope || project ? projects.scopeProject(scope ?? 'project', project) : undefined;
|
|
140
|
+
write(() => {
|
|
141
|
+
load(id);
|
|
142
|
+
repository.edit(id, {
|
|
143
|
+
...data,
|
|
144
|
+
projectId,
|
|
145
|
+
domain: domain && normalize(domain),
|
|
146
|
+
updatedAt: now().toISOString(),
|
|
147
|
+
});
|
|
148
|
+
});
|
|
149
|
+
return show(id);
|
|
150
|
+
}
|
|
151
|
+
function remove(id) {
|
|
152
|
+
write(() => {
|
|
153
|
+
load(id);
|
|
154
|
+
repository.remove(id, now().toISOString());
|
|
155
|
+
});
|
|
156
|
+
}
|
|
157
|
+
function tag(id, action, name) {
|
|
158
|
+
write(() => {
|
|
159
|
+
load(id);
|
|
160
|
+
if (action === 'add')
|
|
161
|
+
tags.attach('decision', id, name);
|
|
162
|
+
else
|
|
163
|
+
tags.detach('decision', id, name);
|
|
164
|
+
});
|
|
165
|
+
return show(id);
|
|
166
|
+
}
|
|
167
|
+
function history(id) {
|
|
168
|
+
load(id);
|
|
169
|
+
return repository.history(id).map(withoutSyncMetadata);
|
|
170
|
+
}
|
|
171
|
+
/** 在写事务中读取决策并固定其快照,历史审核不会被后续编辑覆盖。 */
|
|
172
|
+
function review(id, input) {
|
|
173
|
+
const data = validate(reviewSchema, input);
|
|
174
|
+
return write(() => {
|
|
175
|
+
const { title, content, reason, alternatives, expected, domain, confidence, reviewAt } = load(id);
|
|
176
|
+
const reviewedAt = now().toISOString();
|
|
177
|
+
const row = {
|
|
178
|
+
id: newId(),
|
|
179
|
+
decisionId: id,
|
|
180
|
+
reviewedAt,
|
|
181
|
+
...data,
|
|
182
|
+
snapshot: { title, content, reason, alternatives, expected, domain, confidence, reviewAt },
|
|
183
|
+
};
|
|
184
|
+
repository.append(row);
|
|
185
|
+
repository.edit(id, { updatedAt: reviewedAt });
|
|
186
|
+
return row;
|
|
187
|
+
});
|
|
188
|
+
}
|
|
189
|
+
function saveAiNote(id, note) {
|
|
190
|
+
return write(() => {
|
|
191
|
+
show(id);
|
|
192
|
+
repository.edit(id, { aiNote: validate(nonempty, note), updatedAt: now().toISOString() });
|
|
193
|
+
return show(id);
|
|
194
|
+
});
|
|
195
|
+
}
|
|
196
|
+
return {
|
|
197
|
+
show,
|
|
198
|
+
list,
|
|
199
|
+
candidates,
|
|
200
|
+
countDue,
|
|
201
|
+
create,
|
|
202
|
+
edit,
|
|
203
|
+
remove,
|
|
204
|
+
tag,
|
|
205
|
+
review,
|
|
206
|
+
history,
|
|
207
|
+
saveAiNote,
|
|
208
|
+
};
|
|
209
|
+
}
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
import { and, eq, gte, isNull, sql } from 'drizzle-orm';
|
|
2
|
+
import { z } from 'zod';
|
|
3
|
+
import { commands, commandUsages, decisionReviews } from '../../infrastructure/database/schema.js';
|
|
4
|
+
import { daysFrom, localDay, validate } from '../../shared/input.js';
|
|
5
|
+
import { inScope } from '../../shared/query.js';
|
|
6
|
+
const periodSchema = z.enum(['30d', '90d', '180d', 'all']);
|
|
7
|
+
const highConfidence = 80;
|
|
8
|
+
/** 每项决策只取最新复盘的信心快照,样本为空时保留空值。 */
|
|
9
|
+
export function decisionStats(decisions, reviews, now, earliest) {
|
|
10
|
+
const sample = earliest
|
|
11
|
+
? decisions.filter((row) => localDay(new Date(row.createdAt)) >= earliest)
|
|
12
|
+
: decisions;
|
|
13
|
+
const sampledIds = new Set(sample.map(({ id }) => id));
|
|
14
|
+
const counts = { open: 0, due: 0, reviewed: 0 };
|
|
15
|
+
const domains = new Map();
|
|
16
|
+
for (const item of sample) {
|
|
17
|
+
counts[item.status]++;
|
|
18
|
+
domains.set(item.domain, (domains.get(item.domain) ?? 0) + 1);
|
|
19
|
+
}
|
|
20
|
+
const recent = new Map(Array.from({ length: 6 }, (_, index) => {
|
|
21
|
+
const month = new Date(now.getFullYear(), now.getMonth() - 5 + index, 1);
|
|
22
|
+
return [localDay(month).slice(0, 7), 0];
|
|
23
|
+
}).map(([month, count]) => [month, Number(count)]));
|
|
24
|
+
const latest = new Map();
|
|
25
|
+
for (const row of reviews) {
|
|
26
|
+
const month = localDay(new Date(row.reviewedAt)).slice(0, 7);
|
|
27
|
+
if (recent.has(month))
|
|
28
|
+
recent.set(month, (recent.get(month) ?? 0) + 1);
|
|
29
|
+
if (!sampledIds.has(row.decisionId))
|
|
30
|
+
continue;
|
|
31
|
+
const previous = latest.get(row.decisionId);
|
|
32
|
+
if (!previous ||
|
|
33
|
+
row.reviewedAt > previous.reviewedAt ||
|
|
34
|
+
(row.reviewedAt === previous.reviewedAt && row.id > previous.id))
|
|
35
|
+
latest.set(row.decisionId, row);
|
|
36
|
+
}
|
|
37
|
+
const confident = [...latest.values()].filter((row) => row.snapshot.confidence !== null && row.snapshot.confidence >= highConfidence);
|
|
38
|
+
const accurate = confident.filter((row) => row.rating === 'accurate').length;
|
|
39
|
+
return {
|
|
40
|
+
total: sample.length,
|
|
41
|
+
...counts,
|
|
42
|
+
domains: Object.fromEntries([...domains].sort()),
|
|
43
|
+
reviewsLastSixMonths: [...recent.values()].reduce((total, current) => total + current, 0),
|
|
44
|
+
monthlyReviews: Object.fromEntries(recent),
|
|
45
|
+
highConfidence: {
|
|
46
|
+
threshold: highConfidence,
|
|
47
|
+
samples: confident.length,
|
|
48
|
+
accurate,
|
|
49
|
+
accuracy: confident.length ? accurate / confident.length : null,
|
|
50
|
+
},
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
export function statistics(db, decisions, projects, clock) {
|
|
54
|
+
return (rawPeriod = 'all', selector) => {
|
|
55
|
+
const period = validate(periodSchema, rawPeriod);
|
|
56
|
+
const today = clock();
|
|
57
|
+
const earliest = period === 'all' ? undefined : daysFrom(today, 1 - Number(period.slice(0, -1)));
|
|
58
|
+
const projectId = projects.resolve(selector)?.id ?? null;
|
|
59
|
+
const items = decisions.candidates({ project: selector });
|
|
60
|
+
const ids = new Set(items.map(({ id }) => id));
|
|
61
|
+
const reviews = db
|
|
62
|
+
.select()
|
|
63
|
+
.from(decisionReviews)
|
|
64
|
+
.where(isNull(decisionReviews.deletedAt))
|
|
65
|
+
.all()
|
|
66
|
+
.filter((row) => ids.has(row.decisionId));
|
|
67
|
+
const since = earliest ? new Date(earliest + 'T00:00:00').toISOString() : undefined;
|
|
68
|
+
const sorts = db
|
|
69
|
+
.select({ kind: commandUsages.kind, count: sql `count(*)` })
|
|
70
|
+
.from(commandUsages)
|
|
71
|
+
.innerJoin(commands, eq(commandUsages.commandId, commands.id))
|
|
72
|
+
.where(and(isNull(commands.deletedAt), inScope(commands.projectId, projectId), since ? gte(commandUsages.usedAt, since) : undefined))
|
|
73
|
+
.groupBy(commandUsages.kind)
|
|
74
|
+
.all();
|
|
75
|
+
return {
|
|
76
|
+
period,
|
|
77
|
+
...decisionStats(items, reviews, today, earliest),
|
|
78
|
+
usage: {
|
|
79
|
+
copy: sorts.find((entry) => entry.kind === 'copy')?.count ?? 0,
|
|
80
|
+
run: sorts.find((entry) => entry.kind === 'run')?.count ?? 0,
|
|
81
|
+
},
|
|
82
|
+
};
|
|
83
|
+
};
|
|
84
|
+
}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { and, eq, isNull, or, sql } from 'drizzle-orm';
|
|
2
|
+
import { projectLocalBindings, projects } from '../../infrastructure/database/schema.js';
|
|
3
|
+
export function projectRepository(db) {
|
|
4
|
+
const fields = {
|
|
5
|
+
id: projects.id,
|
|
6
|
+
name: projects.name,
|
|
7
|
+
remote: projects.remote,
|
|
8
|
+
createdAt: projects.createdAt,
|
|
9
|
+
updatedAt: projects.updatedAt,
|
|
10
|
+
root: projectLocalBindings.root,
|
|
11
|
+
aliases: sql `coalesce(${projectLocalBindings.aliases}, '[]')`.mapWith((value) => JSON.parse(value)),
|
|
12
|
+
};
|
|
13
|
+
const select = () => db
|
|
14
|
+
.select(fields)
|
|
15
|
+
.from(projects)
|
|
16
|
+
.leftJoin(projectLocalBindings, eq(projects.id, projectLocalBindings.projectId));
|
|
17
|
+
function bind(id, root, aliases) {
|
|
18
|
+
db.insert(projectLocalBindings)
|
|
19
|
+
.values({ projectId: id, root, aliases })
|
|
20
|
+
.onConflictDoUpdate({ target: projectLocalBindings.projectId, set: { root, aliases } })
|
|
21
|
+
.run();
|
|
22
|
+
}
|
|
23
|
+
const byId = (id) => select()
|
|
24
|
+
.where(and(eq(projects.id, id), isNull(projects.deletedAt)))
|
|
25
|
+
.get();
|
|
26
|
+
return {
|
|
27
|
+
byId,
|
|
28
|
+
byRoot: (root) => select()
|
|
29
|
+
.where(and(isNull(projects.deletedAt), or(eq(projectLocalBindings.root, root), sql `exists (select 1 from json_each(${projectLocalBindings.aliases}) where value = ${root})`)))
|
|
30
|
+
.get(),
|
|
31
|
+
byRemote: (remote) => select()
|
|
32
|
+
.where(and(eq(projects.remote, remote), isNull(projects.deletedAt)))
|
|
33
|
+
.get(),
|
|
34
|
+
insert: ({ root, aliases, ...row }) => {
|
|
35
|
+
db.insert(projects).values(row).run();
|
|
36
|
+
if (root !== null)
|
|
37
|
+
bind(row.id, root, aliases);
|
|
38
|
+
return byId(row.id);
|
|
39
|
+
},
|
|
40
|
+
bind,
|
|
41
|
+
update: (id, patch) => {
|
|
42
|
+
db.update(projects).set(patch).where(eq(projects.id, id)).run();
|
|
43
|
+
return byId(id);
|
|
44
|
+
},
|
|
45
|
+
list: (limit) => select()
|
|
46
|
+
.where(isNull(projects.deletedAt))
|
|
47
|
+
.orderBy(projects.name, projects.id)
|
|
48
|
+
.limit(limit)
|
|
49
|
+
.all(),
|
|
50
|
+
};
|
|
51
|
+
}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import { basename } from 'node:path';
|
|
2
|
+
import { detectGit } from '../../infrastructure/git/detector.js';
|
|
3
|
+
import { AppError } from '../../shared/errors.js';
|
|
4
|
+
import { newId } from '../../shared/input.js';
|
|
5
|
+
export function projectService(repository, write, cwd, preview, now) {
|
|
6
|
+
let current;
|
|
7
|
+
function identify() {
|
|
8
|
+
if (current !== undefined)
|
|
9
|
+
return current;
|
|
10
|
+
const git = detectGit(cwd);
|
|
11
|
+
if (!git)
|
|
12
|
+
return (current = null);
|
|
13
|
+
const atRoot = () => repository.byRoot(git.root);
|
|
14
|
+
const atRemote = () => (git.remote ? repository.byRemote(git.remote) : undefined);
|
|
15
|
+
if (preview)
|
|
16
|
+
return (current = atRoot() ?? atRemote() ?? null);
|
|
17
|
+
current = write(() => {
|
|
18
|
+
const pathMatch = atRoot();
|
|
19
|
+
const remoteMatch = atRemote();
|
|
20
|
+
const timestamp = now().toISOString();
|
|
21
|
+
if (pathMatch) {
|
|
22
|
+
if (git.remote && git.remote !== pathMatch.remote && !remoteMatch) {
|
|
23
|
+
return repository.update(pathMatch.id, { remote: git.remote, updatedAt: timestamp });
|
|
24
|
+
}
|
|
25
|
+
return pathMatch;
|
|
26
|
+
}
|
|
27
|
+
if (remoteMatch) {
|
|
28
|
+
const root = remoteMatch.root ?? git.root;
|
|
29
|
+
const aliases = remoteMatch.root ? [...remoteMatch.aliases, git.root] : [];
|
|
30
|
+
repository.bind(remoteMatch.id, root, aliases);
|
|
31
|
+
return { ...remoteMatch, root, aliases };
|
|
32
|
+
}
|
|
33
|
+
return repository.insert({
|
|
34
|
+
id: newId(),
|
|
35
|
+
name: basename(git.root),
|
|
36
|
+
root: git.root,
|
|
37
|
+
aliases: [],
|
|
38
|
+
remote: git.remote,
|
|
39
|
+
createdAt: timestamp,
|
|
40
|
+
updatedAt: timestamp,
|
|
41
|
+
});
|
|
42
|
+
});
|
|
43
|
+
return current;
|
|
44
|
+
}
|
|
45
|
+
function resolveProject(selector) {
|
|
46
|
+
if (selector === undefined || selector === 'current')
|
|
47
|
+
return identify();
|
|
48
|
+
const project = repository.byId(selector);
|
|
49
|
+
if (!project)
|
|
50
|
+
throw new AppError(3, `Project ${selector} was not found. Run pxo project list.`);
|
|
51
|
+
return project;
|
|
52
|
+
}
|
|
53
|
+
function scopeProject(scope, selector) {
|
|
54
|
+
if (scope === 'global') {
|
|
55
|
+
if (selector !== undefined)
|
|
56
|
+
throw new AppError(2, 'Remove --project when selecting global scope.');
|
|
57
|
+
return null;
|
|
58
|
+
}
|
|
59
|
+
const project = resolveProject(selector);
|
|
60
|
+
if (!project && (scope === 'project' || selector !== undefined)) {
|
|
61
|
+
throw new AppError(2, 'No project was found. Choose a project ID or use global scope.');
|
|
62
|
+
}
|
|
63
|
+
return project?.id ?? null;
|
|
64
|
+
}
|
|
65
|
+
return {
|
|
66
|
+
current: identify,
|
|
67
|
+
resolve: resolveProject,
|
|
68
|
+
scopeProject,
|
|
69
|
+
list: repository.list,
|
|
70
|
+
invalidate() {
|
|
71
|
+
current = undefined;
|
|
72
|
+
},
|
|
73
|
+
};
|
|
74
|
+
}
|
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import { mkdir, mkdtemp, rm } from 'node:fs/promises';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
import { z } from 'zod';
|
|
5
|
+
import { AppError } from '../../shared/errors.js';
|
|
6
|
+
import { manifest, parseSnapshot, serialize, snapshotData, tables } from './snapshot.js';
|
|
7
|
+
function run(program, args, env = process.env, input) {
|
|
8
|
+
return new Promise((resolve) => {
|
|
9
|
+
const child = spawn(program, args, { env, windowsHide: true, timeout: 60_000 });
|
|
10
|
+
const out = [], err = [];
|
|
11
|
+
let size = 0;
|
|
12
|
+
child.stdout.on('data', (chunk) => {
|
|
13
|
+
size += chunk.length;
|
|
14
|
+
if (size > 32 * 1024 * 1024)
|
|
15
|
+
child.kill();
|
|
16
|
+
else
|
|
17
|
+
out.push(chunk);
|
|
18
|
+
});
|
|
19
|
+
child.stderr.on('data', (chunk) => {
|
|
20
|
+
if (err.length < 64)
|
|
21
|
+
err.push(chunk);
|
|
22
|
+
});
|
|
23
|
+
child.stdin.on('error', () => { });
|
|
24
|
+
child.stdin.end(input);
|
|
25
|
+
child.once('error', () => resolve({ code: null, stdout: '', stderr: '' }));
|
|
26
|
+
child.once('close', (code) => resolve({
|
|
27
|
+
code,
|
|
28
|
+
stdout: Buffer.concat(out).toString('utf8'),
|
|
29
|
+
stderr: Buffer.concat(err).toString('utf8'),
|
|
30
|
+
}));
|
|
31
|
+
});
|
|
32
|
+
}
|
|
33
|
+
const shaSchema = z.string().regex(/^[a-f\d]{40}$/u);
|
|
34
|
+
const ref = 'refs/praxo/remote';
|
|
35
|
+
export async function gitHistory(directory, sha) {
|
|
36
|
+
const result = await run('git', [
|
|
37
|
+
'-c',
|
|
38
|
+
'core.longpaths=true',
|
|
39
|
+
'--git-dir=' + directory,
|
|
40
|
+
'log',
|
|
41
|
+
'-20',
|
|
42
|
+
'--format=%H%x09%cI',
|
|
43
|
+
shaSchema.parse(sha),
|
|
44
|
+
'--',
|
|
45
|
+
]);
|
|
46
|
+
return result.code === 0
|
|
47
|
+
? result.stdout
|
|
48
|
+
.trim()
|
|
49
|
+
.split('\n')
|
|
50
|
+
.filter(Boolean)
|
|
51
|
+
.map((line) => {
|
|
52
|
+
const [sha, at] = line.trim().split('\t');
|
|
53
|
+
return { sha: sha ?? '', at: at ?? '' };
|
|
54
|
+
})
|
|
55
|
+
: [];
|
|
56
|
+
}
|
|
57
|
+
/** 将常见 Git/SSH 错误映射为清晰且可操作的诊断提示。 */
|
|
58
|
+
export function sshErrorMessage(stderr, fallback) {
|
|
59
|
+
if (/host key verification failed/iu.test(stderr)) {
|
|
60
|
+
return 'SSH host key verification failed. Run `ssh -T git@github.com` once to trust the host, then retry.';
|
|
61
|
+
}
|
|
62
|
+
if (/permission denied \(publickey|no such identity|could not open a connection to your authentication agent/iu.test(stderr)) {
|
|
63
|
+
return 'SSH authentication failed. Verify your local SSH key is loaded in ssh-agent and added to your Git account.';
|
|
64
|
+
}
|
|
65
|
+
if (/repository not found|does not appear to be a git repository|could not read from remote repository/iu.test(stderr)) {
|
|
66
|
+
return 'Cannot access the remote repository over SSH. Check the repository URL and your SSH permissions.';
|
|
67
|
+
}
|
|
68
|
+
if (/could not resolve hostname|connection timed out|network is unreachable|connection refused/iu.test(stderr)) {
|
|
69
|
+
return 'Cannot reach the remote Git server. Check your network connection and SSH configuration.';
|
|
70
|
+
}
|
|
71
|
+
return fallback;
|
|
72
|
+
}
|
|
73
|
+
/** Git 对象仅由已校验快照构造,完全复用本机 Git/SSH 执行单分支普通推送。 */
|
|
74
|
+
export async function gitTransport(directory, url, branch) {
|
|
75
|
+
const branchResult = await run('git', ['check-ref-format', '--branch', branch]);
|
|
76
|
+
if (branchResult.code !== 0 || branchResult.stdout.trim() !== branch) {
|
|
77
|
+
throw new AppError(2, 'Use a valid Git branch name and install Git before setting up sync.');
|
|
78
|
+
}
|
|
79
|
+
const target = 'refs/heads/' + branch;
|
|
80
|
+
await mkdir(directory, { recursive: true, mode: 0o700 });
|
|
81
|
+
const env = {
|
|
82
|
+
...process.env,
|
|
83
|
+
GIT_TERMINAL_PROMPT: '0',
|
|
84
|
+
GCM_INTERACTIVE: 'Never',
|
|
85
|
+
};
|
|
86
|
+
for (const key of [
|
|
87
|
+
'GIT_DIR',
|
|
88
|
+
'GIT_WORK_TREE',
|
|
89
|
+
'GIT_INDEX_FILE',
|
|
90
|
+
'GIT_COMMON_DIR',
|
|
91
|
+
'GIT_CONFIG_PARAMETERS',
|
|
92
|
+
])
|
|
93
|
+
delete env[key];
|
|
94
|
+
if (!env.GIT_SSH_COMMAND && !env.GIT_SSH) {
|
|
95
|
+
const customSsh = await run('git', ['config', '--get', 'core.sshCommand'], env);
|
|
96
|
+
if (customSsh.code !== 0 || !customSsh.stdout.trim()) {
|
|
97
|
+
env.GIT_SSH_COMMAND = 'ssh -o BatchMode=yes -o ConnectTimeout=15';
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
const options = [
|
|
101
|
+
['core.hooksPath', join(directory, 'disabled-hooks')],
|
|
102
|
+
['core.longpaths', 'true'],
|
|
103
|
+
['user.name', 'Praxo'],
|
|
104
|
+
['user.email', 'sync@praxo.local'],
|
|
105
|
+
];
|
|
106
|
+
env.GIT_CONFIG_COUNT = String(options.length);
|
|
107
|
+
for (const [i, [key, value]] of options.entries()) {
|
|
108
|
+
env['GIT_CONFIG_KEY_' + i] = key;
|
|
109
|
+
env['GIT_CONFIG_VALUE_' + i] = value;
|
|
110
|
+
}
|
|
111
|
+
const git = (args, input, extra) => run('git', ['-C', directory, ...args], extra ? { ...env, ...extra } : env, input);
|
|
112
|
+
const requireGit = async (args, message, input, extra) => {
|
|
113
|
+
const result = await git(args, input, extra);
|
|
114
|
+
if (result.code !== 0)
|
|
115
|
+
throw new AppError(1, sshErrorMessage(result.stderr, message));
|
|
116
|
+
return result.stdout;
|
|
117
|
+
};
|
|
118
|
+
await requireGit(['init', '--bare', '--quiet', '--object-format=sha1'], 'Cannot initialize the sync cache. Check directory permissions.');
|
|
119
|
+
return {
|
|
120
|
+
async fetch() {
|
|
121
|
+
const exists = await git(['ls-remote', '--exit-code', '--refs', '--', url, target]);
|
|
122
|
+
if (exists.code === 2)
|
|
123
|
+
return { sha: null, snapshot: new Map() };
|
|
124
|
+
if (exists.code !== 0)
|
|
125
|
+
throw new AppError(1, sshErrorMessage(exists.stderr, 'Cannot reach the sync repository. Check your connection and local SSH access.'));
|
|
126
|
+
await requireGit([
|
|
127
|
+
'fetch',
|
|
128
|
+
'--quiet',
|
|
129
|
+
'--no-tags',
|
|
130
|
+
'--no-recurse-submodules',
|
|
131
|
+
'--',
|
|
132
|
+
url,
|
|
133
|
+
'+' + target + ':' + ref,
|
|
134
|
+
], 'Could not fetch the sync branch. Check local SSH access and retry.');
|
|
135
|
+
const sha = shaSchema.parse((await requireGit(['rev-parse', ref], 'Cannot read the fetched commit.')).trim());
|
|
136
|
+
async function object(path) {
|
|
137
|
+
const result = await git(['cat-file', 'blob', sha + ':' + path]);
|
|
138
|
+
if (result.code === 0) {
|
|
139
|
+
try {
|
|
140
|
+
return JSON.parse(result.stdout);
|
|
141
|
+
}
|
|
142
|
+
catch {
|
|
143
|
+
/* 损坏文件与缺失文件使用同一诊断。 */
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
throw new AppError(5, 'Missing or invalid ' + path + ' on the sync branch.');
|
|
147
|
+
}
|
|
148
|
+
if (!manifest.safeParse(await object('manifest.json')).success) {
|
|
149
|
+
throw new AppError(5, 'Unsupported sync manifest. Select a Praxo sync branch or upgrade Praxo.');
|
|
150
|
+
}
|
|
151
|
+
const data = await Promise.all(tables.map(async (table) => [table, await object('data/' + table + '.json')]));
|
|
152
|
+
return { sha, snapshot: parseSnapshot(Object.fromEntries(data)) };
|
|
153
|
+
},
|
|
154
|
+
async commit(snapshot, parent, now) {
|
|
155
|
+
const dir = await mkdtemp(join(directory, 'index-'));
|
|
156
|
+
const extra = {
|
|
157
|
+
GIT_INDEX_FILE: join(dir, 'index'),
|
|
158
|
+
GIT_AUTHOR_DATE: now,
|
|
159
|
+
GIT_COMMITTER_DATE: now,
|
|
160
|
+
};
|
|
161
|
+
try {
|
|
162
|
+
const files = {
|
|
163
|
+
'manifest.json': { format: 'praxo-sync', schemaVersion: 1, exportedAt: now },
|
|
164
|
+
...Object.fromEntries(Object.entries(snapshotData(snapshot)).map(([table, rows]) => [
|
|
165
|
+
'data/' + table + '.json',
|
|
166
|
+
rows,
|
|
167
|
+
])),
|
|
168
|
+
};
|
|
169
|
+
const index = await Promise.all(Object.entries(files).map(async ([path, value]) => {
|
|
170
|
+
const sha = await requireGit(['hash-object', '-w', '--stdin'], 'Cannot write sync data to the Git cache.', serialize(value));
|
|
171
|
+
return '100644 ' + sha.trim() + '\t' + path + '\n';
|
|
172
|
+
}));
|
|
173
|
+
await requireGit(['update-index', '--index-info'], 'Cannot build the sync index.', index.join(''), extra);
|
|
174
|
+
const tree = (await requireGit(['write-tree'], 'Cannot build the sync tree.', undefined, extra)).trim();
|
|
175
|
+
const args = ['commit-tree', tree, ...(parent ? ['-p', parent] : []), '-m', 'Praxo sync'];
|
|
176
|
+
return shaSchema.parse((await requireGit(args, 'Cannot create the sync commit.', undefined, extra)).trim());
|
|
177
|
+
}
|
|
178
|
+
finally {
|
|
179
|
+
await rm(dir, { recursive: true, force: true });
|
|
180
|
+
}
|
|
181
|
+
},
|
|
182
|
+
async push(sha) {
|
|
183
|
+
const result = await git([
|
|
184
|
+
'push',
|
|
185
|
+
'--porcelain',
|
|
186
|
+
'--',
|
|
187
|
+
url,
|
|
188
|
+
shaSchema.parse(sha) + ':' + target,
|
|
189
|
+
]);
|
|
190
|
+
if (result.code === 0) {
|
|
191
|
+
await requireGit(['update-ref', ref, sha], 'Push succeeded but cached state could not be updated. Retry sync.');
|
|
192
|
+
return true;
|
|
193
|
+
}
|
|
194
|
+
if (/\[rejected\].*\((?:non-fast-forward|fetch first|stale info)\)|cannot lock ref .*is at .*but expected/iu.test(result.stdout + result.stderr))
|
|
195
|
+
return false;
|
|
196
|
+
throw new AppError(1, sshErrorMessage(result.stderr, 'Git push failed. Check connectivity, branch protection and write permissions, then retry.'));
|
|
197
|
+
},
|
|
198
|
+
async hasAncestor(ancestor, sha) {
|
|
199
|
+
return ((await git([
|
|
200
|
+
'merge-base',
|
|
201
|
+
'--is-ancestor',
|
|
202
|
+
shaSchema.parse(ancestor),
|
|
203
|
+
shaSchema.parse(sha),
|
|
204
|
+
])).code === 0);
|
|
205
|
+
},
|
|
206
|
+
};
|
|
207
|
+
}
|