@event4u/agent-config 2.9.0 → 2.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (96) hide show
  1. package/.agent-src/commands/agents.md +1 -0
  2. package/.agent-src/commands/challenge-me.md +1 -0
  3. package/.agent-src/commands/chat-history.md +1 -0
  4. package/.agent-src/commands/context.md +1 -0
  5. package/.agent-src/commands/council.md +1 -0
  6. package/.agent-src/commands/feature.md +1 -0
  7. package/.agent-src/commands/fix.md +1 -0
  8. package/.agent-src/commands/grill-me.md +1 -0
  9. package/.agent-src/commands/judge.md +1 -0
  10. package/.agent-src/commands/memory.md +1 -0
  11. package/.agent-src/commands/module.md +1 -0
  12. package/.agent-src/commands/onboard.md +32 -4
  13. package/.agent-src/commands/optimize.md +1 -0
  14. package/.agent-src/commands/override.md +1 -0
  15. package/.agent-src/commands/roadmap.md +1 -0
  16. package/.agent-src/commands/tests.md +1 -0
  17. package/.agent-src/rules/no-roadmap-references.md +19 -0
  18. package/.agent-src/skills/nextjs-patterns/SKILL.md +203 -0
  19. package/.agent-src/skills/symfony-workflow/SKILL.md +173 -0
  20. package/.agent-src/templates/scripts/work_engine/hook_bootstrap.py +4 -0
  21. package/.agent-src/templates/scripts/work_engine/hooks/builtin/__init__.py +3 -0
  22. package/.agent-src/templates/scripts/work_engine/hooks/builtin/decision_gate.py +162 -0
  23. package/.agent-src/templates/scripts/work_engine/hooks/builtin/memory_visibility.py +32 -3
  24. package/.agent-src/templates/scripts/work_engine/hooks/settings.py +24 -6
  25. package/.agent-src/templates/scripts/work_engine/scoring/decision_engine.py +351 -0
  26. package/.agent-src/templates/scripts/work_engine/scoring/memory_visibility.py +147 -1
  27. package/.claude-plugin/marketplace.json +3 -1
  28. package/CHANGELOG.md +65 -0
  29. package/README.md +66 -17
  30. package/config/agent-settings.template.yml +85 -0
  31. package/docs/architecture.md +1 -1
  32. package/docs/contracts/STABILITY.md +16 -0
  33. package/docs/contracts/adr-chat-history-split.md +1 -0
  34. package/docs/contracts/adr-forecast-construction-shape.md +1 -0
  35. package/docs/contracts/adr-gtm-context-spine.md +1 -0
  36. package/docs/contracts/adr-level-6-productization.md +147 -0
  37. package/docs/contracts/adr-settings-sync-engine.md +1 -0
  38. package/docs/contracts/adr-wing4-context-spine.md +1 -0
  39. package/docs/contracts/agent-memory-contract.md +1 -0
  40. package/docs/contracts/agents-md-tech-stack.md +1 -0
  41. package/docs/contracts/audit-log-v1.md +1 -0
  42. package/docs/contracts/command-clusters.md +1 -0
  43. package/docs/contracts/command-surface-tiers.md +1 -0
  44. package/docs/contracts/context-paths.md +1 -0
  45. package/docs/contracts/cost-profile-defaults.md +105 -0
  46. package/docs/contracts/cross-wing-handoff.md +1 -0
  47. package/docs/contracts/decision-engine-gates.md +115 -0
  48. package/docs/contracts/decision-trace-v1.md +31 -0
  49. package/docs/contracts/file-ownership-matrix.md +1 -0
  50. package/docs/contracts/hook-architecture-v1.md +47 -0
  51. package/docs/contracts/implement-ticket-flow.md +1 -0
  52. package/docs/contracts/installed-tools-lockfile.md +1 -0
  53. package/docs/contracts/kernel-membership.md +1 -0
  54. package/docs/contracts/linear-ai-rules-inclusion.md +1 -0
  55. package/docs/contracts/linear-ai-three-layers.md +1 -0
  56. package/docs/contracts/linter-structural-model.md +1 -0
  57. package/docs/contracts/load-context-budget-model.md +1 -0
  58. package/docs/contracts/load-context-schema.md +1 -0
  59. package/docs/contracts/memory-visibility-v1.md +34 -0
  60. package/docs/contracts/one-off-script-lifecycle.md +1 -0
  61. package/docs/contracts/orchestration-dsl-v1.md +1 -0
  62. package/docs/contracts/package-self-orientation.md +1 -0
  63. package/docs/contracts/persona-schema.md +1 -0
  64. package/docs/contracts/release-trunk-sync.md +104 -0
  65. package/docs/contracts/roadmap-complexity-standard.md +1 -0
  66. package/docs/contracts/rule-classification.md +1 -0
  67. package/docs/contracts/rule-interactions.md +26 -0
  68. package/docs/contracts/rule-priority-hierarchy.md +1 -0
  69. package/docs/contracts/rule-router.md +1 -0
  70. package/docs/contracts/settings-sync-yaml-subset.md +139 -0
  71. package/docs/contracts/skill-domains.md +1 -0
  72. package/docs/contracts/tier-3-contrib-plugin.md +1 -0
  73. package/docs/contracts/ui-stack-extension.md +1 -0
  74. package/docs/contracts/ui-track-flow.md +1 -0
  75. package/docs/customization.md +1 -1
  76. package/docs/getting-started.md +3 -1
  77. package/docs/installation.md +8 -6
  78. package/docs/readme-split-plan.md +102 -0
  79. package/package.json +1 -1
  80. package/scripts/_cli/cmd_settings_check.py +171 -0
  81. package/scripts/agent-config +40 -0
  82. package/scripts/chat_history.py +19 -0
  83. package/scripts/check_beta_review_markers.py +127 -0
  84. package/scripts/check_council_references.py +46 -5
  85. package/scripts/check_release_trunk_sync.py +152 -0
  86. package/scripts/hooks/dispatch_hook.py +5 -1
  87. package/scripts/hooks/replay_hook.py +144 -0
  88. package/scripts/hooks/state_io.py +24 -1
  89. package/scripts/hooks_doctor.py +184 -0
  90. package/scripts/install.py +3 -3
  91. package/scripts/lint_hook_concern_budget.py +203 -0
  92. package/scripts/roadmap_progress_hook.py +11 -0
  93. package/scripts/schemas/command.schema.json +5 -0
  94. package/scripts/skill_linter.py +11 -2
  95. package/scripts/smoke_quickstart.py +134 -0
  96. package/scripts/validate_decision_engine.py +124 -0
