@caddis/cli 0.4.114 → 0.4.116

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 (20) 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_guide.json +36 -8
  14. package/bundles/antigravity-plugin/scripts/caddis_stories.py +775 -0
  15. package/bundles/antigravity-plugin/skills/_registry.md +1 -0
  16. package/bundles/antigravity-plugin/skills/feature-plan/SKILL.md +27 -0
  17. package/bundles/antigravity-plugin/skills/implement/SKILL.md +5 -0
  18. package/bundles/antigravity-plugin/skills/stories/SKILL.md +50 -0
  19. package/bundles/manifest.json +2 -2
  20. package/package.json +1 -1
@@ -1,5 +1,5 @@
1
1
  {
2
2
  "name": "caddis",
3
- "version": "1.3.198",
3
+ "version": "1.3.200",
4
4
  "description": "caddis — agent-agnostic dev harness as an Antigravity (agy) plugin: TDD skills + commands, single-sourced with the Claude Code plugin."
5
5
  }
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "schema": 1,
3
- "version": "1.3.197",
4
- "generated": "2026-11-13 19:04 UTC",
3
+ "version": "1.3.199",
4
+ "generated": "2026-11-14 05:01 UTC",
5
5
  "commands": [
6
6
  {
7
7
  "name": "add-rules",
@@ -308,6 +308,10 @@
308
308
  "1",
309
309
  "Scope check"
310
310
  ],
311
+ [
312
+ "1b",
313
+ "Jira Epic and Confluence page (interactive only)"
314
+ ],
311
315
  [
312
316
  "2",
313
317
  "Design phases"
@@ -331,17 +335,14 @@
331
335
  [
332
336
  "",
333
337
  "Global Constraints"
334
- ],
335
- [
336
- "",
337
- "Review Focus"
338
338
  ]
339
339
  ],
340
340
  "scripts": [
341
341
  "caddis_lanes.py",
342
342
  "caddis_routing.py",
343
343
  "caddis_spend.py",
344
- "caddis_status.py"
344
+ "caddis_status.py",
345
+ "caddis_stories.py"
345
346
  ],
346
347
  "noArgs": false,
347
348
  "stage": "plan",
@@ -633,6 +634,7 @@
633
634
  "caddis_silence_watch.py",
634
635
  "caddis_spend.py",
635
636
  "caddis_status.py",
637
+ "caddis_stories.py",
636
638
  "caddis_tidy.py",
637
639
  "caddis_todo.py"
638
640
  ],
@@ -1270,6 +1272,32 @@
1270
1272
  "stage": "continuity",
1271
1273
  "daily": false
1272
1274
  },
1275
+ {
1276
+ "name": "stories",
1277
+ "description": "Publish a plan's phases as development stories to the Jira Epic's Confluence page — one marked section per plan",
1278
+ "hint": "<plan path>",
1279
+ "steps": [
1280
+ [
1281
+ "",
1282
+ "Input"
1283
+ ],
1284
+ [
1285
+ "",
1286
+ "Steps"
1287
+ ],
1288
+ [
1289
+ "",
1290
+ "Exit codes"
1291
+ ]
1292
+ ],
1293
+ "scripts": [
1294
+ "caddis_stories.py",
1295
+ "caddis_todo.py"
1296
+ ],
1297
+ "noArgs": false,
1298
+ "stage": "knowledge",
1299
+ "daily": false
1300
+ },
1273
1301
  {
1274
1302
  "name": "tdd",
1275
1303
  "description": "Run a strict red-green-refactor TDD cycle for a unit of behavior",
@@ -2464,7 +2492,7 @@
2464
2492
  ]
2465
2493
  },
