ai-first-os 1.9.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.
Files changed (90) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +226 -0
  3. package/bin/ai-first-os.js +72 -0
  4. package/core/CLAUDE.md +148 -0
  5. package/core/VERSION +1 -0
  6. package/core/agents/ambiguous-spec.md +39 -0
  7. package/core/agents/complete-spec.md +36 -0
  8. package/core/agents/scout.md +25 -0
  9. package/core/install.sh +243 -0
  10. package/core/lib/archive.sh +347 -0
  11. package/core/lib/bootstrap.sh +276 -0
  12. package/core/lib/capture.sh +188 -0
  13. package/core/lib/check-resolvable.sh +172 -0
  14. package/core/lib/close-session.sh +741 -0
  15. package/core/lib/common.sh +1773 -0
  16. package/core/lib/focus-read.sh +282 -0
  17. package/core/lib/manual-link.sh +111 -0
  18. package/core/lib/markdown.py +304 -0
  19. package/core/lib/migrate-backlogs.sh +207 -0
  20. package/core/lib/migrate-canonicals.sh +523 -0
  21. package/core/lib/mount-repo.sh +543 -0
  22. package/core/lib/my-wiki-gates.sh +137 -0
  23. package/core/lib/my-wiki.sh +202 -0
  24. package/core/lib/my_wiki_build.py +548 -0
  25. package/core/lib/my_wiki_graph.py +137 -0
  26. package/core/lib/my_wiki_overview.py +392 -0
  27. package/core/lib/new-memory.sh +160 -0
  28. package/core/lib/new-product.sh +122 -0
  29. package/core/lib/new-workspace.sh +105 -0
  30. package/core/lib/pack-install.sh +114 -0
  31. package/core/lib/recall.sh +235 -0
  32. package/core/lib/recall_index.py +295 -0
  33. package/core/lib/remote-backup.sh +84 -0
  34. package/core/lib/rename-heads.sh +354 -0
  35. package/core/lib/rename-workspaces.sh +271 -0
  36. package/core/lib/session-read.sh +203 -0
  37. package/core/lib/session-start.sh +854 -0
  38. package/core/lib/supersede.sh +436 -0
  39. package/core/lib/sweep.sh +473 -0
  40. package/core/manual/COMO-FUNCIONA.md +251 -0
  41. package/core/manual/HOW-IT-WORKS.md +250 -0
  42. package/core/resolver.md +30 -0
  43. package/core/skills/archive.md +95 -0
  44. package/core/skills/bootstrap.md +226 -0
  45. package/core/skills/capture.md +65 -0
  46. package/core/skills/check-resolvable.md +38 -0
  47. package/core/skills/close-session.md +108 -0
  48. package/core/skills/grill.md +74 -0
  49. package/core/skills/mount-repo.md +97 -0
  50. package/core/skills/my-wiki.md +103 -0
  51. package/core/skills/new-memory.md +76 -0
  52. package/core/skills/new-product.md +55 -0
  53. package/core/skills/new-spec.md +114 -0
  54. package/core/skills/new-workspace.md +53 -0
  55. package/core/skills/recall.md +64 -0
  56. package/core/skills/rename-heads.md +72 -0
  57. package/core/skills/rename-workspaces.md +43 -0
  58. package/core/skills/supersede.md +83 -0
  59. package/core/skills/sweep.md +40 -0
  60. package/core/templates/my-wiki-graph.js +431 -0
  61. package/core/templates/my-wiki-overview.js +174 -0
  62. package/core/templates/my-wiki.html +1017 -0
  63. package/core/templates/node-folder/README.md +11 -0
  64. package/core/templates/node-folder/resolver.md +9 -0
  65. package/core/templates/node-light.md +22 -0
  66. package/core/templates/node-product/README.md +8 -0
  67. package/core/templates/node-repo/README.md +14 -0
  68. package/core/templates/node-repo/context/README.md +22 -0
  69. package/core/templates/node-repo/context/competitors.md +8 -0
  70. package/core/templates/node-repo/context/glossary.md +8 -0
  71. package/core/templates/node-repo/context/open-questions.md +9 -0
  72. package/core/templates/node-repo/context/opportunities.md +9 -0
  73. package/core/templates/node-repo/context/problem.md +8 -0
  74. package/core/templates/node-repo/context/scope.md +8 -0
  75. package/core/templates/node-repo/context/users.md +8 -0
  76. package/core/templates/node-repo/context/vision.md +8 -0
  77. package/core/templates/node-repo/resolver.md +14 -0
  78. package/core/templates/operator.md +17 -0
  79. package/core/templates/person.md +10 -0
  80. package/core/templates/repo-scaffold/ARCHITECTURE.md +3 -0
  81. package/core/templates/repo-scaffold/CLAUDE.md +23 -0
  82. package/core/templates/repo-scaffold/decisions.md +3 -0
  83. package/core/templates/repo-scaffold/evals-run.sh +14 -0
  84. package/core/templates/repo-scaffold/gitignore +3 -0
  85. package/core/templates/repo-scaffold/settings.json +8 -0
  86. package/core/templates/root-resolver.md +5 -0
  87. package/core/templates/strings.md +1361 -0
  88. package/core/templates/tree.md +59 -0
  89. package/core/templates/voice.md +5 -0
  90. package/package.json +23 -0
