@blackbelt-technology/pi-dashboard-team-plugin 0.8.0 → 0.10.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 (174) hide show
  1. package/README.md +18 -1
  2. package/dist/app/assets/{InlineTerminalCard-BRjmM13k.js → InlineTerminalCard-DW7qFTuI.js} +1 -1
  3. package/dist/app/assets/KaTeX_AMS-Regular-BQhdFMY1.woff2 +0 -0
  4. package/dist/app/assets/KaTeX_AMS-Regular-DMm9YOAa.woff +0 -0
  5. package/dist/app/assets/KaTeX_AMS-Regular-DRggAlZN.ttf +0 -0
  6. package/dist/app/assets/KaTeX_Caligraphic-Bold-ATXxdsX0.ttf +0 -0
  7. package/dist/app/assets/KaTeX_Caligraphic-Bold-BEiXGLvX.woff +0 -0
  8. package/dist/app/assets/KaTeX_Caligraphic-Bold-Dq_IR9rO.woff2 +0 -0
  9. package/dist/app/assets/KaTeX_Caligraphic-Regular-CTRA-rTL.woff +0 -0
  10. package/dist/app/assets/KaTeX_Caligraphic-Regular-Di6jR-x-.woff2 +0 -0
  11. package/dist/app/assets/KaTeX_Caligraphic-Regular-wX97UBjC.ttf +0 -0
  12. package/dist/app/assets/KaTeX_Fraktur-Bold-BdnERNNW.ttf +0 -0
  13. package/dist/app/assets/KaTeX_Fraktur-Bold-BsDP51OF.woff +0 -0
  14. package/dist/app/assets/KaTeX_Fraktur-Bold-CL6g_b3V.woff2 +0 -0
  15. package/dist/app/assets/KaTeX_Fraktur-Regular-CB_wures.ttf +0 -0
  16. package/dist/app/assets/KaTeX_Fraktur-Regular-CTYiF6lA.woff2 +0 -0
  17. package/dist/app/assets/KaTeX_Fraktur-Regular-Dxdc4cR9.woff +0 -0
  18. package/dist/app/assets/KaTeX_Main-Bold-Cx986IdX.woff2 +0 -0
  19. package/dist/app/assets/KaTeX_Main-Bold-Jm3AIy58.woff +0 -0
  20. package/dist/app/assets/KaTeX_Main-Bold-waoOVXN0.ttf +0 -0
  21. package/dist/app/assets/KaTeX_Main-BoldItalic-DxDJ3AOS.woff2 +0 -0
  22. package/dist/app/assets/KaTeX_Main-BoldItalic-DzxPMmG6.ttf +0 -0
  23. package/dist/app/assets/KaTeX_Main-BoldItalic-SpSLRI95.woff +0 -0
  24. package/dist/app/assets/KaTeX_Main-Italic-3WenGoN9.ttf +0 -0
  25. package/dist/app/assets/KaTeX_Main-Italic-BMLOBm91.woff +0 -0
  26. package/dist/app/assets/KaTeX_Main-Italic-NWA7e6Wa.woff2 +0 -0
  27. package/dist/app/assets/KaTeX_Main-Regular-B22Nviop.woff2 +0 -0
  28. package/dist/app/assets/KaTeX_Main-Regular-Dr94JaBh.woff +0 -0
  29. package/dist/app/assets/KaTeX_Main-Regular-ypZvNtVU.ttf +0 -0
  30. package/dist/app/assets/KaTeX_Math-BoldItalic-B3XSjfu4.ttf +0 -0
  31. package/dist/app/assets/KaTeX_Math-BoldItalic-CZnvNsCZ.woff2 +0 -0
  32. package/dist/app/assets/KaTeX_Math-BoldItalic-iY-2wyZ7.woff +0 -0
  33. package/dist/app/assets/KaTeX_Math-Italic-DA0__PXp.woff +0 -0
  34. package/dist/app/assets/KaTeX_Math-Italic-flOr_0UB.ttf +0 -0
  35. package/dist/app/assets/KaTeX_Math-Italic-t53AETM-.woff2 +0 -0
  36. package/dist/app/assets/KaTeX_SansSerif-Bold-CFMepnvq.ttf +0 -0
  37. package/dist/app/assets/KaTeX_SansSerif-Bold-D1sUS0GD.woff2 +0 -0
  38. package/dist/app/assets/KaTeX_SansSerif-Bold-DbIhKOiC.woff +0 -0
  39. package/dist/app/assets/KaTeX_SansSerif-Italic-C3H0VqGB.woff2 +0 -0
  40. package/dist/app/assets/KaTeX_SansSerif-Italic-DN2j7dab.woff +0 -0
  41. package/dist/app/assets/KaTeX_SansSerif-Italic-YYjJ1zSn.ttf +0 -0
  42. package/dist/app/assets/KaTeX_SansSerif-Regular-BNo7hRIc.ttf +0 -0
  43. package/dist/app/assets/KaTeX_SansSerif-Regular-CS6fqUqJ.woff +0 -0
  44. package/dist/app/assets/KaTeX_SansSerif-Regular-DDBCnlJ7.woff2 +0 -0
  45. package/dist/app/assets/KaTeX_Script-Regular-C5JkGWo-.ttf +0 -0
  46. package/dist/app/assets/KaTeX_Script-Regular-D3wIWfF6.woff2 +0 -0
  47. package/dist/app/assets/KaTeX_Script-Regular-D5yQViql.woff +0 -0
  48. package/dist/app/assets/KaTeX_Size1-Regular-C195tn64.woff +0 -0
  49. package/dist/app/assets/KaTeX_Size1-Regular-Dbsnue_I.ttf +0 -0
  50. package/dist/app/assets/KaTeX_Size1-Regular-mCD8mA8B.woff2 +0 -0
  51. package/dist/app/assets/KaTeX_Size2-Regular-B7gKUWhC.ttf +0 -0
  52. package/dist/app/assets/KaTeX_Size2-Regular-Dy4dx90m.woff2 +0 -0
  53. package/dist/app/assets/KaTeX_Size2-Regular-oD1tc_U0.woff +0 -0
  54. package/dist/app/assets/KaTeX_Size3-Regular-CTq5MqoE.woff +0 -0
  55. package/dist/app/assets/KaTeX_Size3-Regular-DgpXs0kz.ttf +0 -0
  56. package/dist/app/assets/KaTeX_Size4-Regular-BF-4gkZK.woff +0 -0
  57. package/dist/app/assets/KaTeX_Size4-Regular-DWFBv043.ttf +0 -0
  58. package/dist/app/assets/KaTeX_Size4-Regular-Dl5lxZxV.woff2 +0 -0
  59. package/dist/app/assets/KaTeX_Typewriter-Regular-C0xS9mPB.woff +0 -0
  60. package/dist/app/assets/KaTeX_Typewriter-Regular-CO6r4hn1.woff2 +0 -0
  61. package/dist/app/assets/KaTeX_Typewriter-Regular-D3Ib7_Hf.ttf +0 -0
  62. package/dist/app/assets/{PdfPreview-CCfKQhLL.js → PdfPreview-DQKr3Ptp.js} +1 -1
  63. package/dist/app/assets/{RichDiff-zrt7rxm3.js → RichDiff-FlSFtgaa.js} +7 -7
  64. package/dist/app/assets/abnfDiagram-VCTEODGH-DzBPGdfj.js +1 -0
  65. package/dist/app/assets/arc-Db5WL6r9.js +1 -0
  66. package/dist/app/assets/architectureDiagram-5GKGNRK7-BQpe2TNK.js +36 -0
  67. package/dist/app/assets/{blockDiagram-I7D4REHJ-M5oRqDla.js → blockDiagram-I7D4REHJ-BgCmLaKA.js} +2 -2
  68. package/dist/app/assets/{c4Diagram-7LVT6UL2-C6v6KvuZ.js → c4Diagram-7LVT6UL2-_PhalThw.js} +2 -2
  69. package/dist/app/assets/channel-B49F0XQ7.js +1 -0
  70. package/dist/app/assets/{chunk-2Q5K7J3B-BrSnR-LD.js → chunk-2Q5K7J3B-BTPmsvl_.js} +1 -1
  71. package/dist/app/assets/{chunk-5VM5RSS4-BAqdD3be.js → chunk-5VM5RSS4-CVAIVX2p.js} +1 -1
  72. package/dist/app/assets/{chunk-F27PBJKO-DNLocP_Z.js → chunk-F27PBJKO-D3CtqJt1.js} +1 -1
  73. package/dist/app/assets/{chunk-IMKFNOWR-DwFLWoAj.js → chunk-IMKFNOWR-BqUz3ypv.js} +4 -4
  74. package/dist/app/assets/{chunk-JWPE2WC7-DwOQUkPK.js → chunk-JWPE2WC7-DUZ7N-GF.js} +1 -1
  75. package/dist/app/assets/{chunk-POPQ4Y6H-CN6vxbUi.js → chunk-POPQ4Y6H-07WqhpWx.js} +1 -1
  76. package/dist/app/assets/{chunk-SVP7TREG-mfOuPsxp.js → chunk-SVP7TREG-Cm2L9T4G.js} +1 -1
  77. package/dist/app/assets/{chunk-TICWLB2K-R4JNWs6J.js → chunk-TICWLB2K-eq77BKkc.js} +3 -3
  78. package/dist/app/assets/{chunk-XXDRQBXY-Bwj8o9dr.js → chunk-XXDRQBXY-C7MtNMWW.js} +1 -1
  79. package/dist/app/assets/classDiagram-ZZMXUADV-BRJiKHXN.js +1 -0
  80. package/dist/app/assets/classDiagram-v2-VYDZK3BY-BRJiKHXN.js +1 -0
  81. package/dist/app/assets/cose-bilkent-JH36ORCC-DzKOasFS.js +1 -0
  82. package/dist/app/assets/{cynefin-OW5HDTMX-CNttFTW2.js → cynefin-OW5HDTMX-CfwDMx4l.js} +1 -1
  83. package/dist/app/assets/cynefinDiagram-5FMLGOSQ-B49YEFaN.js +62 -0
  84. package/dist/app/assets/{dagre-GXQ25YYZ-D-VD0Tcu.js → dagre-GXQ25YYZ-DUM8H3yt.js} +2 -2
  85. package/dist/app/assets/{diagram-S7CK7UJ4-CQReIUYr.js → diagram-S7CK7UJ4-BikoIImA.js} +4 -4
  86. package/dist/app/assets/diagram-UQ7AKVKN-C9xJpyKN.js +41 -0
  87. package/dist/app/assets/diagram-VSXAHHWV-DMZrJWN1.js +3 -0
  88. package/dist/app/assets/diagram-VX7I27RA-BgpgslRO.js +24 -0
  89. package/dist/app/assets/diagram-Z3DM3KII-jn5qnmcy.js +24 -0
  90. package/dist/app/assets/ebnfDiagram-PWID7BFC-CH3Fj_if.js +1 -0
  91. package/dist/app/assets/{erDiagram-RLTQ6QDP-DKoQjGux.js → erDiagram-RLTQ6QDP-DMjJBUCG.js} +2 -2
  92. package/dist/app/assets/{flowDiagram-HODETNUW-gq74Q1SF.js → flowDiagram-HODETNUW-oNU24Ye_.js} +4 -4
  93. package/dist/app/assets/ganttDiagram-EL5Y4UJY-C2zwi0FT.js +292 -0
  94. package/dist/app/assets/gitGraphDiagram-WWUBYQGX-BYCKF4kO.js +106 -0
  95. package/dist/app/assets/index-9KN5q5uZ.js +287 -0
  96. package/dist/app/assets/index-B2G_sUzr.js +3 -0
  97. package/dist/app/assets/index-B_GqR51t.css +1 -0
  98. package/dist/app/assets/infoDiagram-27XIBGKW-CrCN2toE.js +2 -0
  99. package/dist/app/assets/{ishikawaDiagram-5VMMS53U-DArpl74K.js → ishikawaDiagram-5VMMS53U-0iJj74kM.js} +2 -2
  100. package/dist/app/assets/{journeyDiagram-3NMN7TZE-B2sUGe5l.js → journeyDiagram-3NMN7TZE-DgMxPj39.js} +2 -2
  101. package/dist/app/assets/{kanban-definition-UXKFOSKX-Cx6oCBKM.js → kanban-definition-UXKFOSKX-DZIb7tVw.js} +7 -7
  102. package/dist/app/assets/katex-C5jXJg4s.js +257 -0
  103. package/dist/app/assets/katex-Ce-tjK1g.css +1 -0
  104. package/dist/app/assets/{layout-BjHuHx4m.js → layout-DQIvBakv.js} +1 -1
  105. package/dist/app/assets/{linear-CgCYMSPy.js → linear-sjXL1SLi.js} +1 -1
  106. package/dist/app/assets/{mdi-DoP81khn.js → mdi-BExM2XdQ.js} +1 -1
  107. package/dist/app/assets/mermaid-block-locator-CurhUNEi.js +5 -0
  108. package/dist/app/assets/mermaid-repair-C9fy3MS0.js +10 -0
  109. package/dist/app/assets/mermaid-repair-api-CO6VbH78.js +1 -0
  110. package/dist/app/assets/mermaid.core-C1pLMwEV.js +310 -0
  111. package/dist/app/assets/{mindmap-definition-YA3MSWOX-DP2Penfk.js → mindmap-definition-YA3MSWOX-Ccil60ZG.js} +3 -3
  112. package/dist/app/assets/pegDiagram-XKGWAZYB-BrI6zt95.js +1 -0
  113. package/dist/app/assets/{pieDiagram-E7YTZNPT-BHJIw8Ie.js → pieDiagram-E7YTZNPT-Cjxxn_Dn.js} +3 -3
  114. package/dist/app/assets/purify.es-CYR4BTuT.js +3 -0
  115. package/dist/app/assets/{quadrantDiagram-AXDQQJYC-CKJDe9v8.js → quadrantDiagram-AXDQQJYC-DZIHLR6S.js} +4 -4
  116. package/dist/app/assets/railroadDiagram-O6MQD6OU-BCBEYQn3.js +1 -0
  117. package/dist/app/assets/{requirementDiagram-BXWQKSXE-CbgXwlu-.js → requirementDiagram-BXWQKSXE-wpVC9c8i.js} +2 -2
  118. package/dist/app/assets/{sankeyDiagram-P5KCCOFB-xTHr7bNV.js → sankeyDiagram-P5KCCOFB-C2BXPZ46.js} +3 -3
  119. package/dist/app/assets/{sequenceDiagram-WJ2MYXX4-BJO_VejT.js → sequenceDiagram-WJ2MYXX4-aXfCHnZ_.js} +2 -2
  120. package/dist/app/assets/sizeCapture-INFHLROL-CkTnQSJD.js +1 -0
  121. package/dist/app/assets/stateDiagram-D77RDMKH-B2MyGf8l.js +1 -0
  122. package/dist/app/assets/stateDiagram-v2-MP3YSRHH-Co0nC0rh.js +1 -0
  123. package/dist/app/assets/swimlanes-42K2YHIH-sOcGW-Ud.js +1 -0
  124. package/dist/app/assets/swimlanesDiagram-VR7AAH4N-xtUfpzrL.js +8 -0
  125. package/dist/app/assets/{timeline-definition-24CTP7MA-BaspCbTG.js → timeline-definition-24CTP7MA-C_9MbuiH.js} +4 -4
  126. package/dist/app/assets/vennDiagram-4TSXK5OY-BWHdyrio.js +34 -0
  127. package/dist/app/assets/{wardleyDiagram-VM6X3IG4-7u6IS5Iz.js → wardleyDiagram-VM6X3IG4-B22lSp2F.js} +2 -2
  128. package/dist/app/assets/{xychartDiagram-S5SC5T6Z-D-TnlcEC.js → xychartDiagram-S5SC5T6Z-CznBdNTF.js} +2 -2
  129. package/dist/app/index.html +2 -2
  130. package/package.json +8 -8
  131. package/src/client/FolderTeamSection.tsx +2 -2
  132. package/src/configSchema.json +63 -2
  133. package/src/extension/guard.ts +86 -5
  134. package/src/extension/index.ts +28 -2
  135. package/src/server/conversations.ts +257 -16
  136. package/src/server/index.ts +9 -2
  137. package/src/server/paths.ts +8 -2
  138. package/src/server/persona.ts +23 -4
  139. package/src/server/personas-service.ts +15 -3
  140. package/src/server/projects.ts +7 -3
  141. package/src/server/records.ts +23 -3
  142. package/src/server/routes.ts +42 -3
  143. package/src/server/skills-service.ts +681 -0
  144. package/src/server/store.ts +28 -4
  145. package/src/server/team.ts +39 -3
  146. package/src/server/types.ts +26 -4
  147. package/src/server/users.ts +9 -3
  148. package/dist/app/assets/abnfDiagram-VCTEODGH-BNRJZIa7.js +0 -1
  149. package/dist/app/assets/arc-Ccw1WVCw.js +0 -1
  150. package/dist/app/assets/architectureDiagram-5GKGNRK7-CmpCS5s2.js +0 -36
  151. package/dist/app/assets/channel-1wFLoesq.js +0 -1
  152. package/dist/app/assets/classDiagram-ZZMXUADV-DeqkIaZ-.js +0 -1
  153. package/dist/app/assets/classDiagram-v2-VYDZK3BY-DeqkIaZ-.js +0 -1
  154. package/dist/app/assets/cose-bilkent-JH36ORCC-qCY2WMN8.js +0 -1
  155. package/dist/app/assets/cynefinDiagram-5FMLGOSQ-CBX-RJXy.js +0 -62
  156. package/dist/app/assets/diagram-UQ7AKVKN-DyEU0WYX.js +0 -41
  157. package/dist/app/assets/diagram-VSXAHHWV-NLLDj0k8.js +0 -3
  158. package/dist/app/assets/diagram-VX7I27RA-Daf-u6xI.js +0 -24
  159. package/dist/app/assets/diagram-Z3DM3KII-B0O71sZp.js +0 -24
  160. package/dist/app/assets/ebnfDiagram-PWID7BFC-BSRAXWwk.js +0 -1
  161. package/dist/app/assets/ganttDiagram-EL5Y4UJY-BIAOolFj.js +0 -292
  162. package/dist/app/assets/gitGraphDiagram-WWUBYQGX-BvZquV67.js +0 -106
  163. package/dist/app/assets/index-BTj-g2DX.js +0 -559
  164. package/dist/app/assets/index-owClP-R3.css +0 -1
  165. package/dist/app/assets/infoDiagram-27XIBGKW-dMwJRmit.js +0 -2
  166. package/dist/app/assets/mermaid.core-DiBBwf02.js +0 -312
  167. package/dist/app/assets/pegDiagram-XKGWAZYB-DuPy_Jk1.js +0 -1
  168. package/dist/app/assets/railroadDiagram-O6MQD6OU-CPmw2XqA.js +0 -1
  169. package/dist/app/assets/sizeCapture-INFHLROL-BOIqspBs.js +0 -1
  170. package/dist/app/assets/stateDiagram-D77RDMKH-B1M9C9C6.js +0 -1
  171. package/dist/app/assets/stateDiagram-v2-MP3YSRHH-BWPtAAkO.js +0 -1
  172. package/dist/app/assets/swimlanes-42K2YHIH-BtpfWryU.js +0 -1
  173. package/dist/app/assets/swimlanesDiagram-VR7AAH4N-CRZvPlTl.js +0 -8
  174. package/dist/app/assets/vennDiagram-4TSXK5OY-Rzs4n1uC.js +0 -34