2466
2494
  "counts": {
2467
- "commands": 41,
2495
+ "commands": 42,
2468
2496
  "agents": 12,
2469
2497
  "skills": 134,
2470
2498
  "core": 51,
@@ -0,0 +1,775 @@
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
+ status: str | None = None
97
+
98
+
99
+ # ---------------------------------------------------------------- plan reading
100
+
101
+ def strip_fences(text: str) -> str:
102
+ """`text` with every line inside a code fence (and the fence lines) blanked. Line numbers stay the same."""
103
+ out: list[str] = []
104
+ fence = ""
105
+ for line in text.split("\n"):
106
+ if not fence:
107
+ m = _FENCE_OPEN.match(line)
108
+ if m:
109
+ fence = m.group(1)
110
+ out.append("")
111
+ continue
112
+ out.append(line)
113
+ else:
114
+ m = _FENCE_CLOSE.match(line)
115
+ if m and m.group(1)[0] == fence[0] and len(m.group(1)) >= len(fence):
116
+ fence = ""
117
+ out.append("")
118
+ return "\n".join(out)
119
+
120
+
121
+ def _headings(text: str) -> list[tuple[int, str, str, str | None]]:
122
+ """(line index, phase id, name, enclosing milestone id) for each phase heading outside a code fence."""
123
+ found = []
124
+ milestone = None
125
+ for index, line in enumerate(strip_fences(text).split("\n")):
126
+ m = _MILESTONE_HEADING.match(line)
127
+ if m:
128
+ milestone = m.group(1).rstrip(":.,")
129
+ continue
130
+ m = _PHASE_HEADING.match(line)
131
+ if m:
132
+ found.append((index, m.group(1), m.group(2).rstrip(_STATUS_MARKS), milestone))
133
+ return found
134
+
135
+
136
+ def phase_headings(text: str) -> list[tuple[str, str, str | None]]:
137
+ """(phase id, name, enclosing milestone id or None) for each `### Phase <id> - <name>` heading, in file order."""
138
+ return [(pid, name, milestone) for _, pid, name, milestone in _headings(text)]
139
+
140
+
141
+ def plain(text: str) -> str:
142
+ """Short plain text: no links, bold or backticks, no `(...)` group, no dash with spaces, one space between words.
143
+ A code span keeps its brackets and dashes; only its backticks go. A `(...)` group that holds a code span still goes."""
144
+ code: list[str] = []
145
+
146
+ def hold(m: re.Match) -> str:
147
+ span = m.group(2)
148
+ if len(span) >= 2 and span[0] == span[-1] == " " and span.strip(" "):
149
+ span = span[1:-1] # CommonMark: one padding space each side
150
+ code.append(span)
151
+ return f"\x00{len(code) - 1}\x00"
152
+
153
+ text = text.replace("\x00", "")
154
+ text = re.sub(r"(?<!`)(`+)(?!`)(.*?)(?<!`)\1(?!`)", hold, text, flags=re.DOTALL)
155
+ text = re.sub(r"\[([^\]]*)\]\([^)]*\)", r"\1", text)
156
+ text = text.replace("**", "").replace("`", "")
157
+ text = re.sub(r"\([^()]*\)", "", text)
158
+ text = re.sub(r"\s*[—–]\s*", " ", text)
159
+ text = re.sub(r"\s+([,;:])(?=\s|$)", r"\1", text)
160
+ text = re.sub(r"\x00(\d+)\x00", lambda m: code[int(m.group(1))], text)
161
+ return re.sub(r"\s+", " ", text).strip()
162
+
163
+
164
+ def _cut(text: str, max_words: int) -> tuple[str, bool]:
165
+ words = text.split()
166
+ if len(words) > max_words:
167
+ return " ".join(words[:max_words]) + " ...", True
168
+ return text, False
169
+
170
+
171
+ def first_sentence(text: str, max_words: int = MAX_WORDS) -> str:
172
+ """The first sentence of `text`, at most `max_words` words (a longer one is cut and ends with ` ...`)."""
173
+ sentence = re.split(r"(?<=[.!?])\s+", text.strip(), maxsplit=1)[0]
174
+ return _cut(sentence, max_words)[0]
175
+
176
+
177
+ def criteria(exit_gate: str | None) -> list[str]:
178
+ """The acceptance criteria: one short clause per sentence or `;` part of the Exit gate, at most 5 lines."""
179
+ if not exit_gate or not exit_gate.strip():
180
+ return ["See the plan."]
181
+ clauses = []
182
+ for clause in re.split(r";\s+|(?<=[.!?])\s+", plain(exit_gate)):
183
+ clause = clause.rstrip(" .;")
184
+ if not clause:
185
+ continue
186
+ text, was_cut = _cut(clause, MAX_WORDS)
187
+ clauses.append(text if was_cut else text + ".")
188
+ if not clauses:
189
+ return ["See the plan."]
190
+ if len(clauses) > MAX_CRITERIA:
191
+ return clauses[:MAX_CRITERIA - 1] + [f"and {len(clauses) - (MAX_CRITERIA - 1)} more in the plan."]
192
+ return clauses
193
+
194
+
195
+ def _risk(plan: Path, phase_id: str) -> str:
196
+ try:
197
+ return phase_risk(plan, phase_id)
198
+ except (OSError, ValueError):
199
+ return "normal"
200
+
201
+
202
+ def story_points(plan: Path, phase_id: str, section: str) -> int:
203
+ """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."""
204
+ files = set()
205
+ for line in _FILES_LINE.findall(section):
206
+ files |= {span for span in re.findall(r"`([^`]+)`", line)
207
+ if ("/" in span or "." in span) and " " not in span}
208
+ programme = any(line.startswith("**Programme phase:**") for line in section.splitlines())
209
+ if programme or len(files) > 8 or _risk(plan, phase_id) == "high":
210
+ return 5
211
+ review = _CROSS_REVIEW.search(section)
212
+ if 1 <= len(files) <= 3 or (review and _SMALL_TIER.search(review.group(1))):
213
+ return 2
214
+ return 3
215
+
216
+
217
+ def dependency(section: str, previous: str | None) -> str:
218
+ """Every `Phase <id>` on the Depends on line as `P<id>`; `None` when the line names no phase; else the previous phase."""
219
+ m = _DEPENDS.search(section)
220
+ if m is None:
221
+ return f"P{previous}" if previous else "None"
222
+ ids = list(dict.fromkeys(re.findall(r"Phase\s+(\d+[a-z]?)", m.group(1))))
223
+ return ", ".join(f"P{i}" for i in ids) if ids else "None"
224
+
225
+
226
+ def _tracker_rows(stripped: str) -> dict[str, dict[str, str]]:
227
+ """Tracker cells by phase id (lower case): {"status": ..., "milestone": ...}."""
228
+ table = tracker_table(stripped)
229
+ if table is None:
230
+ return {}
231
+ columns, lines = table
232
+ rows: dict[str, dict[str, str]] = {}
233
+ for line in lines:
234
+ if not line.strip().startswith("|"):
235
+ continue
236
+ cells = split_cells(line)
237
+ if not cells or all(re.fullmatch(r":?-+:?", c) for c in cells):
238
+ continue
239
+ cell = dict(zip(columns, cells))
240
+ key = re.sub(r"^(phase\s*|p)", "", cell.get("phase", "").strip("*` "), flags=re.I).strip().lower()
241
+ if key and key not in rows:
242
+ rows[key] = cell
243
+ return rows
244
+
245
+
246
+ def _section(path: Path, stripped_lines: list[str], index: int, phase_id: str) -> str:
247
+ try:
248
+ return phase_section(path, phase_id)
249
+ except ValueError:
250
+ end = next((i for i in range(index + 1, len(stripped_lines)) if _ANY_HEADING.match(stripped_lines[i])),
251
+ len(stripped_lines))
252
+ return "\n".join(stripped_lines[index:end]).rstrip() + "\n"
253
+
254
+
255
+ def _slug(meta: dict, path: Path) -> str:
256
+ raw = meta.get("feature") if isinstance(meta.get("feature"), str) and meta.get("feature") else path.stem
257
+ return re.sub(r"[^a-z0-9-]+", "-", raw.lower()).strip("-") or "plan"
258
+
259
+
260
+ def _meta_text(meta: dict, name: str) -> str | None:
261
+ value = meta.get(name)
262
+ return value.strip() if isinstance(value, str) and value.strip() else None
263
+
264
+
265
+ def read_plan(path: Path) -> PlanInfo:
266
+ """The plan's slug, title, Epic, parent page and one story per phase. Raises ValueError when no phase heading."""
267
+ path = Path(path)
268
+ text = path.read_text(encoding="utf-8")
269
+ meta, _ = split_document(text)
270
+ stripped = strip_fences(text)
271
+ stripped_lines = stripped.split("\n")
272
+ headings = _headings(text)
273
+ if not headings:
274
+ raise ValueError(f"no '### Phase <n> - <name>' heading in {path.name}")
275
+ slug = _slug(meta, path)
276
+ title_match = re.search(r"^# (.+)$", stripped, re.M)
277
+ title = _TITLE_SUFFIX.sub("", title_match.group(1)).strip() if title_match else slug
278
+ tracker = _tracker_rows(stripped)
279
+ out: list[Story] = []
280
+ previous = None
281
+ for index, pid, name, heading_milestone in headings:
282
+ section = _section(path, stripped_lines, index, pid)
283
+ row = tracker.get(pid.lower(), {})
284
+ goal = _GOAL.search(section)
285
+ gate = _EXIT_GATE.search(section)
286
+ line_milestone = _MILESTONE_LINE.search(section)
287
+ sprint = (line_milestone.group(1) if line_milestone else None) or heading_milestone \
288
+ or plain(row.get("milestone", "")) or "-"
289
+ out.append(Story(
290
+ story_id=f"{slug}-P{pid}",
291
+ phase=pid,
292
+ summary=plain(name),
293
+ description=first_sentence(plain(goal.group(1))) if goal else "-",
294
+ criteria=criteria(gate.group(1) if gate else None),
295
+ points=story_points(path, pid, section),
296
+ dependency=dependency(section, previous),
297
+ sprint=sprint,
298
+ status=STATUS_WORDS[status_state(row.get("status", ""))],
299
+ ))
300
+ previous = pid
301
+ return PlanInfo(path=path, slug=slug, title=title, epic=_meta_text(meta, "jira_epic"),
302
+ parent=_meta_text(meta, "confluence_parent"), stories=out, status=_meta_text(meta, "status"))
303
+
304
+
305
+ # ---------------------------------------------------------------- rendering
306
+
307
+ def _md_cell(text: str) -> str:
308
+ return text.replace("|", "\\|")
309
+
310
+
311
+ def render_markdown(info: PlanInfo) -> str:
312
+ """The stories as a markdown table: header, rule, one row per story."""
313
+ lines = ["| " + " | ".join(COLUMNS) + " |", "|" + "---|" * len(COLUMNS)]
314
+ for s in info.stories:
315
+ cells = (s.story_id, f"{s.summary}: {s.description}", " ".join(s.criteria), str(s.points), s.dependency,
316
+ s.sprint, s.status)
317
+ lines.append("| " + " | ".join(_md_cell(c) for c in cells) + " |")
318
+ return "\n".join(lines) + "\n"
319
+
320
+
321
+ def _anchor(name: str) -> str:
322
+ return (f'<p><ac:structured-macro ac:name="anchor"><ac:parameter ac:name="">{name}</ac:parameter>'
323
+ f'</ac:structured-macro></p>')
324
+
325
+
326
+ def section_hash(inner: str) -> str:
327
+ """The first 8 hex characters of the sha256 of the section text between the two markers."""
328
+ return hashlib.sha256(inner.encode("utf-8")).hexdigest()[:8]
329
+
330
+
331
+ def _esc(text: str) -> str:
332
+ return html.escape(text, quote=True)
333
+
334
+
335
+ def storage_section(info: PlanInfo) -> str:
336
+ """The plan's section in Confluence storage format: start marker (with the hash), heading, intro, table, end marker."""
337
+ status = f" (plan status: {info.status})" if info.status else ""
338
+ parts = [f"<h2>Development stories: {_esc(info.title + status)}</h2>",
339
+ f"<p>caddis writes this section from the plan file {_esc(info.path.name)}. Do not edit it. "
340
+ f"The next sync replaces it.</p>",
341
+ "<table><tbody><tr>" + "".join(f"<th>{_esc(c)}</th>" for c in COLUMNS) + "</tr>"]
342
+ for s in info.stories:
343
+ items = "".join(f"<li>{_esc(c)}</li>" for c in s.criteria)
344
+ parts.append(f"<tr><td>{_esc(s.story_id)}</td><td><strong>{_esc(s.summary)}</strong><br/>"
345
+ f"{_esc(s.description)}</td><td><ul>{items}</ul></td><td>{s.points}</td>"
346
+ f"<td>{_esc(s.dependency)}</td><td>{_esc(s.sprint)}</td><td>{_esc(s.status)}</td></tr>")
347
+ parts.append("</tbody></table>")
348
+ inner = "".join(parts)
349
+ return (_anchor(f"caddis-stories-{info.slug}-start-{section_hash(inner)}") + inner
350
+ + _anchor(f"caddis-stories-{info.slug}-end"))
351
+
352
+
353
+ # ---------------------------------------------------------------- the marked section on a page
354
+
355
+ class MarkerError(ValueError):
356
+ """The plan's markers on the page are broken (a start with no end, an end before the start, two starts)."""
357
+
358
+
359
+ def _marker_re(slug: str, kind: str) -> re.Pattern:
360
+ """A start or end anchor macro of `slug`, with or without its `<p>` wrapper and with any added attributes."""
361
+ name = f"caddis-stories-{re.escape(slug)}-{kind}" + (r"(?:-([0-9a-f]{8}))?" if kind == "start" else "")
362
+ macro = (r'<ac:structured-macro\b[^>]*\sac:name="anchor"[^>]*>\s*'
363
+ r'<ac:parameter\b[^>]*\sac:name=""[^>]*>\s*' + name + r'\s*</ac:parameter>\s*</ac:structured-macro>')
364
+ return re.compile(r"<p(?:\s[^>]*)?>\s*" + macro + r"\s*</p>|" + macro)
365
+
366
+
367
+ def find_section(body: str, slug: str) -> tuple[int, int, str | None] | None:
368
+ """(start offset, end offset, stored hash) of the plan's section, or None when the page has none of its markers.
369
+
370
+ Raises MarkerError when the markers are broken, so a sync never guesses where the section ends."""
371
+ starts = list(_marker_re(slug, "start").finditer(body))
372
+ ends = list(_marker_re(slug, "end").finditer(body))
373
+ if not starts and not ends:
374
+ return None
375
+ if len(starts) != 1 or len(ends) != 1:
376
+ raise MarkerError(f"{len(starts)} start and {len(ends)} end markers for {slug}")
377
+ start, end = starts[0], ends[0]
378
+ if end.start() < start.end():
379
+ raise MarkerError(f"the end marker of {slug} is before its start marker")
380
+ return start.start(), end.end(), start.group(1) or start.group(2)
381
+
382
+
383
+ def replace_section(body: str, slug: str, section: str) -> tuple[str, str]:
384
+ """(new body, action): `add` appends the section, `update` replaces the old one in place, `unchanged` keeps the
385
+ body when the stored hash equals the new one. Every byte outside the plan's markers stays the same."""
386
+ found = find_section(body, slug)
387
+ if found is None:
388
+ return body + section, "add"
389
+ start, end, stored = found
390
+ own = find_section(section, slug)
391
+ if own is not None and stored is not None and stored == own[2]:
392
+ return body, "unchanged"
393
+ return body[:start] + section + body[end:], "update"
394
+
395
+
396
+ # ---------------------------------------------------------------- Confluence keys and parent page
397
+
398
+ DEFAULT_KEYS_FILE = "~/.caddis/keys.env"
399
+
400
+
401
+ class ConfigError(Exception):
402
+ """CONFLUENCE_URL or CONFLUENCE_TOKEN is missing or not usable. The text names the variable, never its value."""
403
+
404
+
405
+ @dataclass
406
+ class Config:
407
+ base_url: str
408
+ token: str
409
+
410
+ def __repr__(self) -> str: # never show the token in a traceback or a log
411
+ return f"Config(base_url={self.base_url!r}, token='***')"
412
+
413
+
414
+ def load_config(env: Mapping[str, str]) -> Config:
415
+ """CONFLUENCE_URL and CONFLUENCE_TOKEN: the environment first, then the keys file."""
416
+ keys_path = env.get("CADDIS_KEYS_FILE") or DEFAULT_KEYS_FILE
417
+ try:
418
+ file_keys = _parse_keys_file(keys_path)
419
+ except (OSError, UnicodeDecodeError) as exc:
420
+ raise ConfigError(f"cannot read the keys file {keys_path}: {type(exc).__name__}") from None
421
+ values = {}
422
+ for name in ("CONFLUENCE_URL", "CONFLUENCE_TOKEN"):
423
+ value = (env.get(name) or "").strip() or (file_keys.get(name) or "").strip()
424
+ if not value:
425
+ raise ConfigError(f"{name} is not set (environment or {keys_path})")
426
+ values[name] = value
427
+ base_url = values["CONFLUENCE_URL"].rstrip("/")
428
+ parts = urlsplit(base_url)
429
+ if parts.scheme != "https" or not parts.hostname:
430
+ raise ConfigError("CONFLUENCE_URL must use the https scheme and name a host")
431
+ return Config(base_url=base_url, token=values["CONFLUENCE_TOKEN"])
432
+
433
+
434
+ @dataclass
435
+ class ParentRef:
436
+ page_id: str | None
437
+ space: str | None
438
+ title: str | None
439
+
440
+
441
+ def _host(url: str) -> tuple[str, int | None]:
442
+ parts = urlsplit(url)
443
+ return (parts.hostname or "").lower(), parts.port
444
+
445
+
446
+ def parse_parent(url: str, base_url: str) -> ParentRef:
447
+ """The parent page from its URL: `?pageId=<n>`, `/spaces/<KEY>/pages/<n>/...` or `/display/<KEY>/<Title+Words>`.
448
+
449
+ Raises ValueError when the URL is not https on the `base_url` host, or no form matches."""
450
+ url = url.strip()
451
+ parts = urlsplit(url)
452
+ if parts.scheme != "https" or not parts.hostname or _host(url) != _host(base_url):
453
+ raise ValueError("confluence_parent is not an https URL on the CONFLUENCE_URL host")
454
+ page_id = parse_qs(parts.query).get("pageId", [None])[0]
455
+ if page_id and page_id.isdigit():
456
+ return ParentRef(page_id, None, None)
457
+ m = re.search(r"/spaces/([^/]+)/pages/(\d+)(?:/|$)", parts.path)
458
+ if m:
459
+ return ParentRef(m.group(2), unquote_plus(m.group(1)), None)
460
+ m = re.search(r"/display/([^/]+)/([^/]+)/?$", parts.path)
461
+ if m:
462
+ return ParentRef(None, unquote_plus(m.group(1)), unquote_plus(m.group(2)))
463
+ raise ValueError("confluence_parent has no page id and no /display/<space>/<title> form")
464
+
465
+
466
+ # ---------------------------------------------------------------- Confluence REST client
467
+
468
+ _PAGE_EXPAND = "body.storage,version,space,ancestors"
469
+ MAX_ERROR_TEXT = 300
470
+
471
+
472
+ class ConfluenceError(Exception):
473
+ """A Confluence call failed. `status` is the HTTP status, or None for a network failure or a timeout.
474
+ `message` is already redacted and cut: it never holds the token."""
475
+
476
+ def __init__(self, status: int | None, message: str):
477
+ super().__init__(message)
478
+ self.status = status
479
+ self.message = message
480
+
481
+ def __str__(self) -> str:
482
+ return self.message
483
+
484
+
485
+ class _NoRedirect(urllib.request.HTTPRedirectHandler):
486
+ """A redirect is an error: the Authorization header must never follow it to another URL."""
487
+
488
+ def redirect_request(self, req, fp, code, msg, headers, newurl):
489
+ return None
490
+
491
+
492
+ _OPENER = urllib.request.build_opener(_NoRedirect)
493
+
494
+
495
+ def _default_send(req: urllib.request.Request, timeout: float) -> tuple[int, bytes]:
496
+ """urllib transport: (status, body). An HTTP error status is returned, not raised. Network errors raise."""
497
+ try:
498
+ with _OPENER.open(req, timeout=timeout) as resp:
499
+ return resp.status, resp.read()
500
+ except urllib.error.HTTPError as exc:
501
+ try:
502
+ body = exc.read()
503
+ except (OSError, http.client.HTTPException):
504
+ body = b""
505
+ return exc.code, body
506
+
507
+
508
+ class Confluence:
509
+ """Confluence Server REST calls with a Bearer personal access token. The token is sent only in the header."""
510
+
511
+ def __init__(self, base_url: str, token: str, timeout: float = 20.0, send: Callable | None = None):
512
+ self.base_url = base_url.rstrip("/")
513
+ self._token = token
514
+ self.timeout = timeout
515
+ self._send = send or _default_send
516
+ secrets = caddis_redact.load_secrets(Path.home())
517
+ if token:
518
+ secrets = secrets + [token]
519
+ self._secrets = sorted(set(secrets), key=len, reverse=True)
520
+
521
+ def __repr__(self) -> str:
522
+ return f"Confluence(base_url={self.base_url!r})"
523
+
524
+ def _clean(self, text: str) -> str:
525
+ return caddis_redact.redact(text, self._secrets)[:MAX_ERROR_TEXT]
526
+
527
+ def request(self, method: str, path: str, query: dict | None = None, body: dict | None = None) -> dict:
528
+ url = self.base_url + path + ("?" + urlencode(query) if query else "")
529
+ data = json.dumps(body).encode("utf-8") if body is not None else None
530
+ req = urllib.request.Request(url, data=data, method=method)
531
+ req.add_header("Authorization", f"Bearer {self._token}")
532
+ req.add_header("Accept", "application/json")
533
+ req.add_header("X-Atlassian-Token", "no-check")
534
+ if data is not None:
535
+ req.add_header("Content-Type", "application/json")
536
+ try:
537
+ status, raw = self._send(req, self.timeout)
538
+ except ConfluenceError:
539
+ raise
540
+ except (OSError, http.client.HTTPException) as exc:
541
+ reason = self._clean(f"{type(exc).__name__}: {exc}")
542
+ raise ConfluenceError(None, f"network error {method} {path}: {reason}") from None
543
+ text = (raw or b"").decode("utf-8", errors="replace")
544
+ if not 200 <= status < 300:
545
+ raise ConfluenceError(status, f"HTTP {status} {method} {path}: {self._clean(text)}")
546
+ if not text.strip():
547
+ return {}
548
+ try:
549
+ return json.loads(text)
550
+ except ValueError:
551
+ raise ConfluenceError(status, f"HTTP {status} {method} {path}: the answer is not JSON") from None
552
+
553
+ def current_user(self) -> str:
554
+ data = self.request("GET", "/rest/api/user/current")
555
+ return str(data.get("username") or data.get("displayName") or "")
556
+
557
+ def get_page(self, page_id: str) -> dict:
558
+ return self.request("GET", f"/rest/api/content/{quote(str(page_id), safe='')}", {"expand": _PAGE_EXPAND})
559
+
560
+ def find_page(self, space: str, title: str) -> dict | None:
561
+ data = self.request("GET", "/rest/api/content", {"spaceKey": space, "title": title, "expand": _PAGE_EXPAND})
562
+ results = data.get("results") or []
563
+ return results[0] if results else None
564
+
565
+ def create_page(self, space: str, parent_id: str, title: str, storage: str) -> dict:
566
+ return self.request("POST", "/rest/api/content", body={
567
+ "type": "page", "title": title, "space": {"key": space}, "ancestors": [{"id": parent_id}],
568
+ "body": {"storage": {"value": storage, "representation": "storage"}}})
569
+
570
+ def update_page(self, page: dict, storage: str) -> dict:
571
+ """PUT the new body with version + 1. Confluence answers 409 when someone saved the page in between."""
572
+ return self.request("PUT", f"/rest/api/content/{quote(str(page['id']), safe='')}", body={
573
+ "id": page["id"], "type": "page", "title": page["title"], "space": {"key": page["space"]["key"]},
574
+ "version": {"number": page["version"]["number"] + 1},
575
+ "body": {"storage": {"value": storage, "representation": "storage"}}})
576
+
577
+
578
+ # ---------------------------------------------------------------- sync
579
+
580
+ @dataclass
581
+ class SyncResult:
582
+ action: str # create-page | add | update | unchanged
583
+ page_id: str | None
584
+ version: int | None
585
+ warnings: list[str]
586
+
587
+
588
+ def _version(page: dict) -> int | None:
589
+ number = (page.get("version") or {}).get("number")
590
+ return number if isinstance(number, int) else None
591
+
592
+
593
+ def _body(page: dict) -> str:
594
+ return ((page.get("body") or {}).get("storage") or {}).get("value") or ""
595
+
596
+
597
+ def sync_plan(info: PlanInfo, client: Confluence, base_url: str, dry_run: bool) -> SyncResult:
598
+ """Write the plan's section to the Epic page under the parent page: create the page when it is missing, else
599
+ replace only the plan's marked section. A dry run reads only. On a 409 the page is read again and written once more.
600
+ """
601
+ warnings: list[str] = []
602
+ parent = resolve_parent(client, parse_parent(info.parent or "", base_url))
603
+ parent_id = str(parent["id"])
604
+ space = parent["space"]["key"]
605
+ section = storage_section(info)
606
+ page = client.find_page(space, info.epic)
607
+ if page is None:
608
+ if dry_run:
609
+ return SyncResult("create-page", None, None, warnings)
610
+ created = client.create_page(space, parent_id, info.epic, section)
611
+ return SyncResult("create-page", str(created.get("id")), _version(created), warnings)
612
+ if parent_id not in {str(a.get("id")) for a in page.get("ancestors") or []}:
613
+ warnings.append(f"page {info.epic} is not under the parent page")
614
+ new_body, action = replace_section(_body(page), info.slug, section)
615
+ if action == "unchanged" or dry_run:
616
+ return SyncResult(action, str(page["id"]), _version(page), warnings)
617
+ try:
618
+ updated = client.update_page(page, new_body)
619
+ except ConfluenceError as err:
620
+ if err.status != 409:
621
+ raise
622
+ page = client.get_page(str(page["id"]))
623
+ new_body, action = replace_section(_body(page), info.slug, section)
624
+ if action == "unchanged":
625
+ return SyncResult(action, str(page["id"]), _version(page), warnings)
626
+ updated = client.update_page(page, new_body)
627
+ return SyncResult(action, str(page["id"]), _version(updated), warnings)
628
+
629
+
630
+ # ---------------------------------------------------------------- command line
631
+
632
+ def _load(plan: str) -> PlanInfo | None:
633
+ try:
634
+ return read_plan(Path(plan))
635
+ except (OSError, ValueError) as exc:
636
+ print(f"cannot read plan: {exc}", file=sys.stderr)
637
+ return None
638
+
639
+
640
+ def cmd_render(args) -> int:
641
+ info = _load(args.plan)
642
+ if info is None:
643
+ return caddis_exit.ERROR
644
+ sys.stdout.write(storage_section(info) + "\n" if args.format == "storage" else render_markdown(info))
645
+ return caddis_exit.CLEAN
646
+
647
+
648
+ def resolve_parent(client: Confluence, ref: ParentRef) -> dict:
649
+ """The parent page: by id, else by space and title. ConfluenceError 404 when it is not found."""
650
+ if ref.page_id:
651
+ return client.get_page(ref.page_id)
652
+ page = client.find_page(ref.space or "", ref.title or "")
653
+ if page is None:
654
+ raise ConfluenceError(404, "parent page not found")
655
+ return page
656
+
657
+
658
+ def _confluence_failed(err: ConfluenceError) -> int:
659
+ if err.status is None:
660
+ print(f"Confluence not reached: {err}", file=sys.stderr)
661
+ return caddis_exit.NOT_RUN
662
+ print(f"Confluence refused: {err}", file=sys.stderr)
663
+ return caddis_exit.BLOCKED
664
+
665
+
666
+ def cmd_check(args, env: Mapping[str, str], client_factory=Confluence) -> int:
667
+ """Read-only: the login user and, with --plan, the plan's parent page. Every check of input runs before a request."""
668
+ try:
669
+ config = load_config(env)
670
+ except ConfigError as exc:
671
+ print(f"NOT CONFIGURED: {exc}")
672
+ return caddis_exit.NOT_RUN
673
+ ref = None
674
+ if getattr(args, "plan", None):
675
+ info = _load(args.plan)
676
+ if info is None:
677
+ return caddis_exit.ERROR
678
+ if not info.parent:
679
+ print(f"NOT CONFIGURED: {info.path.name} needs confluence_parent")
680
+ return caddis_exit.NOT_RUN
681
+ try:
682
+ ref = parse_parent(info.parent, config.base_url)
683
+ except ValueError as exc:
684
+ print(f"bad input: {exc}", file=sys.stderr)
685
+ return caddis_exit.ERROR
686
+ client = client_factory(config.base_url, config.token)
687
+ try:
688
+ print(f"USER: {client.current_user()}")
689
+ if ref is not None:
690
+ parent = resolve_parent(client, ref)
691
+ space = (parent.get("space") or {}).get("key", ref.space or "?")
692
+ print(f"PARENT: {parent.get('title', '?')} ({parent.get('id', '?')}) in space {space}")
693
+ except ConfluenceError as err:
694
+ return _confluence_failed(err)
695
+ return caddis_exit.CLEAN
696
+
697
+
698
+ _EPIC_KEY = re.compile(r"^[A-Z][A-Z0-9]+-\d+$")
699
+
700
+
701
+ def cmd_sync(args, env: Mapping[str, str], client_factory=Confluence) -> int:
702
+ """Write the plan's stories section to its Epic page. Every check of input runs before the first request."""
703
+ info = _load(args.plan)
704
+ if info is None:
705
+ return caddis_exit.ERROR
706
+ if not info.epic or not info.parent:
707
+ print(f"NOT CONFIGURED: {info.path.name} needs jira_epic and confluence_parent")
708
+ return caddis_exit.NOT_RUN
709
+ if not _EPIC_KEY.match(info.epic):
710
+ print(f"bad input: jira_epic '{info.epic}' is not a Jira key such as ABC-123", file=sys.stderr)
711
+ return caddis_exit.ERROR
712
+ try:
713
+ config = load_config(env)
714
+ except ConfigError as exc:
715
+ print(f"NOT CONFIGURED: {exc}")
716
+ return caddis_exit.NOT_RUN
717
+ try:
718
+ parse_parent(info.parent, config.base_url)
719
+ except ValueError as exc:
720
+ print(f"bad input: {exc}", file=sys.stderr)
721
+ return caddis_exit.ERROR
722
+ client = client_factory(config.base_url, config.token)
723
+ try:
724
+ result = sync_plan(info, client, config.base_url, dry_run=bool(getattr(args, "dry_run", False)))
725
+ except MarkerError:
726
+ print(f"markers broken on page {info.epic}; fix the page by hand", file=sys.stderr)
727
+ return caddis_exit.BLOCKED
728
+ except ConfluenceError as err:
729
+ return _confluence_failed(err)
730
+ for warning in result.warnings:
731
+ print(f"WARN: {warning}", file=sys.stderr)
732
+ print(f"ACTION: {result.action}")
733
+ if result.page_id is None:
734
+ print(f"PAGE: {info.epic} (new)")
735
+ else:
736
+ print(f"PAGE: {info.epic} ({result.page_id}) v{result.version if result.version is not None else '?'}")
737
+ if getattr(args, "dry_run", False):
738
+ print("DRY RUN: nothing written")
739
+ print(storage_section(info))
740
+ return caddis_exit.CLEAN
741
+
742
+
743
+ def _parser() -> argparse.ArgumentParser:
744
+ parser = argparse.ArgumentParser(prog="caddis_stories.py", description="Plan phases as development stories.")
745
+ sub = parser.add_subparsers(dest="command", required=True)
746
+ render = sub.add_parser("render", help="print the stories table of a plan (no network)")
747
+ render.add_argument("--plan", required=True)
748
+ render.add_argument("--format", choices=("md", "storage"), default="md")
749
+ check = sub.add_parser("check", help="read-only: the Confluence login and the plan's parent page")
750
+ check.add_argument("--plan")
751
+ sync = sub.add_parser("sync", help="write the plan's stories section to its Epic page")
752
+ sync.add_argument("--plan", required=True)
753
+ sync.add_argument("--dry-run", action="store_true", help="read only; print the action and the section")
754
+ return parser
755
+
756
+
757
+ def main(argv: list[str] | None = None) -> int:
758
+ for stream in (sys.stdout, sys.stderr):
759
+ if hasattr(stream, "reconfigure"):
760
+ try:
761
+ stream.reconfigure(encoding="utf-8", errors="replace")
762
+ except (OSError, ValueError):
763
+ pass
764
+ args = _parser().parse_args(argv)
765
+ if args.command == "render":
766
+ return cmd_render(args)
767
+ if args.command == "check":
768
+ return cmd_check(args, os.environ)
769
+ if args.command == "sync":
770
+ return cmd_sync(args, os.environ)
771
+ return caddis_exit.ERROR
772
+
773
+
774
+ if __name__ == "__main__":
775
+ raise SystemExit(main())
@@ -109,6 +109,7 @@
109
109
  | Ship Merge | `ship-merge/` | Merge an already-green, already-reviewed PR behind an explicit deploy-confirm, monitor the deploy, validate prod, then clean up the branch — only on green. |
110
110
  | Ship Pr | `ship-pr/` | Open a reviewed PR for the current feature branch — rebase-safe push, PR create/update, monitor CI, STOP at green. Never merges, never deploys (that's /ship-merge). |
111
111
  | Spawn Session | `spawn-session/` | Hand the WORK to a fresh session — generate the handover from the repo, then validate the successor by re-deriving its answers |
112
+ | Stories | `stories/` | Publish a plan's phases as development stories to the Jira Epic's Confluence page — one marked section per plan |
112
113
  | Tdd | `tdd/` | Run a strict red-green-refactor TDD cycle for a unit of behavior |
113
114
  | Ui Brief | `ui-brief/` | Design-first UI brief — lock the aesthetic before writing any code |
114
115
  | Usage Review | `usage-review/` | Review local caddis usage over a window, surface prioritised recommendations, and apply config changes in one step |
@@ -41,6 +41,8 @@ Absolute rules in this mode (they override everything below):
41
41
  a bullet under `## Constraints & decisions` — never a question to the user.
42
42
  - **Honor the caller's output path and slug** (falling back to `.caddis/plans/<feature-slug>.md`);
43
43
  set `feature: <slug>` in the frontmatter to that slug.
44
+ - **Do not write `jira_epic` or `confluence_parent`** (Step 1b is interactive only). Add the assumption: no Jira
45
+ Epic or Confluence page was given (headless). Add both fields to publish the stories with `/caddis:stories`.
44
46
  - **Always write the plan file, then end with exactly one fenced `json` highlights block** — nothing
45
47
  after it:
46
48
  ```json
@@ -93,6 +95,15 @@ exactly what a phase's exit gate needs) and its `## Open questions` into `## Con
93
95
  A headless pipeline that plans straight from a bare title while a complete PRD sits on disk is the
94
96
  failure this closes.
95
97
 
98
+ ## Step 1b — Jira Epic and Confluence page (interactive only)
99
+ Skip this step in headless mode. Ask the user one self-contained AskUserQuestion with these two questions:
100
+ - "Is there a Confluence HLA or HLSA page for this project? Give its URL."
101
+ - "Is there a Jira Epic for this work? Give its key, for example ABC-123."
102
+
103
+ Write `confluence_parent: <URL>` and `jira_epic: <KEY>` into the plan frontmatter only for the answers the user
104
+ gives. With both fields, `/caddis:stories` publishes each phase as a development story to the Confluence page
105
+ titled with the Epic key, and `/caddis:implement` syncs it after each Tracker update.
106
+
96
107
  ## Step 2 — Design phases
97
108
  Break the work into **independently completable** phases (~30–60 min each, clear exit gate). Each phase
98
109
  follows the harness loop: **RED → GREEN → REFACTOR → VERIFY → COMMIT**. Front-load risk.
@@ -263,6 +274,8 @@ Create `.caddis/plans/` if it doesn't exist.
263
274
  type: plan
264
275
  status: draft
265
276
  feature: <feature-slug>
277
+ jira_epic: <KEY>
278
+ confluence_parent: <URL of the HLA or HLSA page>
266
279
  creation-agent: caddis
267
280
  Original Author: Claude Code
268
281
  Creation Date: <YYYY-MM-DDTHH:MM:SSZ>
@@ -423,6 +436,8 @@ Three rules: one attempt, one review.
423
436
  | 1 | M1 | mid | claude | not started | — | — | |
424
437
  ```
425
438
 
439
+ `jira_epic` and `confluence_parent`: Only when Step 1b gave them. Leave out a line that has no answer.
440
+
426
441
  Status words (one vocabulary, `scripts/caddis_status.py`): done is `done`, `merged`, `✅`, `☑`, `✔` or `✓`;
427
442
  `in progress`, `blocked` and `moved` name the other states; anything else (`not started`, `☐`) is to do. A cell
428
443
  that says `pending` is never done.
@@ -493,6 +508,18 @@ Small work that does not meet a trigger skips its block.
493
508
 
494
509
  **Trigger: The plan records a decision.** Record it with `/caddis:decide`.
495
510
 
511
+ ## Step 3b — Offer to publish the stories (interactive only)
512
+ Skip this step in headless mode, and skip it when the plan frontmatter lacks either `jira_epic` or `confluence_parent`.
513
+ Run `python "${CLAUDE_PLUGIN_ROOT}/scripts/caddis_stories.py" sync --plan "<plan path>" --dry-run`.
514
+ - Exit 0: show the `ACTION:` and `PAGE:` lines, then ask one AskUserQuestion: "Publish the stories to the Epic page now?
515
+ The page shows the plan status, for example draft. `/caddis:implement` re-syncs them after each phase." On yes, run
516
+ the same command without `--dry-run`. On no, print `Stories: not published - run /caddis:stories <plan path> later`.
517
+ - Any non-zero exit, of the dry run or of the write (3 = no Confluence keys or the network failed; 1 or 4 = see
518
+ `/caddis:stories`): print `Stories: not published - exit <n> - <first output line>` and go on to Step 4. Never print
519
+ the token. The plan is still done.
520
+
521
+ The plan is a draft and may change after preflight. Publish only on the user's yes.
522
+
496
523
  ## Step 4 — Report
497
524
  Output the plan path (`.caddis/plans/<feature-slug>.md`), the phase list (one line each, with each
498
525
  phase's model tier + lane + execution), confirm the local-coder gate passed (or list the phases that need
@@ -369,6 +369,11 @@ report — do not redo completed work.
369
369
  ACTUALLY ran on (not the planned one — see Step 1), and add a one-line note. This is what lets a
370
370
  future session (or the runner) see progress. Commit the Tracker update with the phase (or as a tiny
371
371
  follow-up commit) — it lives in the plan file, which is fine to commit on this branch.
372
+ - **SYNC THE STORIES** — only when the plan frontmatter has both `jira_epic` and `confluence_parent`. After
373
+ the Tracker commit, run `python "${CLAUDE_PLUGIN_ROOT}/scripts/caddis_stories.py" sync --plan <plan path>`.
374
+ On exit 0, print nothing more. On any other exit, print one line
375
+ `WARN: stories sync exit <n> - <first output line>` and go on. The sync never stops, fails or blocks a
376
+ phase, and you do not retry it in that phase. Never print the Confluence token.
372
377
 
373
378
  If a phase cannot be completed (a blocking gap the plan did not resolve, or a rule above would be
374
379
  violated), **stop there**: leave later phases untouched, record the blocker in the review file, mark the
@@ -0,0 +1,50 @@
1
+ ---
2
+ name: stories
3
+ description: Publish a plan's phases as development stories to the Jira Epic's Confluence page — one marked section per plan
4
+ ---
5
+
6
+ # /stories — plan phases as development stories on Confluence
7
+
8
+ One plan phase becomes one sprint-sized development story. The script writes a "Development stories" table to the
9
+ Confluence page whose title is the plan's Jira Epic key, under the page in `confluence_parent`. It writes only the
10
+ plan's own marked section. It never changes other page content and never deletes a page. Copying the stories into
11
+ Jira is the reader's job: caddis does not call Jira.
12
+
13
+ ## Input
14
+
15
+ - Usage: `/caddis:stories <plan path>`. The plan path is `$ARGUMENTS`; with no argument, ask for it.
16
+ - When no argument is given, find the plan with
17
+ `python "${CLAUDE_PLUGIN_ROOT}/scripts/caddis_todo.py" active-plan`.
18
+ - The plan frontmatter must hold `jira_epic: <KEY>` and `confluence_parent: <URL of the HLA or HLSA page>`.
19
+ - The keys must be in the environment or in `~/.caddis/keys.env`: `CONFLUENCE_URL` (https only) and
20
+ `CONFLUENCE_TOKEN` (a personal access token). Never print, echo or show the token.
21
+
22
+ ## Steps
23
+
24
+ 1. Show the table. Run `python "${CLAUDE_PLUGIN_ROOT}/scripts/caddis_stories.py" render --plan <plan path>` and
25
+ show its output to the user.
26
+ 2. Check the login and the parent page. Run
27
+ `python "${CLAUDE_PLUGIN_ROOT}/scripts/caddis_stories.py" check --plan <plan path>`. It makes read-only calls and
28
+ prints `USER:` and `PARENT:` lines.
29
+ 3. Do a dry run. Run `python "${CLAUDE_PLUGIN_ROOT}/scripts/caddis_stories.py" sync --plan <plan path> --dry-run`.
30
+ Show the `ACTION:` and `PAGE:` lines. It writes nothing.
31
+ 4. Write. Run `python "${CLAUDE_PLUGIN_ROOT}/scripts/caddis_stories.py" sync --plan <plan path>`. Report the
32
+ `ACTION:` and `PAGE:` lines, and each `WARN:` line.
33
+
34
+ Stop at the first step that does not exit 0, and report its output.
35
+
36
+ ## Exit codes
37
+
38
+ | Exit | Meaning | What to do |
39
+ |---|---|---|
40
+ | 0 | Synced, or the section is unchanged | Nothing |
41
+ | 1 | Confluence refused (HTTP error, a second version conflict) or the markers on the page are broken | Read the message. Broken markers: fix the page by hand |
42
+ | 3 | Not configured (no keys, or no `jira_epic` / `confluence_parent`), or the network failed | Add the keys or the fields, or try again later |
43
+ | 4 | Bad input: the plan cannot be read, a bad Epic key, or the parent page is on another host | Fix the plan |
44
+
45
+ ## Rules
46
+
47
+ - The token goes only to the `CONFLUENCE_URL` host. A `confluence_parent` on another host stops the sync before any
48
+ call.
49
+ - A sync rewrites the plan's whole section. A phase removed from the plan leaves the table.
50
+ - When the stored section has the same hash, the sync writes nothing and makes no new page version.
@@ -1,7 +1,7 @@
1
1
  {
2
- "poolVersion": "1.3.198",
2
+ "poolVersion": "1.3.200",
3
3
  "bundles": {
4
- "antigravity-plugin": "1.3.198",
4
+ "antigravity-plugin": "1.3.200",
5
5
  "antigravity-plugin-extras": "1.3.54",
6
6
  "codex": "unknown"
7
7
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@caddis/cli",
3
- "version": "0.4.114",
3
+ "version": "0.4.116",
4
4
  "description": "Install, update and diagnose the caddis dev harness across every coding agent you use (Claude Code, agy/Antigravity, and more).",
5
5
  "keywords": [
6
6
  "caddis",