@@ -0,0 +1,171 @@
1
+ """``agent-config settings:check`` — validate ``.agent-settings.yml`` against the supported YAML subset.
2
+
3
+ Read-only. Implements P3.2 of road-to-proof-not-features.md. The contract
4
+ this checks against is pinned in
5
+ ``docs/contracts/settings-sync-yaml-subset.md``; out-of-subset constructs
6
+ cause :class:`sync_yaml_rt` to raise ``ValueError`` during a sync. This
7
+ CLI surfaces the same findings *before* a sync runs, so users can fix
8
+ their file without watching the merge fail.
9
+
10
+ Output line format::
11
+
12
+ line:N <kind> <verdict> <fix hint>
13
+
14
+ Exit codes:
15
+
16
+ * ``0`` — file is inside the supported subset (or absent and ``--allow-missing``).
17
+ * ``1`` — one or more findings (verdict ``not supported``).
18
+ * ``2`` — file absent (without ``--allow-missing``) or unreadable.
19
+ """
20
+ from __future__ import annotations
21
+
22
+ import argparse
23
+ import re
24
+ import sys
25
+ from pathlib import Path
26
+
27
+ # Imported lazily inside ``main`` so a missing engine cannot break ``--help``.
28
+
29
+ DEFAULT_PATH = ".agent-settings.yml"
30
+
31
+ # Out-of-subset patterns detected by a line-level pre-scan. Each rule is
32
+ # (label, regex, fix hint). The regex is applied to the *stripped* body
33
+ # of each non-comment line so leading indent does not affect matching.
34
+ _PRESCAN_RULES: tuple[tuple[str, re.Pattern[str], str], ...] = (
35
+ (
36
+ "multi-doc separator",
37
+ re.compile(r"^(---|\.\.\.)\s*(#.*)?$"),
38
+ "remove the separator — one YAML document per file only.",
39
+ ),
40
+ (
41
+ "complex key",
42
+ re.compile(r"^\?\s"),
43
+ "rewrite as a plain ``key: value`` mapping line.",
44
+ ),
45
+ (
46
+ "block-scalar indicator",
47
+ re.compile(r":\s*[|>][+-]?\s*(#.*)?$"),
48
+ "inline the value as a single-line quoted scalar.",
49
+ ),
50
+ (
51
+ "tagged scalar",
52
+ re.compile(r":\s*!!?[A-Za-z_]"),
53
+ "remove the ``!tag``; the parser does not honour it.",
54
+ ),
55
+ (
56
+ "anchor / alias",
57
+ re.compile(r":\s*[&*][A-Za-z_]"),
58
+ "expand the anchor inline — anchors / aliases are not supported.",
59
+ ),
60
+ (
61
+ "nested flow-mapping",
62
+ re.compile(r":\s*\{[^}]*:[^}]*\}"),
63
+ "rewrite as a block-style nested mapping (indented child keys).",
64
+ ),
65
+ )
66
+
67
+
68
+ def _scan_line(stripped: str) -> tuple[str, str] | None:
69
+ if not stripped or stripped.startswith("#"):
70
+ return None
71
+ for label, pattern, hint in _PRESCAN_RULES:
72
+ if pattern.search(stripped):
73
+ return label, hint
74
+ return None
75
+
76
+
77
+ def _scan_text(text: str) -> list[dict]:
78
+ findings: list[dict] = []
79
+ for lineno, raw in enumerate(text.splitlines(), 1):
80
+ stripped = raw.strip()
81
+ if "\t" in raw[: len(raw) - len(raw.lstrip(" \t"))]:
82
+ findings.append({
83
+ "line": lineno,
84
+ "kind": "tab in indent",
85
+ "verdict": "not supported",
86
+ "hint": "replace leading tabs with 2 or 4 spaces.",
87
+ })
88
+ continue
89
+ hit = _scan_line(stripped)
90
+ if hit is not None:
91
+ label, hint = hit
92
+ findings.append({
93
+ "line": lineno,
94
+ "kind": label,
95
+ "verdict": "not supported",
96
+ "hint": hint,
97
+ })
98
+ return findings
99
+
100
+
101
+ def _format(finding: dict) -> str:
102
+ return (
103
+ f" ❌ line:{finding['line']:<4} "
104
+ f"{finding['kind']:<22} {finding['verdict']:<14} {finding['hint']}"
105
+ )
106
+
107
+
108
+ def _parse(argv: list[str]) -> argparse.Namespace:
109
+ parser = argparse.ArgumentParser(
110
+ prog="agent-config settings:check",
111
+ description=(
112
+ "Validate .agent-settings.yml against the supported YAML subset "
113
+ "(docs/contracts/settings-sync-yaml-subset.md). Read-only."
114
+ ),
115
+ )
116
+ parser.add_argument("--path", default=DEFAULT_PATH,
117
+ help=f"target settings file (default: ./{DEFAULT_PATH})")
118
+ parser.add_argument("--allow-missing", action="store_true",
119
+ help="exit 0 when the file is absent (CI-friendly)")
120
+ parser.add_argument("--quiet", action="store_true",
121
+ help="suppress non-essential output")
122
+ return parser.parse_args(argv)
123
+
124
+
125
+ def main(argv: list[str]) -> int:
126
+ opts = _parse(argv)
127
+ target = Path(opts.path)
128
+ if not target.is_file():
129
+ if opts.allow_missing:
130
+ if not opts.quiet:
131
+ print(f"✅ {target}: file absent (allow-missing).")
132
+ return 0
133
+ print(f"❌ {target}: file not found.", file=sys.stderr)
134
+ print(" Run `./agent-config sync-agent-settings` to create it.", file=sys.stderr)
135
+ return 2
136
+ try:
137
+ text = target.read_text(encoding="utf-8")
138
+ except OSError as exc:
139
+ print(f"❌ {target}: cannot read: {exc}", file=sys.stderr)
140
+ return 2
141
+
142
+ findings = _scan_text(text)
143
+ if not findings:
144
+ # Final gate: run the round-trip parser to catch anything the
145
+ # pre-scan missed (mismatched indent, malformed mapping lines).
146
+ from scripts import sync_yaml_rt as _rt # noqa: PLC0415
147
+ try:
148
+ _rt.parse(text)
149
+ except ValueError as exc:
150
+ findings.append({
151
+ "line": 0, "kind": "parser",
152
+ "verdict": "not supported", "hint": str(exc),
153
+ })
154
+
155
+ if not findings:
156
+ if not opts.quiet:
157
+ print(f"✅ {target}: inside the supported subset "
158
+ "(docs/contracts/settings-sync-yaml-subset.md).")
159
+ return 0
160
+ print(f"❌ {target}: {len(findings)} finding(s) outside the supported subset.",
161
+ file=sys.stderr)
162
+ for finding in findings:
163
+ print(_format(finding), file=sys.stderr)
164
+ print("", file=sys.stderr)
165
+ print(" Contract: docs/contracts/settings-sync-yaml-subset.md",
166
+ file=sys.stderr)
167
+ return 1
168
+
169
+
170
+ if __name__ == "__main__":
171
+ sys.exit(main(sys.argv[1:]))
@@ -127,10 +127,22 @@ Tier 2 — maintenance / internal (hooks, MCP, memory, telemetry):
127
127
  (experimental — beta gates: docs/contracts/mcp-beta-criteria.md)