@@ -1,20 +1,22 @@
1
1
  /**
2
- * Conversations, agents and the idle sweeper (D5/D8). One conversation = one
2
+ * Conversations, agents and idle ending (D5/D8; core reaper for declared sessions, legacy sweep otherwise — see change: add-session-close-plugin-hook). One conversation = one
3
3
  * persistent pi session found-or-resumed on demand. The host is reached only
4
4
  * through the narrow {@link HostPort}, so the service is unit-testable with a
5
5
  * fake. See change: add-team-plugin.
6
6
  */
7
7
  import { randomBytes, randomUUID } from "node:crypto";
8
8
  import fs from "node:fs";
9
- import type { PluginSpawnOptions } from "@blackbelt-technology/dashboard-plugin-runtime/server";
9
+ import path from "node:path";
10
+ import type { PluginCwdPolicy, PluginSpawnOptions } from "@blackbelt-technology/dashboard-plugin-runtime/server";
10
11
  import { piSessionDirForCwd } from "@blackbelt-technology/pi-dashboard-shared/dashboard-paths.js";
11
12
  import { PRESET_TOOLS } from "../extension/guard.js";
12
13
  import type { Access } from "./access.js";
13
14
  import { canonicalize, type TeamPaths, userKey } from "./paths.js";
14
15
  import { cpLength } from "./persona.js";
