@moberg_hr/work-tree 1.16.0 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (249) hide show
  1. package/README.md +56 -142
  2. package/dist/answer-2J4XLIP7.js +63 -0
  3. package/dist/answer-2J4XLIP7.js.map +1 -0
  4. package/dist/attach-CZKRNPAJ.js +59 -0
  5. package/dist/attach-CZKRNPAJ.js.map +1 -0
  6. package/dist/bin.js +26 -11924
  7. package/dist/bin.js.map +1 -1
  8. package/dist/block-RAIDCJ4F.js +84 -0
  9. package/dist/block-RAIDCJ4F.js.map +1 -0
  10. package/dist/broadcast-BSI5NDDB.js +104 -0
  11. package/dist/broadcast-BSI5NDDB.js.map +1 -0
  12. package/dist/catchup-VVOPL2S5.js +51 -0
  13. package/dist/catchup-VVOPL2S5.js.map +1 -0
  14. package/dist/chunk-3JWTO5VZ.js +135 -0
  15. package/dist/chunk-3JWTO5VZ.js.map +1 -0
  16. package/dist/chunk-4BOK2GXL.js +210 -0
  17. package/dist/chunk-4BOK2GXL.js.map +1 -0
  18. package/dist/chunk-5QK7GB5K.js +112 -0
  19. package/dist/chunk-5QK7GB5K.js.map +1 -0
  20. package/dist/chunk-6AQRYLOB.js +16 -0
  21. package/dist/chunk-6AQRYLOB.js.map +1 -0
  22. package/dist/chunk-6FTIY5M6.js +120 -0
  23. package/dist/chunk-6FTIY5M6.js.map +1 -0
  24. package/dist/chunk-6H3MLDGG.js +48 -0
  25. package/dist/chunk-6H3MLDGG.js.map +1 -0
  26. package/dist/chunk-77XFJQGC.js +103 -0
  27. package/dist/chunk-77XFJQGC.js.map +1 -0
  28. package/dist/chunk-7H4BJ2YA.js +308 -0
  29. package/dist/chunk-7H4BJ2YA.js.map +1 -0
  30. package/dist/chunk-7HEB6SQS.js +257 -0
  31. package/dist/chunk-7HEB6SQS.js.map +1 -0
  32. package/dist/chunk-7NAXFBFI.js +206 -0
  33. package/dist/chunk-7NAXFBFI.js.map +1 -0
  34. package/dist/chunk-7NCW3LUT.js +358 -0
  35. package/dist/chunk-7NCW3LUT.js.map +1 -0
  36. package/dist/chunk-7OLPI334.js +537 -0
  37. package/dist/chunk-7OLPI334.js.map +1 -0
  38. package/dist/chunk-ABQYKTG4.js +38 -0
  39. package/dist/chunk-ABQYKTG4.js.map +1 -0
  40. package/dist/chunk-AH5TM3NB.js +21 -0
  41. package/dist/chunk-AH5TM3NB.js.map +1 -0
  42. package/dist/chunk-AKMPF72Y.js +274 -0
  43. package/dist/chunk-AKMPF72Y.js.map +1 -0
  44. package/dist/chunk-C2BK6EBN.js +162 -0
  45. package/dist/chunk-C2BK6EBN.js.map +1 -0
  46. package/dist/chunk-C2THFSXA.js +37 -0
  47. package/dist/chunk-C2THFSXA.js.map +1 -0
  48. package/dist/chunk-CLGVSX36.js +668 -0
  49. package/dist/chunk-CLGVSX36.js.map +1 -0
  50. package/dist/chunk-CXEC5W5V.js +267 -0
  51. package/dist/chunk-CXEC5W5V.js.map +1 -0
  52. package/dist/chunk-DW4JPVXB.js +41 -0
  53. package/dist/chunk-DW4JPVXB.js.map +1 -0
  54. package/dist/chunk-FR3EWVXI.js +188 -0
  55. package/dist/chunk-FR3EWVXI.js.map +1 -0
  56. package/dist/chunk-H5LKMR45.js +117 -0
  57. package/dist/chunk-H5LKMR45.js.map +1 -0
  58. package/dist/chunk-HSICXDMZ.js +41 -0
  59. package/dist/chunk-HSICXDMZ.js.map +1 -0
  60. package/dist/chunk-HUXS3VAI.js +90 -0
  61. package/dist/chunk-HUXS3VAI.js.map +1 -0
  62. package/dist/chunk-HWUINPIL.js +151 -0
  63. package/dist/chunk-HWUINPIL.js.map +1 -0
  64. package/dist/chunk-IXKVCR4Y.js +487 -0
  65. package/dist/chunk-IXKVCR4Y.js.map +1 -0
  66. package/dist/chunk-JNBYNRFS.js +54 -0
  67. package/dist/chunk-JNBYNRFS.js.map +1 -0
  68. package/dist/chunk-JYTMT5DF.js +421 -0
  69. package/dist/chunk-JYTMT5DF.js.map +1 -0
  70. package/dist/chunk-KA4JVX5U.js +295 -0
  71. package/dist/chunk-KA4JVX5U.js.map +1 -0
  72. package/dist/chunk-KGZ6OZ2T.js +102 -0
  73. package/dist/chunk-KGZ6OZ2T.js.map +1 -0
  74. package/dist/chunk-LNHSBM4L.js +26 -0
  75. package/dist/chunk-LNHSBM4L.js.map +1 -0
  76. package/dist/chunk-M4FVCAT6.js +2406 -0
  77. package/dist/chunk-M4FVCAT6.js.map +1 -0
  78. package/dist/chunk-MAGGGRSB.js +9 -0
  79. package/dist/chunk-MAGGGRSB.js.map +1 -0
  80. package/dist/chunk-N4EYQKSM.js +104 -0
  81. package/dist/chunk-N4EYQKSM.js.map +1 -0
  82. package/dist/chunk-NDWSLQPB.js +112 -0
  83. package/dist/chunk-NDWSLQPB.js.map +1 -0
  84. package/dist/chunk-O3QTWVSK.js +323 -0
  85. package/dist/chunk-O3QTWVSK.js.map +1 -0
  86. package/dist/chunk-P3BL4EOP.js +37 -0
  87. package/dist/chunk-P3BL4EOP.js.map +1 -0
  88. package/dist/chunk-PN44M5EE.js +887 -0
  89. package/dist/chunk-PN44M5EE.js.map +1 -0
  90. package/dist/chunk-PZ4RG6EW.js +132 -0
  91. package/dist/chunk-PZ4RG6EW.js.map +1 -0
  92. package/dist/chunk-Q6WZCO45.js +47 -0
  93. package/dist/chunk-Q6WZCO45.js.map +1 -0
  94. package/dist/chunk-QBAZG4CY.js +230 -0
  95. package/dist/chunk-QBAZG4CY.js.map +1 -0
  96. package/dist/chunk-R2LN3JJJ.js +132 -0
  97. package/dist/chunk-R2LN3JJJ.js.map +1 -0
  98. package/dist/chunk-RCYI7SRA.js +15 -0
  99. package/dist/chunk-RCYI7SRA.js.map +1 -0
  100. package/dist/chunk-RYNBBSLY.js +67 -0
  101. package/dist/chunk-RYNBBSLY.js.map +1 -0
  102. package/dist/chunk-S5HJT7CM.js +30 -0
  103. package/dist/chunk-S5HJT7CM.js.map +1 -0
  104. package/dist/chunk-SNAQOHNL.js +285 -0
  105. package/dist/chunk-SNAQOHNL.js.map +1 -0
  106. package/dist/chunk-SOCPIHCS.js +181 -0
  107. package/dist/chunk-SOCPIHCS.js.map +1 -0
  108. package/dist/chunk-TUC4QY4O.js +147 -0
  109. package/dist/chunk-TUC4QY4O.js.map +1 -0
  110. package/dist/chunk-TUFQJXXO.js +19 -0
  111. package/dist/chunk-TUFQJXXO.js.map +1 -0
  112. package/dist/chunk-UFY7C5PP.js +90 -0
  113. package/dist/chunk-UFY7C5PP.js.map +1 -0
  114. package/dist/chunk-UQ35KLHH.js +34 -0
  115. package/dist/chunk-UQ35KLHH.js.map +1 -0
  116. package/dist/chunk-VJ7SVDED.js +177 -0
  117. package/dist/chunk-VJ7SVDED.js.map +1 -0
  118. package/dist/chunk-VJNSIDOA.js +23 -0
  119. package/dist/chunk-VJNSIDOA.js.map +1 -0
  120. package/dist/chunk-WF5SBVPZ.js +190 -0
  121. package/dist/chunk-WF5SBVPZ.js.map +1 -0
  122. package/dist/chunk-WMJIU3YW.js +29 -0
  123. package/dist/chunk-WMJIU3YW.js.map +1 -0
  124. package/dist/chunk-XJDEROHY.js +19 -0
  125. package/dist/chunk-XJDEROHY.js.map +1 -0
  126. package/dist/chunk-YKODIG22.js +221 -0
  127. package/dist/chunk-YKODIG22.js.map +1 -0
  128. package/dist/chunk-YLG6DO5Y.js +162 -0
  129. package/dist/chunk-YLG6DO5Y.js.map +1 -0
  130. package/dist/chunk-YNKWLC45.js +122 -0
  131. package/dist/chunk-YNKWLC45.js.map +1 -0
  132. package/dist/chunk-YZDD5YGE.js +165 -0
  133. package/dist/chunk-YZDD5YGE.js.map +1 -0
  134. package/dist/chunk-YZWADOEW.js +151 -0
  135. package/dist/chunk-YZWADOEW.js.map +1 -0
  136. package/dist/chunk-ZJN5RWZD.js +76 -0
  137. package/dist/chunk-ZJN5RWZD.js.map +1 -0
  138. package/dist/chunk-ZSHWP2VS.js +22 -0
  139. package/dist/chunk-ZSHWP2VS.js.map +1 -0
  140. package/dist/chunk-ZXPYWZL5.js +307 -0
  141. package/dist/chunk-ZXPYWZL5.js.map +1 -0
  142. package/dist/cleanup-X45MA74G.js +192 -0
  143. package/dist/cleanup-X45MA74G.js.map +1 -0
  144. package/dist/cli-52VWEHIQ.js +18 -0
  145. package/dist/cli-52VWEHIQ.js.map +1 -0
  146. package/dist/command-hook-installer-SGEJTZ2Y.js +204 -0
  147. package/dist/command-hook-installer-SGEJTZ2Y.js.map +1 -0
  148. package/dist/completion-MXX5TRIV.js +118 -0
  149. package/dist/completion-MXX5TRIV.js.map +1 -0
  150. package/dist/config-IEIU7A66.js +410 -0
  151. package/dist/config-IEIU7A66.js.map +1 -0
  152. package/dist/console-reporter-XU6VFUZE.js +10 -0
  153. package/dist/console-reporter-XU6VFUZE.js.map +1 -0
  154. package/dist/diff-K47HB6SA.js +582 -0
  155. package/dist/diff-K47HB6SA.js.map +1 -0
  156. package/dist/digest-FBZTBXQO.js +100 -0
  157. package/dist/digest-FBZTBXQO.js.map +1 -0
  158. package/dist/fork-BKI5UNNS.js +120 -0
  159. package/dist/fork-BKI5UNNS.js.map +1 -0
  160. package/dist/hook-SLMZT5OV.js +220 -0
  161. package/dist/hook-SLMZT5OV.js.map +1 -0
  162. package/dist/hydrate-Y2AAMZTA.js +121 -0
  163. package/dist/hydrate-Y2AAMZTA.js.map +1 -0
  164. package/dist/init-7ESFTYZC.js +187 -0
  165. package/dist/init-7ESFTYZC.js.map +1 -0
  166. package/dist/install-skills-O34BHFHD.js +14 -0
  167. package/dist/install-skills-O34BHFHD.js.map +1 -0
  168. package/dist/install-skills-bin.js +12 -0
  169. package/dist/install-skills-bin.js.map +1 -0
  170. package/dist/list-KEF73NLQ.js +126 -0
  171. package/dist/list-KEF73NLQ.js.map +1 -0
  172. package/dist/move-FKT2P5LY.js +313 -0
  173. package/dist/move-FKT2P5LY.js.map +1 -0
  174. package/dist/note-WGM6LCP2.js +78 -0
  175. package/dist/note-WGM6LCP2.js.map +1 -0
  176. package/dist/overlaps-FRLMMIGC.js +56 -0
  177. package/dist/overlaps-FRLMMIGC.js.map +1 -0
  178. package/dist/pin-MQ5ZE37R.js +45 -0
  179. package/dist/pin-MQ5ZE37R.js.map +1 -0
  180. package/dist/pr-YU3NOW6G.js +118 -0
  181. package/dist/pr-YU3NOW6G.js.map +1 -0
  182. package/dist/prune-26FYYFTO.js +92 -0
  183. package/dist/prune-26FYYFTO.js.map +1 -0
  184. package/dist/pty-host-RWIS55N4.js +826 -0
  185. package/dist/pty-host-RWIS55N4.js.map +1 -0
  186. package/dist/read-AP6T3ZGN.js +57 -0
  187. package/dist/read-AP6T3ZGN.js.map +1 -0
  188. package/dist/recent-IE3LYQ65.js +111 -0
  189. package/dist/recent-IE3LYQ65.js.map +1 -0
  190. package/dist/remove-2UHJQ4DY.js +108 -0
  191. package/dist/remove-2UHJQ4DY.js.map +1 -0
  192. package/dist/report-KM4OZCZB.js +16 -0
  193. package/dist/report-KM4OZCZB.js.map +1 -0
  194. package/dist/resume-UUP6R2IE.js +81 -0
  195. package/dist/resume-UUP6R2IE.js.map +1 -0
  196. package/dist/run-V4755W7C.js +263 -0
  197. package/dist/run-V4755W7C.js.map +1 -0
  198. package/dist/screen-DNX4K23V.js +58 -0
  199. package/dist/screen-DNX4K23V.js.map +1 -0
  200. package/dist/search-3JZXLCR2.js +46 -0
  201. package/dist/search-3JZXLCR2.js.map +1 -0
  202. package/dist/section-TXLC5XO3.js +79 -0
  203. package/dist/section-TXLC5XO3.js.map +1 -0
  204. package/dist/send-6X46WZLC.js +87 -0
  205. package/dist/send-6X46WZLC.js.map +1 -0
  206. package/dist/sessions-T3QDTNP7.js +135 -0
  207. package/dist/sessions-T3QDTNP7.js.map +1 -0
  208. package/dist/snooze-KYSFXLPY.js +65 -0
  209. package/dist/snooze-KYSFXLPY.js.map +1 -0
  210. package/dist/start-SQSDQK4F.js +56 -0
  211. package/dist/start-SQSDQK4F.js.map +1 -0
  212. package/dist/state-4DFV6SHG.js +147 -0
  213. package/dist/state-4DFV6SHG.js.map +1 -0
  214. package/dist/status-H5OW4LYE.js +118 -0
  215. package/dist/status-H5OW4LYE.js.map +1 -0
  216. package/dist/stop-HC7XPSSP.js +45 -0
  217. package/dist/stop-HC7XPSSP.js.map +1 -0
  218. package/dist/sync-3CTAXM6J.js +96 -0
  219. package/dist/sync-3CTAXM6J.js.map +1 -0
  220. package/dist/time-GN6B4QD6.js +111 -0
  221. package/dist/time-GN6B4QD6.js.map +1 -0
  222. package/dist/todo-LWMQY6XW.js +152 -0
  223. package/dist/todo-LWMQY6XW.js.map +1 -0
  224. package/dist/tree-7BMORJ6J.js +235 -0
  225. package/dist/tree-7BMORJ6J.js.map +1 -0
  226. package/dist/update-6LQNLRA4.js +57 -0
  227. package/dist/update-6LQNLRA4.js.map +1 -0
  228. package/dist/wait-MZOZQ3CI.js +57 -0
  229. package/dist/wait-MZOZQ3CI.js.map +1 -0
  230. package/dist/wd-bin.js +21 -11912
  231. package/dist/wd-bin.js.map +1 -1
  232. package/dist/web/assets/PtyView-BrP-ENHg.css +1 -0
  233. package/dist/web/assets/PtyView-M4b0GFVs.js +90 -0
  234. package/dist/web/assets/PtyView-M4b0GFVs.js.map +1 -0
  235. package/dist/web/assets/index-5hi1kMKy.js +116 -0
  236. package/dist/web/assets/index-5hi1kMKy.js.map +1 -0
  237. package/dist/web/assets/index-L8mjakHP.css +1 -0
  238. package/dist/web/index.html +3 -5
  239. package/dist/web-BI3MRQEM.js +7662 -0
  240. package/dist/web-BI3MRQEM.js.map +1 -0
  241. package/npm-shrinkwrap.json +6947 -0
  242. package/package.json +52 -34
  243. package/plugins/work-tree/.claude-plugin/plugin.json +1 -1
  244. package/plugins/work-tree/skills/wd-review/SKILL.md +4 -4
  245. package/plugins/work-tree/skills/work-sessions/SKILL.md +62 -0
  246. package/scripts/postinstall.mjs +15 -45
  247. package/dist/web/assets/index-B9H3vCtL.js +0 -107
  248. package/dist/web/assets/index-B9H3vCtL.js.map +0 -1
  249. package/dist/web/assets/index-BseMpW5i.css +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/core/platform/fs-safe.ts","../src/core/platform/config.ts","../src/core/sessions/saved-prompts.ts"],"sourcesContent":["import fs from 'node:fs';\nimport path from 'node:path';\nimport { createRequire } from 'node:module';\nimport type ProperLockfile from 'proper-lockfile';\n\n/** proper-lockfile, loaded on the first lock: most `work` processes (a hook) never take one. */\nlet lockfileModule: typeof ProperLockfile | null = null;\nconst lockfile = () => (lockfileModule ??= createRequire(import.meta.url)('proper-lockfile') as typeof ProperLockfile);\n\n/**\n * Resolve a path through any symlinks so a tmp-file + rename write replaces\n * the LINK TARGET, not the link. Users routinely symlink config into a\n * dotfiles repo (`~/.claude/settings.json` -> `~/.dotfiles/.../settings.json`);\n * renaming over the link silently detaches it, so our edit lands in a new\n * regular file and the dotfiles copy stops being the live one.\n *\n * Walks links by hand instead of `fs.realpathSync` so a dangling link (target\n * not created yet) still resolves to where it points. Falls back to the path\n * as given when there's nothing there or the links form a cycle. Resolving\n * also keeps the tmp file on the target's filesystem, so the rename can't\n * fail with EXDEV when the link crosses a mount.\n */\nexport function resolveLinkTarget(filePath: string): string {\n let current = filePath;\n const seen = new Set<string>([current]);\n for (let i = 0; i < 32; i++) {\n let stat;\n try {\n stat = fs.lstatSync(current);\n } catch {\n return current; // nothing there — write where we were told\n }\n if (!stat.isSymbolicLink()) return current;\n const next = path.resolve(path.dirname(current), fs.readlinkSync(current));\n if (seen.has(next)) return filePath; // link cycle — don't touch it\n seen.add(next);\n current = next;\n }\n return filePath;\n}\n\n/**\n * Write a file atomically. Writes to a sibling tmp file and renames\n * over the target, so a crash mid-write can't leave a truncated file.\n * Symlinks are followed first (see {@link resolveLinkTarget}) and the\n * existing file's mode is preserved across the replace.\n *\n * On Windows the rename fails (EPERM/EACCES/EBUSY) while another process\n * has the target open without delete sharing — a Claude Code reading\n * `~/.claude/settings.json`, an editor, an antivirus scan — which lasts\n * milliseconds, so it's retried for a few seconds. If it still fails\n * the tmp file is removed rather than left beside the target.\n */\nexport function atomicWriteFile(filePath: string, content: string, renameSync: (from: string, to: string) => void = fs.renameSync): void {\n const target = resolveLinkTarget(filePath);\n const tmpPath = `${target}.tmp-${process.pid}`;\n fs.writeFileSync(tmpPath, content, 'utf-8');\n try {\n fs.chmodSync(tmpPath, fs.statSync(target).mode & 0o777);\n } catch {\n /* target is new — default umask is right */\n }\n for (let attempt = 0; ; attempt++) {\n try {\n renameSync(tmpPath, target);\n return;\n } catch (err) {\n const code = (err as { code?: string }).code;\n if ((code === 'EPERM' || code === 'EACCES' || code === 'EBUSY') && attempt < 12) {\n sleepSync(Math.min(20 * 2 ** attempt, 400));\n continue;\n }\n try {\n fs.unlinkSync(tmpPath);\n } catch {\n /* already gone */\n }\n throw err;\n }\n }\n}\n\n/**\n * Ensure a file exists (creating with the given initial content if missing).\n * Required before `withFileLock` can acquire a lock on it — proper-lockfile\n * resolves the target file's realpath before creating the sibling .lock dir.\n */\nexport function ensureFile(filePath: string, initialContent: string): void {\n if (!fs.existsSync(filePath)) {\n fs.writeFileSync(filePath, initialContent, 'utf-8');\n }\n}\n\n/**\n * Serialize a read-modify-write sequence across processes using the same\n * advisory-lock mechanism as npm/yarn/pnpm. Caller is responsible for\n * ensuring the target file exists first (see `ensureFile`).\n */\nexport async function withFileLock<T>(filePath: string, fn: () => T | Promise<T>): Promise<T> {\n const release = await lockfile().lock(filePath, {\n retries: { retries: 20, minTimeout: 25, maxTimeout: 500, factor: 2 },\n stale: 10_000,\n });\n try {\n return await fn();\n } finally {\n await release();\n }\n}\n\n/**\n * Synchronous sibling of {@link withFileLock}. Serializes a read-modify-write\n * across processes using the same advisory-lock mechanism, but without an\n * `await` so it can be called from synchronous code paths (e.g. the\n * file-backed comment store, whose API is sync and consumed by sync Hono\n * route handlers). Caller is responsible for ensuring the target file exists\n * first (see `ensureFile`).\n */\nexport function withFileLockSync<T>(filePath: string, fn: () => T): T {\n // proper-lockfile's sync API forbids its own retry config (it requires an\n // async flow), so we hand-roll a bounded retry: try to acquire, and on a\n // contended lock (ELOCKED) sleep synchronously and try again.\n const maxAttempts = 30;\n let release: (() => void) | undefined;\n for (let attempt = 0; ; attempt++) {\n try {\n release = lockfile().lockSync(filePath, { stale: 10_000 });\n break;\n } catch (err) {\n const code = (err as { code?: string }).code;\n if (code !== 'ELOCKED' || attempt >= maxAttempts) throw err;\n sleepSync(Math.min(25 * 2 ** Math.min(attempt, 4), 500));\n }\n }\n try {\n return fn();\n } finally {\n release();\n }\n}\n\n/** Block the current thread for `ms` milliseconds without spinning the CPU.\n * Used by `withFileLockSync`'s contention backoff and `atomicWriteFile`'s rename retry. */\nfunction sleepSync(ms: number): void {\n const shared = new Int32Array(new SharedArrayBuffer(4));\n Atomics.wait(shared, 0, 0, ms);\n}\n","import fs from 'node:fs';\nimport path from 'node:path';\nimport os from 'node:os';\nimport { atomicWriteFile } from './fs-safe.js';\nimport { validatePrompts } from '../sessions/saved-prompts.js';\nimport type { SavedPrompt } from '../api-types.js';\n\n/**\n * An opt-in shell command that runs when a session changes status. The command\n * runs with the session's directory as its cwd (passed as the spawn `cwd`\n * option, never interpolated into the command string).\n */\nexport interface StatusHook {\n on: 'idle' | 'needs_input';\n command: string;\n}\n\nexport interface WorkConfig {\n worktreesRoot: string;\n repos: Record<string, string>;\n groups: Record<string, string[]>;\n copyFiles: string[];\n /** Folders the Repos page scans for git repos (repo-scan.ts); default: the one the worktrees root sits in. */\n scanRoots?: string[];\n /** Repos you chose not to enrol (paths), so the Repos page stops offering them. */\n ignoredRepos?: string[];\n /** The Jira watch (jira-watch.ts; turned on and off in the Jira tab): at most this many automatic starts a day (default 5). */\n jiraWatch?: { maxPerDay?: number };\n /** Stacked sessions (stack-sync.ts): bring a parent's new commits into the sessions stacked on it (default true). */\n stacks?: { autoUpdate?: boolean };\n /** The agent that writes work's own summaries — checkpoint names, catch-up, archive summaries, the Jira watch's choice (default `claude`; one without one-shot runs writes none). */\n internalAgent?: string;\n /** The agent the Ctrl+K assistant runs (an adapter's id; Claude Code by default). */\n assistantAgent?: string;\n /** Environment variable names to keep for a session restored after a reboot (the launching shell's values; secret-looking names are never kept). */\n hostEnv?: string[];\n /** Writing session time to Jira as worklogs (jira-worklog.ts): the site, your email, and the API token (from the env var `tokenEnv`, default JIRA_API_TOKEN, or `token`). */\n jiraWorklog?: { site: string; email: string; tokenEnv?: string; token?: string };\n /**\n * AI tool command to launch in worktrees. May include extra args, e.g.\n * \"claude\" (default), \"gemini\", \"codex\", or \"my-tool --some-flag\".\n */\n aiCommand?: string;\n /**\n * Launch `work tree`'s AI session inside the PTY host and attach this\n * terminal to it (like `work attach`), so it survives closing the tab and\n * the dashboard shows the same screen. Default on; `false` launches\n * directly in the terminal. Per call: `--host` / `--no-host`.\n */\n launchViaHost?: boolean;\n /**\n * Per-tool flag overrides. Defaults come from the preset matching the\n * binary in `aiCommand` (see AI_TOOL_PRESETS in core/ai-launcher.ts).\n * Set any value to an empty string to disable that flag for the configured tool.\n */\n aiCommandFlags?: {\n /** Flag for skipping permission checks. */\n unsafe?: string;\n /** Flag for resuming the most recent session. */\n resume?: string;\n /** Flag for passing an initial prompt as a file path. */\n promptFile?: string;\n /** Flag for passing an inline prompt; empty string = positional arg. */\n prompt?: string;\n };\n /** Editor command for opening worktrees. Default: \"code\" */\n editor?: string;\n /**\n * Range of dev-server ports to allocate to worktrees (inclusive).\n * Each worktree gets a stable port exposed as $PORT to the launched process.\n * Default when unset: { start: 3000, end: 3099 }.\n */\n portRange?: { start: number; end: number };\n /**\n * Dev-server command per repo alias, run from the dashboard with this\n * worktree's $PORT (e.g. `{ \"web\": \"npm run dev -- --port $PORT\" }`).\n */\n devCommands?: Record<string, string>;\n /**\n * Stop a session's Claude in the PTY host after this many minutes idle with\n * no window attached; opening the session resumes its conversation. Frees\n * memory (each Claude holds a few hundred MB). Default 240; 0 = never.\n */\n sleepIdleAfterMinutes?: number;\n /**\n * Archived conversations (archive-retention.ts): gzip them once this many\n * days old (default 30; 0 = never; lossless), and delete them after this\n * many (default 0 = never; the summary and prompts stay).\n */\n archive?: { compressAfterDays?: number; dropTranscriptsAfterDays?: number };\n /**\n * Background PR watch in `work web` (both default on): archive a session\n * once all its PRs merged, and tell its Claude when CI fails or reviewers\n * leave feedback.\n */\n prWatch?: {\n autoArchive?: boolean;\n fixCi?: boolean;\n reviewComments?: boolean;\n /** Review bots whose comments go to Claude like a colleague's (logins,\n * e.g. \"copilot-pull-request-reviewer\"). Default: Copilot and\n * github-actions (pr-review.ts DEFAULT_TRUSTED_BOTS); [] = none. */\n trustedBots?: string[];\n /** Start a session's Claude (resuming its conversation) when feedback\n * arrives and it isn't running, so it works on it at once. Default on. */\n wakeClaude?: boolean;\n };\n /**\n * Opt-in desktop notifications. When true, the dashboard fires an OS\n * notification when a session goes idle or needs input. Default: off.\n */\n notifications?: boolean;\n /**\n * Opt-in shell commands run when a session changes status (idle /\n * needs_input). Each command runs with the session dir as its cwd.\n * Generalizes `notifications`; both paths work independently. Default: none.\n */\n statusHooks?: StatusHook[];\n /**\n * One-click instructions in a session's \"Prompts ▾\" menu, replacing the\n * built-in ones: `[{ \"label\": \"Add tests\", \"prompt\": \"…\", \"repos\": [\"api\"] }]`\n * (`repos` optional: only for those repo aliases / group names).\n */\n prompts?: SavedPrompt[];\n}\n\n/** Lowest port we allow to be configured (avoid privileged ports < 1024). */\nconst MIN_PORT = 1024;\n/** Highest valid TCP port. */\nconst MAX_PORT = 65535;\n\n/**\n * Validate a configured port range. Returns the normalized range when it is a\n * pair of integers with `MIN_PORT <= start <= end <= MAX_PORT`, otherwise\n * undefined (callers then fall back to the default range). Rejects non-integers,\n * privileged/out-of-bounds ports, and reversed ranges.\n */\nexport function validatePortRange(value: unknown): { start: number; end: number } | undefined {\n if (!value || typeof value !== 'object') return undefined;\n const { start, end } = value as { start?: unknown; end?: unknown };\n if (typeof start !== 'number' || typeof end !== 'number') return undefined;\n if (!Number.isInteger(start) || !Number.isInteger(end)) return undefined;\n if (start < MIN_PORT || end > MAX_PORT) return undefined;\n if (start > end) return undefined;\n return { start, end };\n}\n\nexport function getConfigDir(): string {\n const dir = path.join(os.homedir(), '.work');\n if (!fs.existsSync(dir)) {\n fs.mkdirSync(dir, { recursive: true });\n }\n return dir;\n}\n\n/** An agent named in config (`internalAgent`, `assistantAgent`): an adapter's id, a plain word — never a path or a command line. */\nexport function isAgentId(v: unknown): v is string {\n return typeof v === 'string' && /^[\\w.-]+$/.test(v);\n}\n\nexport function getConfigPath(): string {\n return path.join(getConfigDir(), 'config.json');\n}\n\nfunction validateDevCommands(raw: unknown): Record<string, string> | undefined {\n if (!raw || typeof raw !== 'object' || Array.isArray(raw)) return undefined;\n const out: Record<string, string> = {};\n for (const [alias, cmd] of Object.entries(raw)) if (typeof cmd === 'string' && cmd.trim()) out[alias] = cmd;\n return out;\n}\n\n/** A list of non-empty strings, or undefined (not a list). */\nfunction stringList(raw: unknown): string[] | undefined {\n return Array.isArray(raw) ? raw.filter((x): x is string => typeof x === 'string' && x.trim().length > 0) : undefined;\n}\n\nexport function loadConfig(): WorkConfig | null {\n const configPath = getConfigPath();\n if (!fs.existsSync(configPath)) {\n return null;\n }\n\n try {\n const raw = fs.readFileSync(configPath, 'utf-8');\n const parsed = JSON.parse(raw);\n return {\n worktreesRoot: parsed.worktreesRoot ?? '',\n repos: parsed.repos ?? {},\n groups: parsed.groups ?? {},\n copyFiles: parsed.copyFiles ?? [],\n scanRoots: stringList(parsed.scanRoots),\n ignoredRepos: stringList(parsed.ignoredRepos),\n aiCommand: parsed.aiCommand,\n aiCommandFlags: parsed.aiCommandFlags,\n editor: parsed.editor,\n portRange: validatePortRange(parsed.portRange),\n notifications: parsed.notifications === true,\n statusHooks: Array.isArray(parsed.statusHooks) ? parsed.statusHooks : [],\n launchViaHost: typeof parsed.launchViaHost === 'boolean' ? parsed.launchViaHost : undefined,\n devCommands: validateDevCommands(parsed.devCommands),\n sleepIdleAfterMinutes:\n typeof parsed.sleepIdleAfterMinutes === 'number' && parsed.sleepIdleAfterMinutes >= 0 ? parsed.sleepIdleAfterMinutes : undefined,\n prompts: validatePrompts(parsed.prompts),\n archive:\n parsed.archive && typeof parsed.archive === 'object'\n ? {\n ...(typeof parsed.archive.compressAfterDays === 'number' && parsed.archive.compressAfterDays >= 0\n ? { compressAfterDays: parsed.archive.compressAfterDays }\n : {}),\n ...(typeof parsed.archive.dropTranscriptsAfterDays === 'number' && parsed.archive.dropTranscriptsAfterDays >= 0\n ? { dropTranscriptsAfterDays: parsed.archive.dropTranscriptsAfterDays }\n : {}),\n }\n : undefined,\n stacks: parsed.stacks && typeof parsed.stacks === 'object' ? { autoUpdate: parsed.stacks.autoUpdate !== false } : undefined,\n internalAgent: isAgentId(parsed.internalAgent) ? parsed.internalAgent : undefined,\n assistantAgent: isAgentId(parsed.assistantAgent) ? parsed.assistantAgent : undefined,\n hostEnv: Array.isArray(parsed.hostEnv)\n ? parsed.hostEnv.filter((n: unknown): n is string => typeof n === 'string' && /^[A-Za-z_][A-Za-z0-9_]*$/.test(n))\n : undefined,\n jiraWorklog:\n parsed.jiraWorklog &&\n typeof parsed.jiraWorklog === 'object' &&\n typeof parsed.jiraWorklog.site === 'string' &&\n typeof parsed.jiraWorklog.email === 'string'\n ? {\n site: parsed.jiraWorklog.site,\n email: parsed.jiraWorklog.email,\n ...(typeof parsed.jiraWorklog.tokenEnv === 'string' ? { tokenEnv: parsed.jiraWorklog.tokenEnv } : {}),\n ...(typeof parsed.jiraWorklog.token === 'string' ? { token: parsed.jiraWorklog.token } : {}),\n }\n : undefined,\n prWatch:\n parsed.prWatch && typeof parsed.prWatch === 'object'\n ? {\n autoArchive: parsed.prWatch.autoArchive !== false,\n fixCi: parsed.prWatch.fixCi !== false,\n reviewComments: parsed.prWatch.reviewComments !== false,\n ...(Array.isArray(parsed.prWatch.trustedBots)\n ? {\n trustedBots: parsed.prWatch.trustedBots.filter(\n (b: unknown): b is string => typeof b === 'string' && b.trim().length > 0,\n ),\n }\n : {}),\n wakeClaude: parsed.prWatch.wakeClaude !== false,\n }\n : undefined,\n };\n } catch {\n return null;\n }\n}\n\nexport function saveConfig(config: WorkConfig): void {\n // Atomic (write temp + rename): a crash or a concurrent reader can never\n // see a half-written config (§5.3 — history/tasks already did this).\n atomicWriteFile(getConfigPath(), JSON.stringify(config, null, 2));\n}\n\nexport function ensureConfig(): WorkConfig {\n const config = loadConfig();\n if (!config) {\n throw new Error('Configuration not found. Run \"work init\" to set up.');\n }\n return config;\n}\n","import type { SavedPrompt } from '../api-types.js';\n\nexport type { SavedPrompt } from '../api-types.js';\n\n/**\n * One-click instructions for a session (\"Prompts ▾\" in its header). Sent\n * like a review comment, so they reach Claude the same safe way: pushed to\n * a terminal the dashboard owns, or on the session's next turn — never\n * typed over a permission prompt. Pure (the demo uses it too).\n *\n * `prompts` in config.json replaces these defaults; `repos` limits one to\n * those repo aliases / group names.\n */\nexport const DEFAULT_PROMPTS: SavedPrompt[] = [\n {\n label: 'Review your changes',\n prompt:\n 'Review the changes on this branch as a strict reviewer would: bugs, missing edge cases, missing tests, leftovers (debug output, TODOs, dead code). Fix what you find, then tell me briefly what you changed.',\n },\n {\n label: 'Add tests',\n prompt:\n 'Add tests for what changed on this branch, following the existing test patterns in this repo. Run them and fix anything that fails.',\n },\n {\n label: 'Run checks and fix',\n prompt:\n \"Run this repo's type check, lint and tests (whatever it has). Fix what fails, and tell me if something is failing for a reason outside this change.\",\n },\n {\n label: 'Commit',\n prompt: \"Commit the current changes with a clear message in this repo's commit style. Don't push.\",\n },\n {\n label: 'Open a pull request',\n prompt:\n 'Push this branch and open a pull request for it with `gh pr create`. Write the title and description yourself from what we did in this conversation: what changed and why, how it was tested, anything a reviewer should look at first. Put the Jira key in the title if the branch or our conversation has one. Open it ready for review, not as a draft, and give me its link.',\n },\n {\n label: 'Rebase on the default branch',\n prompt:\n \"Fetch, then rebase this branch on origin's default branch. Resolve conflicts keeping both sides' intent, run the tests, and tell me about any conflict you weren't sure of.\",\n },\n];\n\nconst MAX_PROMPT = 20_000;\n\n/** The configured list, validated; undefined (use the defaults) when absent. */\nexport function validatePrompts(raw: unknown): SavedPrompt[] | undefined {\n if (!Array.isArray(raw)) return undefined;\n const out: SavedPrompt[] = [];\n for (const p of raw) {\n if (!p || typeof p !== 'object') continue;\n const { label, prompt, repos } = p as Record<string, unknown>;\n if (typeof label !== 'string' || !label.trim() || typeof prompt !== 'string' || !prompt.trim()) continue;\n const item: SavedPrompt = { label: label.trim(), prompt: prompt.trim().slice(0, MAX_PROMPT) };\n if (Array.isArray(repos)) {\n const names = repos.filter((r): r is string => typeof r === 'string' && r.length > 0);\n if (names.length) item.repos = names;\n }\n out.push(item);\n }\n return out;\n}\n\n/** The prompts that apply to a session: unscoped ones, and those naming\n * its target (a repo alias or group name) or one of its repos. */\nexport function promptsForSession(prompts: SavedPrompt[], target: string, repoNames: string[] = []): SavedPrompt[] {\n const names = new Set([target, ...repoNames]);\n return prompts.filter((p) => !p.repos || p.repos.some((r) => names.has(r)));\n}\n"],"mappings":";;;AAAA,OAAO,QAAQ;AACf,OAAO,UAAU;AACjB,SAAS,qBAAqB;AAI9B,IAAI,iBAA+C;AACnD,IAAM,WAAW,MAAO,mBAAmB,cAAc,YAAY,GAAG,EAAE,iBAAiB;AAepF,SAAS,kBAAkB,UAA0B;AAC1D,MAAI,UAAU;AACd,QAAM,OAAO,oBAAI,IAAY,CAAC,OAAO,CAAC;AACtC,WAAS,IAAI,GAAG,IAAI,IAAI,KAAK;AAC3B,QAAI;AACJ,QAAI;AACF,aAAO,GAAG,UAAU,OAAO;AAAA,IAC7B,QAAQ;AACN,aAAO;AAAA,IACT;AACA,QAAI,CAAC,KAAK,eAAe,EAAG,QAAO;AACnC,UAAM,OAAO,KAAK,QAAQ,KAAK,QAAQ,OAAO,GAAG,GAAG,aAAa,OAAO,CAAC;AACzE,QAAI,KAAK,IAAI,IAAI,EAAG,QAAO;AAC3B,SAAK,IAAI,IAAI;AACb,cAAU;AAAA,EACZ;AACA,SAAO;AACT;AAcO,SAA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;AAAA,MAC5C,IACA;AAAA,IACR;AAAA,EACF,QAAQ;AACN,WAAO;AAAA,EACT;AACF;AAEO,SAAS,WAAW,QAA0B;AAGnD,kBAAgB,cAAc,GAAG,KAAK,UAAU,QAAQ,MAAM,CAAC,CAAC;AAClE;AAEO,SAAS,eAA2B;AACzC,QAAM,SAAS,WAAW;AAC1B,MAAI,CAAC,QAAQ;AACX,UAAM,IAAI,MAAM,qDAAqD;AAAA,EACvE;AACA,SAAO;AACT;","names":["fs","path","path","fs"]}
@@ -0,0 +1,206 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ spawn_default
4
+ } from "./chunk-RCYI7SRA.js";
5
+ import {
6
+ debug
7
+ } from "./chunk-N4EYQKSM.js";
8
+
9
+ // src/core/git/git.ts
10
+ import { execFile } from "child_process";
11
+ import fs from "fs";
12
+ import path from "path";
13
+ function git(args, cwd) {
14
+ debug("git", args.join(" "), `cwd=${cwd}`);
15
+ const result = spawn_default.sync("git", args, {
16
+ cwd,
17
+ encoding: "utf-8",
18
+ stdio: ["pipe", "pipe", "pipe"],
19
+ // Avoid flashing a console window on Windows for every git call —
20
+ // matters most when this runs inside the detached `wd --watch` daemon.
21
+ windowsHide: true
22
+ });
23
+ const r = {
24
+ stdout: (result.stdout ?? "").toString().trim(),
25
+ stderr: (result.stderr ?? "").toString().trim(),
26
+ exitCode: result.status ?? 1
27
+ };
28
+ if (r.exitCode !== 0) {
29
+ debug("git failed", { args, exitCode: r.exitCode, stderr: r.stderr });
30
+ }
31
+ return r;
32
+ }
33
+ function parseWorktreeList(cwd) {
34
+ const result = git(["worktree", "list", "--porcelain"], cwd);
35
+ if (result.exitCode !== 0) return [];
36
+ const entries = [];
37
+ let current = {};
38
+ for (const line of result.stdout.split("\n")) {
39
+ const worktreeMatch = line.match(/^worktree (.+)$/);
40
+ if (worktreeMatch) {
41
+ if (current.path) {
42
+ entries.push({
43
+ path: current.path,
44
+ branch: current.branch ?? "",
45
+ head: current.head ?? ""
46
+ });
47
+ }
48
+ current = { path: worktreeMatch[1] };
49
+ continue;
50
+ }
51
+ const headMatch = line.match(/^HEAD (.+)$/);
52
+ if (headMatch) {
53
+ current.head = headMatch[1].substring(0, 7);
54
+ continue;
55
+ }
56
+ const branchMatch = line.match(/^branch (.+)$/);
57
+ if (branchMatch) {
58
+ current.branch = branchMatch[1].replace(/^refs\/heads\//, "");
59
+ }
60
+ }
61
+ if (current.path) {
62
+ entries.push({
63
+ path: current.path,
64
+ branch: current.branch ?? "",
65
+ head: current.head ?? ""
66
+ });
67
+ }
68
+ return entries;
69
+ }
70
+ function localBranchExists(branch, cwd) {
71
+ const result = git(["rev-parse", "--verify", branch], cwd);
72
+ return result.exitCode === 0;
73
+ }
74
+ function remoteBranchExists(branch, cwd) {
75
+ const result = git(["rev-parse", "--verify", `origin/${branch}`], cwd);
76
+ return result.exitCode === 0;
77
+ }
78
+ function isGitRepo(cwd) {
79
+ const result = git(["rev-parse", "--is-inside-work-tree"], cwd);
80
+ return result.exitCode === 0 && result.stdout === "true";
81
+ }
82
+ function getWorktreeRoot(cwd) {
83
+ const result = git(["rev-parse", "--show-toplevel"], cwd);
84
+ if (result.exitCode !== 0 || !result.stdout) return null;
85
+ return result.stdout;
86
+ }
87
+ function getMainRepoRoot(cwd) {
88
+ const result = git(["rev-parse", "--path-format=absolute", "--git-common-dir"], cwd);
89
+ if (result.exitCode !== 0 || !result.stdout) return null;
90
+ const commonDir = result.stdout;
91
+ if (path.basename(commonDir) === ".git") {
92
+ return path.dirname(commonDir);
93
+ }
94
+ return commonDir;
95
+ }
96
+ function getCurrentBranch(cwd) {
97
+ const result = git(["branch", "--show-current"], cwd);
98
+ return result.stdout;
99
+ }
100
+ function getStatus(cwd) {
101
+ const result = git(["status", "--porcelain"], cwd);
102
+ return result.stdout;
103
+ }
104
+ function getStatusChecked(cwd) {
105
+ const result = git(["status", "--porcelain"], cwd);
106
+ return result.exitCode === 0 ? result.stdout : null;
107
+ }
108
+ function repoState(cwd) {
109
+ const result = git(["rev-parse", "--is-inside-work-tree"], cwd);
110
+ if (result.exitCode === 0 && result.stdout === "true") return "repo";
111
+ if (fs.existsSync(path.join(cwd, ".git"))) return "unknown";
112
+ return /not a git repository/i.test(result.stderr) ? "not-a-repo" : "unknown";
113
+ }
114
+ function getDefaultBranch(cwd) {
115
+ const result = git(["symbolic-ref", "refs/remotes/origin/HEAD"], cwd);
116
+ if (result.exitCode === 0 && result.stdout) {
117
+ return result.stdout.replace(/^refs\/remotes\/origin\//, "");
118
+ }
119
+ return null;
120
+ }
121
+ function checkMergeStatus(branch, baseRef, cwd) {
122
+ const branchInBase = git(["merge-base", "--is-ancestor", branch, baseRef], cwd);
123
+ if (branchInBase.exitCode !== 0) {
124
+ if (checkSquashMerged(branch, baseRef, cwd)) return "squash-merged";
125
+ return "unrelated";
126
+ }
127
+ const baseInBranch = git(["merge-base", "--is-ancestor", baseRef, branch], cwd);
128
+ if (baseInBranch.exitCode === 0) return "merged";
129
+ const tip = git(["rev-parse", branch], cwd);
130
+ if (tip.exitCode !== 0) return "unrelated";
131
+ const mainLine = git(["rev-list", "--first-parent", "-n", "500", baseRef], cwd);
132
+ if (mainLine.exitCode === 0 && mainLine.stdout.includes(tip.stdout)) {
133
+ return "stale";
134
+ }
135
+ return "merged";
136
+ }
137
+ function checkSquashMerged(branch, baseRef, cwd) {
138
+ const mb = git(["merge-base", baseRef, branch], cwd);
139
+ if (mb.exitCode !== 0) return false;
140
+ const tree = git(["rev-parse", `${branch}^{tree}`], cwd);
141
+ if (tree.exitCode !== 0) return false;
142
+ const dangling = git(["commit-tree", tree.stdout, "-p", mb.stdout, "-m", ""], cwd);
143
+ if (dangling.exitCode !== 0) return false;
144
+ const cherry = git(["cherry", baseRef, dangling.stdout], cwd);
145
+ if (cherry.exitCode !== 0) return false;
146
+ return cherry.stdout.startsWith("-");
147
+ }
148
+ function isBranchMerged(branch, cwd, baseBranch) {
149
+ const defaultBranch = getDefaultBranch(cwd);
150
+ const bases = baseBranch ? [baseBranch] : [defaultBranch, "main", "master"].filter((b) => b !== null);
151
+ const uniqueBases = [...new Set(bases)];
152
+ for (const base of uniqueBases) {
153
+ if (remoteBranchExists(base, cwd)) {
154
+ const baseRef = `origin/${base}`;
155
+ const status = checkMergeStatus(branch, baseRef, cwd);
156
+ if (status === "merged") return { merged: true, into: baseRef, confidence: "merged" };
157
+ if (status === "squash-merged") return { merged: true, into: baseRef, confidence: "squash-merged" };
158
+ if (status === "stale") return { merged: false, into: null, confidence: null };
159
+ }
160
+ if (localBranchExists(base, cwd)) {
161
+ const status = checkMergeStatus(branch, base, cwd);
162
+ if (status === "merged") return { merged: true, into: base, confidence: "merged" };
163
+ if (status === "squash-merged") return { merged: true, into: base, confidence: "squash-merged" };
164
+ if (status === "stale") return { merged: false, into: null, confidence: null };
165
+ }
166
+ }
167
+ return { merged: false, into: null, confidence: null };
168
+ }
169
+ async function fetchRemoteAsync(cwd) {
170
+ await new Promise((resolve, reject) => {
171
+ execFile("git", ["fetch", "--quiet"], { cwd, timeout: 3e4, windowsHide: true }, (err) => {
172
+ if (err) reject(err);
173
+ else resolve();
174
+ });
175
+ });
176
+ if (!getDefaultBranch(cwd)) {
177
+ git(["remote", "set-head", "origin", "--auto"], cwd);
178
+ }
179
+ }
180
+ function getUnpushedCommits(cwd) {
181
+ const branch = getCurrentBranch(cwd);
182
+ if (!branch) return "";
183
+ const upstreamResult = git(["rev-parse", "--abbrev-ref", `${branch}@{upstream}`], cwd);
184
+ if (upstreamResult.exitCode !== 0) return "";
185
+ const upstream = upstreamResult.stdout;
186
+ const logResult = git(["log", "--oneline", `${upstream}..HEAD`], cwd);
187
+ return logResult.stdout;
188
+ }
189
+
190
+ export {
191
+ git,
192
+ parseWorktreeList,
193
+ localBranchExists,
194
+ remoteBranchExists,
195
+ isGitRepo,
196
+ getWorktreeRoot,
197
+ getMainRepoRoot,
198
+ getCurrentBranch,
199
+ getStatus,
200
+ getStatusChecked,
201
+ repoState,
202
+ isBranchMerged,
203
+ fetchRemoteAsync,
204
+ getUnpushedCommits
205
+ };
206
+ //# sourceMappingURL=chunk-7NAXFBFI.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/core/git/git.ts"],"sourcesContent":["import spawn from '../platform/spawn.js';\nimport { execFile } from 'node:child_process';\nimport fs from 'node:fs';\nimport path from 'node:path';\nimport { debug } from '../platform/logger.js';\n\nexport interface GitResult {\n stdout: string;\n stderr: string;\n exitCode: number;\n}\n\n/** Run a git command synchronously in the given cwd. */\nexport function git(args: string[], cwd: string): GitResult {\n debug('git', args.join(' '), `cwd=${cwd}`);\n const result = spawn.sync('git', args, {\n cwd,\n encoding: 'utf-8',\n stdio: ['pipe', 'pipe', 'pipe'],\n // Avoid flashing a console window on Windows for every git call —\n // matters most when this runs inside the detached `wd --watch` daemon.\n windowsHide: true,\n });\n\n const r = {\n stdout: (result.stdout ?? '').toString().trim(),\n stderr: (result.stderr ?? '').toString().trim(),\n exitCode: result.status ?? 1,\n };\n if (r.exitCode !== 0) {\n debug('git failed', { args, exitCode: r.exitCode, stderr: r.stderr });\n }\n return r;\n}\n\nexport interface WorktreeEntry {\n path: string;\n branch: string;\n head: string;\n}\n\n/** Parse `git worktree list --porcelain` output into structured entries. */\nexport function parseWorktreeList(cwd: string): WorktreeEntry[] {\n const result = git(['worktree', 'list', '--porcelain'], cwd);\n if (result.exitCode !== 0) return [];\n\n const entries: WorktreeEntry[] = [];\n let current: Partial<WorktreeEntry> = {};\n\n for (const line of result.stdout.split('\\n')) {\n const worktreeMatch = line.match(/^worktree (.+)$/);\n if (worktreeMatch) {\n if (current.path) {\n entries.push({\n path: current.path,\n branch: current.branch ?? '',\n head: current.head ?? '',\n });\n }\n current = { path: worktreeMatch[1] };\n continue;\n }\n\n const headMatch = line.match(/^HEAD (.+)$/);\n if (headMatch) {\n current.head = headMatch[1].substring(0, 7);\n continue;\n }\n\n const branchMatch = line.match(/^branch (.+)$/);\n if (branchMatch) {\n current.branch = branchMatch[1].replace(/^refs\\/heads\\//, '');\n }\n }\n\n // Push last entry\n if (current.path) {\n entries.push({\n path: current.path,\n branch: current.branch ?? '',\n head: current.head ?? '',\n });\n }\n\n return entries;\n}\n\n/** Check if a local branch exists. */\nexport function localBranchExists(branch: string, cwd: string): boolean {\n const result = git(['rev-parse', '--verify', branch], cwd);\n return result.exitCode === 0;\n}\n\n/** Check if a remote tracking branch exists. */\nexport function remoteBranchExists(branch: string, cwd: string): boolean {\n const result = git(['rev-parse', '--verify', `origin/${branch}`], cwd);\n return result.exitCode === 0;\n}\n\n/** Check if path is a valid git worktree/repo. */\nexport function isGitRepo(cwd: string): boolean {\n const result = git(['rev-parse', '--is-inside-work-tree'], cwd);\n return result.exitCode === 0 && result.stdout === 'true';\n}\n\n/** Get the absolute toplevel of the worktree containing cwd, or null if not a repo. */\nexport function getWorktreeRoot(cwd: string): string | null {\n const result = git(['rev-parse', '--show-toplevel'], cwd);\n if (result.exitCode !== 0 || !result.stdout) return null;\n return result.stdout;\n}\n\n/**\n * Get the MAIN repo working directory for a (possibly linked) worktree.\n * `--git-common-dir` points at the main repo's `.git` dir; the main repo root\n * is its parent when the basename is `.git`, otherwise the path itself.\n * Returns null on failure.\n */\nexport function getMainRepoRoot(cwd: string): string | null {\n const result = git(['rev-parse', '--path-format=absolute', '--git-common-dir'], cwd);\n if (result.exitCode !== 0 || !result.stdout) return null;\n const commonDir = result.stdout;\n if (path.basename(commonDir) === '.git') {\n return path.dirname(commonDir);\n }\n return commonDir;\n}\n\n/** Get current branch name. */\nexport function getCurrentBranch(cwd: string): string {\n const result = git(['branch', '--show-current'], cwd);\n return result.stdout;\n}\n\n/** Check for uncommitted changes (returns porcelain status). */\nexport function getStatus(cwd: string): string {\n const result = git(['status', '--porcelain'], cwd);\n return result.stdout;\n}\n\n/**\n * Porcelain status, or null when git could not tell (it errored). Anything\n * deciding whether work may be deleted must use this and treat null as\n * \"maybe dirty\": an empty string from a FAILED `git status` is not clean.\n */\nexport function getStatusChecked(cwd: string): string | null {\n const result = git(['status', '--porcelain'], cwd);\n return result.exitCode === 0 ? result.stdout : null;\n}\n\nexport type RepoState = 'repo' | 'not-a-repo' | 'unknown';\n\n/**\n * Whether a directory is a git checkout — with \"can't tell\" kept apart\n * from \"no\". A failing git (dubious ownership on a network share, git\n * missing from a detached process's PATH, a worktree whose main repo was\n * moved) is NOT proof the folder is disposable: 'not-a-repo' needs git to\n * say so AND no `.git` entry in the folder.\n */\nexport function repoState(cwd: string): RepoState {\n const result = git(['rev-parse', '--is-inside-work-tree'], cwd);\n if (result.exitCode === 0 && result.stdout === 'true') return 'repo';\n if (fs.existsSync(path.join(cwd, '.git'))) return 'unknown';\n return /not a git repository/i.test(result.stderr) ? 'not-a-repo' : 'unknown';\n}\n\n/** Get the default branch from origin/HEAD (e.g. \"main\" or \"master\"). */\nexport function getDefaultBranch(cwd: string): string | null {\n const result = git(['symbolic-ref', 'refs/remotes/origin/HEAD'], cwd);\n if (result.exitCode === 0 && result.stdout) {\n // Output is like \"refs/remotes/origin/main\"\n return result.stdout.replace(/^refs\\/remotes\\/origin\\//, '');\n }\n return null;\n}\n\n/**\n * Result of checking a branch against a single base ref.\n *\n * 'merged' is a high-confidence true merge (the branch tip is reachable from\n * base via a merge/fast-forward). 'squash-merged' is the lower-confidence\n * heuristic match from {@link checkSquashMerged} — the branch's squashed patch\n * already appears in base, but there is no real merge commit linking the two.\n * Callers that prune unattended should treat 'squash-merged' as opt-in only.\n */\ntype MergeCheck = 'merged' | 'squash-merged' | 'stale' | 'unrelated';\n\n/**\n * Check if a branch is truly merged into a base ref (not just a stale branch\n * sitting behind base with no unique commits).\n *\n * Returns 'stale' if the branch tip is on the base's first-parent chain\n * (no unique work). Returns 'merged' if the branch has unique commits that\n * are all reachable from base. Returns 'squash-merged' if only the squash\n * heuristic matched. Returns 'unrelated' otherwise.\n */\nfunction checkMergeStatus(branch: string, baseRef: string, cwd: string): MergeCheck {\n // 1. Branch must be an ancestor of base (all its commits are in base)\n const branchInBase = git(['merge-base', '--is-ancestor', branch, baseRef], cwd);\n if (branchInBase.exitCode !== 0) {\n // Not a regular merge — check for squash merge (low-confidence heuristic).\n if (checkSquashMerged(branch, baseRef, cwd)) return 'squash-merged';\n return 'unrelated';\n }\n\n // 2. If base is also ancestor of branch, they're at the same commit\n // (fast-forward merge or empty branch) — nothing left to merge.\n const baseInBranch = git(['merge-base', '--is-ancestor', baseRef, branch], cwd);\n if (baseInBranch.exitCode === 0) return 'merged';\n\n // 3. Branch is ancestor of base — but is it on the main line (stale) or\n // only reachable via a merge commit (truly merged)?\n // A stale branch's tip sits directly on the first-parent chain.\n const tip = git(['rev-parse', branch], cwd);\n if (tip.exitCode !== 0) return 'unrelated';\n const mainLine = git(['rev-list', '--first-parent', '-n', '500', baseRef], cwd);\n if (mainLine.exitCode === 0 && mainLine.stdout.includes(tip.stdout)) {\n return 'stale';\n }\n\n return 'merged';\n}\n\n/**\n * Detect squash merges by creating a temporary dangling commit that represents\n * the branch's tree squashed onto the merge-base, then checking if that patch\n * is already present in the base ref via `git cherry`.\n */\nfunction checkSquashMerged(branch: string, baseRef: string, cwd: string): boolean {\n const mb = git(['merge-base', baseRef, branch], cwd);\n if (mb.exitCode !== 0) return false;\n\n const tree = git(['rev-parse', `${branch}^{tree}`], cwd);\n if (tree.exitCode !== 0) return false;\n\n const dangling = git(['commit-tree', tree.stdout, '-p', mb.stdout, '-m', ''], cwd);\n if (dangling.exitCode !== 0) return false;\n\n const cherry = git(['cherry', baseRef, dangling.stdout], cwd);\n if (cherry.exitCode !== 0) return false;\n\n // If the output starts with \"-\", the patch is already in baseRef (squash-merged)\n return cherry.stdout.startsWith('-');\n}\n\n/** Confidence level for a positive merge result. */\nexport type MergeConfidence = 'merged' | 'squash-merged';\n\nexport interface MergeCheckResult {\n merged: boolean;\n /** The base ref it matched against (e.g. \"origin/main\"), or null if not merged. */\n into: string | null;\n /**\n * How the match was determined when `merged` is true: 'merged' is a\n * high-confidence true merge; 'squash-merged' is the lower-confidence\n * squash heuristic. Null when not merged.\n */\n confidence: MergeConfidence | null;\n}\n\nexport function isBranchMerged(branch: string, cwd: string, baseBranch?: string): MergeCheckResult {\n const defaultBranch = getDefaultBranch(cwd);\n const bases = baseBranch ? [baseBranch] : [defaultBranch, 'main', 'master'].filter((b): b is string => b !== null);\n\n // Deduplicate (e.g. default branch is \"main\" which is already in the list)\n const uniqueBases = [...new Set(bases)];\n\n for (const base of uniqueBases) {\n // Check remote base branch first (most up-to-date after fetch)\n if (remoteBranchExists(base, cwd)) {\n const baseRef = `origin/${base}`;\n const status = checkMergeStatus(branch, baseRef, cwd);\n if (status === 'merged') return { merged: true, into: baseRef, confidence: 'merged' };\n if (status === 'squash-merged') return { merged: true, into: baseRef, confidence: 'squash-merged' };\n if (status === 'stale') return { merged: false, into: null, confidence: null };\n }\n\n // Fall back to local base branch\n if (localBranchExists(base, cwd)) {\n const status = checkMergeStatus(branch, base, cwd);\n if (status === 'merged') return { merged: true, into: base, confidence: 'merged' };\n if (status === 'squash-merged') return { merged: true, into: base, confidence: 'squash-merged' };\n if (status === 'stale') return { merged: false, into: null, confidence: null };\n }\n }\n\n return { merged: false, into: null, confidence: null };\n}\n\n/** Fetch latest remote refs for a repo and ensure origin/HEAD is set. */\nexport function fetchRemote(cwd: string): void {\n git(['fetch', '--quiet'], cwd);\n\n // Ensure origin/HEAD is set so getDefaultBranch works\n if (!getDefaultBranch(cwd)) {\n git(['remote', 'set-head', 'origin', '--auto'], cwd);\n }\n}\n\n/** Async version of fetchRemote — non-blocking. */\nexport async function fetchRemoteAsync(cwd: string): Promise<void> {\n await new Promise<void>((resolve, reject) => {\n execFile('git', ['fetch', '--quiet'], { cwd, timeout: 30000, windowsHide: true }, (err) => {\n if (err) reject(err);\n else resolve();\n });\n });\n if (!getDefaultBranch(cwd)) {\n git(['remote', 'set-head', 'origin', '--auto'], cwd);\n }\n}\n\n/** Rebase a branch onto the default branch. Returns error message or null on success. */\nexport function rebaseOntoMain(branch: string, cwd: string): string | null {\n const defaultBranch = getDefaultBranch(cwd) ?? 'main';\n // Fetch latest first\n git(['fetch', '--quiet'], cwd);\n const base = remoteBranchExists(defaultBranch, cwd) ? `origin/${defaultBranch}` : defaultBranch;\n const result = git(['rebase', base, branch], cwd);\n if (result.exitCode !== 0) {\n // Abort the failed rebase\n git(['rebase', '--abort'], cwd);\n return result.stderr || 'Rebase failed';\n }\n return null;\n}\n\n/** Count merge conflicts between a branch and the default branch. Returns 0 if clean. */\nexport function countConflicts(branch: string, cwd: string): number {\n const defaultBranch = getDefaultBranch(cwd) ?? 'main';\n const base = remoteBranchExists(defaultBranch, cwd) ? `origin/${defaultBranch}` : defaultBranch;\n\n // Use merge-tree to simulate merge without changing worktree\n const mergeBase = git(['merge-base', base, branch], cwd);\n if (mergeBase.exitCode !== 0) return 0;\n\n const result = git(['merge-tree', mergeBase.stdout, base, branch], cwd);\n // Count conflict markers in merge-tree output\n const conflicts = (result.stdout.match(/^<<<<<<< /gm) || []).length;\n return conflicts;\n}\n\n/** Check for unpushed commits. Returns the log output or empty string. */\nexport function getUnpushedCommits(cwd: string): string {\n const branch = getCurrentBranch(cwd);\n if (!branch) return '';\n\n const upstreamResult = git(['rev-parse', '--abbrev-ref', `${branch}@{upstream}`], cwd);\n if (upstreamResult.exitCode !== 0) return '';\n\n const upstream = upstreamResult.stdout;\n const logResult = git(['log', '--oneline', `${upstream}..HEAD`], cwd);\n return logResult.stdout;\n}\n"],"mappings":";;;;;;;;;AACA,SAAS,gBAAgB;AACzB,OAAO,QAAQ;AACf,OAAO,UAAU;AAUV,SAAS,IAAI,MAAgB,KAAwB;AAC1D,QAAM,OAAO,KAAK,KAAK,GAAG,GAAG,OAAO,GAAG,EAAE;AACzC,QAAM,SAAS,cAAM,KAAK,OAAO,MAAM;AAAA,IACrC;AAAA,IACA,UAAU;AAAA,IACV,OAAO,CAAC,QAAQ,QAAQ,MAAM;AAAA;AAAA;AAAA,IAG9B,aAAa;AAAA,EACf,CAAC;AAED,QAAM,IAAI;AAAA,IACR,SAAS,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