128
128
  roadmap:progress Regenerate agents/roadmaps-progress.md from open roadmaps
129
129
  roadmap:progress-check Fail if agents/roadmaps-progress.md is stale (for CI)
130
+ settings:check Validate .agent-settings.yml against the YAML-subset contract
131
+ (docs/contracts/settings-sync-yaml-subset.md). Read-only.
132
+ Exit 0 clean, 1 finding(s), 2 file absent / unreadable.
130
133
  hooks:install Install the pre-commit roadmap-progress hook
131
134
  (use --print to dump it, --force to overwrite an existing hook)
132
135
  hooks:status Print the runtime hook matrix (per-platform install + bindings)
133
136
  Flags: --format json|table, --strict (CI), --project-root <path>
137
+ hooks:doctor Diagnose hook health: concerns + fail-open/closed posture,
138
+ last dispatcher feedback per concern, missing trampolines.
139
+ Wraps hooks:status. Read-only.
140
+ Flags: --format json|table, --strict (CI), --project-root <path>
141
+ hooks:replay Replay a fixture through the universal dispatcher with
142
+ AGENT_CONFIG_REPLAY=1 (no writes under agents/state/).
143
+ Usage: hooks:replay --platform <name> --event <event>
144
+ --payload <path|event-name> [--native-event <native>]
145
+ [--manifest <path>] [--json] [--dry-run]
134
146
  migrate-state Migrate a legacy .implement-ticket-state.json file
