@caddis/cli 0.4.113 → 0.4.115

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 (33) hide show
  1. package/bundles/antigravity-plugin/plugin.json +1 -1
  2. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_exit.cpython-311.pyc +0 -0
  3. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_file_lock.cpython-311.pyc +0 -0
  4. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_frontmatter.cpython-311.pyc +0 -0
  5. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_redact.cpython-311.pyc +0 -0
  6. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_roadmap.cpython-311.pyc +0 -0
  7. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_rows.cpython-311.pyc +0 -0
  8. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_status.cpython-311.pyc +0 -0
  9. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_tidy.cpython-311.pyc +0 -0
  10. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_todo.cpython-311.pyc +0 -0
  11. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_workstreams.cpython-311.pyc +0 -0
  12. package/bundles/antigravity-plugin/scripts/__pycache__/caddis_worktree_safety.cpython-311.pyc +0 -0
  13. package/bundles/antigravity-plugin/scripts/caddis_coordinate.py +107 -1
  14. package/bundles/antigravity-plugin/scripts/caddis_guide.json +34 -7
  15. package/bundles/antigravity-plugin/scripts/caddis_stories.py +760 -0
  16. package/bundles/antigravity-plugin/skills/_registry.md +1 -0
  17. package/bundles/antigravity-plugin/skills/coordinate/SKILL.md +6 -2
  18. package/bundles/antigravity-plugin/skills/feature-plan/SKILL.md +15 -0
  19. package/bundles/antigravity-plugin/skills/implement/SKILL.md +5 -0
  20. package/bundles/antigravity-plugin/skills/stories/SKILL.md +50 -0
  21. package/bundles/manifest.json +2 -2
  22. package/dist/cli.js +207 -113
  23. package/dist/ui/assets/{Activity-B816JVqx.js → Activity-CITEjSUJ.js} +1 -1
  24. package/dist/ui/assets/Benchmarks-B2_1oerW.css +1 -0
  25. package/dist/ui/assets/Benchmarks-ChQoYa0P.js +1 -0
  26. package/dist/ui/assets/{Guide-CnL1DiTr.js → Guide-9Ob-m7gx.js} +1 -1
  27. package/dist/ui/assets/{Palette-BKM_A64G.js → Palette-CinCoveU.js} +1 -1
  28. package/dist/ui/assets/{RoadmapTab-DhC4-kqv.js → RoadmapTab-BeD4-8IU.js} +2 -2
  29. package/dist/ui/assets/{external-link-DagTFCsV.js → external-link-D_rks7KV.js} +1 -1
  30. package/dist/ui/assets/index-CFKn_GzG.js +231 -0
  31. package/dist/ui/index.html +1 -1
  32. package/package.json +1 -1
  33. package/dist/ui/assets/index-Bj5qA-fq.js +0 -226
