agent-concepts 0.0.0-stage → 0.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.
Files changed (139) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +773 -2
  3. package/concepts/bc-brainstorming/body/SKILL.md +43 -0
  4. package/concepts/bc-code-review/body/SKILL.md +120 -0
  5. package/concepts/bc-codebase-design/body/SKILL.md +54 -0
  6. package/concepts/bc-codebase-docs/body/SKILL.md +150 -0
  7. package/concepts/bc-council-audit-security/body/SKILL.md +72 -0
  8. package/concepts/bc-council-chain/body/SKILL.md +71 -0
  9. package/concepts/bc-council-challenge-plan/body/SKILL.md +78 -0
  10. package/concepts/bc-council-find-bugs/body/SKILL.md +70 -0
  11. package/concepts/bc-council-improve-architecture/body/SKILL.md +52 -0
  12. package/concepts/bc-council-mode/body/SKILL.md +56 -0
  13. package/concepts/bc-council-mode/body/examples/agents/README.md +11 -0
  14. package/concepts/bc-council-mode/body/examples/agents/council-change.md +14 -0
  15. package/concepts/bc-council-mode/body/examples/agents/council-compat.md +14 -0
  16. package/concepts/bc-council-mode/body/examples/agents/council-risk.md +14 -0
  17. package/concepts/bc-council-mode/body/references/pass-contracts.md +133 -0
  18. package/concepts/bc-delegate-investigation/body/SKILL.md +119 -0
  19. package/concepts/bc-delegate-investigation/body/examples/pi-settings-snippet.json +8 -0
  20. package/concepts/bc-delegate-investigation/body/pi.md +170 -0
  21. package/concepts/bc-design/body/SKILL.md +49 -0
  22. package/concepts/bc-design/body/design-framework.md +39 -0
  23. package/concepts/bc-design/body/existing-app.md +9 -0
  24. package/concepts/bc-design/body/new-work.md +22 -0
  25. package/concepts/bc-design/body/principles.md +34 -0
  26. package/concepts/bc-design/body/surfaces.md +13 -0
  27. package/concepts/bc-diagnosing-bugs/body/SKILL.md +83 -0
  28. package/concepts/bc-dispatching-parallel-agents/body/SKILL.md +63 -0
  29. package/concepts/bc-domain-modeling/body/SKILL.md +40 -0
  30. package/concepts/bc-executing-plans/body/SKILL.md +50 -0
  31. package/concepts/bc-explain-visually/body/SKILL.md +167 -0
  32. package/concepts/bc-find-bugs/body/SKILL.md +90 -0
  33. package/concepts/bc-finishing-development-branch/body/SKILL.md +73 -0
  34. package/concepts/bc-grilling/body/SKILL.md +22 -0
  35. package/concepts/bc-handoff/body/SKILL.md +104 -0
  36. package/concepts/bc-handoff/body/pickup.md +107 -0
  37. package/concepts/bc-handoff/body/writing.md +217 -0
  38. package/concepts/bc-improve-codebase-architecture/body/SKILL.md +101 -0
  39. package/concepts/bc-json-canvas/body/SKILL.md +40 -0
  40. package/concepts/bc-json-canvas/body/references/EXAMPLES.md +71 -0
  41. package/concepts/bc-json-canvas/body/references/SPEC.md +55 -0
  42. package/concepts/bc-json-canvas/body/references/VALIDATION.md +26 -0
  43. package/concepts/bc-minimal-solution-ladder/body/SKILL.md +120 -0
  44. package/concepts/bc-obsidian-bases/body/SKILL.md +59 -0
  45. package/concepts/bc-obsidian-bases/body/references/EXAMPLES.md +80 -0
  46. package/concepts/bc-obsidian-bases/body/references/FUNCTIONS.md +49 -0
  47. package/concepts/bc-obsidian-bases/body/references/SYNTAX.md +82 -0
  48. package/concepts/bc-obsidian-bases/body/references/TROUBLESHOOTING.md +41 -0
  49. package/concepts/bc-obsidian-markdown/body/SKILL.md +47 -0
  50. package/concepts/bc-obsidian-markdown/body/references/CALLOUTS.md +40 -0
  51. package/concepts/bc-obsidian-markdown/body/references/EMBEDS.md +35 -0
  52. package/concepts/bc-obsidian-markdown/body/references/PROPERTIES.md +37 -0
  53. package/concepts/bc-optimize-code/body/SKILL.md +41 -0
  54. package/concepts/bc-performance-guardrails/body/SKILL.md +53 -0
  55. package/concepts/bc-performance-guardrails/body/measuring.md +29 -0
  56. package/concepts/bc-performance-guardrails/body/targets.md +20 -0
  57. package/concepts/bc-pipeline-to-done/body/SKILL.md +205 -0
  58. package/concepts/bc-pipeline-to-done/body/agents/bc-drain-auditor.md +19 -0
  59. package/concepts/bc-pipeline-to-done/body/agents/bc-drain-reviewer.md +19 -0
  60. package/concepts/bc-pipeline-to-done/body/agents/bc-drain-worker.md +19 -0
  61. package/concepts/bc-pipeline-to-done/body/execute-issue.md +71 -0
  62. package/concepts/bc-pipeline-to-done/body/recovery-bundle.md +79 -0
  63. package/concepts/bc-pipeline-to-done/body/review-contract.md +105 -0
  64. package/concepts/bc-pipeline-to-done/body/roles.md +13 -0
  65. package/concepts/bc-pipeline-to-done/body/scripts/publish-check.py +172 -0
  66. package/concepts/bc-pipeline-to-done/body/source-issues.md +86 -0
  67. package/concepts/bc-pipeline-to-done/body/source-work-items.md +76 -0
  68. package/concepts/bc-plain-language/body/SKILL.md +134 -0
  69. package/concepts/bc-plan-slicing/body/SKILL.md +56 -0
  70. package/concepts/bc-plan-to-pipeline/body/SKILL.md +89 -0
  71. package/concepts/bc-prd-drafting/body/SKILL.md +43 -0
  72. package/concepts/bc-prompting-agents/body/SKILL.md +278 -0
  73. package/concepts/bc-prototype/body/SKILL.md +40 -0
  74. package/concepts/bc-qmd/body/SKILL.md +64 -0
  75. package/concepts/bc-research/body/SKILL.md +26 -0
  76. package/concepts/bc-security-audit/body/AI-AND-LLM.md +25 -0
  77. package/concepts/bc-security-audit/body/ATTACK-CLASSES.md +35 -0
  78. package/concepts/bc-security-audit/body/DESKTOP-MOBILE-AND-LOCAL-IPC.md +28 -0
  79. package/concepts/bc-security-audit/body/RECONNAISSANCE.md +49 -0
  80. package/concepts/bc-security-audit/body/SKILL.md +117 -0
  81. package/concepts/bc-security-audit/body/SUPPLY-CHAIN-AND-RELEASE.md +28 -0
  82. package/concepts/bc-security-audit/body/VALIDATION-AND-REPORTING.md +124 -0
  83. package/concepts/bc-security-audit/body/WEB-PROTOCOL-AND-AUTH.md +27 -0
  84. package/concepts/bc-security-audit/body/validate_audit.py +151 -0
  85. package/concepts/bc-self-improve/body/SKILL.md +104 -0
  86. package/concepts/bc-seo/body/CITATIONS.md +23 -0
  87. package/concepts/bc-seo/body/IMAGE-SEO.md +350 -0
  88. package/concepts/bc-seo/body/SKILL.md +453 -0
  89. package/concepts/bc-setup-project/body/SKILL.md +252 -0
  90. package/concepts/bc-setup-project/body/scaffold.py +2751 -0
  91. package/concepts/bc-setup-project/body/starter-items.md +157 -0
  92. package/concepts/bc-setup-project/body/work-data.md +114 -0
  93. package/concepts/bc-setup-project/body/work_index.py +626 -0
  94. package/concepts/bc-setup-project/body/work_spent.py +220 -0
  95. package/concepts/bc-subagent-driven-development/body/SKILL.md +61 -0
  96. package/concepts/bc-tdd/body/SKILL.md +184 -0
  97. package/concepts/bc-tdd/body/formal.md +77 -0
  98. package/concepts/bc-tdd/body/mocking.md +49 -0
  99. package/concepts/bc-tdd/body/properties.md +59 -0
  100. package/concepts/bc-tdd/body/refactoring.md +12 -0
  101. package/concepts/bc-tdd/body/scripts/confirm-red.py +136 -0
  102. package/concepts/bc-tdd/body/tests.md +59 -0
  103. package/concepts/bc-teach/body/GLOSSARY-FORMAT.md +36 -0
  104. package/concepts/bc-teach/body/LEARNING-RECORD-FORMAT.md +60 -0
  105. package/concepts/bc-teach/body/MISSION-FORMAT.md +34 -0
  106. package/concepts/bc-teach/body/RESOURCES-FORMAT.md +53 -0
  107. package/concepts/bc-teach/body/REVIEW-FORMAT.md +48 -0
  108. package/concepts/bc-teach/body/SKILL.md +281 -0
  109. package/concepts/bc-teach/body/WIKI-FORMAT.md +58 -0
  110. package/concepts/bc-teach/body/scripts/due.py +65 -0
  111. package/concepts/bc-to-spec/body/SKILL.md +21 -0
  112. package/concepts/bc-to-tickets/body/SKILL.md +21 -0
  113. package/concepts/bc-triage/body/AGENT-BRIEF.md +38 -0
  114. package/concepts/bc-triage/body/OUT-OF-SCOPE.md +51 -0
  115. package/concepts/bc-triage/body/SKILL.md +81 -0
  116. package/concepts/bc-unslop/body/SKILL.md +269 -0
  117. package/concepts/bc-using-git-worktrees/body/SKILL.md +91 -0
  118. package/concepts/bc-wiki-maintain/body/SKILL.md +361 -0
  119. package/concepts/bc-wiki-maintain/body/runner/README.md +552 -0
  120. package/concepts/bc-wiki-maintain/body/runner/bc-wiki-lint.service +24 -0
  121. package/concepts/bc-wiki-maintain/body/runner/bc-wiki-lint.timer +15 -0
  122. package/concepts/bc-wiki-maintain/body/runner/bc-wiki-maintain-all.service +29 -0
  123. package/concepts/bc-wiki-maintain/body/runner/bc-wiki-maintain-all.timer +16 -0
  124. package/concepts/bc-wiki-maintain/body/runner/bc-wiki-maintain.service +28 -0
  125. package/concepts/bc-wiki-maintain/body/runner/bc-wiki-maintain.timer +12 -0
  126. package/concepts/bc-wiki-maintain/body/runner/bc-wiki-notify@.service +15 -0
  127. package/concepts/bc-wiki-maintain/body/runner/notify-failure.sh +92 -0
  128. package/concepts/bc-wiki-maintain/body/runner/run-lint.sh +69 -0
  129. package/concepts/bc-wiki-maintain/body/runner/run-promotion-all.sh +103 -0
  130. package/concepts/bc-wiki-maintain/body/runner/run-promotion.sh +270 -0
  131. package/concepts/bc-wiki-maintain/body/wiki_lint.py +958 -0
  132. package/concepts/bc-wiki-maintain/body/wiki_search.py +206 -0
  133. package/concepts/bc-work-sync/body/PLAN.md +46 -0
  134. package/concepts/bc-work-sync/body/SKILL.md +71 -0
  135. package/concepts/bc-writing-plans/body/SKILL.md +79 -0
  136. package/package.json +130 -4
  137. package/packages/agent-kernel-pi/AGENT-KERNEL.md +109 -0
  138. package/packages/agent-kernel-pi/index.js +8 -0
  139. package/packages/agent-kernel-pi/package.json +12 -0
