@laoyuehanni/dsh-git-worktree 0.4.14 → 0.4.16
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/README.md +9 -3
- package/README.zh.md +9 -3
- package/docs/DETAIL.md +5 -2
- package/docs/DETAIL.zh.md +5 -2
- package/lib/client.js +4253 -620
- package/lib/deferred-worktree.d.ts +105 -0
- package/lib/deferred-worktree.js +293 -0
- package/lib/git.d.ts +95 -0
- package/lib/git.js +384 -4
- package/lib/index.d.ts +13 -0
- package/lib/index.js +204 -4
- package/lib/normalize.d.ts +13 -0
- package/lib/normalize.js +51 -0
- package/lib/pr.d.ts +177 -0
- package/lib/pr.js +672 -0
- package/lib/routes.d.ts +61 -3
- package/lib/routes.js +639 -80
- package/lib/wire.d.ts +235 -3
- package/lib/wire.js +17 -0
- package/package.json +1 -1
package/lib/index.js
CHANGED
|
@@ -7,13 +7,15 @@
|
|
|
7
7
|
*/
|
|
8
8
|
import { homedir } from 'node:os';
|
|
9
9
|
import z from '@deepseek-ai/schemastery';
|
|
10
|
+
import { DeferredWorktreeCoordinator } from './deferred-worktree.js';
|
|
10
11
|
import { childProcessExec } from './git.js';
|
|
11
|
-
import {
|
|
12
|
+
import { isForgeServiceLike } from './pr.js';
|
|
13
|
+
import { executeCreateWorktree, handleArmDeferredWorktree, handleCreateBranch, handleCreateWorktree, handleDeferredWorktreeAction, handleDeleteBranch, handleEnsureDirectory, handleFetch, handleGetDeferredWorktree, handleGroupWorktrees, handleHead, handleInspectWorktree, handlePathExists, handlePrCheckout, handlePrContext, handlePrResolve, handlePush, handlePushPlan, handlePushPreview, handlePurgeDirectory, handleRemoveWorktree, handleRenameBranch, handleSetSessionDirectory, handleStatus, handleSwitch, handleUpdate, handleWorktreesAll, } from './routes.js';
|
|
12
14
|
import { validateRootDir } from './settings.js';
|
|
13
15
|
import { handleAuthors, handleHistory, handleCommit } from './routes.js';
|
|
14
16
|
import { ROUTE_AUTHORS, ROUTE_HISTORY, ROUTE_COMMIT } from './wire.js';
|
|
15
17
|
import { streamRoute } from './stream.js';
|
|
16
|
-
import { ROUTE_BRANCH, ROUTE_BRANCH_DELETE, ROUTE_BRANCH_RENAME, ROUTE_ENSURE_DIRECTORY, ROUTE_EXISTS, ROUTE_FETCH, ROUTE_GROUP, ROUTE_HEAD, ROUTE_INSPECT, ROUTE_PUSH, ROUTE_PUSH_PLAN, ROUTE_PUSH_PREVIEW, ROUTE_PURGE, ROUTE_REMOVE, ROUTE_STATUS, ROUTE_SWITCH, ROUTE_UPDATE, ROUTE_WORKTREE, ROUTE_WORKTREES_ALL } from './wire.js';
|
|
18
|
+
import { ROUTE_BRANCH, ROUTE_BRANCH_DELETE, ROUTE_BRANCH_RENAME, ROUTE_DEFERRED, ROUTE_DEFERRED_ACTION, ROUTE_DEFERRED_ARM, ROUTE_DEFERRED_EVENTS, ROUTE_ENSURE_DIRECTORY, ROUTE_EXISTS, ROUTE_FETCH, ROUTE_GROUP, ROUTE_HEAD, ROUTE_INSPECT, ROUTE_PR_CHECKOUT, ROUTE_PR_CONTEXT, ROUTE_PR_RESOLVE, ROUTE_PUSH, ROUTE_PUSH_PLAN, ROUTE_PUSH_PREVIEW, ROUTE_PURGE, ROUTE_REMOVE, ROUTE_SESSION_CWD, ROUTE_STATUS, ROUTE_SWITCH, ROUTE_UPDATE, ROUTE_WORKTREE, ROUTE_WORKTREES_ALL } from './wire.js';
|
|
17
19
|
export const name = 'dsh-git-worktree';
|
|
18
20
|
export const inject = [];
|
|
19
21
|
/** Largest accepted request body (bytes) — these payloads are a few strings. */
|
|
@@ -41,10 +43,13 @@ export const Config = z.object({
|
|
|
41
43
|
autoPruneWorktrees: z.boolean().default(false).volatile(),
|
|
42
44
|
keepWorktrees: z.number().default(KEEP_WORKTREES_DEFAULT).volatile(),
|
|
43
45
|
postCreateCopyFiles: z.array(z.string()).default([]).volatile(),
|
|
46
|
+
hideOfficialWorktreeEntry: z.boolean().default(true).volatile(),
|
|
47
|
+
switchSessionDirectory: z.boolean().default(false).volatile(),
|
|
48
|
+
manageOfficialWorktrees: z.boolean().default(false).volatile(),
|
|
44
49
|
});
|
|
45
50
|
/** Reject stale or misspelled config keys before defaults can hide them. */
|
|
46
51
|
export function validateConfig(config) {
|
|
47
|
-
const unknown = Object.keys(config).find(key => key !== 'rootDir' && key !== 'groupSidebar' && key !== 'fetchBeforeCreate' && key !== 'openGraphByDefault' && key !== 'autoPruneWorktrees' && key !== 'keepWorktrees' && key !== 'postCreateCopyFiles');
|
|
52
|
+
const unknown = Object.keys(config).find(key => key !== 'rootDir' && key !== 'groupSidebar' && key !== 'fetchBeforeCreate' && key !== 'openGraphByDefault' && key !== 'autoPruneWorktrees' && key !== 'keepWorktrees' && key !== 'postCreateCopyFiles' && key !== 'hideOfficialWorktreeEntry' && key !== 'switchSessionDirectory' && key !== 'manageOfficialWorktrees');
|
|
48
53
|
if (unknown !== undefined) {
|
|
49
54
|
throw new Error(`GitWorktreeConfig: unknown key "${unknown}"`);
|
|
50
55
|
}
|
|
@@ -68,6 +73,18 @@ export function validateConfig(config) {
|
|
|
68
73
|
if (autoPruneWorktrees !== undefined && typeof autoPruneWorktrees !== 'boolean') {
|
|
69
74
|
throw new Error('GitWorktreeConfig: "autoPruneWorktrees" must be a boolean');
|
|
70
75
|
}
|
|
76
|
+
const hideOfficialWorktreeEntry = readVolatile(config.hideOfficialWorktreeEntry);
|
|
77
|
+
if (hideOfficialWorktreeEntry !== undefined && typeof hideOfficialWorktreeEntry !== 'boolean') {
|
|
78
|
+
throw new Error('GitWorktreeConfig: "hideOfficialWorktreeEntry" must be a boolean');
|
|
79
|
+
}
|
|
80
|
+
const switchSessionDirectory = readVolatile(config.switchSessionDirectory);
|
|
81
|
+
if (switchSessionDirectory !== undefined && typeof switchSessionDirectory !== 'boolean') {
|
|
82
|
+
throw new Error('GitWorktreeConfig: "switchSessionDirectory" must be a boolean');
|
|
83
|
+
}
|
|
84
|
+
const manageOfficialWorktrees = readVolatile(config.manageOfficialWorktrees);
|
|
85
|
+
if (manageOfficialWorktrees !== undefined && typeof manageOfficialWorktrees !== 'boolean') {
|
|
86
|
+
throw new Error('GitWorktreeConfig: "manageOfficialWorktrees" must be a boolean');
|
|
87
|
+
}
|
|
71
88
|
const postCreateCopyFiles = readVolatile(config.postCreateCopyFiles);
|
|
72
89
|
if (postCreateCopyFiles !== undefined) {
|
|
73
90
|
if (!Array.isArray(postCreateCopyFiles) || !postCreateCopyFiles.every(item => typeof item === 'string')) {
|
|
@@ -103,6 +120,9 @@ export function sectionOf(config) {
|
|
|
103
120
|
const openGraphByDefault = readVolatile(config.openGraphByDefault);
|
|
104
121
|
const autoPruneWorktrees = readVolatile(config.autoPruneWorktrees);
|
|
105
122
|
const keepWorktrees = readVolatile(config.keepWorktrees);
|
|
123
|
+
const hideOfficialWorktreeEntry = readVolatile(config.hideOfficialWorktreeEntry);
|
|
124
|
+
const switchSessionDirectory = readVolatile(config.switchSessionDirectory);
|
|
125
|
+
const manageOfficialWorktrees = readVolatile(config.manageOfficialWorktrees);
|
|
106
126
|
return {
|
|
107
127
|
...(rootDir === undefined ? {} : { rootDir }),
|
|
108
128
|
...(postCreateCopyFiles === undefined ? {} : { postCreateCopyFiles }),
|
|
@@ -113,8 +133,16 @@ export function sectionOf(config) {
|
|
|
113
133
|
openGraphByDefault: openGraphByDefault ?? false,
|
|
114
134
|
autoPruneWorktrees: autoPruneWorktrees ?? false,
|
|
115
135
|
keepWorktrees: keepWorktrees ?? KEEP_WORKTREES_DEFAULT,
|
|
136
|
+
hideOfficialWorktreeEntry: hideOfficialWorktreeEntry ?? true,
|
|
137
|
+
switchSessionDirectory: switchSessionDirectory ?? false,
|
|
138
|
+
manageOfficialWorktrees: manageOfficialWorktrees ?? false,
|
|
116
139
|
};
|
|
117
140
|
}
|
|
141
|
+
const isHostAgentRegistryLike = (value) => typeof value === 'object' && value !== null && typeof value.get === 'function';
|
|
142
|
+
const isHostWorkingDirectoryLike = (value) => typeof value === 'object' && value !== null && typeof value.set === 'function';
|
|
143
|
+
function withHttpStatus(message, httpStatus) {
|
|
144
|
+
return Object.assign(new Error(message), { httpStatus });
|
|
145
|
+
}
|
|
118
146
|
/**
|
|
119
147
|
* Plugin apply: mount the settings presentation policy and HTTP routes on any
|
|
120
148
|
* webServer that comes and goes.
|
|
@@ -124,14 +152,99 @@ export function sectionOf(config) {
|
|
|
124
152
|
export function apply(ctx, config = {}) {
|
|
125
153
|
validateConfig(config);
|
|
126
154
|
const currentConfig = () => ctx.fiber?.config ?? config;
|
|
127
|
-
|
|
155
|
+
let sessionDirectorySetter;
|
|
156
|
+
let deferredWorktrees;
|
|
157
|
+
let forgeService;
|
|
158
|
+
const baseDeps = () => ({
|
|
128
159
|
exec: childProcessExec,
|
|
129
160
|
sectionRootDir: () => readVolatile(currentConfig().rootDir),
|
|
130
161
|
sectionFetchBeforeCreate: () => readVolatile(currentConfig().fetchBeforeCreate),
|
|
131
162
|
sectionPostCreateCopyFiles: () => readVolatile(currentConfig().postCreateCopyFiles),
|
|
163
|
+
sectionManageOfficialWorktrees: () => readVolatile(currentConfig().manageOfficialWorktrees),
|
|
164
|
+
forge: () => forgeService,
|
|
165
|
+
...(sessionDirectorySetter === undefined ? {} : { setSessionDirectory: sessionDirectorySetter }),
|
|
166
|
+
...(deferredWorktrees === undefined ? {} : { deferredWorktrees }),
|
|
132
167
|
home: () => homedir(),
|
|
133
168
|
envHome: () => process.env.DSH_HOME,
|
|
134
169
|
});
|
|
170
|
+
if (typeof ctx.inject === 'function') {
|
|
171
|
+
const injectOptional = ctx.inject.bind(ctx);
|
|
172
|
+
injectOptional(['forge'], (forgeCtx) => {
|
|
173
|
+
const candidate = forgeCtx.forge;
|
|
174
|
+
if (isForgeServiceLike(candidate)) {
|
|
175
|
+
forgeService = candidate;
|
|
176
|
+
forgeCtx.effect(() => () => {
|
|
177
|
+
if (forgeService === candidate)
|
|
178
|
+
forgeService = undefined;
|
|
179
|
+
}, 'git-worktree: optional forge bridge');
|
|
180
|
+
}
|
|
181
|
+
});
|
|
182
|
+
injectOptional(['agents', 'workingDirectory'], (hostCtx) => {
|
|
183
|
+
const agentsCandidate = hostCtx.agents;
|
|
184
|
+
const workingDirCandidate = hostCtx.workingDirectory;
|
|
185
|
+
if (!isHostAgentRegistryLike(agentsCandidate) || !isHostWorkingDirectoryLike(workingDirCandidate))
|
|
186
|
+
return;
|
|
187
|
+
const setter = async (sessionId, targetPath) => {
|
|
188
|
+
const live = agentsCandidate.get(sessionId);
|
|
189
|
+
if (live !== undefined) {
|
|
190
|
+
return await workingDirCandidate.set(live, targetPath);
|
|
191
|
+
}
|
|
192
|
+
if (typeof agentsCandidate.resume === 'function') {
|
|
193
|
+
const resumed = await agentsCandidate.resume({ resumeSessionId: sessionId });
|
|
194
|
+
try {
|
|
195
|
+
return await workingDirCandidate.set(resumed.agent, targetPath);
|
|
196
|
+
}
|
|
197
|
+
finally {
|
|
198
|
+
await resumed.dispose?.();
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
throw withHttpStatus(`Session "${sessionId}" is not loaded`, 404);
|
|
202
|
+
};
|
|
203
|
+
const coordinator = new DeferredWorktreeCoordinator({
|
|
204
|
+
createWorktree: (spec, onPhase, signal) => executeCreateWorktree(baseDeps(), spec, onPhase, signal),
|
|
205
|
+
setWorkingDirectory: (agent, targetPath, signal) => workingDirCandidate.set(agent, targetPath, signal),
|
|
206
|
+
});
|
|
207
|
+
sessionDirectorySetter = setter;
|
|
208
|
+
deferredWorktrees = coordinator;
|
|
209
|
+
const listen = hostCtx.on?.bind(hostCtx);
|
|
210
|
+
const unsubInbox = listen?.('agent/inbox/inserted', (payload) => {
|
|
211
|
+
const record = payload;
|
|
212
|
+
if (record?.agent !== undefined)
|
|
213
|
+
coordinator.onInboxInserted(record.agent, record.message);
|
|
214
|
+
});
|
|
215
|
+
const unsubPreStep = listen?.('agent/pre-step', async (payload, next) => {
|
|
216
|
+
const record = payload;
|
|
217
|
+
const callNext = typeof next === 'function' ? next : async () => undefined;
|
|
218
|
+
if (record?.agent !== undefined && typeof record.step === 'number') {
|
|
219
|
+
const created = await coordinator.onPreStep(record.agent, record.step, record.signal);
|
|
220
|
+
if (!created)
|
|
221
|
+
return await callNext();
|
|
222
|
+
const decision = await callNext();
|
|
223
|
+
if (decision !== undefined && decision.kind !== 'reject' && Array.isArray(decision.messages) && decision.messages.length > 0) {
|
|
224
|
+
const nextStep = record.agent.inbox?.nextStep ?? [];
|
|
225
|
+
const notices = nextStep.filter(item => item.source?.kind === 'working-directory');
|
|
226
|
+
if (notices.length > 0) {
|
|
227
|
+
for (const notice of notices)
|
|
228
|
+
record.agent.inbox?.remove?.(notice.id);
|
|
229
|
+
return { ...decision, messages: [...decision.messages, ...notices] };
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
return decision;
|
|
233
|
+
}
|
|
234
|
+
return await callNext();
|
|
235
|
+
});
|
|
236
|
+
hostCtx.effect(() => async () => {
|
|
237
|
+
unsubInbox?.();
|
|
238
|
+
unsubPreStep?.();
|
|
239
|
+
if (sessionDirectorySetter === setter)
|
|
240
|
+
sessionDirectorySetter = undefined;
|
|
241
|
+
if (deferredWorktrees === coordinator)
|
|
242
|
+
deferredWorktrees = undefined;
|
|
243
|
+
await coordinator.dispose();
|
|
244
|
+
}, 'git-worktree: optional workingDirectory & deferred worktree bridge');
|
|
245
|
+
});
|
|
246
|
+
}
|
|
247
|
+
const deps = () => baseDeps();
|
|
135
248
|
// In dsh 0.1.7+, the settings service projects volatile Config fields into forms.
|
|
136
249
|
// We configure auto: false to inform the host that this plugin provides its own
|
|
137
250
|
// dedicated configuration card (via `plugins.bundle.config`).
|
|
@@ -231,5 +344,92 @@ export function apply(ctx, config = {}) {
|
|
|
231
344
|
postRoute(ROUTE_ENSURE_DIRECTORY, 'ensure-directory', handleEnsureDirectory);
|
|
232
345
|
postRoute(ROUTE_WORKTREES_ALL, 'worktrees-all', handleWorktreesAll);
|
|
233
346
|
postRoute(ROUTE_PURGE, 'purge', handlePurgeDirectory);
|
|
347
|
+
postRoute(ROUTE_SESSION_CWD, 'session-cwd', handleSetSessionDirectory);
|
|
348
|
+
webCtx.effect(() => webCtx.webServer.register({ kind: 'exact', path: ROUTE_DEFERRED, handler: async (req, res) => {
|
|
349
|
+
/* v8 ignore next -- node:http always sets url on server requests. */
|
|
350
|
+
const query = new URL(req.url ?? '/', 'http://x').searchParams;
|
|
351
|
+
send(res, await handleGetDeferredWorktree(deps(), query.get('sessionId') ?? undefined));
|
|
352
|
+
} }), 'git-worktree: deferred-get route');
|
|
353
|
+
const activeDeferredStreams = new Set();
|
|
354
|
+
webCtx.effect(() => () => {
|
|
355
|
+
for (const close of [...activeDeferredStreams])
|
|
356
|
+
close();
|
|
357
|
+
activeDeferredStreams.clear();
|
|
358
|
+
}, 'git-worktree: deferred-events stream teardown');
|
|
359
|
+
webCtx.effect(() => webCtx.webServer.register({ kind: 'exact', path: ROUTE_DEFERRED_EVENTS, handler: (req, res) => {
|
|
360
|
+
/* v8 ignore next -- node:http always sets url on server requests. */
|
|
361
|
+
const query = new URL(req.url ?? '/', 'http://x').searchParams;
|
|
362
|
+
const sessionId = query.get('sessionId')?.trim() ?? '';
|
|
363
|
+
if (sessionId === '') {
|
|
364
|
+
send(res, { status: 400, body: { error: 'query parameter "sessionId" must be non-empty' } });
|
|
365
|
+
return;
|
|
366
|
+
}
|
|
367
|
+
const coordinator = deferredWorktrees;
|
|
368
|
+
if (coordinator === undefined) {
|
|
369
|
+
send(res, { status: 501, body: { error: 'Deferred worktree creation is not supported by this host' } });
|
|
370
|
+
return;
|
|
371
|
+
}
|
|
372
|
+
res.writeHead(200, {
|
|
373
|
+
'content-type': 'text/event-stream; charset=utf-8',
|
|
374
|
+
'cache-control': 'no-store',
|
|
375
|
+
connection: 'keep-alive',
|
|
376
|
+
});
|
|
377
|
+
const writeFrame = (payload) => {
|
|
378
|
+
if (!res.writableEnded)
|
|
379
|
+
res.write(`data: ${JSON.stringify(payload)}\n\n`);
|
|
380
|
+
};
|
|
381
|
+
writeFrame({ state: coordinator.get(sessionId) });
|
|
382
|
+
const unsubscribe = coordinator.subscribe(sessionId, writeFrame);
|
|
383
|
+
const heartbeat = setInterval(() => {
|
|
384
|
+
if (!res.writableEnded)
|
|
385
|
+
res.write(': keepalive\n\n');
|
|
386
|
+
}, 25_000);
|
|
387
|
+
heartbeat.unref?.();
|
|
388
|
+
let closed = false;
|
|
389
|
+
const cleanup = () => {
|
|
390
|
+
if (closed)
|
|
391
|
+
return;
|
|
392
|
+
closed = true;
|
|
393
|
+
activeDeferredStreams.delete(cleanup);
|
|
394
|
+
clearInterval(heartbeat);
|
|
395
|
+
unsubscribe();
|
|
396
|
+
if (!res.writableEnded)
|
|
397
|
+
res.end();
|
|
398
|
+
};
|
|
399
|
+
activeDeferredStreams.add(cleanup);
|
|
400
|
+
req.on('close', cleanup);
|
|
401
|
+
res.on('close', cleanup);
|
|
402
|
+
} }), 'git-worktree: deferred-events route');
|
|
403
|
+
postRoute(ROUTE_DEFERRED_ARM, 'deferred-arm', handleArmDeferredWorktree);
|
|
404
|
+
postRoute(ROUTE_DEFERRED_ACTION, 'deferred-action', handleDeferredWorktreeAction);
|
|
405
|
+
const cancellablePostRoute = (path, label, handle) => {
|
|
406
|
+
webCtx.effect(() => webCtx.webServer.register({ kind: 'exact', path, handler: async (req, res) => {
|
|
407
|
+
let body;
|
|
408
|
+
try {
|
|
409
|
+
body = await readJson(req);
|
|
410
|
+
}
|
|
411
|
+
catch (error) {
|
|
412
|
+
send(res, { status: 400, body: { error: error instanceof Error ? error.message : String(error) } });
|
|
413
|
+
return;
|
|
414
|
+
}
|
|
415
|
+
const controller = new AbortController();
|
|
416
|
+
res.on('close', () => {
|
|
417
|
+
if (!res.writableEnded)
|
|
418
|
+
controller.abort();
|
|
419
|
+
});
|
|
420
|
+
try {
|
|
421
|
+
const outcome = await handle(deps(), body, controller.signal);
|
|
422
|
+
if (!res.writableEnded)
|
|
423
|
+
send(res, outcome);
|
|
424
|
+
}
|
|
425
|
+
catch (error) {
|
|
426
|
+
if (!res.writableEnded)
|
|
427
|
+
send(res, { status: 500, body: { error: error instanceof Error ? error.message : String(error) } });
|
|
428
|
+
}
|
|
429
|
+
} }), `git-worktree: ${label} route`);
|
|
430
|
+
};
|
|
431
|
+
cancellablePostRoute(ROUTE_PR_CONTEXT, 'pr-context', handlePrContext);
|
|
432
|
+
cancellablePostRoute(ROUTE_PR_RESOLVE, 'pr-resolve', handlePrResolve);
|
|
433
|
+
streamPostRoute(ROUTE_PR_CHECKOUT, 'pr-checkout', handlePrCheckout);
|
|
234
434
|
});
|
|
235
435
|
}
|
package/lib/normalize.d.ts
CHANGED
|
@@ -56,3 +56,16 @@ export type BranchNameIssue = 'empty' | 'leadingDash' | 'illegal';
|
|
|
56
56
|
* @returns the issue kind, or null when the name is acceptable.
|
|
57
57
|
*/
|
|
58
58
|
export declare function branchNameIssue(name: string): BranchNameIssue | null;
|
|
59
|
+
/**
|
|
60
|
+
* Default random 4-hex suffix generator (works in both Node and browser).
|
|
61
|
+
* Uses `crypto.getRandomValues` when available and falls back to `Math.random`.
|
|
62
|
+
*/
|
|
63
|
+
export declare function defaultRandomHex4(): string;
|
|
64
|
+
/**
|
|
65
|
+
* Generate a human-readable random branch name based on `base` (`<stem>-<4hex>`),
|
|
66
|
+
* avoiding collisions with `isTaken`. Pure and shared between Host and Client.
|
|
67
|
+
* @param base - local base branch name (without remote prefix) or `HEAD`.
|
|
68
|
+
* @param isTaken - optional predicate returning true when a candidate already exists.
|
|
69
|
+
* @param randomHex - injectable 4-hex generator for deterministic testing.
|
|
70
|
+
*/
|
|
71
|
+
export declare function generateRandomBranchName(base: string, isTaken?: (candidate: string) => boolean, randomHex?: () => string): string;
|
package/lib/normalize.js
CHANGED
|
@@ -91,3 +91,54 @@ export function branchNameIssue(name) {
|
|
|
91
91
|
return 'illegal';
|
|
92
92
|
return null;
|
|
93
93
|
}
|
|
94
|
+
/**
|
|
95
|
+
* Default random 4-hex suffix generator (works in both Node and browser).
|
|
96
|
+
* Uses `crypto.getRandomValues` when available and falls back to `Math.random`.
|
|
97
|
+
*/
|
|
98
|
+
export function defaultRandomHex4() {
|
|
99
|
+
const cryptoObj = globalThis.crypto;
|
|
100
|
+
if (cryptoObj !== undefined && typeof cryptoObj.getRandomValues === 'function') {
|
|
101
|
+
const bytes = new Uint8Array(2);
|
|
102
|
+
cryptoObj.getRandomValues(bytes);
|
|
103
|
+
return Array.from(bytes, byte => byte.toString(16).padStart(2, '0')).join('');
|
|
104
|
+
}
|
|
105
|
+
return Math.floor(Math.random() * 0x10000).toString(16).padStart(4, '0');
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* Normalize a base branch stem so appending `-<4hex>` always produces a valid
|
|
109
|
+
* git branch name (handles detached `HEAD`, trailing slashes/dots, or empty input).
|
|
110
|
+
*/
|
|
111
|
+
function randomBranchStem(base) {
|
|
112
|
+
const trimmed = base.trim();
|
|
113
|
+
if (trimmed === '' || trimmed === 'HEAD')
|
|
114
|
+
return 'wt';
|
|
115
|
+
const cleaned = trimmed
|
|
116
|
+
.replace(/^[-/]+/, '')
|
|
117
|
+
.replace(/[./]+$/, '')
|
|
118
|
+
.replace(/\/+/g, '/');
|
|
119
|
+
if (cleaned === '' || branchNameIssue(`${cleaned}-0000`) !== null)
|
|
120
|
+
return 'wt';
|
|
121
|
+
return cleaned;
|
|
122
|
+
}
|
|
123
|
+
/**
|
|
124
|
+
* Generate a human-readable random branch name based on `base` (`<stem>-<4hex>`),
|
|
125
|
+
* avoiding collisions with `isTaken`. Pure and shared between Host and Client.
|
|
126
|
+
* @param base - local base branch name (without remote prefix) or `HEAD`.
|
|
127
|
+
* @param isTaken - optional predicate returning true when a candidate already exists.
|
|
128
|
+
* @param randomHex - injectable 4-hex generator for deterministic testing.
|
|
129
|
+
*/
|
|
130
|
+
export function generateRandomBranchName(base, isTaken, randomHex = defaultRandomHex4) {
|
|
131
|
+
const stem = randomBranchStem(base);
|
|
132
|
+
for (let attempt = 0; attempt < 32; attempt += 1) {
|
|
133
|
+
const suffix = randomHex().toLowerCase().replace(/[^0-9a-f]/g, '').slice(0, 4).padStart(4, '0');
|
|
134
|
+
const candidate = `${stem}-${suffix}`;
|
|
135
|
+
if (!(isTaken?.(candidate) ?? false))
|
|
136
|
+
return candidate;
|
|
137
|
+
}
|
|
138
|
+
for (let i = 1;; i += 1) {
|
|
139
|
+
const suffix = randomHex().toLowerCase().replace(/[^0-9a-f]/g, '').slice(0, 4).padStart(4, '0');
|
|
140
|
+
const candidate = `${stem}-${suffix}-${i}`;
|
|
141
|
+
if (!(isTaken?.(candidate) ?? false))
|
|
142
|
+
return candidate;
|
|
143
|
+
}
|
|
144
|
+
}
|
package/lib/pr.d.ts
ADDED
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* PR/MR resolution, remote classification, and optional `ctx.forge` integration
|
|
3
|
+
* for isolating pull/merge requests into dedicated Git worktrees.
|
|
4
|
+
*/
|
|
5
|
+
import type { PrContextResult, PrErrorCode, PrProviderKind, PrRemoteInfo, PrResolveResult, WorktreeEntry } from './wire.js';
|
|
6
|
+
/** Minimal repository identity returned by `ctx.forge`. */
|
|
7
|
+
export interface ForgeRepositoryLike {
|
|
8
|
+
readonly forge: string;
|
|
9
|
+
readonly host: string;
|
|
10
|
+
readonly owner: string;
|
|
11
|
+
readonly name: string;
|
|
12
|
+
}
|
|
13
|
+
/** Minimal change request reference returned by `ctx.forge`. */
|
|
14
|
+
export interface ChangeRequestRefLike {
|
|
15
|
+
readonly repository: ForgeRepositoryLike;
|
|
16
|
+
readonly number: number;
|
|
17
|
+
}
|
|
18
|
+
/** Minimal change request snapshot shape from `ctx.forge.latest`. */
|
|
19
|
+
export interface ChangeRequestSnapshotLike {
|
|
20
|
+
readonly url: string;
|
|
21
|
+
readonly title: string;
|
|
22
|
+
readonly state: 'open' | 'closed' | 'merged';
|
|
23
|
+
readonly draft: boolean;
|
|
24
|
+
readonly author: string | null;
|
|
25
|
+
readonly headBranch: string;
|
|
26
|
+
readonly baseBranch: string;
|
|
27
|
+
}
|
|
28
|
+
/** Minimal viewer list entry returned by `ctx.forge.listForViewer`. */
|
|
29
|
+
export interface ForgeViewerSummaryLike {
|
|
30
|
+
readonly ref: ChangeRequestRefLike;
|
|
31
|
+
readonly url: string;
|
|
32
|
+
readonly title: string;
|
|
33
|
+
readonly draft: boolean;
|
|
34
|
+
readonly author: {
|
|
35
|
+
readonly login: string;
|
|
36
|
+
} | null;
|
|
37
|
+
readonly checksRollup: 'none' | 'pending' | 'success' | 'failure';
|
|
38
|
+
readonly reviewDecision: 'approved' | 'changes-requested' | 'review-required' | 'none';
|
|
39
|
+
readonly updatedAt: string;
|
|
40
|
+
}
|
|
41
|
+
export interface ForgeViewerListLike {
|
|
42
|
+
readonly viewer: string;
|
|
43
|
+
readonly items: readonly ForgeViewerSummaryLike[];
|
|
44
|
+
readonly total: number;
|
|
45
|
+
}
|
|
46
|
+
export interface ForgeReadinessLike {
|
|
47
|
+
readonly state: 'ready' | 'unauthenticated' | 'unavailable';
|
|
48
|
+
readonly message: string | null;
|
|
49
|
+
readonly signIn?: {
|
|
50
|
+
readonly command: string;
|
|
51
|
+
} | null;
|
|
52
|
+
}
|
|
53
|
+
/** Minimal duck-typed contract matching `@deepseek-ai/dsh-experimental-forge` `ForgeService`. */
|
|
54
|
+
export interface ForgeServiceLike {
|
|
55
|
+
repositoryFromRemote(url: string): ForgeRepositoryLike | undefined;
|
|
56
|
+
changeRequestFromUrl(url: string): ChangeRequestRefLike | undefined;
|
|
57
|
+
changeRequestUrl(ref: ChangeRequestRefLike): string;
|
|
58
|
+
readiness(repository: ForgeRepositoryLike, signal: AbortSignal): Promise<ForgeReadinessLike>;
|
|
59
|
+
viewerSources?(): readonly {
|
|
60
|
+
readonly forge: string;
|
|
61
|
+
readonly hosts: readonly string[];
|
|
62
|
+
readonly filters: ReadonlySet<string>;
|
|
63
|
+
readonly maxItems: number;
|
|
64
|
+
}[];
|
|
65
|
+
listForViewer?(forge: string, query: {
|
|
66
|
+
readonly host: string;
|
|
67
|
+
readonly filter: 'review-requested' | 'authored' | 'involved';
|
|
68
|
+
readonly repository: {
|
|
69
|
+
readonly owner: string;
|
|
70
|
+
readonly name: string;
|
|
71
|
+
} | null;
|
|
72
|
+
readonly limit: number;
|
|
73
|
+
}, signal: AbortSignal): Promise<ForgeViewerListLike | {
|
|
74
|
+
readonly code: string;
|
|
75
|
+
readonly message: string;
|
|
76
|
+
}>;
|
|
77
|
+
latest?(ref: ChangeRequestRefLike): {
|
|
78
|
+
readonly snapshot?: ChangeRequestSnapshotLike;
|
|
79
|
+
} | undefined;
|
|
80
|
+
fetchChecks?(ref: ChangeRequestRefLike, signal: AbortSignal): Promise<ChangeRequestSnapshotLike | {
|
|
81
|
+
readonly code: string;
|
|
82
|
+
readonly message: string;
|
|
83
|
+
}>;
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* Opportunistically fetch PR/MR metadata (title, author, state, draft, branches) from optional
|
|
87
|
+
* `ctx.forge` when not already cached in `forge.latest`. Failures and timeouts degrade silently
|
|
88
|
+
* to `undefined` so native Git checkout previews are never blocked.
|
|
89
|
+
*/
|
|
90
|
+
export declare function fetchPrMeta(forge: ForgeServiceLike | undefined, remote: PrRemoteInfo | undefined, provider: PrProviderKind, number: number, signal?: AbortSignal): Promise<PrResolveResult['meta'] | undefined>;
|
|
91
|
+
/** Runtime guard for optional `ctx.forge` service injection. */
|
|
92
|
+
export declare function isForgeServiceLike(value: unknown): value is ForgeServiceLike;
|
|
93
|
+
/** Parsed PR/MR user input (numeric ID or full web URL). */
|
|
94
|
+
export type ParsedPrInput = {
|
|
95
|
+
readonly kind: 'number';
|
|
96
|
+
readonly number: number;
|
|
97
|
+
readonly hintProvider?: PrProviderKind;
|
|
98
|
+
} | {
|
|
99
|
+
readonly kind: 'url';
|
|
100
|
+
readonly provider: PrProviderKind;
|
|
101
|
+
readonly host: string;
|
|
102
|
+
readonly owner: string;
|
|
103
|
+
readonly repo: string;
|
|
104
|
+
readonly number: number;
|
|
105
|
+
readonly canonicalUrl: string;
|
|
106
|
+
};
|
|
107
|
+
/**
|
|
108
|
+
* Parse a Git remote fetch URL (`https://`, `http://`, `ssh://`, `git://`, or `git@host:owner/repo.git`)
|
|
109
|
+
* into normalized host, owner/namespace, repository name, and heuristic provider kind.
|
|
110
|
+
*/
|
|
111
|
+
export declare function parseRemoteUrl(url: string): {
|
|
112
|
+
host: string;
|
|
113
|
+
owner: string;
|
|
114
|
+
repo: string;
|
|
115
|
+
provider: PrProviderKind | null;
|
|
116
|
+
} | undefined;
|
|
117
|
+
/**
|
|
118
|
+
* Parse user input into a numeric PR/MR number (`42`, `#42`, `!42`) or a GitHub/GitLab web URL.
|
|
119
|
+
* Supports self-hosted instances, nested GitLab namespaces, and trailing URL paths (`/files`, `/commits`, query, hash).
|
|
120
|
+
*/
|
|
121
|
+
export declare function parsePrInput(input: string): ParsedPrInput | undefined;
|
|
122
|
+
/** Canonical local branch name with provider prefix to avoid multi-host collisions. */
|
|
123
|
+
export declare function formatPrBranchName(provider: PrProviderKind, number: number): string;
|
|
124
|
+
/**
|
|
125
|
+
* Concise PR/MR origin label stored in `<worktreeGitDir>/dsh-worktree-base` for
|
|
126
|
+
* sidebar hover cards (e.g. `PR #42`, `PR #42 → main`, `MR !17 → develop`).
|
|
127
|
+
*/
|
|
128
|
+
export declare function formatPrBaseLabel(provider: PrProviderKind, number: number, baseBranch?: string): string;
|
|
129
|
+
/** Git refspec fetched into a temporary ref (`refs/dsh-pr-tmp/<uuid>`) for a given provider and PR/MR number. */
|
|
130
|
+
export declare function prRefSpec(provider: PrProviderKind, number: number): string;
|
|
131
|
+
/** Build the canonical web URL for a PR/MR on a known remote, using `forge` when available. */
|
|
132
|
+
export declare function buildCanonicalPrUrl(remote: PrRemoteInfo, provider: PrProviderKind, number: number, forge?: ForgeServiceLike): string | null;
|
|
133
|
+
/** Classify repository remotes using optional `ctx.forge` first, falling back to built-in URL parsing. */
|
|
134
|
+
export declare function classifyRemotes(remotes: readonly {
|
|
135
|
+
name: string;
|
|
136
|
+
url: string;
|
|
137
|
+
}[], forge?: ForgeServiceLike): PrRemoteInfo[];
|
|
138
|
+
/** Choose default remote: recognized `upstream` > `origin` > first recognized remote > first remote. */
|
|
139
|
+
export declare function pickDefaultRemote(remotes: readonly PrRemoteInfo[]): string | null;
|
|
140
|
+
/** Error thrown when PR input is invalid or does not belong to the repository. */
|
|
141
|
+
export declare class PrResolutionError extends Error {
|
|
142
|
+
readonly code: PrErrorCode;
|
|
143
|
+
readonly params: Record<string, string | number> | undefined;
|
|
144
|
+
constructor(message: string, code: PrErrorCode, params?: Record<string, string | number>);
|
|
145
|
+
}
|
|
146
|
+
export interface ResolvePrTargetInput {
|
|
147
|
+
repoRoot: string;
|
|
148
|
+
input: string;
|
|
149
|
+
remotes: readonly PrRemoteInfo[];
|
|
150
|
+
worktrees: readonly WorktreeEntry[];
|
|
151
|
+
localBranches: readonly string[];
|
|
152
|
+
requestedRemote?: string;
|
|
153
|
+
requestedProvider?: PrProviderKind;
|
|
154
|
+
forge?: ForgeServiceLike;
|
|
155
|
+
}
|
|
156
|
+
/**
|
|
157
|
+
* Resolve a PR/MR ID or URL against the repository's remotes, verifying repository ownership
|
|
158
|
+
* and reporting any existing isolated worktree or local branch collision.
|
|
159
|
+
*/
|
|
160
|
+
export declare function resolvePrTarget(args: ResolvePrTargetInput): PrResolveResult;
|
|
161
|
+
/**
|
|
162
|
+
* Assemble `/pr-context` payload: classified remotes + optional `ctx.forge` readiness &
|
|
163
|
+
* open PR/MR candidate lists scoped to the repository (or an explicitly selected remote).
|
|
164
|
+
* Failures or unauthenticated states degrade cleanly to `candidates: []` without blocking native Git checkout.
|
|
165
|
+
*/
|
|
166
|
+
export declare function loadPrContext(args: {
|
|
167
|
+
repoRoot: string;
|
|
168
|
+
repoName: string;
|
|
169
|
+
rawRemotes: readonly {
|
|
170
|
+
name: string;
|
|
171
|
+
url: string;
|
|
172
|
+
}[];
|
|
173
|
+
worktrees: readonly WorktreeEntry[];
|
|
174
|
+
requestedRemote?: string;
|
|
175
|
+
forge?: ForgeServiceLike;
|
|
176
|
+
signal?: AbortSignal;
|
|
177
|
+
}): Promise<PrContextResult>;
|