@bbcsoftwarefactory/skills 0.0.0-stage → 0.1.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 (100) hide show
  1. package/dist/index.json +42 -0
  2. package/dist/skills/code-quality-gate/SKILL.md +59 -0
  3. package/dist/skills/code-quality-gate/references/gate-bigo.md +31 -0
  4. package/dist/skills/code-quality-gate/references/gate-earlyreturn.md +73 -0
  5. package/dist/skills/code-quality-gate/references/gate-typesafe.md +32 -0
  6. package/dist/skills/code-quality-gate/references/output-schema.yml +40 -0
  7. package/dist/skills/code-quality-gate/scripts/extract-diff-scope.py +225 -0
  8. package/dist/skills/code-quality-gate/tests/extract-diff-scope.test.sh +200 -0
  9. package/dist/skills/delivery-coordinator/SKILL.md +81 -0
  10. package/dist/skills/delivery-coordinator/references/hud-output.md +55 -0
  11. package/dist/skills/delivery-coordinator/references/intake.md +86 -0
  12. package/dist/skills/delivery-coordinator/references/issue-claim.md +143 -0
  13. package/dist/skills/delivery-coordinator/references/issue-dedup.md +38 -0
  14. package/dist/skills/delivery-coordinator/references/sleuth-regression-exercise.md +60 -0
  15. package/dist/skills/delivery-coordinator/references/visual-reference.md +45 -0
  16. package/dist/skills/delivery-coordinator/references/worktree-isolation.md +19 -0
  17. package/dist/skills/delivery-coordinator/scripts/check-issue-claim.py +363 -0
  18. package/dist/skills/delivery-coordinator/scripts/check-worktree-guard.py +220 -0
  19. package/dist/skills/delivery-coordinator/scripts/classify-change-lane.py +263 -0
  20. package/dist/skills/delivery-coordinator/tests/check-issue-claim.test.sh +221 -0
  21. package/dist/skills/delivery-coordinator/tests/check-worktree-guard.test.sh +123 -0
  22. package/dist/skills/delivery-coordinator/tests/classify-change-lane.test.sh +124 -0
  23. package/dist/skills/documentation-steward/SKILL.md +43 -0
  24. package/dist/skills/documentation-steward/references/discovery.md +17 -0
  25. package/dist/skills/documentation-steward/references/handoff.md +15 -0
  26. package/dist/skills/greptile-review-loop/SKILL.md +57 -0
  27. package/dist/skills/greptile-review-loop/references/review-protocol.md +37 -0
  28. package/dist/skills/greptile-review-loop/scripts/review-loop.py +435 -0
  29. package/dist/skills/greptile-review-loop/tests/review-loop.test.sh +331 -0
  30. package/dist/skills/issue-reviewer/SKILL.md +87 -0
  31. package/dist/skills/issue-reviewer/references/review-format.md +100 -0
  32. package/dist/skills/issue-reviewer/references/triage.md +105 -0
  33. package/dist/skills/issue-reviewer/scripts/fetch-issue-attachments.py +239 -0
  34. package/dist/skills/issue-reviewer/scripts/plan-issue-triage.py +311 -0
  35. package/dist/skills/issue-reviewer/tests/fetch-issue-attachments.test.sh +90 -0
  36. package/dist/skills/issue-reviewer/tests/plan-issue-triage.test.sh +168 -0
  37. package/dist/skills/question-gate/SKILL.md +66 -0
  38. package/dist/skills/question-gate/references/client-hooks.md +111 -0
  39. package/dist/skills/question-gate/references/diagram-routing.md +58 -0
  40. package/dist/skills/question-gate/scripts/triage-question.py +713 -0
  41. package/dist/skills/question-gate/tests/fixtures/question-corpus.json +481 -0
  42. package/dist/skills/question-gate/tests/question-corpus.test.sh +32 -0
  43. package/dist/skills/question-gate/tests/triage-question.test.sh +441 -0
  44. package/dist/skills/regression-testing/SKILL.md +49 -0
  45. package/dist/skills/regression-testing/references/evidence-record.md +35 -0
  46. package/dist/skills/requirements-spec/SKILL.md +59 -0
  47. package/dist/skills/risk-scout/SKILL.md +53 -0
  48. package/dist/skills/risk-scout/references/risk-matrix.md +49 -0
  49. package/dist/skills/skill-clean-architecture/SKILL.md +54 -0
  50. package/dist/skills/skill-clean-architecture/references/layer-rules.md +22 -0
  51. package/dist/skills/skill-clean-architecture/references/source-headers.md +31 -0
  52. package/dist/skills/skill-clean-architecture/scripts/measure-bigo.py +427 -0
  53. package/dist/skills/skill-clean-architecture/tests/fixtures/bigo/bad-utf8.js +1 -0
  54. package/dist/skills/skill-clean-architecture/tests/fixtures/bigo/edge-crlf.ts +6 -0
  55. package/dist/skills/skill-clean-architecture/tests/fixtures/bigo/edge-mixed.ts +15 -0
  56. package/dist/skills/skill-clean-architecture/tests/fixtures/bigo/empty.js +0 -0
  57. package/dist/skills/skill-clean-architecture/tests/fixtures/bigo/no-newline.js +1 -0
  58. package/dist/skills/skill-clean-architecture/tests/fixtures/bigo.expected.yml +95 -0
  59. package/dist/skills/skill-clean-architecture/tests/measure-bigo.test.sh +222 -0
  60. package/dist/skills/tool-depot/SKILL.md +47 -0
  61. package/dist/skills/tool-depot/references/checkout.md +29 -0
  62. package/dist/skills/tool-depot/references/loki-read.md +41 -0
  63. package/dist/skills/tool-depot/references/readonly-access.md +84 -0
  64. package/dist/skills/tool-depot/references/tool-catalog.json +47 -0
  65. package/dist/skills/tool-depot/scripts/loki-runtime-logs.py +305 -0
  66. package/dist/skills/tool-depot/tests/loki-runtime-logs.test.sh +101 -0
  67. package/dist/skills/watcher-observability/SKILL.md +73 -0
  68. package/dist/skills/watcher-observability/references/batch-protocol.md +44 -0
  69. package/dist/skills/watcher-observability/references/configuration.md +31 -0
  70. package/dist/skills/watcher-observability/references/error-scan.md +102 -0
  71. package/dist/skills/watcher-observability/references/live-protocol.md +49 -0
  72. package/dist/skills/watcher-observability/references/server-account.md +72 -0
  73. package/dist/skills/watcher-observability/scripts/error-scan.py +318 -0
  74. package/dist/skills/watcher-observability/scripts/resolve-containers.py +155 -0
  75. package/dist/skills/watcher-observability/scripts/save-counts.py +381 -0
  76. package/dist/skills/watcher-observability/scripts/summarize-logs.py +113 -0
  77. package/dist/skills/watcher-observability/scripts/watch-live.py +606 -0
  78. package/dist/skills/watcher-observability/server/watcher-gate.sh +51 -0
  79. package/dist/skills/watcher-observability/tests/error-scan.test.sh +257 -0
  80. package/dist/skills/watcher-observability/tests/live-windows.test.sh +177 -0
  81. package/dist/skills/watcher-observability/tests/resolve-containers.test.sh +87 -0
  82. package/dist/skills/watcher-observability/tests/save-counts.test.sh +338 -0
  83. package/dist/skills/watcher-observability/tests/sleuth.test.sh +176 -0
  84. package/dist/skills/watcher-observability/tests/summarize-logs.test.sh +105 -0
  85. package/dist/skills/watcher-observability/tests/watcher-config.test.sh +70 -0
  86. package/dist/skills/watcher-observability/tests/watcher-gate.test.sh +110 -0
  87. package/dist/skills/watcher-observability/watcher.json +1 -0
  88. package/dist/skills/workflow-auditor/SKILL.md +55 -0
  89. package/dist/skills/workflow-auditor/references/audit-protocol.md +49 -0
  90. package/dist/skills/workflow-auditor/references/ledger.md +122 -0
  91. package/dist/skills/workflow-auditor/scripts/audit-ledger.py +624 -0
  92. package/dist/skills/workflow-auditor/scripts/list-zed-commands.py +183 -0
  93. package/dist/skills/workflow-auditor/scripts/render-workflow.py +201 -0
  94. package/dist/skills/workflow-auditor/scripts/validate-skills.py +444 -0
  95. package/dist/skills/workflow-auditor/tests/audit-ledger.test.sh +660 -0
  96. package/dist/skills/workflow-auditor/tests/list-zed-commands.test.sh +93 -0
  97. package/dist/skills/workflow-auditor/tests/render-workflow.test.sh +135 -0
  98. package/dist/skills/workflow-auditor/tests/validate-skills.test.sh +190 -0
  99. package/package.json +27 -6
  100. package/README.md +0 -3
