@blackbelt-technology/pi-dashboard-extension 0.7.0 → 0.9.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 (265) hide show
  1. package/.pi/skills/browser/SKILL.md +84 -29
  2. package/.pi/skills/browser/UPSTREAM.md +13 -1
  3. package/.pi/skills/browser/references/challenge.md +183 -0
  4. package/.pi/skills/browser/references/dashboard-relay.md +150 -0
  5. package/.pi/skills/browser/references/electron.agent.md +57 -0
  6. package/.pi/skills/browser/references/own-browser.md +305 -0
  7. package/.pi/skills/browser/references/web.agent.md +323 -0
  8. package/.pi/skills/browser/scripts/check-panerelay.sh +157 -0
  9. package/.pi/skills/doctor/SKILL.md +4 -9
  10. package/.pi/skills/doctor/_lib/checks.ts +133 -54
  11. package/.pi/skills/doctor/_lib/derive-tokens.ts +5 -0
  12. package/.pi/skills/doctor/modules/apple-tools.knowledge.hash +1 -0
  13. package/.pi/skills/doctor/modules/apple-tools.md +52 -0
  14. package/.pi/skills/doctor/modules/mcp-builtin.knowledge.hash +1 -0
  15. package/.pi/skills/doctor/modules/mcp-builtin.md +61 -0
  16. package/.pi/skills/doctor/modules/oauth-redirect-base.knowledge.hash +1 -0
  17. package/.pi/skills/doctor/modules/oauth-redirect-base.md +71 -0
  18. package/.pi/skills/doctor/modules/pi-resolution.knowledge.hash +1 -1
  19. package/.pi/skills/doctor/modules/pi-resolution.md +21 -1
  20. package/.pi/skills/doctor/modules/plugins-bridges.md +14 -1
  21. package/.pi/skills/pi-dashboard/SKILL.md +10 -3
  22. package/.pi/skills/pi-dashboard/references/api-reference.agent.md +69 -0
  23. package/.pi/skills/pi-dashboard/scripts/dashboard-bus.ts +4 -4
  24. package/.pi/skills/project-init/SKILL.md +41 -34
  25. package/.pi/skills/project-init/profiles/coding/AGENTS.md.tmpl +0 -23
  26. package/.pi/skills/project-init/profiles/docs/profile.json +1 -1
  27. package/README.md +19 -0
  28. package/agents/DoxTriage.md +80 -0
  29. package/package.json +30 -16
  30. package/src/ask-user-tool.ts +4 -0
  31. package/src/auto-session-namer.ts +486 -70
  32. package/src/autostart-guard.ts +99 -0
  33. package/src/autostart-lock.ts +258 -0
  34. package/src/bridge-activation.ts +26 -0
  35. package/src/bridge-context.ts +106 -23
  36. package/src/bridge-default-model-gate.ts +38 -0
  37. package/src/bridge-polling.ts +148 -0
  38. package/src/bridge-ticket-client.ts +105 -0
  39. package/src/bridge.ts +1760 -350
  40. package/src/canvas-tool.ts +5 -0
  41. package/src/command-handler.ts +392 -71
  42. package/src/connect-target.ts +130 -0
  43. package/src/connection.ts +846 -17
  44. package/src/custom-entry-forward.ts +92 -0
  45. package/src/endpoint-resolution.ts +253 -0
  46. package/src/event-forwarder.ts +42 -0
  47. package/src/extension-identity.ts +59 -0
  48. package/src/flow-event-wiring.ts +125 -3
  49. package/src/followup-buffer.ts +217 -0
  50. package/src/git-dir-watcher.ts +79 -0
  51. package/src/git-poll.ts +45 -12
  52. package/src/git-probe-scheduler.ts +119 -0
  53. package/src/git-tracker.ts +284 -0
  54. package/src/instance-verification.ts +156 -0
  55. package/src/local-token-header.ts +44 -0
  56. package/src/mcp-token-delivery.ts +147 -0
  57. package/src/message-update-coalescer.ts +340 -0
  58. package/src/model-refresh.ts +95 -0
  59. package/src/model-tracker.ts +118 -35
  60. package/src/notify-proxy.ts +36 -0
  61. package/src/path-gate/decide.ts +149 -0
  62. package/src/path-gate/grant-cache.ts +71 -0
  63. package/src/path-gate/grant-link.ts +108 -0
  64. package/src/path-gate/handler.ts +307 -0
  65. package/src/path-gate/index.ts +155 -0
  66. package/src/path-gate/resolve.ts +126 -0
  67. package/src/path-gate/roots.ts +137 -0
  68. package/src/path-gate/suppression.ts +27 -0
  69. package/src/pending-prompt-emitter.ts +59 -0
  70. package/src/pi-env.d.ts +6 -10
  71. package/src/pi-retry-settings.ts +91 -0
  72. package/src/plugin-request-client.ts +114 -0
  73. package/src/poll-cost.ts +40 -0
  74. package/src/pr-status.ts +338 -0
  75. package/src/process-metrics.ts +77 -1
  76. package/src/process-scan-scheduler.ts +137 -0
  77. package/src/process-scanner.ts +226 -247
  78. package/src/project-init/dox-kb-config.ts +3 -0
  79. package/src/project-init/scaffold.ts +1 -4
  80. package/src/project-init/seed-doctrine.ts +23 -60
  81. package/src/prompt-bus.ts +13 -0
  82. package/src/provider-register.ts +92 -21
  83. package/src/remote-registration-gate.ts +102 -0
  84. package/src/retry-tracker.ts +258 -86
  85. package/src/role-manager.ts +38 -91
  86. package/src/role-model-tools.ts +44 -3
  87. package/src/server-auto-start.ts +331 -20
  88. package/src/server-launcher.ts +70 -34
  89. package/src/server-pin-store.ts +92 -0
  90. package/src/session-move.ts +275 -0
  91. package/src/session-sync.ts +75 -20
  92. package/src/slash-dispatch.ts +66 -81
  93. package/src/subagent-fanout-admission.ts +234 -0
  94. package/src/subagent-forward-sites.ts +69 -0
  95. package/src/subagent-frame-buffer.ts +24 -3
  96. package/src/subagent-frame-strip.ts +109 -0
  97. package/src/subagent-saturation.ts +196 -0
  98. package/src/subagent-tick-throttle.ts +250 -0
  99. package/src/terminal-reload.ts +298 -0
  100. package/src/transcript-backfill.ts +151 -0
  101. package/src/transport-diagnostics.ts +76 -0
  102. package/src/tui-prompt-adapter.ts +13 -1
  103. package/src/turn-actionability.ts +20 -0
  104. package/src/ui-stale-guard.ts +58 -0
  105. package/src/usage-drain.ts +167 -0
  106. package/src/vcs-info.ts +261 -63
  107. package/.pi/skills/doctor/AGENTS.md +0 -27
  108. package/.pi/skills/project-init/dox-doctrine.md +0 -104
  109. package/src/AGENTS.md +0 -57
  110. package/src/__tests__/abort-latch.test.ts +0 -97
  111. package/src/__tests__/agent-settled.test.ts +0 -82
  112. package/src/__tests__/artifact-roots.test.ts +0 -83
  113. package/src/__tests__/ask-user-attachments.test.ts +0 -106
  114. package/src/__tests__/ask-user-schema-discriminator.test.ts +0 -141
  115. package/src/__tests__/ask-user-tool.test.ts +0 -571
  116. package/src/__tests__/auto-session-namer.test.ts +0 -339
  117. package/src/__tests__/bridge-default-model-apply.test.ts +0 -242
  118. package/src/__tests__/bridge-default-model-gate.test.ts +0 -50
  119. package/src/__tests__/bridge-entry-id-pi-070.test.ts +0 -174
  120. package/src/__tests__/bridge-followup-chat-order.test.ts +0 -215
  121. package/src/__tests__/bridge-followup-multi-entry.test.ts +0 -202
  122. package/src/__tests__/bridge-followup-mutation.test.ts +0 -217
  123. package/src/__tests__/bridge-followup-queue-drain.test.ts +0 -266
  124. package/src/__tests__/bridge-hasui-flip.test.ts +0 -109
  125. package/src/__tests__/bridge-no-queue-mutation.test.ts +0 -112
  126. package/src/__tests__/bridge-plugin-emit-event.test.ts +0 -44
  127. package/src/__tests__/bridge-queue-update-forward.test.ts +0 -77
  128. package/src/__tests__/bridge-resume-disconnect.test.ts +0 -333
  129. package/src/__tests__/bridge-shadow-queue-gate.test.ts +0 -299
  130. package/src/__tests__/bridge-shutdown-reset.test.ts +0 -159
  131. package/src/__tests__/bridge-slash-command-routing.test.ts +0 -458
  132. package/src/__tests__/bridge-stop-after-turn.test.ts +0 -72
  133. package/src/__tests__/bridge-system-followup.test.ts +0 -163
  134. package/src/__tests__/bridge-thinking-level-select.test.ts +0 -68
  135. package/src/__tests__/browser-skill-registered.test.ts +0 -84
  136. package/src/__tests__/build-provider-catalogue.test.ts +0 -210
  137. package/src/__tests__/command-handler.test.ts +0 -1180
  138. package/src/__tests__/commit-draft.test.ts +0 -100
  139. package/src/__tests__/connection-dropped-frames.test.ts +0 -78
  140. package/src/__tests__/connection-suppress-auto-start.test.ts +0 -97
  141. package/src/__tests__/connection.test.ts +0 -344
  142. package/src/__tests__/credentials-updated.test.ts +0 -26
  143. package/src/__tests__/custom-provider-apikey-roundtrip.test.ts +0 -128
  144. package/src/__tests__/cwd-missing-probe.test.ts +0 -82
  145. package/src/__tests__/dashboard-commands-shipped.test.ts +0 -53
  146. package/src/__tests__/dashboard-context-injector.test.ts +0 -190
  147. package/src/__tests__/dashboard-default-adapter.test.ts +0 -77
  148. package/src/__tests__/dev-build.test.ts +0 -79
  149. package/src/__tests__/doctor/checks.test.ts +0 -121
  150. package/src/__tests__/doctor/modules.test.ts +0 -64
  151. package/src/__tests__/doctor/provenance-hash.test.ts +0 -94
  152. package/src/__tests__/doctor/router.test.ts +0 -143
  153. package/src/__tests__/empty-actionable-guard-config.test.ts +0 -32
  154. package/src/__tests__/empty-actionable-guard.test.ts +0 -73
  155. package/src/__tests__/enrich-model-metadata.test.ts +0 -222
  156. package/src/__tests__/event-forwarder.test.ts +0 -119
  157. package/src/__tests__/extension-slash-command-detection.test.ts +0 -143
  158. package/src/__tests__/filter-enabled-models.test.ts +0 -151
  159. package/src/__tests__/fixtures/turn-actionability-fixtures.ts +0 -69
  160. package/src/__tests__/fork-entryid-timing.test.ts +0 -88
  161. package/src/__tests__/git-info-status.test.ts +0 -73
  162. package/src/__tests__/git-link-builder.test.ts +0 -102
  163. package/src/__tests__/git-poll.test.ts +0 -69
  164. package/src/__tests__/markdown-image-inliner.test.ts +0 -392
  165. package/src/__tests__/model-resolve.test.ts +0 -379
  166. package/src/__tests__/multiselect-dashboard-routing.test.ts +0 -203
  167. package/src/__tests__/multiselect-list.test.ts +0 -137
  168. package/src/__tests__/multiselect-polyfill.test.ts +0 -92
  169. package/src/__tests__/no-session-replacement-calls.test.ts +0 -99
  170. package/src/__tests__/no-tui-multiselect-arm-regression.test.ts +0 -81
  171. package/src/__tests__/openspec-activity-detector.test.ts +0 -337
  172. package/src/__tests__/openspec-cli-shim.test.ts +0 -145
  173. package/src/__tests__/openspec-poller.test.ts +0 -124
  174. package/src/__tests__/pi-version-tracker.test.ts +0 -109
  175. package/src/__tests__/process-metrics.test.ts +0 -47
  176. package/src/__tests__/process-scanner-kill.test.ts +0 -61
  177. package/src/__tests__/process-scanner.test.ts +0 -292
  178. package/src/__tests__/project-init-detect-stack.test.ts +0 -61
  179. package/src/__tests__/project-init-dox-kb-config.test.ts +0 -53
  180. package/src/__tests__/project-init-profiles.test.ts +0 -84
  181. package/src/__tests__/project-init-scaffold.test.ts +0 -139
  182. package/src/__tests__/project-init-seed-doctrine.test.ts +0 -100
  183. package/src/__tests__/project-trust.test.ts +0 -92
  184. package/src/__tests__/prompt-bus-wiring.test.ts +0 -791
  185. package/src/__tests__/prompt-bus.test.ts +0 -513
  186. package/src/__tests__/prompt-expander.test.ts +0 -398
  187. package/src/__tests__/provider-register-native-models.test.ts +0 -182
  188. package/src/__tests__/provider-register-reload.test.ts +0 -498
  189. package/src/__tests__/provider-register-thinking-levels.test.ts +0 -104
  190. package/src/__tests__/retry-tracker.test.ts +0 -152
  191. package/src/__tests__/role-manager.test.ts +0 -585
  192. package/src/__tests__/role-model-tools-registry-readiness.test.ts +0 -114
  193. package/src/__tests__/role-model-tools.test.ts +0 -229
  194. package/src/__tests__/search-files-completeness.test.ts +0 -111
  195. package/src/__tests__/search-files-ranking.test.ts +0 -168
  196. package/src/__tests__/server-auto-start.test.ts +0 -375
  197. package/src/__tests__/server-launcher-launch.test.ts +0 -96
  198. package/src/__tests__/server-launcher.test.ts +0 -101
  199. package/src/__tests__/server-probe.test.ts +0 -25
  200. package/src/__tests__/session-switch.test.ts +0 -139
  201. package/src/__tests__/session-sync.test.ts +0 -243
  202. package/src/__tests__/single-derivation-guard.test.ts +0 -39
  203. package/src/__tests__/source-detector.test.ts +0 -88
  204. package/src/__tests__/stats-extractor.test.ts +0 -92
  205. package/src/__tests__/subagent-frame-buffer.test.ts +0 -239
  206. package/src/__tests__/tool-result-image-inliner.test.ts +0 -206
  207. package/src/__tests__/tui-prompt-adapter.test.ts +0 -213
  208. package/src/__tests__/turn-actionability.test.ts +0 -86
  209. package/src/__tests__/ui-decorators.test.ts +0 -309
  210. package/src/__tests__/ui-modules.test.ts +0 -293
  211. package/src/__tests__/vcs-info.test.ts +0 -265
  212. package/src/__tests__/visibility-intent.test.ts +0 -43
  213. package/src/__tests__/watchdog.test.ts +0 -161
  214. package/src/abort-latch.ts.AGENTS.md +0 -3
  215. package/src/agent-settled.ts +0 -72
  216. package/src/agent-settled.ts.AGENTS.md +0 -3
  217. package/src/artifact-roots.ts.AGENTS.md +0 -3
  218. package/src/ask-user-attachments.ts.AGENTS.md +0 -3
  219. package/src/ask-user-tool.ts.AGENTS.md +0 -3
  220. package/src/auto-session-namer.ts.AGENTS.md +0 -3
  221. package/src/bridge-context.ts.AGENTS.md +0 -3
  222. package/src/bridge-default-model-gate.ts.AGENTS.md +0 -3
  223. package/src/bridge.ts.AGENTS.md +0 -3
  224. package/src/command-handler.ts.AGENTS.md +0 -3
  225. package/src/commit-draft-agent.ts.AGENTS.md +0 -3
  226. package/src/commit-draft.ts.AGENTS.md +0 -3
  227. package/src/connection.ts.AGENTS.md +0 -3
  228. package/src/dashboard-context-injector.ts.AGENTS.md +0 -3
  229. package/src/dashboard-default-adapter.ts.AGENTS.md +0 -3
  230. package/src/dev-build.ts.AGENTS.md +0 -3
  231. package/src/empty-actionable-guard-config.ts.AGENTS.md +0 -3
  232. package/src/empty-actionable-guard.ts.AGENTS.md +0 -3
  233. package/src/event-forwarder.ts.AGENTS.md +0 -3
  234. package/src/flow-event-wiring.ts.AGENTS.md +0 -3
  235. package/src/git-link-builder.ts.AGENTS.md +0 -3
  236. package/src/git-poll.ts.AGENTS.md +0 -3
  237. package/src/hasui-flip.ts.AGENTS.md +0 -3
  238. package/src/markdown-image-inliner.ts.AGENTS.md +0 -3
  239. package/src/model-tracker.ts.AGENTS.md +0 -3
  240. package/src/multiselect-decode.ts.AGENTS.md +0 -3
  241. package/src/multiselect-list.ts.AGENTS.md +0 -3
  242. package/src/multiselect-polyfill.ts.AGENTS.md +0 -3
  243. package/src/openspec-cli-shim.ts.AGENTS.md +0 -7
  244. package/src/process-metrics.ts.AGENTS.md +0 -3
  245. package/src/process-scanner.ts.AGENTS.md +0 -3
  246. package/src/project-init/AGENTS.md +0 -12
  247. package/src/project-trust.ts.AGENTS.md +0 -3
  248. package/src/prompt-bus.ts.AGENTS.md +0 -3
  249. package/src/prompt-expander.ts.AGENTS.md +0 -3
  250. package/src/provider-register.ts.AGENTS.md +0 -3
  251. package/src/retry-tracker.ts.AGENTS.md +0 -3
  252. package/src/role-manager.ts.AGENTS.md +0 -3
  253. package/src/role-model-tools.ts.AGENTS.md +0 -3
  254. package/src/server-auto-start.ts.AGENTS.md +0 -3
  255. package/src/server-launcher.ts.AGENTS.md +0 -3
  256. package/src/session-sync.ts.AGENTS.md +0 -3
  257. package/src/slash-dispatch.ts.AGENTS.md +0 -3
  258. package/src/source-detector.ts.AGENTS.md +0 -3
  259. package/src/subagent-frame-buffer.ts.AGENTS.md +0 -3
  260. package/src/tool-result-image-inliner.ts.AGENTS.md +0 -3
  261. package/src/tui-prompt-adapter.ts.AGENTS.md +0 -3
  262. package/src/turn-actionability.ts.AGENTS.md +0 -3
  263. package/src/ui-modules.ts.AGENTS.md +0 -3
  264. package/src/vcs-info.ts.AGENTS.md +0 -3
  265. package/src/visibility-intent.ts.AGENTS.md +0 -3