15
16
  import type { ProjectRegistry } from "./projects.js";
16
- import type { LocatedRecord, Locator, RecordStore } from "./records.js";
17
+ import { type LocatedRecord, type Locator, type RecordStore, spawnedSkillNames } from "./records.js";
17
18
  import { collectContextFiles } from "./render.js";
19
+ import { allowed, type SkillBlockReason, type SkillEntry, type SkillSnapshot, type SkillsService } from "./skills-service.js";
18
20
  import type { PersonaStore } from "./store-types.js";
19
21
  import {
20
22
  type AvatarSpec,
@@ -23,6 +25,7 @@ import {
23
25
  type Persona,
24
26
  type PersonaRole,
25
27
  type Project,
28
+ type SpawnedSkill,
26
29
  type TeamConfig,
27
30
  TeamError,
28
31
  WORKSPACE_TARGET,
@@ -38,6 +41,8 @@ export interface HostSession {
38
41
  principalOwner?: { iss: string; sub: string };
39
42
  /** `pluginRefs[pluginId]` = the whole ref the plugin filed at spawn. */
40
43
  pluginRefs?: Record<string, Record<string, unknown>>;
44
+ /** Core-applied close declaration (absent on sessions spawned before add-session-close-plugin-hook). */
45
+ closePolicy?: unknown;
41
46
  }
42
47
 
43
48
  export interface HostPort {
@@ -48,6 +53,12 @@ export interface HostPort {
48
53
  onSessionResolved(h: (sessionId: string, ref: Record<string, unknown>) => void): () => void;
49
54
  onEvent(h: (sessionId: string, event: unknown) => void): () => void;
50
55
  registerPiHandler(type: string, h: (msg: unknown, sessionId: string) => void): void;
56
+ /**
57
+ * Register the team session closer consulted by core's idle reaper before it
58
+ * closes a team session (optional: older hosts lack it).
59
+ * See change: add-session-close-plugin-hook.
60
+ */
61
+ registerSessionCloser?(closer: (req: { sessionId: string }) => "close" | "keep"): void;
51
62
  }
52
63
 
53
64
  export interface Logger {
@@ -65,6 +76,14 @@ export interface ServiceDeps {
65
76
  records: RecordStore;
66
77
  config: () => TeamConfig;
67
78
  logger: Logger;
79
+ /** Skill catalog: start check (D6), listing state (D14), spawn resolver (D7). */
80
+ skills: SkillsService;
81
+ /**
82
+ * Host cwd capability floor for a spawn dir (D7 composition, mirrors
83
+ * `mergeCwdPolicy`'s read of `CwdPolicyRegistry`). Absent (older host, no
84
+ * `host.resolveCwdPolicy` service) → no composition narrowing possible.
85
+ */
86
+ resolveCwdPolicy?: (cwd: string) => PluginCwdPolicy | undefined;
68
87
  /** Absolute path of the team guard extension (`-e`). */
69
88
  guardExtensionPath: string;
70
89
  /** Renders persona.md for (persona, uk) and returns its absolute path. */
@@ -84,6 +103,15 @@ const ACTIVITY_WRITE_MS = 10_000;
84
103
  /** An event older than this is treated as replayed history. */
85
104
  const REPLAY_AGE_MS = 120_000;
86
105
 
106
+ /** Current realpath of a directory, or null when it no longer resolves. */
107
+ function realpathOf(p: string): string | null {
108
+ try {
109
+ return fs.realpathSync(p);
110
+ } catch {
111
+ return null;
112
+ }
113
+ }
114
+
87
115
  export type ConvStatus = "busy" | "running" | "sleeping";
88
116
  type AgentStatus = ConvStatus | "new" | "retired" | "unavailable";
89
117
 
@@ -112,6 +140,10 @@ export interface AgentView {
112
140
  personaStale: boolean;
113
141
  unassigned: boolean;
114
142
  retired: boolean;
143
+ /** Persona skills the caller may use in this target (persona order). */
144
+ effectiveSkills: string[];
145
+ /** Spawn-check state (D6/D14): the first skill that would refuse the start. */
146
+ skillBlock: { skill: string; reason: SkillBlockReason } | null;
115
147
  }
116
148
 
117
149
  interface Pending {
@@ -134,6 +166,7 @@ function newConversationId(): string {
134
166
  }
135
167
 
136
168
  export class ConversationService {
169
+ private readonly d: ServiceDeps;
137
170
  private readonly inFlight = new Map<string, Promise<unknown>>();
138
171
  private readonly createLocks = new Map<string, Promise<void>>();
139
172
  /** Launches admitted but not yet bound, per user (live-cap reservation). */
@@ -146,7 +179,9 @@ export class ConversationService {
146
179
  private readonly unsubs: Array<() => void> = [];
147
180
  private sweepTimer: ReturnType<typeof setInterval> | undefined;
148
181
 
149
- constructor(private readonly d: ServiceDeps) {}
182
+ constructor(d: ServiceDeps) {
183
+ this.d = d;
184
+ }
150
185
 
151
186
  private now(): number {
152
187
  return this.d.now?.() ?? Date.now();
@@ -197,6 +232,12 @@ export class ConversationService {
197
232
  }),
198
233
  this.d.host.onEvent((sessionId, event) => this.onEvent(sessionId, event)),
199
234
  );
235
+ // Idle ending is core's quiescence reaper (declared on spawn); the team
236
+ // closer only keeps a session whose conversation is being ensured.
237
+ // See change: add-session-close-plugin-hook.
238
+ this.d.host.registerSessionCloser?.((req) => this.closeVerdict(req.sessionId));
239
+ // Legacy fallback: sessions without a closePolicy (live from before the
240
+ // upgrade, or an older host) keep the former team idle sweep.
200
241
  this.sweepIdle();
201
242
  if (sweepEveryMs > 0) {
202
243
  this.sweepTimer = setInterval(() => this.sweepIdle(), sweepEveryMs);
@@ -210,6 +251,13 @@ export class ConversationService {
210
251
  this.sweepTimer = undefined;
211
252
  }
212
253
 
254
+ /** Team closer: keep while an ensure of the session's conversation is in flight. */
255
+ closeVerdict(sessionId: string): "close" | "keep" {
256
+ const loc = this.d.records.locate(sessionId);
257
+ if (loc && this.inFlight.has(`${loc.uk}|${loc.personaKey}|${loc.t}|${loc.c}`)) return "keep";
258
+ return "close";
259
+ }
260
+
213
261
  private onEvent(sessionId: string, event: unknown): void {
214
262
  const loc = this.d.records.locate(sessionId);
215
263
  if (!loc) return;
@@ -233,7 +281,11 @@ export class ConversationService {
233
281
  this.d.records.write(loc, rec);
234
282
  }
235
283
 
236
- /** End sessions idle past `idleMinutes` (never `busy`). */
284
+ /**
285
+ * Legacy idle sweep: end UNDECLARED sessions idle past `idleMinutes` (never
286
+ * `busy`). A session carrying a closePolicy is core's reaper's alone.
287
+ * See change: add-session-close-plugin-hook.
288
+ */
237
289
  sweepIdle(): void {
238
290
  const idle = this.idleMs();
239
291
  if (idle === 0) return;
@@ -242,6 +294,7 @@ export class ConversationService {
242
294
  if (r.archived) continue;
243
295
  const s = this.d.host.getSession(r.sessionId);
244
296
  if (!s || s.status === "ended" || s.status === "streaming") continue;
297
+ if (s.closePolicy) continue; // declared: core's reaper owns idle ending
245
298
  // Multi-user: only end a session the record's user owns (a misbound record must not reach another user's).
246
299
  if (this.d.access.mode() === "multi" && (!s.principalOwner || userKey(s.principalOwner.iss, s.principalOwner.sub) !== lr.uk)) continue;
247
300
  const last = Date.parse(r.lastAgentEndAt ?? r.lastActivityAt ?? r.startedAt);
@@ -251,6 +304,83 @@ export class ConversationService {
251
304
  }
252
305
  }
253
306
 
307
+ /**
308
+ * D6 epoch re-check: a managed catalog write between the start check and
309
+ * the session correlating re-runs the check on the now-live session. A
310
+ * revocation aborts it (non-graceful — it was never handed out) and answers
311
+ * the same 409, before any record is written.
312
+ */
313
+ private async assertUnblockedAtCorrelation(
314
+ caller: Caller,
315
+ personaKey: string,
316
+ t: string,
317
+ persona: Persona,
318
+ epoch: number,
319
+ sessionId: string,
320
+ spawned: SpawnedSkill[],
321
+ ): Promise<void> {
322
+ if (this.d.skills.epoch() === epoch) return;
323
+ // The spawned set is authoritative for a session born seconds ago; the persona's current list
324
+ // only covers records without one (audit F4).
325
+ const names = spawned.map((s) => s.name);
326
+ const now = this.d.skills.firstBlockedSkill(names.length > 0 ? names : (persona.skills ?? []), caller, t);
327
+ if (!now) {
328
+ // A managed path edit that MOVED a granted root also aborts, even when every name is still
329
+ // allowed (audit F5).
330
+ for (const s of spawned) {
331
+ const r = this.d.skills.resolveSkillRoot(s.name, caller, t);
332
+ if (r?.root === s.root) continue;
333
+ await this.d.host.abortSpawnedRun({ sessionId, graceful: false });
334
+ throw this.skillBlocked(caller, personaKey, t, { skill: s.name, reason: "invalid" });
335
+ }
336
+ return;
337
+ }
338
+ await this.d.host.abortSpawnedRun({ sessionId, graceful: false });
339
+ throw this.skillBlocked(caller, personaKey, t, now);
340
+ }
341
+
342
+ /**
343
+ * D8: after a successful managed catalog write, end every live, owner-bound
344
+ * session whose grant of `name` changed (denied / removed / realpath
345
+ * moved). Modelled on `sweepIdle`, but revocation is a security event: it
346
+ * ends even a streaming session, non-gracefully, and keeps every record.
347
+ * Reachable only from a successful admin write (SkillsService), never from
348
+ * ensure/resume/restart routes. Returns the number of sessions ended.
349
+ */
350
+ // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: one linear pass over records with per-record owner binding
351
+ async invalidateSkill(name: string, before: SkillEntry | null, after: SkillEntry | null, by: string): Promise<number> {
352
+ const mode = this.d.access.mode();
353
+ let ended = 0;
354
+ for (const lr of this.d.records.scanAll()) {
355
+ if (lr.record.archived) continue;
356
+ const s = this.d.host.getSession(lr.record.sessionId);
357
+ if (!s || s.status === "ended") continue;
358
+ // Same owner binding as sweepIdle: a misbound record never reaches another user's session.
359
+ if (mode === "multi" && (!s.principalOwner || userKey(s.principalOwner.iss, s.principalOwner.sub) !== lr.uk)) continue;
360
+ const persona = this.d.personas.get(lr.record.personaKey, lr.uk);
361
+ // The session is judged by the skills it was SPAWNED with (recorded at correlation); the
362
+ // persona's current list is only the fallback for records predating that (audit F4).
363
+ if (!(spawnedSkillNames(lr.record) ?? persona?.skills ?? []).includes(name)) continue;
364
+ const owner = s.principalOwner ?? { iss: "", sub: "" };
365
+ const holder: Caller = { uk: lr.uk, iss: owner.iss, sub: owner.sub, admin: false };
366
+ if (!this.lostGrant(before, after, holder, lr.t)) continue;
367
+ await this.d.host.abortSpawnedRun({ sessionId: lr.record.sessionId, graceful: false });
368
+ ended++;
369
+ this.d.logger.info(`team.skill_end name=${name} uk=${lr.uk} t=${lr.t} by=${by}`);
370
+ }
371
+ return ended;
372
+ }
373
+
374
+ /** D8 grant delta: the session held the grant and now loses it (denied / removed / realpath moved). */
375
+ private lostGrant(before: SkillEntry | null, after: SkillEntry | null, holder: Caller, t: string): boolean {
376
+ const mode = this.d.access.mode();
377
+ // Only a session that HELD the grant can lose it: widenings and cosmetic edits end nothing.
378
+ if (before === null || !allowed(before, holder, t, mode)) return false;
379
+ const denied = after === null || !allowed(after, holder, t, mode);
380
+ const rootChanged = after !== null && realpathOf(before.path) !== realpathOf(after.path);
381
+ return denied || rootChanged;
382
+ }
383
+
254
384
  // ── resolution helpers ─────────────────────────────────────────────────────
255
385
 
256
386
  private persona(caller: Caller, key: string): Persona {
@@ -360,6 +490,35 @@ export class ConversationService {
360
490
  );
361
491
  }
362
492
 
493
+ /** D6 refusal: log without paths/skill text, answer 409 {skill, reason}. */
494
+ private skillBlocked(caller: Caller, personaKey: string, t: string, b: { skill: string; reason: string }): TeamError {
495
+ this.d.logger.info(`team.skill_not_allowed name=${b.skill} uk=${caller.uk} target=${t} reason=${b.reason}`);
496
+ return new TeamError(409, "skill_not_allowed", { skill: b.skill, reason: b.reason });
497
+ }
498
+
499
+ /**
500
+ * D7 composition: would the host's `mergeCwdPolicy` change the skill set?
501
+ * Mirrors `intersectAllow` (absent caller list = the floor applies
502
+ * wholesale). Returns the first offending skill + counts, or null.
503
+ */
504
+ private composedSkillDelta(cwd: string, requested: readonly { name: string; root: string }[]): { skill: string; requested: number; composed: number } | null {
505
+ const floor = this.d.resolveCwdPolicy?.(cwd)?.skills;
506
+ if (!floor) return null;
507
+ if (requested.length === 0) {
508
+ return floor.length > 0 ? { skill: path.basename(floor[0]), requested: 0, composed: floor.length } : null;
509
+ }
510
+ const keep = new Set(floor);
511
+ const composed = requested.filter((s) => keep.has(s.root));
512
+ if (composed.length === requested.length) return null;
513
+ return { skill: requested.find((s) => !keep.has(s.root))?.name ?? "", requested: requested.length, composed: composed.length };
514
+ }
515
+
516
+ /** D7 refusal: log counts only (no paths), answer 409 {skill, reason:"invalid"}. */
517
+ private skillsNarrowed(caller: Caller, t: string, delta: { skill: string; requested: number; composed: number }): TeamError {
518
+ this.d.logger.info(`team.skills_narrowed name=${delta.skill} uk=${caller.uk} target=${t} requested=${delta.requested} composed=${delta.composed}`);
519
+ return new TeamError(409, "skill_not_allowed", { skill: delta.skill, reason: "invalid" });
520
+ }
521
+
363
522
  // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: many small independent branches (field / state rendering); splitting would scatter one linear flow
364
523
  private async launch(
365
524
  caller: Caller,
@@ -368,7 +527,7 @@ export class ConversationService {
368
527
  c: string,
369
528
  root: { dir: string; project?: Project },
370
529
  resumeFile?: string,
371
- ): Promise<{ sessionId: string; sessionFile?: string; runId: string; spawnToken: string; release: () => void }> {
530
+ ): Promise<{ sessionId: string; sessionFile?: string; runId: string; spawnToken: string; skills: SpawnedSkill[]; release: () => void }> {
372
531
  if (!fs.existsSync(this.d.guardExtensionPath)) throw new TeamError(503, "guard_unavailable");
373
532
  // An unconfined (`full`) persona must never run in multi-user mode, whatever mode it was authored in.
374
533
  if (persona.tools === "full" && this.d.access.mode() === "multi") throw new TeamError(409, "persona_unavailable");
@@ -380,8 +539,15 @@ export class ConversationService {
380
539
  const contextFiles = root.project?.contextFiles ? collectContextFiles(root.dir) : [];
381
540
  const runId = randomUUID();
382
541
  const spawnToken = randomUUID();
383
- const catalog = this.d.config().skillCatalog ?? {};
384
- const skills = (persona.skills ?? []).map((n) => catalog[n]).filter((p): p is string => typeof p === "string");
542
+ const snap = this.d.skills.snapshot();
543
+ const effective = (persona.skills ?? []).flatMap((n) => {
544
+ const r = this.d.skills.resolveSkillRoot(n, caller, t, snap);
545
+ return r ? [r] : [];
546
+ });
547
+ // D7: the host may compose a cwd capability floor into the spawn — refuse
548
+ // rather than run with a narrowed (or forced) skill set.
549
+ const delta = this.composedSkillDelta(root.dir, effective);
550
+ if (delta) throw this.skillsNarrowed(caller, t, delta);
385
551
  const ownerStamp = this.owner(caller);
386
552
 
387
553
  let settleFn: () => void = () => {};
@@ -411,15 +577,33 @@ export class ConversationService {
411
577
  team: { personaKey: persona.key, project: t, conversationId: c, uk: caller.uk, runId },
412
578
  ...(ownerStamp ? { principalOwner: ownerStamp } : {}),
413
579
  },
414
- lifecycle: { recover: false, finalizeOnSocketClose: true },
580
+ lifecycle: {
581
+ recover: false,
582
+ finalizeOnSocketClose: true,
583
+ // Idle ending: core's quiescence reaper with our threshold (none when
584
+ // `idleMinutes` is 0). See change: add-session-close-plugin-hook.
585
+ ...(this.idleMs() > 0
586
+ ? { close: { idle: { afterMs: Math.max(1000, Math.round(this.idleMs())) }, mode: "sleep" as const } }
587
+ : {}),
588
+ },
415
589
  scope: {
416
590
  tools: [...PRESET_TOOLS[persona.tools]],
417
- ...(skills.length ? { skills } : {}),
591
+ // D7: exact skill set — never discovered/settings/package skills.
592
+ // `noSkills` always; `skills` is the effective realpaths (the mapper
593
+ // drops an empty list, so no `--skill` reaches argv); the guard
594
+ // policy travels as one JSON string (`sanitizeExtensionConfig`
595
+ // keeps strings verbatim → `PI_EXT_TEAM_SKILLS`).
596
+ skills: effective.map((s) => s.root),
597
+ noSkills: true,
418
598
  extensions: [this.d.guardExtensionPath],
419
- extensionConfig: { team: { persona: personaFile, root: root.dir, tools: persona.tools, runId } },
599
+ extensionConfig: {
600
+ team: { persona: personaFile, root: root.dir, tools: persona.tools, runId, skills: JSON.stringify(effective) },
601
+ },
420
602
  appendSystemPrompt: [personaFile, ...contextFiles],
421
603
  noContextFiles: true,
422
604
  noProjectTrust: true,
605
+ // No MCP connection for team sessions; the guard name gate stays the backstop.
606
+ noMcp: true,
423
607
  sessionDir: (this.d.sessionDirFor ?? ((cwd: string) => piSessionDirForCwd(cwd)))(root.dir),
424
608
  },
425
609
  spawnToken,
@@ -442,7 +626,7 @@ export class ConversationService {
442
626
  const sessionId = entry.sessionId as string;
443
627
  const s = this.d.host.getSession(sessionId);
444
628
  // The caller releases the slot AFTER the record is written, so the new session is never uncounted.
445
- return { sessionId, sessionFile: s?.sessionFile, runId, spawnToken, release: releaseSlot };
629
+ return { sessionId, sessionFile: s?.sessionFile, runId, spawnToken, skills: effective.map((s) => ({ name: s.name, root: s.root })), release: releaseSlot };
446
630
  } catch (err) {
447
631
  this.pending.delete(runId);
448
632
  releaseSlot();
@@ -487,6 +671,9 @@ export class ConversationService {
487
671
  async createConversation(caller: Caller, personaKey: string, t: string): Promise<{ id: string; sessionId: string }> {
488
672
  const persona = this.persona(caller, personaKey);
489
673
  const root = this.target(caller, persona, t);
674
+ const blocked = this.d.skills.firstBlockedSkill(persona.skills ?? [], caller, t);
675
+ if (blocked) throw this.skillBlocked(caller, personaKey, t, blocked);
676
+ const epoch = this.d.skills.epoch();
490
677
  const lockKey = `${caller.uk}|${personaKey}|${t}`;
491
678
  const prev = this.createLocks.get(lockKey) ?? Promise.resolve();
492
679
  let release: () => void = () => {};
@@ -509,6 +696,8 @@ export class ConversationService {
509
696
  throw err;
510
697
  }
511
698
  try {
699
+ // D6 epoch: a managed write may have landed while the spawn was in flight.
700
+ await this.assertUnblockedAtCorrelation(caller, personaKey, t, persona, epoch, bound.sessionId, bound.skills);
512
701
  const stamp = this.iso();
513
702
  const rec: ConversationRecord = {
514
703
  schemaVersion: 1,
@@ -525,6 +714,9 @@ export class ConversationService {
525
714
  personaUpdatedAt: persona.updatedAt,
526
715
  archived: false,
527
716
  personaSnapshot: this.snapshot(persona),
717
+ // The spawned skill set: revocation and the start check judge THIS set, not the
718
+ // persona's current list (audit F4).
719
+ skills: bound.skills.map((s) => ({ name: s.name, root: s.root })),
528
720
  };
529
721
  this.d.records.write(this.loc(caller, personaKey, t, c), rec);
530
722
  this.logEnsure(caller, personaKey, t, c, "create", bound.sessionId);
@@ -540,6 +732,19 @@ export class ConversationService {
540
732
  }
541
733
  }
542
734
 
735
+ /**
736
+ * Read-only handle on a conversation's transcript: the host session id, so the client can replay history
737
+ * when a start is blocked (`409 skill_not_allowed`) and no session will be spawned. Never spawns, ends or
738
+ * writes. Owner-fail-closed like resume: in multi-user mode only a host session this caller owns is returned.
739
+ * See change: add-team-skill-access.
740
+ */
741
+ historyHandle(caller: Caller, personaKey: string, t: string, c: string): { sessionId: string } {
742
+ const { rec } = this.requireRecord(caller, personaKey, t, c);
743
+ const known = this.d.host.getSession(rec.sessionId);
744
+ if (!known || !this.ownerMatches(known, caller)) throw new TeamError(404, "history_unavailable");
745
+ return { sessionId: rec.sessionId };
746
+ }
747
+
543
748
  async ensureConversation(caller: Caller, personaKey: string, t: string, c: string): Promise<{ sessionId: string }> {
544
749
  const { rec } = this.requireRecord(caller, personaKey, t, c);
545
750
  if (rec.archived) throw new TeamError(409, "conversation_archived");
@@ -560,9 +765,25 @@ export class ConversationService {
560
765
  if (!rec) throw new TeamError(404, "conversation_not_found");
561
766
  const persona = this.persona(caller, personaKey);
562
767
  const root = this.target(caller, persona, t, true);
768
+ const live = this.ownLive(rec, c);
769
+
770
+ // 2. Start check on EVERY path (D6): before reuse, so a revoked skill also
771
+ // ends the live session instead of handing it back out. A live session is
772
+ // also judged by the skill set it was SPAWNED with (audit F4): the persona
773
+ // may have been edited since, but the session keeps the roots it was born
774
+ // with. Records without a spawned set fall back to persona.skills.
775
+ const spawned = spawnedSkillNames(rec);
776
+ const checked = spawned ? [...new Set([...spawned, ...(persona.skills ?? [])])] : (persona.skills ?? []);
777
+ const blocked = this.d.skills.firstBlockedSkill(checked, caller, t);
778
+ if (blocked) {
779
+ if (live && live.status !== "ended" && this.ownerMatches(live, caller)) {
780
+ await this.d.host.abortSpawnedRun({ sessionId: rec.sessionId, graceful: true });
781
+ }
782
+ throw this.skillBlocked(caller, personaKey, t, blocked);
783
+ }
784
+ const epoch = this.d.skills.epoch();
563
785
 
564
786
  // 3. reuse
565
- const live = this.ownLive(rec, c);
566
787
  const team = this.teamRef(live);
567
788
  if (
568
789
  live &&
@@ -614,6 +835,8 @@ export class ConversationService {
614
835
  await this.d.host.abortSpawnedRun({ sessionId: bound.sessionId, graceful: true });
615
836
  throw new TeamError(cur ? 409 : 404, cur ? "conversation_archived" : "conversation_not_found");
616
837
  }
838
+ // D6 epoch: a managed write may have landed while the spawn was in flight.
839
+ await this.assertUnblockedAtCorrelation(caller, personaKey, t, persona, epoch, bound.sessionId, bound.skills);
617
840
  const stamp = this.iso();
618
841
  this.d.records.write(l, {
619
842
  ...cur,
@@ -625,6 +848,8 @@ export class ConversationService {
625
848
  lastActivityAt: stamp,
626
849
  personaUpdatedAt: persona.updatedAt,
627
850
  personaSnapshot: this.snapshot(persona),
851
+ // The spawned skill set (audit F4) — replaces any set recorded by an earlier spawn.
852
+ skills: bound.skills.map((s) => ({ name: s.name, root: s.root })),
628
853
  });
629
854
  this.logEnsure(caller, personaKey, t, c, fileExists ? "resume" : "create", bound.sessionId);
630
855
  return { sessionId: bound.sessionId };
@@ -710,6 +935,8 @@ export class ConversationService {
710
935
  const personas = [...this.d.personas.listShared(), ...this.d.personas.listPrivate(caller.uk)];
711
936
  // Computed ONCE per request (each call re-validates every project path on disk).
712
937
  const usable = new Set(this.d.projects.usableBy(caller, mode).map((x) => x.id));
938
+ // Catalog validated once per request (D14).
939
+ const snap = this.d.skills.snapshot();
713
940
  const out: AgentView[] = [];
714
941
  const seen = new Set<string>();
715
942
 
@@ -719,7 +946,7 @@ export class ConversationService {
719
946
  const active = recs.filter((r) => !r.record.archived);
720
947
  if (!assigned && active.length === 0) continue;
721
948
  seen.add(p.key);
722
- out.push(this.card(p, recs, assigned, mode));
949
+ out.push(this.card(p, recs, assigned, mode, caller, t, snap));
723
950
  }
724
951
  // Retired: records whose persona no longer exists.
725
952
  for (const [key, recs] of byPersona) {
@@ -745,6 +972,8 @@ export class ConversationService {
745
972
  personaStale: false,
746
973
  unassigned: false,
747
974
  retired: true,
975
+ effectiveSkills: [],
976
+ skillBlock: null,
748
977
  });
749
978
  }
750
979
  return out;
@@ -761,11 +990,21 @@ export class ConversationService {
761
990
  };
762
991
  }
763
992
 
764
- private card(p: Persona, recs: LocatedRecord[], assigned: boolean, mode: "single" | "multi"): AgentView {
993
+ private card(
994
+ p: Persona,
995
+ recs: LocatedRecord[],
996
+ assigned: boolean,
997
+ mode: "single" | "multi",
998
+ caller: Caller,
999
+ t: string,
1000
+ snap: SkillSnapshot,
1001
+ ): AgentView {
765
1002
  const active = recs.filter((r) => !r.record.archived);
766
1003
  const fullBlocked = p.tools === "full" && mode === "multi";
1004
+ const skillBlock = this.d.skills.firstBlockedSkill(p.skills ?? [], caller, t, snap);
1005
+ const effectiveSkills = skillBlock ? this.d.skills.effectiveSkills(p.skills ?? [], caller, t, snap) : [...(p.skills ?? [])];
767
1006
  let status: AgentStatus;
768
- if (!assigned || fullBlocked) status = "unavailable";
1007
+ if (!assigned || fullBlocked || skillBlock) status = "unavailable";
769
1008
  else if (active.length === 0) status = "new";
770
1009
  else {
771
1010
  const statuses = active.map((r) => this.statusOf(r.record, r.c));
@@ -787,6 +1026,8 @@ export class ConversationService {
787
1026
  personaStale: active.some((r) => this.isStale(r.record, r.c, p)),
788
1027
  unassigned: !assigned,
789
1028
  retired: false,
1029
+ effectiveSkills,
1030
+ skillBlock,
790
1031
  };
791
1032
  }
792
1033
 
@@ -1,11 +1,11 @@
1
1
  /**
2
2
  * team-plugin · SERVER entry. Mounts `/api/plugins/team/*` and the same-origin
3
3
  * app at `/apps/team/`, and runs the conversation lifecycle (spawn / resume /
4
- * idle ending). See change: add-team-plugin.
4
+ * idle ending via core's reaper). See change: add-team-plugin, add-session-close-plugin-hook.
5
5
  */
6
6
  import path from "node:path";
7
7
  import { fileURLToPath } from "node:url";
8
- import type { ServerPluginContext } from "@blackbelt-technology/dashboard-plugin-runtime/server";
8
+ import type { PluginCwdPolicy, ServerPluginContext } from "@blackbelt-technology/dashboard-plugin-runtime/server";
9
9
  import type { HostPort, HostSession } from "./conversations.js";
10
10
  import { createTeam } from "./team.js";
11
11
  import type { TeamConfig } from "./types.js";
@@ -21,6 +21,8 @@ async function registerPlugin(ctx: ServerPluginContext): Promise<void> {
21
21
  onSessionResolved: (h) => ctx.onSessionResolved(h),
22
22
  onEvent: (h) => ctx.onEvent(h),
23
23
  registerPiHandler: (type, h) => ctx.registerPiHandler(type, h),
24
+ // Optional on older runtimes. See change: add-session-close-plugin-hook.
25
+ registerSessionCloser: (closer) => ctx.registerSessionCloser?.((req) => closer(req)),
24
26
  };
25
27
  const team = createTeam({
26
28
  host,
@@ -30,6 +32,11 @@ async function registerPlugin(ctx: ServerPluginContext): Promise<void> {
30
32
  logger: ctx.logger,
31
33
  guardExtensionPath: path.resolve(HERE, "../extension/index.ts"),
32
34
  distAppDir: path.resolve(HERE, "../../dist/app"),
35
+ // D11: operator's global skills for the admin picker; absent on older hosts → [].
36
+ listOperatorSkills:
37
+ ctx.consume<() => Promise<{ name: string; description: string; path: string; source: string }[]>>("host.listOperatorSkills") ?? undefined,
38
+ // D7 composition: host cwd capability floor; absent (service not published) → no narrowing possible.
39
+ resolveCwdPolicy: ctx.consume<(cwd: string) => PluginCwdPolicy | undefined>("host.resolveCwdPolicy") ?? undefined,
33
40
  });
34
41
  await team.start();
35
42
  ctx.onShutdown(() => team.stop());
@@ -46,14 +46,17 @@ export function personaDirName(key: string): string {
46
46
  return `${p.scope}-${p.slug}`;
47
47
  }
48
48
 
49
- /** Longest-existing-ancestor realpath (symlinks resolved; absent tail kept lexically). */
49
+ /** Longest-existing-ancestor realpath (symlinks resolved; absent tail kept lexically). Native
50
+ * `realpath` so every component gets its on-disk case: on a case-insensitive filesystem the plain
51
+ * JS realpath keeps the typed case, which would let a mis-cased path slip past an `isInside` guard
52
+ * (audit F1). */
50
53
  export function canonicalize(p: string): string {
51
54
  const abs = path.resolve(p);
52
55
  let head = abs;
53
56
  const tail: string[] = [];
54
57
  for (;;) {
55
58
  try {
56
- const real = fs.realpathSync(head);
59
+ const real = fs.realpathSync.native(head);
57
60
  return tail.length ? path.join(real, ...tail.reverse()) : real;
58
61
  } catch {
59
62
  const parent = path.dirname(head);
@@ -107,6 +110,9 @@ export class TeamPaths {
107
110
  privatePersonasDir(uk: string): string {
108
111
  return this.under("users", this.ukSeg(uk), "personas");
109
112
  }
113
+ usersRoot(): string {
114
+ return this.under("users");
115
+ }
110
116
  conversationsDir(uk: string, t: string, personaKey: string): string {
111
117
  if (!isTargetId(t)) throw new TeamError(400, "invalid_target");
112
118
  return this.under("users", this.ukSeg(uk), "conversations", t, personaDirName(personaKey));
@@ -21,7 +21,8 @@ export interface PersonaRules {
21
21
  mode: Mode;
22
22
  scope: PersonaScope;
23
23
  caller: Caller;
24
- skillCatalog: Record<string, string>;
24
+ /** Per skill × target: `ok`, `unknown` (not in catalog) or `not_allowed` (D5). */
25
+ skillRule: (name: string, target: string) => "ok" | "unknown" | "not_allowed";
25
26
  /** Targets the author may assign (always includes `_ws`). */
26
27
  assignableTargets: ReadonlySet<string>;
27
28
  }
@@ -135,9 +136,27 @@ export function validatePersonaInput(body: unknown, rules: PersonaRules, opts: {
135
136
  let skills: string[] | undefined;
136
137
  if (b.skills !== undefined) {
137
138
  const s = b.skills;
138
- if (!Array.isArray(s) || s.length > LIMITS.skillsMax || new Set(s).size !== s.length) fields.skills = "invalid_skills";
139
- else if (!s.every((x) => typeof x === "string" && Object.hasOwn(rules.skillCatalog, x))) fields.skills = "unknown_skill";
140
- else skills = s as string[];
139
+ if (!Array.isArray(s) || s.length > LIMITS.skillsMax || new Set(s).size !== s.length || !s.every((x) => typeof x === "string")) {
140
+ fields.skills = "invalid_skills";
141
+ } else {
142
+ // D5: every listed skill must exist and be allowed for EVERY target (owner
143
+ // binds via the private-scope rule in `skillRule`).
144
+ let unknown = false;
145
+ let notAllowed = false;
146
+ loop: for (const name of s as string[]) {
147
+ for (const t of projects) {
148
+ const r = rules.skillRule(name, t);
149
+ if (r === "unknown") {
150
+ unknown = true;
151
+ break loop;
152
+ }
153
+ if (r === "not_allowed") notAllowed = true;
154
+ }
155
+ }
156
+ if (unknown) fields.skills = "unknown_skill";
157
+ else if (notAllowed) fields.skills = "skill_not_allowed";
158
+ else skills = s as string[];
159
+ }
141
160
  }
142
161
 
143
162
  if (Object.keys(fields).length > 0) return { ok: false, fields };
@@ -6,6 +6,7 @@ import type { Access } from "./access.js";
6
6
  import { isSlug, parsePersonaKey } from "./paths.js";
7
7
  import { LIMITS, type PersonaRules, suffixedSlug, validatePersonaInput } from "./persona.js";
8
8
  import type { ProjectRegistry } from "./projects.js";
9
+ import type { SkillsService } from "./skills-service.js";
9
10
  import type { PersonaStore as FsPersonaStore } from "./store.js";
10
11
  import { type Caller, type Persona, type PersonaScope, type TeamConfig, TeamError, WORKSPACE_TARGET } from "./types.js";
11
12
 
@@ -13,6 +14,7 @@ export interface PersonaServiceDeps {
13
14
  store: FsPersonaStore;
14
15
  projects: ProjectRegistry;
15
16
  access: Access;
17
+ skills: SkillsService;
16
18
  config: () => TeamConfig;
17
19
  now?: () => Date;
18
20
  }
@@ -24,7 +26,11 @@ function publicPersona(p: Persona): Omit<Persona, "owner"> {
24
26
  }
25
27
 
26
28
  export class PersonaService {
27
- constructor(private readonly d: PersonaServiceDeps) {}
29
+ private readonly d: PersonaServiceDeps;
30
+
31
+ constructor(d: PersonaServiceDeps) {
32
+ this.d = d;
33
+ }
28
34
 
29
35
  private now(): string {
30
36
  return (this.d.now?.() ?? new Date()).toISOString();
@@ -37,11 +43,13 @@ export class PersonaService {
37
43
  }
38
44
 
39
45
  private rules(caller: Caller, scope: PersonaScope): PersonaRules {
46
+ // One catalog snapshot per save (D14), shared by every skillRule call.
47
+ const snap = this.d.skills.snapshot();
40
48
  return {
41
49
  mode: this.d.access.mode(),
42
50
  scope,
43
51
  caller,
44
- skillCatalog: this.d.config().skillCatalog ?? {},
52
+ skillRule: (name, target) => this.d.skills.checkSave(name, caller, target, scope, snap),
45
53
  assignableTargets: this.assignable(caller, scope),
46
54
  };
47
55
  }
@@ -152,6 +160,10 @@ export class PersonaService {
152
160
  this.capCheck("private", caller);
153
161
  const usable = this.assignable(caller, "private");
154
162
  const kept = src.projects.filter((id) => usable.has(id));
163
+ const forkProjects = kept.length > 0 ? kept : [WORKSPACE_TARGET];
164
+ // D5: the fork keeps only skills allowed for the forking user on every kept project.
165
+ const snap = this.d.skills.snapshot();
166
+ const keptSkills = src.skills?.filter((n) => forkProjects.every((t) => this.d.skills.checkSave(n, caller, t, "private", snap) === "ok"));
155
167
  const stamp = this.now();
156
168
  const fork: Persona = {
157
169
  schemaVersion: 1,
@@ -166,7 +178,7 @@ export class PersonaService {
166
178
  instructions: src.instructions,
167
179
  tools: src.tools === "full" ? "files" : src.tools,
168
180
  projects: kept.length > 0 ? kept : [WORKSPACE_TARGET],
169
- ...(src.skills ? { skills: src.skills } : {}),
181
+ ...(src.skills ? { skills: keptSkills } : {}),
170
182
  forkedFrom: src.key,
171
183
  createdAt: stamp,
172
184
  updatedAt: stamp,