-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.ts
More file actions
1319 lines (1258 loc) · 52.1 KB
/
Copy pathmain.ts
File metadata and controls
1319 lines (1258 loc) · 52.1 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
/* global activeDocument, window -- Allow document/window references for context menu and resize handling in Obsidian/Electron environment (ESLint browser globals) */
import { Menu, Notice, Plugin, TFile, type Editor, MarkdownView } from "obsidian";
import { SimplicialModel } from "./core/model";
import { normalizeKey, relationKey, resolveNodeId } from "./core/normalize";
import { logger } from "./core/logger";
import { RelationHistory, syncEncounterPersistence, type RelationEventInput } from "./core/history";
import type { SubsetScorer } from "./core/diagnostics";
import { ActivationState, createKernel, propagate, type ActivationSource } from "./core/activation";
import { createSubsetScorer } from "./data/inference/subset-scorer";
import { suggestEncounters } from "./data/inference/encounters";
import type { Hyperedge, PluginSettings, RelationKey, RelationSelection, Simplex } from "./core/types";
import { deserializeReinforcement, serializeReinforcement, type ReinforcementState } from "./data/interactions";
import {
VIEW_TYPE_SIMPLICIAL,
VIEW_TYPE_SIMPLICIAL_DYNAMICS,
VIEW_TYPE_SIMPLICIAL_PANEL,
VIEW_TYPE_SIMPLICIAL_PERSISTENCE,
VIEW_TYPE_SIMPLICIAL_SHEAF,
} from "./core/types";
import { analyzeSheaf } from "./core/sheaf";
import { buildGlobalRoles, buildSheafData, readStoredSheaf } from "./data/sheaf-store";
import {
ensureCentralFile,
getDefaultSettings,
removeHyperedgeFromManagedFile,
removeSimplexFromManagedFile,
readCentralFileState,
writeHyperedgeToCentralFile,
writeHyperedgeToSourceNote,
writeSimplexToCentralFile,
writeSimplexToSourceNote,
} from "./data/persistence";
import { migrateSettings } from "./core/settings";
import { HistoryStore } from "./data/history-store";
import { VaultIndex } from "./data/vault-index";
import { InteractionController } from "./interaction/controller";
import { LayoutEngine } from "./layout/engine";
import { Renderer } from "./render/renderer";
import { CycleHighlightBus } from "./render/cycle-highlight";
import { computePersistenceEvents } from "./core/filtration";
import { TopologyAnalysisService } from "./core/topology/analysis-service";
import { CreateSimplexModal, type RelationDraft } from "./ui/create-simplex-modal";
import { PromoteEncounterModal } from "./ui/promote-encounter-modal";
import { createPromotedNote, MetadataPanel } from "./ui/panel";
import { DynamicsLabView } from "./ui/dynamics-view";
import { PersistenceView } from "./ui/persistence-view";
import { SheafView } from "./ui/sheaf-view";
import { SimplicialView } from "./ui/view";
import { SimplicialSettingTab } from "./settings/setting-tab";
export default class SimplicialPlugin extends Plugin {
settings!: PluginSettings;
model!: SimplicialModel;
index!: VaultIndex;
engine!: LayoutEngine;
renderer!: Renderer;
controller!: InteractionController;
history!: RelationHistory;
historyStore!: HistoryStore;
panelView: MetadataPanel | null = null;
simplicialView: SimplicialView | null = null;
sheafView: SheafView | null = null;
persistenceView: PersistenceView | null = null;
/** The one seam between the barcode and whatever surface draws representative cycles. */
readonly cycleHighlightBus = new CycleHighlightBus();
topologyAnalysis!: TopologyAnalysisService;
private releaseCycleHighlightTarget: (() => void) | null = null;
private saveTimer: number | null = null;
private rescanTimer: number | null = null;
/**
* Rebuilt after each full scan. Building the raw signal graph is the expensive
* part, so it happens once per scan rather than once per panel render.
*/
private subsetScorer: SubsetScorer | null = null;
/** HG-19. Ephemeral attention. Never written to a note; see `core/activation.ts`. */
private activation = new ActivationState();
private activationTimer: number | null = null;
async onload(): Promise<void> {
const saved = ((await this.loadData()) ?? {}) as Partial<PluginSettings>;
this.settings = migrateSettings(getDefaultSettings(), saved);
const applyPerformanceDefaults = !this.settings.performanceDefaultsV045Applied;
if (applyPerformanceDefaults) {
// v0.4.5 makes the two expensive visual analyses explicitly opt-in, even
// for vaults whose earlier data.json left them enabled.
this.settings.enableBettiComputation = false;
this.settings.formalMode = true;
this.settings.performanceDefaultsV045Applied = true;
}
const showTopologyCorrectionNotice = !this.settings.topologyCorrectionNoticeShown;
if (this.settings.maxRenderedDim === 3) {
this.settings.maxRenderedDim = 12;
}
logger.info("plugin", "Loading plugin", {
persistenceMode: this.settings.persistenceMode,
centralFile: this.settings.centralFile,
showEdges: this.settings.showEdges,
showClusters: this.settings.showClusters,
showCores: this.settings.showCores,
pinnedNodeCount: Object.keys(this.settings.pinnedNodes).length,
});
this.model = new SimplicialModel();
this.history = new RelationHistory();
this.historyStore = new HistoryStore(this.app, this.settings.historyFile);
if (this.settings.enableRelationHistory) {
this.history.onAppend((event) => this.historyStore.record(event));
}
this.engine = new LayoutEngine();
this.engine.configure({
noiseAmount: this.settings.noiseAmount,
sleepThreshold: this.settings.sleepThreshold,
repulsionStrength: this.settings.repulsionStrength,
cohesionStrength: this.settings.cohesionStrength,
gravityStrength: this.settings.gravityStrength,
dampingFactor: this.settings.dampingFactor,
boundaryPadding: this.settings.boundaryPadding,
sparseEdgeLength: this.settings.sparseEdgeLength,
sparseGravityBoost: this.settings.sparseGravityBoost,
});
this.controller = new InteractionController(
this.model,
() => this.engine.wake(),
(selection) => this.panelView?.setSelection(selection),
(selection) => void this.openPanel(selection, false),
() => this.queueSaveSettings(),
(tracker) => this.saveInteractionState(tracker),
);
// Restore interaction state if exists
const savedInteractions = this.settings.interactionState;
if (savedInteractions) {
this.controller.setInteractionTracker(deserializeReinforcement(savedInteractions));
}
this.renderer = new Renderer(this.model, this.engine, this.controller, this.settings, {
onContextMenu: (target, event) => this.openCanvasContextMenu(target, event),
onLassoCreate: (nodeIds) => void this.openCreateSimplexModal(nodeIds, nodeIds[0] ?? ""),
onNodeOpen: (nodeId) => void this.openNodeNote(nodeId),
onHoleHover: (hole, explanation) => {
if (hole && explanation) {
// Show subtle notice about the hole on hover
const nodeNames = hole.boundaryNodes.map((id) => id.split("/").pop()?.replace(/\.md$/, "") ?? id);
new Notice(`Missing face: ${explanation.headline}\n${nodeNames.join(" · ")}`, 3000);
}
},
onHoleClick: (hole, explanation) => {
// On hole click, show a more prominent notice with the prompt
const nodeNames = hole.boundaryNodes.map((id) => id.split("/").pop()?.replace(/\.md$/, "") ?? id);
new Notice(`🕳️ ${explanation.headline}\n\nNotes: ${nodeNames.join(" · ")}\n\n${explanation.prompt}`, 8000);
},
});
this.index = new VaultIndex(
this.app,
this.model,
this.settings,
() => this.engine.wake(),
(hyperedge) => this.recordEncounter(hyperedge, "parser"),
);
this.topologyAnalysis = new TopologyAnalysisService(this.model);
// The slider's birth/death lane is fed from the same pairing the barcode draws, so
// the two surfaces cannot disagree. Until a reduction has run there are no markers,
// rather than markers guessed from local simplex appearances.
this.topologyAnalysis.subscribe((state) => {
if (state.status !== "ready" || !state.result) return;
this.simplicialView?.setPersistenceEvents(computePersistenceEvents(state.result.intervals));
});
this.releaseCycleHighlightTarget = this.cycleHighlightBus.registerTarget(this.renderer);
this.restorePinnedNodes();
this.registerView(VIEW_TYPE_SIMPLICIAL, (leaf) => {
const view = new SimplicialView(
leaf,
this.model,
this.renderer,
this.settings,
() => {
this.applyLiveSettings();
this.queueSaveSettings();
},
(reason, delayMs) => this.scheduleFullScan(reason, delayMs),
{
recordEncounter: () => this.createEncounterFromOpenNote(),
openContextuality: () => void this.activateSheafView(),
findExpressiveView: () => this.findExpressiveView(),
},
this.history,
);
this.simplicialView = view;
return view;
});
this.registerView(VIEW_TYPE_SIMPLICIAL_PANEL, (leaf) => {
const panel = new MetadataPanel(leaf, this.model);
panel.setActions({
saveMetadata: (simplexKey, updates) => this.persistSimplexMetadata(simplexKey, updates),
promoteSimplex: (simplexKey) => this.promoteSimplex(simplexKey),
dissolveSimplex: (simplexKey) => this.dissolveSimplex(simplexKey),
relaxSimplex: (simplexKey) => this.relaxSimplex(simplexKey),
saveHyperedgeMetadata: (key, updates) => this.saveHyperedgeMetadata(key, updates),
promoteEncounter: (key) => this.promoteEncounter(key),
crystallizeEncounter: (key) => this.crystallizeEncounter(key),
dissolveHyperedge: (key) => this.dissolveHyperedge(key),
confirmSuggestedEncounter: (key) => this.confirmSuggestedEncounter(key),
});
panel.setHistory(this.history);
panel.setSettings(this.settings);
panel.setSubsetScorer(this.subsetScorer);
this.panelView = panel;
return panel;
});
this.registerView(VIEW_TYPE_SIMPLICIAL_SHEAF, (leaf) => {
const view = new SheafView(leaf, this.model, this.settings, async () => {
await this.saveSettings();
this.refreshSheafAnalysis();
});
this.sheafView = view;
return view;
});
this.addCommand({
id: "open-contextuality-lab",
name: "Open contextuality lab",
callback: () => void this.activateSheafView(),
});
if (this.settings.enablePersistenceView) {
this.registerView(VIEW_TYPE_SIMPLICIAL_PERSISTENCE, (leaf) => {
const view = new PersistenceView(
leaf,
this.model,
this.settings,
this.topologyAnalysis,
this.cycleHighlightBus,
);
this.persistenceView = view;
return view;
});
this.addCommand({
id: "open-persistence-xray",
name: "Open persistence X-ray",
callback: () => void this.activatePersistenceView(),
});
}
if (this.settings.enableDynamicsLab) {
this.registerView(VIEW_TYPE_SIMPLICIAL_DYNAMICS, (leaf) => new DynamicsLabView(leaf, this.model));
this.addCommand({
id: "open-dynamics-lab",
name: "Open dynamics lab",
callback: () => void this.activateDynamicsLab(),
});
}
this.addRibbonIcon("network", "Simplicial graph", () => void this.activateView());
this.addCommand({
id: "open-simplicial",
name: "Open simplicial graph",
callback: () => void this.activateView(),
});
this.addCommand({
id: "find-expressive-view",
name: "Find expressive view (suggestion-only)",
callback: () => void this.findExpressiveView(),
});
this.addCommand({
id: "insert-simplex-symbol",
name: "Insert triangle simplex marker",
editorCallback: (editor: Editor) => editor.replaceSelection("\u25b3 "),
});
this.addCommand({
id: "insert-hyperedge-symbol",
name: "Insert encounter hyperedge marker",
editorCallback: (editor: Editor) => editor.replaceSelection("◇ "),
});
this.addCommand({
id: "form-simplex-from-open-note",
name: "Simplicial: form simplex from open note",
callback: () => void this.formSimplexFromOpenNote(),
});
this.addCommand({
id: "create-encounter",
name: "Simplicial: create encounter from open note",
callback: () => void this.createEncounterFromOpenNote(),
});
this.addCommand({
id: "toggle-edges",
name: "Toggle simplicial edges",
callback: () => {
if (activeDocument.activeElement?.tagName === "INPUT" || activeDocument.activeElement?.tagName === "TEXTAREA")
return;
this.settings.showEdges = !this.settings.showEdges;
void this.saveSettings();
this.renderer.render();
},
});
this.addCommand({
id: "toggle-clusters",
name: "Toggle simplicial clusters",
callback: () => {
if (activeDocument.activeElement?.tagName === "INPUT" || activeDocument.activeElement?.tagName === "TEXTAREA")
return;
this.settings.showClusters = !this.settings.showClusters;
void this.saveSettings();
this.renderer.render();
},
});
this.addCommand({
id: "toggle-cores",
name: "Toggle simplicial cores",
callback: () => {
if (activeDocument.activeElement?.tagName === "INPUT" || activeDocument.activeElement?.tagName === "TEXTAREA")
return;
this.settings.showCores = !this.settings.showCores;
void this.saveSettings();
this.renderer.render();
},
});
this.addCommand({
id: "clear-simplicial-focus",
name: "Clear simplicial focus",
callback: () => {
if (activeDocument.activeElement?.tagName === "INPUT" || activeDocument.activeElement?.tagName === "TEXTAREA") {
(activeDocument.activeElement as HTMLElement).blur();
return;
}
this.controller.clearFocus();
this.renderer.render();
},
});
this.addCommand({
id: "focus-hovered-node",
name: "Focus hovered simplicial node",
callback: () => {
if (activeDocument.activeElement?.tagName === "INPUT" || activeDocument.activeElement?.tagName === "TEXTAREA")
return;
this.controller.focusHoveredNode();
if (this.controller.lockedNodeId) this.registerActivation(this.controller.lockedNodeId, "focused");
this.renderer.render();
},
});
this.addCommand({
id: "open-hovered-simplex-panel",
name: "Open metadata panel for hovered simplex",
callback: () => {
if (activeDocument.activeElement?.tagName === "INPUT" || activeDocument.activeElement?.tagName === "TEXTAREA")
return;
void this.openPanelForCurrentSelection();
},
});
this.addSettingTab(new SimplicialSettingTab(this.app, this));
this.activation.configure({ halfLifeMinutes: this.settings.activationDecayHalfLifeMinutes });
this.registerEvent(
this.app.workspace.on("file-open", (file) => {
if (file) this.registerActivation(file.path, "opened");
}),
);
this.registerEvent(
this.app.vault.on("modify", (file) => {
if (file instanceof TFile) this.registerActivation(file.path, "edited");
}),
);
this.model.subscribe(() => {
this.engine.wake();
});
await this.logPersistenceState();
if (this.settings.enableRelationHistory) {
await this.historyStore.load(this.history);
this.syncEncounterState();
}
this.scheduleFullScan("startup", 0);
this.app.workspace.onLayoutReady(() => {
this.scheduleFullScan("layout-ready", 50);
if (showTopologyCorrectionNotice) {
this.settings.topologyCorrectionNoticeShown = true;
new Notice(
"Topology corrected in v0.4.5: β₁/β₂ are now actual homology ranks. Earlier values counted local missing-face motifs, and each empty triangle was counted three times. No note data was changed.",
10000,
);
}
if (showTopologyCorrectionNotice || applyPerformanceDefaults) void this.saveSettings();
});
this.registerEvent(this.app.metadataCache.on("resolved", () => this.scheduleFullScan("metadata-resolved", 50)));
}
onunload(): void {
if (this.rescanTimer !== null) window.clearTimeout(this.rescanTimer);
if (this.activationTimer !== null) window.clearTimeout(this.activationTimer);
logger.info("plugin", "Unloading plugin", {
indexedNodeCount: this.model.nodes.size,
simplexCount: this.model.simplices.size,
hyperedgeCount: this.model.hyperedges.size,
historyEventCount: this.history.size,
});
this.renderer.destroy();
this.index.destroy();
// Terminates the topology worker and revokes its blob URL. A plugin disable, reload
// or vault switch must not leave one running.
this.releaseCycleHighlightTarget?.();
this.topologyAnalysis.dispose();
}
private restorePinnedNodes(): void {
logger.info("plugin", "Restoring pinned nodes", {
pinnedNodeCount: Object.keys(this.settings.pinnedNodes).length,
});
Object.entries(this.settings.pinnedNodes).forEach(([nodeId, pos]) => {
this.model.setNode(nodeId, { isPinned: true, px: pos.px, py: pos.py });
});
}
async saveSettings(): Promise<void> {
this.applyLiveSettings();
const pinned: PluginSettings["pinnedNodes"] = {};
this.model.getAllNodes().forEach((node) => {
if (node.isPinned) pinned[node.id] = { px: node.px, py: node.py };
});
this.settings.pinnedNodes = pinned;
await this.saveData(this.settings);
this.index?.updateSettings(this.settings);
logger.info("plugin", "Saved persistence state", {
persistenceMode: this.settings.persistenceMode,
centralFile: this.settings.centralFile,
pinnedNodeCount: Object.keys(this.settings.pinnedNodes).length,
filters: {
edges: this.settings.showEdges,
clusters: this.settings.showClusters,
cores: this.settings.showCores,
},
inference: {
linkBaseline: this.settings.linkGraphBaseline,
enabled: this.settings.enableInferredEdges,
threshold: this.settings.inferenceThreshold,
suggestions: this.settings.showSuggestions,
suggestionThreshold: this.settings.suggestionThreshold,
},
layout: {
repulsion: this.settings.repulsionStrength,
cohesion: this.settings.cohesionStrength,
gravity: this.settings.gravityStrength,
damping: this.settings.dampingFactor,
boundaryPadding: this.settings.boundaryPadding,
sparseEdgeLength: this.settings.sparseEdgeLength,
sparseGravityBoost: this.settings.sparseGravityBoost,
labelDensity: this.settings.labelDensity,
renderFilterMetric: this.settings.renderFilterMetric,
renderFilterThreshold: this.settings.renderFilterThreshold,
},
commandUi: {
simplexSize: this.settings.commandSimplexSize,
autoOpenPanel: this.settings.commandAutoOpenPanel,
metadataHoverDelayMs: this.settings.metadataHoverDelayMs,
formalMode: this.settings.formalMode,
},
});
}
/**
* One live-update contract for every settings surface. Visual changes redraw,
* while physics changes are copied into the engine before waking it.
*/
applyLiveSettings(): void {
// Performance lock for v0.4.5: these views are unavailable, not merely
// default-off, so no settings surface can reactivate them indirectly.
this.settings.enableBettiComputation = false;
this.settings.formalMode = true;
this.engine.configure({
noiseAmount: this.settings.noiseAmount,
sleepThreshold: this.settings.sleepThreshold,
repulsionStrength: this.settings.repulsionStrength,
cohesionStrength: this.settings.cohesionStrength,
gravityStrength: this.settings.gravityStrength,
dampingFactor: this.settings.dampingFactor,
boundaryPadding: this.settings.boundaryPadding,
sparseEdgeLength: this.settings.sparseEdgeLength,
sparseGravityBoost: this.settings.sparseGravityBoost,
});
this.engine.refresh();
}
private queueSaveSettings(): void {
if (this.saveTimer !== null) window.clearTimeout(this.saveTimer);
this.saveTimer = window.setTimeout(() => {
this.saveTimer = null;
void this.saveSettings();
}, 150);
}
private saveInteractionState(tracker: ReinforcementState): void {
this.settings.interactionState = serializeReinforcement(tracker);
this.queueSaveSettings();
}
async activateView(): Promise<void> {
await this.app.workspace.getLeaf(true).setViewState({ type: VIEW_TYPE_SIMPLICIAL, active: true });
const right = this.app.workspace.getRightLeaf(false);
if (right) {
await right.setViewState({ type: VIEW_TYPE_SIMPLICIAL_PANEL, active: false });
}
}
async activatePersistenceView(): Promise<void> {
await this.app.workspace.getLeaf(true).setViewState({ type: VIEW_TYPE_SIMPLICIAL_PERSISTENCE, active: true });
}
async activateDynamicsLab(): Promise<void> {
await this.app.workspace.getLeaf(true).setViewState({ type: VIEW_TYPE_SIMPLICIAL_DYNAMICS, active: true });
}
async activateSheafView(): Promise<void> {
await this.app.workspace.getLeaf(true).setViewState({ type: VIEW_TYPE_SIMPLICIAL_SHEAF, active: true });
}
refreshSheafAnalysis(): void {
const stored = readStoredSheaf(this.settings);
if (stored.contexts.length === 0) {
this.renderer.setSheafReport(null);
this.sheafView?.refresh();
return;
}
const data = buildSheafData(this.model, stored, buildGlobalRoles(this.app, this.model));
this.renderer.setSheafReport(analyzeSheaf(this.model, data));
this.sheafView?.refresh();
}
private async persistSimplexMetadata(
simplexKey: string,
updates: { label?: string; weight?: number },
): Promise<void> {
logger.info("plugin", "Persisting simplex metadata", {
simplexKey,
updates,
persistenceMode: this.settings.persistenceMode,
});
this.model.updateMetadata(simplexKey, updates);
const simplex = this.model.getSimplex(simplexKey);
if (!simplex?.sourcePath) {
logger.warn("plugin", "Simplex has no sourcePath; only settings state will be saved", {
simplexKey,
});
await this.saveSettings();
return;
}
await this.persistSimplex(simplex);
await this.saveSettings();
}
private formSimplexFromOpenNote(): void {
const view = this.app.workspace.getActiveViewOfType(MarkdownView);
const file = view?.file;
if (!file) {
new Notice("Open a note first.");
return;
}
const cache = this.app.metadataCache.getFileCache(file);
const links = cache?.links?.map((link) => link.link) ?? [];
const resolvedLinks = links
.map((link) => this.app.metadataCache.getFirstLinkpathDest(link, file.path)?.path ?? link)
.filter((path, index, all) => all.indexOf(path) === index);
const desiredSize = Math.max(2, Math.min(6, this.settings.commandSimplexSize));
const nodes = [file.path, ...resolvedLinks].slice(0, desiredSize);
logger.info("plugin", "Form simplex from open note requested", {
sourcePath: file.path,
linkCount: links.length,
desiredSize,
proposedNodes: nodes,
});
if (nodes.length < desiredSize) {
new Notice(`Need at least ${desiredSize - 1} resolvable outgoing links to form this simplex.`);
return;
}
this.openCreateSimplexModal(nodes, file.path);
}
// --- hypergraph layer -----------------------------------------------------
/**
* Record that a configuration was encountered.
*
* A rescan is not a new encounter: re-reading the same `◇` line on every startup
* would inflate recurrence into meaninglessness, so the parser only ever records
* a set it has never seen. Deliberate user acts do record a repeat.
*/
private recordEncounter(hyperedge: Hyperedge, actor: RelationEventInput["actor"]): void {
const prior = this.history.occurrencesOf(hyperedge.nodes);
if (actor === "parser" && prior.length > 0) return;
this.history.append({
type: prior.length > 0 ? "recurred" : "encountered",
kind: "hyperedge",
nodes: hyperedge.nodes,
actor,
...(hyperedge.label || hyperedge.mode
? {
detail: {
...(hyperedge.label ? { label: hyperedge.label } : {}),
...(hyperedge.mode ? { mode: hyperedge.mode } : {}),
},
}
: {}),
});
this.syncEncounterState();
}
private syncEncounterState(): void {
syncEncounterPersistence(this.model, this.history, this.settings.encounterRecurrenceThreshold);
}
private refreshEncounterSuggestions(): number {
for (const [key, hyperedge] of [...this.model.hyperedges]) {
if (hyperedge.suggested && hyperedge.suggestionSource === "encounter-discovery") this.model.removeHyperedge(key);
}
if (!this.settings.enableEncounterSuggestions) return 0;
const suggestions = suggestEncounters(this.model, {
threshold: this.settings.encounterSuggestionThreshold,
limit: this.settings.maxEncounterSuggestions,
...(this.subsetScorer ? { score: this.subsetScorer } : {}),
});
suggestions.forEach((candidate) => this.model.addHyperedge(candidate));
return suggestions.length;
}
private async confirmSuggestedEncounter(key: RelationKey): Promise<void> {
const candidate = this.model.getHyperedge(key);
if (!candidate?.suggested) return;
const sourcePath =
this.settings.persistenceMode === "central-file" ? this.settings.centralFile : candidate.nodes[0];
const confirmed: Hyperedge = {
...candidate,
suggested: false,
suggestionSource: undefined,
inferred: false,
mode: "encounter",
occurredAt: Date.now(),
persistence: "momentary",
sourcePath,
};
this.model.addHyperedge(confirmed);
this.recordEncounter(confirmed, "user");
await this.persistHyperedge(this.model.getHyperedge(key)!);
this.panelView?.setSelection({ kind: "hyperedge", key });
new Notice("Encounter confirmed and recorded.");
}
/**
* HG-19. Record that a note is in play and spread that to whatever it is in
* relation with.
*
* The hypergraph kernel is the one used for emphasis, because that is the claim
* this plugin makes about attention: it is a group being present at once, not a
* signal walking along edges. The other two exist to be compared against it in
* the Dynamics Lab, not to drive the canvas.
*/
private registerActivation(nodeId: string, source: ActivationSource): void {
if (!this.model.nodes.has(nodeId)) return;
this.activation.register(nodeId, source);
this.refreshActivation();
}
/**
* Attention decays continuously, so the field is recomputed on a slow timer while
* anything is still warm and then stops. There is nothing to persist and nothing
* to clean up in a note — the state exists only for as long as the plugin runs.
*/
private refreshActivation(): void {
if (this.activationTimer !== null) window.clearTimeout(this.activationTimer);
const seed = this.activation.field();
const kernel = createKernel(this.model, "hypergraph");
this.renderer.setActivation(propagate(kernel, seed, 3));
this.engine.wake();
if (seed.size === 0) return;
this.activationTimer = window.setTimeout(() => {
this.activationTimer = null;
this.refreshActivation();
}, 20000);
}
/** HG-12's evidence source. Absent until the vault has been scanned at least once. */
private rebuildSubsetScorer(): void {
const contexts = this.index.getInferenceContexts();
this.subsetScorer = contexts.length > 0 ? createSubsetScorer(contexts, this.settings) : null;
this.panelView?.setSubsetScorer(this.subsetScorer);
}
private createEncounterFromOpenNote(): void {
const view = this.app.workspace.getActiveViewOfType(MarkdownView);
const file = view?.file;
if (!file) {
new Notice("Open a note first.");
return;
}
const cache = this.app.metadataCache.getFileCache(file);
const links = cache?.links?.map((link) => link.link) ?? [];
const resolvedLinks = links
.map((link) => this.app.metadataCache.getFirstLinkpathDest(link, file.path)?.path ?? link)
.filter((path, index, all) => all.indexOf(path) === index);
const nodes = [file.path, ...resolvedLinks];
if (nodes.length < 2) {
new Notice("Need at least one resolvable outgoing link to record an encounter.");
return;
}
logger.info("plugin", "Create encounter from open note requested", {
sourcePath: file.path,
participantCount: nodes.length,
});
this.openCreateRelationModal(nodes, file.path, "hyperedge");
}
private async createHyperedge(draft: RelationDraft, sourcePath: string): Promise<RelationKey> {
const nodes = draft.nodes.map((node) => this.resolveDraftNode(node, sourcePath));
const owner = this.settings.persistenceMode === "central-file" ? this.settings.centralFile : sourcePath;
const hyperedge: Hyperedge = {
nodes,
label: draft.label,
weight: draft.weight,
mode: draft.mode ?? "encounter",
occurredAt: Date.now(),
persistence: "momentary",
sourcePath: owner,
};
const key = this.model.addHyperedge(hyperedge);
if (!key) return "";
this.recordEncounter({ ...hyperedge, nodes: this.model.getHyperedge(key)!.nodes }, "user");
await this.persistHyperedge(this.model.getHyperedge(key)!);
return key;
}
private async persistHyperedge(hyperedge: Hyperedge): Promise<void> {
if (hyperedge.suggested) return;
const shouldWriteCentral =
hyperedge.sourcePath === this.settings.centralFile ||
(!hyperedge.sourcePath && this.settings.persistenceMode === "central-file");
if (shouldWriteCentral) {
const { file, content } = await writeHyperedgeToCentralFile(this.app, this.settings.centralFile, {
...hyperedge,
sourcePath: this.settings.centralFile,
});
await this.app.vault.modify(file, content);
this.index.recordWrite(file.path, content);
return;
}
const file = this.app.vault.getAbstractFileByPath(hyperedge.sourcePath ?? "");
if (!(file instanceof TFile)) {
logger.warn("plugin", "Unable to persist hyperedge to source note", {
nodeKey: normalizeKey(hyperedge.nodes),
sourcePath: hyperedge.sourcePath,
});
return;
}
const content = await writeHyperedgeToSourceNote(this.app, file, hyperedge);
await this.app.vault.modify(file, content);
this.index.recordWrite(file.path, content);
}
private async removeHyperedgeFromNote(hyperedge: Hyperedge): Promise<void> {
const nodeKey = normalizeKey(hyperedge.nodes);
const shouldWriteCentral =
hyperedge.sourcePath === this.settings.centralFile ||
(!hyperedge.sourcePath && this.settings.persistenceMode === "central-file");
const file = shouldWriteCentral
? await ensureCentralFile(this.app, this.settings.centralFile)
: this.app.vault.getAbstractFileByPath(hyperedge.sourcePath ?? "");
if (!(file instanceof TFile)) return;
const content = await removeHyperedgeFromManagedFile(this.app, file, nodeKey);
await this.app.vault.modify(file, content);
this.index.recordWrite(file.path, content);
}
/** HG-08. Always user-initiated, always confirmed — nothing promotes on its own. */
private promoteEncounter(hyperedgeKey: RelationKey): void {
const hyperedge = this.model.getHyperedge(hyperedgeKey);
if (!hyperedge) return;
const faces = this.model.facesImpliedByPromotion(hyperedgeKey);
new PromoteEncounterModal(this.app, hyperedge.nodes, faces, async () => {
const result = this.model.promoteToSimplex(hyperedgeKey);
if (!result) return;
this.history.append({
type: "promoted",
kind: "hyperedge",
nodes: hyperedge.nodes,
actor: "user",
prior: { persistence: hyperedge.persistence ?? "momentary" },
detail: { createdFaceCount: result.createdFaces.length },
});
const simplex = this.model.getSimplex(result.simplexKey);
if (simplex) await this.persistSimplex(simplex);
await this.persistHyperedge(this.model.getHyperedge(hyperedgeKey)!);
this.controller.selectSimplex(result.simplexKey);
await this.openPanel({ kind: "simplex", key: result.simplexKey }, false);
new Notice(
result.createdFaces.length > 0
? `Promoted. ${result.createdFaces.length} face${result.createdFaces.length === 1 ? "" : "s"} asserted.`
: "Promoted. Every implied face already existed.",
);
}).open();
}
/** HG-09. Withdraws the closure claim; the group relation survives. */
private async relaxSimplex(simplexKey: string): Promise<void> {
const simplex = this.model.getSimplex(simplexKey);
if (!simplex || simplex.autoGenerated) return;
const hyperedgeKey = this.model.relaxToHyperedge(simplexKey);
if (!hyperedgeKey) return;
this.history.append({
type: "relaxed",
kind: "simplex",
nodes: simplex.nodes,
actor: "user",
prior: { label: simplex.label ?? null, weight: simplex.weight ?? null },
});
const owner = this.app.vault.getAbstractFileByPath(simplex.sourcePath ?? "");
if (owner instanceof TFile) {
const content = await removeSimplexFromManagedFile(this.app, owner, simplexKey);
await this.app.vault.modify(owner, content);
this.index.recordWrite(owner.path, content);
}
await this.persistHyperedge(this.model.getHyperedge(hyperedgeKey)!);
this.controller.selectHyperedge(hyperedgeKey);
await this.openPanel({ kind: "hyperedge", key: hyperedgeKey }, false);
new Notice("Relaxed to encounter. The group relation is kept; its faces are not asserted.");
}
/**
* HG-10. A recurring encounter precipitates a concept note.
*
* It offers a follow-up encounter including the new concept, but never promotes:
* repetition is evidence, not proof, of simplicial coherence.
*/
private async crystallizeEncounter(hyperedgeKey: RelationKey): Promise<void> {
const hyperedge = this.model.getHyperedge(hyperedgeKey);
if (!hyperedge) return;
const title = hyperedge.label?.trim() || `encounter-${normalizeKey(hyperedge.nodes).replace(/[|/]/g, "-")}`;
const folder = this.settings.crystallizeFolder.replace(/\/+$/, "");
const participants = hyperedge.nodes.map((nodeId) => ` - "[[${nodeId.replace(/\.md$/, "")}]]"`).join("\n");
const body = [
"---",
`originatingEncounter: "${relationKey("hyperedge", hyperedge.nodes)}"`,
"crystallizedFrom:",
participants,
`crystallizedAt: ${Date.now()}`,
"---",
"",
`# ${title}`,
"",
"This note names a concept that emerged from a recurring encounter between:",
"",
...hyperedge.nodes.map((nodeId) => `- [[${nodeId.replace(/\.md$/, "")}]]`),
"",
"The encounter is retained unpromoted — the triad recurring is evidence, not proof,",
"that its pairs are meaningful on their own.",
"",
].join("\n");
const file = await createPromotedNote(this.app, folder ? `${folder}/${title}` : title, body);
this.index.recordWrite(file.path, body);
this.model.crystallizeHyperedge(hyperedgeKey, file.path);
this.history.append({
type: "crystallized",
kind: "hyperedge",
nodes: hyperedge.nodes,
actor: "user",
detail: { conceptNote: file.path },
});
await this.persistHyperedge(this.model.getHyperedge(hyperedgeKey)!);
new Notice(`Crystallized into ${file.basename}. The encounter is unchanged.`);
await this.app.workspace.getLeaf(true).openFile(file);
}
private async dissolveHyperedge(hyperedgeKey: RelationKey): Promise<void> {
const hyperedge = this.model.getHyperedge(hyperedgeKey);
if (!hyperedge) return;
if (hyperedge.suggested) {
this.model.removeHyperedge(hyperedgeKey);
this.panelView?.setSelection(null);
new Notice("Encounter suggestion dismissed.");
return;
}
await this.removeHyperedgeFromNote(hyperedge);
this.model.removeHyperedge(hyperedgeKey);
this.history.append({
type: "dissolved",
kind: "hyperedge",
nodes: hyperedge.nodes,
actor: "user",
prior: { label: hyperedge.label ?? null, mode: hyperedge.mode ?? null },
});
this.controller.clearFocus();
this.panelView?.setSelection(null);
new Notice("Encounter dissolved. Its history is kept.");
}
private async saveHyperedgeMetadata(
hyperedgeKey: RelationKey,
updates: { label?: string; weight?: number; mode?: string },
): Promise<void> {
const updated = this.model.updateHyperedge(hyperedgeKey, updates);
if (!updated) return;
await this.persistHyperedge(updated);
}
private async promoteSimplex(simplexKey: string): Promise<void> {
const simplex = this.model.getSimplex(simplexKey);
if (!simplex || simplex.autoGenerated) return;
// Log interaction
this.controller.logPromote(simplexKey, simplex.nodes);
const noteTitle = simplex.label?.trim() || `simplex-${simplexKey.replace(/\|/g, "-")}`;
const body = simplex.nodes.map((nodeId) => `- [[${nodeId.replace(/\.md$/, "")}]]`).join("\n");
const promotedFile = await createPromotedNote(this.app, noteTitle, body);
const nextSimplex: Simplex = {
...simplex,
sourcePath: promotedFile.path,
userDefined: true,
inferred: false,
suggested: false,
autoGenerated: false,
};
if (simplex.sourcePath && simplex.sourcePath !== promotedFile.path) {
const originalFile = this.app.vault.getAbstractFileByPath(simplex.sourcePath);
if (originalFile instanceof TFile) {
const nextOriginalContent = await removeSimplexFromManagedFile(this.app, originalFile, simplexKey);
await this.app.vault.modify(originalFile, nextOriginalContent);
this.index.recordWrite(originalFile.path, nextOriginalContent);
}
}
const promotedContent = await writeSimplexToSourceNote(this.app, promotedFile, nextSimplex);
await this.app.vault.modify(promotedFile, promotedContent);
this.index.recordWrite(promotedFile.path, promotedContent);
this.model.removeSimplex(simplexKey);
const nextKey = this.model.addSimplex(nextSimplex);
this.controller.selectSimplex(nextKey);
await this.openPanel(nextKey, false);
new Notice(`Simplex now owned by ${promotedFile.basename}.`);
}
private openCreateSimplexModal(nodes: string[], sourcePath: string): void {
this.openCreateRelationModal(nodes, sourcePath, "simplex");
}
private openCreateRelationModal(nodes: string[], sourcePath: string, kind: "simplex" | "hyperedge"): void {
const owner = this.settings.persistenceMode === "central-file" ? this.settings.centralFile : sourcePath;
new CreateSimplexModal(
this.app,
nodes,
owner,
async (draft) => {
if (draft.kind === "hyperedge") {
const key = await this.createHyperedge(draft, sourcePath);
if (!key) return;
this.controller.selectHyperedge(key);
if (this.settings.commandAutoOpenPanel) {
await this.openPanel({ kind: "hyperedge", key }, false);
}
logger.info("plugin", "Encounter created from guided modal", {
relationKey: key,
sourcePath: owner,
hyperedgeCount: this.model.hyperedges.size,
});
new Notice(
this.settings.persistenceMode === "central-file"
? `Encounter added to ${this.settings.centralFile}. No faces were generated.`
: "Encounter added to note frontmatter. No faces were generated.",
);
return;
}
const simplex: Simplex = {
nodes: draft.nodes.map((node) => this.resolveDraftNode(node, sourcePath)),
label: draft.label,
weight: draft.weight,
sourcePath: owner,
userDefined: true,
autoGenerated: false,
};
const key = this.model.addSimplex(simplex);
await this.persistSimplex(this.model.getSimplex(key)!);
this.history.append({ type: "created", kind: "simplex", nodes: simplex.nodes, actor: "user" });
this.controller.selectSimplex(key);
if (this.settings.commandAutoOpenPanel) {
await this.openPanel(key, false);
}
logger.info("plugin", "Simplex created from guided modal", {
simplexKey: key,
sourcePath: simplex.sourcePath,
simplexCount: this.model.simplices.size,
});
new Notice(
this.settings.persistenceMode === "central-file"
? `Simplex added to ${this.settings.centralFile}.`
: "Simplex added to note frontmatter.",
);
},
kind,
).open();
}
private async openPanelForCurrentSelection(): Promise<void> {
const simplexKey =
this.controller.hoveredSimplexKey ??