@@ -0,0 +1,99 @@
1
+ /**
2
+ * Auto-start guards: the worktree refusal predicate (D3) and the durable
3
+ * auto-start log (D4).
4
+ *
5
+ * A pi session running inside a git worktree resolves its dashboard server
6
+ * CLI from that worktree (`resolveServerCliPath()`), so its auto-start would
7
+ * spawn the worktree's server on the SHARED default ports and hijack the host
8
+ * dashboard's gateway. Refusal keys on the resolved **cliPath** (which code is
9
+ * spawned), never on cwd (where the session sits).
10
+ *
11
+ * See change: fix-worktree-server-autostart-leak.
12
+ */
13
+ import { appendFileSync, mkdirSync, realpathSync } from "node:fs";
14
+ import { dirname } from "node:path";
15
+ import { getDashboardServerLogPath } from "@blackbelt-technology/pi-dashboard-shared/dashboard-paths.js";
16
+ // Imported (not re-exported) from the config module so the predicate can never
17
+ // desync from the actual defaults it is protecting. The re-export had no
18
+ // importer — every caller reads the constants from `config.js` directly.
19
+ import {
20
+ DEFAULT_DASHBOARD_PORT,
21
+ DEFAULT_GATEWAY_PORT,
22
+ } from "@blackbelt-technology/pi-dashboard-shared/config.js";
23
+
24
+ /** The path segment that marks a worktree checkout. */
25
+ const WORKTREE_SEGMENT = ".worktrees";
26
+
27
+ /**
28
+ * True when `p` contains a `.worktrees` **path segment**. Segment-aware, so
29
+ * `/repo/.worktrees-backup/os-x/...` does NOT match (E18).
30
+ */
31
+ function hasWorktreeSegment(p: string): boolean {
32
+ // Normalise both separators so a Windows path is matched the same way.
33
+ const parts = p.split(/[\\/]/);
34
+ return parts.includes(WORKTREE_SEGMENT);
35
+ }
36
+
37
+ /**
38
+ * Worktree predicate over a resolved CLI path.
39
+ *
40
+ * Clarification C3: match on **both** the pre-realpath and the post-realpath
41
+ * spelling. `realpath` strips a `.worktrees` segment reached via a symlink
42
+ * (so post-realpath alone misses symlinked worktrees), while pre-realpath
43
+ * alone misses a symlink that POINTS INTO a real worktree. Either limb
44
+ * matching is a refusal.
45
+ */
46
+ export function isWorktreeCliPath(
47
+ cliPath: string,
48
+ realpath: (p: string) => string = realpathSync,
49
+ ): boolean {
50
+ if (hasWorktreeSegment(cliPath)) return true;
51
+ let resolved: string;
52
+ try {
53
+ resolved = realpath(cliPath);
54
+ } catch {
55
+ // Path does not exist yet — the literal spelling is all we have.
56
+ return false;
57
+ }
58
+ return hasWorktreeSegment(resolved);
59
+ }
60
+
61
+ /**
62
+ * Should this session refuse to auto-start a dashboard server?
63
+ *
64
+ * Refuse when the resolved cliPath is a worktree AND it would take at least
65
+ * one shared default port (D3 / E15: gateway-port-only evasion also refuses).
66
+ * A fully isolated worktree dashboard (both ports moved off their defaults —
67
+ * what `isolated-ui-verification` already allocates) is permitted (E16).
68
+ */
69
+ export function shouldRefuseWorktreeAutoStart(
70
+ args: { cliPath: string; port: number; piPort: number },
71
+ realpath?: (p: string) => string,
72
+ ): boolean {
73
+ if (!isWorktreeCliPath(args.cliPath, realpath)) return false;
74
+ return args.port === DEFAULT_DASHBOARD_PORT || args.piPort === DEFAULT_GATEWAY_PORT;
75
+ }
76
+
77
+ /**
78
+ * Append one line to the dashboard server log.
79
+ *
80
+ * D4: `deps.notify` is a transient TUI toast (invisible headless), so refusal
81
+ * and lock-loss must be greppable on disk. The refusal path SKIPS the launch
82
+ * primitive that normally creates this file, so we create the directory and
83
+ * the file ourselves. Best-effort: logging must never break auto-start.
84
+ */
85
+ export function appendAutoStartLog(
86
+ message: string,
87
+ opts: { logPath?: string; now?: () => Date } = {},
88
+ ): void {
89
+ const logPath = opts.logPath ?? getDashboardServerLogPath();
90
+ const stamp = (opts.now?.() ?? new Date()).toISOString();
91
+ try {
92
+ mkdirSync(dirname(logPath), { recursive: true });
93
+ appendFileSync(logPath, `[${stamp}] [auto-start] ${message}\n`);
94
+ } catch {
95
+ /* best-effort — never throw out of the auto-start path */
96
+ }
97
+ }
98
+
99
+
@@ -0,0 +1,258 @@
1
+ /**
2
+ * Single-flight auto-start lock (D2).
3
+ *
4
+ * Nothing serialises the check→spawn window across processes, so N pi
5
+ * sessions each observe "no dashboard" and each spawn one. An advisory
6
+ * lockfile at `~/.pi/dashboard/autostart-<port>.lock`, acquired with an
7
+ * atomic `open(..., 'wx')`, admits exactly one spawner per user per port.
8
+ *
9
+ * Staleness is deliberately more than "is the pid alive":
10
+ * - the spawned server is `detached: true`, so a dead session does not mean
11
+ * a dead spawn — the recorded `childPid` is consulted too (E5);
12
+ * - a reused pid makes a dead holder look alive, so the holder process's
13
+ * start time is cross-checked against the recorded `startedAt` (E6);
14
+ * - a holder that simply died without cleaning up must not wedge auto-start
15
+ * forever, so the lock also expires past `SPAWN_READINESS_BUDGET_MS` (E8).
16
+ *
17
+ * SCOPE — this lock is ADVISORY, and deliberately so. The atomic `wx` create
18
+ * makes the common uncontended path exact, but the break-and-reacquire path
19
+ * (`rmSync` + re-create) and `recordChildPid`'s rewrite are two-step and can
20
+ * interleave under a rare double-break. The backstop for that residual window
21
+ * is the server side of this same change: a loser that does spawn now binds,
22
+ * fails, tears its listeners down and exits rather than lingering on the
23
+ * gateway port. Making the lock exact would need a rename-based claim; it is
24
+ * not worth the complexity given that backstop.
25
+ *
26
+ * See change: fix-worktree-server-autostart-leak.
27
+ */
28
+ import { closeSync, openSync, readFileSync, rmSync, writeSync } from "node:fs";
29
+ import { execFileSync } from "node:child_process"; // ban:child_process-ok — pid start-time probe
30
+ import { join } from "node:path";
31
+ import { getDashboardConfigDir } from "@blackbelt-technology/pi-dashboard-shared/dashboard-paths.js";
32
+ import { isProcessAlive } from "@blackbelt-technology/pi-dashboard-shared/platform/process.js";
33
+ import { SPAWN_READINESS_BUDGET_MS } from "@blackbelt-technology/pi-dashboard-shared/config.js";
34
+
35
+ /** On-disk lock record. `sessionPid` is the ONLY spelling of the holder pid. */
36
+ export interface AutoStartLockRecord {
37
+ /** pid of the pi session holding the lock. */
38
+ sessionPid: number;
39
+ /** epoch ms at which the lock was acquired. */
40
+ startedAt: number;
41
+ /** resolved server CLI path the holder is spawning. */
42
+ cliPath: string;
43
+ /** pid of the detached server child, once known. */
44
+ childPid?: number;
45
+ }
46
+
47
+ /** Injectable OS probes (tests substitute; production uses the real ones). */
48
+ export interface LockProbes {
49
+ now: () => number;
50
+ /** True when a process with this pid exists. */
51
+ isAlive: (pid: number) => boolean;
52
+ /** Process start time in epoch ms, or null when unknown/dead. */
53
+ processStartedAt: (pid: number) => number | null;
54
+ }
55
+
56
+ export function defaultProbes(): LockProbes {
57
+ return {
58
+ now: Date.now,
59
+ isAlive: (pid) => isProcessAlive(pid),
60
+ processStartedAt: (pid) => {
61
+ // `ps` is POSIX. On Windows the spawn simply fails and the catch below
62
+ // returns null, which disables pid-reuse detection there: staleness
63
+ // falls back to liveness plus the age bound. Degrading is the correct
64
+ // direction — a false "stale" verdict would break a LIVE holder's lock
65
+ // and double-spawn, which is the bug this lock exists to prevent.
66
+ try {
67
+ const out = execFileSync("ps", ["-o", "lstart=", "-p", String(pid)], {
68
+ encoding: "utf8",
69
+ }).trim();
70
+ if (!out) return null;
71
+ const ms = Date.parse(out);
72
+ return Number.isFinite(ms) ? ms : null;
73
+ } catch {
74
+ return null;
75
+ }
76
+ },
77
+ };
78
+ }
79
+
80
+ export function autoStartLockPath(port: number, dir?: string): string {
81
+ return join(dir ?? getDashboardConfigDir(), `autostart-${port}.lock`);
82
+ }
83
+
84
+ /** Pid-reuse tolerance: a holder that started this long AFTER the lock is a reuse. */
85
+ const PID_REUSE_SLACK_MS = 2_000;
86
+
87
+ /**
88
+ * Pure staleness decision. A stale lock may be broken and re-acquired.
89
+ *
90
+ * Order matters: an alive detached child keeps the lock live even when the
91
+ * session that started it is gone (E5), because breaking the lock there would
92
+ * race the child that is still binding the port.
93
+ */
94
+ export function isLockStale(
95
+ lock: AutoStartLockRecord | null,
96
+ probes: LockProbes,
97
+ budgetMs: number = SPAWN_READINESS_BUDGET_MS,
98
+ ): boolean {
99
+ // Unreadable / corrupt lock (X7): stale and breakable, never a throw.
100
+ if (!lock || typeof lock.sessionPid !== "number" || typeof lock.startedAt !== "number") {
101
+ return true;
102
+ }
103
+
104
+ // E5: the detached child outlives the session — an alive child holds the lock.
105
+ if (typeof lock.childPid === "number" && probes.isAlive(lock.childPid)) return false;
106
+
107
+ const holderAlive = probes.isAlive(lock.sessionPid);
108
+
109
+ // E6: pid reuse — the "holder" is a younger process that inherited the pid.
110
+ if (holderAlive) {
111
+ const started = probes.processStartedAt(lock.sessionPid);
112
+ if (started !== null && started > lock.startedAt + PID_REUSE_SLACK_MS) return true;
113
+ } else {
114
+ return true;
115
+ }
116
+
117
+ // E7/E8: even a live holder cannot hold past the readiness budget.
118
+ return probes.now() - lock.startedAt > budgetMs;
119
+ }
120
+
121
+ export function readLock(path: string): AutoStartLockRecord | null {
122
+ try {
123
+ return JSON.parse(readFileSync(path, "utf8")) as AutoStartLockRecord;
124
+ } catch {
125
+ // Absent OR corrupt JSON (X7) — both mean "no valid holder".
126
+ return null;
127
+ }
128
+ }
129
+
130
+ export interface AcquireResult {
131
+ /** True when this process now owns the lock. */
132
+ acquired: boolean;
133
+ /** The record blocking acquisition (for the X3 log line). */
134
+ holder?: AutoStartLockRecord | null;
135
+ /** True when the lock could not be used at all (X6: unwritable dir). */
136
+ degraded?: boolean;
137
+ }
138
+
139
+ function writeLockFile(path: string, record: AutoStartLockRecord): boolean {
140
+ try {
141
+ // Atomic create-or-fail. Losing this race means another session won.
142
+ const fd = openSync(path, "wx");
143
+ try {
144
+ writeSync(fd, JSON.stringify(record));
145
+ } finally {
146
+ closeSync(fd);
147
+ }
148
+ return true;
149
+ } catch {
150
+ return false;
151
+ }
152
+ }
153
+
154
+ /**
155
+ * Try to become the single flight for `port`.
156
+ *
157
+ * X6: when the lock directory is unwritable we DEGRADE to the pre-lock
158
+ * behaviour (`acquired: true, degraded: true`) rather than throwing — losing
159
+ * single-flight is strictly better than losing auto-start.
160
+ */
161
+ export function acquireAutoStartLock(
162
+ args: { port: number; cliPath: string; dir?: string; sessionPid?: number },
163
+ probes: LockProbes = defaultProbes(),
164
+ budgetMs: number = SPAWN_READINESS_BUDGET_MS,
165
+ ): AcquireResult {
166
+ const path = autoStartLockPath(args.port, args.dir);
167
+ const record: AutoStartLockRecord = {
168
+ sessionPid: args.sessionPid ?? process.pid,
169
+ startedAt: probes.now(),
170
+ cliPath: args.cliPath,
171
+ };
172
+
173
+ if (writeLockFile(path, record)) return { acquired: true };
174
+
175
+ // Someone holds it — or the directory is unwritable.
176
+ const holder = readLock(path);
177
+ if (holder === null && !isReadableFile(path)) {
178
+ // The create failed and we cannot read a lock record back — the directory
179
+ // or the file is unusable (X6: unwritable/unreadable). Degrade rather than
180
+ // block auto-start: losing single-flight beats losing the dashboard.
181
+ return { acquired: true, degraded: true };
182
+ }
183
+
184
+ if (!isLockStale(holder, probes, budgetMs)) return { acquired: false, holder };
185
+
186
+ // Stale: break it and retry once. A concurrent breaker may beat us — then
187
+ // we genuinely lost and must not spawn.
188
+ try {
189
+ rmSync(path, { force: true });
190
+ } catch {
191
+ return { acquired: false, holder };
192
+ }
193
+ if (writeLockFile(path, { ...record, startedAt: probes.now() })) return { acquired: true };
194
+ return { acquired: false, holder: readLock(path) };
195
+ }
196
+
197
+ /**
198
+ * True only when the lock file exists AND we can read it. An absent file, or
199
+ * one we cannot read (EACCES/EPERM), both mean "no holder we can honour" —
200
+ * treating an unreadable lock as held would wedge auto-start instead of
201
+ * degrading (X6).
202
+ */
203
+ function isReadableFile(path: string): boolean {
204
+ try {
205
+ readFileSync(path);
206
+ return true;
207
+ } catch {
208
+ return false;
209
+ }
210
+ }
211
+
212
+ /** Record the detached child's pid once the launch primitive surfaces it. */
213
+ export function recordChildPid(
214
+ port: number,
215
+ childPid: number,
216
+ dir?: string,
217
+ sessionPid: number = process.pid,
218
+ ): void {
219
+ const path = autoStartLockPath(port, dir);
220
+ const lock = readLock(path);
221
+ // Only mutate a lock we still own. A holder that overran the budget may find
222
+ // its lock already broken and re-acquired by someone else; writing into that
223
+ // record would corrupt the new holder's state.
224
+ if (!lock || lock.sessionPid !== sessionPid) return;
225
+ try {
226
+ const fd = openSync(path, "w");
227
+ try {
228
+ writeSync(fd, JSON.stringify({ ...lock, childPid }));
229
+ } finally {
230
+ closeSync(fd);
231
+ }
232
+ } catch {
233
+ /* best-effort */
234
+ }
235
+ }
236
+
237
+ /**
238
+ * Release the lock. MUST run in a `finally` covering ready, failed and
239
+ * timed-out spawns (E9) — otherwise a failed spawn wedges every other
240
+ * session until the staleness budget elapses.
241
+ */
242
+ export function releaseAutoStartLock(
243
+ port: number,
244
+ dir?: string,
245
+ sessionPid: number = process.pid,
246
+ ): void {
247
+ const path = autoStartLockPath(port, dir);
248
+ // Same ownership rule as `recordChildPid`: never delete a lock that is no
249
+ // longer ours, or a slow holder's `finally` frees the NEW holder's lock and
250
+ // re-opens the double-spawn window the lock exists to close.
251
+ const lock = readLock(path);
252
+ if (lock && lock.sessionPid !== sessionPid) return;
253
+ try {
254
+ rmSync(path, { force: true });
255
+ } catch {
256
+ /* best-effort */
257
+ }
258
+ }
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Bridge activation gate. Decides once per factory invocation, BEFORE any
3
+ * registration, whether the bridge runs in this pi process.
4
+ *
5
+ * Precedence: `PI_DASHBOARD_BRIDGE` env > `bridge.enabled` config > on.
6
+ * A recognised env value never touches the config file. Any failure while
7
+ * resolving fails OPEN (bridge activates) and emits no output — the opt-out
8
+ * must never be able to break the dashboard through an error.
9
+ *
10
+ * See change: add-bridge-env-opt-out.
11
+ */
12
+ import {
13
+ type BridgeActivationConfig,
14
+ bridgeEnvOverride,
15
+ } from "@blackbelt-technology/pi-dashboard-shared/config.js";
16
+
17
+ export function shouldActivateBridge(
18
+ env: Record<string, string | undefined>,
19
+ readConfig: () => BridgeActivationConfig,
20
+ ): boolean {
21
+ try {
22
+ return bridgeEnvOverride(env) ?? readConfig().enabled;
23
+ } catch {
24
+ return true;
25
+ }
26
+ }
@@ -3,7 +3,10 @@
3
3
  * Avoids passing 14+ closure variables to every extracted function.
