@staix/vault-mem-ui 0.0.0-stage → 0.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +15 -0
- package/LICENSE +21 -0
- package/README.md +96 -2
- package/THIRD_PARTY_NOTICES.md +164 -0
- package/bin/vmem-ui.ts +26 -0
- package/dist/panel.css +666 -0
- package/dist/panel.js +355 -0
- package/package.json +53 -4
- package/src/client/App.tsx +167 -0
- package/src/client/a11y.ts +54 -0
- package/src/client/acon.ts +46 -0
- package/src/client/components.tsx +243 -0
- package/src/client/data.ts +66 -0
- package/src/client/fake.ts +48 -0
- package/src/client/graph-export.tsx +21 -0
- package/src/client/host.ts +80 -0
- package/src/client/markdown/parse.ts +620 -0
- package/src/client/markdown/render.tsx +270 -0
- package/src/client/panel.css +666 -0
- package/src/client/panel.tsx +66 -0
- package/src/client/prefs.ts +76 -0
- package/src/client/standalone.ts +44 -0
- package/src/client/store.ts +201 -0
- package/src/client/views/assertions.tsx +109 -0
- package/src/client/views/common.ts +15 -0
- package/src/client/views/history.tsx +205 -0
- package/src/client/views/lint.tsx +27 -0
- package/src/client/views/log.tsx +64 -0
- package/src/client/views/note.tsx +128 -0
- package/src/client/views/notes.tsx +34 -0
- package/src/client/views/overview.tsx +74 -0
- package/src/client/views/promote.tsx +112 -0
- package/src/client/views/proposals.tsx +55 -0
- package/src/client/views/settings.tsx +57 -0
- package/src/client/write.ts +144 -0
- package/src/graph/decisionChains.ts +122 -0
- package/src/graph/derive.ts +338 -0
- package/src/graph/export.ts +44 -0
- package/src/graph/insights.ts +254 -0
- package/src/graph/labels.ts +67 -0
- package/src/graph/layout/client.ts +139 -0
- package/src/graph/layout/engine.ts +107 -0
- package/src/graph/layout/fa2.d.ts +8 -0
- package/src/graph/layout/protocol.ts +70 -0
- package/src/graph/layout/worker.ts +132 -0
- package/src/graph/model.ts +230 -0
- package/src/graph/positions.ts +41 -0
- package/src/graph/search.ts +54 -0
- package/src/graph/style.ts +301 -0
- package/src/graph/target.ts +38 -0
- package/src/graph/types.ts +64 -0
- package/src/graph/view/GraphView.tsx +279 -0
- package/src/graph/view/SidePanels.tsx +141 -0
- package/src/graph/view/cache.ts +42 -0
- package/src/graph/view/canvas.ts +309 -0
- package/src/graph/view/graph-snapshot.ts +75 -0
- package/src/graph/view/lod.ts +30 -0
- package/src/graph/view/motion.ts +4 -0
- package/src/graph/view/state.ts +240 -0
- package/src/plugin/assets.ts +33 -0
- package/src/plugin/graph.ts +71 -0
- package/src/plugin/index.ts +23 -0
- package/src/server/cli.ts +99 -0
- package/src/server/host.ts +287 -0
|
@@ -0,0 +1,144 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The write flow. A host that answers the provider directly (`confirm: "client"`, the default) gets the two-step
|
|
3
|
+
* round trip here: every write is previewed with its fingerprint and the planned changes, and nothing is sent until
|
|
4
|
+
* the person confirms. `acon` answers that round trip itself (`confirm: "host"`): its console shows the preview and
|
|
5
|
+
* holds the fingerprint, and refusing a page that sets `confirmed`/`fingerprint` is the console's own rule, so this
|
|
6
|
+
* client only sends the bare action and reports the outcome.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import type { ActionInput, ActionResult, Change, Host } from "./host.ts";
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* The relations the provider's `link` action accepts. These are `LINK_RELATIONS` from the package's `src/links.ts`,
|
|
13
|
+
* which its `.` entry does not re-export, so the five names are mirrored here; the provider refuses any other value
|
|
14
|
+
* and names this list in the refusal.
|
|
15
|
+
*/
|
|
16
|
+
export const LINK_RELATIONS = ["supports", "contradicts", "extends", "applies-to", "context-for"] as const;
|
|
17
|
+
export type LinkRelation = (typeof LINK_RELATIONS)[number];
|
|
18
|
+
|
|
19
|
+
/** The `link` action's input, before the write flow adds confirmation: exactly the arguments the provider accepts. */
|
|
20
|
+
export type LinkInput = { action: "link"; from: string; to: string; relation: LinkRelation; bidirectional: boolean; vault?: string };
|
|
21
|
+
|
|
22
|
+
/**
|
|
23
|
+
* The provider's two-step `link` action (`case "link"` in the package's `src/ui/plugin.ts`), whose arguments are
|
|
24
|
+
* `from`, `to` and `relation`, with `bidirectional` optional and true by default. `from` and `to` are note paths as
|
|
25
|
+
* the graph reports them (`notes/a.md`), not note ids.
|
|
26
|
+
*/
|
|
27
|
+
export function linkAction(input: { from: string; to: string; relation: LinkRelation; bidirectional: boolean; vault?: string }): LinkInput {
|
|
28
|
+
return {
|
|
29
|
+
action: "link",
|
|
30
|
+
from: input.from,
|
|
31
|
+
to: input.to,
|
|
32
|
+
relation: input.relation,
|
|
33
|
+
bidirectional: input.bidirectional,
|
|
34
|
+
...(input.vault ? { vault: input.vault } : {}),
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export type WriteState =
|
|
39
|
+
| { phase: "idle" }
|
|
40
|
+
| { phase: "confirming"; verb: string }
|
|
41
|
+
| { phase: "waiting"; message: string }
|
|
42
|
+
| {
|
|
43
|
+
phase: "preview";
|
|
44
|
+
input: ActionInput;
|
|
45
|
+
fingerprint: string;
|
|
46
|
+
verb: string;
|
|
47
|
+
preview: string[];
|
|
48
|
+
changes: Change[];
|
|
49
|
+
warnings: string[];
|
|
50
|
+
confirmToken?: string;
|
|
51
|
+
}
|
|
52
|
+
/** `quiet` means the host already reported the outcome to the person (the console's own toast), so no dialog. */
|
|
53
|
+
| { phase: "done"; message: string; quiet?: boolean }
|
|
54
|
+
| { phase: "cancelled"; message: string }
|
|
55
|
+
| { phase: "error"; message: string };
|
|
56
|
+
|
|
57
|
+
/** A refusal names what failed and what to do next; the host's own words come first, unchanged. */
|
|
58
|
+
export function problemText(cause: unknown, fallback: string): string {
|
|
59
|
+
const text = cause instanceof Error ? cause.message : String(cause ?? "").trim();
|
|
60
|
+
return text
|
|
61
|
+
? `${fallback}: ${text}. Check the host connection and try again.`
|
|
62
|
+
: `${fallback}. Check the host connection and try again.`;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* The refusal text a person acts on. A provider that refused a write named its cause, so that text stays first and
|
|
67
|
+
* the next step follows it; a refusal that came without a reason says so rather than inventing one.
|
|
68
|
+
*/
|
|
69
|
+
export function refusalText(error: unknown, action: string): string {
|
|
70
|
+
const cause = typeof error === "string" ? error.trim() : "";
|
|
71
|
+
return cause
|
|
72
|
+
? `${cause}. Fix that and start the write again, or reload the panel first if it may already have been applied.`
|
|
73
|
+
: `${action} was refused without a reason. Reload the panel and try again; if it repeats, check the vault's log.`;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function fromReply(reply: ActionResult, input: ActionInput): WriteState {
|
|
77
|
+
if (reply.needsConfirm === true) {
|
|
78
|
+
if (!reply.fingerprint) {
|
|
79
|
+
return {
|
|
80
|
+
phase: "error",
|
|
81
|
+
message: `${input.action}: the provider asked for confirmation without a fingerprint, so this preview cannot be confirmed and nothing was sent. Start the write again; if it repeats, check the host version.`,
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
return {
|
|
85
|
+
phase: "preview",
|
|
86
|
+
input,
|
|
87
|
+
fingerprint: reply.fingerprint,
|
|
88
|
+
verb: reply.verb ?? input.action,
|
|
89
|
+
preview: reply.preview ?? [],
|
|
90
|
+
changes: reply.changes ?? [],
|
|
91
|
+
warnings: reply.warnings ?? [],
|
|
92
|
+
...(reply.confirmToken ? { confirmToken: reply.confirmToken } : {}),
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
if (reply.ok === false) return { phase: "error", message: refusalText(reply.error, input.action) };
|
|
96
|
+
return { phase: "done", message: reply.message ?? `${input.action}: done` };
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* `acon`'s `host.action` runs the console's own confirmation before it resolves: the preview is shown there, the
|
|
101
|
+
* person confirms or cancels, and the result is the outcome. A cancellation is the person's decision, not a failure.
|
|
102
|
+
*/
|
|
103
|
+
function fromHostReply(reply: ActionResult, input: ActionInput): WriteState {
|
|
104
|
+
if (reply.needsConfirm === true) {
|
|
105
|
+
// Only possible when a host claims to confirm and then hands the preview back: say so rather than loop.
|
|
106
|
+
return {
|
|
107
|
+
phase: "error",
|
|
108
|
+
message: `${input.action}: the host returned the preview instead of an outcome, so nothing was written. This host's confirmation and the console's disagree; reload the panel and try again.`,
|
|
109
|
+
};
|
|
110
|
+
}
|
|
111
|
+
if (reply.cancelled === true) return { phase: "cancelled", message: `${input.action}: cancelled, so nothing was written.` };
|
|
112
|
+
if (reply.ok === false) return { phase: "error", message: refusalText(reply.error, input.action) };
|
|
113
|
+
return { phase: "done", message: reply.message ?? `${input.action}: done`, quiet: true };
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** Ask for the preview of a write, or let the host run the whole round trip when it owns the confirmation. */
|
|
117
|
+
export async function startWrite(host: Host, input: ActionInput): Promise<WriteState> {
|
|
118
|
+
const owned = host.confirm === "host";
|
|
119
|
+
try {
|
|
120
|
+
const reply = await host.action(input);
|
|
121
|
+
return owned ? fromHostReply(reply, input) : fromReply(reply, input);
|
|
122
|
+
} catch (error) {
|
|
123
|
+
return { phase: "error", message: problemText(error, `${input.action} was not sent`) };
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
/** Perform the previewed write, re-sending the fingerprint the preview produced. */
|
|
128
|
+
export async function confirmWrite(host: Host, state: WriteState): Promise<WriteState> {
|
|
129
|
+
if (state.phase !== "preview" || host.confirm === "host") return state;
|
|
130
|
+
try {
|
|
131
|
+
const reply = await host.action({
|
|
132
|
+
...state.input,
|
|
133
|
+
confirmed: true,
|
|
134
|
+
fingerprint: state.fingerprint,
|
|
135
|
+
...(state.confirmToken ? { confirmToken: state.confirmToken } : {}),
|
|
136
|
+
});
|
|
137
|
+
// A retried confirmation can answer `needsConfirm` again (a fingerprint recomputed to the same value);
|
|
138
|
+
// showing that preview again is safer than treating it as done.
|
|
139
|
+
return fromReply(reply, state.input);
|
|
140
|
+
} catch (error) {
|
|
141
|
+
const cause = error instanceof Error ? error.message : String(error ?? "");
|
|
142
|
+
return { phase: "error", message: `${state.verb}: ${cause || "confirmation failed"}. It may already have been applied; reload the panel to check the current state.` };
|
|
143
|
+
}
|
|
144
|
+
}
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
// Ported from STAIxBWLB/maru@b33341df src/lib/graph/decisionChains.ts.
|
|
2
|
+
// Decision-chain lanes (maru-vault-graph-spec §3 F3(c)). Deterministic — NOT
|
|
3
|
+
// force-directed: supersedes edges group type=decision notes into chains,
|
|
4
|
+
// each chain renders as one horizontal timeline lane (oldest → newest);
|
|
5
|
+
// isolated decisions go to a side rail.
|
|
6
|
+
|
|
7
|
+
import type { GraphModel, GraphNode } from "./model";
|
|
8
|
+
|
|
9
|
+
export interface DecisionChain {
|
|
10
|
+
/** Chain members, older before newer; dates and ids break ties. */
|
|
11
|
+
nodes: GraphNode[];
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export interface DecisionChainLayout {
|
|
15
|
+
chains: DecisionChain[];
|
|
16
|
+
/** Decisions with no supersedes relation — side rail, date descending. */
|
|
17
|
+
isolated: GraphNode[];
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
const SUPERSEDES_RELATIONS = new Set(["supersedes", "superseded_by"]);
|
|
21
|
+
|
|
22
|
+
function compareByDate(a: GraphNode, b: GraphNode): number {
|
|
23
|
+
if (a.date && b.date) return a.date.localeCompare(b.date) || a.id.localeCompare(b.id);
|
|
24
|
+
if (a.date) return -1;
|
|
25
|
+
if (b.date) return 1;
|
|
26
|
+
return a.id.localeCompare(b.id);
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** Topological chronology with deterministic date/id ties; malformed cycles fall back to date/id for their remainder. */
|
|
30
|
+
function orderChain(nodes: GraphNode[], forward: Map<string, Set<string>>): GraphNode[] {
|
|
31
|
+
const members = new Map(nodes.map((node) => [node.id, node]));
|
|
32
|
+
const indegree = new Map(nodes.map((node) => [node.id, 0]));
|
|
33
|
+
for (const node of nodes) for (const next of forward.get(node.id) ?? []) if (members.has(next)) indegree.set(next, indegree.get(next)! + 1);
|
|
34
|
+
const heap: GraphNode[] = [];
|
|
35
|
+
const push = (node: GraphNode) => {
|
|
36
|
+
heap.push(node); let index = heap.length - 1;
|
|
37
|
+
while (index > 0) { const parent = Math.floor((index - 1) / 2); if (compareByDate(heap[parent]!, node) <= 0) break; heap[index] = heap[parent]!; index = parent; }
|
|
38
|
+
heap[index] = node;
|
|
39
|
+
};
|
|
40
|
+
const pop = (): GraphNode => {
|
|
41
|
+
const first = heap[0]!, last = heap.pop()!;
|
|
42
|
+
if (heap.length) {
|
|
43
|
+
let index = 0;
|
|
44
|
+
while (index * 2 + 1 < heap.length) {
|
|
45
|
+
let child = index * 2 + 1;
|
|
46
|
+
if (child + 1 < heap.length && compareByDate(heap[child + 1]!, heap[child]!) < 0) child++;
|
|
47
|
+
if (compareByDate(last, heap[child]!) <= 0) break;
|
|
48
|
+
heap[index] = heap[child]!; index = child;
|
|
49
|
+
}
|
|
50
|
+
heap[index] = last;
|
|
51
|
+
}
|
|
52
|
+
return first;
|
|
53
|
+
};
|
|
54
|
+
for (const node of nodes) if (indegree.get(node.id) === 0) push(node);
|
|
55
|
+
const ordered: GraphNode[] = [];
|
|
56
|
+
while (heap.length) {
|
|
57
|
+
const node = pop(); ordered.push(node); indegree.delete(node.id);
|
|
58
|
+
for (const next of forward.get(node.id) ?? []) {
|
|
59
|
+
const degree = indegree.get(next);
|
|
60
|
+
if (degree === undefined) continue;
|
|
61
|
+
indegree.set(next, degree - 1);
|
|
62
|
+
if (degree === 1) push(members.get(next)!);
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
return ordered.concat([...indegree.keys()].map((id) => members.get(id)!).sort(compareByDate));
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** Group decision notes into supersedes chains. Cycle-safe: connected
|
|
69
|
+
* components over the (undirected) supersedes relation, so a malformed
|
|
70
|
+
* A→B→A loop still terminates and lands in one chain. */
|
|
71
|
+
export function buildDecisionChains(model: GraphModel): DecisionChainLayout {
|
|
72
|
+
const decisions = new Map(
|
|
73
|
+
model.nodes.filter((n) => n.type === "decision").map((n) => [n.id, n]),
|
|
74
|
+
);
|
|
75
|
+
|
|
76
|
+
const adjacency = new Map<string, Set<string>>();
|
|
77
|
+
const forward = new Map<string, Set<string>>();
|
|
78
|
+
for (const edge of model.edges) {
|
|
79
|
+
if (!SUPERSEDES_RELATIONS.has(edge.relation)) continue;
|
|
80
|
+
if (!decisions.has(edge.source) || !decisions.has(edge.target)) continue;
|
|
81
|
+
const [older, newer] = edge.relation === "superseded_by" ? [edge.source, edge.target] : [edge.target, edge.source];
|
|
82
|
+
(forward.get(older) ?? forward.set(older, new Set()).get(older)!).add(newer);
|
|
83
|
+
(adjacency.get(edge.source) ?? adjacency.set(edge.source, new Set()).get(edge.source)!)
|
|
84
|
+
.add(edge.target);
|
|
85
|
+
(adjacency.get(edge.target) ?? adjacency.set(edge.target, new Set()).get(edge.target)!)
|
|
86
|
+
.add(edge.source);
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
const visited = new Set<string>();
|
|
90
|
+
const chains: DecisionChain[] = [];
|
|
91
|
+
for (const id of adjacency.keys()) {
|
|
92
|
+
if (visited.has(id)) continue;
|
|
93
|
+
const members: GraphNode[] = [];
|
|
94
|
+
const stack = [id];
|
|
95
|
+
while (stack.length > 0) {
|
|
96
|
+
const current = stack.pop()!;
|
|
97
|
+
if (visited.has(current)) continue; // cycle guard
|
|
98
|
+
visited.add(current);
|
|
99
|
+
const node = decisions.get(current);
|
|
100
|
+
if (node) members.push(node);
|
|
101
|
+
for (const neighbor of adjacency.get(current) ?? []) {
|
|
102
|
+
if (!visited.has(neighbor)) stack.push(neighbor);
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
if (members.length > 1) {
|
|
106
|
+
chains.push({ nodes: orderChain(members, forward) });
|
|
107
|
+
} else if (members.length === 1) {
|
|
108
|
+
// A supersedes edge whose partner isn't a decision note — treat as isolated.
|
|
109
|
+
visited.add(members[0].id);
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
const chained = new Set(chains.flatMap((chain) => chain.nodes.map((node) => node.id)));
|
|
114
|
+
const isolated = [...decisions.values()]
|
|
115
|
+
.filter((n) => !chained.has(n.id))
|
|
116
|
+
.sort((a, b) => compareByDate(b, a));
|
|
117
|
+
|
|
118
|
+
chains.sort(
|
|
119
|
+
(a, b) => compareByDate(b.nodes[b.nodes.length - 1], a.nodes[a.nodes.length - 1]),
|
|
120
|
+
);
|
|
121
|
+
return { chains, isolated };
|
|
122
|
+
}
|
|
@@ -0,0 +1,338 @@
|
|
|
1
|
+
// Ported from STAIxBWLB/maru@b33341df src/lib/graph/derive.ts.
|
|
2
|
+
// Pure derivation pipeline for the graph workbench. The renderer keeps the
|
|
3
|
+
// full topology for stable layout, while these outputs define the one truthful
|
|
4
|
+
// analysis/visibility contract used by every consumer.
|
|
5
|
+
|
|
6
|
+
import type { GraphFilterProfile, GraphMode } from "./types";
|
|
7
|
+
import {
|
|
8
|
+
focusSubgraph,
|
|
9
|
+
graphEdgeVisibilityKey,
|
|
10
|
+
isGeneratedNode,
|
|
11
|
+
withGraphDegrees,
|
|
12
|
+
type GraphModel,
|
|
13
|
+
type GraphNode,
|
|
14
|
+
} from "./model";
|
|
15
|
+
import { graphNodeMatchesSearch } from "./search";
|
|
16
|
+
|
|
17
|
+
export interface DerivedGraphFacets {
|
|
18
|
+
domains: { value: string; count: number }[];
|
|
19
|
+
origins: { value: string; count: number }[];
|
|
20
|
+
types: { value: string; count: number }[];
|
|
21
|
+
relations: { value: string; count: number }[];
|
|
22
|
+
communities: { value: number; count: number }[];
|
|
23
|
+
maxVisibleNeighbors: number;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export type GraphEmptyReason = "empty-source" | "filtered-empty" | null;
|
|
27
|
+
|
|
28
|
+
export interface DerivedGraph {
|
|
29
|
+
/** Facets + relations + Local + k-core, before transient search filtering. */
|
|
30
|
+
analysisModel: GraphModel;
|
|
31
|
+
/** Exact canvas/inspector/export view, including search-as-filter. */
|
|
32
|
+
visibleModel: GraphModel;
|
|
33
|
+
visibleNodeIds: Set<string>;
|
|
34
|
+
visibleEdgeKeys: Set<string>;
|
|
35
|
+
/** Derived degree per analysis node. */
|
|
36
|
+
visibleNeighborCounts: Map<string, number>;
|
|
37
|
+
facets: DerivedGraphFacets;
|
|
38
|
+
/** Persisted selections absent from the source model. */
|
|
39
|
+
pausedFilters: string[];
|
|
40
|
+
emptyReason: GraphEmptyReason;
|
|
41
|
+
/** Local mode requested a canonical target absent from the current source. */
|
|
42
|
+
focusMissing: boolean;
|
|
43
|
+
/** Local focus node kept visible through pruning and search narrowing. */
|
|
44
|
+
protectedFocusId: string | null;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function pruneByMinNeighbors(
|
|
48
|
+
model: GraphModel,
|
|
49
|
+
threshold: number,
|
|
50
|
+
protectId: string | null,
|
|
51
|
+
): GraphModel {
|
|
52
|
+
if (threshold <= 0) return model;
|
|
53
|
+
const neighbors = new Map<string, Set<string>>();
|
|
54
|
+
for (const node of model.nodes) neighbors.set(node.id, new Set());
|
|
55
|
+
for (const edge of model.edges) {
|
|
56
|
+
neighbors.get(edge.source)?.add(edge.target);
|
|
57
|
+
neighbors.get(edge.target)?.add(edge.source);
|
|
58
|
+
}
|
|
59
|
+
const removed = new Set<string>();
|
|
60
|
+
const queue: string[] = [];
|
|
61
|
+
for (const [id, set] of neighbors) {
|
|
62
|
+
if (id !== protectId && set.size < threshold) queue.push(id);
|
|
63
|
+
}
|
|
64
|
+
while (queue.length > 0) {
|
|
65
|
+
const id = queue.pop()!;
|
|
66
|
+
if (removed.has(id)) continue;
|
|
67
|
+
removed.add(id);
|
|
68
|
+
for (const other of neighbors.get(id) ?? []) {
|
|
69
|
+
if (removed.has(other)) continue;
|
|
70
|
+
const set = neighbors.get(other)!;
|
|
71
|
+
set.delete(id);
|
|
72
|
+
if (other !== protectId && set.size < threshold) queue.push(other);
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
return {
|
|
76
|
+
...model,
|
|
77
|
+
nodes: model.nodes.filter((node) => !removed.has(node.id)),
|
|
78
|
+
edges: model.edges.filter(
|
|
79
|
+
(edge) => !removed.has(edge.source) && !removed.has(edge.target),
|
|
80
|
+
),
|
|
81
|
+
};
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
function distinctNeighborCounts(model: GraphModel): Map<string, number> {
|
|
85
|
+
const neighbors = new Map(model.nodes.map((node) => [node.id, new Set<string>()]));
|
|
86
|
+
for (const edge of model.edges) {
|
|
87
|
+
neighbors.get(edge.source)?.add(edge.target);
|
|
88
|
+
neighbors.get(edge.target)?.add(edge.source);
|
|
89
|
+
}
|
|
90
|
+
return new Map([...neighbors].map(([id, ids]) => [id, ids.size]));
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
type NodeFacet = "domain" | "origin" | "type" | "community" | null;
|
|
94
|
+
|
|
95
|
+
function nodePasses(
|
|
96
|
+
node: GraphNode,
|
|
97
|
+
profile: GraphFilterProfile,
|
|
98
|
+
generatedPatterns: readonly string[],
|
|
99
|
+
focusNodeId: string | null,
|
|
100
|
+
activeDomains: ReadonlySet<string>,
|
|
101
|
+
activeOrigins: ReadonlySet<string>,
|
|
102
|
+
activeTypes: ReadonlySet<string>,
|
|
103
|
+
communityActive: boolean,
|
|
104
|
+
omit: NodeFacet = null,
|
|
105
|
+
): boolean {
|
|
106
|
+
if (node.id === focusNodeId) return true;
|
|
107
|
+
if (!profile.showUnresolved && node.type === "unresolved") return false;
|
|
108
|
+
if (!profile.showGenerated && isGeneratedNode(node, generatedPatterns)) return false;
|
|
109
|
+
if (omit !== "domain" && activeDomains.size > 0 && (!node.domain || !activeDomains.has(node.domain))) {
|
|
110
|
+
return false;
|
|
111
|
+
}
|
|
112
|
+
// Ghosts have no origin; an origin filter hides them along with the rest.
|
|
113
|
+
if (omit !== "origin" && activeOrigins.size > 0 && !activeOrigins.has(node.origin)) {
|
|
114
|
+
return false;
|
|
115
|
+
}
|
|
116
|
+
if (omit !== "type" && activeTypes.size > 0 && !activeTypes.has(node.type)) return false;
|
|
117
|
+
if (omit !== "community" && communityActive && node.community !== profile.community) return false;
|
|
118
|
+
return true;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
function countNodeFacet<T extends string | number>(
|
|
122
|
+
nodes: readonly GraphNode[],
|
|
123
|
+
value: (node: GraphNode) => T | null,
|
|
124
|
+
): Map<T, number> {
|
|
125
|
+
const counts = new Map<T, number>();
|
|
126
|
+
for (const node of nodes) {
|
|
127
|
+
const item = value(node);
|
|
128
|
+
if (item != null) counts.set(item, (counts.get(item) ?? 0) + 1);
|
|
129
|
+
}
|
|
130
|
+
return counts;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
function facetItems<T extends string | number>(
|
|
134
|
+
counts: Map<T, number>,
|
|
135
|
+
selected: readonly T[],
|
|
136
|
+
compare: (a: T, b: T) => number,
|
|
137
|
+
): { value: T; count: number }[] {
|
|
138
|
+
for (const value of selected) {
|
|
139
|
+
if (!counts.has(value)) counts.set(value, 0);
|
|
140
|
+
}
|
|
141
|
+
return [...counts.entries()]
|
|
142
|
+
.sort((a, b) => compare(a[0], b[0]))
|
|
143
|
+
.map(([value, count]) => ({ value, count }));
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
export function deriveGraphView(args: {
|
|
147
|
+
model: GraphModel;
|
|
148
|
+
profile: GraphFilterProfile;
|
|
149
|
+
generatedPatterns: readonly string[];
|
|
150
|
+
mode: GraphMode;
|
|
151
|
+
focusNodeId: string | null;
|
|
152
|
+
localDepth: 1 | 2 | 3;
|
|
153
|
+
localDirection: "both" | "incoming" | "outgoing";
|
|
154
|
+
search: string;
|
|
155
|
+
searchAsFilter: boolean;
|
|
156
|
+
}): DerivedGraph {
|
|
157
|
+
const {
|
|
158
|
+
model,
|
|
159
|
+
profile,
|
|
160
|
+
generatedPatterns,
|
|
161
|
+
mode,
|
|
162
|
+
focusNodeId,
|
|
163
|
+
localDepth,
|
|
164
|
+
localDirection,
|
|
165
|
+
search,
|
|
166
|
+
searchAsFilter,
|
|
167
|
+
} = args;
|
|
168
|
+
|
|
169
|
+
const modelDomains = new Set<string>();
|
|
170
|
+
const modelOrigins = new Set<string>();
|
|
171
|
+
const modelTypes = new Set<string>();
|
|
172
|
+
const modelCommunities = new Set<number>();
|
|
173
|
+
for (const node of model.nodes) {
|
|
174
|
+
if (node.domain) modelDomains.add(node.domain);
|
|
175
|
+
if (node.origin !== "unknown") modelOrigins.add(node.origin);
|
|
176
|
+
modelTypes.add(node.type);
|
|
177
|
+
if (node.community != null) modelCommunities.add(node.community);
|
|
178
|
+
}
|
|
179
|
+
const modelRelations = new Set(model.edges.map((edge) => edge.relation));
|
|
180
|
+
|
|
181
|
+
const pausedFilters: string[] = [];
|
|
182
|
+
const activeDomains = new Set(profile.domains.filter((value) => {
|
|
183
|
+
if (modelDomains.has(value)) return true;
|
|
184
|
+
pausedFilters.push(`domain:${value}`);
|
|
185
|
+
return false;
|
|
186
|
+
}));
|
|
187
|
+
const activeOrigins = new Set(profile.origins.filter((value) => {
|
|
188
|
+
if (modelOrigins.has(value)) return true;
|
|
189
|
+
pausedFilters.push(`origin:${value}`);
|
|
190
|
+
return false;
|
|
191
|
+
}));
|
|
192
|
+
const activeTypes = new Set(profile.types.filter((value) => {
|
|
193
|
+
if (modelTypes.has(value)) return true;
|
|
194
|
+
pausedFilters.push(`type:${value}`);
|
|
195
|
+
return false;
|
|
196
|
+
}));
|
|
197
|
+
const activeRelations = new Set(profile.relations.filter((value) => {
|
|
198
|
+
if (modelRelations.has(value)) return true;
|
|
199
|
+
pausedFilters.push(`relation:${value}`);
|
|
200
|
+
return false;
|
|
201
|
+
}));
|
|
202
|
+
const communityActive = profile.community != null && modelCommunities.has(profile.community);
|
|
203
|
+
if (profile.community != null && !communityActive) {
|
|
204
|
+
pausedFilters.push(`community:${profile.community}`);
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
const focusExists = focusNodeId != null && model.nodes.some((node) => node.id === focusNodeId);
|
|
208
|
+
const protectedFocusId = mode === "local" && focusExists ? focusNodeId : null;
|
|
209
|
+
const pass = (node: GraphNode, omit: NodeFacet = null) => nodePasses(
|
|
210
|
+
node,
|
|
211
|
+
profile,
|
|
212
|
+
generatedPatterns,
|
|
213
|
+
protectedFocusId,
|
|
214
|
+
activeDomains,
|
|
215
|
+
activeOrigins,
|
|
216
|
+
activeTypes,
|
|
217
|
+
communityActive,
|
|
218
|
+
omit,
|
|
219
|
+
);
|
|
220
|
+
|
|
221
|
+
// Self-excluding facets keep additive choices visible. Relation counts use
|
|
222
|
+
// the fully node-filtered graph before the relation facet applies itself.
|
|
223
|
+
const domainCounts = countNodeFacet(model.nodes.filter((node) => pass(node, "domain")), (node) => node.domain);
|
|
224
|
+
const originCounts = countNodeFacet(
|
|
225
|
+
model.nodes.filter((node) => pass(node, "origin")),
|
|
226
|
+
(node) => (node.origin === "unknown" ? null : node.origin),
|
|
227
|
+
);
|
|
228
|
+
const typeCounts = countNodeFacet(model.nodes.filter((node) => pass(node, "type")), (node) => node.type);
|
|
229
|
+
const communityCounts = countNodeFacet(
|
|
230
|
+
model.nodes.filter((node) => pass(node, "community")),
|
|
231
|
+
(node) => node.community,
|
|
232
|
+
);
|
|
233
|
+
|
|
234
|
+
const keptNodeIds = new Set(model.nodes.filter((node) => pass(node)).map((node) => node.id));
|
|
235
|
+
const nodeFilteredEdges = model.edges.filter(
|
|
236
|
+
(edge) => keptNodeIds.has(edge.source) && keptNodeIds.has(edge.target),
|
|
237
|
+
);
|
|
238
|
+
const relationCounts = new Map<string, number>();
|
|
239
|
+
for (const edge of nodeFilteredEdges) {
|
|
240
|
+
relationCounts.set(edge.relation, (relationCounts.get(edge.relation) ?? 0) + 1);
|
|
241
|
+
}
|
|
242
|
+
const relationFilteredEdges = activeRelations.size === 0
|
|
243
|
+
? nodeFilteredEdges
|
|
244
|
+
: nodeFilteredEdges.filter((edge) => activeRelations.has(edge.relation));
|
|
245
|
+
|
|
246
|
+
let working = withGraphDegrees({
|
|
247
|
+
...model,
|
|
248
|
+
nodes: model.nodes.filter((node) => keptNodeIds.has(node.id)),
|
|
249
|
+
edges: relationFilteredEdges,
|
|
250
|
+
});
|
|
251
|
+
const focusMissing = mode === "local" && focusNodeId != null && !focusExists;
|
|
252
|
+
if (mode === "local" && protectedFocusId) {
|
|
253
|
+
working = focusSubgraph(working, protectedFocusId, localDepth, localDirection);
|
|
254
|
+
}
|
|
255
|
+
working = withGraphDegrees(
|
|
256
|
+
pruneByMinNeighbors(working, profile.minVisibleNeighbors, protectedFocusId),
|
|
257
|
+
);
|
|
258
|
+
const analysisModel = working;
|
|
259
|
+
|
|
260
|
+
const visibleNodeIds = new Set(analysisModel.nodes.map((node) => node.id));
|
|
261
|
+
const visibleEdgeKeys = new Set(analysisModel.edges.map(graphEdgeVisibilityKey));
|
|
262
|
+
const visibleNeighborCounts = distinctNeighborCounts(analysisModel);
|
|
263
|
+
const maxVisibleNeighbors = Math.max(0, ...visibleNeighborCounts.values());
|
|
264
|
+
|
|
265
|
+
const facets: DerivedGraphFacets = {
|
|
266
|
+
domains: facetItems(domainCounts, profile.domains, (a, b) => a.localeCompare(b)),
|
|
267
|
+
// Workspace before knowledge, matching the legend and the color slots.
|
|
268
|
+
origins: facetItems(originCounts, profile.origins, (a, b) => a.localeCompare(b)).sort(
|
|
269
|
+
(a, b) => (a.value === b.value ? 0 : a.value === "workspace" ? -1 : 1),
|
|
270
|
+
),
|
|
271
|
+
types: facetItems(typeCounts, profile.types, (a, b) => a.localeCompare(b)),
|
|
272
|
+
relations: facetItems(relationCounts, profile.relations, (a, b) => a.localeCompare(b)),
|
|
273
|
+
communities: facetItems(
|
|
274
|
+
communityCounts,
|
|
275
|
+
profile.community == null ? [] : [profile.community],
|
|
276
|
+
(a, b) => a - b,
|
|
277
|
+
),
|
|
278
|
+
maxVisibleNeighbors,
|
|
279
|
+
};
|
|
280
|
+
|
|
281
|
+
const emptyReason: GraphEmptyReason = model.nodes.length === 0
|
|
282
|
+
? "empty-source"
|
|
283
|
+
: analysisModel.nodes.length === 0
|
|
284
|
+
? "filtered-empty"
|
|
285
|
+
: null;
|
|
286
|
+
|
|
287
|
+
const base: DerivedGraph = {
|
|
288
|
+
analysisModel,
|
|
289
|
+
visibleModel: analysisModel,
|
|
290
|
+
visibleNodeIds,
|
|
291
|
+
visibleEdgeKeys,
|
|
292
|
+
visibleNeighborCounts,
|
|
293
|
+
facets,
|
|
294
|
+
pausedFilters,
|
|
295
|
+
emptyReason,
|
|
296
|
+
focusMissing,
|
|
297
|
+
protectedFocusId,
|
|
298
|
+
};
|
|
299
|
+
return applyGraphSearch(base, searchAsFilter ? search : "");
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
/** Transient search narrowing over an analysis-stage derivation. Split out so
|
|
303
|
+
* the expensive facet/local/k-core stage keeps a stable identity across
|
|
304
|
+
* keystrokes — recreating `analysisModel` per keystroke made the insights
|
|
305
|
+
* panel terminate and respawn its worker (with a full structured clone of the
|
|
306
|
+
* graph) on every character typed. */
|
|
307
|
+
export function applyGraphSearch(base: DerivedGraph, search: string): DerivedGraph {
|
|
308
|
+
const query = search.trim();
|
|
309
|
+
if (!query) return base;
|
|
310
|
+
const analysis = base.analysisModel;
|
|
311
|
+
const matched = new Set(
|
|
312
|
+
analysis.nodes.filter((node) => graphNodeMatchesSearch(node, query)).map((node) => node.id),
|
|
313
|
+
);
|
|
314
|
+
const visible = new Set(matched);
|
|
315
|
+
for (const edge of analysis.edges) {
|
|
316
|
+
if (matched.has(edge.source)) visible.add(edge.target);
|
|
317
|
+
if (matched.has(edge.target)) visible.add(edge.source);
|
|
318
|
+
}
|
|
319
|
+
if (base.protectedFocusId) visible.add(base.protectedFocusId);
|
|
320
|
+
const visibleModel = withGraphDegrees({
|
|
321
|
+
...analysis,
|
|
322
|
+
nodes: analysis.nodes.filter((node) => visible.has(node.id)),
|
|
323
|
+
edges: analysis.edges.filter(
|
|
324
|
+
(edge) => visible.has(edge.source) && visible.has(edge.target),
|
|
325
|
+
),
|
|
326
|
+
});
|
|
327
|
+
return {
|
|
328
|
+
...base,
|
|
329
|
+
visibleModel,
|
|
330
|
+
visibleNodeIds: new Set(visibleModel.nodes.map((node) => node.id)),
|
|
331
|
+
visibleEdgeKeys: new Set(visibleModel.edges.map(graphEdgeVisibilityKey)),
|
|
332
|
+
emptyReason: base.emptyReason === "empty-source"
|
|
333
|
+
? "empty-source"
|
|
334
|
+
: visibleModel.nodes.length === 0
|
|
335
|
+
? "filtered-empty"
|
|
336
|
+
: base.emptyReason,
|
|
337
|
+
};
|
|
338
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
import type { GraphModel } from "./model";
|
|
2
|
+
|
|
3
|
+
export type GraphPositions = Readonly<Record<string, readonly [number, number]>>;
|
|
4
|
+
|
|
5
|
+
/** Export graph metadata only. Strings are UTF-8/base64 encoded inside JSON so HTML cannot terminate its data element. */
|
|
6
|
+
export function exportGraphHtml(model: GraphModel, positions: GraphPositions): string {
|
|
7
|
+
const data = {
|
|
8
|
+
nodes: model.nodes.map((node) => {
|
|
9
|
+
const point = Object.hasOwn(positions, node.id) ? positions[node.id] : undefined;
|
|
10
|
+
return {
|
|
11
|
+
id: node.id, label: node.label, type: node.type, domain: node.domain,
|
|
12
|
+
community: node.community, degree: node.degree,
|
|
13
|
+
position: point && Number.isFinite(point[0]) && Number.isFinite(point[1]) ? [point[0], point[1]] : null,
|
|
14
|
+
};
|
|
15
|
+
}),
|
|
16
|
+
edges: model.edges.map((edge) => ({ source: edge.source, target: edge.target, relation: edge.relation })),
|
|
17
|
+
};
|
|
18
|
+
const bytes = new TextEncoder().encode(JSON.stringify(data));
|
|
19
|
+
let binary = "";
|
|
20
|
+
for (let i = 0; i < bytes.length; i += 8192) binary += String.fromCharCode(...bytes.subarray(i, i + 8192));
|
|
21
|
+
const payload = JSON.stringify({ encoding: "base64-utf8", data: btoa(binary) });
|
|
22
|
+
return `<!doctype html>
|
|
23
|
+
<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Vault graph</title>
|
|
24
|
+
<style>body{font:16px system-ui,sans-serif;margin:2rem;max-width:70rem}canvas{width:100%;height:auto;border:1px solid #aaa}li{margin:.3rem 0}</style></head>
|
|
25
|
+
<body><h1>Vault graph</h1><p>Offline graph metadata. Note contents are not included.</p><canvas id="graph" width="1000" height="600" aria-label="Graph visualization"></canvas><h2>Nodes</h2><ul id="nodes"></ul>
|
|
26
|
+
<script id="graph-data" type="application/json">${payload}</script>
|
|
27
|
+
<script>
|
|
28
|
+
const packet = JSON.parse(document.getElementById("graph-data").textContent);
|
|
29
|
+
const bytes = Uint8Array.from(atob(packet.data), c => c.charCodeAt(0));
|
|
30
|
+
const graph = JSON.parse(new TextDecoder().decode(bytes));
|
|
31
|
+
const canvas = document.getElementById("graph"), ctx = canvas.getContext("2d");
|
|
32
|
+
const points = new Map();
|
|
33
|
+
const raw = graph.nodes.map((node, i) => node.position || [Math.cos(i * 2.4) * Math.sqrt(i + 1), Math.sin(i * 2.4) * Math.sqrt(i + 1)]);
|
|
34
|
+
let minX = Infinity, maxX = -Infinity, minY = Infinity, maxY = -Infinity;
|
|
35
|
+
for (const [x, y] of raw) { minX = Math.min(minX, x); maxX = Math.max(maxX, x); minY = Math.min(minY, y); maxY = Math.max(maxY, y); }
|
|
36
|
+
const span = Math.max(maxX - minX, maxY - minY, 1), scale = 520 / span;
|
|
37
|
+
// Graph coordinates use y-up, while a 2D canvas uses y-down.
|
|
38
|
+
graph.nodes.forEach((node, i) => points.set(node.id, [500 + (raw[i][0] - (minX + maxX) / 2) * scale, 300 - (raw[i][1] - (minY + maxY) / 2) * scale]));
|
|
39
|
+
ctx.strokeStyle = "#aaa";
|
|
40
|
+
for (const edge of graph.edges) { const a = points.get(edge.source), b = points.get(edge.target); if (!a || !b) continue; ctx.beginPath(); ctx.moveTo(...a); ctx.lineTo(...b); ctx.stroke(); }
|
|
41
|
+
ctx.fillStyle = "#2458a2"; ctx.font = "12px sans-serif";
|
|
42
|
+
for (const node of graph.nodes) { const p = points.get(node.id); ctx.beginPath(); ctx.arc(p[0], p[1], 4, 0, Math.PI * 2); ctx.fill(); ctx.fillText(node.label, p[0] + 6, p[1] - 6); const li = document.createElement("li"); li.textContent = node.label + " (" + node.type + ", " + node.degree + " links)"; document.getElementById("nodes").append(li); }
|
|
43
|
+
</script></body></html>`;
|
|
44
|
+
}
|