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,548 @@
1
+ #!/usr/bin/env python3
2
+ """My Wiki's builder (spec 060). Internal: `my-wiki.sh` is the invocable; this file has no
3
+ `command:` header and is never called on its own.
4
+
5
+ Called as: my_wiki_build.py BRAIN WSDIR HEAD_FILE VAULT TEMPLATE OUT GENERATED VERSION
6
+
7
+ Reads its input on stdin, in blocks opened by a sentinel line. Everything that needs a reader the
8
+ product already owns is read on the bash side and handed over here: the tree (`os_tree_globs`,
9
+ `os_tree_files`, `os_tree_content_files`), the mount table (`os_mounts_filas`), the runtime prose
10
+ (`os_lang_load`) and git. There is no second parser of any of those formats in this file.
11
+
12
+ %%STRINGS%% KEY<TAB>text
13
+ %%GLOBS%% one `glob:` pattern per line, unexpanded
14
+ %%HEADS%% one path per line — what the `glob:` class reaches
15
+ %%FILES%% one path per line — what the `content:` class reaches
16
+ %%MOUNTS%% remote<TAB>local path<TAB>last merge date
17
+ %%OVERVIEW%% key<TAB>value — the options of the first screen (spec 062)
18
+ %%GATES%% gate<TAB>repo<TAB>spec<TAB>title<TAB>date<TAB>branch, already resolved by git
19
+
20
+ NOTHING OF THE MACHINERY REACHES THE PAGE (spec 060 C3). The filter is `MACHINERY`, below, and it
21
+ runs before anything is read: a file it names is never opened, so its content cannot leak into the
22
+ payload by way of a section, a search body or a listing.
23
+
24
+ NO ENTITY TYPE IS WRITTEN IN THIS FILE (C1). The shelves of a workspace are derived from the
25
+ `glob:` patterns of the brain's own tree: a pattern of the shape `<wsdir>/*/<type>/*` declares a
26
+ type, and its name is the shelf's name. `initiatives` and `people` are the two names this file
27
+ does know, and it knows them as *layouts* the view has — a stretch with a state, a directory of
28
+ people — never as a list of what a brain may contain.
29
+ """
30
+
31
+ import json
32
+ import os
33
+ import re
34
+ import sys
35
+
36
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
37
+ import markdown as md # noqa: E402
38
+ import my_wiki_graph as mwg # noqa: E402 — the Graph screen's data, built once below (spec 061)
39
+ import my_wiki_overview # noqa: E402
40
+
41
+ BRAIN, WSDIR, HEAD_FILE, VAULT, TEMPLATE, OUT, GENERATED, VERSION = sys.argv[1:9]
42
+
43
+ # The machinery, by basename and by path segment. A file this names is never opened.
44
+ MACHINERY_FILES = (
45
+ "resolver.md", "tree.md", "operator.md", "mounts.md", "inbox.md",
46
+ "voice.md", "CLAUDE.md", "AGENTS.md", "skills-lock.md", "skills-lock.json",
47
+ )
48
+ MACHINERY_DIRS = ("roles", "voice", ".os", ".claude", ".git", "skills")
49
+
50
+ # A section's name decides its icon, and a name with no entry gets the generic one. The map is the
51
+ # only place a section name appears, and no name here is required to exist in any brain.
52
+ # One rule for every icon in the page: a section heading, a document group, a shelf. The name
53
+ # is normalized —lowercase, no accents, no trailing "s"— and looked up here; anything unknown gets
54
+ # the generic dot. The page reads this same table from `data.json` (`icons`), so the two never
55
+ # drift.
56
+ SECTION_ICONS = {
57
+ "task": "check", "tarea": "check", "backlog": "check", "pendiente": "check",
58
+ "decision": "gavel", "decisione": "gavel",
59
+ "learning": "bulb", "aprendizaje": "bulb",
60
+ "stakeholder": "people", "people": "people", "persona": "people", "equipo": "people", "team": "people",
61
+ "open question": "question", "pregunta abierta": "question", "abierto": "question", "dudas": "question",
62
+ "development": "code", "desarrollo": "code", "spec": "code",
63
+ "research": "search", "investigacion": "search",
64
+ "context": "compass", "contexto": "compass", "strategy": "compass", "estrategia": "compass",
65
+ "initiative": "flag", "iniciativa": "flag",
66
+ "document": "doc", "documento": "doc", "material": "book", "piece": "doc", "pieza": "doc",
67
+ "resumen": "doc", "summary": "doc", "registro": "doc",
68
+ "mention": "link", "mencione": "link", "mencion": "link",
69
+ }
70
+ DEFAULT_ICON = "dot"
71
+
72
+
73
+ def section_icon(name):
74
+ """The icon of a section or a document group by its name, under one normalization: lowercase,
75
+ accents stripped, a final "s" dropped. "Investigación", "Research" and "researchs" all land on
76
+ the same key."""
77
+ import unicodedata
78
+ n = unicodedata.normalize("NFD", (name or "").strip().lower())
79
+ n = "".join(c for c in n if unicodedata.category(c) != "Mn")
80
+ n = re.sub(r"[\s_-]+", " ", n).strip()
81
+ # A heading that qualifies itself —"Open — closed by the operator", "Decisions (2026)"— is looked
82
+ # up by its head: what comes before the dash, the colon or the parenthesis; then by its first word.
83
+ candidates = [n, re.split(r"\s+[—–-]\s+|:|\(", n)[0].strip(), n.split(" ")[0]]
84
+ for c in candidates:
85
+ for k in (c, c[:-1] if c.endswith("s") else c):
86
+ if k in SECTION_ICONS:
87
+ return SECTION_ICONS[k]
88
+ return DEFAULT_ICON
89
+
90
+ DATE_LED = re.compile(r"^\s*(\d{4}-\d{2}-\d{2})\b[\s·:—-]*(.*)$")
91
+ PEOPLE_LINK = re.compile(r"people/[^\s)\]]+")
92
+
93
+
94
+ # ------------------------------------------------------------------ the input, block by block
95
+ def read_blocks():
96
+ blocks, current = {}, None
97
+ for line in sys.stdin.read().split("\n"):
98
+ if line.startswith("%%") and line.endswith("%%"):
99
+ current = line.strip("%")
100
+ blocks[current] = []
101
+ continue
102
+ if current is not None:
103
+ blocks[current].append(line)
104
+ return blocks
105
+
106
+
107
+ BLOCKS = read_blocks()
108
+
109
+
110
+ def block(name):
111
+ return [l for l in BLOCKS.get(name, []) if l != ""]
112
+
113
+
114
+ STRINGS = {}
115
+ for line in block("STRINGS"):
116
+ k, _, v = line.partition("\t")
117
+ STRINGS[k] = v
118
+
119
+
120
+ def T(key, fallback=""):
121
+ return STRINGS.get(key, fallback or key)
122
+
123
+
124
+ # ------------------------------------------------------------------ what is machinery, what is not
125
+ def is_machinery(rel):
126
+ parts = rel.split("/")
127
+ if parts[-1] in MACHINERY_FILES:
128
+ return True
129
+ for p in parts[:-1]:
130
+ if p in MACHINERY_DIRS:
131
+ return True
132
+ return False
133
+
134
+
135
+ def in_workspaces(rel):
136
+ return rel.startswith(WSDIR + "/")
137
+
138
+
139
+ HEADS = [p for p in block("HEADS") if in_workspaces(p) and not is_machinery(p)]
140
+ CONTENT = [p for p in block("FILES") if in_workspaces(p) and not is_machinery(p)]
141
+ ALL_FILES = sorted(set(HEADS) | set(CONTENT))
142
+
143
+
144
+ # ------------------------------------------------------------------ the shelves come from the tree
145
+ def entity_types():
146
+ """The types the brain's own tree declares under a workspace, in the order they are declared.
147
+
148
+ A pattern of the shape `<wsdir>/*/<type>/*...` declares `<type>`. `initiatives` and `people`
149
+ are layouts of the view, not shelves, so they come out of the list — everything else is a
150
+ shelf, whatever it is called.
151
+ """
152
+ types = []
153
+ prefix = WSDIR + "/*/"
154
+ for g in block("GLOBS"):
155
+ if not g.startswith(prefix):
156
+ continue
157
+ rest = g[len(prefix):].split("/")
158
+ if len(rest) < 2 or rest[0] == "*":
159
+ continue
160
+ t = rest[0]
161
+ if t in ("initiatives", "people"):
162
+ continue
163
+ if t not in types:
164
+ types.append(t)
165
+ return types
166
+
167
+
168
+ TYPES = entity_types()
169
+
170
+
171
+ def shelf_label(t):
172
+ return t.replace("-", " ").replace("_", " ").strip().capitalize()
173
+
174
+
175
+ # ------------------------------------------------------------------ reading a file
176
+ CACHE = {}
177
+
178
+
179
+ def read(rel):
180
+ if rel in CACHE:
181
+ return CACHE[rel]
182
+ try:
183
+ with open(os.path.join(BRAIN, rel), "r", encoding="utf-8", errors="replace") as f:
184
+ raw = f.read()
185
+ except OSError:
186
+ raw = ""
187
+ lines = raw.split("\n")
188
+ if lines and lines[-1] == "":
189
+ lines = lines[:-1]
190
+ fm, start = md.read_frontmatter(lines)
191
+ title, lede, sections = md.split_sections(lines[start:])
192
+ CACHE[rel] = (fm, title, md.strip_lines(lede), sections)
193
+ return CACHE[rel]
194
+
195
+
196
+ def slug_title(rel):
197
+ base = os.path.basename(rel)
198
+ if base == HEAD_FILE:
199
+ base = os.path.basename(os.path.dirname(rel))
200
+ else:
201
+ base = os.path.splitext(base)[0]
202
+ return base.replace("-", " ").replace("_", " ").strip().capitalize()
203
+
204
+
205
+ def link_target(target, ws):
206
+ """A markdown link that names something the wiki has a page for becomes a link to that page;
207
+ anything else keeps its href if it is a URL and is dropped to plain text if it is not."""
208
+ if target.startswith("http://") or target.startswith("https://") or target.startswith("mailto:"):
209
+ return target
210
+ clean = target.split("#")[0].lstrip("./")
211
+ if clean in PAGES:
212
+ return "#/" + clean
213
+ return None
214
+
215
+
216
+ # ------------------------------------------------------------------ the shape of a section (C4)
217
+ def classify(lines):
218
+ lines = md.strip_lines(lines)
219
+ tasks, items = [], []
220
+ for l in lines:
221
+ m = md.TASK_RE.match(l)
222
+ if m:
223
+ tasks.append((m.group(1).lower() == "x", m.group(2).strip()))
224
+ continue
225
+ m = md.ITEM_RE.match(l)
226
+ if m:
227
+ items.append(m.group(1).strip())
228
+ if tasks:
229
+ out = []
230
+ for done, text in tasks:
231
+ m = DATE_LED.match(text)
232
+ date = ""
233
+ rest = text
234
+ if m:
235
+ date, rest = m.group(1), m.group(2) or text
236
+ else:
237
+ m2 = re.search(r"\((?:since|due|desde|vence)[: ]\s*(\d{4}-\d{2}-\d{2})\)", text)
238
+ if m2:
239
+ date = m2.group(1)
240
+ out.append({"done": done, "text": rest, "date": date})
241
+ return "tasks", out
242
+ if items and any(PEOPLE_LINK.search(i) for i in items):
243
+ out = []
244
+ for i in items:
245
+ m = PEOPLE_LINK.search(i)
246
+ path = m.group(0) if m else ""
247
+ out.append({"text": i, "person": path})
248
+ return "people", out
249
+ dated = [DATE_LED.match(i) for i in items]
250
+ if items and sum(1 for d in dated if d) * 2 >= len(items):
251
+ out = []
252
+ for i, d in zip(items, dated):
253
+ if d:
254
+ out.append({"date": d.group(1), "text": d.group(2) or i})
255
+ else:
256
+ out.append({"date": "", "text": i})
257
+ return "decisions", out
258
+ return "prose", lines
259
+
260
+
261
+ # ------------------------------------------------------------------ Development, from the repo (C5)
262
+ MOUNTS = {}
263
+ for line in block("MOUNTS"):
264
+ parts = line.split("\t")
265
+ if len(parts) >= 3:
266
+ MOUNTS[parts[0]] = {"local": parts[1], "merge": parts[2]}
267
+
268
+ SPEC_STATUS = re.compile(r"^(?:status|estado):\s*(.+)$")
269
+
270
+
271
+ def development(remote):
272
+ """The `Development` block of a node with a `repo:`. Read by the local path the mount table
273
+ declares for that remote; with no row for it, the block says the repo is not mounted and
274
+ nothing fails."""
275
+ row = MOUNTS.get(remote)
276
+ short = remote.rstrip("/")
277
+ if short.endswith(".git"):
278
+ short = short[:-4]
279
+ short = "/".join(short.split("/")[-2:])
280
+ if not row or not row["local"] or not os.path.isdir(row["local"]):
281
+ return {"repo": short, "mounted": False, "specs": [], "merge": ""}
282
+ counts = {}
283
+ for sub in ("specs", os.path.join("specs", "done")):
284
+ d = os.path.join(row["local"], sub)
285
+ if not os.path.isdir(d):
286
+ continue
287
+ for name in sorted(os.listdir(d)):
288
+ if not name.endswith(".md"):
289
+ continue
290
+ try:
291
+ with open(os.path.join(d, name), encoding="utf-8", errors="replace") as f:
292
+ head = f.read(2000).split("\n")
293
+ except OSError:
294
+ continue
295
+ fm, _ = md.read_frontmatter(head)
296
+ st = fm.get("status") or fm.get("estado") or ""
297
+ if not st:
298
+ continue
299
+ counts[st] = counts.get(st, 0) + 1
300
+ specs = [{"status": k, "count": v} for k, v in sorted(counts.items())]
301
+ return {"repo": short, "mounted": True, "specs": specs, "merge": row["merge"]}
302
+
303
+
304
+ # ------------------------------------------------------------------ the pages
305
+ PAGES = {}
306
+ WORKSPACES = []
307
+
308
+
309
+ def node_dir(rel):
310
+ return os.path.dirname(rel) if os.path.basename(rel) == HEAD_FILE else os.path.splitext(rel)[0]
311
+
312
+
313
+ def is_person(rel):
314
+ return "/people/" in "/" + rel
315
+
316
+
317
+ def build_page(rel, kind, ws, ptype=""):
318
+ fm, title, lede, sections = read(rel)
319
+ page = {
320
+ "path": rel,
321
+ "kind": kind,
322
+ "ws": ws,
323
+ "type": ptype,
324
+ "typeLabel": shelf_label(ptype) if ptype else "",
325
+ "title": title or slug_title(rel),
326
+ "fm": fm,
327
+ "lede": [],
328
+ "sections": [],
329
+ "docs": [],
330
+ "children": [],
331
+ "mentions": [],
332
+ "dev": None,
333
+ "raw": {"lede": lede, "sections": sections},
334
+ }
335
+ PAGES[rel] = page
336
+ return page
337
+
338
+
339
+ def render_page(page):
340
+ """Second pass: what needs every page to exist before it can be written — the links."""
341
+ ws = page["ws"]
342
+ raw = page.pop("raw")
343
+
344
+ def link(t):
345
+ return link_target(t, ws)
346
+
347
+ page["lede"] = md.render(raw["lede"], link)
348
+ page["summary"] = md.first_paragraph(raw["lede"])[:400]
349
+ out = []
350
+ for name, lines in raw["sections"]:
351
+ form, payload = classify(lines)
352
+ section = {
353
+ "name": name,
354
+ "icon": section_icon(name),
355
+ "form": form,
356
+ }
357
+ if form == "prose":
358
+ section["html"] = md.render(payload, link)
359
+ section["text"] = " ".join(l.strip() for l in payload if l.strip())
360
+ else:
361
+ section["items"] = payload
362
+ section["text"] = " ".join(i.get("text", "") for i in payload)
363
+ out.append(section)
364
+ page["sections"] = out
365
+ if page["fm"].get("repo"):
366
+ page["dev"] = development(page["fm"]["repo"])
367
+
368
+
369
+ # --- the workspaces, their shelves and their initiatives
370
+ ws_slugs = []
371
+ for h in HEADS:
372
+ parts = h.split("/")
373
+ if len(parts) == 3 and parts[0] == WSDIR and parts[2] == HEAD_FILE:
374
+ if parts[1] not in ws_slugs:
375
+ ws_slugs.append(parts[1])
376
+
377
+ for slug in sorted(ws_slugs):
378
+ ws_home = "%s/%s/%s" % (WSDIR, slug, HEAD_FILE)
379
+ home = build_page(ws_home, "workspace", slug)
380
+ ws = {
381
+ "slug": slug,
382
+ "title": home["title"],
383
+ "home": ws_home,
384
+ "shelves": [],
385
+ "orphans": [],
386
+ "people": [],
387
+ }
388
+ WORKSPACES.append(ws)
389
+
390
+ prefix = "%s/%s/" % (WSDIR, slug)
391
+ ws_heads = [h for h in HEADS if h.startswith(prefix) and h != ws_home]
392
+
393
+ # entities, by the types the tree declares
394
+ by_type = {}
395
+ for t in TYPES:
396
+ tp = prefix + t + "/"
397
+ for h in ws_heads:
398
+ if not h.startswith(tp):
399
+ continue
400
+ rest = h[len(tp):]
401
+ if rest.count("/") > 1:
402
+ continue
403
+ build_page(h, "entity", slug, t)
404
+ by_type.setdefault(t, []).append(h)
405
+ for t in TYPES:
406
+ if t in by_type:
407
+ ws["shelves"].append({
408
+ "type": t, "label": shelf_label(t), "icon": section_icon(t), "pages": sorted(by_type[t]),
409
+ })
410
+
411
+ # initiatives: the one type with a fixed meaning
412
+ ip = prefix + "initiatives/"
413
+ for h in ws_heads:
414
+ if h.startswith(ip) and h[len(ip):].count("/") <= 1:
415
+ build_page(h, "initiative", slug, "initiatives")
416
+
417
+ # --- people and documents: everything the content class reaches, attached to its node
418
+ NODE_OF = {}
419
+ for rel, page in PAGES.items():
420
+ NODE_OF[node_dir(rel)] = rel
421
+
422
+ for rel in ALL_FILES:
423
+ if rel in PAGES:
424
+ continue
425
+ ws = rel.split("/")[1] if rel.startswith(WSDIR + "/") else ""
426
+ if is_person(rel):
427
+ page = build_page(rel, "person", ws)
428
+ continue
429
+ d = os.path.dirname(rel)
430
+ owner = None
431
+ while d and "/" in d:
432
+ if d in NODE_OF:
433
+ owner = NODE_OF[d]
434
+ break
435
+ d = os.path.dirname(d)
436
+ page = build_page(rel, "document", ws)
437
+ page["owner"] = owner
438
+ if owner:
439
+ # The folder a document lives in is what says what it is —`decisions/`, `research/`— and
440
+ # the view groups by it. One sitting directly in the node's own folder belongs to no such
441
+ # group: it comes out under the generic heading instead of under the node's own name.
442
+ holder = os.path.dirname(rel)
443
+ group = "" if holder == node_dir(owner) else os.path.basename(holder)
444
+ PAGES[owner]["docs"].append({"path": rel, "group": group})
445
+
446
+ for ws in WORKSPACES:
447
+ ws["people"] = sorted(p for p, v in PAGES.items()
448
+ if v["kind"] == "person" and v["ws"] == ws["slug"])
449
+
450
+ # --- an initiative hangs from the entity its `about:` names (C2)
451
+ for rel, page in PAGES.items():
452
+ if page["kind"] != "initiative":
453
+ continue
454
+ about = page["fm"].get("about", "").strip().strip("`")
455
+ parent = about if about in PAGES and PAGES[about]["kind"] == "entity" else ""
456
+ page["about"] = parent
457
+ if parent:
458
+ PAGES[parent]["children"].append(rel)
459
+ else:
460
+ for ws in WORKSPACES:
461
+ if ws["slug"] == page["ws"]:
462
+ ws["orphans"].append(rel)
463
+
464
+ for rel, page in PAGES.items():
465
+ page["children"].sort()
466
+ for ws in WORKSPACES:
467
+ ws["orphans"].sort()
468
+
469
+ # --- render every page now that every page exists
470
+ for page in list(PAGES.values()):
471
+ render_page(page)
472
+
473
+ # --- a person's relations and mentions (C6)
474
+ for rel, page in PAGES.items():
475
+ if page["kind"] != "person":
476
+ continue
477
+ name = page["title"]
478
+ tail = rel.split("/people/")[-1]
479
+ for other, op in PAGES.items():
480
+ if other == rel or op["kind"] == "person":
481
+ continue
482
+ hit = False
483
+ blob = op.get("summary", "")
484
+ if rel in blob or tail in blob or (name and len(name) > 3 and name in blob):
485
+ hit = True
486
+ for s in op["sections"]:
487
+ if rel in s.get("text", "") or tail in s.get("text", ""):
488
+ hit = True
489
+ if s["form"] == "people":
490
+ for it in s["items"]:
491
+ if it["person"] and (it["person"] in rel or rel.endswith(it["person"])):
492
+ hit = True
493
+ if not hit and name and len(name) > 3 and name in s.get("text", ""):
494
+ hit = True
495
+ if hit:
496
+ page["mentions"].append({
497
+ "path": other, "kind": op["kind"], "title": op["title"],
498
+ "ws": op["ws"],
499
+ })
500
+ page["mentions"].sort(key=lambda m: (m["kind"], m["path"]))
501
+
502
+ # ------------------------------------------------------------------ the payload and the page
503
+ # `owner` stays on a document page (spec 063 C4): the sidebar walks it to find which entity to
504
+ # expand when a document is the one that is open. Every other kind never had the key at all.
505
+ # ------------------------------------------------------------------ Overview, the first screen (spec 062)
506
+ # It replaces *What changed*, which the 062 removed from the menu and from this payload: a list of
507
+ # commits is history, and the first screen is what is waiting for a person.
508
+ OPTIONS = {}
509
+ for line in block("OVERVIEW"):
510
+ k, _, v = line.partition("\t")
511
+ OPTIONS[k] = v
512
+
513
+ OVERVIEW = my_wiki_overview.build(PAGES, WORKSPACES, WSDIR, HEAD_FILE, OPTIONS, block("GATES"))
514
+
515
+ for page in PAGES.values():
516
+ page.pop("owner", None)
517
+
518
+ data = {
519
+ "generated": GENERATED,
520
+ "vault": VAULT,
521
+ "version": VERSION,
522
+ "strings": STRINGS,
523
+ "icons": SECTION_ICONS,
524
+ "workspaces": WORKSPACES,
525
+ "pages": PAGES,
526
+ "graph": mwg.build_graph(PAGES, CACHE, block("HISTORY")),
527
+ "overview": OVERVIEW,
528
+ }
529
+
530
+ payload = json.dumps(data, ensure_ascii=False, separators=(",", ":"))
531
+ payload = payload.replace("</", "<\\/")
532
+
533
+ with open(TEMPLATE, encoding="utf-8") as f:
534
+ html = f.read()
535
+ html = html.replace("{{DATA}}", payload)
536
+ # The first screen's view travels beside the shell, from its own file: the 062 adds its code
537
+ # without a second copy of the template (spec 062).
538
+ with open(os.path.join(os.path.dirname(TEMPLATE), "my-wiki-overview.js"), encoding="utf-8") as f:
539
+ html = html.replace("{{OVERVIEW_JS}}", f.read())
540
+ html = html.replace("{{TITLE}}", md.escape(T("WIKI_TITLE", "My Wiki")))
541
+ with open(os.path.join(os.path.dirname(TEMPLATE), "my-wiki-graph.js"), encoding="utf-8") as f:
542
+ html = html.replace("{{GRAPH_JS}}", "<script id=\"wiki-graph\">\n" + f.read() + "\n</script>")
543
+
544
+ with open(OUT, "w", encoding="utf-8") as f:
545
+ f.write(html)
546
+
547
+ size = os.path.getsize(OUT)
548
+ print("%s\t%d\t%d\t%d" % (OUT, size, len(PAGES), len(WORKSPACES)))
@@ -0,0 +1,137 @@
1
+ #!/usr/bin/env python3
2
+ """My Wiki's Graph screen (spec 061). Internal: `my_wiki_build.py` imports `build_graph` and calls
3
+ it once, after every page of the wiki already exists and is rendered. This file opens no file of
4
+ its own and parses no markdown of its own — everything it needs is handed in by the caller, which
5
+ is spec 060's stopping condition for a second reader of the format.
6
+
7
+ NO SECOND LINK ENGINE. A page's edges come from the same three sources spec 060 already put on the
8
+ page's own fields and cached raw text — `about:`, a path inside backticks, and a path into
9
+ `people/` — and from nothing else. A page that names another one by title, with no path attached,
10
+ draws no edge (spec 061 C2): that is the difference between this graph and a person's `mentions`,
11
+ which is a fuzzy, name-based list built for a different purpose.
12
+
13
+ ONE `git log` FOR EVERY FIRST-COMMIT DATE, NEVER ONE PER FILE. `history_lines` is the untouched
14
+ output of a single call the bash side made; this module walks it once and keeps, for every path,
15
+ the earliest date it saw — regardless of what order the log itself lists commits in, so nothing
16
+ here depends on that log being chronological.
17
+ """
18
+
19
+ import re
20
+
21
+ CODE_RE = re.compile(r"`([^`]+)`")
22
+ PEOPLE_RE = re.compile(r"people/[^\s)\]`]+")
23
+
24
+
25
+ def _clean_path(raw):
26
+ return raw.strip().strip("`").split("#")[0].lstrip("./").rstrip("/")
27
+
28
+
29
+ def _resolve_doc(raw, pages):
30
+ """A backtick span that names a page, directly or by its node's directory."""
31
+ path = _clean_path(raw)
32
+ if path in pages:
33
+ return path
34
+ cand = path + "/README.md"
35
+ if cand in pages:
36
+ return cand
37
+ return None
38
+
39
+
40
+ def _resolve_person(raw, pages):
41
+ """A `people/...` span that names a person page, even when it is shorter than the full path —
42
+ the same tolerance the sections of 060 already give a stakeholder's `[ficha](people/x.md)`."""
43
+ tail = raw.strip().strip("`)]")
44
+ for p, page in pages.items():
45
+ if page.get("kind") != "person":
46
+ continue
47
+ if p == tail or p.endswith("/" + tail.split("/", 1)[-1]):
48
+ return p
49
+ return None
50
+
51
+
52
+ def _raw_text(rel, cache):
53
+ """The page's own markdown — lede and every section's body — exactly as `my_wiki_build.read`
54
+ cached it before rendering. Reading `cache` instead of the file again is what keeps this a
55
+ zero-read module: the bytes were already opened once, by the caller."""
56
+ hit = cache.get(rel)
57
+ if not hit:
58
+ return ""
59
+ _, _, lede, sections = hit
60
+ lines = list(lede)
61
+ for _, body in sections:
62
+ lines.extend(body)
63
+ return "\n".join(lines)
64
+
65
+
66
+ def _links(rel, page, cache, pages):
67
+ out = set()
68
+ about = (page.get("about") or "").strip()
69
+ if about and about in pages:
70
+ out.add(about)
71
+ text = _raw_text(rel, cache)
72
+ for m in CODE_RE.finditer(text):
73
+ hit = _resolve_doc(m.group(1), pages)
74
+ if hit and hit != rel:
75
+ out.add(hit)
76
+ for m in PEOPLE_RE.finditer(text):
77
+ hit = _resolve_person(m.group(0), pages)
78
+ if hit and hit != rel:
79
+ out.add(hit)
80
+ return out
81
+
82
+
83
+ def _first_dates(history_lines):
84
+ first = {}
85
+ date = ""
86
+ for line in history_lines:
87
+ if line.startswith("\x01"):
88
+ date = line[1:].strip()
89
+ continue
90
+ path = line.strip()
91
+ if not path or not date:
92
+ continue
93
+ if path not in first or date < first[path]:
94
+ first[path] = date
95
+ return first
96
+
97
+
98
+ def build_graph(pages, cache, history_lines):
99
+ """-> {"nodes": [...], "edges": [...], "dates": [...]}.
100
+
101
+ Every page of `pages` is a node — workspace, entity, initiative, person and document alike, a
102
+ page with no link at all included (spec 061: shown loose, never hidden). `dates` is the sorted,
103
+ deduplicated set of first-commit dates the graph actually has, the ticks of the "how it grew"
104
+ slider.
105
+ """
106
+ first = _first_dates(history_lines)
107
+ edges = set()
108
+ for rel, page in pages.items():
109
+ for other in _links(rel, page, cache, pages):
110
+ if other in pages:
111
+ edges.add(tuple(sorted((rel, other))))
112
+
113
+ degree = {}
114
+ for a, b in edges:
115
+ degree[a] = degree.get(a, 0) + 1
116
+ degree[b] = degree.get(b, 0) + 1
117
+
118
+ nodes = []
119
+ dates = set()
120
+ for rel, page in pages.items():
121
+ d = first.get(rel, "")
122
+ if d:
123
+ dates.add(d)
124
+ nodes.append({
125
+ "id": rel,
126
+ "kind": page["kind"],
127
+ "ws": page["ws"],
128
+ "title": page["title"],
129
+ "degree": degree.get(rel, 0),
130
+ "first": d,
131
+ })
132
+
133
+ return {
134
+ "nodes": nodes,
135
+ "edges": [{"a": a, "b": b} for a, b in sorted(edges)],
136
+ "dates": sorted(dates),
137
+ }