aw-spec-cli 0.1.14 → 0.1.16

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 (32) hide show
  1. package/assets/.appweaver/STACK-PROFILES.md +1 -1
  2. package/assets/.appweaver/orchestrator/modules/spec-state-gate.orch.yaml +87 -0
  3. package/assets/.appweaver/orchestrator/orchestrator.py +5 -0
  4. package/assets/.appweaver/orchestrator/rev-templates/domain-rule-bindings.skeleton.md +10 -3
  5. package/assets/.appweaver/orchestrator/rev-templates/tech-rule-bindings.skeleton.md +38 -11
  6. package/assets/.appweaver/orchestrator/workflows/aw-spec-adopt.orch.yaml +2 -1
  7. package/assets/.appweaver/orchestrator/workflows/aw-spec-analyze-design.orch.yaml +672 -124
  8. package/assets/.appweaver/orchestrator/workflows/aw-spec-analyze-slice.orch.yaml +700 -72
  9. package/assets/.appweaver/orchestrator/workflows/aw-spec-implement-ui.orch.yaml +531 -135
  10. package/assets/.appweaver/orchestrator/workflows/aw-spec-implement.orch.yaml +573 -145
  11. package/assets/.appweaver/orchestrator/workflows/aw-spec-onboard.orch.yaml +78 -14
  12. package/assets/.appweaver/orchestrator/workflows/aw-spec-plan-ui.orch.yaml +600 -0
  13. package/assets/.appweaver/orchestrator/workflows/aw-spec-plan.orch.yaml +721 -0
  14. package/assets/.appweaver/orchestrator/workflows/aw-spec-select-feature.orch.yaml +3 -3
  15. package/assets/.appweaver/orchestrator/workflows/aw-spec-specify.orch.yaml +119 -32
  16. package/assets/.appweaver/orchestrator/workflows/aw-spec-story-plan.orch.yaml +1147 -0
  17. package/assets/.appweaver/orchestrator/workflows/aw-spec-sync-stories.orch.yaml +1121 -0
  18. package/assets/.appweaver/scripts/bash/aw-spec-actions.sh +2564 -38
  19. package/assets/.appweaver/scripts/bash/aw-xref.sh +2 -1
  20. package/assets/.appweaver/scripts/powershell/aw-spec-actions.ps1 +2458 -22
  21. package/assets/.appweaver/scripts/powershell/aw-xref.ps1 +2 -1
  22. package/assets/.appweaver/scripts/python/aw-payload-parity.py +158 -0
  23. package/assets/.appweaver/scripts/python/aw-xref.py +431 -48
  24. package/assets/.appweaver/templates/design-template.md +88 -54
  25. package/assets/.appweaver/templates/spec-template.md +12 -10
  26. package/assets/.appweaver/templates/story-template.md +83 -12
  27. package/assets/.appweaver/templates/ui-design-template.md +71 -39
  28. package/assets/guardrails/projects/dotnet-default-project/domain-rule-bindings.md +19 -7
  29. package/assets/guardrails/projects/dotnet-default-project/tech-rule-bindings.md +35 -26
  30. package/package.json +1 -1
  31. package/assets/.appweaver/orchestrator/workflows/aw-spec-design-ui.orch.yaml +0 -386
  32. package/assets/.appweaver/orchestrator/workflows/aw-spec-design.orch.yaml +0 -382
