@blackbelt-technology/pi-dashboard-team-plugin 0.8.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 (102) hide show
  1. package/README.md +101 -0
  2. package/dist/app/assets/InlineTerminalCard-6GBZ9nXN.css +32 -0
  3. package/dist/app/assets/InlineTerminalCard-BRjmM13k.js +53 -0
  4. package/dist/app/assets/PdfPreview-CCfKQhLL.js +2 -0
  5. package/dist/app/assets/RichDiff-BU1YI0CM.css +19 -0
  6. package/dist/app/assets/RichDiff-zrt7rxm3.js +41 -0
  7. package/dist/app/assets/abnfDiagram-VCTEODGH-BNRJZIa7.js +1 -0
  8. package/dist/app/assets/arc-Ccw1WVCw.js +1 -0
  9. package/dist/app/assets/architectureDiagram-5GKGNRK7-CmpCS5s2.js +36 -0
  10. package/dist/app/assets/blockDiagram-I7D4REHJ-M5oRqDla.js +129 -0
  11. package/dist/app/assets/c4Diagram-7LVT6UL2-C6v6KvuZ.js +38 -0
  12. package/dist/app/assets/channel-1wFLoesq.js +1 -0
  13. package/dist/app/assets/chunk-2Q5K7J3B-BrSnR-LD.js +1 -0
  14. package/dist/app/assets/chunk-5VM5RSS4-BAqdD3be.js +15 -0
  15. package/dist/app/assets/chunk-F27PBJKO-DNLocP_Z.js +1 -0
  16. package/dist/app/assets/chunk-IMKFNOWR-DwFLWoAj.js +231 -0
  17. package/dist/app/assets/chunk-JWPE2WC7-DwOQUkPK.js +1 -0
  18. package/dist/app/assets/chunk-POPQ4Y6H-CN6vxbUi.js +1 -0
  19. package/dist/app/assets/chunk-SVP7TREG-mfOuPsxp.js +88 -0
  20. package/dist/app/assets/chunk-TICWLB2K-R4JNWs6J.js +206 -0
  21. package/dist/app/assets/chunk-XXDRQBXY-Bwj8o9dr.js +1 -0
  22. package/dist/app/assets/classDiagram-ZZMXUADV-DeqkIaZ-.js +1 -0
  23. package/dist/app/assets/classDiagram-v2-VYDZK3BY-DeqkIaZ-.js +1 -0
  24. package/dist/app/assets/cose-bilkent-JH36ORCC-qCY2WMN8.js +1 -0
  25. package/dist/app/assets/cursor-editorTextHighlight-kG3uUOwL.svg +8 -0
  26. package/dist/app/assets/cynefin-OW5HDTMX-CNttFTW2.js +178 -0
  27. package/dist/app/assets/cynefinDiagram-5FMLGOSQ-CBX-RJXy.js +62 -0
  28. package/dist/app/assets/cytoscape.esm-Bch-eiPH.js +331 -0
  29. package/dist/app/assets/dagre-GXQ25YYZ-D-VD0Tcu.js +4 -0
  30. package/dist/app/assets/defaultLocale-DX6XiGOO.js +1 -0
  31. package/dist/app/assets/diagram-S7CK7UJ4-CQReIUYr.js +30 -0
  32. package/dist/app/assets/diagram-UQ7AKVKN-DyEU0WYX.js +41 -0
  33. package/dist/app/assets/diagram-VSXAHHWV-NLLDj0k8.js +3 -0
  34. package/dist/app/assets/diagram-VX7I27RA-Daf-u6xI.js +24 -0
  35. package/dist/app/assets/diagram-Z3DM3KII-B0O71sZp.js +24 -0
  36. package/dist/app/assets/ebnfDiagram-PWID7BFC-BSRAXWwk.js +1 -0
  37. package/dist/app/assets/erDiagram-RLTQ6QDP-DKoQjGux.js +99 -0
  38. package/dist/app/assets/flowDiagram-HODETNUW-gq74Q1SF.js +168 -0
  39. package/dist/app/assets/ganttDiagram-EL5Y4UJY-BIAOolFj.js +292 -0
  40. package/dist/app/assets/gitGraphDiagram-WWUBYQGX-BvZquV67.js +106 -0
  41. package/dist/app/assets/index-BTj-g2DX.js +559 -0
  42. package/dist/app/assets/index-owClP-R3.css +1 -0
  43. package/dist/app/assets/infoDiagram-27XIBGKW-dMwJRmit.js +2 -0
  44. package/dist/app/assets/init-Gi6I4Gst.js +1 -0
  45. package/dist/app/assets/ishikawaDiagram-5VMMS53U-DArpl74K.js +70 -0
  46. package/dist/app/assets/journeyDiagram-3NMN7TZE-B2sUGe5l.js +139 -0
  47. package/dist/app/assets/kanban-definition-UXKFOSKX-Cx6oCBKM.js +89 -0
  48. package/dist/app/assets/layout-BjHuHx4m.js +1 -0
  49. package/dist/app/assets/linear-CgCYMSPy.js +1 -0
  50. package/dist/app/assets/mdi-DoP81khn.js +1 -0
  51. package/dist/app/assets/mermaid.core-DiBBwf02.js +312 -0
  52. package/dist/app/assets/mindmap-definition-YA3MSWOX-DP2Penfk.js +96 -0
  53. package/dist/app/assets/ordinal-Cboi1Yqb.js +1 -0
  54. package/dist/app/assets/pdf-CcZYcL52.js +12 -0
  55. package/dist/app/assets/pdf.worker.min-CNKzwYUy.js +1 -0
  56. package/dist/app/assets/pdf.worker.min-yatZIOMy.mjs +21 -0
  57. package/dist/app/assets/pdf_viewer-BXbC1ghE.js +346 -0
  58. package/dist/app/assets/pdf_viewer-I4ZZuHqo.css +1 -0
  59. package/dist/app/assets/pegDiagram-XKGWAZYB-DuPy_Jk1.js +1 -0
  60. package/dist/app/assets/pieDiagram-E7YTZNPT-BHJIw8Ie.js +39 -0
  61. package/dist/app/assets/quadrantDiagram-AXDQQJYC-CKJDe9v8.js +7 -0
  62. package/dist/app/assets/railroadDiagram-O6MQD6OU-CPmw2XqA.js +1 -0
  63. package/dist/app/assets/requirementDiagram-BXWQKSXE-CbgXwlu-.js +84 -0
  64. package/dist/app/assets/sankeyDiagram-P5KCCOFB-xTHr7bNV.js +40 -0
  65. package/dist/app/assets/sequenceDiagram-WJ2MYXX4-BJO_VejT.js +162 -0
  66. package/dist/app/assets/sizeCapture-INFHLROL-BOIqspBs.js +1 -0
  67. package/dist/app/assets/stateDiagram-D77RDMKH-B1M9C9C6.js +1 -0
  68. package/dist/app/assets/stateDiagram-v2-MP3YSRHH-BWPtAAkO.js +1 -0
  69. package/dist/app/assets/swimlanes-42K2YHIH-BtpfWryU.js +1 -0
  70. package/dist/app/assets/swimlanesDiagram-VR7AAH4N-CRZvPlTl.js +8 -0
  71. package/dist/app/assets/timeline-definition-24CTP7MA-BaspCbTG.js +120 -0
  72. package/dist/app/assets/vennDiagram-4TSXK5OY-Rzs4n1uC.js +34 -0
  73. package/dist/app/assets/wardleyDiagram-VM6X3IG4-7u6IS5Iz.js +78 -0
  74. package/dist/app/assets/xychartDiagram-S5SC5T6Z-D-TnlcEC.js +7 -0
  75. package/dist/app/index.html +13 -0
  76. package/package.json +82 -0
  77. package/src/client/FolderTeamSection.tsx +96 -0
  78. package/src/client/TeamProjectDialog.tsx +202 -0
  79. package/src/client/index.tsx +9 -0
  80. package/src/client/match-store.ts +107 -0
  81. package/src/client/team-open.ts +27 -0
  82. package/src/configSchema.json +104 -0
  83. package/src/extension/guard.ts +97 -0
  84. package/src/extension/index.ts +44 -0
  85. package/src/i18n.ts +64 -0
  86. package/src/server/access.ts +43 -0
  87. package/src/server/conversations.ts +799 -0
  88. package/src/server/index.ts +39 -0
  89. package/src/server/paths.ts +164 -0
  90. package/src/server/persona.ts +167 -0
  91. package/src/server/personas-service.ts +178 -0
  92. package/src/server/projects.ts +294 -0
  93. package/src/server/records.ts +130 -0
  94. package/src/server/render.ts +50 -0
  95. package/src/server/routes.ts +239 -0
  96. package/src/server/static.ts +73 -0
  97. package/src/server/store-types.ts +8 -0
  98. package/src/server/store.ts +94 -0
  99. package/src/server/team.ts +105 -0
  100. package/src/server/text-write.ts +15 -0
  101. package/src/server/types.ts +112 -0
  102. package/src/server/users.ts +47 -0
