-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathmain.js
More file actions
2302 lines (2188 loc) · 96.3 KB
/
Copy pathmain.js
File metadata and controls
2302 lines (2188 loc) · 96.3 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
const { app, BrowserWindow, Menu, clipboard, dialog, ipcMain, nativeTheme, safeStorage, screen, shell } = require("electron");
const path = require("node:path");
const fs = require("node:fs");
const os = require("node:os");
const crypto = require("node:crypto");
const swfNode = require("./swf-node");
const swarm = require("./swarm-node");
const easelNdi = require("./easel-ndi");
const matrix = require("./matrix");
// Daybook (apps→daybook): registering this module wires every `daybook:*`
// ipcMain handler (digest pipeline, scope/redaction, onboarding). Side-effect
// require, mirroring the prefs/swarm/easel handlers below. See daybook-main.js.
require("./daybook-main");
// Headless launch self-test. `--smoke-test` (or SROS_SMOKE_TEST=1) boots
// the renderer in a hidden window, waits for boot.js to signal ready, and
// exits 0/1. CI runs this against the *packaged* binary (see
// scripts/after-pack-verify.cjs) to catch runtime boot failures — e.g. a
// renderer module that throws at import time — which static asar analysis
// can't see and which dev mode (runs from source) can't reproduce.
const SMOKE_TEST = process.argv.includes("--smoke-test") || process.env.SROS_SMOKE_TEST === "1";
function configureSmokeUserData() {
if (!SMOKE_TEST) return;
const dir = fs.mkdtempSync(path.join(os.tmpdir(), "shape-rotator-os-smoke-"));
app.setPath("userData", dir);
process.stderr.write(`[smoke] userData=${dir}\n`);
}
// Custom URL scheme for shareable deep-links (sros://xxxxx). See the deep-link
// block just above app.whenReady() and apps/os/src/renderer/share-link.js.
const DEEPLINK_SCHEME = "sros";
function runSmokeTest() {
const TIMEOUT_MS = Number(process.env.SROS_SMOKE_TIMEOUT_MS) || 45000;
const log = (m) => process.stdout.write(`[smoke] ${m}\n`);
let settled = false;
const finish = (code, why) => {
if (settled) return;
settled = true;
clearTimeout(timer);
log(code === 0 ? `PASS: ${why}` : `FAIL: ${why}`);
app.exit(code);
};
const timer = setTimeout(
() => finish(1, `renderer did not signal ready within ${TIMEOUT_MS}ms`),
TIMEOUT_MS
);
log(`booting renderer headless (timeout ${TIMEOUT_MS}ms)…`);
const win = new BrowserWindow({
width: 1280, height: 800, show: false,
webPreferences: {
preload: path.join(__dirname, "preload.js"),
contextIsolation: true, sandbox: false, nodeIntegration: false,
},
});
win.webContents.on("console-message", (_e, a, b) => {
// Electron 33 emits (event, MessageDetails{level:number, message}); older
// builds emit (event, level:number, message, …). Handle BOTH — the old
// handler read the details OBJECT as `lvl`, so `lvl >= 2` was always false
// and NO renderer output (errors, warnings, [smoke-cp] checkpoints) was ever
// surfaced. That blindness is why a boot hang showed only the bare timeout.
let lvl, msg;
if (a && typeof a === "object") { lvl = a.level; msg = a.message; }
else { lvl = a; msg = b; }
if (lvl >= 2) log(`renderer: ${msg}`); // surface warnings, errors + [smoke-cp]
});
win.webContents.on("did-fail-load", (_e, ec, desc, url) =>
finish(1, `did-fail-load ${ec} ${desc} ${url}`));
win.webContents.on("render-process-gone", (_e, d) =>
finish(1, `render-process-gone: ${d && d.reason}`));
win.webContents.on("preload-error", (_e, p, err) =>
finish(1, `preload-error ${p}: ${err && err.message}`));
// Boot breadcrumbs from preload/boot.js over IPC — reliable on headless CI
// where renderer console-message capture is not. The last one logged before
// the timeout pinpoints the blocking phase.
ipcMain.on("smoke:trace", (_e, label) => log(`cp:${label}`));
ipcMain.once("smoke:ready", () => finish(0, "renderer signalled ready"));
// ?smoke=1 lets boot.js emit [smoke-cp] checkpoint markers (surfaced above via
// console-message) so a headless-CI boot hang reports HOW FAR boot() got.
win.loadFile(path.join(__dirname, "src", "index.html"), { query: { smoke: "1" } });
}
// One-time userData migration. Electron resolves `app.getPath("userData")`
// from `productName` (or, if unset, the package name). Every time we
// rename the app — `srwk-wall` → `srwk-visualizer` → `Shape Rotator` →
// `Shape Rotator OS` — the userData path changes and a fresh
// launch finds no saved state. This walks the historical names and
// copies any prior contents into the current dir.
//
// We migrate files (not the directory itself) so any pre-existing
// new-path entries win, and we never *delete* the old paths — leaving
// them intact lets users roll back to an older build without losing data.
//
// To add a future rename: prepend the old name to `legacyNames` below.
function migrateLegacyUserData() {
try {
const newDir = app.getPath("userData");
const parent = path.dirname(newDir);
// Earlier names this app ever used for its userData folder, in
// descending recency order. The first one that exists wins.
const legacyNames = ["Shape Rotator", "srwk-visualizer", "srwk-wall"];
let chosen = null;
for (const n of legacyNames) {
const candidate = path.join(parent, n);
if (candidate === newDir) continue; // already running under that name
if (fs.existsSync(candidate) && fs.statSync(candidate).isDirectory()) {
chosen = candidate; break;
}
}
if (!chosen) return;
fs.mkdirSync(newDir, { recursive: true });
const copyTree = (src, dst) => {
for (const entry of fs.readdirSync(src, { withFileTypes: true })) {
const s = path.join(src, entry.name);
const d = path.join(dst, entry.name);
if (entry.isDirectory()) {
fs.mkdirSync(d, { recursive: true });
copyTree(s, d);
} else if (entry.isFile()) {
if (fs.existsSync(d)) continue; // don't clobber newer state
try { fs.copyFileSync(s, d); } catch {}
}
}
};
copyTree(chosen, newDir);
process.stderr.write(`[viz:log] migrated userData from ${chosen} → ${newDir}\n`);
} catch (e) {
process.stderr.write(`[viz:warn] userData migration failed: ${e && e.message}\n`);
}
}
configureSmokeUserData();
migrateLegacyUserData();
const STATE_DIR = app.getPath("userData");
const WINDOW_STATE = path.join(STATE_DIR, "window_state.json");
const PREFS_FILE = path.join(STATE_DIR, "viz_prefs.json");
const LEGACY_PREFS_FILE = path.join(STATE_DIR, "wall_prefs.json");
const CONTEXT_VAULT_DIR = path.join(STATE_DIR, "context-vault");
const CONTEXT_VAULT_MANIFEST = path.join(CONTEXT_VAULT_DIR, "manifest.json");
const CONTEXT_VAULT_ARTICLE_INDEX = path.join(CONTEXT_VAULT_DIR, "shape-rotator-article-index.md");
const CONTEXT_VAULT_RAW_BUNDLE = path.join(CONTEXT_VAULT_DIR, "shape-rotator-transcripts.md");
const CONTEXT_VAULT_CORPUS = CONTEXT_VAULT_ARTICLE_INDEX;
const REPO_COHORT_ARTICLES_DIR = path.resolve(__dirname, "..", "..", "cohort-data", "articles");
const PACKAGED_COHORT_ARTICLES_DIR = process.resourcesPath
? path.join(process.resourcesPath, "cohort-data", "articles")
: null;
// Cohort key (role=cohort_app Supabase JWT) for the GATED T2 evidence read.
// Baked into the packaged app at build time by the beforePack hook
// (Resources/cohort-app-key.json, written from the SRFG_COHORT_KEY build env).
// In dev (unpackaged) there is no resource file, so fall back to the env var.
// Empty => no cohort read; the renderer falls back to the public anon T3 view.
function readBakedCohortKey() {
try {
if (process.resourcesPath) {
const p = path.join(process.resourcesPath, "cohort-app-key.json");
if (fs.existsSync(p)) {
const parsed = JSON.parse(fs.readFileSync(p, "utf8"));
if (parsed && typeof parsed.cohortKey === "string") return parsed.cohortKey.trim();
}
}
} catch {
/* unreadable / malformed → no key, anon T3 fallback */
}
return "";
}
// Precedence: an explicit env override (dev / a provisioned local run) wins over
// the baked resource file. This resolved value is what the renderer receives over
// the "cohort-key:get" bridge, so the renderer never needs its own file access.
const COHORT_KEY = (process.env.SRFG_COHORT_KEY || readBakedCohortKey() || "").trim();
// If a `wall_prefs.json` survived from before the rename (either from this
// install or copied over by migrateLegacyUserData()), promote it to the new
// `viz_prefs.json` filename. We rename rather than copy so the next save
// produces a single canonical file.
function migratePrefsFile() {
try {
if (!fs.existsSync(PREFS_FILE) && fs.existsSync(LEGACY_PREFS_FILE)) {
fs.renameSync(LEGACY_PREFS_FILE, PREFS_FILE);
process.stderr.write(`[viz:log] migrated prefs ${LEGACY_PREFS_FILE} → ${PREFS_FILE}\n`);
}
} catch (e) {
process.stderr.write(`[viz:warn] prefs migration failed: ${e && e.message}\n`);
}
}
migratePrefsFile();
function readJSON(p, fb) { try { return JSON.parse(fs.readFileSync(p, "utf8")); } catch { return fb; } }
function writeJSON(p, d) {
try { fs.mkdirSync(path.dirname(p), { recursive: true }); } catch {}
const tmp = p + ".tmp";
fs.writeFileSync(tmp, JSON.stringify(d));
fs.renameSync(tmp, p);
}
function hashShort(s) {
return crypto.createHash("sha256").update(String(s)).digest("hex").slice(0, 12);
}
function contextVaultRoots() {
// Only the bundled, in-app transcripts are scanned. We deliberately do NOT
// reach into ~/Desktop or ~/Documents: on macOS, any access to those folders
// — even a stat on a non-existent subpath — triggers a TCC "wants to access
// your Documents folder" prompt at boot, which is alarming in the prod app.
return [
{
key: "bundled-raw-scripts",
label: "Bundled transcripts",
path: path.join(__dirname, "src", "content", "context", "raw-scripts"),
max_depth: 1,
bundled: true,
},
];
}
function skipContextVaultEntry(name) {
return name.startsWith(".") || new Set([
"node_modules",
"dist",
"build",
"release",
".git",
".next",
".vercel",
"coverage",
]).has(name);
}
function walkTranscriptFiles(root, out = [], depth = 0, maxDepth = 4) {
if (!root || depth > maxDepth || out.length >= 350) return out;
let entries;
try { entries = fs.readdirSync(root, { withFileTypes: true }); }
catch { return out; }
for (const entry of entries) {
if (out.length >= 350) break;
if (!entry || skipContextVaultEntry(entry.name)) continue;
const fp = path.join(root, entry.name);
if (entry.isDirectory()) {
if (depth < maxDepth) walkTranscriptFiles(fp, out, depth + 1, maxDepth);
continue;
}
if (!entry.isFile()) continue;
if (!/\.(txt|md|markdown)$/i.test(entry.name)) continue;
out.push(fp);
}
return out;
}
function meaningfulLines(text, cap = 14) {
const lines = String(text || "").split(/\r?\n/);
const picked = [];
for (const raw of lines) {
const line = raw.trim();
if (!line) continue;
if (/^\d{1,2}:\d{2}(?::\d{2})?$/.test(line)) continue;
if (/^meeting\s+/i.test(line) && picked.length > 0) continue;
picked.push(line);
if (picked.length >= cap) break;
}
return picked;
}
function inferTranscriptDate(name, text, mtime) {
const hay = `${name}\n${String(text || "").slice(0, 400)}`;
const iso = /\b(20\d{2})[-_ ](0?[1-9]|1[0-2])[-_ ](0?[1-9]|[12]\d|3[01])\b/.exec(hay);
if (iso) {
const y = iso[1];
const m = String(iso[2]).padStart(2, "0");
const d = String(iso[3]).padStart(2, "0");
return `${y}-${m}-${d}`;
}
const month = /\b(Jan(?:uary)?|Feb(?:ruary)?|Mar(?:ch)?|Apr(?:il)?|May|Jun(?:e)?|Jul(?:y)?|Aug(?:ust)?|Sep(?:t(?:ember)?)?|Oct(?:ober)?|Nov(?:ember)?|Dec(?:ember)?)\s+([0-3]?\d)(?:,)?\s+(20\d{2})\b/i.exec(hay);
if (month) {
const months = {
jan: "01", feb: "02", mar: "03", apr: "04", may: "05", jun: "06",
jul: "07", aug: "08", sep: "09", oct: "10", nov: "11", dec: "12",
};
const m = months[month[1].slice(0, 3).toLowerCase()] || "01";
const d = String(month[2]).padStart(2, "0");
return `${month[3]}-${m}-${d}`;
}
try { return new Date(mtime).toISOString().slice(0, 10); }
catch { return null; }
}
function inferSpeakers(text) {
const counts = new Map();
const add = (name) => {
let n = String(name || "").trim().replace(/\s+/g, " ");
n = n.replace(/[.,;:]+$/, "");
if (!n || n.length < 2 || n.length > 48) return;
if (/^(speaker|unknown|meeting|transcript|session)$/i.test(n)) return;
counts.set(n, (counts.get(n) || 0) + 1);
};
for (const line of String(text || "").split(/\r?\n/)) {
const a = /^([^:\n]{2,48}):\s+\S/.exec(line.trim());
if (a) add(a[1]);
const b = /^([^0-9\n]{2,48}?)\s{2,}\d{1,2}:\d{2}(?::\d{2})?\s*$/.exec(line.trim());
if (b) add(b[1]);
}
return Array.from(counts.entries())
.sort((a, b) => b[1] - a[1])
.slice(0, 8)
.map(([name]) => name);
}
function inferSkillAreas(text) {
const t = String(text || "").toLowerCase();
const checks = [
["tee", /\btee\b|trusted execution|tdx|sgx|sev|enclave/],
["dstack", /\bdstack\b|phala/],
["attestation", /attestation|ra-tls|quote verification/],
["formal-verification", /formal verification|kani|cvc5|proof certificate/],
["zk", /\bzk\b|zero[- ]knowledge|groth|snark/],
["threshold-crypto", /threshold|committee signs|mpc signature/],
["mpc", /\bmpc\b|multi-party/],
["agentic", /agent|agents|claude|codex|llm|hermes|smithers/],
["agent-runtime", /runtime|orchestrat|workflow|sandbox|daemon/],
["agent-routing", /routing|router|openrouter|model route/],
["cross-chain", /cross[- ]chain|bridge|wallet|asset|erc ?20|swap/],
["identity", /identity|credential|pubkey|signature|device key/],
["p2p", /\bp2p\b|mdns|lan|peer|gossip/],
["durable-workflows", /durable|cron|checkpoint|resume|handoff/],
["confidential-db", /database|postgres|encrypted-at-rest|confidential db/],
["design", /design|ux|interface|visual|prototype/],
["bd-gtm", /\bgtm\b|distribution|sales|customer|market|launch/],
["research-to-product", /research|paper|product|prototype|productization/],
["generative-media", /video|audio|media|transcript|voice|voxterm/],
["mechanism-design", /mechanism|incentive|market design|auction/],
];
return checks.filter(([, re]) => re.test(t)).map(([k]) => k).slice(0, 8);
}
function inferSignals(text) {
const lines = String(text || "").split(/\r?\n/).map(s => s.trim()).filter(Boolean);
const signalRe = /\b(should|need|needs|want|wants|would love|help|debug|question|ask|resource|tool|demo|ship|build|insight|pattern|risk|privacy|trust|verify|automate|workflow)\b/i;
const out = [];
for (const line of lines) {
if (out.length >= 6) break;
if (/^\d{1,2}:\d{2}/.test(line)) continue;
if (line.length < 28 || line.length > 260) continue;
if (signalRe.test(line)) out.push(line);
}
return out;
}
function transcriptTitle(filePath) {
return path.basename(filePath).replace(/\.(txt|md|markdown)$/i, "").replace(/[_-]+/g, " ").replace(/\s+/g, " ").trim();
}
const ARTICLE_BRIEFS = [
{
key: "llm-agent-memory-workflows-social-routing",
title: "Why LLM agents need memory, workflows, and social routing",
angle: "Useful agent work disappears into private sessions, lost context, and brittle long-running tasks, so Shape Rotator should explain why agent workflows need durable memory, social routing, audit trails, and human override.",
section: "agent infrastructure",
match: /\b(agent|agents|llm|memory|workflow|workflows|routing|router|social|audit|override|long-running|durable|elocute|dumb agent|project intros|office hours)\b/i,
},
{
key: "privacy-capability-product",
title: "Privacy is not the product; capability is the product",
angle: "Private AI infrastructure, TEEs, and data sovereignty only become interesting when they unlock a concrete workflow people already want.",
section: "privacy and capability",
match: /\b(privacy|private|local-first|private-first|tee|tees|dstack|enclave|confidential|sovereignty|capability)\b/i,
},
{
key: "verifiability-ai-infrastructure-ux",
title: "Verifiability is becoming UX for AI infrastructure",
angle: "Remote attestation and deployable proof are moving from backend trust primitives into things users can see, understand, and act on.",
section: "verifiability ux",
match: /\b(verifiability|verify|verification|attestation|remote attestation|proof|dstack|zk|quote|deployable)\b/i,
},
];
function sourceTitleForConcept(source) {
return String(source?.title || "")
.replace(/\btranscripts?\b/ig, "")
.replace(/\bnotes?\b/ig, "")
.replace(/\bsession\b/ig, "")
.replace(/\b(Jan(?:uary)?|Feb(?:ruary)?|Mar(?:ch)?|Apr(?:il)?|May|Jun(?:e)?|Jul(?:y)?|Aug(?:ust)?|Sep(?:t(?:ember)?)?|Oct(?:ober)?|Nov(?:ember)?|Dec(?:ember)?)\s+\d{1,2}(?:,)?(?:\s+20\d{2})?\b/ig, "")
.replace(/\b20\d{2}\b/g, "")
.replace(/\(\d+\)/g, "")
.replace(/[_-]+/g, " ")
.replace(/\s+/g, " ")
.replace(/^[\s,;:.-]+|[\s,;:.-]+$/g, "")
.trim();
}
function articleConcept(source) {
if (source?.article_title) {
return {
title: source.article_title,
dek: source.article_dek || source.article_angle || "",
angle: source.article_angle || source.article_dek || "",
section: source.article_section || "article",
};
}
const hay = [
source?.title,
(source?.skill_areas || []).join(" "),
(source?.signals || []).join(" "),
source?.excerpt,
].filter(Boolean).join(" ");
const matched = ARTICLE_BRIEFS.find(rule => rule.match.test(hay));
if (matched) return { ...matched, dek: matched.angle };
const id = String(source?.article_id || source?.corpus_id || "").trim();
const skills = (source?.skill_areas || []).slice(0, 2).join(" + ");
const focus = skills || sourceTitleForConcept(source) || "cohort context";
return {
title: `${id || "Article draft"}: ${focus} patterns worth drafting`,
dek: `A public-safe article candidate distilled from private context around ${focus}.`,
angle: `Draft a public-safe Shape Rotator article about the reusable ${focus} patterns in this context vault entry.`,
section: "article candidate",
};
}
function articleTitle(source) {
return articleConcept(source).title;
}
function articleDek(source) {
return articleConcept(source).dek;
}
function articleAngle(source) {
return articleConcept(source).angle;
}
function articleSection(source) {
return articleConcept(source).section;
}
function articleSlug(s, fallback = "article") {
const slug = String(s || fallback)
.toLowerCase()
.normalize("NFKD")
.replace(/[\u0300-\u036f]/g, "")
.replace(/[^a-z0-9]+/g, "-")
.replace(/^-+|-+$/g, "")
.slice(0, 72);
return slug || fallback;
}
function uniqList(values = [], cap = 12) {
const out = [];
for (const value of values.map(v => String(v || "").trim()).filter(Boolean)) {
if (out.includes(value)) continue;
out.push(value);
if (out.length >= cap) break;
}
return out;
}
function parseSimpleFrontmatterScalar(value) {
const raw = String(value || "").trim();
if (!raw || raw === "null") return raw === "null" ? null : "";
if (raw.startsWith("[") && raw.endsWith("]")) {
return raw.slice(1, -1)
.split(",")
.map(v => parseSimpleFrontmatterScalar(v))
.filter(v => v !== "");
}
if ((raw.startsWith('"') && raw.endsWith('"')) || (raw.startsWith("'") && raw.endsWith("'"))) {
return raw.slice(1, -1);
}
return raw;
}
function parseSimpleFrontmatter(text) {
const m = /^---\n([\s\S]*?)\n---\n?([\s\S]*)$/.exec(String(text || ""));
if (!m) return { frontmatter: {}, body: String(text || "") };
const frontmatter = {};
let listKey = null;
for (const rawLine of m[1].split(/\r?\n/)) {
const list = /^\s*-\s+(.+)$/.exec(rawLine);
if (list && listKey) {
if (!Array.isArray(frontmatter[listKey])) frontmatter[listKey] = [];
frontmatter[listKey].push(parseSimpleFrontmatterScalar(list[1]));
continue;
}
const kv = /^([A-Za-z0-9_-]+):(?:\s*(.*))?$/.exec(rawLine);
if (!kv) continue;
const key = kv[1];
const value = kv[2] || "";
if (!value.trim()) {
frontmatter[key] = [];
listKey = key;
continue;
}
frontmatter[key] = parseSimpleFrontmatterScalar(value);
listKey = null;
}
return { frontmatter, body: m[2] || "" };
}
function cohortArticleDirs() {
const seen = new Set();
return [PACKAGED_COHORT_ARTICLES_DIR, REPO_COHORT_ARTICLES_DIR].filter((dir) => {
if (!dir) return false;
const key = path.resolve(dir);
if (seen.has(key)) return false;
seen.add(key);
try {
return fs.statSync(dir).isDirectory()
&& fs.readdirSync(dir).some(name => name.endsWith(".md"));
} catch {
return false;
}
});
}
function readCommittedArticles() {
const articlesDir = cohortArticleDirs()[0];
if (!articlesDir) return [];
let files;
try {
files = fs.readdirSync(articlesDir).filter(name => name.endsWith(".md")).sort();
} catch {
return [];
}
const articles = [];
for (const file of files) {
const filePath = path.join(articlesDir, file);
let raw;
try { raw = fs.readFileSync(filePath, "utf8"); }
catch { continue; }
const { frontmatter, body } = parseSimpleFrontmatter(raw);
if (frontmatter.record_type !== "article" || !frontmatter.record_id) continue;
const title = frontmatter.title || sourceTitleForConcept({ title: file });
const slug = frontmatter.slug || articleSlug(title);
articles.push({
id: `article:${frontmatter.record_id}`,
entry_kind: "article",
article_id: frontmatter.record_id,
corpus_id: frontmatter.record_id,
article_title: title,
article_angle: frontmatter.working_angle || "",
article_dek: frontmatter.working_angle || "",
article_section: frontmatter.editorial_section || "article",
article_slug: slug,
article_file: file,
article_body_md: String(body || "").trim(),
article_full_md: String(raw || "").trim(),
content_version: frontmatter.content_version || "",
status: frontmatter.status || "draft",
date: frontmatter.authored_week || null,
source_kind: "cohort-article",
source_refs: (frontmatter.sources || []).map(source => ({ title: String(source || "") })),
support_count: Array.isArray(frontmatter.sources) ? frontmatter.sources.length : 0,
skill_areas: frontmatter.related_clusters || [],
related_teams: frontmatter.related_teams || [],
related_people: frontmatter.related_people || [],
path: filePath,
size_bytes: Buffer.byteLength(raw, "utf8"),
line_count: raw.split(/\r?\n/).length,
char_count: raw.length,
});
}
return articles;
}
function articleDedupeKey(source) {
return String(source?.article_slug || articleSlug(source?.article_title || source?.title || source?.id || "article")).toLowerCase();
}
function mergeCommittedArticles(generatedArticles = []) {
const committed = readCommittedArticles();
const seen = new Set(committed.map(articleDedupeKey));
const generated = generatedArticles.filter(article => {
const key = articleDedupeKey(article);
if (seen.has(key)) return false;
seen.add(key);
return true;
});
return [...committed, ...generated];
}
function articleBriefHaystack(source) {
return [
source?.title,
source?.article_title,
source?.article_angle,
(source?.skill_areas || []).join(" "),
(source?.signals || []).join(" "),
source?.excerpt,
].filter(Boolean).join("\n");
}
function buildArticleEntries(inputSources = []) {
if (!inputSources.length) return [];
return ARTICLE_BRIEFS.map((brief) => {
let matched = inputSources.filter(source => brief.match.test(articleBriefHaystack(source)));
if (!matched.length) matched = inputSources;
const slug = articleSlug(brief.title, brief.key);
const skills = uniqList(matched.flatMap(source => source.skill_areas || []), 10);
const refs = matched.map(source => ({
id: source.id,
title: source.title,
date: source.date,
kind: source.source_kind,
})).filter(ref => ref.id || ref.title);
return {
id: slug,
entry_kind: "article",
article_id: slug,
corpus_id: slug,
article_title: brief.title,
article_angle: brief.angle,
article_dek: brief.angle,
article_section: brief.section,
article_slug: slug,
date: matched.map(source => source.date).filter(Boolean).sort().pop() || null,
source_kind: "article-brief",
support_count: matched.length,
source_refs: refs,
skill_areas: skills,
line_count: matched.reduce((sum, source) => sum + (source.line_count || 0), 0),
size_bytes: matched.reduce((sum, source) => sum + (source.size_bytes || 0), 0),
char_count: matched.reduce((sum, source) => sum + (source.char_count || 0), 0),
};
});
}
function inferSourceKind(filePath, root) {
const hay = `${root?.key || ""} ${root?.label || ""} ${filePath}`.toLowerCase();
if (hay.includes("voxterm")) return "voxterm";
if (root?.key === "shape-rotator-desktop" || hay.includes("transcript")) return "in-person-context";
return "manual";
}
const TRANSCRIPT_HEADER_LIST_FIELDS = new Set([
"speakers",
"calendar_matches",
"related_teams",
"related_people",
]);
function parseTranscriptHeaderList(value) {
const raw = String(value || "").trim();
if (!raw) return [];
const inner = raw.startsWith("[") && raw.endsWith("]")
? raw.slice(1, -1)
: raw;
return inner
.split(",")
.map(item => item.trim().replace(/^['"]|['"]$/g, ""))
.filter(Boolean);
}
function parseTranscriptHeaderMetadata(text) {
const raw = String(text || "");
const header = raw.split(/^-{5}\s*BEGIN TRANSCRIPT\s*-{5}/mi)[0] || "";
const metadata = {};
const titleLine = header.split(/\r?\n/).find(line => /^#\s+/.test(line.trim()));
if (titleLine) metadata.header_title = titleLine.replace(/^#\s+/, "").trim();
for (const line of header.split(/\r?\n/)) {
const match = /^([A-Za-z0-9_-]+):\s*(.*?)\s*$/.exec(line.trim());
if (!match) continue;
const key = match[1];
const value = match[2] || "";
metadata[key] = TRANSCRIPT_HEADER_LIST_FIELDS.has(key)
? parseTranscriptHeaderList(value)
: value;
}
return metadata;
}
function scanTranscriptFile(filePath, root) {
let stat;
try { stat = fs.statSync(filePath); }
catch { return null; }
if (!stat.isFile() || stat.size <= 0) return null;
// Keep individual reads bounded. These are transcripts, not binary blobs.
const maxBytes = 1_500_000;
let raw;
try { raw = fs.readFileSync(filePath, "utf8").slice(0, maxBytes); }
catch { return null; }
const lines = raw.split(/\r?\n/);
const header = parseTranscriptHeaderMetadata(raw);
const title = transcriptTitle(filePath);
const date = inferTranscriptDate(path.basename(filePath), raw, stat.mtimeMs);
const skills = inferSkillAreas(`${title}\n${raw}`);
const speakers = Array.isArray(header.speakers) && header.speakers.length ? header.speakers : inferSpeakers(raw);
const excerptLines = meaningfulLines(raw, 10);
const signals = inferSignals(raw);
const id = hashShort(`${filePath}:${stat.size}:${Math.round(stat.mtimeMs)}`);
const sourceKind = inferSourceKind(filePath, root);
return {
id,
record_id: header.record_id || null,
article_title: null,
article_angle: null,
article_slug: null,
article_dek: null,
article_section: null,
title,
path: filePath,
root_key: root.key,
root_label: root.label,
source_kind: sourceKind,
date,
size_bytes: stat.size,
line_count: lines.length,
char_count: raw.length,
mtime: new Date(stat.mtimeMs).toISOString(),
source_format: header.source_format || null,
segments: Number(header.segments) || null,
review_status: header.review_status || null,
submit_recommendation: header.submit_recommendation || null,
calendar_matches: header.calendar_matches || [],
related_teams: header.related_teams || [],
related_people: header.related_people || [],
utility: header.utility || null,
import_boundary: header.import_boundary || null,
content_boundary: header.content_boundary || header.import_boundary || null,
redactions: header.redactions || null,
speakers,
skill_areas: skills,
signals,
excerpt: excerptLines.join("\n"),
truncated: stat.size > maxBytes,
};
}
function contextVaultTotals(sources = [], rawScripts = []) {
return {
sources: sources.length,
articles: sources.length,
raw_scripts: rawScripts.length,
lines: sources.reduce((n, s) => n + (s.line_count || 0), 0),
bytes: sources.reduce((n, s) => n + (s.size_bytes || 0), 0),
voxterm: sources.filter(s => s.source_kind === "voxterm").length,
in_person_context: sources.filter(s => s.source_kind === "in-person-context").length,
manual: sources.filter(s => s.source_kind === "manual").length,
};
}
function readContextVaultSourceText(filePath, maxBytes = 2_000_000) {
try {
const raw = fs.readFileSync(filePath, "utf8").replace(/\r\n/g, "\n");
return {
text: raw.slice(0, maxBytes),
truncated: Buffer.byteLength(raw, "utf8") > maxBytes,
};
} catch {
return { text: "", truncated: false };
}
}
function existingRawScripts(rawScripts = []) {
const next = [];
let changed = false;
for (const source of Array.isArray(rawScripts) ? rawScripts : []) {
const filePath = source?.path;
if (!filePath) {
changed = true;
continue;
}
try {
const stat = fs.statSync(filePath);
if (!stat.isFile()) {
changed = true;
continue;
}
next.push(source);
} catch {
changed = true;
}
}
return { rawScripts: next, changed };
}
function rawScriptFingerprint(rawScripts = []) {
const parts = [];
for (const source of Array.isArray(rawScripts) ? rawScripts : []) {
const filePath = source?.path || "";
let statSize = source?.size_bytes || 0;
let statMtime = source?.mtime || "";
try {
const stat = fs.statSync(filePath);
statSize = stat.size;
statMtime = Math.round(stat.mtimeMs);
} catch {}
parts.push(JSON.stringify({
id: source?.id || "",
title: source?.title || "",
path: filePath,
source_kind: source?.source_kind || "",
date: source?.date || "",
record_id: source?.record_id || "",
review_status: source?.review_status || "",
submit_recommendation: source?.submit_recommendation || "",
line_count: source?.line_count || 0,
size_bytes: source?.size_bytes || 0,
stat_size: statSize,
stat_mtime: statMtime,
}));
}
return hashShort(parts.sort().join("\n"));
}
function removeContextVaultRawBundle() {
try {
if (fs.existsSync(CONTEXT_VAULT_RAW_BUNDLE)) fs.unlinkSync(CONTEXT_VAULT_RAW_BUNDLE);
} catch {}
}
function writeContextVaultRawBundle(rawScripts = []) {
const generatedAt = new Date().toISOString();
const sourceFingerprint = rawScriptFingerprint(rawScripts);
const lines = [
"---",
'title: "Shape Rotator Transcripts"',
`generated_at: ${JSON.stringify(generatedAt)}`,
`transcript_count: ${rawScripts.length}`,
`source_fingerprint: ${JSON.stringify(sourceFingerprint)}`,
'kind: "transcript-bundle"',
"---",
"",
"# Shape Rotator Transcripts",
"",
"Bundled transcript set for private prompting inside Shape Rotator OS.",
"",
];
for (const source of rawScripts) {
const raw = readContextVaultSourceText(source.path, 2_000_000);
lines.push(`## ${source.title || path.basename(source.path || "transcript")}`);
lines.push("");
lines.push(`source_id: ${source.id || ""}`);
lines.push(`source_kind: ${source.source_kind || "transcript"}`);
lines.push(`date: ${source.date || ""}`);
lines.push(`lines: ${source.line_count || 0}`);
lines.push(`path: ${source.path || ""}`);
if (source.record_id) lines.push(`record_id: ${source.record_id}`);
if (source.review_status) lines.push(`review_status: ${source.review_status}`);
if (source.submit_recommendation) lines.push(`submit_recommendation: ${source.submit_recommendation}`);
if (source.calendar_matches?.length) lines.push(`calendar_matches: [${source.calendar_matches.join(", ")}]`);
if (source.related_teams?.length) lines.push(`related_teams: [${source.related_teams.join(", ")}]`);
if (source.related_people?.length) lines.push(`related_people: [${source.related_people.join(", ")}]`);
if (source.utility) lines.push(`utility: ${source.utility}`);
if (source.content_boundary) lines.push(`content_boundary: ${source.content_boundary}`);
if (source.redactions) lines.push(`redactions: ${source.redactions}`);
lines.push("");
lines.push("----- BEGIN TRANSCRIPT -----");
lines.push(raw.text || "");
if (raw.truncated || source.truncated) lines.push("----- TRUNCATED -----");
lines.push("----- END TRANSCRIPT -----");
lines.push("");
}
fs.mkdirSync(path.dirname(CONTEXT_VAULT_RAW_BUNDLE), { recursive: true });
const body = lines.join("\n");
fs.writeFileSync(CONTEXT_VAULT_RAW_BUNDLE, body);
return {
path: CONTEXT_VAULT_RAW_BUNDLE,
kind: "transcript-bundle",
generated_at: generatedAt,
transcript_count: rawScripts.length,
source_fingerprint: sourceFingerprint,
line_count: body.split(/\r?\n/).length,
char_count: body.length,
size_bytes: Buffer.byteLength(body, "utf8"),
};
}
function normalizeContextVaultRawBundle(rawScripts = [], rawBundle = null) {
if (!rawScripts.length) {
const hadFile = fs.existsSync(CONTEXT_VAULT_RAW_BUNDLE);
removeContextVaultRawBundle();
return { raw_bundle: null, changed: !!rawBundle || hadFile };
}
const sourceFingerprint = rawScriptFingerprint(rawScripts);
if (
!rawBundle
|| rawBundle.kind !== "transcript-bundle"
|| rawBundle.path !== CONTEXT_VAULT_RAW_BUNDLE
|| rawBundle.source_fingerprint !== sourceFingerprint
|| !fs.existsSync(rawBundle.path || "")
) {
return { raw_bundle: writeContextVaultRawBundle(rawScripts), changed: true };
}
return { raw_bundle: rawBundle, changed: false };
}
function writeContextVaultCorpus(sources = []) {
const generatedAt = new Date().toISOString();
const lines = [
"---",
'title: "Shape Rotator Article Index"',
`generated_at: ${JSON.stringify(generatedAt)}`,
`article_count: ${sources.length}`,
'kind: "private-article-index"',
"---",
"",
"# Shape Rotator Article Index",
"",
"Private local article index generated from the local context vault. It is a working list of draft candidates, not public-ready copy.",
"",
"## Prompting Contract",
"",
"- Treat each entry as an article draft candidate.",
"- Separate public-safe synthesis from private/internal notes.",
"- Do not publish private user data, travel logistics, raw notes, or personal details without review.",
"- Prefer extracting reusable OS content: articles, context cards, program notes, asks, journal entries, people/project references, and open questions.",
"- Reference article titles when making claims from this index.",
"",
];
lines.push("## Article Index", "");
lines.push("| title | angle | supporting inputs |");
lines.push("|---|---|---|");
for (const source of sources) {
const title = source.article_title || articleTitle(source);
const angle = source.article_angle || articleAngle(source);
const support = source.support_count || source.source_refs?.length || 0;
lines.push(`| ${title.replace(/\|/g, "\\|")} | ${angle.replace(/\|/g, "\\|")} | ${support} |`);
}
lines.push("", "## Articles", "");
for (const source of sources) {
const title = source.article_title || articleTitle(source);
const angle = source.article_angle || articleAngle(source);
const section = source.article_section || articleSection(source);
const slug = source.article_slug || articleSlug(title);
const skillAreas = (source.skill_areas || []).slice(0, 8);
const support = source.support_count || source.source_refs?.length || 0;
lines.push(`### ${title}`);
lines.push("");
lines.push(`- status: draft-candidate`);
lines.push(`- suggested_slug: ${slug}`);
lines.push(`- editorial_section: ${section}`);
lines.push(`- working_angle: ${angle}`);
lines.push(`- supporting_private_inputs: ${support}`);
lines.push(`- inferred_skill_areas: ${skillAreas.length ? skillAreas.join(", ") : "none inferred"}`);
lines.push("");
lines.push("#### Drafting Cues");
lines.push("");
lines.push("- Review the private input before drafting.");
lines.push("- Extract a public-safe thesis, reusable program context, and any explicit asks.");
if (skillAreas.length) lines.push(`- Inferred areas to consider: ${skillAreas.join(", ")}.`);
lines.push("");
lines.push("#### Article Notes");
lines.push("");
lines.push("- Article body is intentionally not generated here; use the private input only during a reviewed drafting pass.");
lines.push("- Do not copy raw private notes into public OS content.");
lines.push("");
lines.push("#### Publish Boundary");
lines.push("");
lines.push("- Keep private inputs hidden.");
lines.push("- Publish only cleaned synthesis, reusable program context, or explicit asks.");
lines.push("");
}
fs.mkdirSync(path.dirname(CONTEXT_VAULT_CORPUS), { recursive: true });
const body = lines.join("\n");
fs.writeFileSync(CONTEXT_VAULT_CORPUS, body);
return {
path: CONTEXT_VAULT_CORPUS,
kind: "private-article-index",
generated_at: generatedAt,
article_count: sources.length,
line_count: body.split(/\r?\n/).length,
char_count: body.length,
size_bytes: Buffer.byteLength(body, "utf8"),
};
}
function normalizeContextVaultManifest(manifest) {
if (!manifest || !Array.isArray(manifest.sources)) return manifest;
const currentRoots = contextVaultRoots();
const currentRootMap = new Map(currentRoots.map(root => [root.key, root]));
const existingRoots = Array.isArray(manifest.roots) ? manifest.roots : [];
const rawScriptState = existingRawScripts(manifest.raw_scripts);
const rawScripts = rawScriptState.rawScripts;
const roots = existingRoots.map(root => {
const current = currentRootMap.get(root.key);
return current ? { ...root, ...current, exists: fs.existsSync(current.path) } : root;
});
for (const root of currentRoots) {
if (!roots.some(r => r.key === root.key)) {
roots.push({ ...root, exists: fs.existsSync(root.path) });
}
}
if (!manifest.sources.every(source => source.entry_kind === "article")) {
const sources = mergeCommittedArticles(buildArticleEntries(manifest.sources));
const totals = contextVaultTotals(sources, rawScripts);
const corpus = writeContextVaultCorpus(sources);
const rawBundleState = normalizeContextVaultRawBundle(rawScripts, manifest.raw_bundle || null);
const raw_bundle = rawBundleState.raw_bundle;
const next = { ...manifest, schema_version: 2, roots, totals, corpus, raw_bundle, sources, raw_scripts: rawScripts };
try { writeJSON(CONTEXT_VAULT_MANIFEST, next); } catch {}
return next;
}
const rootMap = new Map(roots.map(root => [root.key, root]));
let changed = rawScriptState.changed;
if (JSON.stringify(existingRoots) !== JSON.stringify(roots)) changed = true;
const normalizedSources = manifest.sources.map((source, index) => {
if (source.entry_kind === "article") {
const title = source.article_title || articleTitle(source);
const angle = source.article_angle || articleAngle(source);