135
147
  to the v1 .work-state.json schema (preserves .bak)
136
148
  memory:lookup Retrieve memory entries (text or JSON envelope)
@@ -217,7 +229,9 @@ Examples (Tier 2):
217
229
  ./agent-config mcp:setup
218
230
  ./agent-config mcp:run
219
231
  ./agent-config roadmap:progress
232
+ ./agent-config settings:check
220
233
  ./agent-config hooks:install
234
+ ./agent-config hooks:replay --platform augment --event post_tool_use --payload post_tool_use --json
221
235
  ./agent-config migrate-state
222
236
  ./agent-config memory:lookup --types domain-invariants --key billing
223
237
  ./agent-config memory:signal --type architecture-decision --path src/Foo.php --body "…"
@@ -507,6 +521,20 @@ cmd_hooks_status() {
507
521
  exec python3 "$script" "$@"
508
522
  }
509
523
 
524
+ cmd_hooks_doctor() {
525
+ require_python3
526
+ local script
527
+ script="$(resolve_script "scripts/hooks_doctor.py")" || return 1
528
+ exec python3 "$script" "$@"
529
+ }
530
+
531
+ cmd_hooks_replay() {
532
+ require_python3
533
+ local script
534
+ script="$(resolve_script "scripts/hooks/replay_hook.py")" || return 1
535
+ exec python3 "$script" "$@"
536
+ }
537
+
510
538
  cmd_chat_history_checkpoint() {
511
539
  require_python3
512
540
  local script
@@ -676,6 +704,15 @@ cmd_validate() {
676
704
  exec env PYTHONPATH="$PACKAGE_ROOT" python3 -m scripts._cli.cmd_validate "$@"
677
705
  }
678
706
 
707
+ # `agent-config settings:check` — read-only YAML-subset validator for
708
+ # `.agent-settings.yml` (P3.2 of road-to-proof-not-features.md). Contract
709
+ # pinned in docs/contracts/settings-sync-yaml-subset.md. Exit 0 clean,
710
+ # 1 finding(s), 2 file absent / unreadable.
711
+ cmd_settings_check() {
712
+ require_python3
713
+ exec env PYTHONPATH="$PACKAGE_ROOT" python3 -m scripts._cli.cmd_settings_check "$@"
714
+ }
715
+
679
716
  # `agent-config uninstall` — remove bridge markers (project) or lockfile
680
717
  # entries (global). Idempotent. Pass `--purge` to also delete deployed
681
718
  # content directories under user-scope anchors (destructive). See
@@ -744,6 +781,8 @@ main() {
744
781
  context-hygiene:hook) cmd_context_hygiene_hook "$@" ;;
745
782
  dispatch:hook) cmd_dispatch_hook "$@" ;;
746
783
  hooks:status) cmd_hooks_status "$@" ;;
784
+ hooks:doctor) cmd_hooks_doctor "$@" ;;
785
+ hooks:replay) cmd_hooks_replay "$@" ;;
747
786
  telemetry:record) cmd_telemetry_record "$@" ;;
748
787
  telemetry:status) cmd_telemetry_status "$@" ;;
749
788
  telemetry:report) cmd_telemetry_report "$@" ;;
@@ -757,6 +796,7 @@ main() {
757
796
  export) cmd_export "$@" ;;
758
797
  sync) cmd_sync "$@" ;;
759
798
  validate) cmd_validate "$@" ;;
799
+ settings:check) cmd_settings_check "$@" ;;
760
800
  uninstall) cmd_uninstall "$@" ;;
761
801
  prune) cmd_prune "$@" ;;
762
802
  doctor) cmd_doctor "$@" ;;
@@ -48,6 +48,15 @@ SCHEMA_VERSION = 4
48
48
  DEFAULT_MAX_SESSIONS = 5
