-
Notifications
You must be signed in to change notification settings - Fork 26
Expand file tree
/
Copy pathbuild-bundles.js
More file actions
2428 lines (2290 loc) · 103 KB
/
Copy pathbuild-bundles.js
File metadata and controls
2428 lines (2290 loc) · 103 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
#!/usr/bin/env node
/**
* build-bundles.js — markdown source of truth → cohort surface JSON.
*
* Phase 1 implementation per docs/SHAPE-ROTATOR-OS-SPEC.md §4.4 §6:
* reads cohort-data/{teams,people,clusters,dependencies}/*.md, applies the surface-
* fields whitelist from cohort-data/schema.yml, writes
* apps/os/src/cohort-surface.json and apps/web/cohort-surface.json. The depth side (encrypted
* raw markdown bytes per §3.1) lands once swf-node bundle handling is
* in place.
*
* Usage:
* node scripts/build-bundles.js one-shot build
* node scripts/build-bundles.js --check fail if surface is stale
*
* No external deps beyond js-yaml. No watch mode in this iteration —
* re-run after editing markdown.
*/
const fs = require("node:fs");
const path = require("node:path");
const vm = require("node:vm");
const yaml = require("js-yaml");
const {
publicArticleBlockedNames,
publicArticleCandidateFromReadout,
sanitizePublicArticleText,
} = require("./lib/public-article-policy.cjs");
const {
buildCohortInsightBundle,
publicCohortInsights,
loadEditorialAwardCategories,
} = require("./lib/cohort-insight-engine.cjs");
const { TIERS, isTier } = require("./lib/tiers.cjs");
const REPO_ROOT = path.resolve(__dirname, "..");
const COHORT_DIR = path.join(REPO_ROOT, "cohort-data");
const OS_SURFACE_PATH = path.join(REPO_ROOT, "apps", "os", "src", "cohort-surface.json");
const WEB_SURFACE_PATH = path.join(REPO_ROOT, "apps", "web", "cohort-surface.json");
const OUT_PATHS = [
OS_SURFACE_PATH,
WEB_SURFACE_PATH,
];
// The web copy is generated for local/static serving and intentionally
// gitignored. CI should require only the committed OS surface.
const CHECK_PATHS = [
OS_SURFACE_PATH,
];
const PRIMARY_OUT_PATH = OUT_PATHS[0];
function readSchema() {
const p = path.join(COHORT_DIR, "schema.yml");
if (!fs.existsSync(p)) throw new Error(`schema.yml not found at ${p}`);
return yaml.load(fs.readFileSync(p, "utf8"));
}
// Parse a single markdown file with YAML frontmatter. Returns
// { frontmatter, body } — frontmatter is null if the file has no
// frontmatter block.
function parseMarkdown(file) {
const raw = fs.readFileSync(file, "utf8").replace(/\r\n?/g, "\n");
const m = /^---\n([\s\S]*?)\n---\n?([\s\S]*)$/.exec(raw);
if (!m) return { frontmatter: null, body: raw };
let frontmatter;
try { frontmatter = yaml.load(m[1]); }
catch (e) { throw new Error(`bad YAML in ${file}: ${e.message}`); }
return { frontmatter, body: m[2] };
}
// Pick whitelisted keys from an object (no nested support — we use
// the whole `links` object as one entry, which is what the surface
// schema expects).
function pickSurface(obj, whitelist) {
const out = {};
for (const k of whitelist) {
if (Object.prototype.hasOwnProperty.call(obj || {}, k)) {
out[k] = obj[k];
}
}
return out;
}
function sanitizePersonSurface(surface) {
delete surface.email;
delete surface.dietary_restrictions;
if (surface.links && typeof surface.links === "object") {
const links = { ...surface.links };
delete links.telegram;
surface.links = links;
}
return surface;
}
function extractPublicPersonBio(body) {
const raw = String(body || "").trim();
if (!raw) return "";
const lines = raw.split("\n");
const start = lines.findIndex(line => /^##\s+(about|bio)\s*$/i.test(line.trim()));
if (start < 0) return raw;
const end = lines.findIndex((line, index) => index > start && /^##\s+/.test(line.trim()));
return lines.slice(start + 1, end < 0 ? undefined : end).join("\n").trim();
}
function loadDir(dir, recordType, surfaceFields) {
if (!fs.existsSync(dir)) return [];
const files = fs.readdirSync(dir).filter(f => f.endsWith(".md"));
const records = [];
for (const f of files) {
const fp = path.join(dir, f);
const { frontmatter, body } = parseMarkdown(fp);
if (!frontmatter) {
console.warn(`[build-bundles] skipping ${fp} — no frontmatter`);
continue;
}
if (frontmatter.record_type !== recordType) {
console.warn(`[build-bundles] skipping ${fp} — record_type mismatch (got ${frontmatter.record_type}, expected ${recordType})`);
continue;
}
if (!frontmatter.record_id) {
console.warn(`[build-bundles] skipping ${fp} — no record_id`);
continue;
}
const surface = pickSurface(frontmatter, surfaceFields);
if (recordType === "person") {
sanitizePersonSurface(surface);
const bio = extractPublicPersonBio(body);
if (bio) surface.bio_md = bio;
}
records.push(surface);
}
// Stable order by record_id.
records.sort((a, b) => String(a.record_id).localeCompare(String(b.record_id)));
return records;
}
// Program-page loader. Unlike entity records, program pages carry their full
// markdown body in the bundle so the app can render them offline-first. Body
// is the raw markdown AFTER the frontmatter block — the renderer does the
// light markdown→HTML pass.
function loadProgramDir(dir, surfaceFields) {
if (!fs.existsSync(dir)) return [];
const files = fs.readdirSync(dir).filter(f => f.endsWith(".md"));
const records = [];
for (const f of files) {
const fp = path.join(dir, f);
const { frontmatter, body } = parseMarkdown(fp);
if (!frontmatter) {
console.warn(`[build-bundles] skipping ${fp} — no frontmatter`);
continue;
}
if (frontmatter.record_type !== "program_page") {
console.warn(`[build-bundles] skipping ${fp} — record_type mismatch (got ${frontmatter.record_type}, expected program_page)`);
continue;
}
if (!frontmatter.record_id) {
console.warn(`[build-bundles] skipping ${fp} — no record_id`);
continue;
}
const surface = pickSurface(frontmatter, surfaceFields);
surface.body_md = (body || "").trim();
records.push(surface);
}
// Stable order by frontmatter `order` (numeric, ascending), then record_id.
records.sort((a, b) => {
const ao = Number.isFinite(a.order) ? a.order : 1e9;
const bo = Number.isFinite(b.order) ? b.order : 1e9;
if (ao !== bo) return ao - bo;
return String(a.record_id).localeCompare(String(b.record_id));
});
return records;
}
function githubBlobUrl(relPath) {
return `https://github.com/dmarzzz/shape-rotator-os/blob/main/${String(relPath || "").replace(/\\/g, "/")}`;
}
function recordSourceUrl(recordType, recordId) {
const folder = recordType === "person" ? "people"
: recordType === "team" ? "teams"
: recordType === "ask" ? "asks"
: recordType === "event" ? "events"
: recordType === "cluster" ? "clusters"
: recordType === "dependency" ? "dependencies"
: `${recordType || "record"}s`;
return githubBlobUrl(`cohort-data/${folder}/${recordId}.md`);
}
function firstLine(value) {
return String(value || "").split(/\r?\n/).map(s => s.trim()).filter(Boolean)[0] || "";
}
function compactText(value, max = 180) {
const s = String(value || "").replace(/\s+/g, " ").trim();
return s.length > max ? `${s.slice(0, max - 1).trim()}…` : s;
}
function asArray(value) {
if (Array.isArray(value)) return value.filter(v => v != null && String(v).trim() !== "");
return value == null || String(value).trim() === "" ? [] : [value];
}
function labelize(value) {
return String(value || "not declared").replace(/[-_]+/g, " ");
}
const RECORD_KEYWORD_STOPWORDS = new Set([
"and", "are", "for", "from", "into", "that", "the", "this", "with",
"team", "teams", "user", "users", "app", "apps", "build", "building",
"product", "project", "private", "public", "agent", "agents", "data",
]);
function keywordTokens(value) {
return String(value || "")
.toLowerCase()
.replace(/[^a-z0-9]+/g, " ")
.split(/\s+/)
.filter(token => token.length >= 4 && !RECORD_KEYWORD_STOPWORDS.has(token));
}
function recordKeywords(record = {}) {
const values = [
record.record_id,
String(record.record_id || "").replace(/[-_]+/g, " "),
record.name,
record.focus,
record.now,
record.domain,
record.working_style,
asArray(record.skill_areas).join(" "),
asArray(record.success_dimensions).join(" "),
asArray(record.go_to_them_for).join(" "),
asArray(record.recurring_themes).join(" "),
asArray(record.prior_work).join(" "),
];
return Array.from(new Set(values.flatMap(keywordTokens))).slice(0, 40);
}
function textIncludesAny(text, aliases) {
const hay = String(text || "").toLowerCase();
return aliases.some(alias => alias && hay.includes(String(alias).toLowerCase()));
}
function isoDate(value) {
if (value instanceof Date && !Number.isNaN(value.getTime())) {
return value.toISOString().slice(0, 10);
}
const s = String(value || "");
const m = /^(\d{4}-\d{2}-\d{2})/.exec(s);
return m ? m[1] : "";
}
const MONTH_NUM = {
jan: 1, january: 1,
feb: 2, february: 2,
mar: 3, march: 3,
apr: 4, april: 4,
may: 5,
jun: 6, june: 6,
jul: 7, july: 7,
aug: 8, august: 8,
sep: 9, sept: 9, september: 9,
oct: 10, october: 10,
nov: 11, november: 11,
dec: 12, december: 12,
};
function monthDayToIso(month, day, year = 2026) {
const n = MONTH_NUM[String(month || "").toLowerCase()];
const d = Number(day);
if (!n || !Number.isFinite(d)) return "";
return `${year}-${String(n).padStart(2, "0")}-${String(d).padStart(2, "0")}`;
}
function parseMonthDay(text) {
const m = /\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})\b/i.exec(String(text || ""));
return m ? monthDayToIso(m[1], m[2]) : "";
}
function addDays(iso, days) {
if (!iso) return "";
const d = new Date(`${iso}T00:00:00.000Z`);
if (Number.isNaN(d.getTime())) return "";
d.setUTCDate(d.getUTCDate() + days);
return d.toISOString().slice(0, 10);
}
function loadCalendarTranscriptMatches() {
const p = path.join(REPO_ROOT, "apps", "os", "src", "content", "context", "calendar-transcript-matches.js");
if (!fs.existsSync(p)) return [];
const raw = fs.readFileSync(p, "utf8")
.replace(/export\s+const\s+CALENDAR_TRANSCRIPT_MATCHES\s*=/, "module.exports =");
const sandbox = { module: { exports: [] }, exports: {} };
try {
vm.runInNewContext(raw, sandbox, { filename: p, timeout: 1000 });
return Array.isArray(sandbox.module.exports) ? sandbox.module.exports : [];
} catch (e) {
console.warn(`[build-bundles] transcript match load failed: ${e.message}`);
return [];
}
}
// Evaluate one calendar-matched transcript source against a record's
// aliases. Bundled sources scan the transcript text on disk; held-private
// sources (raw transcripts removed from the public repo per the content
// policy) use the mention snapshot baked into calendar-transcript-matches.js
// when the file left the repo, keyed by record_id.
function transcriptSourceHit(match, source, aliases, recordId) {
const relPath = source.path;
const heldPrivately = !relPath && source.held === "private-vault";
let text = "";
if (relPath) {
const fp = path.join(REPO_ROOT, relPath);
if (!fs.existsSync(fp)) return null;
text = fs.readFileSync(fp, "utf8");
} else if (!heldPrivately) {
return null;
}
const sourceText = `${source.label || ""} ${relPath || ""} ${match.section || ""}`;
const textDirect = heldPrivately
? (source.mentions_direct || []).includes(recordId)
: textIncludesAny(text, aliases.direct);
const directHit = textDirect || textIncludesAny(sourceText, aliases.direct);
const textAny = heldPrivately
? (source.mentions_any || []).includes(recordId)
: textIncludesAny(text, aliases.any);
const anyHit = directHit || textAny || textIncludesAny(sourceText, aliases.any);
if (!anyHit) return null;
const baseLabel = source.label || (relPath ? path.basename(relPath) : "transcript");
return {
directHit,
sourceNamed: textIncludesAny(sourceText, aliases.direct),
heldPrivately,
detail: compactText(`${match.section || "session"} · ${baseLabel}${heldPrivately ? " · held privately" : ""}`, 150),
href: relPath ? githubBlobUrl(relPath) : "",
dedupKey: relPath ? githubBlobUrl(relPath) : `vault:${source.vault_id || baseLabel}`,
vaultId: heldPrivately ? String(source.vault_id || "") : "",
};
}
function personAliases(person, team) {
const aliases = new Set();
const add = (v) => {
const s = String(v || "").trim();
if (s.length >= 3) aliases.add(s.toLowerCase());
};
add(person.record_id);
add(String(person.record_id || "").replace(/[-_]+/g, " "));
add(person.name);
for (const part of String(person.name || "").split(/\s+/)) {
if (part.length >= 4) add(part);
}
for (const v of Object.values(person.links || {})) add(v);
const direct = Array.from(aliases);
if (team) {
add(team.record_id);
add(team.name);
}
return { direct, any: Array.from(aliases) };
}
function teamAliases(team, members = []) {
const directAliases = new Set();
const memberAliases = new Set();
const add = (set, v) => {
const s = String(v || "").trim();
if (s.length >= 3) set.add(s.toLowerCase());
};
add(directAliases, team.record_id);
add(directAliases, String(team.record_id || "").replace(/[-_]+/g, " "));
add(directAliases, team.name);
for (const v of Object.values(team.links || {})) add(directAliases, v);
for (const member of members) {
add(memberAliases, member.record_id);
add(memberAliases, String(member.record_id || "").replace(/[-_]+/g, " "));
add(memberAliases, member.name);
}
return {
direct: Array.from(directAliases),
any: Array.from(new Set([...directAliases, ...memberAliases])),
};
}
// calendar.json is the bot-synced mirror of the upstream Phala calendar, so a
// stray cell may carry an attributed quote with a recording timecode
// ("… — Tina, Apr 27 (01:47:57)") sourced from a private planning transcript.
// Strip any " · "-joined segment that carries a parenthesized H:MM:SS timecode
// before the calendar reaches the bundle or the person/team timelines. This is
// a build-time guard; the durable fix is upstream in the calendar source.
const TIMECODE_RE = /\([0-9]{1,2}:[0-9]{2}:[0-9]{2}\)/;
function scrubTimecodeQuotes(value) {
if (typeof value === "string") {
if (!TIMECODE_RE.test(value)) return value;
return value.split(" · ").filter((seg) => !TIMECODE_RE.test(seg)).join(" · ").trim();
}
if (Array.isArray(value)) return value.map(scrubTimecodeQuotes);
if (value && typeof value === "object") {
const out = {};
for (const [key, inner] of Object.entries(value)) out[key] = scrubTimecodeQuotes(inner);
return out;
}
return value;
}
function calendarBlocks(calendar) {
const blocks = [];
const tabs = calendar?.tabs && typeof calendar.tabs === "object" ? calendar.tabs : {};
for (const [tab, rows] of Object.entries(tabs)) {
if (!Array.isArray(rows) || !rows.length) continue;
const header = rows[0] || [];
for (const row of rows.slice(1)) {
if (!Array.isArray(row)) continue;
const rowStart = parseMonthDay(row[1] || "");
for (let i = 0; i < row.length; i++) {
const text = String(row[i] || "").trim();
if (!text) continue;
const headerLabel = String(header[i] || "");
const dayOffset = i >= 2 && i <= 8 ? i - 2 : 0;
const inferredDate = parseMonthDay(text) || (rowStart ? addDays(rowStart, dayOffset) : "");
blocks.push({
date: inferredDate,
title: firstLine(text) || headerLabel || tab,
detail: compactText(text),
tab,
column: headerLabel,
});
}
}
}
return blocks;
}
function sortTimeline(items) {
return items
.filter(item => item && (item.title || item.detail))
.sort((a, b) => {
const ad = a.date || "9999-99-99";
const bd = b.date || "9999-99-99";
if (ad !== bd) return ad.localeCompare(bd);
return String(a.type || "").localeCompare(String(b.type || ""));
});
}
function latestWeek(weeks) {
const values = asArray(weeks).map(isoDate).filter(Boolean).sort();
return values.length ? values[values.length - 1] : "";
}
function weekSortValue(value) {
return isoDate(value) || "0000-00-00";
}
function compareWeekDesc(a, b) {
return weekSortValue(b?.week_start || b).localeCompare(weekSortValue(a?.week_start || a));
}
function evidenceTimelineItems(transcriptEvidence, kind, recordId) {
const key = kind === "team" ? "team_id" : "person_id";
const rows = Array.isArray(transcriptEvidence?.[kind === "team" ? "teams" : "people"])
? transcriptEvidence[kind === "team" ? "teams" : "people"]
: [];
const view = rows.find(item => String(item?.[key] || "") === String(recordId || ""));
if (!view) return [];
const claims = asArray(view.top_claims).slice(0, 6);
return claims.map((claim) => ({
date: latestWeek(view.weeks),
type: "transcript evidence",
title: labelize(claim.claim_type || "evidence claim"),
detail: compactText(claim.text || "", 230),
source: [claim.evidence_level, claim.confidence, "reviewed evidence card"].filter(Boolean).join(" · "),
evidence_card_id: claim.source_artifact_id || "",
sharing_boundary: view.sharing_boundary?.max_surface || "cohort",
}));
}
const CLAIM_SIGNAL_PRIORITY = {
action_item: 100,
ask: 94,
collaboration_edge: 88,
product_signal: 80,
decision: 72,
risk: 64,
market_signal: 56,
claim: 36,
};
function claimSignalScore(claim, index = 0, context = {}) {
const type = claim?.claim_type || "claim";
const base = CLAIM_SIGNAL_PRIORITY[type] || CLAIM_SIGNAL_PRIORITY.claim;
const confidence = claim?.confidence === "high" ? 8 : claim?.confidence === "medium" ? 4 : 0;
const kind = context.kind || "team";
const recordId = String(context.recordId || "");
const peerIds = kind === "person" ? asArray(claim?.people) : asArray(claim?.teams);
const hasRecord = recordId && peerIds.includes(recordId);
const breadthPenalty = Math.max(0, peerIds.length - 1) * (kind === "person" ? 7 : 9);
const roomPenalty = Math.max(0, asArray(claim?.teams).length + asArray(claim?.people).length - 8) * 2;
const specificity = peerIds.length <= 1 ? 36 : peerIds.length <= 2 ? 20 : peerIds.length <= 4 ? 6 : -14;
const text = String(claim?.text || "").toLowerCase();
const overlapCount = asArray(context.keywords)
.filter(token => token && text.includes(token))
.slice(0, 6).length;
const keywordOverlap = overlapCount * 7;
const lexicalPenalty = overlapCount === 0 && peerIds.length > 4
? 90
: overlapCount === 0 && peerIds.length > 2
? 38
: 0;
const broadAskPenalty = type === "ask" && peerIds.length > 4 ? 42 : 0;
return base + confidence + specificity + keywordOverlap + (hasRecord ? 6 : 0) - breadthPenalty - roomPenalty - lexicalPenalty - broadAskPenalty - index;
}
function signalLabel(type) {
const labels = {
action_item: "next move",
ask: "needs",
collaboration_edge: "connect",
product_signal: "product signal",
decision: "decision",
risk: "risk",
market_signal: "market signal",
claim: "evidence",
};
return labels[type] || labels.claim;
}
function pickSignalClaim(view, context = {}) {
return asArray(view?.top_claims)
.map((claim, index) => ({ claim, score: claimSignalScore(claim, index, context) }))
.sort((a, b) => b.score - a.score)[0]?.claim || null;
}
function signalSpecificity(claim, kind) {
const peers = kind === "person" ? asArray(claim?.people) : asArray(claim?.teams);
if (peers.length <= 1) return "record-specific";
if (peers.length <= 4) return "small-group";
return "shared-session";
}
function compactSignalText(text, max = 138) {
return compactText(String(text || "").replace(/\s+/g, " "), max);
}
function buildCardSignal(view, kind, record) {
const id = kind === "team" ? view?.team_id : view?.person_id;
const claim = pickSignalClaim(view, {
kind,
recordId: id,
keywords: recordKeywords(record),
});
if (!id || !claim) return null;
const sourceCardIds = Array.from(new Set([
claim.source_artifact_id,
...asArray(view.evidence_card_ids),
].filter(Boolean)));
return {
record_id: id,
record_kind: kind,
signal_type: claim.claim_type || "claim",
label: signalLabel(claim.claim_type),
text: compactSignalText(claim.text),
detail_text: compactSignalText(claim.text, 280),
specificity: signalSpecificity(claim, kind),
review_status: "generated",
promotion_state: "needs-review",
confidence: claim.confidence || view.confidence || "low",
evidence_level: claim.evidence_level || "inferred",
evidence_card_count: asArray(view.evidence_card_ids).length,
claim_count: view.claim_count || asArray(view.top_claims).length,
source_card: claim.source_artifact_id || "",
source_card_ids: sourceCardIds.slice(0, 8),
claim_id: claim.claim_id || "",
week: latestWeek(view.weeks),
themes: asArray(view.themes).slice(0, 3),
teams: asArray(claim.teams).filter(team => team !== id).slice(0, 4),
people: asArray(claim.people).filter(person => person !== id).slice(0, 4),
sharing_boundary: view.sharing_boundary || { max_surface: "cohort", raw_allowed: false },
};
}
function buildCardSignals(evidence, records = {}) {
const teamById = new Map(asArray(records.teams).map(record => [record.record_id, record]));
const personById = new Map(asArray(records.people).map(record => [record.record_id, record]));
const teamSignals = asArray(evidence?.teams)
.map(view => buildCardSignal(view, "team", teamById.get(view?.team_id)))
.filter(Boolean)
.sort((a, b) => String(a.record_id).localeCompare(String(b.record_id)));
const personSignals = asArray(evidence?.people)
.map(view => buildCardSignal(view, "person", personById.get(view?.person_id)))
.filter(Boolean)
.sort((a, b) => String(a.record_id).localeCompare(String(b.record_id)));
return {
teams: teamSignals,
people: personSignals,
};
}
function claimsForNote(claims, types, limit = 4) {
const typeSet = new Set(types);
return asArray(claims)
.filter(claim => typeSet.has(claim.claim_type || "claim"))
.map((claim, index) => ({ claim, score: claimSignalScore(claim, index) }))
.sort((a, b) => b.score - a.score)
.map(item => ({
claim_type: item.claim.claim_type || "claim",
label: signalLabel(item.claim.claim_type),
text: compactSignalText(item.claim.text, 220),
confidence: item.claim.confidence || "low",
evidence_level: item.claim.evidence_level || "inferred",
source_card: item.claim.source_artifact_id || "",
source_card_ids: asArray(item.claim.source_artifact_id).slice(0, 1),
teams: asArray(item.claim.teams).slice(0, 8),
people: asArray(item.claim.people).slice(0, 8),
}))
.slice(0, limit);
}
function fieldNoteMarkdown(note) {
const sourceIds = asArray(note.source_card_ids);
const lines = [
`# ${note.title}`,
"",
"## the 60-second version",
"",
note.summary,
"",
];
for (const section of note.sections) {
if (!asArray(section.claims).length) continue;
lines.push(`## ${section.title}`, "");
for (const claim of section.claims) {
lines.push(`- **${claim.label}.** ${claim.text}`);
}
lines.push("");
}
lines.push(
"## provenance",
"",
`Generated from ${note.evidence_card_count} generated transcript evidence card(s) for the week of ${note.week_start}. Claims are paraphrased and cohort-internal unless separately promoted. Source dialogue is not shown here.`,
sourceIds.length ? `Source cards: ${sourceIds.join(", ")}` : "",
"",
);
return lines.join("\n").trim();
}
function buildFieldNotes(weeklyViews) {
return asArray(weeklyViews).map((week) => {
const topClaims = asArray(week.top_claims);
const sections = [
{ title: "what moved", claims: claimsForNote(topClaims, ["action_item", "product_signal", "decision"], 5) },
{ title: "asks and edges", claims: claimsForNote(topClaims, ["ask", "collaboration_edge"], 5) },
{ title: "risks to watch", claims: claimsForNote(topClaims, ["risk", "market_signal"], 4) },
].filter(section => section.claims.length);
const note = {
note_id: `cohort-field-note:${week.week_start || "undated"}`,
note_kind: "cohort_field_note",
week_start: week.week_start || "undated",
title: `Cohort field note: week of ${week.week_start || "undated"}`,
summary: `The transcript evidence for this week spans ${week.evidence_card_count || asArray(week.evidence_card_ids).length} source card(s), ${week.claim_count || topClaims.length} inferred claim(s), ${asArray(week.teams).length} team(s), and ${asArray(week.themes).length} recurring theme(s).`,
evidence_card_count: week.evidence_card_count || asArray(week.evidence_card_ids).length,
claim_count: week.claim_count || topClaims.length,
source_card_ids: asArray(week.evidence_card_ids).slice(0, 24),
teams: asArray(week.teams).slice(0, 16),
people: asArray(week.people).slice(0, 16),
themes: asArray(week.themes).slice(0, 10),
confidence: week.confidence || "low",
sharing_boundary: week.sharing_boundary || { max_surface: "cohort", raw_allowed: false },
review_status: "generated",
promotion_state: "needs-review",
sections,
};
return { ...note, markdown: fieldNoteMarkdown(note) };
});
}
function qaForSessionNote(items, limit = 4) {
return asArray(items).slice(0, limit).map(item => ({
question: compactSignalText(item.question, 180),
answer: compactSignalText(item.answer, 220),
confidence: item.confidence || "low",
evidence_level: item.evidence_level || "inferred",
source_card_ids: asArray(item.source_artifact_id || item.source).slice(0, 1),
teams: asArray(item.teams).slice(0, 8),
people: asArray(item.people).slice(0, 8),
}));
}
function sessionNoteMarkdown(note) {
const lines = [
`# ${note.title}`,
"",
"## the 60-second version",
"",
note.summary,
"",
];
for (const section of note.sections) {
if (!asArray(section.claims).length && !asArray(section.qa).length) continue;
lines.push(`## ${section.title}`, "");
for (const claim of asArray(section.claims)) {
lines.push(`- **${claim.label}.** ${claim.text}`);
}
for (const qa of asArray(section.qa)) {
lines.push(`- **Q.** ${qa.question}`);
if (qa.answer) lines.push(` **A.** ${qa.answer}`);
}
lines.push("");
}
if (asArray(note.teams).length || asArray(note.people).length) {
lines.push("## implicated records", "");
if (asArray(note.teams).length) lines.push(`Teams: ${asArray(note.teams).join(", ")}`);
if (asArray(note.people).length) lines.push(`People: ${asArray(note.people).join(", ")}`);
lines.push("");
}
lines.push(
"## provenance",
"",
`Generated from ${asArray(note.source_card_ids).join(", ") || note.note_id}. Review status: ${note.review_status}. Promotion state: ${note.promotion_state}. Raw transcript text is hidden.`,
"",
);
return lines.join("\n").trim();
}
function buildSessionNotes(evidenceCards) {
return asArray(evidenceCards)
.filter(card => card?.artifact_kind === "transcript_evidence_card")
.map((card) => {
const claims = asArray(card.claims);
const sections = [
{ title: "what changed", claims: claimsForNote(claims, ["action_item", "product_signal", "decision", "market_signal", "claim"], 5) },
{ title: "asks and risks", claims: claimsForNote(claims, ["ask", "risk", "collaboration_edge"], 5) },
{ title: "questions from the room", qa: qaForSessionNote(card.qa, 5) },
].filter(section => asArray(section.claims).length || asArray(section.qa).length);
const note = {
note_id: `cohort-session-note:${card.record_id || card.artifact_id}`,
note_kind: "cohort_session_note",
session_id: card.record_id || "",
title: card.title || `Session note: ${card.record_id || card.artifact_id}`,
summary: card.summary || `Generated from ${claims.length} transcript evidence claim(s).`,
date: isoDate(card.date),
week_start: card.week_start || "undated",
session_kind: card.session_kind || "",
evidence_card_count: 1,
claim_count: claims.length,
question_count: asArray(card.qa).length,
source_card_ids: asArray(card.artifact_id).slice(0, 1),
source: card.source || "",
teams: asArray(card.teams).slice(0, 16),
people: asArray(card.people).slice(0, 16),
themes: asArray(card.themes).slice(0, 10),
confidence: card.confidence || "low",
review_status: card.review_status || "generated",
promotion_state: card.surface_recommendation || "review_for_cohort",
sharing_boundary: card.sharing_boundary || { max_surface: "cohort", raw_allowed: false },
sections,
references: asArray(card.references).slice(0, 6),
};
return { ...note, markdown: sessionNoteMarkdown(note) };
})
.sort((a, b) => {
const ad = weekSortValue(a.date || a.week_start);
const bd = weekSortValue(b.date || b.week_start);
if (ad !== bd) return bd.localeCompare(ad);
return String(a.note_id).localeCompare(String(b.note_id));
});
}
function countBy(values) {
const out = {};
for (const value of values) {
const key = String(value || "unknown");
out[key] = (out[key] || 0) + 1;
}
return Object.fromEntries(Object.entries(out).sort((a, b) => a[0].localeCompare(b[0])));
}
function signalInventoryClaim(claim, card) {
return {
signal_id: claim.claim_id || `${card.artifact_id}:claim`,
signal_kind: "claim",
signal_type: claim.claim_type || "claim",
label: signalLabel(claim.claim_type),
text: compactSignalText(claim.text, 320),
source_card_id: card.artifact_id || "",
session_id: card.record_id || card.vault_id || "",
session_title: card.title || "",
date: isoDate(card.date),
week_start: card.week_start || "undated",
confidence: claim.confidence || card.confidence || "low",
evidence_level: claim.evidence_level || "inferred",
review_status: card.review_status || "generated",
promotion_state: card.surface_recommendation || "review_for_cohort",
sharing_boundary: card.sharing_boundary || { max_surface: "cohort", raw_allowed: false },
teams: asArray(claim.teams || card.teams).slice(0, 24),
people: asArray(claim.people || card.people).slice(0, 24),
themes: asArray(card.themes).slice(0, 10),
};
}
function signalInventoryQuestion(item, card) {
return {
signal_id: item.qa_id || `${card.artifact_id}:qa`,
signal_kind: "qa",
signal_type: "question",
label: "question",
text: compactSignalText(item.question, 260),
answer: compactSignalText(item.answer, 320),
source_card_id: card.artifact_id || "",
session_id: card.record_id || card.vault_id || "",
session_title: card.title || "",
date: isoDate(card.date),
week_start: card.week_start || "undated",
confidence: item.confidence || card.confidence || "low",
evidence_level: item.evidence_level || "inferred",
review_status: card.review_status || "generated",
promotion_state: card.surface_recommendation || "review_for_cohort",
sharing_boundary: card.sharing_boundary || { max_surface: "cohort", raw_allowed: false },
teams: asArray(item.teams || card.teams).slice(0, 24),
people: asArray(item.people || card.people).slice(0, 24),
themes: asArray(card.themes).slice(0, 10),
};
}
function buildSignalInventory(evidenceCards) {
const sources = asArray(evidenceCards)
.filter(card => card?.artifact_kind === "transcript_evidence_card")
.map((card) => {
const claimSignals = asArray(card.claims).map(claim => signalInventoryClaim(claim, card));
const qaSignals = asArray(card.qa).map(item => signalInventoryQuestion(item, card));
const signals = [...claimSignals, ...qaSignals];
return {
source_card_id: card.artifact_id || "",
session_id: card.record_id || card.vault_id || "",
title: card.title || card.record_id || card.artifact_id || "transcript evidence",
summary: card.summary || "",
date: isoDate(card.date),
week_start: card.week_start || "undated",
session_kind: card.session_kind || "",
consent: card.consent || "unknown",
confidence: card.confidence || "low",
review_status: card.review_status || "generated",
promotion_state: card.surface_recommendation || "review_for_cohort",
sharing_boundary: card.sharing_boundary || { max_surface: "cohort", raw_allowed: false },
claim_signal_count: claimSignals.length,
qa_signal_count: qaSignals.length,
total_signal_count: signals.length,
signal_type_counts: countBy(claimSignals.map(signal => signal.signal_type)),
teams: asArray(card.teams).slice(0, 24),
people: asArray(card.people).slice(0, 24),
themes: asArray(card.themes).slice(0, 10),
signals,
};
})
.sort((a, b) => {
const ad = weekSortValue(a.date || a.week_start);
const bd = weekSortValue(b.date || b.week_start);
if (ad !== bd) return bd.localeCompare(ad);
return String(a.source_card_id).localeCompare(String(b.source_card_id));
});
const allSignals = sources.flatMap(source => source.signals);
const claimSignals = allSignals.filter(signal => signal.signal_kind === "claim");
const qaSignals = allSignals.filter(signal => signal.signal_kind === "qa");
return {
schema_version: 1,
source_card_count: sources.length,
total_signal_count: allSignals.length,
claim_signal_count: claimSignals.length,
qa_signal_count: qaSignals.length,
signal_type_counts: countBy(claimSignals.map(signal => signal.signal_type)),
review_status_counts: countBy(sources.map(source => source.review_status)),
coverage: {
sources_without_claims: sources.filter(source => source.claim_signal_count === 0).map(source => source.source_card_id),
sources_without_questions: sources.filter(source => source.qa_signal_count === 0).map(source => source.source_card_id),
min_signals_per_source: sources.length ? Math.min(...sources.map(source => source.total_signal_count)) : 0,
max_signals_per_source: sources.length ? Math.max(...sources.map(source => source.total_signal_count)) : 0,
},
sources,
};
}
const PROJECT_WEEK_PRIVACY = {
max_surface: "cohort",
raw_allowed: false,
detail_level: "project-level derived status; raw transcript and person-level detail excluded",
};
const GENERIC_PROJECT_SIGNAL_TOKENS = new Set([
"across", "after", "agent", "agentic", "agents", "apps", "based", "before",
"build", "buyer", "buyers", "coding", "cohort", "collaboration", "community",
"consumer", "conversion", "customer", "customers", "data", "demo", "design",
"aggregation", "broad", "control", "delegate", "distribution", "durable",
"either", "enough", "evidence", "first", "giving", "hands",
"market", "milestone", "model", "native", "often", "paid", "partner",
"people", "privacy", "product", "project", "projects", "quality", "research",
"retention", "review", "signal", "single", "solution", "source", "status",
"technical", "toward", "users", "without", "workflow", "workflows",
]);
function projectSnapshotKeywords(team = {}) {
const journey = team.journey || {};
const values = [
...recordKeywords(team),
journey.primary_bottleneck,
journey.icp,
journey.problem,
journey.solution,
journey.evidence_notes,
journey.next_milestone,
];
return Array.from(new Set(values.flatMap(keywordTokens))).slice(0, 80);
}
function projectIdentityTokens(team = {}) {
const journey = team.journey || {};
const values = [
team.record_id,
team.name,
team.focus,
team.domain,
team.now,
asArray(team.skill_areas).join(" "),
journey.icp,
journey.problem,
journey.solution,
journey.next_milestone,
];
return Array.from(new Set(values.flatMap(keywordTokens)))
.filter(token => token.length >= 5 && !GENERIC_PROJECT_SIGNAL_TOKENS.has(token))
.slice(0, 60);
}
function projectNames(team = {}, { includeTokens = false } = {}) {
const fullNames = [
team.record_id,
team.name,
String(team.name || "").replace(/[^a-z0-9]+/gi, " "),
]
.map(value => String(value || "").toLowerCase().trim())
.filter(value => value.length >= 3);
if (!includeTokens) return fullNames;
const tokens = fullNames
.flatMap(keywordTokens)
.filter(token => token.length >= 5 && !GENERIC_PROJECT_SIGNAL_TOKENS.has(token));
return Array.from(new Set([...fullNames, ...tokens]));
}
function projectClaimMatchDetails(claim, team = {}, peerTeams = []) {
const text = String(claim?.text || "").toLowerCase();
const directNameMatch = projectNames(team).some(name => text.includes(name));
const otherNames = asArray(peerTeams)
.filter(peer => String(peer?.record_id || "") !== String(team?.record_id || ""))
.flatMap(peer => projectNames(peer, { includeTokens: true }));
const directOtherProjectMatch = otherNames.some(name => text.includes(name));
const matchedTokens = projectIdentityTokens(team).filter(token => text.includes(token)).slice(0, 12);
const teamMentionCount = asArray(claim?.teams).length;
const isProjectSpecific = directNameMatch
|| (!directOtherProjectMatch && matchedTokens.length >= (teamMentionCount > 1 ? 2 : 1))
|| teamMentionCount <= 1;
return {
direct_name_match: directNameMatch,
direct_other_project_match: directOtherProjectMatch,
matched_tokens: matchedTokens,
is_project_specific: isProjectSpecific,
};
}
function declaredBottleneckCategory(value) {
const text = String(value || "").toLowerCase();
if (!text) return "not declared";
if (/\b(gtm|icp|market|buyer|customer|retention|monetization|monetisation|sales|distribution)\b/.test(text)) return "GTM / ICP";
if (/\b(solution|technical|risk|architecture|security|privacy|verification|proof|quality|infra)\b/.test(text)) return "Solution Quality";
if (/\b(product|workflow|demo|prototype|ux|shipping|mvp)\b/.test(text)) return "Product / Workflow";
if (/\b(intro|mentor|support|dogfood|partner|collaboration)\b/.test(text)) return "Cohort Support";
return labelize(value);
}
function observedCategoryWeights(claims) {
const weights = {
"GTM / ICP": 0,
"Solution Quality": 0,
"Product / Workflow": 0,
"Cohort Support": 0,
};
for (const claim of asArray(claims)) {
const type = String(claim.claim_type || "claim");
const text = `${type} ${claim.text || ""}`.toLowerCase();
if (/\b(user|users|customer|buyer|icp|market|gtm|distribution|paid|paying|pilot|retention|moneti[sz]ation|pricing|signup|conversion|design partner|community|sales)\b/.test(text)) {
weights["GTM / ICP"] += type === "market_signal" ? 4 : 3;
}
if (/\b(technical|architecture|tee|attestation|attested|verify|verification|proof|security|privacy|credential|database|deploy|deployment|enclave|latency|scale|failure|risk|registry|postgres|dstack)\b/.test(text)) {
weights["Solution Quality"] += type === "risk" ? 4 : 3;
}
if (/\b(product|workflow|demo|ship|build|prototype|poc|mvp|feature|ux|agent|tool|app|integration|api|loop|milestone)\b/.test(text)) {
weights["Product / Workflow"] += ["product_signal", "action_item", "decision"].includes(type) ? 4 : 2;
}
if (/\b(ask|intro|mentor|feedback|dogfood|partner|collaboration|office hour|pair|help|route|review)\b/.test(text)) {
weights["Cohort Support"] += ["ask", "collaboration_edge"].includes(type) ? 4 : 2;
}
}
return weights;
}