@@ -0,0 +1,183 @@
1
+ #!/usr/bin/env python3
2
+ """List the slash commands a Zed-hosted agent advertises for a project.
3
+
4
+ Zed's Agent Panel can run the Zed native agent or an external ACP agent
5
+ (Cursor, Codex, OpenCode...). Each one exposes its own commands, so the `/`
6
+ menu can stay empty even when `.agents/skills/` is correct. This script
7
+ performs the same ACP handshake Zed performs and prints what the agent says.
8
+
9
+ Usage:
10
+ python3 -I -B skills/workflow-auditor/scripts/list-zed-commands.py [project-dir] [--agent cursor]
11
+
12
+ It is read-only: it starts one agent process, asks for a session, prints the
13
+ advertised commands and exits. No prompt is sent and no file is touched.
14
+ Standard library only; replaces list-zed-commands.mjs so Node is no longer a
15
+ second runtime requirement (ADR 0001).
16
+ """
17
+
18
+ import json
19
+ import os
20
+ from pathlib import Path
21
+ from queue import Empty, Queue
22
+ import re
23
+ import subprocess
24
+ import sys
25
+ from threading import Thread
26
+ from time import monotonic
27
+
28
+ SESSION_GRACE = 20 # commands arrive shortly after the session opens
29
+ OVERALL_TIMEOUT = 60
30
+ SCOPE = re.compile(r'\((project|user) skill\)$')
31
+
32
+
33
+ def parse_args(argv):
34
+ agent = argv[argv.index('--agent') + 1] if '--agent' in argv and argv.index('--agent') + 1 < len(argv) else 'cursor'
35
+ project = next((a for a in argv if not a.startswith('--') and a != agent), None)
36
+ # realpath, not abspath: the agent runs in the real directory (macOS: /var is
37
+ # /private/var), and ACP compares the session cwd with the one it sees.
38
+ return agent, os.path.realpath(project or os.getcwd())
39
+
40
+
41
+ def resolve_launcher(name):
42
+ """Zed keeps registry-hosted ACP agents here, one directory per version."""
43
+ home = Path.home()
44
+ roots = [Path(os.environ['LOCALAPPDATA'], 'Zed', 'external_agents', 'registry', name)] \
45
+ if os.environ.get('LOCALAPPDATA') else []
46
+ roots += [home / 'Library' / 'Application Support' / 'Zed' / 'external_agents' / 'registry' / name,
47
+ home / '.local' / 'share' / 'zed' / 'external_agents' / 'registry' / name]
48
+ for root in roots:
49
+ if not root.is_dir():
50
+ continue
51
+ version = next((entry for entry in os.listdir(root) if entry.startswith('v_')), None)
52
+ if not version:
53
+ continue
54
+ dist = root / version / 'dist-package'
55
+ # Windows ships a .ps1 launcher; the .cmd wrapper breaks paths with spaces.
56
+ for candidate in (dist / f'{name}-agent.ps1', dist / f'{name}-agent', dist / f'{name}-agent.cmd'):
57
+ if candidate.exists():
58
+ return str(candidate)
59
+ return None
60
+
61
+
62
+ def pump(stream, queue, tag):
63
+ for raw in iter(stream.readline, b''):
64
+ queue.put((tag, raw.decode('utf-8', 'replace')))
65
+ queue.put((tag, None))
66
+
67
+
68
+ def drain_stderr(events, agent, wait=0.5):
69
+ """Print the agent's remaining stderr lines, so its own error message is not lost."""
70
+ end = monotonic() + wait
71
+ while True:
72
+ try:
73
+ tag, text = events.get(timeout=max(0, end - monotonic()))
74
+ except Empty:
75
+ return
76
+ if tag == 'err' and text is None:
77
+ return
78
+ if tag == 'err' and text.strip():
79
+ print(f'[{agent}] {text.strip()}', file=sys.stderr)
80
+
81
+
82
+ def main(argv):
83
+ agent, cwd = parse_args(argv)
84
+ launcher = resolve_launcher(agent)
85
+ if not launcher:
86
+ print(f"No {agent} agent found in Zed's ACP registry.\n"
87
+ 'Install it from the Agent Panel (zed: acp registry) or pass --agent <name>.', file=sys.stderr)
88
+ return 2
89
+ if os.name == 'nt' and launcher.endswith('.ps1'):
90
+ argv_agent = ['powershell.exe', '-NoProfile', '-ExecutionPolicy', 'Bypass', '-File', launcher, 'acp']
91
+ else:
92
+ argv_agent = [launcher, 'acp']
93
+ try:
94
+ child = subprocess.Popen(argv_agent, cwd=cwd, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
95
+ stderr=subprocess.PIPE)
96
+ except OSError as error:
97
+ print(f'Could not start {agent}: {error.strerror or error}', file=sys.stderr)
98
+ return 2
99
+
100
+ events = Queue()
101
+ for stream, tag in ((child.stdout, 'out'), (child.stderr, 'err')):
102
+ Thread(target=pump, args=(stream, events, tag), daemon=True).start()
103
+
104
+ def send(payload):
105
+ child.stdin.write((json.dumps(payload, separators=(',', ':')) + '\n').encode())
106
+ child.stdin.flush()
107
+
108
+ def finish(code):
109
+ if child.poll() is None:
110
+ child.kill()
111
+ child.wait()
112
+ return code
113
+
114
+ send({'jsonrpc': '2.0', 'id': 1, 'method': 'initialize', 'params': {
115
+ 'protocolVersion': 1,
116
+ 'clientCapabilities': {'fs': {'readTextFile': False, 'writeTextFile': False}, 'terminal': False}}})
117
+ # Two clocks, as in the Node version: the overall timeout always applies, and
118
+ # once the session opens a shorter grace period ends the run successfully.
119
+ overall = monotonic() + OVERALL_TIMEOUT
120
+ grace = None
121
+ session_open = False
122
+ while True:
123
+ deadline = overall if grace is None else min(overall, grace)
124
+ try:
125
+ tag, text = events.get(timeout=max(0, deadline - monotonic()))
126
+ except Empty:
127
+ if session_open and grace <= overall:
128
+ return finish(0)
129
+ print(f'Timeout: the agent did not advertise commands within {OVERALL_TIMEOUT}s.', file=sys.stderr)
130
+ return finish(1)
131
+ if text is None:
132
+ if tag == 'out' and session_open:
133
+ return finish(0) # the agent closed its output: nothing more can arrive
134
+ if tag == 'out':
135
+ # Closed before a session opened: nothing can ever arrive. Waiting for the
136
+ # overall timeout only hid the real cause behind a misleading "Timeout".
137
+ try:
138
+ code = child.wait(timeout=2)
139
+ except subprocess.TimeoutExpired:
140
+ code = 'still running'
141
+ drain_stderr(events, agent)
142
+ print(f'The {agent} agent exited (code {code}) before opening a session.', file=sys.stderr)
143
+ return finish(1)
144
+ continue
145
+ if tag == 'err':
146
+ if text.strip():
147
+ print(f'[{agent}] {text.strip()}', file=sys.stderr)
148
+ continue
149
+ line = text.strip()
150
+ if not line:
151
+ continue
152
+ try:
153
+ message = json.loads(line)
154
+ except ValueError:
155
+ continue
156
+ if not isinstance(message, dict):
157
+ continue
158
+ ident = message.get('id')
159
+ if ident == 1 and not isinstance(ident, bool):
160
+ send({'jsonrpc': '2.0', 'id': 2, 'method': 'session/new', 'params': {'cwd': cwd, 'mcpServers': []}})
161
+ continue
162
+ if ident == 2 and not isinstance(ident, bool):
163
+ if message.get('error'):
164
+ error = json.dumps(message['error'], separators=(',', ':'), ensure_ascii=False)
165
+ print(f'Session error: {error}', file=sys.stderr)
166
+ return finish(1)
167
+ session_open = True
168
+ grace = monotonic() + SESSION_GRACE
169
+ continue
170
+ params = message.get('params')
171
+ update = params.get('update') if isinstance(params, dict) else None
172
+ if isinstance(update, dict) and update.get('sessionUpdate') == 'available_commands_update':
173
+ commands = update.get('availableCommands') or []
174
+ print(f'{len(commands)} commands advertised for {cwd} ({agent})')
175
+ for entry in commands:
176
+ description = entry.get('description')
177
+ scope = SCOPE.search(description) if isinstance(description, str) else None
178
+ print(f' /{entry.get("name")}' + (f' ({scope.group(1)} skill)' if scope else ''))
179
+ sys.stdout.flush()
180
+
181
+
182
+ if __name__ == '__main__':
183
+ sys.exit(main(sys.argv[1:]))
@@ -0,0 +1,201 @@
1
+ #!/usr/bin/env python3
2
+ """render-workflow.py: generate the README workflow Mermaid block from one source.
3
+
4
+ Usage:
5
+ python3 -I -B scripts/render-workflow.py [--check | --write] [repo-root]
6
+
7
+ docs/diagrams/workflow.json is the single source of the workflow stages and edges
8
+ (ADR 0002). --check (the default, used by CI) only reads: it fails when the README
9
+ block between the workflow markers differs from what the JSON generates, when the
10
+ JSON is invalid, or when a stage's `agents` phrase is missing from the AGENTS.md
11
+ handoff block. --write replaces only the text between the two markers, atomically.
12
+
13
+ Standard library only. JSON is parsed with `json`, which cannot run code.
14
+ """
15
+
16
+ import json
17
+ import os
18
+ from pathlib import Path
19
+ import re
20
+ import sys
21
+ import tempfile
22
+
23
+ SOURCE = Path('docs/diagrams/workflow.json')
24
+ README = Path('README.md')
25
+ AGENTS = Path('AGENTS.md')
26
+ BEGIN = '<!-- workflow:begin generated by skills/workflow-auditor/scripts/render-workflow.py from docs/diagrams/workflow.json; do not edit by hand -->'
27
+ END = '<!-- workflow:end -->'
28
+ ID = re.compile(r'[A-Za-z][A-Za-z0-9]{0,39}')
29
+ # Characters that would end a Mermaid label or start new syntax: they could
30
+ # inject a node or an edge, so labels may not contain them.
31
+ UNSAFE_LABEL = re.compile(r'["`\[\]\n\r]')
32
+ UNSAFE_EDGE_LABEL = re.compile(r'[|"`\n\r]')
33
+ ARROWS = {'solid': '-->', 'dotted': '-.->'}
34
+
35
+
36
+ class Invalid(Exception):
37
+ """The workflow source or its mirrors are not consistent."""
38
+
39
+
40
+ def require(condition, message):
41
+ if not condition:
42
+ raise Invalid(message)
43
+
44
+
45
+ def exact_keys(obj, required, optional, where):
46
+ require(isinstance(obj, dict), f'{where}: must be an object')
47
+ keys = set(obj)
48
+ require(required <= keys, f'{where}: missing {sorted(required - keys)}')
49
+ require(keys <= required | optional, f'{where}: unknown {sorted(keys - required - optional)}')
50
+
51
+
52
+ def text(value, where, unsafe):
53
+ require(isinstance(value, str) and value.strip() == value and value, f'{where}: must be a trimmed, non-empty string')
54
+ require(len(value) <= 160, f'{where}: longer than 160 characters')
55
+ require(not unsafe.search(value), f'{where}: contains a character that would break Mermaid syntax')
56
+ return value
57
+
58
+
59
+ def validate(doc):
60
+ exact_keys(doc, {'version', 'direction', 'nodes', 'groups', 'edges'}, set(), 'workflow')
61
+ require(doc['version'] == 1, 'workflow.version: must be 1')
62
+ require(doc['direction'] in ('TD', 'LR'), 'workflow.direction: must be TD or LR')
63
+ require(isinstance(doc['nodes'], dict) and doc['nodes'], 'workflow.nodes: must be a non-empty object')
64
+ for node_id, node in doc['nodes'].items():
65
+ require(ID.fullmatch(node_id), f'node id {node_id!r}: must match {ID.pattern}')
66
+ exact_keys(node, {'label', 'agents'}, set(), f'nodes.{node_id}')
67
+ text(node['label'], f'nodes.{node_id}.label', UNSAFE_LABEL)
68
+ text(node['agents'], f'nodes.{node_id}.agents', re.compile(r'[\n\r]'))
69
+ require(isinstance(doc['groups'], list), 'workflow.groups: must be a list')
70
+ require(isinstance(doc['edges'], list), 'workflow.edges: must be a list')
71
+ seen_groups, used = set(), set()
72
+ for index, group in enumerate(doc['groups']):
73
+ exact_keys(group, {'id', 'title', 'edges'}, set(), f'groups[{index}]')
74
+ require(ID.fullmatch(group['id']) and group['id'] not in doc['nodes'], f'groups[{index}].id: invalid or reused')
75
+ require(group['id'] not in seen_groups, f'groups[{index}].id: duplicate {group["id"]}')
76
+ seen_groups.add(group['id'])
77
+ text(group['title'], f'groups[{index}].title', UNSAFE_LABEL)
78
+ require(isinstance(group['edges'], list) and group['edges'], f'groups[{index}].edges: must be a non-empty list')
79
+ for where, edge in iter_edges(doc):
80
+ exact_keys(edge, {'from', 'to'}, {'style', 'label'}, where)
81
+ for end in ('from', 'to'):
82
+ require(edge[end] in doc['nodes'], f'{where}.{end}: unknown node {edge[end]!r}')
83
+ used.add(edge[end])
84
+ require(edge.get('style', 'solid') in ARROWS, f'{where}.style: must be solid or dotted')
85
+ if 'label' in edge:
86
+ text(edge['label'], f'{where}.label', UNSAFE_EDGE_LABEL)
87
+ unused = sorted(set(doc['nodes']) - used)
88
+ require(not unused, f'nodes not used by any edge: {unused}')
89
+ return doc
90
+
91
+
92
+ def iter_edges(doc):
93
+ for index, group in enumerate(doc['groups']):
94
+ for j, edge in enumerate(group['edges']):
95
+ yield f'groups[{index}].edges[{j}]', edge
96
+ for j, edge in enumerate(doc['edges']):
97
+ yield f'edges[{j}]', edge
98
+
99
+
100
+ def render(doc):
101
+ """Deterministic Mermaid: a label is printed at a node's first appearance."""
102
+ declared = set()
103
+
104
+ def ref(node_id):
105
+ if node_id in declared:
106
+ return node_id
107
+ declared.add(node_id)
108
+ return f'{node_id}["{doc["nodes"][node_id]["label"]}"]'
109
+
110
+ def line(edge, indent):
111
+ arrow = ARROWS[edge.get('style', 'solid')]
112
+ if 'label' in edge:
113
+ arrow += f'|{edge["label"]}|'
114
+ return f'{indent}{ref(edge["from"])} {arrow} {ref(edge["to"])}'
115
+
116
+ out = [f'flowchart {doc["direction"]}']
117
+ for group in doc['groups']:
118
+ out.append(f' subgraph {group["id"]}["{group["title"]}"]')
119
+ out += [line(edge, ' ') for edge in group['edges']]
120
+ out.append(' end')
121
+ out += [line(edge, ' ') for edge in doc['edges']]
122
+ return '\n'.join(out) + '\n'
123
+
124
+
125
+ def generated_section(doc):
126
+ return f'{BEGIN}\n\n```mermaid\n{render(doc)}```\n\n{END}'
127
+
128
+
129
+ def read_text(path):
130
+ require(path.is_file() and not path.is_symlink(), f'{path}: must be a regular file, not a symlink')
131
+ return path.read_text(encoding='utf-8')
132
+
133
+
134
+ def section_bounds(readme):
135
+ require(readme.count(BEGIN) == 1 and readme.count(END) == 1, f'{README}: needs exactly one pair of workflow markers')
136
+ start, end = readme.index(BEGIN), readme.index(END) + len(END)
137
+ require(start < end, f'{README}: workflow markers are out of order')
138
+ return start, end
139
+
140
+
141
+ def check_agents(root, doc):
142
+ block = re.search(r'## Skill handoffs\s+```text\n(.*?)```', read_text(root / AGENTS), re.S)
143
+ require(block, f'{AGENTS}: handoff block not found')
144
+ missing = [f'{node_id} ({node["agents"]!r})' for node_id, node in doc['nodes'].items()
145
+ if node['agents'] not in block.group(1)]
146
+ require(not missing, f'{AGENTS}: handoff block lacks the agents phrase of {", ".join(missing)}')
147
+
148
+
149
+ def load(root):
150
+ try:
151
+ doc = json.loads(read_text(root / SOURCE))
152
+ except ValueError as exc:
153
+ raise Invalid(f'{SOURCE}: invalid JSON ({exc})') from None
154
+ return validate(doc)
155
+
156
+
157
+ def run(root, write):
158
+ doc = load(root)
159
+ check_agents(root, doc)
160
+ readme = read_text(root / README)
161
+ start, end = section_bounds(readme)
162
+ expected = generated_section(doc)
163
+ if readme[start:end] == expected:
164
+ return 'up to date'
165
+ if not write:
166
+ raise Invalid(f'{README}: workflow block differs from {SOURCE}; run render-workflow.py --write')
167
+ updated = readme[:start] + expected + readme[end:]
168
+ target = root / README
169
+ fd, tmp = tempfile.mkstemp(dir=str(target.parent), prefix='.README.', suffix='.tmp')
170
+ try:
171
+ with os.fdopen(fd, 'w', encoding='utf-8', newline='') as handle:
172
+ handle.write(updated)
173
+ os.replace(tmp, target)
174
+ except BaseException:
175
+ if os.path.exists(tmp):
176
+ os.unlink(tmp)
177
+ raise
178
+ return 'written'
179
+
180
+
181
+ def main(argv):
182
+ flags = [a for a in argv if a.startswith('--')]
183
+ paths = [a for a in argv if not a.startswith('--')]
184
+ if any(f not in ('--check', '--write', '--help') for f in flags) or len(paths) > 1 or \
185
+ ('--check' in flags and '--write' in flags):
186
+ print(__doc__.split('\n\n')[1], file=sys.stderr)
187
+ return 2
188
+ if '--help' in flags:
189
+ print(__doc__)
190
+ return 0
191
+ root = Path(paths[0]) if paths else Path(__file__).resolve().parents[3]
192
+ try:
193
+ print(f'workflow: {run(root, "--write" in flags)}')
194
+ except (Invalid, OSError) as exc:
195
+ print(f'workflow: {exc}', file=sys.stderr)
196
+ return 1
197
+ return 0
198
+
199
+
200
+ if __name__ == '__main__':
201
+ sys.exit(main(sys.argv[1:]))