@blackbelt-technology/pi-dashboard-team-plugin 0.9.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 +4 -4
  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
@@ -0,0 +1,681 @@
1
+ /**
2
+ * Admin skill catalog (D1–D4, D14). Union of config entries (`skillCatalog`,
3
+ * read-only) and managed entries (`<teamHome>/skills.json`, schemaVersion 1,
4
+ * written under an in-process mutex). One identity: the catalog name IS the
5
+ * skill's pi name. Every consumer reads normalised entries through this
6
+ * service. See change: add-team-skill-access.
7
+ */
8
+ import fs from "node:fs";
9
+ import path from "node:path";
10
+ import type { Access } from "./access.js";
11
+ import type { HostSession, Logger } from "./conversations.js";
12
+ import { atomicWriteJson, canonicalize, type FsOps, isInside, isTargetId, realFs, type TeamPaths, userKey } from "./paths.js";
13
+ import type { ProjectRegistry } from "./projects.js";
14
+ import { type LocatedRecord, spawnedSkillNames } from "./records.js";
15
+ import { type Caller, type Mode, type Persona, type PersonaScope, type SkillCatalogEntry, type TeamConfig, TeamError } from "./types.js";
16
+
17
+ type SkillUsers = "*" | { iss: string; sub: string }[];
18
+ type SkillTargets = "*" | string[];
19
+
20
+ /** Normalised catalog entry (legacy string + missing users/targets defaulted to `"*"`). */
21
+ export interface SkillEntry {
22
+ name: string;
23
+ source: "config" | "managed";
24
+ path: string;
25
+ users: SkillUsers;
26
+ targets: SkillTargets;
27
+ }
28
+
29
+ export type SkillBlockReason = "missing" | "invalid" | "users" | "targets";
30
+
31
+ const SKILL_PATH_MAX_BYTES = 512;
32
+
33
+ /** Only the head of SKILL.md is read for frontmatter; it lives at the top of the file (audit F6). */
34
+ const FRONTMATTER_MAX_BYTES = 8 * 1024;
35
+
36
+ /** pi skill name: `[a-z0-9-]`, 1–64 chars, no leading/trailing/doubled hyphen. */
37
+ const SKILL_NAME_RE = /^[a-z0-9](?:[a-z0-9]|-(?=[a-z0-9])){0,63}$/;
38
+
39
+ function isValidSkillName(name: unknown): name is string {
40
+ return typeof name === "string" && SKILL_NAME_RE.test(name);
41
+ }
42
+
43
+ /** D4 predicate: (single-user, or users match exactly) ∧ targets match. Pure. */
44
+ export function allowed(entry: Pick<SkillEntry, "users" | "targets">, caller: Caller, target: string, mode: Mode): boolean {
45
+ const usersOk =
46
+ mode === "single" || entry.users === "*" || entry.users.some((u) => u.iss === caller.iss && u.sub === caller.sub);
47
+ const targetsOk = entry.targets === "*" || entry.targets.includes(target);
48
+ return usersOk && targetsOk;
49
+ }
50
+
51
+ export interface CheckedSkill {
52
+ entry: SkillEntry;
53
+ valid: boolean;
54
+ /** realpath directory granted to the guard; only when valid. */
55
+ root?: string;
56
+ invalidReason?: string;
57
+ description?: string;
58
+ }
59
+
60
+ export interface SkillSnapshot {
61
+ rows: CheckedSkill[];
62
+ byName: Map<string, CheckedSkill>;
63
+ managedLoadError: string | null;
64
+ }
65
+
66
+ export interface AdminSkillRow {
67
+ name: string;
68
+ source: "config" | "managed";
69
+ path: string;
70
+ users: SkillUsers;
71
+ targets: SkillTargets;
72
+ valid: boolean;
73
+ invalidReason?: string;
74
+ description?: string;
75
+ usage: { personas: number; liveSessions: number };
76
+ }
77
+
78
+ export interface ImpactPreview {
79
+ endSessions: number;
80
+ blockedPersonas: { key: string; name: string; lostTargets: string[] }[];
81
+ otherUsersPrivate: number;
82
+ }
83
+
84
+ export interface OperatorSkill {
85
+ name: string;
86
+ description: string;
87
+ path: string;
88
+ source: string;
89
+ }
90
+
91
+ /** Read-side persona access for the usage/impact passes (all users' private personas). */
92
+ interface SkillPersonaSource {
93
+ get(key: string, uk: string): Persona | null;
94
+ listShared(): Persona[];
95
+ allPrivate(): { uk: string; persona: Persona }[];
96
+ }
97
+
98
+ interface SkillRecords {
99
+ scanAll(): LocatedRecord[];
100
+ }
101
+
102
+ interface ManagedRecord {
103
+ name: string;
104
+ path: string;
105
+ users: SkillUsers;
106
+ targets: SkillTargets;
107
+ createdAt: string;
108
+ createdBy: string;
109
+ updatedAt: string;
110
+ updatedBy: string;
111
+ }
112
+
113
+ interface ManagedFile {
114
+ schemaVersion: 1;
115
+ skills: ManagedRecord[];
116
+ }
117
+
118
+ export interface SkillsServiceDeps {
119
+ paths: TeamPaths;
120
+ projects: ProjectRegistry;
121
+ access: Access;
122
+ config: () => TeamConfig;
123
+ logger: Logger;
124
+ personas: SkillPersonaSource;
125
+ records: SkillRecords;
126
+ getSession: (id: string) => HostSession | undefined;
127
+ /** pi agent dir (`~/.pi/agent`): a skill root may lie inside it, never contain it. */
128
+ agentDir: string;
129
+ /** Parent of every per-cwd pi session dir (holds every team transcript). */
130
+ sessionsRoot: string;
131
+ /** Dashboard home (`~/.pi/dashboard`). */
132
+ dashboardHome: string;
133
+ /** `host.listOperatorSkills`; absent on older hosts → `available()` answers `[]`. */
134
+ listOperatorSkills?: () => Promise<OperatorSkill[]>;
135
+ /**
136
+ * D8 seam, called after a successful managed update/delete with the entry
137
+ * before and after and the admin's uk (for the per-end audit line); returns
138
+ * the number of sessions the change ended. Absent → 0.
139
+ */
140
+ onManagedWrite?: (name: string, before: SkillEntry | null, after: SkillEntry | null, by: string) => number | Promise<number>;
141
+ ops?: FsOps;
142
+ now?: () => Date;
143
+ }
144
+
145
+ function parseUsers(v: unknown): SkillUsers | null {
146
+ if (v === undefined || v === "*") return "*";
147
+ if (Array.isArray(v) && v.every((u) => !!u && typeof (u as { iss?: unknown }).iss === "string" && typeof (u as { sub?: unknown }).sub === "string")) {
148
+ return v.map((u: { iss: string; sub: string }) => ({ iss: u.iss, sub: u.sub }));
149
+ }
150
+ return null;
151
+ }
152
+
153
+ function parseTargets(v: unknown): SkillTargets | null {
154
+ if (v === undefined || v === "*") return "*";
155
+ if (Array.isArray(v) && v.length > 0 && v.every((t) => isTargetId(t))) return v as string[];
156
+ return null;
157
+ }
158
+
159
+ /** Frontmatter scalar fields of a SKILL.md (naive `key: value` scan between the `---` fences). */
160
+ function parseFrontmatter(raw: string): Record<string, string> {
161
+ const out: Record<string, string> = {};
162
+ const lines = raw.split(/\r?\n/);
163
+ if ((lines[0] ?? "").trim() !== "---") return out;
164
+ for (let i = 1; i < lines.length; i++) {
165
+ if (lines[i].trim() === "---") break;
166
+ const kv = /^([A-Za-z][A-Za-z0-9_-]*)\s*:\s*(.*)$/.exec(lines[i]);
167
+ if (kv) out[kv[1]] = kv[2].trim().replace(/^['"]|['"]$/g, "");
168
+ }
169
+ return out;
170
+ }
171
+
172
+ const WRITE_KEYS = new Set(["name", "path", "users", "targets"]);
173
+
174
+ /** The first `FRONTMATTER_MAX_BYTES` of `md` — frontmatter lives at the top; the body is never read here (audit F6). */
175
+ function readHead(md: string): string {
176
+ const fd = fs.openSync(md, "r");
177
+ try {
178
+ const buf = Buffer.alloc(FRONTMATTER_MAX_BYTES);
179
+ const bytes = fs.readSync(fd, buf, 0, buf.length, 0);
180
+ return buf.toString("utf8", 0, bytes);
181
+ } finally {
182
+ fs.closeSync(fd);
183
+ }
184
+ }
185
+ export class SkillsService {
186
+ private readonly d: SkillsServiceDeps;
187
+ private readonly ops: FsOps;
188
+ private readonly file: string;
189
+ private managed: { error: string | null; records: ManagedRecord[] } | undefined;
190
+ private readonly warned = new Set<string>();
191
+ /** Frontmatter memoised by the SKILL.md file's (realpath, mtimeMs, size), checked BEFORE any
192
+ * read so a memo hit costs only a stat; the read itself is capped at the first 8 KiB (audit F6). */
193
+ private readonly fmMemo = new Map<string, Record<string, string>>();
194
+ private tail: Promise<unknown> = Promise.resolve();
195
+ private epochN = 0;
196
+
197
+ constructor(d: SkillsServiceDeps) {
198
+ this.d = d;
199
+ this.ops = d.ops ?? realFs;
200
+ this.file = path.join(d.paths.home, "skills.json");
201
+ }
202
+
203
+ /** Monotonic counter, bumped by every successful managed write (check-then-act seam, D6). */
204
+ epoch(): number {
205
+ return this.epochN;
206
+ }
207
+
208
+ private enqueue<T>(fn: () => Promise<T>): Promise<T> {
209
+ const next = this.tail.then(fn, fn);
210
+ this.tail = next.catch(() => undefined);
211
+ return next;
212
+ }
213
+
214
+ // ── managed store ────────────────────────────────────────────────────────
215
+
216
+ /** Loaded once, then kept in memory; a bad file is ignored and blocks writes. */
217
+ private loadManaged(): { error: string | null; records: ManagedRecord[] } {
218
+ if (this.managed) return this.managed;
219
+ let raw: string;
220
+ try {
221
+ raw = fs.readFileSync(this.file, "utf8");
222
+ } catch {
223
+ return (this.managed = { error: null, records: [] });
224
+ }
225
+ let parsed: unknown;
226
+ try {
227
+ parsed = JSON.parse(raw);
228
+ } catch {
229
+ this.d.logger.warn("team.skills_store_invalid reason=unreadable");
230
+ return (this.managed = { error: "unreadable", records: [] });
231
+ }
232
+ const f = parsed as ManagedFile | null;
233
+ if (f?.schemaVersion !== 1 || !Array.isArray(f.skills)) {
234
+ this.d.logger.warn("team.skills_store_invalid reason=schema_version");
235
+ return (this.managed = { error: "schema_version", records: [] });
236
+ }
237
+ const records: ManagedRecord[] = [];
238
+ for (const r of f.skills) {
239
+ const users = parseUsers(r?.users);
240
+ const targets = parseTargets(r?.targets);
241
+ if (typeof r?.name !== "string" || typeof r.path !== "string" || !users || !targets) {
242
+ this.d.logger.warn("team.skills_store_invalid reason=entry_shape");
243
+ continue;
244
+ }
245
+ records.push({ ...r, users, targets });
246
+ }
247
+ return (this.managed = { error: null, records });
248
+ }
249
+
250
+ private persist(records: ManagedRecord[]): void {
251
+ atomicWriteJson(this.file, { schemaVersion: 1, skills: records } satisfies ManagedFile, this.ops);
252
+ this.managed = { error: null, records };
253
+ this.epochN++;
254
+ }
255
+
256
+ // ── normalisation + validation ───────────────────────────────────────────
257
+
258
+ private normalise(name: string, value: unknown, source: SkillEntry["source"]): SkillEntry | null {
259
+ const v = (typeof value === "string" ? { path: value } : value) as Partial<SkillCatalogEntry> | null;
260
+ if (!v || typeof v.path !== "string" || v.path.length === 0) return null;
261
+ const users = parseUsers(v.users);
262
+ const targets = parseTargets(v.targets);
263
+ if (!users || !targets) return null;
264
+ return { name, source, path: v.path, users, targets };
265
+ }
266
+
267
+ // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: one linear validation ladder per rejection reason
268
+ private validatePath(raw: string): { ok: true; root: string } | { ok: false; reason: string } {
269
+ if (typeof raw !== "string" || raw.length === 0 || raw.includes("\0") || !path.isAbsolute(raw)) return { ok: false, reason: "not_absolute" };
270
+ if (Buffer.byteLength(raw, "utf8") > SKILL_PATH_MAX_BYTES) return { ok: false, reason: "too_long" };
271
+ let real: string;
272
+ let st: fs.Stats;
273
+ try {
274
+ // Native realpath: on-disk case, so the exclusions below cannot be slipped past with a
275
+ // mis-cased candidate on a case-insensitive filesystem (audit F1).
276
+ real = fs.realpathSync.native(raw);
277
+ st = fs.statSync(real);
278
+ } catch {
279
+ return { ok: false, reason: "missing" };
280
+ }
281
+ if (!st.isDirectory()) return { ok: false, reason: "not_directory" };
282
+ try {
283
+ // lstat: SKILL.md must be a REGULAR file — a symlink would let the granted root vouch for
284
+ // bytes living elsewhere (audit F2).
285
+ if (!fs.lstatSync(path.join(real, "SKILL.md")).isFile()) return { ok: false, reason: "no_skill_md" };
286
+ } catch {
287
+ return { ok: false, reason: "no_skill_md" };
288
+ }
289
+ // Bidirectional exclusion (D3): never inside team home / project roots, never containing
290
+ // team home / project roots / agent dir / sessions root / dashboard home.
291
+ for (const p of this.d.projects.all()) {
292
+ if (p.path && (isInside(p.path, real) || isInside(real, p.path))) return { ok: false, reason: "protected_dir" };
293
+ }
294
+ if (isInside(this.d.paths.home, real) || isInside(real, this.d.paths.home)) return { ok: false, reason: "protected_dir" };
295
+ for (const fixed of [this.d.agentDir, this.d.sessionsRoot, this.d.dashboardHome]) {
296
+ if (isInside(real, canonicalize(fixed))) return { ok: false, reason: "protected_dir" };
297
+ }
298
+ return { ok: true, root: real };
299
+ }
300
+
301
+ private checkEntry(entry: SkillEntry): CheckedSkill {
302
+ const v = this.validatePath(entry.path);
303
+ if (!v.ok) return this.invalid(entry, v.reason);
304
+ const fm = this.frontmatter(v.root);
305
+ const piName = fm.name || path.basename(v.root);
306
+ if (piName !== entry.name) return this.invalid(entry, "name_mismatch");
307
+ return { entry, valid: true, root: v.root, description: this.description(fm) };
308
+ }
309
+
310
+ private invalid(entry: SkillEntry, reason: string): CheckedSkill {
311
+ this.warnInvalid(entry.name, reason);
312
+ return { entry, valid: false, invalidReason: reason };
313
+ }
314
+
315
+ private warnInvalid(name: string, reason: string): void {
316
+ const k = `${name}:${reason}`;
317
+ if (this.warned.has(k)) return;
318
+ this.warned.add(k);
319
+ this.d.logger.warn(`team.skill_invalid name=${name} reason=${reason}`);
320
+ }
321
+
322
+ private frontmatter(root: string): Record<string, string> {
323
+ const md = path.join(root, "SKILL.md");
324
+ try {
325
+ const st = fs.statSync(md);
326
+ const key = `${root}:${st.mtimeMs}:${st.size}`;
327
+ const hit = this.fmMemo.get(key);
328
+ if (hit !== undefined) return hit;
329
+ if (this.fmMemo.size > 1000) this.fmMemo.clear();
330
+ const fm = parseFrontmatter(readHead(md));
331
+ this.fmMemo.set(key, fm);
332
+ return fm;
333
+ } catch {
334
+ return {};
335
+ }
336
+ }
337
+
338
+ private description(fm: Record<string, string>): string {
339
+ return fm.description ?? "";
340
+ }
341
+
342
+ // ── snapshot + decisions ─────────────────────────────────────────────────
343
+
344
+ /** Union of config and managed entries, each validated once per call. */
345
+ snapshot(): SkillSnapshot {
346
+ const rows: CheckedSkill[] = [];
347
+ const byName = new Map<string, CheckedSkill>();
348
+ const config = this.d.config().skillCatalog ?? {};
349
+ for (const [name, value] of Object.entries(config)) {
350
+ if (!isValidSkillName(name)) {
351
+ this.warnInvalid(name, "invalid_name");
352
+ continue;
353
+ }
354
+ const entry = this.normalise(name, value, "config");
355
+ if (!entry) {
356
+ this.warnInvalid(name, "invalid_entry");
357
+ continue;
358
+ }
359
+ const chk = this.checkEntry(entry);
360
+ rows.push(chk);
361
+ byName.set(name, chk);
362
+ }
363
+ const configNames = new Set(byName.keys());
364
+ for (const r of this.loadManaged().records) {
365
+ const entry = this.normalise(r.name, r, "managed");
366
+ const chk = entry ? this.checkEntry(entry) : this.invalid({ name: r.name, source: "managed", path: r.path, users: r.users, targets: r.targets }, "invalid_entry");
367
+ if (configNames.has(r.name)) {
368
+ // D2: config wins; the managed entry is reported invalid.
369
+ chk.valid = false;
370
+ chk.invalidReason = "shadowed_by_config";
371
+ delete chk.root;
372
+ delete chk.description;
373
+ }
374
+ rows.push(chk);
375
+ if (!configNames.has(r.name)) byName.set(r.name, chk);
376
+ }
377
+ return { rows, byName, managedLoadError: this.loadManaged().error };
378
+ }
379
+
380
+ lookup(name: string, snap: SkillSnapshot = this.snapshot()): CheckedSkill | null {
381
+ return snap.byName.get(name) ?? null;
382
+ }
383
+
384
+ /** D4 + D3 in one: existence, validity, users, targets — for persona saves (D5). */
385
+ checkSave(name: string, caller: Caller, target: string, scope: PersonaScope, snap: SkillSnapshot = this.snapshot()): "ok" | "unknown" | "not_allowed" {
386
+ const chk = snap.byName.get(name) ?? null;
387
+ if (!chk) return "unknown";
388
+ if (!chk.valid || !chk.root) return "not_allowed";
389
+ if (scope === "shared") {
390
+ // Shared personas are user-agnostic at save time; only targets bind.
391
+ const e = chk.entry;
392
+ return e.targets === "*" || e.targets.includes(target) ? "ok" : "not_allowed";
393
+ }
394
+ return allowed(chk.entry, caller, target, this.d.access.mode()) ? "ok" : "not_allowed";
395
+ }
396
+
397
+ /** D6/D14 helper: first failing skill in persona order, or null. */
398
+ firstBlockedSkill(
399
+ skills: readonly string[],
400
+ caller: Caller,
401
+ target: string,
402
+ snap: SkillSnapshot = this.snapshot(),
403
+ ): { skill: string; reason: SkillBlockReason } | null {
404
+ const mode = this.d.access.mode();
405
+ for (const name of skills) {
406
+ const chk = snap.byName.get(name);
407
+ if (!chk) return { skill: name, reason: "missing" };
408
+ if (!chk.valid || !chk.root) return { skill: name, reason: "invalid" };
409
+ if (!allowed(chk.entry, caller, target, mode)) {
410
+ const e = chk.entry;
411
+ const usersOk = mode === "single" || e.users === "*" || e.users.some((u) => u.iss === caller.iss && u.sub === caller.sub);
412
+ return { skill: name, reason: usersOk ? "targets" : "users" };
413
+ }
414
+ }
415
+ return null;
416
+ }
417
+
418
+ /** The persona's skill names the caller may use in the target, in persona order. */
419
+ effectiveSkills(skills: readonly string[], caller: Caller, target: string, snap: SkillSnapshot = this.snapshot()): string[] {
420
+ return skills.filter((n) => this.firstBlockedSkill([n], caller, target, snap) === null);
421
+ }
422
+
423
+ /** Spawn resolver (slice C transport): {name, realpath root} for an allowed skill, else null. */
424
+ resolveSkillRoot(name: string, caller: Caller, target: string, snap: SkillSnapshot = this.snapshot()): { name: string; root: string } | null {
425
+ const chk = snap.byName.get(name);
426
+ if (!chk?.valid || !chk.root) return null;
427
+ if (!allowed(chk.entry, caller, target, this.d.access.mode())) return null;
428
+ return { name, root: chk.root };
429
+ }
430
+
431
+ // ── listings ─────────────────────────────────────────────────────────────
432
+
433
+ /** `/me` + non-admin listing names: allowed for at least one usable target. */
434
+ visibleNames(caller: Caller, usableTargets: readonly string[], snap: SkillSnapshot = this.snapshot()): string[] {
435
+ const mode = this.d.access.mode();
436
+ const out: string[] = [];
437
+ for (const chk of snap.byName.values()) {
438
+ if (!chk.valid) continue;
439
+ if (usableTargets.some((t) => allowed(chk.entry, caller, t, mode))) out.push(chk.entry.name);
440
+ }
441
+ return out.sort();
442
+ }
443
+
444
+ callerList(caller: Caller, usableTargets: readonly string[], snap: SkillSnapshot = this.snapshot()): { skills: { name: string; description?: string; targets: string[] }[] } {
445
+ const mode = this.d.access.mode();
446
+ const skills: { name: string; description?: string; targets: string[] }[] = [];
447
+ for (const chk of snap.byName.values()) {
448
+ if (!chk.valid) continue;
449
+ const targets = usableTargets.filter((t) => allowed(chk.entry, caller, t, mode));
450
+ if (targets.length > 0) skills.push({ name: chk.entry.name, description: chk.description, targets });
451
+ }
452
+ return { skills: skills.sort((a, b) => a.name.localeCompare(b.name)) };
453
+ }
454
+
455
+ adminList(snap: SkillSnapshot = this.snapshot()): { skills: AdminSkillRow[]; managedLoadError?: string } {
456
+ const usage = this.usage();
457
+ const skills = snap.rows
458
+ .map((chk) => this.rowOf(chk, usage))
459
+ .sort((a, b) => a.name.localeCompare(b.name) || a.source.localeCompare(b.source));
460
+ return { skills, ...(snap.managedLoadError ? { managedLoadError: snap.managedLoadError } : {}) };
461
+ }
462
+
463
+ private rowOf(chk: CheckedSkill, usage: Map<string, { personas: number; liveSessions: number }>): AdminSkillRow {
464
+ return {
465
+ name: chk.entry.name,
466
+ source: chk.entry.source,
467
+ path: chk.entry.path,
468
+ users: chk.entry.users,
469
+ targets: chk.entry.targets,
470
+ valid: chk.valid,
471
+ ...(chk.invalidReason ? { invalidReason: chk.invalidReason } : {}),
472
+ ...(chk.description !== undefined ? { description: chk.description } : {}),
473
+ usage: usage.get(chk.entry.name) ?? { personas: 0, liveSessions: 0 },
474
+ };
475
+ }
476
+
477
+ /** Live, owner-bound conversation records (same owner-binding rule as the former idle sweep). */
478
+ private liveRecords(): LocatedRecord[] {
479
+ const multi = this.d.access.mode() === "multi";
480
+ const out: LocatedRecord[] = [];
481
+ for (const lr of this.d.records.scanAll()) {
482
+ if (lr.record.archived) continue;
483
+ const s = this.d.getSession(lr.record.sessionId);
484
+ if (!s || s.status === "ended") continue;
485
+ if (multi && (!s.principalOwner || userKey(s.principalOwner.iss, s.principalOwner.sub) !== lr.uk)) continue;
486
+ out.push(lr);
487
+ }
488
+ return out;
489
+ }
490
+
491
+ private usage(): Map<string, { personas: number; liveSessions: number }> {
492
+ const counts = new Map<string, { personas: number; liveSessions: number }>();
493
+ const bump = (name: string, k: "personas" | "liveSessions") => {
494
+ const c = counts.get(name) ?? { personas: 0, liveSessions: 0 };
495
+ c[k]++;
496
+ counts.set(name, c);
497
+ };
498
+ for (const p of this.d.personas.listShared()) for (const n of p.skills ?? []) bump(n, "personas");
499
+ for (const { persona } of this.d.personas.allPrivate()) for (const n of persona.skills ?? []) bump(n, "personas");
500
+ for (const lr of this.liveRecords()) {
501
+ const p = this.d.personas.get(lr.record.personaKey, lr.uk);
502
+ for (const n of p?.skills ?? []) bump(n, "liveSessions");
503
+ }
504
+ return counts;
505
+ }
506
+
507
+ /** `GET /skills/available`: the operator's global skills; `[]` without the host service (D11). */
508
+ async available(): Promise<OperatorSkill[]> {
509
+ return (await this.d.listOperatorSkills?.()) ?? [];
510
+ }
511
+
512
+ // ── managed writes ───────────────────────────────────────────────────────
513
+
514
+ private requireAdmin(caller: Caller): void {
515
+ if (!caller.admin) throw new TeamError(403, "admin_required");
516
+ }
517
+
518
+ private bodyFields(body: unknown, allowedKeys: string[]): { b: Record<string, unknown>; fields: Record<string, string> } {
519
+ const b = (body && typeof body === "object" && !Array.isArray(body) ? body : {}) as Record<string, unknown>;
520
+ const fields: Record<string, string> = {};
521
+ for (const k of Object.keys(b)) if (!allowedKeys.includes(k)) fields[k] = "unknown_field";
522
+ return { b, fields };
523
+ }
524
+
525
+ private throwInvalid(fields: Record<string, string>): never {
526
+ throw new TeamError(400, "invalid_skill", { fields });
527
+ }
528
+
529
+ /** `fields.name = "name_mismatch"` for identity failures, `fields.path` for path failures. */
530
+ private fieldsOf(invalidReason: string): Record<string, string> {
531
+ return invalidReason === "name_mismatch" ? { name: "name_mismatch" } : { path: invalidReason };
532
+ }
533
+
534
+ async create(caller: Caller, body: unknown): Promise<AdminSkillRow> {
535
+ this.requireAdmin(caller);
536
+ const { b, fields } = this.bodyFields(body, [...WRITE_KEYS]);
537
+ if (!isValidSkillName(b.name)) fields.name = "invalid_name";
538
+ if (typeof b.path !== "string" || b.path.length === 0) fields.path = "invalid_path";
539
+ const users = parseUsers(b.users);
540
+ const targets = parseTargets(b.targets);
541
+ if (!users || !targets) {
542
+ if (!users) fields.users = "invalid_users";
543
+ if (!targets) fields.targets = "invalid_targets";
544
+ this.throwInvalid(fields);
545
+ }
546
+ if (Object.keys(fields).length > 0) this.throwInvalid(fields);
547
+ const name = b.name as string;
548
+ const rawPath = b.path as string;
549
+ return this.enqueue(async () => {
550
+ const state = this.loadManaged();
551
+ if (state.error) throw new TeamError(503, "skill_store_unavailable");
552
+ if (Object.hasOwn(this.d.config().skillCatalog ?? {}, name) || state.records.some((r) => r.name === name)) {
553
+ throw new TeamError(409, "skill_exists");
554
+ }
555
+ const chk = this.checkEntry({ name, source: "managed", path: rawPath, users, targets });
556
+ if (!chk.valid) this.throwInvalid(this.fieldsOf(chk.invalidReason as string));
557
+ const stamp = (this.d.now?.() ?? new Date()).toISOString();
558
+ this.persist([
559
+ ...state.records,
560
+ { name, path: rawPath, users, targets, createdAt: stamp, createdBy: caller.uk, updatedAt: stamp, updatedBy: caller.uk },
561
+ ]);
562
+ this.d.logger.info(`team.skill_write op=create name=${name} by=${caller.uk}`);
563
+ return this.rowOf(chk, new Map());
564
+ });
565
+ }
566
+
567
+ async update(caller: Caller, name: string, body: unknown): Promise<AdminSkillRow> {
568
+ this.requireAdmin(caller);
569
+ const { b, fields } = this.bodyFields(body, ["path", "users", "targets"]);
570
+ const users = b.users === undefined ? "*" : parseUsers(b.users);
571
+ const targets = b.targets === undefined ? "*" : parseTargets(b.targets);
572
+ if (b.path !== undefined && (typeof b.path !== "string" || b.path.length === 0)) fields.path = "invalid_path";
573
+ if (b.users !== undefined && !users) fields.users = "invalid_users";
574
+ if (b.targets !== undefined && !targets) fields.targets = "invalid_targets";
575
+ if (Object.keys(fields).length > 0) this.throwInvalid(fields);
576
+ // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: optional-field merge with per-field validation
577
+ return this.enqueue(async () => {
578
+ const state = this.loadManaged();
579
+ if (state.error) throw new TeamError(503, "skill_store_unavailable");
580
+ if (Object.hasOwn(this.d.config().skillCatalog ?? {}, name)) throw new TeamError(409, "skill_readonly");
581
+ const i = state.records.findIndex((r) => r.name === name);
582
+ if (i < 0) throw new TeamError(404, "skill_not_found");
583
+ const cur = state.records[i];
584
+ const merged = {
585
+ path: (b.path as string) ?? cur.path,
586
+ users: b.users === undefined ? cur.users : (users as SkillUsers),
587
+ targets: b.targets === undefined ? cur.targets : (targets as SkillTargets),
588
+ };
589
+ const before = this.normalise(name, cur, "managed");
590
+ const chk = this.checkEntry({ name, source: "managed", ...merged });
591
+ if (!chk.valid) this.throwInvalid(this.fieldsOf(chk.invalidReason as string));
592
+ const stamp = (this.d.now?.() ?? new Date()).toISOString();
593
+ this.persist(state.records.map((r, j) => (j === i ? { ...r, ...merged, updatedAt: stamp, updatedBy: caller.uk } : r)));
594
+ this.d.logger.info(`team.skill_write op=update name=${name} by=${caller.uk}`);
595
+ const ended = (await this.d.onManagedWrite?.(name, before, chk.entry, caller.uk)) ?? 0;
596
+ this.d.logger.info(`team.skill_invalidated name=${name} sessions=${ended}`);
597
+ return this.rowOf(chk, new Map());
598
+ });
599
+ }
600
+
601
+ async remove(caller: Caller, name: string): Promise<void> {
602
+ this.requireAdmin(caller);
603
+ await this.enqueue(async () => {
604
+ const state = this.loadManaged();
605
+ if (state.error) throw new TeamError(503, "skill_store_unavailable");
606
+ if (Object.hasOwn(this.d.config().skillCatalog ?? {}, name)) throw new TeamError(409, "skill_readonly");
607
+ const i = state.records.findIndex((r) => r.name === name);
608
+ if (i < 0) throw new TeamError(404, "skill_not_found");
609
+ const before = this.normalise(name, state.records[i], "managed");
610
+ this.persist(state.records.filter((_, j) => j !== i));
611
+ this.d.logger.info(`team.skill_write op=delete name=${name} by=${caller.uk}`);
612
+ const ended = (await this.d.onManagedWrite?.(name, before, null, caller.uk)) ?? 0;
613
+ this.d.logger.info(`team.skill_invalidated name=${name} sessions=${ended}`);
614
+ });
615
+ }
616
+
617
+ // ── impact preview (D8/D14, dry run) ─────────────────────────────────────
618
+
619
+ // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: dry-run decision table over personas and live sessions
620
+ async impact(caller: Caller, name: string, body: unknown): Promise<ImpactPreview> {
621
+ this.requireAdmin(caller);
622
+ const { b, fields } = this.bodyFields(body, ["path", "users", "targets", "remove"]);
623
+ if (b.remove !== undefined && typeof b.remove !== "boolean") fields.remove = "invalid_remove";
624
+ if (Object.keys(fields).length > 0) this.throwInvalid(fields);
625
+ const snap = this.snapshot();
626
+ const cur = snap.byName.get(name);
627
+ if (!cur) throw new TeamError(404, "skill_not_found");
628
+
629
+ let after: CheckedSkill | null = null;
630
+ if (b.remove !== true) {
631
+ const users = b.users === undefined ? cur.entry.users : parseUsers(b.users);
632
+ const targets = b.targets === undefined ? cur.entry.targets : parseTargets(b.targets);
633
+ const rawPath = b.path === undefined ? cur.entry.path : b.path;
634
+ if (!users || !targets || typeof rawPath !== "string") this.throwInvalid({ path: "invalid_path" });
635
+ const chk = this.checkEntry({ name, source: cur.entry.source, path: rawPath as string, users, targets });
636
+ if (!chk.valid) this.throwInvalid(this.fieldsOf(chk.invalidReason as string));
637
+ after = chk;
638
+ }
639
+
640
+ const mode = this.d.access.mode();
641
+ const before: CheckedSkill | null = cur.valid ? cur : null;
642
+ const rootChanged = before !== null && after !== null && before.root !== after.root;
643
+ const principalOf = (p: { iss: string; sub: string }): Caller => ({ uk: "", iss: p.iss, sub: p.sub, admin: false });
644
+ const beforeAllows = (principal: Caller, t: string) => before !== null && allowed(before.entry, principal, t, mode);
645
+ const afterAllows = (principal: Caller, t: string) => after !== null && allowed(after.entry, principal, t, mode) && !rootChanged;
646
+ const targetsOk = (e: { targets: SkillTargets }, t: string) => e.targets === "*" || e.targets.includes(t);
647
+ const someUser = (e: { users: SkillUsers }) => e.users === "*" || e.users.length > 0;
648
+ const beforeShared = (t: string) => before !== null && targetsOk(before.entry, t) && someUser(before.entry);
649
+ const afterShared = (t: string) => after !== null && targetsOk(after.entry, t) && someUser(after.entry) && !rootChanged;
650
+
651
+ let endSessions = 0;
652
+ for (const lr of this.liveRecords()) {
653
+ // A session is judged by the skills it was spawned with (recorded at spawn); the persona's
654
+ // CURRENT list is only the fallback for records that predate spawned-set records (audit F4).
655
+ const held = spawnedSkillNames(lr.record) ?? (this.d.personas.get(lr.record.personaKey, lr.uk)?.skills ?? []);
656
+ if (!held.includes(name)) continue;
657
+ const owner = mode === "single" ? { iss: "local", sub: "local" } : this.d.getSession(lr.record.sessionId)?.principalOwner;
658
+ if (!owner) continue;
659
+ if (beforeAllows(principalOf(owner), lr.t) && !afterAllows(principalOf(owner), lr.t)) endSessions++;
660
+ }
661
+
662
+ const blockedPersonas: ImpactPreview["blockedPersonas"] = [];
663
+ let otherUsersPrivate = 0;
664
+ const consider = (p: Persona, ownerUk: string | null) => {
665
+ if (!p.skills?.includes(name)) return;
666
+ let lost: string[];
667
+ if (p.scope === "private" && p.owner) {
668
+ const principal = principalOf(p.owner);
669
+ lost = p.projects.filter((t) => beforeAllows(principal, t) && !afterAllows(principal, t));
670
+ } else {
671
+ lost = p.projects.filter((t) => beforeShared(t) && !afterShared(t));
672
+ }
673
+ if (lost.length === 0) return;
674
+ if (ownerUk !== null && ownerUk !== caller.uk) otherUsersPrivate++;
675
+ else blockedPersonas.push({ key: p.key, name: p.name, lostTargets: lost });
676
+ };
677
+ for (const p of this.d.personas.listShared()) consider(p, null);
678
+ for (const { uk, persona } of this.d.personas.allPrivate()) consider(persona, uk);
679
+ return { endSessions, blockedPersonas, otherUsersPrivate };
680
+ }
681
+ }