@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,294 @@
1
+ /**
2
+ * Project registry (D13/D17): admin-config projects (read-only) + folders
3
+ * enabled from the dashboard (`TEAM_HOME/projects.json`), path validation,
4
+ * allowlists and folder → project matching. See change: add-team-plugin.
5
+ */
6
+ import fs from "node:fs";
7
+ import path from "node:path";
8
+ import { atomicWriteJson, canonicalize, type FsOps, isInside, isSlug, realFs, type TeamPaths } from "./paths.js";
9
+ import { cpLength } from "./persona.js";
10
+ import { type Caller, type Mode, type Project, type ProjectConfigEntry, type TeamConfig, TeamError } from "./types.js";
11
+
12
+ const FOLDER_PROJECTS_MAX = 200;
13
+
14
+ interface ProjectLogger {
15
+ info(msg: string): void;
16
+ warn(msg: string): void;
17
+ }
18
+
19
+ interface StoredFolderProject {
20
+ id: string;
21
+ name: string;
22
+ path: string;
23
+ users: "*" | { iss: string; sub: string }[];
24
+ contextFiles: boolean;
25
+ createdBy: string;
26
+ createdAt: string;
27
+ }
28
+
29
+ interface FolderFile {
30
+ schemaVersion: 1;
31
+ projects: StoredFolderProject[];
32
+ }
33
+
34
+ export type PathCheck = { ok: true; real: string } | { ok: false; reason: string };
35
+
36
+ export interface ProjectDeps {
37
+ paths: TeamPaths;
38
+ config: () => TeamConfig;
39
+ logger: ProjectLogger;
40
+ /** pi agent dir (`~/.pi`); a project may not contain or lie inside it. */
41
+ piDir: string;
42
+ now?: () => Date;
43
+ ops?: FsOps;
44
+ }
45
+
46
+ type UsersSpec = "*" | { iss: string; sub: string }[];
47
+
48
+ function parseUsers(v: unknown): UsersSpec | null {
49
+ if (v === "*") return "*";
50
+ if (Array.isArray(v) && v.every((u) => u && typeof u.iss === "string" && typeof u.sub === "string")) {
51
+ return v.map((u: { iss: string; sub: string }) => ({ iss: u.iss, sub: u.sub }));
52
+ }
53
+ return null;
54
+ }
55
+
56
+ /** Strip leading/trailing "-" with plain loops (no backtracking regex on caller-controlled input). */
57
+ function trimDashes(v: string): string {
58
+ let a = 0;
59
+ let b = v.length;
60
+ while (a < b && v[a] === "-") a++;
61
+ while (b > a && v[b - 1] === "-") b--;
62
+ return v.slice(a, b);
63
+ }
64
+
65
+ function slugify(base: string): string {
66
+ const s = trimDashes(base.toLowerCase().replace(/[^a-z0-9]+/g, "-")).slice(0, 40);
67
+ const t = trimDashes(s);
68
+ return isSlug(t) ? t : "project";
69
+ }
70
+
71
+ export class ProjectRegistry {
72
+ private readonly ops: FsOps;
73
+ private accepted = new Set<string>();
74
+ private acceptedFor = "";
75
+ private readonly warned = new Set<string>();
76
+
77
+ constructor(private readonly deps: ProjectDeps) {
78
+ this.ops = deps.ops ?? realFs;
79
+ this.activate();
80
+ }
81
+
82
+ /** Validate a candidate project root (D13). */
83
+ validatePath(p: unknown): PathCheck {
84
+ if (typeof p !== "string" || p.length === 0 || p.includes("\0")) return { ok: false, reason: "not_absolute" };
85
+ if (!path.isAbsolute(p)) return { ok: false, reason: "not_absolute" };
86
+ let real: string;
87
+ try {
88
+ real = fs.realpathSync(p);
89
+ } catch {
90
+ return { ok: false, reason: "missing" };
91
+ }
92
+ try {
93
+ if (!fs.statSync(real).isDirectory()) return { ok: false, reason: "not_directory" };
94
+ } catch {
95
+ return { ok: false, reason: "missing" };
96
+ }
97
+ for (const forbidden of [this.deps.paths.home, canonicalize(this.deps.piDir)]) {
98
+ if (isInside(forbidden, real) || isInside(real, forbidden)) return { ok: false, reason: "overlaps_protected_dir" };
99
+ }
100
+ return { ok: true, real };
101
+ }
102
+
103
+ private warnOnce(id: string, reason: string): void {
104
+ const k = `${id}:${reason}`;
105
+ if (this.warned.has(k)) return;
106
+ this.warned.add(k);
107
+ this.deps.logger.warn(`team.project_invalid projectId=${id} reason=${reason}`);
108
+ }
109
+
110
+ private configEntries(): Record<string, ProjectConfigEntry> {
111
+ return this.deps.config().projects ?? {};
112
+ }
113
+
114
+ /** Re-derive the accepted set when the config changed (activation semantics). */
115
+ private activate(): void {
116
+ const entries = this.configEntries();
117
+ const sig = JSON.stringify(entries);
118
+ if (sig === this.acceptedFor) return;
119
+ this.acceptedFor = sig;
120
+ this.accepted = new Set();
121
+ for (const [id, e] of Object.entries(entries)) {
122
+ if (!isSlug(id)) {
123
+ this.warnOnce(id, "invalid_id");
124
+ continue;
125
+ }
126
+ if (!e || typeof e.name !== "string" || cpLength(e.name) < 1 || cpLength(e.name) > 60 || parseUsers(e.users) === null) {
127
+ this.warnOnce(id, "invalid_entry");
128
+ continue;
129
+ }
130
+ const check = this.validatePath(e.path);
131
+ if (!check.ok) {
132
+ this.warnOnce(id, check.reason);
133
+ continue;
134
+ }
135
+ this.accepted.add(id);
136
+ }
137
+ }
138
+
139
+ private readFolderFile(): StoredFolderProject[] {
140
+ try {
141
+ const raw = JSON.parse(fs.readFileSync(this.deps.paths.projectsFile(), "utf8")) as FolderFile;
142
+ return raw?.schemaVersion === 1 && Array.isArray(raw.projects) ? raw.projects : [];
143
+ } catch {
144
+ return [];
145
+ }
146
+ }
147
+
148
+ private writeFolderFile(projects: StoredFolderProject[]): void {
149
+ atomicWriteJson(this.deps.paths.projectsFile(), { schemaVersion: 1, projects } satisfies FolderFile, this.ops);
150
+ }
151
+
152
+ private toProject(
153
+ id: string,
154
+ name: string,
155
+ p: string,
156
+ users: UsersSpec,
157
+ contextFiles: boolean,
158
+ source: Project["source"],
159
+ ): Project {
160
+ const check = this.validatePath(p);
161
+ if (!check.ok && source === "config") this.warnOnce(id, check.reason);
162
+ return { id, name, path: check.ok ? check.real : undefined, users, contextFiles, source, available: check.ok };
163
+ }
164
+
165
+ /** Every project (config wins over a folder-enabled one on id or path). */
166
+ all(): Project[] {
167
+ this.activate();
168
+ const out: Project[] = [];
169
+ const ids = new Set<string>();
170
+ const paths = new Set<string>();
171
+ for (const [id, e] of Object.entries(this.configEntries())) {
172
+ if (!this.accepted.has(id)) continue;
173
+ const users = parseUsers(e.users) ?? [];
174
+ const proj = this.toProject(id, e.name, e.path, users, e.contextFiles === true, "config");
175
+ out.push(proj);
176
+ ids.add(id);
177
+ const c = this.validatePath(e.path);
178
+ if (c.ok) paths.add(c.real);
179
+ }
180
+ for (const f of this.readFolderFile()) {
181
+ const c = this.validatePath(f.path);
182
+ if (ids.has(f.id) || (c.ok && paths.has(c.real))) {
183
+ this.warnOnce(f.id, "shadowed_by_config");
184
+ continue;
185
+ }
186
+ out.push(this.toProject(f.id, f.name, f.path, f.users, f.contextFiles === true, "folder"));
187
+ ids.add(f.id);
188
+ }
189
+ return out;
190
+ }
191
+
192
+ get(id: string): Project | undefined {
193
+ return this.all().find((p) => p.id === id);
194
+ }
195
+
196
+ canUse(project: Project, caller: Caller, mode: Mode): boolean {
197
+ if (mode === "single") return true;
198
+ if (project.users === "*") return true;
199
+ return project.users.some((u) => u.iss === caller.iss && u.sub === caller.sub);
200
+ }
201
+
202
+ /** Projects the caller may use (listed even when unavailable). */
203
+ usableBy(caller: Caller, mode: Mode): Project[] {
204
+ return this.all().filter((p) => this.canUse(p, caller, mode));
205
+ }
206
+
207
+ /** `realpath(cwd)` equal to a usable project, else the nearest containing one (D17). */
208
+ resolveFolder(caller: Caller, mode: Mode, cwd: string): Project | null {
209
+ if (typeof cwd !== "string" || !path.isAbsolute(cwd)) return null;
210
+ let real: string;
211
+ try {
212
+ real = fs.realpathSync(cwd);
213
+ } catch {
214
+ return null;
215
+ }
216
+ let best: Project | null = null;
217
+ for (const p of this.usableBy(caller, mode)) {
218
+ if (!p.available || !p.path || !isInside(p.path, real)) continue;
219
+ if (!best || (p.path?.length ?? 0) > (best.path?.length ?? 0)) best = p;
220
+ }
221
+ return best;
222
+ }
223
+
224
+ /** May the caller enable this folder as a project? */
225
+ enableable(caller: Caller, cwd: string): boolean {
226
+ if (!caller.admin) return false;
227
+ const check = this.validatePath(cwd);
228
+ if (!check.ok) return false;
229
+ return !this.all().some((p) => p.path === check.real);
230
+ }
231
+
232
+ // ── folder-enabled writes (D17) ────────────────────────────────────────────
233
+
234
+ enable(
235
+ caller: Caller,
236
+ body: { path?: unknown; name?: unknown; users?: unknown; contextFiles?: unknown },
237
+ ): { id: string } {
238
+ if (!caller.admin) throw new TeamError(403, "admin_required");
239
+ const check = this.validatePath(body.path);
240
+ if (!check.ok) throw new TeamError(400, "invalid_project", { reason: check.reason });
241
+ if (this.all().some((p) => p.path === check.real)) throw new TeamError(409, "project_exists");
242
+ const stored = this.readFolderFile();
243
+ if (stored.length >= FOLDER_PROJECTS_MAX) throw new TeamError(409, "project_limit");
244
+ const base = path.basename(check.real);
245
+ const name = body.name === undefined ? base : body.name;
246
+ if (typeof name !== "string" || cpLength(name) < 1 || cpLength(name) > 60) throw new TeamError(400, "invalid_project", { reason: "name" });
247
+ const users = body.users === undefined ? "*" : parseUsers(body.users);
248
+ if (users === null || (Array.isArray(users) && users.length === 0)) throw new TeamError(400, "invalid_project", { reason: "users" });
249
+ const taken = new Set([...Object.keys(this.configEntries()), ...stored.map((s) => s.id)]);
250
+ let id = slugify(base);
251
+ for (let n = 2; taken.has(id); n++) id = `${slugify(base).slice(0, 36)}-${n}`;
252
+ stored.push({
253
+ id,
254
+ name,
255
+ path: check.real,
256
+ users,
257
+ contextFiles: body.contextFiles === true,
258
+ createdBy: caller.uk,
259
+ createdAt: (this.deps.now?.() ?? new Date()).toISOString(),
260
+ });
261
+ this.writeFolderFile(stored);
262
+ return { id };
263
+ }
264
+
265
+ private requireFolderProject(id: string): StoredFolderProject[] {
266
+ if (Object.hasOwn(this.configEntries(), id) && this.accepted.has(id)) throw new TeamError(409, "project_readonly");
267
+ const stored = this.readFolderFile();
268
+ if (!stored.some((s) => s.id === id)) throw new TeamError(404, "project_not_found");
269
+ return stored;
270
+ }
271
+
272
+ patch(caller: Caller, id: string, body: { name?: unknown; users?: unknown; contextFiles?: unknown }): void {
273
+ if (!caller.admin) throw new TeamError(403, "admin_required");
274
+ const stored = this.requireFolderProject(id);
275
+ const cur = stored.find((s) => s.id === id) as StoredFolderProject;
276
+ if (body.name !== undefined) {
277
+ if (typeof body.name !== "string" || cpLength(body.name) < 1 || cpLength(body.name) > 60) throw new TeamError(400, "invalid_project", { reason: "name" });
278
+ cur.name = body.name;
279
+ }
280
+ if (body.users !== undefined) {
281
+ const users = parseUsers(body.users);
282
+ if (users === null || (Array.isArray(users) && users.length === 0)) throw new TeamError(400, "invalid_project", { reason: "users" });
283
+ cur.users = users;
284
+ }
285
+ if (body.contextFiles !== undefined) cur.contextFiles = body.contextFiles === true;
286
+ this.writeFolderFile(stored);
287
+ }
288
+
289
+ disable(caller: Caller, id: string): void {
290
+ if (!caller.admin) throw new TeamError(403, "admin_required");
291
+ const stored = this.requireFolderProject(id);
292
+ this.writeFolderFile(stored.filter((s) => s.id !== id));
293
+ }
294
+ }
@@ -0,0 +1,130 @@
1
+ /**
2
+ * Conversation records (D5): one JSON file per conversation under
3
+ * `users/<uk>/conversations/<t>/<scope>-<slug>/<c>.json`, plus an in-memory
4
+ * sessionId → locator index for event routing. See change: add-team-plugin.
5
+ */
6
+ import fs from "node:fs";
7
+ import path from "node:path";
8
+ import { atomicWriteJson, type FsOps, LOCAL_USER_KEY, personaDirName, realFs, type TeamPaths } from "./paths.js";
9
+ import { type ConversationRecord, TeamError } from "./types.js";
10
+
11
+ const CONVERSATION_ID_RE = /^[A-Za-z0-9_-]{22}$/;
12
+
13
+ export interface Locator {
14
+ uk: string;
15
+ t: string;
16
+ personaKey: string;
17
+ c: string;
18
+ }
19
+
20
+ export interface LocatedRecord extends Locator {
21
+ record: ConversationRecord;
22
+ }
23
+
24
+ function personaKeyFromDir(name: string): string | null {
25
+ if (name.startsWith("shared-")) return `shared:${name.slice(7)}`;
26
+ if (name.startsWith("private-")) return `private:${name.slice(8)}`;
27
+ return null;
28
+ }
29
+
30
+ export class RecordStore {
31
+ private index = new Map<string, Locator>();
32
+
33
+ constructor(
34
+ private readonly paths: TeamPaths,
35
+ private readonly ops: FsOps = realFs,
36
+ ) {}
37
+
38
+ private file(l: Locator): string {
39
+ if (!CONVERSATION_ID_RE.test(l.c)) throw new TeamError(404, "conversation_not_found");
40
+ return this.paths.confine(path.join(this.paths.conversationsDir(l.uk, l.t, l.personaKey), `${l.c}.json`));
41
+ }
42
+
43
+ read(l: Locator): ConversationRecord | null {
44
+ try {
45
+ const raw = JSON.parse(fs.readFileSync(this.file(l), "utf8")) as ConversationRecord;
46
+ return raw?.schemaVersion === 1 ? raw : null;
47
+ } catch {
48
+ return null;
49
+ }
50
+ }
51
+
52
+ write(l: Locator, record: ConversationRecord): void {
53
+ atomicWriteJson(this.file(l), record, this.ops);
54
+ this.index.set(record.sessionId, { ...l });
55
+ }
56
+
57
+ delete(l: Locator): void {
58
+ const rec = this.read(l);
59
+ fs.rmSync(this.file(l), { force: true });
60
+ if (rec) this.index.delete(rec.sessionId);
61
+ }
62
+
63
+ /** Records of one user for a target, optionally one persona. */
64
+ // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: many small independent branches (field / state rendering); splitting would scatter one linear flow
65
+ list(uk: string, t: string, personaKey?: string): LocatedRecord[] {
66
+ const out: LocatedRecord[] = [];
67
+ let personaDirs: string[];
68
+ const base = (() => {
69
+ try {
70
+ return this.paths.confine(path.join(this.paths.conversationsRoot(uk), t));
71
+ } catch {
72
+ return null;
73
+ }
74
+ })();
75
+ if (!base) return out;
76
+ if (personaKey) personaDirs = [personaDirName(personaKey)];
77
+ else {
78
+ try {
79
+ personaDirs = fs.readdirSync(base);
80
+ } catch {
81
+ return out;
82
+ }
83
+ }
84
+ for (const d of personaDirs) {
85
+ const pk = personaKeyFromDir(d);
86
+ if (!pk) continue;
87
+ let files: string[];
88
+ try {
89
+ files = fs.readdirSync(path.join(base, d)).filter((f) => f.endsWith(".json"));
90
+ } catch {
91
+ continue;
92
+ }
93
+ for (const f of files) {
94
+ const c = f.slice(0, -5);
95
+ if (!CONVERSATION_ID_RE.test(c)) continue;
96
+ const record = this.read({ uk, t, personaKey: pk, c });
97
+ if (record) out.push({ uk, t, personaKey: pk, c, record });
98
+ }
99
+ }
100
+ return out;
101
+ }
102
+
103
+ /** Every record of every user (startup index + idle sweep). */
104
+ scanAll(): LocatedRecord[] {
105
+ const out: LocatedRecord[] = [];
106
+ const usersDir = path.join(this.paths.home, "users");
107
+ let users: string[];
108
+ try {
109
+ users = fs.readdirSync(usersDir);
110
+ } catch {
111
+ return out;
112
+ }
113
+ for (const uk of users) {
114
+ if (uk !== LOCAL_USER_KEY && !/^[0-9a-f]{32}$/.test(uk)) continue;
115
+ let targets: string[];
116
+ try {
117
+ targets = fs.readdirSync(this.paths.conversationsRoot(uk));
118
+ } catch {
119
+ continue;
120
+ }
121
+ for (const t of targets) out.push(...this.list(uk, t));
122
+ }
123
+ for (const r of out) this.index.set(r.record.sessionId, { uk: r.uk, t: r.t, personaKey: r.personaKey, c: r.c });
124
+ return out;
125
+ }
126
+
127
+ locate(sessionId: string): Locator | undefined {
128
+ return this.index.get(sessionId);
129
+ }
130
+ }
@@ -0,0 +1,50 @@
1
+ /**
2
+ * Persona rendering (D6): persona.md outside every target + project context
3
+ * file collection. See change: add-team-plugin.
4
+ */
5
+ import fs from "node:fs";
6
+ import path from "node:path";
7
+ import { canonicalize, isInside } from "./paths.js";
8
+ import { atomicWriteText } from "./text-write.js";
9
+ import type { Persona } from "./types.js";
10
+
11
+ /** pi's cwd anchor; persona text must not be able to move the bridge's splice point. */
12
+ const ANCHOR = "\nCurrent working directory: ";
13
+ const ZWJ = "\u200d";
14
+ const CONTEXT_FILE_MAX_BYTES = 64 * 1024;
15
+
16
+ function neutraliseAnchor(text: string): string {
17
+ return text.split(ANCHOR).join(`\n${ZWJ}${ANCHOR.slice(1)}`);
18
+ }
19
+
20
+ export function renderPersonaMarkdown(persona: Pick<Persona, "name" | "description" | "role" | "instructions">): string {
21
+ const header = `# ${persona.name}${persona.role === "leader" ? " (leader)" : ""}`;
22
+ const desc = persona.description ? `\n\n${persona.description}` : "";
23
+ return neutraliseAnchor(`${header}${desc}\n\n${persona.instructions}\n`);
24
+ }
25
+
26
+ /** Render to `<runtimeDir>/persona.md` and return its path. */
27
+ export function writePersonaFile(runtimeDir: string, persona: Persona): string {
28
+ const file = path.join(runtimeDir, "persona.md");
29
+ atomicWriteText(file, renderPersonaMarkdown(persona));
30
+ return file;
31
+ }
32
+
33
+ /** Project root `AGENTS.md` / `CLAUDE.md`: regular files resolving inside the root, ≤ 64 KiB. */
34
+ export function collectContextFiles(root: string): string[] {
35
+ const out: string[] = [];
36
+ const realRoot = canonicalize(root);
37
+ for (const name of ["AGENTS.md", "CLAUDE.md"]) {
38
+ const candidate = path.join(realRoot, name);
39
+ try {
40
+ const real = fs.realpathSync(candidate);
41
+ if (!isInside(realRoot, real)) continue;
42
+ const st = fs.statSync(real);
43
+ if (!st.isFile() || st.size > CONTEXT_FILE_MAX_BYTES) continue;
44
+ out.push(real);
45
+ } catch {
46
+ /* absent */
47
+ }
48
+ }
49
+ return out;
50
+ }