@@ -0,0 +1,83 @@
1
+ ---
2
+ command: supersede
3
+ capability: Mark a file as replaced by another
4
+ description: Write on a file the mark that says which other file replaced it, so a session that opens the old one knows what to read instead, and audit the marks of the whole brain — the ones that point at a file that is not there, the ones that close a cycle, and the heads that were replaced and still read as open work. Manually triggered.
5
+ description_es: Escribe sobre un archivo la marca que dice qué otro archivo lo reemplazó, para que una sesión que abra el viejo sepa qué leer en su lugar, y audita las marcas de todo el brain — las que apuntan a un archivo que no está, las que cierran un ciclo y las cabezas reemplazadas que siguen leyéndose como trabajo abierto. Se dispara a mano.
6
+ ---
7
+
8
+ # supersede — a file declares what replaced it
9
+
10
+ A research document from March and one from July that contradicts it are two files a session reads
11
+ as equally current. Git does not settle it: the agent reads the working tree, never the history. The
12
+ answer is one line in the older file, naming the newer one.
13
+
14
+ ## How it is run
15
+
16
+ ```
17
+ .os/core/lib/supersede.sh --brain . --file <old path> --by <new path>
18
+ .os/core/lib/supersede.sh --brain . --check
19
+ ```
20
+
21
+ Both paths are relative to the brain. The mark goes on the file that **was** replaced and points
22
+ forward; the rule itself lives in `.os/core/CLAUDE.md`, and this file does not restate it.
23
+
24
+ ## What it writes
25
+
26
+ One key in the frontmatter of the old file:
27
+
28
+ ```
29
+ superseded_by: workspaces/acme/products/kit/research/2026-07-11-kit.md
30
+ ```
31
+
32
+ A file that has no frontmatter at all gets a three-line block created above its body, untouched. A
33
+ file whose frontmatter cannot be read —no closing `---`, or past the bound— is refused with the
34
+ reason: writing over it would corrupt it in silence.
35
+
36
+ ## What it refuses
37
+
38
+ | Refusal | Why |
39
+ |---|---|
40
+ | a path that is not `.md`, or that no line of `tree.md` reaches | The mark goes on documents of the brain; anything else is a file this system does not govern |
41
+ | an absolute path, a `..`, or one that resolves outside the brain | Every path of the mark is a path of this brain |
42
+ | a symbolic link | Mark the file it points at, by its own path |
43
+ | a body that opens with a `---` that is not a frontmatter | The key would land in the middle of the prose |
44
+ | a file it cannot write | A write that did not happen never reports success |
45
+ | a `--by` that leads back to `--file`, or a chain it could not finish | A cycle hangs whoever follows it, and undecided is not the same as clean |
46
+
47
+ ## What happens to a head
48
+
49
+ When the file is the head of a node or an initiative and its `status` is `active` with nothing
50
+ depending on it, the status also goes to `closed` — and the output says so. Three heads are left as
51
+ they are, with the mark written, the reason printed and exit code 3:
52
+
53
+ | State of the head | Why it stays open |
54
+ |---|---|
55
+ | `ongoing` | Permanent work does not end because a document was replaced |
56
+ | `blocked` | Closing it drops what it is waiting for without anyone reading it |
57
+ | another head declares it in `depends_on:` | A closed dependency reads as satisfied, and that other head would show as unblocked by nobody |
58
+
59
+ In those three the decision is the operator's: close it by hand, or re-point what depends on it.
60
+
61
+ ## What `--check` reports
62
+
63
+ | Finding | What to do |
64
+ |---|---|
65
+ | points at nothing | Fix the path, or drop the key |
66
+ | points at itself | Drop the key |
67
+ | cycle | Two files, or twenty, lead back to the first; decide which one is current and drop the other keys |
68
+ | chain undecided | The chain is longer than the walk's bound; read it by hand |
69
+ | mark inside an unreadable frontmatter | Close the frontmatter, or the mark exists for nobody |
70
+ | open head | Its `status` is `active` after the mark; close it |
71
+
72
+ It exits non-zero when it found something and writes nothing, which is what it takes to hang it off
73
+ a cron. Over a brain whose `tree.md` it could not read it exits non-zero too, instead of reporting
74
+ that everything resolves.
75
+
76
+ ## What it does not do
77
+
78
+ It does not decide that a document is stale. Deciding is the operator's; this command records the
79
+ decision where the next session will read it.
80
+
81
+ There is no line about this in the session scan, on purpose: the scan reads the head of every node
82
+ and never opens a content file, and the documents this mark exists for are content. A startup line
83
+ would count half of them. The audit above covers both.
@@ -0,0 +1,40 @@
1
+ ---
2
+ command: sweep
3
+ capability: See what is pending
4
+ capability: See what is blocked and why
5
+ capability: See how the roadmap is going
6
+ description: Run one of the three global scans over every workspace plus the root's own work — what is pending, what is blocked and why, or how the roadmap is going — reading frontmatter only. Manually triggered; the mode is an argument, not a separate command.
7
+ description_es: Corre uno de los tres barridos globales sobre todos los espacios de trabajo más el trabajo propio de la raíz — qué hay pendiente, qué está trabado y por qué, o cómo va el roadmap — leyendo solo frontmatter. Se dispara a mano; el modo es un argumento, no un comando aparte.
8
+ ---
9
+
10
+ # sweep — the three global scans
11
+
12
+ Three modes of one tool, not three commands. They answer "what do I have pending?", "what is blocked
13
+ and why?" and "how is the roadmap going?" reading frontmatter only, across every organization at
14
+ once — and the root's own work along with them, grouped separately.
15
+
16
+ ## How it is run
17
+
18
+ ```
19
+ .os/core/lib/sweep.sh --brain . --mode pending
20
+ .os/core/lib/sweep.sh --brain . --mode blocked
21
+ .os/core/lib/sweep.sh --brain . --mode roadmap
22
+ ```
23
+
24
+ The environment table —the one mapping a mounted node's remote to its local path on this machine—
25
+ is read on its own from `mounts.md`, at the root of the brain: `--mounts <path>` is an override and
26
+ does not need to be passed. With no table the scan covers the brain only and says so; with a mount
27
+ declared and not cloned, it reports it as unreachable and continues. `mount-repo` writes it.
28
+
29
+ ## What to do with the output
30
+
31
+ **The output is the state.** It is shown exactly as it came out and it is not recomputed, nor
32
+ completed with inferences, nor summarized. Above it goes a one-line reading and a suggested next
33
+ action.
34
+
35
+ **Whatever shows up under "Sin clasificar" is never guessed.** A head without `status` or without
36
+ `horizon` has no state the scan can deduce: the operator is offered the chance to write it, with the
37
+ path.
38
+
39
+ **The body of an initiative is loaded only once the operator picks a focus.** The scan reads
40
+ frontmatter: enough to choose, not enough to work.
@@ -0,0 +1,431 @@
1
+ /* My Wiki's Graph screen (spec 061). Inlined verbatim into the page by `my_wiki_build.py`, in one
2
+ <script id="wiki-graph"> block, right before `wiki-view` so `WIKIGRAPH` exists when the router
3
+ first runs. No DOM is touched outside a function body, so this whole file loads and its pure
4
+ half (WIKIGRAPH.neighbors/atDate/applyHide/view/radius/layout) runs the same way in a plain
5
+ Node `vm` context as it does in the page — that pure half is what the suite exercises headless,
6
+ the same pattern `wiki-core` set in spec 060. `WIKIGRAPH.mount` is the DOM half; nothing calls
7
+ it outside a real page. */
8
+ var WIKIGRAPH = (function () {
9
+ // One radius per kind, before its own connections grow it (spec 061 C1).
10
+ var BASE_RADIUS = {workspace: 14, entity: 9, initiative: 7, person: 6, document: 4};
11
+ var COLORS = {workspace: 'var(--text)', entity: 'var(--accent)', initiative: '#0f8b8d',
12
+ person: '#d97706', document: 'var(--muted)'};
13
+ var LEGEND_ORDER = ['workspace', 'entity', 'initiative', 'person', 'document'];
14
+
15
+ function radius(kind, degree) {
16
+ var base = BASE_RADIUS[kind] || 5;
17
+ return base + Math.min(degree || 0, 12) * 0.5;
18
+ }
19
+
20
+ // Every neighbour of one node, from the edge list alone — what a hover highlights (C3).
21
+ function neighbors(edges, id) {
22
+ var seen = {}, out = [];
23
+ for (var i = 0; i < edges.length; i++) {
24
+ var e = edges[i], other = null;
25
+ if (e.a === id) other = e.b;
26
+ else if (e.b === id) other = e.a;
27
+ if (other !== null && !seen[other]) { seen[other] = true; out.push(other); }
28
+ }
29
+ return out;
30
+ }
31
+
32
+ function edgesAmong(edges, ids) {
33
+ return edges.filter(function (e) { return ids[e.a] && ids[e.b]; });
34
+ }
35
+
36
+ function scope(graph, ws) {
37
+ if (!ws) return graph;
38
+ var nodes = graph.nodes.filter(function (n) { return n.ws === ws; });
39
+ var ids = {};
40
+ nodes.forEach(function (n) { ids[n.id] = true; });
41
+ return {nodes: nodes, edges: edgesAmong(graph.edges, ids), dates: graph.dates};
42
+ }
43
+
44
+ // Only what already existed at `date` — the state one tick of "how it grew" shows (C5). A node
45
+ // with no known first commit is treated as always having been there, never hidden by a date it
46
+ // does not carry.
47
+ function atDate(graph, date) {
48
+ if (!date) return graph;
49
+ var ids = {};
50
+ var nodes = graph.nodes.filter(function (n) {
51
+ var ok = !n.first || n.first <= date;
52
+ if (ok) ids[n.id] = true;
53
+ return ok;
54
+ });
55
+ return {nodes: nodes, edges: edgesAmong(graph.edges, ids), dates: graph.dates};
56
+ }
57
+
58
+ // Hiding a type never recomputes anything about the rest (C4): it is a pure filter on top of
59
+ // whatever scope/date already produced.
60
+ function applyHide(graph, hide) {
61
+ hide = hide || {};
62
+ var nodes = graph.nodes.filter(function (n) { return !hide[n.kind]; });
63
+ var ids = {};
64
+ nodes.forEach(function (n) { ids[n.id] = true; });
65
+ return {nodes: nodes, edges: edgesAmong(graph.edges, ids), dates: graph.dates};
66
+ }
67
+
68
+ // The one composition point every other filter goes through, headless-testable end to end.
69
+ function view(graph, opts) {
70
+ opts = opts || {};
71
+ var g = scope(graph, opts.ws);
72
+ g = atDate(g, opts.date);
73
+ g = applyHide(g, opts.hide);
74
+ return g;
75
+ }
76
+
77
+ // A minimal force layout: repulsion between every pair, a spring on every edge, a pull to the
78
+ // centre so a page with no link at all still settles on the canvas instead of flying off it
79
+ // (spec 061: an unlinked page shows loose and dim, never hidden). Fixed tick count, no timers,
80
+ // no DOM — the same run in Node as in the page, which is how C7's 650-node budget is measured.
81
+ function layout(graph, opts) {
82
+ opts = opts || {};
83
+ // 60 ticks is a compromise, not a perfect settle: spec 061's budget is 650 nodes drawn in
84
+ // under 2 seconds, and a rough, organic scatter reads fine for a screen nobody stares at
85
+ // pixel-perfect. More ticks converge tighter but blow the budget well before 650 nodes do.
86
+ var w = opts.width || 760, h = opts.height || 520, ticks = opts.ticks || 60;
87
+ var n = graph.nodes.length;
88
+ var nodes = graph.nodes.map(function (node, i) {
89
+ var a = n ? (i / n) * Math.PI * 2 : 0;
90
+ return {
91
+ id: node.id, kind: node.kind, degree: node.degree,
92
+ x: w / 2 + Math.cos(a) * (Math.min(w, h) / 3),
93
+ y: h / 2 + Math.sin(a) * (Math.min(w, h) / 3),
94
+ vx: 0, vy: 0,
95
+ };
96
+ });
97
+ var index = {};
98
+ nodes.forEach(function (node, i) { index[node.id] = i; });
99
+ var edges = [];
100
+ for (var e = 0; e < graph.edges.length; e++) {
101
+ var a = index[graph.edges[e].a], b = index[graph.edges[e].b];
102
+ if (a !== undefined && b !== undefined) edges.push({a: a, b: b});
103
+ }
104
+ var REPEL = 2600, SPRING = 0.02, LEN = 70, CENTER = 0.012, DAMP = 0.85;
105
+ for (var t = 0; t < ticks; t++) {
106
+ for (var i = 0; i < nodes.length; i++) {
107
+ var ni = nodes[i];
108
+ for (var j = i + 1; j < nodes.length; j++) {
109
+ var nj = nodes[j];
110
+ var dx = ni.x - nj.x, dy = ni.y - nj.y;
111
+ var d2 = dx * dx + dy * dy + 0.01;
112
+ var f = REPEL / d2;
113
+ var d = Math.sqrt(d2);
114
+ var fx = (dx / d) * f, fy = (dy / d) * f;
115
+ ni.vx += fx; ni.vy += fy;
116
+ nj.vx -= fx; nj.vy -= fy;
117
+ }
118
+ }
119
+ for (var k = 0; k < edges.length; k++) {
120
+ var na = nodes[edges[k].a], nb = nodes[edges[k].b];
121
+ var ex = nb.x - na.x, ey = nb.y - na.y;
122
+ var ed = Math.sqrt(ex * ex + ey * ey) || 0.01;
123
+ var stretch = (ed - LEN) * SPRING;
124
+ var sfx = (ex / ed) * stretch, sfy = (ey / ed) * stretch;
125
+ na.vx += sfx; na.vy += sfy;
126
+ nb.vx -= sfx; nb.vy -= sfy;
127
+ }
128
+ for (var m = 0; m < nodes.length; m++) {
129
+ var nm = nodes[m];
130
+ nm.vx += (w / 2 - nm.x) * CENTER;
131
+ nm.vy += (h / 2 - nm.y) * CENTER;
132
+ nm.vx *= DAMP; nm.vy *= DAMP;
133
+ nm.x += nm.vx; nm.y += nm.vy;
134
+ }
135
+ }
136
+ return nodes;
137
+ }
138
+
139
+ return {
140
+ COLORS: COLORS, LEGEND_ORDER: LEGEND_ORDER,
141
+ radius: radius, neighbors: neighbors, scope: scope, atDate: atDate, applyHide: applyHide,
142
+ view: view, layout: layout,
143
+ };
144
+ })();
145
+ if (typeof module !== 'undefined' && module.exports) { module.exports = WIKIGRAPH; }
146
+
147
+ (function () {
148
+ // The DOM half (spec 066): a <canvas> with its own force simulation, pan and zoom, drag, hover
149
+ // highlight, click to open, filters and the time slider. Nothing loads from outside the page.
150
+ function ensureStyle() {
151
+ if (typeof document === 'undefined' || document.getElementById('wiki-graph-style')) return;
152
+ var css =
153
+ '.graph-legend{display:flex;gap:14px;margin-bottom:10px;flex-wrap:wrap;font-size:13px;color:var(--text);align-items:center}' +
154
+ '.graph-legend .sw{width:10px;height:10px;border-radius:999px;display:inline-block;margin-right:6px}' +
155
+ '.graph-filters{margin-left:auto;display:flex;gap:8px}' +
156
+ '.graph-filters .chip{cursor:pointer;user-select:none}' +
157
+ '.graph-wrap{border:1px solid var(--border);background:var(--card);border-radius:12px;overflow:hidden;position:relative}' +
158
+ '.graph-wrap canvas{display:block;width:100%;cursor:grab}' +
159
+ '.graph-wrap canvas.grabbing{cursor:grabbing}' +
160
+ '.graph-hint{position:absolute;right:10px;bottom:8px;font-size:11.5px;color:var(--muted);pointer-events:none}' +
161
+ '.graph-slider-row{display:flex;align-items:center;gap:12px;margin-top:12px}' +
162
+ '.graph-slider-row input[type=range]{flex:1;accent-color:var(--accent)}' +
163
+ '.graph-date{font-family:ui-monospace,Menlo,monospace;font-size:12.5px;color:var(--muted);min-width:86px;text-align:right}';
164
+ var styleTag = document.createElement('style');
165
+ styleTag.id = 'wiki-graph-style';
166
+ styleTag.textContent = css;
167
+ document.head.appendChild(styleTag);
168
+ }
169
+ function esc(s) {
170
+ return String(s == null ? '' : s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
171
+ }
172
+ function cssVar(name, fallback) {
173
+ try { var v = getComputedStyle(document.documentElement).getPropertyValue(name).trim(); return v || fallback; } catch (e) { return fallback; }
174
+ }
175
+ function hexA(hex, a) {
176
+ var m = /^#([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})$/i.exec(hex || '');
177
+ if (!m) return hex;
178
+ return 'rgba(' + parseInt(m[1], 16) + ',' + parseInt(m[2], 16) + ',' + parseInt(m[3], 16) + ',' + a + ')';
179
+ }
180
+
181
+ // What survives between visits to the screen inside one visit to the page: the camera, the
182
+ // filters, the date, and where the reader left the nodes.
183
+ var keep = {};
184
+
185
+ WIKIGRAPH.mount = function (root, DATA, T, href, opts) {
186
+ ensureStyle();
187
+ opts = opts || {};
188
+ var full = DATA.graph || {nodes: [], edges: [], dates: []};
189
+ // The builder's edges are the explicit links (about:, paths in backticks, people). The graph
190
+ // also needs the structure the brain already has —a document hangs from its node, an
191
+ // initiative from its entity, an entity from its workspace— or most pages float alone.
192
+ if (!full._structured) {
193
+ var seen = {}; full.edges.forEach(function (e) { seen[e.a + '|' + e.b] = 1; seen[e.b + '|' + e.a] = 1; });
194
+ var homes = {}; (DATA.workspaces || []).forEach(function (w) { homes[w.slug] = w.home; });
195
+ function link(a, b) { if (!a || !b || a === b || seen[a + '|' + b]) return; seen[a + '|' + b] = 1; seen[b + '|' + a] = 1; full.edges.push({a: a, b: b, structural: true}); }
196
+ var pages = DATA.pages || {};
197
+ for (var id in pages) {
198
+ var pg = pages[id];
199
+ // The builder keeps the tree on the node: `docs` are the documents that hang from it,
200
+ // `children` its initiatives, `about` the entity an initiative belongs to.
201
+ (pg.docs || []).forEach(function (d) { var dp = d && (d.path || d); if (pages[dp]) link(dp, id); });
202
+ (pg.children || []).forEach(function (c) { if (pages[c]) link(c, id); });
203
+ if (pg.kind === 'initiative') {
204
+ var ent = pg.about || (pg.fm && pg.fm.about) || '';
205
+ ent = String(ent).replace(/^\.?\/?/, '');
206
+ if (ent && pages[ent]) link(id, ent); else if (homes[pg.ws]) link(id, homes[pg.ws]);
207
+ } else if ((pg.kind === 'entity' || pg.kind === 'person') && homes[pg.ws]) link(id, homes[pg.ws]);
208
+ }
209
+ var deg = {}; full.edges.forEach(function (e) { deg[e.a] = (deg[e.a] || 0) + 1; deg[e.b] = (deg[e.b] || 0) + 1; });
210
+ full.nodes.forEach(function (n) { n.degree = deg[n.id] || 0; });
211
+ full._structured = true;
212
+ }
213
+ var dates = full.dates || [];
214
+ var k = keep[opts.ws] || (keep[opts.ws] = {hide: {document: true, person: false}, labels: false, dateIdx: dates.length ? dates.length - 1 : -1, cam: null, pos: {}});
215
+ var state = {ws: opts.ws, hover: null, drag: null, playing: null, raf: null, alpha: 1};
216
+ var COLORS = {workspace: cssVar('--text', '#1c1b22'), entity: cssVar('--accent', '#4b5563'), initiative: '#0f8b8d', person: '#d97706', document: cssVar('--muted', '#6b6a75')};
217
+
218
+ root.innerHTML =
219
+ '<div class="graph-legend">' +
220
+ [['entity', T('WIKI_GRAPH_ENTITY', 'Entities')], ['initiative', T('WIKI_GRAPH_INITIATIVE', 'Initiatives')], ['person', T('WIKI_GRAPH_PERSON', 'People')], ['document', T('WIKI_GRAPH_DOCUMENT', 'Documents')]]
221
+ .map(function (l) { return '<span><span class="sw" style="background:' + COLORS[l[0]] + '"></span>' + esc(l[1]) + '</span>'; }).join('') +
222
+ '<span class="graph-filters">' +
223
+ '<span class="chip' + (k.hide.document ? '' : ' vio') + '" data-hide="document">' + esc(T('WIKI_GRAPH_SHOW_DOCS', 'Show documents')) + '</span>' +
224
+ '<span class="chip' + (k.hide.person ? '' : ' vio') + '" data-hide="person">' + esc(T('WIKI_GRAPH_SHOW_PEOPLE', 'Show people')) + '</span>' +
225
+ '<label class="chip" style="cursor:pointer;gap:6px"><input type="checkbox" data-labels' + (k.labels ? ' checked' : '') + ' style="margin:0"> ' + esc(T('WIKI_GRAPH_LABELS', 'Labels')) + '</label>' +
226
+ '</span></div>' +
227
+ '<div class="graph-wrap"><canvas></canvas><div class="graph-hint">' + esc(T('WIKI_GRAPH_HINT', 'drag · wheel to zoom · double-click to fit · click opens')) + '</div></div>' +
228
+ (dates.length ? '<div class="graph-slider-row"><span class="muted" style="font-size:13px">' + esc(T('WIKI_GRAPH_GREW', 'How it grew')) + '</span>' +
229
+ '<input type="range" min="0" max="' + (dates.length - 1) + '" value="' + k.dateIdx + '">' +
230
+ '<span class="graph-date"></span><button class="btn" data-play>' + esc(T('WIKI_GRAPH_PLAY', 'Play')) + '</button></div>' : '');
231
+
232
+ var canvas = root.querySelector('canvas'), ctx = canvas.getContext('2d');
233
+ var wrap = root.querySelector('.graph-wrap');
234
+ var W = 0, H = 520, dpr = window.devicePixelRatio || 1;
235
+ function size() {
236
+ W = wrap.clientWidth || 760;
237
+ canvas.width = W * dpr; canvas.height = H * dpr; canvas.style.height = H + 'px';
238
+ ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
239
+ }
240
+ size();
241
+
242
+ // The graph on screen: the pure half filters by workspace, date and hidden kinds.
243
+ var nodes = [], edges = [], byId = {}, adj = {};
244
+ function rebuild(reheat) {
245
+ var g = WIKIGRAPH.view(full, {ws: state.ws, date: k.dateIdx >= 0 ? dates[k.dateIdx] : null, hide: k.hide});
246
+ var old = {}; nodes.forEach(function (n) { old[n.id] = n; });
247
+ nodes = g.nodes.map(function (n) {
248
+ var p = old[n.id] || k.pos[n.id];
249
+ var r = WIKIGRAPH.radius(n.kind, n.degree) * 1.7;
250
+ return {id: n.id, kind: n.kind, title: n.title, degree: n.degree, r: r,
251
+ x: p ? p.x : (W / 2 + (Math.random() - .5) * W * .6), y: p ? p.y : (H / 2 + (Math.random() - .5) * H * .6),
252
+ vx: 0, vy: 0, fx: p && p.fx != null ? p.fx : null, fy: p && p.fy != null ? p.fy : null};
253
+ });
254
+ byId = {}; nodes.forEach(function (n) { byId[n.id] = n; });
255
+ edges = g.edges.filter(function (e) { return byId[e.a] && byId[e.b]; });
256
+ adj = {}; edges.forEach(function (e) { (adj[e.a] = adj[e.a] || {})[e.b] = 1; (adj[e.b] = adj[e.b] || {})[e.a] = 1; });
257
+ if (reheat) state.alpha = 1;
258
+ if (!k.cam) fit(true);
259
+ loop();
260
+ }
261
+
262
+ // Camera ------------------------------------------------------------------------
263
+ function fit(silent) {
264
+ if (!nodes.length) { k.cam = {x: 0, y: 0, s: 1}; return; }
265
+ var minX = 1e9, minY = 1e9, maxX = -1e9, maxY = -1e9;
266
+ nodes.forEach(function (n) { minX = Math.min(minX, n.x); maxX = Math.max(maxX, n.x); minY = Math.min(minY, n.y); maxY = Math.max(maxY, n.y); });
267
+ var s = Math.min(2.2, Math.max(.2, .92 * Math.min(W / Math.max(1, maxX - minX + 80), H / Math.max(1, maxY - minY + 80))));
268
+ k.cam = {s: s, x: W / 2 - s * (minX + maxX) / 2, y: H / 2 - s * (minY + maxY) / 2};
269
+ if (!silent) draw();
270
+ }
271
+ function toWorld(px, py) { return {x: (px - k.cam.x) / k.cam.s, y: (py - k.cam.y) / k.cam.s}; }
272
+
273
+ // Physics -----------------------------------------------------------------------
274
+ // Repulsion between every pair (n² is fine for a few hundred nodes), links as springs, a soft
275
+ // pull to the centre, velocity damping, and a temperature that cools until the graph sleeps.
276
+ function tick() {
277
+ var n = nodes.length; if (!n) return;
278
+ var a = state.alpha;
279
+ var k2 = 2600 * a;
280
+ for (var i = 0; i < n; i++) {
281
+ var p = nodes[i];
282
+ for (var j = i + 1; j < n; j++) {
283
+ var q = nodes[j];
284
+ var dx = p.x - q.x, dy = p.y - q.y, d2 = dx * dx + dy * dy + 0.01;
285
+ if (d2 > 90000) continue;
286
+ var f = k2 / d2;
287
+ var fx = dx * f, fy = dy * f;
288
+ p.vx += fx; p.vy += fy; q.vx -= fx; q.vy -= fy;
289
+ }
290
+ }
291
+ var springK = 0.02 * a + 0.002;
292
+ for (var e = 0; e < edges.length; e++) {
293
+ var s1 = byId[edges[e].a], s2 = byId[edges[e].b];
294
+ var ddx = s2.x - s1.x, ddy = s2.y - s1.y, d = Math.sqrt(ddx * ddx + ddy * ddy) + 0.01;
295
+ var rest = 34 + s1.r + s2.r;
296
+ var f2 = (d - rest) * springK;
297
+ var ux = ddx / d * f2, uy = ddy / d * f2;
298
+ s1.vx += ux; s1.vy += uy; s2.vx -= ux; s2.vy -= uy;
299
+ }
300
+ var cx = 0, cy = 0; nodes.forEach(function (m) { cx += m.x; cy += m.y; }); cx /= n; cy /= n;
301
+ nodes.forEach(function (m) {
302
+ m.vx += (cx - m.x) * 0.0015 * a + (W / 2 - cx) * 0.0005;
303
+ m.vy += (cy - m.y) * 0.0015 * a + (H / 2 - cy) * 0.0005;
304
+ if (m.fx != null) { m.x = m.fx; m.y = m.fy; m.vx = 0; m.vy = 0; return; }
305
+ m.vx *= 0.82; m.vy *= 0.82;
306
+ m.x += m.vx; m.y += m.vy;
307
+ });
308
+ state.alpha = Math.max(0, a - 0.008);
309
+ }
310
+ function loop() {
311
+ if (state.raf) return;
312
+ var step = function () {
313
+ state.raf = null;
314
+ if (state.alpha > 0.003 || state.drag) { tick(); draw(); state.raf = requestAnimationFrame(step); }
315
+ else { draw(); nodes.forEach(function (m) { k.pos[m.id] = {x: m.x, y: m.y, fx: m.fx, fy: m.fy}; }); }
316
+ };
317
+ state.raf = requestAnimationFrame(step);
318
+ }
319
+
320
+ // Drawing ----------------------------------------------------------------------
321
+ function draw() {
322
+ ctx.save(); ctx.clearRect(0, 0, W, H);
323
+ ctx.translate(k.cam.x, k.cam.y); ctx.scale(k.cam.s, k.cam.s);
324
+ var hov = state.hover, nb = hov ? (adj[hov] || {}) : null;
325
+ var border = cssVar('--border', '#e5e5e8'), accent = cssVar('--accent', '#4b5563'), text = cssVar('--text', '#1c1b22');
326
+ ctx.lineWidth = 1 / k.cam.s;
327
+ edges.forEach(function (e) {
328
+ var a = byId[e.a], b = byId[e.b];
329
+ var hi = hov && (e.a === hov || e.b === hov);
330
+ ctx.strokeStyle = hi ? accent : (e.structural ? border : accent);
331
+ ctx.globalAlpha = hov ? (hi ? 1 : .15) : (e.structural ? .9 : .55);
332
+ ctx.lineWidth = (hi ? 1.8 : 1) / k.cam.s;
333
+ ctx.beginPath(); ctx.moveTo(a.x, a.y); ctx.lineTo(b.x, b.y); ctx.stroke();
334
+ });
335
+ var labelOK = k.cam.s > 0.55;
336
+ nodes.forEach(function (m) {
337
+ var dim = hov && m.id !== hov && !nb[m.id];
338
+ ctx.globalAlpha = dim ? .18 : 1;
339
+ ctx.fillStyle = COLORS[m.kind] || COLORS.document;
340
+ ctx.beginPath(); ctx.arc(m.x, m.y, m.r, 0, Math.PI * 2); ctx.fill();
341
+ if (m.id === hov) { ctx.strokeStyle = accent; ctx.lineWidth = 2 / k.cam.s; ctx.beginPath(); ctx.arc(m.x, m.y, m.r + 4 / k.cam.s, 0, Math.PI * 2); ctx.stroke(); }
342
+ var showLabel = m.id === hov || (nb && nb[m.id]) || (k.labels && !hov && (m.kind !== 'document' || (labelOK && k.cam.s > 1.1)));
343
+ if (showLabel && (labelOK || m.id === hov || m.kind !== 'document')) {
344
+ ctx.fillStyle = text; ctx.globalAlpha = dim ? .18 : (m.kind === 'document' ? .75 : 1);
345
+ ctx.font = ((m.kind === 'entity' || m.kind === 'workspace' ? 13 : 11.5) / Math.max(k.cam.s, .8)) + 'px ' + cssVar('--font', 'system-ui');
346
+ ctx.fillText(m.title, m.x + m.r + 4 / k.cam.s, m.y + 4 / k.cam.s);
347
+ }
348
+ });
349
+ ctx.restore();
350
+ var dl = root.querySelector('.graph-date'); if (dl) dl.textContent = k.dateIdx >= 0 ? dates[k.dateIdx] : '';
351
+ }
352
+
353
+ // Interaction ------------------------------------------------------------------
354
+ function nodeAt(px, py) {
355
+ var w = toWorld(px, py), best = null, bd = 1e9;
356
+ nodes.forEach(function (m) { var dx = m.x - w.x, dy = m.y - w.y, d = dx * dx + dy * dy; var rr = (m.r + 6 / k.cam.s); if (d < rr * rr && d < bd) { bd = d; best = m; } });
357
+ return best;
358
+ }
359
+ function pt(ev) { var r = canvas.getBoundingClientRect(); return {x: ev.clientX - r.left, y: ev.clientY - r.top}; }
360
+ var pressed = null, moved = false;
361
+ canvas.addEventListener('mousedown', function (ev) {
362
+ var p = pt(ev), m = nodeAt(p.x, p.y);
363
+ pressed = {x: p.x, y: p.y, node: m, cam: {x: k.cam.x, y: k.cam.y}}; moved = false;
364
+ if (m) { state.drag = m; m.fx = m.x; m.fy = m.y; state.alpha = Math.max(state.alpha, .3); loop(); }
365
+ canvas.classList.add('grabbing');
366
+ });
367
+ window.addEventListener('mousemove', function (ev) {
368
+ var p = pt(ev);
369
+ if (pressed) {
370
+ if (Math.abs(p.x - pressed.x) + Math.abs(p.y - pressed.y) > 3) moved = true;
371
+ if (pressed.node) { var w = toWorld(p.x, p.y); pressed.node.fx = w.x; pressed.node.fy = w.y; state.alpha = Math.max(state.alpha, .3); loop(); }
372
+ else { k.cam.x = pressed.cam.x + (p.x - pressed.x); k.cam.y = pressed.cam.y + (p.y - pressed.y); draw(); }
373
+ return;
374
+ }
375
+ var m = nodeAt(p.x, p.y), id = m ? m.id : null;
376
+ if (id !== state.hover) { state.hover = id; canvas.style.cursor = m ? 'pointer' : 'grab'; draw(); }
377
+ });
378
+ window.addEventListener('mouseup', function (ev) {
379
+ if (!pressed) return;
380
+ var m = pressed.node;
381
+ // A dropped node stays exactly where it was released — `fx`/`fy` keep pinning it, the same
382
+ // way Obsidian's graph pins a node once dragged (spec 066 C1). It moves again only if
383
+ // someone drags it again; nothing un-pins it on its own.
384
+ if (m) { if (!moved) { location.hash = href(m.id); } state.drag = null; }
385
+ pressed = null; canvas.classList.remove('grabbing'); loop();
386
+ });
387
+ canvas.addEventListener('wheel', function (ev) {
388
+ ev.preventDefault();
389
+ var p = pt(ev), w = toWorld(p.x, p.y);
390
+ var s = Math.min(4, Math.max(.1, k.cam.s * (ev.deltaY < 0 ? 1.12 : 1 / 1.12)));
391
+ k.cam = {s: s, x: p.x - w.x * s, y: p.y - w.y * s};
392
+ draw();
393
+ }, {passive: false});
394
+ canvas.addEventListener('dblclick', function () { fit(); });
395
+ canvas.addEventListener('mouseleave', function () { if (state.hover) { state.hover = null; draw(); } });
396
+
397
+ Array.prototype.forEach.call(root.querySelectorAll('[data-hide]'), function (c) {
398
+ c.onclick = function () { var kind = c.getAttribute('data-hide'); k.hide[kind] = !k.hide[kind]; c.classList.toggle('vio', !k.hide[kind]); rebuild(false); };
399
+ });
400
+ var lb = root.querySelector('[data-labels]');
401
+ if (lb) lb.onchange = function () { k.labels = !!lb.checked; draw(); };
402
+ var slider = root.querySelector('input[type=range]');
403
+ if (slider) slider.oninput = function () { k.dateIdx = parseInt(slider.value, 10); rebuild(false); };
404
+ var play = root.querySelector('[data-play]');
405
+ if (play) play.onclick = function () {
406
+ if (state.playing) { clearInterval(state.playing); state.playing = null; play.textContent = T('WIKI_GRAPH_PLAY', 'Play'); return; }
407
+ k.dateIdx = 0; slider.value = 0; rebuild(true); play.textContent = T('WIKI_GRAPH_PAUSE', 'Pause');
408
+ state.playing = setInterval(function () {
409
+ if (k.dateIdx >= dates.length - 1) { clearInterval(state.playing); state.playing = null; play.textContent = T('WIKI_GRAPH_PLAY', 'Play'); return; }
410
+ k.dateIdx++; slider.value = k.dateIdx; rebuild(false);
411
+ }, 500);
412
+ };
413
+ window.addEventListener('resize', function () { size(); draw(); });
414
+
415
+ rebuild(true);
416
+ // `_debug` is read only by evals/fixtures/wiki-graph-headless.js (spec 066's `canvas` mode),
417
+ // which has no browser to click and drag in. It exposes nothing a real caller uses.
418
+ return {
419
+ unmount: function () { if (state.playing) clearInterval(state.playing); },
420
+ _debug: {
421
+ nodes: function () { return nodes; },
422
+ state: state,
423
+ cam: function () { return k.cam; },
424
+ hide: function () { return k.hide; },
425
+ neighborsOf: function (id) { return Object.keys(adj[id] || {}); },
426
+ colors: COLORS,
427
+ edgeCount: function () { return edges.length; },
428
+ },
429
+ };
430
+ };
431
+ })();