ai-first-os 2.3.0 → 2.4.1

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.
@@ -0,0 +1,677 @@
1
+ #!/usr/bin/env python3
2
+ """Tools behind capabilities/. Called by the thin bash wrappers in scripts/.
3
+
4
+ capability_tools.py apply SPEC [--root DIR] apply a spec's "## Capability changes"
5
+ capability_tools.py check-evals OUTPUT [--root DIR] every requirement has Evals: ids with a PASS line
6
+ capability_tools.py check-diagrams [--root DIR] diagram form + the general diagram names every capability
7
+ capability_tools.py blocks [--root DIR] print every mermaid block as FILE<TAB>INDEX<TAB>path (see render-mermaid.sh)
8
+
9
+ Exit codes: 0 ok / nothing to do · 1 stopped (prints capability, requirement and rule) · 2 misused.
10
+ The format lives in capabilities/README.md and nowhere else.
11
+ """
12
+ import os
13
+ import re
14
+ import sys
15
+
16
+ DIAGRAM_TYPES = ("flowchart", "graph", "stateDiagram-v2", "sequenceDiagram")
17
+ EVAL_ID = re.compile(r"S\d{3}-[A-Za-z0-9]+")
18
+ SLUG = re.compile(r"^[a-z0-9]+(-[a-z0-9]+)*$")
19
+ KINDS = ("DIAGRAM", "RENAMED", "REMOVED", "MODIFIED", "ADDED")
20
+
21
+
22
+ class Stop(Exception):
23
+ def __init__(self, cap, req, rule, msg):
24
+ super().__init__(msg)
25
+ self.cap, self.req, self.rule, self.msg = cap, req, rule, msg
26
+
27
+ def __str__(self):
28
+ return "capability: %s · requirement: %s · rule %s: %s" % (self.cap, self.req or "-", self.rule, self.msg)
29
+
30
+
31
+ # ---------------------------------------------------------------- text helpers
32
+
33
+ FENCE = re.compile(r"^ {0,3}(`{3,}|~{3,})(.*)$")
34
+ FENCE_END = re.compile(r"^ {0,3}(`{3,}|~{3,})[ \t]*$")
35
+
36
+
37
+ def fence_open(line):
38
+ """CommonMark opening fence: up to 3 spaces of indent, 3+ backticks or tildes. -> (char, length, info) or None."""
39
+ m = FENCE.match(line)
40
+ if not m:
41
+ return None
42
+ f, info = m.group(1), m.group(2)
43
+ if f[0] == "`" and "`" in info:
44
+ return None
45
+ return (f[0], len(f), info.strip())
46
+
47
+
48
+ def fence_close(line, st):
49
+ """Closes a fence opened as st: same character, at least the same length, up to 3 spaces of indent."""
50
+ m = FENCE_END.match(line)
51
+ return bool(m) and m.group(1)[0] == st[0] and len(m.group(1)) >= st[1]
52
+
53
+
54
+ def outside_fence(lines):
55
+ """Yield (index, line, inside) for each line; inside is True for lines in or on a fence."""
56
+ st = None
57
+ for i, line in enumerate(lines):
58
+ if st:
59
+ yield i, line, True
60
+ if fence_close(line, st):
61
+ st = None
62
+ else:
63
+ st = fence_open(line)
64
+ yield i, line, bool(st)
65
+
66
+
67
+ def scan_mermaid(lines):
68
+ """-> (blocks, suspects). blocks: (open_idx, close_idx or None, body). suspects: messages for fences whose
69
+ info string mentions mermaid without being exactly 'mermaid' (never skipped silently)."""
70
+ blocks, suspects = [], []
71
+ st = None
72
+ cur = None
73
+ for i, l in enumerate(lines):
74
+ if st:
75
+ if fence_close(l, st):
76
+ if cur is not None:
77
+ blocks.append((cur[0], i, cur[1]))
78
+ st, cur = None, None
79
+ elif cur is not None:
80
+ cur[1].append(l)
81
+ else:
82
+ st = fence_open(l)
83
+ if st:
84
+ word = st[2].split()[0] if st[2].split() else ""
85
+ if word == "mermaid":
86
+ cur = [i, []]
87
+ elif "mermaid" in st[2].lower():
88
+ suspects.append("line %d: fence info '%s' looks like mermaid but is not exactly 'mermaid'" % (i + 1, st[2]))
89
+ if st and cur is not None:
90
+ blocks.append((cur[0], None, cur[1]))
91
+ return blocks, suspects
92
+
93
+
94
+ def norm(lines):
95
+ out = [l.rstrip() for l in lines]
96
+ while out and not out[0]:
97
+ out.pop(0)
98
+ while out and not out[-1]:
99
+ out.pop()
100
+ return out
101
+
102
+
103
+ def read_lines(path):
104
+ with open(path, encoding="utf-8") as f:
105
+ return f.read().split("\n")
106
+
107
+
108
+ def find_root(args):
109
+ root = None
110
+ rest = []
111
+ it = iter(args)
112
+ for a in it:
113
+ if a == "--root":
114
+ root = next(it, None)
115
+ if root is None:
116
+ print("--root needs a value", file=sys.stderr)
117
+ sys.exit(2)
118
+ else:
119
+ rest.append(a)
120
+ if root is None:
121
+ root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
122
+ return os.path.abspath(root), rest
123
+
124
+
125
+ # ---------------------------------------------------------------- the capability file
126
+
127
+ class Cap:
128
+ """A capabilities/<slug>.md: header (title, diagram, purpose), requirements, tail."""
129
+
130
+ def __init__(self, slug, lines):
131
+ self.slug = slug
132
+ idx = None
133
+ for i, l, inside in outside_fence(lines):
134
+ if not inside and l.strip() == "## Requirements":
135
+ idx = i
136
+ break
137
+ if idx is None:
138
+ raise Stop(slug, None, "file", "capabilities/%s.md has no '## Requirements' section" % slug)
139
+ self.header = lines[: idx + 1]
140
+ body = lines[idx + 1:]
141
+ self.reqs = [] # [name, lines]
142
+ self.tail = []
143
+ cur = None
144
+ for i, l, inside in outside_fence(body):
145
+ if not inside and l.startswith("### Requirement:"):
146
+ cur = [l[len("### Requirement:"):].strip(), [l]]
147
+ self.reqs.append(cur)
148
+ elif not inside and re.match(r"^## ", l):
149
+ self.tail = body[i:]
150
+ break
151
+ elif cur is not None:
152
+ cur[1].append(l)
153
+ for r in self.reqs:
154
+ r[1] = norm(r[1])
155
+
156
+ def names(self):
157
+ return [r[0] for r in self.reqs]
158
+
159
+ def get(self, name):
160
+ for r in self.reqs:
161
+ if r[0] == name:
162
+ return r
163
+ return None
164
+
165
+ def set_diagram(self, block):
166
+ blocks, _ = scan_mermaid(self.header)
167
+ if not blocks or blocks[0][1] is None:
168
+ raise Stop(self.slug, None, 11, "the file has no closed mermaid diagram to replace")
169
+ o, c, _ = blocks[0]
170
+ self.header = self.header[:o] + block + self.header[c + 1:]
171
+
172
+ def render(self):
173
+ out = list(norm(self.header))
174
+ out.append("")
175
+ for _, ls in self.reqs:
176
+ out.extend(ls)
177
+ out.append("")
178
+ if self.tail:
179
+ out.extend(self.tail)
180
+ while out and not out[-1]:
181
+ out.pop()
182
+ return "\n".join(out) + "\n"
183
+
184
+
185
+ def new_cap_text(slug, purpose, diagram):
186
+ title = slug.replace("-", " ")
187
+ title = title[0].upper() + title[1:]
188
+ out = ["# " + title, ""] + diagram + ["", "## Purpose", purpose, "", "## Requirements", ""]
189
+ return out
190
+
191
+
192
+ # ---------------------------------------------------------------- the spec's section
193
+
194
+ def section_lines(spec_lines):
195
+ start = None
196
+ for i, l, inside in outside_fence(spec_lines):
197
+ if inside:
198
+ continue
199
+ if start is None:
200
+ if re.match(r"^## Capability changes\s*$", l):
201
+ start = i + 1
202
+ elif re.match(r"^## ", l):
203
+ return spec_lines[start:i]
204
+ return spec_lines[start:] if start is not None else None
205
+
206
+
207
+ def split_headed(lines, prefix):
208
+ """Split lines in blocks by headings that start with prefix (outside fences): [(heading, body)]."""
209
+ blocks = []
210
+ cur = None
211
+ for i, l, inside in outside_fence(lines):
212
+ if not inside and l.startswith(prefix):
213
+ cur = [l, []]
214
+ blocks.append(cur)
215
+ elif cur is not None:
216
+ cur[1].append(l)
217
+ return blocks
218
+
219
+
220
+ def parse_requirements(cap, kind, body):
221
+ """Requirement blocks of a ADDED / MODIFIED body, as [(name, lines at file level, scenarios, drops, evals)]."""
222
+ reqs = []
223
+ for head, rbody in split_headed(body, "#### Requirement:"):
224
+ name = head[len("#### Requirement:"):].strip()
225
+ text = [head] + rbody
226
+ scenarios = []
227
+ evals = []
228
+ drops = []
229
+ for i, l, inside in outside_fence(text):
230
+ if inside:
231
+ continue
232
+ if l.startswith("##### Scenario:"):
233
+ scenarios.append(l[len("##### Scenario:"):].strip())
234
+ m = re.match(r"^Evals:\s*(.*)$", l)
235
+ if m:
236
+ evals.extend(EVAL_ID.findall(m.group(1)))
237
+ m = re.match(r"^Drops scenario:\s*(.+)$", l)
238
+ if m:
239
+ drops.append(m.group(1).strip())
240
+ if not evals:
241
+ raise Stop(cap, name, 8, "%s requirement has no 'Evals:' line with an id" % kind)
242
+ if not scenarios:
243
+ raise Stop(cap, name, 8, "%s requirement has no scenario" % kind)
244
+ filelines = []
245
+ # lower every heading by one level outside fences (spec-level #### -> file-level ###)
246
+ for (_, l, inside) in outside_fence(text):
247
+ if not inside and re.match(r"^#{4,} ", l):
248
+ l = l[1:]
249
+ if not inside and l.startswith("Drops scenario:"):
250
+ continue
251
+ filelines.append(l)
252
+ filelines[0] = "### Requirement: " + name
253
+ reqs.append((name, norm(filelines), scenarios, drops, evals))
254
+ return reqs
255
+
256
+
257
+ def scenarios_of(lines):
258
+ out = []
259
+ for _, l, inside in outside_fence(lines):
260
+ if not inside and l.startswith("#### Scenario:"):
261
+ out.append(l[len("#### Scenario:"):].strip())
262
+ return out
263
+
264
+
265
+ def diagram_block(cap, body, is_new):
266
+ lines = norm(body)
267
+ if len(lines) == 1 and re.match(r"^Diagram:\s*unchanged\s*$", lines[0]):
268
+ if is_new:
269
+ raise Stop(cap, None, 11, "a new capability needs a mermaid diagram, never 'Diagram: unchanged'")
270
+ return None
271
+ blocks, suspects = scan_mermaid(lines)
272
+ if (len(blocks) == 1 and not suspects and blocks[0][1] is not None
273
+ and blocks[0][0] == 0 and blocks[0][1] == len(lines) - 1):
274
+ return lines
275
+ raise Stop(cap, None, 11, "DIAGRAM block must be exactly one closed ```mermaid block and nothing else, or the line 'Diagram: unchanged'")
276
+
277
+
278
+ def apply(root, spec_path):
279
+ spec_lines = read_lines(spec_path)
280
+ sec = section_lines(spec_lines)
281
+ if sec is None:
282
+ return {}
283
+ blocks = split_headed(sec, "### ")
284
+ if not blocks:
285
+ return {}
286
+ caps = {} # slug -> {kind: body}
287
+ order = []
288
+ for head, body in blocks:
289
+ m = re.match(r"^### (\S+) · (\S+)\s*$", head)
290
+ if not m or m.group(2) not in KINDS or not SLUG.match(m.group(1)):
291
+ raise Stop(head[4:].strip() or "?", None, "format", "heading must be '### <capability> · <%s>'" % "|".join(KINDS))
292
+ slug, kind = m.groups()
293
+ if slug not in caps:
294
+ caps[slug] = {}
295
+ order.append(slug)
296
+ if kind in caps[slug]:
297
+ raise Stop(slug, None, 9, "two %s blocks for the same capability" % kind)
298
+ caps[slug][kind] = body
299
+ writes = {}
300
+ for slug in order:
301
+ kinds = caps[slug]
302
+ path = os.path.join(root, "capabilities", slug + ".md")
303
+ exists = os.path.isfile(path)
304
+ # rule 7
305
+ if not exists:
306
+ for k in kinds:
307
+ if k not in ("ADDED", "DIAGRAM"):
308
+ raise Stop(slug, None, 7, "a capability without a file only accepts ADDED, not %s" % k)
309
+ if "ADDED" not in kinds:
310
+ raise Stop(slug, None, 7, "a capability without a file needs an ADDED block")
311
+ # rule 11
312
+ if "DIAGRAM" not in kinds:
313
+ raise Stop(slug, None, 11, "the capability has no DIAGRAM block")
314
+ diagram = diagram_block(slug, kinds["DIAGRAM"], not exists)
315
+ purpose = None
316
+ added = []
317
+ if "ADDED" in kinds:
318
+ body = kinds["ADDED"]
319
+ pre = []
320
+ for l in body:
321
+ if l.startswith("#### Requirement:"):
322
+ break
323
+ pre.append(l)
324
+ for l in pre:
325
+ m = re.match(r"^Purpose:\s*(.+)$", l)
326
+ if m:
327
+ purpose = m.group(1).strip()
328
+ if not exists and not purpose:
329
+ raise Stop(slug, None, 7, "a new capability's ADDED block needs a 'Purpose:' line")
330
+ added = parse_requirements(slug, "ADDED", body)
331
+ modified = parse_requirements(slug, "MODIFIED", kinds["MODIFIED"]) if "MODIFIED" in kinds else []
332
+ removed = []
333
+ if "REMOVED" in kinds:
334
+ for head, _ in split_headed(kinds["REMOVED"], "#### Requirement:"):
335
+ removed.append(head[len("#### Requirement:"):].strip())
336
+ renamed = []
337
+ if "RENAMED" in kinds:
338
+ frm = None
339
+ for l in kinds["RENAMED"]:
340
+ m = re.match(r"^FROM:\s*(.+)$", l.strip())
341
+ if m:
342
+ frm = m.group(1).strip()
343
+ m = re.match(r"^TO:\s*(.+)$", l.strip())
344
+ if m:
345
+ if frm is None:
346
+ raise Stop(slug, m.group(1).strip(), 6, "TO without a FROM before it")
347
+ renamed.append((frm, m.group(1).strip()))
348
+ frm = None
349
+ # rule 9
350
+ seen = {}
351
+ def claim(name, tag):
352
+ if name in seen:
353
+ raise Stop(slug, name, 9, "the requirement appears in two sections (%s and %s)" % (seen[name], tag))
354
+ seen[name] = tag
355
+ for a, b in renamed:
356
+ claim(a, "RENAMED")
357
+ for n in removed:
358
+ claim(n, "REMOVED")
359
+ for n, *_ in added:
360
+ claim(n, "ADDED")
361
+ for n, *_ in modified:
362
+ if n in [b for _, b in renamed] and seen.get(n) is None:
363
+ seen[n] = "MODIFIED"
364
+ continue
365
+ claim(n, "MODIFIED")
366
+ for _, b in renamed:
367
+ if b in seen and seen[b] not in ("MODIFIED",):
368
+ raise Stop(slug, b, 9, "the new name of a rename appears in another section (%s)" % seen[b])
369
+ # build
370
+ if exists:
371
+ cap = Cap(slug, read_lines(path))
372
+ else:
373
+ cap = Cap(slug, new_cap_text(slug, purpose, diagram) )
374
+ # rule 6 renamed
375
+ for a, b in renamed:
376
+ r = cap.get(a)
377
+ if r is None:
378
+ raise Stop(slug, a, 6, "RENAMED: the old requirement does not exist")
379
+ if cap.get(b) is not None:
380
+ raise Stop(slug, b, 6, "RENAMED: the new name already exists")
381
+ r[0] = b
382
+ r[1][0] = "### Requirement: " + b
383
+ # rule 5 removed
384
+ for n in removed:
385
+ r = cap.get(n)
386
+ if r is None:
387
+ raise Stop(slug, n, 5, "REMOVED: the requirement does not exist")
388
+ cap.reqs.remove(r)
389
+ # rule 3 modified
390
+ for n, lines, scen, drops, ev in modified:
391
+ r = cap.get(n)
392
+ if r is None:
393
+ raise Stop(slug, n, 3, "MODIFIED: the requirement does not exist")
394
+ lost = [s for s in scenarios_of(r[1]) if s not in scen and s not in drops]
395
+ if lost:
396
+ raise Stop(slug, n, 3, "MODIFIED drops scenario(s) without 'Drops scenario:': %s" % "; ".join(lost))
397
+ r[1] = lines
398
+ # rule 4 added
399
+ for n, lines, scen, drops, ev in added:
400
+ r = cap.get(n)
401
+ if r is not None:
402
+ if norm(r[1]) == lines:
403
+ continue
404
+ raise Stop(slug, n, 4, "ADDED: a requirement with that name exists with other text")
405
+ cap.reqs.append([n, lines])
406
+ if diagram is not None:
407
+ cap.set_diagram(diagram)
408
+ writes[path] = cap.render()
409
+ return writes
410
+
411
+
412
+ # ---------------------------------------------------------------- checks
413
+
414
+ def cap_files(root):
415
+ d = os.path.join(root, "capabilities")
416
+ if not os.path.isdir(d):
417
+ return []
418
+ return sorted(f for f in os.listdir(d) if f.endswith(".md") and f != "README.md")
419
+
420
+
421
+ def mermaid_blocks(lines):
422
+ """[(start_line_number, body_lines, closed)] for each mermaid fence (any fence length, backticks or tildes)."""
423
+ return [(o + 1, body, c is not None) for o, c, body in scan_mermaid(lines)[0]]
424
+
425
+
426
+ def form_problems(body, closed):
427
+ p = []
428
+ if not closed:
429
+ p.append("the fence never closes")
430
+ first = next((l.strip() for l in body if l.strip() and not l.strip().startswith("%%")), "")
431
+ if not any(first == t or first.startswith(t + " ") for t in DIAGRAM_TYPES):
432
+ p.append("does not open with a known diagram type (%s)" % ", ".join(DIAGRAM_TYPES))
433
+ for j, l in enumerate(body):
434
+ for a, b in ("[]", "{}", "()"):
435
+ if l.count(a) != l.count(b):
436
+ p.append("line %d: unbalanced %s%s" % (j + 1, a, b))
437
+ if l.count('"') % 2:
438
+ p.append("line %d: unbalanced quotes" % (j + 1))
439
+ return p
440
+
441
+
442
+ def node_texts(body):
443
+ """Every node id and node label of a diagram, comments excluded: exact strings, never substrings."""
444
+ texts = set()
445
+ for l in body:
446
+ l = re.sub(r"%%.*$", "", l)
447
+ for m in re.finditer(r'"([^"]*)"', l):
448
+ texts.add(m.group(1).strip())
449
+ l = re.sub(r'"[^"]*"', '""', l)
450
+ for m in re.finditer(r"[\[\(\{>]+([^\[\]\(\)\{\}\"]*)[\]\)\}]+", l):
451
+ texts.add(m.group(1).strip())
452
+ rest = re.sub(r"[\[\(\{>]+[^\[\]\(\)\{\}]*[\]\)\}]+", " ", l)
453
+ rest = re.sub(r"\|[^|]*\|", " ", rest)
454
+ rest = re.sub(r"--\s+[^>]*?\s+-->", " --> ", rest)
455
+ for piece in re.split(r"\s*(?:<?[-=]{2,}[>xo-]?|[-=]\.+-?>?|&|;)\s*", rest):
456
+ piece = piece.strip()
457
+ if piece:
458
+ texts.add(piece)
459
+ return texts
460
+
461
+
462
+ def check_diagrams(root):
463
+ problems = []
464
+ arch = os.path.join(root, "ARCHITECTURE.md")
465
+ general = None
466
+ # A repo with no capability file needs no general diagram: the first capability brings it. From the first
467
+ # capability file on, the general diagram is required and has to name every capability.
468
+ caps = cap_files(root)
469
+ if os.path.isfile(arch):
470
+ lines = read_lines(arch)
471
+ first_h2 = next((i for i, l, ins in outside_fence(lines) if not ins and l.startswith("## ")), len(lines))
472
+ for q in scan_mermaid(lines)[1]:
473
+ problems.append("ARCHITECTURE.md: " + q)
474
+ bl = [b for b in mermaid_blocks(lines)]
475
+ before = [b for b in bl if b[0] <= first_h2]
476
+ if len(before) != 1 and caps:
477
+ problems.append("ARCHITECTURE.md: the general diagram is missing or doubled: expected one mermaid block before the first '##' title, found %d (this repo has capability files, so it needs the general diagram)" % len(before))
478
+ for start, body, closed in before:
479
+ general = node_texts(body)
480
+ for q in form_problems(body, closed):
481
+ problems.append("ARCHITECTURE.md block at line %d: %s" % (start, q))
482
+ elif caps:
483
+ problems.append("ARCHITECTURE.md is missing")
484
+ for f in caps:
485
+ lines = read_lines(os.path.join(root, "capabilities", f))
486
+ for q in scan_mermaid(lines)[1]:
487
+ problems.append("capabilities/%s: %s" % (f, q))
488
+ bl = mermaid_blocks(lines)
489
+ if len(bl) != 1:
490
+ problems.append("capabilities/%s: expected exactly one mermaid block, found %d" % (f, len(bl)))
491
+ continue
492
+ start, body, closed = bl[0]
493
+ title = next((i for i, l in enumerate(lines) if l.startswith("# ")), None)
494
+ between = [l for l in lines[(title + 1 if title is not None else 0): start - 1] if l.strip()]
495
+ if title is None or between:
496
+ problems.append("capabilities/%s: the mermaid block must be the first thing after the '#' title" % f)
497
+ for q in form_problems(body, closed):
498
+ problems.append("capabilities/%s: %s" % (f, q))
499
+ slug = f[:-3]
500
+ if general is not None and slug not in general:
501
+ problems.append("ARCHITECTURE.md: the general diagram has no node for capability '%s'" % slug)
502
+ return problems
503
+
504
+
505
+ def requirements_of(root, f):
506
+ lines = read_lines(os.path.join(root, "capabilities", f))
507
+ reqs = []
508
+ cur = None
509
+ for i, l, inside in outside_fence(lines):
510
+ if inside:
511
+ if cur is not None:
512
+ cur[1].append(l)
513
+ continue
514
+ if l.startswith("### Requirement:"):
515
+ cur = [l[len("### Requirement:"):].strip(), [l]]
516
+ reqs.append(cur)
517
+ elif re.match(r"^## ", l):
518
+ cur = None
519
+ elif cur is not None:
520
+ cur[1].append(l)
521
+ return reqs
522
+
523
+
524
+ def check_evals(root, output_path):
525
+ with open(output_path, encoding="utf-8", errors="replace") as f:
526
+ out = f.read().split("\n")
527
+ passed = set()
528
+ for l in out:
529
+ m = re.match(r"^PASS (S\d{3}-[A-Za-z0-9]+)\b", l)
530
+ if m:
531
+ passed.add(m.group(1))
532
+ failed = set()
533
+ for l in out:
534
+ m = re.match(r"^FAIL (S\d{3}-[A-Za-z0-9]+)\b", l)
535
+ if m:
536
+ failed.add(m.group(1))
537
+ problems = []
538
+ for f in cap_files(root):
539
+ for name, ls in requirements_of(root, f):
540
+ ids = []
541
+ has = False
542
+ for _, l, inside in outside_fence(ls):
543
+ if inside:
544
+ continue
545
+ m = re.match(r"^Evals:\s*(.*)$", l)
546
+ if m:
547
+ has = True
548
+ ids.extend(EVAL_ID.findall(m.group(1)))
549
+ if not has or not ids:
550
+ problems.append("capabilities/%s · %s: no 'Evals:' line with an id" % (f, name))
551
+ continue
552
+ for i in ids:
553
+ if i not in passed:
554
+ why = "FAIL" if i in failed else "no PASS line"
555
+ problems.append("capabilities/%s · %s: %s (%s)" % (f, name, i, why))
556
+ return problems
557
+
558
+
559
+ def write_all(writes):
560
+ """All-or-nothing: every target goes to a temp file first, then each is renamed into place. If anything
561
+ fails, what was already replaced is restored and the temp files are removed. -> messages written."""
562
+ plan, done, made_dir = [], [], []
563
+ try:
564
+ for path, text in writes.items():
565
+ old = None
566
+ if os.path.isfile(path):
567
+ with open(path, encoding="utf-8") as f:
568
+ old = f.read()
569
+ if old == text:
570
+ continue
571
+ d = os.path.dirname(path)
572
+ if not os.path.isdir(d):
573
+ os.makedirs(d)
574
+ made_dir.append(d)
575
+ tmp = "%s.tmp-%d" % (path, os.getpid())
576
+ with open(tmp, "w", encoding="utf-8", newline="\n") as f:
577
+ f.write(text)
578
+ plan.append((path, tmp, old))
579
+ for path, tmp, old in plan:
580
+ os.replace(tmp, path)
581
+ done.append((path, old))
582
+ except Exception:
583
+ for path, old in reversed(done):
584
+ try:
585
+ if old is None:
586
+ os.remove(path)
587
+ else:
588
+ with open(path, "w", encoding="utf-8", newline="\n") as f:
589
+ f.write(old)
590
+ except OSError:
591
+ pass
592
+ for _, tmp, _ in plan:
593
+ try:
594
+ os.remove(tmp)
595
+ except OSError:
596
+ pass
597
+ for d in made_dir:
598
+ try:
599
+ os.rmdir(d)
600
+ except OSError:
601
+ pass
602
+ raise
603
+ return ["capabilities/%s: written" % os.path.basename(p) for p, _, _ in plan]
604
+
605
+
606
+ # ---------------------------------------------------------------- main
607
+
608
+ def main(argv):
609
+ if len(argv) < 2:
610
+ print(__doc__, file=sys.stderr)
611
+ return 2
612
+ cmd = argv[1]
613
+ root, rest = find_root(argv[2:])
614
+ if "--root" in argv[2:] and not os.path.isdir(root):
615
+ # A mistyped folder would read as a newborn repo with no capabilities and pass: stop instead.
616
+ print("--root is not an existing directory: %s" % root, file=sys.stderr)
617
+ return 2
618
+ if cmd == "apply":
619
+ if len(rest) != 1 or not os.path.isfile(rest[0]):
620
+ print("usage: apply-capability-changes.sh <spec> [--root DIR]", file=sys.stderr)
621
+ return 2
622
+ try:
623
+ writes = apply(root, rest[0])
624
+ except Stop as e:
625
+ print("STOP " + str(e), file=sys.stderr)
626
+ return 1
627
+ except Exception as e:
628
+ print("STOP internal error while reading: %s" % e, file=sys.stderr)
629
+ return 1
630
+ try:
631
+ for msg in write_all(writes):
632
+ print(msg)
633
+ except Exception as e: # nothing half-written: write_all restored what it had replaced
634
+ print("STOP write failed, originals restored: %s" % e, file=sys.stderr)
635
+ return 1
636
+ return 0
637
+ if cmd == "check-evals":
638
+ if len(rest) != 1 or not os.path.isfile(rest[0]):
639
+ print("usage: check-capability-evals.sh <suite output> [--root DIR]", file=sys.stderr)
640
+ return 2
641
+ p = check_evals(root, rest[0])
642
+ for x in p:
643
+ print("STOP " + x, file=sys.stderr)
644
+ return 1 if p else 0
645
+ if cmd == "check-diagrams":
646
+ p = check_diagrams(root)
647
+ for x in p:
648
+ print("STOP " + x, file=sys.stderr)
649
+ return 1 if p else 0
650
+ if cmd == "blocks":
651
+ # blocks DIR: writes each mermaid block to DIR/NNN.mmd and prints "NNN<TAB>file<TAB>block-number"
652
+ if len(rest) != 1:
653
+ return 2
654
+ d = rest[0]
655
+ os.makedirs(d, exist_ok=True)
656
+ files = [os.path.join(root, "ARCHITECTURE.md")] if os.path.isfile(os.path.join(root, "ARCHITECTURE.md")) else []
657
+ files += [os.path.join(root, "capabilities", f) for f in cap_files(root)]
658
+ n = 0
659
+ for path in files:
660
+ lines_ = read_lines(path)
661
+ bad = scan_mermaid(lines_)[1] + ["line %d: the mermaid fence never closes" % st for st, _, cl in mermaid_blocks(lines_) if not cl]
662
+ if bad:
663
+ for q in bad:
664
+ print("STOP %s: %s" % (os.path.relpath(path, root), q), file=sys.stderr)
665
+ return 1
666
+ for k, (start, body, closed) in enumerate(mermaid_blocks(lines_), 1):
667
+ n += 1
668
+ with open(os.path.join(d, "%03d.mmd" % n), "w", encoding="utf-8") as f:
669
+ f.write("\n".join(body) + "\n")
670
+ print("%03d\t%s\t%d\t%d" % (n, os.path.relpath(path, root), k, start))
671
+ return 0
672
+ print("unknown command: " + cmd, file=sys.stderr)
673
+ return 2
674
+
675
+
676
+ if __name__ == "__main__":
677
+ sys.exit(main(sys.argv))
@@ -0,0 +1,4 @@
1
+ #!/usr/bin/env bash
2
+ # Usage: scripts/check-capability-diagrams.sh [--root DIR] — diagram form, and the general diagram names every capability; no network, no browser.
3
+ # Exit: 0 ok · 1 stopped (says capability, requirement and rule) · 2 misused. Format: capabilities/README.md.
4
+ exec python3 "$(dirname "$0")/capability_tools.py" check-diagrams "$@"
@@ -0,0 +1,4 @@
1
+ #!/usr/bin/env bash
2
+ # Usage: scripts/check-capability-evals.sh <suite output> [--root DIR] — every requirement names Evals: ids and each has a PASS line.
3
+ # Exit: 0 ok · 1 stopped (says capability, requirement and rule) · 2 misused. Format: capabilities/README.md.
4
+ exec python3 "$(dirname "$0")/capability_tools.py" check-evals "$@"