@@ -124,7 +124,8 @@ function Invoke-ResolveDomain {
124
124
  # wrong corpus is how a Java project ends up being handed C# rules.
125
125
  function Invoke-ResolveTech {
126
126
  param([string[]]$Rest)
127
- $commandName = 'aw-spec-design'
127
+ $commandName = 'aw-spec-plan' # inert: every caller passes --command. Kept current
128
+ # so a hand-run defaults to a LIVE command, not a dead one.
128
129
  for ($i = 0; $i -lt $Rest.Count; $i++) {
129
130
  switch ($Rest[$i]) {
130
131
  '--command' { $commandName = $Rest[++$i] }
@@ -876,7 +877,7 @@ function Invoke-VersionState { # op in read|init (feature-dir, plus --bootstra
876
877
  # spec.md's `## Change History` is the sync anchor between the spec and its story
877
878
  # backlog: each row names the requirement ids that version touched, and each story
878
879
  # records the version it last synced at, so "is this story stale" is one integer
879
- # comparison rather than a diff. update-stories reads the rows; specify and
880
+ # comparison rather than a diff. sync-stories reads the rows; specify and
880
881
  # update-spec append them.
881
882
  #
882
883
  # The ledger is hand-writable, which is the point — a spec can be edited by hand —
@@ -953,6 +954,14 @@ sep = (next((i for i in range(hi + 1, sec_end)
953
954
  if re.match(r'^\|[\s\-:|]+\|$', lines[i].strip())), -1) if hi >= 0 else -1)
954
955
  rows = [i for i in range(sep + 1, sec_end) if lines[i].lstrip().startswith("|")] if sep >= 0 else []
955
956
  has_ledger = hi >= 0 and sep >= 0
957
+ # THE VERSIONS THE TABLE ACTUALLY CARRIES, read from the rows located above rather than by
958
+ # an unbounded scan, so a version-looking cell in another section's table cannot be counted
959
+ # as history. This is the EVIDENCE that a change was recorded; the document's **Version**
960
+ # header is only the CLAIM, and hand editing parts the two in both directions.
961
+ row_versions = [m.group(1) for m in
962
+ (re.match(r'^\|\s*(v\d+(?:\.\d+)?)\s*\|', lines[i].lstrip()) for i in rows)
963
+ if m]
964
+ newest_row = max(row_versions, key=vtuple) if row_versions else ""
956
965
 
957
966
  def cell(s, limit=160):
958
967
  """One markdown table cell. A newline ENDS a row and a bare pipe STARTS a column, so
@@ -982,7 +991,7 @@ if dspec and os.path.isfile(dspec) and os.path.getsize(dspec) > 0:
982
991
  out.update(open_change=cr, delta_authored=delta_authored)
983
992
  out.update(version=recorded_ver, doc_version=doc_ver, spec_sha256=actual,
984
993
  recorded_sha256=recorded_hash, body_changed=(recorded_hash != actual),
985
- has_ledger=has_ledger, ledger_rows=len(rows),
994
+ has_ledger=has_ledger, ledger_rows=len(rows), newest_row=newest_row,
986
995
  first_stamp=(not recorded_hash))
987
996
 
988
997
  if op == "check":
@@ -1016,21 +1025,66 @@ if op == "check":
1016
1025
  out["state"] = "unstamped" # pre-ledger spec; stamp adopts it
1017
1026
  elif recorded_hash == actual:
1018
1027
  out["state"] = "clean"
1028
+ # THE ROW IS THE EVIDENCE; THE HEADER IS ONLY THE CLAIM. The body has moved since the
1029
+ # kit last stamped, and what makes that edit legible downstream is a version ROW naming
1030
+ # the ids it touched: sync-stories reads rows, story-plan's staleness check reads rows,
1031
+ # and neither ever opens the **Version** header. Taking the header as proof accepted the
1032
+ # commonest hand-edit mistake there is — bump the number, forget the row — and that one
1033
+ # passed every tripwire in the kit, raised no work anywhere, and was then buried for good
1034
+ # by the next run's stamp adopting its hash. So the test is a row ABOVE the version the
1035
+ # kit last recorded, and the header is only asked whether it kept up.
1036
+ elif newest_row and vtuple(newest_row) > vtuple(recorded_ver):
1037
+ out["state"] = ("ledgered_edit" if vtuple(doc_ver) >= vtuple(newest_row)
1038
+ else "header_behind") # recorded; stamp reconciles the header
1019
1039
  elif vtuple(doc_ver) > vtuple(recorded_ver):
1020
- out["state"] = "ledgered_edit" # hand-edited AND a row was written
1040
+ # The header claims a version the table never recorded. Refused for the same reason
1041
+ # an unrowed edit is: without the row nothing can say WHICH requirements moved, so
1042
+ # every story citing one is stale with nothing able to detect it.
1043
+ out["state"] = "unrowed_edit"
1044
+ out.update(ok=False, error="spec.md's header reads %s but the Change History carries "
1045
+ "no row above %s — the version was bumped and what it changed was never "
1046
+ "recorded. The row is what a story reads to learn that a requirement it "
1047
+ "cites has moved; the header is read by nobody. Add a row naming the ids "
1048
+ "you changed (keep the header at %s), then re-run."
1049
+ % (doc_ver or "no version", recorded_ver, doc_ver))
1021
1050
  elif vtuple(doc_ver) < vtuple(recorded_ver):
1022
1051
  out["state"] = "rollback"
1023
1052
  out.update(ok=False, error="spec.md reads %s but the kit last wrote %s — the "
1024
1053
  "document is behind its own ledger" % (doc_ver or "no version", recorded_ver))
1025
1054
  else:
1026
1055
  out["state"] = "unledgered_edit"
1056
+ # BOTH ROUTES, BECAUSE NOT EVERY EDIT HAS AN ID TO NAME. Law 5 requires a version row
1057
+ # to name at least one id, so an edit to Aggregate Boundary, Experience Scope or any
1058
+ # other load-bearing prose has nothing legal to put in the cell — and being told to
1059
+ # "add a row naming the ids you changed" sent that person round a loop with no exit.
1060
+ # The protocol has always sanctioned re-baselining instead when the diff finds no id
1061
+ # (SPEC-EDIT-PROTOCOL.md, "The short version" step 4 and the PR checklist); it was
1062
+ # simply never named at the one place anybody reads it.
1027
1063
  out.update(ok=False, error="spec.md has changed since %s but no Change History row "
1028
1064
  "was added. Every story citing an edited requirement is now silently "
1029
- "stale. Add a row naming the ids you changed, then re-run."
1065
+ "stale. Add a row naming the ids you changed, then re-run — or, if this "
1066
+ "edit touched NO requirement (prose only: scope, boundary, wording that "
1067
+ "defines no id), re-run spec-stamp to re-baseline instead. Run spec-diff "
1068
+ "against the snapshot to see which of the two this is."
1030
1069
  % recorded_ver)
1031
1070
  elif op == "stamp":
1071
+ # THE VERSION IS THE HIGHEST OF THE THREE PLACES ONE IS WRITTEN, and the document's
1072
+ # header is reconciled up to it. Taking the header alone let a hand edit that DID write
1073
+ # its row — without bumping the header — leave the kit recording a version below the
1074
+ # newest row; the next hand edit then read as a `rollback`, the document behind its own
1075
+ # ledger, when nothing had rolled back. Rewriting the header is the authority
1076
+ # ledger-append already exercises: the kit owns the number, the row is what it is
1077
+ # computed from, and re-hashing after the rewrite is what keeps the baseline honest.
1078
+ stamp_ver = max([recorded_ver or "v1.0", doc_ver or "v1.0"] +
1079
+ ([newest_row] if newest_row else []), key=vtuple)
1080
+ if doc_ver and vtuple(doc_ver) < vtuple(stamp_ver):
1081
+ text = re.sub(r'^(\*\*Version\*\*:\s*)v[\d.]+', r'\g<1>' + stamp_ver,
1082
+ text, count=1, flags=re.M)
1083
+ open(spec, "w", encoding="utf-8").write(text)
1084
+ actual = hashlib.sha256(contract_of(text).encode("utf-8")).hexdigest()
1085
+ out.update(header_rewritten=True, doc_version=stamp_ver, spec_sha256=actual)
1032
1086
  av.setdefault("feature", feature); av.setdefault("active_change", "")
1033
- av["version"] = doc_ver or recorded_ver
1087
+ av["version"] = stamp_ver
1034
1088
  av["spec_sha256"] = actual; av["updated"] = now()
1035
1089
  open(avp, "w", encoding="utf-8").write(json.dumps(av, indent=2) + "\n")
1036
1090
  out.update(version=av["version"], state="stamped")
@@ -1039,7 +1093,7 @@ elif op == "append":
1039
1093
  # A version that names no ids is a bump nothing can reconcile against: every
1040
1094
  # story keeps its old stamp and the gap compounds at the next real change.
1041
1095
  bail("ledger-append: --ids is required — a version row that names no requirement "
1042
- "ids leaves update-stories nothing to act on", 2)
1096
+ "ids leaves sync-stories nothing to act on", 2)
1043
1097
  # The next number comes from the highest of all three places a version is written —
1044
1098
  # what the kit last recorded, what the document's header claims, and the newest row
1045
1099
  # actually in the table. A hand edit routinely moves one and not the others, and
@@ -1084,7 +1138,7 @@ elif op == "rowids":
1084
1138
  # for the reason the header of this file gives: a row the model DECLARED can omit an id
1085
1139
  # it moved, and an omitted id is silent. The v1.0 row was the one exception — written by
1086
1140
  # the author from a template whose placeholder literally reads "FR-001…FR-00n", which
1087
- # update-stories then has to be told not to trust. This op closes that gap: the caller
1141
+ # sync-stories then has to be told not to trust. This op closes that gap: the caller
1088
1142
  # diffs the finished document against nothing and hands the ids in, exactly as the
1089
1143
  # extend path does, so the first row is observed like all the rest.
1090
1144
  if not ids:
@@ -1211,6 +1265,60 @@ def scan(path):
1211
1265
  return out
1212
1266
  def ids(path):
1213
1267
  return {k: v[2] for k, v in scan(path).items()}
1268
+ # A DEFINITION THE SCAN CANNOT KEY IS A REQUIREMENT THAT CAN CHANGE WITH NO LEDGER RECORD OF
1269
+ # IT. The parser keys an id to the line that defines it and hashes the block under it; three
1270
+ # authoring forms fall outside that and each one is silent — the edit lands, change_count
1271
+ # stays 0, no row is appended, and spec-stamp re-baselines the new body as clean, for every
1272
+ # story citing that id. Reported rather than parsed around: widening the parser to accept
1273
+ # them would make the ledger's shapes whatever anyone happened to type, and the fix a person
1274
+ # wants here is to write the requirement in the form the template uses.
1275
+ LOOSE_DEF = re.compile(r'^\s*(?:[-*+]\s+)?([A-Z]{2}-\d+)\s*[:—–-]')
1276
+ def unkeyed_warnings(path, keyed):
1277
+ warn = []
1278
+ if not path or not os.path.isfile(path): return warn
1279
+ raw = COV.sub("", open(path, encoding="utf-8", errors="replace").read())
1280
+ hm = HIST.search(raw)
1281
+ above, below = (raw[:hm.start()], raw[hm.end():]) if hm else (raw, "")
1282
+ lines = above.split("\n")
1283
+ plain = []
1284
+ for line in lines:
1285
+ m = LOOSE_DEF.match(line)
1286
+ if m and m.group(1) not in keyed and m.group(1) not in plain: plain.append(m.group(1))
1287
+ if plain:
1288
+ warn.append("written without bold ids (`- %s: …` rather than `- **%s**: …`), so the "
1289
+ "diff cannot key them to a definition and an edit to one raises no "
1290
+ "ledger row: %s" % (plain[0], plain[0], ", ".join(sorted(plain))))
1291
+ if hm:
1292
+ low = []
1293
+ for line in below.split("\n"):
1294
+ m = DEF_CELL.match(line) or DEF_BULL.match(line) or LOOSE_DEF.match(line)
1295
+ if m and m.group(1) not in keyed and m.group(1) not in low: low.append(m.group(1))
1296
+ if low:
1297
+ warn.append("defined BELOW the '## Change History' table, where the scan stops "
1298
+ "— the ledger reads nothing under its own table, so these are "
1299
+ "invisible to every version comparison: %s" % ", ".join(sorted(low)))
1300
+ orphaned = []
1301
+ for n, line in enumerate(lines):
1302
+ m = DEF_CELL.match(line) or DEF_BULL.match(line) or DEF_OPEN.match(line)
1303
+ if not m: continue
1304
+ j = n + 1
1305
+ while (j < len(lines) and lines[j].strip()
1306
+ and not lines[j].lstrip().startswith("#") and not is_def(lines[j])):
1307
+ j += 1
1308
+ # j is the first line outside the hashed block. A BLANK there, followed by indented
1309
+ # prose that opens no new definition, is a continuation the hash cannot see.
1310
+ if j < len(lines) and not lines[j].strip():
1311
+ k = j + 1
1312
+ if (k < len(lines) and lines[k].strip()
1313
+ and (lines[k].startswith(" ") or lines[k].startswith("\t"))
1314
+ and not is_def(lines[k]) and not lines[k].lstrip().startswith("#")
1315
+ and m.group(1) not in orphaned):
1316
+ orphaned.append(m.group(1))
1317
+ if orphaned:
1318
+ warn.append("carry continuation text below a BLANK line — the hashed block ends at "
1319
+ "the blank, so anything under it can be rewritten with no diff: %s"
1320
+ % ", ".join(sorted(orphaned)))
1321
+ return warn
1214
1322
  # Ids the ledger has already spent. An id is PERMANENT: re-issuing one silently re-points
1215
1323
  # stories, designs and code that have already shipped. Read from the SNAPSHOT's history, so
1216
1324
  # it is what the ledger said before this run, and only meaningful when there is a snapshot.
@@ -1229,10 +1337,11 @@ reissued = sorted(set(added) & spent(snap))
1229
1337
  # THE STORY-FACING SUBSET. A story cites FR- and BR- ids and nothing else, so those are the
1230
1338
  # only classes the backlog can act on — the same scoping spec-coverage applies, for the same
1231
1339
  # reason. The scan is deliberately class-blind (CN-/DC-/IC-/UX-/SC- all move the contract and
1232
- # all belong in the ledger row), but handing that whole set to update-stories as "the
1340
+ # all belong in the ledger row), but handing that whole set to sync-stories as "the
1233
1341
  # requirements this run touched" asks it to raise a story for a success criterion.
1234
1342
  STORY_CLASS = ("FR-", "BR-")
1235
1343
  story_ids = [c for c in changed if c.startswith(STORY_CLASS)]
1344
+ warnings = unkeyed_warnings(spec, set(after))
1236
1345
  print(json.dumps({
1237
1346
  "ok": True, "had_snapshot": bool(snap and os.path.isfile(snap)),
1238
1347
  "added": added, "removed": removed, "modified": modified,
@@ -1252,9 +1361,15 @@ print(json.dumps({
1252
1361
  # spec on disk that the next run's entry check would refuse too.
1253
1362
  "reissued": reissued, "reissued_csv": ", ".join(reissued),
1254
1363
  "reissued_any": bool(reissued),
1255
- # changed, narrowed to the classes a story can cite — what update-stories works from.
1364
+ # changed, narrowed to the classes a story can cite — what sync-stories works from.
1256
1365
  "story_ids": story_ids, "story_ids_csv": ", ".join(story_ids),
1257
1366
  "story_id_count": len(story_ids),
1367
+ # Ids the document states in a form the ledger cannot key to a definition. Not a
1368
+ # verdict on this run's changes — a standing property of the document, reported every
1369
+ # time because the requirement it describes can move silently until it is rewritten.
1370
+ "warnings": warnings, "warning_count": len(warnings),
1371
+ "any_warnings": bool(warnings),
1372
+ "warnings_note": " // ".join(warnings),
1258
1373
  }))
1259
1374
  '@
1260
1375
 
@@ -1289,9 +1404,24 @@ def parse_fm(text):
1289
1404
  fm[key] = (fm[key] + ", " + im.group(1).strip()) if fm[key] else im.group(1).strip()
1290
1405
  return fm
1291
1406
 
1292
- def frontmatter(path):
1293
- try: return parse_fm(open(path, encoding="utf-8", errors="replace").read())
1294
- except Exception: return {}
1407
+ def read(path):
1408
+ try: return open(path, encoding="utf-8", errors="replace").read()
1409
+ except Exception: return ""
1410
+
1411
+ def bound_ids(fm, text):
1412
+ """The constraint ids this story is built to satisfy. Read from the `constraints:`
1413
+ FRONTMATTER field, which story-stamp lifts from the spec — the body's `## Constraints`
1414
+ section is model-authored prose, so an id the model left out of it would be invisible to
1415
+ exactly the scan that exists to notice a bound moving under someone.
1416
+
1417
+ ABSENT IS NOT EMPTY. A story written before the field existed has no key at all and its
1418
+ ids are still only in the body, so that case falls back to the section. An explicitly
1419
+ empty `constraints: []` is an answer — this story is bound by nothing — and is taken as
1420
+ one. The fallback goes when every live backlog has been re-stamped."""
1421
+ if "constraints" in fm:
1422
+ return sorted(set(re.findall(r'\b(?:CN|DC|IC|UX)-\d+', fm["constraints"])))
1423
+ bm = re.search(r'^##\s+Constraints\s*$(.*?)(?=^##\s|\Z)', text, re.M | re.S)
1424
+ return sorted(set(re.findall(r'\b(?:CN|DC|IC|UX)-\d+', bm.group(1)))) if bm else []
1295
1425
 
1296
1426
  stories = []
1297
1427
  if os.path.isdir(sdir):
@@ -1299,27 +1429,44 @@ if os.path.isdir(sdir):
1299
1429
  if not name.endswith(".md"): continue
1300
1430
  path = os.path.join(sdir, name)
1301
1431
  if not os.path.isfile(path): continue
1302
- fm = frontmatter(path)
1432
+ text = read(path); fm = parse_fm(text)
1303
1433
  sid = fm.get("id") or name[:-3]
1304
1434
  # An unparseable story is reported as open rather than skipped: a story the scan
1305
1435
  # cannot read is exactly the one whose requirements must not move unannounced.
1306
1436
  status = (fm.get("status") or "open").strip().lower()
1307
1437
  cites = [c.strip() for c in re.findall(r'[A-Z]{2}-\d+', fm.get("exercises", ""))]
1438
+ bounds = bound_ids(fm, text)
1308
1439
  stories.append({"id": sid, "status": status, "exercises": cites,
1440
+ "cites_csv": ", ".join(cites),
1441
+ "constraints": bounds,
1442
+ "constraints_csv": ", ".join(bounds),
1443
+ "carried": sorted(set(cites) | set(bounds)),
1444
+ "title": (fm.get("title") or "").strip().strip("[]"),
1445
+ "spec_version": (fm.get("spec_version") or "").strip(),
1446
+ "type": (fm.get("type") or "functional").strip().lower(),
1447
+ "follows": (fm.get("follows") or "").strip(),
1309
1448
  "in_flight": os.path.isdir(os.path.join(sdir, sid))})
1310
1449
 
1311
1450
  open_stories = [s for s in stories if s["status"] == "open"]
1451
+ # TWO SETS, DELIBERATELY DIFFERENT. `covered` is the DELIVERY relation — what open stories
1452
+ # are delivering — and analyze-slice subtracts it from a feature-scoped run as "these have
1453
+ # open stories" (law 39). A constraint is met, never delivered, so folding one in here would
1454
+ # drop a bound the code must still satisfy out of the feature gate's scope.
1455
+ # `carried` is the wider question specify has to ask: what would an open story FEEL if this
1456
+ # ran moved it. That one has to include the bounds, or amending a CN-/DC-/IC-/UX- disturbs
1457
+ # stories built against it and nothing anywhere says so (law 15).
1312
1458
  covered = sorted({c for s in open_stories for c in s["exercises"]})
1459
+ carried = sorted({c for s in open_stories for c in s["carried"]})
1313
1460
 
1314
1461
  # ASKING ABOUT NOTHING IS NOT ASKING ABOUT EVERYTHING. `--ids ""` is a caller saying "this
1315
1462
  # run disturbed no requirement" — a pure addition — and the answer is an empty set. Only
1316
1463
  # the absence of the flag means "tell me about the whole backlog". Conflating the two made
1317
1464
  # an enhancement that touched nothing existing prompt about every requirement with a story.
1318
- targets = queried if os.environ.get("AW_IDS_GIVEN") else covered
1465
+ targets = queried if os.environ.get("AW_IDS_GIVEN") else carried
1319
1466
 
1320
1467
  affected, aff_ids, aff_stories, inflight = [], [], [], []
1321
1468
  for rid in targets:
1322
- hit = [s for s in open_stories if rid in s["exercises"]]
1469
+ hit = [s for s in open_stories if rid in s["carried"]]
1323
1470
  if not hit: continue
1324
1471
  aff_ids.append(rid)
1325
1472
  names = [s["id"] for s in hit]
@@ -1327,11 +1474,33 @@ for rid in targets:
1327
1474
  aff_stories += names; inflight += flying
1328
1475
  affected.append({"id": rid, "stories": names, "in_flight": flying})
1329
1476
 
1477
+ # THE COMPLEMENT, NAMED. `affected` is "these ids have live work"; its complement is
1478
+ # "these ids have nobody on them", and that is the set sync-stories raises new stories for.
1479
+ # Derived here rather than in the caller because the orchestrator binds values and never
1480
+ # computes them, and a subtraction done in a prompt is a subtraction nothing can check.
1481
+ unlinked = [rid for rid in targets if rid not in aff_ids]
1482
+
1483
+ # One line per open story, for a prompt that has to ask about them. A story id on its own
1484
+ # is not something an author can answer about: what it cites and whether someone is already
1485
+ # implementing it are the whole basis of the decision.
1486
+ digest = "\n".join(
1487
+ " %-16s %-9s %-11s cites %s%s%s" % (
1488
+ s["id"], s["status"], "IN FLIGHT" if s["in_flight"] else "not started",
1489
+ s["cites_csv"] or "nothing",
1490
+ (" bound by " + s["constraints_csv"]) if s["constraints_csv"] else "",
1491
+ (" @ " + s["spec_version"]) if s["spec_version"] else "")
1492
+ for s in open_stories) or " (no open stories)"
1493
+
1330
1494
  print(json.dumps({
1331
1495
  "ok": True, "stories_dir": sdir, "stories_exist": os.path.isdir(sdir),
1332
1496
  "story_count": len(stories), "open_count": len(open_stories),
1497
+ "stories": stories, "digest": digest,
1333
1498
  "queried": queried, "covered": covered, "covered_csv": ", ".join(covered),
1499
+ "carried": carried, "carried_csv": ", ".join(carried),
1500
+ "carried_count": len(carried), "any_carried": bool(carried),
1334
1501
  "affected": affected, "affected_ids": aff_ids, "affected_csv": ", ".join(aff_ids),
1502
+ "unlinked": unlinked, "unlinked_csv": ", ".join(unlinked),
1503
+ "unlinked_count": len(unlinked), "any_unlinked": bool(unlinked),
1335
1504
  "story_csv": ", ".join(sorted(set(aff_stories))),
1336
1505
  "in_flight_csv": ", ".join(sorted(set(inflight))),
1337
1506
  "any": bool(aff_ids), "any_in_flight": bool(inflight),
@@ -1363,6 +1532,1175 @@ function Invoke-StoryRefs {
1363
1532
  # Fenced out of the ledger on purpose — spec-check, spec-diff and ledger-append all cut
1364
1533
  # the block out before they look, so writing it is not a spec edit and a story raised
1365
1534
  # against FR-003 does not read as FR-003 having changed.
1535
+ # ─────────────────────────────── ledger-read ───────────────────────────────
1536
+ # THE WORK SET: which requirements this sync has to account for. The ledger records what
1537
+ # each version touched and every story records the version it last synced at, so the
1538
+ # question "what has moved since the backlog was last in step" is answerable by reading
1539
+ # rows — no diffing, no hashing, no model.
1540
+ #
1541
+ # The set is the union of the ids named by every row ABOVE THE LOWEST spec_version across
1542
+ # the OPEN stories, not the ids of the newest row alone. Those are the same set whenever
1543
+ # the backlog is one version behind, which is the ordinary case; they diverge only when a
1544
+ # sync was skipped, and that is exactly the case worth getting right. Two specify runs
1545
+ # without a sync between them leave the middle version named by no row anyone reads, and
1546
+ # its requirements would get no story with nothing to say so — a silent gap, in the one
1547
+ # mechanism built to make gaps loud.
1548
+ #
1549
+ # THE v1.0 CASE (E42). At v1.0 nothing has moved yet: there is no "since" to read from. So
1550
+ # when no open story carries a readable spec version — an empty backlog, or stories written
1551
+ # before the field existed — the work set is every FR-/BR- the DOCUMENT declares, and the
1552
+ # per-id four-case table does the rest. A second run over the same spec then creates
1553
+ # nothing, because by then every id has a story.
1554
+ #
1555
+ # Scoped to FR-/BR- throughout, the same scoping spec-coverage applies: those are the only
1556
+ # classes a story's `exercises:` can name. CN-/DC-/IC-/UX- move the contract and belong in
1557
+ # the ledger row, but they are constraints a story CARRIES, not slices of work it delivers.
1558
+ $PyLedgerRead = @'
1559
+ import json, os, re, sys
1560
+ fd = os.environ["AW_FD"]
1561
+ spec = os.path.join(fd, "spec.md"); sdir = os.path.join(fd, "stories")
1562
+
1563
+ def bail(msg, code=1):
1564
+ print(json.dumps({"ok": False, "error": msg}))
1565
+ sys.stderr.write(msg + "\n"); sys.exit(code)
1566
+
1567
+ if not os.path.isfile(spec): bail("no spec.md at %s" % fd)
1568
+ text = open(spec, encoding="utf-8", errors="replace").read()
1569
+
1570
+ COV = re.compile(r'<!--\s*AW:COVERAGE:BEGIN\s*-->.*?<!--\s*AW:COVERAGE:END\s*-->', re.S)
1571
+
1572
+ def vtuple(v):
1573
+ m = re.match(r'v?(\d+)(?:\.(\d+))?', (v or "").strip())
1574
+ return (int(m.group(1)), int(m.group(2) or 0)) if m else (0, 0)
1575
+
1576
+ def rids(s):
1577
+ """FR-/BR- ids in order of appearance, deduped, then sorted by class and number so
1578
+ two callers reading the same row always produce the same csv."""
1579
+ seen, out = set(), []
1580
+ for t in re.findall(r'\b(?:FR|BR)-\d+', s or ""):
1581
+ if t not in seen: seen.add(t); out.append(t)
1582
+ return sorted(out, key=lambda r: (r.split("-")[0], int(r.split("-")[1])))
1583
+
1584
+ def nids(s):
1585
+ """The classes a row can name that a STORY cannot be raised for: the bounds a slice is
1586
+ built to satisfy and the outcomes the feature gate scores. Kept apart from rids()
1587
+ rather than widening it, because the work set drives story creation and a story for a
1588
+ success criterion is not a thing — but a row that moved one of these still has to be
1589
+ said out loud, and until now it produced an empty work set and a run that stopped with
1590
+ 'the backlog is already in step'."""
1591
+ seen, out = set(), []
1592
+ for t in re.findall(r'\b(?:CN|DC|IC|UX|SC)-\d+', s or ""):
1593
+ if t not in seen: seen.add(t); out.append(t)
1594
+ return sorted(out, key=lambda r: (r.split("-")[0], int(r.split("-")[1])))
1595
+
1596
+ def parse_fm(text):
1597
+ """Frontmatter as a flat dict. A value may be inline (`exercises: [FR-001, BR-002]`) or
1598
+ a YAML block list under an empty key — both are valid YAML and a hand edit produces
1599
+ either, so a parser that read only the inline form saw a perfectly good story as citing
1600
+ nothing, and a story citing nothing is invisible to every gate that exists to protect
1601
+ it. Block items are folded into the inline shape so every caller stays regex-simple."""
1602
+ m = re.match(r'^---\s*\n(.*?)\n---\s*\n', text, re.S)
1603
+ if not m: return {}
1604
+ fm, key, block = {}, None, set()
1605
+ for line in m.group(1).split("\n"):
1606
+ km = re.match(r'^([A-Za-z_]+):\s*(.*)$', line)
1607
+ if km:
1608
+ key = km.group(1); fm[key] = km.group(2).strip(); continue
1609
+ im = re.match(r'^\s+-\s+(.*)$', line) if key else None
1610
+ if im and (key in block or not fm[key]):
1611
+ block.add(key)
1612
+ fm[key] = (fm[key] + ", " + im.group(1).strip()) if fm[key] else im.group(1).strip()
1613
+ return fm
1614
+
1615
+ # THE LEDGER TABLE, located the same way _spec_ledger locates it — heading, separator rule,
1616
+ # then the rows under it, bounded by the next `## `. Any other section carries its own
1617
+ # table (Story Coverage does), and an unbounded search would read one of those as history.
1618
+ lines = text.split("\n")
1619
+ hi = next((i for i, l in enumerate(lines)
1620
+ if re.match(r'^##\s+Change History\s*$', l.strip())), -1)
1621
+ sec_end = (next((i for i in range(hi + 1, len(lines)) if lines[i].startswith("## ")),
1622
+ len(lines)) if hi >= 0 else -1)
1623
+ sep = (next((i for i in range(hi + 1, sec_end)
1624
+ if re.match(r'^\|[\s\-:|]+\|$', lines[i].strip())), -1) if hi >= 0 else -1)
1625
+ row_lines = [i for i in range(sep + 1, sec_end) if lines[i].lstrip().startswith("|")] if sep >= 0 else []
1626
+ has_ledger = hi >= 0 and sep >= 0
1627
+
1628
+ def cells(line):
1629
+ parts = re.split(r'(?<!\\)\|', line)
1630
+ return [c.strip().replace("\\|", "|") for c in parts[1:-1]] if len(parts) >= 3 else []
1631
+
1632
+ rows = []
1633
+ for i in row_lines:
1634
+ c = cells(lines[i]); c += [""] * (5 - len(c))
1635
+ # A row whose first cell is not a version is the template's own placeholder line, or a
1636
+ # note somebody left in the table. It records no version, so it orders against nothing.
1637
+ if not re.match(r'^v\d', c[0]): continue
1638
+ rows.append({"version": c[0], "date": c[1], "change": c[2], "ids_cell": c[3],
1639
+ "stories": c[4], "requirements": rids(c[3]),
1640
+ "non_story": nids(c[3])})
1641
+ rows.sort(key=lambda r: vtuple(r["version"]))
1642
+
1643
+ # WHAT THE DOCUMENT STILL DECLARES. Read from the requirement's DEFINING line — the bolded
1644
+ # id the template gives every requirement — and with the Change History cut away, so the
1645
+ # ids named in a row's own cell are never mistaken for requirements the spec carries.
1646
+ body = COV.sub("", text).split("\n## Change History")[0]
1647
+ declared = []
1648
+ for line in body.split("\n"):
1649
+ m = re.search(r'\*\*((?:FR|BR)-\d+)\*\*', line)
1650
+ if m and m.group(1) not in declared: declared.append(m.group(1))
1651
+ declared.sort(key=lambda r: (r.split("-")[0], int(r.split("-")[1])))
1652
+
1653
+ stories = []
1654
+ if os.path.isdir(sdir):
1655
+ for name in sorted(os.listdir(sdir)):
1656
+ if not name.endswith(".md"): continue
1657
+ p = os.path.join(sdir, name)
1658
+ if not os.path.isfile(p): continue
1659
+ fm = parse_fm(open(p, encoding="utf-8", errors="replace").read())
1660
+ sid = fm.get("id") or name[:-3]
1661
+ stories.append({"id": sid, "status": (fm.get("status") or "open").strip().lower(),
1662
+ "spec_version": (fm.get("spec_version") or "").strip(),
1663
+ "follows": (fm.get("follows") or "").strip(),
1664
+ "in_flight": os.path.isdir(os.path.join(sdir, sid)),
1665
+ "cites": rids(fm.get("exercises", ""))})
1666
+ open_stories = [s for s in stories if s["status"] == "open"]
1667
+
1668
+ # THE FLOOR is the oldest version any open story is still sitting at, and everything above
1669
+ # it is unsynced. A story whose spec_version is missing or unreadable counts as v0.0 rather
1670
+ # than being skipped: it has demonstrably never synced, and putting the whole ledger above
1671
+ # it is the same answer enumerating from the document would give.
1672
+ floors = [vtuple(s["spec_version"]) for s in open_stories]
1673
+ readable = [s for s in open_stories if re.match(r'^v?\d', s["spec_version"] or "")]
1674
+ # A BACKLOG THAT IS ENTIRELY CLOSED IS NOT A BACKLOG THAT NEVER SYNCED. Reading the floor
1675
+ # from open stories alone made the last story closing look exactly like a feature nobody has
1676
+ # ever sliced: no floor took the enumerate-the-whole-document branch below, so one idle
1677
+ # re-run after finishing a feature raised a fresh story for every requirement in the spec —
1678
+ # each one reported as work the contract had moved on, when nothing had moved at all. A
1679
+ # CLOSED story carries a stamp too, and it records which version its work was measured
1680
+ # against. CANCELLED ones are excluded: abandoned work delivered nothing and settles nothing,
1681
+ # so it establishes no floor and leaves its requirements to be sliced again.
1682
+ closed_stories = [s for s in stories if s["status"] == "closed"]
1683
+ floor_source = "open" if floors else ("closed" if closed_stories else "none")
1684
+ floor = (min(floors) if floors
1685
+ else (min(vtuple(s["spec_version"]) for s in closed_stories) if closed_stories
1686
+ else None))
1687
+
1688
+ latest = rows[-1] if rows else None
1689
+ out = {"ok": True, "feature_dir": fd, "has_ledger": has_ledger,
1690
+ "row_count": len(rows), "ledger_empty": len(rows) == 0,
1691
+ "rows": rows,
1692
+ "latest_version": latest["version"] if latest else "",
1693
+ "latest_change": latest["change"] if latest else "",
1694
+ "latest_ids_csv": ", ".join(latest["requirements"]) if latest else "",
1695
+ "spec_ids_csv": ", ".join(declared), "spec_id_count": len(declared),
1696
+ "story_count": len(stories), "open_count": len(open_stories),
1697
+ "unversioned_open": len(open_stories) - len(readable)}
1698
+
1699
+ if not has_ledger:
1700
+ out.update(ok=False, error="spec.md has no '## Change History' table. That table is "
1701
+ "where a story learns a requirement it cites has moved, so a spec without "
1702
+ "one cannot be kept in step with its backlog.")
1703
+ print(json.dumps(out)); sys.stderr.write(out["error"] + "\n"); sys.exit(2)
1704
+
1705
+ if not rows:
1706
+ # An empty ledger is not corruption — it is a spec that has never been versioned, which
1707
+ # means specify has not finished with it. Reported, not raised: the caller warns and
1708
+ # stops, because there is no "since" to sync from and inventing one would raise a
1709
+ # backlog against a document nobody has committed to.
1710
+ out.update(work_csv="", work_count=0, work_source="none", span_versions_csv="",
1711
+ gap=False, removed_csv="",
1712
+ non_story_csv="", non_story_count=0, non_story_any=False,
1713
+ work_kind="none",
1714
+ work_note="the Change History table carries no version row")
1715
+ print(json.dumps(out)); sys.exit(0)
1716
+
1717
+ if floor is None:
1718
+ # E42 — nothing has moved because nothing has synced. Enumerate from the document.
1719
+ source, span = "spec", []
1720
+ candidates = list(declared)
1721
+ note = ("nothing has synced against this spec yet — no open story records a version and "
1722
+ "nothing has closed against it — so there is no 'since' to read from: the work "
1723
+ "set is every requirement the document declares, and the per-id rules then "
1724
+ "create only what has no story")
1725
+ else:
1726
+ span = [r for r in rows if vtuple(r["version"]) > floor]
1727
+ seen, candidates = set(), []
1728
+ for r in span:
1729
+ for rid in r["requirements"]:
1730
+ if rid not in seen: seen.add(rid); candidates.append(rid)
1731
+ candidates.sort(key=lambda r: (r.split("-")[0], int(r.split("-")[1])))
1732
+ source = "ledger"
1733
+ note = ("%d version row(s) above the oldest %s story's v%d.%d: %s"
1734
+ % (len(span), floor_source, floor[0], floor[1],
1735
+ ", ".join(r["version"] for r in span) or "none"))
1736
+
1737
+ # THE SPAN IS A PREFILTER; STALENESS IS PER ID. The floor is the oldest version any open
1738
+ # story sits at, and a story whose requirements never move sits there forever — Order-001
1739
+ # holding v1.0 keeps v1.1 and v1.2 in the span long after everything they named has been
1740
+ # synced. Reading the span alone therefore re-offered the same requirements on every run,
1741
+ # and each re-offer is a model call rewriting a story that was already in step.
1742
+ #
1743
+ # So the span says which ids are WORTH CHECKING and this says which have actually moved
1744
+ # under someone: an id is stale when it has no open story at all, or when some open story
1745
+ # citing it is stamped BELOW the newest version that touched it. An id whose every open
1746
+ # story is at or above that version is in step, whatever the floor says.
1747
+ moved_at = {}
1748
+ for r in rows:
1749
+ for rid in r["requirements"]:
1750
+ v = vtuple(r["version"])
1751
+ if v > moved_at.get(rid, (0, 0)): moved_at[rid] = v
1752
+
1753
+ def carried_on(story_id, rid, at):
1754
+ """Has a follow-on already taken this requirement off that story's hands, at or above
1755
+ the version that moved it. The `follows` link is the whole record of that hand-off."""
1756
+ return any(s["follows"] == story_id and rid in s["cites"]
1757
+ and vtuple(s["spec_version"]) >= at for s in open_stories)
1758
+
1759
+ work, in_step = [], []
1760
+ for rid in candidates:
1761
+ holders = [s for s in open_stories if rid in s["cites"]]
1762
+ at = moved_at.get(rid, (0, 0))
1763
+ behind = []
1764
+ for s in holders:
1765
+ if vtuple(s["spec_version"]) >= at: continue
1766
+ # AN IN-FLIGHT STORY CANNOT BE BROUGHT UP TO DATE, BY DESIGN. It is never rewritten
1767
+ # (§5.5), so its spec_version can never rise, so reading it as a staleness signal
1768
+ # gives a signal that never clears — and a sync that mints a fresh follow-on for the
1769
+ # same requirement on every run. What clears it is the follow-on itself: once one
1770
+ # exists carrying this id at or above the version that moved it, the hand-off has
1771
+ # happened and the original is history in progress, not unfinished business.
1772
+ if s["in_flight"] and carried_on(s["id"], rid, at): continue
1773
+ behind.append(s["id"])
1774
+ # A CLOSED STORY STAMPED AT OR ABOVE THE VERSION THAT LAST MOVED THIS REQUIREMENT
1775
+ # DELIVERED THE WORDING THE SPEC ASKS FOR TODAY, so the requirement is FINISHED rather
1776
+ # than unsliced. Reading "no open story cites it" as work on its own could not tell those
1777
+ # two apart, which is what let a fully delivered feature re-raise its entire backlog.
1778
+ # A closed story stamped BELOW that version is the other case and stays work: the
1779
+ # contract moved after it shipped, so what shipped is no longer what the spec asks for,
1780
+ # and backlog-plan names the closed story it is re-opening against.
1781
+ delivered = any(rid in s["cites"] and vtuple(s["spec_version"]) >= at
1782
+ for s in closed_stories)
1783
+ (in_step if ((holders and not behind) or (not holders and delivered))
1784
+ else work).append(rid)
1785
+
1786
+ # A row names what a version TOUCHED, and that includes ids it REMOVED. A removed
1787
+ # requirement has no wording left to write a story from, so it leaves the work set — but it
1788
+ # is reported, because every open story citing one is orphaned and that is a decision for a
1789
+ # person, not a default (E1).
1790
+ removed = [i for i in work if i not in declared]
1791
+ work = [i for i in work if i in declared]
1792
+
1793
+ # WHAT MOVED THAT NO STORY CAN BE RAISED FOR. Constraints and success criteria travel in
1794
+ # the same version rows as requirements and are read by the same downstream gates, but they
1795
+ # produce no work set — so a row naming only those left this run stopping at "the backlog is
1796
+ # already in step. Nothing was written." about the exact ids story-plan-check had just
1797
+ # reported as stale. Carried out separately so the caller can say so without the work gate
1798
+ # having to admit ids it must not slice.
1799
+ #
1800
+ # work_kind IS FOR THE LOG, NOT FOR THE BRANCH. A row naming FR-001 AND CN-001 is
1801
+ # `story` — the work set is real — and branching on the enum alone would print the
1802
+ # requirement path, sync the stories, and say nothing at all about the constraint. The
1803
+ # caller announces on non_story_csv being non-empty, whatever work_any says.
1804
+ non_story = sorted({i for r in span for i in r["non_story"]},
1805
+ key=lambda r: (r.split("-")[0], int(r.split("-")[1])))
1806
+ work_kind = ("story" if work else ("non_story" if non_story else "none"))
1807
+
1808
+ out.update(work_csv=", ".join(work), work_count=len(work), work_source=source,
1809
+ work_note=note, work_any=bool(work),
1810
+ non_story_csv=", ".join(non_story), non_story_count=len(non_story),
1811
+ non_story_any=bool(non_story), work_kind=work_kind,
1812
+ candidates_csv=", ".join(candidates), candidate_count=len(candidates),
1813
+ in_step_csv=", ".join(in_step), in_step_count=len(in_step),
1814
+ floor_source=floor_source,
1815
+ span_versions_csv=", ".join(r["version"] for r in span),
1816
+ span_count=len(span), gap=len(span) > 1,
1817
+ removed_csv=", ".join(removed), removed_count=len(removed),
1818
+ synced_floor=("v%d.%d" % floor) if floor else "")
1819
+ print(json.dumps(out))
1820
+ '@
1821
+
1822
+ function Invoke-LedgerRead {
1823
+ param([string[]]$Rest)
1824
+ $fdArg = ''
1825
+ for ($i = 0; $i -lt $Rest.Count; $i++) {
1826
+ switch ($Rest[$i]) { '--feature-dir' { $fdArg = $Rest[++$i] } }
1827
+ }
1828
+ $repo = Get-RepoRoot
1829
+ $fd = Resolve-FeatureDir -Arg $fdArg -RepoRoot $repo
1830
+ if (-not $fd) { Write-Error 'ledger-read: no feature set and no --feature-dir'; exit 1 }
1831
+ $py = Get-Py; if (-not $py) { Write-Error 'ledger-read: python3 required'; exit 1 }
1832
+ $env:AW_FD = $fd
1833
+ $PyLedgerRead | & $py -
1834
+ }
1835
+
1836
+ # ─────────────────────────────── slice-mode ────────────────────────────────
1837
+ # Which slicing strategy the launch line asked for, and what is left of the input once that
1838
+ # word is taken out of it. Its own op rather than a `condition:` in the workflow, because
1839
+ # the engine compares a whole rendered value: `{{USER_INPUT}} == single-run` only matches an
1840
+ # input carrying the strategy and no guidance at all, and `sync-stories single-run keep the
1841
+ # payment rules together` — the form the launch line documents — would silently slice by
1842
+ # default while looking as though it had been told not to.
1843
+ #
1844
+ # ONLY THE FIRST WORD IS A STRATEGY. Guidance is free prose, and "keep the single sign-on
1845
+ # requirements in one story" is a slicing instruction with the token sitting in the middle
1846
+ # of it. Reading the token anywhere in the string would turn that sentence into the opposite
1847
+ # of what it asks, with nothing to say so.
1848
+ $PySliceMode = @'
1849
+ import json, os, re
1850
+ raw = (os.environ.get("AW_INPUT", "") or "").strip()
1851
+
1852
+ # `single-run` is the spelling the launch line documents; the others are what people write
1853
+ # when they mean it. `auto` is the default and is accepted explicitly so a launch line can
1854
+ # say so — a strategy nobody can name is one nobody can turn off.
1855
+ TOKENS = {"single-run": "single", "single-story": "single", "single": "single",
1856
+ "one-story": "single", "auto": "auto", "per-slice": "auto", "default": "auto"}
1857
+
1858
+ strategy, guidance = "auto", raw
1859
+ m = re.match(r'^([A-Za-z][A-Za-z0-9_-]*)\s*[:,]?\s*(.*)$', raw, re.S)
1860
+ if m and m.group(1).lower() in TOKENS:
1861
+ strategy = TOKENS[m.group(1).lower()]
1862
+ guidance = m.group(2).strip()
1863
+
1864
+ if strategy == "single":
1865
+ note = ("one story was asked for (single-run): the whole work set goes into a single "
1866
+ "slice unless it is too heavy to be picked up as one piece of work, in which "
1867
+ "case it is split along its dependencies and the split is reported")
1868
+ else:
1869
+ note = "the slicing is decided from the requirements themselves"
1870
+
1871
+ print(json.dumps({"ok": True, "strategy": strategy, "guidance": guidance,
1872
+ "single": strategy == "single", "note": note,
1873
+ "raw": raw, "tokens": sorted(TOKENS)}))
1874
+ '@
1875
+
1876
+ function Invoke-SliceMode {
1877
+ param([string[]]$Rest)
1878
+ $input_ = ''
1879
+ for ($i = 0; $i -lt $Rest.Count; $i++) {
1880
+ switch ($Rest[$i]) {
1881
+ '--input' { $input_ = $Rest[++$i] }
1882
+ }
1883
+ }
1884
+ $py = Get-Py; if (-not $py) { Write-Error 'slice-mode: python3 required'; exit 1 }
1885
+ $env:AW_INPUT = $input_
1886
+ $PySliceMode | & $py -
1887
+ }
1888
+
1889
+ # ─────────────────────────────── backlog-plan ──────────────────────────────
1890
+ # The grouping is a judgment; everything that follows from it is arithmetic. This op does
1891
+ # the arithmetic, in two modes over the same inputs so the two passes cannot disagree about
1892
+ # what a group contains:
1893
+ #
1894
+ # scan which OPEN stories already stand in front of a group's requirements — the
1895
+ # candidates the author is asked about, and the wording of that question.
1896
+ # plan given the author's answer, the flat list of story files to write: one entry per
1897
+ # file, each already carrying its id, its path, and the ids it must end up citing.
1898
+ #
1899
+ # THE FOUR CASES (§5.4) resolve per group, not per requirement, because a group IS the story:
1900
+ #
1901
+ # no open story cites anything in the group -> create
1902
+ # an open story does, no stories/<ID>/ yet -> update in place (asked)
1903
+ # an open story does, a story plan already exists -> mint a follow-on (asked); the
1904
+ # original is never rewritten (§5.5)
1905
+ # the author declines -> that story is left alone AND the ids
1906
+ # it covers leave the group; whatever
1907
+ # remains becomes a new story
1908
+ #
1909
+ # The last line is the one worth reading twice. Declining does not abandon the group — it
1910
+ # withdraws the requirements that story is already carrying and creates a story for the
1911
+ # rest. A group of three where one id has a story the author will not touch still delivers
1912
+ # the other two.
1913
+ #
1914
+ # ONE GROUP, ONE ABSORBING STORY. Where the author approves two stories in the same group,
1915
+ # the first by id takes the group's unclaimed requirements and the others are refreshed
1916
+ # against the current spec without gaining ids. Two stories both claiming the same new
1917
+ # requirement is not a state the completeness rule can read.
1918
+ #
1919
+ # AND THE ORDER. Plan mode also resolves the dependency edges the grouping declared between
1920
+ # slices, folds in the `depends_on:` an updated story already carries, breaks any cycle, and
1921
+ # lays the result out in WAVES: wave N holds the stories whose every dependency sits below N,
1922
+ # so one wave is a set with no ordering between its members — they may be picked up in
1923
+ # parallel. The plan comes back sorted by wave, which is also the order the stories are
1924
+ # written in, so meeting the cap costs the LAST wave rather than an arbitrary slice of the
1925
+ # backlog. See the block above the wave computation for why `follows:` is not an edge.
1926
+ $PyBacklogPlan = @'
1927
+ import json, os, re, sys
1928
+ fd = os.environ["AW_FD"]; mode = os.environ.get("AW_MODE", "scan")
1929
+ sdir = os.path.join(fd, "stories")
1930
+ feature = os.path.basename(fd.rstrip("/\\"))
1931
+
1932
+ def bail(msg, code=2):
1933
+ print(json.dumps({"ok": False, "error": msg}))
1934
+ sys.stderr.write(msg + "\n"); sys.exit(code)
1935
+
1936
+ def rids(s):
1937
+ seen, out = set(), []
1938
+ for t in re.findall(r'\b(?:FR|BR)-\d+', s or ""):
1939
+ if t not in seen: seen.add(t); out.append(t)
1940
+ return sorted(out, key=lambda r: (r.split("-")[0], int(r.split("-")[1])))
1941
+
1942
+ def sids(s):
1943
+ """Story ids out of a csv, a JSON list or a YAML inline list. A story id is a feature
1944
+ name and a number; a template placeholder (`[]`, `[STORY-ID]`) is neither, and must
1945
+ never become a dependency edge nobody can resolve."""
1946
+ seen, out = set(), []
1947
+ for t in re.split(r'[,\s\[\]"\']+', s or ""):
1948
+ t = t.strip()
1949
+ if re.match(r'^[A-Za-z][\w.]*-\d+$', t) and t not in seen:
1950
+ seen.add(t); out.append(t)
1951
+ return out
1952
+
1953
+ def wave_of(s):
1954
+ """A story's declared wave. Absent — a story written before the field existed — reads
1955
+ as 1, the conservative floor: nothing is KNOWN to have to land before it."""
1956
+ m = re.match(r'^\s*(\d+)\s*$', (s or "").strip())
1957
+ return int(m.group(1)) if m else 1
1958
+
1959
+ def names(s):
1960
+ """Story ids out of a csv or a JSON list. A multi-select answer arrives as the engine's
1961
+ JSON rendering of a list, so both spellings have to read the same."""
1962
+ seen, out = set(), []
1963
+ for t in re.split(r'[,\s\[\]"\']+', s or ""):
1964
+ t = t.strip()
1965
+ if t and t not in seen: seen.add(t); out.append(t)
1966
+ return out
1967
+
1968
+ def parse_fm(text):
1969
+ """Frontmatter as a flat dict. A value may be inline (`exercises: [FR-001, BR-002]`) or
1970
+ a YAML block list under an empty key — both are valid YAML and a hand edit produces
1971
+ either, so a parser that read only the inline form saw a perfectly good story as citing
1972
+ nothing, and a story citing nothing is invisible to every gate that exists to protect
1973
+ it. Block items are folded into the inline shape so every caller stays regex-simple."""
1974
+ m = re.match(r'^---\s*\n(.*?)\n---\s*\n', text, re.S)
1975
+ if not m: return {}
1976
+ fm, key, block = {}, None, set()
1977
+ for line in m.group(1).split("\n"):
1978
+ km = re.match(r'^([A-Za-z_]+):\s*(.*)$', line)
1979
+ if km:
1980
+ key = km.group(1); fm[key] = km.group(2).strip(); continue
1981
+ im = re.match(r'^\s+-\s+(.*)$', line) if key else None
1982
+ if im and (key in block or not fm[key]):
1983
+ block.add(key)
1984
+ fm[key] = (fm[key] + ", " + im.group(1).strip()) if fm[key] else im.group(1).strip()
1985
+ return fm
1986
+
1987
+ # ---- the backlog -----------------------------------------------------------------
1988
+ stories, used_numbers = [], []
1989
+ if os.path.isdir(sdir):
1990
+ for name in sorted(os.listdir(sdir)):
1991
+ if not name.endswith(".md"): continue
1992
+ p = os.path.join(sdir, name)
1993
+ if not os.path.isfile(p): continue
1994
+ fm = parse_fm(open(p, encoding="utf-8", errors="replace").read())
1995
+ sid = fm.get("id") or name[:-3]
1996
+ # Numbers come from the FILENAME as well as the id, and from CLOSED and CANCELLED
1997
+ # stories as well as open ones. An id is permanent once minted: re-issuing the
1998
+ # number of a story that shipped re-points its execution artefacts at new work.
1999
+ for cand in (sid, name[:-3]):
2000
+ m = re.search(r'-(\d+)$', cand)
2001
+ if m: used_numbers.append(int(m.group(1)))
2002
+ stories.append({"id": sid, "status": (fm.get("status") or "open").strip().lower(),
2003
+ "title": (fm.get("title") or "").strip().strip("[]"),
2004
+ "spec_version": (fm.get("spec_version") or "").strip(),
2005
+ "cites": rids(fm.get("exercises", "")),
2006
+ "wave": wave_of(fm.get("wave", "")),
2007
+ "deps": sids(fm.get("depends_on", "")),
2008
+ "in_flight": os.path.isdir(os.path.join(sdir, sid)),
2009
+ "path": p})
2010
+ open_stories = [s for s in stories if s["status"] == "open"]
2011
+ # Closed and cancelled stories hold no requirement — completeness is "no OPEN stories" —
2012
+ # but they are the reason a create can look like duplicated work, so they are read in
2013
+ # order to say so. See the create branch below.
2014
+ done_stories = [s for s in stories if s["status"] != "open"]
2015
+ by_id = {s["id"]: s for s in stories}
2016
+ _next = [max(used_numbers) + 1 if used_numbers else 1]
2017
+
2018
+ def mint():
2019
+ n = _next[0]; _next[0] += 1
2020
+ return "%s-%03d" % (feature, n)
2021
+
2022
+ # ---- the groups ------------------------------------------------------------------
2023
+ raw = (os.environ.get("AW_GROUPS") or "").strip()
2024
+ try:
2025
+ parsed = json.loads(raw) if raw else []
2026
+ except Exception as e:
2027
+ bail("backlog-plan: --groups is not valid JSON (%s)" % e)
2028
+ if isinstance(parsed, dict): parsed = parsed.get("groups") or []
2029
+ if not isinstance(parsed, list):
2030
+ bail("backlog-plan: --groups must be a JSON list of groups")
2031
+
2032
+ # Ids are read from the group's OWN requirements field, never scraped from its prose. A
2033
+ # rationale that mentions FR-004 as the reason two others belong together would otherwise
2034
+ # pull a third requirement into the story, and nothing downstream would question it.
2035
+ work = rids(os.environ.get("AW_WORK", ""))
2036
+ groups, dropped = [], []
2037
+ for i, g in enumerate(parsed):
2038
+ if not isinstance(g, dict): continue
2039
+ src = g.get("requirements")
2040
+ if isinstance(src, list): src = ", ".join(str(x) for x in src)
2041
+ ids = rids(src if src is not None else g.get("requirements_csv", ""))
2042
+ if work:
2043
+ outside = [x for x in ids if x not in work]
2044
+ dropped += outside
2045
+ ids = [x for x in ids if x in work]
2046
+ if not ids: continue
2047
+ # `depends_on` names OTHER GROUPS by key, or open stories already in the backlog by
2048
+ # id. Kept as raw tokens: a group key only becomes a story id once the plan has minted
2049
+ # one, so resolving here would have to guess at a name that does not exist yet.
2050
+ dep_src = g.get("depends_on")
2051
+ if dep_src is None: dep_src = g.get("depends_on_csv")
2052
+ if isinstance(dep_src, list): dep_src = ", ".join(str(x) for x in dep_src)
2053
+ deps_raw = [x for x in re.split(r'[,\s\[\]"\']+', str(dep_src or "")) if x.strip()]
2054
+ groups.append({"key": g.get("id") or ("g%d" % (i + 1)),
2055
+ "title": (g.get("title") or "").strip(),
2056
+ "rationale": (g.get("rationale") or "").strip(),
2057
+ "complexity": (g.get("complexity") or "").strip().lower(),
2058
+ "deps_raw": deps_raw,
2059
+ "ids": ids, "ids_csv": ", ".join(ids)})
2060
+
2061
+ # Every work-set id must land in exactly one group. One the model left out gets no story
2062
+ # and nothing says so; one it repeated gets two, each claiming the same requirement.
2063
+ placed = [x for g in groups for x in g["ids"]]
2064
+ repeated = sorted({x for x in placed if placed.count(x) > 1})
2065
+
2066
+ # A REPEATED ID IS RESOLVED HERE, not merely reported. Two groups both claiming one
2067
+ # requirement become two stories both claiming it, and "does this requirement still have
2068
+ # open stories" — the completeness rule — then answers for work that was never really
2069
+ # duplicated. The grouping is a judgment; the arithmetic over it is not. So the id stays in
2070
+ # the FIRST group that claimed it and leaves the rest, which is deterministic (the same
2071
+ # grouping always yields the same slices) and loses no coverage, because the id still
2072
+ # reaches exactly one story. repeated_notice reports what that touched.
2073
+ if repeated:
2074
+ seen_ids = set()
2075
+ for g in groups:
2076
+ keep_ids = [x for x in g["ids"] if x not in seen_ids]
2077
+ seen_ids.update(keep_ids)
2078
+ g["ids"], g["ids_csv"] = keep_ids, ", ".join(keep_ids)
2079
+ groups = [g for g in groups if g["ids"]]
2080
+ placed = [x for g in groups for x in g["ids"]]
2081
+
2082
+ missed = [x for x in work if x not in placed]
2083
+
2084
+ def candidates_of(g):
2085
+ """Open stories standing in front of this group, each with what it already covers OF
2086
+ THIS GROUP — the intersection, not its whole citation list, because that is what the
2087
+ author is being asked to move."""
2088
+ out = []
2089
+ for s in open_stories:
2090
+ shared = [x for x in g["ids"] if x in s["cites"]]
2091
+ if not shared: continue
2092
+ out.append({"story": s["id"], "title": s["title"], "in_flight": s["in_flight"],
2093
+ "spec_version": s["spec_version"], "cites_csv": ", ".join(s["cites"]),
2094
+ "shared_csv": ", ".join(shared), "shared": shared,
2095
+ "group": g["key"], "group_title": g["title"], "group_ids_csv": g["ids_csv"],
2096
+ "action": "followon" if s["in_flight"] else "update"})
2097
+ return sorted(out, key=lambda c: c["story"])
2098
+
2099
+ base = {"ok": True, "feature": feature, "feature_dir": fd, "stories_dir": sdir,
2100
+ "group_count": len(groups), "groups": groups,
2101
+ "work_csv": ", ".join(work),
2102
+ "unplaced_csv": ", ".join(missed), "unplaced_count": len(missed),
2103
+ "repeated_csv": ", ".join(repeated), "repeated_count": len(repeated),
2104
+ "dropped_csv": ", ".join(sorted(set(dropped))),
2105
+ "groups_digest": "\n".join(
2106
+ " [%s] %s\n requirements: %s%s%s"
2107
+ % (g["key"], g["title"] or "(untitled)", g["ids_csv"],
2108
+ ("\n stands behind: " + ", ".join(g["deps_raw"])) if g["deps_raw"] else "",
2109
+ ("\n " + g["rationale"]) if g["rationale"] else "")
2110
+ for g in groups) or " (no groups)"}
2111
+
2112
+ # THE STRATEGY IS THE AUTHOR'S; THE ARITHMETIC OVER IT IS NOT. `single` asked for one story
2113
+ # covering the whole work set, and the grouping may still have returned several — because a
2114
+ # slice nobody can pick up is not a story, and splitting it is the honest answer. So the
2115
+ # split is REPORTED rather than refused or hidden: quietly handing six stories to someone
2116
+ # who asked for one is the kind of silent disobedience that makes an option not worth having.
2117
+ strategy = (os.environ.get("AW_STRATEGY") or "").strip().lower() or "auto"
2118
+ try:
2119
+ ceiling = int((os.environ.get("AW_CEILING") or "").strip() or 8)
2120
+ except ValueError:
2121
+ ceiling = 8
2122
+ oversized = [g["key"] for g in groups if len(g["ids"]) > ceiling]
2123
+ split_note, split_count = "", 0
2124
+ if strategy == "single" and len(groups) > 1:
2125
+ split_count = len(groups)
2126
+ split_note = ("one story was asked for and the work set was too heavy for one: it is "
2127
+ "split into %d, in dependency order — %s" % (len(groups), "; ".join(
2128
+ "[%s] %s (%s)" % (g["key"], g["title"] or "untitled", g["ids_csv"])
2129
+ for g in groups)))
2130
+ elif strategy == "single" and len(groups) == 1:
2131
+ split_note = ("one story was asked for and one covers the whole work set: %s"
2132
+ % groups[0]["ids_csv"])
2133
+ base.update(strategy=strategy, ceiling=ceiling, split_count=split_count,
2134
+ split_note=split_note, oversized_csv=", ".join(oversized))
2135
+
2136
+ if mode == "scan":
2137
+ cands = [c for g in groups for c in candidates_of(g)]
2138
+ lines = []
2139
+ for c in cands:
2140
+ lines.append(
2141
+ " %s (%s)\n"
2142
+ " group [%s] %s covers %s\n"
2143
+ " this story already covers %s of it, and cites %s in total\n"
2144
+ " %s"
2145
+ % (c["story"], c["title"] or "untitled",
2146
+ c["group"], c["group_title"] or "", c["group_ids_csv"],
2147
+ c["shared_csv"], c["cites_csv"],
2148
+ ("ALREADY IN FLIGHT (story plan exists) — picking it mints a FOLLOW-ON "
2149
+ "carrying the change; this story is never rewritten"
2150
+ if c["in_flight"] else
2151
+ "not started (no story plan yet) — picking it rewrites this story to "
2152
+ "cover the whole group")))
2153
+ base.update(candidates=cands, candidate_count=len(cands),
2154
+ candidate_ids=[c["story"] for c in cands],
2155
+ candidate_csv=", ".join(c["story"] for c in cands),
2156
+ any_candidates=bool(cands),
2157
+ ask_digest="\n".join(lines) or " (no existing story covers any of these)")
2158
+ print(json.dumps(base)); sys.exit(0)
2159
+
2160
+ # ---- plan ------------------------------------------------------------------------
2161
+ approved = set(names(os.environ.get("AW_OK", "")))
2162
+ version = (os.environ.get("AW_VER") or "").strip()
2163
+ plan, skipped, notes = [], [], []
2164
+ for g in groups:
2165
+ cands = candidates_of(g)
2166
+ declined = [c for c in cands if c["story"] not in approved]
2167
+ # A declined story keeps its requirements: the author said do not disturb it, and
2168
+ # raising a second story over the same ids disturbs it just as thoroughly.
2169
+ held = {x for c in declined for x in c["shared"]}
2170
+ skipped += [c["story"] for c in declined]
2171
+ remaining = [x for x in g["ids"] if x not in held]
2172
+ taken = [c for c in cands if c["story"] in approved]
2173
+
2174
+ if taken:
2175
+ # ONE APPROVED STORY ABSORBS THE GROUP'S UNCLAIMED REQUIREMENTS — the first by id.
2176
+ # Every OTHER approved story keeps exactly the ids it already cites, so those ids
2177
+ # are RESERVED out of what the carrier gains: two open stories both claiming one
2178
+ # requirement is not a state the completeness rule can read, and the run would have
2179
+ # created that state itself rather than merely reporting it.
2180
+ carrier = taken[0]; s = by_id[carrier["story"]]
2181
+ reserved = {x for c in taken[1:] for x in c["shared"]}
2182
+ gained = [x for x in remaining if x not in reserved]
2183
+ if carrier["in_flight"]:
2184
+ # §5.5 — the original stays open and unchanged, and closes having delivered
2185
+ # what it was written to deliver. The follow-on carries the remainder.
2186
+ carry = [x for x in g["ids"] if x in s["cites"] or x in gained]
2187
+ carry = [x for x in carry if x not in held]
2188
+ sid = mint()
2189
+ plan.append({"action": "followon", "story": sid, "follows": carrier["story"],
2190
+ "path": os.path.join(sdir, sid + ".md"),
2191
+ "requirements_csv": ", ".join(carry), "existing_csv": "",
2192
+ "prior_csv": ", ".join(s["cites"]), "prior_title": s["title"],
2193
+ "prior_path": s["path"],
2194
+ "group": g["key"], "group_title": g["title"],
2195
+ "group_ids_csv": g["ids_csv"], "complexity": g["complexity"],
2196
+ "rationale": g["rationale"], "spec_version": version})
2197
+ else:
2198
+ keep = sorted(set(s["cites"]) | set(gained),
2199
+ key=lambda r: (r.split("-")[0], int(r.split("-")[1])))
2200
+ plan.append({"action": "update", "story": s["id"], "follows": "",
2201
+ "path": s["path"],
2202
+ "requirements_csv": ", ".join(keep),
2203
+ "existing_csv": ", ".join(s["cites"]),
2204
+ "prior_csv": ", ".join(s["cites"]), "prior_title": s["title"],
2205
+ "prior_path": s["path"],
2206
+ "group": g["key"], "group_title": g["title"],
2207
+ "group_ids_csv": g["ids_csv"], "complexity": g["complexity"],
2208
+ "rationale": g["rationale"], "spec_version": version})
2209
+ carrier_sid = plan[-1]["story"]
2210
+ for c in taken[1:]:
2211
+ s2 = by_id[c["story"]]
2212
+ if c["in_flight"]:
2213
+ # AN IN-FLIGHT STORY IS NEVER REWRITTEN, whatever position it holds in the
2214
+ # group. Its story plan was derived from this body, and
2215
+ # rewriting the body leaves the three disagreeing with nothing to say so —
2216
+ # which is the whole reason §5.5 exists. Being second in a group is not a
2217
+ # different situation from being first, so it gets the same answer: its own
2218
+ # follow-on, carrying the ids it already covers of this group.
2219
+ #
2220
+ # That link is also what clears its staleness. ledger-read discounts an
2221
+ # in-flight story once an open story whose `follows` names it cites the same
2222
+ # id; skipping it instead would leave it stale forever and re-offered on
2223
+ # every run.
2224
+ carry2 = [x for x in c["shared"] if x not in held]
2225
+ if not carry2:
2226
+ notes.append("%s was approved and is in flight, but every requirement "
2227
+ "it covers of group [%s] is held by a story left "
2228
+ "untouched; nothing to carry" % (c["story"], g["key"]))
2229
+ continue
2230
+ sid2 = mint()
2231
+ notes.append("%s was approved and is IN FLIGHT, so it is not rewritten; "
2232
+ "%s carries %s forward from it, while %s takes the group's "
2233
+ "unclaimed requirements"
2234
+ % (c["story"], sid2, ", ".join(carry2), carrier_sid))
2235
+ plan.append({"action": "followon", "story": sid2, "follows": c["story"],
2236
+ "path": os.path.join(sdir, sid2 + ".md"),
2237
+ "requirements_csv": ", ".join(carry2), "existing_csv": "",
2238
+ "prior_csv": ", ".join(s2["cites"]), "prior_title": s2["title"],
2239
+ "prior_path": s2["path"],
2240
+ "group": g["key"], "group_title": g["title"],
2241
+ "group_ids_csv": g["ids_csv"], "complexity": g["complexity"],
2242
+ "rationale": g["rationale"], "spec_version": version})
2243
+ continue
2244
+ notes.append("%s was approved but %s takes the group's unclaimed requirements; "
2245
+ "%s is refreshed against the current spec without gaining ids"
2246
+ % (c["story"], carrier_sid, c["story"]))
2247
+ plan.append({"action": "update", "story": s2["id"], "follows": "",
2248
+ "path": s2["path"],
2249
+ "requirements_csv": ", ".join(s2["cites"]),
2250
+ "existing_csv": ", ".join(s2["cites"]),
2251
+ "prior_csv": ", ".join(s2["cites"]), "prior_title": s2["title"],
2252
+ "prior_path": s2["path"],
2253
+ "group": g["key"], "group_title": g["title"],
2254
+ "group_ids_csv": g["ids_csv"], "complexity": g["complexity"],
2255
+ "rationale": g["rationale"], "spec_version": version})
2256
+ elif remaining:
2257
+ sid = mint()
2258
+ # A REQUIREMENT WHOSE ONLY STORIES ARE CLOSED RE-ENTERS THE WORK SET, and that is
2259
+ # right: a version row above the closed story's stamp means the contract moved
2260
+ # AFTER it shipped, so what shipped is no longer what the spec asks for. It reads
2261
+ # as duplicated work to anyone who remembers delivering it, so the run names the
2262
+ # story it is re-opening against rather than leaving them to find it.
2263
+ shipped = ["%s (%s)" % (d["id"], ", ".join(x for x in remaining if x in d["cites"]))
2264
+ for d in done_stories if any(x in d["cites"] for x in remaining)]
2265
+ if shipped:
2266
+ notes.append("%s covers requirements already delivered by %s — the spec moved "
2267
+ "after those closed, so this is the change, not a repeat"
2268
+ % (sid, "; ".join(shipped)))
2269
+ plan.append({"action": "create", "story": sid, "follows": "",
2270
+ "path": os.path.join(sdir, sid + ".md"),
2271
+ "requirements_csv": ", ".join(remaining), "existing_csv": "",
2272
+ "prior_csv": "", "prior_title": "", "prior_path": "",
2273
+ "group": g["key"], "group_title": g["title"],
2274
+ "group_ids_csv": g["ids_csv"], "complexity": g["complexity"],
2275
+ "rationale": g["rationale"], "spec_version": version})
2276
+ else:
2277
+ notes.append("group [%s] (%s) is entirely covered by stories left untouched; "
2278
+ "nothing to write" % (g["key"], g["ids_csv"]))
2279
+
2280
+ # ---- waves: the order these stories can actually be picked up in -------------------
2281
+ # The grouping declared which slices stand behind which; turning that into an order is
2282
+ # arithmetic, so it happens here and not in the prompt — the same grouping always yields
2283
+ # the same waves.
2284
+ #
2285
+ # A WAVE IS AN ELIGIBILITY LEVEL, NOT A SCHEDULE. Wave N means every story this one depends
2286
+ # on sits in a wave below N. Two stories in the SAME wave therefore have no dependency
2287
+ # between them and may be picked up in parallel; it does not say they start together, and
2288
+ # nothing waits for a whole wave to finish. That is also why the number is not a priority:
2289
+ # wave 1 is "nothing blocks this", not "do this first".
2290
+ #
2291
+ # THE EDGE SET IS A UNION of what the grouping declared and what an updated story already
2292
+ # carries in `depends_on:`. The sync sees one feature's spec; an edge someone added by hand
2293
+ # may name work it has no view of, and dropping it would silently un-order real work. Both
2294
+ # are claims about CODE ordering, and the union is exactly what the story ends up citing —
2295
+ # so the wave and the frontmatter cannot disagree about what stands in front of what.
2296
+ #
2297
+ # `follows:` is NOT an edge. A follow-on carries the remainder of a story in flight, and the
2298
+ # remainder is often buildable alongside it — §5.5 asks the author to say in Notes which
2299
+ # half has to land first. Making it an implicit edge would put an ordering in the waves that
2300
+ # no frontmatter field explains.
2301
+ entries_of, by_story = {}, {}
2302
+ for e in plan:
2303
+ entries_of.setdefault(e["group"], []).append(e["story"]); by_story[e["story"]] = e
2304
+ preds = {e["story"]: set() for e in plan}
2305
+ external, unresolved = {}, [] # stories outside this run, at the wave they declare
2306
+
2307
+ for g in groups:
2308
+ tgt = entries_of.get(g["key"], [])
2309
+ if not tgt: continue # the group wrote nothing; its edges order nothing
2310
+ for tok in g["deps_raw"]:
2311
+ tok = tok.strip()
2312
+ if not tok or tok == g["key"]: continue
2313
+ if tok in entries_of:
2314
+ src = entries_of[tok]
2315
+ elif tok in by_id and by_id[tok]["status"] == "open":
2316
+ external[tok] = by_id[tok]["wave"]; src = [tok]
2317
+ else:
2318
+ unresolved.append("%s (named by group [%s])" % (tok, g["key"])); continue
2319
+ for x in tgt: preds[x].update(s for s in src if s != x)
2320
+
2321
+ for e in plan:
2322
+ if e["action"] != "update": continue
2323
+ for d in by_id.get(e["story"], {}).get("deps", []):
2324
+ if d == e["story"] or d in preds[e["story"]]: continue
2325
+ if d not in preds: external[d] = by_id[d]["wave"] if d in by_id else 1
2326
+ preds[e["story"]].add(d)
2327
+
2328
+ # A CYCLE IS REJECTED AT AUTHORING TIME (§6.1), and this is where it would be authored.
2329
+ # Depth-first over a sorted node order, dropping the one edge that closes each cycle: only
2330
+ # edges that actually close one are lost, and the choice is deterministic — the same
2331
+ # grouping always breaks the same edge. Reported, because a dropped edge was a real claim
2332
+ # about ordering and the cycle it sat in is a fact about the slicing, not a glitch.
2333
+ cycles, state = [], {}
2334
+ def walk(node):
2335
+ state[node] = 1
2336
+ for m in sorted(preds.get(node, ())):
2337
+ if state.get(m) == 1:
2338
+ preds[node].discard(m); cycles.append("%s -> %s" % (node, m)); continue
2339
+ if state.get(m) != 2 and m in preds: walk(m)
2340
+ state[node] = 2
2341
+ for node in sorted(preds):
2342
+ if state.get(node) != 2: walk(node)
2343
+
2344
+ # Longest path from a root, relaxed to a fixed point. A story with no dependency is wave 1,
2345
+ # which is what puts every independent story in the same wave.
2346
+ wave = dict(external)
2347
+ for _ in range(len(preds) + 1):
2348
+ moved = False
2349
+ for node in sorted(preds):
2350
+ w = 1 + max([wave.get(m, 1) for m in preds[node]] or [0])
2351
+ if wave.get(node) != w: wave[node] = w; moved = True
2352
+ if not moved: break
2353
+ for e in plan:
2354
+ e["wave"] = wave.get(e["story"], 1)
2355
+ e["depends_on_csv"] = ", ".join(sorted(preds.get(e["story"], ())))
2356
+
2357
+ # Written in wave order, so a run that meets the cap writes the stories that can be STARTED
2358
+ # rather than an arbitrary prefix of them. The story id is not the order — the wave is.
2359
+ plan.sort(key=lambda e: (e["wave"], e["story"]))
2360
+ for i, e in enumerate(plan): e["seq"] = i + 1
2361
+
2362
+ waves = {}
2363
+ for e in plan: waves.setdefault(e["wave"], []).append(e["story"])
2364
+ wave_digest = "\n".join(" wave %d: %s" % (w, ", ".join(waves[w]))
2365
+ for w in sorted(waves)) or " (nothing to write)"
2366
+ if unresolved:
2367
+ notes.append("the grouping named dependencies matching no slice and no open story, so "
2368
+ "they set no order: %s" % "; ".join(sorted(set(unresolved))))
2369
+ if cycles:
2370
+ notes.append("slices were declared to depend on each other in a cycle; the edge closing "
2371
+ "each one is dropped, because a backlog with no order at all is worse than "
2372
+ "one missing an edge someone can re-add: %s" % ", ".join(cycles))
2373
+
2374
+ # THE WRITE LOOP HAS A CEILING AND THE ENGINE DOES NOT SAY WHEN IT HITS IT — `over:` stops
2375
+ # at max_iterations with no message, so plan entries past it are simply never written and
2376
+ # the run reports success. The caller passes its own ceiling here so the overflow is named
2377
+ # while the story ids still exist to name. Nothing is dropped from the plan: the ids are
2378
+ # reported and the entries stay, so raising the cap and re-running writes them.
2379
+ try:
2380
+ cap = int((os.environ.get("AW_CAP") or "").strip() or 0)
2381
+ except ValueError:
2382
+ cap = 0
2383
+ overflow = [e["story"] for e in plan[cap:]] if cap > 0 else []
2384
+
2385
+ counts = {a: sum(1 for e in plan if e["action"] == a) for a in ("create", "update", "followon")}
2386
+ base.update(plan=plan, plan_count=len(plan), any_plan=bool(plan),
2387
+ cap=cap, overflow_csv=", ".join(overflow), overflow_count=len(overflow),
2388
+ create_count=counts["create"], update_count=counts["update"],
2389
+ followon_count=counts["followon"],
2390
+ skipped_csv=", ".join(sorted(set(skipped))),
2391
+ stories_csv=", ".join(e["story"] for e in plan),
2392
+ wave_digest=wave_digest, wave_count=len(waves),
2393
+ max_wave=(max(waves) if waves else 0),
2394
+ cycle_csv=", ".join(cycles),
2395
+ unresolved_deps_csv=", ".join(sorted(set(unresolved))),
2396
+ notes=notes, notes_text="\n".join(" - " + n for n in notes),
2397
+ plan_digest="\n".join(
2398
+ " w%-3d %-9s %-16s %s%s%s"
2399
+ % (e["wave"], e["action"], e["story"], e["requirements_csv"],
2400
+ (" (follows %s)" % e["follows"]) if e["follows"] else "",
2401
+ (" [after %s]" % e["depends_on_csv"]) if e["depends_on_csv"] else "")
2402
+ for e in plan) or " (nothing to write)")
2403
+ print(json.dumps(base))
2404
+ '@
2405
+
2406
+ function Invoke-BacklogPlan {
2407
+ param([string[]]$Rest)
2408
+ $fdArg = ''; $groups = ''; $approved = ''; $work = ''; $version = ''; $mode = 'scan'; $cap = ''
2409
+ $strategy = ''; $ceiling = ''
2410
+ for ($i = 0; $i -lt $Rest.Count; $i++) {
2411
+ switch ($Rest[$i]) {
2412
+ '--feature-dir' { $fdArg = $Rest[++$i] }
2413
+ '--groups' { $groups = $Rest[++$i] }
2414
+ '--approved' { $approved = $Rest[++$i] }
2415
+ '--work' { $work = $Rest[++$i] }
2416
+ '--version' { $version = $Rest[++$i] }
2417
+ '--cap' { $cap = $Rest[++$i] }
2418
+ '--strategy' { $strategy = $Rest[++$i] }
2419
+ '--ceiling' { $ceiling = $Rest[++$i] }
2420
+ '--plan' { $mode = 'plan' }
2421
+ }
2422
+ }
2423
+ $repo = Get-RepoRoot
2424
+ $fd = Resolve-FeatureDir -Arg $fdArg -RepoRoot $repo
2425
+ if (-not $fd) { Write-Error 'backlog-plan: no feature set and no --feature-dir'; exit 1 }
2426
+ $py = Get-Py; if (-not $py) { Write-Error 'backlog-plan: python3 required'; exit 1 }
2427
+ $env:AW_FD = $fd; $env:AW_GROUPS = $groups; $env:AW_OK = $approved
2428
+ $env:AW_WORK = $work; $env:AW_VER = $version; $env:AW_MODE = $mode; $env:AW_CAP = $cap
2429
+ $env:AW_STRATEGY = $strategy; $env:AW_CEILING = $ceiling
2430
+ $PyBacklogPlan | & $py -
2431
+ }
2432
+
2433
+ # ─────────────────────────────── story-stamp ───────────────────────────────
2434
+ # The story's frontmatter is the gate surface — `exercises:`, `spec_version:`, `status:`
2435
+ # and `follows:` are what spec-coverage, check-stories, analyze-slice and close-story read,
2436
+ # and none of them opens the body. So those fields are OBSERVED and written by the kit, not
2437
+ # declared by the model that wrote the prose, for the same reason the Change History row is
2438
+ # computed rather than announced: a model that drops one id from `exercises:` produces a
2439
+ # story that reads perfectly and is invisible to every gate built to protect it. Silent,
2440
+ # and in the one field where silence costs the most.
2441
+ #
2442
+ # Everything else in the block is left exactly as the author wrote it, and a key the file
2443
+ # is missing is appended in template order rather than the block being rebuilt — a story
2444
+ # carrying a work_item or a depends_on must not lose it to a stamp.
2445
+ $PyStoryStamp = @'
2446
+ import json, os, re, sys, datetime
2447
+ fd = os.environ["AW_FD"]; story = os.environ["AW_STORY"].strip()
2448
+ path = os.path.join(fd, "stories", story + ".md")
2449
+
2450
+ def bail(msg, code=2):
2451
+ print(json.dumps({"ok": False, "story": story, "path": path, "error": msg}))
2452
+ sys.stderr.write(msg + "\n"); sys.exit(code)
2453
+
2454
+ if not os.path.isfile(path):
2455
+ bail("story-stamp: no story file at %s — the authoring step did not write it" % path)
2456
+
2457
+ def rids(s):
2458
+ seen, out = set(), []
2459
+ for t in re.findall(r'\b(?:FR|BR)-\d+', s or ""):
2460
+ if t not in seen: seen.add(t); out.append(t)
2461
+ return sorted(out, key=lambda r: (r.split("-")[0], int(r.split("-")[1])))
2462
+
2463
+ def sids(s):
2464
+ """Story ids out of a csv or an inline list. A story id is a feature name and a number;
2465
+ the template's placeholders are neither, and must not become a dependency edge."""
2466
+ seen, out = set(), []
2467
+ for t in re.split(r'[,\s\[\]"\']+', s or ""):
2468
+ t = t.strip()
2469
+ if re.match(r'^[A-Za-z][\w.]*-\d+$', t) and t not in seen:
2470
+ seen.add(t); out.append(t)
2471
+ return out
2472
+
2473
+ def cids(s):
2474
+ """Constraint ids, deduped and ordered by class then number so two readers of the same
2475
+ text always produce the same csv. SC- is NOT one of these: a success criterion is a
2476
+ feature-level outcome analyze-slice scores, not a bound a slice is built to satisfy,
2477
+ and putting one here would hand it to the generation prompt as a bound."""
2478
+ seen, out = set(), []
2479
+ for t in re.findall(r'\b(?:CN|DC|IC|UX)-\d+', s or ""):
2480
+ if t not in seen: seen.add(t); out.append(t)
2481
+ return sorted(out, key=lambda r: (r.split("-")[0], int(r.split("-")[1])))
2482
+
2483
+ def lanes(s):
2484
+ """backend / frontend out of a csv or an inline list. Anything else is not a lane."""
2485
+ out = []
2486
+ for t in re.split(r'[,\s\[\]"\']+', (s or "").lower()):
2487
+ if t in ("backend", "frontend") and t not in out: out.append(t)
2488
+ return sorted(out)
2489
+
2490
+ COV = re.compile(r'<!--\s*AW:COVERAGE:BEGIN\s*-->.*?<!--\s*AW:COVERAGE:END\s*-->', re.S)
2491
+ # An id keyed to the line that DEFINES it, in the two shapes the spec template uses:
2492
+ # a leading table cell (Data Classification) and a bold id opening a bullet (everything
2493
+ # else). The same two shapes spec-diff scores, for the same reason — a cross-reference
2494
+ # inside another requirement's prose defines nothing.
2495
+ DEF_CELL = re.compile(r'^\s*\|\s*((?:CN|DC|IC|UX)-\d+)\s*\|')
2496
+ DEF_BULL = re.compile(r'^\s*(?:[-*+]\s+)?\*\*((?:CN|DC|IC|UX)-\d+)\*\*')
2497
+
2498
+ def spec_constraints():
2499
+ """Every constraint id the spec DEFINES. Spec constraints are declared aggregate-wide —
2500
+ "constraints that must ALWAYS hold for the aggregate, independent of any single
2501
+ operation" — so there is no per-requirement relation to infer and no judgment to make:
2502
+ the feature's whole constraint set binds every slice of it. Change History is cut away
2503
+ first (its rows NAME ids without defining them), and so is the coverage block."""
2504
+ sp = os.path.join(fd, "spec.md")
2505
+ if not os.path.isfile(sp): return []
2506
+ t = COV.sub("", open(sp, encoding="utf-8", errors="replace").read())
2507
+ t = re.split(r'^##\s+Change History\s*$', t, maxsplit=1, flags=re.M)[0]
2508
+ found = []
2509
+ for line in t.split("\n"):
2510
+ m = DEF_CELL.match(line) or DEF_BULL.match(line)
2511
+ if m and m.group(1) not in found: found.append(m.group(1))
2512
+ return sorted(found, key=lambda r: (r.split("-")[0], int(r.split("-")[1])))
2513
+
2514
+ text = open(path, encoding="utf-8", errors="replace").read()
2515
+ m = re.match(r'^---\s*\n(.*?)\n---\s*\n', text, re.S)
2516
+ if m:
2517
+ block, body = m.group(1), text[m.end():]
2518
+ else:
2519
+ # A model that returned the prose and no frontmatter leaves a story every gate skips.
2520
+ # Synthesised rather than refused: the body is the expensive half and it is already on
2521
+ # disk, and the fields below are exactly the ones this op is authoritative for.
2522
+ block, body = "", text.lstrip("\n")
2523
+
2524
+ # The block as an ordered list of (key, rendered line), so an unrecognised key and its
2525
+ # continuation lines survive untouched.
2526
+ lines = block.split("\n") if block else []
2527
+ order, seen_key = [], None
2528
+ for line in lines:
2529
+ km = re.match(r'^([A-Za-z_]+):\s*(.*)$', line)
2530
+ if km:
2531
+ seen_key = km.group(1); order.append([seen_key, [line]])
2532
+ elif order and (line.startswith(" ") or line.startswith("\t")):
2533
+ order[-1][1].append(line) # a block-list item under the key above
2534
+ elif line.strip():
2535
+ order.append([None, [line]])
2536
+
2537
+ def put(key, value):
2538
+ """Set a key to a single-line value, collapsing a block list into the inline form."""
2539
+ line = ("%s: %s" % (key, value)) if value != "" else ("%s:" % key)
2540
+ for entry in order:
2541
+ if entry[0] == key:
2542
+ entry[1] = [line]
2543
+ return "set"
2544
+ order.append([key, [line]])
2545
+ return "added"
2546
+
2547
+ TEMPLATE_ORDER = ["id", "type", "status", "title", "exercises", "constraints",
2548
+ "spec_version", "depends_on", "wave", "follows",
2549
+ "designed_lanes", "dropped_lanes", "work_item", "created"]
2550
+ def get(key):
2551
+ for entry in order:
2552
+ if entry[0] == key: return entry[1][0].split(":", 1)[1].strip()
2553
+ return ""
2554
+
2555
+ changed = {}
2556
+ changed["id"] = put("id", story)
2557
+
2558
+ if os.environ.get("AW_IDS_GIVEN"):
2559
+ ids = rids(os.environ.get("AW_IDS", ""))
2560
+ changed["exercises"] = put("exercises", "[" + ", ".join(ids) + "]")
2561
+ else:
2562
+ ids = rids(get("exercises"))
2563
+
2564
+ # THE BOUNDS THIS SLICE MUST MEET, AS A FRONTMATTER FIELD THE KIT WRITES. Everything a gate
2565
+ # reads lives in frontmatter; the story's `## Constraints` section was the one exception,
2566
+ # and being model-authored it could omit an id with nothing able to notice — a missing bound
2567
+ # in a generation prompt that never opens the spec. Lifted here, so the gate surface is
2568
+ # complete by construction and the section keeps its per-slice prose.
2569
+ if os.environ.get("AW_CONSTRAINTS_GIVEN"):
2570
+ cons = spec_constraints()
2571
+ changed["constraints"] = put("constraints", "[" + ", ".join(cons) + "]")
2572
+ else:
2573
+ cons = cids(get("constraints"))
2574
+
2575
+ ver = (os.environ.get("AW_VER") or "").strip()
2576
+ if ver: changed["spec_version"] = put("spec_version", ver)
2577
+
2578
+ fol = (os.environ.get("AW_FOLLOWS") or "").strip()
2579
+ if fol: changed["follows"] = put("follows", fol)
2580
+
2581
+ ttl = (os.environ.get("AW_TITLE") or "").strip()
2582
+ if ttl and (not get("title") or get("title").startswith("[")):
2583
+ changed["title"] = put("title", ttl)
2584
+
2585
+ # Placeholders the template ships. Left alone once a real value is in them, so a story
2586
+ # CLOSED between the plan and the write is not quietly re-opened by a stamp.
2587
+ if not get("type") or get("type").startswith("["):
2588
+ changed["type"] = put("type", "functional" if ids else "technical")
2589
+ if not get("status") or get("status").startswith("["):
2590
+ changed["status"] = put("status", "open")
2591
+ # ORDERING IS A UNION, NEVER A REPLACEMENT. The edges passed in are what this run's slicing
2592
+ # declared; the ones already in the file may name work outside this feature, which the sync
2593
+ # cannot see. Dropping either loses a real claim about what has to land first, and a lost
2594
+ # edge is silent — no later stage re-derives it.
2595
+ deps = sorted(set(sids(get("depends_on")) + sids(os.environ.get("AW_DEPS", ""))) - {story})
2596
+ if deps or not get("depends_on") or get("depends_on").startswith("["):
2597
+ changed["depends_on"] = put("depends_on", "[" + ", ".join(deps) + "]")
2598
+
2599
+ # THE WAVE IS AN ELIGIBILITY LEVEL, NOT A PRIORITY: every story this one depends on sits in
2600
+ # a lower one, so stories sharing a wave have no ordering between them and may be picked up
2601
+ # in parallel. Computed by backlog-plan from `depends_on`, and written here for the same
2602
+ # reason `exercises:` is — a field the gates and the listings read is observed, not declared.
2603
+ # A story stamped without one floors at 1: nothing is KNOWN to have to land before it.
2604
+ wv = (os.environ.get("AW_WAVE") or "").strip()
2605
+ if wv.isdigit():
2606
+ changed["wave"] = put("wave", wv)
2607
+ elif not get("wave").isdigit():
2608
+ changed["wave"] = put("wave", "1")
2609
+
2610
+ # WHICH LANES WERE DESIGNED, AND WHICH WERE DROPPED — two fields, because one of them cannot
2611
+ # say the difference. analyze-design STOPS on a lane whose plan is behind; story-plan DROPS
2612
+ # it and designs the other, so one command later "this slice has no user-facing surface" and
2613
+ # "the UI lane was out of scope when this was designed" are the same state on disk, and a
2614
+ # UX--bearing requirement can ship backend-only with a green story-scoped gate.
2615
+ # Designed ACCUMULATES across passes (a lane that has a design keeps having one); dropped is
2616
+ # whatever has been dropped and not since designed, so the two never both claim a lane.
2617
+ if os.environ.get("AW_DESIGNED_GIVEN") or os.environ.get("AW_DROPPED_GIVEN"):
2618
+ designed = sorted(set(lanes(get("designed_lanes")))
2619
+ | set(lanes(os.environ.get("AW_DESIGNED", ""))))
2620
+ dropped = sorted((set(lanes(get("dropped_lanes")))
2621
+ | set(lanes(os.environ.get("AW_DROPPED", "")))) - set(designed))
2622
+ changed["designed_lanes"] = put("designed_lanes", "[" + ", ".join(designed) + "]")
2623
+ changed["dropped_lanes"] = put("dropped_lanes", "[" + ", ".join(dropped) + "]")
2624
+
2625
+ if not get("created") or get("created").startswith("["):
2626
+ changed["created"] = put("created", datetime.date.today().isoformat())
2627
+ for k in ("title", "follows", "work_item"):
2628
+ if not any(e[0] == k for e in order): put(k, "")
2629
+
2630
+ # Rendered back in template order, with anything unrecognised kept after it in the order it
2631
+ # was written. A story is read by people as well as by gates.
2632
+ rank = {k: i for i, k in enumerate(TEMPLATE_ORDER)}
2633
+ order.sort(key=lambda e: rank.get(e[0], len(TEMPLATE_ORDER)))
2634
+ out_block = "\n".join(l for e in order for l in e[1])
2635
+ open(path, "w", encoding="utf-8").write("---\n" + out_block + "\n---\n\n" + body.lstrip("\n"))
2636
+
2637
+ # THE STAMP OWNS THE ID SET; THE SECTION KEEPS ITS PROSE. `## Constraints` is not a list of
2638
+ # ids — each line says what THIS slice has to do about the bound it names, and that line is
2639
+ # the whole reason the section is worth reading. So the body is RECONCILED, never rewritten:
2640
+ # an id now in the frontmatter with no line in the section is reported for the caller to
2641
+ # announce, and a line naming an id the spec no longer defines is reported the same way.
2642
+ # Neither is silently written or silently deleted.
2643
+ bm = re.search(r'^##\s+Constraints\s*$(.*?)(?=^##\s|\Z)', body, re.M | re.S)
2644
+ body_ids = set(cids(bm.group(1))) if bm else set()
2645
+ unlined = [c for c in cons if c not in body_ids]
2646
+ orphan_lines = sorted(body_ids - set(cons),
2647
+ key=lambda r: (r.split("-")[0], int(r.split("-")[1])))
2648
+
2649
+ print(json.dumps({"ok": True, "story": story, "path": path,
2650
+ "exercises": ids, "exercises_csv": ", ".join(ids),
2651
+ "constraints": cons, "constraints_csv": ", ".join(cons),
2652
+ "unlined_csv": ", ".join(unlined), "unlined_any": bool(unlined),
2653
+ "orphan_lines_csv": ", ".join(orphan_lines),
2654
+ "constraints_reconciled": not (unlined or orphan_lines),
2655
+ "designed_lanes": get("designed_lanes"),
2656
+ "dropped_lanes": get("dropped_lanes"),
2657
+ "spec_version": get("spec_version"), "status": get("status"),
2658
+ "depends_on": get("depends_on"), "wave": get("wave"),
2659
+ "follows": get("follows"), "title": get("title"),
2660
+ "type": get("type"), "had_frontmatter": bool(m),
2661
+ "fields": sorted(changed)}))
2662
+ '@
2663
+
2664
+ function Invoke-StoryStamp {
2665
+ param([string[]]$Rest)
2666
+ $fdArg = ''; $story = ''; $ids = ''; $version = ''; $follows = ''; $idsGiven = ''; $title = ''
2667
+ $deps = ''; $wave = ''; $consGiven = ''
2668
+ $designed = ''; $designedGiven = ''; $dropped = ''; $droppedGiven = ''
2669
+ for ($i = 0; $i -lt $Rest.Count; $i++) {
2670
+ switch ($Rest[$i]) {
2671
+ '--feature-dir' { $fdArg = $Rest[++$i] }
2672
+ '--story' { $story = $Rest[++$i] }
2673
+ '--ids' { $ids = $Rest[++$i]; $idsGiven = '1' }
2674
+ '--version' { $version = $Rest[++$i] }
2675
+ '--follows' { $follows = $Rest[++$i] }
2676
+ '--title' { $title = $Rest[++$i] }
2677
+ '--depends-on' { $deps = $Rest[++$i] }
2678
+ '--wave' { $wave = $Rest[++$i] }
2679
+ # A BARE FLAG, NOT A CSV: the ids are lifted from the spec this op already has
2680
+ # a --feature-dir for. Nothing upstream has to enumerate them, and the second
2681
+ # caller (story-plan) can write the lane keys without re-lifting constraints
2682
+ # from a spec that may have moved past this story's spec_version.
2683
+ '--constraints' { $consGiven = '1' }
2684
+ '--designed-lanes' { $designed = $Rest[++$i]; $designedGiven = '1' }
2685
+ '--dropped-lanes' { $dropped = $Rest[++$i]; $droppedGiven = '1' }
2686
+ }
2687
+ }
2688
+ if (-not $story) { Write-Error 'story-stamp: --story is required'; exit 1 }
2689
+ $repo = Get-RepoRoot
2690
+ $fd = Resolve-FeatureDir -Arg $fdArg -RepoRoot $repo
2691
+ if (-not $fd) { Write-Error 'story-stamp: no feature set and no --feature-dir'; exit 1 }
2692
+ $py = Get-Py; if (-not $py) { Write-Error 'story-stamp: python3 required'; exit 1 }
2693
+ $env:AW_FD = $fd; $env:AW_STORY = $story; $env:AW_IDS = $ids
2694
+ $env:AW_IDS_GIVEN = $idsGiven; $env:AW_VER = $version
2695
+ $env:AW_FOLLOWS = $follows; $env:AW_TITLE = $title
2696
+ $env:AW_DEPS = $deps; $env:AW_WAVE = $wave
2697
+ $env:AW_CONSTRAINTS_GIVEN = $consGiven
2698
+ $env:AW_DESIGNED = $designed; $env:AW_DESIGNED_GIVEN = $designedGiven
2699
+ $env:AW_DROPPED = $dropped; $env:AW_DROPPED_GIVEN = $droppedGiven
2700
+ $PyStoryStamp | & $py -
2701
+ Remove-Item Env:AW_CONSTRAINTS_GIVEN, Env:AW_DESIGNED, Env:AW_DESIGNED_GIVEN, Env:AW_DROPPED, Env:AW_DROPPED_GIVEN -ErrorAction SilentlyContinue
2702
+ }
2703
+
1366
2704
  $PySpecCoverage = @'
1367
2705
  import json, os, re, sys
1368
2706
  fd = os.environ["AW_FD"]
@@ -1618,6 +2956,8 @@ function Invoke-FeaturePaths {
1618
2956
  $spec = Join-Path $fd 'spec.md'
1619
2957
  $design = Join-Path $fd 'design.md'
1620
2958
  $uiDesign = Join-Path $fd 'design.ui.md'
2959
+ $backendPlan = Join-Path $fd 'backend-plan.md'
2960
+ $frontendPlan = Join-Path $fd 'frontend-plan.md'
1621
2961
  # needs_bootstrap, not spec_exists, is what picks specify's branch. A crashed first run
1622
2962
  # leaves spec.md on disk with the marker still up, and branching on the file alone read
1623
2963
  # that as a spec to EXTEND — re-applying the same input over an unfinished v1.0.
@@ -1635,6 +2975,10 @@ function Invoke-FeaturePaths {
1635
2975
  spec_exists = (Test-Path $spec)
1636
2976
  design_exists = (Test-Path $design)
1637
2977
  ui_design_exists = (Test-Path $uiDesign)
2978
+ backend_plan_file = $backendPlan
2979
+ frontend_plan_file = $frontendPlan
2980
+ backend_plan_exists = (Test-Path $backendPlan)
2981
+ frontend_plan_exists = (Test-Path $frontendPlan)
1638
2982
  bootstrap_pending = $bootstrapPending
1639
2983
  needs_bootstrap = ((-not (Test-Path $spec)) -or $bootstrapPending)
1640
2984
  })
@@ -1743,12 +3087,37 @@ function Get-ProjectMarkers {
1743
3087
  return $out
1744
3088
  }
1745
3089
 
3090
+ # Does a manifest belong to the ecosystem the caller asked about. The repo-scope fallback
3091
+ # below is deliberate — a .NET solution legitimately sits ABOVE the lane it scaffolds — but
3092
+ # it answers with whatever manifest it finds, so in a two-lane repo where only the frontend
3093
+ # is scaffolded the service lane's gate passes on the frontend's package.json. Knowing the
3094
+ # lane's ecosystem is what turns that hit back into a miss.
3095
+ function Get-MarkerEcosystem {
3096
+ param([string]$Marker)
3097
+ switch -Wildcard (Split-Path -Leaf $Marker) {
3098
+ '*.sln' { return 'dotnet' }
3099
+ '*.csproj' { return 'dotnet' }
3100
+ 'package.json' { return 'node' }
3101
+ 'pom.xml' { return 'java' }
3102
+ 'build.gradle' { return 'java' }
3103
+ 'build.gradle.kts' { return 'java' }
3104
+ 'go.mod' { return 'go' }
3105
+ 'Cargo.toml' { return 'rust' }
3106
+ 'pyproject.toml' { return 'python' }
3107
+ default { return '' }
3108
+ }
3109
+ }
3110
+
1746
3111
  function Invoke-DetectProject {
1747
3112
  param([string[]]$Rest)
1748
- $scopeRoot = ''
3113
+ $scopeRoot = ''; $ecosystem = ''
1749
3114
  for ($i = 0; $i -lt $Rest.Count; $i++) {
1750
3115
  switch ($Rest[$i]) {
1751
3116
  { $_ -in '--root','--source-path','-Root' } { $scopeRoot = $Rest[++$i] }
3117
+ # The lane's ecosystem, passed in by the caller that already resolved it.
3118
+ # NOT re-derived here: lane-gate binds it from stacks.json before this op runs,
3119
+ # and a second guess is a second thing to keep in step with that file.
3120
+ { $_ -in '--ecosystem','-Ecosystem' } { $ecosystem = $Rest[++$i] }
1752
3121
  }
1753
3122
  }
1754
3123
  $repo = Get-RepoRoot
@@ -1765,7 +3134,18 @@ function Invoke-DetectProject {
1765
3134
  $scope = 'repo'
1766
3135
  $markers = @(Get-ProjectMarkers -Repo $repo -Start $repo)
1767
3136
  }
1768
- Write-Json ([ordered]@{ scaffolded = ($markers.Count -gt 0); markers = @($markers); scope = $scope })
3137
+ $scaffolded = ($markers.Count -gt 0)
3138
+ # UNASKED IS NOT UNMATCHED. With no --ecosystem the caller has told us nothing to judge
3139
+ # against, and answering false there would fail every existing call site.
3140
+ $match = $true
3141
+ if ($ecosystem -and $scaffolded) {
3142
+ $match = $false
3143
+ foreach ($m in $markers) {
3144
+ if ((Get-MarkerEcosystem -Marker $m) -eq $ecosystem) { $match = $true; break }
3145
+ }
3146
+ }
3147
+ Write-Json ([ordered]@{ scaffolded = $scaffolded; markers = @($markers); scope = $scope
3148
+ ecosystem = $ecosystem; ecosystem_match = $match })
1769
3149
  }
1770
3150
 
1771
3151
 
@@ -2547,16 +3927,27 @@ function Invoke-DesignScaffold {
2547
3927
  # --lane. In a brownfield repo onboard GENERATES a code-derived override for both
2548
3928
  # names, so the defaults already yield the as-built structure.
2549
3929
  for ($i = 0; $i -lt $Rest.Count; $i++) { switch ($Rest[$i]) { { $_ -in '--feature-dir','-FeatureDir' } { $fdArg = $Rest[++$i] } { $_ -in '--lane','-Lane' } { $lane = $Rest[++$i] } { $_ -in '--template','-Template' } { $tplName = $Rest[++$i] } } }
3930
+ # backend/frontend are the PLAN-phase pairs: the same templates, the plan document
3931
+ # names, and a MIGRATION — a legacy design.md / design.ui.md is RENAMED into the
3932
+ # plan name so a feature never carries both spellings of the same master.
3933
+ # service/ui stay byte-identical for their existing callers (adopt, the delta chain).
3934
+ $legacyName = ''
2550
3935
  switch ($lane) {
2551
- 'service' { $docName = 'design.md'; if (-not $tplName) { $tplName = 'design-template' } }
2552
- 'ui' { $docName = 'design.ui.md'; if (-not $tplName) { $tplName = 'ui-design-template' } }
2553
- default { Write-Error ("design-scaffold: unknown --lane '" + $lane + "' (service|ui)"); exit 1 }
3936
+ 'service' { $docName = 'design.md'; if (-not $tplName) { $tplName = 'design-template' } }
3937
+ 'ui' { $docName = 'design.ui.md'; if (-not $tplName) { $tplName = 'ui-design-template' } }
3938
+ 'backend' { $docName = 'backend-plan.md'; $legacyName = 'design.md'; if (-not $tplName) { $tplName = 'design-template' } }
3939
+ 'frontend' { $docName = 'frontend-plan.md'; $legacyName = 'design.ui.md'; if (-not $tplName) { $tplName = 'ui-design-template' } }
3940
+ default { Write-Error ("design-scaffold: unknown --lane '" + $lane + "' (service|ui|backend|frontend)"); exit 1 }
2554
3941
  }
2555
3942
  $repo = Get-RepoRoot
2556
3943
  $fd = Resolve-FeatureDir -Arg $fdArg -RepoRoot $repo
2557
3944
  if (-not $fd) { Write-Error 'design-scaffold: no feature set (run /appweaver select-feature first) and no --feature-dir'; exit 1 }
2558
3945
  New-Item -ItemType Directory -Force -Path $fd | Out-Null
2559
3946
  $target = Join-Path $fd $docName
3947
+ $migrated = $false
3948
+ if ((-not (Test-Path $target)) -and $legacyName -and (Test-Path (Join-Path $fd $legacyName))) {
3949
+ Move-Item (Join-Path $fd $legacyName) $target; $migrated = $true
3950
+ }
2560
3951
  if (Test-Path $target) { $created = $false }
2561
3952
  else {
2562
3953
  $tpl = Resolve-NamedTemplate -Name $tplName -RepoRoot $repo
@@ -2570,7 +3961,1040 @@ function Invoke-DesignScaffold {
2570
3961
  $overrideActive = Test-Path (Join-Path $repo (".appweaver/templates/overrides/" + $tplName + ".md"))
2571
3962
  $templateSource = Resolve-NamedTemplate -Name $tplName -RepoRoot $repo
2572
3963
  $tsOut = if ($templateSource) { $templateSource } else { '' }
2573
- Write-Json ([ordered]@{ feature_dir = $fd; design_doc = $target; lane = $lane; created = $created; override_active = $overrideActive; template = $tplName; template_source = $tsOut })
3964
+ Write-Json ([ordered]@{ feature_dir = $fd; design_doc = $target; lane = $lane; created = $created; migrated = $migrated; override_active = $overrideActive; template = $tplName; template_source = $tsOut })
3965
+ }
3966
+
3967
+
3968
+ # ─────────────────────────────── test-diff ─────────────────────────────────
3969
+ # The TECHNICAL-STORY ORACLE — twin of the bash action; the python payload is
3970
+ # byte-identical by contract.
3971
+ $PyTestDiff = @'
3972
+ import json, os, re, subprocess
3973
+ root = os.environ.get("AW_ROOT") or "."
3974
+ fd = os.environ.get("AW_FD", "")
3975
+ want = (os.environ.get("AW_BASE") or "").strip()
3976
+ agg = os.path.basename(fd.rstrip("/\\"))
3977
+
3978
+ def git(*a):
3979
+ """A git read that never raises. A working copy this command cannot interrogate is a
3980
+ FACT TO REPORT — the caller decides what an unreadable oracle means — never a crash
3981
+ that takes the gate down with it."""
3982
+ try:
3983
+ p = subprocess.run(["git", "-C", root] + list(a), capture_output=True, text=True)
3984
+ except Exception:
3985
+ return 1, ""
3986
+ return p.returncode, (p.stdout or "").strip()
3987
+
3988
+ DIR_RE = re.compile(r'(^|/)(tests?|specs?|__tests__|testing|test-suite)(/|$)', re.I)
3989
+
3990
+ # The kit's OWN trees, which hold documents and configuration and never tests. The spec
3991
+ # tree is derived rather than assumed: `specs/` matches the RSpec directory convention
3992
+ # exactly, so without this every requirement document — and this gate's own verdict file,
3993
+ # written before the diff is taken — counted as a modified test.
3994
+ SKIP = [".appweaver/"]
3995
+ if fd:
3996
+ _rel = os.path.relpath(fd, root).replace("\\", "/")
3997
+ SKIP.append((_rel.rsplit("/", 1)[0] if "/" in _rel else _rel).rstrip("/") + "/")
3998
+
3999
+ def is_test(path):
4000
+ """A path is a TEST when a directory on it says so, or its own filename does — the
4001
+ four conventions every shipped stack uses between them: a tests/ directory, a
4002
+ Name.Tests.cs / NameTest.java suffix, a test_name.py / name_test.go affix, and a
4003
+ name.test.ts / name.spec.ts infix. Deliberately GENEROUS: over-calling a file a test
4004
+ costs a louder message, under-calling one costs a technical story that changed
4005
+ behaviour and passed its own oracle."""
4006
+ p = path.replace("\\", "/")
4007
+ if any(p.startswith(s) for s in SKIP):
4008
+ return False
4009
+ stem, ext = os.path.splitext(os.path.basename(p))
4010
+ # Prose is never a test, wherever it sits. A tests/ directory holds its own README
4011
+ # and a docs tree holds files named for testing; counting either would fail a
4012
+ # technical story over a paragraph.
4013
+ if ext.lower() in (".md", ".markdown", ".txt", ".rst", ".adoc"):
4014
+ return False
4015
+ if DIR_RE.search(os.path.dirname(p)):
4016
+ return True
4017
+ stem = stem.lower()
4018
+ if stem.startswith(("test", "spec")) or stem.endswith(("test", "tests", "spec", "specs")):
4019
+ return True
4020
+ return any(k in stem for k in (".test", ".spec", "_test", "_spec", "-test", "-spec"))
4021
+
4022
+ out = {"ok": True, "aggregate": agg, "git": False, "checked": False,
4023
+ "base": "", "base_ref": "", "base_kind": "none", "files_changed": 0,
4024
+ "tests_changed": [], "tests_changed_csv": "", "tests_changed_count": 0,
4025
+ "tests_deleted": [], "tests_deleted_csv": "",
4026
+ "tests_added": [], "tests_added_csv": "", "tests_added_count": 0,
4027
+ "slice_tests_changed": [], "slice_tests_changed_csv": "", "slice_tests_changed_count": 0,
4028
+ "any_test_changed": False, "clean": True, "oracle": "clean",
4029
+ "note": "", "digest": ""}
4030
+
4031
+ if git("rev-parse", "--is-inside-work-tree")[1] != "true":
4032
+ out["oracle"] = "unverified"
4033
+ out["note"] = ("Not a git working copy, so the test suite's history cannot be read. The "
4034
+ "unchanged-suite oracle is UNVERIFIED for this run — not passed.")
4035
+ out["digest"] = out["note"]
4036
+ print(json.dumps(out)); raise SystemExit(0)
4037
+ out["git"] = out["checked"] = True
4038
+
4039
+ # WHICH BASELINE. An explicit --base wins. Otherwise the fork point from the integration
4040
+ # branch, which is what a story's work sits on top of; falling back to HEAD, which sees
4041
+ # the working tree alone. The kind is reported because it changes what the answer MEANS:
4042
+ # a `head` baseline cannot see a test modified in a commit this branch already made.
4043
+ head = git("rev-parse", "HEAD")[1]
4044
+ if want and git("rev-parse", "--verify", want + "^{commit}")[0] == 0:
4045
+ out["base"], out["base_ref"], out["base_kind"] = git("rev-parse", want)[1], want, "given"
4046
+ if not out["base"]:
4047
+ cands = []
4048
+ rc, ref = git("symbolic-ref", "--quiet", "refs/remotes/origin/HEAD")
4049
+ if rc == 0 and ref:
4050
+ cands.append(ref.split("refs/remotes/", 1)[-1])
4051
+ cands += ["origin/main", "origin/master", "main", "master"]
4052
+ seen = set()
4053
+ for c in cands:
4054
+ if c in seen:
4055
+ continue
4056
+ seen.add(c)
4057
+ if git("rev-parse", "--verify", c + "^{commit}")[0] != 0:
4058
+ continue
4059
+ rc, mb = git("merge-base", "HEAD", c)
4060
+ if rc != 0 or not mb:
4061
+ continue
4062
+ out["base"], out["base_ref"] = mb, c
4063
+ out["base_kind"] = "head" if mb == head else "merge-base"
4064
+ break
4065
+ if not out["base"]:
4066
+ out["base"], out["base_kind"] = head or "HEAD", "head"
4067
+
4068
+ rc, diff = git("diff", "--name-status", "--find-renames", out["base"])
4069
+ changed, added, deleted, files = [], [], [], 0
4070
+ for line in diff.splitlines():
4071
+ parts = line.split("\t")
4072
+ if len(parts) < 2:
4073
+ continue
4074
+ code, paths = parts[0].strip(), parts[1:]
4075
+ files += 1
4076
+ hits = [p for p in paths if is_test(p)]
4077
+ if not hits:
4078
+ continue
4079
+ p = hits[-1]
4080
+ if code.startswith("A") or code.startswith("C"):
4081
+ # A NEW test is not a changed one. A refactor that adds characterisation tests is
4082
+ # exactly the work a technical story exists to do.
4083
+ added.append(p)
4084
+ elif code.startswith("R"):
4085
+ # A pure rename moves a test without changing what it asserts; anything less than
4086
+ # a 100% match carries an edit inside it.
4087
+ (added if code == "R100" else changed).append(p)
4088
+ elif code.startswith("D"):
4089
+ deleted.append(p); changed.append(p)
4090
+ else:
4091
+ changed.append(p)
4092
+
4093
+ # Untracked files are ADDITIONS the diff cannot see — reported as such so a new test
4094
+ # written in the working tree is not mistaken for a missing one.
4095
+ for p in git("ls-files", "--others", "--exclude-standard")[1].splitlines():
4096
+ p = p.strip()
4097
+ if p and is_test(p) and p not in added:
4098
+ added.append(p); files += 1
4099
+
4100
+ changed = sorted(set(changed)); added = sorted(set(added)); deleted = sorted(set(deleted))
4101
+ low = agg.lower()
4102
+ slice_changed = [p for p in changed if low and low in p.lower()]
4103
+ out.update(files_changed=files,
4104
+ tests_changed=changed, tests_changed_csv=", ".join(changed),
4105
+ tests_changed_count=len(changed),
4106
+ tests_deleted=deleted, tests_deleted_csv=", ".join(deleted),
4107
+ tests_added=added, tests_added_csv=", ".join(added), tests_added_count=len(added),
4108
+ slice_tests_changed=slice_changed, slice_tests_changed_csv=", ".join(slice_changed),
4109
+ slice_tests_changed_count=len(slice_changed),
4110
+ any_test_changed=bool(changed), clean=not changed,
4111
+ # The DIFF's state in one word — clean | changed | unverified — so a caller can
4112
+ # branch on it without recombining a boolean with a "could I even look" flag.
4113
+ # It says what the suite did, never what that means for a story.
4114
+ oracle="changed" if changed else "clean")
4115
+
4116
+ kindnote = {"given": "the ref given on the command line",
4117
+ "merge-base": "the fork point from %s — every commit this branch added is in view" % out["base_ref"],
4118
+ "head": "HEAD — only uncommitted work is in view, so a test modified in a commit "
4119
+ "already made on this branch is NOT counted"}[out["base_kind"]]
4120
+ lines = ["Test-suite diff against %s (%s): %s" % (out["base"][:12], out["base_kind"], kindnote),
4121
+ " files changed: %d" % files,
4122
+ " tests MODIFIED or DELETED (%d): %s" % (len(changed), ", ".join(changed) or "none"),
4123
+ " tests ADDED (%d): %s" % (len(added), ", ".join(added) or "none")]
4124
+ if slice_changed:
4125
+ lines.append(" of those, on this aggregate (%s): %s" % (agg, ", ".join(slice_changed)))
4126
+ out["note"] = kindnote
4127
+ out["digest"] = "\n".join(lines)
4128
+ print(json.dumps(out))
4129
+ '@
4130
+
4131
+ function Invoke-TestDiff {
4132
+ param([string[]]$Rest)
4133
+ $fdArg = ''; $base = ''
4134
+ for ($i = 0; $i -lt $Rest.Count; $i++) { switch ($Rest[$i]) { { $_ -in '--feature-dir','-FeatureDir' } { $fdArg = $Rest[++$i] } { $_ -in '--base','-Base' } { $base = $Rest[++$i] } } }
4135
+ $py = Get-Py; if (-not $py) { Write-Error 'test-diff: python3 required'; exit 1 }
4136
+ $repo = Get-RepoRoot
4137
+ $fd = Resolve-FeatureDir -Arg $fdArg -RepoRoot $repo
4138
+ if (-not $fd) { $fd = '' }
4139
+ $env:AW_ROOT = $repo; $env:AW_FD = $fd; $env:AW_BASE = $base
4140
+ $PyTestDiff | & $py -
4141
+ Remove-Item Env:AW_ROOT, Env:AW_FD, Env:AW_BASE -ErrorAction SilentlyContinue
4142
+ }
4143
+
4144
+ # ─────────────────────────── plan-check / plan-stamp ────────────────────────
4145
+ # The plan documents' derivation tracking — twin of the bash implementation; the
4146
+ # python payloads are IDENTICAL, so the two shells cannot drift. Each plan doc
4147
+ # derives from ONE spec version and carries its OWN track file beside the spec
4148
+ # (.aw-plan-track.backend-plan.json / .aw-plan-track.frontend-plan.json) recording
4149
+ # {spec_version, sha256}, so the two lanes' stamps never share a write. plan-check
4150
+ # reads the record back against the spec's Change History ledger; plan-stamp is the
4151
+ # only writer. Both always exit 0 with an ok/state field — the workflow's
4152
+ # verify_context owns the stop.
4153
+ $PyPlanCheck = @'
4154
+ import json, os, re, sys, hashlib
4155
+ doc = os.environ["AW_DOC"]; fd = os.environ["AW_FD"]
4156
+ spec = os.path.join(fd, "spec.md")
4157
+ # One track file per plan document (.aw-plan-track.backend-plan.json /
4158
+ # .aw-plan-track.frontend-plan.json) — parallel lane stamps never contend on a shared file.
4159
+ stem = os.path.splitext(os.path.basename(doc))[0]
4160
+ track_path = os.path.join(fd, ".aw-plan-track.%s.json" % stem)
4161
+ def vtuple(v):
4162
+ try: return tuple(int(x) for x in v.lstrip("vV").split("."))
4163
+ except Exception: return (0,)
4164
+ out = {"doc": doc, "doc_exists": os.path.isfile(doc), "state": "", "derived_version": "",
4165
+ "current_version": "", "changed_csv": "", "changed_summary": "",
4166
+ "body_changed": False, "body_sha256": ""}
4167
+ # Current version = the widest of the ledger's rows and the **Version** header — the
4168
+ # same widest-wins rule ledger-append uses, so a hand-moved header cannot hide a row.
4169
+ rows = []; cur = ""; idcol = -1
4170
+ if os.path.isfile(spec):
4171
+ text = open(spec, encoding="utf-8", errors="replace").read()
4172
+ m = re.search(r'^##\s+Change History\s*$', text, re.M)
4173
+ if m:
4174
+ for line in text[m.end():].splitlines():
4175
+ if idcol < 0 and line.lstrip().startswith("|") and "requirements changed" in line.lower():
4176
+ hdr = [c.strip().lower() for c in line.strip().strip("|").split("|")]
4177
+ idcol = next((i for i, c in enumerate(hdr) if "requirements changed" in c), -1)
4178
+ rm = re.match(r'^\|\s*(v\d+(?:\.\d+)?)\s*\|', line)
4179
+ if rm: rows.append((rm.group(1), line))
4180
+ hv = re.search(r'^\*\*Version\*\*:\s*(v[\d.]+)', text, re.M)
4181
+ cands = [r[0] for r in rows] + ([hv.group(1)] if hv else [])
4182
+ if cands: cur = max(cands, key=vtuple)
4183
+ out["current_version"] = cur
4184
+ if not out["doc_exists"]:
4185
+ out["state"] = "fresh"; print(json.dumps(out)); sys.exit(0)
4186
+ # THE HASH ITSELF, not only the boolean it was reduced to. "Has this document moved since it
4187
+ # was stamped" answers the freshness question; WHICH shape it is now is what a gate verdict
4188
+ # has to record and a story pass has to name, or approved-then-changed-then-never-re-approved
4189
+ # has nothing to compare against. Taken before the untracked exit so a document with no
4190
+ # derivation record still reports what it is.
4191
+ body = open(doc, encoding="utf-8", errors="replace").read()
4192
+ out["body_sha256"] = hashlib.sha256(body.encode("utf-8")).hexdigest()
4193
+ try: track = json.load(open(track_path, encoding="utf-8"))
4194
+ except Exception: track = {}
4195
+ entry = track.get(os.path.basename(doc))
4196
+ if not entry:
4197
+ # A document with no derivation record — a migrated legacy master, or a baseline
4198
+ # lost by hand. There is no stamp to diff against, so the caller reconciles the
4199
+ # WHOLE document once and plan-stamp baselines it.
4200
+ out["state"] = "untracked"; print(json.dumps(out)); sys.exit(0)
4201
+ derived = entry.get("spec_version", "")
4202
+ out["derived_version"] = derived
4203
+ out["body_changed"] = out["body_sha256"] != entry.get("sha256", "")
4204
+ moved = [r for r in rows if vtuple(r[0]) > vtuple(derived)]
4205
+ # Scrape ONLY the ledger's "Requirements changed" cell when it names one. The
4206
+ # Stories cell holds ids of the form <Aggregate>-nnn, which read as requirement ids
4207
+ # whenever the aggregate is spelled in caps (EDI-001, HR-002) — those would arrive
4208
+ # as requirements for the plan to conform, and there is no such requirement.
4209
+ def _scope(line):
4210
+ if idcol >= 0:
4211
+ cells = [c.strip() for c in line.strip().strip("|").split("|")]
4212
+ if idcol < len(cells): return cells[idcol]
4213
+ return line
4214
+ ids = sorted({i for _v, line in moved for i in re.findall(r'[A-Z]{2}-\d+', _scope(line))})
4215
+ out["changed_csv"] = ", ".join(ids)
4216
+ out["changed_summary"] = " // ".join(line.strip() for _v, line in moved)
4217
+ behind = bool(moved) or bool(cur and vtuple(cur) > vtuple(derived))
4218
+ if out["body_changed"] and behind: out["state"] = "edited_behind"
4219
+ elif out["body_changed"]: out["state"] = "edited"
4220
+ elif behind: out["state"] = "behind"
4221
+ else: out["state"] = "clean"
4222
+ print(json.dumps(out))
4223
+ '@
4224
+
4225
+ $PyPlanStamp = @'
4226
+ import json, os, re, sys, hashlib, datetime
4227
+ doc = os.environ["AW_DOC"]; fd = os.environ["AW_FD"]
4228
+ ids = os.environ.get("AW_IDS", "").strip(); note = os.environ.get("AW_NOTE", "").strip()
4229
+ no_row = os.environ.get("AW_NOROW", "false") == "true"
4230
+ spec = os.path.join(fd, "spec.md")
4231
+ # One track file per plan document (.aw-plan-track.backend-plan.json /
4232
+ # .aw-plan-track.frontend-plan.json) — parallel lane stamps never contend on a shared file.
4233
+ stem = os.path.splitext(os.path.basename(doc))[0]
4234
+ track_path = os.path.join(fd, ".aw-plan-track.%s.json" % stem)
4235
+ def vtuple(v):
4236
+ try: return tuple(int(x) for x in v.lstrip("vV").split("."))
4237
+ except Exception: return (0,)
4238
+ if not os.path.isfile(doc):
4239
+ print(json.dumps({"ok": False, "error": "plan document %s does not exist" % doc, "version": ""})); sys.exit(0)
4240
+ cur = ""
4241
+ if os.path.isfile(spec):
4242
+ st = open(spec, encoding="utf-8", errors="replace").read()
4243
+ m = re.search(r'^##\s+Change History\s*$', st, re.M)
4244
+ rows = re.findall(r'^\|\s*(v\d+(?:\.\d+)?)\s*\|', st[m.end():] if m else "", re.M)
4245
+ hv = re.search(r'^\*\*Version\*\*:\s*(v[\d.]+)', st, re.M)
4246
+ cands = rows + ([hv.group(1)] if hv else [])
4247
+ if cands: cur = max(cands, key=vtuple)
4248
+ text = open(doc, encoding="utf-8", errors="replace").read()
4249
+ # The ledger-survival fence: a plan whose update dropped the Change History section is
4250
+ # NOT baselined — a lost ledger silently baselined over could never be noticed again.
4251
+ hist = re.search(r'^##+\s*(?:\d+\.\s*)?Change History\s*$', text, re.M)
4252
+ if not hist:
4253
+ print(json.dumps({"ok": False, "version": cur,
4254
+ "error": "the plan document has no 'Change History' section — the write dropped the ledger; nothing was baselined"}))
4255
+ sys.exit(0)
4256
+ warnings = []
4257
+ if not re.search(r'^##+.*Assumptions', text, re.M):
4258
+ warnings.append("no 'Assumptions' section found")
4259
+ if not re.search(r'^##+.*(Workarounds|Deviations)', text, re.M):
4260
+ warnings.append("no 'Workarounds/Deviations' section found")
4261
+ row_txt = ""
4262
+ if not no_row:
4263
+ # Bounded to the Change History section; the row's cell count follows the section's
4264
+ # own table so the append fits the greenfield, UI and onboard-generated shapes alike.
4265
+ lines = text.split("\n")
4266
+ hline = text[:hist.start()].count("\n")
4267
+ end = len(lines)
4268
+ for i in range(hline + 1, len(lines)):
4269
+ if re.match(r'^##', lines[i]): end = i; break
4270
+ tbl = [i for i in range(hline + 1, end) if lines[i].lstrip().startswith("|")]
4271
+ ncells = 5
4272
+ if tbl: ncells = max(3, lines[tbl[0]].strip().strip("|").count("|") + 1)
4273
+ change = note or ("Conformed to spec %s" % (cur or "(unversioned)"))
4274
+ if ids: change = "%s — %s" % (change, ids)
4275
+ change = change.replace("|", "/").replace("\n", " ")
4276
+ cells = [cur or "v?", datetime.date.today().isoformat(), change] + ["—"] * (ncells - 3)
4277
+ row_txt = "| " + " | ".join(cells[:ncells]) + " |"
4278
+ lines.insert((tbl[-1] + 1) if tbl else end, row_txt)
4279
+ text = "\n".join(lines)
4280
+ if cur:
4281
+ text = re.sub(r'^(\*\*Version\*\*:\s*)v[\d.]+', r'\g<1>' + cur, text, count=1, flags=re.M)
4282
+ open(doc, "w", encoding="utf-8").write(text)
4283
+ try: track = json.load(open(track_path, encoding="utf-8"))
4284
+ except Exception: track = {}
4285
+ track[os.path.basename(doc)] = {
4286
+ "spec_version": cur,
4287
+ "sha256": hashlib.sha256(text.encode("utf-8")).hexdigest(),
4288
+ "updated": datetime.datetime.now().isoformat(timespec="seconds")}
4289
+ open(track_path, "w", encoding="utf-8").write(json.dumps(track, indent=2) + "\n")
4290
+ print(json.dumps({"ok": True, "version": cur, "row": row_txt, "warnings": warnings}))
4291
+ '@
4292
+
4293
+ function Invoke-PlanCheck {
4294
+ param([string[]]$Rest)
4295
+ $fdArg = ''; $doc = ''
4296
+ for ($i = 0; $i -lt $Rest.Count; $i++) { switch ($Rest[$i]) { { $_ -in '--feature-dir','-FeatureDir' } { $fdArg = $Rest[++$i] } { $_ -in '--doc','-Doc' } { $doc = $Rest[++$i] } } }
4297
+ if (-not $doc) { Write-Error 'plan-check: --doc required'; exit 1 }
4298
+ $py = Get-Py; if (-not $py) { Write-Error 'plan-check: python3 required'; exit 1 }
4299
+ $repo = Get-RepoRoot
4300
+ $fd = Resolve-FeatureDir -Arg $fdArg -RepoRoot $repo
4301
+ if (-not $fd) { Write-Error 'plan-check: no feature set and no --feature-dir'; exit 1 }
4302
+ $env:AW_DOC = $doc; $env:AW_FD = $fd
4303
+ $PyPlanCheck | & $py -
4304
+ Remove-Item Env:AW_DOC, Env:AW_FD -ErrorAction SilentlyContinue
4305
+ }
4306
+
4307
+ function Invoke-PlanStamp {
4308
+ param([string[]]$Rest)
4309
+ $fdArg = ''; $doc = ''; $ids = ''; $note = ''; $noRow = 'false'
4310
+ for ($i = 0; $i -lt $Rest.Count; $i++) { switch ($Rest[$i]) { { $_ -in '--feature-dir','-FeatureDir' } { $fdArg = $Rest[++$i] } { $_ -in '--doc','-Doc' } { $doc = $Rest[++$i] } { $_ -in '--ids','-Ids' } { $ids = $Rest[++$i] } { $_ -in '--note','-Note' } { $note = $Rest[++$i] } { $_ -in '--no-row','-NoRow' } { $noRow = 'true' } } }
4311
+ if (-not $doc) { Write-Error 'plan-stamp: --doc required'; exit 1 }
4312
+ $py = Get-Py; if (-not $py) { Write-Error 'plan-stamp: python3 required'; exit 1 }
4313
+ $repo = Get-RepoRoot
4314
+ $fd = Resolve-FeatureDir -Arg $fdArg -RepoRoot $repo
4315
+ if (-not $fd) { Write-Error 'plan-stamp: no feature set and no --feature-dir'; exit 1 }
4316
+ $env:AW_DOC = $doc; $env:AW_FD = $fd; $env:AW_IDS = $ids; $env:AW_NOTE = $note; $env:AW_NOROW = $noRow
4317
+ $PyPlanStamp | & $py -
4318
+ Remove-Item Env:AW_DOC, Env:AW_FD, Env:AW_IDS, Env:AW_NOTE, Env:AW_NOROW -ErrorAction SilentlyContinue
4319
+ }
4320
+
4321
+ # ───────────────────────────────── gate-result ──────────────────────────────
4322
+ # The machine-readable verdict every analyze gate writes beside its markdown
4323
+ # report. CI cannot branch on prose, and a verdict is exactly the kind of dated,
4324
+ # derived record the model must never write — so the script writes it.
4325
+ #
4326
+ # Shared by design: analyze-design writes one per feature, and analyze-slice /
4327
+ # analyze-code will write one per story and per run. The CORE keys are fixed
4328
+ # (gate, status, feature, spec_version, story, gap_count, gap_refs, report,
4329
+ # generated_at) so a pipeline can read any gate's result with one expression;
4330
+ # everything gate-specific arrives through repeatable --field k=v and lands under
4331
+ # "fields", where it cannot destabilise that core.
4332
+ #
4333
+ # NOTE the returned `ok` means THE FILE WAS WRITTEN. The pass/fail verdict is
4334
+ # `status` — binding a workflow gate to `ok` would pass on every run.
4335
+ $PyGateResult = @'
4336
+ import json, os, sys, datetime
4337
+ gate = (os.environ.get("AW_GATE", "") or "").strip() or "gate"
4338
+ fd = os.environ.get("AW_FD", "")
4339
+ report = (os.environ.get("AW_REPORT", "") or "").strip()
4340
+ out = (os.environ.get("AW_OUT", "") or "").strip()
4341
+ # "pass" only on an explicit affirmative. An absent or unreadable verdict is a FAIL,
4342
+ # because a result that defaults green turns every broken run into a passing one.
4343
+ ok = (os.environ.get("AW_OK", "") or "").strip().lower() in ("true", "1", "yes", "pass", "ok")
4344
+ # Written BESIDE the markdown report and named after it, so a job holding either path
4345
+ # holds the other. --out overrides; with no report named at all it falls back to a
4346
+ # dotfile in the feature directory under the gate's own name.
4347
+ if not out:
4348
+ out = (os.path.splitext(report)[0] + ".json") if report else os.path.join(fd, ".aw-gate-%s.json" % gate)
4349
+ try: gap_count = int((os.environ.get("AW_GAPS", "") or "").strip() or 0)
4350
+ except ValueError: gap_count = 0
4351
+ refs = [r.strip() for r in (os.environ.get("AW_REFS", "") or "").replace(";", ",").split(",") if r.strip()]
4352
+ # A fail reporting zero findings reads as green to anything that sums the number
4353
+ # rather than reading the status, so a red verdict always carries at least one.
4354
+ if not ok and gap_count < 1: gap_count = max(1, len(refs))
4355
+ # --field k=v, repeatable, arriving newline-separated. Keeps the CORE schema below
4356
+ # fixed for every gate while each one carries its own detail underneath.
4357
+ fields = {}
4358
+ for line in (os.environ.get("AW_FIELDS", "") or "").splitlines():
4359
+ k, sep, v = line.partition("=")
4360
+ if sep and k.strip(): fields[k.strip()] = v.strip()
4361
+ res = {"gate": gate,
4362
+ "status": "pass" if ok else "fail",
4363
+ "feature": os.path.basename(fd.rstrip("/\\")),
4364
+ "feature_dir": fd,
4365
+ "spec_version": (os.environ.get("AW_VERSION", "") or "").strip(),
4366
+ "story": (os.environ.get("AW_STORY", "") or "").strip(),
4367
+ "gap_count": gap_count,
4368
+ "gap_refs": refs,
4369
+ "report": report,
4370
+ "note": (os.environ.get("AW_NOTE", "") or "").strip(),
4371
+ "fields": fields,
4372
+ "generated_at": datetime.datetime.now().isoformat(timespec="seconds")}
4373
+ d = os.path.dirname(out)
4374
+ if d and not os.path.isdir(d): os.makedirs(d, exist_ok=True)
4375
+ open(out, "w", encoding="utf-8").write(json.dumps(res, indent=2) + "\n")
4376
+ print(json.dumps({"ok": True, "result_file": out, "status": res["status"], "gap_count": gap_count}))
4377
+ '@
4378
+
4379
+ function Invoke-GateResult {
4380
+ param([string[]]$Rest)
4381
+ $fdArg = ''; $gate = ''; $ok = ''; $version = ''; $story = ''; $report = ''; $out = ''; $gaps = ''; $refs = ''; $note = ''; $fields = @()
4382
+ for ($i = 0; $i -lt $Rest.Count; $i++) { switch ($Rest[$i]) { { $_ -in '--gate','-Gate' } { $gate = $Rest[++$i] } { $_ -in '--feature-dir','-FeatureDir' } { $fdArg = $Rest[++$i] } { $_ -in '--ok','-Ok' } { $ok = $Rest[++$i] } { $_ -in '--spec-version','-SpecVersion' } { $version = $Rest[++$i] } { $_ -in '--story','-Story' } { $story = $Rest[++$i] } { $_ -in '--report','-Report' } { $report = $Rest[++$i] } { $_ -in '--out','-Out' } { $out = $Rest[++$i] } { $_ -in '--gap-count','-GapCount' } { $gaps = $Rest[++$i] } { $_ -in '--gap-refs','-GapRefs' } { $refs = $Rest[++$i] } { $_ -in '--note','-Note' } { $note = $Rest[++$i] } { $_ -in '--field','-Field' } { $fields += $Rest[++$i] } } }
4383
+ if (-not $gate) { Write-Error 'gate-result: --gate required'; exit 1 }
4384
+ $py = Get-Py; if (-not $py) { Write-Error 'gate-result: python3 required'; exit 1 }
4385
+ $repo = Get-RepoRoot
4386
+ $fd = Resolve-FeatureDir -Arg $fdArg -RepoRoot $repo
4387
+ if (-not $fd) { Write-Error 'gate-result: no feature set and no --feature-dir'; exit 1 }
4388
+ $env:AW_GATE = $gate; $env:AW_FD = $fd; $env:AW_OK = $ok; $env:AW_VERSION = $version; $env:AW_STORY = $story
4389
+ $env:AW_REPORT = $report; $env:AW_OUT = $out; $env:AW_GAPS = $gaps; $env:AW_REFS = $refs; $env:AW_NOTE = $note
4390
+ $env:AW_FIELDS = ($fields -join "`n")
4391
+ $PyGateResult | & $py -
4392
+ Remove-Item Env:AW_GATE, Env:AW_FD, Env:AW_OK, Env:AW_VERSION, Env:AW_STORY, Env:AW_REPORT, Env:AW_OUT, Env:AW_GAPS, Env:AW_REFS, Env:AW_NOTE, Env:AW_FIELDS -ErrorAction SilentlyContinue
4393
+ }
4394
+
4395
+ # ──────────────────────────────── gate-read ────────────────────────────────
4396
+ # THE OTHER HALF OF gate-result. Twin of the bash action; the python payload is
4397
+ # byte-identical by contract.
4398
+ $PyGateRead = @'
4399
+ import json, os
4400
+ gate = (os.environ.get("AW_GATE", "") or "").strip()
4401
+ fd = os.environ.get("AW_FD", "")
4402
+ report = (os.environ.get("AW_REPORT", "") or "").strip()
4403
+ path = (os.environ.get("AW_FILE", "") or "").strip()
4404
+ # Resolved the same way gate-result names it, so the writer and the reader cannot drift:
4405
+ # beside the markdown report and named after it. The per-gate defaults are the report paths
4406
+ # those two workflows set; the dotfile is gate-result's own fallback.
4407
+ DEFAULT = {"analyze-design": "plan-analyze-report.json",
4408
+ "analyze-slice": "slice-analyze-report.json"}
4409
+ if not path:
4410
+ if report: path = os.path.splitext(report)[0] + ".json"
4411
+ elif gate in DEFAULT: path = os.path.join(fd, DEFAULT[gate])
4412
+ else: path = os.path.join(fd, ".aw-gate-%s.json" % gate)
4413
+
4414
+ out = {"ok": True, "gate": gate, "result_file": path, "exists": os.path.isfile(path),
4415
+ "status": "", "certified": False, "aborted": False, "note": "",
4416
+ "spec_version": "", "story": "", "report": "", "generated_at": "",
4417
+ "gap_count": 0, "gap_refs_csv": "",
4418
+ "backend_sha256": "", "frontend_sha256": "",
4419
+ "backend_in_scope": "", "frontend_in_scope": "", "fields": {}}
4420
+ res = {}
4421
+ if out["exists"]:
4422
+ try: res = json.load(open(path, encoding="utf-8"))
4423
+ except Exception: res = {}
4424
+ if not isinstance(res, dict) or not res:
4425
+ out["note"] = ("no readable verdict at %s — this gate has not certified anything here"
4426
+ % path)
4427
+ print(json.dumps(out)); raise SystemExit(0)
4428
+
4429
+ fields = res.get("fields") or {}
4430
+ if not isinstance(fields, dict): fields = {}
4431
+ out.update(status=(res.get("status") or "").strip(),
4432
+ note=(res.get("note") or "").strip(),
4433
+ spec_version=(res.get("spec_version") or "").strip(),
4434
+ story=(res.get("story") or "").strip(),
4435
+ report=(res.get("report") or "").strip(),
4436
+ generated_at=(res.get("generated_at") or "").strip(),
4437
+ gap_count=res.get("gap_count") or 0,
4438
+ gap_refs_csv=", ".join(res.get("gap_refs") or []),
4439
+ fields=fields,
4440
+ backend_sha256=(fields.get("backend_sha256") or "").strip(),
4441
+ frontend_sha256=(fields.get("frontend_sha256") or "").strip(),
4442
+ backend_in_scope=(fields.get("backend_in_scope") or "").strip(),
4443
+ frontend_in_scope=(fields.get("frontend_in_scope") or "").strip())
4444
+ # A verdict written before any analysis ran carries no spec version, because the workflow
4445
+ # has not read one yet. That, and not the note's wording, is what separates the aborted red
4446
+ # from a real one — the note is prose and prose gets edited.
4447
+ out["aborted"] = out["status"] != "pass" and not out["spec_version"]
4448
+ out["certified"] = out["status"] == "pass"
4449
+ print(json.dumps(out))
4450
+ '@
4451
+
4452
+ function Invoke-GateRead {
4453
+ param([string[]]$Rest)
4454
+ $fdArg = ''; $gate = ''; $report = ''; $file = ''
4455
+ for ($i = 0; $i -lt $Rest.Count; $i++) { switch ($Rest[$i]) { { $_ -in '--feature-dir','-FeatureDir' } { $fdArg = $Rest[++$i] } { $_ -in '--gate','-Gate' } { $gate = $Rest[++$i] } { $_ -in '--report','-Report' } { $report = $Rest[++$i] } { $_ -in '--file','-File' } { $file = $Rest[++$i] } } }
4456
+ if (-not $gate) { Write-Error 'gate-read: --gate required'; exit 1 }
4457
+ $py = Get-Py; if (-not $py) { Write-Error 'gate-read: python3 required'; exit 1 }
4458
+ $repo = Get-RepoRoot
4459
+ $fd = Resolve-FeatureDir -Arg $fdArg -RepoRoot $repo
4460
+ if (-not $fd) { Write-Error 'gate-read: no feature set and no --feature-dir'; exit 1 }
4461
+ $env:AW_GATE = $gate; $env:AW_FD = $fd; $env:AW_REPORT = $report; $env:AW_FILE = $file
4462
+ $PyGateRead | & $py -
4463
+ Remove-Item Env:AW_GATE, Env:AW_FD, Env:AW_REPORT, Env:AW_FILE -ErrorAction SilentlyContinue
4464
+ }
4465
+
4466
+ # ─────────────── story-plan-check / story-plan-doc / log-append ───────────────
4467
+ # The per-story execution design ("story design", one document per lane) + the
4468
+ # feature's append-only logs. Twins of the bash actions; the python payloads are
4469
+ # byte-identical by contract.
4470
+ $PyStoryPlanCheck = @'
4471
+ import json, os, re, sys
4472
+ fd = os.environ["AW_FD"]
4473
+ sdir = os.path.join(fd, "stories")
4474
+ spec = os.path.join(fd, "spec.md")
4475
+
4476
+ def parse_fm(text):
4477
+ """Frontmatter as a flat dict — inline and block-list values both fold to the
4478
+ inline shape (same reader story-refs uses, for the same reason)."""
4479
+ m = re.match(r'^---\s*\n(.*?)\n---\s*\n', text, re.S)
4480
+ if not m: return {}
4481
+ fm, key, block = {}, None, set()
4482
+ for line in m.group(1).split("\n"):
4483
+ km = re.match(r'^([A-Za-z_]+):\s*(.*)$', line)
4484
+ if km:
4485
+ key = km.group(1); fm[key] = km.group(2).strip(); continue
4486
+ im = re.match(r'^\s+-\s+(.*)$', line) if key else None
4487
+ if im and (key in block or not fm[key]):
4488
+ block.add(key)
4489
+ fm[key] = (fm[key] + ", " + im.group(1).strip()) if fm[key] else im.group(1).strip()
4490
+ return fm
4491
+
4492
+ def vtuple(v):
4493
+ try: return tuple(int(x) for x in v.lstrip("vV").split("."))
4494
+ except Exception: return (0,)
4495
+
4496
+ # ---- the backlog ------------------------------------------------------------
4497
+ stories = []
4498
+ if os.path.isdir(sdir):
4499
+ for name in sorted(os.listdir(sdir)):
4500
+ # stories.md is the GENERATED index beside the stories, not a story
4501
+ if not name.endswith(".md") or name == "stories.md": continue
4502
+ p = os.path.join(sdir, name)
4503
+ if not os.path.isfile(p): continue
4504
+ text = open(p, encoding="utf-8", errors="replace").read()
4505
+ fm = parse_fm(text)
4506
+ sid = fm.get("id") or name[:-3]
4507
+ stories.append({"id": sid, "file_id": name[:-3],
4508
+ "status": (fm.get("status") or "open").strip().lower(),
4509
+ "type": (fm.get("type") or "functional").strip().lower(),
4510
+ "title": (fm.get("title") or "").strip().strip("[]"),
4511
+ "spec_version": (fm.get("spec_version") or "").strip(),
4512
+ "cites": re.findall(r'\b(?:FR|BR)-\d+', fm.get("exercises", "")),
4513
+ "wave": (fm.get("wave") or "").strip(),
4514
+ "deps": [d for d in re.split(r'[,\s\[\]"\']+',
4515
+ fm.get("depends_on", "") or "")
4516
+ if re.match(r'^[A-Za-z][\w.]*-\d+$', d)],
4517
+ "fm": fm, "path": p, "text": text})
4518
+
4519
+ def lanes(s):
4520
+ """backend / frontend out of a csv or an inline list; anything else is not a lane."""
4521
+ out = []
4522
+ for tok in re.split(r'[,\s\[\]"\']+', (s or "").lower()):
4523
+ if tok in ("backend", "frontend") and tok not in out: out.append(tok)
4524
+ return sorted(out)
4525
+ open_stories = [s for s in stories if s["status"] == "open"]
4526
+ open_ids = [s["id"] for s in open_stories]
4527
+ digest = "\n".join(" %-16s %s%s" % (s["id"], s["title"] or "(untitled)",
4528
+ (" cites " + ", ".join(s["cites"])) if s["cites"] else "")
4529
+ for s in open_stories) or " (no open stories)"
4530
+
4531
+ # ---- which story ------------------------------------------------------------
4532
+ want = (os.environ.get("AW_STORY") or "").strip()
4533
+ free = os.environ.get("AW_INPUT") or ""
4534
+ target, reason = None, ""
4535
+ if want:
4536
+ hit = [s for s in stories if s["id"] == want or s["file_id"] == want]
4537
+ target = hit[0] if hit else None
4538
+ if not target: reason = "not-found"
4539
+ else:
4540
+ # every known story id appearing as a whole token in the free text; one match
4541
+ # resolves, several is a question, none is a question
4542
+ named = [s for s in stories
4543
+ if re.search(r'(?<![\w-])' + re.escape(s["id"]) + r'(?![\w-])', free)]
4544
+ if len(named) == 1: target = named[0]
4545
+ else: reason = "ambiguous" if named else "none-given"
4546
+
4547
+ out = {"ok": True, "stories_dir": sdir, "stories_exist": os.path.isdir(sdir),
4548
+ "open_count": len(open_stories), "any_open": bool(open_stories),
4549
+ "open_ids": open_ids, "open_ids_csv": ", ".join(open_ids), "digest": digest,
4550
+ "resolved": bool(target), "needs_pick": not target, "pick_reason": reason,
4551
+ "story": "", "story_path": "", "story_status": "", "story_open": False,
4552
+ "story_type": "", "is_technical": False,
4553
+ "status_msg": "", "story_title": "", "exercises_csv": "", "constraints_csv": "",
4554
+ "story_spec_version": "", "current_version": "", "stale_csv": "", "stale_note": "",
4555
+ "story_wave": "", "depends_on_csv": "", "open_deps_csv": "",
4556
+ "unresolved_deps_csv": "", "deps_note": "", "deps_clear": True,
4557
+ "designed_lanes_csv": "", "dropped_lanes_csv": "", "lane_keys_present": False,
4558
+ "be_lane_designed": False, "fe_lane_designed": False,
4559
+ "be_lane_dropped": False, "fe_lane_dropped": False,
4560
+ "story_dir": "", "if_tmp": "", "legacy_doc": "", "legacy_doc_exists": False,
4561
+ "be_doc_path": "", "be_doc_exists": False, "be_next_pass": 1, "be_pass_tmp": "",
4562
+ "be_last_pass": 0, "be_doc_spec_version": "", "be_doc_stale": False,
4563
+ "be_pass_plan_hash": "",
4564
+ "fe_doc_path": "", "fe_doc_exists": False, "fe_next_pass": 1, "fe_pass_tmp": "",
4565
+ "fe_last_pass": 0, "fe_doc_spec_version": "", "fe_doc_stale": False,
4566
+ "fe_pass_plan_hash": "",
4567
+ "adr_path": os.path.join(fd, "adr.md"), "adr_exists": os.path.isfile(os.path.join(fd, "adr.md")),
4568
+ "if_path": os.path.join(fd, "interfaces.md"), "if_exists": os.path.isfile(os.path.join(fd, "interfaces.md")),
4569
+ "spec_exists": os.path.isfile(spec)}
4570
+
4571
+ # ---- the ledger (widest-wins current version, same rule ledger-append uses) --
4572
+ rows, cur = [], ""
4573
+ if os.path.isfile(spec):
4574
+ stext = open(spec, encoding="utf-8", errors="replace").read()
4575
+ m = re.search(r'^##\s+Change History\s*$', stext, re.M)
4576
+ if m:
4577
+ for line in stext[m.end():].splitlines():
4578
+ rm = re.match(r'^\|\s*(v\d+(?:\.\d+)?)\s*\|', line)
4579
+ if rm: rows.append((rm.group(1), line))
4580
+ hv = re.search(r'^\*\*Version\*\*:\s*(v[\d.]+)', stext, re.M)
4581
+ cands = [r[0] for r in rows] + ([hv.group(1)] if hv else [])
4582
+ if cands: cur = max(cands, key=vtuple)
4583
+ out["current_version"] = cur
4584
+
4585
+ if not target:
4586
+ print(json.dumps(out)); sys.exit(0)
4587
+
4588
+ # ---- the resolved story -----------------------------------------------------
4589
+ status = target["status"]
4590
+ out.update(story=target["id"], story_path=target["path"], story_status=status,
4591
+ story_open=(status == "open"), story_title=target["title"],
4592
+ story_type=target["type"], is_technical=(target["type"] == "technical"),
4593
+ exercises_csv=", ".join(target["cites"]),
4594
+ story_spec_version=target["spec_version"])
4595
+ if status != "open":
4596
+ verb = {"closed": "was closed — its plan is history. Remaining work needs its own story "
4597
+ "(sync-stories mints a follow-on when the spec moves)",
4598
+ "cancelled": "was cancelled — cancelled work is not planned; open a new story if the need returns",
4599
+ "draft": "is a draft proposal — run /appweaver sync-spec to merge it into the contract first; "
4600
+ "story-plan designs only against merged requirements"}
4601
+ out["status_msg"] = "Story %s %s." % (
4602
+ target["id"], verb.get(status, "has status '%s', not open" % status))
4603
+
4604
+ # THE BOUNDS COME FROM FRONTMATTER, which story-stamp lifts from the spec. They are barred
4605
+ # from exercises: by design — a constraint is met, not delivered — and they were read out of
4606
+ # the BODY's ## Constraints section until that section turned out to be the one gate surface
4607
+ # the kit did not write: a model that omitted an id dropped a bound out of the generation
4608
+ # prompt with nothing able to contradict it.
4609
+ #
4610
+ # ABSENT IS NOT EMPTY. A story stamped before the field existed carries its ids only in the
4611
+ # body, so a missing key falls back to the section; an explicit `constraints: []` is an
4612
+ # answer and is taken as one. The fallback goes once every live backlog is re-stamped.
4613
+ if "constraints" in target["fm"]:
4614
+ cons = sorted(set(re.findall(r'\b(?:CN|DC|IC|UX)-\d+', target["fm"]["constraints"])))
4615
+ else:
4616
+ cm = re.search(r'^##\s+Constraints\s*$(.*?)(?=^##\s|\Z)', target["text"], re.M | re.S)
4617
+ cons = sorted(set(re.findall(r'\b(?:CN|DC|IC|UX)-\d+', cm.group(1)))) if cm else []
4618
+ out["constraints_csv"] = ", ".join(cons)
4619
+
4620
+ # WHAT HAS TO LAND FIRST. sync-stories computes depends_on: and wave: and stamps both, and
4621
+ # until now nothing downstream read either — the ordering was recorded and never enforced.
4622
+ # Two different misses, kept apart: a dependency whose story is still OPEN here is work in
4623
+ # progress, and one with no story file in this feature is UNRESOLVED, which is the ordinary
4624
+ # shape of a cross-feature edge (Payment-004 from Order) and not the same as satisfied.
4625
+ #
4626
+ # The wave is surfaced and NOT gated. A story becomes startable when its own dependencies
4627
+ # land, not when the whole previous wave finishes, so warning on "an open story in a lower
4628
+ # wave" would serialise a wave that exists precisely to be unordered.
4629
+ # WHICH LANES THIS STORY WAS DESIGNED FOR, AND WHICH WERE DROPPED. story-plan stamps both,
4630
+ # because one of them cannot say the difference: a story with no UI design either has no
4631
+ # user-facing surface or had its UI lane dropped when it was designed, and those two states
4632
+ # are the same absence on disk. `lane_keys_present` is what keeps the distinction honest for
4633
+ # a story stamped before the fields existed — it has NEITHER key, and absent must never be
4634
+ # read as "no surface".
4635
+ des = lanes(target["fm"].get("designed_lanes", ""))
4636
+ drp = lanes(target["fm"].get("dropped_lanes", ""))
4637
+ out.update(designed_lanes_csv=", ".join(des), dropped_lanes_csv=", ".join(drp),
4638
+ lane_keys_present=("designed_lanes" in target["fm"]
4639
+ or "dropped_lanes" in target["fm"]),
4640
+ be_lane_designed=("backend" in des), fe_lane_designed=("frontend" in des),
4641
+ be_lane_dropped=("backend" in drp), fe_lane_dropped=("frontend" in drp))
4642
+
4643
+ deps = target["deps"]
4644
+ by_id = {s["id"]: s for s in stories}
4645
+ open_deps = [d for d in deps if d in by_id and by_id[d]["status"] == "open"]
4646
+ unresolved = [d for d in deps if d not in by_id]
4647
+ out.update(story_wave=target["wave"], depends_on_csv=", ".join(deps),
4648
+ open_deps_csv=", ".join(open_deps),
4649
+ unresolved_deps_csv=", ".join(unresolved),
4650
+ deps_clear=not (open_deps or unresolved))
4651
+ if open_deps or unresolved:
4652
+ parts = []
4653
+ if open_deps:
4654
+ parts.append("still open in this feature: %s" % ", ".join(open_deps))
4655
+ if unresolved:
4656
+ parts.append("no story file here — check the feature that owns them: %s"
4657
+ % ", ".join(unresolved))
4658
+ out["deps_note"] = (
4659
+ "ORDERING: %s declares depends_on: %s, and %s. This is a notice, not a refusal — "
4660
+ "the dependency is about CODE ordering, and calling into work that has not landed "
4661
+ "is where it starts to cost something."
4662
+ % (target["id"], ", ".join(deps), "; ".join(parts)))
4663
+
4664
+ # staleness: ledger rows ABOVE the story's stamp naming an id the story carries —
4665
+ # exercises: AND the Constraints section, so a moved bound is announced too
4666
+ sv = target["spec_version"]
4667
+ if sv:
4668
+ carried = set(target["cites"]) | set(cons)
4669
+ moved = [r for r in rows if vtuple(r[0]) > vtuple(sv)]
4670
+ stale = sorted({i for _v, l in moved for i in re.findall(r'[A-Z]{2}-\d+', l) if i in carried})
4671
+ out["stale_csv"] = ", ".join(stale)
4672
+ if stale:
4673
+ out["stale_note"] = (
4674
+ "CAUTION: the spec moved above this story's stamp (%s -> %s) on ids this story "
4675
+ "carries: %s. Design against the CURRENT spec text, record the divergence under "
4676
+ "Risks, and consider /appweaver sync-stories to bring the backlog back in step."
4677
+ % (sv, cur or "?", ", ".join(stale)))
4678
+
4679
+ # doc / pass state + the temp paths the workflow writes through. ONE DOCUMENT PER
4680
+ # LANE: the service design and the UI design are authored by different steps, under
4681
+ # different rule sets, from different code, and are read by different implement
4682
+ # commands — folded into one file, every one of those becomes a section boundary the
4683
+ # next reader has to trust. Pass numbers are per file, so a run that designs only the
4684
+ # backend leaves the frontend's count exactly where it was.
4685
+ #
4686
+ # legacy_doc is the pre-split story-plan.md. It is REPORTED, never read and never
4687
+ # written: a design nobody consumes must not sit silently beside two that are.
4688
+ stdir = os.path.join(sdir, target["id"])
4689
+ legacy = os.path.join(stdir, "story-plan.md")
4690
+ out.update(story_dir=stdir, if_tmp=os.path.join(stdir, ".if-entries.tmp.md"),
4691
+ legacy_doc=legacy, legacy_doc_exists=os.path.isfile(legacy))
4692
+ for lane, stem in (("be", "backend"), ("fe", "frontend")):
4693
+ doc = os.path.join(stdir, "story-%s-plan.md" % stem)
4694
+ out[lane + "_doc_path"] = doc
4695
+ out[lane + "_doc_exists"] = os.path.isfile(doc)
4696
+ out[lane + "_pass_tmp"] = os.path.join(stdir, ".%s-pass.tmp.md" % stem)
4697
+ if out[lane + "_doc_exists"]:
4698
+ d = open(doc, encoding="utf-8", errors="replace").read()
4699
+ nums = [int(n) for n in re.findall(r'^##\s+Design pass\s+(\d+)', d, re.M)]
4700
+ out[lane + "_next_pass"] = (max(nums) + 1) if nums else 1
4701
+ # What implement needs on top of the path: WHICH pass it builds from (the last
4702
+ # one — earlier passes are superseded history) and the spec version that pass was
4703
+ # designed against. A design behind the current spec is ANNOUNCED at implement,
4704
+ # never refused: the story is legitimately in flight, and the spec may well have
4705
+ # moved on ids this story does not carry. stale_csv is the sharper signal and it
4706
+ # is already computed above.
4707
+ out[lane + "_last_pass"] = max(nums) if nums else 0
4708
+ dv = (parse_fm(d).get("spec_version") or "").strip().strip('"')
4709
+ out[lane + "_doc_spec_version"] = dv
4710
+ out[lane + "_doc_stale"] = bool(dv and cur and vtuple(dv) < vtuple(cur))
4711
+ # THE FEATURE PLAN THIS PASS WAS DESIGNED AGAINST, as analyze-design certified it.
4712
+ # A story pass is written once and read forever, so comparing only the CURRENT plan
4713
+ # against the CURRENT verdict leaves the case law 40 is actually about: a pass
4714
+ # designed against plan H1 still generating after the plan was edited to H2 and
4715
+ # re-gated. The hash is script-written into the pass header by story-plan-doc; the
4716
+ # LAST pass is the one implement builds from, so it is the last one read here.
4717
+ hs = re.findall(r'^##\s+Design pass\s+\d+\b[^\n]*?\(plan\s+([0-9a-f]{8,64})\)',
4718
+ d, re.M)
4719
+ out[lane + "_pass_plan_hash"] = hs[-1] if hs else ""
4720
+ print(json.dumps(out))
4721
+ '@
4722
+
4723
+ $PyStoryPlanDoc = @'
4724
+ import json, os, re, sys, datetime
4725
+ fd = os.environ["AW_FD"]; story = os.environ["AW_STORY"].strip()
4726
+ pf = os.environ["AW_PASS"]; ver = (os.environ.get("AW_VER") or "").strip()
4727
+ lane = (os.environ.get("AW_LANE") or "backend").strip().lower()
4728
+ phash = re.sub(r'[^0-9a-f]', '', (os.environ.get("AW_PLAN_HASH") or "").strip().lower())
4729
+ sdir = os.path.join(fd, "stories", story)
4730
+ doc = os.path.join(sdir, "story-%s-plan.md" % lane)
4731
+
4732
+ def bail(msg, code=2):
4733
+ print(json.dumps({"ok": False, "doc": doc, "error": msg}))
4734
+ sys.stderr.write(msg + "\n"); sys.exit(code)
4735
+
4736
+ if lane not in ("backend", "frontend"):
4737
+ bail("story-plan-doc: --lane must be backend or frontend, not '%s'" % lane)
4738
+ if not os.path.isfile(os.path.join(fd, "stories", story + ".md")):
4739
+ bail("story-plan-doc: no story file for '%s' — the plan lives beside a story that exists" % story)
4740
+ if not os.path.isfile(pf):
4741
+ bail("story-plan-doc: pass file missing at %s — the authoring step wrote nothing" % pf)
4742
+ content = open(pf, encoding="utf-8", errors="replace").read().strip()
4743
+ if not content:
4744
+ bail("story-plan-doc: the authored pass is empty — nothing appended")
4745
+ # the pass header is SCRIPT-written; strip one the model wrote anyway rather than
4746
+ # letting the doc double-number
4747
+ content = re.sub(r'^##\s+Design pass\b[^\n]*\n+', '', content, count=1)
4748
+
4749
+ LANE_WORD = "SERVICE" if lane == "backend" else "UI"
4750
+ LANE_READER = "/appweaver implement" if lane == "backend" else "/appweaver implement-ui"
4751
+ os.makedirs(sdir, exist_ok=True)
4752
+ today = datetime.date.today().isoformat()
4753
+ created = not os.path.isfile(doc)
4754
+ if created:
4755
+ open(doc, "w", encoding="utf-8").write("""---
4756
+ created: %s
4757
+ updated: %s
4758
+ passes: 0
4759
+ spec_version: ""
4760
+ ---
4761
+
4762
+ <!--
4763
+ STORY DESIGN (%s LANE) — the ephemeral execution design for ONE story, read by
4764
+ %s.
4765
+
4766
+ Identity is positional: the file lives in the story's directory and carries no
4767
+ story id in its text. Every /appweaver story-plan run APPENDS a "## Design pass N"
4768
+ section to THIS lane's file — nothing is edited in place, so a manual edit to an
4769
+ earlier pass survives a re-run. THE LATEST PASS WINS; earlier passes are the
4770
+ iteration history.
4771
+
4772
+ EDIT IT BEFORE YOU IMPLEMENT. This is the document a design is corrected in by
4773
+ hand: change the latest pass and implement builds what you changed. Re-running
4774
+ story-plan instead appends a fresh pass that supersedes it, so hand-edit to
4775
+ adjust, re-run to redesign.
4776
+
4777
+ It is scaffolding for confirming the implementation strategy — archived with the
4778
+ story at close, never maintained afterwards. Durable decisions do not live here:
4779
+ the latest pass PROPOSES ADRs (ratified into the feature's adr.md at close), and
4780
+ published-surface changes are appended to the feature's interfaces.md as proposed
4781
+ entries at design time. spec_version below is the spec the LATEST pass was
4782
+ designed against. The other lane's design, where the project has one, sits beside
4783
+ this file — the two are written apart on purpose and neither restates the other.
4784
+ -->
4785
+ """ % (today, today, LANE_WORD, LANE_READER))
4786
+ text = open(doc, encoding="utf-8", errors="replace").read()
4787
+ nums = [int(n) for n in re.findall(r'^##\s+Design pass\s+(\d+)', text, re.M)]
4788
+ n = (max(nums) + 1) if nums else 1
4789
+ header = "## Design pass %d — %s%s%s" % (
4790
+ n, today, (" (spec %s)" % ver) if ver else "",
4791
+ (" (plan %s)" % phash) if phash else "")
4792
+ text = text.rstrip("\n") + "\n\n" + header + "\n\n" + content + "\n"
4793
+ # frontmatter stamps — first match only, which is the frontmatter by position
4794
+ text = re.sub(r'^(updated:).*$', r'\g<1> ' + today, text, count=1, flags=re.M)
4795
+ text = re.sub(r'^(passes:).*$', r'\g<1> %d' % n, text, count=1, flags=re.M)
4796
+ if ver:
4797
+ text = re.sub(r'^(spec_version:).*$', r'\g<1> %s' % ver, text, count=1, flags=re.M)
4798
+ open(doc, "w", encoding="utf-8").write(text)
4799
+ os.remove(pf)
4800
+ print(json.dumps({"ok": True, "doc": doc, "lane": lane, "pass": n, "created": created,
4801
+ "spec_version": ver, "plan_hash": phash, "story_dir": sdir}))
4802
+ '@
4803
+
4804
+ $PyLogAppend = @'
4805
+ import json, os, re, sys, time, errno, datetime
4806
+ fd = os.environ["AW_FD"]; log = os.environ["AW_LOG"]
4807
+ ef = os.environ["AW_ENTRIES"]; status = (os.environ.get("AW_STATUS") or "").strip()
4808
+ fname, prefix, default_status, title = {
4809
+ "interfaces": ("interfaces.md", "IF", "proposed", "Interface Log"),
4810
+ "adr": ("adr.md", "ADR", "accepted", "Architecture Decision Log")}[log]
4811
+ status = status or default_status
4812
+ path = os.path.join(fd, fname)
4813
+
4814
+ def bail(msg, code=2):
4815
+ print(json.dumps({"ok": False, "log": path, "error": msg}))
4816
+ sys.stderr.write(msg + "\n"); sys.exit(code)
4817
+
4818
+ if not os.path.isfile(ef):
4819
+ bail("log-append: entries file missing at %s — the authoring step wrote nothing" % ef)
4820
+ raw = open(ef, encoding="utf-8", errors="replace").read().strip()
4821
+ if not raw or raw.lower().rstrip(".") == "none":
4822
+ os.remove(ef)
4823
+ print(json.dumps({"ok": True, "log": path, "appended": 0, "ids_csv": "",
4824
+ "unknown_ids_csv": "", "bad_supersedes_csv": "", "none": True}))
4825
+ sys.exit(0)
4826
+
4827
+ # every entry must arrive as '## <PREFIX>-NEW — <title>': the script is the only id
4828
+ # authority, so a model-numbered entry is refused rather than trusted
4829
+ blocks = [b.strip() for b in re.split(r'(?=^##\s)', raw, flags=re.M) if b.strip()]
4830
+ bad = [b.splitlines()[0] for b in blocks
4831
+ if not re.match(r'^##\s+%s-NEW\s+[—-]+\s+\S' % prefix, b)]
4832
+ if bad:
4833
+ bail("log-append: every entry must start '## %s-NEW — <title>' (the script assigns "
4834
+ "ids); got: %s" % (prefix, " | ".join(bad[:3])))
4835
+
4836
+ SCAFFOLD = {
4837
+ "interfaces": """<!--
4838
+ INTERFACE LOG — this feature's published-surface contract. APPEND-ONLY.
4839
+
4840
+ WHO WRITES: /appweaver plan publishes this feature's surface whenever it authors or
4841
+ conforms backend-plan.md; a BE story plan appends an entry only where its slice
4842
+ changes that surface. Both land as status: proposed, and story close verifies each
4843
+ against the as-built and flips it to live.
4844
+ WHO READS: /appweaver plan-ui and the FE story designs — this log is the BE-to-FE
4845
+ contract anchor, and the plan documents CITE these ids rather than restating them.
4846
+ The current surface per interface is the LATEST entry — one that names an earlier
4847
+ id in `supersedes:` replaces it. Never edit an existing entry; publish a
4848
+ superseding one. status: proposed -> live -> superseded | retired.
4849
+ `serves:` cites the FR-/BR- ids the interface exists for, so a spec change to
4850
+ those ids flags the contract for review.
4851
+ -->
4852
+
4853
+ # Interface Log
4854
+ """,
4855
+ "adr": """<!--
4856
+ ADR LOG — this feature's durable decisions. APPEND-ONLY.
4857
+
4858
+ A story plan PROPOSES ADRs in its latest design pass; they are ratified into this
4859
+ log at story close, or the architect appends directly. Never rewrite an entry —
4860
+ supersede it with a new one naming `supersedes:`. An ADR records ONLY what neither
4861
+ the code nor the rules can say: a deliberate choice among rule-compliant
4862
+ alternatives, a rejected alternative and why, or a trade-off with its revisit
4863
+ trigger. It never restates what code shows or a rule mandates.
4864
+ -->
4865
+
4866
+ # Architecture Decision Log
4867
+ """}
4868
+ # THE ID ASSIGNMENT AND THE WRITE ARE ONE OPERATION. `nxt = max(existing) + 1` is computed
4869
+ # from a whole-file read and the file is then written back truncating — so two runs that
4870
+ # read before either wrote both compute the same next id, and the second write drops the
4871
+ # first's entry entirely. The wave model exists to have same-wave stories designed in
4872
+ # parallel, and this is the artefact §0.3 calls the cross-lane contract anchor, so the race
4873
+ # is not hypothetical: two story-plan runs, or plan and story-plan, is the ordinary case.
4874
+ # Git catches a lost entry across branches and never within one working tree.
4875
+ #
4876
+ # The lock is named for the FILE, so every writer of interfaces.md contends on one lock
4877
+ # whichever op or shell it came from — aw-xref.py names its own the same way for the same
4878
+ # reason. A lock older than the timeout belonged to a run that died holding it; breaking it
4879
+ # is right, because the alternative is a wedged feature nobody can append to again.
4880
+ LOCK_TIMEOUT = 30.0
4881
+ def take_lock(target):
4882
+ lp = target + ".aw-lock"
4883
+ start = time.time()
4884
+ while True:
4885
+ try:
4886
+ h = os.open(lp, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o644)
4887
+ os.write(h, ("%d\n" % os.getpid()).encode("utf-8")); os.close(h)
4888
+ return lp
4889
+ except OSError as e:
4890
+ if e.errno != errno.EEXIST: raise
4891
+ try: age = time.time() - os.path.getmtime(lp)
4892
+ except OSError: age = 0.0
4893
+ if age > LOCK_TIMEOUT:
4894
+ try: os.unlink(lp)
4895
+ except OSError: pass
4896
+ continue
4897
+ if time.time() - start > LOCK_TIMEOUT:
4898
+ bail("log-append: %s has been locked by another run for over %ds. If no "
4899
+ "other /appweaver command is running, delete %s and re-run."
4900
+ % (os.path.basename(target), int(LOCK_TIMEOUT), lp))
4901
+ time.sleep(0.05)
4902
+
4903
+ def drop_lock(lp):
4904
+ try: os.unlink(lp)
4905
+ except OSError: pass
4906
+
4907
+ lock = take_lock(path)
4908
+ created = not os.path.isfile(path)
4909
+ if created:
4910
+ open(path, "w", encoding="utf-8").write(SCAFFOLD[log])
4911
+ text = open(path, encoding="utf-8", errors="replace").read()
4912
+ existing = set(re.findall(r'^##\s+(%s-\d+)' % prefix, text, re.M))
4913
+ nums = [int(i.split("-")[1]) for i in existing]
4914
+ nxt = (max(nums) + 1) if nums else 1
4915
+ today = datetime.date.today().isoformat()
4916
+
4917
+ spec = os.path.join(fd, "spec.md")
4918
+ known = set(re.findall(r'\b[A-Z]{2}-\d+\b',
4919
+ open(spec, encoding="utf-8", errors="replace").read())) \
4920
+ if os.path.isfile(spec) else set()
4921
+
4922
+ assigned, unknown, badsup, out_blocks = [], [], [], []
4923
+ for b in blocks:
4924
+ bid = "%s-%03d" % (prefix, nxt); nxt += 1
4925
+ lines = b.splitlines()
4926
+ lines[0] = lines[0].replace("%s-NEW" % prefix, bid, 1)
4927
+ body = "\n".join(lines[1:]).strip("\n")
4928
+ # status and date are script-stamped, whatever the model wrote
4929
+ body = re.sub(r'^status:.*\n?', '', body, flags=re.M)
4930
+ body = re.sub(r'^date:.*\n?', '', body, flags=re.M)
4931
+ body = ("status: %s\ndate: %s" % (status, today)) + ("\n" + body if body else "")
4932
+ for line in body.splitlines():
4933
+ if line.startswith("serves:"):
4934
+ unknown += [i for i in re.findall(r'\b[A-Z]{2}-\d+\b', line)
4935
+ if known and i not in known]
4936
+ if line.startswith("supersedes:"):
4937
+ badsup += [i for i in re.findall(r'\b%s-\d+\b' % prefix, line)
4938
+ if i not in existing]
4939
+ out_blocks.append(lines[0] + "\n\n" + body)
4940
+ assigned.append(bid)
4941
+
4942
+ text = text.rstrip("\n") + "\n\n" + "\n\n".join(out_blocks) + "\n"
4943
+ open(path, "w", encoding="utf-8").write(text)
4944
+ drop_lock(lock)
4945
+ os.remove(ef)
4946
+ print(json.dumps({"ok": True, "log": path, "appended": len(assigned),
4947
+ "ids_csv": ", ".join(assigned),
4948
+ "unknown_ids_csv": ", ".join(sorted(set(unknown))),
4949
+ "bad_supersedes_csv": ", ".join(sorted(set(badsup))),
4950
+ "none": False, "created_log": created}))
4951
+ '@
4952
+
4953
+ function Invoke-StoryPlanCheck {
4954
+ param([string[]]$Rest)
4955
+ $fdArg = ''; $inp = ''; $story = ''
4956
+ for ($i = 0; $i -lt $Rest.Count; $i++) { switch ($Rest[$i]) { { $_ -in '--feature-dir','-FeatureDir' } { $fdArg = $Rest[++$i] } { $_ -in '--input','-InputText' } { $inp = $Rest[++$i] } { $_ -in '--story','-Story' } { $story = $Rest[++$i] } } }
4957
+ $py = Get-Py; if (-not $py) { Write-Error 'story-plan-check: python3 required'; exit 1 }
4958
+ $repo = Get-RepoRoot
4959
+ $fd = Resolve-FeatureDir -Arg $fdArg -RepoRoot $repo
4960
+ if (-not $fd) { Write-Error 'story-plan-check: no feature set and no --feature-dir'; exit 1 }
4961
+ $env:AW_FD = $fd; $env:AW_INPUT = $inp; $env:AW_STORY = $story
4962
+ $PyStoryPlanCheck | & $py -
4963
+ Remove-Item Env:AW_FD, Env:AW_INPUT, Env:AW_STORY -ErrorAction SilentlyContinue
4964
+ }
4965
+
4966
+ function Invoke-StoryPlanDoc {
4967
+ param([string[]]$Rest)
4968
+ $fdArg = ''; $story = ''; $passFile = ''; $specVersion = ''; $lane = 'backend'; $planHash = ''
4969
+ # --plan-hash is the CERTIFIED feature-plan hash — the one analyze-design recorded in
4970
+ # its verdict, never a fresh one taken here. Stamped into the pass header so a pass
4971
+ # keeps saying which plan shape it was designed against long after the plan moved.
4972
+ for ($i = 0; $i -lt $Rest.Count; $i++) { switch ($Rest[$i]) { { $_ -in '--feature-dir','-FeatureDir' } { $fdArg = $Rest[++$i] } { $_ -in '--story','-Story' } { $story = $Rest[++$i] } { $_ -in '--lane','-Lane' } { $lane = $Rest[++$i] } { $_ -in '--pass-file','-PassFile' } { $passFile = $Rest[++$i] } { $_ -in '--spec-version','-SpecVersion' } { $specVersion = $Rest[++$i] } { $_ -in '--plan-hash','-PlanHash' } { $planHash = $Rest[++$i] } } }
4973
+ if (-not $story) { Write-Error 'story-plan-doc: --story is required'; exit 1 }
4974
+ if (-not $passFile) { Write-Error 'story-plan-doc: --pass-file is required'; exit 1 }
4975
+ $py = Get-Py; if (-not $py) { Write-Error 'story-plan-doc: python3 required'; exit 1 }
4976
+ $repo = Get-RepoRoot
4977
+ $fd = Resolve-FeatureDir -Arg $fdArg -RepoRoot $repo
4978
+ if (-not $fd) { Write-Error 'story-plan-doc: no feature set and no --feature-dir'; exit 1 }
4979
+ $env:AW_FD = $fd; $env:AW_STORY = $story; $env:AW_LANE = $lane; $env:AW_PASS = $passFile; $env:AW_VER = $specVersion
4980
+ $env:AW_PLAN_HASH = $planHash
4981
+ $PyStoryPlanDoc | & $py -
4982
+ Remove-Item Env:AW_FD, Env:AW_STORY, Env:AW_LANE, Env:AW_PASS, Env:AW_VER, Env:AW_PLAN_HASH -ErrorAction SilentlyContinue
4983
+ }
4984
+
4985
+ function Invoke-LogAppend {
4986
+ param([string[]]$Rest)
4987
+ $fdArg = ''; $log = ''; $entriesFile = ''; $status = ''
4988
+ for ($i = 0; $i -lt $Rest.Count; $i++) { switch ($Rest[$i]) { { $_ -in '--feature-dir','-FeatureDir' } { $fdArg = $Rest[++$i] } { $_ -in '--log','-Log' } { $log = $Rest[++$i] } { $_ -in '--entries-file','-EntriesFile' } { $entriesFile = $Rest[++$i] } { $_ -in '--status','-Status' } { $status = $Rest[++$i] } } }
4989
+ if ($log -notin 'adr','interfaces') { Write-Error 'log-append: --log must be adr or interfaces'; exit 1 }
4990
+ if (-not $entriesFile) { Write-Error 'log-append: --entries-file is required'; exit 1 }
4991
+ $py = Get-Py; if (-not $py) { Write-Error 'log-append: python3 required'; exit 1 }
4992
+ $repo = Get-RepoRoot
4993
+ $fd = Resolve-FeatureDir -Arg $fdArg -RepoRoot $repo
4994
+ if (-not $fd) { Write-Error 'log-append: no feature set and no --feature-dir'; exit 1 }
4995
+ $env:AW_FD = $fd; $env:AW_LOG = $log; $env:AW_ENTRIES = $entriesFile; $env:AW_STATUS = $status
4996
+ $PyLogAppend | & $py -
4997
+ Remove-Item Env:AW_FD, Env:AW_LOG, Env:AW_ENTRIES, Env:AW_STATUS -ErrorAction SilentlyContinue
2574
4998
  }
2575
4999
 
2576
5000
  # Read one field out of the lane model. Twin of the bash inline python readers: the
@@ -2968,13 +5392,25 @@ switch ($sub) {
2968
5392
  'spec-snapshot' { Invoke-SpecSnapshot -Rest $rest }
2969
5393
  'spec-diff' { Invoke-SpecDiff -Rest $rest }
2970
5394
  'story-refs' { Invoke-StoryRefs -Rest $rest }
5395
+ 'slice-mode' { Invoke-SliceMode -Rest $rest }
5396
+ 'backlog-plan' { Invoke-BacklogPlan -Rest $rest }
5397
+ 'story-stamp' { Invoke-StoryStamp -Rest $rest }
5398
+ 'story-plan-check' { Invoke-StoryPlanCheck -Rest $rest }
5399
+ 'story-plan-doc' { Invoke-StoryPlanDoc -Rest $rest }
5400
+ 'log-append' { Invoke-LogAppend -Rest $rest }
5401
+ 'ledger-read' { Invoke-LedgerRead -Rest $rest }
2971
5402
  'spec-coverage' { Invoke-SpecCoverage -Rest $rest }
2972
5403
  'spec-preserve' { Invoke-SpecPreserve -Rest $rest }
2973
5404
  'spec-markers' { Invoke-SpecMarkers -Rest $rest }
2974
5405
  'feature-paths' { Invoke-FeaturePaths -Rest $rest }
2975
5406
  'design-scaffold' { Invoke-DesignScaffold -Rest $rest }
5407
+ 'plan-check' { Invoke-PlanCheck -Rest $rest }
5408
+ 'plan-stamp' { Invoke-PlanStamp -Rest $rest }
5409
+ 'gate-result' { Invoke-GateResult -Rest $rest }
5410
+ 'gate-read' { Invoke-GateRead -Rest $rest }
2976
5411
  'build-compile' { Invoke-BuildCompile -Rest $rest }
2977
5412
  'test-run' { Invoke-TestRun -Rest $rest }
5413
+ 'test-diff' { Invoke-TestDiff -Rest $rest }
2978
5414
  'run-migrate' { Invoke-RunMigrate -Rest $rest }
2979
5415
  'deploy-dispatch' { Invoke-DeployDispatch -Rest $rest }
2980
5416
  'cr-setup' { Invoke-CrSetup -Rest $rest }