@moberg_hr/work-tree 2.0.5 → 2.0.7
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/dist/bin.js +1 -1
- package/dist/{chunk-46UD4QBL.js → chunk-5RRKVAIZ.js} +3 -2
- package/dist/chunk-5RRKVAIZ.js.map +1 -0
- package/dist/{chunk-UBC5DNLT.js → chunk-6HDVRMCX.js} +3 -3
- package/dist/{chunk-BSCAA322.js → chunk-7Z2USU3A.js} +22 -8
- package/dist/chunk-7Z2USU3A.js.map +1 -0
- package/dist/chunk-C4LRHXEB.js +9 -0
- package/dist/{chunk-FOG4WG3Y.js → chunk-CNFPZVNO.js} +2 -2
- package/dist/{chunk-ESPZRTUB.js → chunk-DH2PLKCW.js} +2 -2
- package/dist/{chunk-XHOQ7BWT.js → chunk-HB2I7GF7.js} +2 -2
- package/dist/{chunk-K7BSZRRF.js → chunk-IOO2OAUC.js} +4 -4
- package/dist/{chunk-G2O7EIKX.js → chunk-J2ZJ2DIJ.js} +2 -2
- package/dist/{chunk-XBNLSKTX.js → chunk-K3ESY6OJ.js} +3 -3
- package/dist/{chunk-HIXC67MU.js → chunk-LDCY457K.js} +2 -2
- package/dist/{chunk-CP6EFKEO.js → chunk-M2QL43DS.js} +2 -2
- package/dist/{chunk-XE2X7KH6.js → chunk-N23HFT4X.js} +73 -34
- package/dist/chunk-N23HFT4X.js.map +1 -0
- package/dist/{chunk-2VH5SJHF.js → chunk-QDNCUUNQ.js} +4 -4
- package/dist/chunk-QWIGFAKZ.js +334 -0
- package/dist/chunk-QWIGFAKZ.js.map +1 -0
- package/dist/{chunk-LRNAHZAK.js → chunk-VICXQQ5X.js} +4 -4
- package/dist/{chunk-YF66LR6K.js → chunk-YXTJVPOI.js} +16 -16
- package/dist/{cleanup-MCWFGGS6.js → cleanup-YVQOAMSK.js} +7 -7
- package/dist/{cli-LS45WVSJ.js → cli-VSCHBZRS.js} +3 -3
- package/dist/{config-TPYNBTVM.js → config-4W5MMHLU.js} +5 -5
- package/dist/{fork-ET4OKRNC.js → fork-ZBEMNEPA.js} +5 -5
- package/dist/{init-NGL64E3F.js → init-J2AB37DO.js} +5 -5
- package/dist/{move-I7SYL4FY.js → move-O7NEJZQV.js} +9 -13
- package/dist/move-O7NEJZQV.js.map +1 -0
- package/dist/{overlaps-3LZXSDYZ.js → overlaps-SKKGH6EG.js} +4 -4
- package/dist/{pr-JM4DRRIV.js → pr-AC44DGJY.js} +2 -2
- package/dist/{prune-5NUZUVYL.js → prune-NQOVBIFT.js} +6 -6
- package/dist/{remove-EFQQQRCW.js → remove-JESX7RCN.js} +5 -5
- package/dist/{sessions-CAOAXKKG.js → sessions-T6UXM2OX.js} +4 -4
- package/dist/{sync-LSUID373.js → sync-E4CU4IHG.js} +6 -6
- package/dist/{tree-CMDHHEUW.js → tree-RAN6SQKW.js} +32 -2
- package/dist/tree-RAN6SQKW.js.map +1 -0
- package/dist/{update-K73WHYY3.js → update-5DM5V2E3.js} +3 -3
- package/dist/wd-bin.js +2 -2
- package/dist/web/assets/{PtyView-Bst9Dw6x.js → PtyView-Ci395OL2.js} +2 -2
- package/dist/web/assets/{PtyView-Bst9Dw6x.js.map → PtyView-Ci395OL2.js.map} +1 -1
- package/dist/web/assets/index-D-_oxT3O.css +1 -0
- package/dist/web/assets/index-DjdfILvB.js +118 -0
- package/dist/web/assets/index-DjdfILvB.js.map +1 -0
- package/dist/web/index.html +2 -2
- package/dist/{web-PY55DXYZ.js → web-EUI5U2H4.js} +166 -317
- package/dist/web-EUI5U2H4.js.map +1 -0
- package/npm-shrinkwrap.json +2 -2
- package/package.json +1 -1
- package/dist/chunk-46UD4QBL.js.map +0 -1
- package/dist/chunk-BSCAA322.js.map +0 -1
- package/dist/chunk-GHO7HYP6.js +0 -9
- package/dist/chunk-XE2X7KH6.js.map +0 -1
- package/dist/move-I7SYL4FY.js.map +0 -1
- package/dist/tree-CMDHHEUW.js.map +0 -1
- package/dist/web/assets/index-CV8NpZB8.css +0 -1
- package/dist/web/assets/index-CcSEllUR.js +0 -117
- package/dist/web/assets/index-CcSEllUR.js.map +0 -1
- package/dist/web-PY55DXYZ.js.map +0 -1
- /package/dist/{chunk-UBC5DNLT.js.map → chunk-6HDVRMCX.js.map} +0 -0
- /package/dist/{chunk-GHO7HYP6.js.map → chunk-C4LRHXEB.js.map} +0 -0
- /package/dist/{chunk-FOG4WG3Y.js.map → chunk-CNFPZVNO.js.map} +0 -0
- /package/dist/{chunk-ESPZRTUB.js.map → chunk-DH2PLKCW.js.map} +0 -0
- /package/dist/{chunk-XHOQ7BWT.js.map → chunk-HB2I7GF7.js.map} +0 -0
- /package/dist/{chunk-K7BSZRRF.js.map → chunk-IOO2OAUC.js.map} +0 -0
- /package/dist/{chunk-G2O7EIKX.js.map → chunk-J2ZJ2DIJ.js.map} +0 -0
- /package/dist/{chunk-XBNLSKTX.js.map → chunk-K3ESY6OJ.js.map} +0 -0
- /package/dist/{chunk-HIXC67MU.js.map → chunk-LDCY457K.js.map} +0 -0
- /package/dist/{chunk-CP6EFKEO.js.map → chunk-M2QL43DS.js.map} +0 -0
- /package/dist/{chunk-2VH5SJHF.js.map → chunk-QDNCUUNQ.js.map} +0 -0
- /package/dist/{chunk-LRNAHZAK.js.map → chunk-VICXQQ5X.js.map} +0 -0
- /package/dist/{chunk-YF66LR6K.js.map → chunk-YXTJVPOI.js.map} +0 -0
- /package/dist/{cleanup-MCWFGGS6.js.map → cleanup-YVQOAMSK.js.map} +0 -0
- /package/dist/{cli-LS45WVSJ.js.map → cli-VSCHBZRS.js.map} +0 -0
- /package/dist/{config-TPYNBTVM.js.map → config-4W5MMHLU.js.map} +0 -0
- /package/dist/{fork-ET4OKRNC.js.map → fork-ZBEMNEPA.js.map} +0 -0
- /package/dist/{init-NGL64E3F.js.map → init-J2AB37DO.js.map} +0 -0
- /package/dist/{overlaps-3LZXSDYZ.js.map → overlaps-SKKGH6EG.js.map} +0 -0
- /package/dist/{pr-JM4DRRIV.js.map → pr-AC44DGJY.js.map} +0 -0
- /package/dist/{prune-5NUZUVYL.js.map → prune-NQOVBIFT.js.map} +0 -0
- /package/dist/{remove-EFQQQRCW.js.map → remove-JESX7RCN.js.map} +0 -0
- /package/dist/{sessions-CAOAXKKG.js.map → sessions-T6UXM2OX.js.map} +0 -0
- /package/dist/{sync-LSUID373.js.map → sync-E4CU4IHG.js.map} +0 -0
- /package/dist/{update-K73WHYY3.js.map → update-5DM5V2E3.js.map} +0 -0
package/npm-shrinkwrap.json
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@moberg_hr/work-tree",
|
|
3
|
-
"version": "2.0.
|
|
3
|
+
"version": "2.0.7",
|
|
4
4
|
"lockfileVersion": 3,
|
|
5
5
|
"requires": true,
|
|
6
6
|
"packages": {
|
|
7
7
|
"": {
|
|
8
8
|
"name": "@moberg_hr/work-tree",
|
|
9
|
-
"version": "2.0.
|
|
9
|
+
"version": "2.0.7",
|
|
10
10
|
"hasInstallScript": true,
|
|
11
11
|
"license": "MIT",
|
|
12
12
|
"dependencies": {
|
package/package.json
CHANGED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/core/pr/ship.ts"],"sourcesContent":["import path from 'node:path';\nimport crossSpawn from '../platform/spawn.js';\nimport type { WorktreeSession } from '../sessions/history.js';\nimport type {\n ChecksState,\n FailingCheck,\n MergeMethod,\n MergeSelection,\n RepoShipState,\n ShipPr,\n ShipPreflight,\n ShipResult,\n} from '../api-types.js';\n\nexport type {\n ChecksState,\n MergeMethod,\n MergeSelection,\n RepoShipState,\n ShipAction,\n ShipPr,\n ShipPreflight,\n ShipResult,\n} from '../api-types.js';\n\n/**\n * Ship a session's work: push, open a PR, merge it — per repo, because a\n * group's repos ship independently: backend can be merged and done while\n * frontend still waits for review.\n *\n * Group rules (the careful part):\n * - A repo whose PR is MERGED, or that was never touched (no commits vs\n * the base, clean, no PR), is `done` — never a blocker for the others.\n * - Merge takes an explicit list of repos, each with the PR head SHA the\n * user was shown. The server re-checks every one of them and merges\n * NONE if any is blocked or its PR moved; repos not listed are left\n * alone. So a group can be shipped in parts, deliberately.\n * - The session is archived only when a merge actually merged something\n * AND every repo is done afterwards.\n *\n * Every git/gh call goes through a `CommandRunner` with an argv array — no\n * shell (§1.1) — injectable so the decision logic is unit-testable.\n */\n\nexport interface RunResult {\n code: number;\n stdout: string;\n stderr: string;\n}\nexport type CommandRunner = (cmd: string, args: string[], cwd: string) => Promise<RunResult>;\n\n/**\n * Real runner: cross-spawn, not execFile — on Windows execFile only finds\n * .exe files, so a `gh` installed as a .cmd shim (scoop, wrappers) would\n * look \"not installed\"; cross-spawn resolves shims like `work tree` does,\n * with cmd-escaped args. Exit code 127 = the binary itself is missing.\n */\nexport const defaultRunner: CommandRunner = (cmd, args, cwd) =>\n new Promise((resolve) => {\n let stdout = '';\n let stderr = '';\n let settled = false;\n const done = (r: RunResult) => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n resolve(r);\n };\n const child = crossSpawn(cmd, args, { cwd, windowsHide: true });\n const timer = setTimeout(() => {\n child.kill();\n done({ code: 124, stdout, stderr: stderr || `${cmd} timed out` });\n }, 60_000);\n child.stdout?.on('data', (d: Buffer) => {\n stdout += d.toString();\n });\n child.stderr?.on('data', (d: Buffer) => {\n stderr += d.toString();\n });\n child.on('error', (err: NodeJS.ErrnoException) => {\n done({ code: err.code === 'ENOENT' ? 127 : 1, stdout, stderr: err.message });\n });\n child.on('close', (code) => done({ code: code ?? 1, stdout, stderr }));\n });\n\n/** The repos a session ships: each worktree path, named by its folder. */\nexport function shipRepos(session: WorktreeSession): Array<{ name: string; path: string }> {\n return session.paths.map((p) => ({\n name: session.isGroup ? path.basename(p) : session.target,\n path: p,\n }));\n}\n\ninterface CheckRollupItem {\n status?: string | null;\n conclusion?: string | null;\n state?: string | null;\n /** Check runs carry name + detailsUrl; commit statuses context + targetUrl. */\n name?: string | null;\n context?: string | null;\n detailsUrl?: string | null;\n targetUrl?: string | null;\n}\n\nconst FAILED = ['FAILURE', 'ERROR', 'CANCELLED', 'TIMED_OUT', 'ACTION_REQUIRED', 'STARTUP_FAILURE'];\n\n/** The failed checks in a rollup, named, with their links. */\nexport function failingFromRollup(rollup: CheckRollupItem[] | null | undefined): FailingCheck[] {\n return (rollup ?? [])\n .filter((c) => FAILED.includes((c.conclusion ?? c.state ?? '').toUpperCase()))\n .map((c) => {\n const url = c.detailsUrl ?? c.targetUrl ?? undefined;\n return { name: c.name ?? c.context ?? 'check', ...(url ? { url } : {}) };\n });\n}\n\n/** Collapse gh's statusCheckRollup (check runs + commit statuses). */\nexport function checksFromRollup(rollup: CheckRollupItem[] | null | undefined): ChecksState {\n if (!rollup || rollup.length === 0) return 'none';\n let pending = false;\n for (const c of rollup) {\n const v = (c.conclusion ?? c.state ?? '').toUpperCase();\n if (FAILED.includes(v)) {\n return 'fail';\n }\n const status = (c.status ?? '').toUpperCase();\n if (!v || v === 'PENDING' || v === 'EXPECTED' || (status && status !== 'COMPLETED')) pending = true;\n }\n return pending ? 'pending' : 'pass';\n}\n\ntype RepoFacts = Omit<RepoShipState, 'mergeBlockers' | 'done' | 'doneReason'>;\n\n/** Done = nothing left to ship from this repo. */\nexport function repoDone(r: RepoFacts): { done: boolean; reason?: 'merged' | 'untouched' } {\n // Merged AND nothing since: a follow-up commit (pushed or not) or an\n // edit after the merge is new work — it must stay visible, get pushed,\n // and block archiving until it's shipped too.\n // A tree git couldn't read may hold anything: never done on a guess.\n if (r.gitError) return { done: false };\n if (r.pr?.state === 'MERGED') {\n const nothingSince = r.dirtyFiles === 0 && !r.ahead && (!r.localSha || r.localSha === r.pr.headSha);\n return nothingSince ? { done: true, reason: 'merged' } : { done: false };\n }\n // Untouched only when every fact was read: a gh that failed (no network right after a\n // wake) is not \"no PR\", and a git that failed is not \"0 commits\" — reading them so once\n // archived a group whose other PR was still open.\n if (!r.pr && !r.ghError && r.dirtyFiles === 0 && r.commitsVsBase === 0) return { done: true, reason: 'untouched' };\n return { done: false };\n}\n\n/** Why \"merge\" isn't available for this repo right now ([] = go). */\nexport function mergeBlockers(r: RepoFacts): string[] {\n if (repoDone(r).done) return [];\n const out: string[] = [];\n if (r.gitError) out.push(r.gitError);\n if (r.ghError) out.push(r.ghError);\n if (r.dirtyFiles > 0) out.push(`${r.dirtyFiles} uncommitted file${r.dirtyFiles === 1 ? '' : 's'} — commit or stash first`);\n if (!r.hasUpstream) out.push('branch not pushed yet');\n if (r.ahead && r.ahead > 0) out.push(`${r.ahead} unpushed commit${r.ahead === 1 ? '' : 's'}`);\n if (r.behind && r.behind > 0) out.push(`origin has ${r.behind} commit${r.behind === 1 ? '' : 's'} you don't have locally — pull first`);\n if (!r.pr) {\n if (!r.ghError) out.push('no pull request');\n return out;\n }\n if (r.pr.state === 'CLOSED') out.push('pull request is closed');\n if (r.pr.state === 'MERGED') {\n // Not done (repoDone), so there's work after the merge.\n out.push(`PR #${r.pr.number} is already merged — the new work needs a new PR`);\n return out;\n }\n if (r.pr.isDraft) out.push('pull request is a draft');\n // The PR must be exactly what you have locally: otherwise merging lands\n // commits you haven't seen (or leaves out ones you have).\n if (r.localSha && r.pr.headSha && r.pr.headSha !== r.localSha && !(r.ahead || r.behind)) {\n out.push(\"the PR's head isn't your local HEAD — push or pull first\");\n }\n switch (r.pr.mergeStateStatus) {\n case 'DIRTY':\n out.push('merge conflicts with the base branch');\n break;\n case 'BEHIND':\n out.push('branch is behind the base branch');\n break;\n case 'BLOCKED':\n out.push('blocked by branch protection (reviews or required checks)');\n break;\n default:\n break;\n }\n if (r.pr.checks === 'fail') out.push('checks failing');\n else if (r.pr.checks === 'pending') out.push('checks still running');\n return out;\n}\n\nfunction oneLineErr(s: string): string {\n return (\n s\n .split(/\\r?\\n/)\n .map((l) => l.trim())\n .find(Boolean) ?? ''\n );\n}\n\n/** Whether to ask GitHub about a repo's PR at all (the PR watch skips\n * branches that were never pushed and have no PR it knows of). */\nexport type AskGh = (repo: { name: string; hasUpstream: boolean; commitsVsBase: number | null }) => boolean;\n\nasync function inspectRepo(repo: { name: string; path: string }, run: CommandRunner, askGh?: AskGh): Promise<RepoShipState> {\n const git = (...args: string[]) => run('git', args, repo.path);\n const branch = (await git('rev-parse', '--abbrev-ref', 'HEAD')).stdout.trim();\n const localSha = (await git('rev-parse', 'HEAD')).stdout.trim();\n const status = await git('status', '--porcelain');\n const dirtyFiles = status.stdout.split('\\n').filter((l) => l.trim()).length;\n const gitError =\n status.code === 0 ? undefined : `git couldn't read the working tree (${oneLineErr(status.stderr) || `exit ${status.code}`})`;\n\n // \"Published\" = origin/<branch> exists — NOT whatever @{u} points at.\n // `work tree` forks branches tracking origin/main, so @{u} is often the\n // base: measuring against it hides unpushed commits, and a plain push\n // fails (\"upstream branch ... does not match the name of your current\n // branch\").\n const remoteRef = `refs/remotes/origin/${branch}`;\n const hasUpstream = (await git('rev-parse', '--verify', '--quiet', remoteRef)).code === 0;\n const upstream = await git('rev-parse', '--abbrev-ref', '--symbolic-full-name', '@{u}');\n const tracksRemote = upstream.code === 0 && upstream.stdout.trim() === `origin/${branch}`;\n let ahead: number | null = null;\n let behind: number | null = null;\n if (hasUpstream) {\n const counts = await git('rev-list', '--left-right', '--count', `${remoteRef}...HEAD`);\n const [b, a] = counts.stdout.trim().split(/\\s+/).map(Number);\n if (Number.isFinite(a) && Number.isFinite(b)) {\n ahead = a;\n behind = b;\n }\n }\n\n let commitsVsBase: number | null = null;\n const baseRef = (await git('rev-parse', '--abbrev-ref', 'origin/HEAD')).stdout.trim();\n // A git that failed (a timeout under load) tells nothing: no count, so never \"untouched\".\n if (status.code === 0 && baseRef && baseRef !== 'origin/HEAD') {\n // Only a count git gave: `Number('')` is 0, which read a failed git as \"no commits\".\n const count = await git('rev-list', '--count', `${baseRef}..HEAD`);\n if (count.code === 0 && /^\\d+$/.test(count.stdout.trim())) commitsVsBase = Number(count.stdout.trim());\n }\n\n let pr: ShipPr | null = null;\n let ghError: string | undefined;\n const skipGh = askGh ? !askGh({ name: repo.name, hasUpstream, commitsVsBase }) : false;\n const view = skipGh\n ? { code: 1, stdout: '', stderr: 'no pull requests found (not asked: never pushed)' }\n : await run(\n 'gh',\n [\n 'pr',\n 'view',\n branch,\n '--json',\n 'number,url,state,isDraft,mergeStateStatus,headRefOid,mergedAt,updatedAt,statusCheckRollup,reviewDecision',\n ],\n repo.path,\n );\n if (view.code === 0) {\n try {\n const j = JSON.parse(view.stdout) as {\n number: number;\n url: string;\n state: ShipPr['state'];\n isDraft: boolean;\n mergeStateStatus?: string;\n headRefOid: string;\n mergedAt?: string | null;\n updatedAt?: string;\n statusCheckRollup?: CheckRollupItem[];\n reviewDecision?: string | null;\n };\n pr = {\n number: j.number,\n url: j.url,\n state: j.state,\n isDraft: j.isDraft,\n mergeStateStatus: j.mergeStateStatus ?? 'UNKNOWN',\n checks: checksFromRollup(j.statusCheckRollup),\n headSha: j.headRefOid,\n ...(j.mergedAt ? { mergedAt: j.mergedAt } : {}),\n ...(j.updatedAt ? { updatedAt: j.updatedAt } : {}),\n ...(typeof j.reviewDecision === 'string' ? { reviewDecision: j.reviewDecision } : {}),\n ...(checksFromRollup(j.statusCheckRollup) === 'fail' ? { failing: failingFromRollup(j.statusCheckRollup) } : {}),\n };\n } catch {\n ghError = 'could not read `gh pr view` output';\n }\n } else if (view.code === 127) {\n ghError = 'GitHub CLI (gh) not found — install it to open and merge PRs';\n } else if (!/no pull requests found/i.test(view.stderr)) {\n ghError = oneLineErr(view.stderr) || 'gh pr view failed';\n }\n\n const facts: RepoFacts = {\n name: repo.name,\n path: repo.path,\n branch,\n localSha,\n dirtyFiles,\n hasUpstream,\n tracksRemote,\n ahead,\n behind,\n pr,\n ghError,\n commitsVsBase,\n ...(gitError ? { gitError } : {}),\n };\n const { done, reason } = repoDone(facts);\n return { ...facts, done, doneReason: reason, mergeBlockers: mergeBlockers(facts) };\n}\n\nexport async function shipPreflight(\n session: WorktreeSession,\n run: CommandRunner = defaultRunner,\n opts: { askGh?: AskGh } = {},\n): Promise<ShipPreflight> {\n const repos = await Promise.all(shipRepos(session).map((r) => inspectRepo(r, run, opts.askGh)));\n return { repos };\n}\n\nasync function push(r: RepoShipState, run: CommandRunner): Promise<ShipResult> {\n // Set tracking to origin/<branch> unless it already is; a plain push\n // with tracking on the base branch is refused by git.\n const args = r.tracksRemote ? ['push'] : ['push', '-u', 'origin', r.branch];\n const res = await run('git', args, r.path);\n return res.code === 0\n ? { repo: r.name, ok: true, message: r.hasUpstream ? 'pushed' : `published ${r.branch}` }\n : { repo: r.name, ok: false, message: oneLineErr(res.stderr) || 'git push failed' };\n}\n\n/**\n * push / create-pr across the session's repos. Done repos and repos with\n * no commits vs the base are skipped (reported ok), never failed.\n */\nexport async function runShipAction(\n session: WorktreeSession,\n action: 'push' | 'create-pr',\n opts: { draft?: boolean } = {},\n run: CommandRunner = defaultRunner,\n): Promise<ShipResult[]> {\n const { repos } = await shipPreflight(session, run);\n const results: ShipResult[] = [];\n for (const r of repos) {\n if (r.done) {\n results.push({ repo: r.name, ok: true, message: r.doneReason === 'merged' ? 'already merged' : 'untouched — skipped' });\n continue;\n }\n if (r.commitsVsBase === 0 && !r.pr) {\n results.push({ repo: r.name, ok: true, message: 'no commits vs the base branch — skipped' });\n continue;\n }\n if (action === 'push') {\n if (r.hasUpstream && !r.ahead && r.tracksRemote) {\n results.push({ repo: r.name, ok: true, message: 'nothing to push' });\n continue;\n }\n results.push(await push(r, run));\n continue;\n }\n // create-pr (a MERGED PR that isn't done means new work → new PR)\n if (r.pr && r.pr.state === 'OPEN') {\n results.push({ repo: r.name, ok: true, message: `PR #${r.pr.number} already open`, url: r.pr.url });\n continue;\n }\n if (r.ghError) {\n results.push({ repo: r.name, ok: false, message: r.ghError });\n continue;\n }\n if (!r.hasUpstream || (r.ahead ?? 0) > 0 || !r.tracksRemote) {\n const pushed = await push(r, run);\n if (!pushed.ok) {\n results.push(pushed);\n continue;\n }\n }\n const args = ['pr', 'create', '--fill', '--head', r.branch];\n if (opts.draft) args.push('--draft');\n const res = await run('gh', args, r.path);\n if (res.code === 0) {\n const url = res.stdout\n .trim()\n .split(/\\s+/)\n .find((t) => t.startsWith('http'));\n results.push({ repo: r.name, ok: true, message: opts.draft ? 'draft PR opened' : 'PR opened', url });\n } else {\n results.push({ repo: r.name, ok: false, message: oneLineErr(res.stderr) || 'gh pr create failed' });\n }\n }\n return results;\n}\n\nexport interface MergeOutcome {\n results: ShipResult[];\n /** Something was merged by this call. */\n mergedAny: boolean;\n /** After this call, every repo in the session is done. */\n allDone: boolean;\n}\n\n/**\n * Merge exactly the selected repos, at exactly the PR heads the user saw.\n *\n * Validation happens for ALL selected repos before ANY merge: an unknown\n * repo, a PR that moved (someone pushed after the user looked), or any\n * blocker refuses the whole call — no half-applied selection. Repos not\n * selected are never touched, so shipping a group in parts is a deliberate\n * choice, not an accident.\n */\nexport async function mergeSelected(\n session: WorktreeSession,\n selection: MergeSelection[],\n method: MergeMethod,\n run: CommandRunner = defaultRunner,\n): Promise<MergeOutcome> {\n const { repos } = await shipPreflight(session, run);\n const byName = new Map(repos.map((r) => [r.name, r]));\n if (selection.length === 0) {\n return {\n results: [{ repo: '-', ok: false, message: 'no repositories selected' }],\n mergedAny: false,\n allDone: repos.every((r) => r.done),\n };\n }\n\n const problems: ShipResult[] = [];\n for (const sel of selection) {\n const r = byName.get(sel.name);\n if (!r) {\n problems.push({ repo: sel.name, ok: false, message: 'not a repository of this session' });\n } else if (r.done) {\n problems.push({ repo: r.name, ok: false, message: r.doneReason === 'merged' ? 'already merged' : 'nothing to merge' });\n } else if (!r.pr || r.pr.headSha !== sel.headSha) {\n problems.push({\n repo: r.name,\n ok: false,\n message: 'the pull request changed since you looked — review it again before merging',\n });\n } else if (r.mergeBlockers.length > 0) {\n problems.push({ repo: r.name, ok: false, message: `not merged: ${r.mergeBlockers.join('; ')}` });\n }\n }\n if (problems.length > 0) {\n const failed = new Set(problems.map((p) => p.repo));\n const held = selection\n .filter((s) => !failed.has(s.name))\n .map((s) => ({ repo: s.name, ok: false, message: 'not merged: another selected repo is blocked' }));\n return { results: [...problems, ...held], mergedAny: false, allDone: repos.every((r) => r.done) };\n }\n\n const results: ShipResult[] = [];\n const mergedNow = new Set<string>();\n for (const sel of selection) {\n const r = byName.get(sel.name)!;\n const res = await run('gh', ['pr', 'merge', String(r.pr!.number), `--${method}`, '--match-head-commit', sel.headSha], r.path);\n if (res.code === 0) {\n mergedNow.add(r.name);\n results.push({ repo: r.name, ok: true, merged: true, message: `PR #${r.pr!.number} merged (${method})`, url: r.pr!.url });\n } else {\n // Stop at the first failure rather than keep merging a partially\n // failing selection; what's merged is reported as merged.\n results.push({ repo: r.name, ok: false, message: oneLineErr(res.stderr) || 'gh pr merge failed' });\n break;\n }\n }\n const attempted = new Set(results.map((x) => x.repo));\n for (const sel of selection) {\n if (!attempted.has(sel.name)) {\n results.push({ repo: sel.name, ok: false, message: 'not merged: stopped after an earlier failure' });\n }\n }\n const allDone = repos.every((r) => r.done || mergedNow.has(r.name));\n return { results, mergedAny: mergedNow.size > 0, allDone };\n}\n"],"mappings":";;;;;;AAAA,OAAO,UAAU;AAyDV,IAAM,gBAA+B,CAAC,KAAK,MAAM,QACtD,IAAI,QAAQ,CAAC,YAAY;AACvB,MAAI,SAAS;AACb,MAAI,SAAS;AACb,MAAI,UAAU;AACd,QAAM,OAAO,CAAC,MAAiB;AAC7B,QAAI,QAAS;AACb,cAAU;AACV,iBAAa,KAAK;AAClB,YAAQ,CAAC;AAAA,EACX;AACA,QAAM,QAAQ,cAAW,KAAK,MAAM,EAAE,KAAK,aAAa,KAAK,CAAC;AAC9D,QAAM,QAAQ,WAAW,MAAM;AAC7B,UAAM,KAAK;AACX,SAAK,EAAE,MAAM,KAAK,QAAQ,QAAQ,UAAU,GAAG,GAAG,aAAa,CAAC;AAAA,EAClE,GAAG,GAAM;AACT,QAAM,QAAQ,GAAG,QAAQ,CAAC,MAAc;AACtC,cAAU,EAAE,SAAS;AAAA,EACvB,CAAC;AACD,QAAM,QAA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;AAEA,QAAM,UAAwB,CAAC;AAC/B,QAAM,YAAY,oBAAI,IAAY;AAClC,aAAW,OAAO,WAAW;AAC3B,UAAM,IAAI,OAAO,IAAI,IAAI,IAAI;AAC7B,UAAM,MAAM,MAAM,IAAI,MAAM,CAAC,MAAM,SAAS,OAAO,EAAE,GAAI,MAAM,GAAG,KAAK,MAAM,IAAI,uBAAuB,IAAI,OAAO,GAAG,EAAE,IAAI;AAC5H,QAAI,IAAI,SAAS,GAAG;AAClB,gBAAU,IAAI,EAAE,IAAI;AACpB,cAAQ,KAAK,EAAE,MAAM,EAAE,MAAM,IAAI,MAAM,QAAQ,MAAM,SAAS,OAAO,EAAE,GAAI,MAAM,YAAY,MAAM,KAAK,KAAK,EAAE,GAAI,IAAI,CAAC;AAAA,IAC1H,OAAO;AAGL,cAAQ,KAAK,EAAE,MAAM,EAAE,MAAM,IAAI,OAAO,SAAS,WAAW,IAAI,MAAM,KAAK,qBAAqB,CAAC;AACjG;AAAA,IACF;AAAA,EACF;AACA,QAAM,YAAY,IAAI,IAAI,QAAQ,IAAI,CAAC,MAAM,EAAE,IAAI,CAAC;AACpD,aAAW,OAAO,WAAW;AAC3B,QAAI,CAAC,UAAU,IAAI,IAAI,IAAI,GAAG;AAC5B,cAAQ,KAAK,EAAE,MAAM,IAAI,MAAM,IAAI,OAAO,SAAS,+CAA+C,CAAC;AAAA,IACrG;AAAA,EACF;AACA,QAAM,UAAU,MAAM,MAAM,CAAC,MAAM,EAAE,QAAQ,UAAU,IAAI,EAAE,IAAI,CAAC;AAClE,SAAO,EAAE,SAAS,WAAW,UAAU,OAAO,GAAG,QAAQ;AAC3D;","names":[]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/core/worktree/repo-rules.ts","../src/core/worktree/repo-scan.ts"],"sourcesContent":["/**\n * The rules for enrolling repos and making groups (repo-admin.ts, the Repos\n * page, the demo): what alias a repo gets, and why one can't be used. Pure,\n * without node:path — the demo and the SPA import it.\n */\n\n/** A path's last part. */\nconst baseName = (p: string) =>\n p\n .replace(/[\\\\/]+$/, '')\n .split(/[\\\\/]/)\n .pop() ?? p;\n/** Its folder. */\nconst dirName = (p: string) => p.replace(/[\\\\/]+$/, '').replace(/[\\\\/][^\\\\/]*$/, '');\n\n/** A resolved path written one way, for comparing: `/`, no trailing separator, lowercase when `caseless` (Windows). */\nexport function pathKey(resolved: string, caseless: boolean): string {\n const r = resolved.replace(/\\\\/g, '/').replace(/\\/+$/, '');\n return caseless ? r.toLowerCase() : r;\n}\n\n/** Two paths as the same folder: separators, a trailing one and (with a drive letter) case don't matter. */\nconst sameFolder = (a: string, b: string) => {\n const caseless = /^[a-z]:/i.test(a) || /^[a-z]:/i.test(b);\n return pathKey(a, caseless) === pathKey(b, caseless);\n};\n\nconst ALIAS_RE = /^[a-z0-9][a-z0-9._-]*$/;\n\n/** A folder name as an alias: lowercase, only a-z 0-9 . _ - . Pure. */\nexport function aliasFromFolder(folder: string): string {\n return (\n folder\n .toLowerCase()\n .replace(/[^a-z0-9._-]+/g, '-')\n .replace(/^[-._]+|[-._]+$/g, '') || 'repo'\n );\n}\n\n/**\n * The alias a found repo would get: its folder's, or — taken by an alias\n * or a group — its parent folder's in front (`iom-contracts`), then -2, -3….\n * Pure.\n */\nexport function suggestAlias(repoPath: string, taken: (alias: string) => boolean): string {\n const base = aliasFromFolder(baseName(repoPath));\n if (!taken(base)) return base;\n const withParent = `${aliasFromFolder(baseName(dirName(repoPath)))}-${base}`;\n if (!taken(withParent)) return withParent;\n for (let n = 2; ; n++) if (!taken(`${base}-${n}`)) return `${base}-${n}`;\n}\n\n/**\n * Why a repo can't be enrolled under `alias`; null when it can. Besides the\n * alias itself (its characters, an alias or group of that name), the\n * folder: worktrees go in `<worktreesRoot>/<folder>/`, so two repos with the\n * same folder name would share them. Pure.\n */\nexport function enrollProblem(\n alias: string,\n repoPath: string,\n config: { repos: Record<string, string>; groups: Record<string, string[]> },\n): string | null {\n if (!ALIAS_RE.test(alias)) return 'an alias is lowercase letters, digits, . _ - (starting with a letter or digit)';\n if (alias in config.repos) return `“${alias}” is already the alias of ${config.repos[alias]}`;\n if (alias in config.groups) return `“${alias}” is a group`;\n const same = Object.entries(config.repos).find(([, p]) => sameFolder(p, repoPath));\n if (same) return `already enrolled as “${same[0]}”`;\n const folder = baseName(repoPath).toLowerCase();\n const clash = Object.entries(config.repos).find(([, p]) => baseName(p).toLowerCase() === folder);\n if (clash) return `another repo has the folder name “${baseName(repoPath)}” (${clash[0]}): their worktrees would share a folder`;\n if (Object.keys(config.groups).some((g) => g.toLowerCase() === folder))\n return `a group is called “${folder}”: its worktrees would share a folder`;\n return null;\n}\n\n/** Why a group can't be called `name`, or made of `members`; null when it can. Pure. */\nexport function groupProblem(\n name: string,\n members: string[],\n config: { repos: Record<string, string>; groups: Record<string, string[]> },\n opts: { creating: boolean },\n): string | null {\n // The name is checked when it is given; an existing group keeps the one it has.\n if (opts.creating) {\n if (!ALIAS_RE.test(name)) return 'a group name is lowercase letters, digits, . _ - (starting with a letter or digit)';\n if (name in config.groups) return `a group “${name}” already exists`;\n if (name in config.repos) return `“${name}” is a repo's alias`;\n if (Object.values(config.repos).some((p) => baseName(p).toLowerCase() === name)) return `a repo's folder is called “${name}”`;\n } else if (!(name in config.groups)) {\n return `no group “${name}”`;\n }\n if (new Set(members).size < 2) return 'a group needs at least two repos';\n const unknown = members.filter((m) => !(m in config.repos));\n if (unknown.length) return `not enrolled: ${unknown.join(', ')}`;\n return null;\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\nimport { BUILD_DIR_NAMES } from '../cleanup/build-folders.js';\nimport { pathKey } from './repo-rules.js';\nexport { aliasFromFolder, enrollProblem, groupProblem, suggestAlias } from './repo-rules.js';\n\n/**\n * Finding the git repos in a folder (the Repos page, `work config scan`):\n * a breadth-first walk, a few levels deep, that stops at each repo it finds\n * (a repo inside a repo is that repo's business), and skips what is never a\n * project of its own — build output, dot-folders, work's worktrees, a\n * worktree's or a submodule's `.git` file. Reads only: directory listings\n * and the `.git` entries.\n */\n\nexport interface FoundRepo {\n /** As found on disk. */\n path: string;\n /** Its folder name. */\n folder: string;\n /** `owner/name` from its origin URL, when it has one. */\n origin: string | null;\n}\n\n/** One way to write a path, for comparing: resolved, no trailing separator, `/`, lowercase on Windows. Pure. */\nexport function samePathKey(p: string, platform: NodeJS.Platform = process.platform): string {\n return pathKey(path.resolve(p), platform === 'win32');\n}\n\n/** `owner/name` from an origin URL (https or ssh, with or without .git); null when it isn't one. Pure. */\nexport function ownerRepo(url: string): string | null {\n const m = /[:/]([^/:]+)\\/([^/]+?)(?:\\.git)?\\/?$/.exec(url.trim());\n return m ? `${m[1]}/${m[2]}` : null;\n}\n\n/** The origin URL in a `.git/config` text. Pure. */\nexport function originUrl(configText: string): string | null {\n const section = /\\[remote \"origin\"\\]([\\s\\S]*?)(?=\\n\\[|$)/.exec(configText);\n const url = section ? /^\\s*url\\s*=\\s*(.+)$/m.exec(section[1]) : null;\n if (!url) return null;\n // As git writes a value: maybe quoted, with \\\\ and \\\" escaped (a Windows path).\n const v = url[1].trim().replace(/^\"(.*)\"$/, '$1');\n return v.replace(/\\\\([\"\\\\])/g, '$1');\n}\n\n/** What a folder's `.git` says it is: a repo, a linked worktree or a submodule (a `.git` file), or nothing. */\nfunction gitKind(dir: string): 'repo' | 'linked' | null {\n const g = path.join(dir, '.git');\n let st: fs.Stats;\n try {\n st = fs.statSync(g);\n } catch {\n return null;\n }\n if (st.isDirectory()) return 'repo';\n // A file: `gitdir: …/.git/worktrees/x` (a worktree) or `…/.git/modules/x` (a submodule) — part of another repo.\n return 'linked';\n}\n\nfunction readOrigin(dir: string): string | null {\n try {\n const url = originUrl(fs.readFileSync(path.join(dir, '.git', 'config'), 'utf-8'));\n return url ? ownerRepo(url) : null;\n } catch {\n return null;\n }\n}\n\n/**\n * The git repos under `root`, at most `depth` folders down (1 = its\n * children). `skip`: folders never walked into (work's worktrees root),\n * compared with samePathKey. A root that doesn't exist gives none.\n */\nexport function scanForRepos(root: string, opts: { depth?: number; skip?: string[] } = {}): FoundRepo[] {\n const depth = opts.depth ?? 2;\n const skip = new Set((opts.skip ?? []).filter(Boolean).map((p) => samePathKey(p)));\n const found: FoundRepo[] = [];\n let level: string[] = [root];\n for (let d = 0; d <= depth && level.length; d++) {\n const next: string[] = [];\n for (const dir of level) {\n if (skip.has(samePathKey(dir))) continue;\n const kind = d === 0 ? null : gitKind(dir);\n if (kind === 'repo') {\n found.push({ path: dir, folder: path.basename(dir), origin: readOrigin(dir) });\n continue; // a repo's insides are its own\n }\n if (kind === 'linked') continue;\n let entries: fs.Dirent[];\n try {\n entries = fs.readdirSync(dir, { withFileTypes: true });\n } catch {\n continue;\n }\n for (const e of entries) {\n if (!e.isDirectory() || e.name.startsWith('.') || BUILD_DIR_NAMES.has(e.name.toLowerCase())) continue;\n next.push(path.join(dir, e.name));\n }\n }\n level = next;\n }\n return found.sort((a, b) => a.folder.localeCompare(b.folder));\n}\n"],"mappings":";;;;;;AAOA,IAAM,WAAW,CAAC,MAChB,EACG,QAAQ,WAAW,EAAE,EACrB,MAAM,OAAO,EACb,IAAI,KAAK;AAEd,IAAM,UAAU,CAAC,MAAc,EAAE,QAAQ,WAAW,EAAE,EAAE,QAAQ,iBAAiB,EAAE;AAG5E,SAAS,QAAQ,UAAkB,UAA2B;AACnE,QAAM,IAAI,SAAS,QAAQ,OAAO,GAAG,EAAE,QAAQ,QAAQ,EAAE;AACzD,SAAO,WAAW,EAAE,YAAY,IAAI;AACtC;AAGA,IAAM,aAAa,CAAC,GAAW,MAAc;AAC3C,QAAM,WAAW,WAAW,KAAK,CAAC,KAAK,WAAW,KAAK,CAAC;AACxD,SAAO,QAAQ,GAAG,QAAQ,MAAM,QAAQ,GAAG,QAAQ;AACrD;AAEA,IAAM,WAAW;AAGV,SAAS,gBAAgB,QAAwB;AACtD,SACE,OACG,YAAY,EACZ,QAAQ,kBAAkB,GAAG,EAC7B,QAAQ,oBAAoB,EAAE,KAAK;AAE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,EACV;AACA,SAAO,MAAM,KAAK,CAAC,GAAG,MAAM,EAAE,OAAO,cAAc,EAAE,MAAM,CAAC;AAC9D;","names":[]}
|
package/dist/chunk-GHO7HYP6.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/core/git/base-spec.ts","../src/core/worktree/worktree.ts","../src/core/archive/archive-restore.ts","../src/core/worktree/copy-files.ts"],"sourcesContent":["/**\n * Parsing for `work tree --base`. A base can be specified two ways, and\n * they compose:\n *\n * --base dev → default base for every repo\n * --base backend=dev --base front=x → per-repo overrides\n * --base dev --base front=x → dev for all, front overridden to x\n *\n * yargs collects repeated `--base` flags into an array (a single flag stays\n * a string), so this accepts `string | string[] | undefined`.\n */\n\nexport interface BaseSpec {\n /** Base applied to any repo without a per-repo override. */\n default?: string;\n /** alias → base branch overrides. */\n perRepo: Record<string, string>;\n}\n\n/** Thrown by {@link parseBaseSpec} on malformed or conflicting input. */\nexport class BaseSpecError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'BaseSpecError';\n }\n}\n\n/**\n * Parse raw `--base` values into a {@link BaseSpec}. A value containing `=`\n * is treated as an `alias=branch` override; anything else is a bare default.\n * Throws {@link BaseSpecError} on empty halves or conflicting duplicates.\n */\nexport function parseBaseSpec(raw: string | string[] | undefined): BaseSpec {\n const spec: BaseSpec = { perRepo: {} };\n if (raw === undefined) return spec;\n const values = Array.isArray(raw) ? raw : [raw];\n\n for (const value of values) {\n const v = value.trim();\n if (!v) continue;\n const eq = v.indexOf('=');\n if (eq === -1) {\n if (spec.default !== undefined && spec.default !== v) {\n throw new BaseSpecError(`Conflicting default --base values: '${spec.default}' and '${v}'`);\n }\n spec.default = v;\n } else {\n const alias = v.slice(0, eq).trim();\n const branch = v.slice(eq + 1).trim();\n if (!alias || !branch) {\n throw new BaseSpecError(`Invalid --base '${value}'. Use 'alias=branch' or a bare 'branch'.`);\n }\n const prior = spec.perRepo[alias];\n if (prior !== undefined && prior !== branch) {\n throw new BaseSpecError(`Conflicting --base for '${alias}': '${prior}' and '${branch}'`);\n }\n spec.perRepo[alias] = branch;\n }\n }\n\n return spec;\n}\n\n/** The resolved base for one repo alias: its override, else the default. */\nexport function baseForAlias(spec: BaseSpec, alias: string): string | undefined {\n return spec.perRepo[alias] ?? spec.default;\n}\n\n/** True when no base was requested at all (plain HEAD-fork behavior). */\nexport function isEmptyBaseSpec(spec: BaseSpec): boolean {\n return spec.default === undefined && Object.keys(spec.perRepo).length === 0;\n}\n\n/** The alias keys carrying a per-repo override. */\nexport function baseSpecOverrideAliases(spec: BaseSpec): string[] {\n return Object.keys(spec.perRepo);\n}\n\n/** Normalize the loose `setupWorktree` parameter into a {@link BaseSpec}. */\nexport function toBaseSpec(base: string | BaseSpec | undefined): BaseSpec {\n if (base === undefined) return { perRepo: {} };\n if (typeof base === 'string') return { default: base, perRepo: {} };\n return base;\n}\n","import fs from 'node:fs';\nimport { agentFor } from '../agents/index.js';\nimport { restoreArchivedUncommitted } from '../archive/archive-restore.js';\nimport path from 'node:path';\nimport { debug } from '../platform/logger.js';\nimport type { WorkConfig } from '../platform/config.js';\nimport { getConfigDir } from '../platform/config.js';\nimport { resolveProjectTarget } from './resolve.js';\nimport {\n findSession,\n loadHistory,\n upsertSession,\n upsertSessionWithPort,\n setSessionTitle,\n forgetOtherBaseCheckoutEntries,\n} from '../sessions/history.js';\nimport { bestEffort } from '../platform/best-effort.js';\nimport { readArchive, restoreArchivedTranscripts } from '../archive/session-archive.js';\nimport { sessionIdFor } from '../sessions/session-id.js';\nimport {\n git,\n parseWorktreeList,\n localBranchExists,\n remoteBranchExists,\n isGitRepo,\n getCurrentBranch,\n getStatusChecked,\n repoState,\n getUnpushedCommits,\n} from '../git/git.js';\nimport { copyConfigFiles } from './copy-files.js';\nimport { type BaseSpec, baseForAlias, baseSpecOverrideAliases, isEmptyBaseSpec, toBaseSpec } from '../git/base-spec.js';\nimport { report } from '../platform/report.js';\n\n/**\n * Pull latest changes for a checkout we're switching into (a worktree that\n * already existed, or the base repo). Runs fetch + pull in that directory.\n * Best-effort: a branch with no upstream is skipped silently; a failed pull\n * (dirty tree, conflicts) only warns and never blocks the switch.\n */\nexport function pullLatestForBranch(worktreePath: string, branchName: string): void {\n // Skip purely local branches — `git pull` would print a \"no tracking\n // information\" error that reads as a failure rather than a no-op.\n const upstream = git(['rev-parse', '--abbrev-ref', `${branchName}@{upstream}`], worktreePath);\n if (upstream.exitCode !== 0) return;\n\n report('info', ` Pulling latest changes for ${branchName}...`);\n // Fetch first so origin/* is fresh even if the pull below can't fast-forward.\n git(['fetch', '--quiet'], worktreePath);\n const pull = git(['pull', '--quiet'], worktreePath);\n if (pull.exitCode !== 0) {\n report('warn', ` ⚠ Could not pull '${branchName}' (uncommitted changes or conflicts). Worktree may be behind origin.`);\n const firstErrLine = pull.stderr.split('\\n')[0];\n if (firstErrLine) report('detail', ` ${firstErrLine}`);\n }\n}\n\n/**\n * Create a single git worktree for one repo.\n * Returns true on success, false on failure.\n *\n * When `baseBranch` is provided, the new branch is created from that base\n * instead of HEAD. Only valid for new branches — errors if the target branch\n * already exists locally or on remote.\n *\n * `pull` (default true) only affects the already-exists path: a freshly created\n * worktree is at its branch tip anyway.\n */\n/** Same folder: git prints forward slashes and long names on Windows, where a path may come as a short 8.3 name or in another case. */\nfunction samePath(a: string, b: string): boolean {\n const norm = (p: string) => {\n let r = path.resolve(p);\n try {\n r = fs.realpathSync.native(r);\n } catch {\n /* not there: as given */\n }\n return process.platform === 'win32' ? r.toLowerCase() : r;\n };\n return norm(a) === norm(b);\n}\n\nexport function createSingleWorktree(\n repoPath: string,\n worktreePath: string,\n branchName: string,\n config: WorkConfig,\n baseBranch?: string,\n pull = true,\n): boolean {\n debug('createSingleWorktree', { repoPath, worktreePath, branchName, baseBranch });\n\n // Check if the worktree already exists at the target path (idempotent re-run)\n if (fs.existsSync(worktreePath)) {\n if (isGitRepo(worktreePath)) {\n const currentBranch = getCurrentBranch(worktreePath);\n if (currentBranch === branchName) {\n report('warn', ` Worktree already exists at: ${worktreePath}`);\n if (pull) pullLatestForBranch(worktreePath, branchName);\n return true;\n }\n // This repo's worktree, on another branch now (Claude or you switched\n // it): it is the session's checkout, used as it is. `git worktree add`\n // into it would fail, and re-entering or restoring the session with it.\n const ours = parseWorktreeList(repoPath).some((wt) => samePath(wt.path, worktreePath));\n if (ours) {\n report(\n 'warn',\n ` Worktree already exists at: ${worktreePath} (on ${currentBranch ?? 'a detached HEAD'}, not ${branchName}: using it as it is)`,\n );\n if (pull && currentBranch) pullLatestForBranch(worktreePath, currentBranch);\n return true;\n }\n }\n }\n\n // Check if the branch is already checked out in another worktree\n const worktrees = parseWorktreeList(repoPath);\n const existingForBranch = worktrees.find((wt) => wt.branch === branchName && wt.path !== worktreePath);\n\n if (existingForBranch) {\n report('error', ` Branch '${branchName}' is already checked out in a worktree at: ${existingForBranch.path}`);\n report('error', ' Remove that worktree first, or use the existing one.');\n return false;\n }\n\n // Create parent directory\n const parentDir = path.dirname(worktreePath);\n fs.mkdirSync(parentDir, { recursive: true });\n\n // Fetch remote refs first so origin/* is up to date even if pull fails below\n git(['fetch', '--quiet'], repoPath);\n\n // Pull latest changes for current branch in main repo\n const baseRepoBranch = getCurrentBranch(repoPath);\n const baseBranchLabel = baseRepoBranch ?? '(detached HEAD)';\n report('info', ` Pulling latest changes for main repo (on ${baseBranchLabel})...`);\n if (baseRepoBranch && !['master', 'main', 'dev'].includes(baseRepoBranch)) {\n report('warn', ` ⚠ Warning: base repo is on '${baseRepoBranch}', not master/main/dev`);\n }\n const baseRepoPull = git(['pull', '--quiet'], repoPath);\n const baseRepoPullFailed = baseRepoPull.exitCode !== 0;\n if (baseRepoPullFailed) {\n report('warn', ` ⚠ Could not pull '${baseBranchLabel}' (uncommitted changes, conflicts, or no upstream).`);\n const firstErrLine = baseRepoPull.stderr.split('\\n')[0];\n if (firstErrLine) report('detail', ` ${firstErrLine}`);\n }\n\n const hasLocal = localBranchExists(branchName, repoPath);\n const hasRemote = remoteBranchExists(branchName, repoPath);\n\n // --base requires a brand-new branch\n if (baseBranch && (hasLocal || hasRemote)) {\n report('error', ` Cannot use --base: branch '${branchName}' already exists ${hasLocal ? 'locally' : 'on remote'}`);\n return false;\n }\n\n // Pull latest changes if branch exists locally\n if (hasLocal) {\n report('info', ` Pulling latest changes for ${branchName}...`);\n const prevBranch = getCurrentBranch(repoPath);\n git(['checkout', branchName, '--quiet'], repoPath);\n const branchPull = git(['pull', '--quiet'], repoPath);\n if (branchPull.exitCode !== 0) {\n report('warn', ` ⚠ Could not pull '${branchName}'. Worktree may be behind origin.`);\n const firstErrLine = branchPull.stderr.split('\\n')[0];\n if (firstErrLine) report('detail', ` ${firstErrLine}`);\n }\n if (prevBranch) {\n git(['checkout', prevBranch, '--quiet'], repoPath);\n }\n }\n\n // Create worktree\n let result;\n let branchSource: 'local' | 'remote' | 'new' = 'new';\n if (hasLocal || hasRemote) {\n if (hasRemote && !hasLocal) {\n branchSource = 'remote';\n result = git(['worktree', 'add', worktreePath, '-b', branchName, '--track', `origin/${branchName}`], repoPath);\n } else {\n branchSource = 'local';\n result = git(['worktree', 'add', worktreePath, branchName], repoPath);\n }\n } else if (baseBranch) {\n // Validate the base branch exists\n const baseLocal = localBranchExists(baseBranch, repoPath);\n const baseRemote = remoteBranchExists(baseBranch, repoPath);\n\n if (!baseLocal && !baseRemote) {\n report('error', ` Base branch '${baseBranch}' does not exist locally or on remote`);\n return false;\n }\n\n const baseRef = baseLocal ? baseBranch : `origin/${baseBranch}`;\n result = git(['worktree', 'add', worktreePath, '-b', branchName, baseRef], repoPath);\n } else {\n // If pulling the base repo branch failed, use origin/<baseRepoBranch> as the\n // source so the new branch isn't created from a stale local HEAD.\n const fallbackToRemote = baseRepoPullFailed && !!baseRepoBranch && remoteBranchExists(baseRepoBranch, repoPath);\n if (fallbackToRemote) {\n report('step', ` Using origin/${baseRepoBranch} as base (local '${baseRepoBranch}' is stale)`);\n result = git(['worktree', 'add', worktreePath, '-b', branchName, `origin/${baseRepoBranch}`], repoPath);\n } else {\n result = git(['worktree', 'add', worktreePath, '-b', branchName], repoPath);\n }\n }\n\n if (result.exitCode !== 0) {\n debug('git worktree add failed', { exitCode: result.exitCode, stdout: result.stdout, stderr: result.stderr });\n report('error', ' Failed to create worktree');\n if (result.stderr) {\n report('error', ` ${result.stderr}`);\n }\n return false;\n }\n\n // Copy configuration files from main repo\n if (config.copyFiles && config.copyFiles.length > 0) {\n copyConfigFiles(repoPath, worktreePath, config.copyFiles);\n }\n\n if (branchSource === 'remote') {\n report('step', ` Tracking remote branch origin/${branchName}`);\n } else if (branchSource === 'local') {\n report('step', ` Using existing local branch ${branchName}`);\n } else if (baseBranch) {\n report('step', ` Created new branch ${branchName} from ${baseBranch}`);\n } else {\n report('step', ` Created new branch ${branchName}`);\n }\n\n report('success', ` Created worktree: ${worktreePath}`);\n return true;\n}\n\n/**\n * Remove a single git worktree.\n * Returns true on success, false if blocked (uncommitted/unpushed changes).\n */\n/**\n * Would `removeSingleWorktree(…, force)` refuse this worktree? Same checks,\n * no side effects — lets callers stop the session's Claude only when the\n * worktree is really going away (a refused non-forced removal must leave\n * the running agent alone).\n */\nexport function wouldRefuseRemoval(worktreePath: string, force: boolean): boolean {\n if (force || !fs.existsSync(worktreePath)) return false;\n const state = repoState(worktreePath);\n if (state === 'not-a-repo') return false;\n if (state === 'unknown') return true; // git can't read it: can't prove it's safe\n const status = getStatusChecked(worktreePath);\n if (status === null) return true;\n return !!status || !!getUnpushedCommits(worktreePath);\n}\n\n/**\n * git got through its checks and failed while deleting the files (a path too\n * long for Windows, a file another program holds) — as opposed to refusing\n * (\"contains modified or untracked files\", \"is locked\").\n */\nexport function isDeleteFailure(stderr: string): boolean {\n return /failed to delete/i.test(stderr);\n}\n\nexport function removeSingleWorktree(repoPath: string, worktreePath: string, branchName: string, force: boolean): boolean {\n if (!fs.existsSync(worktreePath)) {\n report('warn', ` Worktree does not exist at: ${worktreePath}`);\n return true; // Nothing to remove is success\n }\n\n // A folder that is definitely not a git checkout (a leftover) is just\n // deleted. One git merely failed to read is NOT: without --force it's\n // refused, because every check below would read as \"clean\".\n const state = repoState(worktreePath);\n if (state === 'not-a-repo') {\n fs.rmSync(worktreePath, { recursive: true, force: true });\n git(['worktree', 'prune'], repoPath);\n report('info', ` Removed invalid worktree directory: ${worktreePath}`);\n return true;\n }\n if (state === 'unknown' && !force) {\n report(\n 'warn',\n ` git can't read ${worktreePath} (ownership, a moved main repo, git not on PATH?) — not removing it. Check it, or use --force.`,\n );\n return false;\n }\n\n if (!force) {\n // Check for uncommitted changes\n const status = getStatusChecked(worktreePath);\n if (status === null) {\n report('warn', ` Could not check ${worktreePath} for uncommitted changes — not removing it.`);\n return false;\n }\n if (status) {\n report('warn', ` Uncommitted changes in: ${worktreePath}`);\n report('info', status);\n return false;\n }\n\n // Check for unpushed commits\n const unpushed = getUnpushedCommits(worktreePath);\n if (unpushed) {\n report('warn', ` Unpushed commits in: ${worktreePath}`);\n report('info', unpushed);\n return false;\n }\n }\n\n // core.longpaths: a worktree's node_modules / bin / obj easily pass\n // Windows' 260-character limit, and without it git stops half way with\n // \"Filename too long\" (a no-op elsewhere).\n const args = force\n ? ['-c', 'core.longpaths=true', 'worktree', 'remove', worktreePath, '--force']\n : ['-c', 'core.longpaths=true', 'worktree', 'remove', worktreePath];\n\n const result = git(args, repoPath);\n\n if (result.exitCode === 0) {\n report('success', ` Removed worktree: ${worktreePath}`);\n return true;\n } else if (isDeleteFailure(result.stderr)) {\n // git had passed its own checks (and ours above) and failed while\n // deleting files: finish the delete ourselves — Node handles long paths —\n // then let git forget the registration. A git REFUSAL never gets here.\n try {\n fs.rmSync(worktreePath, { recursive: true, force: true, maxRetries: 3, retryDelay: 200 });\n } catch (err) {\n report('error', ` Failed to remove worktree: ${worktreePath}`);\n report('error', ` ${(err as Error).message}`);\n return false;\n }\n git(['worktree', 'prune'], repoPath);\n const why = result.stderr.split('\\n')[0].replace(/^error:\\s*/, '');\n report('success', ` Removed worktree: ${worktreePath} (finished the delete git could not: ${why})`);\n return true;\n } else if (force && state === 'unknown') {\n // git can't handle it (its main repo moved, say) and the user forced\n // it: delete the folder, then let git forget the registration.\n fs.rmSync(worktreePath, { recursive: true, force: true });\n git(['worktree', 'prune'], repoPath);\n report('success', ` Removed worktree folder git could not read: ${worktreePath}`);\n return true;\n } else {\n report('error', ` Failed to remove worktree: ${worktreePath}`);\n if (result.stderr) {\n report('error', ` ${result.stderr}`);\n }\n return false;\n }\n}\n\n/** Caller-tunable behavior for {@link setupWorktree}. */\nexport interface WorktreeSetupOptions {\n /**\n * Pull latest changes when switching into a worktree that already exists.\n * Default true; `work tree --no-pull` turns it off.\n */\n pull?: boolean;\n /**\n * Per repo alias: the branch to check out instead of the session's — set\n * when restoring an archived session whose worktree was removed while on\n * another branch (archive.json `heads`). The folder keeps the session's name.\n */\n checkoutFor?: Record<string, string>;\n /** Name the session (its title, shown instead of the branch); empty keeps what it has. */\n name?: string;\n}\n\n/**\n * Result of setupWorktree — everything needed to launch an AI session.\n */\nexport interface WorktreeSetupResult {\n /** Directory to launch the AI tool in. */\n launchDir: string;\n /** All worktree paths created/found (for session tracking). */\n paths: string[];\n /** Whether the target is a group. */\n isGroup: boolean;\n /** Stable dev-server port allocated to this worktree, if allocation succeeded. */\n port?: number;\n}\n\n/**\n * High-level worktree setup: resolve target, create worktree(s), copy group\n * CLAUDE.md, and record the session. Used by both the CLI command and the TUI.\n *\n * Returns the setup result on success, or null on failure.\n */\nexport async function setupWorktree(\n targetName: string,\n branchName: string,\n config: WorkConfig,\n base?: string | BaseSpec,\n jiraKey?: string,\n opts: WorktreeSetupOptions = {},\n): Promise<WorktreeSetupResult | null> {\n const spec = toBaseSpec(base);\n debug('setupWorktree', { targetName, branchName, spec, jiraKey, opts });\n const target = resolveProjectTarget(targetName, config);\n if (!target) {\n debug('setupWorktree: target not found', targetName);\n return null;\n }\n\n const workTreeDirName = branchName.replace(/\\//g, '-');\n\n // Coming back to an archived session whose merged branch archiving\n // deleted: put the branch back at the tip it had, so the worktree is that\n // work (branch resolution would otherwise start a new branch from base).\n bestEffort('recreate the archived branch', () =>\n recreateArchivedBranches(target.isGroup ? target.name : targetName, branchName, target.repoAliases, config),\n );\n // And its worktree comes back on the branch it was on (Claude may have\n // switched from the session's), not a new one of the session's name.\n const checkoutFor = opts.checkoutFor ?? archivedHeads(target.isGroup ? target.name : targetName, branchName);\n if (checkoutFor) opts = { ...opts, checkoutFor };\n\n const result = target.isGroup\n ? await setupGroupWorktree(target.name, target.repoAliases, branchName, workTreeDirName, config, spec, jiraKey, opts)\n : await setupSingleWorktree(targetName, branchName, workTreeDirName, config, spec, jiraKey, opts);\n // Coming back to an archived session: put its conversation back where\n // Claude looks for it (only files that aren't there), so it continues.\n if (result) {\n const sessionTarget = target.isGroup ? target.name : targetName;\n const session = findSession(loadHistory(), sessionTarget, branchName);\n if (session) bestEffort('restore the archived conversation', () => restoreArchivedTranscripts(session), 0);\n // And the uncommitted work archiving saved when it removed the worktree.\n if (session)\n await restoreArchivedUncommitted(session, config).catch((err: Error) =>\n report('warn', `couldn't put back its uncommitted changes: ${err.message}`),\n );\n if (opts.name?.trim()) await setSessionTitle(sessionTarget, branchName, opts.name);\n }\n return result;\n}\n\n/**\n * For each repo whose local branch archiving deleted (archive.json\n * `branchesDeleted`): recreate it at the recorded tip when neither a local\n * nor a remote branch of that name exists and the commit is still there.\n * Returns the aliases it recreated the branch in.\n */\nexport function recreateArchivedBranches(sessionTarget: string, branch: string, aliases: string[], config: WorkConfig): string[] {\n const session = findSession(loadHistory(), sessionTarget, branch);\n if (!session) return [];\n const rec = readArchive(sessionIdFor(session));\n if (!rec?.tips || !rec.branchesDeleted?.length) return [];\n const done: string[] = [];\n for (const alias of aliases) {\n const repo = config.repos[alias];\n const tip = rec.tips[alias];\n // The branch it was on: the session's, or the one Claude switched to.\n const name = rec.heads?.[alias] ?? branch;\n if (!repo || !tip || !rec.branchesDeleted.includes(alias)) continue;\n if (localBranchExists(name, repo) || remoteBranchExists(name, repo)) continue;\n if (git(['cat-file', '-e', `${tip}^{commit}`], repo).exitCode !== 0) continue;\n if (git(['branch', name, tip], repo).exitCode === 0) done.push(alias);\n }\n return done;\n}\n\n/**\n * An archived session whose worktree was removed while (some of) its repos\n * were on another branch: alias → that branch, for setupWorktree to check\n * out. Undefined otherwise (the worktree was kept, or on the session's branch).\n */\nexport function archivedHeads(sessionTarget: string, branch: string): Record<string, string> | undefined {\n const session = findSession(loadHistory(), sessionTarget, branch);\n if (!session?.archivedAt) return undefined;\n const rec = readArchive(sessionIdFor(session));\n return rec?.worktreeRemoved && rec.heads && Object.keys(rec.heads).length ? rec.heads : undefined;\n}\n\nasync function setupGroupWorktree(\n groupName: string,\n repoAliases: string[],\n branchName: string,\n workTreeDirName: string,\n config: WorkConfig,\n spec: BaseSpec,\n jiraKey?: string,\n opts: WorktreeSetupOptions = {},\n): Promise<WorktreeSetupResult | null> {\n const groupWorktreePath = path.join(config.worktreesRoot, groupName, workTreeDirName);\n\n // Pre-validate --base across all repos before creating anything. Each repo\n // resolves its own base: a per-repo override (`alias=branch`) if present,\n // otherwise the bare default.\n if (!isEmptyBaseSpec(spec)) {\n const unknownAliases = baseSpecOverrideAliases(spec).filter((a) => !repoAliases.includes(a));\n if (unknownAliases.length > 0) {\n report(\n 'error',\n `--base names repo(s) not in group '${groupName}': ${unknownAliases.join(', ')}. Group repos: ${repoAliases.join(', ')}`,\n );\n return null;\n }\n\n const missingBase: string[] = [];\n const branchExists: string[] = [];\n\n for (const alias of repoAliases) {\n const repoPath = config.repos[alias];\n const repoBase = baseForAlias(spec, alias);\n if (!repoBase) continue; // no base applied to this repo → forks HEAD\n if (!localBranchExists(repoBase, repoPath) && !remoteBranchExists(repoBase, repoPath)) {\n missingBase.push(`${alias} (${repoBase})`);\n }\n if (localBranchExists(branchName, repoPath) || remoteBranchExists(branchName, repoPath)) {\n branchExists.push(alias);\n }\n }\n\n if (missingBase.length > 0) {\n report('error', `Base branch not found in: ${missingBase.join(', ')}`);\n return null;\n }\n if (branchExists.length > 0) {\n report('error', `Cannot use --base: branch '${branchName}' already exists in: ${branchExists.join(', ')}`);\n return null;\n }\n }\n\n report('step', `Creating group worktree: ${groupName}/${branchName}`);\n report('detail', `Directory: ${groupWorktreePath}`);\n report('info', '');\n\n fs.mkdirSync(groupWorktreePath, { recursive: true });\n\n const createdWorktrees: Array<{ repoPath: string; worktreePath: string }> = [];\n // Per-repo fork point, keyed by worktree path (matches the session `paths`).\n const baseBranches: Record<string, string> = {};\n\n for (const alias of repoAliases) {\n const repoPath = config.repos[alias];\n const repoName = path.basename(repoPath);\n const subWorktreePath = path.join(groupWorktreePath, repoName);\n const repoBase = baseForAlias(spec, alias);\n\n report('step', `[${alias}] (${repoName}):`);\n const success = createSingleWorktree(\n repoPath,\n subWorktreePath,\n opts.checkoutFor?.[alias] ?? branchName,\n config,\n repoBase,\n opts.pull !== false,\n );\n\n if (success) {\n createdWorktrees.push({ repoPath, worktreePath: subWorktreePath });\n if (repoBase) baseBranches[subWorktreePath] = repoBase;\n } else {\n // Rollback\n report('info', '');\n report('warn', 'Rolling back created worktrees due to failure...');\n for (const wt of createdWorktrees) {\n removeSingleWorktree(wt.repoPath, wt.worktreePath, branchName, true);\n }\n try {\n if (fs.readdirSync(groupWorktreePath).length === 0) {\n fs.rmSync(groupWorktreePath, { recursive: true, force: true });\n }\n } catch {\n /* */\n }\n report('error', 'Failed to create group worktree. Changes have been rolled back.');\n return null;\n }\n }\n\n // Copy the group's instructions file, under the name its agent reads (CLAUDE.md, AGENTS.md…).\n const configDir = getConfigDir();\n const claudeMdSrc = path.join(configDir, `${groupName}.claude.md`);\n const instructionsFile = agentFor(config, findSession(loadHistory(), groupName, branchName)).instructionsFile;\n const claudeMdDest = path.join(groupWorktreePath, instructionsFile);\n\n if (fs.existsSync(claudeMdSrc)) {\n fs.copyFileSync(claudeMdSrc, claudeMdDest);\n report('info', '');\n report('success', `Copied the group's ${instructionsFile} to the worktree root`);\n } else {\n report('info', '');\n report('warn', `Warning: the group's ${instructionsFile} not found at ${claudeMdSrc}`);\n report('warn', `Run 'work config regengroup ${groupName}' to generate it.`);\n }\n\n const allPaths = createdWorktrees.map((wt) => wt.worktreePath);\n // Representative base for the single-line \"vs X\" badge: the explicit\n // default, else a per-repo value only when every repo shares it.\n const distinctBases = [...new Set(Object.values(baseBranches))];\n const representativeBase = spec.default ?? (distinctBases.length === 1 ? distinctBases[0] : undefined);\n const { port } = await upsertSessionWithPort(groupName, true, branchName, allPaths, config, jiraKey, representativeBase, baseBranches);\n\n report('info', '');\n report('info', `Branch: ${branchName}`);\n if (port !== undefined) report('detail', `Dev-server port: ${port}`);\n\n return { launchDir: groupWorktreePath, paths: allPaths, isGroup: true, port };\n}\n\nasync function setupSingleWorktree(\n targetName: string,\n branchName: string,\n workTreeDirName: string,\n config: WorkConfig,\n spec: BaseSpec,\n jiraKey?: string,\n opts: WorktreeSetupOptions = {},\n): Promise<WorktreeSetupResult | null> {\n const repoPath = config.repos[targetName];\n const repoName = path.basename(repoPath);\n let workTreePath = path.join(config.worktreesRoot, repoName, workTreeDirName);\n\n // For a single repo, the only valid per-repo override alias is the target.\n const unknownAliases = baseSpecOverrideAliases(spec).filter((a) => a !== targetName);\n if (unknownAliases.length > 0) {\n report('error', `--base names repo(s) other than '${targetName}': ${unknownAliases.join(', ')}`);\n return null;\n }\n const baseBranch = baseForAlias(spec, targetName);\n\n if (!fs.existsSync(repoPath)) {\n report('error', `Repository path does not exist: ${repoPath}`);\n return null;\n }\n\n // Check for existing worktree at any path\n const worktrees = parseWorktreeList(repoPath);\n const existing = worktrees.find((wt) => wt.branch === branchName && path.resolve(wt.path) !== path.resolve(repoPath));\n\n if (existing) {\n if (baseBranch) {\n report('error', `Cannot use --base: worktree for '${branchName}' already exists at ${existing.path}`);\n return null;\n }\n report('info', `Worktree already exists at: ${existing.path}`);\n workTreePath = existing.path;\n if (opts.pull !== false) pullLatestForBranch(workTreePath, branchName);\n } else {\n const success = createSingleWorktree(\n repoPath,\n workTreePath,\n opts.checkoutFor?.[targetName] ?? branchName,\n config,\n baseBranch,\n opts.pull !== false,\n );\n if (!success) return null;\n }\n\n const { port } = await upsertSessionWithPort(\n targetName,\n false,\n branchName,\n [workTreePath],\n config,\n jiraKey,\n baseBranch,\n baseBranch ? { [workTreePath]: baseBranch } : undefined,\n );\n\n report('info', `Branch: ${branchName}`);\n if (port !== undefined) report('detail', `Dev-server port: ${port}`);\n\n return { launchDir: workTreePath, paths: [workTreePath], isGroup: false, port };\n}\n\n/**\n * Remove all worktrees for a session and clean up.\n * Returns true if all worktrees were successfully removed.\n * When force=false, stops on uncommitted/unpushed changes.\n */\n/** For comparing folders: absolute, long-form (Windows 8.3 names expanded), `/`, case-folded. */\nconst normalizeWorktreePath = (p: string): string => {\n let full = path.resolve(p);\n try {\n full = fs.realpathSync.native(full);\n } catch {\n /* gone: compare as given */\n }\n return full.replace(/\\\\/g, '/').replace(/\\/$/, '').toLowerCase();\n};\n\nexport function teardownWorktree(\n target: string,\n isGroup: boolean,\n branch: string,\n config: WorkConfig,\n force: boolean = true,\n /** The session's folders, when the caller knows them: the worktree is the\n * one AT that folder, whatever branch is checked out there now (you may\n * have switched branches inside it). Without them, found by branch. */\n paths?: string[],\n): boolean {\n const workTreeDirName = branch.replace(/\\//g, '-');\n\n if (isGroup && config.groups[target]) {\n const aliases = config.groups[target];\n const groupWorktreePath = path.join(config.worktreesRoot, target, workTreeDirName);\n let allRemoved = true;\n\n for (const alias of aliases) {\n const repoPath = config.repos[alias];\n if (!repoPath) continue;\n const repoName = path.basename(repoPath);\n const subWorktreePath = path.join(groupWorktreePath, repoName);\n report('step', `[${alias}] (${repoName}):`);\n if (!removeSingleWorktree(repoPath, subWorktreePath, branch, force)) {\n allRemoved = false;\n }\n }\n\n // Clean up the group's instructions file (its agent's name) and empty parent dir\n const claudeMd = path.join(groupWorktreePath, agentFor(config, findSession(loadHistory(), target, branch)).instructionsFile);\n try {\n if (fs.existsSync(claudeMd)) fs.unlinkSync(claudeMd);\n } catch {\n /* */\n }\n try {\n if (fs.existsSync(groupWorktreePath) && fs.readdirSync(groupWorktreePath).length === 0) {\n fs.rmSync(groupWorktreePath, { recursive: true, force: true });\n report('success', `Cleaned up group directory: ${groupWorktreePath}`);\n }\n } catch {\n /* */\n }\n\n return allRemoved;\n } else {\n const repoPath = config.repos[target];\n if (repoPath) {\n const worktrees = parseWorktreeList(repoPath);\n const at = paths?.[0] ? normalizeWorktreePath(paths[0]) : null;\n const wt =\n (at ? worktrees.find((w) => normalizeWorktreePath(w.path) === at) : undefined) ?? worktrees.find((w) => w.branch === branch);\n if (wt) {\n return removeSingleWorktree(repoPath, wt.path, branch, force);\n }\n }\n report('warn', `No worktree found for branch '${branch}' in '${target}'.`);\n return false;\n }\n}\n\n/** What opening a repo's own checkout gave: the session it is, or why not. */\nexport type BaseCheckoutResult = { ok: true; repoPath: string; branch: string; dropped: string[] } | { ok: false; error: string };\n\n/**\n * Work on a repo's own checkout, on whatever branch it has (`work tree\n * <repo>` with no branch, or the New worktree dialog with the branch left\n * empty): no worktree, the session is the checkout itself. Pulls first\n * (unless `pull: false`), and drops the entries recorded for this checkout\n * when it was on another branch — one session per checkout. A group has no\n * single checkout: it needs a branch.\n */\nexport async function openBaseCheckout(\n targetName: string,\n config: WorkConfig,\n opts: { pull?: boolean; jiraKey?: string; name?: string } = {},\n): Promise<BaseCheckoutResult> {\n const target = resolveProjectTarget(targetName, config);\n if (!target) return { ok: false, error: `Project or group not found: ${targetName}` };\n if (target.isGroup) return { ok: false, error: `${targetName} is a group: give it a branch (a group has no one checkout to open)` };\n const repoPath = config.repos[targetName];\n if (!repoPath) return { ok: false, error: `Repository path not configured for: ${targetName}` };\n if (!fs.existsSync(repoPath)) return { ok: false, error: `Repository path does not exist: ${repoPath}` };\n const branch = getCurrentBranch(repoPath) ?? '(detached)';\n // Detached HEAD has no upstream to pull from — skip rather than warn.\n if (opts.pull !== false && branch && branch !== '(detached)') pullLatestForBranch(repoPath, branch);\n await upsertSession(targetName, false, branch, [repoPath], opts.jiraKey);\n if (opts.name?.trim()) await setSessionTitle(targetName, branch, opts.name);\n const dropped = await forgetOtherBaseCheckoutEntries(targetName, branch, repoPath);\n return { ok: true, repoPath, branch, dropped };\n}\n","import path from 'node:path';\nimport type { WorkConfig } from '../platform/config.js';\nimport type { WorktreeSession } from '../sessions/history.js';\nimport { archiveDirFor, archiveRoot, readArchive, writeArchiveRecord } from './session-archive.js';\nimport { restoreUncommitted } from './archive-uncommitted.js';\nimport { sessionIdFor } from '../sessions/session-id.js';\nimport { report } from '../platform/report.js';\n\n/**\n * Restore of an archived session whose worktree was removed: put back the\n * uncommitted work archiving saved (archive-uncommitted.ts), once. A repo\n * whose save was put back, or couldn't be, isn't tried again — a later\n * `work tree` into it must not bring old changes back over newer work. What\n * couldn't be put back says where it is (its ref and patch stay).\n */\nexport async function restoreArchivedUncommitted(\n s: WorktreeSession,\n config: WorkConfig,\n root = archiveRoot(),\n): Promise<{ restored: string[]; failed: Array<{ repo: string; error: string }> }> {\n const id = sessionIdFor(s);\n const rec = readArchive(id, root);\n const out = { restored: [] as string[], failed: [] as Array<{ repo: string; error: string }> };\n if (!rec?.worktreeRemoved || !rec.uncommitted) return out;\n const dir = archiveDirFor(id, root);\n const now = new Date().toISOString();\n let changed = false;\n for (const [alias, saved] of Object.entries(rec.uncommitted)) {\n if (saved.restoredAt || saved.restoreError) continue;\n const wt = worktreeFor(s, alias, config);\n const r = wt ? await restoreUncommitted(wt, saved, dir) : { ok: false as const, error: `no worktree of ${alias} in the session` };\n if (r.ok) {\n saved.restoredAt = now;\n out.restored.push(alias);\n report('info', `${alias}: put back ${saved.files} uncommitted file${saved.files === 1 ? '' : 's'} saved when it was archived`);\n } else {\n saved.restoreError = r.error;\n out.failed.push({ repo: alias, error: r.error });\n report('warn', `${alias}: its uncommitted changes from the archive weren't put back: ${r.error}`);\n }\n changed = true;\n }\n if (changed) writeArchiveRecord(rec, root);\n return out;\n}\n\n/** The session's worktree of a repo: its only path, or (a group) the one named after the repo's folder. */\nfunction worktreeFor(s: WorktreeSession, alias: string, config: WorkConfig): string | null {\n if (!s.isGroup) return s.paths[0] ?? null;\n const repo = config.repos[alias];\n if (!repo) return null;\n const name = path.basename(repo).toLowerCase();\n return s.paths.find((p) => path.basename(p).toLowerCase() === name) ?? null;\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\nimport { globSync } from 'glob';\nimport { report } from '../platform/report.js';\n\n/** Directories to exclude when copying files. */\nconst EXCLUDED_DIRS = ['bin', 'obj', 'node_modules', '.git'];\n\n/**\n * Copy files matching configured patterns from a source repo into a worktree.\n * Handles .claude directory specially (direct path match).\n * Other patterns use recursive glob with exclusion filtering.\n */\nexport function copyConfigFiles(repoPath: string, worktreePath: string, patterns: string[]): void {\n for (const pattern of patterns) {\n // Normalize pattern separators to forward slashes for glob\n const normalized = pattern.replace(/\\\\/g, '/');\n\n // Handle .claude directory specially (direct path match)\n if (normalized.startsWith('.claude/')) {\n const relativePath = normalized;\n const sourcePath = path.join(repoPath, relativePath);\n\n if (fs.existsSync(sourcePath)) {\n const destPath = path.join(worktreePath, relativePath);\n const destDir = path.dirname(destPath);\n fs.mkdirSync(destDir, { recursive: true });\n fs.copyFileSync(sourcePath, destPath);\n report('info', ` Copied: ${relativePath}`);\n }\n continue;\n }\n\n // Use glob for pattern matching (recursive)\n const matches = globSync(`**/${normalized}`, {\n cwd: repoPath,\n nodir: true,\n posix: true,\n dot: true,\n });\n\n for (const match of matches) {\n // Check exclusion directories\n const parts = match.split('/');\n if (parts.some((p) => EXCLUDED_DIRS.includes(p))) {\n continue;\n }\n\n const sourcePath = path.join(repoPath, match);\n const destPath = path.join(worktreePath, match);\n const destDir = path.dirname(destPath);\n\n fs.mkdirSync(destDir, { recursive: true });\n fs.copyFileSync(sourcePath, destPath);\n report('info', ` Copied: ${match}`);\n }\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAo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,OAAO,OAAO,GAAG,UAAU,sEAAsE;AAClI,QAAM,WAAW,OAAO,MAAM,UAAU;AACxC,MAAI,CAAC,SAAU,QAAO,EAAE,IAAI,OAAO,OAAO,uCAAuC,UAAU,GAAG;AAC9F,MAAI,CAACA,IAAG,WAAW,QAAQ,EAAG,QAAO,EAAE,IAAI,OAAO,OAAO,mCAAmC,QAAQ,GAAG;AACvG,QAAM,SAAS,iBAAiB,QAAQ,KAAK;AAE7C,MAAI,KAAK,SAAS,SAAS,UAAU,WAAW,aAAc,qBAAoB,UAAU,MAAM;AAClG,QAAM,cAAc,YAAY,OAAO,QAAQ,CAAC,QAAQ,GAAG,KAAK,OAAO;AACvE,MAAI,KAAK,MAAM,KAAK,EAAG,OAAM,gBAAgB,YAAY,QAAQ,KAAK,IAAI;AAC1E,QAAM,UAAU,MAAM,+BAA+B,YAAY,QAAQ,QAAQ;AACjF,SAAO,EAAE,IAAI,MAAM,UAAU,QAAQ,QAAQ;AAC/C;","names":["fs","path","path","path","path","fs"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/commands/move.ts","../src/core/move/move.ts"],"sourcesContent":["import path from 'node:path';\nimport chalk from 'chalk';\nimport type { CommandModule } from 'yargs';\nimport { exportBundle, importBundle, MoveError, runningHere, unsavedWork } from '../core/move/move.js';\nimport { loadHistory } from '../core/sessions/history.js';\n\n/**\n * `work move export <dir>` / `work move import <dir>` — take your sessions,\n * conversations and setup to another computer (core/move/move.ts).\n */\nexport const moveCommand: CommandModule = {\n command: 'move <action> <dir>',\n describe: 'Move work to another computer: export a bundle here, import it there',\n builder: (y) =>\n y\n .positional('action', { choices: ['export', 'import'] as const, describe: 'export a bundle here, or import one' })\n .positional('dir', { type: 'string', describe: 'The bundle folder (new for export)' })\n .option('force', { type: 'boolean', describe: 'export: even with work not pushed; import: replace the sessions here' })\n .option('repos-root', { type: 'string', describe: 'import: where the repos are on this computer (each in its folder name)' })\n .option('worktrees-root', { type: 'string', describe: 'import: where worktrees go on this computer' })\n .option('clone', { type: 'boolean', describe: \"import: clone repos that aren't here from their origin\" }),\n handler: async (argv) => {\n const dir = path.resolve(argv.dir as string);\n try {\n if (argv.action === 'export') {\n const unsaved = await unsavedWork(loadHistory());\n if (unsaved.length) {\n console.log(chalk.yellow(\"Work that's only on this computer (the other one gets worktrees from origin):\"));\n for (const u of unsaved) console.log(` ${u.session}: ${u.what} ${chalk.gray(u.path)}`);\n if (!argv.force) {\n console.log(chalk.gray('Commit and push it (or ask its Claude), then export again — or --force to leave it behind.'));\n process.exitCode = 1;\n return;\n }\n }\n const r = exportBundle(dir);\n console.log(chalk.green(`Exported ${r.sessions} session(s) and ${r.transcripts} conversation file(s) to ${r.dir}`));\n console.log(chalk.gray('Copy the folder to the other computer and run `work move import <folder>` there (with work web stopped).'));\n return;\n }\n const running = await runningHere();\n if (running.length) {\n console.error(chalk.red(`Stop ${running.join(' and ')} first: an import replaces the database they hold.`));\n process.exitCode = 1;\n return;\n }\n const r = await importBundle(dir, {\n force: argv.force === true,\n clone: argv.clone === true,\n reposRoot: typeof argv['repos-root'] === 'string' ? path.resolve(argv['repos-root']) : undefined,\n worktreesRoot: typeof argv['worktrees-root'] === 'string' ? path.resolve(argv['worktrees-root']) : undefined,\n });\n console.log(chalk.green(`Imported ${r.sessions} session(s); ${r.transcripts} conversation file(s) put back for Claude.`));\n if (r.repos.cloned.length) console.log(`Cloned: ${r.repos.cloned.join(', ')}`);\n if (r.repos.missing.length)\n console.log(chalk.yellow(`Not on this computer: ${r.repos.missing.join(', ')} — clone them (or run again with --clone).`));\n if (r.worktrees.created.length) console.log(`Worktrees recreated: ${r.worktrees.created.join(', ')}`);\n for (const f of r.worktrees.failed) console.log(chalk.yellow(` ${f.session}: ${f.error}`));\n console.log(chalk.gray('Start `work web`: sessions resume their conversations when you open them.'));\n } catch (err) {\n if (!(err instanceof MoveError)) throw err;\n console.error(chalk.red(err.message));\n process.exitCode = 1;\n }\n },\n};\n","import fs from 'node:fs';\nimport os from 'node:os';\nimport path from 'node:path';\nimport { getConfigDir, getConfigPath, loadConfig } from '../platform/config.js';\nimport { replaceDb, snapshotDb, withDb } from '../platform/db.js';\nimport { atomicWriteFile } from '../platform/fs-safe.js';\nimport { loadHistory, saveHistory, type WorktreeSession } from '../sessions/history.js';\nimport { sessionIdFor } from '../sessions/session-id.js';\nimport { agentOf } from '../agents/index.js';\nimport { originUrl } from '../worktree/repo-scan.js';\nimport { defaultRunner, type CommandRunner } from '../pr/ship.js';\nimport { createInProcess, type CreateWorktree } from '../worktree/setup-child.js';\nimport { readWebUrl, webServerResponds } from '../platform/web-discovery.js';\nimport { findHost } from '../pty/pty-host-client.js';\n\n/**\n * Moving work to another computer (`work move export` / `import`). A bundle\n * is a folder you carry over (OneDrive, a USB stick): a snapshot of\n * state.db, config.json, work's own conversation copies and archives, the\n * groups' instruction files, every live session's agent transcripts, and a\n * manifest with each repo's origin. Never `~/.work` itself live in a synced\n * folder: syncing a database corrupts it, and two computers would both run\n * the PR and Jira watches.\n *\n * Import writes it all back with paths moved to the new computer (another\n * home folder, or other repo / worktree roots), clones repos that aren't\n * there (`--clone`), recreates live sessions' worktrees from their branches\n * on origin — so export first checks nothing is uncommitted or unpushed —\n * and puts the transcripts back where the agent looks, so conversations\n * resume. Checkpoint refs and wd's own review scopes stay behind (they live\n * in the old repos, keyed by old paths).\n */\n\nexport const BUNDLE_VERSION = 1;\n\nexport interface MoveManifest {\n version: number;\n exportedAt: string;\n from: { home: string; platform: string; worktreesRoot: string };\n /** Each repo's folder and origin URL, so a missing one can be cloned. */\n repos: Record<string, { path: string; origin: string | null }>;\n sessions: Array<{ id: string; target: string; branch: string; archived: boolean; transcripts: number }>;\n}\n\n/** A refusal, in words for the CLI. */\nexport class MoveError extends Error {}\n\nconst exists = (p: string) => fs.existsSync(p);\n\n// ---- before export: what wouldn't survive the move -------------------------------\n\nexport interface Unsaved {\n session: string;\n repo: string;\n path: string;\n what: string;\n}\n\n/**\n * Work only this computer has, per live session's repo: uncommitted files,\n * commits not on origin. Import recreates worktrees from origin, so these\n * would stay behind.\n */\nexport async function unsavedWork(sessions: WorktreeSession[], run: CommandRunner = defaultRunner): Promise<Unsaved[]> {\n const out: Unsaved[] = [];\n for (const s of sessions) {\n if (s.archivedAt) continue;\n for (const p of s.paths) {\n if (!exists(p)) continue;\n const at = { session: `${s.target} · ${s.branch || '(its checkout)'}`, repo: s.isGroup ? path.basename(p) : s.target, path: p };\n const status = await run('git', ['status', '--porcelain'], p);\n const dirty = status.code === 0 ? status.stdout.split('\\n').filter((l) => l.trim()).length : 0;\n if (dirty) out.push({ ...at, what: `${dirty} uncommitted file${dirty === 1 ? '' : 's'}` });\n const branch = (await run('git', ['rev-parse', '--abbrev-ref', 'HEAD'], p)).stdout.trim();\n if (!branch || branch === 'HEAD') continue;\n const onOrigin = (await run('git', ['rev-parse', '--verify', '--quiet', `refs/remotes/origin/${branch}`], p)).code === 0;\n const against = onOrigin ? `origin/${branch}` : 'origin/HEAD';\n const ahead = Number((await run('git', ['rev-list', '--count', `${against}..HEAD`], p)).stdout.trim()) || 0;\n if (ahead)\n out.push({ ...at, what: `${ahead} commit${ahead === 1 ? '' : 's'} not pushed${onOrigin ? '' : ` (${branch} isn't on origin)`}` });\n }\n }\n return out;\n}\n\n// ---- export ------------------------------------------------------------------------\n\nexport interface ExportResult {\n dir: string;\n sessions: number;\n transcripts: number;\n}\n\n/** Write the bundle into `dest` (a new or empty folder). */\nexport function exportBundle(dest: string, now = new Date()): ExportResult {\n if (exists(dest) && fs.readdirSync(dest).length) throw new MoveError(`${dest} isn't empty: give a new folder`);\n const home = getConfigDir();\n const config = loadConfig();\n if (!config) throw new MoveError('nothing to move: work has no config here');\n fs.mkdirSync(dest, { recursive: true });\n snapshotDb(path.join(dest, 'state.db'));\n fs.copyFileSync(getConfigPath(), path.join(dest, 'config.json'));\n for (const dir of ['conversations', 'archive']) {\n if (exists(path.join(home, dir))) fs.cpSync(path.join(home, dir), path.join(dest, dir), { recursive: true });\n }\n for (const f of fs.readdirSync(home).filter((n) => n.endsWith('.claude.md'))) {\n fs.mkdirSync(path.join(dest, 'instructions'), { recursive: true });\n fs.copyFileSync(path.join(home, f), path.join(dest, 'instructions', f));\n }\n\n const history = loadHistory();\n let transcripts = 0;\n const sessions: MoveManifest['sessions'] = [];\n for (const s of history) {\n const id = sessionIdFor(s);\n // An archived session's conversation is in its archive already.\n const files = s.archivedAt ? [] : (agentOf(s).conversation?.files(s) ?? []);\n for (const f of files) {\n fs.mkdirSync(path.join(dest, 'transcripts', id), { recursive: true });\n fs.copyFileSync(f.file, path.join(dest, 'transcripts', id, path.basename(f.file)));\n }\n transcripts += files.length;\n sessions.push({ id, target: s.target, branch: s.branch, archived: !!s.archivedAt, transcripts: files.length });\n }\n const repos: MoveManifest['repos'] = {};\n for (const [alias, p] of Object.entries(config.repos)) {\n let origin: string | null = null;\n try {\n origin = originUrl(fs.readFileSync(path.join(p, '.git', 'config'), 'utf-8'));\n } catch {\n /* not there, or not a plain repo */\n }\n repos[alias] = { path: p, origin };\n }\n const manifest: MoveManifest = {\n version: BUNDLE_VERSION,\n exportedAt: now.toISOString(),\n from: { home: os.homedir(), platform: process.platform, worktreesRoot: config.worktreesRoot },\n repos,\n sessions,\n };\n fs.writeFileSync(path.join(dest, 'manifest.json'), JSON.stringify(manifest, null, 2));\n return { dir: dest, sessions: history.length, transcripts };\n}\n\n// ---- paths on the new computer (pure) ---------------------------------------------\n\nexport interface PathRule {\n from: string;\n to: string;\n}\n\nconst norm = (p: string, caseless: boolean) => {\n const n = p.replace(/\\\\/g, '/').replace(/\\/+$/, '');\n return caseless ? n.toLowerCase() : n;\n};\n\n/**\n * Where things go: the worktrees root and each repo to the folders given\n * (`--worktrees-root`, `--repos-root` + its folder name), else the same\n * place under the new home folder; anything else under the old home moves\n * with it. Longest first, so the most specific rule wins. Pure.\n */\nexport function remapRules(\n m: Pick<MoveManifest, 'from' | 'repos'>,\n opts: { reposRoot?: string; worktreesRoot?: string },\n newHome: string,\n join: (...parts: string[]) => string = path.join,\n): PathRule[] {\n const caseless = m.from.platform === 'win32';\n const homeSwap = (p: string) => remapPath(p, [{ from: m.from.home, to: newHome }], caseless, join);\n const base = (p: string) =>\n p\n .replace(/[\\\\/]+$/, '')\n .split(/[\\\\/]/)\n .pop() ?? p;\n const rules: PathRule[] = [\n { from: m.from.worktreesRoot, to: opts.worktreesRoot ?? homeSwap(m.from.worktreesRoot) },\n ...Object.values(m.repos).map((r) => ({ from: r.path, to: opts.reposRoot ? join(opts.reposRoot, base(r.path)) : homeSwap(r.path) })),\n { from: m.from.home, to: newHome },\n ];\n return rules.sort((a, b) => b.from.length - a.from.length);\n}\n\n/** `p` under the first rule whose folder holds it, written for this computer; unchanged when none does. Pure. */\nexport function remapPath(p: string, rules: PathRule[], caseless: boolean, join: (...parts: string[]) => string = path.join): string {\n const key = norm(p, caseless);\n for (const r of rules) {\n const from = norm(r.from, caseless);\n if (key !== from && !key.startsWith(`${from}/`)) continue;\n const rest = p.replace(/\\\\/g, '/').slice(from.length).split('/').filter(Boolean);\n return rest.length ? join(r.to, ...rest) : r.to;\n }\n return p;\n}\n\n/** A session with its paths (and per-repo bases, keyed by path) moved. Pure. */\nexport function remapSession(s: WorktreeSession, move: (p: string) => string): WorktreeSession {\n const out: WorktreeSession = { ...s, paths: s.paths.map(move) };\n if (s.baseBranches) out.baseBranches = Object.fromEntries(Object.entries(s.baseBranches).map(([p, b]) => [move(p), b]));\n return out;\n}\n\n// ---- import ------------------------------------------------------------------------\n\n/**\n * What holds the database open here and must stop before an import replaces\n * it: work web, the PTY host. A host that doesn't answer counts as running.\n */\nexport async function runningHere(): Promise<string[]> {\n const out: string[] = [];\n const url = readWebUrl();\n if (url && (await webServerResponds(url))) out.push('work web (`work web --stop`)');\n try {\n if (await findHost()) out.push('the PTY host (`work pty-host --stop`)');\n } catch {\n out.push('the PTY host (`work pty-host --stop`)');\n }\n return out;\n}\n\nexport function readManifest(dir: string): MoveManifest {\n let raw: unknown;\n try {\n raw = JSON.parse(fs.readFileSync(path.join(dir, 'manifest.json'), 'utf-8'));\n } catch {\n throw new MoveError(`${dir} isn't a work bundle (no manifest.json): make one with \\`work move export\\``);\n }\n const m = raw as MoveManifest;\n if (!m || typeof m !== 'object' || typeof m.from?.home !== 'string' || typeof m.repos !== 'object')\n throw new MoveError(`${dir}/manifest.json isn't one work can read`);\n if (m.version > BUNDLE_VERSION) throw new MoveError(`this bundle is from a newer work (v${m.version}): update work first`);\n if (!exists(path.join(dir, 'state.db')) || !exists(path.join(dir, 'config.json')))\n throw new MoveError(`${dir} is missing state.db or config.json`);\n return m;\n}\n\nexport interface ImportOptions {\n reposRoot?: string;\n worktreesRoot?: string;\n /** Clone repos that aren't on this computer, from their origin. */\n clone?: boolean;\n /** Replace what this computer has already. */\n force?: boolean;\n}\n\nexport interface ImportReport {\n sessions: number;\n repos: { cloned: string[]; missing: string[] };\n worktrees: { created: string[]; failed: Array<{ session: string; error: string }> };\n transcripts: number;\n}\n\nexport interface ImportDeps {\n run: CommandRunner;\n create: CreateWorktree;\n /** Where a session's agent looks for its conversations (null: it starts fresh). */\n restoreDir: (s: WorktreeSession) => string | null;\n}\n\nconst defaultImportDeps = (): ImportDeps => ({\n run: defaultRunner,\n create: createInProcess,\n restoreDir: (s) => agentOf(s).conversation?.restoreDir?.(s) ?? null,\n});\n\n/** Bring a bundle in. The caller makes sure no work web or PTY host runs (they hold the database). */\nexport async function importBundle(dir: string, opts: ImportOptions = {}, deps: ImportDeps = defaultImportDeps()): Promise<ImportReport> {\n const m = readManifest(dir);\n if (!opts.force && exists(getConfigPath()) && loadHistory().length)\n throw new MoveError('work here has sessions already; importing replaces them (--force to do it anyway)');\n const caseless = m.from.platform === 'win32';\n const rules = remapRules(m, opts, os.homedir());\n const move = (p: string) => remapPath(p, rules, caseless);\n\n // config.json, as JSON: keys this version doesn't know come along.\n const raw = JSON.parse(fs.readFileSync(path.join(dir, 'config.json'), 'utf-8')) as Record<string, unknown>;\n if (typeof raw.worktreesRoot === 'string') raw.worktreesRoot = move(raw.worktreesRoot);\n if (raw.repos && typeof raw.repos === 'object')\n raw.repos = Object.fromEntries(\n Object.entries(raw.repos as Record<string, unknown>).map(([a, p]) => [a, typeof p === 'string' ? move(p) : p]),\n );\n for (const key of ['scanRoots', 'ignoredRepos'])\n if (Array.isArray(raw[key])) raw[key] = (raw[key] as unknown[]).map((p) => (typeof p === 'string' ? move(p) : p));\n fs.mkdirSync(getConfigDir(), { recursive: true });\n atomicWriteFile(getConfigPath(), JSON.stringify(raw, null, 2));\n\n // The database, then its sessions' paths. Its Claudes start when you open them here.\n replaceDb(path.join(dir, 'state.db'));\n const history = loadHistory().map((s) => remapSession(s, move));\n saveHistory(history);\n withDb((d) => d.prepare('DELETE FROM pty_sessions').run());\n\n // work's own files.\n for (const sub of ['conversations', 'archive'])\n if (exists(path.join(dir, sub))) fs.cpSync(path.join(dir, sub), path.join(getConfigDir(), sub), { recursive: true, force: false });\n if (exists(path.join(dir, 'instructions')))\n for (const f of fs.readdirSync(path.join(dir, 'instructions')))\n fs.copyFileSync(path.join(dir, 'instructions', f), path.join(getConfigDir(), f));\n\n const report: ImportReport = {\n sessions: history.length,\n repos: { cloned: [], missing: [] },\n worktrees: { created: [], failed: [] },\n transcripts: 0,\n };\n const config = loadConfig()!;\n for (const [alias, p] of Object.entries(config.repos)) {\n if (exists(p)) continue;\n const origin = m.repos[alias]?.origin;\n if (opts.clone && origin) {\n fs.mkdirSync(path.dirname(p), { recursive: true });\n const r = await deps.run('git', ['clone', origin, p], path.dirname(p));\n if (r.code === 0) {\n report.repos.cloned.push(alias);\n continue;\n }\n }\n report.repos.missing.push(alias);\n }\n\n // Live sessions get their worktrees back, from their branches on origin.\n const missing = new Set(report.repos.missing);\n for (const s of history) {\n if (s.archivedAt || !s.branch || s.paths.every(exists)) continue;\n const label = `${s.target} · ${s.branch}`;\n const repos = s.isGroup ? (config.groups[s.target] ?? []) : [s.target];\n if (repos.some((r) => missing.has(r))) {\n report.worktrees.failed.push({ session: label, error: `its repo isn't here (${repos.filter((r) => missing.has(r)).join(', ')})` });\n continue;\n }\n // A repo's own checkout (`work tree <repo>`) comes with the repo.\n if (!s.isGroup && config.repos[s.target] && s.paths[0] === config.repos[s.target]) continue;\n const r = await deps.create({ target: s.target, branch: s.branch }, config);\n if (r.ok) report.worktrees.created.push(label);\n else report.worktrees.failed.push({ session: label, error: r.error });\n }\n\n // Conversations back where the agent looks, so they resume.\n for (const s of loadHistory()) {\n const from = path.join(dir, 'transcripts', sessionIdFor(s));\n const to = exists(from) ? deps.restoreDir(s) : null;\n if (!to) continue;\n fs.mkdirSync(to, { recursive: true });\n for (const f of fs.readdirSync(from)) {\n if (exists(path.join(to, f))) continue;\n fs.copyFileSync(path.join(from, f), path.join(to, f));\n report.transcripts++;\n }\n }\n return report;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,OAAOA,WAAU;AACjB,OAAO,WAAW;;;ACDlB,OAAO,QAAQ;AACf,OAAO,QAAQ;AACf,OAAO,UAAU;AA+BV,IAAM,iBAAiB;AAYvB,IAAM,YAAN,cAAwB,MAAM;AAAC;AAEtC,IAAM,SAAS,CAAC,MAAc,GAAG,WAAW,CAAC;AAgB7C,eAAsB,YAAY,UAA6B,MAAqB,eAAmC;AACrH,QAAM,MAAiB,CAAC;AACxB,aAAW,KAAK,UAAU;AACxB,QAAI,EAAE,WAAY;AAClB,eAAW,KAAK,EAAE,OAAO;AACvB,UAAI,CAAC,OAAO,CAAC,EAAG;AAChB,YAAM,KAAK,EAAE,SAAS,GAAG,EAAE,MAAM,SAAM,EAAE,UAAU,gBAAgB,IAAI,MAAM,EAAE,UAAU,KAAK,SAAS,CAAC,IAAI,EAAE,QAAQ,MAAM,EAAE;AAC9H,YAAM,SAAS,MAAM,IAAI,OAAO,CAAC,UAAU,aAAa,GAAG,CAAC;AAC5D,YAAM,QAAQ,OAAO,SAAS,IAAI,OAAO,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,IAAI,wBAAwB,EAAE,UAAU,QAAQ,KAAK,IAAI,CAAC,EAAE;AACpG,iBAAW,KAAK,EAAE,UAAU,OAAQ,SAAQ,IAAI,MAAM,OAAO,KAAK,EAAE,OAAO,KAAK,EAAE,KAAK,EAAE,CAAC;AAC1F,cAAQ,IAAI,MAAM,KAAK,2EAA2E,CAAC;AAAA,IACrG,SAAS,KAAK;AACZ,UAAI,EAAE,eAAe,WAAY,OAAM;AACvC,cAAQ,MAAM,MAAM,IAAI,IAAI,OAAO,CAAC;AACpC,cAAQ,WAAW;AAAA,IACrB;AAAA,EACF;AACF;","names":["path","r","path","r"]}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/commands/tree.ts"],"sourcesContent":["import fs from 'node:fs';\nimport { agentFor } from '../core/agents/index.js';\nimport chalk from 'chalk';\nimport type { CommandModule } from 'yargs';\nimport { ensureConfig } from '../core/platform/config.js';\nimport { resolveProjectTarget, getAllTargetNames, resolveFromCwd } from '../core/worktree/resolve.js';\nimport { openBaseCheckout, setupWorktree } from '../core/worktree/worktree.js';\nimport { findSession, loadHistory, recordLaunch } from '../core/sessions/history.js';\nimport { attachSession } from './shared/attach-session.js';\nimport { openVSCode, launchAi } from '../core/platform/launch.js';\nimport { parseBaseSpec, isEmptyBaseSpec, BaseSpecError } from '../core/git/base-spec.js';\n\nexport const treeCommand: CommandModule = {\n command: ['tree [target] [branch]', 't [target] [branch]'],\n describe: 'Create or switch to a worktree and launch the configured AI tool',\n builder: (yargs) =>\n yargs\n .showHelpOnFail(true)\n .positional('target', {\n describe: 'Project alias or group name',\n type: 'string',\n })\n .positional('branch', {\n describe: 'Branch name (e.g., feature/login). Omit to work on the base repo.',\n type: 'string',\n })\n .option('here', {\n describe: 'Infer target and branch from the current worktree directory',\n type: 'boolean',\n default: false,\n })\n .option('open', {\n describe: 'Open VS Code in the worktree after creation',\n type: 'boolean',\n default: false,\n })\n .option('unsafe', {\n describe: 'Launch the AI tool with its skip-permissions flag (default: --dangerously-skip-permissions)',\n type: 'boolean',\n default: false,\n })\n .option('pull', {\n describe: 'Pull latest changes when switching into an existing worktree or the base repo. Use --no-pull to skip.',\n type: 'boolean',\n default: true,\n })\n .option('host', {\n describe:\n 'Run the AI session in the PTY host and attach this terminal to it (the default): it survives closing the tab, shows in `work web` — the same screen there and here — and restores after a reboot. Ctrl+] detaches. --no-host (or config `launchViaHost: false`) launches directly in this terminal instead.',\n type: 'boolean',\n })\n .option('fresh', {\n describe: 'Start a new AI conversation instead of continuing the previous one for this directory',\n type: 'boolean',\n default: false,\n })\n .option('base', {\n describe:\n 'Base branch to fork from instead of HEAD. Repeatable. Use a bare branch (--base dev) for all repos, or alias=branch (--base backend=dev --base frontend=feat/x) for per-repo bases in a group.',\n type: 'string',\n })\n .option('prompt', {\n describe: 'Initial prompt to send to the AI tool on startup',\n type: 'string',\n })\n .option('prompt-file', {\n describe: 'File containing the initial prompt (deleted after reading)',\n type: 'string',\n })\n .option('name', {\n describe: 'Name the session (shown instead of the branch; rename later with F2 in the dashboard)',\n type: 'string',\n })\n .option('jira-key', {\n describe: 'Link a Jira issue key to this worktree session',\n type: 'string',\n hidden: true,\n })\n .option('setup-only', {\n describe: 'Create worktree without launching the AI tool (used by dashboard)',\n type: 'boolean',\n default: false,\n hidden: true,\n }),\n handler: async (argv) => {\n let targetName = argv.target as string | undefined;\n let branchName = argv.branch as string | undefined;\n const here = argv.here as boolean;\n const open = argv.open as boolean;\n const unsafe = argv.unsafe as boolean;\n const pull = argv.pull as boolean;\n const fresh = argv.fresh as boolean;\n const setupOnly = argv['setup-only'] as boolean;\n let baseSpec;\n try {\n baseSpec = parseBaseSpec(argv.base as string | string[] | undefined);\n } catch (err) {\n if (err instanceof BaseSpecError) {\n console.error(err.message);\n process.exitCode = 1;\n return;\n }\n throw err;\n }\n const jiraKey = argv['jira-key'] as string | undefined;\n const promptFile = argv['prompt-file'] as string | undefined;\n let initialPrompt = argv.prompt as string | undefined;\n\n // --prompt-file takes precedence: read and delete the temp file\n if (promptFile) {\n try {\n initialPrompt = fs.readFileSync(promptFile, 'utf-8');\n fs.unlinkSync(promptFile);\n } catch {\n // ignore — fall through to --prompt or no prompt\n }\n }\n\n const config = ensureConfig();\n // Via the host unless told otherwise: one Claude that the terminal and\n // the dashboard both show. A direct launch is invisible to work web.\n const viaHost = (argv.host as boolean | undefined) ?? config.launchViaHost ?? true;\n\n /**\n * Launch the AI tool, continuing the previous conversation for this\n * directory when there is one. `--continue` errors out (\"No conversation\n * found to continue\") in a directory the tool has never run in, so the flag\n * is gated on an existing transcript.\n */\n const launchTool = async (dir: string, port: number | undefined, sessionKey: { target: string; branch: string }): Promise<void> => {\n recordLaunch(sessionKey.target, sessionKey.branch, { unsafe: !!unsafe });\n if (viaHost) {\n const session = findSession(loadHistory(), sessionKey.target, sessionKey.branch);\n if (session) {\n // The host decides --continue itself (the agent's own canResume\n // gate); `fresh` and the prompt ride along on the first spawn.\n process.exitCode = await attachSession(session, {\n unsafe,\n fresh,\n initialPrompt,\n forwardEnv: true,\n });\n return;\n }\n console.log(chalk.yellow('Session not found in history — launching directly instead of via the PTY host.'));\n }\n // The session's agent: what to run, and whether it can resume here.\n const agent = agentFor(config, findSession(loadHistory(), sessionKey.target, sessionKey.branch));\n const tool = agent.launch.tool(config);\n const resume = !fresh && agent.launch.canResume(dir);\n if (resume) {\n console.log(chalk.gray(`Continuing the previous ${tool.cmd} conversation (--fresh starts a new one).`));\n }\n console.log(`Starting ${tool.cmd}...`);\n launchAi(dir, tool, { unsafe, initialPrompt, resume }, port);\n };\n\n // --here: infer target and branch from the current worktree directory\n if (here) {\n if (targetName) {\n console.error('Cannot combine --here with an explicit target.');\n process.exitCode = 1;\n return;\n }\n const inferred = resolveFromCwd(config, process.cwd());\n if ('error' in inferred) {\n console.error(inferred.error);\n process.exitCode = 1;\n return;\n }\n targetName = inferred.target;\n branchName = inferred.isBaseRepo ? undefined : inferred.branch;\n console.log(chalk.cyan(`Resolved from current directory: ${targetName}${branchName ? ' @ ' + branchName : ' (base repo)'}`));\n } else if (!targetName) {\n console.error('Specify a target, or use --here to infer it from the current directory.');\n process.exitCode = 1;\n return;\n }\n\n // --base requires a branch name\n if (!isEmptyBaseSpec(baseSpec) && !branchName) {\n console.error('--base requires a branch name');\n console.log(chalk.yellow(`Usage: work tree ${targetName} <branch> --base <base>`));\n process.exitCode = 1;\n return;\n }\n\n // Resolve project target (for validation and base-repo handling)\n const target = resolveProjectTarget(targetName, config);\n if (!target) {\n const allNames = getAllTargetNames(config);\n console.error(`Project or group not found: ${targetName}`);\n console.log(chalk.yellow(`Available: ${allNames.join(', ')}`));\n console.log(chalk.yellow('Add a new project with: work config add <alias> <path>'));\n process.exitCode = 1;\n return;\n }\n\n // No branch specified — work directly on the base repo\n if (!branchName) {\n if (target.isGroup) {\n console.error('Branch is required for group targets.');\n console.log(chalk.yellow(`Usage: work tree ${targetName} <branch>`));\n process.exitCode = 1;\n return;\n }\n\n console.log(chalk.cyan(`Working on base repo: ${targetName}`));\n const opened = await openBaseCheckout(targetName, config, {\n pull,\n jiraKey,\n name: typeof argv.name === 'string' ? argv.name : undefined,\n });\n if (!opened.ok) {\n console.error(opened.error);\n process.exitCode = 1;\n return;\n }\n const { repoPath, branch: currentBranch } = opened;\n console.log(`Repo path: ${repoPath}`);\n if (opened.dropped.length) console.log(chalk.gray(`Replaced older entries for this checkout: ${opened.dropped.join(', ')}`));\n\n if (open) openVSCode(repoPath);\n if (!setupOnly) await launchTool(repoPath, undefined, { target: targetName, branch: currentBranch });\n return;\n }\n\n // Create/switch worktree via shared core logic\n const result = await setupWorktree(targetName, branchName, config, baseSpec, jiraKey, { pull, name: argv.name as string | undefined });\n if (!result) {\n process.exitCode = 1;\n return;\n }\n\n if (open) {\n for (const p of result.paths) {\n openVSCode(p);\n }\n }\n\n console.log(`Worktree path: ${result.launchDir}`);\n if (!setupOnly) {\n await launchTool(result.launchDir, result.port, { target: targetName, branch: branchName });\n }\n },\n};\n"],"mappings":";;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