4
4
  */
5
5
  import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
6
+ import { shouldSkipByPrefilter } from "./auto-session-namer.js";
6
7
  import type { ConnectionManager } from "./connection.js";
8
+ import type { GitTracker } from "./git-tracker.js";
9
+ import type { PrStatusScheduler } from "./pr-status.js";
7
10
 
8
11
  export interface BridgeContext {
9
12
  pi: ExtensionAPI;
@@ -27,7 +30,24 @@ export interface BridgeContext {
27
30
  lastSessionDir: string | undefined;
28
31
  lastFirstMessage: string | undefined;
29
32
  lastGitBranch: string | undefined;
30
- lastGitPrNumber: number | undefined;
33
+ /**
34
+ * Last serialized PR tuple (`PrTuple`) sent via `git_info_update`, or
35
+ * `undefined` when nothing sent yet. Replaces `lastGitPrNumber`.
36
+ * See change: redesign-composer-session-strip (D5).
37
+ */
38
+ lastGitPrJson: string | undefined;
39
+ /**
40
+ * Per-bridge async PR-status scheduler (stable reference across
41
+ * `syncBc()` snapshots). Absent in unit-test contexts that don't need it.
42
+ * See change: redesign-composer-session-strip (D5).
43
+ */
44
+ prStatus?: PrStatusScheduler;
45
+ /**
46
+ * Per-bridge git tracker (facts cache, HEAD branch, async status probe).
47
+ * Stable reference across `syncBc()` snapshots. Absent in unit-test contexts.
48
+ * See change: optimize-polling-hot-paths.
49
+ */
50
+ gitTracker?: GitTracker;
31
51
  /**
32
52
  * Last serialized `GitWorktreeInfo` snapshot sent to the server, or
33
53
  * the literal string `"null"` when we explicitly cleared worktree
@@ -92,12 +112,30 @@ export interface BridgeContext {
92
112
  // separately by the `__`-prefix rule. See change: fix-extension-slash-commands-in-dashboard.
93
113
  export const DASHBOARD_NATIVE_COMMANDS = new Set(["roles"]);
94
114
 
95
- /** Filter out hidden commands (names starting with __) and dashboard-native commands from commands list */
115
+ /**
116
+ * Filter out hidden commands (names starting with __) and dashboard-native
117
+ * commands from the commands list, and fill in `CommandInfo.path` from pi's
118
+ * `sourceInfo.path`.
119
+ *
120
+ * The path mapping lives here, not at a sender, because all five
121
+ * `commands_list` senders pass through this one function (session register,
122
+ * spawn, flow rediscovery, `session_start` reload, `request_commands`). The
123
+ * server retains the *latest* list, so a sender that skipped the mapping would
124
+ * replace a good list with a path-less one and flip every skill to
125
+ * `not-loaded`. `sourceInfo` is a pi-internal shape, so its absence is
126
+ * tolerated rather than assumed. See change: fix-skill-discovery-parity.
127
+ */
96
128
  export function filterHiddenCommands(commands: any[]): any[] {
97
- return commands.filter((cmd) =>
98
- !cmd.name.startsWith("__") &&
99
- !DASHBOARD_NATIVE_COMMANDS.has(cmd.name)
100
- );
129
+ return commands
130
+ .filter((cmd) =>
131
+ !cmd.name.startsWith("__") &&
132
+ !DASHBOARD_NATIVE_COMMANDS.has(cmd.name)
133
+ )
134
+ .map((cmd) => {
135
+ const sourcePath = cmd?.sourceInfo?.path;
136
+ if (cmd?.path !== undefined || typeof sourcePath !== "string") return cmd;
137
+ return { ...cmd, path: sourcePath };
138
+ });
101
139
  }
102
140
 
103
141
  /**
@@ -126,23 +164,6 @@ export function isExtensionSlashCommand(
126
164
  return commandList.some((c) => c?.name === cmdName && c?.source === "extension");
127
165
  }
128
166
 
129
- /**
130
- * Feature-detect upstream `pi.dispatchCommand(text, opts)` (pi 0.71+).
131
- * Returns true iff `dispatchCommand` resolves to a function on the supplied
132
- * object. Fast path uses a direct `typeof` access; when that is false an
133
- * `in`-operator fallback with a guarded `typeof` detects getter-backed /
134
- * Proxy-hidden properties. Returns false for null/undefined and non-functions.
135
- * See change: resolve-global-prompt-templates-from-dashboard.
136
- */
137
- export function hasDispatchCommand(pi: unknown): boolean {
138
- if (pi == null) return false;
139
- if (typeof (pi as any).dispatchCommand === "function") return true;
140
- if ("dispatchCommand" in (pi as object)) {
141
- return typeof (pi as any).dispatchCommand === "function";
142
- }
143
- return false;
144
- }
145
-
146
167
  /**
147
168
  * Pure predicate: is this bridge running inside a dashboard-spawned
148
169
  * headless `pi --mode rpc` session?
@@ -215,6 +236,68 @@ export function extractFirstAssistantReply(ctx: any): string | undefined {
215
236
  return undefined;
216
237
  }
217
238
 
239
+ /** Concatenated text of one entry's content, or "" when it carries none. */
240
+ function entryText(entry: any): string {
241
+ if (typeof entry?.content === "string") return entry.content;
242
+ if (!Array.isArray(entry?.content)) return "";
243
+ let text = "";
244
+ for (const part of entry.content) {
245
+ if (part?.type === "text" && typeof part.text === "string") text += part.text;
246
+ }
247
+ return text;
248
+ }
249
+
250
+ /**
251
+ * The ADVANCING transcript window fed to the auto-naming summarizer: the most
252
+ * recent user entry carrying non-empty text — skipping tool-result-only entries
253
+ * and empty entries — paired with the assistant reply of that same turn.
254
+ *
255
+ * Naming used to send the FIRST user message and FIRST assistant reply forever,
256
+ * so every retry re-sent a byte-identical request and a session that opened
257
+ * with a greeting was skipped for life. Only WHICH turn is sent changes here:
258
+ * the slice bounds are preserved exactly (user 200 chars, assistant 2000), so
259
+ * at most two bounded slices still leave the process.
260
+ * See change: fix-auto-naming-reasoning-model (design D6).
261
+ */
262
+ export function extractLatestTurnWindow(ctx: any): { userMsg?: string; assistantReply?: string } {
263
+ try {
264
+ const entries = ctx?.sessionManager?.getEntries?.();
265
+ if (!entries || !Array.isArray(entries)) return {};
266
+
267
+ const windowAt = (i: number, text: string) => {
268
+ let assistantReply: string | undefined;
269
+ for (let j = i + 1; j < entries.length; j++) {
270
+ if (entries[j]?.role !== "assistant") continue;
271
+ const reply = entryText(entries[j]);
272
+ if (reply) { assistantReply = reply.slice(0, 2000); break; }
273
+ }
274
+ return { userMsg: text.slice(0, 200), assistantReply };
275
+ };
276
+
277
+ let latestNonEmpty: { i: number; text: string } | undefined;
278
+ for (let i = entries.length - 1; i >= 0; i--) {
279
+ const entry = entries[i];
280
+ if (entry?.role !== "user") continue;
281
+ const text = entryText(entry).trim();
282
+ // A tool-result-only entry carries the `user` role but no text — it is
283
+ // not something a human said, so it can never be the naming window.
284
+ if (!text) continue;
285
+ if (latestNonEmpty === undefined) latestNonEmpty = { i, text };
286
+ // Select the latest turn the PRE-FILTER would accept. Selecting merely
287
+ // the latest non-empty turn means a trailing "ok" / "thanks" masks an
288
+ // otherwise-nameable session, because the pre-filter then rejects the
289
+ // window and the session is skipped — the exact defect the advancing
290
+ // window exists to remove.
291
+ if (!shouldSkipByPrefilter(text)) return windowAt(i, text);
292
+ }
293
+ // Nothing substantive was ever said: fall back to the latest non-empty
294
+ // turn so a genuinely trivial session still reports `skipped-prefilter`
295
+ // rather than `not-ready`.
296
+ if (latestNonEmpty) return windowAt(latestNonEmpty.i, latestNonEmpty.text);
297
+ } catch { /* ignore */ }
298
+ return {};
299
+ }
300
+
218
301
  /**
219
302
  * Defensive read of pi's `ctx.cwd` guarded getter. That getter throws once the
220
303
  * session is replaced (new/fork/resume/reload). During a `session_start` for a
@@ -21,6 +21,9 @@
21
21
  * See changes: fix-resume-keeps-session-model (original gate),
22
22
  * fix-default-model-new-session-entry-count (signal correction).
23
23
  */
24
+ /**
25
+ * Inputs to {@link shouldApplyDefaultModel}.
26
+ */
24
27
  export interface DefaultModelGateInput {
25
28
  /** `event.reason` from the pi `session_start` event. */
26
29
  reason: string | undefined;
@@ -37,6 +40,36 @@ export interface DefaultModelGateInput {
37
40
  hasModelRegistry: boolean;
38
41
  /** Whether `config.defaultModel` is set to a non-empty string. */
39
42
  hasDefaultModel: boolean;
43
+ /**
44
+ * Whether the pi process was launched with an explicit `--model` argument.
45
+ * An explicit model on the command line is authoritative — a "default"
46
+ * never overrides it. Derive it in the bridge via
47
+ * {@link hasExplicitModelArg}(process.argv).
48
+ * See change: fix-default-model-clobbers-explicit-model (issue #595).
49
+ */
50
+ hasExplicitModel: boolean;
51
+ }
52
+
53
+ /**
54
+ * True when the pi process argv carries an explicit `--model` flag.
55
+ *
56
+ * Exact-token match on `--model`, mirroring pi's own parser (`cli/args.js`:
57
+ * `arg === "--model"`, value in the next argv slot) — the `--model=x` equals
58
+ * form is not a pi flag, `--models` is a distinct flag, and there is no `-m`
59
+ * alias. The bridge runs inside the pi process, so the argv to pass is
60
+ * pi's own `process.argv` — this covers every spawner that passes `--model`
61
+ * (pi-subagents children, automation-plugin run spawns, worktree init hooks,
62
+ * and a user's manual `pi --model X`).
63
+ *
64
+ * Accepted fail-safe false-positives (pinned by tests): a trailing dangling
65
+ * `--model` with no value, a literal `--model` after `--`, and a `--model`
66
+ * swallowed as another flag's value all count as explicit — skipping the
67
+ * dashboard default is always safer than clobbering the caller's choice.
68
+ *
69
+ * See change: fix-default-model-clobbers-explicit-model (issue #595).
70
+ */
71
+ export function hasExplicitModelArg(argv: string[]): boolean {
72
+ return argv.includes("--model");
40
73
  }
41
74
 
42
75
  export function shouldApplyDefaultModel(args: DefaultModelGateInput): boolean {
@@ -44,5 +77,10 @@ export function shouldApplyDefaultModel(args: DefaultModelGateInput): boolean {
44
77
  if (args.entryCount !== 0) return false;
45
78
  if (!args.hasModelRegistry) return false;
46
79
  if (!args.hasDefaultModel) return false;
80
+ // An explicit `--model` on the launch command line is the spawner's resolved
81
+ // choice (subagent agent definition, automation run, worktree init hook, or
82
+ // the user) — the configured default never overrides it, matching plain pi
83
+ // CLI behavior. See change: fix-default-model-clobbers-explicit-model.
84
+ if (args.hasExplicitModel) return false;
47
85
  return true;
48
86
  }