49
49
  VALID_FREQS = {"per_turn", "per_phase", "per_tool"}
50
50
  VALID_OVERFLOW = {"rotate", "compress"}
51
+
52
+ # Replay-mode signal — when set, every write to the on-disk transcript
53
+ # is a no-op. Honoured per `docs/contracts/hook-architecture-v1.md`
54
+ # § Replay mode so fixture dispatches never mutate real session state.
55
+ REPLAY_ENV_VAR = "AGENT_CONFIG_REPLAY"
56
+
57
+
58
+ def _is_replay_mode() -> bool:
59
+ return os.environ.get(REPLAY_ENV_VAR, "").strip() == "1"
51
60
  _WS_RE = re.compile(r"\s+")
52
61
  SESSION_ID_LEN = 16
53
62
  SESSION_ID_UNKNOWN = "<unknown>"
@@ -247,6 +256,8 @@ def init(freq: str = "per_phase", *,
247
256
  raise ValueError(f"freq must be one of {sorted(VALID_FREQS)}")
248
257
  p = path or file_path()
249
258
  header = _build_header(freq)
259
+ if _is_replay_mode():
260
+ return header
250
261
  p.parent.mkdir(parents=True, exist_ok=True)
251
262
  with p.open("w", encoding="utf-8") as fh:
252
263
  fh.write(json.dumps(header, ensure_ascii=False) + "\n")
@@ -318,6 +329,8 @@ def append(entry: dict[str, Any], *, path: Path | None = None,
318
329
  entry["s"] = session
319
330
  elif "s" not in entry and _session_tag_enabled():
320
331
  entry["s"] = _last_body_session_id(p)
332
+ if _is_replay_mode():
333
+ return
321
334
  with p.open("a", encoding="utf-8") as fh:
322
335
  fh.write(json.dumps(entry, ensure_ascii=False) + "\n")
323
336
 
@@ -328,7 +341,11 @@ def _atomic_write_text(p: Path, text: str) -> None:
328
341
  Multiple processes writing to the same target use disjoint tmp paths
329
342
  (PID + uuid), so concurrent writes no longer collide on a shared
330
343
  ``.tmp`` file. The final ``replace`` is atomic on POSIX.
344
+
345
+ Under `AGENT_CONFIG_REPLAY=1` the call is a no-op.
331
346
  """
347
+ if _is_replay_mode():
348
+ return
332
349
  tmp = p.with_suffix(
333
350
  f"{p.suffix}.{os.getpid()}.{uuid.uuid4().hex[:8]}.tmp",
334
351
  )
@@ -405,6 +422,8 @@ def prepend_entries(entries: list[dict[str, Any]], *,
405
422
 
406
423
 
407
424
  def clear(*, path: Path | None = None) -> None:
425
+ if _is_replay_mode():
426
+ return
408
427
  p = path or file_path()
409
428
  if p.exists():
410
429
  p.unlink()
@@ -0,0 +1,127 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ Beta-review-marker checker for `docs/contracts/`.
4
+
5
+ Every contract whose frontmatter declares `stability: beta` MUST carry
6
+ exactly one of the following frontmatter markers (per
7
+ `docs/contracts/STABILITY.md` § Beta-review markers, ratified in
8
+ `road-to-productization.md` § P5.4):
9
+
10
+ - `promote-to: stable`
11
+ - `keep-beta-until: YYYY-MM-DD` (max 90 days from the last review)
12
+ - `superseded-by: <contract-id>`
13
+
14
+ Exit codes: 0 = clean, 1 = violations found, 3 = internal error.
15
+
16
+ Usage:
17
+ python3 scripts/check_beta_review_markers.py
18
+ python3 scripts/check_beta_review_markers.py --json
19
+ """
20
+
21
+ from __future__ import annotations
22
+
23
+ import argparse
24
+ import json
25
+ import re
26
+ import sys
27
+ from dataclasses import asdict, dataclass
28
+ from datetime import date, timedelta
29
+ from pathlib import Path
30
+
31
+ ROOT = Path(__file__).resolve().parent.parent
32
+ CONTRACTS_DIR = Path("docs/contracts")
33
+
34
+ FRONTMATTER_RE = re.compile(r"^---\s*\n(.*?)\n---\s*\n", re.DOTALL)
35
+ STABILITY_RE = re.compile(r"^stability:\s*(\w+)\s*$", re.MULTILINE)
36
+ PROMOTE_RE = re.compile(r"^promote-to:\s*stable\s*$", re.MULTILINE)
37
+ KEEP_RE = re.compile(r"^keep-beta-until:\s*(\d{4}-\d{2}-\d{2})\s*$", re.MULTILINE)
38
+ SUPERSEDED_RE = re.compile(r"^superseded-by:\s*\S+\s*$", re.MULTILINE)
39
+
40
+ MAX_REVIEW_WINDOW_DAYS = 90
41
+
42
+
43
+ @dataclass
44
+ class Violation:
45
+ file: str
46
+ reason: str
47
+ severity: str # "error" | "warning"
48
+
49
+
50
+ def read_frontmatter(path: Path) -> str | None:
51
+ if not path.exists():
52
+ return None
53
+ txt = path.read_text(encoding="utf-8")
54
+ m = FRONTMATTER_RE.match(txt)
55
+ return m.group(1) if m else None
56
+
57
+
58
+ def check_one(path: Path, today: date) -> list[Violation]:
59
+ fm = read_frontmatter(path)
60
+ if fm is None:
61
+ return []
62
+ sm = STABILITY_RE.search(fm)
63
+ if not sm or sm.group(1) != "beta":
64
+ return []
65
+ markers = [
66
+ ("promote-to", bool(PROMOTE_RE.search(fm))),
67
+ ("keep-beta-until", bool(KEEP_RE.search(fm))),
68
+ ("superseded-by", bool(SUPERSEDED_RE.search(fm))),
69
+ ]
70
+ set_markers = [name for name, present in markers if present]
71
+ rel = str(path.relative_to(ROOT))
72
+ if not set_markers:
73
+ return [Violation(
74
+ file=rel,
75
+ reason="stability=beta but no review marker; add one of "
76
+ "`promote-to: stable` | `keep-beta-until: <date>` | "
77
+ "`superseded-by: <id>` (see STABILITY.md § Beta-review markers)",
78
+ severity="error",
79
+ )]
80
+ if len(set_markers) > 1:
81
+ return [Violation(
82
+ file=rel,
83
+ reason=f"multiple beta-review markers set ({', '.join(set_markers)}); "
84
+ "exactly one is allowed",
85
+ severity="error",
86
+ )]
87
+ km = KEEP_RE.search(fm)
88
+ if km:
89
+ review_date = date.fromisoformat(km.group(1))
90
+ max_date = today + timedelta(days=MAX_REVIEW_WINDOW_DAYS)
91
+ if review_date > max_date:
92
+ return [Violation(
93
+ file=rel,
94
+ reason=f"keep-beta-until={review_date} exceeds the "
95
+ f"{MAX_REVIEW_WINDOW_DAYS}-day window (max: {max_date})",
96
+ severity="error",
97
+ )]
98
+ return []
99
+
100
+
101
+ def main() -> int:
102
+ ap = argparse.ArgumentParser()
103
+ ap.add_argument("--json", action="store_true", help="machine-readable output")
104
+ args = ap.parse_args()
105
+ today = date.today()
106
+ violations: list[Violation] = []
107
+ for p in sorted((ROOT / CONTRACTS_DIR).glob("*.md")):
108
+ violations.extend(check_one(p, today))
109
+ if args.json:
110
+ print(json.dumps({"violations": [asdict(v) for v in violations]}, indent=2))
111
+ else:
112
+ if not violations:
113
+ print("✅ All beta contracts carry a valid review marker.")
114
+ else:
115
+ for v in violations:
116
+ icon = "❌" if v.severity == "error" else "⚠️ "
117
+ print(f"{icon} {v.file}: {v.reason}")
118
+ print(f"\n{len(violations)} violation(s).")
119
+ return 1 if any(v.severity == "error" for v in violations) else 0
120
+
121
+
122
+ if __name__ == "__main__":
123
+ try:
124
+ sys.exit(main())
125
+ except Exception as exc: # pragma: no cover
126
+ print(f"internal error: {exc}", file=sys.stderr)
127
+ sys.exit(3)
@@ -14,8 +14,10 @@ council files. Directory mentions and placeholder paths
14
14
  output-path convention, not a live reference.
15
15
 
16
16
  Forbidden hits in this codebase exist today (kernel-membership ADRs
17
- cite real session JSONs as decision traces). Suppress them with an
18
- inline pragma at the end of the line:
17
+ cite real session JSONs as decision traces). Two source/target shapes
18
+ are exempt structurally see STRUCTURAL_CARVEOUTS below — because
19
+ they encode immutable decision provenance, not transient drafting
20
+ state. Anything else needs an inline pragma at the end of the line:
19
21
 
20
22
  `agents/council-sessions/...json` <!-- council-ref-allowed: <reason> -->
21
23
 
@@ -82,6 +84,31 @@ ALLOWLIST_FILES: frozenset[str] = frozenset({
82
84
 
83
85
  INLINE_PRAGMA = re.compile(r"<!--\s*council-ref-allowed:[^>]*-->")
84
86
 
87
+ # Structural carve-outs — (source_pattern, target_pattern) pairs where
88
+ # the reference is immutable decision provenance rather than transient
89
+ # drafting state. Driven by the 2026-05-14 P3.4 council round
90
+ # (agents/council-sessions/2026-05-14-p3-4-references/synthesis.md).
91
+ #
92
+ # Each entry: source file matches `source` regex AND the captured
93
+ # reference path matches `target` regex → reference is allowed without
94
+ # an inline pragma.
95
+ STRUCTURAL_CARVEOUTS: tuple[tuple[re.Pattern[str], re.Pattern[str]], ...] = (
96
+ # (a) evaluation-context → council-question:
97
+ # the question file is a frozen function-parameter / spend-gate
98
+ # input, not a documentation link.
99
+ (
100
+ re.compile(r"^agents/contexts/evaluation-[^/]+\.md$"),
101
+ re.compile(r"^agents/council-questions/[^/]+\.md$"),
102
+ ),
103
+ # (b) contract → council-session-synthesis:
104
+ # the synthesis file is the audit-trail receipt the contract cites
105
+ # as decision provenance; the contract inlines the decision body.
106
+ (
107
+ re.compile(r"^docs/contracts/[^/]+\.md$"),
108
+ re.compile(r"^agents/council-sessions/[^/]+/synthesis\.md$"),
109
+ ),
110
+ )
111
+
85
112
 
86
113
  def _is_allowlisted(rel: str) -> bool:
87
114
  if rel in ALLOWLIST_FILES:
@@ -89,8 +116,17 @@ def _is_allowlisted(rel: str) -> bool:
89
116
  return any(rel.startswith(prefix) for prefix in ALLOWLIST_PREFIXES)
90
117
 
91
118
 
119
+ def _is_structurally_allowed(source_rel: str, target_capture: str) -> bool:
120
+ """True when (source, target) matches a structural carve-out pair."""
121
+ for src_re, tgt_re in STRUCTURAL_CARVEOUTS:
122
+ if src_re.match(source_rel) and tgt_re.match(target_capture):
123
+ return True
124
+ return False
125
+
126
+
92
127
  def _scan_file(path: Path) -> list[tuple[int, str]]:
93
128
  findings: list[tuple[int, str]] = []
129
+ rel = path.as_posix()
94
130
  try:
95
131
  text = path.read_text(encoding="utf-8")
96
132
  except (OSError, UnicodeDecodeError):
@@ -99,6 +135,8 @@ def _scan_file(path: Path) -> list[tuple[int, str]]:
99
135
  if INLINE_PRAGMA.search(line):
100
136
  continue
101
137
  for m in PATTERN.finditer(line):
138
+ if _is_structurally_allowed(rel, m.group(0)):
139
+ continue
102
140
  findings.append((ln, m.group(0)))
103
141
  return findings
104
142
 
@@ -136,10 +174,13 @@ def main() -> int:
136
174
  print(
137
175
  "\nRule: .agent-src/rules/no-roadmap-references.md (council clause)\n"
138
176
  "Fix: inline the convergence summary (members + date) instead of\n"
139
- "linking the file. Append "
177
+ "linking the file. Two source/target shapes are exempt structurally\n"
178
+ "(evaluation-context → council-question, contract →\n"
179
+ "council-session-synthesis) — see STRUCTURAL_CARVEOUTS in this\n"
180
+ "script. Otherwise append "
140
181
  "<!-- council-ref-allowed: <reason> --> on the same line to\n"
141
- "suppress when the reference is genuinely required (ADR / contract\n"
142
- "decision trace)."
182
+ "suppress when the reference is genuinely required (ADR decision\n"
183
+ "trace)."
143
184
  )
144
185
  return 1
145
186
 
@@ -0,0 +1,152 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ Release-trunk-sync CI gate (road-to-productization P1.3).
4
+
5
+ Fails if `main` is more than one tagged release behind the current
6
+ release-prep branch's target version. No-ops on every other branch
7
+ class. Owner contract: `docs/contracts/release-trunk-sync.md`.
8
+
9
+ Exit codes: 0 = pass / no-op, 1 = main is too far behind, 3 = internal
10
+ error (git unavailable, malformed tag, etc.).
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ import os
16
+ import re
17
+ import subprocess
18
+ import sys
19
+ from pathlib import Path
20
+
21
+ RELEASE_BRANCH_RE = re.compile(r"^release/(\d+)\.(\d+)\.(\d+)$")
22
+ SEMVER_TAG_RE = re.compile(r"^(\d+)\.(\d+)\.(\d+)$")
23
+ BOOTSTRAP_FILE = Path("docs/contracts/release-trunk-sync.bootstrap")
24
+
25
+
26
+ def _git(*args: str) -> str:
27
+ proc = subprocess.run(
28
+ ["git", *args], capture_output=True, text=True, check=False
29
+ )
30
+ if proc.returncode != 0:
31
+ return ""
32
+ return proc.stdout.strip()
33
+
34
+
35
+ def _current_branch() -> str:
36
+ return _git("rev-parse", "--abbrev-ref", "HEAD")
37
+
38
+
39
+ def _parse_semver(text: str) -> tuple[int, int, int] | None:
40
+ m = SEMVER_TAG_RE.match(text)
41
+ if not m:
42
+ return None
43
+ return int(m.group(1)), int(m.group(2)), int(m.group(3))
44
+
45
+
46
+ def _all_tags() -> list[tuple[int, int, int]]:
47
+ raw = _git("tag", "--list")
48
+ tags = []
49
+ for line in raw.splitlines():
50
+ parsed = _parse_semver(line.strip())
51
+ if parsed is not None:
52
+ tags.append(parsed)
53
+ tags.sort()
54
+ return tags
55
+
56
+
57
+ def _main_tag() -> tuple[int, int, int] | None:
58
+ """Highest semver tag whose commit is reachable from main."""
59
+ # Try local main, fall back to origin/main.
60
+ for ref in ("refs/heads/main", "refs/remotes/origin/main"):
61
+ head = _git("rev-parse", "--verify", ref)
62
+ if head:
63
+ break
64
+ else:
65
+ return None
66
+ # `git tag --merged <main>` lists tags reachable from main.
67
+ raw = _git("tag", "--merged", head)
68
+ reachable: list[tuple[int, int, int]] = []
69
+ for line in raw.splitlines():
70
+ parsed = _parse_semver(line.strip())
71
+ if parsed is not None:
72
+ reachable.append(parsed)
73
+ if not reachable:
74
+ return None
75
+ return max(reachable)
76
+
77
+
78
+ def _prior_release(
79
+ target: tuple[int, int, int], tags: list[tuple[int, int, int]]
80
+ ) -> tuple[int, int, int] | None:
81
+ earlier = [t for t in tags if t < target]
82
+ return max(earlier) if earlier else None
83
+
84
+
85
+ def _bootstrap_ok(target: tuple[int, int, int]) -> bool:
86
+ if not BOOTSTRAP_FILE.exists():
87
+ return False
88
+ target_s = "{0}.{1}.{2}".format(*target)
89
+ for line in BOOTSTRAP_FILE.read_text().splitlines():
90
+ line = line.strip()
91
+ if not line or line.startswith("#"):
92
+ continue
93
+ if line == target_s:
94
+ return True
95
+ return False
96
+
97
+
98
+ def main() -> int:
99
+ branch = _current_branch()
100
+ if branch == "HEAD" or not branch:
101
+ print("::warning::detached HEAD — release-trunk-sync gate skipped")
102
+ return 0
103
+ # CI override: GitHub Actions sometimes runs on the merge ref.
104
+ ci_ref = os.environ.get("GITHUB_HEAD_REF") or os.environ.get(
105
+ "GITHUB_REF_NAME"
106
+ )
107
+ if ci_ref:
108
+ branch = ci_ref
109
+ m = RELEASE_BRANCH_RE.match(branch)
110
+ if not m:
111
+ return 0 # non-release branch class — gate is a no-op
112
+ target = (int(m.group(1)), int(m.group(2)), int(m.group(3)))
113
+ tags = _all_tags()
114
+ if not tags:
115
+ print(
116
+ "::warning::no semver tags found — release-trunk-sync gate skipped"
117
+ )
118
+ return 0
119
+ main_tag = _main_tag()
120
+ if main_tag is None:
121
+ print(
122
+ "::warning::no semver tag reachable from main — gate skipped"
123
+ )
124
+ return 0
125
+ if main_tag >= target:
126
+ return 0 # main already at or ahead of release target
127
+ prior = _prior_release(target, tags)
128
+ if prior is not None and main_tag >= prior:
129
+ return 0 # within the one-release tolerance
130
+ if _bootstrap_ok(target):
131
+ target_s = "{0}.{1}.{2}".format(*target)
132
+ print(
133
+ f"::warning::release-trunk-sync gate suppressed for {target_s} "
134
+ "via bootstrap file"
135
+ )
136
+ return 0
137
+ main_s = "{0}.{1}.{2}".format(*main_tag)
138
+ target_s = "{0}.{1}.{2}".format(*target)
139
+ print(
140
+ f"::error::main is at {main_s}; release-prep branch targets "
141
+ f"{target_s}. Main must be no more than one tagged release behind. "
142
+ "See docs/contracts/release-trunk-sync.md."
143
+ )
144
+ return 1
145
+
146
+
147
+ if __name__ == "__main__":
148
+ try:
149
+ sys.exit(main())
150
+ except Exception as exc: # noqa: BLE001
151
+ print(f"::error::release-trunk-sync gate internal error: {exc}")
152
+ sys.exit(3)