@@ -0,0 +1,39 @@
1
+ /**
2
+ * team-plugin · SERVER entry. Mounts `/api/plugins/team/*` and the same-origin
3
+ * app at `/apps/team/`, and runs the conversation lifecycle (spawn / resume /
4
+ * idle ending). See change: add-team-plugin.
5
+ */
6
+ import path from "node:path";
7
+ import { fileURLToPath } from "node:url";
8
+ import type { ServerPluginContext } from "@blackbelt-technology/dashboard-plugin-runtime/server";
9
+ import type { HostPort, HostSession } from "./conversations.js";
10
+ import { createTeam } from "./team.js";
11
+ import type { TeamConfig } from "./types.js";
12
+
13
+ const HERE = path.dirname(fileURLToPath(import.meta.url));
14
+
15
+ async function registerPlugin(ctx: ServerPluginContext): Promise<void> {
16
+ const host: HostPort = {
17
+ spawnSession: (o) => ctx.spawnSession(o),
18
+ abortSpawnedRun: (a) => ctx.abortSpawnedRun(a),
19
+ getSession: (id) => ctx.sessionManager.getSession(id) as HostSession | undefined,
20
+ listAll: () => ctx.sessionManager.listAll() as HostSession[],
21
+ onSessionResolved: (h) => ctx.onSessionResolved(h),
22
+ onEvent: (h) => ctx.onEvent(h),
23
+ registerPiHandler: (type, h) => ctx.registerPiHandler(type, h),
24
+ };
25
+ const team = createTeam({
26
+ host,
27
+ identity: ctx.identity,
28
+ fastify: ctx.fastify,
29
+ config: () => ctx.getPluginConfig<TeamConfig>() ?? {},
30
+ logger: ctx.logger,
31
+ guardExtensionPath: path.resolve(HERE, "../extension/index.ts"),
32
+ distAppDir: path.resolve(HERE, "../../dist/app"),
33
+ });
34
+ await team.start();
35
+ ctx.onShutdown(() => team.stop());
36
+ ctx.logger.info("team plugin server entry activated");
37
+ }
38
+
39
+ export default registerPlugin;
@@ -0,0 +1,164 @@
1
+ /**
2
+ * Team data layout + path safety (D2). All paths are built from validated
3
+ * slugs + a hashed user key and asserted to lie under TEAM_HOME after
4
+ * canonicalising the longest existing ancestor.
5
+ * See change: add-team-plugin.
6
+ */
7
+ import { createHash } from "node:crypto";
8
+ import fs from "node:fs";
9
+ import os from "node:os";
10
+ import path from "node:path";
11
+ import { TeamError, WORKSPACE_TARGET } from "./types.js";
12
+
13
+ const SLUG_RE = /^[a-z0-9][a-z0-9-]{0,39}$/;
14
+
15
+ export function isSlug(v: unknown): v is string {
16
+ return typeof v === "string" && SLUG_RE.test(v);
17
+ }
18
+
19
+ /** `uk = hex(sha256(iss + "\0" + sub)).slice(0, 32)`. */
20
+ export function userKey(iss: string, sub: string): string {
21
+ return createHash("sha256").update(`${iss}\0${sub}`).digest("hex").slice(0, 32);
22
+ }
23
+
24
+ export const LOCAL_USER_KEY = "local";
25
+
26
+ /** A target id is a project slug or `_ws`. */
27
+ export function isTargetId(v: unknown): v is string {
28
+ return v === WORKSPACE_TARGET || isSlug(v);
29
+ }
30
+
31
+ /** Persona key `<scope>:<slug>` → parts, else null. */
32
+ export function parsePersonaKey(key: unknown): { scope: "shared" | "private"; slug: string } | null {
33
+ if (typeof key !== "string") return null;
34
+ const i = key.indexOf(":");
35
+ if (i < 0) return null;
36
+ const scope = key.slice(0, i);
37
+ const slug = key.slice(i + 1);
38
+ if ((scope !== "shared" && scope !== "private") || !isSlug(slug)) return null;
39
+ return { scope, slug };
40
+ }
41
+
42
+ /** Folder-safe form of a persona key: `<scope>-<slug>`. */
43
+ export function personaDirName(key: string): string {
44
+ const p = parsePersonaKey(key);
45
+ if (!p) throw new TeamError(400, "invalid_persona_key");
46
+ return `${p.scope}-${p.slug}`;
47
+ }
48
+
49
+ /** Longest-existing-ancestor realpath (symlinks resolved; absent tail kept lexically). */
50
+ export function canonicalize(p: string): string {
51
+ const abs = path.resolve(p);
52
+ let head = abs;
53
+ const tail: string[] = [];
54
+ for (;;) {
55
+ try {
56
+ const real = fs.realpathSync(head);
57
+ return tail.length ? path.join(real, ...tail.reverse()) : real;
58
+ } catch {
59
+ const parent = path.dirname(head);
60
+ if (parent === head) return abs;
61
+ tail.push(path.basename(head));
62
+ head = parent;
63
+ }
64
+ }
65
+ }
66
+
67
+ /** True when `child` equals or lies inside `parent` (both canonical). */
68
+ export function isInside(parent: string, child: string): boolean {
69
+ const rel = path.relative(parent, child);
70
+ return rel === "" || (!rel.startsWith("..") && !path.isAbsolute(rel));
71
+ }
72
+
73
+ export function resolveTeamHome(configured: string | undefined, env: NodeJS.ProcessEnv = process.env): string {
74
+ const pick = env.PI_TEAM_HOME?.trim() || configured?.trim();
75
+ const base = pick
76
+ ? pick.startsWith("~/")
77
+ ? path.join(os.homedir(), pick.slice(2))
78
+ : pick
79
+ : path.join(os.homedir(), ".pi", "dashboard", "team");
80
+ return path.resolve(base);
81
+ }
82
+
83
+ export class TeamPaths {
84
+ readonly home: string;
85
+ constructor(home: string) {
86
+ this.home = canonicalize(home);
87
+ }
88
+
89
+ /** Assert `p` canonicalises under TEAM_HOME. */
90
+ confine(p: string): string {
91
+ const canon = canonicalize(p);
92
+ if (!isInside(this.home, canon)) throw new TeamError(500, "path_escape");
93
+ return p;
94
+ }
95
+
96
+ private under(...parts: string[]): string {
97
+ return this.confine(path.join(this.home, ...parts));
98
+ }
99
+
100
+ sharedPersonasDir(): string {
101
+ return this.under("personas");
102
+ }
103
+ userDir(uk: string): string {
104
+ if (uk !== LOCAL_USER_KEY && !/^[0-9a-f]{32}$/.test(uk)) throw new TeamError(500, "invalid_user_key");
105
+ return this.under("users", uk);
106
+ }
107
+ privatePersonasDir(uk: string): string {
108
+ return this.under("users", this.ukSeg(uk), "personas");
109
+ }
110
+ conversationsDir(uk: string, t: string, personaKey: string): string {
111
+ if (!isTargetId(t)) throw new TeamError(400, "invalid_target");
112
+ return this.under("users", this.ukSeg(uk), "conversations", t, personaDirName(personaKey));
113
+ }
114
+ conversationsRoot(uk: string): string {
115
+ return this.under("users", this.ukSeg(uk), "conversations");
116
+ }
117
+ workspaceDir(uk: string): string {
118
+ return this.under("users", this.ukSeg(uk), "workspace");
119
+ }
120
+ runtimeDir(uk: string, personaKey: string): string {
121
+ return this.under("users", this.ukSeg(uk), "runtime", personaDirName(personaKey));
122
+ }
123
+ projectsFile(): string {
124
+ return this.under("projects.json");
125
+ }
126
+ usersFile(): string {
127
+ return this.under("users.json");
128
+ }
129
+ private ukSeg(uk: string): string {
130
+ if (uk !== LOCAL_USER_KEY && !/^[0-9a-f]{32}$/.test(uk)) throw new TeamError(500, "invalid_user_key");
131
+ return uk;
132
+ }
133
+ }
134
+
135
+ /** Atomic JSON write: tmp + rename; the tmp file is removed when the rename fails. */
136
+ export interface FsOps {
137
+ writeFile(p: string, data: string): void;
138
+ rename(a: string, b: string): void;
139
+ rm(p: string): void;
140
+ mkdir(p: string): void;
141
+ }
142
+
143
+ export const realFs: FsOps = {
144
+ writeFile: (p, d) => fs.writeFileSync(p, d, { mode: 0o600 }),
145
+ rename: (a, b) => fs.renameSync(a, b),
146
+ rm: (p) => fs.rmSync(p, { force: true }),
147
+ mkdir: (p) => fs.mkdirSync(p, { recursive: true, mode: 0o700 }),
148
+ };
149
+
150
+ export function atomicWriteJson(file: string, value: unknown, ops: FsOps = realFs): void {
151
+ ops.mkdir(path.dirname(file));
152
+ const tmp = `${file}.${process.pid}.${Math.random().toString(36).slice(2)}.tmp`;
153
+ try {
154
+ ops.writeFile(tmp, `${JSON.stringify(value, null, 2)}\n`);
155
+ ops.rename(tmp, file);
156
+ } catch (err) {
157
+ try {
158
+ ops.rm(tmp);
159
+ } catch {
160
+ /* best effort */
161
+ }
162
+ throw err;
163
+ }
164
+ }
@@ -0,0 +1,167 @@
1
+ /**
2
+ * Persona input validation (D3/D4). Pure: all environment (mode, admin,
3
+ * allowed targets, skill catalog) arrives through `PersonaRules`.
4
+ * See change: add-team-plugin.
5
+ */
6
+ import { isSlug } from "./paths.js";
7
+ import { type AvatarSpec, type Caller, type Mode, type PersonaRole, type PersonaScope, type ToolsPreset, WORKSPACE_TARGET } from "./types.js";
8
+
9
+ export const LIMITS = {
10
+ nameMax: 60,
11
+ descriptionMax: 280,
12
+ instructionsMaxBytes: 32768,
13
+ modelMax: 200,
14
+ projectsMax: 50,
15
+ skillsMax: 50,
16
+ privatePerUser: 50,
17
+ shared: 200,
18
+ } as const;
19
+
20
+ export interface PersonaRules {
21
+ mode: Mode;
22
+ scope: PersonaScope;
23
+ caller: Caller;
24
+ skillCatalog: Record<string, string>;
25
+ /** Targets the author may assign (always includes `_ws`). */
26
+ assignableTargets: ReadonlySet<string>;
27
+ }
28
+
29
+ interface PersonaInput {
30
+ slug?: string;
31
+ name: string;
32
+ description: string;
33
+ avatar: AvatarSpec;
34
+ role: PersonaRole;
35
+ model?: string;
36
+ instructions: string;
37
+ tools: ToolsPreset;
38
+ projects: string[];
39
+ skills?: string[];
40
+ }
41
+
42
+ export type Validation =
43
+ | { ok: true; value: PersonaInput }
44
+ | { ok: false; fields: Record<string, string> };
45
+
46
+ const ALLOWED_KEYS = new Set([
47
+ "slug",
48
+ "scope",
49
+ "name",
50
+ "description",
51
+ "avatar",
52
+ "role",
53
+ "model",
54
+ "instructions",
55
+ "tools",
56
+ "projects",
57
+ "skills",
58
+ ]);
59
+
60
+ export const cpLength = (s: string): number => [...s].length;
61
+
62
+ // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: many small independent branches (field / state rendering); splitting would scatter one linear flow
63
+ export function validatePersonaInput(body: unknown, rules: PersonaRules, opts: { create: boolean }): Validation {
64
+ const fields: Record<string, string> = {};
65
+ if (typeof body !== "object" || body === null || Array.isArray(body)) {
66
+ return { ok: false, fields: { _: "body_required" } };
67
+ }
68
+ const b = body as Record<string, unknown>;
69
+ for (const k of Object.keys(b)) if (!ALLOWED_KEYS.has(k)) fields[k] = "unknown_field";
70
+
71
+ let slug: string | undefined;
72
+ if (opts.create) {
73
+ if (!isSlug(b.slug)) fields.slug = "invalid_slug";
74
+ else slug = b.slug;
75
+ } else if (b.slug !== undefined) {
76
+ fields.slug = "immutable";
77
+ }
78
+
79
+ const name = b.name;
80
+ if (typeof name !== "string" || cpLength(name) < 1 || cpLength(name) > LIMITS.nameMax) fields.name = "invalid_length";
81
+
82
+ const description = b.description === undefined ? "" : b.description;
83
+ if (typeof description !== "string" || cpLength(description) > LIMITS.descriptionMax) fields.description = "invalid_length";
84
+
85
+ const instructions = b.instructions === undefined ? "" : b.instructions;
86
+ if (typeof instructions !== "string" || Buffer.byteLength(instructions, "utf8") > LIMITS.instructionsMaxBytes) {
87
+ fields.instructions = "too_long";
88
+ }
89
+
90
+ let avatar: AvatarSpec = { kind: "initials" };
91
+ if (b.avatar !== undefined) {
92
+ const a = b.avatar as Record<string, unknown> | null;
93
+ if (a && typeof a === "object" && a.kind === "initials" && Object.keys(a).length === 1) avatar = { kind: "initials" };
94
+ else if (
95
+ a &&
96
+ typeof a === "object" &&
97
+ a.kind === "gallery" &&
98
+ typeof a.id === "string" &&
99
+ /^[a-z0-9-]{1,40}$/.test(a.id) &&
100
+ Object.keys(a).length === 2
101
+ ) {
102
+ avatar = { kind: "gallery", id: a.id };
103
+ } else fields.avatar = "invalid_avatar";
104
+ }
105
+
106
+ let role: PersonaRole = "member";
107
+ if (b.role !== undefined) {
108
+ if (b.role === "leader" || b.role === "member") role = b.role;
109
+ else fields.role = "invalid_role";
110
+ }
111
+
112
+ let model: string | undefined;
113
+ if (b.model !== undefined) {
114
+ if (typeof b.model !== "string" || b.model.length === 0 || b.model.length > LIMITS.modelMax || b.model.includes("\0")) {
115
+ fields.model = "invalid_model";
116
+ } else model = b.model;
117
+ }
118
+
119
+ let tools: ToolsPreset = "chat";
120
+ if (b.tools !== undefined) {
121
+ if (b.tools === "chat" || b.tools === "files" || b.tools === "full") tools = b.tools;
122
+ else fields.tools = "invalid_tools";
123
+ }
124
+ if (tools === "full" && !(rules.mode === "single" && rules.scope === "shared")) fields.tools = "full_not_allowed";
125
+
126
+ let projects: string[] = [WORKSPACE_TARGET];
127
+ if (b.projects !== undefined) {
128
+ const p = b.projects;
129
+ if (!Array.isArray(p) || p.length < 1 || p.length > LIMITS.projectsMax) fields.projects = "invalid_projects";
130
+ else if (new Set(p).size !== p.length) fields.projects = "duplicate_projects";
131
+ else if (!p.every((x) => typeof x === "string" && rules.assignableTargets.has(x))) fields.projects = "unknown_project";
132
+ else projects = p as string[];
133
+ }
134
+
135
+ let skills: string[] | undefined;
136
+ if (b.skills !== undefined) {
137
+ 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[];
141
+ }
142
+
143
+ if (Object.keys(fields).length > 0) return { ok: false, fields };
144
+ return {
145
+ ok: true,
146
+ value: {
147
+ slug,
148
+ name: name as string,
149
+ description: description as string,
150
+ avatar,
151
+ role,
152
+ model,
153
+ instructions: instructions as string,
154
+ tools,
155
+ projects,
156
+ skills,
157
+ },
158
+ };
159
+ }
160
+
161
+ /** Fork slug: base truncated so `<base>-<n>` fits 40 chars. */
162
+ export function suffixedSlug(base: string, n: number): string {
163
+ if (n <= 1) return base;
164
+ const suffix = `-${n}`;
165
+ const trimmed = base.slice(0, 40 - suffix.length).replace(/-+$/, "");
166
+ return `${trimmed}${suffix}`;
167
+ }
@@ -0,0 +1,178 @@
1
+ /**
2
+ * Persona operations (D3/D4): create / update / delete / fork with the
3
+ * admin + owner gates and caps. See change: add-team-plugin.
4
+ */
5
+ import type { Access } from "./access.js";
6
+ import { isSlug, parsePersonaKey } from "./paths.js";
7
+ import { LIMITS, type PersonaRules, suffixedSlug, validatePersonaInput } from "./persona.js";
8
+ import type { ProjectRegistry } from "./projects.js";
9
+ import type { PersonaStore as FsPersonaStore } from "./store.js";
10
+ import { type Caller, type Persona, type PersonaScope, type TeamConfig, TeamError, WORKSPACE_TARGET } from "./types.js";
11
+
12
+ export interface PersonaServiceDeps {
13
+ store: FsPersonaStore;
14
+ projects: ProjectRegistry;
15
+ access: Access;
16
+ config: () => TeamConfig;
17
+ now?: () => Date;
18
+ }
19
+
20
+ /** Wire form: no `owner` (callers only ever see their own private personas). */
21
+ function publicPersona(p: Persona): Omit<Persona, "owner"> {
22
+ const { owner: _owner, ...rest } = p;
23
+ return rest;
24
+ }
25
+
26
+ export class PersonaService {
27
+ constructor(private readonly d: PersonaServiceDeps) {}
28
+
29
+ private now(): string {
30
+ return (this.d.now?.() ?? new Date()).toISOString();
31
+ }
32
+
33
+ private assignable(caller: Caller, scope: PersonaScope): Set<string> {
34
+ const mode = this.d.access.mode();
35
+ const ids = scope === "shared" ? this.d.projects.all().map((p) => p.id) : this.d.projects.usableBy(caller, mode).map((p) => p.id);
36
+ return new Set([WORKSPACE_TARGET, ...ids]);
37
+ }
38
+
39
+ private rules(caller: Caller, scope: PersonaScope): PersonaRules {
40
+ return {
41
+ mode: this.d.access.mode(),
42
+ scope,
43
+ caller,
44
+ skillCatalog: this.d.config().skillCatalog ?? {},
45
+ assignableTargets: this.assignable(caller, scope),
46
+ };
47
+ }
48
+
49
+ list(caller: Caller): Omit<Persona, "owner">[] {
50
+ return [...this.d.store.listShared(), ...this.d.store.listPrivate(caller.uk)].map(publicPersona);
51
+ }
52
+
53
+ private requireWritable(caller: Caller, key: string): Persona {
54
+ const parsed = parsePersonaKey(key);
55
+ if (!parsed) throw new TeamError(404, "persona_not_found");
56
+ const p = this.d.store.get(key, caller.uk);
57
+ if (!p) throw new TeamError(404, "persona_not_found");
58
+ if (parsed.scope === "shared" && !caller.admin) throw new TeamError(403, "admin_required");
59
+ return p;
60
+ }
61
+
62
+ private capCheck(scope: PersonaScope, caller: Caller): void {
63
+ const n = this.d.store.count(scope, caller.uk);
64
+ if (n >= (scope === "shared" ? LIMITS.shared : LIMITS.privatePerUser)) throw new TeamError(409, "persona_limit");
65
+ }
66
+
67
+ create(caller: Caller, body: unknown): Omit<Persona, "owner"> {
68
+ const raw = (body && typeof body === "object" ? (body as Record<string, unknown>).scope : undefined) ?? "private";
69
+ if (raw !== "shared" && raw !== "private") throw new TeamError(400, "invalid_persona", { fields: { scope: "invalid_scope" } });
70
+ const scope: PersonaScope = raw;
71
+ if (scope === "shared" && !caller.admin) throw new TeamError(403, "admin_required");
72
+ const v = validatePersonaInput(body, this.rules(caller, scope), { create: true });
73
+ if (!v.ok) throw new TeamError(400, "invalid_persona", { fields: v.fields });
74
+ const slug = v.value.slug as string;
75
+ const key = `${scope}:${slug}`;
76
+ if (this.d.store.exists(key, caller.uk)) throw new TeamError(409, "slug_taken");
77
+ this.capCheck(scope, caller);
78
+ const stamp = this.now();
79
+ const persona: Persona = {
80
+ schemaVersion: 1,
81
+ key,
82
+ scope,
83
+ ...(scope === "private" ? { owner: { iss: caller.iss, sub: caller.sub } } : {}),
84
+ name: v.value.name,
85
+ description: v.value.description,
86
+ avatar: v.value.avatar,
87
+ role: v.value.role,
88
+ ...(v.value.model ? { model: v.value.model } : {}),
89
+ instructions: v.value.instructions,
90
+ tools: v.value.tools,
91
+ projects: v.value.projects,
92
+ ...(v.value.skills ? { skills: v.value.skills } : {}),
93
+ createdAt: stamp,
94
+ updatedAt: stamp,
95
+ updatedBy: caller.uk,
96
+ };
97
+ this.d.store.put(persona, caller.uk);
98
+ return publicPersona(persona);
99
+ }
100
+
101
+ update(caller: Caller, key: string, body: unknown): Omit<Persona, "owner"> {
102
+ const cur = this.requireWritable(caller, key);
103
+ const v = validatePersonaInput(body, this.rules(caller, cur.scope), { create: false });
104
+ if (!v.ok) throw new TeamError(400, "invalid_persona", { fields: v.fields });
105
+ // A scope in the body is only legal when unchanged.
106
+ const bodyScope = (body as Record<string, unknown>).scope;
107
+ if (bodyScope !== undefined && bodyScope !== cur.scope) throw new TeamError(400, "invalid_persona", { fields: { scope: "immutable" } });
108
+ let updatedAt = this.now();
109
+ if (updatedAt <= cur.updatedAt) updatedAt = new Date(Date.parse(cur.updatedAt) + 1).toISOString();
110
+ const next: Persona = {
111
+ ...cur,
112
+ name: v.value.name,
113
+ description: v.value.description,
114
+ avatar: v.value.avatar,
115
+ role: v.value.role,
116
+ model: v.value.model,
117
+ instructions: v.value.instructions,
118
+ tools: v.value.tools,
119
+ projects: v.value.projects,
120
+ skills: v.value.skills,
121
+ updatedAt,
122
+ updatedBy: caller.uk,
123
+ };
124
+ if (!next.model) delete next.model;
125
+ if (!next.skills) delete next.skills;
126
+ this.d.store.put(next, caller.uk);
127
+ return publicPersona(next);
128
+ }
129
+
130
+ remove(caller: Caller, key: string): void {
131
+ this.requireWritable(caller, key);
132
+ this.d.store.remove(key, caller.uk);
133
+ }
134
+
135
+ // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: many small independent branches (field / state rendering); splitting would scatter one linear flow
136
+ fork(caller: Caller, key: string, body: unknown): Omit<Persona, "owner"> {
137
+ const src = this.d.store.get(key, caller.uk);
138
+ if (!src) throw new TeamError(404, "persona_not_found");
139
+ const b = body && typeof body === "object" ? (body as Record<string, unknown>) : {};
140
+ for (const k of Object.keys(b)) if (k !== "slug") throw new TeamError(400, "invalid_persona", { fields: { [k]: "unknown_field" } });
141
+ const srcSlug = (parsePersonaKey(key) as { slug: string }).slug;
142
+ let slug: string;
143
+ if (b.slug !== undefined) {
144
+ if (!isSlug(b.slug)) throw new TeamError(400, "invalid_persona", { fields: { slug: "invalid_slug" } });
145
+ if (this.d.store.exists(`private:${b.slug}`, caller.uk)) throw new TeamError(409, "slug_taken");
146
+ slug = b.slug;
147
+ } else {
148
+ let n = 1;
149
+ slug = suffixedSlug(srcSlug, n);
150
+ while (this.d.store.exists(`private:${slug}`, caller.uk)) slug = suffixedSlug(srcSlug, ++n);
151
+ }
152
+ this.capCheck("private", caller);
153
+ const usable = this.assignable(caller, "private");
154
+ const kept = src.projects.filter((id) => usable.has(id));
155
+ const stamp = this.now();
156
+ const fork: Persona = {
157
+ schemaVersion: 1,
158
+ key: `private:${slug}`,
159
+ scope: "private",
160
+ owner: { iss: caller.iss, sub: caller.sub },
161
+ name: src.name,
162
+ description: src.description,
163
+ avatar: src.avatar,
164
+ role: src.role,
165
+ ...(src.model ? { model: src.model } : {}),
166
+ instructions: src.instructions,
167
+ tools: src.tools === "full" ? "files" : src.tools,
168
+ projects: kept.length > 0 ? kept : [WORKSPACE_TARGET],
169
+ ...(src.skills ? { skills: src.skills } : {}),
170
+ forkedFrom: src.key,
171
+ createdAt: stamp,
172
+ updatedAt: stamp,
173
+ updatedBy: caller.uk,
174
+ };
175
+ this.d.store.put(fork, caller.uk);
176
+ return publicPersona(fork);
177
+ }
178
+ }