@@ -0,0 +1,760 @@
1
+ """Plan phases as development stories: one plan phase is one sprint-sized story.
2
+
3
+ `render --plan <path> [--format md|storage]` prints the stories table of a plan, with no network.
4
+ `check [--plan <path>]` proves the Confluence login and that the plan's parent page can be read (GET only).
5
+ `sync --plan <path> [--dry-run]` writes the plan's section to the Epic page: the sub-page of `confluence_parent` whose
6
+ title is `jira_epic`. It creates the page when it is missing and replaces only the plan's marked section (anchor macros
7
+ `caddis-stories-<slug>-start-<hash8>` and `caddis-stories-<slug>-end`). Broken markers stop the sync with no write.
8
+
9
+ Keys: `CONFLUENCE_URL` (https only) and `CONFLUENCE_TOKEN` (a personal access token, sent as a Bearer header), from the
10
+ environment first, then `CADDIS_KEYS_FILE` or `~/.caddis/keys.env`. The token goes only to the `CONFLUENCE_URL` host
11
+ and never into output: every text from Confluence goes through `caddis_redact`.
12
+
13
+ Story rules (plan `confluence-stories.md`, Constraints): the summary is the phase name, the description is the first
14
+ sentence of its Goal, the acceptance criteria come from its Exit gate, the dependency from its Depends on line (else the
15
+ previous phase), the target sprint is its Milestone, the status comes from the plan Tracker, and the estimate is 2, 3
16
+ or 5 story points.
17
+ Exit codes: 0 clean, 1 Confluence refused or broken markers, 3 not configured or network failure, 4 bad input.
18
+ """
19
+
20
+ from __future__ import annotations
21
+
22
+ import argparse
23
+ from collections.abc import Callable, Mapping
24
+ from dataclasses import dataclass
25
+ import hashlib
26
+ import html
27
+ import http.client
28
+ import json
29
+ import os
30
+ from pathlib import Path
31
+ import re
32
+ import sys
33
+ import urllib.error
34
+ from urllib.parse import parse_qs, quote, unquote_plus, urlencode, urlsplit
35
+ import urllib.request
36
+
37
+ try:
38
+ import caddis_exit
39
+ except ModuleNotFoundError as exc:
40
+ if exc.name != "caddis_exit":
41
+ raise
42
+ sys.path.insert(0, str(Path(__file__).resolve().parent))
43
+ sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "claude-harness" / "scripts"))
44
+ import caddis_exit
45
+
46
+ import caddis_redact
47
+ from caddis_frontmatter import split_document
48
+ from caddis_review import phase_risk, phase_section
49
+ from caddis_rows import split_cells
50
+ from caddis_status import status_state
51
+ from caddis_todo import tracker_table
52
+ from oss_model import _parse_keys_file
53
+
54
+ _FENCE_OPEN = re.compile(r"^\s*(`{3,}|~{3,})")
55
+ _FENCE_CLOSE = re.compile(r"^\s*(`{3,}|~{3,})\s*$")
56
+ _PHASE_HEADING = re.compile(r"^### Phase (\d+[a-z]?)\s*[-—–:]\s*(.+?)\s*$")
57
+ _MILESTONE_HEADING = re.compile(r"^### Milestone\s+(\S+)")
58
+ _ANY_HEADING = re.compile(r"^#{1,3} ")
59
+ _STATUS_MARKS = "✅⏳🔲❌⚠️🚧 \t"
60
+ _GOAL = re.compile(r"^\*\*Goal:\*\*\s*(.+)$", re.M)
61
+ _EXIT_GATE = re.compile(r"^\*\*Exit gate:\*\*\s*(.+)$", re.M)
62
+ _MILESTONE_LINE = re.compile(r"^\*\*Milestone:\*\*\s*(\S+)", re.M)
63
+ _DEPENDS = re.compile(r"^\*\*Depends on:\*\*(.*)$", re.M)
64
+ _FILES_LINE = re.compile(r"^\*\*(?:Touches|Files):\*\*(.*)$", re.M)
65
+ _CROSS_REVIEW = re.compile(r"^\*\*Cross-review:\*\*(.*)$", re.M)
66
+ _SMALL_TIER = re.compile(r"(?i)\btier\s*(0|1-small)\b")
67
+ _TITLE_SUFFIX = re.compile(r"\s+[-—]\s+Implementation Plan\s*$")
68
+ MAX_WORDS = 25
69
+ MAX_CRITERIA = 5
70
+ STATUS_WORDS = {"todo": "To do", "in-progress": "In progress", "blocked": "Blocked", "done": "Done", "moved": "Moved"}
71
+ COLUMNS = ("Story ID", "User Story / Deliverable", "Acceptance Criteria", "Estimate", "Dependency", "Target Sprint",
72
+ "Status")
73
+
74
+
75
+ @dataclass
76
+ class Story:
77
+ story_id: str
78
+ phase: str
79
+ summary: str
80
+ description: str
81
+ criteria: list[str]
82
+ points: int
83
+ dependency: str
84
+ sprint: str
85
+ status: str
86
+
87
+
88
+ @dataclass
89
+ class PlanInfo:
90
+ path: Path
91
+ slug: str
92
+ title: str
93
+ epic: str | None
94
+ parent: str | None
95
+ stories: list[Story]
96
+
97
+
98
+ # ---------------------------------------------------------------- plan reading
99
+
100
+ def strip_fences(text: str) -> str:
101
+ """`text` with every line inside a code fence (and the fence lines) blanked. Line numbers stay the same."""
102
+ out: list[str] = []
103
+ fence = ""
104
+ for line in text.split("\n"):
105
+ if not fence:
106
+ m = _FENCE_OPEN.match(line)
107
+ if m:
108
+ fence = m.group(1)
109
+ out.append("")
110
+ continue
111
+ out.append(line)
112
+ else:
113
+ m = _FENCE_CLOSE.match(line)
114
+ if m and m.group(1)[0] == fence[0] and len(m.group(1)) >= len(fence):
115
+ fence = ""
116
+ out.append("")
117
+ return "\n".join(out)
118
+
119
+
120
+ def _headings(text: str) -> list[tuple[int, str, str, str | None]]:
121
+ """(line index, phase id, name, enclosing milestone id) for each phase heading outside a code fence."""
122
+ found = []
123
+ milestone = None
124
+ for index, line in enumerate(strip_fences(text).split("\n")):
125
+ m = _MILESTONE_HEADING.match(line)
126
+ if m:
127
+ milestone = m.group(1).rstrip(":.,")
128
+ continue
129
+ m = _PHASE_HEADING.match(line)
130
+ if m:
131
+ found.append((index, m.group(1), m.group(2).rstrip(_STATUS_MARKS), milestone))
132
+ return found
133
+
134
+
135
+ def phase_headings(text: str) -> list[tuple[str, str, str | None]]:
136
+ """(phase id, name, enclosing milestone id or None) for each `### Phase <id> - <name>` heading, in file order."""
137
+ return [(pid, name, milestone) for _, pid, name, milestone in _headings(text)]
138
+
139
+
140
+ def plain(text: str) -> str:
141
+ """Short plain text: no links, bold or backticks, no `(...)` group, no dash with spaces, one space between words."""
142
+ text = re.sub(r"\[([^\]]*)\]\([^)]*\)", r"\1", text)
143
+ text = text.replace("**", "").replace("`", "")
144
+ text = re.sub(r"\([^()]*\)", "", text)
145
+ text = re.sub(r"\s*[—–]\s*", " ", text)
146
+ text = re.sub(r"\s+([,;:])(?=\s|$)", r"\1", text)
147
+ return re.sub(r"\s+", " ", text).strip()
148
+
149
+
150
+ def _cut(text: str, max_words: int) -> tuple[str, bool]:
151
+ words = text.split()
152
+ if len(words) > max_words:
153
+ return " ".join(words[:max_words]) + " ...", True
154
+ return text, False
155
+
156
+
157
+ def first_sentence(text: str, max_words: int = MAX_WORDS) -> str:
158
+ """The first sentence of `text`, at most `max_words` words (a longer one is cut and ends with ` ...`)."""
159
+ sentence = re.split(r"(?<=[.!?])\s+", text.strip(), maxsplit=1)[0]
160
+ return _cut(sentence, max_words)[0]
161
+
162
+
163
+ def criteria(exit_gate: str | None) -> list[str]:
164
+ """The acceptance criteria: one short clause per sentence or `;` part of the Exit gate, at most 5 lines."""
165
+ if not exit_gate or not exit_gate.strip():
166
+ return ["See the plan."]
167
+ clauses = []
168
+ for clause in re.split(r";\s+|(?<=[.!?])\s+", plain(exit_gate)):
169
+ clause = clause.rstrip(" .;")
170
+ if not clause:
171
+ continue
172
+ text, was_cut = _cut(clause, MAX_WORDS)
173
+ clauses.append(text if was_cut else text + ".")
174
+ if not clauses:
175
+ return ["See the plan."]
176
+ if len(clauses) > MAX_CRITERIA:
177
+ return clauses[:MAX_CRITERIA - 1] + [f"and {len(clauses) - (MAX_CRITERIA - 1)} more in the plan."]
178
+ return clauses
179
+
180
+
181
+ def _risk(plan: Path, phase_id: str) -> str:
182
+ try:
183
+ return phase_risk(plan, phase_id)
184
+ except (OSError, ValueError):
185
+ return "normal"
186
+
187
+
188
+ def story_points(plan: Path, phase_id: str, section: str) -> int:
189
+ """5 for a programme phase, a high risk or more than 8 files; 2 for 1-3 files or a tier 0 / 1-small review; else 3."""
190
+ files = set()
191
+ for line in _FILES_LINE.findall(section):
192
+ files |= {span for span in re.findall(r"`([^`]+)`", line)
193
+ if ("/" in span or "." in span) and " " not in span}
194
+ programme = any(line.startswith("**Programme phase:**") for line in section.splitlines())
195
+ if programme or len(files) > 8 or _risk(plan, phase_id) == "high":
196
+ return 5
197
+ review = _CROSS_REVIEW.search(section)
198
+ if 1 <= len(files) <= 3 or (review and _SMALL_TIER.search(review.group(1))):
199
+ return 2
200
+ return 3
201
+
202
+
203
+ def dependency(section: str, previous: str | None) -> str:
204
+ """Every `Phase <id>` on the Depends on line as `P<id>`; `None` when the line names no phase; else the previous phase."""
205
+ m = _DEPENDS.search(section)
206
+ if m is None:
207
+ return f"P{previous}" if previous else "None"
208
+ ids = list(dict.fromkeys(re.findall(r"Phase\s+(\d+[a-z]?)", m.group(1))))
209
+ return ", ".join(f"P{i}" for i in ids) if ids else "None"
210
+
211
+
212
+ def _tracker_rows(stripped: str) -> dict[str, dict[str, str]]:
213
+ """Tracker cells by phase id (lower case): {"status": ..., "milestone": ...}."""
214
+ table = tracker_table(stripped)
215
+ if table is None:
216
+ return {}
217
+ columns, lines = table
218
+ rows: dict[str, dict[str, str]] = {}
219
+ for line in lines:
220
+ if not line.strip().startswith("|"):
221
+ continue
222
+ cells = split_cells(line)
223
+ if not cells or all(re.fullmatch(r":?-+:?", c) for c in cells):
224
+ continue
225
+ cell = dict(zip(columns, cells))
226
+ key = re.sub(r"^(phase\s*|p)", "", cell.get("phase", "").strip("*` "), flags=re.I).strip().lower()
227
+ if key and key not in rows:
228
+ rows[key] = cell
229
+ return rows
230
+
231
+
232
+ def _section(path: Path, stripped_lines: list[str], index: int, phase_id: str) -> str:
233
+ try:
234
+ return phase_section(path, phase_id)
235
+ except ValueError:
236
+ end = next((i for i in range(index + 1, len(stripped_lines)) if _ANY_HEADING.match(stripped_lines[i])),
237
+ len(stripped_lines))
238
+ return "\n".join(stripped_lines[index:end]).rstrip() + "\n"
239
+
240
+
241
+ def _slug(meta: dict, path: Path) -> str:
242
+ raw = meta.get("feature") if isinstance(meta.get("feature"), str) and meta.get("feature") else path.stem
243
+ return re.sub(r"[^a-z0-9-]+", "-", raw.lower()).strip("-") or "plan"
244
+
245
+
246
+ def _meta_text(meta: dict, name: str) -> str | None:
247
+ value = meta.get(name)
248
+ return value.strip() if isinstance(value, str) and value.strip() else None
249
+
250
+
251
+ def read_plan(path: Path) -> PlanInfo:
252
+ """The plan's slug, title, Epic, parent page and one story per phase. Raises ValueError when no phase heading."""
253
+ path = Path(path)
254
+ text = path.read_text(encoding="utf-8")
255
+ meta, _ = split_document(text)
256
+ stripped = strip_fences(text)
257
+ stripped_lines = stripped.split("\n")
258
+ headings = _headings(text)
259
+ if not headings:
260
+ raise ValueError(f"no '### Phase <n> - <name>' heading in {path.name}")
261
+ slug = _slug(meta, path)
262
+ title_match = re.search(r"^# (.+)$", stripped, re.M)
263
+ title = _TITLE_SUFFIX.sub("", title_match.group(1)).strip() if title_match else slug
264
+ tracker = _tracker_rows(stripped)
265
+ out: list[Story] = []
266
+ previous = None
267
+ for index, pid, name, heading_milestone in headings:
268
+ section = _section(path, stripped_lines, index, pid)
269
+ row = tracker.get(pid.lower(), {})
270
+ goal = _GOAL.search(section)
271
+ gate = _EXIT_GATE.search(section)
272
+ line_milestone = _MILESTONE_LINE.search(section)
273
+ sprint = (line_milestone.group(1) if line_milestone else None) or heading_milestone \
274
+ or plain(row.get("milestone", "")) or "-"
275
+ out.append(Story(
276
+ story_id=f"{slug}-P{pid}",
277
+ phase=pid,
278
+ summary=plain(name),
279
+ description=first_sentence(plain(goal.group(1))) if goal else "-",
280
+ criteria=criteria(gate.group(1) if gate else None),
281
+ points=story_points(path, pid, section),
282
+ dependency=dependency(section, previous),
283
+ sprint=sprint,
284
+ status=STATUS_WORDS[status_state(row.get("status", ""))],
285
+ ))
286
+ previous = pid
287
+ return PlanInfo(path=path, slug=slug, title=title, epic=_meta_text(meta, "jira_epic"),
288
+ parent=_meta_text(meta, "confluence_parent"), stories=out)
289
+
290
+
291
+ # ---------------------------------------------------------------- rendering
292
+
293
+ def _md_cell(text: str) -> str:
294
+ return text.replace("|", "\\|")
295
+
296
+
297
+ def render_markdown(info: PlanInfo) -> str:
298
+ """The stories as a markdown table: header, rule, one row per story."""
299
+ lines = ["| " + " | ".join(COLUMNS) + " |", "|" + "---|" * len(COLUMNS)]
300
+ for s in info.stories:
301
+ cells = (s.story_id, f"{s.summary}: {s.description}", " ".join(s.criteria), str(s.points), s.dependency,
302
+ s.sprint, s.status)
303
+ lines.append("| " + " | ".join(_md_cell(c) for c in cells) + " |")
304
+ return "\n".join(lines) + "\n"
305
+
306
+
307
+ def _anchor(name: str) -> str:
308
+ return (f'<p><ac:structured-macro ac:name="anchor"><ac:parameter ac:name="">{name}</ac:parameter>'
309
+ f'</ac:structured-macro></p>')
310
+
311
+
312
+ def section_hash(inner: str) -> str:
313
+ """The first 8 hex characters of the sha256 of the section text between the two markers."""
314
+ return hashlib.sha256(inner.encode("utf-8")).hexdigest()[:8]
315
+
316
+
317
+ def _esc(text: str) -> str:
318
+ return html.escape(text, quote=True)
319
+
320
+
321
+ def storage_section(info: PlanInfo) -> str:
322
+ """The plan's section in Confluence storage format: start marker (with the hash), heading, intro, table, end marker."""
323
+ parts = [f"<h2>Development stories: {_esc(info.title)}</h2>",
324
+ f"<p>caddis writes this section from the plan file {_esc(info.path.name)}. Do not edit it. "
325
+ f"The next sync replaces it.</p>",
326
+ "<table><tbody><tr>" + "".join(f"<th>{_esc(c)}</th>" for c in COLUMNS) + "</tr>"]
327
+ for s in info.stories:
328
+ items = "".join(f"<li>{_esc(c)}</li>" for c in s.criteria)
329
+ parts.append(f"<tr><td>{_esc(s.story_id)}</td><td><strong>{_esc(s.summary)}</strong><br/>"
330
+ f"{_esc(s.description)}</td><td><ul>{items}</ul></td><td>{s.points}</td>"
331
+ f"<td>{_esc(s.dependency)}</td><td>{_esc(s.sprint)}</td><td>{_esc(s.status)}</td></tr>")
332
+ parts.append("</tbody></table>")
333
+ inner = "".join(parts)
334
+ return (_anchor(f"caddis-stories-{info.slug}-start-{section_hash(inner)}") + inner
335
+ + _anchor(f"caddis-stories-{info.slug}-end"))
336
+
337
+
338
+ # ---------------------------------------------------------------- the marked section on a page
339
+
340
+ class MarkerError(ValueError):
341
+ """The plan's markers on the page are broken (a start with no end, an end before the start, two starts)."""
342
+
343
+
344
+ def _marker_re(slug: str, kind: str) -> re.Pattern:
345
+ """A start or end anchor macro of `slug`, with or without its `<p>` wrapper and with any added attributes."""
346
+ name = f"caddis-stories-{re.escape(slug)}-{kind}" + (r"(?:-([0-9a-f]{8}))?" if kind == "start" else "")
347
+ macro = (r'<ac:structured-macro\b[^>]*\sac:name="anchor"[^>]*>\s*'
348
+ r'<ac:parameter\b[^>]*\sac:name=""[^>]*>\s*' + name + r'\s*</ac:parameter>\s*</ac:structured-macro>')
349
+ return re.compile(r"<p(?:\s[^>]*)?>\s*" + macro + r"\s*</p>|" + macro)
350
+
351
+
352
+ def find_section(body: str, slug: str) -> tuple[int, int, str | None] | None:
353
+ """(start offset, end offset, stored hash) of the plan's section, or None when the page has none of its markers.
354
+
355
+ Raises MarkerError when the markers are broken, so a sync never guesses where the section ends."""
356
+ starts = list(_marker_re(slug, "start").finditer(body))
357
+ ends = list(_marker_re(slug, "end").finditer(body))
358
+ if not starts and not ends:
359
+ return None
360
+ if len(starts) != 1 or len(ends) != 1:
361
+ raise MarkerError(f"{len(starts)} start and {len(ends)} end markers for {slug}")
362
+ start, end = starts[0], ends[0]
363
+ if end.start() < start.end():
364
+ raise MarkerError(f"the end marker of {slug} is before its start marker")
365
+ return start.start(), end.end(), start.group(1) or start.group(2)
366
+
367
+
368
+ def replace_section(body: str, slug: str, section: str) -> tuple[str, str]:
369
+ """(new body, action): `add` appends the section, `update` replaces the old one in place, `unchanged` keeps the
370
+ body when the stored hash equals the new one. Every byte outside the plan's markers stays the same."""
371
+ found = find_section(body, slug)
372
+ if found is None:
373
+ return body + section, "add"
374
+ start, end, stored = found
375
+ own = find_section(section, slug)
376
+ if own is not None and stored is not None and stored == own[2]:
377
+ return body, "unchanged"
378
+ return body[:start] + section + body[end:], "update"
379
+
380
+
381
+ # ---------------------------------------------------------------- Confluence keys and parent page
382
+
383
+ DEFAULT_KEYS_FILE = "~/.caddis/keys.env"
384
+
385
+
386
+ class ConfigError(Exception):
387
+ """CONFLUENCE_URL or CONFLUENCE_TOKEN is missing or not usable. The text names the variable, never its value."""
388
+
389
+
390
+ @dataclass
391
+ class Config:
392
+ base_url: str
393
+ token: str
394
+
395
+ def __repr__(self) -> str: # never show the token in a traceback or a log
396
+ return f"Config(base_url={self.base_url!r}, token='***')"
397
+
398
+
399
+ def load_config(env: Mapping[str, str]) -> Config:
400
+ """CONFLUENCE_URL and CONFLUENCE_TOKEN: the environment first, then the keys file."""
401
+ keys_path = env.get("CADDIS_KEYS_FILE") or DEFAULT_KEYS_FILE
402
+ try:
403
+ file_keys = _parse_keys_file(keys_path)
404
+ except (OSError, UnicodeDecodeError) as exc:
405
+ raise ConfigError(f"cannot read the keys file {keys_path}: {type(exc).__name__}") from None
406
+ values = {}
407
+ for name in ("CONFLUENCE_URL", "CONFLUENCE_TOKEN"):
408
+ value = (env.get(name) or "").strip() or (file_keys.get(name) or "").strip()
409
+ if not value:
410
+ raise ConfigError(f"{name} is not set (environment or {keys_path})")
411
+ values[name] = value
412
+ base_url = values["CONFLUENCE_URL"].rstrip("/")
413
+ parts = urlsplit(base_url)
414
+ if parts.scheme != "https" or not parts.hostname:
415
+ raise ConfigError("CONFLUENCE_URL must use the https scheme and name a host")
416
+ return Config(base_url=base_url, token=values["CONFLUENCE_TOKEN"])
417
+
418
+
419
+ @dataclass
420
+ class ParentRef:
421
+ page_id: str | None
422
+ space: str | None
423
+ title: str | None
424
+
425
+
426
+ def _host(url: str) -> tuple[str, int | None]:
427
+ parts = urlsplit(url)
428
+ return (parts.hostname or "").lower(), parts.port
429
+
430
+
431
+ def parse_parent(url: str, base_url: str) -> ParentRef:
432
+ """The parent page from its URL: `?pageId=<n>`, `/spaces/<KEY>/pages/<n>/...` or `/display/<KEY>/<Title+Words>`.
433
+
434
+ Raises ValueError when the URL is not https on the `base_url` host, or no form matches."""
435
+ url = url.strip()
436
+ parts = urlsplit(url)
437
+ if parts.scheme != "https" or not parts.hostname or _host(url) != _host(base_url):
438
+ raise ValueError("confluence_parent is not an https URL on the CONFLUENCE_URL host")
439
+ page_id = parse_qs(parts.query).get("pageId", [None])[0]
440
+ if page_id and page_id.isdigit():
441
+ return ParentRef(page_id, None, None)
442
+ m = re.search(r"/spaces/([^/]+)/pages/(\d+)(?:/|$)", parts.path)
443
+ if m:
444
+ return ParentRef(m.group(2), unquote_plus(m.group(1)), None)
445
+ m = re.search(r"/display/([^/]+)/([^/]+)/?$", parts.path)
446
+ if m:
447
+ return ParentRef(None, unquote_plus(m.group(1)), unquote_plus(m.group(2)))
448
+ raise ValueError("confluence_parent has no page id and no /display/<space>/<title> form")
449
+
450
+
451
+ # ---------------------------------------------------------------- Confluence REST client
452
+
453
+ _PAGE_EXPAND = "body.storage,version,space,ancestors"
454
+ MAX_ERROR_TEXT = 300
455
+
456
+
457
+ class ConfluenceError(Exception):
458
+ """A Confluence call failed. `status` is the HTTP status, or None for a network failure or a timeout.
459
+ `message` is already redacted and cut: it never holds the token."""
460
+
461
+ def __init__(self, status: int | None, message: str):
462
+ super().__init__(message)
463
+ self.status = status
464
+ self.message = message
465
+
466
+ def __str__(self) -> str:
467
+ return self.message
468
+
469
+
470
+ class _NoRedirect(urllib.request.HTTPRedirectHandler):
471
+ """A redirect is an error: the Authorization header must never follow it to another URL."""
472
+
473
+ def redirect_request(self, req, fp, code, msg, headers, newurl):
474
+ return None
475
+
476
+
477
+ _OPENER = urllib.request.build_opener(_NoRedirect)
478
+
479
+
480
+ def _default_send(req: urllib.request.Request, timeout: float) -> tuple[int, bytes]:
481
+ """urllib transport: (status, body). An HTTP error status is returned, not raised. Network errors raise."""
482
+ try:
483
+ with _OPENER.open(req, timeout=timeout) as resp:
484
+ return resp.status, resp.read()
485
+ except urllib.error.HTTPError as exc:
486
+ try:
487
+ body = exc.read()
488
+ except (OSError, http.client.HTTPException):
489
+ body = b""
490
+ return exc.code, body
491
+
492
+
493
+ class Confluence:
494
+ """Confluence Server REST calls with a Bearer personal access token. The token is sent only in the header."""
495
+
496
+ def __init__(self, base_url: str, token: str, timeout: float = 20.0, send: Callable | None = None):
497
+ self.base_url = base_url.rstrip("/")
498
+ self._token = token
499
+ self.timeout = timeout
500
+ self._send = send or _default_send
501
+ secrets = caddis_redact.load_secrets(Path.home())
502
+ if token:
503
+ secrets = secrets + [token]
504
+ self._secrets = sorted(set(secrets), key=len, reverse=True)
505
+
506
+ def __repr__(self) -> str:
507
+ return f"Confluence(base_url={self.base_url!r})"
508
+
509
+ def _clean(self, text: str) -> str:
510
+ return caddis_redact.redact(text, self._secrets)[:MAX_ERROR_TEXT]
511
+
512
+ def request(self, method: str, path: str, query: dict | None = None, body: dict | None = None) -> dict:
513
+ url = self.base_url + path + ("?" + urlencode(query) if query else "")
514
+ data = json.dumps(body).encode("utf-8") if body is not None else None
515
+ req = urllib.request.Request(url, data=data, method=method)
516
+ req.add_header("Authorization", f"Bearer {self._token}")
517
+ req.add_header("Accept", "application/json")
518
+ req.add_header("X-Atlassian-Token", "no-check")
519
+ if data is not None:
520
+ req.add_header("Content-Type", "application/json")
521
+ try:
522
+ status, raw = self._send(req, self.timeout)
523
+ except ConfluenceError:
524
+ raise
525
+ except (OSError, http.client.HTTPException) as exc:
526
+ reason = self._clean(f"{type(exc).__name__}: {exc}")
527
+ raise ConfluenceError(None, f"network error {method} {path}: {reason}") from None
528
+ text = (raw or b"").decode("utf-8", errors="replace")
529
+ if not 200 <= status < 300:
530
+ raise ConfluenceError(status, f"HTTP {status} {method} {path}: {self._clean(text)}")
531
+ if not text.strip():
532
+ return {}
533
+ try:
534
+ return json.loads(text)
535
+ except ValueError:
536
+ raise ConfluenceError(status, f"HTTP {status} {method} {path}: the answer is not JSON") from None
537
+
538
+ def current_user(self) -> str:
539
+ data = self.request("GET", "/rest/api/user/current")
540
+ return str(data.get("username") or data.get("displayName") or "")
541
+
542
+ def get_page(self, page_id: str) -> dict:
543
+ return self.request("GET", f"/rest/api/content/{quote(str(page_id), safe='')}", {"expand": _PAGE_EXPAND})
544
+
545
+ def find_page(self, space: str, title: str) -> dict | None:
546
+ data = self.request("GET", "/rest/api/content", {"spaceKey": space, "title": title, "expand": _PAGE_EXPAND})
547
+ results = data.get("results") or []
548
+ return results[0] if results else None
549
+
550
+ def create_page(self, space: str, parent_id: str, title: str, storage: str) -> dict:
551
+ return self.request("POST", "/rest/api/content", body={
552
+ "type": "page", "title": title, "space": {"key": space}, "ancestors": [{"id": parent_id}],
553
+ "body": {"storage": {"value": storage, "representation": "storage"}}})
554
+
555
+ def update_page(self, page: dict, storage: str) -> dict:
556
+ """PUT the new body with version + 1. Confluence answers 409 when someone saved the page in between."""
557
+ return self.request("PUT", f"/rest/api/content/{quote(str(page['id']), safe='')}", body={
558
+ "id": page["id"], "type": "page", "title": page["title"], "space": {"key": page["space"]["key"]},
559
+ "version": {"number": page["version"]["number"] + 1},
560
+ "body": {"storage": {"value": storage, "representation": "storage"}}})
561
+
562
+
563
+ # ---------------------------------------------------------------- sync
564
+
565
+ @dataclass
566
+ class SyncResult:
567
+ action: str # create-page | add | update | unchanged
568
+ page_id: str | None
569
+ version: int | None
570
+ warnings: list[str]
571
+
572
+
573
+ def _version(page: dict) -> int | None:
574
+ number = (page.get("version") or {}).get("number")
575
+ return number if isinstance(number, int) else None
576
+
577
+
578
+ def _body(page: dict) -> str:
579
+ return ((page.get("body") or {}).get("storage") or {}).get("value") or ""
580
+
581
+
582
+ def sync_plan(info: PlanInfo, client: Confluence, base_url: str, dry_run: bool) -> SyncResult:
583
+ """Write the plan's section to the Epic page under the parent page: create the page when it is missing, else
584
+ replace only the plan's marked section. A dry run reads only. On a 409 the page is read again and written once more.
585
+ """
586
+ warnings: list[str] = []
587
+ parent = resolve_parent(client, parse_parent(info.parent or "", base_url))
588
+ parent_id = str(parent["id"])
589
+ space = parent["space"]["key"]
590
+ section = storage_section(info)
591
+ page = client.find_page(space, info.epic)
592
+ if page is None:
593
+ if dry_run:
594
+ return SyncResult("create-page", None, None, warnings)
595
+ created = client.create_page(space, parent_id, info.epic, section)
596
+ return SyncResult("create-page", str(created.get("id")), _version(created), warnings)
597
+ if parent_id not in {str(a.get("id")) for a in page.get("ancestors") or []}:
598
+ warnings.append(f"page {info.epic} is not under the parent page")
599
+ new_body, action = replace_section(_body(page), info.slug, section)
600
+ if action == "unchanged" or dry_run:
601
+ return SyncResult(action, str(page["id"]), _version(page), warnings)
602
+ try:
603
+ updated = client.update_page(page, new_body)
604
+ except ConfluenceError as err:
605
+ if err.status != 409:
606
+ raise
607
+ page = client.get_page(str(page["id"]))
608
+ new_body, action = replace_section(_body(page), info.slug, section)
609
+ if action == "unchanged":
610
+ return SyncResult(action, str(page["id"]), _version(page), warnings)
611
+ updated = client.update_page(page, new_body)
612
+ return SyncResult(action, str(page["id"]), _version(updated), warnings)
613
+
614
+
615
+ # ---------------------------------------------------------------- command line
616
+
617
+ def _load(plan: str) -> PlanInfo | None:
618
+ try:
619
+ return read_plan(Path(plan))
620
+ except (OSError, ValueError) as exc:
621
+ print(f"cannot read plan: {exc}", file=sys.stderr)
622
+ return None
623
+
624
+
625
+ def cmd_render(args) -> int:
626
+ info = _load(args.plan)
627
+ if info is None:
628
+ return caddis_exit.ERROR
629
+ sys.stdout.write(storage_section(info) + "\n" if args.format == "storage" else render_markdown(info))
630
+ return caddis_exit.CLEAN
631
+
632
+
633
+ def resolve_parent(client: Confluence, ref: ParentRef) -> dict:
634
+ """The parent page: by id, else by space and title. ConfluenceError 404 when it is not found."""
635
+ if ref.page_id:
636
+ return client.get_page(ref.page_id)
637
+ page = client.find_page(ref.space or "", ref.title or "")
638
+ if page is None:
639
+ raise ConfluenceError(404, "parent page not found")
640
+ return page
641
+
642
+
643
+ def _confluence_failed(err: ConfluenceError) -> int:
644
+ if err.status is None:
645
+ print(f"Confluence not reached: {err}", file=sys.stderr)
646
+ return caddis_exit.NOT_RUN
647
+ print(f"Confluence refused: {err}", file=sys.stderr)
648
+ return caddis_exit.BLOCKED
649
+
650
+
651
+ def cmd_check(args, env: Mapping[str, str], client_factory=Confluence) -> int:
652
+ """Read-only: the login user and, with --plan, the plan's parent page. Every check of input runs before a request."""
653
+ try:
654
+ config = load_config(env)
655
+ except ConfigError as exc:
656
+ print(f"NOT CONFIGURED: {exc}")
657
+ return caddis_exit.NOT_RUN
658
+ ref = None
659
+ if getattr(args, "plan", None):
660
+ info = _load(args.plan)
661
+ if info is None:
662
+ return caddis_exit.ERROR
663
+ if not info.parent:
664
+ print(f"NOT CONFIGURED: {info.path.name} needs confluence_parent")
665
+ return caddis_exit.NOT_RUN
666
+ try:
667
+ ref = parse_parent(info.parent, config.base_url)
668
+ except ValueError as exc:
669
+ print(f"bad input: {exc}", file=sys.stderr)
670
+ return caddis_exit.ERROR
671
+ client = client_factory(config.base_url, config.token)
672
+ try:
673
+ print(f"USER: {client.current_user()}")
674
+ if ref is not None:
675
+ parent = resolve_parent(client, ref)
676
+ space = (parent.get("space") or {}).get("key", ref.space or "?")
677
+ print(f"PARENT: {parent.get('title', '?')} ({parent.get('id', '?')}) in space {space}")
678
+ except ConfluenceError as err:
679
+ return _confluence_failed(err)
680
+ return caddis_exit.CLEAN
681
+
682
+
683
+ _EPIC_KEY = re.compile(r"^[A-Z][A-Z0-9]+-\d+$")
684
+
685
+
686
+ def cmd_sync(args, env: Mapping[str, str], client_factory=Confluence) -> int:
687
+ """Write the plan's stories section to its Epic page. Every check of input runs before the first request."""
688
+ info = _load(args.plan)
689
+ if info is None:
690
+ return caddis_exit.ERROR
691
+ if not info.epic or not info.parent:
692
+ print(f"NOT CONFIGURED: {info.path.name} needs jira_epic and confluence_parent")
693
+ return caddis_exit.NOT_RUN
694
+ if not _EPIC_KEY.match(info.epic):
695
+ print(f"bad input: jira_epic '{info.epic}' is not a Jira key such as ABC-123", file=sys.stderr)
696
+ return caddis_exit.ERROR
697
+ try:
698
+ config = load_config(env)
699
+ except ConfigError as exc:
700
+ print(f"NOT CONFIGURED: {exc}")
701
+ return caddis_exit.NOT_RUN
702
+ try:
703
+ parse_parent(info.parent, config.base_url)
704
+ except ValueError as exc:
705
+ print(f"bad input: {exc}", file=sys.stderr)
706
+ return caddis_exit.ERROR
707
+ client = client_factory(config.base_url, config.token)
708
+ try:
709
+ result = sync_plan(info, client, config.base_url, dry_run=bool(getattr(args, "dry_run", False)))
710
+ except MarkerError:
711
+ print(f"markers broken on page {info.epic}; fix the page by hand", file=sys.stderr)
712
+ return caddis_exit.BLOCKED
713
+ except ConfluenceError as err:
714
+ return _confluence_failed(err)
715
+ for warning in result.warnings:
716
+ print(f"WARN: {warning}", file=sys.stderr)
717
+ print(f"ACTION: {result.action}")
718
+ if result.page_id is None:
719
+ print(f"PAGE: {info.epic} (new)")
720
+ else:
721
+ print(f"PAGE: {info.epic} ({result.page_id}) v{result.version if result.version is not None else '?'}")
722
+ if getattr(args, "dry_run", False):
723
+ print("DRY RUN: nothing written")
724
+ print(storage_section(info))
725
+ return caddis_exit.CLEAN
726
+
727
+
728
+ def _parser() -> argparse.ArgumentParser:
729
+ parser = argparse.ArgumentParser(prog="caddis_stories.py", description="Plan phases as development stories.")
730
+ sub = parser.add_subparsers(dest="command", required=True)
731
+ render = sub.add_parser("render", help="print the stories table of a plan (no network)")
732
+ render.add_argument("--plan", required=True)
733
+ render.add_argument("--format", choices=("md", "storage"), default="md")
734
+ check = sub.add_parser("check", help="read-only: the Confluence login and the plan's parent page")
735
+ check.add_argument("--plan")
736
+ sync = sub.add_parser("sync", help="write the plan's stories section to its Epic page")
737
+ sync.add_argument("--plan", required=True)
738
+ sync.add_argument("--dry-run", action="store_true", help="read only; print the action and the section")
739
+ return parser
740
+
741
+
742
+ def main(argv: list[str] | None = None) -> int:
743
+ for stream in (sys.stdout, sys.stderr):
744
+ if hasattr(stream, "reconfigure"):
745
+ try:
746
+ stream.reconfigure(encoding="utf-8", errors="replace")
747
+ except (OSError, ValueError):
748
+ pass
749
+ args = _parser().parse_args(argv)
750
+ if args.command == "render":
751
+ return cmd_render(args)
752
+ if args.command == "check":
753
+ return cmd_check(args, os.environ)
754
+ if args.command == "sync":
755
+ return cmd_sync(args, os.environ)
756
+ return caddis_exit.ERROR
757
+
758
+
759
+ if __name__ == "__main__":
760
+ raise SystemExit(main())