Repository navigation
Expand file tree
/
Copy pathprojects.js
More file actions
1809 lines (1673 loc) · 76.6 KB
/
Copy pathprojects.js
File metadata and controls
1809 lines (1673 loc) · 76.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// projects.js — Projects: a piece of work with a folder on disk.
//
// A project owns a root folder under the projects root (default ~/Switchboard),
// attaches zero or more folders (the cwds sessions run in), and files sessions
// under itself or under one of its tracks. The folder on disk carries the
// context: CLAUDE.md / AGENTS.md is the brief every session below it reads,
// plan.md holds the plan in whatever form the agent writes it, plan-tracker.md
// is the fixed-format checklist Switchboard reads for progress, and todos.md
// the follow-ups.
//
// Rows live in their own tables (db.js: projects, project_folders, tracks) and
// the session ↔ project link is session_meta.projectId / trackId. Nothing here
// is keyed on the `project:<path>` settings blob, which is deleted when a folder
// is hidden.
//
// Like session-cache.js this is a singleton initialised with init(ctx) so tests
// can hand it a fake db and a fake session list.
const fs = require('fs');
const os = require('os');
const path = require('path');
const crypto = require('crypto');
const git = require('./git');
const planParser = require('./public/plan-parser');
const sessionConfig = require('./public/session-config');
const DEFAULT_ROOT_NAME = 'Switchboard';
const REPOS_DIR = 'repos';
const ADDED_FILES_DIR = 'added-files';
const BRANCH_NAME_RE = /^(?!-)[A-Za-z0-9._\/-]+$/;
const SLUG_MAX = 60;
const FOLDER_MODES = new Set(['in-place', 'worktree']);
const PROJECT_STATUSES = new Set(['active', 'done']);
// A .env is a few lines; anything larger under that name is something else.
const ENV_FILE_MAX_BYTES = 1024 * 1024;
const ENV_SKIP_DIRS = new Set(['.git', 'node_modules', 'vendor', '.venv', 'venv']);
const scheduleTime = require('./public/schedule-time');
let db, log, buildProjectsFromCache, notifyRendererProjectsChanged, isHarnessId, plansDir;
function init(ctx) {
db = ctx.db;
log = ctx.log || console;
buildProjectsFromCache = ctx.buildProjectsFromCache;
notifyRendererProjectsChanged = ctx.notifyRendererProjectsChanged || (() => {});
// Which CLI ids a track may name. Main passes the harness registry; tests
// and callers that do not care accept anything.
isHarnessId = ctx.isHarnessId || (() => true);
// Where Claude Code keeps plan-mode plans (~/.claude/plans), for adopting one.
plansDir = ctx.plansDir || path.join(os.homedir(), '.claude', 'plans');
// Project templates; tests point this at a temp folder or the bundled one.
templatesDir = ctx.templatesDir || null;
}
// --- Root and slugs ---
function expandHome(p) {
if (p === '~') return os.homedir();
if (p.startsWith('~' + path.sep) || p.startsWith('~/')) return path.join(os.homedir(), p.slice(2));
return p;
}
/** Where new projects are created. A global-only setting, like hiddenProjects. */
function projectsRoot() {
const global = (db.getSetting && db.getSetting('global')) || {};
const configured = typeof global.projectsRoot === 'string' ? global.projectsRoot.trim() : '';
return configured ? path.resolve(expandHome(configured)) : path.join(os.homedir(), DEFAULT_ROOT_NAME);
}
/** Lowercase, runs of non [a-z0-9] become "-", trimmed, at most SLUG_MAX chars. */
function slugify(name) {
let slug = String(name || '')
.toLowerCase()
.replace(/[^a-z0-9]+/g, '-')
.replace(/^-+|-+$/g, '');
if (slug.length > SLUG_MAX) slug = slug.slice(0, SLUG_MAX).replace(/-+$/g, '');
return slug;
}
/** slugify(name), with -2, -3, … appended while a project already uses it. */
function uniqueSlug(name) {
const base = slugify(name) || 'project';
if (!db.getProjectBySlug(base)) return base;
for (let n = 2; ; n++) {
const candidate = `${base}-${n}`;
if (!db.getProjectBySlug(candidate)) return candidate;
}
}
// --- Files written into a new project folder ---
//
// The brief uses absolute paths throughout, because a session may start in an
// attached folder rather than the project folder and "./plan.md" would then
// point at the wrong place.
//
// Everything Switchboard owns — the title, the project folder, the working
// rules and the attached-folder list — sits in one block between markers. It
// is rewritten whole on every sync, so a change to any of it reaches projects
// that already exist. Anything outside the markers is the user's and is never
// touched.
const MANAGED_START = '<!-- switchboard:managed -->';
const MANAGED_END = '<!-- /switchboard:managed -->';
const MANAGED_NOTE = '<!-- Managed by Switchboard: this block is replaced on update. Put your own notes outside it. -->';
const BRIEF_FILES = ['CLAUDE.md', 'AGENTS.md'];
function foldersSection(folderPaths) {
const lines = ['## Attached folders'];
if (!folderPaths.length) {
lines.push('No folders are attached yet. Attach the repos this project works in from the project settings in Switchboard.');
} else {
lines.push("These attached folders are part of the project's working context. Unless the user specifies otherwise, interpret their requests—including questions, explanations, investigations, reviews, planning, and changes—in the context of these folders. Inspect the relevant attached folders to understand the request and ground your response in their contents. The project folder holds shared plans, notes, drafts, and context; it is not the full scope of the work. The first time you work in an attached folder in a session, read its own instructions (CLAUDE.md or AGENTS.md at its root) and follow them there. Once read, they hold for the rest of the session; do not re-read them before each task.");
for (const p of folderPaths) lines.push(`- ${p}`);
}
return lines.join('\n') + '\n';
}
// The plan itself is the agent's to shape (plan.md). What Switchboard reads is
// the tracker (plan-tracker.md), whose format is fixed so progress can be
// parsed. Neither is read at the start of a session; the rules say to open
// them only when the user brings the plan or the todos up. None of these
// files is created up front: the agent makes them when it first needs them.
const PROJECT_FILES = ['plan.md', 'plan-tracker.md', 'todos.md', 'memory.md'];
/** The one block Switchboard owns: title, folder, rules, attached folders. */
function managedBlock(name, root, folderPaths = []) {
return `${MANAGED_START}
${MANAGED_NOTE}
# ${name}
Project folder: ${root}
${briefRules(root)}
${foldersSection(folderPaths)}${MANAGED_END}
`;
}
/**
* A new brief: the managed block, then whatever the template adds below it as
* the user's own text. Without a template the managed block is the whole file.
*/
function defaultBrief(name, root, folderPaths = [], header = null) {
const block = managedBlock(name, root, folderPaths);
return header ? `${block}\n${header}` : block;
}
function briefRules(root) {
const plan = path.join(root, 'plan.md');
const tracker = path.join(root, 'plan-tracker.md');
const todos = path.join(root, 'todos.md');
const memory = path.join(root, 'memory.md');
return `## Working rules
- This folder is the project. Keep plans, notes and drafts here, not in the attached folders.
- When the user asks for a plan, write it to ${plan} in whatever form fits the work.
- Whenever you write or change a plan, also keep ${tracker} up to date: one
"## Phase N: title" heading per phase, each with "- [ ]" checkbox items under it.
Tick an item when it is finished and the heading's own checkbox when the whole
phase is done. Switchboard reads this file to show progress.
- Keep follow-ups and ideas in ${todos} as "- [ ]" checkbox lines. When asked to
add a todo, append it there. Tick a todo when it is done. Work that is already
a phase or an item in the tracker does not belong in the todos as well.
- Anything you want to remember across sessions goes in ${memory}.
- Read ${plan}, ${tracker} or ${todos} only when the user brings up the plan or
the todos. Not at the start of a session, and not again before each task.
What you have already read stays current until you change it.
- These files may not exist yet. Create them when you first need them.
`;
}
function writeIfMissing(filePath, content) {
if (fs.existsSync(filePath)) return false;
fs.writeFileSync(filePath, content, 'utf8');
return true;
}
/** Only the brief is written up front; plan, tracker, todos and memory are the agent's to create. */
function writeProjectFiles(root, name, folderPaths, header = null) {
const brief = defaultBrief(name, root, folderPaths, header);
for (const file of BRIEF_FILES) writeIfMissing(path.join(root, file), brief);
}
// --- Templates ---
//
// A template is a folder under <data dir>/templates/<kind>/ with a
// template.json ({ name, description, tracks }) and the files a new project
// starts with. Three are seeded from the app's own templates/ folder the
// first time the folder is missing; after that they are the user's to edit,
// and a new folder there is a new template with no code change. A template's
// CLAUDE.md is the top of the brief; the working rules and the folder block
// are still appended, so every project keeps the same contract.
const BUNDLED_TEMPLATES_DIR = path.join(__dirname, 'templates');
const TEMPLATE_META = 'template.json';
const TEMPLATE_KIND_RE = /^[a-z0-9][a-z0-9-]*$/;
let templatesDir = null;
function dataDir() {
return process.env.SWITCHBOARD_DATA_DIR ? path.resolve(process.env.SWITCHBOARD_DATA_DIR) : path.join(os.homedir(), '.switchboard');
}
function templatesRoot() {
return templatesDir || path.join(dataDir(), 'templates');
}
/** Copy the bundled templates in when the folder does not exist yet. Never overwrites. */
function seedTemplates() {
const dir = templatesRoot();
if (fs.existsSync(dir)) return false;
if (!fs.existsSync(BUNDLED_TEMPLATES_DIR)) return false;
try {
fs.cpSync(BUNDLED_TEMPLATES_DIR, dir, { recursive: true });
return true;
} catch (err) {
log.error?.(`[projects] could not seed templates into ${dir}`, err);
return false;
}
}
function readTemplate(kind) {
if (typeof kind !== 'string' || !TEMPLATE_KIND_RE.test(kind)) return null;
const dir = path.join(templatesRoot(), kind);
const metaPath = path.join(dir, TEMPLATE_META);
if (!fs.existsSync(metaPath)) return null;
let meta;
try { meta = JSON.parse(fs.readFileSync(metaPath, 'utf8')); } catch { return null; }
const tracks = (Array.isArray(meta.tracks) ? meta.tracks : [])
.map(t => (typeof t === 'string' ? { name: t } : t))
.filter(t => t && typeof t.name === 'string' && t.name.trim())
.map(t => ({ name: t.name.trim(), cli: typeof t.cli === 'string' && t.cli ? t.cli : null }));
return { kind, dir, name: typeof meta.name === 'string' && meta.name.trim() ? meta.name.trim() : kind, description: typeof meta.description === 'string' ? meta.description : '', tracks };
}
function listTemplates() {
seedTemplates();
const dir = templatesRoot();
const templates = [];
if (fs.existsSync(dir)) {
for (const entry of fs.readdirSync(dir, { withFileTypes: true })) {
if (!entry.isDirectory()) continue;
const template = readTemplate(entry.name);
if (template) templates.push({ kind: template.kind, name: template.name, description: template.description, tracks: template.tracks });
}
}
templates.sort((a, b) => a.name.localeCompare(b.name));
return { dir, templates };
}
function renderTemplateText(text, vars) {
return String(text).replace(/\{\{\s*(name|slug|root)\s*\}\}/g, (_m, key) => vars[key] ?? '');
}
/**
* Copy a template's files into a new project folder. Markdown files have
* {{name}}, {{slug}} and {{root}} filled in; template.json and the brief
* files are skipped (the brief is composed separately). Returns the brief
* header from the template's CLAUDE.md, or null.
*/
function applyTemplate(template, root, vars) {
let header = null;
const walk = (from, rel) => {
for (const entry of fs.readdirSync(from, { withFileTypes: true })) {
const childRel = rel ? path.join(rel, entry.name) : entry.name;
const source = path.join(from, entry.name);
if (entry.isDirectory()) {
fs.mkdirSync(path.join(root, childRel), { recursive: true });
walk(source, childRel);
continue;
}
if (!entry.isFile()) continue;
if (!rel && entry.name === TEMPLATE_META) continue;
if (!rel && BRIEF_FILES.includes(entry.name)) {
if (entry.name === 'CLAUDE.md' || (entry.name === 'AGENTS.md' && !header)) {
header = renderTemplateText(fs.readFileSync(source, 'utf8'), vars).trimEnd() + '\n';
}
continue;
}
const dest = path.join(root, childRel);
if (fs.existsSync(dest)) continue;
if (/\.md$/i.test(entry.name)) fs.writeFileSync(dest, renderTemplateText(fs.readFileSync(source, 'utf8'), vars), 'utf8');
else fs.copyFileSync(source, dest);
}
};
walk(template.dir, '');
return header;
}
/**
* Create one of the agent-owned files when the user opens it from the page
* before any session has. Only the four known names, only when missing.
*/
function createProjectFile(projectId, name, content) {
const project = db.getProject(projectId);
if (!project) return { error: 'Project not found' };
if (!PROJECT_FILES.includes(name)) return { error: `Not a project file: ${name}` };
const filePath = path.join(project.root, name);
if (fs.existsSync(filePath)) return { ok: true, filePath, created: false };
const label = name.replace(/\.md$/, '').replace(/-/g, ' ');
const text = typeof content === 'string' ? content : `# ${project.name} ${label}\n\n`;
try { fs.writeFileSync(filePath, text, 'utf8'); } catch (err) { return { error: err.message }; }
return { ok: true, filePath, created: true };
}
/** Files the user has dropped into this project's durable context folder. */
function addedFilesAtRoot(root) {
const dirPath = path.join(root, ADDED_FILES_DIR);
let entries;
try {
if (!fs.lstatSync(dirPath).isDirectory()) return { dirPath, files: [] };
entries = fs.readdirSync(dirPath, { withFileTypes: true });
} catch { entries = []; }
const files = [];
for (const entry of entries) {
if (!entry.isFile()) continue;
const filePath = path.join(dirPath, entry.name);
let stat;
try { stat = fs.lstatSync(filePath); } catch { continue; }
files.push({
name: entry.name,
relativePath: path.join(ADDED_FILES_DIR, entry.name),
type: 'file',
size: stat.size,
modified: stat.mtime.toISOString(),
});
}
files.sort((a, b) => a.name.localeCompare(b.name, undefined, { numeric: true, sensitivity: 'base' }));
return { dirPath, files };
}
// Bounds for the Overview's Recent Files walk, so a project folder that
// collects something huge cannot stall the page.
const RECENT_FILES_MAX_DEPTH = 6;
const RECENT_FILES_MAX_ENTRIES = 5000;
/**
* The newest files in the project folder, by when each was created, so a plan
* edited every hour does not crowd out a file added today. Skips the briefs
* every project starts with, attached repositories under repos/, hidden
* entries and dependency folders. Symlinks are not followed.
*/
function listRecentProjectFiles(projectId, limit = 5) {
const project = db.getProject(projectId);
if (!project) return { error: 'Project not found' };
const count = Math.max(1, Math.min(50, Number(limit) || 5));
const root = project.root;
const found = [];
let visited = 0;
const walk = (rel, depth) => {
let entries;
try { entries = fs.readdirSync(path.join(root, rel), { withFileTypes: true }); } catch { return; }
for (const entry of entries) {
if (++visited > RECENT_FILES_MAX_ENTRIES) return;
if (entry.name.startsWith('.')) continue;
const childRel = rel ? path.join(rel, entry.name) : entry.name;
if (entry.isDirectory()) {
if ((!rel && entry.name === REPOS_DIR) || ENV_SKIP_DIRS.has(entry.name) || depth >= RECENT_FILES_MAX_DEPTH) continue;
walk(childRel, depth + 1);
} else if (entry.isFile() && !(!rel && BRIEF_FILES.includes(entry.name))) {
let stat;
try { stat = fs.lstatSync(path.join(root, childRel)); } catch { continue; }
// Filesystems that do not record creation time report 0; use mtime there.
const addedMs = stat.birthtimeMs > 0 ? stat.birthtimeMs : stat.mtimeMs;
found.push({ name: entry.name, relativePath: childRel, added: new Date(addedMs).toISOString(), size: stat.size, addedMs });
}
}
};
walk('', 0);
found.sort((a, b) => b.addedMs - a.addedMs || a.relativePath.localeCompare(b.relativePath));
return { ok: true, files: found.slice(0, count).map(({ addedMs, ...file }) => file) };
}
function listAddedFiles(projectId) {
const project = db.getProject(projectId);
if (!project) return { error: 'Project not found' };
return { ok: true, ...addedFilesAtRoot(project.root) };
}
/** Pick a non-destructive destination such as "brief (2).pdf" on collisions. */
function uniqueAddedFilePath(dirPath, name) {
const first = path.join(dirPath, name);
if (!fs.existsSync(first)) return first;
const ext = path.extname(name);
const stem = name.slice(0, name.length - ext.length);
for (let n = 2; ; n++) {
const candidate = path.join(dirPath, `${stem} (${n})${ext}`);
if (!fs.existsSync(candidate)) return candidate;
}
}
/**
* Copy dropped files into <project>/added-files without overwriting anything.
* Source paths come from Electron's webUtils.getPathForFile; main still
* validates every one before touching the project folder.
*/
async function addProjectFiles(projectId, sourcePaths) {
const project = db.getProject(projectId);
if (!project) return { error: 'Project not found' };
if (!Array.isArray(sourcePaths) || !sourcePaths.length) return { error: 'No files were dropped' };
const dirPath = path.join(project.root, ADDED_FILES_DIR);
const added = [];
const errors = [];
const seen = new Set();
for (const raw of sourcePaths) {
const source = typeof raw === 'string' && path.isAbsolute(raw) ? path.resolve(raw) : '';
if (!source) {
errors.push(`${path.basename(String(raw || 'File')) || 'File'}: Source path must be absolute`);
continue;
}
if (seen.has(source)) continue;
seen.add(source);
const label = path.basename(source) || String(raw || 'File');
try {
const stat = await fs.promises.lstat(source);
if (!stat.isFile()) throw new Error('Only files can be added');
await fs.promises.mkdir(dirPath, { recursive: true });
const dirStat = await fs.promises.lstat(dirPath);
if (!dirStat.isDirectory()) throw new Error(`${ADDED_FILES_DIR} must be a regular folder`);
const [rootReal, dirReal] = await Promise.all([
fs.promises.realpath(project.root),
fs.promises.realpath(dirPath),
]);
if (path.dirname(dirReal) !== rootReal) throw new Error(`${ADDED_FILES_DIR} must be inside the project folder`);
const destination = uniqueAddedFilePath(dirPath, label);
await fs.promises.copyFile(source, destination, fs.constants.COPYFILE_EXCL);
added.push(path.basename(destination));
} catch (err) {
errors.push(`${label}: ${err.message}`);
}
}
if (added.length) notifyRendererProjectsChanged();
return { ok: true, ...addedFilesAtRoot(project.root), added, errors };
}
/**
* Replace the managed block in one brief file. When the markers are missing —
* the user deleted them — the block goes back at the top, where a new brief
* puts it, and the user's own text stays below.
*/
function syncBriefFile(filePath, block) {
if (!fs.existsSync(filePath)) return false;
const text = fs.readFileSync(filePath, 'utf8');
// Remove every complete block, not just the first. Do not let an unclosed
// legacy header consume a later block (or the user's notes between them).
let inserted = false;
const replacement = () => {
if (inserted) return '';
inserted = true;
return block.trimEnd() + '\n';
};
let next = text.replace(/<!-- switchboard:managed -->(?:(?!<!-- switchboard:managed -->)[\s\S])*?<!-- \/switchboard:managed -->\r?\n?/g, replacement);
// Older briefs left the outer managed marker open and owned only this
// header plus individually delimited rules/folders sections. Keep any text
// outside those sections, including notes after the final folders marker.
next = next.replace(/<!-- switchboard:managed -->\r?\n<!-- Managed by Switchboard: this block is replaced on update\. Put your own notes outside it\. -->\r?\n# [^\r\n]*\r?\nProject folder: [^\r\n]*\r?\n\s*(?=<!-- switchboard:rules -->)/g, replacement);
next = next.replace(/<!-- switchboard:(rules|folders) -->[\s\S]*?<!-- \/switchboard:\1 -->\r?\n?/g, '');
if (!inserted) next = block.trimEnd() + '\n\n' + next.trimStart();
if (next !== text) fs.writeFileSync(filePath, next, 'utf8');
return true;
}
/**
* Keep the managed block in CLAUDE.md and AGENTS.md current — the title, the
* project folder, the working rules and the attached-folder list. Generated
* instructions belong only in the project root, never in attached repos.
*/
async function syncProjectBrief(projectId) {
const project = db.getProject(projectId);
if (!project) return;
const folders = db.listProjectFolders(projectId);
const block = managedBlock(project.name, project.root, folders.map(f => f.path));
for (const file of BRIEF_FILES) {
try { syncBriefFile(path.join(project.root, file), block); } catch (err) {
log.error?.(`[projects] could not update ${file} in ${project.root}`, err);
}
}
}
/**
* Bring every project's brief up to date at startup, so a Switchboard upgrade
* that changes the working rules reaches projects that already exist. Each
* file is only written when its text actually changed, so this is normally a
* no-op.
*/
async function syncAllProjectBriefs() {
let projectList = [];
try { projectList = db.listProjects() || []; } catch (err) {
log.error?.('[projects] could not list projects to sync briefs', err);
return;
}
for (const project of projectList) {
try { await syncProjectBrief(project.id); } catch (err) {
log.error?.(`[projects] could not sync the brief for ${project.name}`, err);
}
}
}
/**
* Save the brief from the project page. CLAUDE.md and AGENTS.md always carry
* the same text in the project root. The managed folder block is re-synced, which
* puts it back if the user deleted it. Returns the text as written.
*/
async function saveBrief(projectId, content) {
const project = db.getProject(projectId);
if (!project) return { error: 'Project not found' };
if (typeof content !== 'string') return { error: 'Brief must be text' };
const text = content.endsWith('\n') || content === '' ? content : content + '\n';
try {
for (const file of BRIEF_FILES) fs.writeFileSync(path.join(project.root, file), text, 'utf8');
} catch (err) {
return { error: `Could not write the brief: ${err.message}` };
}
await syncProjectBrief(projectId);
const saved = fs.readFileSync(path.join(project.root, 'CLAUDE.md'), 'utf8');
return { ok: true, content: saved };
}
// --- Validation helpers ---
function isDirectory(p) {
try { return fs.statSync(p).isDirectory(); } catch { return false; }
}
function normalizeFolderSpec(spec) {
if (!spec || typeof spec !== 'object') return { error: 'Folder must be an object' };
const folderPath = typeof spec.path === 'string' ? spec.path.trim() : '';
if (!folderPath || !path.isAbsolute(folderPath)) return { error: 'Folder path must be absolute' };
if (!isDirectory(folderPath)) return { error: `Not a directory: ${folderPath}` };
const mode = spec.mode || 'in-place';
if (!FOLDER_MODES.has(mode)) return { error: `Unknown folder mode: ${mode}` };
// Only a worktree needs .env copied; an in-place folder already has its own.
const copyEnv = mode === 'worktree' && Array.isArray(spec.copyEnv)
? spec.copyEnv.filter(name => typeof name === 'string')
: [];
return { path: path.resolve(folderPath), mode, branch: typeof spec.branch === 'string' ? spec.branch.trim() : '', copyEnv };
}
// realpath of the longest existing ancestor, with the rest joined back on.
// A session cwd may be a directory that no longer exists (a removed worktree),
// and on macOS /var is a symlink to /private/var, so comparing a resolved
// path against a realpath'd root would miss.
function realOrResolved(p) {
const resolved = path.resolve(p);
let current = resolved;
const tail = [];
for (;;) {
try { return path.join(fs.realpathSync(current), ...tail); } catch {}
const parent = path.dirname(current);
if (parent === current) return resolved;
tail.unshift(path.basename(current));
current = parent;
}
}
function isInside(child, parent) {
if (child === parent) return true;
return child.startsWith(parent.endsWith(path.sep) ? parent : parent + path.sep);
}
// --- Tree node shape handed to the renderer ---
function trackNode(row) {
return {
id: row.id, projectId: row.projectId, name: row.name,
cwd: row.cwd || null, cli: row.cli || null, status: row.status || 'active',
sortOrder: row.sortOrder || 0, created: row.created,
sessions: [],
};
}
/** A schedule row as the renderer sees it: booleans, nulls, and nothing it cannot use. */
function scheduleNode(row) {
return {
id: row.id, name: row.name,
projectId: row.projectId || null, trackId: row.trackId || null, cwd: row.cwd || null,
prompt: row.prompt,
every: row.every, atHour: row.atHour ?? null, atMinute: row.atMinute ?? null,
weekday: row.weekday ?? null, cron: row.cron || null,
cli: row.cli || null, enabled: !!row.enabled, catchUp: !!row.catchUp,
sessionConfig: row.sessionConfig || {},
sourceFile: row.sourceFile || null,
lastRunAt: row.lastRunAt || null, lastSessionId: row.lastSessionId || null,
created: row.created,
};
}
function projectNode(row, folderRows = [], trackRows = [], scheduleRows = []) {
const added = addedFilesAtRoot(row.root);
return {
id: row.id, name: row.name, slug: row.slug, root: row.root,
status: row.status || 'active',
sharedBranch: row.sharedBranch === undefined ? true : !!row.sharedBranch,
branchName: row.branchName || null,
defaultCwd: row.defaultCwd || null,
snoozedUntil: row.snoozedUntil || null,
snoozedAt: row.snoozedAt || null,
created: row.created, modified: row.modified,
lastActivity: null, sessionCount: 0,
addedFilesPath: added.dirPath,
addedFiles: added.files,
folders: folderRows.map(f => ({
path: f.path, mode: f.mode || 'in-place', sourcePath: f.sourcePath || null,
branch: f.branch || null, sortOrder: f.sortOrder || 0,
})),
tracks: trackRows.map(trackNode),
schedules: scheduleRows.map(scheduleNode),
sessions: [],
};
}
function loadProjectNode(id) {
const row = db.getProject(id);
if (!row) return null;
return projectNode(row, db.listProjectFolders(id), db.listTracks(id), db.listSchedulesByProject(id));
}
// --- Create / update / delete ---
async function createProject(spec) {
const name = typeof spec?.name === 'string' ? spec.name.trim() : '';
if (!name) return { error: 'Project name is required' };
const folders = [];
for (const raw of (Array.isArray(spec.folders) ? spec.folders : [])) {
const normalized = normalizeFolderSpec(raw);
if (normalized.error) return { error: normalized.error };
if (folders.some(f => f.path === normalized.path)) continue;
folders.push(normalized);
}
const branchName = typeof spec.branchName === 'string' && spec.branchName.trim() ? spec.branchName.trim() : null;
if (branchName && !BRANCH_NAME_RE.test(branchName)) return { error: `Invalid branch name: ${branchName}` };
let template = null;
if (spec.template) {
template = readTemplate(spec.template);
if (!template) return { error: `Unknown template: ${spec.template}` };
}
const slug = uniqueSlug(name);
const rootDir = projectsRoot();
const root = path.join(rootDir, slug);
if (fs.existsSync(root)) {
return { error: `A folder named "${slug}" already exists in ${rootDir}` };
}
// In-place folders are listed in the brief right away; worktree folders
// are added after the row exists, since their path is only known once the
// checkout is made.
const inPlace = folders.filter(f => f.mode === 'in-place');
try {
fs.mkdirSync(root, { recursive: true });
const header = template ? applyTemplate(template, root, { name, slug, root }) : null;
writeProjectFiles(root, name, inPlace.map(f => f.path), header);
} catch (err) {
return { error: `Could not create ${root}: ${err.message}` };
}
const now = new Date().toISOString();
const row = {
id: crypto.randomUUID(), name, slug, root,
status: 'active',
sharedBranch: spec.sharedBranch === undefined ? true : !!spec.sharedBranch,
branchName,
created: now, modified: now,
};
db.insertProject(row);
inPlace.forEach((f, i) => db.upsertProjectFolder({ projectId: row.id, path: f.path, mode: 'in-place', sortOrder: i }));
// A template's tracks start in the project folder and inherit the default CLI
// unless the template names one.
if (template) {
template.tracks.forEach((t, i) => db.insertTrack({
id: crypto.randomUUID(), projectId: row.id, name: t.name, cwd: null,
cli: t.cli && isHarnessId(t.cli) ? t.cli : null, status: 'active', sortOrder: i, created: now,
}));
}
const errors = [];
for (const f of folders.filter(f => f.mode === 'worktree')) {
const result = await attachWorktree(db.getProject(row.id), { path: f.path, branch: f.branch, copyEnv: f.copyEnv }, { notify: false });
if (result.error) errors.push(`${f.path}: ${result.error}`);
}
log.info?.(`[projects] created "${name}" at ${root}`);
refreshPlanWatchers();
notifyRendererProjectsChanged();
return { ok: true, project: loadProjectNode(row.id), errors };
}
function updateProject(id, patch) {
const row = db.getProject(id);
if (!row) return { error: 'Project not found' };
const clean = {};
if (typeof patch?.name === 'string') {
const name = patch.name.trim();
if (!name) return { error: 'Project name is required' };
clean.name = name;
}
if (patch?.status !== undefined) {
if (!PROJECT_STATUSES.has(patch.status)) return { error: `Unknown status: ${patch.status}` };
clean.status = patch.status;
}
if (patch?.sharedBranch !== undefined) clean.sharedBranch = !!patch.sharedBranch;
if (patch?.branchName !== undefined) {
clean.branchName = typeof patch.branchName === 'string' && patch.branchName.trim() ? patch.branchName.trim() : null;
}
if (patch?.defaultCwd !== undefined) {
const cwd = normalizeCwdWithinProject(row, patch.defaultCwd);
if (cwd.error) return { error: cwd.error };
clean.defaultCwd = cwd.cwd;
}
if (patch?.snoozedUntil !== undefined) {
const snooze = normalizeSnooze(row, patch.snoozedUntil, clean.status || row.status);
if (snooze.error) return { error: snooze.error };
Object.assign(clean, snooze);
} else if (clean.status === 'done' && row.snoozedUntil) {
// Finishing a project ends its snooze; Done is not a place to wake up into.
clean.snoozedUntil = null;
clean.snoozedAt = null;
}
if (!Object.keys(clean).length) return { ok: true, project: loadProjectNode(id) };
clean.modified = new Date().toISOString();
db.updateProject(id, clean);
// The brief's title comes from the project name, so a rename rewrites it.
if (clean.name) syncProjectBrief(id).catch(err => log.error?.('[projects] could not retitle the brief', err));
notifyRendererProjectsChanged();
return { ok: true, project: loadProjectNode(id) };
}
/**
* A snooze is a wake time in the future, or null to wake now. Snoozing again
* to the same instant keeps the original snoozedAt, so a repeated click does
* not churn the row. Only visibility changes: sessions keep running.
*/
function normalizeSnooze(row, value, status) {
if (value === null || value === '') return { snoozedUntil: null, snoozedAt: null };
if (typeof value !== 'string') return { error: 'Wake time must be an ISO date' };
const wake = Date.parse(value);
if (!Number.isFinite(wake)) return { error: 'Wake time must be an ISO date' };
if (wake <= Date.now()) return { error: 'Wake time must be in the future' };
if (status === 'done') return { error: 'A finished project cannot be snoozed' };
const iso = new Date(wake).toISOString();
const sameWake = row.snoozedUntil && Date.parse(row.snoozedUntil) === wake && row.snoozedAt;
return { snoozedUntil: iso, snoozedAt: sameWake ? row.snoozedAt : new Date().toISOString() };
}
/** Rows only. The folder on disk and every session stay. */
function deleteProject(id) {
const row = db.getProject(id);
if (!row) return { error: 'Project not found' };
db.deleteProject(id);
log.info?.(`[projects] removed "${row.name}" (folder kept at ${row.root})`);
refreshPlanWatchers();
notifyRendererProjectsChanged();
return { ok: true, root: row.root };
}
async function attachFolder(id, spec) {
const row = db.getProject(id);
if (!row) return { error: 'Project not found' };
const normalized = normalizeFolderSpec(spec);
if (normalized.error) return { error: normalized.error };
if (normalized.mode === 'worktree') return attachWorktree(row, normalized);
const existing = db.listProjectFolders(id);
if (existing.some(f => f.path === normalized.path)) return { ok: true, project: loadProjectNode(id) };
const sortOrder = existing.reduce((max, f) => Math.max(max, f.sortOrder || 0), -1) + 1;
db.upsertProjectFolder({ projectId: id, path: normalized.path, mode: 'in-place', sortOrder });
db.updateProject(id, { modified: new Date().toISOString() });
await syncProjectBrief(id);
notifyRendererProjectsChanged();
return { ok: true, project: loadProjectNode(id) };
}
// --- .env files ---
//
// git worktree add checks out tracked files only, so a repository's .env stays
// behind in the source checkout and the new worktree cannot run the app. The
// new project dialog lists what it found and the user picks; nothing is copied
// unless a name was asked for.
/** A sample file is listed but never picked by default: it is usually tracked already. */
function isEnvSample(name) {
return /^\.env\.(example|sample|template|dist)$/i.test(path.basename(name));
}
/**
* The .env files recursively within a folder: `.env` and `.env.*`, sorted, files
* only, as relative paths. Hidden directories, dependency folders and symlinks are skipped.
* Big files are left out — a .env is a few lines, and anything large
* under that name is something else.
*/
function listEnvFiles(dir) {
const root = typeof dir === 'string' ? path.resolve(dir.trim()) : '';
if (!root || !isDirectory(root)) return [];
const names = [];
const pending = [''];
while (pending.length) {
const relativeDir = pending.pop();
let entries;
try { entries = fs.readdirSync(path.join(root, relativeDir), { withFileTypes: true }); } catch { continue; }
for (const entry of entries) {
const relativePath = path.join(relativeDir, entry.name);
if (entry.isDirectory()) {
if (!entry.name.startsWith('.') && !ENV_SKIP_DIRS.has(entry.name)) pending.push(relativePath);
continue;
}
// Do not follow symlinks, including links to directories outside the repo.
if (!entry.isFile()) continue;
if (entry.name !== '.env' && !entry.name.startsWith('.env.')) continue;
try { if (fs.statSync(path.join(root, relativePath)).size > ENV_FILE_MAX_BYTES) continue; } catch { continue; }
names.push(relativePath);
}
}
names.sort();
return names;
}
/** The names the dialog ticks for the user: everything but the samples. */
function defaultEnvSelection(dir) {
return listEnvFiles(dir).filter(name => !isEnvSample(name));
}
/**
* Copy the named .env files from one folder to another. A name the source
* does not actually have is ignored, so the renderer can never name a path of
* its own, and an existing destination is never overwritten.
*/
function copyEnvFiles(source, target, names) {
const wanted = Array.isArray(names) ? names : [];
if (!wanted.length) return { copied: [], skipped: [] };
const available = new Set(listEnvFiles(source));
const copied = [];
const skipped = [];
for (const name of wanted) {
if (!available.has(name)) { skipped.push(name); continue; }
const dest = path.join(target, name);
if (fs.existsSync(dest)) { skipped.push(name); continue; }
try {
// Create missing parents, but never copy through a destination symlink.
let parent = target;
for (const part of name.split(path.sep).slice(0, -1)) {
parent = path.join(parent, part);
try { fs.mkdirSync(parent); } catch (err) { if (err.code !== 'EEXIST') throw err; }
const stat = fs.lstatSync(parent);
if (!stat.isDirectory() || stat.isSymbolicLink()) throw new Error('Unsafe destination directory');
}
fs.copyFileSync(path.join(source, name), dest, fs.constants.COPYFILE_EXCL);
fs.chmodSync(dest, fs.statSync(path.join(source, name)).mode & 0o777);
copied.push(name);
} catch (err) {
log.error?.(`[projects] could not copy ${name} into ${target}`, err);
skipped.push(name);
}
}
return { copied, skipped };
}
/** The branch a project's worktrees use: one shared name, or per folder. */
function worktreeBranchFor(project, requested) {
if (project.sharedBranch === undefined || project.sharedBranch) return project.branchName || project.slug;
return (typeof requested === 'string' && requested.trim()) ? requested.trim() : project.slug;
}
/**
* Check a repository out under <project>/repos/<name> on the project's branch
* and attach that checkout. Git creates the branch and worktree registration;
* Switchboard writes no instruction files or ignore rules in the repository.
*/
async function attachWorktree(project, spec, { notify = true } = {}) {
const source = typeof spec?.path === 'string' ? path.resolve(spec.path.trim()) : '';
if (!source || !isDirectory(source)) return { error: `Not a directory: ${source || spec?.path}` };
let top;
try { top = await git.repoRoot(source); } catch { return { error: `${source} is not inside a git repository` }; }
if (realOrResolved(top) !== realOrResolved(source)) {
return { error: `${source} is not the root of a git repository (${top} is)` };
}
const branch = worktreeBranchFor(project, spec.branch);
if (!BRANCH_NAME_RE.test(branch)) return { error: `Invalid branch name: ${branch}` };
const existing = db.listProjectFolders(project.id);
if (existing.some(f => f.sourcePath === source)) return { error: 'That repository is already attached on a branch' };
const target = path.join(project.root, REPOS_DIR, path.basename(source));
if (fs.existsSync(target)) return { error: `${target} already exists` };
if (existing.some(f => f.path === target)) return { error: 'That folder is already attached' };
try {
fs.mkdirSync(path.join(project.root, REPOS_DIR), { recursive: true });
await git.worktreeAdd(source, target, branch);
} catch (err) {
return { error: `git worktree add failed: ${err.message}` };
}
// The checkout has tracked files only. Bring the .env files the user picked
// across so a session in the worktree can run the app. Never fatal: the
// worktree is attached either way.
const env = copyEnvFiles(source, target, spec.copyEnv);
if (env.copied.length) log.info?.(`[projects] copied ${env.copied.join(', ')} into ${target}`);
const sortOrder = existing.reduce((max, f) => Math.max(max, f.sortOrder || 0), -1) + 1;
db.upsertProjectFolder({ projectId: project.id, path: target, mode: 'worktree', sourcePath: source, branch, sortOrder });
db.updateProject(project.id, { modified: new Date().toISOString() });
await syncProjectBrief(project.id);
log.info?.(`[projects] worktree ${target} on ${branch} from ${source}`);
if (notify) notifyRendererProjectsChanged();
return { ok: true, project: loadProjectNode(project.id), folder: { path: target, mode: 'worktree', sourcePath: source, branch }, copiedEnv: env.copied };
}
/**
* Detach a folder. For a worktree folder, removeWorktree also deletes the
* checkout (never the branch); a dirty checkout is refused with dirty: true
* unless force is set, so the caller can ask before losing changes.
*/
async function detachFolder(id, folderPath, opts = {}) {
const row = db.getProject(id);
if (!row) return { error: 'Project not found' };
const folder = db.listProjectFolders(id).find(f => f.path === folderPath) || null;
let worktreeRemoved = false;
if (folder?.mode === 'worktree') {
if (opts.removeWorktree && fs.existsSync(folder.path)) {
try {
await git.worktreeRemove(folder.sourcePath, folder.path, { force: !!opts.force });
worktreeRemoved = true;
} catch (err) {
return { error: `Could not remove the worktree: ${err.message}`, dirty: git.isDirtyWorktreeError(err) };
}
}
}
db.deleteProjectFolder(id, folderPath);
// A default or track cwd that pointed into the detached folder falls back
// to the project folder rather than a place the project no longer works in.
if (row.defaultCwd && isInside(realOrResolved(row.defaultCwd), realOrResolved(folderPath))) {
db.updateProject(id, { defaultCwd: null });
}
for (const track of db.listTracks(id)) {
if (track.cwd && isInside(realOrResolved(track.cwd), realOrResolved(folderPath))) db.updateTrack(track.id, { cwd: null });
}
db.updateProject(id, { modified: new Date().toISOString() });
await syncProjectBrief(id);
notifyRendererProjectsChanged();
return { ok: true, project: loadProjectNode(id), worktreeRemoved };
}
/** Source repository of a project worktree folder, for task inheritance. */
function worktreeParentFor(folderPath) {
if (!folderPath) return null;
const folder = db.listAllProjectFolders().find(f => f.mode === 'worktree' && f.path === folderPath);
return folder?.sourcePath || null;
}
// --- Launch context ---
/**
* Extra directories for a session that belongs to a project: the project
* folder and every attached folder, except the cwd itself and anything
* already under it. A parent of the cwd (the project folder above a worktree,
* a repo above a track that starts in one of its subfolders) is added too:
* the CLI only edits under the cwd unless told otherwise, and the plan and
* todos live in the project folder. Claude loads CLAUDE.md from added
* directories when CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD is set, so a
* session started in a repo still gets the brief and a session started in the
* project folder sees each repo's instructions.
*/
function launchContext(projectId, cwd) {
const project = db.getProject(projectId);
if (!project) return null;
const real = realOrResolved(cwd || project.root);
const folders = db.listProjectFolders(projectId);
const candidates = [project.root, ...folders.map(f => f.path)];
const addDirs = [];
for (const p of candidates) {
const realP = realOrResolved(p);
if (realP === real || isInside(realP, real)) continue;
if (!addDirs.includes(p)) addDirs.push(p);
}
// Starting inside a project worktree: the caller must not ask the CLI for
// another worktree on top of it.
const worktree = folders.some(f => f.mode === 'worktree' && isInside(real, realOrResolved(f.path)));
return {
addDirs,
env: addDirs.length ? { CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD: '1' } : {},
worktree,
};
}
/** addDirs travels as a comma-separated string (see harnesses buildLaunchArgs). */
function mergeAddDirs(existing, extra) {
const list = String(existing || '').split(',').map(s => s.trim()).filter(Boolean);
for (const dir of extra || []) if (!list.includes(dir)) list.push(dir);
return list.join(',');
}
// --- Tracks ---
/**
* Where sessions start, for a project's default or a track. It has to be the
* project folder, an attached folder, or somewhere inside one of them; null
* means "not set" (the project folder, or for a track the project's default).
* Returns { cwd } or { error }.
*/
function normalizeCwdWithinProject(project, cwd) {
if (cwd === undefined || cwd === null || cwd === '') return { cwd: null };
if (typeof cwd !== 'string' || !path.isAbsolute(cwd)) return { error: 'Folder must be an absolute path' };
const resolved = path.resolve(cwd);