@@ -0,0 +1,626 @@
1
+ #!/usr/bin/env python3
2
+ """Write the pipeline table in work/README.md from the open work items.
3
+
4
+ Usage: python3 .bc-agent/scripts/work_index.py [--check | --json] [work-dir]
5
+
6
+ --json prints the work data of every item (all four folders) as one JSON object
7
+ and writes nothing; the bc-setup-project skill's work-data.md lists its fields.
8
+
9
+ Every item in 1-planned/ and 2-active/ needs a `Blocked by:` line naming full
10
+ item names (`012-search-ranking`, comma-separated) or `nothing`. A `Stage:` line
11
+ is optional; an unknown stage is an error. A `Kind:` line (security, bug, feature, ...)
12
+ is optional and free text, as are `Needs owner:` and `Changes UI:` lines. An optional `Ready for agent: yes` line (bc-pipeline-to-done
13
+ may build the item unattended) or `Waiting on owner: <question>` line (parked) is shown
14
+ in the Folder column; an item with both is an error. Unknown names, dropped blockers, self-blocks and cycles among open
15
+ items are errors. A blocker in 3-done/ is satisfied; an item is ready when all
16
+ its blockers are done.
17
+
18
+ The optional work/order.md is the owner's ranking of open items, top first, as
19
+ a numbered list (`1. 012-search-ranking`, ASCII digits); other lines are ignored.
20
+ Lines end at \r\n, \r or \n; whitespace in a line is space or tab only.
21
+ Names in 3-done/ or 4-dropped/ (or their month folders) are skipped unless an
22
+ open item has the same name; an unknown or repeated name is an error.
23
+ Without the file there is no owner order; the three tiers below still apply.
24
+ Unlisted blockers do not inherit a listed item’s rank; dashboard-written orders list every open item, so this
25
+ only affects hand-written partial lists.
26
+
27
+ The table is a topological order of the open items: an item never precedes an
28
+ open item it is transitively blocked by. Among the items available at each
29
+ point it picks: active items, then planned items that an active item is
30
+ (transitively) blocked by, then other planned items, then owner order (listed before
31
+ unlisted), ready before not ready, more open items transitively unblocked
32
+ first, then the stage order from the
33
+ `Stages:` line in `.bc-agent/AGENTS.md` (default: now, next, later,
34
+ unscheduled; an item without a `Stage:` line sorts after every stage), then
35
+ the name. A valid owner order is a fixed point: ranking by
36
+ it reproduces it. `--check` writes nothing and exits 1 while the
37
+ table is out of date, and, when work/order.md exists, while it leaves out an
38
+ open item or lists an item above an item it
39
+ is Blocked by. The owner's dashboard writes every open item and never puts one
40
+ above its blocker, so either fault comes from an agent.
41
+
42
+ Where --check says to add a missing item: an item whose Kind is a top kind goes
43
+ directly below the top group (the run of listed items at the top of order.md
44
+ whose Kind is a top kind), or at the top when there is none, so it never jumps
45
+ ahead of a top item the owner placed; several new top items go oldest first.
46
+ Every other item goes directly above the first listed item that waits on it,
47
+ else at the bottom. Either way an item stays below every item it is Blocked by
48
+ and above the first item that waits on it. Top kinds come from the
49
+ `Top kinds:` line in `.bc-agent/AGENTS.md` (default: security, bug, build,
50
+ architecture; `none` turns top placement off).
51
+
52
+ `--check` also warns, on stderr and without changing the exit code, about each
53
+ item in 1-planned/ that has no `Planned:` line: it has not been through
54
+ bc-plan-to-pipeline, so it must be planned before it moves to 2-active/. It also warns
55
+ about a malformed `Held by: <tool> <session> since <YYYY-MM-DD HH:MM> <UTC or +HH:MM>`
56
+ line, and about any `Held by:` line in a done or dropped item.
57
+ Python 3.9 or later, standard library only.
58
+ """
59
+ from __future__ import annotations
60
+
61
+ import json
62
+ import re
63
+ import subprocess
64
+ import sys
65
+ from datetime import datetime, timezone
66
+ from pathlib import Path
67
+
68
+ DEFAULT_STAGES = ("now", "next", "later", "unscheduled")
69
+ DEFAULT_TOP_KINDS = ("security", "bug", "build", "architecture")
70
+ START = "<!-- work-index:start -->"
71
+ END = "<!-- work-index:end -->"
72
+ COMMAND = "python3 .bc-agent/scripts/work_index.py"
73
+ ITEM_NAME = re.compile(r"^\d{3}-")
74
+ ORDER_LINE = re.compile(r"^[ \t]*[0-9]+\.[ \t]+([0-9]{3}-[^ \t]+)[ \t]*$")
75
+ MONTH = re.compile(r"^\d{4}-\d{2}$")
76
+ LINK = re.compile(r"!?\[([^\]]+)\]\((?:[^()]|\([^()]*\))*\)")
77
+ ABBREVIATION = re.compile(r"\b(?:e\.g|i\.e|vs|etc|Mr|Mrs|Ms|Dr)\.$", re.I)
78
+ WHY_LIMIT = 160
79
+ JSON_FORMAT_VERSION = 1
80
+ HEADER_LINES = {"why": "Why", "done_when": "Done when", "stage": "Stage", "blocked_by": "Blocked by",
81
+ "kind": "Kind", "needs_owner": "Needs owner", "changes_ui": "Changes UI",
82
+ "source": "Source", "planned": "Planned", "ready_for_agent": "Ready for agent",
83
+ "waiting_on_owner": "Waiting on owner", "held_by": "Held by"}
84
+ HELD_BY = re.compile(r"^(\S+) (\S+) since (\d{4}-\d{2}-\d{2} \d{2}:\d{2} (?:UTC|[+-]\d{2}:\d{2}))$")
85
+ STEP = re.compile(r"^- \[([ xX])\] ?(.*)$")
86
+ REVIEW = re.compile(r"^(approved|changes requested) by (\S.*?) (\d{4}-\d{2}-\d{2})$")
87
+ GATE = re.compile(r"^(pass|fail) (\S.*?) at ([0-9a-f]{7,40}) (\d{4}-\d{2}-\d{2})$")
88
+ SPENT = re.compile(r"^(.+?) active, (.+?) tokens, (.+?) \(estimated; (.+)\)$")
89
+ SPENT_FORM = "Spent: <active time> active, <tokens> tokens, <cost> (estimated; <sources>)"
90
+ STEP_RECORDS = {"review": ("Review", REVIEW, ("result", "reviewer", "date"),
91
+ "Review: <approved | changes requested> by <reviewer> <YYYY-MM-DD>"),
92
+ "gate": ("Gate", GATE, ("result", "command", "commit", "date"),
93
+ "Gate: <pass | fail> <command> at <commit> <YYYY-MM-DD>")}
94
+
95
+
96
+ class WorkIndexError(Exception):
97
+ pass
98
+
99
+
100
+ class StageError(WorkIndexError):
101
+ pass
102
+
103
+
104
+ def read_text(path: Path) -> str:
105
+ return path.read_bytes().decode("utf-8").replace("\r\n", "\n")
106
+
107
+
108
+ def read_stages(project: Path) -> tuple[str, ...]:
109
+ agents = project / ".bc-agent" / "AGENTS.md"
110
+ if agents.is_file():
111
+ match = re.search(r"^Stages:[ \t]*(.+)$", read_text(agents), re.M)
112
+ if match:
113
+ stages = tuple(s.strip() for s in match.group(1).split(",") if s.strip())
114
+ if stages:
115
+ return stages
116
+ return DEFAULT_STAGES
117
+
118
+
119
+ def read_top_kinds(project: Path) -> tuple[str, ...]:
120
+ agents = project / ".bc-agent" / "AGENTS.md"
121
+ if agents.is_file():
122
+ match = re.search(r"^Top kinds:[ \t]*(.+)$", read_text(agents), re.M)
123
+ if match:
124
+ kinds = tuple(k.strip().lower() for k in match.group(1).split(",") if k.strip())
125
+ return () if kinds == ("none",) else kinds
126
+ return DEFAULT_TOP_KINDS
127
+
128
+
129
+ def entries(work: Path, folder: str) -> list[str]:
130
+ path = work / folder
131
+ return sorted(name.name for name in path.iterdir() if ITEM_NAME.match(name.name)) if path.is_dir() else []
132
+
133
+
134
+ def first_sentence(why: str) -> str:
135
+ why = LINK.sub(r"\1", why)
136
+ in_code = False
137
+ for i, char in enumerate(why):
138
+ if char == "`":
139
+ in_code = not in_code
140
+ if char != "." or in_code or (i + 1 < len(why) and not why[i + 1].isspace()):
141
+ continue
142
+ if ABBREVIATION.search(why[: i + 1]):
143
+ continue
144
+ why = why[: i + 1]
145
+ break
146
+ if len(why) > WHY_LIMIT:
147
+ why = why[: WHY_LIMIT - 1].rstrip() + "…"
148
+ return why.replace("|", "\\|")
149
+
150
+
151
+ def read_item(work: Path, folder: str, name: str, stages: tuple[str, ...]) -> dict:
152
+ rel = f"{folder}/{name}/plan.md" if (work / folder / name).is_dir() else f"{folder}/{name}"
153
+ if not (work / rel).is_file():
154
+ raise WorkIndexError(f"{rel}: missing")
155
+ text = read_text(work / rel)
156
+ stage_match = re.search(r"^Stage: (.+)$", text, re.M)
157
+ stage = stage_match.group(1).strip() if stage_match else None
158
+ if stage is not None and stage not in stages:
159
+ raise StageError(f"{rel}: unknown Stage line (one of: {', '.join(stages)})")
160
+ kind_match = re.search(r"^Kind:[ \t]*(.+)$", text, re.M)
161
+ kind = kind_match.group(1).strip().lower() if kind_match else None
162
+ why_match = re.search(r"^Why: (.+)$", text, re.M)
163
+ why = first_sentence(why_match.group(1) if why_match else "")
164
+ parts = re.split(r"^## Steps$", text, maxsplit=1, flags=re.M)
165
+ steps = re.split(r"^## ", parts[1], maxsplit=1, flags=re.M)[0] if len(parts) > 1 else ""
166
+ done = len(re.findall(r"^- \[x\]", steps, re.M | re.I))
167
+ total = len(re.findall(r"^- \[[ x]\]", steps, re.M | re.I))
168
+ blocked_match = re.search(r"^Blocked by:[ \t]*(.*)$", text, re.M)
169
+ if not blocked_match or not blocked_match.group(1).strip():
170
+ raise StageError(f"{rel}: missing Blocked by line (item names such as 012-search-ranking, or nothing)")
171
+ blocked = blocked_match.group(1).strip()
172
+ ready = re.search(r"^Ready for agent:[ \t]*yes[ \t]*$", text, re.M | re.I) is not None
173
+ waiting = re.search(r"^Waiting on owner:[ \t]*\S", text, re.M) is not None
174
+ if ready and waiting:
175
+ raise StageError(f"{rel}: has both Waiting on owner and Ready for agent: yes; "
176
+ "remove the ready line until the owner's answer is recorded")
177
+ marker = ", waiting on owner" if waiting else ", ready for agent" if ready else ""
178
+ blockers = [] if blocked == "nothing" else [b.strip() for b in blocked.split(",") if b.strip()]
179
+ return {
180
+ "blockers": blockers,
181
+ "stage": stage, "kind": kind, "name": name.removesuffix(".md"), "path": rel, "folder": folder[2:],
182
+ "status": folder[2:] + marker, "why": why, "steps": f"{done}/{total}" if total else "—",
183
+ }
184
+
185
+
186
+ def archive_folders(work: Path, top: str) -> list[str]:
187
+ """A status folder plus its month folders."""
188
+ folders = [top]
189
+ if (work / top).is_dir():
190
+ folders += [f"{top}/{m.name}" for m in (work / top).iterdir() if m.is_dir() and MONTH.match(m.name)]
191
+ return folders
192
+
193
+
194
+ def closed_names(work: Path) -> dict[str, str]:
195
+ """Map each done or dropped item name to its status folder."""
196
+ names = {}
197
+ for folder in archive_folders(work, "3-done") + archive_folders(work, "4-dropped"):
198
+ for name in entries(work, folder):
199
+ names[name.removesuffix(".md")] = folder.split("/")[0]
200
+ return names
201
+
202
+
203
+ def read_owner_order(work: Path, open_items: dict | set, closed: dict[str, str]) -> tuple[dict[str, int], list[str]]:
204
+ """Rank of each open item listed in work/order.md, plus errors for unknown or repeated names."""
205
+ path = work / "order.md"
206
+ if not path.is_file():
207
+ return {}, []
208
+ rank: dict[str, int] = {}
209
+ seen: set[str] = set()
210
+ errors = []
211
+ for line in re.split(r"\r\n|\r|\n", read_text(path)):
212
+ match = ORDER_LINE.match(line)
213
+ if not match:
214
+ continue
215
+ name = match.group(1)
216
+ if name in closed and name not in open_items:
217
+ continue
218
+ if name in seen:
219
+ errors.append(f"order.md: names {name} more than once")
220
+ continue
221
+ seen.add(name)
222
+ if name in open_items:
223
+ rank[name] = len(rank)
224
+ elif name not in closed:
225
+ errors.append(f"order.md: names unknown item {name}")
226
+ return rank, errors
227
+
228
+
229
+ def order_items(work: Path, items: list[dict], stages: tuple[str, ...]) -> list[dict]:
230
+ open_items = {i["name"]: i for i in items}
231
+ closed = closed_names(work)
232
+ rank, errors = read_owner_order(work, open_items, closed)
233
+ for i in items:
234
+ for b in i["blockers"]:
235
+ if b == i["name"]:
236
+ errors.append(f"{i['path']}: Blocked by names the item itself")
237
+ elif b in open_items:
238
+ continue
239
+ elif b not in closed:
240
+ errors.append(f"{i['path']}: Blocked by names unknown item {b}")
241
+ elif closed[b] == "4-dropped":
242
+ errors.append(f"{i['path']}: Blocked by names dropped item {b}; change the plan")
243
+ if errors:
244
+ raise WorkIndexError("\n".join(errors))
245
+ waits = {n: [b for b in i["blockers"] if b in open_items] for n, i in open_items.items()}
246
+ dependents: dict[str, list[str]] = {n: [] for n in open_items}
247
+ for n in sorted(open_items):
248
+ for b in waits[n]:
249
+ dependents[b].append(n)
250
+ cycle = find_cycle(waits)
251
+ if cycle:
252
+ raise WorkIndexError(f"dependency cycle: {' -> '.join(cycle)}")
253
+
254
+ def reach(n: str, seen: set[str]) -> set[str]:
255
+ for d in dependents[n]:
256
+ if d not in seen:
257
+ seen.add(d)
258
+ reach(d, seen)
259
+ return seen
260
+
261
+ feeds_active: set[str] = set()
262
+ stack = [b for n, i in open_items.items() if i["folder"] == "active" for b in waits[n]]
263
+ while stack:
264
+ b = stack.pop()
265
+ if b not in feeds_active:
266
+ feeds_active.add(b)
267
+ stack.extend(waits[b])
268
+
269
+ def key(n: str) -> tuple:
270
+ i = open_items[n]
271
+ tier = 0 if i["folder"] == "active" else 1 if n in feeds_active else 2
272
+ return (tier, rank.get(n, float("inf")), bool(waits[n]), -len(reach(n, set())), stages.index(i["stage"]) if i["stage"] else len(stages), n)
273
+
274
+ for n, i in open_items.items():
275
+ i["waits"] = ", ".join(f"[{b}]({open_items[b]['path']})" for b in waits[n]) or "—"
276
+ i["unblocks"] = ", ".join(dependents[n]) or "—"
277
+ placed: list[str] = []
278
+ remaining = set(open_items)
279
+ while remaining:
280
+ available = [n for n in remaining if all(b in placed for b in waits[n])]
281
+ best = min(available, key=key)
282
+ placed.append(best)
283
+ remaining.remove(best)
284
+ return [open_items[n] for n in placed]
285
+
286
+
287
+ def find_cycle(waits: dict[str, list[str]]) -> list[str] | None:
288
+ state: dict[str, int] = {}
289
+ stack: list[str] = []
290
+
291
+ def visit(n: str) -> list[str] | None:
292
+ state[n] = 1
293
+ stack.append(n)
294
+ for b in waits[n]:
295
+ if state.get(b) == 1:
296
+ return stack[stack.index(b):] + [b]
297
+ if b not in state:
298
+ found = visit(b)
299
+ if found:
300
+ return found
301
+ stack.pop()
302
+ state[n] = 2
303
+ return None
304
+
305
+ for n in sorted(waits):
306
+ if n not in state:
307
+ found = visit(n)
308
+ if found:
309
+ return found
310
+ return None
311
+
312
+
313
+ def build_block(work: Path, stages: tuple[str, ...]) -> str:
314
+ items = []
315
+ errors = []
316
+ for folder in ("2-active", "1-planned"):
317
+ for name in entries(work, folder):
318
+ try:
319
+ items.append(read_item(work, folder, name, stages))
320
+ except StageError as error:
321
+ errors.append(str(error))
322
+ if errors:
323
+ open_names = {n.removesuffix(".md") for f in ("2-active", "1-planned") for n in entries(work, f)}
324
+ errors += read_owner_order(work, open_names, closed_names(work))[1]
325
+ raise WorkIndexError("\n".join(errors))
326
+ items = order_items(work, items, stages)
327
+ done = sum(len(entries(work, f)) for f in archive_folders(work, "3-done"))
328
+ dropped = sum(len(entries(work, f)) for f in archive_folders(work, "4-dropped"))
329
+ ideas_path = work / "0-ideas.md"
330
+ if not ideas_path.is_file():
331
+ raise WorkIndexError("0-ideas.md: missing")
332
+ ideas = len(re.findall(r"^- ", read_text(ideas_path), re.M))
333
+ return "\n".join([
334
+ START,
335
+ f"<!-- Generated by `{COMMAND}`; do not edit by hand. -->",
336
+ "",
337
+ "| # | Item | Folder | Waits on | Unblocks | Why | Steps |",
338
+ "| --- | --- | --- | --- | --- | --- | --- |",
339
+ *(f"| {n} | [{i['name']}]({i['path']}) | {i['status']} | {i['waits']} | {i['unblocks']} | {i['why']} | {i['steps']} |"
340
+ for n, i in enumerate(items, 1)),
341
+ "",
342
+ f"- [Ideas](0-ideas.md): {ideas}",
343
+ f"- [Done](3-done/): {done}",
344
+ f"- [Dropped](4-dropped/): {dropped}",
345
+ END,
346
+ ])
347
+
348
+
349
+ def owner_order_errors(work: Path, stages: tuple[str, ...], top_kinds: tuple[str, ...] = DEFAULT_TOP_KINDS) -> list[str]:
350
+ """What --check reports about work/order.md: open items it leaves out, and items listed above an item they wait on.
351
+
352
+ The owner's dashboard writes every open item and refuses to put one above its blocker, so either fault means an
353
+ agent created an item or added a Blocked by line without placing it; the message says where it goes.
354
+ """
355
+ if not (work / "order.md").is_file():
356
+ return []
357
+ items = {i["name"]: i for i in (read_item(work, f, n, stages) for f in ("2-active", "1-planned") for n in entries(work, f))}
358
+ rank, _ = read_owner_order(work, items, closed_names(work))
359
+ waits = {n: [b for b in i["blockers"] if b in items] for n, i in items.items()}
360
+
361
+ def waits_on(n: str, target: str, seen: set[str]) -> bool:
362
+ for b in waits[n]:
363
+ if b == target or (b not in seen and (seen.add(b) or waits_on(b, target, seen))):
364
+ return True
365
+ return False
366
+
367
+ listed = sorted(rank, key=rank.get)
368
+ missing = sorted(set(items) - set(rank))
369
+ placed = list(listed)
370
+ where: dict[str, str] = {}
371
+ for n in (m for m in missing if items[m]["kind"] in top_kinds):
372
+ at = next((i for i, m in enumerate(placed) if items[m]["kind"] not in top_kinds), len(placed))
373
+ at = max([at] + [i + 1 for i, m in enumerate(placed) if waits_on(n, m, set())])
374
+ at = min([at] + [i for i, m in enumerate(placed) if waits_on(m, n, set())])
375
+ where[n] = f"directly below {placed[at - 1]}" if at else "at the top"
376
+ placed.insert(at, n)
377
+ for n in missing:
378
+ if n not in where:
379
+ first = next((m for m in placed if waits_on(m, n, set())), None)
380
+ where[n] = f"directly above {first}, the first listed item that waits on it" if first else "at the bottom"
381
+ errors = [f"order.md does not list {n}; add it {where[n]}, and move no other line (the owner sets this order)"
382
+ for n in missing]
383
+ for n in listed:
384
+ for b in waits[n]:
385
+ if b in rank and rank[b] > rank[n]:
386
+ errors.append(f"order.md lists {n} above {b}, which it waits on; check with the owner before changing the Blocked by line or the order")
387
+ return errors
388
+
389
+
390
+ def section(text: str, heading: str) -> str | None:
391
+ parts = re.split(rf"^## {heading}[ \t]*$", text, maxsplit=1, flags=re.M)
392
+ return re.split(r"^## ", parts[1], maxsplit=1, flags=re.M)[0] if len(parts) > 1 else None
393
+
394
+
395
+ def parse_steps(text: str) -> list[dict]:
396
+ """Each `- [ ]` line under `## Steps` with its indented continuation lines; `Notes:` (inline or on its own line) split off."""
397
+ bodies: list[tuple[bool, list[str]]] = []
398
+ current: list[str] | None = None
399
+ for line in (section(text, "Steps") or "").split("\n"):
400
+ match = STEP.match(line)
401
+ if match:
402
+ current = [match.group(2).strip()]
403
+ bodies.append((match.group(1) != " ", current))
404
+ elif current is not None and line[:1] in (" ", "\t") and line.strip():
405
+ current.append(line.strip())
406
+ else:
407
+ current = None
408
+ steps = []
409
+ for checked, lines in bodies:
410
+ body, notes = "\n".join(lines), None
411
+ found = re.search(r"(?:^|\s)Notes:[ \t]*", body)
412
+ if found:
413
+ body, notes = body[:found.start()].rstrip(), body[found.end():].strip() or None
414
+ steps.append({"text": body, "checked": checked, "notes": notes, **step_records(notes)})
415
+ return steps
416
+
417
+
418
+ def step_records(notes: str | None) -> dict[str, list[dict]]:
419
+ """`Review:` and `Gate:` lines in a step's Notes, each starting a line; fields `None` when the line is malformed."""
420
+ records = {}
421
+ for key, (label, pattern, fields, _) in STEP_RECORDS.items():
422
+ records[key] = []
423
+ for text in re.findall(rf"^{label}:[ \t]*(.*)$", notes or "", re.M):
424
+ match = pattern.match(text.strip())
425
+ records[key].append({**dict(zip(fields, match.groups() if match else [None] * len(fields))),
426
+ "text": text.strip()})
427
+ return records
428
+
429
+
430
+ def step_record_warnings(work: Path) -> list[str]:
431
+ """`--check` warnings: a malformed `Review:` or `Gate:` line in any item's step Notes."""
432
+ warnings = []
433
+ for folder in ["1-planned", "2-active"] + archive_folders(work, "3-done") + archive_folders(work, "4-dropped"):
434
+ for name in entries(work, folder):
435
+ rel = f"{folder}/{name}/plan.md" if (work / folder / name).is_dir() else f"{folder}/{name}"
436
+ if not (work / rel).is_file():
437
+ continue
438
+ for number, step in enumerate(parse_steps(read_text(work / rel)), 1):
439
+ for key, (label, _, fields, form) in STEP_RECORDS.items():
440
+ for record in step[key]:
441
+ if record[fields[0]] is None:
442
+ warnings.append(f"{rel} step {number} has a malformed {label}: line; write `{form}`")
443
+ return warnings
444
+
445
+
446
+ LIFECYCLE = re.compile(r"(?:^|/)[1-4]-(planned|active|done|dropped)/")
447
+
448
+
449
+ def step_key(line: str) -> str | None:
450
+ """The step text of a `- [ ]` diff line, without any inline Notes, so a tick that also edits the Notes still matches."""
451
+ match = STEP.match(line)
452
+ return re.split(r"(?:^|\s)Notes:", match.group(2), maxsplit=1)[0].strip() if match else None
453
+
454
+
455
+ def item_history(path: Path) -> list[dict]:
456
+ """Folder moves and step ticks of one item file, oldest first, from one `git log --follow` call.
457
+
458
+ Empty when the file is uncommitted, outside a git repository, or git is missing."""
459
+ try:
460
+ result = subprocess.run(
461
+ ["git", "-c", "core.quotepath=off", "log", "--follow", "-M", "--format=%x01%H %cI",
462
+ "--raw", "-p", "--unified=0", "--no-color", "--", path.name],
463
+ cwd=path.parent, capture_output=True, text=True, encoding="utf-8", errors="replace")
464
+ except OSError:
465
+ return []
466
+ if result.returncode != 0:
467
+ return []
468
+ history: list[dict] = []
469
+ folder = None
470
+ for chunk in reversed(result.stdout.split("\x01")[1:]): # --reverse breaks --follow
471
+ lines = chunk.split("\n")
472
+ commit, date = lines[0].split(" ", 1)
473
+ stamp = {"date": date, "commit": commit}
474
+ unticked, ticked = set(), []
475
+ for line in lines[1:]:
476
+ if line.startswith(":"):
477
+ found = LIFECYCLE.search(line.split("\t")[-1])
478
+ if found and folder is None:
479
+ history.append({"event": "created", "folder": found.group(1), **stamp})
480
+ elif found and found.group(1) != folder:
481
+ history.append({"event": "moved", "from": folder, "to": found.group(1), **stamp})
482
+ folder = found.group(1) if found else folder
483
+ elif line.startswith("-") and not line.startswith("---") and (key := step_key(line[1:])) is not None:
484
+ if STEP.match(line[1:]).group(1) == " ":
485
+ unticked.add(key)
486
+ elif line.startswith("+") and not line.startswith("+++") and (key := step_key(line[1:])) is not None:
487
+ if STEP.match(line[1:]).group(1) != " ":
488
+ ticked.append(key)
489
+ history += [{"event": "ticked", "step": key, **stamp} for key in ticked if key in unticked]
490
+ return history
491
+
492
+
493
+ def held_by_data(path: Path, text: str | None) -> dict | None:
494
+ """The parsed `Held by:` line plus its age: seconds since the last commit that added the line (None when uncommitted)."""
495
+ if text is None:
496
+ return None
497
+ match = HELD_BY.match(text)
498
+ committed = age = None
499
+ try:
500
+ result = subprocess.run(["git", "log", "-1", "--format=%cI", "-S", f"Held by: {text}", "--", path.name],
501
+ cwd=path.parent, capture_output=True, text=True, encoding="utf-8", errors="replace")
502
+ committed = result.stdout.strip() or None if result.returncode == 0 else None
503
+ except OSError:
504
+ pass
505
+ if committed:
506
+ age = int((datetime.now(timezone.utc) - datetime.fromisoformat(committed)).total_seconds())
507
+ tool, session, since = match.groups() if match else (None, None, None)
508
+ return {"tool": tool, "session": session, "since": since, "committed": committed, "age_seconds": age}
509
+
510
+
511
+ def spent_data(outcome: str | None) -> dict | None:
512
+ """The `Spent:` line in the Outcome, parsed; fields `None` when it is malformed."""
513
+ found = re.search(r"^Spent:[ \t]*(.*)$", outcome or "", re.M)
514
+ if not found:
515
+ return None
516
+ match = SPENT.match(found.group(1).strip())
517
+ fields = match.groups() if match else (None,) * 4
518
+ return {**dict(zip(("active", "tokens", "cost", "sources"), fields)), "text": found.group(1).strip()}
519
+
520
+
521
+ def spent_warnings(work: Path) -> list[str]:
522
+ """`--check` warnings: a malformed `Spent:` line in any item's Outcome."""
523
+ warnings = []
524
+ for folder in ["1-planned", "2-active"] + archive_folders(work, "3-done") + archive_folders(work, "4-dropped"):
525
+ for name in entries(work, folder):
526
+ rel = f"{folder}/{name}/plan.md" if (work / folder / name).is_dir() else f"{folder}/{name}"
527
+ if not (work / rel).is_file():
528
+ continue
529
+ data = spent_data(section(read_text(work / rel), "Outcome"))
530
+ if data and data["active"] is None and not data["text"].startswith("not measured"):
531
+ warnings.append(f"{rel} has a malformed Spent: line; write `{SPENT_FORM}` "
532
+ f"(python3 .bc-agent/scripts/work_spent.py <item> prints it)")
533
+ return warnings
534
+
535
+
536
+ def held_by_warnings(work: Path) -> list[str]:
537
+ """`--check` warnings: a malformed `Held by:` line, or one left in a done or dropped item."""
538
+ warnings = []
539
+ for folder in ["1-planned", "2-active"] + archive_folders(work, "3-done") + archive_folders(work, "4-dropped"):
540
+ for name in entries(work, folder):
541
+ rel = f"{folder}/{name}/plan.md" if (work / folder / name).is_dir() else f"{folder}/{name}"
542
+ if not (work / rel).is_file():
543
+ continue
544
+ match = re.search(r"^Held by:[ \t]*(.*)$", read_text(work / rel), re.M)
545
+ if not match:
546
+ continue
547
+ if folder[0] in "34":
548
+ warnings.append(f"{rel} has a Held by: line but is closed; remove it")
549
+ elif not HELD_BY.match(match.group(1).strip()):
550
+ warnings.append(f"{rel} has a malformed Held by: line; write `Held by: <tool> <session> since <YYYY-MM-DD HH:MM> <UTC or +HH:MM>`")
551
+ return warnings
552
+
553
+
554
+ def item_data(work: Path, folder: str, name: str) -> dict:
555
+ rel = f"{folder}/{name}/plan.md" if (work / folder / name).is_dir() else f"{folder}/{name}"
556
+ if not (work / rel).is_file():
557
+ raise WorkIndexError(f"{rel}: missing")
558
+ text = read_text(work / rel)
559
+ title = re.search(r"^# (.+)$", text, re.M)
560
+ header = {}
561
+ for key, label in HEADER_LINES.items():
562
+ match = re.search(rf"^{label}:[ \t]*(.*)$", text, re.M)
563
+ header[key] = match.group(1).strip() if match and match.group(1).strip() else None
564
+ outcome = section(text, "Outcome")
565
+ item = name.removesuffix(".md")
566
+ return {
567
+ "number": item[:3], "slug": item[4:], "name": item, "folder": folder.split("/")[0][2:], "path": rel,
568
+ "title": title.group(1).strip() if title else None, "header": header, "steps": parse_steps(text),
569
+ "outcome": outcome.strip() or None if outcome is not None else None,
570
+ "history": item_history(work / rel), "held_by": held_by_data(work / rel, header["held_by"]),
571
+ "spent": spent_data(outcome),
572
+ }
573
+
574
+
575
+ def work_data(work: Path, stages: tuple[str, ...]) -> dict:
576
+ folders = ["1-planned", "2-active"] + archive_folders(work, "3-done") + archive_folders(work, "4-dropped")
577
+ items = [item_data(work, f, n) for f in sorted(folders, key=lambda f: (f.split("/")[0], f)) for n in entries(work, f)]
578
+ return {"format_version": JSON_FORMAT_VERSION, "stages": list(stages), "items": items}
579
+
580
+
581
+ def unplanned_items(work: Path) -> list[str]:
582
+ """Items in 1-planned/ without a `Planned:` line (bc-plan-to-pipeline writes it)."""
583
+ missing = []
584
+ for name in entries(work, "1-planned"):
585
+ rel = f"1-planned/{name}/plan.md" if (work / "1-planned" / name).is_dir() else f"1-planned/{name}"
586
+ if (work / rel).is_file() and not re.search(r"^Planned:", read_text(work / rel), re.M):
587
+ missing.append(rel)
588
+ return missing
589
+
590
+
591
+ def main(argv: list[str]) -> int:
592
+ check = "--check" in argv
593
+ paths = [arg for arg in argv if arg not in ("--check", "--json")]
594
+ work = Path(paths[0]) if paths else Path(__file__).resolve().parents[2] / "work"
595
+ try:
596
+ if "--json" in argv:
597
+ print(json.dumps(work_data(work, read_stages(work.resolve().parent)), ensure_ascii=False, indent=2))
598
+ return 0
599
+ block = build_block(work, read_stages(work.resolve().parent))
600
+ readme_path = work / "README.md"
601
+ readme = read_text(readme_path)
602
+ start, end = readme.find(START), readme.find(END)
603
+ if start < 0 or end < start:
604
+ raise WorkIndexError(f"{readme_path}: missing {START} … {END} markers")
605
+ updated = readme[:start] + block + readme[end + len(END):]
606
+ if check:
607
+ project = work.resolve().parent
608
+ for rel in unplanned_items(work):
609
+ print(f"work-index: warning: {rel} has no Planned: line; run bc-plan-to-pipeline on it before it moves to 2-active/", file=sys.stderr)
610
+ for warning in held_by_warnings(work) + step_record_warnings(work) + spent_warnings(work):
611
+ print(f"work-index: warning: {warning}", file=sys.stderr)
612
+ errors = owner_order_errors(work, read_stages(project), read_top_kinds(project))
613
+ if updated != readme:
614
+ errors.insert(0, f"work/README.md is out of date; run {COMMAND}")
615
+ if errors:
616
+ raise WorkIndexError("\n".join(errors))
617
+ elif updated != readme:
618
+ readme_path.write_bytes(updated.encode("utf-8"))
619
+ except (WorkIndexError, OSError, UnicodeDecodeError) as error:
620
+ print(f"work-index: {error}", file=sys.stderr)
621
+ return 1
622
+ return 0
623
+
624
+
625
+ if __name__ == "__main__":
626
+ raise SystemExit(main(sys.argv[1:]))