cadre-ai 1.1.0 → 1.1.2
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.
- package/package.json +1 -1
- package/scripts/cadre-cli.js +231 -41
- package/scripts/mcp/cadre-server.js +1 -1
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
// AUTO-GENERATED by pnpm build from src/*.ts -- do not edit by hand.
|
|
3
3
|
// Edit TypeScript sources under src/ instead.
|
|
4
|
-
const __CADRE_EMBEDDED_ASSETS__ = {"skill":{"version":1,"schema":"cadre.skill.v1","id":"cadre","name":"Cadre","markdownUse":"human_projection_only","description":"Context-driven development methodology for organized, spec-first coding. JSON is the authoritative agent/runtime contract; Markdown exists only as platform shim or generated human projection.","activation":{"triggers":["project has cadre/","user mentions specs, plans, tracks, or context-driven development","user asks for cadre-* workflow","user asks about Cadre project status, track management, review, ship, land, release, archive, setup, or artifact sync","project is a polyrepo control repo with cadre/repos.json"],"requiredRuntime":"Cadre MCP","startup":[{"tool":"cadre_project","arguments":{"action":"ping"},"purpose":"Verify Cadre MCP availability before every Cadre workflow"},{"rule":"Every project-scoped Cadre MCP call must include a per-call root argument pointing at the project root or a path inside it"},{"rule":"If Cadre MCP tools are unavailable, halt and ask the user to install, enable, or restart the Cadre plugin"}]},"lazyContext":{"defaultResponseMode":"compact","detailMode":"Use responseMode=detail only for full plans, code-intelligence evidence, or long style-guide content","canonicalArtifacts":["cadre/product.json","cadre/product_guidelines.json","cadre/tech-stack.json","cadre/workflow.json","cadre/patterns.jsonl","cadre/tracks.json","track metadata.json/spec.json/plan.json/learnings.jsonl/handoff.json","cadre/styleguides/*.json"],"humanProjections":["cadre/product.md","cadre/product_guidelines.md","cadre/workflow.md","cadre/patterns.md","track spec.md/plan.md/learnings.md/HANDOFF.md","cadre/code_styleguides/*.md"],"rules":["Do not read Markdown projections as canonical truth","Do not eagerly read the whole cadre/ tree on activation","Resolve live status from MCP packets and track metadata, not generated indexes"]},"workflows":{"setup":{"intent":"Setup project","protocol":"cadre://workflow-protocol?workflow=setup"},"newtrack":{"intent":"Create work","protocol":"cadre://workflow-protocol?workflow=newtrack"},"implement":{"intent":"Start or resume implementation","protocol":"cadre://workflow-protocol?workflow=implement"},"status":{"intent":"Status, team board, or fleet board","protocol":"cadre://workflow-protocol?workflow=status"},"validate":{"intent":"Validate project state","protocol":"cadre://workflow-protocol?workflow=validate"},"flag":{"intent":"Flag blocked or skipped work","protocol":"cadre://workflow-protocol?workflow=flag"},"revise":{"intent":"Revise spec or plan","protocol":"cadre://workflow-protocol?workflow=revise"},"review":{"intent":"Review quality gate","protocol":"cadre://workflow-protocol?workflow=review"},"ship":{"intent":"Ship monorepo work","protocol":"cadre://workflow-protocol?workflow=ship"},"land":{"intent":"Land polyrepo work","protocol":"cadre://workflow-protocol?workflow=land"},"handoff":{"intent":"Handoff context","protocol":"cadre://workflow-protocol?workflow=handoff"},"archive":{"intent":"Archive completed tracks","protocol":"cadre://workflow-protocol?workflow=archive"},"release":{"intent":"Release summary or version","protocol":"cadre://workflow-protocol?workflow=release"},"refresh":{"intent":"Refresh stale context","protocol":"cadre://workflow-protocol?workflow=refresh"},"revert":{"intent":"Revert tracked commits","protocol":"cadre://workflow-protocol?workflow=revert"},"formula":{"intent":"Formula or template operations","protocol":"cadre://workflow-protocol?workflow=formula"},"artifacts":{"intent":"Sync canonical artifacts","protocol":"cadre://workflow-protocol?workflow=artifacts"}},"references":{"mcp-contract":{"uri":"cadre://agent-reference?name=mcp-contract"},"provider-evidence":{"uri":"cadre://agent-reference?name=provider-evidence"},"team-ops":{"uri":"cadre://agent-reference?name=team-ops"},"cadre-sync":{"uri":"cadre://agent-reference?name=cadre-sync"},"ownership-guard":{"uri":"cadre://agent-reference?name=ownership-guard"},"parallel-execution":{"uri":"cadre://agent-reference?name=parallel-execution"},"polyrepo-git":{"uri":"cadre://agent-reference?name=polyrepo-git"},"template-locator":{"uri":"cadre://agent-reference?name=template-locator"}},"operatingDefaults":["Setup writes native Cadre event, message, formula, and local wisp state through packets","Shared sync is recommended for teams and packet-owned","Hosted provider evidence must come through official provider MCPs and be written back through Cadre packets","LSP/code-intelligence packets should be used for repo maps, impact checks, review assistance, diagnostics, and test-impact hints"],"forbidden":["Do not mutate cadre/, provider state, indexes, worker state, event/message state, or merge/cleanup state outside Cadre packets","Do not use Markdown as alternate input, legacy import source, or runtime state","Do not manually edit generated Markdown projections as workflow state"]},"protocols":{"archive":{"version":1,"schema":"cadre.protocol.v1","id":"cadre-archive","description":"Archive completed tracks","workflow":"archive","markdownUse":"human_projection_only","preconditions":[{"tool":"cadre_project","arguments":{"action":"ping"},"requirement":"Cadre MCP must be available"},{"requirement":"Every project-scoped packet call includes root"},{"requirement":"If a required packet returns ok:false, halt and report the packet error"}],"packetFlow":[{"step":1,"instruction":"Resolve the project root with `cadre_project` using `action: \"root\"`."},{"step":2,"instruction":"Call `cadre_workflow` with `workflow: \"archive\"` and the resolved root. Pass `trackId`, cutoff, or scope arguments as structured JSON fields only."},{"step":3,"instruction":"Present the dry-run `tracks` list, packet warnings, cleanup scope, and any review_bundle manifest/path list without inlining large artifact contents into model context."},{"step":4,"instruction":"To archive reviewed work, call `cadre_workflow` again with `workflow: \"archive\"`, `execute: true`, and `humanConfirmed: true`."},{"step":5,"instruction":"Summarize archived track ids, packet warnings, changed canonical JSON/JSONL artifacts, generated human projections, and any packet errors."}],"confirmation":{"requiredForMutation":true,"dryRunFirst":true,"executeArgument":"execute","humanConfirmationArgument":"humanConfirmed"},"forbiddenActions":["Do not recreate Cadre control-plane, native event/message state, index, worktree, provider, merge, or cleanup state with shell commands","Do not read or write Markdown projections as canonical state","Do not use Markdown payload fields, legacy Markdown import, or prompt-side state repair"],"responseSummary":["packet ok/error state","selected track or scope","warnings and blockers","changed canonical JSON/JSONL artifacts","generated human projections when relevant","next recommended packet"],"references":["mcp-contract"]},"artifacts":{"version":1,"schema":"cadre.protocol.v1","id":"cadre-artifacts","description":"Sync canonical Cadre artifacts with generated human projections","workflow":"artifacts","markdownUse":"human_projection_only","preconditions":[{"tool":"cadre_project","arguments":{"action":"ping"},"requirement":"Cadre MCP must be available"},{"requirement":"Every project-scoped packet call includes root"},{"requirement":"If a required packet returns ok:false, halt and report the packet error"}],"packetFlow":[{"step":1,"instruction":"Resolve the project root with `cadre_project` using `action: \"root\"`."},{"step":2,"instruction":"For discovery, call `cadre_artifact` with `action: \"catalog\"`, `\"schema\"`, `\"validate\"`, `\"render\"`, or `\"diff\"` and structured JSON arguments."},{"step":3,"instruction":"For preview, call `cadre_artifact` with `action: \"sync\"`, the requested scope, and no legacy Markdown import fields."},{"step":4,"instruction":"Review `review_bundle` when present. The bundle contains a manifest/path list for full proposed artifacts so large Markdown projections stay out of model context."},{"step":5,"instruction":"To apply reviewed synchronization, call `cadre_artifact` again with `action: \"sync\"`, `execute: true`, and `humanConfirmed: true`."},{"step":6,"instruction":"Summarize changed canonical JSON/JSONL artifacts, regenerated human projections, skipped unmarked projections, warnings, and next recommended packet."}],"confirmation":{"requiredForMutation":true,"dryRunFirst":true,"executeArgument":"execute","humanConfirmationArgument":"humanConfirmed"},"forbiddenActions":["Do not recreate Cadre control-plane, native event/message state, index, worktree, provider, merge, or cleanup state with shell commands","Do not read or write Markdown projections as canonical state","Do not use Markdown payload fields, legacy Markdown import, or prompt-side state repair"],"responseSummary":["packet ok/error state","selected track or scope","warnings and blockers","changed canonical JSON/JSONL artifacts","generated human projections when relevant","next recommended packet"],"references":["mcp-contract","template-locator"]},"flag":{"version":1,"schema":"cadre.protocol.v1","id":"cadre-flag","description":"Flag the current task as blocked or skipped with a reason","workflow":"flag","markdownUse":"human_projection_only","preconditions":[{"tool":"cadre_project","arguments":{"action":"ping"},"requirement":"Cadre MCP must be available"},{"requirement":"Every project-scoped packet call includes root"},{"requirement":"If a required packet returns ok:false, halt and report the packet error"}],"packetFlow":[{"step":1,"instruction":"Resolve the project root with `cadre_project` using `action: \"root\"`."},{"step":2,"instruction":"Call `cadre_workflow` with `workflow: \"flag\"`, the resolved root, `trackId`, desired status, reason, and any task selectors as structured JSON fields."},{"step":3,"instruction":"Present the dry-run status change, selected track, reason, warnings, and review_bundle manifest/path list when returned."},{"step":4,"instruction":"When mutation is intended, pass `execute: true` and `humanConfirmed: true` so Cadre packets update canonical JSON state and generated projections."},{"step":5,"instruction":"Summarize selected track, resulting status, reason, changed canonical JSON artifacts, generated human projections, and packet warnings."}],"confirmation":{"requiredForMutation":true,"dryRunFirst":true,"executeArgument":"execute","humanConfirmationArgument":"humanConfirmed"},"forbiddenActions":["Do not recreate Cadre control-plane, native event/message state, index, worktree, provider, merge, or cleanup state with shell commands","Do not read or write Markdown projections as canonical state","Do not use Markdown payload fields, legacy Markdown import, or prompt-side state repair"],"responseSummary":["packet ok/error state","selected track or scope","warnings and blockers","changed canonical JSON/JSONL artifacts","generated human projections when relevant","next recommended packet"],"references":["mcp-contract"]},"formula":{"version":1,"schema":"cadre.protocol.v1","id":"cadre-formula","description":"Manage native Cadre formulas and local wisps","workflow":"formula","markdownUse":"human_projection_only","preconditions":[{"tool":"cadre_project","arguments":{"action":"ping"},"requirement":"Cadre MCP must be available"},{"requirement":"Every project-scoped packet call includes root"},{"requirement":"If a required packet returns ok:false, halt and report the packet error"}],"packetFlow":[{"step":1,"instruction":"Resolve the project root with `cadre_project` using `action: \"root\"`."},{"step":2,"instruction":"Call `cadre_workflow` with `workflow: \"formula\"` and the requested native formula operation as structured JSON arguments: list, show, cook, wisp_create, wisp_list, wisp_update_step, wisp_squash, wisp_burn, or pour."},{"step":3,"instruction":"Use `pour` for reviewed persistent output; it routes generated spec and plan JSON through normal `cadre-newtrack` creation with formula trace fields. Local wisps remain under `cadre/local/wisps/` until squashed or burned; `wisp_squash` records a durable digest and control commit."},{"step":4,"instruction":"Summarize available formulas, generated draft tracks, canonical JSON artifacts, or packet errors."}],"confirmation":{"requiredForMutation":true,"dryRunFirst":false,"executeArgument":"execute","humanConfirmationArgument":"humanConfirmed"},"forbiddenActions":["Do not recreate Cadre control-plane, native event/message state, index, worktree, provider, merge, or cleanup state with shell commands","Do not read or write Markdown projections as canonical state","Do not use Markdown payload fields, legacy Markdown import, or prompt-side state repair"],"responseSummary":["packet ok/error state","selected track or scope","warnings and blockers","changed canonical JSON/JSONL artifacts","generated human projections when relevant","next recommended packet"],"references":["mcp-contract"]},"handoff":{"version":1,"schema":"cadre.protocol.v1","id":"cadre-handoff","description":"Create context handoff for transferring implementation to next section/session","workflow":"handoff","markdownUse":"human_projection_only","preconditions":[{"tool":"cadre_project","arguments":{"action":"ping"},"requirement":"Cadre MCP must be available"},{"requirement":"Every project-scoped packet call includes root"},{"requirement":"If a required packet returns ok:false, halt and report the packet error"}],"packetFlow":[{"step":1,"instruction":"Resolve the project root with `cadre_project` using `action: \"root\"`."},{"step":2,"instruction":"Call `cadre_workflow` with `workflow: \"handoff\"` and any `trackId`, recipient, audience, or scope arguments as structured JSON fields."},{"step":3,"instruction":"Review the returned `track_context`, native message/event state, handoff path, warnings, and review_bundle manifest/path list without inlining large artifacts into model context."},{"step":4,"instruction":"To write the handoff, call `cadre_workflow` again with `workflow: \"handoff\"`, `execute: true`, and `humanConfirmed: true`."},{"step":5,"instruction":"Summarize the handoff path, recipient or audience, open risks, changed canonical JSON artifacts, generated human projections, and next packet."}],"confirmation":{"requiredForMutation":true,"dryRunFirst":true,"executeArgument":"execute","humanConfirmationArgument":"humanConfirmed"},"forbiddenActions":["Do not recreate Cadre control-plane, native event/message state, index, worktree, provider, merge, or cleanup state with shell commands","Do not read or write Markdown projections as canonical state","Do not use Markdown payload fields, legacy Markdown import, or prompt-side state repair"],"responseSummary":["packet ok/error state","selected track or scope","warnings and blockers","changed canonical JSON/JSONL artifacts","generated human projections when relevant","next recommended packet"],"references":["mcp-contract"]},"implement":{"version":1,"schema":"cadre.protocol.v1","id":"cadre-implement","description":"Execute tasks from a track's implementation plan","workflow":"implement","markdownUse":"human_projection_only","preconditions":[{"tool":"cadre_project","arguments":{"action":"ping"},"requirement":"Cadre MCP must be available"},{"requirement":"Every project-scoped packet call includes root"},{"requirement":"If a required packet returns ok:false, halt and report the packet error"}],"packetFlow":[{"step":1,"instruction":"Resolve the project root with `cadre_project` using `action: \"root\"`."},{"step":2,"instruction":"Call `cadre_workflow` with `workflow: \"implement\"`, the resolved root, and optional track/task selectors as structured JSON fields."},{"step":3,"instruction":"Use the returned `prepare_implementation.styleGuides` JSON context before product edits; Markdown style-guide projections are human-readable only."},{"step":4,"instruction":"Use the returned `prepare_implementation` and `phase_schedule` to choose the next ready task while respecting ownership, repo, and dependency JSON fields."},{"step":5,"instruction":"For parallel work, use `cadre_parallel` packets for planning, worker setup, finish recording, merge-back, and cleanup."},{"step":6,"instruction":"After each task, call `cadre_complete_task` with coverage, verification, changed files, and summary evidence as structured JSON fields. If no commit SHA is supplied, Cadre creates the task product commit, records the Cadre control-plane commit, and writes `refs/notes/cadre` trace notes."},{"step":7,"instruction":"Summarize completed work, style guides used, tests run, coverage, commits, changed canonical JSON artifacts, generated human projections, and next packet."}],"confirmation":{"requiredForMutation":true,"dryRunFirst":false,"executeArgument":"execute","humanConfirmationArgument":"humanConfirmed"},"forbiddenActions":["Do not recreate Cadre control-plane, native event/message state, index, worktree, provider, merge, or cleanup state with shell commands","Do not read or write Markdown projections as canonical state","Do not use Markdown payload fields, legacy Markdown import, or prompt-side state repair"],"responseSummary":["packet ok/error state","selected track or scope","warnings and blockers","changed canonical JSON/JSONL artifacts","generated human projections when relevant","next recommended packet"],"references":["parallel-execution","mcp-contract","ownership-guard"]},"land":{"version":1,"schema":"cadre.protocol.v1","id":"cadre-land","description":"Open and link the cross-repo PR group for a polyrepo track, then let the merge train land it","workflow":"land","markdownUse":"human_projection_only","preconditions":[{"tool":"cadre_project","arguments":{"action":"ping"},"requirement":"Cadre MCP must be available"},{"requirement":"Every project-scoped packet call includes root"},{"requirement":"If a required packet returns ok:false, halt and report the packet error"}],"packetFlow":[{"step":1,"instruction":"Resolve the project root with `cadre_project` using `action: \"root\"`."},{"step":2,"instruction":"Call `cadre_workflow` with `workflow: \"land\"` and the requested `trackId` as structured JSON."},{"step":3,"instruction":"Use the returned topology, polyrepo preflight, review gate, fleet status, provider actions, git actions, and review_bundle manifest/path list."},{"step":4,"instruction":"When the packet reports `phase_state: \"ready\"` or `\"pending_provider\"`, call the packet again with `execute: true` only after required review and provider evidence are available."},{"step":5,"instruction":"If the packet returns `phase_state: \"pending_provider\"`, execute only the returned provider MCP actions and write evidence back through Cadre packets."},{"step":6,"instruction":"Summarize every repo result, linked review artifact, CI state, publication ledger path, control commit, git-note push state, packet warnings, changed canonical JSON artifacts, generated human projections, and remaining blockers."}],"confirmation":{"requiredForMutation":true,"dryRunFirst":false,"executeArgument":"execute","humanConfirmationArgument":"humanConfirmed"},"forbiddenActions":["Do not recreate Cadre control-plane, native event/message state, index, worktree, provider, merge, or cleanup state with shell commands","Do not read or write Markdown projections as canonical state","Do not use Markdown payload fields, legacy Markdown import, or prompt-side state repair"],"responseSummary":["packet ok/error state","selected track or scope","warnings and blockers","changed canonical JSON/JSONL artifacts","generated human projections when relevant","next recommended packet"],"references":["provider-evidence","polyrepo-git","mcp-contract"]},"newtrack":{"version":1,"schema":"cadre.protocol.v1","id":"cadre-newtrack","description":"Create a new feature or bug track with spec and plan","workflow":"newtrack","markdownUse":"human_projection_only","preconditions":[{"tool":"cadre_project","arguments":{"action":"ping"},"requirement":"Cadre MCP must be available"},{"requirement":"Every project-scoped packet call includes root"},{"requirement":"If a required packet returns ok:false, halt and report the packet error"}],"packetFlow":[{"step":1,"instruction":"Resolve the project root with `cadre_project` using `action: \"root\"`."},{"step":2,"instruction":"Draft structured `spec` and `plan` JSON from the user request and current project context. Do not send Markdown fields such as `specText`, `planText`, or `planPath`."},{"step":3,"instruction":"Call `cadre_workflow` with `workflow: \"newtrack\"`, `trackId`, `spec`, `plan`, and any metadata as structured JSON fields."},{"step":4,"instruction":"Review the returned canonical spec/plan JSON artifacts, generated Markdown projection previews, learnings starter, plan assistance, and review_bundle manifest/path list without inlining large artifacts into model context."},{"step":5,"instruction":"To create the track after approval, call `cadre_workflow` again with `workflow: \"newtrack\"`, `execute: true`, and `humanConfirmed: true` using the same JSON payload."},{"step":6,"instruction":"Summarize created track id, native event record, worktree plan, changed canonical JSON artifacts, generated human projections, and next packet."}],"confirmation":{"requiredForMutation":true,"dryRunFirst":true,"executeArgument":"execute","humanConfirmationArgument":"humanConfirmed"},"forbiddenActions":["Do not recreate Cadre control-plane, native event/message state, index, worktree, provider, merge, or cleanup state with shell commands","Do not read or write Markdown projections as canonical state","Do not use Markdown payload fields, legacy Markdown import, or prompt-side state repair"],"responseSummary":["packet ok/error state","selected track or scope","warnings and blockers","changed canonical JSON/JSONL artifacts","generated human projections when relevant","next recommended packet"],"references":["mcp-contract"]},"refresh":{"version":1,"schema":"cadre.protocol.v1","id":"cadre-refresh","description":"Sync context docs with current codebase state","workflow":"refresh","markdownUse":"human_projection_only","preconditions":[{"tool":"cadre_project","arguments":{"action":"ping"},"requirement":"Cadre MCP must be available"},{"requirement":"Every project-scoped packet call includes root"},{"requirement":"If a required packet returns ok:false, halt and report the packet error"}],"packetFlow":[{"step":1,"instruction":"Resolve the project root with `cadre_project` using `action: \"root\"`."},{"step":2,"instruction":"Call `cadre_workflow` with `workflow: \"refresh\"` and any requested scope as structured JSON fields."},{"step":3,"instruction":"Use the returned doctor, workspace diagnostics, dependency graph, LSP evidence, and review_bundle manifest/path list to identify stale canonical JSON/JSONL context without inlining large artifacts into model context."},{"step":4,"instruction":"When packet-supported document updates are requested, call the workflow packet again with `execute: true` and `humanConfirmed: true`."},{"step":5,"instruction":"Summarize refreshed canonical context, regenerated human projections, stale areas, diagnostics, and packet warnings."}],"confirmation":{"requiredForMutation":true,"dryRunFirst":true,"executeArgument":"execute","humanConfirmationArgument":"humanConfirmed"},"forbiddenActions":["Do not recreate Cadre control-plane, native event/message state, index, worktree, provider, merge, or cleanup state with shell commands","Do not read or write Markdown projections as canonical state","Do not use Markdown payload fields, legacy Markdown import, or prompt-side state repair"],"responseSummary":["packet ok/error state","selected track or scope","warnings and blockers","changed canonical JSON/JSONL artifacts","generated human projections when relevant","next recommended packet"],"references":["mcp-contract"]},"release":{"version":1,"schema":"cadre.protocol.v1","id":"cadre-release","description":"Cut a local release - changelog plus version evidence across completed tracks","workflow":"release","markdownUse":"human_projection_only","preconditions":[{"tool":"cadre_project","arguments":{"action":"ping"},"requirement":"Cadre MCP must be available"},{"requirement":"Every project-scoped packet call includes root"},{"requirement":"If a required packet returns ok:false, halt and report the packet error"}],"packetFlow":[{"step":1,"instruction":"Resolve the project root with `cadre_project` using `action: \"root\"`."},{"step":2,"instruction":"Call `cadre_workflow` with `workflow: \"release\"` and any requested version, date, or scope arguments as structured JSON fields."},{"step":3,"instruction":"Review returned completed tracks, release evidence, warnings, proposed artifacts, and review_bundle manifest/path list without inlining large artifacts into model context."},{"step":4,"instruction":"To write release artifacts, call `cadre_workflow` again with `workflow: \"release\"`, `execute: true`, and `humanConfirmed: true`."},{"step":5,"instruction":"Summarize release scope, version intent, generated artifacts, changed canonical JSON/JSONL state, generated human projections, and remaining blockers."}],"confirmation":{"requiredForMutation":true,"dryRunFirst":true,"executeArgument":"execute","humanConfirmationArgument":"humanConfirmed"},"forbiddenActions":["Do not recreate Cadre control-plane, native event/message state, index, worktree, provider, merge, or cleanup state with shell commands","Do not read or write Markdown projections as canonical state","Do not use Markdown payload fields, legacy Markdown import, or prompt-side state repair"],"responseSummary":["packet ok/error state","selected track or scope","warnings and blockers","changed canonical JSON/JSONL artifacts","generated human projections when relevant","next recommended packet"],"references":["mcp-contract"]},"revert":{"version":1,"schema":"cadre.protocol.v1","id":"cadre-revert","description":"Revert tracks, phases, or tasks through Cadre packets","workflow":"revert","markdownUse":"human_projection_only","preconditions":[{"tool":"cadre_project","arguments":{"action":"ping"},"requirement":"Cadre MCP must be available"},{"requirement":"Every project-scoped packet call includes root"},{"requirement":"If a required packet returns ok:false, halt and report the packet error"}],"packetFlow":[{"step":1,"instruction":"Resolve the project root with `cadre_project` using `action: \"root\"`."},{"step":2,"instruction":"Call `cadre_workflow` with `workflow: \"revert\"` and the requested `trackId`, commit, repo, or scope arguments as structured JSON fields."},{"step":3,"instruction":"Present the packet dry-run revert scope, planned git actions, affected canonical JSON artifacts, generated projections, warnings, and review_bundle manifest/path list."},{"step":4,"instruction":"To execute an approved revert, call `cadre_workflow` again with `workflow: \"revert\"`, `execute: true`, and `humanConfirmed: true`."},{"step":5,"instruction":"Summarize reverted scope, tests requested or run, changed canonical JSON/JSONL artifacts, generated human projections, packet warnings, and follow-up packets."}],"confirmation":{"requiredForMutation":true,"dryRunFirst":true,"executeArgument":"execute","humanConfirmationArgument":"humanConfirmed"},"forbiddenActions":["Do not recreate Cadre control-plane, native event/message state, index, worktree, provider, merge, or cleanup state with shell commands","Do not read or write Markdown projections as canonical state","Do not use Markdown payload fields, legacy Markdown import, or prompt-side state repair"],"responseSummary":["packet ok/error state","selected track or scope","warnings and blockers","changed canonical JSON/JSONL artifacts","generated human projections when relevant","next recommended packet"],"references":["mcp-contract"]},"review":{"version":1,"schema":"cadre.protocol.v1","id":"cadre-review","description":"Review a track's diff before shipping (quality gate)","workflow":"review","markdownUse":"human_projection_only","preconditions":[{"tool":"cadre_project","arguments":{"action":"ping"},"requirement":"Cadre MCP must be available"},{"requirement":"Every project-scoped packet call includes root"},{"requirement":"If a required packet returns ok:false, halt and report the packet error"}],"packetFlow":[{"step":1,"instruction":"Resolve the project root with `cadre_project` using `action: \"root\"`."},{"step":2,"instruction":"Call `cadre_workflow` with `workflow: \"review\"` and the requested `trackId` as structured JSON."},{"step":3,"instruction":"Use the returned track context, review assistance, machine gate, review gate, provider evidence state, and review_bundle manifest/path list."},{"step":4,"instruction":"When provider evidence is required, call `cadre_review` with structured provider MCP evidence; do not fetch or mutate provider state through shell commands."},{"step":5,"instruction":"To record a verdict, call `cadre_mutate` with `action: \"record_review\"` and the structured verdict/evidence payload."},{"step":6,"instruction":"Summarize findings first, then gate state, evidence, changed canonical JSON artifacts, generated human projections, and next packet."}],"confirmation":{"requiredForMutation":true,"dryRunFirst":false,"executeArgument":"execute","humanConfirmationArgument":"humanConfirmed"},"forbiddenActions":["Do not recreate Cadre control-plane, native event/message state, index, worktree, provider, merge, or cleanup state with shell commands","Do not read or write Markdown projections as canonical state","Do not use Markdown payload fields, legacy Markdown import, or prompt-side state repair"],"responseSummary":["packet ok/error state","selected track or scope","warnings and blockers","changed canonical JSON/JSONL artifacts","generated human projections when relevant","next recommended packet"],"references":["mcp-contract"]},"revise":{"version":1,"schema":"cadre.protocol.v1","id":"cadre-revise","description":"Update spec/plan when implementation reveals issues","workflow":"revise","markdownUse":"human_projection_only","preconditions":[{"tool":"cadre_project","arguments":{"action":"ping"},"requirement":"Cadre MCP must be available"},{"requirement":"Every project-scoped packet call includes root"},{"requirement":"If a required packet returns ok:false, halt and report the packet error"}],"packetFlow":[{"step":1,"instruction":"Resolve the project root with `cadre_project` using `action: \"root\"`."},{"step":2,"instruction":"Call `cadre_workflow` with `workflow: \"revise\"`, the requested `trackId`, and proposed structured `spec` or `plan` JSON fields. Do not send Markdown fields such as `specText`, `planText`, or `planPath`."},{"step":3,"instruction":"Use the returned track context and impact analysis to review proposed canonical JSON changes and generated Markdown projection previews."},{"step":4,"instruction":"When packet-supported mutation is requested, call the workflow packet again with `execute: true` and `humanConfirmed: true` after reviewing the review_bundle manifest/path list without inlining large artifacts into model context."},{"step":5,"instruction":"Summarize changed requirements, affected tasks, tests to update, changed canonical JSON artifacts, generated human projections, and packet warnings."}],"confirmation":{"requiredForMutation":true,"dryRunFirst":true,"executeArgument":"execute","humanConfirmationArgument":"humanConfirmed"},"forbiddenActions":["Do not recreate Cadre control-plane, native event/message state, index, worktree, provider, merge, or cleanup state with shell commands","Do not read or write Markdown projections as canonical state","Do not use Markdown payload fields, legacy Markdown import, or prompt-side state repair"],"responseSummary":["packet ok/error state","selected track or scope","warnings and blockers","changed canonical JSON/JSONL artifacts","generated human projections when relevant","next recommended packet"],"references":["mcp-contract"]},"setup":{"version":1,"schema":"cadre.protocol.v1","id":"cadre-setup","description":"Initialize project with Cadre context-driven development","workflow":"setup","markdownUse":"human_projection_only","preconditions":[{"tool":"cadre_project","arguments":{"action":"ping"},"requirement":"Cadre MCP must be available"},{"requirement":"Every project-scoped packet call includes root"},{"requirement":"If a required packet returns ok:false, halt and report the packet error"}],"packetFlow":[{"step":1,"instruction":"Call `cadre_project` with `action: \"ping\"` to confirm MCP availability."},{"step":2,"instruction":"Call `cadre_workflow` with `workflow: \"setup\"`, the root candidate, structured `product`, optional `productGuidelines`, optional `workflowPolicy`, and `techStack` JSON fields. Use the returned setup review artifacts and native state summary for the user review."},{"step":3,"instruction":"Use the returned doctor report, workspace diagnostics, dependency graph, LSP evidence, template inventory, and selected JSON style guides."},{"step":4,"instruction":"Present returned setup review artifacts using the review_bundle manifest/path list so large generated Markdown projections do not enter model context."},{"step":5,"instruction":"When the user confirms the setup payload and review artifacts, call `cadre_workflow` again with `workflow: \"setup\"`, `execute: true`, and `humanConfirmed: true`."},{"step":6,"instruction":"Summarize created canonical JSON/JSONL files, generated human projections, selected code style guides, native state initialization, warnings, and next packet."}],"confirmation":{"requiredForMutation":true,"dryRunFirst":true,"executeArgument":"execute","humanConfirmationArgument":"humanConfirmed"},"forbiddenActions":["Do not recreate Cadre control-plane, native event/message state, index, worktree, provider, merge, or cleanup state with shell commands","Do not read or write Markdown projections as canonical state","Do not use Markdown payload fields, legacy Markdown import, or prompt-side state repair"],"responseSummary":["packet ok/error state","selected track or scope","warnings and blockers","changed canonical JSON/JSONL artifacts","generated human projections when relevant","next recommended packet"],"references":["template-locator","mcp-contract"]},"ship":{"version":1,"schema":"cadre.protocol.v1","id":"cadre-ship","description":"Rebase a reviewed track onto main, publish it, and prepare the PR","workflow":"ship","markdownUse":"human_projection_only","preconditions":[{"tool":"cadre_project","arguments":{"action":"ping"},"requirement":"Cadre MCP must be available"},{"requirement":"Every project-scoped packet call includes root"},{"requirement":"If a required packet returns ok:false, halt and report the packet error"}],"packetFlow":[{"step":1,"instruction":"Resolve the project root with `cadre_project` using `action: \"root\"`."},{"step":2,"instruction":"Call `cadre_workflow` with `workflow: \"ship\"` and the requested `trackId` as structured JSON."},{"step":3,"instruction":"Use the returned review gate, git actions, provider actions, CI evidence, warnings, and review_bundle manifest/path list."},{"step":4,"instruction":"When the packet reports `phase_state: \"ready\"` or `\"pending_provider\"`, call the packet again with `execute: true` only after required review and provider evidence are available."},{"step":5,"instruction":"If the packet returns `phase_state: \"pending_provider\"`, execute only returned provider MCP actions and write evidence back through Cadre packets."},{"step":6,"instruction":"Summarize branch, review gate, provider artifact, CI state, publication ledger path, control commit, git-note push state, changed canonical JSON artifacts, generated human projections, and next packet."}],"confirmation":{"requiredForMutation":true,"dryRunFirst":false,"executeArgument":"execute","humanConfirmationArgument":"humanConfirmed"},"forbiddenActions":["Do not recreate Cadre control-plane, native event/message state, index, worktree, provider, merge, or cleanup state with shell commands","Do not read or write Markdown projections as canonical state","Do not use Markdown payload fields, legacy Markdown import, or prompt-side state repair"],"responseSummary":["packet ok/error state","selected track or scope","warnings and blockers","changed canonical JSON/JSONL artifacts","generated human projections when relevant","next recommended packet"],"references":["provider-evidence","polyrepo-git","mcp-contract"]},"status":{"version":1,"schema":"cadre.protocol.v1","id":"cadre-status","description":"Display current Cadre project progress","workflow":"status","markdownUse":"human_projection_only","preconditions":[{"tool":"cadre_project","arguments":{"action":"ping"},"requirement":"Cadre MCP must be available"},{"requirement":"Every project-scoped packet call includes root"},{"requirement":"If a required packet returns ok:false, halt and report the packet error"}],"packetFlow":[{"step":1,"instruction":"Resolve the project root with `cadre_project` using `action: \"root\"`."},{"step":2,"instruction":"Call `cadre_workflow` with `workflow: \"status\"` and a `mode` such as `live`, `team`, `fleet`, or `review` as structured JSON fields."},{"step":3,"instruction":"For rich resources, read the matching MCP resource when useful instead of eagerly loading the whole Cadre control plane."},{"step":4,"instruction":"Summarize active track, ownership, blockers, review queue, fleet health, canonical JSON state, generated projection status, and next packet."}],"confirmation":{"requiredForMutation":true,"dryRunFirst":false,"executeArgument":"execute","humanConfirmationArgument":"humanConfirmed"},"forbiddenActions":["Do not recreate Cadre control-plane, native event/message state, index, worktree, provider, merge, or cleanup state with shell commands","Do not read or write Markdown projections as canonical state","Do not use Markdown payload fields, legacy Markdown import, or prompt-side state repair"],"responseSummary":["packet ok/error state","selected track or scope","warnings and blockers","changed canonical JSON/JSONL artifacts","generated human projections when relevant","next recommended packet"],"references":["mcp-contract"]},"validate":{"version":1,"schema":"cadre.protocol.v1","id":"cadre-validate","description":"Validate Cadre project integrity","workflow":"validate","markdownUse":"human_projection_only","preconditions":[{"tool":"cadre_project","arguments":{"action":"ping"},"requirement":"Cadre MCP must be available"},{"requirement":"Every project-scoped packet call includes root"},{"requirement":"If a required packet returns ok:false, halt and report the packet error"}],"packetFlow":[{"step":1,"instruction":"Resolve the project root with `cadre_project` using `action: \"root\"`."},{"step":2,"instruction":"Call `cadre_workflow` with `workflow: \"validate\"` and any requested track, scope, or repair intent as structured JSON fields."},{"step":3,"instruction":"Use the returned doctor report, team inventory, plan integrity, collision scan, provider status, and review_bundle manifest/path list."},{"step":4,"instruction":"When packet-supported repair is requested, call the workflow packet again with `execute: true` and `humanConfirmed: true` after reviewing proposed canonical JSON changes."},{"step":5,"instruction":"Summarize errors before warnings, then repaired canonical JSON/JSONL artifacts, generated human projections, remaining risks, and next packet."}],"confirmation":{"requiredForMutation":true,"dryRunFirst":false,"executeArgument":"execute","humanConfirmationArgument":"humanConfirmed"},"forbiddenActions":["Do not recreate Cadre control-plane, native event/message state, index, worktree, provider, merge, or cleanup state with shell commands","Do not read or write Markdown projections as canonical state","Do not use Markdown payload fields, legacy Markdown import, or prompt-side state repair"],"responseSummary":["packet ok/error state","selected track or scope","warnings and blockers","changed canonical JSON/JSONL artifacts","generated human projections when relevant","next recommended packet"],"references":["mcp-contract"]}},"references":{"cadre-sync":{"version":1,"schema":"cadre.reference.v1","id":"cadre-sync","title":"Control-Plane Sync","markdownUse":"human_projection_only","rules":["Spec, plan, repository config, provider config, and topology conflicts are","Ephemeral worker state and native local state details are MCP-owned and regenerated or","Track-id collisions, shared-mode retries, and sync safety classification are"],"sections":[{"heading":"Predicate","body":"`cadre_project` with `action: \"topology\"` reports whether the project uses local\nor shared control-plane sync. Shared sync applies equally to monorepo and\npolyrepo projects. Product code publication is separate and happens only through\nship or land packets."},{"heading":"Preamble","body":"Before any workflow mutates Cadre state, call the workflow packet requested by\nthe protocol. The packet is responsible for shared-mode preflight, remote\nverification, native state sync, merge-driver health, conflict detection, and\nbounded retry policy.\n\nIf the packet reports a sync conflict, halt and summarize the conflicting files\nor state categories from the packet result. Do not hand-merge Cadre files\nstate, or generated state JSON."},{"heading":"Postamble","body":"After a workflow packet mutates Cadre state, use the next packet named by the\nresult for sync or publication. `cadre_project` with\n`action: \"sync_control_plane\"` owns shared control-plane publication and refuses\nto publish when product-code changes are mixed into the control-plane surface."},{"heading":"Conflict Policy","body":"- Spec, plan, repository config, provider config, and topology conflicts are\n surfaced to the user by packet results.\n- Ephemeral worker state and native local state details are MCP-owned and regenerated or\n repaired only through packets.\n- Track-id collisions, shared-mode retries, and sync safety classification are\n handled by packets. Agents report the packet result and stop when it blocks."}]},"mcp-contract":{"version":1,"schema":"cadre.reference.v1","id":"mcp-contract","title":"Cadre MCP Contract","markdownUse":"human_projection_only","rules":["`cadre_workflow` coordinates setup, newtrack, implement, status, validate,","`cadre_project` handles ping, doctor, root, topology, tech-stack summary,","`cadre_status` returns live, team, mine, available, collision, fleet, and","`cadre_track` returns bounded track context, parsed plans, integrity checks,","`cadre_parallel` plans task waves, sets up workers, records worker finish","`cadre_mutate` owns control-plane writes such as claim, heartbeat, status,","`cadre_complete_task` performs the journaled task-completion transaction.","`cadre_review` owns review assistance, machine gates, review gates,","`cadre_intel` owns repo maps, LSP setup/review/impact, workspace diagnostics,","`cadre_artifact` owns canonical artifact catalog/schema/import/validation,","`cadre_project action: integrations` and `cadre://integrations` report","`cadre_job` starts, lists, cancels, and reads async job artifacts.","`cadre://team-board?root=...`","`cadre://fleet-board?root=...`","`cadre://my-next-actions?root=...`","`cadre://review-queue?root=...`","`cadre://handoff-inbox?root=...`","`cadre://track-context?root=...&trackId=...`","`cadre://review-evidence?root=...&trackId=...`","`cadre://track-plan?root=...&trackId=...`","`cadre://track-spec?root=...&trackId=...`","`cadre://parallel-state?root=...&trackId=...`","`cadre://quality-gate?root=...&trackId=...`","`cadre://repo-map?root=...`","`cadre://integrations?root=...`","`cadre://workspace-health?root=...`","`cadre://workspace-diagnostics?root=...`","`cadre://test-impact?root=...&files=...`","`cadre://lsp-status?root=...`","`cadre://repo-topology?root=...`","`cadre://provider-actions?root=...&trackId=...&workflow=ship|land`","`cadre://ship-plan?root=...&trackId=...`","`cadre://land-plan?root=...&trackId=...`","`cadre://release-plan?root=...`","`cadre://job-result?root=...&jobId=...`","`cadre://artifact-catalog?root=...`","`cadre://artifact-schema?root=...&artifact=...`","`cadre://artifact-preview?root=...&artifact=...`","`cadre://artifact-sync-plan?root=...&scope=...`","`cadre://styleguide-selection?root=...&trackId=...`"],"sections":[{"heading":"Primary Packets","body":"- `cadre_workflow` coordinates setup, newtrack, implement, status, validate,\n review, ship, land, archive, release, handoff, refresh, flag, revert, revise,\n and formula flows.\n- `cadre_project` handles ping, doctor, root, topology, tech-stack summary,\n shared sync, and polyrepo preflight.\n- `cadre_status` returns live, team, mine, available, collision, fleet, and\n native state summary views.\n- `cadre_track` returns bounded track context, parsed plans, integrity checks,\n phase schedules, implementation prep, planning evidence, and worktree plans.\n- `cadre_parallel` plans task waves, sets up workers, records worker finish\n state, merges safe workers, and cleans merged workers.\n- `cadre_mutate` owns control-plane writes such as claim, heartbeat, status,\n metadata, review, worker state, task result, and index regeneration.\n- `cadre_complete_task` performs the journaled task-completion transaction.\n- `cadre_review` owns review assistance, machine gates, review gates,\n provider-evidence writes, and PR/MR/CI status normalization.\n- `cadre_intel` owns repo maps, LSP setup/review/impact, workspace diagnostics,\n test impact, dependency graphs, and daemon lifecycle.\n- `cadre_artifact` owns canonical artifact catalog/schema/import/validation,\n deterministic projection rendering, diffing, and sync review bundles.\n- `cadre_project action: integrations` and `cadre://integrations` report\n configured optional MCPs plus LSP coverage in one bounded view.\n- `cadre_job` starts, lists, cancels, and reads async job artifacts."},{"heading":"Response Modes","body":"Default compact responses include summaries, counts, warnings, next actions, and\nresource URIs. Use `responseMode: \"detail\"` for full plan bodies, full LSP\nevidence, long command outputs, or full style-guide content."},{"heading":"Compact Resources","body":"Use MCP resources for bounded dashboards:\n\n- `cadre://team-board?root=...`\n- `cadre://fleet-board?root=...`\n- `cadre://my-next-actions?root=...`\n- `cadre://review-queue?root=...`\n- `cadre://handoff-inbox?root=...`\n- `cadre://track-context?root=...&trackId=...`\n- `cadre://review-evidence?root=...&trackId=...`\n- `cadre://track-plan?root=...&trackId=...`\n- `cadre://track-spec?root=...&trackId=...`\n- `cadre://parallel-state?root=...&trackId=...`\n- `cadre://quality-gate?root=...&trackId=...`\n- `cadre://repo-map?root=...`\n- `cadre://integrations?root=...`\n- `cadre://workspace-health?root=...`\n- `cadre://workspace-diagnostics?root=...`\n- `cadre://test-impact?root=...&files=...`\n- `cadre://lsp-status?root=...`\n- `cadre://repo-topology?root=...`\n- `cadre://provider-actions?root=...&trackId=...&workflow=ship|land`\n- `cadre://ship-plan?root=...&trackId=...`\n- `cadre://land-plan?root=...&trackId=...`\n- `cadre://release-plan?root=...`\n- `cadre://job-result?root=...&jobId=...`\n- `cadre://artifact-catalog?root=...`\n- `cadre://artifact-schema?root=...&artifact=...`\n- `cadre://artifact-preview?root=...&artifact=...`\n- `cadre://artifact-sync-plan?root=...&scope=...`\n- `cadre://styleguide-selection?root=...&trackId=...`\n\nResource templates are discoverable through MCP, so clients should prefer\ntemplate discovery when available."}]},"ownership-guard":{"version":1,"schema":"cadre.reference.v1","id":"ownership-guard","title":"Ownership Guard","markdownUse":"human_projection_only","rules":[],"sections":[{"heading":"Packet Flow","body":"1. Resolve the project root with `cadre_project` using `action: \"root\"`.\n2. For track context, call `cadre_track` with `action: \"context\"` and the target\n `trackId`.\n3. To take or refresh ownership, call `cadre_mutate` with `action: \"claim\"` or\n use the workflow packet that performs the claim for the current operation.\n4. For long-running work, call `cadre_mutate` with `action: \"heartbeat\"` when the\n workflow packet asks for a heartbeat."},{"heading":"Foreign Holder","body":"If a packet reports that the track is held by another operator, present the\nholder, status, and packet-provided options to the user. Continue only by calling\nthe takeover packet with the packet-prescribed argument. If the user declines or\nthe packet returns `ok:false`, halt."},{"heading":"Handoff Exception","body":"If the packet reports a pending handoff addressed to the current operator, use\nthe pickup or claim packet path named by the result. Do not clear handoff labels\nor mirror ownership directly."},{"heading":"Staleness","body":"The canonical stale ownership window is thirty minutes. Packets compute and\nenforce this value. Agents should report stale reclaim evidence returned by the\npacket and then continue through packetized claim or heartbeat calls only."}]},"parallel-execution":{"version":1,"schema":"cadre.reference.v1","id":"parallel-execution","title":"Parallel Worker Dispatch","markdownUse":"human_projection_only","rules":["Work only on the product files assigned in the packet payload.","Run product tests, builds, linters, and commits according to the worker prompt.","Do not mutate Cadre control-plane files, native Cadre event/message state, provider state, worktree","Return structured evidence to the coordinator: worker id, task id, repo,","If product implementation fails, return the failure evidence. The coordinator","Use only `cadre_parallel`, `cadre_complete_task`, and other Cadre MCP packets","Treat `parallel_state.json` and native Cadre event/message state as packet-owned artifacts.","A worker conflict, failed test, missing commit, low coverage, or missing native task evidence","Product shell commands are allowed only for product implementation,"],"sections":[{"heading":"Packet Flow","body":"1. Call `cadre_workflow` with `workflow: \"implement\"` and the selected `trackId`\n to obtain implementation prep and the phase schedule.\n2. For a parallel phase, call `cadre_parallel` with `action: \"plan\"` or\n `action: \"next_wave\"` to obtain the ready worker set.\n3. Call `cadre_parallel` with `action: \"setup_workers\"` and the current client\n `agentIdentifier` (`\"claude\"` or `\"codex\"`) to get the packet-owned\n worktree/setup plan and selected dispatch adapter. Add `execute:true` only\n when the user or workflow has authorized mutation.\n4. Dispatch exactly the workers returned by the packet. Do not add, remove,\n reorder, split, or merge workers outside the packet result.\n5. As each worker finishes, call `cadre_parallel` with `action: \"record_finish\"`\n and the worker result evidence. Use `execute:true` when recording completion.\n6. After the wave finishes, call `cadre_parallel` with `action: \"merge_back\"` for\n the packet-owned merge plan. Add `execute:true` only when ready to mutate.\n7. Call `cadre_parallel` with `action: \"cleanup\"` for packet-owned cleanup. Add\n `execute:true` only after merge-back is clean or the packet explicitly marks a\n worker safe to clean.\n8. Repeat `next_wave` until the packet reports no ready workers.\n\nAll dependency gates, file collision checks, repo routing, event/message updates,\nparallel audit state, merge conflict state, task completion, and cleanup are\npacket-owned."},{"heading":"Dispatching Each Worker","body":"<!-- AGENT:claude -->\nPass `agentIdentifier:\"claude\"` to `cadre_parallel` when setting up workers.\nThen call the **`Task` tool** once per packet worker using the MCP-returned\n`selected_dispatch`, worker prompt, worktree, owned files, and expected result\nschema. Worker calls are awaitable; wait for every worker in the wave before\ncalling the next Cadre packet.\n<!-- /AGENT:claude -->\n<!-- AGENT:codex -->\nPass `agentIdentifier:\"codex\"` to `cadre_parallel` when setting up workers.\nThen use Codex multi-agent tools from the MCP-returned `selected_dispatch`.\nSearch tool discovery for `multi_agent_v1.spawn_agent`, spawn one worker agent\nper packet worker, pass the worker prompt and dispatch payload, and wait with\nthe corresponding multi-agent wait tool before calling the next Cadre packet.\nIf the selected dispatch mechanism is unavailable, halt with a clear\n`dispatch-unavailable` message instead of simulating worker state locally.\n<!-- /AGENT:codex -->"},{"heading":"Worker Rules","body":"- Work only on the product files assigned in the packet payload.\n- Run product tests, builds, linters, and commits according to the worker prompt.\n- Do not mutate Cadre control-plane files, native Cadre event/message state, provider state, worktree\n topology, merge state, or cleanup state directly.\n- Return structured evidence to the coordinator: worker id, task id, repo,\n commit evidence, tests run, coverage when available, files changed, summary,\n and blockers.\n- If product implementation fails, return the failure evidence. The coordinator\n records it through Cadre packets."},{"heading":"Coordinator Rules","body":"- Use only `cadre_parallel`, `cadre_complete_task`, and other Cadre MCP packets\n named by packet results for Cadre state changes.\n- Treat `parallel_state.json` and native Cadre event/message state as packet-owned artifacts.\n- A worker conflict, failed test, missing commit, low coverage, or missing native\n task evidence is handled by the packet result. Report the packet error and halt when\n it is blocking.\n- Product shell commands are allowed only for product implementation,\n verification, and commits inside worker scope."}],"platforms":{"codex":{"agentIdentifier":"codex","dispatch":"Pass agentIdentifier:\"codex\" to setup_workers. Use the returned selected_dispatch to discover multi_agent_v1.spawn_agent, spawn one worker per packet worker, wait for all workers, then call the next Cadre packet. If unavailable, halt with dispatch-unavailable."},"claude":{"agentIdentifier":"claude","dispatch":"Pass agentIdentifier:\"claude\" to setup_workers. Use the returned selected_dispatch to call the Task tool once per MCP-provided worker prompt. Pass dispatch payload, worktree, owned files, expected result schema, and wait for every worker before calling the next Cadre packet."}}},"polyrepo-git":{"version":1,"schema":"cadre.reference.v1","id":"polyrepo-git","title":"Polyrepo Routing And Worktrees","markdownUse":"human_projection_only","rules":["`cadre_track` with `action: \"context\"`","`cadre_track` with `action: \"worktree_plan\"`","`cadre_parallel` worker packets","`cadre_workflow` with `workflow: \"ship\"`, `workflow: \"land\"`, or"],"sections":[{"heading":"Topology","body":"Call `cadre_project` with `action: \"topology\"` or the workflow packet requested\nby the protocol. The packet reports whether the project is monorepo or polyrepo,\nthe control repo, enabled product repos, default repo, and any topology warnings.\n\nIf topology data is missing or invalid, halt on the packet error. Do not infer\nrepository layout by reading or rewriting Cadre state directly."},{"heading":"Task Repository Routing","body":"Plan tasks may carry repo annotations, and polyrepo metadata may carry per-repo\nbranch and worktree information. Agents consume this routing only through packet\nresults such as:\n\n- `cadre_track` with `action: \"context\"`\n- `cadre_track` with `action: \"worktree_plan\"`\n- `cadre_parallel` worker packets\n- `cadre_workflow` with `workflow: \"ship\"`, `workflow: \"land\"`, or\n `workflow: \"validate\"`\n\nTask completion, commit evidence, repo-specific SHA evidence, and progress\nrecording go through `cadre_complete_task` or the packet named by the current\nworkflow result."},{"heading":"Product Commands","body":"Workers may run product implementation, verification, and commit commands inside\nthe repo/worktree path provided by a packet. These commands are for target\nproject code only. They must not mutate Cadre control-plane files, native Cadre event/message state,\nworktree topology, merge state, or cleanup state."},{"heading":"Ship, Land, Revert, And Cleanup","body":"Use `cadre_workflow` packets for ship, land, revert, archive, and release\noperations. Use `cadre_parallel` packets for worker setup, merge-back, and\ncleanup. If a packet returns a hard gate for missing submodules, branch state,\nprovider evidence, review state, or validation, halt and report it."}]},"provider-evidence":{"version":1,"schema":"cadre.reference.v1","id":"provider-evidence","title":"Provider Evidence","markdownUse":"human_projection_only","rules":["Local review may return `phase_state: \"pending_provider\"` when hosted evidence","Ship and land packets fail closed when hosted evidence is required for the","Provider action packets return the exact evidence key and minimum fields the","`cadre_review` with `action: \"provider_evidence\"`","`cadre_workflow` with `workflow: \"ship\"` or `workflow: \"land\"` and","`cadre_mutate` with `action: \"record_review\"` when recording the final review","Cadre native Cadre packets for notes or labels when the workflow packet asks for them"],"sections":[{"heading":"Review Versus Publication","body":"- Local review may return `phase_state: \"pending_provider\"` when hosted evidence\n is unavailable. Treat this as pending evidence, not as a local review failure.\n- Ship and land packets fail closed when hosted evidence is required for the\n selected provider mode and has not been written back.\n- Provider action packets return the exact evidence key and minimum fields the\n provider MCP result must satisfy."},{"heading":"Write-Back Targets","body":"Use these packet paths to persist provider evidence:\n\n- `cadre_review` with `action: \"provider_evidence\"`\n- `cadre_workflow` with `workflow: \"ship\"` or `workflow: \"land\"` and\n `providerEvidence`\n- `cadre_mutate` with `action: \"record_review\"` when recording the final review\n verdict\n- Cadre native Cadre packets for notes or labels when the workflow packet asks for them\n\nNever treat a hosted label, provider issue state, or PR/MR review as Cadre state\nuntil a Cadre packet records the corresponding decision."}]},"team-ops":{"version":1,"schema":"cadre.reference.v1","id":"team-ops","title":"Team Operations","markdownUse":"human_projection_only","rules":["`in_progress` after worker setup","`awaiting_merge` after tested worker completion with commit evidence","`merged` after safe merge-back","`failed` or `conflict` when the worker cannot be merged safely","GitHub or GitLab provider MCP for PR/MR metadata, review approvals, CI status,","Sourcegraph or internal code-search MCP for cross-repo symbol search when","Issue tracker MCP such as Jira or Linear when roadmap evidence lives outside","CI-specific MCP for Buildkite, CircleCI, Argo, Jenkins, or other systems that","Sentry, Datadog, Honeycomb, or logging MCP for incident and runtime evidence.","Knowledge-base MCP for product/domain documents used as read-only evidence."],"sections":[{"heading":"Sync Mode","body":"Use `local` mode for solo work or private experiments. Use `shared` mode when\nmultiple people need to see ownership, leases, review queues, blockers, and\navailable work. Shared sync is packet-owned; agents should rely on Cadre packet\nresults for pre/post sync status and recovery instructions.\n\nGenerated setup can configure `.gitattributes` for parallel worker state so shared control-plane merges stay low-conflict."},{"heading":"Parallelism","body":"Parallel work is task-level and dependency-aware. `cadre_parallel` returns only\ntasks whose phase, dependencies, worker state, and file claims are ready. A\nsequential phase dispatches one unfinished task at a time. A parallel phase may\ndispatch multiple independent tasks when file claims do not conflict.\n\nWorker status transitions:\n\n- `in_progress` after worker setup\n- `awaiting_merge` after tested worker completion with commit evidence\n- `merged` after safe merge-back\n- `failed` or `conflict` when the worker cannot be merged safely\n\nCleanup removes merged workers by default; force is required for unfinished,\nfailed, or conflicted workers."},{"heading":"MCP And LSP Use","body":"Use `cadre_intel` before prompt-side repo scans when possible. It can return\nrepo maps, dependency graphs, workspace diagnostics, test impact, LSP setup,\nLSP impact, and warm review evidence. Polyrepo projects return repo-qualified\nresults so clients can distinguish control-plane files from product-repo files.\nUse `cadre://integrations` when you need one bounded view of provider, code\nsearch, issue, CI, logging, knowledge-base, and LSP coverage.\n\nRecommended optional MCP additions for larger teams:\n\n- GitHub or GitLab provider MCP for PR/MR metadata, review approvals, CI status,\n and hosted provider evidence.\n- Sourcegraph or internal code-search MCP for cross-repo symbol search when\n product repos are not fully local.\n- Issue tracker MCP such as Jira or Linear when roadmap evidence lives outside\n Cadre.\n- CI-specific MCP for Buildkite, CircleCI, Argo, Jenkins, or other systems that\n are not covered by GitHub/GitLab checks.\n- Sentry, Datadog, Honeycomb, or logging MCP for incident and runtime evidence.\n- Knowledge-base MCP for product/domain documents used as read-only evidence."}]},"template-locator":{"version":1,"schema":"cadre.reference.v1","id":"template-locator","title":"Cadre Template Assets","markdownUse":"human_projection_only","rules":["`cadre_workflow` with reviewable dry-runs reports review artifacts and a","`cadre_workflow` with `workflow: \"setup_scaffold\"` and `execute:true` writes","`cadre_workflow` with `workflow: \"newtrack\"` writes per-track files, including","`cadre_intel` owns LSP setup, warm review, cold review, and daemon status","`cadre_mutate` owns derived index refreshes and other Cadre state mutations."],"sections":[{"heading":"Packet Ownership","body":"- `cadre_workflow` with reviewable dry-runs reports review artifacts and a\n token-safe `review_bundle` with full proposed files on disk. Setup, new-track,\n revise, refresh document updates, release artifacts, and handoff artifacts use\n this pattern.\n- `cadre_workflow` with `workflow: \"setup_scaffold\"` and `execute:true` writes\n the setup scaffold from bundled templates and confirmed setup payload.\n- `cadre_workflow` with `workflow: \"newtrack\"` writes per-track files, including\n template-backed track learnings.\n- `cadre_intel` owns LSP setup, warm review, cold review, and daemon status\n checks.\n- `cadre_mutate` owns derived index refreshes and other Cadre state mutations."},{"heading":"Style Guides","body":"Setup always selects the general style guide when available, adds guides derived\nfrom structured `techStack` JSON, and unions any explicit `styleGuideIds` passed\nto the packet.\nThe setup packet returns `styleGuides.detected`, `styleGuides.selected`,\n`styleGuides.written`, `styleGuides.skipped`, and `styleGuides.missing`.\n\nIf `styleGuides.missing` is non-empty, surface the packet warning and keep the\nvalid selected guides. Do not remove user-supplied `styleGuideIds` just to make a\ndry-run warning disappear. If the packet returns `ok:false`, halt and surface the\npacket error. Do not replace the packet with manual copying."},{"heading":"Workflow Review Bundles","body":"Reviewable workflow dry-runs return `review_artifacts` as metadata only and\n`review_bundle` with a manifest path, absolute review file paths, and optional\nshell commands for local rendering. Use those files for human review instead of\npasting complete generated files into chat/model context by default."},{"heading":"Agent Use","body":"Use template references only to understand what the packet-created files mean.\nAll setup, new-track, LSP, style-guide, and index writes are packet-owned."}]}},"templates":{"ci/cadre-merge-train.github.yml":"# Cadre cross-repo merge train (GitHub Actions).\n#\n# Scaffolded into the CONTROL repo at .github/workflows/cadre-merge-train.yml\n# by /cadre-setup when provider_mode == \"github\" and merge_train.enabled.\n#\n# What it does: when every PR in a track group (label `cadre-track:<id>`,\n# spread across the control repo + product submodule repos) is APPROVED and\n# CI-GREEN, it merges them in a fixed order — PRODUCT repos first, then bumps\n# each submodule gitlink to the freshly-merged SHA on the control track branch,\n# then merges the CONTROL PR LAST. The control PR is the single \"seal\" commit;\n# there is no true cross-repo atomic merge, so on any failure it HALTS, leaves\n# already-merged product PRs in place, comments the failure, and re-fires once\n# the failing repo is green again.\n#\n# PREREQUISITE — cross-repo token: the default GITHUB_TOKEN cannot act on other\n# repos. Provide a PAT or GitHub App installation token (scopes: repo, workflow,\n# read:org) with write access to EVERY product repo, stored as the\n# `CADRE_TRAIN_TOKEN` secret in this control repo.\n#\n# Also configure branch protection on every product repo's default branch and on\n# the control branch: require approvals + the relevant status checks. The train\n# only automates the merge click; protection is what enforces review/CI.\n\nname: cadre-merge-train\n\n# TRIGGER MODEL: pull_request_review / check_suite fire only for events in THIS\n# (control) repo — i.e. when the CONTROL PR is reviewed or its checks complete, the\n# job derives the track from that PR's group label and tries to land. A review/green\n# on a PRODUCT repo does NOT fire this workflow. To auto-fire on product-repo\n# approvals, either (a) have each product repo send a `repository_dispatch` to this\n# repo on approval (carrying the track id), or (b) dispatch manually with the track\n# id, or (c) add a `schedule:` and extend the job to scan open control-repo PRs for\n# group labels (the job is idempotent + re-runnable). Re-running `/cadre-land`\n# also re-checks status from your machine.\non:\n pull_request_review:\n types: [submitted]\n check_suite:\n types: [completed]\n # schedule:\n # - cron: \"*/5 * * * *\" # uncomment for auto-fire on product-repo approvals\n workflow_dispatch:\n inputs:\n track:\n description: \"Track id to attempt to land (e.g. auth_20260609)\"\n required: true\n\n# Per-track concurrency: serialize landings WITHIN a track, but let different\n# tracks land in parallel — otherwise one stalled/conflicted track blocks every\n# other (see /cadre-land §7). The track id is known here only for workflow_dispatch;\n# for review/check events we key on the triggering control PR (one control PR per\n# track, so per-PR == per-track), falling back to run_id so we never collapse\n# unrelated events onto one global lane.\nconcurrency:\n group: cadre-merge-train-${{ github.event.inputs.track || github.event.pull_request.number || github.event.check_suite.pull_requests[0].number || github.run_id }}\n cancel-in-progress: false\n\njobs:\n land:\n runs-on: ubuntu-latest\n steps:\n - name: Checkout control repo\n uses: actions/checkout@v4\n with:\n token: ${{ secrets.CADRE_TRAIN_TOKEN }}\n submodules: false\n fetch-depth: 0\n\n - name: Run merge train\n env:\n GH_TOKEN: ${{ secrets.CADRE_TRAIN_TOKEN }}\n EVENT_TRACK: ${{ github.event.inputs.track }}\n run: |\n set -euo pipefail\n\n # --- Resolve the track id and the group label -------------------------\n PREFIX=\"$(jq -r '.merge_train.group_label_prefix // \"cadre-track\"' cadre/config.json)\"\n AUTO_FIRE=\"$(jq -r '.merge_train.auto_fire // true' cadre/config.json)\"\n CONTROL_REPO=\"${GITHUB_REPOSITORY}\"\n\n # Derive the candidate track from the triggering PR's labels, or from\n # the manual dispatch input.\n TRACK=\"${EVENT_TRACK:-}\"\n if [ -z \"$TRACK\" ]; then\n PR_NUMBER=\"$(jq -r '.pull_request.number // .check_suite.pull_requests[0].number // empty' \"$GITHUB_EVENT_PATH\")\"\n if [ -n \"$PR_NUMBER\" ]; then\n TRACK=\"$(gh pr view \"$PR_NUMBER\" --repo \"$CONTROL_REPO\" --json labels \\\n --jq \".labels[].name | select(startswith(\\\"${PREFIX}:\\\")) | sub(\\\"${PREFIX}:\\\"; \\\"\\\")\" || true)\"\n fi\n fi\n if [ -z \"$TRACK\" ]; then echo \"No track group on this event; nothing to do.\"; exit 0; fi\n LABEL=\"${PREFIX}:${TRACK}\"\n echo \"Track=$TRACK Label=$LABEL auto_fire=$AUTO_FIRE\"\n if [ \"$AUTO_FIRE\" != \"true\" ] && [ -z \"$EVENT_TRACK\" ]; then\n echo \"auto_fire disabled; only workflow_dispatch may land. Exiting.\"; exit 0\n fi\n\n # --- Helper: is a PR approved AND all required checks green? -----------\n pr_ready() { # repo pr_number\n local repo=\"$1\" num=\"$2\"\n local decision state\n decision=\"$(gh pr view \"$num\" --repo \"$repo\" --json reviewDecision --jq '.reviewDecision')\"\n state=\"$(gh pr view \"$num\" --repo \"$repo\" --json statusCheckRollup \\\n --jq '[.statusCheckRollup[]?.conclusion // .statusCheckRollup[]?.state] | map(select(. != null and . != \"SUCCESS\" and . != \"NEUTRAL\" and . != \"SKIPPED\")) | length')\"\n [ \"$decision\" = \"APPROVED\" ] && [ \"$state\" = \"0\" ]\n }\n\n # --- Gather the group from metadata.json ------------------------------\n META=\"cadre/tracks/${TRACK}/metadata.json\"\n if [ ! -f \"$META\" ]; then echo \"No metadata for $TRACK; abort.\"; exit 1; fi\n\n # Ordered repo list: metadata.merge_order entries first (in their given\n # order), then the alphabetical remainder. Never drop a repo, never\n # duplicate one — a name listed in merge_order but absent from .repos is\n # ignored; a repo absent from merge_order falls into the alpha tail.\n # De-dupe $head preserving first-seen order — a user typo such as\n # \"repo-order: api > api > web\" would otherwise process api twice.\n mapfile -t REPO_NAMES < <(jq -r '\n (.merge_order // []) as $order\n | (.repos | keys) as $all\n | ($order\n | map(select(. as $n | $all | index($n)))\n | reduce .[] as $n ([]; if (index($n)) then . else . + [$n] end)) as $head\n | ($all | map(select(. as $n | $head | index($n) | not)) | sort) as $tail\n | ($head + $tail)[]\n ' \"$META\")\n CONTROL_PR=\"$(jq -r '.control_pr_url // empty' \"$META\" | sed -E 's#.*/([0-9]+)/?$#\\1#')\"\n\n # --- Phase 1: verify EVERY sibling PR is approved + green -------------\n # Also classify each product PR as landed (already MERGED) vs blocking\n # (not ready), so a HALF-LANDED train can surface what is still holding\n # it up on the control PR instead of failing silently.\n echo \"::group::Pre-flight verification\"\n LANDED=\"\"; BLOCKING=\"\"; HALT=0\n for name in \"${REPO_NAMES[@]}\"; do\n repo=\"$(jq -r --arg n \"$name\" '.repos[$n].repo_slug // empty' \"$META\")\"\n pr=\"$(jq -r --arg n \"$name\" '.repos[$n].pr_url // empty' \"$META\" | sed -E 's#.*/([0-9]+)/?$#\\1#')\"\n [ -z \"$pr\" ] && continue\n echo \"check $repo#$pr\"\n state=\"$(gh pr view \"$pr\" --repo \"$repo\" --json state --jq '.state')\"\n if [ \"$state\" = \"MERGED\" ]; then\n LANDED=\"${LANDED:+$LANDED, }${name} (${repo}#${pr})\"\n continue\n fi\n if ! pr_ready \"$repo\" \"$pr\"; then\n BLOCKING=\"${BLOCKING:+$BLOCKING, }${name} (${repo}#${pr})\"\n HALT=1\n fi\n done\n # If the train is half-landed (>=1 product PR merged) and something is\n # still blocking, post/refresh a status comment on the control PR.\n if [ \"$HALT\" = \"1\" ]; then\n if [ -n \"$LANDED\" ] && [ -n \"$CONTROL_PR\" ]; then\n MARKER=\"<!-- cadre-merge-train:status -->\"\n BODY=\"${MARKER}\n 🚧 **cadre merge-train — half landed.**\n Already merged: ${LANDED:-(none)}\n Still blocking: ${BLOCKING:-(none)}\n\n The merged product PRs cannot be reverted automatically; the train will\n re-fire and complete once the blocking repos are approved + green.\"\n # Refresh the existing status comment if present, else create one.\n existing=\"$(gh pr view \"$CONTROL_PR\" --repo \"$CONTROL_REPO\" --json comments \\\n --jq \"[.comments[] | select(.body | startswith(\\\"${MARKER}\\\"))][0].id // empty\" || true)\"\n if [ -n \"$existing\" ]; then\n gh api -X PATCH \"repos/${CONTROL_REPO}/issues/comments/${existing}\" -f body=\"$BODY\" >/dev/null || true\n else\n gh pr comment \"$CONTROL_PR\" --repo \"$CONTROL_REPO\" --body \"$BODY\" || true\n fi\n fi\n echo \"Product PR(s) not ready (blocking: ${BLOCKING:-?}); halting.\"\n echo \"::endgroup::\"\n exit 0\n fi\n if [ -n \"$CONTROL_PR\" ]; then\n pr_ready \"$CONTROL_REPO\" \"$CONTROL_PR\" || { echo \"Control PR not ready; halting.\"; exit 0; }\n fi\n echo \"::endgroup::\"\n\n # --- Phase 2: merge each PRODUCT PR, capture new default-branch SHA ---\n git config user.name \"cadre-merge-train\"\n git config user.email \"cadre-merge-train@users.noreply.github.com\"\n BRANCH=\"track/${TRACK}\"\n git fetch origin \"$BRANCH\" && git checkout \"$BRANCH\"\n\n for name in \"${REPO_NAMES[@]}\"; do\n repo=\"$(jq -r --arg n \"$name\" '.repos[$n].repo_slug // empty' \"$META\")\"\n pr=\"$(jq -r --arg n \"$name\" '.repos[$n].pr_url // empty' \"$META\" | sed -E 's#.*/([0-9]+)/?$#\\1#')\"\n sub=\"$(jq -r --arg n \"$name\" '.repos[$n].submodule_path // empty' \"$META\")\"\n [ -z \"$pr\" ] && continue\n echo \"::group::Merge product $repo#$pr\"\n # Idempotent re-fire: if this PR is ALREADY merged (e.g. an earlier\n # train run merged it but then halted on a sibling), do NOT re-merge —\n # but STILL reconstruct its gitlink bump below so a re-fire converges.\n pr_state=\"$(gh pr view \"$pr\" --repo \"$repo\" --json state --jq '.state')\"\n if [ \"$pr_state\" = \"MERGED\" ]; then\n echo \" $repo#$pr already MERGED; skipping merge, reconstructing gitlink bump.\"\n else\n pr_ready \"$repo\" \"$pr\" || { echo \"REGRESSED before merge: $repo#$pr. Halting.\"; exit 1; }\n # Merge with a MERGE COMMIT (squash disabled by guardrail) so the\n # gitlink can pin to a single deterministic merge SHA.\n gh pr merge \"$pr\" --repo \"$repo\" --merge --delete-branch=false\n fi\n # Pin the gitlink to the MERGE COMMIT (not the branch head): the base\n # branch may have advanced past our merge by the time we read it, so\n # pinning the head would silently capture unrelated commits.\n base=\"$(gh pr view \"$pr\" --repo \"$repo\" --json baseRefName --jq '.baseRefName')\"\n new_sha=\"$(gh pr view \"$pr\" --repo \"$repo\" --json mergeCommit --jq '.mergeCommit.oid')\"\n if [ -z \"$new_sha\" ] || [ \"$new_sha\" = \"null\" ]; then\n # Merge commit (squash disabled by guardrail) not yet readable; do\n # NOT bump to a wrong/empty SHA — halt and let the train re-fire.\n echo \" ${name}: merge commit not yet available; halting to re-fire.\"\n echo \"::endgroup::\"\n exit 1\n fi\n echo \" ${name} -> ${new_sha} (merge commit)\"\n # Bump the submodule gitlink on the control track branch.\n # Fetch the base branch ref (fetch-by-bare-SHA is rejected by many hosts),\n # which now contains the just-merged commit, then pin the gitlink to it.\n git -C \"$sub\" fetch origin \"$base\" || git submodule update --init \"$sub\"\n git -C \"$sub\" checkout \"$new_sha\"\n git add \"$sub\"\n echo \"::endgroup::\"\n done\n\n # --- Phase 3: commit submodule bumps, push control track branch ------\n if ! git diff --cached --quiet; then\n git commit -m \"cadre(train): bump submodules to merged SHAs for ${TRACK}\"\n git push origin \"$BRANCH\"\n fi\n\n # --- Phase 4: re-await control PR check on bumped commit, merge LAST -\n if [ -n \"$CONTROL_PR\" ]; then\n echo \"Waiting for control PR #$CONTROL_PR checks on bumped commit...\"\n for _ in $(seq 1 30); do\n if pr_ready \"$CONTROL_REPO\" \"$CONTROL_PR\"; then\n # Merge commit (squash disabled by guardrail) for the control seal PR too.\n gh pr merge \"$CONTROL_PR\" --repo \"$CONTROL_REPO\" --merge --delete-branch\n echo \"Merge train complete for ${TRACK}.\"\n exit 0\n fi\n sleep 20\n done\n gh pr comment \"$CONTROL_PR\" --repo \"$CONTROL_REPO\" \\\n --body \"⚠️ cadre merge-train: product PRs merged and submodules bumped, but the control PR's checks did not go green in time. Re-run when CI passes.\"\n echo \"Control PR not green after bump; product PRs already merged. Halting (re-fires later).\"\n exit 1\n fi\n","ci/cadre-merge-train.gitlab.yml":"# Cadre cross-repo merge train (GitLab CI).\n#\n# Scaffolded into the CONTROL repo by /cadre-setup when provider_mode == \"gitlab\"\n# and merge_train.enabled. Either commit this as `.gitlab-ci.yml` or `include:` it\n# from an existing pipeline.\n#\n# What it does: when every Merge Request in a track group (label\n# `cadre-track:<id>`, across the control project + product submodule projects)\n# is APPROVED and pipeline-GREEN, it merges them in a fixed order — PRODUCT\n# projects first, then bumps each submodule gitlink to the merged SHA on the\n# control track branch, then merges the CONTROL MR LAST. No true cross-project\n# atomic merge exists, so on any failure it HALTS, leaves already-merged product\n# MRs in place, comments the failure, and re-fires when the failing project is\n# green again.\n#\n# PREREQUISITES:\n# - CADRE_TRAIN_TOKEN: a GROUP access token (or PAT) with `api` + `write_repository`\n# scope and Developer+ on EVERY product project, set as a masked CI/CD variable.\n# - `glab` available in the runner image, or use the REST API via curl (token in\n# CADRE_TRAIN_TOKEN). The job below uses `glab`.\n# - Branch protection / approval rules on each product project's default branch\n# and the control branch. GitLab's own \"Merge when pipeline succeeds\" and\n# merge trains are complementary; this job is the cross-project coordinator.\n\nstages:\n - merge-train\n\ncadre-merge-train:\n stage: merge-train\n image: registry.gitlab.com/gitlab-org/cli:latest\n # Serialize trains PER TRACK so two pipelines never merge/bump submodules\n # concurrently for the same track, while different tracks still land in parallel\n # (a single global lane would let one stalled track block every other — see\n # /cadre-land §7). CADRE_TRACK is the required track id for this run.\n resource_group: cadre-merge-train-$CADRE_TRACK\n rules:\n # GitLab has no cross-project \"sibling MR approved\" webhook, so this job is\n # driven by: a recurring **pipeline schedule** (set CADRE_TRACK on the\n # schedule, or leave it unset to scan — see note below), a **manual run**\n # (CI → Run pipeline → web), or an external **trigger** (e.g. a webhook from a\n # product project on approval). This is the \"re-fires when green\" mechanism on\n # GitLab — a schedule every few minutes is the simplest setup.\n - if: '$CI_PIPELINE_SOURCE == \"schedule\"'\n - if: '$CI_PIPELINE_SOURCE == \"web\"'\n - if: '$CI_PIPELINE_SOURCE == \"trigger\"'\n variables:\n GITLAB_TOKEN: $CADRE_TRAIN_TOKEN\n script:\n - apk add --no-cache jq git bash >/dev/null 2>&1 || true\n - |\n set -euo pipefail\n export GITLAB_HOST=\"${CI_SERVER_HOST}\"\n PREFIX=\"$(jq -r '.merge_train.group_label_prefix // \"cadre-track\"' cadre/config.json)\"\n AUTO_FIRE=\"$(jq -r '.merge_train.auto_fire // true' cadre/config.json)\"\n TRACK=\"${CADRE_TRACK:-}\"\n if [ -z \"$TRACK\" ]; then echo \"Set CADRE_TRACK (CI/CD var or trigger) to the track id.\"; exit 0; fi\n # Honor auto_fire: on a scheduled run, only proceed when auto_fire is on.\n # Manual (web) / trigger runs always proceed (explicit human/system intent).\n if [ \"$AUTO_FIRE\" != \"true\" ] && [ \"$CI_PIPELINE_SOURCE\" = \"schedule\" ]; then\n echo \"auto_fire disabled; scheduled runs are skipped. Trigger manually to land.\"; exit 0\n fi\n LABEL=\"${PREFIX}:${TRACK}\"\n META=\"cadre/tracks/${TRACK}/metadata.json\"\n if [ ! -f \"$META\" ]; then echo \"No metadata for $TRACK; abort.\"; exit 1; fi\n echo \"Track=$TRACK Label=$LABEL auto_fire=$AUTO_FIRE\"\n\n # mr_ready PROJECT IID -> approved AND pipeline success\n mr_ready() {\n local proj=\"$1\" iid=\"$2\" approved pipe\n approved=\"$(glab api \"projects/$(printf '%s' \"$proj\" | sed 's#/#%2F#g')/merge_requests/${iid}/approvals\" --jq '.approved // false')\"\n pipe=\"$(glab api \"projects/$(printf '%s' \"$proj\" | sed 's#/#%2F#g')/merge_requests/${iid}\" --jq '.pipeline.status // .head_pipeline.status // \"unknown\"')\"\n [ \"$approved\" = \"true\" ] && [ \"$pipe\" = \"success\" ]\n }\n\n # Ordered repo list: metadata.merge_order entries first (in their given\n # order), then the alphabetical remainder. Never drop or duplicate a repo;\n # a name in merge_order but absent from .repos is ignored, a repo absent\n # from merge_order falls into the alpha tail.\n # De-dupe $head preserving first-seen order — a user typo such as\n # \"repo-order: api > api > web\" would otherwise process api twice.\n mapfile -t REPO_NAMES < <(jq -r '\n (.merge_order // []) as $order\n | (.repos | keys) as $all\n | ($order\n | map(select(. as $n | $all | index($n)))\n | reduce .[] as $n ([]; if (index($n)) then . else . + [$n] end)) as $head\n | ($all | map(select(. as $n | $head | index($n) | not)) | sort) as $tail\n | ($head + $tail)[]\n ' \"$META\")\n CONTROL_PROJ=\"${CI_PROJECT_PATH}\"\n CONTROL_MR=\"$(jq -r '.control_pr_url // empty' \"$META\" | sed -E 's#.*/([0-9]+)/?$#\\1#')\"\n\n # Phase 1: verify every sibling MR approved + green. Also classify each\n # product MR as landed (already merged) vs blocking (not ready), so a\n # HALF-LANDED train can surface what is still holding it up on the control\n # MR instead of failing silently.\n LANDED=\"\"; BLOCKING=\"\"; HALT=0\n for name in \"${REPO_NAMES[@]}\"; do\n proj=\"$(jq -r --arg n \"$name\" '.repos[$n].repo_slug // empty' \"$META\")\"\n iid=\"$(jq -r --arg n \"$name\" '.repos[$n].pr_url // empty' \"$META\" | sed -E 's#.*/([0-9]+)/?$#\\1#')\"\n [ -z \"$iid\" ] && continue\n enc=\"$(printf '%s' \"$proj\" | sed 's#/#%2F#g')\"\n state=\"$(glab api \"projects/${enc}/merge_requests/${iid}\" --jq '.state')\"\n if [ \"$state\" = \"merged\" ]; then\n LANDED=\"${LANDED:+$LANDED, }${name} (${proj}!${iid})\"\n continue\n fi\n if ! mr_ready \"$proj\" \"$iid\"; then\n BLOCKING=\"${BLOCKING:+$BLOCKING, }${name} (${proj}!${iid})\"\n HALT=1\n fi\n done\n # If the train is half-landed (>=1 product MR merged) and something is still\n # blocking, post/refresh a status note on the control MR.\n if [ \"$HALT\" = \"1\" ]; then\n if [ -n \"$LANDED\" ] && [ -n \"$CONTROL_MR\" ]; then\n cenc=\"$(printf '%s' \"$CONTROL_PROJ\" | sed 's#/#%2F#g')\"\n MARKER=\"<!-- cadre-merge-train:status -->\"\n BODY=\"${MARKER}\n 🚧 **cadre merge-train — half landed.**\n Already merged: ${LANDED:-(none)}\n Still blocking: ${BLOCKING:-(none)}\n\n The merged product MRs cannot be reverted automatically; the train will\n re-fire and complete once the blocking projects are approved + green.\"\n # Refresh the existing status note if present, else create one.\n existing=\"$(glab api \"projects/${cenc}/merge_requests/${CONTROL_MR}/notes\" --jq \"[.[] | select(.body | startswith(\\\"${MARKER}\\\"))][0].id // empty\" 2>/dev/null || true)\"\n if [ -n \"$existing\" ]; then\n glab api --method PUT \"projects/${cenc}/merge_requests/${CONTROL_MR}/notes/${existing}\" -f body=\"$BODY\" >/dev/null || true\n else\n glab mr note \"$CONTROL_MR\" -m \"$BODY\" || true\n fi\n fi\n echo \"Product MR(s) not ready (blocking: ${BLOCKING:-?}); halting.\"; exit 0\n fi\n if [ -n \"$CONTROL_MR\" ]; then mr_ready \"$CONTROL_PROJ\" \"$CONTROL_MR\" || { echo \"Control MR not ready; halting.\"; exit 0; }; fi\n\n git config user.name \"cadre-merge-train\"\n git config user.email \"cadre-merge-train@users.noreply.gitlab.com\"\n BRANCH=\"track/${TRACK}\"\n git fetch origin \"$BRANCH\" && git checkout \"$BRANCH\"\n\n # Phase 2: merge product MRs, bump submodules\n for name in \"${REPO_NAMES[@]}\"; do\n proj=\"$(jq -r --arg n \"$name\" '.repos[$n].repo_slug // empty' \"$META\")\"\n iid=\"$(jq -r --arg n \"$name\" '.repos[$n].pr_url // empty' \"$META\" | sed -E 's#.*/([0-9]+)/?$#\\1#')\"\n sub=\"$(jq -r --arg n \"$name\" '.repos[$n].submodule_path // empty' \"$META\")\"\n [ -z \"$iid\" ] && continue\n enc=\"$(printf '%s' \"$proj\" | sed 's#/#%2F#g')\"\n target=\"$(glab api \"projects/${enc}/merge_requests/${iid}\" --jq '.target_branch')\"\n # Idempotent re-fire: if this MR is ALREADY merged (e.g. an earlier train\n # run merged it but then halted on a sibling), do NOT re-merge — but STILL\n # reconstruct its gitlink bump below so a re-fire converges.\n mr_state=\"$(glab api \"projects/${enc}/merge_requests/${iid}\" --jq '.state')\"\n if [ \"$mr_state\" = \"merged\" ]; then\n echo \" $proj!$iid already merged; skipping merge, reconstructing gitlink bump.\"\n new_sha=\"$(glab api \"projects/${enc}/merge_requests/${iid}\" --jq '.merge_commit_sha // .sha // empty')\"\n else\n mr_ready \"$proj\" \"$iid\" || { echo \"REGRESSED: $proj!$iid. Halting.\"; exit 1; }\n # Merge with a MERGE COMMIT (squash disabled by guardrail — do NOT set\n # squash=true) so the gitlink can pin to a single deterministic merge\n # SHA. Read it from the merge PUT response (.merge_commit_sha, falling\n # back to .sha) — not the branch head, which may have advanced past our\n # merge and would silently capture unrelated commits.\n merge_resp=\"$(glab api --method PUT \"projects/${enc}/merge_requests/${iid}/merge\")\"\n new_sha=\"$(printf '%s' \"$merge_resp\" | jq -r '.merge_commit_sha // .sha // empty')\"\n fi\n if [ -z \"$new_sha\" ] || [ \"$new_sha\" = \"null\" ]; then\n # Merge commit (squash disabled by guardrail) not yet readable; do NOT\n # bump to a wrong/empty SHA — halt and let the train re-fire.\n echo \" ${name}: merge commit not yet available; halting to re-fire.\"; exit 1\n fi\n echo \" ${name} -> ${new_sha} (merge commit)\"\n # Fetch the target branch ref (fetch-by-bare-SHA is rejected by many hosts),\n # which now contains the just-merged commit, then pin the gitlink to it.\n git -C \"$sub\" fetch origin \"$target\" || git submodule update --init \"$sub\"\n git -C \"$sub\" checkout \"$new_sha\"\n git add \"$sub\"\n done\n\n # Phase 3: commit + push submodule bumps\n if ! git diff --cached --quiet; then\n git commit -m \"cadre(train): bump submodules to merged SHAs for ${TRACK}\"\n git push \"https://oauth2:${CADRE_TRAIN_TOKEN}@${CI_SERVER_HOST}/${CI_PROJECT_PATH}.git\" \"HEAD:${BRANCH}\"\n fi\n\n # Phase 4: merge control MR LAST\n if [ -n \"$CONTROL_MR\" ]; then\n enc=\"$(printf '%s' \"$CONTROL_PROJ\" | sed 's#/#%2F#g')\"\n for _ in $(seq 1 30); do\n if mr_ready \"$CONTROL_PROJ\" \"$CONTROL_MR\"; then\n # Merge commit (squash disabled by guardrail — do NOT set squash=true)\n # for the control seal MR too.\n glab api --method PUT \"projects/${enc}/merge_requests/${CONTROL_MR}/merge\" >/dev/null\n echo \"Merge train complete for ${TRACK}.\"; exit 0\n fi\n sleep 20\n done\n glab mr note \"$CONTROL_MR\" -m \"⚠️ cadre merge-train: product MRs merged and submodules bumped, but the control MR pipeline did not go green in time. Re-run when CI passes.\" || true\n echo \"Control MR not green after bump; product MRs already merged. Halting (re-fires later).\"; exit 1\n fi\n","ci/cadre-monorepo-check.github.yml":"# Cadre target-project drift gate (GitHub Actions).\n#\n# Scaffolded by cadre-setup into .github/workflows/cadre-monorepo-check.yml.\n# This template is for Cadre-initialized product repositories, not the Cadre\n# harness package. It intentionally avoids harness-package drift gates,\n# generated plugin checks, and generator maintenance commands.\n\nname: cadre-monorepo-check\n\non:\n pull_request:\n\nconcurrency:\n group: cadre-monorepo-check-${{ github.ref }}\n cancel-in-progress: true\n\njobs:\n cadre-project-check:\n runs-on: ubuntu-latest\n steps:\n - name: Checkout repo\n uses: actions/checkout@v4\n\n - name: tracks.json index is fresh\n run: |\n set -euo pipefail\n if [ ! -f cadre/tracks.json ]; then\n echo \"No cadre/tracks.json — skipping freshness gate.\"\n exit 0\n fi\n entries=\"$(mktemp)\"\n expected=\"$(mktemp)\"\n actual=\"$(mktemp)\"\n : > \"$entries\"\n if [ -d cadre/tracks ]; then\n find cadre/tracks -mindepth 2 -maxdepth 2 -name metadata.json -print | sort | while read -r md; do\n dir=\"${md%metadata.json}\"\n jq \\\n --arg metadata_path \"$md\" \\\n --arg spec_path \"${dir}spec.json\" \\\n --arg plan_path \"${dir}plan.json\" \\\n '{track_id, name:(.name // .description // .track_id), status:(.status // \"new\"), priority:(.priority // \"medium\"), owner:(.owner // null), reviewer:(.reviewer // null), tags:(.tags // []), review:(.review // null), metadata_path:$metadata_path, spec_path:$spec_path, plan_path:$plan_path}' \\\n \"$md\" >> \"$entries\"\n done\n fi\n jq -S 'del(.generated_at)' cadre/tracks.json > \"$actual\"\n jq -S '{\n version: 1,\n schema: \"cadre.tracks_index.v1\",\n counts: (reduce .[] as $t ({new:0,in_progress:0,completed:0,blocked:0,skipped:0}; .[$t.status] = ((.[$t.status] // 0) + 1))),\n tracks: (sort_by(.track_id))\n }' \"$entries\" > \"$expected\"\n if ! diff -u \"$expected\" \"$actual\"; then\n echo \"::error::cadre/tracks.json is stale. Run cadre_mutate action regen_index through Cadre MCP and commit the result.\"\n exit 1\n fi\n echo \"cadre/tracks.json matches track metadata.\"\n\n - name: Shared sync merge contract present\n run: |\n set -euo pipefail\n mode=\"$(jq -r '.sync_mode // \"local\"' cadre/config.json 2>/dev/null || echo local)\"\n if [ \"$mode\" != \"shared\" ]; then\n echo \"sync_mode is '$mode' — skipping .gitattributes guard.\"\n exit 0\n fi\n missing=0\n for line in \\\n 'cadre/tracks/**/parallel_state.json merge=ours'; do\n pat=\"$(printf '%s' \"$line\" | sed 's/ */[[:space:]][[:space:]]*/g')\"\n if ! grep -Eq \"$pat\" .gitattributes 2>/dev/null; then\n echo \"::error::Missing required shared-mode .gitattributes line: $line\"\n missing=1\n fi\n done\n [ \"$missing\" -eq 0 ] || exit 1\n echo \".gitattributes contains the required shared-mode merge rules.\"\n\n - name: Configured project gate\n run: |\n set -euo pipefail\n if [ ! -f cadre/config.json ]; then\n echo \"No cadre/config.json — skipping project gate.\"\n exit 0\n fi\n gate=\"$(jq -r '.ci_check_command // .check_command // .review_machine_gate_command // .machine_gate_command // .test_command // empty' cadre/config.json)\"\n if [ -z \"$gate\" ]; then\n echo \"No Cadre project gate command configured.\"\n exit 0\n fi\n echo \"Running Cadre project gate: $gate\"\n bash -lc \"$gate\"\n\n - name: Review verdict cleared for track PR\n env:\n PR_HEAD_SHA: ${{ github.event.pull_request.head.sha }}\n HEAD_REF: ${{ github.event.pull_request.head.ref }}\n run: |\n set -euo pipefail\n if [ ! -d cadre ]; then\n echo \"No cadre/ directory — review gate not initialized.\"\n exit 0\n fi\n case \"$HEAD_REF\" in\n track/*) track_id=\"${HEAD_REF#track/}\" ;;\n *)\n echo \"Head branch '$HEAD_REF' is not a track branch — review gate not applicable.\"\n exit 0 ;;\n esac\n META=\"cadre/tracks/$track_id/metadata.json\"\n if [ ! -f \"$META\" ]; then\n echo \"::error::Track branch '$HEAD_REF' has no $META — cannot verify review.\"\n exit 1\n fi\n verdict=\"$(jq -r '.review.verdict // \"absent\"' \"$META\")\"\n blocking=\"$(jq -r '.review.blocking_count // 0' \"$META\")\"\n self_reviewed=\"$(jq -r '.review.self_reviewed // false' \"$META\")\"\n reviewed_sha=\"$(jq -r '.review.reviewed_sha // \"\"' \"$META\")\"\n require_second=\"$(jq -r '.require_second_reviewer // false' cadre/config.json 2>/dev/null || echo false)\"\n if [ \"$verdict\" = \"absent\" ]; then\n echo \"::error::Track '$track_id' has no recorded review verdict. Run cadre-review before merging.\"\n exit 1\n fi\n if [ \"$verdict\" != \"approved\" ] || [ \"$blocking\" -gt 0 ]; then\n echo \"::error::Track '$track_id' has not cleared review (verdict: $verdict, blocking findings: $blocking).\"\n exit 1\n fi\n if [ \"$require_second\" = \"true\" ] && [ \"$self_reviewed\" = \"true\" ]; then\n echo \"::error::Track '$track_id' has only a self-review but require_second_reviewer is set.\"\n exit 1\n fi\n if [ -z \"$reviewed_sha\" ]; then\n echo \"::error::Track '$track_id' is missing review.reviewed_sha. Re-run cadre-review.\"\n exit 1\n fi\n if [ \"$reviewed_sha\" != \"$PR_HEAD_SHA\" ]; then\n echo \"::warning::PR head $PR_HEAD_SHA differs from review.reviewed_sha $reviewed_sha. This can be expected after ship/land rebases; Cadre enforces the hard pre-rebase guard during publication.\"\n fi\n echo \"Track '$track_id' review cleared.\"\n","ci/cadre-monorepo-check.gitlab.yml":"# Cadre target-project drift gate (GitLab CI).\n#\n# Scaffolded by cadre-setup into .gitlab-ci.yml. This template is for\n# Cadre-initialized product repositories, not the Cadre harness package. It\n# intentionally avoids harness-package drift gates, generated plugin checks,\n# and generator maintenance commands.\n\nstages:\n - check\n\ncadre-monorepo-check:\n stage: check\n image: alpine:latest\n rules:\n - if: '$CI_PIPELINE_SOURCE == \"merge_request_event\"'\n script:\n - apk add --no-cache bash jq git >/dev/null 2>&1 || true\n - |\n set -eu\n if [ ! -f cadre/tracks.json ]; then\n echo \"No cadre/tracks.json — skipping freshness gate.\"\n else\n entries=\"$(mktemp)\"\n expected=\"$(mktemp)\"\n actual=\"$(mktemp)\"\n : > \"$entries\"\n if [ -d cadre/tracks ]; then\n find cadre/tracks -mindepth 2 -maxdepth 2 -name metadata.json -print | sort | while read -r md; do\n dir=\"${md%metadata.json}\"\n jq \\\n --arg metadata_path \"$md\" \\\n --arg spec_path \"${dir}spec.json\" \\\n --arg plan_path \"${dir}plan.json\" \\\n '{track_id, name:(.name // .description // .track_id), status:(.status // \"new\"), priority:(.priority // \"medium\"), owner:(.owner // null), reviewer:(.reviewer // null), tags:(.tags // []), review:(.review // null), metadata_path:$metadata_path, spec_path:$spec_path, plan_path:$plan_path}' \\\n \"$md\" >> \"$entries\"\n done\n fi\n jq -S 'del(.generated_at)' cadre/tracks.json > \"$actual\"\n jq -S '{\n version: 1,\n schema: \"cadre.tracks_index.v1\",\n counts: (reduce .[] as $t ({new:0,in_progress:0,completed:0,blocked:0,skipped:0}; .[$t.status] = ((.[$t.status] // 0) + 1))),\n tracks: (sort_by(.track_id))\n }' \"$entries\" > \"$expected\"\n if ! diff -u \"$expected\" \"$actual\"; then\n echo \"ERROR: cadre/tracks.json is stale. Run cadre_mutate action regen_index through Cadre MCP and commit the result.\"\n exit 1\n fi\n echo \"cadre/tracks.json matches track metadata.\"\n fi\n - |\n set -eu\n mode=\"$(jq -r '.sync_mode // \"local\"' cadre/config.json 2>/dev/null || echo local)\"\n if [ \"$mode\" != \"shared\" ]; then\n echo \"sync_mode is '$mode' — skipping .gitattributes guard.\"\n else\n missing=0\n for line in \\\n 'cadre/tracks/**/parallel_state.json merge=ours'; do\n pat=\"$(printf '%s' \"$line\" | sed 's/ */[[:space:]][[:space:]]*/g')\"\n if ! grep -Eq \"$pat\" .gitattributes 2>/dev/null; then\n echo \"ERROR: Missing required shared-mode .gitattributes line: $line\"\n missing=1\n fi\n done\n [ \"$missing\" -eq 0 ] || exit 1\n echo \".gitattributes contains the required shared-mode merge rules.\"\n fi\n - |\n set -eu\n if [ ! -f cadre/config.json ]; then\n echo \"No cadre/config.json — skipping project gate.\"\n else\n gate=\"$(jq -r '.ci_check_command // .check_command // .review_machine_gate_command // .machine_gate_command // .test_command // empty' cadre/config.json)\"\n if [ -z \"$gate\" ]; then\n echo \"No Cadre project gate command configured.\"\n else\n echo \"Running Cadre project gate: $gate\"\n bash -lc \"$gate\"\n fi\n fi\n - |\n set -eu\n if [ ! -d cadre ]; then\n echo \"No cadre/ directory — review gate not initialized.\"\n exit 0\n fi\n HEAD_REF=\"${CI_MERGE_REQUEST_SOURCE_BRANCH_NAME:-}\"\n MR_HEAD_SHA=\"${CI_MERGE_REQUEST_SOURCE_BRANCH_SHA:-}\"\n case \"$HEAD_REF\" in\n track/*) track_id=\"${HEAD_REF#track/}\" ;;\n *)\n echo \"Source branch '$HEAD_REF' is not a track branch — review gate not applicable.\"\n exit 0 ;;\n esac\n META=\"cadre/tracks/$track_id/metadata.json\"\n if [ ! -f \"$META\" ]; then\n echo \"ERROR: Track branch '$HEAD_REF' has no $META — cannot verify review.\"\n exit 1\n fi\n verdict=\"$(jq -r '.review.verdict // \"absent\"' \"$META\")\"\n blocking=\"$(jq -r '.review.blocking_count // 0' \"$META\")\"\n self_reviewed=\"$(jq -r '.review.self_reviewed // false' \"$META\")\"\n reviewed_sha=\"$(jq -r '.review.reviewed_sha // \"\"' \"$META\")\"\n require_second=\"$(jq -r '.require_second_reviewer // false' cadre/config.json 2>/dev/null || echo false)\"\n if [ \"$verdict\" = \"absent\" ]; then\n echo \"ERROR: Track '$track_id' has no recorded review verdict. Run cadre-review before merging.\"\n exit 1\n fi\n if [ \"$verdict\" != \"approved\" ] || [ \"$blocking\" -gt 0 ]; then\n echo \"ERROR: Track '$track_id' has not cleared review (verdict: $verdict, blocking findings: $blocking).\"\n exit 1\n fi\n if [ \"$require_second\" = \"true\" ] && [ \"$self_reviewed\" = \"true\" ]; then\n echo \"ERROR: Track '$track_id' has only a self-review but require_second_reviewer is set.\"\n exit 1\n fi\n if [ -z \"$reviewed_sha\" ]; then\n echo \"ERROR: Track '$track_id' is missing review.reviewed_sha. Re-run cadre-review.\"\n exit 1\n fi\n if [ -n \"$MR_HEAD_SHA\" ] && [ \"$reviewed_sha\" != \"$MR_HEAD_SHA\" ]; then\n echo \"WARNING: MR head $MR_HEAD_SHA differs from review.reviewed_sha $reviewed_sha. This can be expected after ship/land rebases; Cadre enforces the hard pre-rebase guard during publication.\"\n fi\n echo \"Track '$track_id' review cleared.\"\n","config.json":"{\n \"sync_mode\": \"local\",\n \"auto_open\": false,\n \"require_second_reviewer\": false,\n \"allow_unreviewed_ship\": false,\n \"allow_unpinned_review_ship\": false,\n \"provider_mode\": \"local\",\n \"provider_mcp_required\": false,\n \"remote_host\": \"\",\n \"control_remote\": \"origin\",\n \"control_branch\": \"main\",\n \"pull_on_command_start\": true,\n \"coverage_command\": \"\",\n \"traceability\": {\n \"auto_product_commits\": true,\n \"auto_control_commits\": true,\n \"auto_automation_commits\": true,\n \"commit_local_wisps\": false,\n \"git_notes\": true,\n \"notes_ref\": \"refs/notes/cadre\",\n \"push_notes\": true\n },\n \"merge_train\": {\n \"enabled\": true,\n \"auto_fire\": true,\n \"group_label_prefix\": \"cadre-track\"\n }\n}\n","learnings_seed.json":"{\n \"version\": 1,\n \"schema\": \"cadre.learnings_seed.v1\",\n \"id\": \"initial\",\n \"kind\": \"learnings_seed\",\n \"text\": \"# Track Learnings: {{track_id}}\\n\\nPatterns, gotchas, and context discovered during implementation.\\n\\n## Codebase Patterns (Inherited)\\n\\n<!-- Patterns summarized from canonical cadre/patterns.jsonl events or archived track learnings -->\\n\\n---\\n\\n<!-- Learnings from implementation will be appended below -->\\n<!-- Format for each entry:\\n\\n## [YYYY-MM-DD HH:MM] - Phase N Task M: <task_name>\\nkey: <track_id>:p<i>:t<j>:<sha7>\\nSession/thread ref if available\\n- **Implemented:** <brief description of what was done>\\n- **Files changed:** <list of files modified/created>\\n- **Commit:** <sha_7chars>\\n- **Learnings:**\\n - Patterns: <reusable patterns discovered>\\n - Gotchas: <things to watch out for>\\n - Context: <useful context for future>\\n---\\n\\n-->\\n\"\n}\n","manifest.json":"{\n \"templates\": [\n {\n \"id\": \"product\",\n \"source\": \"product.json\",\n \"target\": \"cadre/product.json\",\n \"projection\": \"cadre/product.md\",\n \"purpose\": \"Product summary, users, workflows, domain model, invariants, architecture boundaries, data ownership, and release expectations.\",\n \"scope\": \"target-project\"\n },\n {\n \"id\": \"workflow\",\n \"source\": \"workflow.json\",\n \"target\": \"cadre/workflow.json\",\n \"projection\": \"cadre/workflow.md\",\n \"purpose\": \"Project development, verification, review, and commit expectations.\",\n \"scope\": \"target-project\"\n },\n {\n \"id\": \"product-guidelines\",\n \"source\": \"product_guidelines.json\",\n \"target\": \"cadre/product_guidelines.json\",\n \"projection\": \"cadre/product_guidelines.md\",\n \"purpose\": \"Product principles, user promises, non-goals, and decision rules reviewed during setup.\",\n \"scope\": \"target-project\"\n },\n {\n \"id\": \"patterns\",\n \"source\": \"patterns_seed.json\",\n \"target\": \"cadre/patterns.jsonl\",\n \"projection\": \"cadre/patterns.md\",\n \"purpose\": \"Reusable codebase patterns and completed-track learnings.\",\n \"scope\": \"target-project\"\n },\n {\n \"id\": \"learnings\",\n \"source\": \"learnings_seed.json\",\n \"target\": \"cadre/tracks/<track_id>/learnings.jsonl\",\n \"projection\": \"cadre/tracks/<track_id>/learnings.md\",\n \"purpose\": \"Per-track learning journal starter.\",\n \"scope\": \"target-project\"\n },\n {\n \"id\": \"config\",\n \"source\": \"config.json\",\n \"target\": \"cadre/config.json\",\n \"purpose\": \"Cadre sync, provider, review, and quality defaults.\",\n \"scope\": \"target-project\"\n },\n {\n \"id\": \"repos\",\n \"source\": \"repos.json\",\n \"target\": \"cadre/repos.json\",\n \"purpose\": \"Polyrepo topology starter.\",\n \"scope\": \"target-project\"\n },\n {\n \"id\": \"style-guides\",\n \"source\": \"styleguides/*.json\",\n \"target\": \"cadre/styleguides/*.json\",\n \"projection\": \"cadre/code_styleguides/*.md\",\n \"purpose\": \"Language-specific implementation guidance selected by setup packets.\",\n \"scope\": \"target-project\"\n },\n {\n \"id\": \"target-monorepo-ci\",\n \"source\": \"ci/cadre-monorepo-check.github.yml\",\n \"target\": \".github/workflows/cadre-monorepo-check.yml\",\n \"purpose\": \"Cadre target-project drift and review gate for GitHub monorepos.\",\n \"scope\": \"target-project\"\n },\n {\n \"id\": \"target-monorepo-ci-gitlab\",\n \"source\": \"ci/cadre-monorepo-check.gitlab.yml\",\n \"target\": \".gitlab-ci.yml\",\n \"purpose\": \"Cadre target-project drift and review gate for GitLab monorepos.\",\n \"scope\": \"target-project\"\n },\n {\n \"id\": \"polyrepo-merge-train-github\",\n \"source\": \"ci/cadre-merge-train.github.yml\",\n \"target\": \".github/workflows/cadre-merge-train.yml\",\n \"purpose\": \"Cross-repo merge train for GitHub polyrepo control repositories.\",\n \"scope\": \"target-project\"\n },\n {\n \"id\": \"polyrepo-merge-train-gitlab\",\n \"source\": \"ci/cadre-merge-train.gitlab.yml\",\n \"target\": \".gitlab-ci.yml\",\n \"purpose\": \"Cross-repo merge train for GitLab polyrepo control repositories.\",\n \"scope\": \"target-project\"\n }\n ]\n}\n","patterns_seed.json":"{\n \"version\": 1,\n \"schema\": \"cadre.patterns_seed.v1\",\n \"id\": \"initial\",\n \"kind\": \"patterns_seed\",\n \"text\": \"# Codebase Patterns\\n\\nReusable patterns discovered during development. **Read this before starting new work.**\\n\\nThis file is the project's institutional knowledge - learnings extracted from completed tracks that help future development.\\n\\n---\\n\\n## Code Conventions\\n\\n<!-- Patterns related to code style, naming, imports -->\\n\\n## Architecture\\n\\n<!-- Patterns related to architecture decisions, module structure -->\\n\\n## Gotchas\\n\\n<!-- Common mistakes to avoid, things that are easy to forget -->\\n\\n## Testing\\n\\n<!-- Patterns for testing approaches -->\\n\\n## Context\\n\\n<!-- Useful context about where things are located -->\\n\\n---\\n\\nLast refreshed: YYYY-MM-DD\\n\"\n}\n","product.json":"{\n \"version\": 1,\n \"schema\": \"cadre.product.v1\",\n \"kind\": \"product\",\n \"title\": \"Product Context\",\n \"summary\": \"Use this file to keep product intent detailed enough for agents to make\\nimplementation decisions without re-discovering the business model every time.\",\n \"sections\": [\n {\n \"heading\": \"Product Summary\",\n \"body\": \"- What the product is:\\n- Who it serves:\\n- Primary value proposition:\\n- Deployment or operating model:\"\n },\n {\n \"heading\": \"Users And Personas\",\n \"body\": \"- Primary users:\\n- Secondary users:\\n- Operators, administrators, or integrators:\\n- Permissions, tenancy, or access boundaries that shape user workflows:\"\n },\n {\n \"heading\": \"Core Workflows\",\n \"body\": \"- Workflow 1:\\n- Workflow 2:\\n- Workflow 3:\\n- Setup, onboarding, or provisioning flow:\\n- Review, audit, support, or recovery flow:\"\n },\n {\n \"heading\": \"Domain Model\",\n \"body\": \"- Core entities:\\n- Important relationships:\\n- State machines or lifecycle stages:\\n- Identifiers, keys, scopes, or hierarchy rules:\"\n },\n {\n \"heading\": \"Product Invariants\",\n \"body\": \"- Behaviors that must remain stable:\\n- Security, privacy, or compliance guarantees:\\n- Determinism, compatibility, or migration guarantees:\\n- Performance or availability expectations:\"\n },\n {\n \"heading\": \"Architecture Boundaries\",\n \"body\": \"- Public trust boundaries:\\n- Service or module ownership:\\n- API, SDK, CLI, or UI responsibilities:\\n- Generated artifacts or contracts that must stay in sync:\"\n },\n {\n \"heading\": \"Data And Integrations\",\n \"body\": \"- Primary data stores and ownership:\\n- External services or provider dependencies:\\n- Event, analytics, audit, or observability expectations:\\n- Data retention, privacy, or redaction rules:\"\n },\n {\n \"heading\": \"Quality And Release Expectations\",\n \"body\": \"- Test surfaces that protect product behavior:\\n- Documentation, API contract, or SDK fixture expectations:\\n- Rollout, migration, compatibility, or rollback requirements:\"\n },\n {\n \"heading\": \"Open Questions\",\n \"body\": \"- Product assumptions that still need confirmation:\\n- Known risks or decisions to revisit:\"\n }\n ]\n}\n","product_guidelines.json":"{\n \"version\": 1,\n \"schema\": \"cadre.product_guidelines.v1\",\n \"kind\": \"product_guidelines\",\n \"title\": \"Product Guidelines\",\n \"summary\": \"Use this file to capture product rules that should shape implementation choices,\\nreview decisions, and acceptance criteria.\",\n \"sections\": [\n {\n \"heading\": \"Product Principles\",\n \"body\": \"- Put the primary user workflow first.\\n- Prefer changes that reduce ambiguity in the user's next action.\\n- Keep product behavior explainable from the UI, docs, or API contract.\\n- Preserve explicit product invariants unless a spec intentionally revises them.\"\n },\n {\n \"heading\": \"User Promises\",\n \"body\": \"- Record promises the product must keep for users, teams, operators, or\\n integrators.\\n- Note the situations where reliability, privacy, accessibility, or performance\\n matter more than feature breadth.\"\n },\n {\n \"heading\": \"Trust And Safety Boundaries\",\n \"body\": \"- Record authentication, authorization, tenancy, privacy, and audit guarantees.\\n- Identify public trust boundaries and internal-only surfaces.\\n- State which data must be redacted, encrypted, scoped, or excluded from logs.\"\n },\n {\n \"heading\": \"Domain And Workflow Rules\",\n \"body\": \"- List lifecycle, state-machine, ordering, idempotency, and concurrency rules.\\n- Capture deterministic evaluation, attribution, or compatibility requirements.\\n- Note workflows that require preview, rollback, migration, or audit support.\"\n },\n {\n \"heading\": \"Data Ownership\",\n \"body\": \"- Map major product data to its owning store, service, module, or external\\n provider.\\n- Record generated artifacts, contracts, fixtures, migrations, or SDK assets that\\n must be updated alongside behavior changes.\"\n },\n {\n \"heading\": \"Non-Goals\",\n \"body\": \"- List behaviors, audiences, platforms, or workflows this project intentionally\\n does not serve yet.\\n- Record tempting shortcuts or alternate architectures that should not be used\\n without revising product context first.\"\n },\n {\n \"heading\": \"Decision Rules\",\n \"body\": \"- When product tradeoffs appear, write the rule the team should use to choose.\\n- Link decisions back to product context, usage evidence, support requests, or\\n explicit user feedback.\\n- Prefer tests and review evidence around product invariants, trust boundaries,\\n tenancy, authorization, data ownership, and public contracts.\"\n },\n {\n \"heading\": \"Review Checklist\",\n \"body\": \"- Does the change preserve the product invariants in `cadre/product.json`?\\n- Are user-visible behavior, docs, API contracts, SDK fixtures, generated\\n artifacts, and migrations updated together when needed?\\n- Are privacy, audit, observability, and rollback implications covered?\\n- Are non-goals and compatibility boundaries still respected?\"\n }\n ]\n}\n","repos.json":"{\n \"mode\": \"polyrepo\",\n \"control_repo\": { \"name\": \"REPLACE_control_repo_name\", \"path\": \".\" },\n \"default_repo\": \"REPLACE_default_repo_name\",\n \"repos\": [\n {\n \"name\": \"REPLACE_repo_name\",\n \"submodule_path\": \"repos/REPLACE_repo_name\",\n \"url\": \"git@host:org/REPLACE_repo_name.git\",\n \"default_branch\": \"main\",\n \"enabled\": true\n }\n ]\n}\n","styleguides/android.json":"{\n \"version\": 1,\n \"schema\": \"cadre.styleguide.v1\",\n \"kind\": \"styleguide\",\n \"id\": \"android\",\n \"title\": \"Android (Kotlin) Style Guide Summary\",\n \"summary\": \"This document summarizes key rules and best practices from the Android Kotlin Style Guide and Architecture Guidelines for building idiomatic, maintainable Android applications.\",\n \"sections\": [\n {\n \"heading\": \"1. Formatting and Tooling\",\n \"body\": \"- **ktlint:** Enforce via Gradle plugin. All code must pass `./gradlew ktlintCheck` before review.\\n- **detekt:** Use for static analysis beyond formatting. Fail CI on new issues.\\n- **Android Lint:** Run `./gradlew lint` and resolve all errors and relevant warnings before release builds.\\n- Follow all base [Kotlin Coding Conventions](kotlin.md) for formatting, naming, and language features.\"\n },\n {\n \"heading\": \"2. Architecture (MVVM + Clean)\",\n \"body\": \"- **MVVM:** Use ViewModel + LiveData/StateFlow + View/Fragment as the standard architecture. ViewModels must not hold references to `Context`, `View`, or `Fragment`.\\n- **Single-activity:** Prefer a single-activity app with multiple Fragments or Jetpack Compose destinations over multiple Activities.\\n- **Repository pattern:** Abstract data sources behind a `Repository` interface. ViewModels call repositories; repositories call data sources (API, Room, DataStore).\\n- **Use cases / Interactors:** Extract business logic into `UseCase` classes (one responsibility each) for complex or reused logic. Keep ViewModels thin.\\n- **Unidirectional data flow (UDF):** State flows down (ViewModel → View); events flow up (View → ViewModel). Use `StateFlow`/`SharedFlow` or sealed `UiState` classes.\"\n },\n {\n \"heading\": \"3. ViewModels\",\n \"body\": \"- **`viewModelScope`:** Always use `viewModelScope` to launch coroutines from a ViewModel. Coroutines are cancelled automatically when the ViewModel is cleared.\\n- **Expose `StateFlow`/`LiveData`, not `MutableStateFlow`/`MutableLiveData`:** Use backing properties: `private val _state = MutableStateFlow(...)` exposed as `val state: StateFlow<...> = _state.asStateFlow()`.\\n- **`UiState` sealed class:** Model screen state with a sealed class: `sealed class UiState { object Loading; data class Success(val data: T); data class Error(val message: String) }`.\\n- **No Android framework imports:** ViewModels must not import `android.*` classes (except `Application` in `AndroidViewModel`). This ensures testability.\\n- **`SavedStateHandle`:** Use `SavedStateHandle` in ViewModels to survive process death, not `onSaveInstanceState` in Fragments.\"\n },\n {\n \"heading\": \"4. Fragments and Activities\",\n \"body\": \"- **Fragment arguments via `newInstance`:** Always pass arguments via `Bundle` in a static `newInstance()` factory method. Never set properties directly on a Fragment after construction.\\n- **View binding:** Use View Binding (`viewBinding = true`) over `findViewById`. Never use synthetic imports (Kotlin Android Extensions is deprecated).\\n- **Lifecycle awareness:** Collect `Flow` in `lifecycleScope.launch { repeatOnLifecycle(STARTED) { ... } }`. Do not collect in `onCreate` without `repeatOnLifecycle`.\\n- **`onViewCreated`:** Set up views and observers in `onViewCreated`, not `onCreateView`. Release view references in `onDestroyView` (especially with View Binding: set binding to `null`).\\n- **Avoid back-stack manipulation:** Let the NavController manage the back stack. Do not call `fragmentManager.popBackStack()` manually.\"\n },\n {\n \"heading\": \"5. Jetpack Navigation\",\n \"body\": \"- **Single NavGraph per activity:** Define all destinations and actions in `nav_graph.xml`. Use nested graphs for feature modules.\\n- **Safe Args:** Use the Safe Args Gradle plugin for type-safe navigation arguments. Do not use raw `Bundle` keys for navigation data.\\n- **Deep links:** Declare deep link URIs in the NavGraph, not in `AndroidManifest.xml` `intent-filter` manually.\"\n },\n {\n \"heading\": \"6. Room (Database)\",\n \"body\": \"- **`@Entity`:** Every table is a `data class` annotated with `@Entity`. Name tables explicitly with `tableName`.\\n- **`@Dao` interfaces:** Use `suspend` functions in DAOs for insert/update/delete. Return `Flow<T>` for queries to observe changes reactively.\\n- **No business logic in DAOs:** DAOs perform only data access. Transformations and filtering go in the repository or use case.\\n- **Database migrations:** Always write an explicit `Migration` for schema changes. Never use `fallbackToDestructiveMigration()` in production.\\n- **`@TypeConverter`:** Register converters for non-primitive types (e.g., `Date`, enums, custom objects).\"\n },\n {\n \"heading\": \"7. Networking (Retrofit + OkHttp)\",\n \"body\": \"- **Suspend functions in API interfaces:** Use `suspend fun` in Retrofit service interfaces — no `Call<T>`, no RxJava.\\n- **Sealed result types:** Wrap API responses in a `Result<T>` or `NetworkResult<T>` sealed class in the repository. Never expose raw Retrofit exceptions to ViewModels.\\n- **OkHttp interceptors:** Use interceptors for auth headers, logging (`HttpLoggingInterceptor`), and retry logic. Do not add auth logic inside API service interfaces.\\n- **Timeouts:** Always configure connect, read, and write timeouts on `OkHttpClient`. Never use the default (unlimited) timeouts.\"\n },\n {\n \"heading\": \"8. Dependency Injection (Hilt)\",\n \"body\": \"- **Hilt over manual DI:** Use Hilt (built on Dagger) as the standard DI framework. Avoid `ServiceLocator` patterns.\\n- **`@HiltViewModel`:** Annotate all ViewModels. Inject via `by viewModels()` in Fragments/Activities.\\n- **`@Singleton` scope:** Scope repositories and network clients to `@Singleton`. Scope ViewModels to `@HiltViewModel` (automatic).\\n- **Modules for external dependencies:** Create `@Module` + `@InstallIn` classes to provide third-party types (Retrofit, Room, etc.) that cannot be annotated directly.\"\n },\n {\n \"heading\": \"9. Permissions\",\n \"body\": \"- **Request at the latest possible moment:** Ask for permissions immediately before the feature that needs them, not at app launch.\\n- **`ActivityResultContracts`:** Use `registerForActivityResult(RequestPermission())` — not `onRequestPermissionsResult`.\\n- **Handle denial gracefully:** Always handle both granted and denied cases. Show rationale with `shouldShowRequestPermissionRationale` before re-requesting.\"\n },\n {\n \"heading\": \"10. Testing\",\n \"body\": \"- **ViewModel tests:** Test ViewModels with JUnit 4/5 and `kotlinx-coroutines-test`. Use `TestCoroutineDispatcher`/`UnconfinedTestDispatcher` and `Turbine` for `Flow` assertions.\\n- **Robolectric for unit tests:** Use Robolectric for tests needing Android framework context without an emulator.\\n- **Espresso / Compose UI tests:** Write UI tests for critical user journeys. Use `IdlingResource` for async operations in Espresso.\\n- **Fake over mock:** Prefer fake implementations of repositories/data sources over Mockito mocks for ViewModel tests. Fakes are more maintainable and realistic.\"\n },\n {\n \"heading\": \"11. Resources\",\n \"body\": \"- **Naming conventions:**\\n - Layouts: `fragment_user_profile.xml`, `item_order_card.xml`, `view_loading_spinner.xml`\\n - IDs: `@+id/tvUserName` (type prefix) or `@+id/userNameText` (descriptive) — pick one and be consistent.\\n - Strings: `user_profile_title`, `error_network_unavailable` — use `feature_description` format.\\n - Drawables: `ic_` for icons, `bg_` for backgrounds, `img_` for images.\\n- **`strings.xml`:** All user-visible strings go in `strings.xml`. No hardcoded strings in layouts or code.\\n- **Dimensions:** Define reusable spacing in `dimens.xml`. Use `8dp` grid system.\\n\\n*Sources: [Android Kotlin Style Guide](https://developer.android.com/kotlin/style-guide) · [Guide to app architecture](https://developer.android.com/topic/architecture) · [Hilt docs](https://developer.android.com/training/dependency-injection/hilt-android)*\"\n }\n ],\n \"languages\": [\n \"android\"\n ],\n \"frameworks\": [],\n \"file_patterns\": [],\n \"applies_to\": [\n \"planning\",\n \"implementation\",\n \"review\",\n \"tests\"\n ],\n \"rules\": [\n {\n \"id\": \"android-rule-1\",\n \"severity\": \"guidance\",\n \"summary\": \"**ktlint:** Enforce via Gradle plugin. All code must pass `./gradlew ktlintCheck` before review.\"\n },\n {\n \"id\": \"android-rule-2\",\n \"severity\": \"guidance\",\n \"summary\": \"**detekt:** Use for static analysis beyond formatting. Fail CI on new issues.\"\n },\n {\n \"id\": \"android-rule-3\",\n \"severity\": \"guidance\",\n \"summary\": \"**Android Lint:** Run `./gradlew lint` and resolve all errors and relevant warnings before release builds.\"\n },\n {\n \"id\": \"android-rule-4\",\n \"severity\": \"guidance\",\n \"summary\": \"Follow all base [Kotlin Coding Conventions](kotlin.md) for formatting, naming, and language features.\"\n },\n {\n \"id\": \"android-rule-5\",\n \"severity\": \"guidance\",\n \"summary\": \"**MVVM:** Use ViewModel + LiveData/StateFlow + View/Fragment as the standard architecture. ViewModels must not hold references to `Context`, `View`, or `Fragment`.\"\n },\n {\n \"id\": \"android-rule-6\",\n \"severity\": \"guidance\",\n \"summary\": \"**Single-activity:** Prefer a single-activity app with multiple Fragments or Jetpack Compose destinations over multiple Activities.\"\n },\n {\n \"id\": \"android-rule-7\",\n \"severity\": \"guidance\",\n \"summary\": \"**Repository pattern:** Abstract data sources behind a `Repository` interface. ViewModels call repositories; repositories call data sources (API, Room, DataStore).\"\n },\n {\n \"id\": \"android-rule-8\",\n \"severity\": \"guidance\",\n \"summary\": \"**Use cases / Interactors:** Extract business logic into `UseCase` classes (one responsibility each) for complex or reused logic. Keep ViewModels thin.\"\n },\n {\n \"id\": \"android-rule-9\",\n \"severity\": \"guidance\",\n \"summary\": \"**Unidirectional data flow (UDF):** State flows down (ViewModel → View); events flow up (View → ViewModel). Use `StateFlow`/`SharedFlow` or sealed `UiState` classes.\"\n },\n {\n \"id\": \"android-rule-10\",\n \"severity\": \"guidance\",\n \"summary\": \"**`viewModelScope`:** Always use `viewModelScope` to launch coroutines from a ViewModel. Coroutines are cancelled automatically when the ViewModel is cleared.\"\n },\n {\n \"id\": \"android-rule-11\",\n \"severity\": \"guidance\",\n \"summary\": \"**Expose `StateFlow`/`LiveData`, not `MutableStateFlow`/`MutableLiveData`:** Use backing properties: `private val _state = MutableStateFlow(...)` exposed as `val state: StateFlow<...> = _state.asStateFlow()`.\"\n },\n {\n \"id\": \"android-rule-12\",\n \"severity\": \"guidance\",\n \"summary\": \"**`UiState` sealed class:** Model screen state with a sealed class: `sealed class UiState { object Loading; data class Success(val data: T); data class Error(val message: String) }`.\"\n },\n {\n \"id\": \"android-rule-13\",\n \"severity\": \"guidance\",\n \"summary\": \"**No Android framework imports:** ViewModels must not import `android.*` classes (except `Application` in `AndroidViewModel`). This ensures testability.\"\n },\n {\n \"id\": \"android-rule-14\",\n \"severity\": \"guidance\",\n \"summary\": \"**`SavedStateHandle`:** Use `SavedStateHandle` in ViewModels to survive process death, not `onSaveInstanceState` in Fragments.\"\n },\n {\n \"id\": \"android-rule-15\",\n \"severity\": \"guidance\",\n \"summary\": \"**Fragment arguments via `newInstance`:** Always pass arguments via `Bundle` in a static `newInstance()` factory method. Never set properties directly on a Fragment after construction.\"\n },\n {\n \"id\": \"android-rule-16\",\n \"severity\": \"guidance\",\n \"summary\": \"**View binding:** Use View Binding (`viewBinding = true`) over `findViewById`. Never use synthetic imports (Kotlin Android Extensions is deprecated).\"\n },\n {\n \"id\": \"android-rule-17\",\n \"severity\": \"guidance\",\n \"summary\": \"**Lifecycle awareness:** Collect `Flow` in `lifecycleScope.launch { repeatOnLifecycle(STARTED) { ... } }`. Do not collect in `onCreate` without `repeatOnLifecycle`.\"\n },\n {\n \"id\": \"android-rule-18\",\n \"severity\": \"guidance\",\n \"summary\": \"**`onViewCreated`:** Set up views and observers in `onViewCreated`, not `onCreateView`. Release view references in `onDestroyView` (especially with View Binding: set binding to `null`).\"\n },\n {\n \"id\": \"android-rule-19\",\n \"severity\": \"guidance\",\n \"summary\": \"**Avoid back-stack manipulation:** Let the NavController manage the back stack. Do not call `fragmentManager.popBackStack()` manually.\"\n },\n {\n \"id\": \"android-rule-20\",\n \"severity\": \"guidance\",\n \"summary\": \"**Single NavGraph per activity:** Define all destinations and actions in `nav_graph.xml`. Use nested graphs for feature modules.\"\n },\n {\n \"id\": \"android-rule-21\",\n \"severity\": \"guidance\",\n \"summary\": \"**Safe Args:** Use the Safe Args Gradle plugin for type-safe navigation arguments. Do not use raw `Bundle` keys for navigation data.\"\n },\n {\n \"id\": \"android-rule-22\",\n \"severity\": \"guidance\",\n \"summary\": \"**Deep links:** Declare deep link URIs in the NavGraph, not in `AndroidManifest.xml` `intent-filter` manually.\"\n },\n {\n \"id\": \"android-rule-23\",\n \"severity\": \"guidance\",\n \"summary\": \"**`@Entity`:** Every table is a `data class` annotated with `@Entity`. Name tables explicitly with `tableName`.\"\n },\n {\n \"id\": \"android-rule-24\",\n \"severity\": \"guidance\",\n \"summary\": \"**`@Dao` interfaces:** Use `suspend` functions in DAOs for insert/update/delete. Return `Flow<T>` for queries to observe changes reactively.\"\n },\n {\n \"id\": \"android-rule-25\",\n \"severity\": \"guidance\",\n \"summary\": \"**No business logic in DAOs:** DAOs perform only data access. Transformations and filtering go in the repository or use case.\"\n },\n {\n \"id\": \"android-rule-26\",\n \"severity\": \"guidance\",\n \"summary\": \"**Database migrations:** Always write an explicit `Migration` for schema changes. Never use `fallbackToDestructiveMigration()` in production.\"\n },\n {\n \"id\": \"android-rule-27\",\n \"severity\": \"guidance\",\n \"summary\": \"**`@TypeConverter`:** Register converters for non-primitive types (e.g., `Date`, enums, custom objects).\"\n },\n {\n \"id\": \"android-rule-28\",\n \"severity\": \"guidance\",\n \"summary\": \"**Suspend functions in API interfaces:** Use `suspend fun` in Retrofit service interfaces — no `Call<T>`, no RxJava.\"\n },\n {\n \"id\": \"android-rule-29\",\n \"severity\": \"guidance\",\n \"summary\": \"**Sealed result types:** Wrap API responses in a `Result<T>` or `NetworkResult<T>` sealed class in the repository. Never expose raw Retrofit exceptions to ViewModels.\"\n },\n {\n \"id\": \"android-rule-30\",\n \"severity\": \"guidance\",\n \"summary\": \"**OkHttp interceptors:** Use interceptors for auth headers, logging (`HttpLoggingInterceptor`), and retry logic. Do not add auth logic inside API service interfaces.\"\n },\n {\n \"id\": \"android-rule-31\",\n \"severity\": \"guidance\",\n \"summary\": \"**Timeouts:** Always configure connect, read, and write timeouts on `OkHttpClient`. Never use the default (unlimited) timeouts.\"\n },\n {\n \"id\": \"android-rule-32\",\n \"severity\": \"guidance\",\n \"summary\": \"**Hilt over manual DI:** Use Hilt (built on Dagger) as the standard DI framework. Avoid `ServiceLocator` patterns.\"\n },\n {\n \"id\": \"android-rule-33\",\n \"severity\": \"guidance\",\n \"summary\": \"**`@HiltViewModel`:** Annotate all ViewModels. Inject via `by viewModels()` in Fragments/Activities.\"\n },\n {\n \"id\": \"android-rule-34\",\n \"severity\": \"guidance\",\n \"summary\": \"**`@Singleton` scope:** Scope repositories and network clients to `@Singleton`. Scope ViewModels to `@HiltViewModel` (automatic).\"\n },\n {\n \"id\": \"android-rule-35\",\n \"severity\": \"guidance\",\n \"summary\": \"**Modules for external dependencies:** Create `@Module` + `@InstallIn` classes to provide third-party types (Retrofit, Room, etc.) that cannot be annotated directly.\"\n },\n {\n \"id\": \"android-rule-36\",\n \"severity\": \"guidance\",\n \"summary\": \"**Request at the latest possible moment:** Ask for permissions immediately before the feature that needs them, not at app launch.\"\n },\n {\n \"id\": \"android-rule-37\",\n \"severity\": \"guidance\",\n \"summary\": \"**`ActivityResultContracts`:** Use `registerForActivityResult(RequestPermission())` — not `onRequestPermissionsResult`.\"\n },\n {\n \"id\": \"android-rule-38\",\n \"severity\": \"guidance\",\n \"summary\": \"**Handle denial gracefully:** Always handle both granted and denied cases. Show rationale with `shouldShowRequestPermissionRationale` before re-requesting.\"\n },\n {\n \"id\": \"android-rule-39\",\n \"severity\": \"guidance\",\n \"summary\": \"**ViewModel tests:** Test ViewModels with JUnit 4/5 and `kotlinx-coroutines-test`. Use `TestCoroutineDispatcher`/`UnconfinedTestDispatcher` and `Turbine` for `Flow` assertions.\"\n },\n {\n \"id\": \"android-rule-40\",\n \"severity\": \"guidance\",\n \"summary\": \"**Robolectric for unit tests:** Use Robolectric for tests needing Android framework context without an emulator.\"\n },\n {\n \"id\": \"android-rule-41\",\n \"severity\": \"guidance\",\n \"summary\": \"**Espresso / Compose UI tests:** Write UI tests for critical user journeys. Use `IdlingResource` for async operations in Espresso.\"\n },\n {\n \"id\": \"android-rule-42\",\n \"severity\": \"guidance\",\n \"summary\": \"**Fake over mock:** Prefer fake implementations of repositories/data sources over Mockito mocks for ViewModel tests. Fakes are more maintainable and realistic.\"\n },\n {\n \"id\": \"android-rule-43\",\n \"severity\": \"guidance\",\n \"summary\": \"**Naming conventions:**\"\n },\n {\n \"id\": \"android-rule-44\",\n \"severity\": \"guidance\",\n \"summary\": \"Layouts: `fragment_user_profile.xml`, `item_order_card.xml`, `view_loading_spinner.xml`\"\n },\n {\n \"id\": \"android-rule-45\",\n \"severity\": \"guidance\",\n \"summary\": \"IDs: `@+id/tvUserName` (type prefix) or `@+id/userNameText` (descriptive) — pick one and be consistent.\"\n },\n {\n \"id\": \"android-rule-46\",\n \"severity\": \"guidance\",\n \"summary\": \"Strings: `user_profile_title`, `error_network_unavailable` — use `feature_description` format.\"\n },\n {\n \"id\": \"android-rule-47\",\n \"severity\": \"guidance\",\n \"summary\": \"Drawables: `ic_` for icons, `bg_` for backgrounds, `img_` for images.\"\n },\n {\n \"id\": \"android-rule-48\",\n \"severity\": \"guidance\",\n \"summary\": \"**`strings.xml`:** All user-visible strings go in `strings.xml`. No hardcoded strings in layouts or code.\"\n },\n {\n \"id\": \"android-rule-49\",\n \"severity\": \"guidance\",\n \"summary\": \"**Dimensions:** Define reusable spacing in `dimens.xml`. Use `8dp` grid system.\"\n }\n ],\n \"source\": \"bundled_template\"\n}\n","styleguides/compose-multiplatform.json":"{\n \"version\": 1,\n \"schema\": \"cadre.styleguide.v1\",\n \"kind\": \"styleguide\",\n \"id\": \"compose-multiplatform\",\n \"title\": \"Compose Multiplatform Style Guide Summary\",\n \"summary\": \"This document summarizes key rules and best practices for building idiomatic, high-performance, and maintainable Compose Multiplatform (CMP) applications across Android, iOS, Desktop, and Web.\",\n \"sections\": [\n {\n \"heading\": \"1. Formatting and Tooling\",\n \"body\": \"- **ktlint & detekt:** Enforce via Gradle plugins. All code must pass linting before merging.\\n- **Compose Rules (detekt-compose):** Use Twitter/Facebook/Custom Compose lint rules to catch common performance pitfalls (e.g., \\\"MutableState in ViewModel should be private\\\").\\n- **Trailing lambdas:** Always use trailing lambda syntax for the content parameter of a Composable.\\n- **Naming:**\\n - **Composables:** `UpperCamelCase` (e.g., `PrimaryButton`). Names must be nouns.\\n - **Composable factories:** `UpperCamelCase` if they return `Unit`.\\n - **Modifier extensions:** `lowerCamelCase` (e.g., `Modifier.customPadding()`).\"\n },\n {\n \"heading\": \"2. Architecture (UDF + Component-based)\",\n \"body\": \"- **Unidirectional Data Flow (UDF):** State flows down (State); Events flow up (Callbacks).\\n- **State over Events:** Prefer modeling screen state as a single `UiState` data class rather than multiple independent flows.\\n- **ViewModel (Multiplatform):** Use `androidx.lifecycle.ViewModel` (now multiplatform-ready) or a shared `CmpViewModel` to hold logic.\\n- **Component-based UI:** Break UI into small, reusable, and stateless Composables. A Composable over 50 lines is a candidate for decomposition.\\n- **Stateless vs Stateful:**\\n - **Stateless:** Accepts state as parameters and emits events via callbacks. High reusability.\\n - **Stateful:** Manages its own state or interacts with a ViewModel. Use sparingly at the screen/feature root.\"\n },\n {\n \"heading\": \"3. Composable Design\",\n \"body\": \"- **Modifier as first optional parameter:** Every UI Composable should accept a `modifier: Modifier = Modifier` as its first optional parameter.\\n ```kotlin\\n @Composable\\n fun MyComponent(\\n text: String,\\n modifier: Modifier = Modifier,\\n onClicked: () -> Unit\\n ) { ... }\\n ```\\n- **Explicit parameter ordering:** Required parameters first, then `modifier`, then optional parameters, then the trailing lambda (if any).\\n- **Stability:** Ensure parameters are stable or immutable. Use `@Stable` or `@Immutable` on domain models if Compose cannot infer it. Avoid passing `List` directly; use `ImmutableList` (from kotlinx-collections-immutable) or a wrapper.\\n- **Slot API:** Use the \\\"Slot\\\" pattern (accepting `@Composable () -> Unit` lambdas) to increase flexibility and avoid deep parameter propogation.\"\n },\n {\n \"heading\": \"4. State Management\",\n \"body\": \"- **`remember` & `mutableStateOf`:** Use for local, UI-only state. Always use `rememberSaveable` for state that must survive configuration changes (Android).\\n- **`StateFlow` to `State`:** Collect flows using `collectAsStateWithLifecycle()` (requires `lifecycle-runtime-compose` multiplatform) to ensure lifecycle-aware updates.\\n- **State Hoisting:** Lift state up to make Composables stateless. The caller should control the state.\\n- **Don't pass `MutableState`:** Pass the raw value and a callback function, never a `MutableState<T>` object, to child Composables.\\n- **Side Effects:** Use `LaunchedEffect`, `SideEffect`, and `DisposableEffect` correctly. Never perform side effects directly in the Composable's body.\"\n },\n {\n \"heading\": \"5. Multiplatform Patterns (Expect/Actual)\",\n \"body\": \"- **Platform-specific UI:** Use `expect`/`actual` for platform-native components (e.g., `MapView`, `WebView`).\\n- **CompositionLocal:** Use `CompositionLocal` for cross-cutting concerns like Themes, Localizations, or Platform-specific configurations.\\n- **Platform Check:** Use `LocalWindowInfo.current` or custom platform-specific `CompositionLocal` instead of hardcoded platform checks inside generic UI code.\\n- **Shared Resources:** Use `Compose Multiplatform Resources` (lib) for shared strings, fonts, and images.\"\n },\n {\n \"heading\": \"6. Layout and Modifiers\",\n \"body\": \"- **Modifier Order Matters:** Modifiers are applied sequentially. `Modifier.padding(8.dp).clickable { }` is different from `Modifier.clickable { }.padding(8.dp)`.\\n- **Prefer `weight` in Rows/Columns:** Use `Modifier.weight()` for flexible layouts rather than hardcoded sizes.\\n- **Avoid `fillMaxSize()` in nested scrolling:** Use `wrapContentHeight()` or specific sizes to avoid infinite height constraints in `LazyColumn`.\\n- **Custom Modifiers:** Extract repeated modifier chains into extension functions for readability.\"\n },\n {\n \"heading\": \"7. Navigation\",\n \"body\": \"- **Compose Navigation Multiplatform:** Use the official `androidx.navigation:navigation-compose` (now Multiplatform).\\n- **Type-safe Navigation:** Use Kotlin Serialization with the Navigation component for type-safe arguments.\\n- **Single NavHost:** Keep the `NavHost` at the top level of each platform's entry point or in a shared `App()` Composable.\"\n },\n {\n \"heading\": \"8. Performance\",\n \"body\": \"- **Minimize Recomposition:** \\n - Pass only necessary data.\\n - Use `derivedStateOf` for state that depends on other state to avoid redundant recompositions.\\n - Use `remember` with keys to cache expensive calculations.\\n- **Lazy Collections:** Always use `LazyColumn`, `LazyRow`, and `LazyVerticalGrid` for large or dynamic lists. Use `key` in `items()` for stable identification.\\n- **Avoid heavy computation in `@Composable`:** Move business logic and heavy mapping to the ViewModel or use `remember`.\\n- **Phase isolation:** Use `Modifier.graphicsLayer` or lambda-based modifiers (e.g., `Modifier.offset { ... }`) for frequent updates like animations to skip the \\\"recomposition\\\" and \\\"layout\\\" phases.\"\n },\n {\n \"heading\": \"9. Testing\",\n \"body\": \"- **Compose UI Test:** Use `createComposeRule()` (Android) and `runComposeUiTest` (Multiplatform) to verify UI behavior.\\n- **Semantics:** Use `Modifier.semantics { contentDescription = \\\"...\\\" }` to make UI testable and accessible.\\n- **Screenshot Testing:** Use libraries like Roborazzi or Paparazzi for cross-platform visual regression testing.\"\n },\n {\n \"heading\": \"10. Desktop & iOS Specifics\",\n \"body\": \"- **Desktop:** Handle window resizing, keyboard shortcuts, and mouse hover states using `onPointerEvent`.\\n- **iOS:** Ensure `UIKitView` is used correctly for native interop. Respect safe area insets via `WindowInsets.safeDrawing`.\\n- **Web (Wasm/JS):** Be mindful of heavy computations as Wasm/JS performance characteristics differ from JVM/Native.\\n\\n*Sources: [Compose Multiplatform Docs](https://www.jetbrains.com/lp/compose-multiplatform/) · [Jetpack Compose Best Practices](https://developer.android.com/develop/ui/compose/performance) · [Kotlin Multiplatform Guidelines](https://kotlinlang.org/docs/multiplatform.html)*\"\n }\n ],\n \"languages\": [\n \"compose-multiplatform\"\n ],\n \"frameworks\": [],\n \"file_patterns\": [],\n \"applies_to\": [\n \"planning\",\n \"implementation\",\n \"review\",\n \"tests\"\n ],\n \"rules\": [\n {\n \"id\": \"compose-multiplatform-rule-1\",\n \"severity\": \"guidance\",\n \"summary\": \"**ktlint & detekt:** Enforce via Gradle plugins. All code must pass linting before merging.\"\n },\n {\n \"id\": \"compose-multiplatform-rule-2\",\n \"severity\": \"guidance\",\n \"summary\": \"**Compose Rules (detekt-compose):** Use Twitter/Facebook/Custom Compose lint rules to catch common performance pitfalls (e.g., \\\"MutableState in ViewModel should be private\\\").\"\n },\n {\n \"id\": \"compose-multiplatform-rule-3\",\n \"severity\": \"guidance\",\n \"summary\": \"**Trailing lambdas:** Always use trailing lambda syntax for the content parameter of a Composable.\"\n },\n {\n \"id\": \"compose-multiplatform-rule-4\",\n \"severity\": \"guidance\",\n \"summary\": \"**Naming:**\"\n },\n {\n \"id\": \"compose-multiplatform-rule-5\",\n \"severity\": \"guidance\",\n \"summary\": \"**Composables:** `UpperCamelCase` (e.g., `PrimaryButton`). Names must be nouns.\"\n },\n {\n \"id\": \"compose-multiplatform-rule-6\",\n \"severity\": \"guidance\",\n \"summary\": \"**Composable factories:** `UpperCamelCase` if they return `Unit`.\"\n },\n {\n \"id\": \"compose-multiplatform-rule-7\",\n \"severity\": \"guidance\",\n \"summary\": \"**Modifier extensions:** `lowerCamelCase` (e.g., `Modifier.customPadding()`).\"\n },\n {\n \"id\": \"compose-multiplatform-rule-8\",\n \"severity\": \"guidance\",\n \"summary\": \"**Unidirectional Data Flow (UDF):** State flows down (State); Events flow up (Callbacks).\"\n },\n {\n \"id\": \"compose-multiplatform-rule-9\",\n \"severity\": \"guidance\",\n \"summary\": \"**State over Events:** Prefer modeling screen state as a single `UiState` data class rather than multiple independent flows.\"\n },\n {\n \"id\": \"compose-multiplatform-rule-10\",\n \"severity\": \"guidance\",\n \"summary\": \"**ViewModel (Multiplatform):** Use `androidx.lifecycle.ViewModel` (now multiplatform-ready) or a shared `CmpViewModel` to hold logic.\"\n },\n {\n \"id\": \"compose-multiplatform-rule-11\",\n \"severity\": \"guidance\",\n \"summary\": \"**Component-based UI:** Break UI into small, reusable, and stateless Composables. A Composable over 50 lines is a candidate for decomposition.\"\n },\n {\n \"id\": \"compose-multiplatform-rule-12\",\n \"severity\": \"guidance\",\n \"summary\": \"**Stateless vs Stateful:**\"\n },\n {\n \"id\": \"compose-multiplatform-rule-13\",\n \"severity\": \"guidance\",\n \"summary\": \"**Stateless:** Accepts state as parameters and emits events via callbacks. High reusability.\"\n },\n {\n \"id\": \"compose-multiplatform-rule-14\",\n \"severity\": \"guidance\",\n \"summary\": \"**Stateful:** Manages its own state or interacts with a ViewModel. Use sparingly at the screen/feature root.\"\n },\n {\n \"id\": \"compose-multiplatform-rule-15\",\n \"severity\": \"guidance\",\n \"summary\": \"**Modifier as first optional parameter:** Every UI Composable should accept a `modifier: Modifier = Modifier` as its first optional parameter.\"\n },\n {\n \"id\": \"compose-multiplatform-rule-16\",\n \"severity\": \"guidance\",\n \"summary\": \"**Explicit parameter ordering:** Required parameters first, then `modifier`, then optional parameters, then the trailing lambda (if any).\"\n },\n {\n \"id\": \"compose-multiplatform-rule-17\",\n \"severity\": \"guidance\",\n \"summary\": \"**Stability:** Ensure parameters are stable or immutable. Use `@Stable` or `@Immutable` on domain models if Compose cannot infer it. Avoid passing `List` directly; use `ImmutableList` (from kotlinx-collections-immutable) or a wrapper.\"\n },\n {\n \"id\": \"compose-multiplatform-rule-18\",\n \"severity\": \"guidance\",\n \"summary\": \"**Slot API:** Use the \\\"Slot\\\" pattern (accepting `@Composable () -> Unit` lambdas) to increase flexibility and avoid deep parameter propogation.\"\n },\n {\n \"id\": \"compose-multiplatform-rule-19\",\n \"severity\": \"guidance\",\n \"summary\": \"**`remember` & `mutableStateOf`:** Use for local, UI-only state. Always use `rememberSaveable` for state that must survive configuration changes (Android).\"\n },\n {\n \"id\": \"compose-multiplatform-rule-20\",\n \"severity\": \"guidance\",\n \"summary\": \"**`StateFlow` to `State`:** Collect flows using `collectAsStateWithLifecycle()` (requires `lifecycle-runtime-compose` multiplatform) to ensure lifecycle-aware updates.\"\n },\n {\n \"id\": \"compose-multiplatform-rule-21\",\n \"severity\": \"guidance\",\n \"summary\": \"**State Hoisting:** Lift state up to make Composables stateless. The caller should control the state.\"\n },\n {\n \"id\": \"compose-multiplatform-rule-22\",\n \"severity\": \"guidance\",\n \"summary\": \"**Don't pass `MutableState`:** Pass the raw value and a callback function, never a `MutableState<T>` object, to child Composables.\"\n },\n {\n \"id\": \"compose-multiplatform-rule-23\",\n \"severity\": \"guidance\",\n \"summary\": \"**Side Effects:** Use `LaunchedEffect`, `SideEffect`, and `DisposableEffect` correctly. Never perform side effects directly in the Composable's body.\"\n },\n {\n \"id\": \"compose-multiplatform-rule-24\",\n \"severity\": \"guidance\",\n \"summary\": \"**Platform-specific UI:** Use `expect`/`actual` for platform-native components (e.g., `MapView`, `WebView`).\"\n },\n {\n \"id\": \"compose-multiplatform-rule-25\",\n \"severity\": \"guidance\",\n \"summary\": \"**CompositionLocal:** Use `CompositionLocal` for cross-cutting concerns like Themes, Localizations, or Platform-specific configurations.\"\n },\n {\n \"id\": \"compose-multiplatform-rule-26\",\n \"severity\": \"guidance\",\n \"summary\": \"**Platform Check:** Use `LocalWindowInfo.current` or custom platform-specific `CompositionLocal` instead of hardcoded platform checks inside generic UI code.\"\n },\n {\n \"id\": \"compose-multiplatform-rule-27\",\n \"severity\": \"guidance\",\n \"summary\": \"**Shared Resources:** Use `Compose Multiplatform Resources` (lib) for shared strings, fonts, and images.\"\n },\n {\n \"id\": \"compose-multiplatform-rule-28\",\n \"severity\": \"guidance\",\n \"summary\": \"**Modifier Order Matters:** Modifiers are applied sequentially. `Modifier.padding(8.dp).clickable { }` is different from `Modifier.clickable { }.padding(8.dp)`.\"\n },\n {\n \"id\": \"compose-multiplatform-rule-29\",\n \"severity\": \"guidance\",\n \"summary\": \"**Prefer `weight` in Rows/Columns:** Use `Modifier.weight()` for flexible layouts rather than hardcoded sizes.\"\n },\n {\n \"id\": \"compose-multiplatform-rule-30\",\n \"severity\": \"guidance\",\n \"summary\": \"**Avoid `fillMaxSize()` in nested scrolling:** Use `wrapContentHeight()` or specific sizes to avoid infinite height constraints in `LazyColumn`.\"\n },\n {\n \"id\": \"compose-multiplatform-rule-31\",\n \"severity\": \"guidance\",\n \"summary\": \"**Custom Modifiers:** Extract repeated modifier chains into extension functions for readability.\"\n },\n {\n \"id\": \"compose-multiplatform-rule-32\",\n \"severity\": \"guidance\",\n \"summary\": \"**Compose Navigation Multiplatform:** Use the official `androidx.navigation:navigation-compose` (now Multiplatform).\"\n },\n {\n \"id\": \"compose-multiplatform-rule-33\",\n \"severity\": \"guidance\",\n \"summary\": \"**Type-safe Navigation:** Use Kotlin Serialization with the Navigation component for type-safe arguments.\"\n },\n {\n \"id\": \"compose-multiplatform-rule-34\",\n \"severity\": \"guidance\",\n \"summary\": \"**Single NavHost:** Keep the `NavHost` at the top level of each platform's entry point or in a shared `App()` Composable.\"\n },\n {\n \"id\": \"compose-multiplatform-rule-35\",\n \"severity\": \"guidance\",\n \"summary\": \"**Minimize Recomposition:**\"\n },\n {\n \"id\": \"compose-multiplatform-rule-36\",\n \"severity\": \"guidance\",\n \"summary\": \"Pass only necessary data.\"\n },\n {\n \"id\": \"compose-multiplatform-rule-37\",\n \"severity\": \"guidance\",\n \"summary\": \"Use `derivedStateOf` for state that depends on other state to avoid redundant recompositions.\"\n },\n {\n \"id\": \"compose-multiplatform-rule-38\",\n \"severity\": \"guidance\",\n \"summary\": \"Use `remember` with keys to cache expensive calculations.\"\n },\n {\n \"id\": \"compose-multiplatform-rule-39\",\n \"severity\": \"guidance\",\n \"summary\": \"**Lazy Collections:** Always use `LazyColumn`, `LazyRow`, and `LazyVerticalGrid` for large or dynamic lists. Use `key` in `items()` for stable identification.\"\n },\n {\n \"id\": \"compose-multiplatform-rule-40\",\n \"severity\": \"guidance\",\n \"summary\": \"**Avoid heavy computation in `@Composable`:** Move business logic and heavy mapping to the ViewModel or use `remember`.\"\n },\n {\n \"id\": \"compose-multiplatform-rule-41\",\n \"severity\": \"guidance\",\n \"summary\": \"**Phase isolation:** Use `Modifier.graphicsLayer` or lambda-based modifiers (e.g., `Modifier.offset { ... }`) for frequent updates like animations to skip the \\\"recomposition\\\" and \\\"layout\\\" phases.\"\n },\n {\n \"id\": \"compose-multiplatform-rule-42\",\n \"severity\": \"guidance\",\n \"summary\": \"**Compose UI Test:** Use `createComposeRule()` (Android) and `runComposeUiTest` (Multiplatform) to verify UI behavior.\"\n },\n {\n \"id\": \"compose-multiplatform-rule-43\",\n \"severity\": \"guidance\",\n \"summary\": \"**Semantics:** Use `Modifier.semantics { contentDescription = \\\"...\\\" }` to make UI testable and accessible.\"\n },\n {\n \"id\": \"compose-multiplatform-rule-44\",\n \"severity\": \"guidance\",\n \"summary\": \"**Screenshot Testing:** Use libraries like Roborazzi or Paparazzi for cross-platform visual regression testing.\"\n },\n {\n \"id\": \"compose-multiplatform-rule-45\",\n \"severity\": \"guidance\",\n \"summary\": \"**Desktop:** Handle window resizing, keyboard shortcuts, and mouse hover states using `onPointerEvent`.\"\n },\n {\n \"id\": \"compose-multiplatform-rule-46\",\n \"severity\": \"guidance\",\n \"summary\": \"**iOS:** Ensure `UIKitView` is used correctly for native interop. Respect safe area insets via `WindowInsets.safeDrawing`.\"\n },\n {\n \"id\": \"compose-multiplatform-rule-47\",\n \"severity\": \"guidance\",\n \"summary\": \"**Web (Wasm/JS):** Be mindful of heavy computations as Wasm/JS performance characteristics differ from JVM/Native.\"\n }\n ],\n \"source\": \"bundled_template\"\n}\n","styleguides/dart.json":"{\n \"version\": 1,\n \"schema\": \"cadre.styleguide.v1\",\n \"kind\": \"styleguide\",\n \"id\": \"dart\",\n \"title\": \"Effective Dart Style Guide Summary\",\n \"summary\": \"This document summarizes key rules and best practices from the official \\\"Effective Dart\\\" guide for writing idiomatic, performant, and maintainable Dart code.\",\n \"sections\": [\n {\n \"heading\": \"1. Formatting\",\n \"body\": \"- **`dart format`:** All Dart code **must** be formatted with `dart format` (formerly `dartfmt`). Non-negotiable.\\n- **Indentation:** 2 spaces. No tabs.\\n- **Line Length:** 80 characters maximum.\\n- **Trailing commas:** Add a trailing comma after the last item in multi-line argument/parameter lists to keep `dart format` from collapsing them to one line.\"\n },\n {\n \"heading\": \"2. Naming\",\n \"body\": \"- **`UpperCamelCase`:** For classes, enums, typedefs, and type parameters.\\n- **`lowerCamelCase`:** For variables, parameters, named parameters, functions, methods, and constant variables.\\n- **`lowercase_with_underscores`:** For libraries, packages, directories, and source files.\\n- **`_lowerCamelCase`:** For private identifiers (prefix with `_`).\\n- **Acronyms:** Capitalize only the first letter — `Http`, `Url`, `Json`, not `HTTP`, `URL`, `JSON` (exception: well-known two-letter acronyms like `IO`).\\n- **Boolean naming:** Name boolean variables and getters as affirmative phrases: `isEmpty`, `hasChildren`, `canClose`. Avoid `isNotEmpty` as a variable name.\"\n },\n {\n \"heading\": \"3. Types\",\n \"body\": \"- **Prefer type inference:** Let Dart infer types for local variables (`var x = ...`). Annotate when the type is not obvious or when required for API clarity.\\n- **`dynamic`:** Avoid `dynamic`. Use it only when genuinely dynamic behavior is needed. Prefer `Object?` for unknown values.\\n- **`Object` vs `dynamic`:** Prefer `Object?` for a type that accepts any value — it still participates in type checking; `dynamic` opts out entirely.\\n- **`var` vs explicit type:** Use `var` for local variables. Use explicit types for top-level and class-level declarations.\\n- **Nullable vs non-nullable:** With null safety, prefer non-nullable types. Only add `?` when `null` is a genuinely valid value.\\n- **Late variables:** Use `late` only when initialization is deferred but guaranteed before use. Prefer passing values in constructors.\"\n },\n {\n \"heading\": \"4. Functions and Methods\",\n \"body\": \"- **Named parameters:** Prefer named parameters for functions with more than two parameters or when parameter meaning is not obvious from the call site.\\n- **Required named parameters:** Mark mandatory named parameters `required`. Do not simulate with assertions on nullable params.\\n- **Arrow functions:** Use `=>` for simple single-expression functions and getters.\\n- **`async`/`await`:** Prefer `async`/`await` over raw `Future` chaining (`.then`, `.catchError`). Never mix them in the same function body.\\n- **Avoid `async` without `await`:** Do not mark a function `async` if it does not contain `await`.\\n- **`Stream`:** Return `Stream` for multiple asynchronous values. Use `async*` with `yield` to create streams.\"\n },\n {\n \"heading\": \"5. Variables and Control Flow\",\n \"body\": \"- **`final` by default:** Prefer `final` for variables that are not reassigned. Use `const` for compile-time constants.\\n- **`const` constructors:** Define `const` constructors for immutable classes. Use `const` at call sites for constant objects.\\n- **`??` and `?.`:** Use the null-aware operators instead of explicit null checks. Use `??=` for lazy initialization.\\n- **Cascade (`..`):** Use cascades to perform a sequence of operations on the same object. Do not cascade when the receiver is a temporary.\\n- **`is` over `as`:** Prefer `if (obj is Foo)` over `(obj as Foo)` to avoid runtime cast errors.\\n- **Avoid `late final` + nullable:** Pick one. Either the variable is `late` and always initialized, or it is nullable.\"\n },\n {\n \"heading\": \"6. Collections\",\n \"body\": \"- **Collection literals:** Use `[]`, `{}`, `<K,V>{}` over `List()`, `Set()`, `Map()` constructors.\\n- **Collection-if and collection-for:** Use these inside literals instead of building collections with `add`/`addAll` in a loop.\\n- **Spreads (`...`):** Use the spread operator to combine collections. Prefer over `addAll`.\\n- **`where`, `map`, `toList()`:** Chain iterable methods for transformations. Call `toList()` at the end to materialize only once.\\n- **Avoid `length` for emptiness:** Use `isEmpty`/`isNotEmpty` instead of `list.length == 0`.\"\n },\n {\n \"heading\": \"7. Classes and Constructors\",\n \"body\": \"- **Initializer lists:** Initialize fields in the initializer list, not the constructor body.\\n- **Shorthand field initialization:** Use `this.field` constructor parameters to initialize fields directly.\\n- **Factory constructors:** Use `factory` for constructors that return a cached or subtype instance.\\n- **`@immutable`:** Annotate classes with `@immutable` when all fields are `final`.\\n- **No public `late` fields:** Avoid public `late` fields. Prefer constructor initialization.\\n- **Extension methods:** Use extensions to add methods to existing types without subclassing.\"\n },\n {\n \"heading\": \"8. Error Handling\",\n \"body\": \"- **Exceptions for programming errors:** Throw `Error` subtypes (e.g., `ArgumentError`, `StateError`) for programming mistakes.\\n- **Exceptions for runtime failures:** Throw `Exception` subtypes for runtime failures the caller can recover from.\\n- **Avoid catching `Error`:** Catch specific exception types. Catching `Object` or `Error` is a sign of poor error modeling.\\n- **`on` before `catch`:** Use `on ExceptionType catch (e)` to restrict what you catch. Never use a bare `catch` without `on`.\"\n },\n {\n \"heading\": \"9. Documentation\",\n \"body\": \"- **`///` doc comments:** Use `///` (not `/** */`) for documentation on all public APIs.\\n- **Single-sentence summary:** Start every doc comment with a one-sentence summary that ends with a period.\\n- **Markdown:** Doc comments support Markdown. Use code blocks (`` ` ``) for inline code references.\\n- **`@param`, `@returns`:** Do not use these tags — Dart doc tools read the prose. Write parameter descriptions inline.\\n- **Prose over tags:** Describe behavior, edge cases, and usage in full sentences.\\n\\n*Source: [Effective Dart](https://dart.dev/effective-dart)*\"\n }\n ],\n \"languages\": [\n \"dart\"\n ],\n \"frameworks\": [],\n \"file_patterns\": [],\n \"applies_to\": [\n \"planning\",\n \"implementation\",\n \"review\",\n \"tests\"\n ],\n \"rules\": [\n {\n \"id\": \"dart-rule-1\",\n \"severity\": \"guidance\",\n \"summary\": \"**`dart format`:** All Dart code **must** be formatted with `dart format` (formerly `dartfmt`). Non-negotiable.\"\n },\n {\n \"id\": \"dart-rule-2\",\n \"severity\": \"guidance\",\n \"summary\": \"**Indentation:** 2 spaces. No tabs.\"\n },\n {\n \"id\": \"dart-rule-3\",\n \"severity\": \"guidance\",\n \"summary\": \"**Line Length:** 80 characters maximum.\"\n },\n {\n \"id\": \"dart-rule-4\",\n \"severity\": \"guidance\",\n \"summary\": \"**Trailing commas:** Add a trailing comma after the last item in multi-line argument/parameter lists to keep `dart format` from collapsing them to one line.\"\n },\n {\n \"id\": \"dart-rule-5\",\n \"severity\": \"guidance\",\n \"summary\": \"**`UpperCamelCase`:** For classes, enums, typedefs, and type parameters.\"\n },\n {\n \"id\": \"dart-rule-6\",\n \"severity\": \"guidance\",\n \"summary\": \"**`lowerCamelCase`:** For variables, parameters, named parameters, functions, methods, and constant variables.\"\n },\n {\n \"id\": \"dart-rule-7\",\n \"severity\": \"guidance\",\n \"summary\": \"**`lowercase_with_underscores`:** For libraries, packages, directories, and source files.\"\n },\n {\n \"id\": \"dart-rule-8\",\n \"severity\": \"guidance\",\n \"summary\": \"**`_lowerCamelCase`:** For private identifiers (prefix with `_`).\"\n },\n {\n \"id\": \"dart-rule-9\",\n \"severity\": \"guidance\",\n \"summary\": \"**Acronyms:** Capitalize only the first letter — `Http`, `Url`, `Json`, not `HTTP`, `URL`, `JSON` (exception: well-known two-letter acronyms like `IO`).\"\n },\n {\n \"id\": \"dart-rule-10\",\n \"severity\": \"guidance\",\n \"summary\": \"**Boolean naming:** Name boolean variables and getters as affirmative phrases: `isEmpty`, `hasChildren`, `canClose`. Avoid `isNotEmpty` as a variable name.\"\n },\n {\n \"id\": \"dart-rule-11\",\n \"severity\": \"guidance\",\n \"summary\": \"**Prefer type inference:** Let Dart infer types for local variables (`var x = ...`). Annotate when the type is not obvious or when required for API clarity.\"\n },\n {\n \"id\": \"dart-rule-12\",\n \"severity\": \"guidance\",\n \"summary\": \"**`dynamic`:** Avoid `dynamic`. Use it only when genuinely dynamic behavior is needed. Prefer `Object?` for unknown values.\"\n },\n {\n \"id\": \"dart-rule-13\",\n \"severity\": \"guidance\",\n \"summary\": \"**`Object` vs `dynamic`:** Prefer `Object?` for a type that accepts any value — it still participates in type checking; `dynamic` opts out entirely.\"\n },\n {\n \"id\": \"dart-rule-14\",\n \"severity\": \"guidance\",\n \"summary\": \"**`var` vs explicit type:** Use `var` for local variables. Use explicit types for top-level and class-level declarations.\"\n },\n {\n \"id\": \"dart-rule-15\",\n \"severity\": \"guidance\",\n \"summary\": \"**Nullable vs non-nullable:** With null safety, prefer non-nullable types. Only add `?` when `null` is a genuinely valid value.\"\n },\n {\n \"id\": \"dart-rule-16\",\n \"severity\": \"guidance\",\n \"summary\": \"**Late variables:** Use `late` only when initialization is deferred but guaranteed before use. Prefer passing values in constructors.\"\n },\n {\n \"id\": \"dart-rule-17\",\n \"severity\": \"guidance\",\n \"summary\": \"**Named parameters:** Prefer named parameters for functions with more than two parameters or when parameter meaning is not obvious from the call site.\"\n },\n {\n \"id\": \"dart-rule-18\",\n \"severity\": \"guidance\",\n \"summary\": \"**Required named parameters:** Mark mandatory named parameters `required`. Do not simulate with assertions on nullable params.\"\n },\n {\n \"id\": \"dart-rule-19\",\n \"severity\": \"guidance\",\n \"summary\": \"**Arrow functions:** Use `=>` for simple single-expression functions and getters.\"\n },\n {\n \"id\": \"dart-rule-20\",\n \"severity\": \"guidance\",\n \"summary\": \"**`async`/`await`:** Prefer `async`/`await` over raw `Future` chaining (`.then`, `.catchError`). Never mix them in the same function body.\"\n },\n {\n \"id\": \"dart-rule-21\",\n \"severity\": \"guidance\",\n \"summary\": \"**Avoid `async` without `await`:** Do not mark a function `async` if it does not contain `await`.\"\n },\n {\n \"id\": \"dart-rule-22\",\n \"severity\": \"guidance\",\n \"summary\": \"**`Stream`:** Return `Stream` for multiple asynchronous values. Use `async*` with `yield` to create streams.\"\n },\n {\n \"id\": \"dart-rule-23\",\n \"severity\": \"guidance\",\n \"summary\": \"**`final` by default:** Prefer `final` for variables that are not reassigned. Use `const` for compile-time constants.\"\n },\n {\n \"id\": \"dart-rule-24\",\n \"severity\": \"guidance\",\n \"summary\": \"**`const` constructors:** Define `const` constructors for immutable classes. Use `const` at call sites for constant objects.\"\n },\n {\n \"id\": \"dart-rule-25\",\n \"severity\": \"guidance\",\n \"summary\": \"**`??` and `?.`:** Use the null-aware operators instead of explicit null checks. Use `??=` for lazy initialization.\"\n },\n {\n \"id\": \"dart-rule-26\",\n \"severity\": \"guidance\",\n \"summary\": \"**Cascade (`..`):** Use cascades to perform a sequence of operations on the same object. Do not cascade when the receiver is a temporary.\"\n },\n {\n \"id\": \"dart-rule-27\",\n \"severity\": \"guidance\",\n \"summary\": \"**`is` over `as`:** Prefer `if (obj is Foo)` over `(obj as Foo)` to avoid runtime cast errors.\"\n },\n {\n \"id\": \"dart-rule-28\",\n \"severity\": \"guidance\",\n \"summary\": \"**Avoid `late final` + nullable:** Pick one. Either the variable is `late` and always initialized, or it is nullable.\"\n },\n {\n \"id\": \"dart-rule-29\",\n \"severity\": \"guidance\",\n \"summary\": \"**Collection literals:** Use `[]`, `{}`, `<K,V>{}` over `List()`, `Set()`, `Map()` constructors.\"\n },\n {\n \"id\": \"dart-rule-30\",\n \"severity\": \"guidance\",\n \"summary\": \"**Collection-if and collection-for:** Use these inside literals instead of building collections with `add`/`addAll` in a loop.\"\n },\n {\n \"id\": \"dart-rule-31\",\n \"severity\": \"guidance\",\n \"summary\": \"**Spreads (`...`):** Use the spread operator to combine collections. Prefer over `addAll`.\"\n },\n {\n \"id\": \"dart-rule-32\",\n \"severity\": \"guidance\",\n \"summary\": \"**`where`, `map`, `toList()`:** Chain iterable methods for transformations. Call `toList()` at the end to materialize only once.\"\n },\n {\n \"id\": \"dart-rule-33\",\n \"severity\": \"guidance\",\n \"summary\": \"**Avoid `length` for emptiness:** Use `isEmpty`/`isNotEmpty` instead of `list.length == 0`.\"\n },\n {\n \"id\": \"dart-rule-34\",\n \"severity\": \"guidance\",\n \"summary\": \"**Initializer lists:** Initialize fields in the initializer list, not the constructor body.\"\n },\n {\n \"id\": \"dart-rule-35\",\n \"severity\": \"guidance\",\n \"summary\": \"**Shorthand field initialization:** Use `this.field` constructor parameters to initialize fields directly.\"\n },\n {\n \"id\": \"dart-rule-36\",\n \"severity\": \"guidance\",\n \"summary\": \"**Factory constructors:** Use `factory` for constructors that return a cached or subtype instance.\"\n },\n {\n \"id\": \"dart-rule-37\",\n \"severity\": \"guidance\",\n \"summary\": \"**`@immutable`:** Annotate classes with `@immutable` when all fields are `final`.\"\n },\n {\n \"id\": \"dart-rule-38\",\n \"severity\": \"guidance\",\n \"summary\": \"**No public `late` fields:** Avoid public `late` fields. Prefer constructor initialization.\"\n },\n {\n \"id\": \"dart-rule-39\",\n \"severity\": \"guidance\",\n \"summary\": \"**Extension methods:** Use extensions to add methods to existing types without subclassing.\"\n },\n {\n \"id\": \"dart-rule-40\",\n \"severity\": \"guidance\",\n \"summary\": \"**Exceptions for programming errors:** Throw `Error` subtypes (e.g., `ArgumentError`, `StateError`) for programming mistakes.\"\n },\n {\n \"id\": \"dart-rule-41\",\n \"severity\": \"guidance\",\n \"summary\": \"**Exceptions for runtime failures:** Throw `Exception` subtypes for runtime failures the caller can recover from.\"\n },\n {\n \"id\": \"dart-rule-42\",\n \"severity\": \"guidance\",\n \"summary\": \"**Avoid catching `Error`:** Catch specific exception types. Catching `Object` or `Error` is a sign of poor error modeling.\"\n },\n {\n \"id\": \"dart-rule-43\",\n \"severity\": \"guidance\",\n \"summary\": \"**`on` before `catch`:** Use `on ExceptionType catch (e)` to restrict what you catch. Never use a bare `catch` without `on`.\"\n },\n {\n \"id\": \"dart-rule-44\",\n \"severity\": \"guidance\",\n \"summary\": \"**`///` doc comments:** Use `///` (not `/** */`) for documentation on all public APIs.\"\n },\n {\n \"id\": \"dart-rule-45\",\n \"severity\": \"guidance\",\n \"summary\": \"**Single-sentence summary:** Start every doc comment with a one-sentence summary that ends with a period.\"\n },\n {\n \"id\": \"dart-rule-46\",\n \"severity\": \"guidance\",\n \"summary\": \"**Markdown:** Doc comments support Markdown. Use code blocks (`` ` ``) for inline code references.\"\n },\n {\n \"id\": \"dart-rule-47\",\n \"severity\": \"guidance\",\n \"summary\": \"**`@param`, `@returns`:** Do not use these tags — Dart doc tools read the prose. Write parameter descriptions inline.\"\n },\n {\n \"id\": \"dart-rule-48\",\n \"severity\": \"guidance\",\n \"summary\": \"**Prose over tags:** Describe behavior, edge cases, and usage in full sentences.\"\n }\n ],\n \"source\": \"bundled_template\"\n}\n","styleguides/flutter.json":"{\n \"version\": 1,\n \"schema\": \"cadre.styleguide.v1\",\n \"kind\": \"styleguide\",\n \"id\": \"flutter\",\n \"title\": \"Effective Flutter Style Guide Summary\",\n \"summary\": \"This document summarizes key rules and best practices for writing idiomatic Flutter code, building on Effective Dart with Flutter-specific widget, state, and performance conventions.\",\n \"sections\": [\n {\n \"heading\": \"1. Formatting and Tooling\",\n \"body\": \"- **`dart format`:** All Flutter code must be formatted with `dart format`. Run via `flutter format .`.\\n- **`flutter analyze`:** Treat all analyzer warnings as errors. Enforce in CI.\\n- **Trailing commas:** Always add trailing commas after the last argument in multi-line widget trees — this keeps `dart format` from collapsing widget hierarchies to one line.\\n- **Import ordering:** `dart:` → `package:flutter/` → other `package:` → relative imports.\"\n },\n {\n \"heading\": \"2. Widget Design\",\n \"body\": \"- **`StatelessWidget` by default:** Reach for `StatelessWidget` first. Only use `StatefulWidget` when local mutable state is genuinely needed.\\n- **Small, composable widgets:** Prefer extracting reusable pieces into their own widgets over large `build` methods. A build method over ~50 lines is a sign it should be split.\\n- **`const` constructors everywhere:** Define `const` constructors on all widgets. Use `const` at call sites to skip unnecessary rebuilds.\\n- **`Key` usage:** Pass `Key` to the parent `Widget` constructor, not to child widgets inside `build`. Use `ValueKey`, `ObjectKey`, or `UniqueKey` — not `GlobalKey` unless absolutely required (e.g., form validation, imperative scroll).\\n- **`Widget` over helper methods:** Extract sub-trees into separate `Widget` classes rather than private `_buildXxx()` methods. Widget classes participate in the element tree and optimize rebuilds; helper methods do not.\"\n },\n {\n \"heading\": \"3. State Management\",\n \"body\": \"- **Lift state up:** Keep state as low in the tree as needed and no lower. Share state by lifting to a common ancestor.\\n- **`setState` scope:** Call `setState` with the minimum code needed. Only pass the mutation, not the full rebuild computation.\\n- **Avoid storing `BuildContext` across async gaps:** After an `await`, check `mounted` before using `context`. Never store `context` in a field for later use.\\n- **Inherited widgets / providers:** Use `InheritedWidget`, `Provider`, `Riverpod`, or `Bloc` for state that many widgets need. Do not prop-drill through 3+ layers.\\n- **`initState` / `dispose`:** Always pair resource acquisition (`initState`, `addListener`) with release (`dispose`, `removeListener`). Never call `setState` in `initState`.\\n- **`didChangeDependencies`:** Use for operations that depend on `InheritedWidget` values, not `initState`.\"\n },\n {\n \"heading\": \"4. Performance\",\n \"body\": \"- **`const` widgets:** Mark widgets and their constructors `const` whenever possible — this is the single highest-ROI optimization in Flutter.\\n- **`ListView.builder`:** Use `ListView.builder` (or `GridView.builder`, `CustomScrollView`) for lists of unknown or large length. Never use `ListView(children: items.map(...).toList())` for long lists.\\n- **`RepaintBoundary`:** Wrap expensive, independently-animating subtrees in `RepaintBoundary` to isolate repaints.\\n- **Avoid rebuilding with `AnimatedBuilder`:** Pass only the widget that changes as the `child` parameter — it is cached and not rebuilt on animation ticks.\\n- **`ImageCache` and `precacheImage`:** Precache images likely to be shown soon. Prefer `AssetImage`/`NetworkImage` with proper caching over `Image.memory` for large images.\\n- **Avoid work in `build`:** Never compute values, parse data, or make network calls inside `build()`. Compute in `initState`, `didUpdateWidget`, or a state management layer.\"\n },\n {\n \"heading\": \"5. Layout\",\n \"body\": \"- **Prefer `Column`/`Row` over `Stack` where possible:** `Stack` is for overlay scenarios; prefer linear layouts for sequential content.\\n- **`Expanded` and `Flexible`:** Use `Expanded` to fill remaining space. Use `Flexible` when you want to allow shrinking. Never use `SizedBox.expand()` inside `Column`/`Row` — use `Expanded`.\\n- **`SizedBox` for spacing:** Prefer `SizedBox(height: 8)` over `Padding(padding: EdgeInsets.only(top: 8))` for simple fixed spacing.\\n- **`MediaQuery` and `LayoutBuilder`:** Use `LayoutBuilder` for widget-local responsive constraints. Use `MediaQuery.of(context)` sparingly — changes trigger full rebuilds.\\n- **Avoid unbounded height/width:** `Column` inside a `ListView` without a bounded height will throw. Use `shrinkWrap: true` or wrap in `SizedBox` with an explicit dimension when nesting scrollables.\"\n },\n {\n \"heading\": \"6. Navigation and Routing\",\n \"body\": \"- **Named routes or `go_router`:** Prefer declarative routing (`go_router`, `auto_route`) over imperative `Navigator.push` for deep linking and complex flows.\\n- **`WillPopScope` / `PopScope`:** Handle back navigation explicitly when there is unsaved state or a multi-step flow.\\n- **Pass data via constructor, not `arguments`:** Prefer typed constructor injection over `ModalRoute.of(context)!.settings.arguments`. Use route parameters with `go_router`.\"\n },\n {\n \"heading\": \"7. Theming and Styling\",\n \"body\": \"- **Use `Theme.of(context)`:** Never hardcode colors or text styles. Always derive from the active `ThemeData`.\\n- **`TextTheme`:** Use `Theme.of(context).textTheme.bodyLarge` etc. — do not define ad-hoc `TextStyle` objects everywhere.\\n- **`ColorScheme`:** Use Material 3's `ColorScheme` roles (`primary`, `surface`, `onPrimary`) rather than direct `Color` values.\\n- **`ThemeExtension`:** Define custom theme data in a `ThemeExtension<T>` instead of global constants.\"\n },\n {\n \"heading\": \"8. Testing\",\n \"body\": \"- **Widget tests over unit tests for UI:** Test widget behavior with `flutter_test`'s `WidgetTester`. Avoid screenshot testing as the primary regression tool.\\n- **`find.byType`, `find.byKey`:** Prefer `find.byKey(ValueKey('submit'))` for interactive elements. Use `find.byType` for presence checks.\\n- **`pumpAndSettle`:** Use after triggering async operations. Use `pump(Duration)` for animations you control explicitly.\\n- **Golden tests:** Use sparingly — they are brittle across platforms. Gate on a single reference platform in CI.\"\n },\n {\n \"heading\": \"9. Naming and File Structure\",\n \"body\": \"- **One widget per file:** Each top-level `Widget` subclass lives in its own file.\\n- **File names match class names:** `UserProfileCard` → `user_profile_card.dart`.\\n- **Feature-first folder structure:** Group by feature (`lib/features/auth/`, `lib/features/home/`), not by type (`lib/widgets/`, `lib/models/`).\\n- **`_` prefix for private widgets:** Private helper widgets within a file are prefixed with `_`.\\n\\n*Sources: [Flutter Docs](https://docs.flutter.dev) · [Effective Dart](https://dart.dev/effective-dart) · [Flutter Performance Best Practices](https://docs.flutter.dev/perf/best-practices)*\"\n }\n ],\n \"languages\": [\n \"flutter\"\n ],\n \"frameworks\": [],\n \"file_patterns\": [],\n \"applies_to\": [\n \"planning\",\n \"implementation\",\n \"review\",\n \"tests\"\n ],\n \"rules\": [\n {\n \"id\": \"flutter-rule-1\",\n \"severity\": \"guidance\",\n \"summary\": \"**`dart format`:** All Flutter code must be formatted with `dart format`. Run via `flutter format .`.\"\n },\n {\n \"id\": \"flutter-rule-2\",\n \"severity\": \"guidance\",\n \"summary\": \"**`flutter analyze`:** Treat all analyzer warnings as errors. Enforce in CI.\"\n },\n {\n \"id\": \"flutter-rule-3\",\n \"severity\": \"guidance\",\n \"summary\": \"**Trailing commas:** Always add trailing commas after the last argument in multi-line widget trees — this keeps `dart format` from collapsing widget hierarchies to one line.\"\n },\n {\n \"id\": \"flutter-rule-4\",\n \"severity\": \"guidance\",\n \"summary\": \"**Import ordering:** `dart:` → `package:flutter/` → other `package:` → relative imports.\"\n },\n {\n \"id\": \"flutter-rule-5\",\n \"severity\": \"guidance\",\n \"summary\": \"**`StatelessWidget` by default:** Reach for `StatelessWidget` first. Only use `StatefulWidget` when local mutable state is genuinely needed.\"\n },\n {\n \"id\": \"flutter-rule-6\",\n \"severity\": \"guidance\",\n \"summary\": \"**Small, composable widgets:** Prefer extracting reusable pieces into their own widgets over large `build` methods. A build method over ~50 lines is a sign it should be split.\"\n },\n {\n \"id\": \"flutter-rule-7\",\n \"severity\": \"guidance\",\n \"summary\": \"**`const` constructors everywhere:** Define `const` constructors on all widgets. Use `const` at call sites to skip unnecessary rebuilds.\"\n },\n {\n \"id\": \"flutter-rule-8\",\n \"severity\": \"guidance\",\n \"summary\": \"**`Key` usage:** Pass `Key` to the parent `Widget` constructor, not to child widgets inside `build`. Use `ValueKey`, `ObjectKey`, or `UniqueKey` — not `GlobalKey` unless absolutely required (e.g., form validation, imperative scroll).\"\n },\n {\n \"id\": \"flutter-rule-9\",\n \"severity\": \"guidance\",\n \"summary\": \"**`Widget` over helper methods:** Extract sub-trees into separate `Widget` classes rather than private `_buildXxx()` methods. Widget classes participate in the element tree and optimize rebuilds; helper methods do not.\"\n },\n {\n \"id\": \"flutter-rule-10\",\n \"severity\": \"guidance\",\n \"summary\": \"**Lift state up:** Keep state as low in the tree as needed and no lower. Share state by lifting to a common ancestor.\"\n },\n {\n \"id\": \"flutter-rule-11\",\n \"severity\": \"guidance\",\n \"summary\": \"**`setState` scope:** Call `setState` with the minimum code needed. Only pass the mutation, not the full rebuild computation.\"\n },\n {\n \"id\": \"flutter-rule-12\",\n \"severity\": \"guidance\",\n \"summary\": \"**Avoid storing `BuildContext` across async gaps:** After an `await`, check `mounted` before using `context`. Never store `context` in a field for later use.\"\n },\n {\n \"id\": \"flutter-rule-13\",\n \"severity\": \"guidance\",\n \"summary\": \"**Inherited widgets / providers:** Use `InheritedWidget`, `Provider`, `Riverpod`, or `Bloc` for state that many widgets need. Do not prop-drill through 3+ layers.\"\n },\n {\n \"id\": \"flutter-rule-14\",\n \"severity\": \"guidance\",\n \"summary\": \"**`initState` / `dispose`:** Always pair resource acquisition (`initState`, `addListener`) with release (`dispose`, `removeListener`). Never call `setState` in `initState`.\"\n },\n {\n \"id\": \"flutter-rule-15\",\n \"severity\": \"guidance\",\n \"summary\": \"**`didChangeDependencies`:** Use for operations that depend on `InheritedWidget` values, not `initState`.\"\n },\n {\n \"id\": \"flutter-rule-16\",\n \"severity\": \"guidance\",\n \"summary\": \"**`const` widgets:** Mark widgets and their constructors `const` whenever possible — this is the single highest-ROI optimization in Flutter.\"\n },\n {\n \"id\": \"flutter-rule-17\",\n \"severity\": \"guidance\",\n \"summary\": \"**`ListView.builder`:** Use `ListView.builder` (or `GridView.builder`, `CustomScrollView`) for lists of unknown or large length. Never use `ListView(children: items.map(...).toList())` for long lists.\"\n },\n {\n \"id\": \"flutter-rule-18\",\n \"severity\": \"guidance\",\n \"summary\": \"**`RepaintBoundary`:** Wrap expensive, independently-animating subtrees in `RepaintBoundary` to isolate repaints.\"\n },\n {\n \"id\": \"flutter-rule-19\",\n \"severity\": \"guidance\",\n \"summary\": \"**Avoid rebuilding with `AnimatedBuilder`:** Pass only the widget that changes as the `child` parameter — it is cached and not rebuilt on animation ticks.\"\n },\n {\n \"id\": \"flutter-rule-20\",\n \"severity\": \"guidance\",\n \"summary\": \"**`ImageCache` and `precacheImage`:** Precache images likely to be shown soon. Prefer `AssetImage`/`NetworkImage` with proper caching over `Image.memory` for large images.\"\n },\n {\n \"id\": \"flutter-rule-21\",\n \"severity\": \"guidance\",\n \"summary\": \"**Avoid work in `build`:** Never compute values, parse data, or make network calls inside `build()`. Compute in `initState`, `didUpdateWidget`, or a state management layer.\"\n },\n {\n \"id\": \"flutter-rule-22\",\n \"severity\": \"guidance\",\n \"summary\": \"**Prefer `Column`/`Row` over `Stack` where possible:** `Stack` is for overlay scenarios; prefer linear layouts for sequential content.\"\n },\n {\n \"id\": \"flutter-rule-23\",\n \"severity\": \"guidance\",\n \"summary\": \"**`Expanded` and `Flexible`:** Use `Expanded` to fill remaining space. Use `Flexible` when you want to allow shrinking. Never use `SizedBox.expand()` inside `Column`/`Row` — use `Expanded`.\"\n },\n {\n \"id\": \"flutter-rule-24\",\n \"severity\": \"guidance\",\n \"summary\": \"**`SizedBox` for spacing:** Prefer `SizedBox(height: 8)` over `Padding(padding: EdgeInsets.only(top: 8))` for simple fixed spacing.\"\n },\n {\n \"id\": \"flutter-rule-25\",\n \"severity\": \"guidance\",\n \"summary\": \"**`MediaQuery` and `LayoutBuilder`:** Use `LayoutBuilder` for widget-local responsive constraints. Use `MediaQuery.of(context)` sparingly — changes trigger full rebuilds.\"\n },\n {\n \"id\": \"flutter-rule-26\",\n \"severity\": \"guidance\",\n \"summary\": \"**Avoid unbounded height/width:** `Column` inside a `ListView` without a bounded height will throw. Use `shrinkWrap: true` or wrap in `SizedBox` with an explicit dimension when nesting scrollables.\"\n },\n {\n \"id\": \"flutter-rule-27\",\n \"severity\": \"guidance\",\n \"summary\": \"**Named routes or `go_router`:** Prefer declarative routing (`go_router`, `auto_route`) over imperative `Navigator.push` for deep linking and complex flows.\"\n },\n {\n \"id\": \"flutter-rule-28\",\n \"severity\": \"guidance\",\n \"summary\": \"**`WillPopScope` / `PopScope`:** Handle back navigation explicitly when there is unsaved state or a multi-step flow.\"\n },\n {\n \"id\": \"flutter-rule-29\",\n \"severity\": \"guidance\",\n \"summary\": \"**Pass data via constructor, not `arguments`:** Prefer typed constructor injection over `ModalRoute.of(context)!.settings.arguments`. Use route parameters with `go_router`.\"\n },\n {\n \"id\": \"flutter-rule-30\",\n \"severity\": \"guidance\",\n \"summary\": \"**Use `Theme.of(context)`:** Never hardcode colors or text styles. Always derive from the active `ThemeData`.\"\n },\n {\n \"id\": \"flutter-rule-31\",\n \"severity\": \"guidance\",\n \"summary\": \"**`TextTheme`:** Use `Theme.of(context).textTheme.bodyLarge` etc. — do not define ad-hoc `TextStyle` objects everywhere.\"\n },\n {\n \"id\": \"flutter-rule-32\",\n \"severity\": \"guidance\",\n \"summary\": \"**`ColorScheme`:** Use Material 3's `ColorScheme` roles (`primary`, `surface`, `onPrimary`) rather than direct `Color` values.\"\n },\n {\n \"id\": \"flutter-rule-33\",\n \"severity\": \"guidance\",\n \"summary\": \"**`ThemeExtension`:** Define custom theme data in a `ThemeExtension<T>` instead of global constants.\"\n },\n {\n \"id\": \"flutter-rule-34\",\n \"severity\": \"guidance\",\n \"summary\": \"**Widget tests over unit tests for UI:** Test widget behavior with `flutter_test`'s `WidgetTester`. Avoid screenshot testing as the primary regression tool.\"\n },\n {\n \"id\": \"flutter-rule-35\",\n \"severity\": \"guidance\",\n \"summary\": \"**`find.byType`, `find.byKey`:** Prefer `find.byKey(ValueKey('submit'))` for interactive elements. Use `find.byType` for presence checks.\"\n },\n {\n \"id\": \"flutter-rule-36\",\n \"severity\": \"guidance\",\n \"summary\": \"**`pumpAndSettle`:** Use after triggering async operations. Use `pump(Duration)` for animations you control explicitly.\"\n },\n {\n \"id\": \"flutter-rule-37\",\n \"severity\": \"guidance\",\n \"summary\": \"**Golden tests:** Use sparingly — they are brittle across platforms. Gate on a single reference platform in CI.\"\n },\n {\n \"id\": \"flutter-rule-38\",\n \"severity\": \"guidance\",\n \"summary\": \"**One widget per file:** Each top-level `Widget` subclass lives in its own file.\"\n },\n {\n \"id\": \"flutter-rule-39\",\n \"severity\": \"guidance\",\n \"summary\": \"**File names match class names:** `UserProfileCard` → `user_profile_card.dart`.\"\n },\n {\n \"id\": \"flutter-rule-40\",\n \"severity\": \"guidance\",\n \"summary\": \"**Feature-first folder structure:** Group by feature (`lib/features/auth/`, `lib/features/home/`), not by type (`lib/widgets/`, `lib/models/`).\"\n },\n {\n \"id\": \"flutter-rule-41\",\n \"severity\": \"guidance\",\n \"summary\": \"**`_` prefix for private widgets:** Private helper widgets within a file are prefixed with `_`.\"\n }\n ],\n \"source\": \"bundled_template\"\n}\n","styleguides/general.json":"{\n \"version\": 1,\n \"schema\": \"cadre.styleguide.v1\",\n \"kind\": \"styleguide\",\n \"id\": \"general\",\n \"title\": \"General Code Style Principles\",\n \"summary\": \"This document outlines general coding principles that apply across all languages and frameworks used in this project.\",\n \"sections\": [\n {\n \"heading\": \"Readability\",\n \"body\": \"- Code should be easy to read and understand by humans.\\n- Avoid overly clever or obscure constructs.\"\n },\n {\n \"heading\": \"Consistency\",\n \"body\": \"- Follow existing patterns in the codebase.\\n- Maintain consistent formatting, naming, and structure.\"\n },\n {\n \"heading\": \"Simplicity\",\n \"body\": \"- Prefer simple solutions over complex ones.\\n- Break down complex problems into smaller, manageable parts.\"\n },\n {\n \"heading\": \"Maintainability\",\n \"body\": \"- Write code that is easy to modify and extend.\\n- Minimize dependencies and coupling.\"\n },\n {\n \"heading\": \"Documentation\",\n \"body\": \"- Document *why* something is done, not just *what*.\\n- Keep documentation up-to-date with code changes.\"\n }\n ],\n \"languages\": [],\n \"frameworks\": [],\n \"file_patterns\": [],\n \"applies_to\": [\n \"planning\",\n \"implementation\",\n \"review\",\n \"tests\"\n ],\n \"rules\": [\n {\n \"id\": \"general-rule-1\",\n \"severity\": \"guidance\",\n \"summary\": \"Code should be easy to read and understand by humans.\"\n },\n {\n \"id\": \"general-rule-2\",\n \"severity\": \"guidance\",\n \"summary\": \"Avoid overly clever or obscure constructs.\"\n },\n {\n \"id\": \"general-rule-3\",\n \"severity\": \"guidance\",\n \"summary\": \"Follow existing patterns in the codebase.\"\n },\n {\n \"id\": \"general-rule-4\",\n \"severity\": \"guidance\",\n \"summary\": \"Maintain consistent formatting, naming, and structure.\"\n },\n {\n \"id\": \"general-rule-5\",\n \"severity\": \"guidance\",\n \"summary\": \"Prefer simple solutions over complex ones.\"\n },\n {\n \"id\": \"general-rule-6\",\n \"severity\": \"guidance\",\n \"summary\": \"Break down complex problems into smaller, manageable parts.\"\n },\n {\n \"id\": \"general-rule-7\",\n \"severity\": \"guidance\",\n \"summary\": \"Write code that is easy to modify and extend.\"\n },\n {\n \"id\": \"general-rule-8\",\n \"severity\": \"guidance\",\n \"summary\": \"Minimize dependencies and coupling.\"\n },\n {\n \"id\": \"general-rule-9\",\n \"severity\": \"guidance\",\n \"summary\": \"Document *why* something is done, not just *what*.\"\n },\n {\n \"id\": \"general-rule-10\",\n \"severity\": \"guidance\",\n \"summary\": \"Keep documentation up-to-date with code changes.\"\n }\n ],\n \"source\": \"bundled_template\"\n}\n","styleguides/go.json":"{\n \"version\": 1,\n \"schema\": \"cadre.styleguide.v1\",\n \"kind\": \"styleguide\",\n \"id\": \"go\",\n \"title\": \"Effective Go Style Guide Summary\",\n \"summary\": \"This document summarizes key rules and best practices from the official \\\"Effective Go\\\" guide for writing idiomatic Go code.\",\n \"sections\": [\n {\n \"heading\": \"1. Formatting\",\n \"body\": \"- **`gofmt`:** All Go code **must** be formatted with `gofmt` (or `go fmt`). This is a non-negotiable, automated standard.\\n- **Indentation:** Use tabs for indentation (`gofmt` handles this).\\n- **Line Length:** Go has no strict line length limit. Let `gofmt` handle line wrapping.\"\n },\n {\n \"heading\": \"2. Naming\",\n \"body\": \"- **`MixedCaps`:** Use `MixedCaps` or `mixedCaps` for multi-word names. Do not use underscores.\\n- **Exported vs. Unexported:** Names starting with an uppercase letter are exported (public). Names starting with a lowercase letter are not exported (private).\\n- **Package Names:** Short, concise, single-word, lowercase names.\\n- **Getters:** Do not name getters with a `Get` prefix. A getter for a field named `owner` should be named `Owner()`.\\n- **Interface Names:** One-method interfaces are named by the method name plus an `-er` suffix (e.g., `Reader`, `Writer`).\"\n },\n {\n \"heading\": \"3. Control Structures\",\n \"body\": \"- **`if`:** No parentheses around the condition. Braces are mandatory. Can include an initialization statement (e.g., `if err := file.Chmod(0664); err != nil`).\\n- **`for`:** Go's only looping construct. Unifies `for` and `while`. Use `for...range` to iterate over slices, maps, strings, and channels.\\n- **`switch`:** More general than in C. Cases do not fall through by default (use `fallthrough` explicitly). Can be used without an expression to function as a cleaner `if-else-if` chain.\"\n },\n {\n \"heading\": \"4. Functions\",\n \"body\": \"- **Multiple Returns:** Functions can return multiple values. This is the standard way to return a result and an error (e.g., `value, err`).\\n- **Named Result Parameters:** Return parameters can be named. This can make code clearer and more concise.\\n- **`defer`:** Schedules a function call to be run immediately before the function executing `defer` returns. Use it for cleanup tasks like closing files.\"\n },\n {\n \"heading\": \"5. Data\",\n \"body\": \"- **`new` vs. `make`:**\\n - `new(T)`: Allocates memory for a new item of type `T`, zeroes it, and returns a pointer (`*T`).\\n - `make(T, ...)`: Creates and initializes slices, maps, and channels only. Returns an initialized value of type `T` (not a pointer).\\n- **Slices:** The preferred way to work with sequences. They are more flexible than arrays.\\n- **Maps:** Use the \\\"comma ok\\\" idiom to check for the existence of a key: `value, ok := myMap[key]`.\"\n },\n {\n \"heading\": \"6. Interfaces\",\n \"body\": \"- **Implicit Implementation:** A type implements an interface by implementing its methods. No `implements` keyword is needed.\\n- **Small Interfaces:** Prefer many small interfaces over one large one. The standard library is full of single-method interfaces (e.g., `io.Reader`).\"\n },\n {\n \"heading\": \"7. Concurrency\",\n \"body\": \"- **Share Memory By Communicating:** This is the core philosophy. Do not communicate by sharing memory; instead, share memory by communicating.\\n- **Goroutines:** Lightweight, concurrently executing functions. Start one with the `go` keyword.\\n- **Channels:** Typed conduits for communication between goroutines. Use `make` to create them.\"\n },\n {\n \"heading\": \"8. Errors\",\n \"body\": \"- **`error` type:** The built-in `error` interface is the standard way to handle errors.\\n- **Explicit Error Handling:** Do not discard errors with the blank identifier (`_`). Check for errors explicitly.\\n- **`panic`:** Reserved for truly exceptional, unrecoverable situations. Generally, libraries should not panic.\\n\\n*Source: [Effective Go](https://go.dev/doc/effective_go)*\"\n }\n ],\n \"languages\": [\n \"go\"\n ],\n \"frameworks\": [],\n \"file_patterns\": [],\n \"applies_to\": [\n \"planning\",\n \"implementation\",\n \"review\",\n \"tests\"\n ],\n \"rules\": [\n {\n \"id\": \"go-rule-1\",\n \"severity\": \"guidance\",\n \"summary\": \"**`gofmt`:** All Go code **must** be formatted with `gofmt` (or `go fmt`). This is a non-negotiable, automated standard.\"\n },\n {\n \"id\": \"go-rule-2\",\n \"severity\": \"guidance\",\n \"summary\": \"**Indentation:** Use tabs for indentation (`gofmt` handles this).\"\n },\n {\n \"id\": \"go-rule-3\",\n \"severity\": \"guidance\",\n \"summary\": \"**Line Length:** Go has no strict line length limit. Let `gofmt` handle line wrapping.\"\n },\n {\n \"id\": \"go-rule-4\",\n \"severity\": \"guidance\",\n \"summary\": \"**`MixedCaps`:** Use `MixedCaps` or `mixedCaps` for multi-word names. Do not use underscores.\"\n },\n {\n \"id\": \"go-rule-5\",\n \"severity\": \"guidance\",\n \"summary\": \"**Exported vs. Unexported:** Names starting with an uppercase letter are exported (public). Names starting with a lowercase letter are not exported (private).\"\n },\n {\n \"id\": \"go-rule-6\",\n \"severity\": \"guidance\",\n \"summary\": \"**Package Names:** Short, concise, single-word, lowercase names.\"\n },\n {\n \"id\": \"go-rule-7\",\n \"severity\": \"guidance\",\n \"summary\": \"**Getters:** Do not name getters with a `Get` prefix. A getter for a field named `owner` should be named `Owner()`.\"\n },\n {\n \"id\": \"go-rule-8\",\n \"severity\": \"guidance\",\n \"summary\": \"**Interface Names:** One-method interfaces are named by the method name plus an `-er` suffix (e.g., `Reader`, `Writer`).\"\n },\n {\n \"id\": \"go-rule-9\",\n \"severity\": \"guidance\",\n \"summary\": \"**`if`:** No parentheses around the condition. Braces are mandatory. Can include an initialization statement (e.g., `if err := file.Chmod(0664); err != nil`).\"\n },\n {\n \"id\": \"go-rule-10\",\n \"severity\": \"guidance\",\n \"summary\": \"**`for`:** Go's only looping construct. Unifies `for` and `while`. Use `for...range` to iterate over slices, maps, strings, and channels.\"\n },\n {\n \"id\": \"go-rule-11\",\n \"severity\": \"guidance\",\n \"summary\": \"**`switch`:** More general than in C. Cases do not fall through by default (use `fallthrough` explicitly). Can be used without an expression to function as a cleaner `if-else-if` chain.\"\n },\n {\n \"id\": \"go-rule-12\",\n \"severity\": \"guidance\",\n \"summary\": \"**Multiple Returns:** Functions can return multiple values. This is the standard way to return a result and an error (e.g., `value, err`).\"\n },\n {\n \"id\": \"go-rule-13\",\n \"severity\": \"guidance\",\n \"summary\": \"**Named Result Parameters:** Return parameters can be named. This can make code clearer and more concise.\"\n },\n {\n \"id\": \"go-rule-14\",\n \"severity\": \"guidance\",\n \"summary\": \"**`defer`:** Schedules a function call to be run immediately before the function executing `defer` returns. Use it for cleanup tasks like closing files.\"\n },\n {\n \"id\": \"go-rule-15\",\n \"severity\": \"guidance\",\n \"summary\": \"**`new` vs. `make`:**\"\n },\n {\n \"id\": \"go-rule-16\",\n \"severity\": \"guidance\",\n \"summary\": \"`new(T)`: Allocates memory for a new item of type `T`, zeroes it, and returns a pointer (`*T`).\"\n },\n {\n \"id\": \"go-rule-17\",\n \"severity\": \"guidance\",\n \"summary\": \"`make(T, ...)`: Creates and initializes slices, maps, and channels only. Returns an initialized value of type `T` (not a pointer).\"\n },\n {\n \"id\": \"go-rule-18\",\n \"severity\": \"guidance\",\n \"summary\": \"**Slices:** The preferred way to work with sequences. They are more flexible than arrays.\"\n },\n {\n \"id\": \"go-rule-19\",\n \"severity\": \"guidance\",\n \"summary\": \"**Maps:** Use the \\\"comma ok\\\" idiom to check for the existence of a key: `value, ok := myMap[key]`.\"\n },\n {\n \"id\": \"go-rule-20\",\n \"severity\": \"guidance\",\n \"summary\": \"**Implicit Implementation:** A type implements an interface by implementing its methods. No `implements` keyword is needed.\"\n },\n {\n \"id\": \"go-rule-21\",\n \"severity\": \"guidance\",\n \"summary\": \"**Small Interfaces:** Prefer many small interfaces over one large one. The standard library is full of single-method interfaces (e.g., `io.Reader`).\"\n },\n {\n \"id\": \"go-rule-22\",\n \"severity\": \"guidance\",\n \"summary\": \"**Share Memory By Communicating:** This is the core philosophy. Do not communicate by sharing memory; instead, share memory by communicating.\"\n },\n {\n \"id\": \"go-rule-23\",\n \"severity\": \"guidance\",\n \"summary\": \"**Goroutines:** Lightweight, concurrently executing functions. Start one with the `go` keyword.\"\n },\n {\n \"id\": \"go-rule-24\",\n \"severity\": \"guidance\",\n \"summary\": \"**Channels:** Typed conduits for communication between goroutines. Use `make` to create them.\"\n },\n {\n \"id\": \"go-rule-25\",\n \"severity\": \"guidance\",\n \"summary\": \"**`error` type:** The built-in `error` interface is the standard way to handle errors.\"\n },\n {\n \"id\": \"go-rule-26\",\n \"severity\": \"guidance\",\n \"summary\": \"**Explicit Error Handling:** Do not discard errors with the blank identifier (`_`). Check for errors explicitly.\"\n },\n {\n \"id\": \"go-rule-27\",\n \"severity\": \"guidance\",\n \"summary\": \"**`panic`:** Reserved for truly exceptional, unrecoverable situations. Generally, libraries should not panic.\"\n }\n ],\n \"source\": \"bundled_template\"\n}\n","styleguides/html-css.json":"{\n \"version\": 1,\n \"schema\": \"cadre.styleguide.v1\",\n \"kind\": \"styleguide\",\n \"id\": \"html-css\",\n \"title\": \"Google HTML/CSS Style Guide Summary\",\n \"summary\": \"This document summarizes key rules and best practices from the Google HTML/CSS Style Guide.\",\n \"sections\": [\n {\n \"heading\": \"1. General Rules\",\n \"body\": \"- **Protocol:** Use HTTPS for all embedded resources.\\n- **Indentation:** Indent by 2 spaces. Do not use tabs.\\n- **Capitalization:** Use only lowercase for all code (element names, attributes, selectors, properties).\\n- **Trailing Whitespace:** Remove all trailing whitespace.\\n- **Encoding:** Use UTF-8 (without a BOM). Specify `<meta charset=\\\"utf-8\\\">` in HTML.\"\n },\n {\n \"heading\": \"2. HTML Style Rules\",\n \"body\": \"- **Document Type:** Use `<!doctype html>`.\\n- **HTML Validity:** Use valid HTML.\\n- **Semantics:** Use HTML elements according to their intended purpose (e.g., use `<p>` for paragraphs, not for spacing).\\n- **Multimedia Fallback:** Provide `alt` text for images and transcripts/captions for audio/video.\\n- **Separation of Concerns:** Strictly separate structure (HTML), presentation (CSS), and behavior (JavaScript). Link to CSS and JS from external files.\\n- **`type` Attributes:** Omit `type` attributes for stylesheets (`<link>`) and scripts (`<script>`).\"\n },\n {\n \"heading\": \"3. HTML Formatting Rules\",\n \"body\": \"- **General:** Use a new line for every block, list, or table element, and indent its children.\\n- **Quotation Marks:** Use double quotation marks (`\\\"\\\"`) for attribute values.\"\n },\n {\n \"heading\": \"4. CSS Style Rules\",\n \"body\": \"- **CSS Validity:** Use valid CSS.\\n- **Class Naming:** Use meaningful, generic names. Separate words with a hyphen (`-`).\\n - **Good:** `.video-player`, `.site-navigation`\\n - **Bad:** `.vid`, `.red-text`\\n- **ID Selectors:** Avoid using ID selectors for styling. Prefer class selectors.\\n- **Shorthand Properties:** Use shorthand properties where possible (e.g., `padding`, `font`).\\n- **`0` and Units:** Omit units for `0` values (e.g., `margin: 0;`).\\n- **Leading `0`s:** Always include leading `0`s for decimal values (e.g., `font-size: 0.8em;`).\\n- **Hexadecimal Notation:** Use 3-character hex notation where possible (e.g., `#fff`).\\n- **`!important`:** Avoid using `!important`.\"\n },\n {\n \"heading\": \"5. CSS Formatting Rules\",\n \"body\": \"- **Declaration Order:** Alphabetize declarations within a rule.\\n- **Indentation:** Indent all block content.\\n- **Semicolons:** Use a semicolon after every declaration.\\n- **Spacing:**\\n - Use a space after a property name's colon (`font-weight: bold;`).\\n - Use a space between the last selector and the opening brace (`.foo {`).\\n - Start a new line for each selector and declaration.\\n- **Rule Separation:** Separate rules with a new line.\\n- **Quotation Marks:** Use single quotes (`''`) for attribute selectors and property values (e.g., `[type='text']`).\\n\\n**BE CONSISTENT.** When editing code, match the existing style.\\n\\n*Source: [Google HTML/CSS Style Guide](https://google.github.io/styleguide/htmlcssguide.html)*\"\n }\n ],\n \"languages\": [\n \"html-css\"\n ],\n \"frameworks\": [],\n \"file_patterns\": [],\n \"applies_to\": [\n \"planning\",\n \"implementation\",\n \"review\",\n \"tests\"\n ],\n \"rules\": [\n {\n \"id\": \"html-css-rule-1\",\n \"severity\": \"guidance\",\n \"summary\": \"**Protocol:** Use HTTPS for all embedded resources.\"\n },\n {\n \"id\": \"html-css-rule-2\",\n \"severity\": \"guidance\",\n \"summary\": \"**Indentation:** Indent by 2 spaces. Do not use tabs.\"\n },\n {\n \"id\": \"html-css-rule-3\",\n \"severity\": \"guidance\",\n \"summary\": \"**Capitalization:** Use only lowercase for all code (element names, attributes, selectors, properties).\"\n },\n {\n \"id\": \"html-css-rule-4\",\n \"severity\": \"guidance\",\n \"summary\": \"**Trailing Whitespace:** Remove all trailing whitespace.\"\n },\n {\n \"id\": \"html-css-rule-5\",\n \"severity\": \"guidance\",\n \"summary\": \"**Encoding:** Use UTF-8 (without a BOM). Specify `<meta charset=\\\"utf-8\\\">` in HTML.\"\n },\n {\n \"id\": \"html-css-rule-6\",\n \"severity\": \"guidance\",\n \"summary\": \"**Document Type:** Use `<!doctype html>`.\"\n },\n {\n \"id\": \"html-css-rule-7\",\n \"severity\": \"guidance\",\n \"summary\": \"**HTML Validity:** Use valid HTML.\"\n },\n {\n \"id\": \"html-css-rule-8\",\n \"severity\": \"guidance\",\n \"summary\": \"**Semantics:** Use HTML elements according to their intended purpose (e.g., use `<p>` for paragraphs, not for spacing).\"\n },\n {\n \"id\": \"html-css-rule-9\",\n \"severity\": \"guidance\",\n \"summary\": \"**Multimedia Fallback:** Provide `alt` text for images and transcripts/captions for audio/video.\"\n },\n {\n \"id\": \"html-css-rule-10\",\n \"severity\": \"guidance\",\n \"summary\": \"**Separation of Concerns:** Strictly separate structure (HTML), presentation (CSS), and behavior (JavaScript). Link to CSS and JS from external files.\"\n },\n {\n \"id\": \"html-css-rule-11\",\n \"severity\": \"guidance\",\n \"summary\": \"**`type` Attributes:** Omit `type` attributes for stylesheets (`<link>`) and scripts (`<script>`).\"\n },\n {\n \"id\": \"html-css-rule-12\",\n \"severity\": \"guidance\",\n \"summary\": \"**General:** Use a new line for every block, list, or table element, and indent its children.\"\n },\n {\n \"id\": \"html-css-rule-13\",\n \"severity\": \"guidance\",\n \"summary\": \"**Quotation Marks:** Use double quotation marks (`\\\"\\\"`) for attribute values.\"\n },\n {\n \"id\": \"html-css-rule-14\",\n \"severity\": \"guidance\",\n \"summary\": \"**CSS Validity:** Use valid CSS.\"\n },\n {\n \"id\": \"html-css-rule-15\",\n \"severity\": \"guidance\",\n \"summary\": \"**Class Naming:** Use meaningful, generic names. Separate words with a hyphen (`-`).\"\n },\n {\n \"id\": \"html-css-rule-16\",\n \"severity\": \"guidance\",\n \"summary\": \"**Good:** `.video-player`, `.site-navigation`\"\n },\n {\n \"id\": \"html-css-rule-17\",\n \"severity\": \"guidance\",\n \"summary\": \"**Bad:** `.vid`, `.red-text`\"\n },\n {\n \"id\": \"html-css-rule-18\",\n \"severity\": \"guidance\",\n \"summary\": \"**ID Selectors:** Avoid using ID selectors for styling. Prefer class selectors.\"\n },\n {\n \"id\": \"html-css-rule-19\",\n \"severity\": \"guidance\",\n \"summary\": \"**Shorthand Properties:** Use shorthand properties where possible (e.g., `padding`, `font`).\"\n },\n {\n \"id\": \"html-css-rule-20\",\n \"severity\": \"guidance\",\n \"summary\": \"**`0` and Units:** Omit units for `0` values (e.g., `margin: 0;`).\"\n },\n {\n \"id\": \"html-css-rule-21\",\n \"severity\": \"guidance\",\n \"summary\": \"**Leading `0`s:** Always include leading `0`s for decimal values (e.g., `font-size: 0.8em;`).\"\n },\n {\n \"id\": \"html-css-rule-22\",\n \"severity\": \"guidance\",\n \"summary\": \"**Hexadecimal Notation:** Use 3-character hex notation where possible (e.g., `#fff`).\"\n },\n {\n \"id\": \"html-css-rule-23\",\n \"severity\": \"guidance\",\n \"summary\": \"**`!important`:** Avoid using `!important`.\"\n },\n {\n \"id\": \"html-css-rule-24\",\n \"severity\": \"guidance\",\n \"summary\": \"**Declaration Order:** Alphabetize declarations within a rule.\"\n },\n {\n \"id\": \"html-css-rule-25\",\n \"severity\": \"guidance\",\n \"summary\": \"**Indentation:** Indent all block content.\"\n },\n {\n \"id\": \"html-css-rule-26\",\n \"severity\": \"guidance\",\n \"summary\": \"**Semicolons:** Use a semicolon after every declaration.\"\n },\n {\n \"id\": \"html-css-rule-27\",\n \"severity\": \"guidance\",\n \"summary\": \"**Spacing:**\"\n },\n {\n \"id\": \"html-css-rule-28\",\n \"severity\": \"guidance\",\n \"summary\": \"Use a space after a property name's colon (`font-weight: bold;`).\"\n },\n {\n \"id\": \"html-css-rule-29\",\n \"severity\": \"guidance\",\n \"summary\": \"Use a space between the last selector and the opening brace (`.foo {`).\"\n },\n {\n \"id\": \"html-css-rule-30\",\n \"severity\": \"guidance\",\n \"summary\": \"Start a new line for each selector and declaration.\"\n },\n {\n \"id\": \"html-css-rule-31\",\n \"severity\": \"guidance\",\n \"summary\": \"**Rule Separation:** Separate rules with a new line.\"\n },\n {\n \"id\": \"html-css-rule-32\",\n \"severity\": \"guidance\",\n \"summary\": \"**Quotation Marks:** Use single quotes (`''`) for attribute selectors and property values (e.g., `[type='text']`).\"\n }\n ],\n \"source\": \"bundled_template\"\n}\n","styleguides/javascript.json":"{\n \"version\": 1,\n \"schema\": \"cadre.styleguide.v1\",\n \"kind\": \"styleguide\",\n \"id\": \"javascript\",\n \"title\": \"Google JavaScript Style Guide Summary\",\n \"summary\": \"This document summarizes key rules and best practices from the Google JavaScript Style Guide.\",\n \"sections\": [\n {\n \"heading\": \"1. Source File Basics\",\n \"body\": \"- **File Naming:** All lowercase, with underscores (`_`) or dashes (`-`). Extension must be `.js`.\\n- **File Encoding:** UTF-8.\\n- **Whitespace:** Use only ASCII horizontal spaces (0x20). Tabs are forbidden for indentation.\"\n },\n {\n \"heading\": \"2. Source File Structure\",\n \"body\": \"- New files should be ES modules (`import`/`export`).\\n- **Exports:** Use named exports (`export {MyClass};`). **Do not use default exports.**\\n- **Imports:** Do not use line-wrapped imports. The `.js` extension in import paths is mandatory.\"\n },\n {\n \"heading\": \"3. Formatting\",\n \"body\": \"- **Braces:** Required for all control structures (`if`, `for`, `while`, etc.), even single-line blocks. Use K&R style (\\\"Egyptian brackets\\\").\\n- **Indentation:** +2 spaces for each new block.\\n- **Semicolons:** Every statement must be terminated with a semicolon.\\n- **Column Limit:** 80 characters.\\n- **Line-wrapping:** Indent continuation lines at least +4 spaces.\\n- **Whitespace:** Use single blank lines between methods. No trailing whitespace.\"\n },\n {\n \"heading\": \"4. Language Features\",\n \"body\": \"- **Variable Declarations:** Use `const` by default, `let` if reassignment is needed. **`var` is forbidden.**\\n- **Array Literals:** Use trailing commas. Do not use the `Array` constructor.\\n- **Object Literals:** Use trailing commas and shorthand properties. Do not use the `Object` constructor.\\n- **Classes:** Do not use JavaScript getter/setter properties (`get name()`). Provide ordinary methods instead.\\n- **Functions:** Prefer arrow functions for nested functions to preserve `this` context.\\n- **String Literals:** Use single quotes (`'`). Use template literals (`` ` ``) for multi-line strings or complex interpolation.\\n- **Control Structures:** Prefer `for-of` loops. `for-in` loops should only be used on dict-style objects.\\n- **`this`:** Only use `this` in class constructors, methods, or in arrow functions defined within them.\\n- **Equality Checks:** Always use identity operators (`===` / `!==`).\"\n },\n {\n \"heading\": \"5. Disallowed Features\",\n \"body\": \"- `with` keyword.\\n- `eval()` or `Function(...string)`.\\n- Automatic Semicolon Insertion.\\n- Modifying builtin objects (`Array.prototype.foo = ...`).\"\n },\n {\n \"heading\": \"6. Naming\",\n \"body\": \"- **Classes:** `UpperCamelCase`.\\n- **Methods & Functions:** `lowerCamelCase`.\\n- **Constants:** `CONSTANT_CASE` (all uppercase with underscores).\\n- **Non-constant Fields & Variables:** `lowerCamelCase`.\"\n },\n {\n \"heading\": \"7. JSDoc\",\n \"body\": \"- JSDoc is used on all classes, fields, and methods.\\n- Use `@param`, `@return`, `@override`, `@deprecated`.\\n- Type annotations are enclosed in braces (e.g., `/** @param {string} userName */`).\\n\\n*Source: [Google JavaScript Style Guide](https://google.github.io/styleguide/jsguide.html)*\"\n }\n ],\n \"languages\": [\n \"javascript\"\n ],\n \"frameworks\": [],\n \"file_patterns\": [],\n \"applies_to\": [\n \"planning\",\n \"implementation\",\n \"review\",\n \"tests\"\n ],\n \"rules\": [\n {\n \"id\": \"javascript-rule-1\",\n \"severity\": \"guidance\",\n \"summary\": \"**File Naming:** All lowercase, with underscores (`_`) or dashes (`-`). Extension must be `.js`.\"\n },\n {\n \"id\": \"javascript-rule-2\",\n \"severity\": \"guidance\",\n \"summary\": \"**File Encoding:** UTF-8.\"\n },\n {\n \"id\": \"javascript-rule-3\",\n \"severity\": \"guidance\",\n \"summary\": \"**Whitespace:** Use only ASCII horizontal spaces (0x20). Tabs are forbidden for indentation.\"\n },\n {\n \"id\": \"javascript-rule-4\",\n \"severity\": \"guidance\",\n \"summary\": \"New files should be ES modules (`import`/`export`).\"\n },\n {\n \"id\": \"javascript-rule-5\",\n \"severity\": \"guidance\",\n \"summary\": \"**Exports:** Use named exports (`export {MyClass};`). **Do not use default exports.**\"\n },\n {\n \"id\": \"javascript-rule-6\",\n \"severity\": \"guidance\",\n \"summary\": \"**Imports:** Do not use line-wrapped imports. The `.js` extension in import paths is mandatory.\"\n },\n {\n \"id\": \"javascript-rule-7\",\n \"severity\": \"guidance\",\n \"summary\": \"**Braces:** Required for all control structures (`if`, `for`, `while`, etc.), even single-line blocks. Use K&R style (\\\"Egyptian brackets\\\").\"\n },\n {\n \"id\": \"javascript-rule-8\",\n \"severity\": \"guidance\",\n \"summary\": \"**Indentation:** +2 spaces for each new block.\"\n },\n {\n \"id\": \"javascript-rule-9\",\n \"severity\": \"guidance\",\n \"summary\": \"**Semicolons:** Every statement must be terminated with a semicolon.\"\n },\n {\n \"id\": \"javascript-rule-10\",\n \"severity\": \"guidance\",\n \"summary\": \"**Column Limit:** 80 characters.\"\n },\n {\n \"id\": \"javascript-rule-11\",\n \"severity\": \"guidance\",\n \"summary\": \"**Line-wrapping:** Indent continuation lines at least +4 spaces.\"\n },\n {\n \"id\": \"javascript-rule-12\",\n \"severity\": \"guidance\",\n \"summary\": \"**Whitespace:** Use single blank lines between methods. No trailing whitespace.\"\n },\n {\n \"id\": \"javascript-rule-13\",\n \"severity\": \"guidance\",\n \"summary\": \"**Variable Declarations:** Use `const` by default, `let` if reassignment is needed. **`var` is forbidden.**\"\n },\n {\n \"id\": \"javascript-rule-14\",\n \"severity\": \"guidance\",\n \"summary\": \"**Array Literals:** Use trailing commas. Do not use the `Array` constructor.\"\n },\n {\n \"id\": \"javascript-rule-15\",\n \"severity\": \"guidance\",\n \"summary\": \"**Object Literals:** Use trailing commas and shorthand properties. Do not use the `Object` constructor.\"\n },\n {\n \"id\": \"javascript-rule-16\",\n \"severity\": \"guidance\",\n \"summary\": \"**Classes:** Do not use JavaScript getter/setter properties (`get name()`). Provide ordinary methods instead.\"\n },\n {\n \"id\": \"javascript-rule-17\",\n \"severity\": \"guidance\",\n \"summary\": \"**Functions:** Prefer arrow functions for nested functions to preserve `this` context.\"\n },\n {\n \"id\": \"javascript-rule-18\",\n \"severity\": \"guidance\",\n \"summary\": \"**String Literals:** Use single quotes (`'`). Use template literals (`` ` ``) for multi-line strings or complex interpolation.\"\n },\n {\n \"id\": \"javascript-rule-19\",\n \"severity\": \"guidance\",\n \"summary\": \"**Control Structures:** Prefer `for-of` loops. `for-in` loops should only be used on dict-style objects.\"\n },\n {\n \"id\": \"javascript-rule-20\",\n \"severity\": \"guidance\",\n \"summary\": \"**`this`:** Only use `this` in class constructors, methods, or in arrow functions defined within them.\"\n },\n {\n \"id\": \"javascript-rule-21\",\n \"severity\": \"guidance\",\n \"summary\": \"**Equality Checks:** Always use identity operators (`===` / `!==`).\"\n },\n {\n \"id\": \"javascript-rule-22\",\n \"severity\": \"guidance\",\n \"summary\": \"`with` keyword.\"\n },\n {\n \"id\": \"javascript-rule-23\",\n \"severity\": \"guidance\",\n \"summary\": \"`eval()` or `Function(...string)`.\"\n },\n {\n \"id\": \"javascript-rule-24\",\n \"severity\": \"guidance\",\n \"summary\": \"Automatic Semicolon Insertion.\"\n },\n {\n \"id\": \"javascript-rule-25\",\n \"severity\": \"guidance\",\n \"summary\": \"Modifying builtin objects (`Array.prototype.foo = ...`).\"\n },\n {\n \"id\": \"javascript-rule-26\",\n \"severity\": \"guidance\",\n \"summary\": \"**Classes:** `UpperCamelCase`.\"\n },\n {\n \"id\": \"javascript-rule-27\",\n \"severity\": \"guidance\",\n \"summary\": \"**Methods & Functions:** `lowerCamelCase`.\"\n },\n {\n \"id\": \"javascript-rule-28\",\n \"severity\": \"guidance\",\n \"summary\": \"**Constants:** `CONSTANT_CASE` (all uppercase with underscores).\"\n },\n {\n \"id\": \"javascript-rule-29\",\n \"severity\": \"guidance\",\n \"summary\": \"**Non-constant Fields & Variables:** `lowerCamelCase`.\"\n },\n {\n \"id\": \"javascript-rule-30\",\n \"severity\": \"guidance\",\n \"summary\": \"JSDoc is used on all classes, fields, and methods.\"\n },\n {\n \"id\": \"javascript-rule-31\",\n \"severity\": \"guidance\",\n \"summary\": \"Use `@param`, `@return`, `@override`, `@deprecated`.\"\n },\n {\n \"id\": \"javascript-rule-32\",\n \"severity\": \"guidance\",\n \"summary\": \"Type annotations are enclosed in braces (e.g., `/** @param {string} userName */`).\"\n }\n ],\n \"source\": \"bundled_template\"\n}\n","styleguides/kotlin.json":"{\n \"version\": 1,\n \"schema\": \"cadre.styleguide.v1\",\n \"kind\": \"styleguide\",\n \"id\": \"kotlin\",\n \"title\": \"Kotlin Coding Conventions Style Guide Summary\",\n \"summary\": \"This document summarizes key rules and best practices from the official Kotlin Coding Conventions and JetBrains style guide for writing idiomatic, concise, and safe Kotlin code.\",\n \"sections\": [\n {\n \"heading\": \"1. Formatting\",\n \"body\": \"- **ktlint / detekt:** Format with `ktlint` and lint with `detekt`. Enforce both in CI.\\n- **Indentation:** 4 spaces. No tabs. Continuation lines: 4 spaces (not 8).\\n- **Line Length:** 120 characters maximum (Kotlin convention; some projects use 100).\\n- **Trailing lambdas:** When the last parameter is a lambda, move it outside the parentheses. Omit the parentheses entirely if the lambda is the only parameter.\"\n },\n {\n \"heading\": \"2. Naming\",\n \"body\": \"- **`UpperCamelCase`:** For classes, objects, interfaces, and enum entries.\\n- **`lowerCamelCase`:** For functions, properties, local variables, and parameters.\\n- **`SCREAMING_SNAKE_CASE`:** For `const val` top-level and companion object constants only.\\n- **`_` prefix:** Do not use. Kotlin backing properties use `_name` as a convention for private backing fields exposed via a public property — this is the single accepted use.\\n- **Acronyms:** Use `UpperCamelCase` even for acronyms: `XmlParser`, `HttpClient`, not `XMLParser`.\\n- **Boolean properties:** Name as `isEnabled`, `hasError`, `canClose`. Prefix with `is`, `has`, or `can`.\\n- **Test functions:** Use backtick names for test readability: `` `should throw when user is null`() ``.\"\n },\n {\n \"heading\": \"3. Null Safety\",\n \"body\": \"- **Non-nullable by default:** Prefer non-nullable types. Add `?` only when `null` is a genuinely valid value.\\n- **Avoid `!!`:** The `!!` operator is a code smell. It bypasses null safety and throws `NullPointerException`. Use `?.`, `?:`, `let`, `also`, or explicit null checks instead.\\n- **`?.let { }`:** Use for null-conditional execution. Prefer `if (x != null)` when the block is long and `x` is used multiple times (smart cast).\\n- **Elvis operator `?:`:** Use for default values: `val name = user?.name ?: \\\"Anonymous\\\"`.\\n- **`requireNotNull` / `checkNotNull`:** Use to assert non-nullability at runtime with a clear message: `requireNotNull(user) { \\\"User must not be null\\\" }`.\"\n },\n {\n \"heading\": \"4. Classes and Objects\",\n \"body\": \"- **`data class`:** Use for classes that hold data. They get `equals`, `hashCode`, `toString`, `copy`, and `componentN` for free.\\n- **`sealed class`:** Use for closed type hierarchies (discriminated unions). Prefer `sealed class` over `enum class` when variants carry different data.\\n- **`object`:** Use for singletons and companion objects. Do not use a class with a private constructor + static `getInstance()`.\\n- **`companion object`:** Use for factory methods and constants logically associated with a class. Name the companion only if it will be referenced by name.\\n- **`val` over `var`:** Prefer immutable `val` properties. Use `var` only when mutation is necessary.\\n- **`init` blocks:** Minimize logic in `init` blocks. Prefer constructor parameter defaults and `lazy` properties.\\n- **`lazy`:** Use `by lazy { }` for properties that are expensive to compute and not always needed.\"\n },\n {\n \"heading\": \"5. Functions\",\n \"body\": \"- **Expression bodies:** Use `= expression` for single-expression functions. Omit braces and `return`.\\n- **Default parameter values:** Use default values instead of overloaded functions.\\n- **Named arguments:** Use named arguments when calling functions with many parameters or when the parameter type is a primitive and meaning is unclear.\\n- **Extension functions:** Use extension functions to add behavior to existing types without subclassing. Place extensions in a file named `TypeExtensions.kt`.\\n- **Scope functions (`let`, `run`, `with`, `apply`, `also`):**\\n - `apply`: Configure an object — use when returning the object. (`builder.apply { ... }`)\\n - `also`: Perform side effects — use when returning the object. (`list.also { log(it) }`)\\n - `let`: Transform a value, especially with nullability. (`str?.let { process(it) }`)\\n - `run`/`with`: Group a block of operations on an object. Prefer `run` for nullable receivers, `with` for non-null.\\n - **Do not nest scope functions more than 2 levels deep.**\\n- **`operator fun`:** Only implement operator overloads when the semantics are universally clear (e.g., `+` for numeric types, `get`/`set` for collections).\"\n },\n {\n \"heading\": \"6. Collections\",\n \"body\": \"- **Immutable collections:** Prefer `listOf`, `mapOf`, `setOf`. Use `mutableListOf` etc. only when mutation is needed.\\n- **`Sequence` for lazy pipelines:** Use `asSequence()` for long transformation chains on large collections to avoid creating intermediate lists.\\n- **Avoid `null` in collections:** Prefer `emptyList()` over `null` for absent collections. Use `filterNotNull()` to clean mixed lists.\\n- **`associate`, `groupBy`, `partition`:** Use the stdlib collection transforms instead of manual loops.\\n- **Destructuring:** Use destructuring declarations in `for` loops and `map` operations: `for ((key, value) in map)`.\"\n },\n {\n \"heading\": \"7. Coroutines\",\n \"body\": \"- **`suspend` functions:** Mark any function that calls another `suspend` function or performs async I/O as `suspend`. Do not block inside `suspend` functions — use `withContext(Dispatchers.IO)`.\\n- **Structured concurrency:** Always launch coroutines in a `CoroutineScope`. Never use `GlobalScope` in application code.\\n- **`Dispatchers.Main` / `.IO` / `.Default`:** Use the correct dispatcher — `Main` for UI, `IO` for blocking I/O, `Default` for CPU work.\\n- **`Flow`:** Use `Flow<T>` for streams of values. Use `StateFlow`/`SharedFlow` for hot streams. Call `.collect {}` in a lifecycle-aware scope.\\n- **Error handling:** Use `try/catch` inside coroutines. Use `CoroutineExceptionHandler` for unhandled exceptions in `launch`. `async`/`await` propagates exceptions at the `await` site.\\n- **`viewModelScope` / `lifecycleScope`:** Use these scopes in Android (see Android guide) to tie coroutine lifetime to the component.\"\n },\n {\n \"heading\": \"8. Error Handling\",\n \"body\": \"- **Exceptions for exceptional cases:** Do not use exceptions for normal control flow. Return `Result<T>`, `sealed class`, or nullable values for expected failure paths.\\n- **`runCatching`:** Use `runCatching { }` for concise try-catch with `Result<T>` return.\\n- **Avoid catching `Throwable`:** Catch specific exception types. Catching `Throwable` also catches `Error` (e.g., `OutOfMemoryError`).\"\n },\n {\n \"heading\": \"9. Documentation\",\n \"body\": \"- **KDoc (`/** */`):** Use KDoc for all public API documentation.\\n- **`@param`, `@return`, `@throws`:** Include these tags for public functions with non-obvious parameters or return values.\\n- **`@since`:** Mark API additions with `@since <version>`.\\n- **Avoid redundant comments:** Do not restate the function name in the doc. Add information about behavior, edge cases, or constraints.\\n\\n*Source: [Kotlin Coding Conventions](https://kotlinlang.org/docs/coding-conventions.html)*\"\n }\n ],\n \"languages\": [\n \"kotlin\"\n ],\n \"frameworks\": [],\n \"file_patterns\": [],\n \"applies_to\": [\n \"planning\",\n \"implementation\",\n \"review\",\n \"tests\"\n ],\n \"rules\": [\n {\n \"id\": \"kotlin-rule-1\",\n \"severity\": \"guidance\",\n \"summary\": \"**ktlint / detekt:** Format with `ktlint` and lint with `detekt`. Enforce both in CI.\"\n },\n {\n \"id\": \"kotlin-rule-2\",\n \"severity\": \"guidance\",\n \"summary\": \"**Indentation:** 4 spaces. No tabs. Continuation lines: 4 spaces (not 8).\"\n },\n {\n \"id\": \"kotlin-rule-3\",\n \"severity\": \"guidance\",\n \"summary\": \"**Line Length:** 120 characters maximum (Kotlin convention; some projects use 100).\"\n },\n {\n \"id\": \"kotlin-rule-4\",\n \"severity\": \"guidance\",\n \"summary\": \"**Trailing lambdas:** When the last parameter is a lambda, move it outside the parentheses. Omit the parentheses entirely if the lambda is the only parameter.\"\n },\n {\n \"id\": \"kotlin-rule-5\",\n \"severity\": \"guidance\",\n \"summary\": \"**`UpperCamelCase`:** For classes, objects, interfaces, and enum entries.\"\n },\n {\n \"id\": \"kotlin-rule-6\",\n \"severity\": \"guidance\",\n \"summary\": \"**`lowerCamelCase`:** For functions, properties, local variables, and parameters.\"\n },\n {\n \"id\": \"kotlin-rule-7\",\n \"severity\": \"guidance\",\n \"summary\": \"**`SCREAMING_SNAKE_CASE`:** For `const val` top-level and companion object constants only.\"\n },\n {\n \"id\": \"kotlin-rule-8\",\n \"severity\": \"guidance\",\n \"summary\": \"**`_` prefix:** Do not use. Kotlin backing properties use `_name` as a convention for private backing fields exposed via a public property — this is the single accepted use.\"\n },\n {\n \"id\": \"kotlin-rule-9\",\n \"severity\": \"guidance\",\n \"summary\": \"**Acronyms:** Use `UpperCamelCase` even for acronyms: `XmlParser`, `HttpClient`, not `XMLParser`.\"\n },\n {\n \"id\": \"kotlin-rule-10\",\n \"severity\": \"guidance\",\n \"summary\": \"**Boolean properties:** Name as `isEnabled`, `hasError`, `canClose`. Prefix with `is`, `has`, or `can`.\"\n },\n {\n \"id\": \"kotlin-rule-11\",\n \"severity\": \"guidance\",\n \"summary\": \"**Test functions:** Use backtick names for test readability: `` `should throw when user is null`() ``.\"\n },\n {\n \"id\": \"kotlin-rule-12\",\n \"severity\": \"guidance\",\n \"summary\": \"**Non-nullable by default:** Prefer non-nullable types. Add `?` only when `null` is a genuinely valid value.\"\n },\n {\n \"id\": \"kotlin-rule-13\",\n \"severity\": \"guidance\",\n \"summary\": \"**Avoid `!!`:** The `!!` operator is a code smell. It bypasses null safety and throws `NullPointerException`. Use `?.`, `?:`, `let`, `also`, or explicit null checks instead.\"\n },\n {\n \"id\": \"kotlin-rule-14\",\n \"severity\": \"guidance\",\n \"summary\": \"**`?.let { }`:** Use for null-conditional execution. Prefer `if (x != null)` when the block is long and `x` is used multiple times (smart cast).\"\n },\n {\n \"id\": \"kotlin-rule-15\",\n \"severity\": \"guidance\",\n \"summary\": \"**Elvis operator `?:`:** Use for default values: `val name = user?.name ?: \\\"Anonymous\\\"`.\"\n },\n {\n \"id\": \"kotlin-rule-16\",\n \"severity\": \"guidance\",\n \"summary\": \"**`requireNotNull` / `checkNotNull`:** Use to assert non-nullability at runtime with a clear message: `requireNotNull(user) { \\\"User must not be null\\\" }`.\"\n },\n {\n \"id\": \"kotlin-rule-17\",\n \"severity\": \"guidance\",\n \"summary\": \"**`data class`:** Use for classes that hold data. They get `equals`, `hashCode`, `toString`, `copy`, and `componentN` for free.\"\n },\n {\n \"id\": \"kotlin-rule-18\",\n \"severity\": \"guidance\",\n \"summary\": \"**`sealed class`:** Use for closed type hierarchies (discriminated unions). Prefer `sealed class` over `enum class` when variants carry different data.\"\n },\n {\n \"id\": \"kotlin-rule-19\",\n \"severity\": \"guidance\",\n \"summary\": \"**`object`:** Use for singletons and companion objects. Do not use a class with a private constructor + static `getInstance()`.\"\n },\n {\n \"id\": \"kotlin-rule-20\",\n \"severity\": \"guidance\",\n \"summary\": \"**`companion object`:** Use for factory methods and constants logically associated with a class. Name the companion only if it will be referenced by name.\"\n },\n {\n \"id\": \"kotlin-rule-21\",\n \"severity\": \"guidance\",\n \"summary\": \"**`val` over `var`:** Prefer immutable `val` properties. Use `var` only when mutation is necessary.\"\n },\n {\n \"id\": \"kotlin-rule-22\",\n \"severity\": \"guidance\",\n \"summary\": \"**`init` blocks:** Minimize logic in `init` blocks. Prefer constructor parameter defaults and `lazy` properties.\"\n },\n {\n \"id\": \"kotlin-rule-23\",\n \"severity\": \"guidance\",\n \"summary\": \"**`lazy`:** Use `by lazy { }` for properties that are expensive to compute and not always needed.\"\n },\n {\n \"id\": \"kotlin-rule-24\",\n \"severity\": \"guidance\",\n \"summary\": \"**Expression bodies:** Use `= expression` for single-expression functions. Omit braces and `return`.\"\n },\n {\n \"id\": \"kotlin-rule-25\",\n \"severity\": \"guidance\",\n \"summary\": \"**Default parameter values:** Use default values instead of overloaded functions.\"\n },\n {\n \"id\": \"kotlin-rule-26\",\n \"severity\": \"guidance\",\n \"summary\": \"**Named arguments:** Use named arguments when calling functions with many parameters or when the parameter type is a primitive and meaning is unclear.\"\n },\n {\n \"id\": \"kotlin-rule-27\",\n \"severity\": \"guidance\",\n \"summary\": \"**Extension functions:** Use extension functions to add behavior to existing types without subclassing. Place extensions in a file named `TypeExtensions.kt`.\"\n },\n {\n \"id\": \"kotlin-rule-28\",\n \"severity\": \"guidance\",\n \"summary\": \"**Scope functions (`let`, `run`, `with`, `apply`, `also`):**\"\n },\n {\n \"id\": \"kotlin-rule-29\",\n \"severity\": \"guidance\",\n \"summary\": \"`apply`: Configure an object — use when returning the object. (`builder.apply { ... }`)\"\n },\n {\n \"id\": \"kotlin-rule-30\",\n \"severity\": \"guidance\",\n \"summary\": \"`also`: Perform side effects — use when returning the object. (`list.also { log(it) }`)\"\n },\n {\n \"id\": \"kotlin-rule-31\",\n \"severity\": \"guidance\",\n \"summary\": \"`let`: Transform a value, especially with nullability. (`str?.let { process(it) }`)\"\n },\n {\n \"id\": \"kotlin-rule-32\",\n \"severity\": \"guidance\",\n \"summary\": \"`run`/`with`: Group a block of operations on an object. Prefer `run` for nullable receivers, `with` for non-null.\"\n },\n {\n \"id\": \"kotlin-rule-33\",\n \"severity\": \"guidance\",\n \"summary\": \"**Do not nest scope functions more than 2 levels deep.**\"\n },\n {\n \"id\": \"kotlin-rule-34\",\n \"severity\": \"guidance\",\n \"summary\": \"**`operator fun`:** Only implement operator overloads when the semantics are universally clear (e.g., `+` for numeric types, `get`/`set` for collections).\"\n },\n {\n \"id\": \"kotlin-rule-35\",\n \"severity\": \"guidance\",\n \"summary\": \"**Immutable collections:** Prefer `listOf`, `mapOf`, `setOf`. Use `mutableListOf` etc. only when mutation is needed.\"\n },\n {\n \"id\": \"kotlin-rule-36\",\n \"severity\": \"guidance\",\n \"summary\": \"**`Sequence` for lazy pipelines:** Use `asSequence()` for long transformation chains on large collections to avoid creating intermediate lists.\"\n },\n {\n \"id\": \"kotlin-rule-37\",\n \"severity\": \"guidance\",\n \"summary\": \"**Avoid `null` in collections:** Prefer `emptyList()` over `null` for absent collections. Use `filterNotNull()` to clean mixed lists.\"\n },\n {\n \"id\": \"kotlin-rule-38\",\n \"severity\": \"guidance\",\n \"summary\": \"**`associate`, `groupBy`, `partition`:** Use the stdlib collection transforms instead of manual loops.\"\n },\n {\n \"id\": \"kotlin-rule-39\",\n \"severity\": \"guidance\",\n \"summary\": \"**Destructuring:** Use destructuring declarations in `for` loops and `map` operations: `for ((key, value) in map)`.\"\n },\n {\n \"id\": \"kotlin-rule-40\",\n \"severity\": \"guidance\",\n \"summary\": \"**`suspend` functions:** Mark any function that calls another `suspend` function or performs async I/O as `suspend`. Do not block inside `suspend` functions — use `withContext(Dispatchers.IO)`.\"\n },\n {\n \"id\": \"kotlin-rule-41\",\n \"severity\": \"guidance\",\n \"summary\": \"**Structured concurrency:** Always launch coroutines in a `CoroutineScope`. Never use `GlobalScope` in application code.\"\n },\n {\n \"id\": \"kotlin-rule-42\",\n \"severity\": \"guidance\",\n \"summary\": \"**`Dispatchers.Main` / `.IO` / `.Default`:** Use the correct dispatcher — `Main` for UI, `IO` for blocking I/O, `Default` for CPU work.\"\n },\n {\n \"id\": \"kotlin-rule-43\",\n \"severity\": \"guidance\",\n \"summary\": \"**`Flow`:** Use `Flow<T>` for streams of values. Use `StateFlow`/`SharedFlow` for hot streams. Call `.collect {}` in a lifecycle-aware scope.\"\n },\n {\n \"id\": \"kotlin-rule-44\",\n \"severity\": \"guidance\",\n \"summary\": \"**Error handling:** Use `try/catch` inside coroutines. Use `CoroutineExceptionHandler` for unhandled exceptions in `launch`. `async`/`await` propagates exceptions at the `await` site.\"\n },\n {\n \"id\": \"kotlin-rule-45\",\n \"severity\": \"guidance\",\n \"summary\": \"**`viewModelScope` / `lifecycleScope`:** Use these scopes in Android (see Android guide) to tie coroutine lifetime to the component.\"\n },\n {\n \"id\": \"kotlin-rule-46\",\n \"severity\": \"guidance\",\n \"summary\": \"**Exceptions for exceptional cases:** Do not use exceptions for normal control flow. Return `Result<T>`, `sealed class`, or nullable values for expected failure paths.\"\n },\n {\n \"id\": \"kotlin-rule-47\",\n \"severity\": \"guidance\",\n \"summary\": \"**`runCatching`:** Use `runCatching { }` for concise try-catch with `Result<T>` return.\"\n },\n {\n \"id\": \"kotlin-rule-48\",\n \"severity\": \"guidance\",\n \"summary\": \"**Avoid catching `Throwable`:** Catch specific exception types. Catching `Throwable` also catches `Error` (e.g., `OutOfMemoryError`).\"\n },\n {\n \"id\": \"kotlin-rule-49\",\n \"severity\": \"guidance\",\n \"summary\": \"**KDoc (`/** */`):** Use KDoc for all public API documentation.\"\n },\n {\n \"id\": \"kotlin-rule-50\",\n \"severity\": \"guidance\",\n \"summary\": \"**`@param`, `@return`, `@throws`:** Include these tags for public functions with non-obvious parameters or return values.\"\n },\n {\n \"id\": \"kotlin-rule-51\",\n \"severity\": \"guidance\",\n \"summary\": \"**`@since`:** Mark API additions with `@since <version>`.\"\n },\n {\n \"id\": \"kotlin-rule-52\",\n \"severity\": \"guidance\",\n \"summary\": \"**Avoid redundant comments:** Do not restate the function name in the doc. Add information about behavior, edge cases, or constraints.\"\n }\n ],\n \"source\": \"bundled_template\"\n}\n","styleguides/python.json":"{\n \"version\": 1,\n \"schema\": \"cadre.styleguide.v1\",\n \"kind\": \"styleguide\",\n \"id\": \"python\",\n \"title\": \"Google Python Style Guide Summary\",\n \"summary\": \"This document summarizes key rules and best practices from the Google Python Style Guide.\",\n \"sections\": [\n {\n \"heading\": \"1. Python Language Rules\",\n \"body\": \"- **Linting:** Run `pylint` on your code to catch bugs and style issues.\\n- **Imports:** Use `import x` for packages/modules. Use `from x import y` only when `y` is a submodule.\\n- **Exceptions:** Use built-in exception classes. Do not use bare `except:` clauses.\\n- **Global State:** Avoid mutable global state. Module-level constants are okay and should be `ALL_CAPS_WITH_UNDERSCORES`.\\n- **Comprehensions:** Use for simple cases. Avoid for complex logic where a full loop is more readable.\\n- **Default Argument Values:** Do not use mutable objects (like `[]` or `{}`) as default values.\\n- **True/False Evaluations:** Use implicit false (e.g., `if not my_list:`). Use `if foo is None:` to check for `None`.\\n- **Type Annotations:** Strongly encouraged for all public APIs.\"\n },\n {\n \"heading\": \"2. Python Style Rules\",\n \"body\": \"- **Line Length:** Maximum 80 characters.\\n- **Indentation:** 4 spaces per indentation level. Never use tabs.\\n- **Blank Lines:** Two blank lines between top-level definitions (classes, functions). One blank line between method definitions.\\n- **Whitespace:** Avoid extraneous whitespace. Surround binary operators with single spaces.\\n- **Docstrings:** Use `\\\"\\\"\\\"triple double quotes\\\"\\\"\\\"`. Every public module, function, class, and method must have a docstring.\\n - **Format:** Start with a one-line summary. Include `Args:`, `Returns:`, and `Raises:` sections.\\n- **Strings:** Use f-strings for formatting. Be consistent with single (`'`) or double (`\\\"`) quotes.\\n- **`TODO` Comments:** Use `TODO(username): Fix this.` format.\\n- **Imports Formatting:** Imports should be on separate lines and grouped: standard library, third-party, and your own application's imports.\"\n },\n {\n \"heading\": \"3. Naming\",\n \"body\": \"- **General:** `snake_case` for modules, functions, methods, and variables.\\n- **Classes:** `PascalCase`.\\n- **Constants:** `ALL_CAPS_WITH_UNDERSCORES`.\\n- **Internal Use:** Use a single leading underscore (`_internal_variable`) for internal module/class members.\"\n },\n {\n \"heading\": \"4. Main\",\n \"body\": \"- All executable files should have a `main()` function that contains the main logic, called from a `if __name__ == '__main__':` block.\\n\\n**BE CONSISTENT.** When editing code, match the existing style.\\n\\n*Source: [Google Python Style Guide](https://google.github.io/styleguide/pyguide.html)*\"\n }\n ],\n \"languages\": [\n \"python\"\n ],\n \"frameworks\": [],\n \"file_patterns\": [],\n \"applies_to\": [\n \"planning\",\n \"implementation\",\n \"review\",\n \"tests\"\n ],\n \"rules\": [\n {\n \"id\": \"python-rule-1\",\n \"severity\": \"guidance\",\n \"summary\": \"**Linting:** Run `pylint` on your code to catch bugs and style issues.\"\n },\n {\n \"id\": \"python-rule-2\",\n \"severity\": \"guidance\",\n \"summary\": \"**Imports:** Use `import x` for packages/modules. Use `from x import y` only when `y` is a submodule.\"\n },\n {\n \"id\": \"python-rule-3\",\n \"severity\": \"guidance\",\n \"summary\": \"**Exceptions:** Use built-in exception classes. Do not use bare `except:` clauses.\"\n },\n {\n \"id\": \"python-rule-4\",\n \"severity\": \"guidance\",\n \"summary\": \"**Global State:** Avoid mutable global state. Module-level constants are okay and should be `ALL_CAPS_WITH_UNDERSCORES`.\"\n },\n {\n \"id\": \"python-rule-5\",\n \"severity\": \"guidance\",\n \"summary\": \"**Comprehensions:** Use for simple cases. Avoid for complex logic where a full loop is more readable.\"\n },\n {\n \"id\": \"python-rule-6\",\n \"severity\": \"guidance\",\n \"summary\": \"**Default Argument Values:** Do not use mutable objects (like `[]` or `{}`) as default values.\"\n },\n {\n \"id\": \"python-rule-7\",\n \"severity\": \"guidance\",\n \"summary\": \"**True/False Evaluations:** Use implicit false (e.g., `if not my_list:`). Use `if foo is None:` to check for `None`.\"\n },\n {\n \"id\": \"python-rule-8\",\n \"severity\": \"guidance\",\n \"summary\": \"**Type Annotations:** Strongly encouraged for all public APIs.\"\n },\n {\n \"id\": \"python-rule-9\",\n \"severity\": \"guidance\",\n \"summary\": \"**Line Length:** Maximum 80 characters.\"\n },\n {\n \"id\": \"python-rule-10\",\n \"severity\": \"guidance\",\n \"summary\": \"**Indentation:** 4 spaces per indentation level. Never use tabs.\"\n },\n {\n \"id\": \"python-rule-11\",\n \"severity\": \"guidance\",\n \"summary\": \"**Blank Lines:** Two blank lines between top-level definitions (classes, functions). One blank line between method definitions.\"\n },\n {\n \"id\": \"python-rule-12\",\n \"severity\": \"guidance\",\n \"summary\": \"**Whitespace:** Avoid extraneous whitespace. Surround binary operators with single spaces.\"\n },\n {\n \"id\": \"python-rule-13\",\n \"severity\": \"guidance\",\n \"summary\": \"**Docstrings:** Use `\\\"\\\"\\\"triple double quotes\\\"\\\"\\\"`. Every public module, function, class, and method must have a docstring.\"\n },\n {\n \"id\": \"python-rule-14\",\n \"severity\": \"guidance\",\n \"summary\": \"**Format:** Start with a one-line summary. Include `Args:`, `Returns:`, and `Raises:` sections.\"\n },\n {\n \"id\": \"python-rule-15\",\n \"severity\": \"guidance\",\n \"summary\": \"**Strings:** Use f-strings for formatting. Be consistent with single (`'`) or double (`\\\"`) quotes.\"\n },\n {\n \"id\": \"python-rule-16\",\n \"severity\": \"guidance\",\n \"summary\": \"**`TODO` Comments:** Use `TODO(username): Fix this.` format.\"\n },\n {\n \"id\": \"python-rule-17\",\n \"severity\": \"guidance\",\n \"summary\": \"**Imports Formatting:** Imports should be on separate lines and grouped: standard library, third-party, and your own application's imports.\"\n },\n {\n \"id\": \"python-rule-18\",\n \"severity\": \"guidance\",\n \"summary\": \"**General:** `snake_case` for modules, functions, methods, and variables.\"\n },\n {\n \"id\": \"python-rule-19\",\n \"severity\": \"guidance\",\n \"summary\": \"**Classes:** `PascalCase`.\"\n },\n {\n \"id\": \"python-rule-20\",\n \"severity\": \"guidance\",\n \"summary\": \"**Constants:** `ALL_CAPS_WITH_UNDERSCORES`.\"\n },\n {\n \"id\": \"python-rule-21\",\n \"severity\": \"guidance\",\n \"summary\": \"**Internal Use:** Use a single leading underscore (`_internal_variable`) for internal module/class members.\"\n },\n {\n \"id\": \"python-rule-22\",\n \"severity\": \"guidance\",\n \"summary\": \"All executable files should have a `main()` function that contains the main logic, called from a `if __name__ == '__main__':` block.\"\n }\n ],\n \"source\": \"bundled_template\"\n}\n","styleguides/rust.json":"{\n \"version\": 1,\n \"schema\": \"cadre.styleguide.v1\",\n \"kind\": \"styleguide\",\n \"id\": \"rust\",\n \"title\": \"Effective Rust Style Guide Summary\",\n \"summary\": \"This document summarizes key rules and best practices from the official Rust API Guidelines, Rust Style Guide, and idiomatic Rust conventions for writing safe, performant, and maintainable Rust code.\",\n \"sections\": [\n {\n \"heading\": \"1. Formatting\",\n \"body\": \"- **`rustfmt`:** All Rust code **must** be formatted with `rustfmt`. This is non-negotiable. Run via `cargo fmt`.\\n- **`clippy`:** Run `cargo clippy` and fix all warnings before review. Treat lints as errors in CI: `RUSTFLAGS=\\\"-D warnings\\\"`.\\n- **Indentation:** 4 spaces. No tabs.\\n- **Line Length:** 100 characters maximum (rustfmt default).\"\n },\n {\n \"heading\": \"2. Naming\",\n \"body\": \"- **`snake_case`:** For functions, methods, variables, modules, and crates.\\n- **`UpperCamelCase`:** For types, traits, enums, and struct names.\\n- **`SCREAMING_SNAKE_CASE`:** For constants and statics.\\n- **`snake_case`:** For crate names (hyphens in `Cargo.toml` map to underscores in code).\\n- **Acronyms:** Treat acronyms as words — `HttpClient`, not `HTTPClient`; `JsonParser`, not `JSONParser`.\\n- **Getters:** Do not prefix with `get_`. A getter for `name` is `name()`, not `get_name()`.\\n- **Setters:** Use `set_name()`.\\n- **Builders:** Use the `Builder` suffix and return `Self` or `Result<T>` from `build()`.\\n- **Iterator adaptors:** Name the struct for its iterator, e.g., `Lines` for a `lines()` method.\"\n },\n {\n \"heading\": \"3. Ownership and Borrowing\",\n \"body\": \"- **Prefer borrowing over cloning:** Pass `&T` or `&mut T` unless ownership transfer is required.\\n- **Prefer `&str` over `&String`:** Accept `&str` in function arguments; callers with `String` can deref. Same for `&[T]` over `&Vec<T>` and `&Path` over `&PathBuf`.\\n- **Minimize `clone()`:** A `clone()` call is a code smell if it can be avoided with a borrow.\\n- **Avoid `unwrap()` in library code:** Use `?` to propagate errors. Reserve `unwrap()` for prototypes, tests, or genuinely infallible paths (document why).\\n- **Use `expect()` over `unwrap()`** when a panic is intended: `expect(\\\"config file must exist\\\")` produces better diagnostics.\"\n },\n {\n \"heading\": \"4. Error Handling\",\n \"body\": \"- **`Result<T, E>` is the standard:** Use it for all fallible functions. Never silently discard errors.\\n- **`?` operator:** Use `?` to propagate errors up the call stack. Do not write `match` blocks for simple propagation.\\n- **Error types:** In libraries, define a custom error type implementing `std::error::Error`. Use `thiserror` crate. In applications, use `anyhow` for ergonomic error context.\\n- **`panic!`:** Reserved for unrecoverable programming errors (invariant violations). Libraries must not panic in normal operation.\\n- **`unwrap_or_else`, `map`, `and_then`:** Chain `Result`/`Option` combinators for concise, readable error paths.\"\n },\n {\n \"heading\": \"5. Types and Traits\",\n \"body\": \"- **Newtype pattern:** Wrap primitive types in newtypes to enforce invariants: `struct Meters(f64);`.\\n- **Derive common traits:** Derive `Debug`, `Clone`, `PartialEq`, `Eq`, `Hash`, `Default` where appropriate. Always derive `Debug`.\\n- **`Default` trait:** Implement `Default` for types that have a sensible zero/empty value. Use `#[derive(Default)]` when possible.\\n- **Trait objects vs. generics:** Prefer generics (`fn foo<T: Trait>(x: T)`) for performance. Use `dyn Trait` only when type erasure is needed (heterogeneous collections, dynamic dispatch).\\n- **`impl Trait` in return position:** Use for simple cases to hide concrete return types without boxing.\\n- **Sealed traits:** Use the sealed-trait pattern to prevent external implementations of traits not designed for extension.\\n- **Iterator:** Implement `Iterator` for custom collections. Return `impl Iterator` from methods rather than concrete types.\"\n },\n {\n \"heading\": \"6. Enums and Pattern Matching\",\n \"body\": \"- **Enums over booleans:** Prefer `enum Direction { Left, Right }` over `bool` for clarity.\\n- **`match` is exhaustive:** Always handle all variants. Prefer explicit arms over `_ =>` wildcards when variants may be added.\\n- **`if let` / `while let`:** Use for single-pattern matching instead of a full `match` block.\\n- **`Option` instead of null:** Never model absence with sentinel values. Use `Option<T>`.\\n- **Avoid nested `match`:** Flatten with combinators (`map`, `and_then`, `unwrap_or`) or `?`.\"\n },\n {\n \"heading\": \"7. Concurrency\",\n \"body\": \"- **Fearless concurrency:** Let the compiler enforce thread safety via `Send` and `Sync` bounds.\\n- **Prefer channels over shared state:** Use `std::sync::mpsc` or `tokio::sync` channels.\\n- **`Arc<Mutex<T>>`:** Standard pattern for shared mutable state. Lock for the minimum scope needed.\\n- **`async`/`await`:** Use for I/O-bound concurrency. Use `tokio` or `async-std` as the runtime. Do not block inside async functions — use `tokio::task::spawn_blocking` for CPU-bound work.\\n- **`rayon`:** Use for data-parallel CPU-bound work instead of manual threading.\"\n },\n {\n \"heading\": \"8. Modules and Visibility\",\n \"body\": \"- **`pub` is an API contract:** Only `pub` what is intended to be part of the public API. Default to private.\\n- **`pub(crate)`:** Use for items shared within a crate but not externally.\\n- **`mod.rs` vs. inline modules:** Prefer `module/mod.rs` for multi-file modules. Prefer inline `mod` for small, single-file submodules.\\n- **`use` declarations:** Group imports: std → external crates → local. Use `rustfmt` to sort.\\n- **Re-exports:** Re-export public types at the crate root to flatten the API surface.\"\n },\n {\n \"heading\": \"9. Performance\",\n \"body\": \"- **Zero-cost abstractions:** Trust iterators, closures, and generics — they compile to the same code as manual loops.\\n- **Avoid unnecessary allocation:** Prefer stack types and slices. Profile before switching to `Box`, `Vec`, or `Arc`.\\n- **`Cow<str>` / `Cow<[T]>`:** Use when a function sometimes needs to allocate and sometimes doesn't.\\n- **Inline:** Use `#[inline]` on small hot functions. Use `#[inline(always)]` sparingly.\"\n },\n {\n \"heading\": \"10. Documentation\",\n \"body\": \"- **`///` doc comments:** All public items **must** have doc comments. Include an example in `# Examples` for non-trivial functions.\\n- **`//!` module docs:** Add module-level documentation explaining purpose and usage.\\n- **`# Panics` / `# Errors` / `# Safety`:** Document these sections on any function that panics, returns `Result`, or is `unsafe`.\\n- **`cargo doc --open`:** Verify documentation renders correctly before publishing.\\n- **`unsafe` blocks:** Every `unsafe` block **must** have a `// SAFETY:` comment explaining why the invariants are upheld.\\n\\n*Sources: [Rust API Guidelines](https://rust-lang.github.io/api-guidelines/) · [Rust Style Guide](https://doc.rust-lang.org/nightly/style-guide/) · [The Rust Book](https://doc.rust-lang.org/book/)*\"\n }\n ],\n \"languages\": [\n \"rust\"\n ],\n \"frameworks\": [],\n \"file_patterns\": [],\n \"applies_to\": [\n \"planning\",\n \"implementation\",\n \"review\",\n \"tests\"\n ],\n \"rules\": [\n {\n \"id\": \"rust-rule-1\",\n \"severity\": \"guidance\",\n \"summary\": \"**`rustfmt`:** All Rust code **must** be formatted with `rustfmt`. This is non-negotiable. Run via `cargo fmt`.\"\n },\n {\n \"id\": \"rust-rule-2\",\n \"severity\": \"guidance\",\n \"summary\": \"**`clippy`:** Run `cargo clippy` and fix all warnings before review. Treat lints as errors in CI: `RUSTFLAGS=\\\"-D warnings\\\"`.\"\n },\n {\n \"id\": \"rust-rule-3\",\n \"severity\": \"guidance\",\n \"summary\": \"**Indentation:** 4 spaces. No tabs.\"\n },\n {\n \"id\": \"rust-rule-4\",\n \"severity\": \"guidance\",\n \"summary\": \"**Line Length:** 100 characters maximum (rustfmt default).\"\n },\n {\n \"id\": \"rust-rule-5\",\n \"severity\": \"guidance\",\n \"summary\": \"**`snake_case`:** For functions, methods, variables, modules, and crates.\"\n },\n {\n \"id\": \"rust-rule-6\",\n \"severity\": \"guidance\",\n \"summary\": \"**`UpperCamelCase`:** For types, traits, enums, and struct names.\"\n },\n {\n \"id\": \"rust-rule-7\",\n \"severity\": \"guidance\",\n \"summary\": \"**`SCREAMING_SNAKE_CASE`:** For constants and statics.\"\n },\n {\n \"id\": \"rust-rule-8\",\n \"severity\": \"guidance\",\n \"summary\": \"**`snake_case`:** For crate names (hyphens in `Cargo.toml` map to underscores in code).\"\n },\n {\n \"id\": \"rust-rule-9\",\n \"severity\": \"guidance\",\n \"summary\": \"**Acronyms:** Treat acronyms as words — `HttpClient`, not `HTTPClient`; `JsonParser`, not `JSONParser`.\"\n },\n {\n \"id\": \"rust-rule-10\",\n \"severity\": \"guidance\",\n \"summary\": \"**Getters:** Do not prefix with `get_`. A getter for `name` is `name()`, not `get_name()`.\"\n },\n {\n \"id\": \"rust-rule-11\",\n \"severity\": \"guidance\",\n \"summary\": \"**Setters:** Use `set_name()`.\"\n },\n {\n \"id\": \"rust-rule-12\",\n \"severity\": \"guidance\",\n \"summary\": \"**Builders:** Use the `Builder` suffix and return `Self` or `Result<T>` from `build()`.\"\n },\n {\n \"id\": \"rust-rule-13\",\n \"severity\": \"guidance\",\n \"summary\": \"**Iterator adaptors:** Name the struct for its iterator, e.g., `Lines` for a `lines()` method.\"\n },\n {\n \"id\": \"rust-rule-14\",\n \"severity\": \"guidance\",\n \"summary\": \"**Prefer borrowing over cloning:** Pass `&T` or `&mut T` unless ownership transfer is required.\"\n },\n {\n \"id\": \"rust-rule-15\",\n \"severity\": \"guidance\",\n \"summary\": \"**Prefer `&str` over `&String`:** Accept `&str` in function arguments; callers with `String` can deref. Same for `&[T]` over `&Vec<T>` and `&Path` over `&PathBuf`.\"\n },\n {\n \"id\": \"rust-rule-16\",\n \"severity\": \"guidance\",\n \"summary\": \"**Minimize `clone()`:** A `clone()` call is a code smell if it can be avoided with a borrow.\"\n },\n {\n \"id\": \"rust-rule-17\",\n \"severity\": \"guidance\",\n \"summary\": \"**Avoid `unwrap()` in library code:** Use `?` to propagate errors. Reserve `unwrap()` for prototypes, tests, or genuinely infallible paths (document why).\"\n },\n {\n \"id\": \"rust-rule-18\",\n \"severity\": \"guidance\",\n \"summary\": \"**Use `expect()` over `unwrap()`** when a panic is intended: `expect(\\\"config file must exist\\\")` produces better diagnostics.\"\n },\n {\n \"id\": \"rust-rule-19\",\n \"severity\": \"guidance\",\n \"summary\": \"**`Result<T, E>` is the standard:** Use it for all fallible functions. Never silently discard errors.\"\n },\n {\n \"id\": \"rust-rule-20\",\n \"severity\": \"guidance\",\n \"summary\": \"**`?` operator:** Use `?` to propagate errors up the call stack. Do not write `match` blocks for simple propagation.\"\n },\n {\n \"id\": \"rust-rule-21\",\n \"severity\": \"guidance\",\n \"summary\": \"**Error types:** In libraries, define a custom error type implementing `std::error::Error`. Use `thiserror` crate. In applications, use `anyhow` for ergonomic error context.\"\n },\n {\n \"id\": \"rust-rule-22\",\n \"severity\": \"guidance\",\n \"summary\": \"**`panic!`:** Reserved for unrecoverable programming errors (invariant violations). Libraries must not panic in normal operation.\"\n },\n {\n \"id\": \"rust-rule-23\",\n \"severity\": \"guidance\",\n \"summary\": \"**`unwrap_or_else`, `map`, `and_then`:** Chain `Result`/`Option` combinators for concise, readable error paths.\"\n },\n {\n \"id\": \"rust-rule-24\",\n \"severity\": \"guidance\",\n \"summary\": \"**Newtype pattern:** Wrap primitive types in newtypes to enforce invariants: `struct Meters(f64);`.\"\n },\n {\n \"id\": \"rust-rule-25\",\n \"severity\": \"guidance\",\n \"summary\": \"**Derive common traits:** Derive `Debug`, `Clone`, `PartialEq`, `Eq`, `Hash`, `Default` where appropriate. Always derive `Debug`.\"\n },\n {\n \"id\": \"rust-rule-26\",\n \"severity\": \"guidance\",\n \"summary\": \"**`Default` trait:** Implement `Default` for types that have a sensible zero/empty value. Use `#[derive(Default)]` when possible.\"\n },\n {\n \"id\": \"rust-rule-27\",\n \"severity\": \"guidance\",\n \"summary\": \"**Trait objects vs. generics:** Prefer generics (`fn foo<T: Trait>(x: T)`) for performance. Use `dyn Trait` only when type erasure is needed (heterogeneous collections, dynamic dispatch).\"\n },\n {\n \"id\": \"rust-rule-28\",\n \"severity\": \"guidance\",\n \"summary\": \"**`impl Trait` in return position:** Use for simple cases to hide concrete return types without boxing.\"\n },\n {\n \"id\": \"rust-rule-29\",\n \"severity\": \"guidance\",\n \"summary\": \"**Sealed traits:** Use the sealed-trait pattern to prevent external implementations of traits not designed for extension.\"\n },\n {\n \"id\": \"rust-rule-30\",\n \"severity\": \"guidance\",\n \"summary\": \"**Iterator:** Implement `Iterator` for custom collections. Return `impl Iterator` from methods rather than concrete types.\"\n },\n {\n \"id\": \"rust-rule-31\",\n \"severity\": \"guidance\",\n \"summary\": \"**Enums over booleans:** Prefer `enum Direction { Left, Right }` over `bool` for clarity.\"\n },\n {\n \"id\": \"rust-rule-32\",\n \"severity\": \"guidance\",\n \"summary\": \"**`match` is exhaustive:** Always handle all variants. Prefer explicit arms over `_ =>` wildcards when variants may be added.\"\n },\n {\n \"id\": \"rust-rule-33\",\n \"severity\": \"guidance\",\n \"summary\": \"**`if let` / `while let`:** Use for single-pattern matching instead of a full `match` block.\"\n },\n {\n \"id\": \"rust-rule-34\",\n \"severity\": \"guidance\",\n \"summary\": \"**`Option` instead of null:** Never model absence with sentinel values. Use `Option<T>`.\"\n },\n {\n \"id\": \"rust-rule-35\",\n \"severity\": \"guidance\",\n \"summary\": \"**Avoid nested `match`:** Flatten with combinators (`map`, `and_then`, `unwrap_or`) or `?`.\"\n },\n {\n \"id\": \"rust-rule-36\",\n \"severity\": \"guidance\",\n \"summary\": \"**Fearless concurrency:** Let the compiler enforce thread safety via `Send` and `Sync` bounds.\"\n },\n {\n \"id\": \"rust-rule-37\",\n \"severity\": \"guidance\",\n \"summary\": \"**Prefer channels over shared state:** Use `std::sync::mpsc` or `tokio::sync` channels.\"\n },\n {\n \"id\": \"rust-rule-38\",\n \"severity\": \"guidance\",\n \"summary\": \"**`Arc<Mutex<T>>`:** Standard pattern for shared mutable state. Lock for the minimum scope needed.\"\n },\n {\n \"id\": \"rust-rule-39\",\n \"severity\": \"guidance\",\n \"summary\": \"**`async`/`await`:** Use for I/O-bound concurrency. Use `tokio` or `async-std` as the runtime. Do not block inside async functions — use `tokio::task::spawn_blocking` for CPU-bound work.\"\n },\n {\n \"id\": \"rust-rule-40\",\n \"severity\": \"guidance\",\n \"summary\": \"**`rayon`:** Use for data-parallel CPU-bound work instead of manual threading.\"\n },\n {\n \"id\": \"rust-rule-41\",\n \"severity\": \"guidance\",\n \"summary\": \"**`pub` is an API contract:** Only `pub` what is intended to be part of the public API. Default to private.\"\n },\n {\n \"id\": \"rust-rule-42\",\n \"severity\": \"guidance\",\n \"summary\": \"**`pub(crate)`:** Use for items shared within a crate but not externally.\"\n },\n {\n \"id\": \"rust-rule-43\",\n \"severity\": \"guidance\",\n \"summary\": \"**`mod.rs` vs. inline modules:** Prefer `module/mod.rs` for multi-file modules. Prefer inline `mod` for small, single-file submodules.\"\n },\n {\n \"id\": \"rust-rule-44\",\n \"severity\": \"guidance\",\n \"summary\": \"**`use` declarations:** Group imports: std → external crates → local. Use `rustfmt` to sort.\"\n },\n {\n \"id\": \"rust-rule-45\",\n \"severity\": \"guidance\",\n \"summary\": \"**Re-exports:** Re-export public types at the crate root to flatten the API surface.\"\n },\n {\n \"id\": \"rust-rule-46\",\n \"severity\": \"guidance\",\n \"summary\": \"**Zero-cost abstractions:** Trust iterators, closures, and generics — they compile to the same code as manual loops.\"\n },\n {\n \"id\": \"rust-rule-47\",\n \"severity\": \"guidance\",\n \"summary\": \"**Avoid unnecessary allocation:** Prefer stack types and slices. Profile before switching to `Box`, `Vec`, or `Arc`.\"\n },\n {\n \"id\": \"rust-rule-48\",\n \"severity\": \"guidance\",\n \"summary\": \"**`Cow<str>` / `Cow<[T]>`:** Use when a function sometimes needs to allocate and sometimes doesn't.\"\n },\n {\n \"id\": \"rust-rule-49\",\n \"severity\": \"guidance\",\n \"summary\": \"**Inline:** Use `#[inline]` on small hot functions. Use `#[inline(always)]` sparingly.\"\n },\n {\n \"id\": \"rust-rule-50\",\n \"severity\": \"guidance\",\n \"summary\": \"**`///` doc comments:** All public items **must** have doc comments. Include an example in `# Examples` for non-trivial functions.\"\n },\n {\n \"id\": \"rust-rule-51\",\n \"severity\": \"guidance\",\n \"summary\": \"**`//!` module docs:** Add module-level documentation explaining purpose and usage.\"\n },\n {\n \"id\": \"rust-rule-52\",\n \"severity\": \"guidance\",\n \"summary\": \"**`# Panics` / `# Errors` / `# Safety`:** Document these sections on any function that panics, returns `Result`, or is `unsafe`.\"\n },\n {\n \"id\": \"rust-rule-53\",\n \"severity\": \"guidance\",\n \"summary\": \"**`cargo doc --open`:** Verify documentation renders correctly before publishing.\"\n },\n {\n \"id\": \"rust-rule-54\",\n \"severity\": \"guidance\",\n \"summary\": \"**`unsafe` blocks:** Every `unsafe` block **must** have a `// SAFETY:` comment explaining why the invariants are upheld.\"\n }\n ],\n \"source\": \"bundled_template\"\n}\n","styleguides/swift.json":"{\n \"version\": 1,\n \"schema\": \"cadre.styleguide.v1\",\n \"kind\": \"styleguide\",\n \"id\": \"swift\",\n \"title\": \"Swift API Design Guidelines Style Guide Summary\",\n \"summary\": \"This document summarizes key rules and best practices from the Swift API Design Guidelines and Swift.org style conventions for writing idiomatic, safe, and expressive Swift code.\",\n \"sections\": [\n {\n \"heading\": \"1. Formatting\",\n \"body\": \"- **SwiftFormat / SwiftLint:** Format with `swiftformat` and lint with `swiftlint`. Enforce both in CI. Include `.swiftlint.yml` in the repository root.\\n- **Indentation:** 4 spaces. No tabs.\\n- **Line Length:** 120 characters maximum (SwiftLint default; adjust to team preference).\\n- **Blank lines:** One blank line between declarations. Two blank lines between major sections (e.g., before `// MARK:` sections).\"\n },\n {\n \"heading\": \"2. Naming\",\n \"body\": \"- **`UpperCamelCase`:** For types (class, struct, enum, protocol, typealias) and enum cases.\\n- **`lowerCamelCase`:** For functions, methods, properties, parameters, and local variables.\\n- **Clarity at the call site:** Name things so usage reads like prose: `list.insert(element, at: index)`, not `list.insert(element, position: index)`.\\n- **Omit needless words:** Do not repeat the type in the name. `backgroundColor`, not `backgroundColorOfView`. `users.remove(at: index)`, not `users.removeElement(at: index)`.\\n- **Boolean properties:** Start with `is`, `has`, `can`, or `should`: `isEnabled`, `hasChildren`, `canClose`.\\n- **Protocol naming:**\\n - Protocols describing what something *is*: noun (`Collection`, `Sequence`).\\n - Protocols describing a *capability*: `-able`, `-ible`, `-ing` suffix (`Hashable`, `Codable`, `Equatable`).\\n- **Avoid abbreviations:** Use full words. `destinationURL` not `destURL`, `error` not `err`, `index` not `idx`. Well-known abbreviations (`URL`, `ID`, `JSON`) are fine.\\n- **First argument label:** Omit when it is obviously part of the function name: `x.addSubview(y)` not `x.addSubview(view: y)`. Include when it adds clarity: `a.move(from: b, to: c)`.\"\n },\n {\n \"heading\": \"3. Types\",\n \"body\": \"- **`struct` by default:** Prefer value types (`struct`, `enum`) over reference types (`class`). Use `class` only when identity semantics, inheritance, or reference sharing is required.\\n- **`final` by default:** Mark classes `final` unless designed for subclassing. Subclassable classes are a design decision, not a default.\\n- **`enum` for closed sets:** Use `enum` for a fixed set of related values. Use `CaseIterable` when you need to enumerate cases.\\n- **Associated values:** Use `enum` with associated values as discriminated unions: `enum Result<T> { case success(T); case failure(Error) }`.\\n- **`typealias`:** Use to clarify the role of complex types: `typealias Completion = (Result<User, Error>) -> Void`.\\n- **`extension` over subclass:** Prefer extending a type to add behavior over subclassing. Extensions cannot store state — use composition for that.\"\n },\n {\n \"heading\": \"4. Optionals\",\n \"body\": \"- **Avoid `!` force-unwrap:** Force-unwrap is a crash waiting to happen. Use `guard let`, `if let`, or `??` instead.\\n- **`guard let` for early exit:** Use `guard let` to unwrap optionals at the top of a function when `nil` means \\\"cannot proceed\\\". This reduces nesting.\\n- **`if let` for optional use:** Use `if let` when the `nil` case is a legitimate alternate path.\\n- **Optional chaining (`?.`):** Use for accessing properties/methods on optionals where `nil` propagation is correct.\\n- **`??` for defaults:** Use the nil-coalescing operator for fallback values: `let name = user?.name ?? \\\"Unknown\\\"`.\\n- **Implicit optionals (`!` type):** Use `@IBOutlet weak var button: UIButton!` and similarly initialized-before-use patterns — keep to `@IBOutlet` and injection patterns only. Never use `!` types for general logic.\"\n },\n {\n \"heading\": \"5. Functions and Closures\",\n \"body\": \"- **Single responsibility:** Each function does one thing. Break down large functions.\\n- **`@discardableResult`:** Add only when ignoring the result is a common and correct pattern. Do not add it to silence warnings mechanically.\\n- **Trailing closure syntax:** Use trailing closure syntax when the closure is the last parameter and its role is clear: `UIView.animate(withDuration: 0.3) { ... }`.\\n- **`@escaping`:** Mark closures `@escaping` when they outlive the function call. Document the lifecycle implications.\\n- **`inout`:** Use `inout` sparingly. Prefer returning a new value over mutating in place unless performance is critical.\\n- **`throws` / `async throws`:** Use `throws` for functions that can fail with typed errors. Use `async` for asynchronous work. Combine as `async throws` for async-fallible functions.\"\n },\n {\n \"heading\": \"6. Error Handling\",\n \"body\": \"- **`throws` + `try`:** Use Swift's typed error handling for recoverable errors. Functions that can fail return via `throw`, not via optional or sentinel values.\\n- **`do / catch`:** Handle errors at the appropriate layer. Do not `try!` unless a failure is genuinely impossible and you can prove it.\\n- **`Result<T, Error>`:** Use `Result` for asynchronous completions that predate `async/await`, or when you need to store a result for later.\\n- **Custom error types:** Define `enum MyError: Error, LocalizedError` with associated values for structured error information. Implement `errorDescription` for user-facing messages.\\n- **`try?`:** Use when `nil` on failure is acceptable and the error is irrelevant to the caller.\"\n },\n {\n \"heading\": \"7. Concurrency (Swift Concurrency)\",\n \"body\": \"- **`async`/`await`:** Prefer Swift Concurrency over completion handlers, Combine, or DispatchQueue-based async code for new code.\\n- **`Task { }`:** Use to bridge from synchronous to async context. Use `Task.detached` only when the task must not inherit actor context.\\n- **`@MainActor`:** Annotate types or functions that must run on the main thread. Use `@MainActor` on ViewModels/Controllers rather than `DispatchQueue.main.async`.\\n- **`actor`:** Use `actor` types for shared mutable state. Actors serialize access and eliminate data races.\\n- **`Sendable`:** Mark types crossing actor boundaries as `Sendable`. Do not suppress `Sendable` warnings with `@unchecked Sendable` without justification.\\n- **`async let`:** Use `async let` for independent concurrent work within a function: `async let user = fetchUser(); async let feed = fetchFeed(); let (u, f) = try await (user, feed)`.\"\n },\n {\n \"heading\": \"8. Memory Management\",\n \"body\": \"- **ARC is automatic:** Do not call `retain`/`release`. ARC handles memory.\\n- **`weak` for delegates and callbacks:** Mark delegate properties `weak var` to avoid retain cycles. Capture `[weak self]` in closures that outlive the object.\\n- **`unowned` only when guaranteed:** Use `unowned` instead of `weak` only when the referenced object is guaranteed to outlive the closure/property. Incorrect `unowned` crashes; incorrect `weak` just produces `nil`.\\n- **`[weak self]` + guard:** Pattern: `{ [weak self] in guard let self = self else { return } ... }` (or `[weak self] in self?.doWork()`).\"\n },\n {\n \"heading\": \"9. Collections and Functional Patterns\",\n \"body\": \"- **`map`, `filter`, `compactMap`, `reduce`:** Use functional transforms over `for` loops for collection transformations.\\n- **`compactMap`:** Use to filter `nil` from a sequence of optionals: `names.compactMap { user(id: $0)?.name }`.\\n- **`flatMap` on sequences:** Use to flatten sequences: `[[1,2],[3,4]].flatMap { $0 }` → `[1,2,3,4]`.\\n- **`lazy`:** Use `collection.lazy.filter { }.map { }` to avoid allocating intermediate arrays for long pipelines.\"\n },\n {\n \"heading\": \"10. Documentation\",\n \"body\": \"- **`///` doc comments:** Use triple-slash comments for all public API. Xcode renders these in Quick Help.\\n- **Summary + discussion:** First line is the summary. Add a blank line then the discussion for longer explanations.\\n- **`- Parameter`, `- Returns`, `- Throws`:** Document parameters, return values, and thrown errors using these list items.\\n- **`- Note:`, `- Important:`, `- Warning:`:** Use callout keywords for additional reader guidance.\\n- **Code examples:** Include brief usage examples in doc comments for complex APIs using fenced code blocks.\\n\\n*Sources: [Swift API Design Guidelines](https://swift.org/documentation/api-design-guidelines/) · [Swift.org Style Guide](https://google.github.io/swift/) · [Swift Concurrency](https://docs.swift.org/swift-book/documentation/the-swift-programming-language/concurrency/)*\"\n }\n ],\n \"languages\": [\n \"swift\"\n ],\n \"frameworks\": [],\n \"file_patterns\": [],\n \"applies_to\": [\n \"planning\",\n \"implementation\",\n \"review\",\n \"tests\"\n ],\n \"rules\": [\n {\n \"id\": \"swift-rule-1\",\n \"severity\": \"guidance\",\n \"summary\": \"**SwiftFormat / SwiftLint:** Format with `swiftformat` and lint with `swiftlint`. Enforce both in CI. Include `.swiftlint.yml` in the repository root.\"\n },\n {\n \"id\": \"swift-rule-2\",\n \"severity\": \"guidance\",\n \"summary\": \"**Indentation:** 4 spaces. No tabs.\"\n },\n {\n \"id\": \"swift-rule-3\",\n \"severity\": \"guidance\",\n \"summary\": \"**Line Length:** 120 characters maximum (SwiftLint default; adjust to team preference).\"\n },\n {\n \"id\": \"swift-rule-4\",\n \"severity\": \"guidance\",\n \"summary\": \"**Blank lines:** One blank line between declarations. Two blank lines between major sections (e.g., before `// MARK:` sections).\"\n },\n {\n \"id\": \"swift-rule-5\",\n \"severity\": \"guidance\",\n \"summary\": \"**`UpperCamelCase`:** For types (class, struct, enum, protocol, typealias) and enum cases.\"\n },\n {\n \"id\": \"swift-rule-6\",\n \"severity\": \"guidance\",\n \"summary\": \"**`lowerCamelCase`:** For functions, methods, properties, parameters, and local variables.\"\n },\n {\n \"id\": \"swift-rule-7\",\n \"severity\": \"guidance\",\n \"summary\": \"**Clarity at the call site:** Name things so usage reads like prose: `list.insert(element, at: index)`, not `list.insert(element, position: index)`.\"\n },\n {\n \"id\": \"swift-rule-8\",\n \"severity\": \"guidance\",\n \"summary\": \"**Omit needless words:** Do not repeat the type in the name. `backgroundColor`, not `backgroundColorOfView`. `users.remove(at: index)`, not `users.removeElement(at: index)`.\"\n },\n {\n \"id\": \"swift-rule-9\",\n \"severity\": \"guidance\",\n \"summary\": \"**Boolean properties:** Start with `is`, `has`, `can`, or `should`: `isEnabled`, `hasChildren`, `canClose`.\"\n },\n {\n \"id\": \"swift-rule-10\",\n \"severity\": \"guidance\",\n \"summary\": \"**Protocol naming:**\"\n },\n {\n \"id\": \"swift-rule-11\",\n \"severity\": \"guidance\",\n \"summary\": \"Protocols describing what something *is*: noun (`Collection`, `Sequence`).\"\n },\n {\n \"id\": \"swift-rule-12\",\n \"severity\": \"guidance\",\n \"summary\": \"Protocols describing a *capability*: `-able`, `-ible`, `-ing` suffix (`Hashable`, `Codable`, `Equatable`).\"\n },\n {\n \"id\": \"swift-rule-13\",\n \"severity\": \"guidance\",\n \"summary\": \"**Avoid abbreviations:** Use full words. `destinationURL` not `destURL`, `error` not `err`, `index` not `idx`. Well-known abbreviations (`URL`, `ID`, `JSON`) are fine.\"\n },\n {\n \"id\": \"swift-rule-14\",\n \"severity\": \"guidance\",\n \"summary\": \"**First argument label:** Omit when it is obviously part of the function name: `x.addSubview(y)` not `x.addSubview(view: y)`. Include when it adds clarity: `a.move(from: b, to: c)`.\"\n },\n {\n \"id\": \"swift-rule-15\",\n \"severity\": \"guidance\",\n \"summary\": \"**`struct` by default:** Prefer value types (`struct`, `enum`) over reference types (`class`). Use `class` only when identity semantics, inheritance, or reference sharing is required.\"\n },\n {\n \"id\": \"swift-rule-16\",\n \"severity\": \"guidance\",\n \"summary\": \"**`final` by default:** Mark classes `final` unless designed for subclassing. Subclassable classes are a design decision, not a default.\"\n },\n {\n \"id\": \"swift-rule-17\",\n \"severity\": \"guidance\",\n \"summary\": \"**`enum` for closed sets:** Use `enum` for a fixed set of related values. Use `CaseIterable` when you need to enumerate cases.\"\n },\n {\n \"id\": \"swift-rule-18\",\n \"severity\": \"guidance\",\n \"summary\": \"**Associated values:** Use `enum` with associated values as discriminated unions: `enum Result<T> { case success(T); case failure(Error) }`.\"\n },\n {\n \"id\": \"swift-rule-19\",\n \"severity\": \"guidance\",\n \"summary\": \"**`typealias`:** Use to clarify the role of complex types: `typealias Completion = (Result<User, Error>) -> Void`.\"\n },\n {\n \"id\": \"swift-rule-20\",\n \"severity\": \"guidance\",\n \"summary\": \"**`extension` over subclass:** Prefer extending a type to add behavior over subclassing. Extensions cannot store state — use composition for that.\"\n },\n {\n \"id\": \"swift-rule-21\",\n \"severity\": \"guidance\",\n \"summary\": \"**Avoid `!` force-unwrap:** Force-unwrap is a crash waiting to happen. Use `guard let`, `if let`, or `??` instead.\"\n },\n {\n \"id\": \"swift-rule-22\",\n \"severity\": \"guidance\",\n \"summary\": \"**`guard let` for early exit:** Use `guard let` to unwrap optionals at the top of a function when `nil` means \\\"cannot proceed\\\". This reduces nesting.\"\n },\n {\n \"id\": \"swift-rule-23\",\n \"severity\": \"guidance\",\n \"summary\": \"**`if let` for optional use:** Use `if let` when the `nil` case is a legitimate alternate path.\"\n },\n {\n \"id\": \"swift-rule-24\",\n \"severity\": \"guidance\",\n \"summary\": \"**Optional chaining (`?.`):** Use for accessing properties/methods on optionals where `nil` propagation is correct.\"\n },\n {\n \"id\": \"swift-rule-25\",\n \"severity\": \"guidance\",\n \"summary\": \"**`??` for defaults:** Use the nil-coalescing operator for fallback values: `let name = user?.name ?? \\\"Unknown\\\"`.\"\n },\n {\n \"id\": \"swift-rule-26\",\n \"severity\": \"guidance\",\n \"summary\": \"**Implicit optionals (`!` type):** Use `@IBOutlet weak var button: UIButton!` and similarly initialized-before-use patterns — keep to `@IBOutlet` and injection patterns only. Never use `!` types for general logic.\"\n },\n {\n \"id\": \"swift-rule-27\",\n \"severity\": \"guidance\",\n \"summary\": \"**Single responsibility:** Each function does one thing. Break down large functions.\"\n },\n {\n \"id\": \"swift-rule-28\",\n \"severity\": \"guidance\",\n \"summary\": \"**`@discardableResult`:** Add only when ignoring the result is a common and correct pattern. Do not add it to silence warnings mechanically.\"\n },\n {\n \"id\": \"swift-rule-29\",\n \"severity\": \"guidance\",\n \"summary\": \"**Trailing closure syntax:** Use trailing closure syntax when the closure is the last parameter and its role is clear: `UIView.animate(withDuration: 0.3) { ... }`.\"\n },\n {\n \"id\": \"swift-rule-30\",\n \"severity\": \"guidance\",\n \"summary\": \"**`@escaping`:** Mark closures `@escaping` when they outlive the function call. Document the lifecycle implications.\"\n },\n {\n \"id\": \"swift-rule-31\",\n \"severity\": \"guidance\",\n \"summary\": \"**`inout`:** Use `inout` sparingly. Prefer returning a new value over mutating in place unless performance is critical.\"\n },\n {\n \"id\": \"swift-rule-32\",\n \"severity\": \"guidance\",\n \"summary\": \"**`throws` / `async throws`:** Use `throws` for functions that can fail with typed errors. Use `async` for asynchronous work. Combine as `async throws` for async-fallible functions.\"\n },\n {\n \"id\": \"swift-rule-33\",\n \"severity\": \"guidance\",\n \"summary\": \"**`throws` + `try`:** Use Swift's typed error handling for recoverable errors. Functions that can fail return via `throw`, not via optional or sentinel values.\"\n },\n {\n \"id\": \"swift-rule-34\",\n \"severity\": \"guidance\",\n \"summary\": \"**`do / catch`:** Handle errors at the appropriate layer. Do not `try!` unless a failure is genuinely impossible and you can prove it.\"\n },\n {\n \"id\": \"swift-rule-35\",\n \"severity\": \"guidance\",\n \"summary\": \"**`Result<T, Error>`:** Use `Result` for asynchronous completions that predate `async/await`, or when you need to store a result for later.\"\n },\n {\n \"id\": \"swift-rule-36\",\n \"severity\": \"guidance\",\n \"summary\": \"**Custom error types:** Define `enum MyError: Error, LocalizedError` with associated values for structured error information. Implement `errorDescription` for user-facing messages.\"\n },\n {\n \"id\": \"swift-rule-37\",\n \"severity\": \"guidance\",\n \"summary\": \"**`try?`:** Use when `nil` on failure is acceptable and the error is irrelevant to the caller.\"\n },\n {\n \"id\": \"swift-rule-38\",\n \"severity\": \"guidance\",\n \"summary\": \"**`async`/`await`:** Prefer Swift Concurrency over completion handlers, Combine, or DispatchQueue-based async code for new code.\"\n },\n {\n \"id\": \"swift-rule-39\",\n \"severity\": \"guidance\",\n \"summary\": \"**`Task { }`:** Use to bridge from synchronous to async context. Use `Task.detached` only when the task must not inherit actor context.\"\n },\n {\n \"id\": \"swift-rule-40\",\n \"severity\": \"guidance\",\n \"summary\": \"**`@MainActor`:** Annotate types or functions that must run on the main thread. Use `@MainActor` on ViewModels/Controllers rather than `DispatchQueue.main.async`.\"\n },\n {\n \"id\": \"swift-rule-41\",\n \"severity\": \"guidance\",\n \"summary\": \"**`actor`:** Use `actor` types for shared mutable state. Actors serialize access and eliminate data races.\"\n },\n {\n \"id\": \"swift-rule-42\",\n \"severity\": \"guidance\",\n \"summary\": \"**`Sendable`:** Mark types crossing actor boundaries as `Sendable`. Do not suppress `Sendable` warnings with `@unchecked Sendable` without justification.\"\n },\n {\n \"id\": \"swift-rule-43\",\n \"severity\": \"guidance\",\n \"summary\": \"**`async let`:** Use `async let` for independent concurrent work within a function: `async let user = fetchUser(); async let feed = fetchFeed(); let (u, f) = try await (user, feed)`.\"\n },\n {\n \"id\": \"swift-rule-44\",\n \"severity\": \"guidance\",\n \"summary\": \"**ARC is automatic:** Do not call `retain`/`release`. ARC handles memory.\"\n },\n {\n \"id\": \"swift-rule-45\",\n \"severity\": \"guidance\",\n \"summary\": \"**`weak` for delegates and callbacks:** Mark delegate properties `weak var` to avoid retain cycles. Capture `[weak self]` in closures that outlive the object.\"\n },\n {\n \"id\": \"swift-rule-46\",\n \"severity\": \"guidance\",\n \"summary\": \"**`unowned` only when guaranteed:** Use `unowned` instead of `weak` only when the referenced object is guaranteed to outlive the closure/property. Incorrect `unowned` crashes; incorrect `weak` just produces `nil`.\"\n },\n {\n \"id\": \"swift-rule-47\",\n \"severity\": \"guidance\",\n \"summary\": \"**`[weak self]` + guard:** Pattern: `{ [weak self] in guard let self = self else { return } ... }` (or `[weak self] in self?.doWork()`).\"\n },\n {\n \"id\": \"swift-rule-48\",\n \"severity\": \"guidance\",\n \"summary\": \"**`map`, `filter`, `compactMap`, `reduce`:** Use functional transforms over `for` loops for collection transformations.\"\n },\n {\n \"id\": \"swift-rule-49\",\n \"severity\": \"guidance\",\n \"summary\": \"**`compactMap`:** Use to filter `nil` from a sequence of optionals: `names.compactMap { user(id: $0)?.name }`.\"\n },\n {\n \"id\": \"swift-rule-50\",\n \"severity\": \"guidance\",\n \"summary\": \"**`flatMap` on sequences:** Use to flatten sequences: `[[1,2],[3,4]].flatMap { $0 }` → `[1,2,3,4]`.\"\n },\n {\n \"id\": \"swift-rule-51\",\n \"severity\": \"guidance\",\n \"summary\": \"**`lazy`:** Use `collection.lazy.filter { }.map { }` to avoid allocating intermediate arrays for long pipelines.\"\n },\n {\n \"id\": \"swift-rule-52\",\n \"severity\": \"guidance\",\n \"summary\": \"**`///` doc comments:** Use triple-slash comments for all public API. Xcode renders these in Quick Help.\"\n },\n {\n \"id\": \"swift-rule-53\",\n \"severity\": \"guidance\",\n \"summary\": \"**Summary + discussion:** First line is the summary. Add a blank line then the discussion for longer explanations.\"\n },\n {\n \"id\": \"swift-rule-54\",\n \"severity\": \"guidance\",\n \"summary\": \"**`- Parameter`, `- Returns`, `- Throws`:** Document parameters, return values, and thrown errors using these list items.\"\n },\n {\n \"id\": \"swift-rule-55\",\n \"severity\": \"guidance\",\n \"summary\": \"**`- Note:`, `- Important:`, `- Warning:`:** Use callout keywords for additional reader guidance.\"\n },\n {\n \"id\": \"swift-rule-56\",\n \"severity\": \"guidance\",\n \"summary\": \"**Code examples:** Include brief usage examples in doc comments for complex APIs using fenced code blocks.\"\n }\n ],\n \"source\": \"bundled_template\"\n}\n","styleguides/swiftui.json":"{\n \"version\": 1,\n \"schema\": \"cadre.styleguide.v1\",\n \"kind\": \"styleguide\",\n \"id\": \"swiftui\",\n \"title\": \"Effective SwiftUI Style Guide Summary\",\n \"summary\": \"This document summarizes key rules and best practices for writing idiomatic SwiftUI code, building on Swift API Design Guidelines with SwiftUI-specific view, state, and composition conventions.\",\n \"sections\": [\n {\n \"heading\": \"1. Formatting and Tooling\",\n \"body\": \"- **SwiftFormat:** Format all SwiftUI code with `swiftformat`. Add `.swiftformat` config to the repo.\\n- **SwiftLint:** Enforce with `.swiftlint.yml`. Treat all errors as CI failures.\\n- **Trailing closures and `ViewBuilder`:** Use trailing closure syntax for all `ViewBuilder` content parameters — this is the SwiftUI idiom.\\n- **`// MARK:` sections:** Organize view files with `// MARK: - Body`, `// MARK: - Subviews`, `// MARK: - View Model` sections for long files.\"\n },\n {\n \"heading\": \"2. View Design\",\n \"body\": \"- **Small, composable views:** Decompose complex `body` implementations into private child views or separate `View` structs. A `body` over ~30 lines should be split.\\n- **`some View` return type:** Always use `some View` as the return type of `body`. Do not erase to `AnyView` without a concrete reason.\\n- **`AnyView` avoidance:** `AnyView` disables SwiftUI's diff engine. Use conditional views, `Group`, or `@ViewBuilder` functions instead. If `AnyView` is unavoidable, contain it to a single call site.\\n- **`@ViewBuilder` functions:** Extract reusable sub-trees into `@ViewBuilder` private methods or standalone `View` structs. Prefer structs for views reused across files.\\n- **Previews:** Every view **must** have a `#Preview` (or `PreviewProvider`). Include multiple preview variants: light/dark, different data states (empty, loaded, error), and different device sizes.\"\n },\n {\n \"heading\": \"3. State Management\",\n \"body\": \"- **Choose the right property wrapper:**\\n - `@State`: Local, view-owned, value-type state. Keep it minimal and view-specific.\\n - `@Binding`: Pass mutable state down from a parent. Never derive a `@Binding` from a computed property.\\n - `@StateObject`: Own a reference-type observable object for the lifetime of this view subtree.\\n - `@ObservedObject`: Receive an observable object from a parent. The parent owns its lifetime.\\n - `@EnvironmentObject`: Inject a shared object through the view hierarchy. Use for app-wide state (user session, theme, router).\\n - `@Environment`: Read system values (`\\\\.colorScheme`, `\\\\.dismiss`, `\\\\.locale`) and custom environment keys.\\n- **Observation (`@Observable`):** In iOS 17+, prefer `@Observable` macro over `ObservableObject`/`@Published` — it is more efficient (only the accessed properties trigger redraws).\\n- **Minimize `@State`:** Lift state up to the smallest common ancestor that needs it. Do not put everything in the root view.\\n- **No logic in `body`:** Move business logic, data transformations, and side effects into the ViewModel or a computed property. `body` should be pure view construction.\"\n },\n {\n \"heading\": \"4. ViewModel Pattern\",\n \"body\": \"- **`@Observable` / `ObservableObject` ViewModel:** Each screen has a ViewModel that is `@Observable` (iOS 17+) or `ObservableObject`. The view is a thin rendering layer.\\n- **`@StateObject` for injection:** Create the ViewModel in the view that owns it with `@StateObject var vm = MyViewModel()`. Pass to children via `@ObservedObject` or `@EnvironmentObject`.\\n- **`@MainActor` on ViewModels:** Annotate the ViewModel class with `@MainActor` to ensure all published property updates occur on the main thread.\\n- **Async tasks via `Task`:** Trigger async operations from `.task { }` modifier (cancelled automatically on view disappearance) or `Task { }` in response to user actions.\\n- **`.onAppear` vs `.task`:** Prefer `.task { }` for async work (auto-cancels). Use `.onAppear` only for synchronous side effects.\"\n },\n {\n \"heading\": \"5. Layout and Composition\",\n \"body\": \"- **Use modifiers in the right order:** Modifier order matters in SwiftUI. Background and border go before padding; padding before frame.\\n ```swift\\n Text(\\\"Hello\\\")\\n .background(Color.blue) // applies to text bounds\\n .padding() // then pads\\n .border(Color.red) // border around padded area\\n ```\\n- **`Group` for applying modifiers to multiple views:** Use `Group { }` to apply the same modifier to several views without a container.\\n- **`ViewThatFits`:** Use for adaptive layouts that switch between compact and expanded presentations.\\n- **`LazyVStack` / `LazyHStack` / `LazyVGrid`:** Use lazy containers for long or dynamically-loaded lists. Use eager `VStack`/`HStack` only for short, fixed-count content.\\n- **`GeometryReader` sparingly:** `GeometryReader` takes all available space and can break layouts. Prefer `containerRelativeFrame` (iOS 17+), `frame(maxWidth: .infinity)`, or `Layout` protocol instead.\\n- **`Spacer()` vs fixed spacing:** Use `Spacer()` to push views apart in a stack. Use `.padding()` or `.frame(height: 8)` for fixed spacing.\"\n },\n {\n \"heading\": \"6. Navigation\",\n \"body\": \"- **`NavigationStack`:** Use `NavigationStack` (iOS 16+) over `NavigationView`. Use path-based navigation for programmatic control: `NavigationStack(path: $path)`.\\n- **`navigationDestination(for:)`:** Register destinations with `.navigationDestination(for: MyType.self)` and drive navigation by appending to the path.\\n- **`NavigationPath`:** Use for heterogeneous navigation stacks. Use typed `[MyRoute]` arrays when all destinations are the same type.\\n- **`.sheet`, `.fullScreenCover`, `.popover`:** Control presentation with `@State var isPresented = false` and `item:`-based variants for associated data.\\n- **Avoid `NavigationLink(isActive:)`:** Deprecated in iOS 16+. Use path-based navigation instead.\"\n },\n {\n \"heading\": \"7. Animation\",\n \"body\": \"- **`withAnimation { }`:** Wrap state changes that should animate in `withAnimation`. Prefer this over `.animation(_:value:)` on views.\\n- **`.animation(_:value:)`:** Use on a view when only that view should animate in response to a specific state value changing.\\n- **Explicit animations over implicit:** Prefer `withAnimation(.spring())` triggered by state changes over `.animation(.spring())` on views — explicit animations are more predictable.\\n- **`matchedGeometryEffect`:** Use for hero animations between views. Always pair with a shared `@Namespace`.\\n- **`Animatable` and `AnimatableModifier`:** Implement for custom animations on non-standard properties.\"\n },\n {\n \"heading\": \"8. Performance\",\n \"body\": \"- **`Equatable` views:** Make views `Equatable` and use `.equatable()` to skip redraws when input is unchanged.\\n- **Stable identities in `ForEach`:** Pass stable `Identifiable` models or explicit `id:` parameters. Avoid `ForEach(items, id: \\\\.self)` for complex objects — use a proper `id` property.\\n- **Avoid heavy computation in `body`:** Any expensive computation in `body` runs on every redraw. Move to a stored property or the ViewModel.\\n- **`@Observable` over `ObservableObject`:** `@Observable` tracks property access precisely — only views that read a changed property redraw. `@Published` triggers redraws for all observers of any property change.\\n- **`task(id:)`:** Use `task(id: someValue) { }` to restart async work when a value changes, instead of `onChange(of:) { Task { ... } }`.\"\n },\n {\n \"heading\": \"9. Accessibility\",\n \"body\": \"- **`.accessibilityLabel`:** Every interactive element and image must have an accessibility label.\\n- **`.accessibilityHint`:** Add hints for non-obvious actions: `.accessibilityHint(\\\"Double-tap to expand details\\\")`.\\n- **`.accessibilityElement(children: .combine)`:** Group visually related elements into a single accessible element.\\n- **Dynamic Type:** Use semantic text styles (`.font(.headline)`) not fixed sizes. Test with the largest and smallest Dynamic Type sizes.\\n- **Color contrast:** Do not convey information with color alone. Use labels, icons, or patterns as secondary indicators.\"\n },\n {\n \"heading\": \"10. File and Code Organization\",\n \"body\": \"- **One view per file:** Each top-level `View` struct lives in its own file.\\n- **File naming:** File name matches the type name: `UserProfileView.swift`.\\n- **Extension for subviews:** Place private subviews in an `extension` at the bottom of the same file:\\n ```swift\\n // MARK: - Subviews\\n private extension UserProfileView {\\n var headerSection: some View { ... }\\n }\\n ```\\n- **Feature folder structure:** `Features/Auth/`, `Features/Home/` — group screens, ViewModels, and models by feature.\\n- **Shared components:** Place reusable design-system components in `Components/` or a dedicated Swift package.\\n\\n*Sources: [SwiftUI Documentation](https://developer.apple.com/documentation/swiftui) · [Swift API Design Guidelines](https://swift.org/documentation/api-design-guidelines/) · [Observation framework](https://developer.apple.com/documentation/observation)*\"\n }\n ],\n \"languages\": [\n \"swiftui\"\n ],\n \"frameworks\": [],\n \"file_patterns\": [],\n \"applies_to\": [\n \"planning\",\n \"implementation\",\n \"review\",\n \"tests\"\n ],\n \"rules\": [\n {\n \"id\": \"swiftui-rule-1\",\n \"severity\": \"guidance\",\n \"summary\": \"**SwiftFormat:** Format all SwiftUI code with `swiftformat`. Add `.swiftformat` config to the repo.\"\n },\n {\n \"id\": \"swiftui-rule-2\",\n \"severity\": \"guidance\",\n \"summary\": \"**SwiftLint:** Enforce with `.swiftlint.yml`. Treat all errors as CI failures.\"\n },\n {\n \"id\": \"swiftui-rule-3\",\n \"severity\": \"guidance\",\n \"summary\": \"**Trailing closures and `ViewBuilder`:** Use trailing closure syntax for all `ViewBuilder` content parameters — this is the SwiftUI idiom.\"\n },\n {\n \"id\": \"swiftui-rule-4\",\n \"severity\": \"guidance\",\n \"summary\": \"**`// MARK:` sections:** Organize view files with `// MARK: - Body`, `// MARK: - Subviews`, `// MARK: - View Model` sections for long files.\"\n },\n {\n \"id\": \"swiftui-rule-5\",\n \"severity\": \"guidance\",\n \"summary\": \"**Small, composable views:** Decompose complex `body` implementations into private child views or separate `View` structs. A `body` over ~30 lines should be split.\"\n },\n {\n \"id\": \"swiftui-rule-6\",\n \"severity\": \"guidance\",\n \"summary\": \"**`some View` return type:** Always use `some View` as the return type of `body`. Do not erase to `AnyView` without a concrete reason.\"\n },\n {\n \"id\": \"swiftui-rule-7\",\n \"severity\": \"guidance\",\n \"summary\": \"**`AnyView` avoidance:** `AnyView` disables SwiftUI's diff engine. Use conditional views, `Group`, or `@ViewBuilder` functions instead. If `AnyView` is unavoidable, contain it to a single call site.\"\n },\n {\n \"id\": \"swiftui-rule-8\",\n \"severity\": \"guidance\",\n \"summary\": \"**`@ViewBuilder` functions:** Extract reusable sub-trees into `@ViewBuilder` private methods or standalone `View` structs. Prefer structs for views reused across files.\"\n },\n {\n \"id\": \"swiftui-rule-9\",\n \"severity\": \"guidance\",\n \"summary\": \"**Previews:** Every view **must** have a `#Preview` (or `PreviewProvider`). Include multiple preview variants: light/dark, different data states (empty, loaded, error), and different device sizes.\"\n },\n {\n \"id\": \"swiftui-rule-10\",\n \"severity\": \"guidance\",\n \"summary\": \"**Choose the right property wrapper:**\"\n },\n {\n \"id\": \"swiftui-rule-11\",\n \"severity\": \"guidance\",\n \"summary\": \"`@State`: Local, view-owned, value-type state. Keep it minimal and view-specific.\"\n },\n {\n \"id\": \"swiftui-rule-12\",\n \"severity\": \"guidance\",\n \"summary\": \"`@Binding`: Pass mutable state down from a parent. Never derive a `@Binding` from a computed property.\"\n },\n {\n \"id\": \"swiftui-rule-13\",\n \"severity\": \"guidance\",\n \"summary\": \"`@StateObject`: Own a reference-type observable object for the lifetime of this view subtree.\"\n },\n {\n \"id\": \"swiftui-rule-14\",\n \"severity\": \"guidance\",\n \"summary\": \"`@ObservedObject`: Receive an observable object from a parent. The parent owns its lifetime.\"\n },\n {\n \"id\": \"swiftui-rule-15\",\n \"severity\": \"guidance\",\n \"summary\": \"`@EnvironmentObject`: Inject a shared object through the view hierarchy. Use for app-wide state (user session, theme, router).\"\n },\n {\n \"id\": \"swiftui-rule-16\",\n \"severity\": \"guidance\",\n \"summary\": \"`@Environment`: Read system values (`\\\\.colorScheme`, `\\\\.dismiss`, `\\\\.locale`) and custom environment keys.\"\n },\n {\n \"id\": \"swiftui-rule-17\",\n \"severity\": \"guidance\",\n \"summary\": \"**Observation (`@Observable`):** In iOS 17+, prefer `@Observable` macro over `ObservableObject`/`@Published` — it is more efficient (only the accessed properties trigger redraws).\"\n },\n {\n \"id\": \"swiftui-rule-18\",\n \"severity\": \"guidance\",\n \"summary\": \"**Minimize `@State`:** Lift state up to the smallest common ancestor that needs it. Do not put everything in the root view.\"\n },\n {\n \"id\": \"swiftui-rule-19\",\n \"severity\": \"guidance\",\n \"summary\": \"**No logic in `body`:** Move business logic, data transformations, and side effects into the ViewModel or a computed property. `body` should be pure view construction.\"\n },\n {\n \"id\": \"swiftui-rule-20\",\n \"severity\": \"guidance\",\n \"summary\": \"**`@Observable` / `ObservableObject` ViewModel:** Each screen has a ViewModel that is `@Observable` (iOS 17+) or `ObservableObject`. The view is a thin rendering layer.\"\n },\n {\n \"id\": \"swiftui-rule-21\",\n \"severity\": \"guidance\",\n \"summary\": \"**`@StateObject` for injection:** Create the ViewModel in the view that owns it with `@StateObject var vm = MyViewModel()`. Pass to children via `@ObservedObject` or `@EnvironmentObject`.\"\n },\n {\n \"id\": \"swiftui-rule-22\",\n \"severity\": \"guidance\",\n \"summary\": \"**`@MainActor` on ViewModels:** Annotate the ViewModel class with `@MainActor` to ensure all published property updates occur on the main thread.\"\n },\n {\n \"id\": \"swiftui-rule-23\",\n \"severity\": \"guidance\",\n \"summary\": \"**Async tasks via `Task`:** Trigger async operations from `.task { }` modifier (cancelled automatically on view disappearance) or `Task { }` in response to user actions.\"\n },\n {\n \"id\": \"swiftui-rule-24\",\n \"severity\": \"guidance\",\n \"summary\": \"**`.onAppear` vs `.task`:** Prefer `.task { }` for async work (auto-cancels). Use `.onAppear` only for synchronous side effects.\"\n },\n {\n \"id\": \"swiftui-rule-25\",\n \"severity\": \"guidance\",\n \"summary\": \"**Use modifiers in the right order:** Modifier order matters in SwiftUI. Background and border go before padding; padding before frame.\"\n },\n {\n \"id\": \"swiftui-rule-26\",\n \"severity\": \"guidance\",\n \"summary\": \"**`Group` for applying modifiers to multiple views:** Use `Group { }` to apply the same modifier to several views without a container.\"\n },\n {\n \"id\": \"swiftui-rule-27\",\n \"severity\": \"guidance\",\n \"summary\": \"**`ViewThatFits`:** Use for adaptive layouts that switch between compact and expanded presentations.\"\n },\n {\n \"id\": \"swiftui-rule-28\",\n \"severity\": \"guidance\",\n \"summary\": \"**`LazyVStack` / `LazyHStack` / `LazyVGrid`:** Use lazy containers for long or dynamically-loaded lists. Use eager `VStack`/`HStack` only for short, fixed-count content.\"\n },\n {\n \"id\": \"swiftui-rule-29\",\n \"severity\": \"guidance\",\n \"summary\": \"**`GeometryReader` sparingly:** `GeometryReader` takes all available space and can break layouts. Prefer `containerRelativeFrame` (iOS 17+), `frame(maxWidth: .infinity)`, or `Layout` protocol instead.\"\n },\n {\n \"id\": \"swiftui-rule-30\",\n \"severity\": \"guidance\",\n \"summary\": \"**`Spacer()` vs fixed spacing:** Use `Spacer()` to push views apart in a stack. Use `.padding()` or `.frame(height: 8)` for fixed spacing.\"\n },\n {\n \"id\": \"swiftui-rule-31\",\n \"severity\": \"guidance\",\n \"summary\": \"**`NavigationStack`:** Use `NavigationStack` (iOS 16+) over `NavigationView`. Use path-based navigation for programmatic control: `NavigationStack(path: $path)`.\"\n },\n {\n \"id\": \"swiftui-rule-32\",\n \"severity\": \"guidance\",\n \"summary\": \"**`navigationDestination(for:)`:** Register destinations with `.navigationDestination(for: MyType.self)` and drive navigation by appending to the path.\"\n },\n {\n \"id\": \"swiftui-rule-33\",\n \"severity\": \"guidance\",\n \"summary\": \"**`NavigationPath`:** Use for heterogeneous navigation stacks. Use typed `[MyRoute]` arrays when all destinations are the same type.\"\n },\n {\n \"id\": \"swiftui-rule-34\",\n \"severity\": \"guidance\",\n \"summary\": \"**`.sheet`, `.fullScreenCover`, `.popover`:** Control presentation with `@State var isPresented = false` and `item:`-based variants for associated data.\"\n },\n {\n \"id\": \"swiftui-rule-35\",\n \"severity\": \"guidance\",\n \"summary\": \"**Avoid `NavigationLink(isActive:)`:** Deprecated in iOS 16+. Use path-based navigation instead.\"\n },\n {\n \"id\": \"swiftui-rule-36\",\n \"severity\": \"guidance\",\n \"summary\": \"**`withAnimation { }`:** Wrap state changes that should animate in `withAnimation`. Prefer this over `.animation(_:value:)` on views.\"\n },\n {\n \"id\": \"swiftui-rule-37\",\n \"severity\": \"guidance\",\n \"summary\": \"**`.animation(_:value:)`:** Use on a view when only that view should animate in response to a specific state value changing.\"\n },\n {\n \"id\": \"swiftui-rule-38\",\n \"severity\": \"guidance\",\n \"summary\": \"**Explicit animations over implicit:** Prefer `withAnimation(.spring())` triggered by state changes over `.animation(.spring())` on views — explicit animations are more predictable.\"\n },\n {\n \"id\": \"swiftui-rule-39\",\n \"severity\": \"guidance\",\n \"summary\": \"**`matchedGeometryEffect`:** Use for hero animations between views. Always pair with a shared `@Namespace`.\"\n },\n {\n \"id\": \"swiftui-rule-40\",\n \"severity\": \"guidance\",\n \"summary\": \"**`Animatable` and `AnimatableModifier`:** Implement for custom animations on non-standard properties.\"\n },\n {\n \"id\": \"swiftui-rule-41\",\n \"severity\": \"guidance\",\n \"summary\": \"**`Equatable` views:** Make views `Equatable` and use `.equatable()` to skip redraws when input is unchanged.\"\n },\n {\n \"id\": \"swiftui-rule-42\",\n \"severity\": \"guidance\",\n \"summary\": \"**Stable identities in `ForEach`:** Pass stable `Identifiable` models or explicit `id:` parameters. Avoid `ForEach(items, id: \\\\.self)` for complex objects — use a proper `id` property.\"\n },\n {\n \"id\": \"swiftui-rule-43\",\n \"severity\": \"guidance\",\n \"summary\": \"**Avoid heavy computation in `body`:** Any expensive computation in `body` runs on every redraw. Move to a stored property or the ViewModel.\"\n },\n {\n \"id\": \"swiftui-rule-44\",\n \"severity\": \"guidance\",\n \"summary\": \"**`@Observable` over `ObservableObject`:** `@Observable` tracks property access precisely — only views that read a changed property redraw. `@Published` triggers redraws for all observers of any property change.\"\n },\n {\n \"id\": \"swiftui-rule-45\",\n \"severity\": \"guidance\",\n \"summary\": \"**`task(id:)`:** Use `task(id: someValue) { }` to restart async work when a value changes, instead of `onChange(of:) { Task { ... } }`.\"\n },\n {\n \"id\": \"swiftui-rule-46\",\n \"severity\": \"guidance\",\n \"summary\": \"**`.accessibilityLabel`:** Every interactive element and image must have an accessibility label.\"\n },\n {\n \"id\": \"swiftui-rule-47\",\n \"severity\": \"guidance\",\n \"summary\": \"**`.accessibilityHint`:** Add hints for non-obvious actions: `.accessibilityHint(\\\"Double-tap to expand details\\\")`.\"\n },\n {\n \"id\": \"swiftui-rule-48\",\n \"severity\": \"guidance\",\n \"summary\": \"**`.accessibilityElement(children: .combine)`:** Group visually related elements into a single accessible element.\"\n },\n {\n \"id\": \"swiftui-rule-49\",\n \"severity\": \"guidance\",\n \"summary\": \"**Dynamic Type:** Use semantic text styles (`.font(.headline)`) not fixed sizes. Test with the largest and smallest Dynamic Type sizes.\"\n },\n {\n \"id\": \"swiftui-rule-50\",\n \"severity\": \"guidance\",\n \"summary\": \"**Color contrast:** Do not convey information with color alone. Use labels, icons, or patterns as secondary indicators.\"\n },\n {\n \"id\": \"swiftui-rule-51\",\n \"severity\": \"guidance\",\n \"summary\": \"**One view per file:** Each top-level `View` struct lives in its own file.\"\n },\n {\n \"id\": \"swiftui-rule-52\",\n \"severity\": \"guidance\",\n \"summary\": \"**File naming:** File name matches the type name: `UserProfileView.swift`.\"\n },\n {\n \"id\": \"swiftui-rule-53\",\n \"severity\": \"guidance\",\n \"summary\": \"**Extension for subviews:** Place private subviews in an `extension` at the bottom of the same file:\"\n },\n {\n \"id\": \"swiftui-rule-54\",\n \"severity\": \"guidance\",\n \"summary\": \"**Feature folder structure:** `Features/Auth/`, `Features/Home/` — group screens, ViewModels, and models by feature.\"\n },\n {\n \"id\": \"swiftui-rule-55\",\n \"severity\": \"guidance\",\n \"summary\": \"**Shared components:** Place reusable design-system components in `Components/` or a dedicated Swift package.\"\n }\n ],\n \"source\": \"bundled_template\"\n}\n","styleguides/typescript.json":"{\n \"version\": 1,\n \"schema\": \"cadre.styleguide.v1\",\n \"kind\": \"styleguide\",\n \"id\": \"typescript\",\n \"title\": \"Google TypeScript Style Guide Summary\",\n \"summary\": \"This document summarizes key rules and best practices from the Google TypeScript Style Guide, which is enforced by the `gts` tool.\",\n \"sections\": [\n {\n \"heading\": \"1. Language Features\",\n \"body\": \"- **Variable Declarations:** Always use `const` or `let`. **`var` is forbidden.** Use `const` by default.\\n- **Modules:** Use ES6 modules (`import`/`export`). **Do not use `namespace`.**\\n- **Exports:** Use named exports (`export {MyClass};`). **Do not use default exports.**\\n- **Classes:**\\n - **Do not use `#private` fields.** Use TypeScript's `private` visibility modifier.\\n - Mark properties never reassigned outside the constructor with `readonly`.\\n - **Never use the `public` modifier** (it's the default). Restrict visibility with `private` or `protected` where possible.\\n- **Functions:** Prefer function declarations for named functions. Use arrow functions for anonymous functions/callbacks.\\n- **String Literals:** Use single quotes (`'`). Use template literals (`` ` ``) for interpolation and multi-line strings.\\n- **Equality Checks:** Always use triple equals (`===`) and not equals (`!==`).\\n- **Type Assertions:** **Avoid type assertions (`x as SomeType`) and non-nullability assertions (`y!`)**. If you must use them, provide a clear justification.\"\n },\n {\n \"heading\": \"2. Disallowed Features\",\n \"body\": \"- **`any` Type:** **Avoid `any`**. Prefer `unknown` or a more specific type.\\n- **Wrapper Objects:** Do not instantiate `String`, `Boolean`, or `Number` wrapper classes.\\n- **Automatic Semicolon Insertion (ASI):** Do not rely on it. **Explicitly end all statements with a semicolon.**\\n- **`const enum`:** Do not use `const enum`. Use plain `enum` instead.\\n- **`eval()` and `Function(...string)`:** Forbidden.\"\n },\n {\n \"heading\": \"3. Naming\",\n \"body\": \"- **`UpperCamelCase`:** For classes, interfaces, types, enums, and decorators.\\n- **`lowerCamelCase`:** For variables, parameters, functions, methods, and properties.\\n- **`CONSTANT_CASE`:** For global constant values, including enum values.\\n- **`_` Prefix/Suffix:** **Do not use `_` as a prefix or suffix** for identifiers, including for private properties.\"\n },\n {\n \"heading\": \"4. Type System\",\n \"body\": \"- **Type Inference:** Rely on type inference for simple, obvious types. Be explicit for complex types.\\n- **`undefined` and `null`:** Both are supported. Be consistent within your project.\\n- **Optional vs. `|undefined`:** Prefer optional parameters and fields (`?`) over adding `|undefined` to the type.\\n- **`Array<T>` Type:** Use `T[]` for simple types. Use `Array<T>` for more complex union types (e.g., `Array<string | number>`).\\n- **`{}` Type:** **Do not use `{}`**. Prefer `unknown`, `Record<string, unknown>`, or `object`.\"\n },\n {\n \"heading\": \"5. Comments and Documentation\",\n \"body\": \"- **JSDoc:** Use `/** JSDoc */` for documentation, `//` for implementation comments.\\n- **Redundancy:** **Do not declare types in `@param` or `@return` blocks** (e.g., `/** @param {string} user */`). This is redundant in TypeScript.\\n- **Add Information:** Comments must add information, not just restate the code.\\n\\n*Source: [Google TypeScript Style Guide](https://google.github.io/styleguide/tsguide.html)*\"\n }\n ],\n \"languages\": [\n \"typescript\"\n ],\n \"frameworks\": [],\n \"file_patterns\": [],\n \"applies_to\": [\n \"planning\",\n \"implementation\",\n \"review\",\n \"tests\"\n ],\n \"rules\": [\n {\n \"id\": \"typescript-rule-1\",\n \"severity\": \"guidance\",\n \"summary\": \"**Variable Declarations:** Always use `const` or `let`. **`var` is forbidden.** Use `const` by default.\"\n },\n {\n \"id\": \"typescript-rule-2\",\n \"severity\": \"guidance\",\n \"summary\": \"**Modules:** Use ES6 modules (`import`/`export`). **Do not use `namespace`.**\"\n },\n {\n \"id\": \"typescript-rule-3\",\n \"severity\": \"guidance\",\n \"summary\": \"**Exports:** Use named exports (`export {MyClass};`). **Do not use default exports.**\"\n },\n {\n \"id\": \"typescript-rule-4\",\n \"severity\": \"guidance\",\n \"summary\": \"**Classes:**\"\n },\n {\n \"id\": \"typescript-rule-5\",\n \"severity\": \"guidance\",\n \"summary\": \"**Do not use `#private` fields.** Use TypeScript's `private` visibility modifier.\"\n },\n {\n \"id\": \"typescript-rule-6\",\n \"severity\": \"guidance\",\n \"summary\": \"Mark properties never reassigned outside the constructor with `readonly`.\"\n },\n {\n \"id\": \"typescript-rule-7\",\n \"severity\": \"guidance\",\n \"summary\": \"**Never use the `public` modifier** (it's the default). Restrict visibility with `private` or `protected` where possible.\"\n },\n {\n \"id\": \"typescript-rule-8\",\n \"severity\": \"guidance\",\n \"summary\": \"**Functions:** Prefer function declarations for named functions. Use arrow functions for anonymous functions/callbacks.\"\n },\n {\n \"id\": \"typescript-rule-9\",\n \"severity\": \"guidance\",\n \"summary\": \"**String Literals:** Use single quotes (`'`). Use template literals (`` ` ``) for interpolation and multi-line strings.\"\n },\n {\n \"id\": \"typescript-rule-10\",\n \"severity\": \"guidance\",\n \"summary\": \"**Equality Checks:** Always use triple equals (`===`) and not equals (`!==`).\"\n },\n {\n \"id\": \"typescript-rule-11\",\n \"severity\": \"guidance\",\n \"summary\": \"**Type Assertions:** **Avoid type assertions (`x as SomeType`) and non-nullability assertions (`y!`)**. If you must use them, provide a clear justification.\"\n },\n {\n \"id\": \"typescript-rule-12\",\n \"severity\": \"guidance\",\n \"summary\": \"**`any` Type:** **Avoid `any`**. Prefer `unknown` or a more specific type.\"\n },\n {\n \"id\": \"typescript-rule-13\",\n \"severity\": \"guidance\",\n \"summary\": \"**Wrapper Objects:** Do not instantiate `String`, `Boolean`, or `Number` wrapper classes.\"\n },\n {\n \"id\": \"typescript-rule-14\",\n \"severity\": \"guidance\",\n \"summary\": \"**Automatic Semicolon Insertion (ASI):** Do not rely on it. **Explicitly end all statements with a semicolon.**\"\n },\n {\n \"id\": \"typescript-rule-15\",\n \"severity\": \"guidance\",\n \"summary\": \"**`const enum`:** Do not use `const enum`. Use plain `enum` instead.\"\n },\n {\n \"id\": \"typescript-rule-16\",\n \"severity\": \"guidance\",\n \"summary\": \"**`eval()` and `Function(...string)`:** Forbidden.\"\n },\n {\n \"id\": \"typescript-rule-17\",\n \"severity\": \"guidance\",\n \"summary\": \"**`UpperCamelCase`:** For classes, interfaces, types, enums, and decorators.\"\n },\n {\n \"id\": \"typescript-rule-18\",\n \"severity\": \"guidance\",\n \"summary\": \"**`lowerCamelCase`:** For variables, parameters, functions, methods, and properties.\"\n },\n {\n \"id\": \"typescript-rule-19\",\n \"severity\": \"guidance\",\n \"summary\": \"**`CONSTANT_CASE`:** For global constant values, including enum values.\"\n },\n {\n \"id\": \"typescript-rule-20\",\n \"severity\": \"guidance\",\n \"summary\": \"**`_` Prefix/Suffix:** **Do not use `_` as a prefix or suffix** for identifiers, including for private properties.\"\n },\n {\n \"id\": \"typescript-rule-21\",\n \"severity\": \"guidance\",\n \"summary\": \"**Type Inference:** Rely on type inference for simple, obvious types. Be explicit for complex types.\"\n },\n {\n \"id\": \"typescript-rule-22\",\n \"severity\": \"guidance\",\n \"summary\": \"**`undefined` and `null`:** Both are supported. Be consistent within your project.\"\n },\n {\n \"id\": \"typescript-rule-23\",\n \"severity\": \"guidance\",\n \"summary\": \"**Optional vs. `|undefined`:** Prefer optional parameters and fields (`?`) over adding `|undefined` to the type.\"\n },\n {\n \"id\": \"typescript-rule-24\",\n \"severity\": \"guidance\",\n \"summary\": \"**`Array<T>` Type:** Use `T[]` for simple types. Use `Array<T>` for more complex union types (e.g., `Array<string | number>`).\"\n },\n {\n \"id\": \"typescript-rule-25\",\n \"severity\": \"guidance\",\n \"summary\": \"**`{}` Type:** **Do not use `{}`**. Prefer `unknown`, `Record<string, unknown>`, or `object`.\"\n },\n {\n \"id\": \"typescript-rule-26\",\n \"severity\": \"guidance\",\n \"summary\": \"**JSDoc:** Use `/** JSDoc */` for documentation, `//` for implementation comments.\"\n },\n {\n \"id\": \"typescript-rule-27\",\n \"severity\": \"guidance\",\n \"summary\": \"**Redundancy:** **Do not declare types in `@param` or `@return` blocks** (e.g., `/** @param {string} user */`). This is redundant in TypeScript.\"\n },\n {\n \"id\": \"typescript-rule-28\",\n \"severity\": \"guidance\",\n \"summary\": \"**Add Information:** Comments must add information, not just restate the code.\"\n }\n ],\n \"source\": \"bundled_template\"\n}\n","workflow.json":"{\n \"version\": 1,\n \"schema\": \"cadre.workflow.v1\",\n \"kind\": \"workflow\",\n \"title\": \"Project Workflow\",\n \"summary\": \"\",\n \"sections\": [\n {\n \"heading\": \"Guiding Principles\",\n \"body\": \"1. **Cadre State Is Packet-Owned:** Cadre records progress through MCP\\n task-completion, mutation, workflow, review, native event/message, and validation packets.\\n2. **The JSON Plan Is Authoritative:** `plan.json` describes the work. `plan.md`\\n is generated for human review only and must not drive runtime behavior.\\n3. **The Tech Stack Is Deliberate:** Changes to the tech stack must be reflected\\n in Cadre context through the appropriate packet before implementation relies on\\n them.\\n4. **Test-Driven Development:** Write tests before implementing behavior whenever\\n the task is testable.\\n5. **High Code Coverage:** Aim for more than 80 percent coverage for new or\\n changed modules unless the packet records an approved exception.\\n6. **User Experience First:** Product decisions should prioritize the user's\\n workflow, clarity, and failure recovery.\\n7. **Non-Interactive and CI-Aware:** Prefer one-shot project commands for tests,\\n builds, linters, and formatters.\"\n },\n {\n \"heading\": \"Task Lifecycle\",\n \"body\": \"All Cadre orchestration uses MCP packets. If a required packet returns `ok:false`,\\nhalt and report the packet error instead of recreating Cadre state logic outside\\nMCP.\\n\\n1. **Select Work:** Use Cadre status or implementation-prep packets to select the\\n next available track, phase, or task.\\n2. **Claim Work:** Use the implementation workflow packet or mutation packet to\\n claim ownership before product edits begin.\\n3. **Red Phase:** Add or update product tests that express the expected behavior.\\n Run the relevant project test command and confirm the new test fails for the\\n intended reason when practical.\\n4. **Green Phase:** Implement the smallest product change that satisfies the test\\n and acceptance criteria.\\n5. **Refactor:** Improve clarity, duplication, performance, and accessibility\\n while preserving behavior.\\n6. **Verify:** Run targeted tests first, then broader project checks according to\\n risk. Include coverage when the project has coverage tooling.\\n7. **Commit Product Work:** Make clear product commits for the completed unit of\\n work according to the team's normal commit policy.\\n8. **Record Completion:** Call the Cadre task-completion packet with test,\\n coverage, commit, and summary evidence. The packet updates plan state, metadata,\\n journals, events, and indexes.\"\n },\n {\n \"heading\": \"Commit Discipline\",\n \"body\": \"- Cadre uses Conventional Commit subjects for traceable work: product commits\\n use `feat(scope): subject`, control-plane commits use `cadre(workflow):\\n subject`, and automation commits use `cadre(train): subject`.\\n- Prefer one product commit per completed task or coherent implementation\\n checkpoint. When `cadre_complete_task` is called without a commit SHA, Cadre\\n stages the task-owned product files and creates the task commit automatically.\\n- Durable Cadre state changes are committed by the packet that writes them. Setup,\\n track creation, revision, refresh, completion records, review evidence,\\n publication ledgers, archive, release, handoff, artifact sync, status flags,\\n and squashed wisps all receive control-plane commits.\\n- Cadre writes structured commit trace notes to `refs/notes/cadre` using the\\n `cadre.commit_trace.v1` schema. Notes link commits back to track, task, repo,\\n workflow, tests, coverage, provider evidence, and event ids.\\n- Do not mark a task complete until its product commit, verification summary,\\n Cadre control-plane commit, and trace note have been recorded or the packet\\n explicitly reports a local/transient classification.\"\n },\n {\n \"heading\": \"Polyrepo Notes\",\n \"body\": \"In polyrepo mode, Cadre packets identify the repo, branch, worktree, task, and\\ncommit evidence for each product repository. Product commands run in the\\nappropriate repo worktree. Cadre control-plane synchronization, cross-repo review\\nlinks, fleet status, and merge-train metadata are packet-owned.\\n\\nIn monorepo mode, the same packet lifecycle applies with a single product repo.\"\n },\n {\n \"heading\": \"Quality Gates\",\n \"body\": \"Before marking any task complete through Cadre packets, verify:\\n\\n- Tests for the changed behavior pass.\\n- Coverage meets the project's threshold or the packet records an approved reason.\\n- Code follows the relevant style guide in `styleguides/*.json`; Markdown under\\n `code_styleguides/` is generated for human readability only.\\n- Public APIs are documented when the project convention requires it.\\n- Type checks, lint checks, and static analysis pass when configured.\\n- User-facing changes have appropriate accessibility and responsive checks.\\n- Documentation is updated when behavior, setup, or operations changed.\\n- Security-sensitive changes receive explicit review evidence.\"\n },\n {\n \"heading\": \"Phase Completion\",\n \"body\": \"When a task completes a phase, use Cadre workflow and completion packets to gather\\nphase evidence, validate coverage, record the checkpoint, and refresh indexes.\\nManual verification plans may be summarized for the user, but Cadre checkpoint\\nstate is recorded only through packets.\"\n },\n {\n \"heading\": \"Development Commands\",\n \"body\": \"Project setup, tests, builds, linters, formatters, local servers, and product\\ncommits remain normal product work. Use the commands configured by the project and\\nkeep them non-interactive. These commands must not mutate Cadre control-plane,\\nprovider, index, review, archive, handoff, event, message, or validation state directly.\"\n }\n ]\n}\n"}};
|
|
4
|
+
const __CADRE_EMBEDDED_ASSETS__ = {"skill":{"version":1,"schema":"cadre.skill.v1","id":"cadre","name":"Cadre","markdownUse":"human_projection_only","description":"Context-driven development methodology for organized, spec-first coding. JSON is the authoritative agent/runtime contract; Markdown exists only as platform shim or generated human projection.","activation":{"triggers":["project has cadre/","user mentions specs, plans, tracks, or context-driven development","user asks for cadre-* workflow","user asks about Cadre project status, track management, review, ship, land, release, archive, setup, or artifact sync","project is a polyrepo control repo with cadre/repos.json"],"requiredRuntime":"Cadre MCP","startup":[{"tool":"cadre_project","arguments":{"action":"ping"},"purpose":"Verify Cadre MCP availability before every Cadre workflow"},{"rule":"Every project-scoped Cadre MCP call must include a per-call root argument pointing at the project root or a path inside it"},{"rule":"If Cadre MCP tools are unavailable, halt and ask the user to install, enable, or restart the Cadre plugin"}]},"lazyContext":{"defaultResponseMode":"compact","detailMode":"Use responseMode=detail only for full plans, code-intelligence evidence, or long style-guide content","canonicalArtifacts":["cadre/product.json","cadre/product_guidelines.json","cadre/tech-stack.json","cadre/workflow.json","cadre/patterns.jsonl","cadre/tracks.json","track metadata.json/spec.json/plan.json/learnings.jsonl/handoff.json","cadre/styleguides/*.json"],"humanProjections":["cadre/product.md","cadre/product_guidelines.md","cadre/workflow.md","cadre/patterns.md","track spec.md/plan.md/learnings.md/HANDOFF.md","cadre/code_styleguides/*.md"],"rules":["Do not read Markdown projections as canonical truth","Do not eagerly read the whole cadre/ tree on activation","Resolve live status from MCP packets and track metadata, not generated indexes"]},"workflows":{"setup":{"intent":"Setup project","protocol":"cadre://workflow-protocol?workflow=setup"},"newtrack":{"intent":"Create work","protocol":"cadre://workflow-protocol?workflow=newtrack"},"implement":{"intent":"Start or resume implementation","protocol":"cadre://workflow-protocol?workflow=implement"},"status":{"intent":"Status, team board, or fleet board","protocol":"cadre://workflow-protocol?workflow=status"},"validate":{"intent":"Validate project state","protocol":"cadre://workflow-protocol?workflow=validate"},"flag":{"intent":"Flag blocked or skipped work","protocol":"cadre://workflow-protocol?workflow=flag"},"revise":{"intent":"Revise spec or plan","protocol":"cadre://workflow-protocol?workflow=revise"},"review":{"intent":"Review quality gate","protocol":"cadre://workflow-protocol?workflow=review"},"ship":{"intent":"Ship monorepo work","protocol":"cadre://workflow-protocol?workflow=ship"},"land":{"intent":"Land polyrepo work","protocol":"cadre://workflow-protocol?workflow=land"},"handoff":{"intent":"Handoff context","protocol":"cadre://workflow-protocol?workflow=handoff"},"archive":{"intent":"Archive completed tracks","protocol":"cadre://workflow-protocol?workflow=archive"},"release":{"intent":"Release summary or version","protocol":"cadre://workflow-protocol?workflow=release"},"refresh":{"intent":"Refresh stale context","protocol":"cadre://workflow-protocol?workflow=refresh"},"revert":{"intent":"Revert tracked commits","protocol":"cadre://workflow-protocol?workflow=revert"},"formula":{"intent":"Formula or template operations","protocol":"cadre://workflow-protocol?workflow=formula"},"artifacts":{"intent":"Sync canonical artifacts","protocol":"cadre://workflow-protocol?workflow=artifacts"}},"references":{"mcp-contract":{"uri":"cadre://agent-reference?name=mcp-contract"},"provider-evidence":{"uri":"cadre://agent-reference?name=provider-evidence"},"team-ops":{"uri":"cadre://agent-reference?name=team-ops"},"cadre-sync":{"uri":"cadre://agent-reference?name=cadre-sync"},"ownership-guard":{"uri":"cadre://agent-reference?name=ownership-guard"},"parallel-execution":{"uri":"cadre://agent-reference?name=parallel-execution"},"polyrepo-git":{"uri":"cadre://agent-reference?name=polyrepo-git"},"template-locator":{"uri":"cadre://agent-reference?name=template-locator"}},"operatingDefaults":["Setup writes native Cadre event, message, formula, and local wisp state through packets","Shared sync is recommended for teams and packet-owned","Hosted provider evidence must come through official provider MCPs and be written back through Cadre packets","LSP/code-intelligence packets should be used for repo maps, impact checks, review assistance, diagnostics, and test-impact hints"],"forbidden":["Do not mutate cadre/, provider state, indexes, worker state, event/message state, or merge/cleanup state outside Cadre packets","Do not use Markdown as alternate input, legacy import source, or runtime state","Do not manually edit generated Markdown projections as workflow state"]},"protocols":{"archive":{"version":1,"schema":"cadre.protocol.v1","id":"cadre-archive","description":"Archive completed tracks","workflow":"archive","markdownUse":"human_projection_only","preconditions":[{"tool":"cadre_project","arguments":{"action":"ping"},"requirement":"Cadre MCP must be available"},{"requirement":"Every project-scoped packet call includes root"},{"requirement":"If a required packet returns ok:false, halt and report the packet error"}],"packetFlow":[{"step":1,"instruction":"Resolve the project root with `cadre_project` using `action: \"root\"`."},{"step":2,"instruction":"Call `cadre_workflow` with `workflow: \"archive\"` and the resolved root. Pass `trackId`, cutoff, or scope arguments as structured JSON fields only."},{"step":3,"instruction":"Present the dry-run `tracks` list, packet warnings, cleanup scope, and any review_bundle manifest/path list without inlining large artifact contents into model context."},{"step":4,"instruction":"To archive reviewed work, call `cadre_workflow` again with `workflow: \"archive\"`, `execute: true`, and `humanConfirmed: true`."},{"step":5,"instruction":"Summarize archived track ids, packet warnings, changed canonical JSON/JSONL artifacts, generated human projections, and any packet errors."}],"confirmation":{"requiredForMutation":true,"dryRunFirst":true,"executeArgument":"execute","humanConfirmationArgument":"humanConfirmed"},"forbiddenActions":["Do not recreate Cadre control-plane, native event/message state, index, worktree, provider, merge, or cleanup state with shell commands","Do not read or write Markdown projections as canonical state","Do not use Markdown payload fields, legacy Markdown import, or prompt-side state repair"],"responseSummary":["packet ok/error state","selected track or scope","warnings and blockers","changed canonical JSON/JSONL artifacts","generated human projections when relevant","next recommended packet"],"references":["mcp-contract"]},"artifacts":{"version":1,"schema":"cadre.protocol.v1","id":"cadre-artifacts","description":"Sync canonical Cadre artifacts with generated human projections","workflow":"artifacts","markdownUse":"human_projection_only","preconditions":[{"tool":"cadre_project","arguments":{"action":"ping"},"requirement":"Cadre MCP must be available"},{"requirement":"Every project-scoped packet call includes root"},{"requirement":"If a required packet returns ok:false, halt and report the packet error"}],"packetFlow":[{"step":1,"instruction":"Resolve the project root with `cadre_project` using `action: \"root\"`."},{"step":2,"instruction":"For discovery, call `cadre_artifact` with `action: \"catalog\"`, `\"schema\"`, `\"validate\"`, `\"render\"`, or `\"diff\"` and structured JSON arguments."},{"step":3,"instruction":"For preview, call `cadre_artifact` with `action: \"sync\"`, the requested scope, and no legacy Markdown import fields."},{"step":4,"instruction":"Review `review_bundle` when present. The bundle contains a manifest/path list for full proposed artifacts so large Markdown projections stay out of model context."},{"step":5,"instruction":"To apply reviewed synchronization, call `cadre_artifact` again with `action: \"sync\"`, `execute: true`, and `humanConfirmed: true`."},{"step":6,"instruction":"Summarize changed canonical JSON/JSONL artifacts, regenerated human projections, skipped unmarked projections, warnings, and next recommended packet."}],"confirmation":{"requiredForMutation":true,"dryRunFirst":true,"executeArgument":"execute","humanConfirmationArgument":"humanConfirmed"},"forbiddenActions":["Do not recreate Cadre control-plane, native event/message state, index, worktree, provider, merge, or cleanup state with shell commands","Do not read or write Markdown projections as canonical state","Do not use Markdown payload fields, legacy Markdown import, or prompt-side state repair"],"responseSummary":["packet ok/error state","selected track or scope","warnings and blockers","changed canonical JSON/JSONL artifacts","generated human projections when relevant","next recommended packet"],"references":["mcp-contract","template-locator"]},"flag":{"version":1,"schema":"cadre.protocol.v1","id":"cadre-flag","description":"Flag the current task as blocked or skipped with a reason","workflow":"flag","markdownUse":"human_projection_only","preconditions":[{"tool":"cadre_project","arguments":{"action":"ping"},"requirement":"Cadre MCP must be available"},{"requirement":"Every project-scoped packet call includes root"},{"requirement":"If a required packet returns ok:false, halt and report the packet error"}],"packetFlow":[{"step":1,"instruction":"Resolve the project root with `cadre_project` using `action: \"root\"`."},{"step":2,"instruction":"Call `cadre_workflow` with `workflow: \"flag\"`, the resolved root, `trackId`, desired status, reason, and any task selectors as structured JSON fields."},{"step":3,"instruction":"Present the dry-run status change, selected track, reason, warnings, and review_bundle manifest/path list when returned."},{"step":4,"instruction":"When mutation is intended, pass `execute: true` and `humanConfirmed: true` so Cadre packets update canonical JSON state and generated projections."},{"step":5,"instruction":"Summarize selected track, resulting status, reason, changed canonical JSON artifacts, generated human projections, and packet warnings."}],"confirmation":{"requiredForMutation":true,"dryRunFirst":true,"executeArgument":"execute","humanConfirmationArgument":"humanConfirmed"},"forbiddenActions":["Do not recreate Cadre control-plane, native event/message state, index, worktree, provider, merge, or cleanup state with shell commands","Do not read or write Markdown projections as canonical state","Do not use Markdown payload fields, legacy Markdown import, or prompt-side state repair"],"responseSummary":["packet ok/error state","selected track or scope","warnings and blockers","changed canonical JSON/JSONL artifacts","generated human projections when relevant","next recommended packet"],"references":["mcp-contract"]},"formula":{"version":1,"schema":"cadre.protocol.v1","id":"cadre-formula","description":"Manage native Cadre formulas and local wisps","workflow":"formula","markdownUse":"human_projection_only","preconditions":[{"tool":"cadre_project","arguments":{"action":"ping"},"requirement":"Cadre MCP must be available"},{"requirement":"Every project-scoped packet call includes root"},{"requirement":"If a required packet returns ok:false, halt and report the packet error"}],"packetFlow":[{"step":1,"instruction":"Resolve the project root with `cadre_project` using `action: \"root\"`."},{"step":2,"instruction":"Call `cadre_workflow` with `workflow: \"formula\"` and the requested native formula operation as structured JSON arguments: list, show, cook, wisp_create, wisp_list, wisp_update_step, wisp_squash, wisp_burn, or pour."},{"step":3,"instruction":"Use `pour` for reviewed persistent output; it routes generated spec and plan JSON through normal `cadre-newtrack` creation with formula trace fields. Local wisps remain under `cadre/local/wisps/` until squashed or burned; `wisp_squash` records a durable digest and control commit."},{"step":4,"instruction":"Summarize available formulas, generated draft tracks, canonical JSON artifacts, or packet errors."}],"confirmation":{"requiredForMutation":true,"dryRunFirst":false,"executeArgument":"execute","humanConfirmationArgument":"humanConfirmed"},"forbiddenActions":["Do not recreate Cadre control-plane, native event/message state, index, worktree, provider, merge, or cleanup state with shell commands","Do not read or write Markdown projections as canonical state","Do not use Markdown payload fields, legacy Markdown import, or prompt-side state repair"],"responseSummary":["packet ok/error state","selected track or scope","warnings and blockers","changed canonical JSON/JSONL artifacts","generated human projections when relevant","next recommended packet"],"references":["mcp-contract"]},"handoff":{"version":1,"schema":"cadre.protocol.v1","id":"cadre-handoff","description":"Create context handoff for transferring implementation to next section/session","workflow":"handoff","markdownUse":"human_projection_only","preconditions":[{"tool":"cadre_project","arguments":{"action":"ping"},"requirement":"Cadre MCP must be available"},{"requirement":"Every project-scoped packet call includes root"},{"requirement":"If a required packet returns ok:false, halt and report the packet error"}],"packetFlow":[{"step":1,"instruction":"Resolve the project root with `cadre_project` using `action: \"root\"`."},{"step":2,"instruction":"Call `cadre_workflow` with `workflow: \"handoff\"` and any `trackId`, recipient, audience, or scope arguments as structured JSON fields."},{"step":3,"instruction":"Review the returned `track_context`, native message/event state, handoff path, warnings, and review_bundle manifest/path list without inlining large artifacts into model context."},{"step":4,"instruction":"To write the handoff, call `cadre_workflow` again with `workflow: \"handoff\"`, `execute: true`, and `humanConfirmed: true`."},{"step":5,"instruction":"Summarize the handoff path, recipient or audience, open risks, changed canonical JSON artifacts, generated human projections, and next packet."}],"confirmation":{"requiredForMutation":true,"dryRunFirst":true,"executeArgument":"execute","humanConfirmationArgument":"humanConfirmed"},"forbiddenActions":["Do not recreate Cadre control-plane, native event/message state, index, worktree, provider, merge, or cleanup state with shell commands","Do not read or write Markdown projections as canonical state","Do not use Markdown payload fields, legacy Markdown import, or prompt-side state repair"],"responseSummary":["packet ok/error state","selected track or scope","warnings and blockers","changed canonical JSON/JSONL artifacts","generated human projections when relevant","next recommended packet"],"references":["mcp-contract"]},"implement":{"version":1,"schema":"cadre.protocol.v1","id":"cadre-implement","description":"Execute tasks from a track's implementation plan","workflow":"implement","markdownUse":"human_projection_only","preconditions":[{"tool":"cadre_project","arguments":{"action":"ping"},"requirement":"Cadre MCP must be available"},{"requirement":"Every project-scoped packet call includes root"},{"requirement":"If a required packet returns ok:false, halt and report the packet error"}],"packetFlow":[{"step":1,"instruction":"Resolve the project root with `cadre_project` using `action: \"root\"`."},{"step":2,"instruction":"Call `cadre_workflow` with `workflow: \"implement\"`, the resolved root, and optional track/task selectors as structured JSON fields."},{"step":3,"instruction":"Use the returned `prepare_implementation.styleGuides` JSON context before product edits; Markdown style-guide projections are human-readable only."},{"step":4,"instruction":"Use the returned `prepare_implementation` and `phase_schedule` to choose the next ready task while respecting ownership, repo, and dependency JSON fields."},{"step":5,"instruction":"For parallel work, use `cadre_parallel` packets for planning, worker setup, finish recording, merge-back, and cleanup."},{"step":6,"instruction":"After each task, call `cadre_complete_task` with coverage, verification, changed files, and summary evidence as structured JSON fields. If no commit SHA is supplied, Cadre creates the task product commit, records the Cadre control-plane commit, and writes `refs/notes/cadre` trace notes."},{"step":7,"instruction":"Summarize completed work, style guides used, tests run, coverage, commits, changed canonical JSON artifacts, generated human projections, and next packet."}],"confirmation":{"requiredForMutation":true,"dryRunFirst":false,"executeArgument":"execute","humanConfirmationArgument":"humanConfirmed"},"forbiddenActions":["Do not recreate Cadre control-plane, native event/message state, index, worktree, provider, merge, or cleanup state with shell commands","Do not read or write Markdown projections as canonical state","Do not use Markdown payload fields, legacy Markdown import, or prompt-side state repair"],"responseSummary":["packet ok/error state","selected track or scope","warnings and blockers","changed canonical JSON/JSONL artifacts","generated human projections when relevant","next recommended packet"],"references":["parallel-execution","mcp-contract","ownership-guard"]},"land":{"version":1,"schema":"cadre.protocol.v1","id":"cadre-land","description":"Open and link the cross-repo PR group for a polyrepo track, then let the merge train land it","workflow":"land","markdownUse":"human_projection_only","preconditions":[{"tool":"cadre_project","arguments":{"action":"ping"},"requirement":"Cadre MCP must be available"},{"requirement":"Every project-scoped packet call includes root"},{"requirement":"If a required packet returns ok:false, halt and report the packet error"}],"packetFlow":[{"step":1,"instruction":"Resolve the project root with `cadre_project` using `action: \"root\"`."},{"step":2,"instruction":"Call `cadre_workflow` with `workflow: \"land\"` and the requested `trackId` as structured JSON."},{"step":3,"instruction":"Use the returned topology, polyrepo preflight, review gate, fleet status, provider actions, git actions, and review_bundle manifest/path list."},{"step":4,"instruction":"When the packet reports `phase_state: \"ready\"` or `\"pending_provider\"`, call the packet again with `execute: true` only after required review and provider evidence are available."},{"step":5,"instruction":"If the packet returns `phase_state: \"pending_provider\"`, execute only the returned provider MCP actions and write evidence back through Cadre packets."},{"step":6,"instruction":"Summarize every repo result, linked review artifact, CI state, publication ledger path, control commit, git-note push state, packet warnings, changed canonical JSON artifacts, generated human projections, and remaining blockers."}],"confirmation":{"requiredForMutation":true,"dryRunFirst":false,"executeArgument":"execute","humanConfirmationArgument":"humanConfirmed"},"forbiddenActions":["Do not recreate Cadre control-plane, native event/message state, index, worktree, provider, merge, or cleanup state with shell commands","Do not read or write Markdown projections as canonical state","Do not use Markdown payload fields, legacy Markdown import, or prompt-side state repair"],"responseSummary":["packet ok/error state","selected track or scope","warnings and blockers","changed canonical JSON/JSONL artifacts","generated human projections when relevant","next recommended packet"],"references":["provider-evidence","polyrepo-git","mcp-contract"]},"newtrack":{"version":1,"schema":"cadre.protocol.v1","id":"cadre-newtrack","description":"Create a new feature or bug track with spec and plan","workflow":"newtrack","markdownUse":"human_projection_only","preconditions":[{"tool":"cadre_project","arguments":{"action":"ping"},"requirement":"Cadre MCP must be available"},{"requirement":"Every project-scoped packet call includes root"},{"requirement":"If a required packet returns ok:false, halt and report the packet error"}],"packetFlow":[{"step":1,"instruction":"Resolve the project root with `cadre_project` using `action: \"root\"`."},{"step":2,"instruction":"Draft structured `spec` and `plan` JSON from the user request and current project context. Do not send Markdown fields such as `specText`, `planText`, or `planPath`."},{"step":3,"instruction":"Call `cadre_workflow` with `workflow: \"newtrack\"`, `trackId`, `spec`, `plan`, and any metadata as structured JSON fields."},{"step":4,"instruction":"Review the returned canonical spec/plan JSON artifacts, generated Markdown projection previews, learnings starter, plan assistance, and review_bundle manifest/path list without inlining large artifacts into model context."},{"step":5,"instruction":"To create the track after approval, call `cadre_workflow` again with `workflow: \"newtrack\"`, `execute: true`, and `humanConfirmed: true` using the same JSON payload."},{"step":6,"instruction":"Summarize created track id, native event record, worktree plan, changed canonical JSON artifacts, generated human projections, and next packet."}],"confirmation":{"requiredForMutation":true,"dryRunFirst":true,"executeArgument":"execute","humanConfirmationArgument":"humanConfirmed"},"forbiddenActions":["Do not recreate Cadre control-plane, native event/message state, index, worktree, provider, merge, or cleanup state with shell commands","Do not read or write Markdown projections as canonical state","Do not use Markdown payload fields, legacy Markdown import, or prompt-side state repair"],"responseSummary":["packet ok/error state","selected track or scope","warnings and blockers","changed canonical JSON/JSONL artifacts","generated human projections when relevant","next recommended packet"],"references":["mcp-contract"]},"refresh":{"version":1,"schema":"cadre.protocol.v1","id":"cadre-refresh","description":"Sync context docs with current codebase state","workflow":"refresh","markdownUse":"human_projection_only","preconditions":[{"tool":"cadre_project","arguments":{"action":"ping"},"requirement":"Cadre MCP must be available"},{"requirement":"Every project-scoped packet call includes root"},{"requirement":"If a required packet returns ok:false, halt and report the packet error"}],"packetFlow":[{"step":1,"instruction":"Resolve the project root with `cadre_project` using `action: \"root\"`."},{"step":2,"instruction":"Call `cadre_workflow` with `workflow: \"refresh\"` and any requested scope as structured JSON fields."},{"step":3,"instruction":"Use the returned doctor, workspace diagnostics, dependency graph, LSP evidence, and review_bundle manifest/path list to identify stale canonical JSON/JSONL context without inlining large artifacts into model context."},{"step":4,"instruction":"When packet-supported document updates are requested, call the workflow packet again with `execute: true` and `humanConfirmed: true`."},{"step":5,"instruction":"Summarize refreshed canonical context, regenerated human projections, stale areas, diagnostics, and packet warnings."}],"confirmation":{"requiredForMutation":true,"dryRunFirst":true,"executeArgument":"execute","humanConfirmationArgument":"humanConfirmed"},"forbiddenActions":["Do not recreate Cadre control-plane, native event/message state, index, worktree, provider, merge, or cleanup state with shell commands","Do not read or write Markdown projections as canonical state","Do not use Markdown payload fields, legacy Markdown import, or prompt-side state repair"],"responseSummary":["packet ok/error state","selected track or scope","warnings and blockers","changed canonical JSON/JSONL artifacts","generated human projections when relevant","next recommended packet"],"references":["mcp-contract"]},"release":{"version":1,"schema":"cadre.protocol.v1","id":"cadre-release","description":"Cut a local release - changelog plus version evidence across completed tracks","workflow":"release","markdownUse":"human_projection_only","preconditions":[{"tool":"cadre_project","arguments":{"action":"ping"},"requirement":"Cadre MCP must be available"},{"requirement":"Every project-scoped packet call includes root"},{"requirement":"If a required packet returns ok:false, halt and report the packet error"}],"packetFlow":[{"step":1,"instruction":"Resolve the project root with `cadre_project` using `action: \"root\"`."},{"step":2,"instruction":"Call `cadre_workflow` with `workflow: \"release\"` and any requested version, date, or scope arguments as structured JSON fields."},{"step":3,"instruction":"Review returned completed tracks, release evidence, warnings, proposed artifacts, and review_bundle manifest/path list without inlining large artifacts into model context."},{"step":4,"instruction":"To write release artifacts, call `cadre_workflow` again with `workflow: \"release\"`, `execute: true`, and `humanConfirmed: true`."},{"step":5,"instruction":"Summarize release scope, version intent, generated artifacts, changed canonical JSON/JSONL state, generated human projections, and remaining blockers."}],"confirmation":{"requiredForMutation":true,"dryRunFirst":true,"executeArgument":"execute","humanConfirmationArgument":"humanConfirmed"},"forbiddenActions":["Do not recreate Cadre control-plane, native event/message state, index, worktree, provider, merge, or cleanup state with shell commands","Do not read or write Markdown projections as canonical state","Do not use Markdown payload fields, legacy Markdown import, or prompt-side state repair"],"responseSummary":["packet ok/error state","selected track or scope","warnings and blockers","changed canonical JSON/JSONL artifacts","generated human projections when relevant","next recommended packet"],"references":["mcp-contract"]},"revert":{"version":1,"schema":"cadre.protocol.v1","id":"cadre-revert","description":"Revert tracks, phases, or tasks through Cadre packets","workflow":"revert","markdownUse":"human_projection_only","preconditions":[{"tool":"cadre_project","arguments":{"action":"ping"},"requirement":"Cadre MCP must be available"},{"requirement":"Every project-scoped packet call includes root"},{"requirement":"If a required packet returns ok:false, halt and report the packet error"}],"packetFlow":[{"step":1,"instruction":"Resolve the project root with `cadre_project` using `action: \"root\"`."},{"step":2,"instruction":"Call `cadre_workflow` with `workflow: \"revert\"` and the requested `trackId`, commit, repo, or scope arguments as structured JSON fields."},{"step":3,"instruction":"Present the packet dry-run revert scope, planned git actions, affected canonical JSON artifacts, generated projections, warnings, and review_bundle manifest/path list."},{"step":4,"instruction":"To execute an approved revert, call `cadre_workflow` again with `workflow: \"revert\"`, `execute: true`, and `humanConfirmed: true`."},{"step":5,"instruction":"Summarize reverted scope, tests requested or run, changed canonical JSON/JSONL artifacts, generated human projections, packet warnings, and follow-up packets."}],"confirmation":{"requiredForMutation":true,"dryRunFirst":true,"executeArgument":"execute","humanConfirmationArgument":"humanConfirmed"},"forbiddenActions":["Do not recreate Cadre control-plane, native event/message state, index, worktree, provider, merge, or cleanup state with shell commands","Do not read or write Markdown projections as canonical state","Do not use Markdown payload fields, legacy Markdown import, or prompt-side state repair"],"responseSummary":["packet ok/error state","selected track or scope","warnings and blockers","changed canonical JSON/JSONL artifacts","generated human projections when relevant","next recommended packet"],"references":["mcp-contract"]},"review":{"version":1,"schema":"cadre.protocol.v1","id":"cadre-review","description":"Review a track's diff before shipping (quality gate)","workflow":"review","markdownUse":"human_projection_only","preconditions":[{"tool":"cadre_project","arguments":{"action":"ping"},"requirement":"Cadre MCP must be available"},{"requirement":"Every project-scoped packet call includes root"},{"requirement":"If a required packet returns ok:false, halt and report the packet error"}],"packetFlow":[{"step":1,"instruction":"Resolve the project root with `cadre_project` using `action: \"root\"`."},{"step":2,"instruction":"Call `cadre_workflow` with `workflow: \"review\"` and the requested `trackId` as structured JSON."},{"step":3,"instruction":"Use the returned track context, review assistance, machine gate, review gate, provider evidence state, and review_bundle manifest/path list."},{"step":4,"instruction":"When provider evidence is required, call `cadre_review` with structured provider MCP evidence; do not fetch or mutate provider state through shell commands."},{"step":5,"instruction":"To record a verdict, call `cadre_mutate` with `action: \"record_review\"` and the structured verdict/evidence payload."},{"step":6,"instruction":"Summarize findings first, then gate state, evidence, changed canonical JSON artifacts, generated human projections, and next packet."}],"confirmation":{"requiredForMutation":true,"dryRunFirst":false,"executeArgument":"execute","humanConfirmationArgument":"humanConfirmed"},"forbiddenActions":["Do not recreate Cadre control-plane, native event/message state, index, worktree, provider, merge, or cleanup state with shell commands","Do not read or write Markdown projections as canonical state","Do not use Markdown payload fields, legacy Markdown import, or prompt-side state repair"],"responseSummary":["packet ok/error state","selected track or scope","warnings and blockers","changed canonical JSON/JSONL artifacts","generated human projections when relevant","next recommended packet"],"references":["mcp-contract"]},"revise":{"version":1,"schema":"cadre.protocol.v1","id":"cadre-revise","description":"Update spec/plan when implementation reveals issues","workflow":"revise","markdownUse":"human_projection_only","preconditions":[{"tool":"cadre_project","arguments":{"action":"ping"},"requirement":"Cadre MCP must be available"},{"requirement":"Every project-scoped packet call includes root"},{"requirement":"If a required packet returns ok:false, halt and report the packet error"}],"packetFlow":[{"step":1,"instruction":"Resolve the project root with `cadre_project` using `action: \"root\"`."},{"step":2,"instruction":"Call `cadre_workflow` with `workflow: \"revise\"`, the requested `trackId`, and proposed structured `spec` or `plan` JSON fields. Do not send Markdown fields such as `specText`, `planText`, or `planPath`."},{"step":3,"instruction":"Use the returned track context and impact analysis to review proposed canonical JSON changes and generated Markdown projection previews."},{"step":4,"instruction":"When packet-supported mutation is requested, call the workflow packet again with `execute: true` and `humanConfirmed: true` after reviewing the review_bundle manifest/path list without inlining large artifacts into model context."},{"step":5,"instruction":"Summarize changed requirements, affected tasks, tests to update, changed canonical JSON artifacts, generated human projections, and packet warnings."}],"confirmation":{"requiredForMutation":true,"dryRunFirst":true,"executeArgument":"execute","humanConfirmationArgument":"humanConfirmed"},"forbiddenActions":["Do not recreate Cadre control-plane, native event/message state, index, worktree, provider, merge, or cleanup state with shell commands","Do not read or write Markdown projections as canonical state","Do not use Markdown payload fields, legacy Markdown import, or prompt-side state repair"],"responseSummary":["packet ok/error state","selected track or scope","warnings and blockers","changed canonical JSON/JSONL artifacts","generated human projections when relevant","next recommended packet"],"references":["mcp-contract"]},"setup":{"version":1,"schema":"cadre.protocol.v1","id":"cadre-setup","description":"Initialize project with Cadre context-driven development","workflow":"setup","markdownUse":"human_projection_only","preconditions":[{"tool":"cadre_project","arguments":{"action":"ping"},"requirement":"Cadre MCP must be available"},{"requirement":"Every project-scoped packet call includes root"},{"requirement":"If a required packet returns ok:false, halt and report the packet error"}],"packetFlow":[{"step":1,"instruction":"Call `cadre_project` with `action: \"ping\"` to confirm MCP availability. If the client asks for repeated approval on Cadre MCP tools, tell the user to rerun `cadre install`; the installer bootstraps Cadre-only MCP approval rules for Codex and Claude without approving shell commands or non-Cadre tools."},{"step":2,"instruction":"Call `cadre_workflow` with `workflow: \"setup\"`, the root candidate, structured `product`, optional `productGuidelines`, optional `workflowPolicy`, and `techStack` JSON fields. Use the returned setup review artifacts and native state summary for the user review."},{"step":3,"instruction":"Use the returned doctor report, workspace diagnostics, dependency graph, LSP evidence, template inventory, and selected JSON style guides."},{"step":4,"instruction":"Present returned setup review artifacts using the review_bundle manifest/path list so large generated Markdown projections do not enter model context."},{"step":5,"instruction":"When the user confirms the setup payload and review artifacts, call `cadre_workflow` again with `workflow: \"setup\"`, `execute: true`, and `humanConfirmed: true`."},{"step":6,"instruction":"Summarize created canonical JSON/JSONL files, generated human projections, selected code style guides, native state initialization, warnings, and next packet."}],"confirmation":{"requiredForMutation":true,"dryRunFirst":true,"executeArgument":"execute","humanConfirmationArgument":"humanConfirmed"},"forbiddenActions":["Do not recreate Cadre control-plane, native event/message state, index, worktree, provider, merge, or cleanup state with shell commands","Do not read or write Markdown projections as canonical state","Do not use Markdown payload fields, legacy Markdown import, or prompt-side state repair"],"responseSummary":["packet ok/error state","selected track or scope","warnings and blockers","changed canonical JSON/JSONL artifacts","generated human projections when relevant","next recommended packet"],"references":["template-locator","mcp-contract"]},"ship":{"version":1,"schema":"cadre.protocol.v1","id":"cadre-ship","description":"Rebase a reviewed track onto main, publish it, and prepare the PR","workflow":"ship","markdownUse":"human_projection_only","preconditions":[{"tool":"cadre_project","arguments":{"action":"ping"},"requirement":"Cadre MCP must be available"},{"requirement":"Every project-scoped packet call includes root"},{"requirement":"If a required packet returns ok:false, halt and report the packet error"}],"packetFlow":[{"step":1,"instruction":"Resolve the project root with `cadre_project` using `action: \"root\"`."},{"step":2,"instruction":"Call `cadre_workflow` with `workflow: \"ship\"` and the requested `trackId` as structured JSON."},{"step":3,"instruction":"Use the returned review gate, git actions, provider actions, CI evidence, warnings, and review_bundle manifest/path list."},{"step":4,"instruction":"When the packet reports `phase_state: \"ready\"` or `\"pending_provider\"`, call the packet again with `execute: true` only after required review and provider evidence are available."},{"step":5,"instruction":"If the packet returns `phase_state: \"pending_provider\"`, execute only returned provider MCP actions and write evidence back through Cadre packets."},{"step":6,"instruction":"Summarize branch, review gate, provider artifact, CI state, publication ledger path, control commit, git-note push state, changed canonical JSON artifacts, generated human projections, and next packet."}],"confirmation":{"requiredForMutation":true,"dryRunFirst":false,"executeArgument":"execute","humanConfirmationArgument":"humanConfirmed"},"forbiddenActions":["Do not recreate Cadre control-plane, native event/message state, index, worktree, provider, merge, or cleanup state with shell commands","Do not read or write Markdown projections as canonical state","Do not use Markdown payload fields, legacy Markdown import, or prompt-side state repair"],"responseSummary":["packet ok/error state","selected track or scope","warnings and blockers","changed canonical JSON/JSONL artifacts","generated human projections when relevant","next recommended packet"],"references":["provider-evidence","polyrepo-git","mcp-contract"]},"status":{"version":1,"schema":"cadre.protocol.v1","id":"cadre-status","description":"Display current Cadre project progress","workflow":"status","markdownUse":"human_projection_only","preconditions":[{"tool":"cadre_project","arguments":{"action":"ping"},"requirement":"Cadre MCP must be available"},{"requirement":"Every project-scoped packet call includes root"},{"requirement":"If a required packet returns ok:false, halt and report the packet error"}],"packetFlow":[{"step":1,"instruction":"Resolve the project root with `cadre_project` using `action: \"root\"`."},{"step":2,"instruction":"Call `cadre_workflow` with `workflow: \"status\"` and a `mode` such as `live`, `team`, `fleet`, or `review` as structured JSON fields."},{"step":3,"instruction":"For rich resources, read the matching MCP resource when useful instead of eagerly loading the whole Cadre control plane."},{"step":4,"instruction":"Summarize active track, ownership, blockers, review queue, fleet health, canonical JSON state, generated projection status, and next packet."}],"confirmation":{"requiredForMutation":true,"dryRunFirst":false,"executeArgument":"execute","humanConfirmationArgument":"humanConfirmed"},"forbiddenActions":["Do not recreate Cadre control-plane, native event/message state, index, worktree, provider, merge, or cleanup state with shell commands","Do not read or write Markdown projections as canonical state","Do not use Markdown payload fields, legacy Markdown import, or prompt-side state repair"],"responseSummary":["packet ok/error state","selected track or scope","warnings and blockers","changed canonical JSON/JSONL artifacts","generated human projections when relevant","next recommended packet"],"references":["mcp-contract"]},"validate":{"version":1,"schema":"cadre.protocol.v1","id":"cadre-validate","description":"Validate Cadre project integrity","workflow":"validate","markdownUse":"human_projection_only","preconditions":[{"tool":"cadre_project","arguments":{"action":"ping"},"requirement":"Cadre MCP must be available"},{"requirement":"Every project-scoped packet call includes root"},{"requirement":"If a required packet returns ok:false, halt and report the packet error"}],"packetFlow":[{"step":1,"instruction":"Resolve the project root with `cadre_project` using `action: \"root\"`."},{"step":2,"instruction":"Call `cadre_workflow` with `workflow: \"validate\"` and any requested track, scope, or repair intent as structured JSON fields."},{"step":3,"instruction":"Use the returned doctor report, team inventory, plan integrity, collision scan, provider status, and review_bundle manifest/path list."},{"step":4,"instruction":"When packet-supported repair is requested, call the workflow packet again with `execute: true` and `humanConfirmed: true` after reviewing proposed canonical JSON changes."},{"step":5,"instruction":"Summarize errors before warnings, then repaired canonical JSON/JSONL artifacts, generated human projections, remaining risks, and next packet."}],"confirmation":{"requiredForMutation":true,"dryRunFirst":false,"executeArgument":"execute","humanConfirmationArgument":"humanConfirmed"},"forbiddenActions":["Do not recreate Cadre control-plane, native event/message state, index, worktree, provider, merge, or cleanup state with shell commands","Do not read or write Markdown projections as canonical state","Do not use Markdown payload fields, legacy Markdown import, or prompt-side state repair"],"responseSummary":["packet ok/error state","selected track or scope","warnings and blockers","changed canonical JSON/JSONL artifacts","generated human projections when relevant","next recommended packet"],"references":["mcp-contract"]}},"references":{"cadre-sync":{"version":1,"schema":"cadre.reference.v1","id":"cadre-sync","title":"Control-Plane Sync","markdownUse":"human_projection_only","rules":["Spec, plan, repository config, provider config, and topology conflicts are","Ephemeral worker state and native local state details are MCP-owned and regenerated or","Track-id collisions, shared-mode retries, and sync safety classification are"],"sections":[{"heading":"Predicate","body":"`cadre_project` with `action: \"topology\"` reports whether the project uses local\nor shared control-plane sync. Shared sync applies equally to monorepo and\npolyrepo projects. Product code publication is separate and happens only through\nship or land packets."},{"heading":"Preamble","body":"Before any workflow mutates Cadre state, call the workflow packet requested by\nthe protocol. The packet is responsible for shared-mode preflight, remote\nverification, native state sync, merge-driver health, conflict detection, and\nbounded retry policy.\n\nIf the packet reports a sync conflict, halt and summarize the conflicting files\nor state categories from the packet result. Do not hand-merge Cadre files\nstate, or generated state JSON."},{"heading":"Postamble","body":"After a workflow packet mutates Cadre state, use the next packet named by the\nresult for sync or publication. `cadre_project` with\n`action: \"sync_control_plane\"` owns shared control-plane publication and refuses\nto publish when product-code changes are mixed into the control-plane surface."},{"heading":"Conflict Policy","body":"- Spec, plan, repository config, provider config, and topology conflicts are\n surfaced to the user by packet results.\n- Ephemeral worker state and native local state details are MCP-owned and regenerated or\n repaired only through packets.\n- Track-id collisions, shared-mode retries, and sync safety classification are\n handled by packets. Agents report the packet result and stop when it blocks."}]},"mcp-contract":{"version":1,"schema":"cadre.reference.v1","id":"mcp-contract","title":"Cadre MCP Contract","markdownUse":"human_projection_only","rules":["`cadre_workflow` coordinates setup, newtrack, implement, status, validate,","`cadre_project` handles ping, doctor, root, topology, tech-stack summary,","`cadre_status` returns live, team, mine, available, collision, fleet, and","`cadre_track` returns bounded track context, parsed plans, integrity checks,","`cadre_parallel` plans task waves, sets up workers, records worker finish","`cadre_mutate` owns control-plane writes such as claim, heartbeat, status,","`cadre_complete_task` performs the journaled task-completion transaction.","`cadre_review` owns review assistance, machine gates, review gates,","`cadre_intel` owns repo maps, LSP setup/review/impact, workspace diagnostics,","`cadre_artifact` owns canonical artifact catalog/schema/import/validation,","`cadre_project action: integrations` and `cadre://integrations` report","`cadre_job` starts, lists, cancels, and reads async job artifacts.","`cadre://team-board?root=...`","`cadre://fleet-board?root=...`","`cadre://my-next-actions?root=...`","`cadre://review-queue?root=...`","`cadre://handoff-inbox?root=...`","`cadre://track-context?root=...&trackId=...`","`cadre://review-evidence?root=...&trackId=...`","`cadre://track-plan?root=...&trackId=...`","`cadre://track-spec?root=...&trackId=...`","`cadre://parallel-state?root=...&trackId=...`","`cadre://quality-gate?root=...&trackId=...`","`cadre://repo-map?root=...`","`cadre://integrations?root=...`","`cadre://workspace-health?root=...`","`cadre://workspace-diagnostics?root=...`","`cadre://test-impact?root=...&files=...`","`cadre://lsp-status?root=...`","`cadre://repo-topology?root=...`","`cadre://provider-actions?root=...&trackId=...&workflow=ship|land`","`cadre://ship-plan?root=...&trackId=...`","`cadre://land-plan?root=...&trackId=...`","`cadre://release-plan?root=...`","`cadre://job-result?root=...&jobId=...`","`cadre://artifact-catalog?root=...`","`cadre://artifact-schema?root=...&artifact=...`","`cadre://artifact-preview?root=...&artifact=...`","`cadre://artifact-sync-plan?root=...&scope=...`","`cadre://styleguide-selection?root=...&trackId=...`"],"sections":[{"heading":"Primary Packets","body":"- `cadre_workflow` coordinates setup, newtrack, implement, status, validate,\n review, ship, land, archive, release, handoff, refresh, flag, revert, revise,\n and formula flows.\n- `cadre_project` handles ping, doctor, root, topology, tech-stack summary,\n shared sync, and polyrepo preflight.\n- `cadre_status` returns live, team, mine, available, collision, fleet, and\n native state summary views.\n- `cadre_track` returns bounded track context, parsed plans, integrity checks,\n phase schedules, implementation prep, planning evidence, and worktree plans.\n- `cadre_parallel` plans task waves, sets up workers, records worker finish\n state, merges safe workers, and cleans merged workers.\n- `cadre_mutate` owns control-plane writes such as claim, heartbeat, status,\n metadata, review, worker state, task result, and index regeneration.\n- `cadre_complete_task` performs the journaled task-completion transaction.\n- `cadre_review` owns review assistance, machine gates, review gates,\n provider-evidence writes, and PR/MR/CI status normalization.\n- `cadre_intel` owns repo maps, LSP setup/review/impact, workspace diagnostics,\n test impact, dependency graphs, and daemon lifecycle.\n- `cadre_artifact` owns canonical artifact catalog/schema/import/validation,\n deterministic projection rendering, diffing, and sync review bundles.\n- `cadre_project action: integrations` and `cadre://integrations` report\n configured optional MCPs plus LSP coverage in one bounded view.\n- `cadre_job` starts, lists, cancels, and reads async job artifacts."},{"heading":"Response Modes","body":"Default compact responses include summaries, counts, warnings, next actions, and\nresource URIs. Use `responseMode: \"detail\"` for full plan bodies, full LSP\nevidence, long command outputs, or full style-guide content."},{"heading":"Compact Resources","body":"Use MCP resources for bounded dashboards:\n\n- `cadre://team-board?root=...`\n- `cadre://fleet-board?root=...`\n- `cadre://my-next-actions?root=...`\n- `cadre://review-queue?root=...`\n- `cadre://handoff-inbox?root=...`\n- `cadre://track-context?root=...&trackId=...`\n- `cadre://review-evidence?root=...&trackId=...`\n- `cadre://track-plan?root=...&trackId=...`\n- `cadre://track-spec?root=...&trackId=...`\n- `cadre://parallel-state?root=...&trackId=...`\n- `cadre://quality-gate?root=...&trackId=...`\n- `cadre://repo-map?root=...`\n- `cadre://integrations?root=...`\n- `cadre://workspace-health?root=...`\n- `cadre://workspace-diagnostics?root=...`\n- `cadre://test-impact?root=...&files=...`\n- `cadre://lsp-status?root=...`\n- `cadre://repo-topology?root=...`\n- `cadre://provider-actions?root=...&trackId=...&workflow=ship|land`\n- `cadre://ship-plan?root=...&trackId=...`\n- `cadre://land-plan?root=...&trackId=...`\n- `cadre://release-plan?root=...`\n- `cadre://job-result?root=...&jobId=...`\n- `cadre://artifact-catalog?root=...`\n- `cadre://artifact-schema?root=...&artifact=...`\n- `cadre://artifact-preview?root=...&artifact=...`\n- `cadre://artifact-sync-plan?root=...&scope=...`\n- `cadre://styleguide-selection?root=...&trackId=...`\n\nResource templates are discoverable through MCP, so clients should prefer\ntemplate discovery when available."}]},"ownership-guard":{"version":1,"schema":"cadre.reference.v1","id":"ownership-guard","title":"Ownership Guard","markdownUse":"human_projection_only","rules":[],"sections":[{"heading":"Packet Flow","body":"1. Resolve the project root with `cadre_project` using `action: \"root\"`.\n2. For track context, call `cadre_track` with `action: \"context\"` and the target\n `trackId`.\n3. To take or refresh ownership, call `cadre_mutate` with `action: \"claim\"` or\n use the workflow packet that performs the claim for the current operation.\n4. For long-running work, call `cadre_mutate` with `action: \"heartbeat\"` when the\n workflow packet asks for a heartbeat."},{"heading":"Foreign Holder","body":"If a packet reports that the track is held by another operator, present the\nholder, status, and packet-provided options to the user. Continue only by calling\nthe takeover packet with the packet-prescribed argument. If the user declines or\nthe packet returns `ok:false`, halt."},{"heading":"Handoff Exception","body":"If the packet reports a pending handoff addressed to the current operator, use\nthe pickup or claim packet path named by the result. Do not clear handoff labels\nor mirror ownership directly."},{"heading":"Staleness","body":"The canonical stale ownership window is thirty minutes. Packets compute and\nenforce this value. Agents should report stale reclaim evidence returned by the\npacket and then continue through packetized claim or heartbeat calls only."}]},"parallel-execution":{"version":1,"schema":"cadre.reference.v1","id":"parallel-execution","title":"Parallel Worker Dispatch","markdownUse":"human_projection_only","rules":["Work only on the product files assigned in the packet payload.","Run product tests, builds, linters, and commits according to the worker prompt.","Do not mutate Cadre control-plane files, native Cadre event/message state, provider state, worktree","Return structured evidence to the coordinator: worker id, task id, repo,","If product implementation fails, return the failure evidence. The coordinator","Use only `cadre_parallel`, `cadre_complete_task`, and other Cadre MCP packets","Treat `parallel_state.json` and native Cadre event/message state as packet-owned artifacts.","A worker conflict, failed test, missing commit, low coverage, or missing native task evidence","Product shell commands are allowed only for product implementation,"],"sections":[{"heading":"Packet Flow","body":"1. Call `cadre_workflow` with `workflow: \"implement\"` and the selected `trackId`\n to obtain implementation prep and the phase schedule.\n2. For a parallel phase, call `cadre_parallel` with `action: \"plan\"` or\n `action: \"next_wave\"` to obtain the ready worker set.\n3. Call `cadre_parallel` with `action: \"setup_workers\"` and the current client\n `agentIdentifier` (`\"claude\"` or `\"codex\"`) to get the packet-owned\n worktree/setup plan and selected dispatch adapter. Add `execute:true` only\n when the user or workflow has authorized mutation.\n4. Dispatch exactly the workers returned by the packet. Do not add, remove,\n reorder, split, or merge workers outside the packet result.\n5. As each worker finishes, call `cadre_parallel` with `action: \"record_finish\"`\n and the worker result evidence. Use `execute:true` when recording completion.\n6. After the wave finishes, call `cadre_parallel` with `action: \"merge_back\"` for\n the packet-owned merge plan. Add `execute:true` only when ready to mutate.\n7. Call `cadre_parallel` with `action: \"cleanup\"` for packet-owned cleanup. Add\n `execute:true` only after merge-back is clean or the packet explicitly marks a\n worker safe to clean.\n8. Repeat `next_wave` until the packet reports no ready workers.\n\nAll dependency gates, file collision checks, repo routing, event/message updates,\nparallel audit state, merge conflict state, task completion, and cleanup are\npacket-owned."},{"heading":"Dispatching Each Worker","body":"<!-- AGENT:claude -->\nPass `agentIdentifier:\"claude\"` to `cadre_parallel` when setting up workers.\nThen call the **`Task` tool** once per packet worker using the MCP-returned\n`selected_dispatch`, worker prompt, worktree, owned files, and expected result\nschema. Worker calls are awaitable; wait for every worker in the wave before\ncalling the next Cadre packet.\n<!-- /AGENT:claude -->\n<!-- AGENT:codex -->\nPass `agentIdentifier:\"codex\"` to `cadre_parallel` when setting up workers.\nThen use Codex multi-agent tools from the MCP-returned `selected_dispatch`.\nSearch tool discovery for `multi_agent_v1.spawn_agent`, spawn one worker agent\nper packet worker, pass the worker prompt and dispatch payload, and wait with\nthe corresponding multi-agent wait tool before calling the next Cadre packet.\nIf the selected dispatch mechanism is unavailable, halt with a clear\n`dispatch-unavailable` message instead of simulating worker state locally.\n<!-- /AGENT:codex -->"},{"heading":"Worker Rules","body":"- Work only on the product files assigned in the packet payload.\n- Run product tests, builds, linters, and commits according to the worker prompt.\n- Do not mutate Cadre control-plane files, native Cadre event/message state, provider state, worktree\n topology, merge state, or cleanup state directly.\n- Return structured evidence to the coordinator: worker id, task id, repo,\n commit evidence, tests run, coverage when available, files changed, summary,\n and blockers.\n- If product implementation fails, return the failure evidence. The coordinator\n records it through Cadre packets."},{"heading":"Coordinator Rules","body":"- Use only `cadre_parallel`, `cadre_complete_task`, and other Cadre MCP packets\n named by packet results for Cadre state changes.\n- Treat `parallel_state.json` and native Cadre event/message state as packet-owned artifacts.\n- A worker conflict, failed test, missing commit, low coverage, or missing native\n task evidence is handled by the packet result. Report the packet error and halt when\n it is blocking.\n- Product shell commands are allowed only for product implementation,\n verification, and commits inside worker scope."}],"platforms":{"codex":{"agentIdentifier":"codex","dispatch":"Pass agentIdentifier:\"codex\" to setup_workers. Use the returned selected_dispatch to discover multi_agent_v1.spawn_agent, spawn one worker per packet worker, wait for all workers, then call the next Cadre packet. If unavailable, halt with dispatch-unavailable."},"claude":{"agentIdentifier":"claude","dispatch":"Pass agentIdentifier:\"claude\" to setup_workers. Use the returned selected_dispatch to call the Task tool once per MCP-provided worker prompt. Pass dispatch payload, worktree, owned files, expected result schema, and wait for every worker before calling the next Cadre packet."}}},"polyrepo-git":{"version":1,"schema":"cadre.reference.v1","id":"polyrepo-git","title":"Polyrepo Routing And Worktrees","markdownUse":"human_projection_only","rules":["`cadre_track` with `action: \"context\"`","`cadre_track` with `action: \"worktree_plan\"`","`cadre_parallel` worker packets","`cadre_workflow` with `workflow: \"ship\"`, `workflow: \"land\"`, or"],"sections":[{"heading":"Topology","body":"Call `cadre_project` with `action: \"topology\"` or the workflow packet requested\nby the protocol. The packet reports whether the project is monorepo or polyrepo,\nthe control repo, enabled product repos, default repo, and any topology warnings.\n\nIf topology data is missing or invalid, halt on the packet error. Do not infer\nrepository layout by reading or rewriting Cadre state directly."},{"heading":"Task Repository Routing","body":"Plan tasks may carry repo annotations, and polyrepo metadata may carry per-repo\nbranch and worktree information. Agents consume this routing only through packet\nresults such as:\n\n- `cadre_track` with `action: \"context\"`\n- `cadre_track` with `action: \"worktree_plan\"`\n- `cadre_parallel` worker packets\n- `cadre_workflow` with `workflow: \"ship\"`, `workflow: \"land\"`, or\n `workflow: \"validate\"`\n\nTask completion, commit evidence, repo-specific SHA evidence, and progress\nrecording go through `cadre_complete_task` or the packet named by the current\nworkflow result."},{"heading":"Product Commands","body":"Workers may run product implementation, verification, and commit commands inside\nthe repo/worktree path provided by a packet. These commands are for target\nproject code only. They must not mutate Cadre control-plane files, native Cadre event/message state,\nworktree topology, merge state, or cleanup state."},{"heading":"Ship, Land, Revert, And Cleanup","body":"Use `cadre_workflow` packets for ship, land, revert, archive, and release\noperations. Use `cadre_parallel` packets for worker setup, merge-back, and\ncleanup. If a packet returns a hard gate for missing submodules, branch state,\nprovider evidence, review state, or validation, halt and report it."}]},"provider-evidence":{"version":1,"schema":"cadre.reference.v1","id":"provider-evidence","title":"Provider Evidence","markdownUse":"human_projection_only","rules":["Local review may return `phase_state: \"pending_provider\"` when hosted evidence","Ship and land packets fail closed when hosted evidence is required for the","Provider action packets return the exact evidence key and minimum fields the","`cadre_review` with `action: \"provider_evidence\"`","`cadre_workflow` with `workflow: \"ship\"` or `workflow: \"land\"` and","`cadre_mutate` with `action: \"record_review\"` when recording the final review","Cadre native Cadre packets for notes or labels when the workflow packet asks for them"],"sections":[{"heading":"Review Versus Publication","body":"- Local review may return `phase_state: \"pending_provider\"` when hosted evidence\n is unavailable. Treat this as pending evidence, not as a local review failure.\n- Ship and land packets fail closed when hosted evidence is required for the\n selected provider mode and has not been written back.\n- Provider action packets return the exact evidence key and minimum fields the\n provider MCP result must satisfy."},{"heading":"Write-Back Targets","body":"Use these packet paths to persist provider evidence:\n\n- `cadre_review` with `action: \"provider_evidence\"`\n- `cadre_workflow` with `workflow: \"ship\"` or `workflow: \"land\"` and\n `providerEvidence`\n- `cadre_mutate` with `action: \"record_review\"` when recording the final review\n verdict\n- Cadre native Cadre packets for notes or labels when the workflow packet asks for them\n\nNever treat a hosted label, provider issue state, or PR/MR review as Cadre state\nuntil a Cadre packet records the corresponding decision."}]},"team-ops":{"version":1,"schema":"cadre.reference.v1","id":"team-ops","title":"Team Operations","markdownUse":"human_projection_only","rules":["`in_progress` after worker setup","`awaiting_merge` after tested worker completion with commit evidence","`merged` after safe merge-back","`failed` or `conflict` when the worker cannot be merged safely","GitHub or GitLab provider MCP for PR/MR metadata, review approvals, CI status,","Sourcegraph or internal code-search MCP for cross-repo symbol search when","Issue tracker MCP such as Jira or Linear when roadmap evidence lives outside","CI-specific MCP for Buildkite, CircleCI, Argo, Jenkins, or other systems that","Sentry, Datadog, Honeycomb, or logging MCP for incident and runtime evidence.","Knowledge-base MCP for product/domain documents used as read-only evidence."],"sections":[{"heading":"Sync Mode","body":"Use `local` mode for solo work or private experiments. Use `shared` mode when\nmultiple people need to see ownership, leases, review queues, blockers, and\navailable work. Shared sync is packet-owned; agents should rely on Cadre packet\nresults for pre/post sync status and recovery instructions.\n\nGenerated setup can configure `.gitattributes` for parallel worker state so shared control-plane merges stay low-conflict."},{"heading":"Parallelism","body":"Parallel work is task-level and dependency-aware. `cadre_parallel` returns only\ntasks whose phase, dependencies, worker state, and file claims are ready. A\nsequential phase dispatches one unfinished task at a time. A parallel phase may\ndispatch multiple independent tasks when file claims do not conflict.\n\nWorker status transitions:\n\n- `in_progress` after worker setup\n- `awaiting_merge` after tested worker completion with commit evidence\n- `merged` after safe merge-back\n- `failed` or `conflict` when the worker cannot be merged safely\n\nCleanup removes merged workers by default; force is required for unfinished,\nfailed, or conflicted workers."},{"heading":"MCP And LSP Use","body":"Use `cadre_intel` before prompt-side repo scans when possible. It can return\nrepo maps, dependency graphs, workspace diagnostics, test impact, LSP setup,\nLSP impact, and warm review evidence. Polyrepo projects return repo-qualified\nresults so clients can distinguish control-plane files from product-repo files.\nUse `cadre://integrations` when you need one bounded view of provider, code\nsearch, issue, CI, logging, knowledge-base, and LSP coverage.\n\nRecommended optional MCP additions for larger teams:\n\n- GitHub or GitLab provider MCP for PR/MR metadata, review approvals, CI status,\n and hosted provider evidence.\n- Sourcegraph or internal code-search MCP for cross-repo symbol search when\n product repos are not fully local.\n- Issue tracker MCP such as Jira or Linear when roadmap evidence lives outside\n Cadre.\n- CI-specific MCP for Buildkite, CircleCI, Argo, Jenkins, or other systems that\n are not covered by GitHub/GitLab checks.\n- Sentry, Datadog, Honeycomb, or logging MCP for incident and runtime evidence.\n- Knowledge-base MCP for product/domain documents used as read-only evidence."}]},"template-locator":{"version":1,"schema":"cadre.reference.v1","id":"template-locator","title":"Cadre Template Assets","markdownUse":"human_projection_only","rules":["`cadre_workflow` with reviewable dry-runs reports review artifacts and a","`cadre_workflow` with `workflow: \"setup_scaffold\"` and `execute:true` writes","`cadre_workflow` with `workflow: \"newtrack\"` writes per-track files, including","`cadre_intel` owns LSP setup, warm review, cold review, and daemon status","`cadre_mutate` owns derived index refreshes and other Cadre state mutations."],"sections":[{"heading":"Packet Ownership","body":"- `cadre_workflow` with reviewable dry-runs reports review artifacts and a\n token-safe `review_bundle` with full proposed files on disk. Setup, new-track,\n revise, refresh document updates, release artifacts, and handoff artifacts use\n this pattern.\n- `cadre_workflow` with `workflow: \"setup_scaffold\"` and `execute:true` writes\n the setup scaffold from bundled templates and confirmed setup payload.\n- `cadre_workflow` with `workflow: \"newtrack\"` writes per-track files, including\n template-backed track learnings.\n- `cadre_intel` owns LSP setup, warm review, cold review, and daemon status\n checks.\n- `cadre_mutate` owns derived index refreshes and other Cadre state mutations."},{"heading":"Style Guides","body":"Setup always selects the general style guide when available, adds guides derived\nfrom structured `techStack` JSON, and unions any explicit `styleGuideIds` passed\nto the packet.\nThe setup packet returns `styleGuides.detected`, `styleGuides.selected`,\n`styleGuides.written`, `styleGuides.skipped`, and `styleGuides.missing`.\n\nIf `styleGuides.missing` is non-empty, surface the packet warning and keep the\nvalid selected guides. Do not remove user-supplied `styleGuideIds` just to make a\ndry-run warning disappear. If the packet returns `ok:false`, halt and surface the\npacket error. Do not replace the packet with manual copying."},{"heading":"Workflow Review Bundles","body":"Reviewable workflow dry-runs return `review_artifacts` as metadata only and\n`review_bundle` with a manifest path, absolute review file paths, and optional\nshell commands for local rendering. Use those files for human review instead of\npasting complete generated files into chat/model context by default."},{"heading":"Agent Use","body":"Use template references only to understand what the packet-created files mean.\nAll setup, new-track, LSP, style-guide, and index writes are packet-owned."}]}},"templates":{"ci/cadre-merge-train.github.yml":"# Cadre cross-repo merge train (GitHub Actions).\n#\n# Scaffolded into the CONTROL repo at .github/workflows/cadre-merge-train.yml\n# by /cadre-setup when provider_mode == \"github\" and merge_train.enabled.\n#\n# What it does: when every PR in a track group (label `cadre-track:<id>`,\n# spread across the control repo + product submodule repos) is APPROVED and\n# CI-GREEN, it merges them in a fixed order — PRODUCT repos first, then bumps\n# each submodule gitlink to the freshly-merged SHA on the control track branch,\n# then merges the CONTROL PR LAST. The control PR is the single \"seal\" commit;\n# there is no true cross-repo atomic merge, so on any failure it HALTS, leaves\n# already-merged product PRs in place, comments the failure, and re-fires once\n# the failing repo is green again.\n#\n# PREREQUISITE — cross-repo token: the default GITHUB_TOKEN cannot act on other\n# repos. Provide a PAT or GitHub App installation token (scopes: repo, workflow,\n# read:org) with write access to EVERY product repo, stored as the\n# `CADRE_TRAIN_TOKEN` secret in this control repo.\n#\n# Also configure branch protection on every product repo's default branch and on\n# the control branch: require approvals + the relevant status checks. The train\n# only automates the merge click; protection is what enforces review/CI.\n\nname: cadre-merge-train\n\n# TRIGGER MODEL: pull_request_review / check_suite fire only for events in THIS\n# (control) repo — i.e. when the CONTROL PR is reviewed or its checks complete, the\n# job derives the track from that PR's group label and tries to land. A review/green\n# on a PRODUCT repo does NOT fire this workflow. To auto-fire on product-repo\n# approvals, either (a) have each product repo send a `repository_dispatch` to this\n# repo on approval (carrying the track id), or (b) dispatch manually with the track\n# id, or (c) add a `schedule:` and extend the job to scan open control-repo PRs for\n# group labels (the job is idempotent + re-runnable). Re-running `/cadre-land`\n# also re-checks status from your machine.\non:\n pull_request_review:\n types: [submitted]\n check_suite:\n types: [completed]\n # schedule:\n # - cron: \"*/5 * * * *\" # uncomment for auto-fire on product-repo approvals\n workflow_dispatch:\n inputs:\n track:\n description: \"Track id to attempt to land (e.g. auth_20260609)\"\n required: true\n\n# Per-track concurrency: serialize landings WITHIN a track, but let different\n# tracks land in parallel — otherwise one stalled/conflicted track blocks every\n# other (see /cadre-land §7). The track id is known here only for workflow_dispatch;\n# for review/check events we key on the triggering control PR (one control PR per\n# track, so per-PR == per-track), falling back to run_id so we never collapse\n# unrelated events onto one global lane.\nconcurrency:\n group: cadre-merge-train-${{ github.event.inputs.track || github.event.pull_request.number || github.event.check_suite.pull_requests[0].number || github.run_id }}\n cancel-in-progress: false\n\njobs:\n land:\n runs-on: ubuntu-latest\n steps:\n - name: Checkout control repo\n uses: actions/checkout@v4\n with:\n token: ${{ secrets.CADRE_TRAIN_TOKEN }}\n submodules: false\n fetch-depth: 0\n\n - name: Run merge train\n env:\n GH_TOKEN: ${{ secrets.CADRE_TRAIN_TOKEN }}\n EVENT_TRACK: ${{ github.event.inputs.track }}\n run: |\n set -euo pipefail\n\n # --- Resolve the track id and the group label -------------------------\n PREFIX=\"$(jq -r '.merge_train.group_label_prefix // \"cadre-track\"' cadre/config.json)\"\n AUTO_FIRE=\"$(jq -r '.merge_train.auto_fire // true' cadre/config.json)\"\n CONTROL_REPO=\"${GITHUB_REPOSITORY}\"\n\n # Derive the candidate track from the triggering PR's labels, or from\n # the manual dispatch input.\n TRACK=\"${EVENT_TRACK:-}\"\n if [ -z \"$TRACK\" ]; then\n PR_NUMBER=\"$(jq -r '.pull_request.number // .check_suite.pull_requests[0].number // empty' \"$GITHUB_EVENT_PATH\")\"\n if [ -n \"$PR_NUMBER\" ]; then\n TRACK=\"$(gh pr view \"$PR_NUMBER\" --repo \"$CONTROL_REPO\" --json labels \\\n --jq \".labels[].name | select(startswith(\\\"${PREFIX}:\\\")) | sub(\\\"${PREFIX}:\\\"; \\\"\\\")\" || true)\"\n fi\n fi\n if [ -z \"$TRACK\" ]; then echo \"No track group on this event; nothing to do.\"; exit 0; fi\n LABEL=\"${PREFIX}:${TRACK}\"\n echo \"Track=$TRACK Label=$LABEL auto_fire=$AUTO_FIRE\"\n if [ \"$AUTO_FIRE\" != \"true\" ] && [ -z \"$EVENT_TRACK\" ]; then\n echo \"auto_fire disabled; only workflow_dispatch may land. Exiting.\"; exit 0\n fi\n\n # --- Helper: is a PR approved AND all required checks green? -----------\n pr_ready() { # repo pr_number\n local repo=\"$1\" num=\"$2\"\n local decision state\n decision=\"$(gh pr view \"$num\" --repo \"$repo\" --json reviewDecision --jq '.reviewDecision')\"\n state=\"$(gh pr view \"$num\" --repo \"$repo\" --json statusCheckRollup \\\n --jq '[.statusCheckRollup[]?.conclusion // .statusCheckRollup[]?.state] | map(select(. != null and . != \"SUCCESS\" and . != \"NEUTRAL\" and . != \"SKIPPED\")) | length')\"\n [ \"$decision\" = \"APPROVED\" ] && [ \"$state\" = \"0\" ]\n }\n\n # --- Gather the group from metadata.json ------------------------------\n META=\"cadre/tracks/${TRACK}/metadata.json\"\n if [ ! -f \"$META\" ]; then echo \"No metadata for $TRACK; abort.\"; exit 1; fi\n\n # Ordered repo list: metadata.merge_order entries first (in their given\n # order), then the alphabetical remainder. Never drop a repo, never\n # duplicate one — a name listed in merge_order but absent from .repos is\n # ignored; a repo absent from merge_order falls into the alpha tail.\n # De-dupe $head preserving first-seen order — a user typo such as\n # \"repo-order: api > api > web\" would otherwise process api twice.\n mapfile -t REPO_NAMES < <(jq -r '\n (.merge_order // []) as $order\n | (.repos | keys) as $all\n | ($order\n | map(select(. as $n | $all | index($n)))\n | reduce .[] as $n ([]; if (index($n)) then . else . + [$n] end)) as $head\n | ($all | map(select(. as $n | $head | index($n) | not)) | sort) as $tail\n | ($head + $tail)[]\n ' \"$META\")\n CONTROL_PR=\"$(jq -r '.control_pr_url // empty' \"$META\" | sed -E 's#.*/([0-9]+)/?$#\\1#')\"\n\n # --- Phase 1: verify EVERY sibling PR is approved + green -------------\n # Also classify each product PR as landed (already MERGED) vs blocking\n # (not ready), so a HALF-LANDED train can surface what is still holding\n # it up on the control PR instead of failing silently.\n echo \"::group::Pre-flight verification\"\n LANDED=\"\"; BLOCKING=\"\"; HALT=0\n for name in \"${REPO_NAMES[@]}\"; do\n repo=\"$(jq -r --arg n \"$name\" '.repos[$n].repo_slug // empty' \"$META\")\"\n pr=\"$(jq -r --arg n \"$name\" '.repos[$n].pr_url // empty' \"$META\" | sed -E 's#.*/([0-9]+)/?$#\\1#')\"\n [ -z \"$pr\" ] && continue\n echo \"check $repo#$pr\"\n state=\"$(gh pr view \"$pr\" --repo \"$repo\" --json state --jq '.state')\"\n if [ \"$state\" = \"MERGED\" ]; then\n LANDED=\"${LANDED:+$LANDED, }${name} (${repo}#${pr})\"\n continue\n fi\n if ! pr_ready \"$repo\" \"$pr\"; then\n BLOCKING=\"${BLOCKING:+$BLOCKING, }${name} (${repo}#${pr})\"\n HALT=1\n fi\n done\n # If the train is half-landed (>=1 product PR merged) and something is\n # still blocking, post/refresh a status comment on the control PR.\n if [ \"$HALT\" = \"1\" ]; then\n if [ -n \"$LANDED\" ] && [ -n \"$CONTROL_PR\" ]; then\n MARKER=\"<!-- cadre-merge-train:status -->\"\n BODY=\"${MARKER}\n 🚧 **cadre merge-train — half landed.**\n Already merged: ${LANDED:-(none)}\n Still blocking: ${BLOCKING:-(none)}\n\n The merged product PRs cannot be reverted automatically; the train will\n re-fire and complete once the blocking repos are approved + green.\"\n # Refresh the existing status comment if present, else create one.\n existing=\"$(gh pr view \"$CONTROL_PR\" --repo \"$CONTROL_REPO\" --json comments \\\n --jq \"[.comments[] | select(.body | startswith(\\\"${MARKER}\\\"))][0].id // empty\" || true)\"\n if [ -n \"$existing\" ]; then\n gh api -X PATCH \"repos/${CONTROL_REPO}/issues/comments/${existing}\" -f body=\"$BODY\" >/dev/null || true\n else\n gh pr comment \"$CONTROL_PR\" --repo \"$CONTROL_REPO\" --body \"$BODY\" || true\n fi\n fi\n echo \"Product PR(s) not ready (blocking: ${BLOCKING:-?}); halting.\"\n echo \"::endgroup::\"\n exit 0\n fi\n if [ -n \"$CONTROL_PR\" ]; then\n pr_ready \"$CONTROL_REPO\" \"$CONTROL_PR\" || { echo \"Control PR not ready; halting.\"; exit 0; }\n fi\n echo \"::endgroup::\"\n\n # --- Phase 2: merge each PRODUCT PR, capture new default-branch SHA ---\n git config user.name \"cadre-merge-train\"\n git config user.email \"cadre-merge-train@users.noreply.github.com\"\n BRANCH=\"track/${TRACK}\"\n git fetch origin \"$BRANCH\" && git checkout \"$BRANCH\"\n\n for name in \"${REPO_NAMES[@]}\"; do\n repo=\"$(jq -r --arg n \"$name\" '.repos[$n].repo_slug // empty' \"$META\")\"\n pr=\"$(jq -r --arg n \"$name\" '.repos[$n].pr_url // empty' \"$META\" | sed -E 's#.*/([0-9]+)/?$#\\1#')\"\n sub=\"$(jq -r --arg n \"$name\" '.repos[$n].submodule_path // empty' \"$META\")\"\n [ -z \"$pr\" ] && continue\n echo \"::group::Merge product $repo#$pr\"\n # Idempotent re-fire: if this PR is ALREADY merged (e.g. an earlier\n # train run merged it but then halted on a sibling), do NOT re-merge —\n # but STILL reconstruct its gitlink bump below so a re-fire converges.\n pr_state=\"$(gh pr view \"$pr\" --repo \"$repo\" --json state --jq '.state')\"\n if [ \"$pr_state\" = \"MERGED\" ]; then\n echo \" $repo#$pr already MERGED; skipping merge, reconstructing gitlink bump.\"\n else\n pr_ready \"$repo\" \"$pr\" || { echo \"REGRESSED before merge: $repo#$pr. Halting.\"; exit 1; }\n # Merge with a MERGE COMMIT (squash disabled by guardrail) so the\n # gitlink can pin to a single deterministic merge SHA.\n gh pr merge \"$pr\" --repo \"$repo\" --merge --delete-branch=false\n fi\n # Pin the gitlink to the MERGE COMMIT (not the branch head): the base\n # branch may have advanced past our merge by the time we read it, so\n # pinning the head would silently capture unrelated commits.\n base=\"$(gh pr view \"$pr\" --repo \"$repo\" --json baseRefName --jq '.baseRefName')\"\n new_sha=\"$(gh pr view \"$pr\" --repo \"$repo\" --json mergeCommit --jq '.mergeCommit.oid')\"\n if [ -z \"$new_sha\" ] || [ \"$new_sha\" = \"null\" ]; then\n # Merge commit (squash disabled by guardrail) not yet readable; do\n # NOT bump to a wrong/empty SHA — halt and let the train re-fire.\n echo \" ${name}: merge commit not yet available; halting to re-fire.\"\n echo \"::endgroup::\"\n exit 1\n fi\n echo \" ${name} -> ${new_sha} (merge commit)\"\n # Bump the submodule gitlink on the control track branch.\n # Fetch the base branch ref (fetch-by-bare-SHA is rejected by many hosts),\n # which now contains the just-merged commit, then pin the gitlink to it.\n git -C \"$sub\" fetch origin \"$base\" || git submodule update --init \"$sub\"\n git -C \"$sub\" checkout \"$new_sha\"\n git add \"$sub\"\n echo \"::endgroup::\"\n done\n\n # --- Phase 3: commit submodule bumps, push control track branch ------\n if ! git diff --cached --quiet; then\n git commit -m \"cadre(train): bump submodules to merged SHAs for ${TRACK}\"\n git push origin \"$BRANCH\"\n fi\n\n # --- Phase 4: re-await control PR check on bumped commit, merge LAST -\n if [ -n \"$CONTROL_PR\" ]; then\n echo \"Waiting for control PR #$CONTROL_PR checks on bumped commit...\"\n for _ in $(seq 1 30); do\n if pr_ready \"$CONTROL_REPO\" \"$CONTROL_PR\"; then\n # Merge commit (squash disabled by guardrail) for the control seal PR too.\n gh pr merge \"$CONTROL_PR\" --repo \"$CONTROL_REPO\" --merge --delete-branch\n echo \"Merge train complete for ${TRACK}.\"\n exit 0\n fi\n sleep 20\n done\n gh pr comment \"$CONTROL_PR\" --repo \"$CONTROL_REPO\" \\\n --body \"⚠️ cadre merge-train: product PRs merged and submodules bumped, but the control PR's checks did not go green in time. Re-run when CI passes.\"\n echo \"Control PR not green after bump; product PRs already merged. Halting (re-fires later).\"\n exit 1\n fi\n","ci/cadre-merge-train.gitlab.yml":"# Cadre cross-repo merge train (GitLab CI).\n#\n# Scaffolded into the CONTROL repo by /cadre-setup when provider_mode == \"gitlab\"\n# and merge_train.enabled. Either commit this as `.gitlab-ci.yml` or `include:` it\n# from an existing pipeline.\n#\n# What it does: when every Merge Request in a track group (label\n# `cadre-track:<id>`, across the control project + product submodule projects)\n# is APPROVED and pipeline-GREEN, it merges them in a fixed order — PRODUCT\n# projects first, then bumps each submodule gitlink to the merged SHA on the\n# control track branch, then merges the CONTROL MR LAST. No true cross-project\n# atomic merge exists, so on any failure it HALTS, leaves already-merged product\n# MRs in place, comments the failure, and re-fires when the failing project is\n# green again.\n#\n# PREREQUISITES:\n# - CADRE_TRAIN_TOKEN: a GROUP access token (or PAT) with `api` + `write_repository`\n# scope and Developer+ on EVERY product project, set as a masked CI/CD variable.\n# - `glab` available in the runner image, or use the REST API via curl (token in\n# CADRE_TRAIN_TOKEN). The job below uses `glab`.\n# - Branch protection / approval rules on each product project's default branch\n# and the control branch. GitLab's own \"Merge when pipeline succeeds\" and\n# merge trains are complementary; this job is the cross-project coordinator.\n\nstages:\n - merge-train\n\ncadre-merge-train:\n stage: merge-train\n image: registry.gitlab.com/gitlab-org/cli:latest\n # Serialize trains PER TRACK so two pipelines never merge/bump submodules\n # concurrently for the same track, while different tracks still land in parallel\n # (a single global lane would let one stalled track block every other — see\n # /cadre-land §7). CADRE_TRACK is the required track id for this run.\n resource_group: cadre-merge-train-$CADRE_TRACK\n rules:\n # GitLab has no cross-project \"sibling MR approved\" webhook, so this job is\n # driven by: a recurring **pipeline schedule** (set CADRE_TRACK on the\n # schedule, or leave it unset to scan — see note below), a **manual run**\n # (CI → Run pipeline → web), or an external **trigger** (e.g. a webhook from a\n # product project on approval). This is the \"re-fires when green\" mechanism on\n # GitLab — a schedule every few minutes is the simplest setup.\n - if: '$CI_PIPELINE_SOURCE == \"schedule\"'\n - if: '$CI_PIPELINE_SOURCE == \"web\"'\n - if: '$CI_PIPELINE_SOURCE == \"trigger\"'\n variables:\n GITLAB_TOKEN: $CADRE_TRAIN_TOKEN\n script:\n - apk add --no-cache jq git bash >/dev/null 2>&1 || true\n - |\n set -euo pipefail\n export GITLAB_HOST=\"${CI_SERVER_HOST}\"\n PREFIX=\"$(jq -r '.merge_train.group_label_prefix // \"cadre-track\"' cadre/config.json)\"\n AUTO_FIRE=\"$(jq -r '.merge_train.auto_fire // true' cadre/config.json)\"\n TRACK=\"${CADRE_TRACK:-}\"\n if [ -z \"$TRACK\" ]; then echo \"Set CADRE_TRACK (CI/CD var or trigger) to the track id.\"; exit 0; fi\n # Honor auto_fire: on a scheduled run, only proceed when auto_fire is on.\n # Manual (web) / trigger runs always proceed (explicit human/system intent).\n if [ \"$AUTO_FIRE\" != \"true\" ] && [ \"$CI_PIPELINE_SOURCE\" = \"schedule\" ]; then\n echo \"auto_fire disabled; scheduled runs are skipped. Trigger manually to land.\"; exit 0\n fi\n LABEL=\"${PREFIX}:${TRACK}\"\n META=\"cadre/tracks/${TRACK}/metadata.json\"\n if [ ! -f \"$META\" ]; then echo \"No metadata for $TRACK; abort.\"; exit 1; fi\n echo \"Track=$TRACK Label=$LABEL auto_fire=$AUTO_FIRE\"\n\n # mr_ready PROJECT IID -> approved AND pipeline success\n mr_ready() {\n local proj=\"$1\" iid=\"$2\" approved pipe\n approved=\"$(glab api \"projects/$(printf '%s' \"$proj\" | sed 's#/#%2F#g')/merge_requests/${iid}/approvals\" --jq '.approved // false')\"\n pipe=\"$(glab api \"projects/$(printf '%s' \"$proj\" | sed 's#/#%2F#g')/merge_requests/${iid}\" --jq '.pipeline.status // .head_pipeline.status // \"unknown\"')\"\n [ \"$approved\" = \"true\" ] && [ \"$pipe\" = \"success\" ]\n }\n\n # Ordered repo list: metadata.merge_order entries first (in their given\n # order), then the alphabetical remainder. Never drop or duplicate a repo;\n # a name in merge_order but absent from .repos is ignored, a repo absent\n # from merge_order falls into the alpha tail.\n # De-dupe $head preserving first-seen order — a user typo such as\n # \"repo-order: api > api > web\" would otherwise process api twice.\n mapfile -t REPO_NAMES < <(jq -r '\n (.merge_order // []) as $order\n | (.repos | keys) as $all\n | ($order\n | map(select(. as $n | $all | index($n)))\n | reduce .[] as $n ([]; if (index($n)) then . else . + [$n] end)) as $head\n | ($all | map(select(. as $n | $head | index($n) | not)) | sort) as $tail\n | ($head + $tail)[]\n ' \"$META\")\n CONTROL_PROJ=\"${CI_PROJECT_PATH}\"\n CONTROL_MR=\"$(jq -r '.control_pr_url // empty' \"$META\" | sed -E 's#.*/([0-9]+)/?$#\\1#')\"\n\n # Phase 1: verify every sibling MR approved + green. Also classify each\n # product MR as landed (already merged) vs blocking (not ready), so a\n # HALF-LANDED train can surface what is still holding it up on the control\n # MR instead of failing silently.\n LANDED=\"\"; BLOCKING=\"\"; HALT=0\n for name in \"${REPO_NAMES[@]}\"; do\n proj=\"$(jq -r --arg n \"$name\" '.repos[$n].repo_slug // empty' \"$META\")\"\n iid=\"$(jq -r --arg n \"$name\" '.repos[$n].pr_url // empty' \"$META\" | sed -E 's#.*/([0-9]+)/?$#\\1#')\"\n [ -z \"$iid\" ] && continue\n enc=\"$(printf '%s' \"$proj\" | sed 's#/#%2F#g')\"\n state=\"$(glab api \"projects/${enc}/merge_requests/${iid}\" --jq '.state')\"\n if [ \"$state\" = \"merged\" ]; then\n LANDED=\"${LANDED:+$LANDED, }${name} (${proj}!${iid})\"\n continue\n fi\n if ! mr_ready \"$proj\" \"$iid\"; then\n BLOCKING=\"${BLOCKING:+$BLOCKING, }${name} (${proj}!${iid})\"\n HALT=1\n fi\n done\n # If the train is half-landed (>=1 product MR merged) and something is still\n # blocking, post/refresh a status note on the control MR.\n if [ \"$HALT\" = \"1\" ]; then\n if [ -n \"$LANDED\" ] && [ -n \"$CONTROL_MR\" ]; then\n cenc=\"$(printf '%s' \"$CONTROL_PROJ\" | sed 's#/#%2F#g')\"\n MARKER=\"<!-- cadre-merge-train:status -->\"\n BODY=\"${MARKER}\n 🚧 **cadre merge-train — half landed.**\n Already merged: ${LANDED:-(none)}\n Still blocking: ${BLOCKING:-(none)}\n\n The merged product MRs cannot be reverted automatically; the train will\n re-fire and complete once the blocking projects are approved + green.\"\n # Refresh the existing status note if present, else create one.\n existing=\"$(glab api \"projects/${cenc}/merge_requests/${CONTROL_MR}/notes\" --jq \"[.[] | select(.body | startswith(\\\"${MARKER}\\\"))][0].id // empty\" 2>/dev/null || true)\"\n if [ -n \"$existing\" ]; then\n glab api --method PUT \"projects/${cenc}/merge_requests/${CONTROL_MR}/notes/${existing}\" -f body=\"$BODY\" >/dev/null || true\n else\n glab mr note \"$CONTROL_MR\" -m \"$BODY\" || true\n fi\n fi\n echo \"Product MR(s) not ready (blocking: ${BLOCKING:-?}); halting.\"; exit 0\n fi\n if [ -n \"$CONTROL_MR\" ]; then mr_ready \"$CONTROL_PROJ\" \"$CONTROL_MR\" || { echo \"Control MR not ready; halting.\"; exit 0; }; fi\n\n git config user.name \"cadre-merge-train\"\n git config user.email \"cadre-merge-train@users.noreply.gitlab.com\"\n BRANCH=\"track/${TRACK}\"\n git fetch origin \"$BRANCH\" && git checkout \"$BRANCH\"\n\n # Phase 2: merge product MRs, bump submodules\n for name in \"${REPO_NAMES[@]}\"; do\n proj=\"$(jq -r --arg n \"$name\" '.repos[$n].repo_slug // empty' \"$META\")\"\n iid=\"$(jq -r --arg n \"$name\" '.repos[$n].pr_url // empty' \"$META\" | sed -E 's#.*/([0-9]+)/?$#\\1#')\"\n sub=\"$(jq -r --arg n \"$name\" '.repos[$n].submodule_path // empty' \"$META\")\"\n [ -z \"$iid\" ] && continue\n enc=\"$(printf '%s' \"$proj\" | sed 's#/#%2F#g')\"\n target=\"$(glab api \"projects/${enc}/merge_requests/${iid}\" --jq '.target_branch')\"\n # Idempotent re-fire: if this MR is ALREADY merged (e.g. an earlier train\n # run merged it but then halted on a sibling), do NOT re-merge — but STILL\n # reconstruct its gitlink bump below so a re-fire converges.\n mr_state=\"$(glab api \"projects/${enc}/merge_requests/${iid}\" --jq '.state')\"\n if [ \"$mr_state\" = \"merged\" ]; then\n echo \" $proj!$iid already merged; skipping merge, reconstructing gitlink bump.\"\n new_sha=\"$(glab api \"projects/${enc}/merge_requests/${iid}\" --jq '.merge_commit_sha // .sha // empty')\"\n else\n mr_ready \"$proj\" \"$iid\" || { echo \"REGRESSED: $proj!$iid. Halting.\"; exit 1; }\n # Merge with a MERGE COMMIT (squash disabled by guardrail — do NOT set\n # squash=true) so the gitlink can pin to a single deterministic merge\n # SHA. Read it from the merge PUT response (.merge_commit_sha, falling\n # back to .sha) — not the branch head, which may have advanced past our\n # merge and would silently capture unrelated commits.\n merge_resp=\"$(glab api --method PUT \"projects/${enc}/merge_requests/${iid}/merge\")\"\n new_sha=\"$(printf '%s' \"$merge_resp\" | jq -r '.merge_commit_sha // .sha // empty')\"\n fi\n if [ -z \"$new_sha\" ] || [ \"$new_sha\" = \"null\" ]; then\n # Merge commit (squash disabled by guardrail) not yet readable; do NOT\n # bump to a wrong/empty SHA — halt and let the train re-fire.\n echo \" ${name}: merge commit not yet available; halting to re-fire.\"; exit 1\n fi\n echo \" ${name} -> ${new_sha} (merge commit)\"\n # Fetch the target branch ref (fetch-by-bare-SHA is rejected by many hosts),\n # which now contains the just-merged commit, then pin the gitlink to it.\n git -C \"$sub\" fetch origin \"$target\" || git submodule update --init \"$sub\"\n git -C \"$sub\" checkout \"$new_sha\"\n git add \"$sub\"\n done\n\n # Phase 3: commit + push submodule bumps\n if ! git diff --cached --quiet; then\n git commit -m \"cadre(train): bump submodules to merged SHAs for ${TRACK}\"\n git push \"https://oauth2:${CADRE_TRAIN_TOKEN}@${CI_SERVER_HOST}/${CI_PROJECT_PATH}.git\" \"HEAD:${BRANCH}\"\n fi\n\n # Phase 4: merge control MR LAST\n if [ -n \"$CONTROL_MR\" ]; then\n enc=\"$(printf '%s' \"$CONTROL_PROJ\" | sed 's#/#%2F#g')\"\n for _ in $(seq 1 30); do\n if mr_ready \"$CONTROL_PROJ\" \"$CONTROL_MR\"; then\n # Merge commit (squash disabled by guardrail — do NOT set squash=true)\n # for the control seal MR too.\n glab api --method PUT \"projects/${enc}/merge_requests/${CONTROL_MR}/merge\" >/dev/null\n echo \"Merge train complete for ${TRACK}.\"; exit 0\n fi\n sleep 20\n done\n glab mr note \"$CONTROL_MR\" -m \"⚠️ cadre merge-train: product MRs merged and submodules bumped, but the control MR pipeline did not go green in time. Re-run when CI passes.\" || true\n echo \"Control MR not green after bump; product MRs already merged. Halting (re-fires later).\"; exit 1\n fi\n","ci/cadre-monorepo-check.github.yml":"# Cadre target-project drift gate (GitHub Actions).\n#\n# Scaffolded by cadre-setup into .github/workflows/cadre-monorepo-check.yml.\n# This template is for Cadre-initialized product repositories, not the Cadre\n# harness package. It intentionally avoids harness-package drift gates,\n# generated plugin checks, and generator maintenance commands.\n\nname: cadre-monorepo-check\n\non:\n pull_request:\n\nconcurrency:\n group: cadre-monorepo-check-${{ github.ref }}\n cancel-in-progress: true\n\njobs:\n cadre-project-check:\n runs-on: ubuntu-latest\n steps:\n - name: Checkout repo\n uses: actions/checkout@v4\n\n - name: tracks.json index is fresh\n run: |\n set -euo pipefail\n if [ ! -f cadre/tracks.json ]; then\n echo \"No cadre/tracks.json — skipping freshness gate.\"\n exit 0\n fi\n entries=\"$(mktemp)\"\n expected=\"$(mktemp)\"\n actual=\"$(mktemp)\"\n : > \"$entries\"\n if [ -d cadre/tracks ]; then\n find cadre/tracks -mindepth 2 -maxdepth 2 -name metadata.json -print | sort | while read -r md; do\n dir=\"${md%metadata.json}\"\n jq \\\n --arg metadata_path \"$md\" \\\n --arg spec_path \"${dir}spec.json\" \\\n --arg plan_path \"${dir}plan.json\" \\\n '{track_id, name:(.name // .description // .track_id), status:(.status // \"new\"), priority:(.priority // \"medium\"), owner:(.owner // null), reviewer:(.reviewer // null), tags:(.tags // []), review:(.review // null), metadata_path:$metadata_path, spec_path:$spec_path, plan_path:$plan_path}' \\\n \"$md\" >> \"$entries\"\n done\n fi\n jq -S 'del(.generated_at)' cadre/tracks.json > \"$actual\"\n jq -S '{\n version: 1,\n schema: \"cadre.tracks_index.v1\",\n counts: (reduce .[] as $t ({new:0,in_progress:0,completed:0,blocked:0,skipped:0}; .[$t.status] = ((.[$t.status] // 0) + 1))),\n tracks: (sort_by(.track_id))\n }' \"$entries\" > \"$expected\"\n if ! diff -u \"$expected\" \"$actual\"; then\n echo \"::error::cadre/tracks.json is stale. Run cadre_mutate action regen_index through Cadre MCP and commit the result.\"\n exit 1\n fi\n echo \"cadre/tracks.json matches track metadata.\"\n\n - name: Shared sync merge contract present\n run: |\n set -euo pipefail\n mode=\"$(jq -r '.sync_mode // \"local\"' cadre/config.json 2>/dev/null || echo local)\"\n if [ \"$mode\" != \"shared\" ]; then\n echo \"sync_mode is '$mode' — skipping .gitattributes guard.\"\n exit 0\n fi\n missing=0\n for line in \\\n 'cadre/tracks/**/parallel_state.json merge=ours'; do\n pat=\"$(printf '%s' \"$line\" | sed 's/ */[[:space:]][[:space:]]*/g')\"\n if ! grep -Eq \"$pat\" .gitattributes 2>/dev/null; then\n echo \"::error::Missing required shared-mode .gitattributes line: $line\"\n missing=1\n fi\n done\n [ \"$missing\" -eq 0 ] || exit 1\n echo \".gitattributes contains the required shared-mode merge rules.\"\n\n - name: Configured project gate\n run: |\n set -euo pipefail\n if [ ! -f cadre/config.json ]; then\n echo \"No cadre/config.json — skipping project gate.\"\n exit 0\n fi\n gate=\"$(jq -r '.ci_check_command // .check_command // .review_machine_gate_command // .machine_gate_command // .test_command // empty' cadre/config.json)\"\n if [ -z \"$gate\" ]; then\n echo \"No Cadre project gate command configured.\"\n exit 0\n fi\n echo \"Running Cadre project gate: $gate\"\n bash -lc \"$gate\"\n\n - name: Review verdict cleared for track PR\n env:\n PR_HEAD_SHA: ${{ github.event.pull_request.head.sha }}\n HEAD_REF: ${{ github.event.pull_request.head.ref }}\n run: |\n set -euo pipefail\n if [ ! -d cadre ]; then\n echo \"No cadre/ directory — review gate not initialized.\"\n exit 0\n fi\n case \"$HEAD_REF\" in\n track/*) track_id=\"${HEAD_REF#track/}\" ;;\n *)\n echo \"Head branch '$HEAD_REF' is not a track branch — review gate not applicable.\"\n exit 0 ;;\n esac\n META=\"cadre/tracks/$track_id/metadata.json\"\n if [ ! -f \"$META\" ]; then\n echo \"::error::Track branch '$HEAD_REF' has no $META — cannot verify review.\"\n exit 1\n fi\n verdict=\"$(jq -r '.review.verdict // \"absent\"' \"$META\")\"\n blocking=\"$(jq -r '.review.blocking_count // 0' \"$META\")\"\n self_reviewed=\"$(jq -r '.review.self_reviewed // false' \"$META\")\"\n reviewed_sha=\"$(jq -r '.review.reviewed_sha // \"\"' \"$META\")\"\n require_second=\"$(jq -r '.require_second_reviewer // false' cadre/config.json 2>/dev/null || echo false)\"\n if [ \"$verdict\" = \"absent\" ]; then\n echo \"::error::Track '$track_id' has no recorded review verdict. Run cadre-review before merging.\"\n exit 1\n fi\n if [ \"$verdict\" != \"approved\" ] || [ \"$blocking\" -gt 0 ]; then\n echo \"::error::Track '$track_id' has not cleared review (verdict: $verdict, blocking findings: $blocking).\"\n exit 1\n fi\n if [ \"$require_second\" = \"true\" ] && [ \"$self_reviewed\" = \"true\" ]; then\n echo \"::error::Track '$track_id' has only a self-review but require_second_reviewer is set.\"\n exit 1\n fi\n if [ -z \"$reviewed_sha\" ]; then\n echo \"::error::Track '$track_id' is missing review.reviewed_sha. Re-run cadre-review.\"\n exit 1\n fi\n if [ \"$reviewed_sha\" != \"$PR_HEAD_SHA\" ]; then\n echo \"::warning::PR head $PR_HEAD_SHA differs from review.reviewed_sha $reviewed_sha. This can be expected after ship/land rebases; Cadre enforces the hard pre-rebase guard during publication.\"\n fi\n echo \"Track '$track_id' review cleared.\"\n","ci/cadre-monorepo-check.gitlab.yml":"# Cadre target-project drift gate (GitLab CI).\n#\n# Scaffolded by cadre-setup into .gitlab-ci.yml. This template is for\n# Cadre-initialized product repositories, not the Cadre harness package. It\n# intentionally avoids harness-package drift gates, generated plugin checks,\n# and generator maintenance commands.\n\nstages:\n - check\n\ncadre-monorepo-check:\n stage: check\n image: alpine:latest\n rules:\n - if: '$CI_PIPELINE_SOURCE == \"merge_request_event\"'\n script:\n - apk add --no-cache bash jq git >/dev/null 2>&1 || true\n - |\n set -eu\n if [ ! -f cadre/tracks.json ]; then\n echo \"No cadre/tracks.json — skipping freshness gate.\"\n else\n entries=\"$(mktemp)\"\n expected=\"$(mktemp)\"\n actual=\"$(mktemp)\"\n : > \"$entries\"\n if [ -d cadre/tracks ]; then\n find cadre/tracks -mindepth 2 -maxdepth 2 -name metadata.json -print | sort | while read -r md; do\n dir=\"${md%metadata.json}\"\n jq \\\n --arg metadata_path \"$md\" \\\n --arg spec_path \"${dir}spec.json\" \\\n --arg plan_path \"${dir}plan.json\" \\\n '{track_id, name:(.name // .description // .track_id), status:(.status // \"new\"), priority:(.priority // \"medium\"), owner:(.owner // null), reviewer:(.reviewer // null), tags:(.tags // []), review:(.review // null), metadata_path:$metadata_path, spec_path:$spec_path, plan_path:$plan_path}' \\\n \"$md\" >> \"$entries\"\n done\n fi\n jq -S 'del(.generated_at)' cadre/tracks.json > \"$actual\"\n jq -S '{\n version: 1,\n schema: \"cadre.tracks_index.v1\",\n counts: (reduce .[] as $t ({new:0,in_progress:0,completed:0,blocked:0,skipped:0}; .[$t.status] = ((.[$t.status] // 0) + 1))),\n tracks: (sort_by(.track_id))\n }' \"$entries\" > \"$expected\"\n if ! diff -u \"$expected\" \"$actual\"; then\n echo \"ERROR: cadre/tracks.json is stale. Run cadre_mutate action regen_index through Cadre MCP and commit the result.\"\n exit 1\n fi\n echo \"cadre/tracks.json matches track metadata.\"\n fi\n - |\n set -eu\n mode=\"$(jq -r '.sync_mode // \"local\"' cadre/config.json 2>/dev/null || echo local)\"\n if [ \"$mode\" != \"shared\" ]; then\n echo \"sync_mode is '$mode' — skipping .gitattributes guard.\"\n else\n missing=0\n for line in \\\n 'cadre/tracks/**/parallel_state.json merge=ours'; do\n pat=\"$(printf '%s' \"$line\" | sed 's/ */[[:space:]][[:space:]]*/g')\"\n if ! grep -Eq \"$pat\" .gitattributes 2>/dev/null; then\n echo \"ERROR: Missing required shared-mode .gitattributes line: $line\"\n missing=1\n fi\n done\n [ \"$missing\" -eq 0 ] || exit 1\n echo \".gitattributes contains the required shared-mode merge rules.\"\n fi\n - |\n set -eu\n if [ ! -f cadre/config.json ]; then\n echo \"No cadre/config.json — skipping project gate.\"\n else\n gate=\"$(jq -r '.ci_check_command // .check_command // .review_machine_gate_command // .machine_gate_command // .test_command // empty' cadre/config.json)\"\n if [ -z \"$gate\" ]; then\n echo \"No Cadre project gate command configured.\"\n else\n echo \"Running Cadre project gate: $gate\"\n bash -lc \"$gate\"\n fi\n fi\n - |\n set -eu\n if [ ! -d cadre ]; then\n echo \"No cadre/ directory — review gate not initialized.\"\n exit 0\n fi\n HEAD_REF=\"${CI_MERGE_REQUEST_SOURCE_BRANCH_NAME:-}\"\n MR_HEAD_SHA=\"${CI_MERGE_REQUEST_SOURCE_BRANCH_SHA:-}\"\n case \"$HEAD_REF\" in\n track/*) track_id=\"${HEAD_REF#track/}\" ;;\n *)\n echo \"Source branch '$HEAD_REF' is not a track branch — review gate not applicable.\"\n exit 0 ;;\n esac\n META=\"cadre/tracks/$track_id/metadata.json\"\n if [ ! -f \"$META\" ]; then\n echo \"ERROR: Track branch '$HEAD_REF' has no $META — cannot verify review.\"\n exit 1\n fi\n verdict=\"$(jq -r '.review.verdict // \"absent\"' \"$META\")\"\n blocking=\"$(jq -r '.review.blocking_count // 0' \"$META\")\"\n self_reviewed=\"$(jq -r '.review.self_reviewed // false' \"$META\")\"\n reviewed_sha=\"$(jq -r '.review.reviewed_sha // \"\"' \"$META\")\"\n require_second=\"$(jq -r '.require_second_reviewer // false' cadre/config.json 2>/dev/null || echo false)\"\n if [ \"$verdict\" = \"absent\" ]; then\n echo \"ERROR: Track '$track_id' has no recorded review verdict. Run cadre-review before merging.\"\n exit 1\n fi\n if [ \"$verdict\" != \"approved\" ] || [ \"$blocking\" -gt 0 ]; then\n echo \"ERROR: Track '$track_id' has not cleared review (verdict: $verdict, blocking findings: $blocking).\"\n exit 1\n fi\n if [ \"$require_second\" = \"true\" ] && [ \"$self_reviewed\" = \"true\" ]; then\n echo \"ERROR: Track '$track_id' has only a self-review but require_second_reviewer is set.\"\n exit 1\n fi\n if [ -z \"$reviewed_sha\" ]; then\n echo \"ERROR: Track '$track_id' is missing review.reviewed_sha. Re-run cadre-review.\"\n exit 1\n fi\n if [ -n \"$MR_HEAD_SHA\" ] && [ \"$reviewed_sha\" != \"$MR_HEAD_SHA\" ]; then\n echo \"WARNING: MR head $MR_HEAD_SHA differs from review.reviewed_sha $reviewed_sha. This can be expected after ship/land rebases; Cadre enforces the hard pre-rebase guard during publication.\"\n fi\n echo \"Track '$track_id' review cleared.\"\n","config.json":"{\n \"sync_mode\": \"local\",\n \"auto_open\": false,\n \"require_second_reviewer\": false,\n \"allow_unreviewed_ship\": false,\n \"allow_unpinned_review_ship\": false,\n \"provider_mode\": \"local\",\n \"provider_mcp_required\": false,\n \"remote_host\": \"\",\n \"control_remote\": \"origin\",\n \"control_branch\": \"main\",\n \"pull_on_command_start\": true,\n \"coverage_command\": \"\",\n \"traceability\": {\n \"auto_product_commits\": true,\n \"auto_control_commits\": true,\n \"auto_automation_commits\": true,\n \"commit_local_wisps\": false,\n \"git_notes\": true,\n \"notes_ref\": \"refs/notes/cadre\",\n \"push_notes\": true\n },\n \"merge_train\": {\n \"enabled\": true,\n \"auto_fire\": true,\n \"group_label_prefix\": \"cadre-track\"\n }\n}\n","learnings_seed.json":"{\n \"version\": 1,\n \"schema\": \"cadre.learnings_seed.v1\",\n \"id\": \"initial\",\n \"kind\": \"learnings_seed\",\n \"text\": \"# Track Learnings: {{track_id}}\\n\\nPatterns, gotchas, and context discovered during implementation.\\n\\n## Codebase Patterns (Inherited)\\n\\n<!-- Patterns summarized from canonical cadre/patterns.jsonl events or archived track learnings -->\\n\\n---\\n\\n<!-- Learnings from implementation will be appended below -->\\n<!-- Format for each entry:\\n\\n## [YYYY-MM-DD HH:MM] - Phase N Task M: <task_name>\\nkey: <track_id>:p<i>:t<j>:<sha7>\\nSession/thread ref if available\\n- **Implemented:** <brief description of what was done>\\n- **Files changed:** <list of files modified/created>\\n- **Commit:** <sha_7chars>\\n- **Learnings:**\\n - Patterns: <reusable patterns discovered>\\n - Gotchas: <things to watch out for>\\n - Context: <useful context for future>\\n---\\n\\n-->\\n\"\n}\n","manifest.json":"{\n \"templates\": [\n {\n \"id\": \"product\",\n \"source\": \"product.json\",\n \"target\": \"cadre/product.json\",\n \"projection\": \"cadre/product.md\",\n \"purpose\": \"Product summary, users, workflows, domain model, invariants, architecture boundaries, data ownership, and release expectations.\",\n \"scope\": \"target-project\"\n },\n {\n \"id\": \"workflow\",\n \"source\": \"workflow.json\",\n \"target\": \"cadre/workflow.json\",\n \"projection\": \"cadre/workflow.md\",\n \"purpose\": \"Project development, verification, review, and commit expectations.\",\n \"scope\": \"target-project\"\n },\n {\n \"id\": \"product-guidelines\",\n \"source\": \"product_guidelines.json\",\n \"target\": \"cadre/product_guidelines.json\",\n \"projection\": \"cadre/product_guidelines.md\",\n \"purpose\": \"Product principles, user promises, non-goals, and decision rules reviewed during setup.\",\n \"scope\": \"target-project\"\n },\n {\n \"id\": \"patterns\",\n \"source\": \"patterns_seed.json\",\n \"target\": \"cadre/patterns.jsonl\",\n \"projection\": \"cadre/patterns.md\",\n \"purpose\": \"Reusable codebase patterns and completed-track learnings.\",\n \"scope\": \"target-project\"\n },\n {\n \"id\": \"learnings\",\n \"source\": \"learnings_seed.json\",\n \"target\": \"cadre/tracks/<track_id>/learnings.jsonl\",\n \"projection\": \"cadre/tracks/<track_id>/learnings.md\",\n \"purpose\": \"Per-track learning journal starter.\",\n \"scope\": \"target-project\"\n },\n {\n \"id\": \"config\",\n \"source\": \"config.json\",\n \"target\": \"cadre/config.json\",\n \"purpose\": \"Cadre sync, provider, review, and quality defaults.\",\n \"scope\": \"target-project\"\n },\n {\n \"id\": \"repos\",\n \"source\": \"repos.json\",\n \"target\": \"cadre/repos.json\",\n \"purpose\": \"Polyrepo topology starter.\",\n \"scope\": \"target-project\"\n },\n {\n \"id\": \"style-guides\",\n \"source\": \"styleguides/*.json\",\n \"target\": \"cadre/styleguides/*.json\",\n \"projection\": \"cadre/code_styleguides/*.md\",\n \"purpose\": \"Language-specific implementation guidance selected by setup packets.\",\n \"scope\": \"target-project\"\n },\n {\n \"id\": \"target-monorepo-ci\",\n \"source\": \"ci/cadre-monorepo-check.github.yml\",\n \"target\": \".github/workflows/cadre-monorepo-check.yml\",\n \"purpose\": \"Cadre target-project drift and review gate for GitHub monorepos.\",\n \"scope\": \"target-project\"\n },\n {\n \"id\": \"target-monorepo-ci-gitlab\",\n \"source\": \"ci/cadre-monorepo-check.gitlab.yml\",\n \"target\": \".gitlab-ci.yml\",\n \"purpose\": \"Cadre target-project drift and review gate for GitLab monorepos.\",\n \"scope\": \"target-project\"\n },\n {\n \"id\": \"polyrepo-merge-train-github\",\n \"source\": \"ci/cadre-merge-train.github.yml\",\n \"target\": \".github/workflows/cadre-merge-train.yml\",\n \"purpose\": \"Cross-repo merge train for GitHub polyrepo control repositories.\",\n \"scope\": \"target-project\"\n },\n {\n \"id\": \"polyrepo-merge-train-gitlab\",\n \"source\": \"ci/cadre-merge-train.gitlab.yml\",\n \"target\": \".gitlab-ci.yml\",\n \"purpose\": \"Cross-repo merge train for GitLab polyrepo control repositories.\",\n \"scope\": \"target-project\"\n }\n ]\n}\n","patterns_seed.json":"{\n \"version\": 1,\n \"schema\": \"cadre.patterns_seed.v1\",\n \"id\": \"initial\",\n \"kind\": \"patterns_seed\",\n \"text\": \"# Codebase Patterns\\n\\nReusable patterns discovered during development. **Read this before starting new work.**\\n\\nThis file is the project's institutional knowledge - learnings extracted from completed tracks that help future development.\\n\\n---\\n\\n## Code Conventions\\n\\n<!-- Patterns related to code style, naming, imports -->\\n\\n## Architecture\\n\\n<!-- Patterns related to architecture decisions, module structure -->\\n\\n## Gotchas\\n\\n<!-- Common mistakes to avoid, things that are easy to forget -->\\n\\n## Testing\\n\\n<!-- Patterns for testing approaches -->\\n\\n## Context\\n\\n<!-- Useful context about where things are located -->\\n\\n---\\n\\nLast refreshed: YYYY-MM-DD\\n\"\n}\n","product.json":"{\n \"version\": 1,\n \"schema\": \"cadre.product.v1\",\n \"kind\": \"product\",\n \"title\": \"Product Context\",\n \"summary\": \"Use this file to keep product intent detailed enough for agents to make\\nimplementation decisions without re-discovering the business model every time.\",\n \"sections\": [\n {\n \"heading\": \"Product Summary\",\n \"body\": \"- What the product is:\\n- Who it serves:\\n- Primary value proposition:\\n- Deployment or operating model:\"\n },\n {\n \"heading\": \"Users And Personas\",\n \"body\": \"- Primary users:\\n- Secondary users:\\n- Operators, administrators, or integrators:\\n- Permissions, tenancy, or access boundaries that shape user workflows:\"\n },\n {\n \"heading\": \"Core Workflows\",\n \"body\": \"- Workflow 1:\\n- Workflow 2:\\n- Workflow 3:\\n- Setup, onboarding, or provisioning flow:\\n- Review, audit, support, or recovery flow:\"\n },\n {\n \"heading\": \"Domain Model\",\n \"body\": \"- Core entities:\\n- Important relationships:\\n- State machines or lifecycle stages:\\n- Identifiers, keys, scopes, or hierarchy rules:\"\n },\n {\n \"heading\": \"Product Invariants\",\n \"body\": \"- Behaviors that must remain stable:\\n- Security, privacy, or compliance guarantees:\\n- Determinism, compatibility, or migration guarantees:\\n- Performance or availability expectations:\"\n },\n {\n \"heading\": \"Architecture Boundaries\",\n \"body\": \"- Public trust boundaries:\\n- Service or module ownership:\\n- API, SDK, CLI, or UI responsibilities:\\n- Generated artifacts or contracts that must stay in sync:\"\n },\n {\n \"heading\": \"Data And Integrations\",\n \"body\": \"- Primary data stores and ownership:\\n- External services or provider dependencies:\\n- Event, analytics, audit, or observability expectations:\\n- Data retention, privacy, or redaction rules:\"\n },\n {\n \"heading\": \"Quality And Release Expectations\",\n \"body\": \"- Test surfaces that protect product behavior:\\n- Documentation, API contract, or SDK fixture expectations:\\n- Rollout, migration, compatibility, or rollback requirements:\"\n },\n {\n \"heading\": \"Open Questions\",\n \"body\": \"- Product assumptions that still need confirmation:\\n- Known risks or decisions to revisit:\"\n }\n ]\n}\n","product_guidelines.json":"{\n \"version\": 1,\n \"schema\": \"cadre.product_guidelines.v1\",\n \"kind\": \"product_guidelines\",\n \"title\": \"Product Guidelines\",\n \"summary\": \"Use this file to capture product rules that should shape implementation choices,\\nreview decisions, and acceptance criteria.\",\n \"sections\": [\n {\n \"heading\": \"Product Principles\",\n \"body\": \"- Put the primary user workflow first.\\n- Prefer changes that reduce ambiguity in the user's next action.\\n- Keep product behavior explainable from the UI, docs, or API contract.\\n- Preserve explicit product invariants unless a spec intentionally revises them.\"\n },\n {\n \"heading\": \"User Promises\",\n \"body\": \"- Record promises the product must keep for users, teams, operators, or\\n integrators.\\n- Note the situations where reliability, privacy, accessibility, or performance\\n matter more than feature breadth.\"\n },\n {\n \"heading\": \"Trust And Safety Boundaries\",\n \"body\": \"- Record authentication, authorization, tenancy, privacy, and audit guarantees.\\n- Identify public trust boundaries and internal-only surfaces.\\n- State which data must be redacted, encrypted, scoped, or excluded from logs.\"\n },\n {\n \"heading\": \"Domain And Workflow Rules\",\n \"body\": \"- List lifecycle, state-machine, ordering, idempotency, and concurrency rules.\\n- Capture deterministic evaluation, attribution, or compatibility requirements.\\n- Note workflows that require preview, rollback, migration, or audit support.\"\n },\n {\n \"heading\": \"Data Ownership\",\n \"body\": \"- Map major product data to its owning store, service, module, or external\\n provider.\\n- Record generated artifacts, contracts, fixtures, migrations, or SDK assets that\\n must be updated alongside behavior changes.\"\n },\n {\n \"heading\": \"Non-Goals\",\n \"body\": \"- List behaviors, audiences, platforms, or workflows this project intentionally\\n does not serve yet.\\n- Record tempting shortcuts or alternate architectures that should not be used\\n without revising product context first.\"\n },\n {\n \"heading\": \"Decision Rules\",\n \"body\": \"- When product tradeoffs appear, write the rule the team should use to choose.\\n- Link decisions back to product context, usage evidence, support requests, or\\n explicit user feedback.\\n- Prefer tests and review evidence around product invariants, trust boundaries,\\n tenancy, authorization, data ownership, and public contracts.\"\n },\n {\n \"heading\": \"Review Checklist\",\n \"body\": \"- Does the change preserve the product invariants in `cadre/product.json`?\\n- Are user-visible behavior, docs, API contracts, SDK fixtures, generated\\n artifacts, and migrations updated together when needed?\\n- Are privacy, audit, observability, and rollback implications covered?\\n- Are non-goals and compatibility boundaries still respected?\"\n }\n ]\n}\n","repos.json":"{\n \"mode\": \"polyrepo\",\n \"control_repo\": { \"name\": \"REPLACE_control_repo_name\", \"path\": \".\" },\n \"default_repo\": \"REPLACE_default_repo_name\",\n \"repos\": [\n {\n \"name\": \"REPLACE_repo_name\",\n \"submodule_path\": \"repos/REPLACE_repo_name\",\n \"url\": \"git@host:org/REPLACE_repo_name.git\",\n \"default_branch\": \"main\",\n \"enabled\": true\n }\n ]\n}\n","styleguides/android.json":"{\n \"version\": 1,\n \"schema\": \"cadre.styleguide.v1\",\n \"kind\": \"styleguide\",\n \"id\": \"android\",\n \"title\": \"Android (Kotlin) Style Guide Summary\",\n \"summary\": \"This document summarizes key rules and best practices from the Android Kotlin Style Guide and Architecture Guidelines for building idiomatic, maintainable Android applications.\",\n \"sections\": [\n {\n \"heading\": \"1. Formatting and Tooling\",\n \"body\": \"- **ktlint:** Enforce via Gradle plugin. All code must pass `./gradlew ktlintCheck` before review.\\n- **detekt:** Use for static analysis beyond formatting. Fail CI on new issues.\\n- **Android Lint:** Run `./gradlew lint` and resolve all errors and relevant warnings before release builds.\\n- Follow all base [Kotlin Coding Conventions](kotlin.md) for formatting, naming, and language features.\"\n },\n {\n \"heading\": \"2. Architecture (MVVM + Clean)\",\n \"body\": \"- **MVVM:** Use ViewModel + LiveData/StateFlow + View/Fragment as the standard architecture. ViewModels must not hold references to `Context`, `View`, or `Fragment`.\\n- **Single-activity:** Prefer a single-activity app with multiple Fragments or Jetpack Compose destinations over multiple Activities.\\n- **Repository pattern:** Abstract data sources behind a `Repository` interface. ViewModels call repositories; repositories call data sources (API, Room, DataStore).\\n- **Use cases / Interactors:** Extract business logic into `UseCase` classes (one responsibility each) for complex or reused logic. Keep ViewModels thin.\\n- **Unidirectional data flow (UDF):** State flows down (ViewModel → View); events flow up (View → ViewModel). Use `StateFlow`/`SharedFlow` or sealed `UiState` classes.\"\n },\n {\n \"heading\": \"3. ViewModels\",\n \"body\": \"- **`viewModelScope`:** Always use `viewModelScope` to launch coroutines from a ViewModel. Coroutines are cancelled automatically when the ViewModel is cleared.\\n- **Expose `StateFlow`/`LiveData`, not `MutableStateFlow`/`MutableLiveData`:** Use backing properties: `private val _state = MutableStateFlow(...)` exposed as `val state: StateFlow<...> = _state.asStateFlow()`.\\n- **`UiState` sealed class:** Model screen state with a sealed class: `sealed class UiState { object Loading; data class Success(val data: T); data class Error(val message: String) }`.\\n- **No Android framework imports:** ViewModels must not import `android.*` classes (except `Application` in `AndroidViewModel`). This ensures testability.\\n- **`SavedStateHandle`:** Use `SavedStateHandle` in ViewModels to survive process death, not `onSaveInstanceState` in Fragments.\"\n },\n {\n \"heading\": \"4. Fragments and Activities\",\n \"body\": \"- **Fragment arguments via `newInstance`:** Always pass arguments via `Bundle` in a static `newInstance()` factory method. Never set properties directly on a Fragment after construction.\\n- **View binding:** Use View Binding (`viewBinding = true`) over `findViewById`. Never use synthetic imports (Kotlin Android Extensions is deprecated).\\n- **Lifecycle awareness:** Collect `Flow` in `lifecycleScope.launch { repeatOnLifecycle(STARTED) { ... } }`. Do not collect in `onCreate` without `repeatOnLifecycle`.\\n- **`onViewCreated`:** Set up views and observers in `onViewCreated`, not `onCreateView`. Release view references in `onDestroyView` (especially with View Binding: set binding to `null`).\\n- **Avoid back-stack manipulation:** Let the NavController manage the back stack. Do not call `fragmentManager.popBackStack()` manually.\"\n },\n {\n \"heading\": \"5. Jetpack Navigation\",\n \"body\": \"- **Single NavGraph per activity:** Define all destinations and actions in `nav_graph.xml`. Use nested graphs for feature modules.\\n- **Safe Args:** Use the Safe Args Gradle plugin for type-safe navigation arguments. Do not use raw `Bundle` keys for navigation data.\\n- **Deep links:** Declare deep link URIs in the NavGraph, not in `AndroidManifest.xml` `intent-filter` manually.\"\n },\n {\n \"heading\": \"6. Room (Database)\",\n \"body\": \"- **`@Entity`:** Every table is a `data class` annotated with `@Entity`. Name tables explicitly with `tableName`.\\n- **`@Dao` interfaces:** Use `suspend` functions in DAOs for insert/update/delete. Return `Flow<T>` for queries to observe changes reactively.\\n- **No business logic in DAOs:** DAOs perform only data access. Transformations and filtering go in the repository or use case.\\n- **Database migrations:** Always write an explicit `Migration` for schema changes. Never use `fallbackToDestructiveMigration()` in production.\\n- **`@TypeConverter`:** Register converters for non-primitive types (e.g., `Date`, enums, custom objects).\"\n },\n {\n \"heading\": \"7. Networking (Retrofit + OkHttp)\",\n \"body\": \"- **Suspend functions in API interfaces:** Use `suspend fun` in Retrofit service interfaces — no `Call<T>`, no RxJava.\\n- **Sealed result types:** Wrap API responses in a `Result<T>` or `NetworkResult<T>` sealed class in the repository. Never expose raw Retrofit exceptions to ViewModels.\\n- **OkHttp interceptors:** Use interceptors for auth headers, logging (`HttpLoggingInterceptor`), and retry logic. Do not add auth logic inside API service interfaces.\\n- **Timeouts:** Always configure connect, read, and write timeouts on `OkHttpClient`. Never use the default (unlimited) timeouts.\"\n },\n {\n \"heading\": \"8. Dependency Injection (Hilt)\",\n \"body\": \"- **Hilt over manual DI:** Use Hilt (built on Dagger) as the standard DI framework. Avoid `ServiceLocator` patterns.\\n- **`@HiltViewModel`:** Annotate all ViewModels. Inject via `by viewModels()` in Fragments/Activities.\\n- **`@Singleton` scope:** Scope repositories and network clients to `@Singleton`. Scope ViewModels to `@HiltViewModel` (automatic).\\n- **Modules for external dependencies:** Create `@Module` + `@InstallIn` classes to provide third-party types (Retrofit, Room, etc.) that cannot be annotated directly.\"\n },\n {\n \"heading\": \"9. Permissions\",\n \"body\": \"- **Request at the latest possible moment:** Ask for permissions immediately before the feature that needs them, not at app launch.\\n- **`ActivityResultContracts`:** Use `registerForActivityResult(RequestPermission())` — not `onRequestPermissionsResult`.\\n- **Handle denial gracefully:** Always handle both granted and denied cases. Show rationale with `shouldShowRequestPermissionRationale` before re-requesting.\"\n },\n {\n \"heading\": \"10. Testing\",\n \"body\": \"- **ViewModel tests:** Test ViewModels with JUnit 4/5 and `kotlinx-coroutines-test`. Use `TestCoroutineDispatcher`/`UnconfinedTestDispatcher` and `Turbine` for `Flow` assertions.\\n- **Robolectric for unit tests:** Use Robolectric for tests needing Android framework context without an emulator.\\n- **Espresso / Compose UI tests:** Write UI tests for critical user journeys. Use `IdlingResource` for async operations in Espresso.\\n- **Fake over mock:** Prefer fake implementations of repositories/data sources over Mockito mocks for ViewModel tests. Fakes are more maintainable and realistic.\"\n },\n {\n \"heading\": \"11. Resources\",\n \"body\": \"- **Naming conventions:**\\n - Layouts: `fragment_user_profile.xml`, `item_order_card.xml`, `view_loading_spinner.xml`\\n - IDs: `@+id/tvUserName` (type prefix) or `@+id/userNameText` (descriptive) — pick one and be consistent.\\n - Strings: `user_profile_title`, `error_network_unavailable` — use `feature_description` format.\\n - Drawables: `ic_` for icons, `bg_` for backgrounds, `img_` for images.\\n- **`strings.xml`:** All user-visible strings go in `strings.xml`. No hardcoded strings in layouts or code.\\n- **Dimensions:** Define reusable spacing in `dimens.xml`. Use `8dp` grid system.\\n\\n*Sources: [Android Kotlin Style Guide](https://developer.android.com/kotlin/style-guide) · [Guide to app architecture](https://developer.android.com/topic/architecture) · [Hilt docs](https://developer.android.com/training/dependency-injection/hilt-android)*\"\n }\n ],\n \"languages\": [\n \"android\"\n ],\n \"frameworks\": [],\n \"file_patterns\": [],\n \"applies_to\": [\n \"planning\",\n \"implementation\",\n \"review\",\n \"tests\"\n ],\n \"rules\": [\n {\n \"id\": \"android-rule-1\",\n \"severity\": \"guidance\",\n \"summary\": \"**ktlint:** Enforce via Gradle plugin. All code must pass `./gradlew ktlintCheck` before review.\"\n },\n {\n \"id\": \"android-rule-2\",\n \"severity\": \"guidance\",\n \"summary\": \"**detekt:** Use for static analysis beyond formatting. Fail CI on new issues.\"\n },\n {\n \"id\": \"android-rule-3\",\n \"severity\": \"guidance\",\n \"summary\": \"**Android Lint:** Run `./gradlew lint` and resolve all errors and relevant warnings before release builds.\"\n },\n {\n \"id\": \"android-rule-4\",\n \"severity\": \"guidance\",\n \"summary\": \"Follow all base [Kotlin Coding Conventions](kotlin.md) for formatting, naming, and language features.\"\n },\n {\n \"id\": \"android-rule-5\",\n \"severity\": \"guidance\",\n \"summary\": \"**MVVM:** Use ViewModel + LiveData/StateFlow + View/Fragment as the standard architecture. ViewModels must not hold references to `Context`, `View`, or `Fragment`.\"\n },\n {\n \"id\": \"android-rule-6\",\n \"severity\": \"guidance\",\n \"summary\": \"**Single-activity:** Prefer a single-activity app with multiple Fragments or Jetpack Compose destinations over multiple Activities.\"\n },\n {\n \"id\": \"android-rule-7\",\n \"severity\": \"guidance\",\n \"summary\": \"**Repository pattern:** Abstract data sources behind a `Repository` interface. ViewModels call repositories; repositories call data sources (API, Room, DataStore).\"\n },\n {\n \"id\": \"android-rule-8\",\n \"severity\": \"guidance\",\n \"summary\": \"**Use cases / Interactors:** Extract business logic into `UseCase` classes (one responsibility each) for complex or reused logic. Keep ViewModels thin.\"\n },\n {\n \"id\": \"android-rule-9\",\n \"severity\": \"guidance\",\n \"summary\": \"**Unidirectional data flow (UDF):** State flows down (ViewModel → View); events flow up (View → ViewModel). Use `StateFlow`/`SharedFlow` or sealed `UiState` classes.\"\n },\n {\n \"id\": \"android-rule-10\",\n \"severity\": \"guidance\",\n \"summary\": \"**`viewModelScope`:** Always use `viewModelScope` to launch coroutines from a ViewModel. Coroutines are cancelled automatically when the ViewModel is cleared.\"\n },\n {\n \"id\": \"android-rule-11\",\n \"severity\": \"guidance\",\n \"summary\": \"**Expose `StateFlow`/`LiveData`, not `MutableStateFlow`/`MutableLiveData`:** Use backing properties: `private val _state = MutableStateFlow(...)` exposed as `val state: StateFlow<...> = _state.asStateFlow()`.\"\n },\n {\n \"id\": \"android-rule-12\",\n \"severity\": \"guidance\",\n \"summary\": \"**`UiState` sealed class:** Model screen state with a sealed class: `sealed class UiState { object Loading; data class Success(val data: T); data class Error(val message: String) }`.\"\n },\n {\n \"id\": \"android-rule-13\",\n \"severity\": \"guidance\",\n \"summary\": \"**No Android framework imports:** ViewModels must not import `android.*` classes (except `Application` in `AndroidViewModel`). This ensures testability.\"\n },\n {\n \"id\": \"android-rule-14\",\n \"severity\": \"guidance\",\n \"summary\": \"**`SavedStateHandle`:** Use `SavedStateHandle` in ViewModels to survive process death, not `onSaveInstanceState` in Fragments.\"\n },\n {\n \"id\": \"android-rule-15\",\n \"severity\": \"guidance\",\n \"summary\": \"**Fragment arguments via `newInstance`:** Always pass arguments via `Bundle` in a static `newInstance()` factory method. Never set properties directly on a Fragment after construction.\"\n },\n {\n \"id\": \"android-rule-16\",\n \"severity\": \"guidance\",\n \"summary\": \"**View binding:** Use View Binding (`viewBinding = true`) over `findViewById`. Never use synthetic imports (Kotlin Android Extensions is deprecated).\"\n },\n {\n \"id\": \"android-rule-17\",\n \"severity\": \"guidance\",\n \"summary\": \"**Lifecycle awareness:** Collect `Flow` in `lifecycleScope.launch { repeatOnLifecycle(STARTED) { ... } }`. Do not collect in `onCreate` without `repeatOnLifecycle`.\"\n },\n {\n \"id\": \"android-rule-18\",\n \"severity\": \"guidance\",\n \"summary\": \"**`onViewCreated`:** Set up views and observers in `onViewCreated`, not `onCreateView`. Release view references in `onDestroyView` (especially with View Binding: set binding to `null`).\"\n },\n {\n \"id\": \"android-rule-19\",\n \"severity\": \"guidance\",\n \"summary\": \"**Avoid back-stack manipulation:** Let the NavController manage the back stack. Do not call `fragmentManager.popBackStack()` manually.\"\n },\n {\n \"id\": \"android-rule-20\",\n \"severity\": \"guidance\",\n \"summary\": \"**Single NavGraph per activity:** Define all destinations and actions in `nav_graph.xml`. Use nested graphs for feature modules.\"\n },\n {\n \"id\": \"android-rule-21\",\n \"severity\": \"guidance\",\n \"summary\": \"**Safe Args:** Use the Safe Args Gradle plugin for type-safe navigation arguments. Do not use raw `Bundle` keys for navigation data.\"\n },\n {\n \"id\": \"android-rule-22\",\n \"severity\": \"guidance\",\n \"summary\": \"**Deep links:** Declare deep link URIs in the NavGraph, not in `AndroidManifest.xml` `intent-filter` manually.\"\n },\n {\n \"id\": \"android-rule-23\",\n \"severity\": \"guidance\",\n \"summary\": \"**`@Entity`:** Every table is a `data class` annotated with `@Entity`. Name tables explicitly with `tableName`.\"\n },\n {\n \"id\": \"android-rule-24\",\n \"severity\": \"guidance\",\n \"summary\": \"**`@Dao` interfaces:** Use `suspend` functions in DAOs for insert/update/delete. Return `Flow<T>` for queries to observe changes reactively.\"\n },\n {\n \"id\": \"android-rule-25\",\n \"severity\": \"guidance\",\n \"summary\": \"**No business logic in DAOs:** DAOs perform only data access. Transformations and filtering go in the repository or use case.\"\n },\n {\n \"id\": \"android-rule-26\",\n \"severity\": \"guidance\",\n \"summary\": \"**Database migrations:** Always write an explicit `Migration` for schema changes. Never use `fallbackToDestructiveMigration()` in production.\"\n },\n {\n \"id\": \"android-rule-27\",\n \"severity\": \"guidance\",\n \"summary\": \"**`@TypeConverter`:** Register converters for non-primitive types (e.g., `Date`, enums, custom objects).\"\n },\n {\n \"id\": \"android-rule-28\",\n \"severity\": \"guidance\",\n \"summary\": \"**Suspend functions in API interfaces:** Use `suspend fun` in Retrofit service interfaces — no `Call<T>`, no RxJava.\"\n },\n {\n \"id\": \"android-rule-29\",\n \"severity\": \"guidance\",\n \"summary\": \"**Sealed result types:** Wrap API responses in a `Result<T>` or `NetworkResult<T>` sealed class in the repository. Never expose raw Retrofit exceptions to ViewModels.\"\n },\n {\n \"id\": \"android-rule-30\",\n \"severity\": \"guidance\",\n \"summary\": \"**OkHttp interceptors:** Use interceptors for auth headers, logging (`HttpLoggingInterceptor`), and retry logic. Do not add auth logic inside API service interfaces.\"\n },\n {\n \"id\": \"android-rule-31\",\n \"severity\": \"guidance\",\n \"summary\": \"**Timeouts:** Always configure connect, read, and write timeouts on `OkHttpClient`. Never use the default (unlimited) timeouts.\"\n },\n {\n \"id\": \"android-rule-32\",\n \"severity\": \"guidance\",\n \"summary\": \"**Hilt over manual DI:** Use Hilt (built on Dagger) as the standard DI framework. Avoid `ServiceLocator` patterns.\"\n },\n {\n \"id\": \"android-rule-33\",\n \"severity\": \"guidance\",\n \"summary\": \"**`@HiltViewModel`:** Annotate all ViewModels. Inject via `by viewModels()` in Fragments/Activities.\"\n },\n {\n \"id\": \"android-rule-34\",\n \"severity\": \"guidance\",\n \"summary\": \"**`@Singleton` scope:** Scope repositories and network clients to `@Singleton`. Scope ViewModels to `@HiltViewModel` (automatic).\"\n },\n {\n \"id\": \"android-rule-35\",\n \"severity\": \"guidance\",\n \"summary\": \"**Modules for external dependencies:** Create `@Module` + `@InstallIn` classes to provide third-party types (Retrofit, Room, etc.) that cannot be annotated directly.\"\n },\n {\n \"id\": \"android-rule-36\",\n \"severity\": \"guidance\",\n \"summary\": \"**Request at the latest possible moment:** Ask for permissions immediately before the feature that needs them, not at app launch.\"\n },\n {\n \"id\": \"android-rule-37\",\n \"severity\": \"guidance\",\n \"summary\": \"**`ActivityResultContracts`:** Use `registerForActivityResult(RequestPermission())` — not `onRequestPermissionsResult`.\"\n },\n {\n \"id\": \"android-rule-38\",\n \"severity\": \"guidance\",\n \"summary\": \"**Handle denial gracefully:** Always handle both granted and denied cases. Show rationale with `shouldShowRequestPermissionRationale` before re-requesting.\"\n },\n {\n \"id\": \"android-rule-39\",\n \"severity\": \"guidance\",\n \"summary\": \"**ViewModel tests:** Test ViewModels with JUnit 4/5 and `kotlinx-coroutines-test`. Use `TestCoroutineDispatcher`/`UnconfinedTestDispatcher` and `Turbine` for `Flow` assertions.\"\n },\n {\n \"id\": \"android-rule-40\",\n \"severity\": \"guidance\",\n \"summary\": \"**Robolectric for unit tests:** Use Robolectric for tests needing Android framework context without an emulator.\"\n },\n {\n \"id\": \"android-rule-41\",\n \"severity\": \"guidance\",\n \"summary\": \"**Espresso / Compose UI tests:** Write UI tests for critical user journeys. Use `IdlingResource` for async operations in Espresso.\"\n },\n {\n \"id\": \"android-rule-42\",\n \"severity\": \"guidance\",\n \"summary\": \"**Fake over mock:** Prefer fake implementations of repositories/data sources over Mockito mocks for ViewModel tests. Fakes are more maintainable and realistic.\"\n },\n {\n \"id\": \"android-rule-43\",\n \"severity\": \"guidance\",\n \"summary\": \"**Naming conventions:**\"\n },\n {\n \"id\": \"android-rule-44\",\n \"severity\": \"guidance\",\n \"summary\": \"Layouts: `fragment_user_profile.xml`, `item_order_card.xml`, `view_loading_spinner.xml`\"\n },\n {\n \"id\": \"android-rule-45\",\n \"severity\": \"guidance\",\n \"summary\": \"IDs: `@+id/tvUserName` (type prefix) or `@+id/userNameText` (descriptive) — pick one and be consistent.\"\n },\n {\n \"id\": \"android-rule-46\",\n \"severity\": \"guidance\",\n \"summary\": \"Strings: `user_profile_title`, `error_network_unavailable` — use `feature_description` format.\"\n },\n {\n \"id\": \"android-rule-47\",\n \"severity\": \"guidance\",\n \"summary\": \"Drawables: `ic_` for icons, `bg_` for backgrounds, `img_` for images.\"\n },\n {\n \"id\": \"android-rule-48\",\n \"severity\": \"guidance\",\n \"summary\": \"**`strings.xml`:** All user-visible strings go in `strings.xml`. No hardcoded strings in layouts or code.\"\n },\n {\n \"id\": \"android-rule-49\",\n \"severity\": \"guidance\",\n \"summary\": \"**Dimensions:** Define reusable spacing in `dimens.xml`. Use `8dp` grid system.\"\n }\n ],\n \"source\": \"bundled_template\"\n}\n","styleguides/compose-multiplatform.json":"{\n \"version\": 1,\n \"schema\": \"cadre.styleguide.v1\",\n \"kind\": \"styleguide\",\n \"id\": \"compose-multiplatform\",\n \"title\": \"Compose Multiplatform Style Guide Summary\",\n \"summary\": \"This document summarizes key rules and best practices for building idiomatic, high-performance, and maintainable Compose Multiplatform (CMP) applications across Android, iOS, Desktop, and Web.\",\n \"sections\": [\n {\n \"heading\": \"1. Formatting and Tooling\",\n \"body\": \"- **ktlint & detekt:** Enforce via Gradle plugins. All code must pass linting before merging.\\n- **Compose Rules (detekt-compose):** Use Twitter/Facebook/Custom Compose lint rules to catch common performance pitfalls (e.g., \\\"MutableState in ViewModel should be private\\\").\\n- **Trailing lambdas:** Always use trailing lambda syntax for the content parameter of a Composable.\\n- **Naming:**\\n - **Composables:** `UpperCamelCase` (e.g., `PrimaryButton`). Names must be nouns.\\n - **Composable factories:** `UpperCamelCase` if they return `Unit`.\\n - **Modifier extensions:** `lowerCamelCase` (e.g., `Modifier.customPadding()`).\"\n },\n {\n \"heading\": \"2. Architecture (UDF + Component-based)\",\n \"body\": \"- **Unidirectional Data Flow (UDF):** State flows down (State); Events flow up (Callbacks).\\n- **State over Events:** Prefer modeling screen state as a single `UiState` data class rather than multiple independent flows.\\n- **ViewModel (Multiplatform):** Use `androidx.lifecycle.ViewModel` (now multiplatform-ready) or a shared `CmpViewModel` to hold logic.\\n- **Component-based UI:** Break UI into small, reusable, and stateless Composables. A Composable over 50 lines is a candidate for decomposition.\\n- **Stateless vs Stateful:**\\n - **Stateless:** Accepts state as parameters and emits events via callbacks. High reusability.\\n - **Stateful:** Manages its own state or interacts with a ViewModel. Use sparingly at the screen/feature root.\"\n },\n {\n \"heading\": \"3. Composable Design\",\n \"body\": \"- **Modifier as first optional parameter:** Every UI Composable should accept a `modifier: Modifier = Modifier` as its first optional parameter.\\n ```kotlin\\n @Composable\\n fun MyComponent(\\n text: String,\\n modifier: Modifier = Modifier,\\n onClicked: () -> Unit\\n ) { ... }\\n ```\\n- **Explicit parameter ordering:** Required parameters first, then `modifier`, then optional parameters, then the trailing lambda (if any).\\n- **Stability:** Ensure parameters are stable or immutable. Use `@Stable` or `@Immutable` on domain models if Compose cannot infer it. Avoid passing `List` directly; use `ImmutableList` (from kotlinx-collections-immutable) or a wrapper.\\n- **Slot API:** Use the \\\"Slot\\\" pattern (accepting `@Composable () -> Unit` lambdas) to increase flexibility and avoid deep parameter propogation.\"\n },\n {\n \"heading\": \"4. State Management\",\n \"body\": \"- **`remember` & `mutableStateOf`:** Use for local, UI-only state. Always use `rememberSaveable` for state that must survive configuration changes (Android).\\n- **`StateFlow` to `State`:** Collect flows using `collectAsStateWithLifecycle()` (requires `lifecycle-runtime-compose` multiplatform) to ensure lifecycle-aware updates.\\n- **State Hoisting:** Lift state up to make Composables stateless. The caller should control the state.\\n- **Don't pass `MutableState`:** Pass the raw value and a callback function, never a `MutableState<T>` object, to child Composables.\\n- **Side Effects:** Use `LaunchedEffect`, `SideEffect`, and `DisposableEffect` correctly. Never perform side effects directly in the Composable's body.\"\n },\n {\n \"heading\": \"5. Multiplatform Patterns (Expect/Actual)\",\n \"body\": \"- **Platform-specific UI:** Use `expect`/`actual` for platform-native components (e.g., `MapView`, `WebView`).\\n- **CompositionLocal:** Use `CompositionLocal` for cross-cutting concerns like Themes, Localizations, or Platform-specific configurations.\\n- **Platform Check:** Use `LocalWindowInfo.current` or custom platform-specific `CompositionLocal` instead of hardcoded platform checks inside generic UI code.\\n- **Shared Resources:** Use `Compose Multiplatform Resources` (lib) for shared strings, fonts, and images.\"\n },\n {\n \"heading\": \"6. Layout and Modifiers\",\n \"body\": \"- **Modifier Order Matters:** Modifiers are applied sequentially. `Modifier.padding(8.dp).clickable { }` is different from `Modifier.clickable { }.padding(8.dp)`.\\n- **Prefer `weight` in Rows/Columns:** Use `Modifier.weight()` for flexible layouts rather than hardcoded sizes.\\n- **Avoid `fillMaxSize()` in nested scrolling:** Use `wrapContentHeight()` or specific sizes to avoid infinite height constraints in `LazyColumn`.\\n- **Custom Modifiers:** Extract repeated modifier chains into extension functions for readability.\"\n },\n {\n \"heading\": \"7. Navigation\",\n \"body\": \"- **Compose Navigation Multiplatform:** Use the official `androidx.navigation:navigation-compose` (now Multiplatform).\\n- **Type-safe Navigation:** Use Kotlin Serialization with the Navigation component for type-safe arguments.\\n- **Single NavHost:** Keep the `NavHost` at the top level of each platform's entry point or in a shared `App()` Composable.\"\n },\n {\n \"heading\": \"8. Performance\",\n \"body\": \"- **Minimize Recomposition:** \\n - Pass only necessary data.\\n - Use `derivedStateOf` for state that depends on other state to avoid redundant recompositions.\\n - Use `remember` with keys to cache expensive calculations.\\n- **Lazy Collections:** Always use `LazyColumn`, `LazyRow`, and `LazyVerticalGrid` for large or dynamic lists. Use `key` in `items()` for stable identification.\\n- **Avoid heavy computation in `@Composable`:** Move business logic and heavy mapping to the ViewModel or use `remember`.\\n- **Phase isolation:** Use `Modifier.graphicsLayer` or lambda-based modifiers (e.g., `Modifier.offset { ... }`) for frequent updates like animations to skip the \\\"recomposition\\\" and \\\"layout\\\" phases.\"\n },\n {\n \"heading\": \"9. Testing\",\n \"body\": \"- **Compose UI Test:** Use `createComposeRule()` (Android) and `runComposeUiTest` (Multiplatform) to verify UI behavior.\\n- **Semantics:** Use `Modifier.semantics { contentDescription = \\\"...\\\" }` to make UI testable and accessible.\\n- **Screenshot Testing:** Use libraries like Roborazzi or Paparazzi for cross-platform visual regression testing.\"\n },\n {\n \"heading\": \"10. Desktop & iOS Specifics\",\n \"body\": \"- **Desktop:** Handle window resizing, keyboard shortcuts, and mouse hover states using `onPointerEvent`.\\n- **iOS:** Ensure `UIKitView` is used correctly for native interop. Respect safe area insets via `WindowInsets.safeDrawing`.\\n- **Web (Wasm/JS):** Be mindful of heavy computations as Wasm/JS performance characteristics differ from JVM/Native.\\n\\n*Sources: [Compose Multiplatform Docs](https://www.jetbrains.com/lp/compose-multiplatform/) · [Jetpack Compose Best Practices](https://developer.android.com/develop/ui/compose/performance) · [Kotlin Multiplatform Guidelines](https://kotlinlang.org/docs/multiplatform.html)*\"\n }\n ],\n \"languages\": [\n \"compose-multiplatform\"\n ],\n \"frameworks\": [],\n \"file_patterns\": [],\n \"applies_to\": [\n \"planning\",\n \"implementation\",\n \"review\",\n \"tests\"\n ],\n \"rules\": [\n {\n \"id\": \"compose-multiplatform-rule-1\",\n \"severity\": \"guidance\",\n \"summary\": \"**ktlint & detekt:** Enforce via Gradle plugins. All code must pass linting before merging.\"\n },\n {\n \"id\": \"compose-multiplatform-rule-2\",\n \"severity\": \"guidance\",\n \"summary\": \"**Compose Rules (detekt-compose):** Use Twitter/Facebook/Custom Compose lint rules to catch common performance pitfalls (e.g., \\\"MutableState in ViewModel should be private\\\").\"\n },\n {\n \"id\": \"compose-multiplatform-rule-3\",\n \"severity\": \"guidance\",\n \"summary\": \"**Trailing lambdas:** Always use trailing lambda syntax for the content parameter of a Composable.\"\n },\n {\n \"id\": \"compose-multiplatform-rule-4\",\n \"severity\": \"guidance\",\n \"summary\": \"**Naming:**\"\n },\n {\n \"id\": \"compose-multiplatform-rule-5\",\n \"severity\": \"guidance\",\n \"summary\": \"**Composables:** `UpperCamelCase` (e.g., `PrimaryButton`). Names must be nouns.\"\n },\n {\n \"id\": \"compose-multiplatform-rule-6\",\n \"severity\": \"guidance\",\n \"summary\": \"**Composable factories:** `UpperCamelCase` if they return `Unit`.\"\n },\n {\n \"id\": \"compose-multiplatform-rule-7\",\n \"severity\": \"guidance\",\n \"summary\": \"**Modifier extensions:** `lowerCamelCase` (e.g., `Modifier.customPadding()`).\"\n },\n {\n \"id\": \"compose-multiplatform-rule-8\",\n \"severity\": \"guidance\",\n \"summary\": \"**Unidirectional Data Flow (UDF):** State flows down (State); Events flow up (Callbacks).\"\n },\n {\n \"id\": \"compose-multiplatform-rule-9\",\n \"severity\": \"guidance\",\n \"summary\": \"**State over Events:** Prefer modeling screen state as a single `UiState` data class rather than multiple independent flows.\"\n },\n {\n \"id\": \"compose-multiplatform-rule-10\",\n \"severity\": \"guidance\",\n \"summary\": \"**ViewModel (Multiplatform):** Use `androidx.lifecycle.ViewModel` (now multiplatform-ready) or a shared `CmpViewModel` to hold logic.\"\n },\n {\n \"id\": \"compose-multiplatform-rule-11\",\n \"severity\": \"guidance\",\n \"summary\": \"**Component-based UI:** Break UI into small, reusable, and stateless Composables. A Composable over 50 lines is a candidate for decomposition.\"\n },\n {\n \"id\": \"compose-multiplatform-rule-12\",\n \"severity\": \"guidance\",\n \"summary\": \"**Stateless vs Stateful:**\"\n },\n {\n \"id\": \"compose-multiplatform-rule-13\",\n \"severity\": \"guidance\",\n \"summary\": \"**Stateless:** Accepts state as parameters and emits events via callbacks. High reusability.\"\n },\n {\n \"id\": \"compose-multiplatform-rule-14\",\n \"severity\": \"guidance\",\n \"summary\": \"**Stateful:** Manages its own state or interacts with a ViewModel. Use sparingly at the screen/feature root.\"\n },\n {\n \"id\": \"compose-multiplatform-rule-15\",\n \"severity\": \"guidance\",\n \"summary\": \"**Modifier as first optional parameter:** Every UI Composable should accept a `modifier: Modifier = Modifier` as its first optional parameter.\"\n },\n {\n \"id\": \"compose-multiplatform-rule-16\",\n \"severity\": \"guidance\",\n \"summary\": \"**Explicit parameter ordering:** Required parameters first, then `modifier`, then optional parameters, then the trailing lambda (if any).\"\n },\n {\n \"id\": \"compose-multiplatform-rule-17\",\n \"severity\": \"guidance\",\n \"summary\": \"**Stability:** Ensure parameters are stable or immutable. Use `@Stable` or `@Immutable` on domain models if Compose cannot infer it. Avoid passing `List` directly; use `ImmutableList` (from kotlinx-collections-immutable) or a wrapper.\"\n },\n {\n \"id\": \"compose-multiplatform-rule-18\",\n \"severity\": \"guidance\",\n \"summary\": \"**Slot API:** Use the \\\"Slot\\\" pattern (accepting `@Composable () -> Unit` lambdas) to increase flexibility and avoid deep parameter propogation.\"\n },\n {\n \"id\": \"compose-multiplatform-rule-19\",\n \"severity\": \"guidance\",\n \"summary\": \"**`remember` & `mutableStateOf`:** Use for local, UI-only state. Always use `rememberSaveable` for state that must survive configuration changes (Android).\"\n },\n {\n \"id\": \"compose-multiplatform-rule-20\",\n \"severity\": \"guidance\",\n \"summary\": \"**`StateFlow` to `State`:** Collect flows using `collectAsStateWithLifecycle()` (requires `lifecycle-runtime-compose` multiplatform) to ensure lifecycle-aware updates.\"\n },\n {\n \"id\": \"compose-multiplatform-rule-21\",\n \"severity\": \"guidance\",\n \"summary\": \"**State Hoisting:** Lift state up to make Composables stateless. The caller should control the state.\"\n },\n {\n \"id\": \"compose-multiplatform-rule-22\",\n \"severity\": \"guidance\",\n \"summary\": \"**Don't pass `MutableState`:** Pass the raw value and a callback function, never a `MutableState<T>` object, to child Composables.\"\n },\n {\n \"id\": \"compose-multiplatform-rule-23\",\n \"severity\": \"guidance\",\n \"summary\": \"**Side Effects:** Use `LaunchedEffect`, `SideEffect`, and `DisposableEffect` correctly. Never perform side effects directly in the Composable's body.\"\n },\n {\n \"id\": \"compose-multiplatform-rule-24\",\n \"severity\": \"guidance\",\n \"summary\": \"**Platform-specific UI:** Use `expect`/`actual` for platform-native components (e.g., `MapView`, `WebView`).\"\n },\n {\n \"id\": \"compose-multiplatform-rule-25\",\n \"severity\": \"guidance\",\n \"summary\": \"**CompositionLocal:** Use `CompositionLocal` for cross-cutting concerns like Themes, Localizations, or Platform-specific configurations.\"\n },\n {\n \"id\": \"compose-multiplatform-rule-26\",\n \"severity\": \"guidance\",\n \"summary\": \"**Platform Check:** Use `LocalWindowInfo.current` or custom platform-specific `CompositionLocal` instead of hardcoded platform checks inside generic UI code.\"\n },\n {\n \"id\": \"compose-multiplatform-rule-27\",\n \"severity\": \"guidance\",\n \"summary\": \"**Shared Resources:** Use `Compose Multiplatform Resources` (lib) for shared strings, fonts, and images.\"\n },\n {\n \"id\": \"compose-multiplatform-rule-28\",\n \"severity\": \"guidance\",\n \"summary\": \"**Modifier Order Matters:** Modifiers are applied sequentially. `Modifier.padding(8.dp).clickable { }` is different from `Modifier.clickable { }.padding(8.dp)`.\"\n },\n {\n \"id\": \"compose-multiplatform-rule-29\",\n \"severity\": \"guidance\",\n \"summary\": \"**Prefer `weight` in Rows/Columns:** Use `Modifier.weight()` for flexible layouts rather than hardcoded sizes.\"\n },\n {\n \"id\": \"compose-multiplatform-rule-30\",\n \"severity\": \"guidance\",\n \"summary\": \"**Avoid `fillMaxSize()` in nested scrolling:** Use `wrapContentHeight()` or specific sizes to avoid infinite height constraints in `LazyColumn`.\"\n },\n {\n \"id\": \"compose-multiplatform-rule-31\",\n \"severity\": \"guidance\",\n \"summary\": \"**Custom Modifiers:** Extract repeated modifier chains into extension functions for readability.\"\n },\n {\n \"id\": \"compose-multiplatform-rule-32\",\n \"severity\": \"guidance\",\n \"summary\": \"**Compose Navigation Multiplatform:** Use the official `androidx.navigation:navigation-compose` (now Multiplatform).\"\n },\n {\n \"id\": \"compose-multiplatform-rule-33\",\n \"severity\": \"guidance\",\n \"summary\": \"**Type-safe Navigation:** Use Kotlin Serialization with the Navigation component for type-safe arguments.\"\n },\n {\n \"id\": \"compose-multiplatform-rule-34\",\n \"severity\": \"guidance\",\n \"summary\": \"**Single NavHost:** Keep the `NavHost` at the top level of each platform's entry point or in a shared `App()` Composable.\"\n },\n {\n \"id\": \"compose-multiplatform-rule-35\",\n \"severity\": \"guidance\",\n \"summary\": \"**Minimize Recomposition:**\"\n },\n {\n \"id\": \"compose-multiplatform-rule-36\",\n \"severity\": \"guidance\",\n \"summary\": \"Pass only necessary data.\"\n },\n {\n \"id\": \"compose-multiplatform-rule-37\",\n \"severity\": \"guidance\",\n \"summary\": \"Use `derivedStateOf` for state that depends on other state to avoid redundant recompositions.\"\n },\n {\n \"id\": \"compose-multiplatform-rule-38\",\n \"severity\": \"guidance\",\n \"summary\": \"Use `remember` with keys to cache expensive calculations.\"\n },\n {\n \"id\": \"compose-multiplatform-rule-39\",\n \"severity\": \"guidance\",\n \"summary\": \"**Lazy Collections:** Always use `LazyColumn`, `LazyRow`, and `LazyVerticalGrid` for large or dynamic lists. Use `key` in `items()` for stable identification.\"\n },\n {\n \"id\": \"compose-multiplatform-rule-40\",\n \"severity\": \"guidance\",\n \"summary\": \"**Avoid heavy computation in `@Composable`:** Move business logic and heavy mapping to the ViewModel or use `remember`.\"\n },\n {\n \"id\": \"compose-multiplatform-rule-41\",\n \"severity\": \"guidance\",\n \"summary\": \"**Phase isolation:** Use `Modifier.graphicsLayer` or lambda-based modifiers (e.g., `Modifier.offset { ... }`) for frequent updates like animations to skip the \\\"recomposition\\\" and \\\"layout\\\" phases.\"\n },\n {\n \"id\": \"compose-multiplatform-rule-42\",\n \"severity\": \"guidance\",\n \"summary\": \"**Compose UI Test:** Use `createComposeRule()` (Android) and `runComposeUiTest` (Multiplatform) to verify UI behavior.\"\n },\n {\n \"id\": \"compose-multiplatform-rule-43\",\n \"severity\": \"guidance\",\n \"summary\": \"**Semantics:** Use `Modifier.semantics { contentDescription = \\\"...\\\" }` to make UI testable and accessible.\"\n },\n {\n \"id\": \"compose-multiplatform-rule-44\",\n \"severity\": \"guidance\",\n \"summary\": \"**Screenshot Testing:** Use libraries like Roborazzi or Paparazzi for cross-platform visual regression testing.\"\n },\n {\n \"id\": \"compose-multiplatform-rule-45\",\n \"severity\": \"guidance\",\n \"summary\": \"**Desktop:** Handle window resizing, keyboard shortcuts, and mouse hover states using `onPointerEvent`.\"\n },\n {\n \"id\": \"compose-multiplatform-rule-46\",\n \"severity\": \"guidance\",\n \"summary\": \"**iOS:** Ensure `UIKitView` is used correctly for native interop. Respect safe area insets via `WindowInsets.safeDrawing`.\"\n },\n {\n \"id\": \"compose-multiplatform-rule-47\",\n \"severity\": \"guidance\",\n \"summary\": \"**Web (Wasm/JS):** Be mindful of heavy computations as Wasm/JS performance characteristics differ from JVM/Native.\"\n }\n ],\n \"source\": \"bundled_template\"\n}\n","styleguides/dart.json":"{\n \"version\": 1,\n \"schema\": \"cadre.styleguide.v1\",\n \"kind\": \"styleguide\",\n \"id\": \"dart\",\n \"title\": \"Effective Dart Style Guide Summary\",\n \"summary\": \"This document summarizes key rules and best practices from the official \\\"Effective Dart\\\" guide for writing idiomatic, performant, and maintainable Dart code.\",\n \"sections\": [\n {\n \"heading\": \"1. Formatting\",\n \"body\": \"- **`dart format`:** All Dart code **must** be formatted with `dart format` (formerly `dartfmt`). Non-negotiable.\\n- **Indentation:** 2 spaces. No tabs.\\n- **Line Length:** 80 characters maximum.\\n- **Trailing commas:** Add a trailing comma after the last item in multi-line argument/parameter lists to keep `dart format` from collapsing them to one line.\"\n },\n {\n \"heading\": \"2. Naming\",\n \"body\": \"- **`UpperCamelCase`:** For classes, enums, typedefs, and type parameters.\\n- **`lowerCamelCase`:** For variables, parameters, named parameters, functions, methods, and constant variables.\\n- **`lowercase_with_underscores`:** For libraries, packages, directories, and source files.\\n- **`_lowerCamelCase`:** For private identifiers (prefix with `_`).\\n- **Acronyms:** Capitalize only the first letter — `Http`, `Url`, `Json`, not `HTTP`, `URL`, `JSON` (exception: well-known two-letter acronyms like `IO`).\\n- **Boolean naming:** Name boolean variables and getters as affirmative phrases: `isEmpty`, `hasChildren`, `canClose`. Avoid `isNotEmpty` as a variable name.\"\n },\n {\n \"heading\": \"3. Types\",\n \"body\": \"- **Prefer type inference:** Let Dart infer types for local variables (`var x = ...`). Annotate when the type is not obvious or when required for API clarity.\\n- **`dynamic`:** Avoid `dynamic`. Use it only when genuinely dynamic behavior is needed. Prefer `Object?` for unknown values.\\n- **`Object` vs `dynamic`:** Prefer `Object?` for a type that accepts any value — it still participates in type checking; `dynamic` opts out entirely.\\n- **`var` vs explicit type:** Use `var` for local variables. Use explicit types for top-level and class-level declarations.\\n- **Nullable vs non-nullable:** With null safety, prefer non-nullable types. Only add `?` when `null` is a genuinely valid value.\\n- **Late variables:** Use `late` only when initialization is deferred but guaranteed before use. Prefer passing values in constructors.\"\n },\n {\n \"heading\": \"4. Functions and Methods\",\n \"body\": \"- **Named parameters:** Prefer named parameters for functions with more than two parameters or when parameter meaning is not obvious from the call site.\\n- **Required named parameters:** Mark mandatory named parameters `required`. Do not simulate with assertions on nullable params.\\n- **Arrow functions:** Use `=>` for simple single-expression functions and getters.\\n- **`async`/`await`:** Prefer `async`/`await` over raw `Future` chaining (`.then`, `.catchError`). Never mix them in the same function body.\\n- **Avoid `async` without `await`:** Do not mark a function `async` if it does not contain `await`.\\n- **`Stream`:** Return `Stream` for multiple asynchronous values. Use `async*` with `yield` to create streams.\"\n },\n {\n \"heading\": \"5. Variables and Control Flow\",\n \"body\": \"- **`final` by default:** Prefer `final` for variables that are not reassigned. Use `const` for compile-time constants.\\n- **`const` constructors:** Define `const` constructors for immutable classes. Use `const` at call sites for constant objects.\\n- **`??` and `?.`:** Use the null-aware operators instead of explicit null checks. Use `??=` for lazy initialization.\\n- **Cascade (`..`):** Use cascades to perform a sequence of operations on the same object. Do not cascade when the receiver is a temporary.\\n- **`is` over `as`:** Prefer `if (obj is Foo)` over `(obj as Foo)` to avoid runtime cast errors.\\n- **Avoid `late final` + nullable:** Pick one. Either the variable is `late` and always initialized, or it is nullable.\"\n },\n {\n \"heading\": \"6. Collections\",\n \"body\": \"- **Collection literals:** Use `[]`, `{}`, `<K,V>{}` over `List()`, `Set()`, `Map()` constructors.\\n- **Collection-if and collection-for:** Use these inside literals instead of building collections with `add`/`addAll` in a loop.\\n- **Spreads (`...`):** Use the spread operator to combine collections. Prefer over `addAll`.\\n- **`where`, `map`, `toList()`:** Chain iterable methods for transformations. Call `toList()` at the end to materialize only once.\\n- **Avoid `length` for emptiness:** Use `isEmpty`/`isNotEmpty` instead of `list.length == 0`.\"\n },\n {\n \"heading\": \"7. Classes and Constructors\",\n \"body\": \"- **Initializer lists:** Initialize fields in the initializer list, not the constructor body.\\n- **Shorthand field initialization:** Use `this.field` constructor parameters to initialize fields directly.\\n- **Factory constructors:** Use `factory` for constructors that return a cached or subtype instance.\\n- **`@immutable`:** Annotate classes with `@immutable` when all fields are `final`.\\n- **No public `late` fields:** Avoid public `late` fields. Prefer constructor initialization.\\n- **Extension methods:** Use extensions to add methods to existing types without subclassing.\"\n },\n {\n \"heading\": \"8. Error Handling\",\n \"body\": \"- **Exceptions for programming errors:** Throw `Error` subtypes (e.g., `ArgumentError`, `StateError`) for programming mistakes.\\n- **Exceptions for runtime failures:** Throw `Exception` subtypes for runtime failures the caller can recover from.\\n- **Avoid catching `Error`:** Catch specific exception types. Catching `Object` or `Error` is a sign of poor error modeling.\\n- **`on` before `catch`:** Use `on ExceptionType catch (e)` to restrict what you catch. Never use a bare `catch` without `on`.\"\n },\n {\n \"heading\": \"9. Documentation\",\n \"body\": \"- **`///` doc comments:** Use `///` (not `/** */`) for documentation on all public APIs.\\n- **Single-sentence summary:** Start every doc comment with a one-sentence summary that ends with a period.\\n- **Markdown:** Doc comments support Markdown. Use code blocks (`` ` ``) for inline code references.\\n- **`@param`, `@returns`:** Do not use these tags — Dart doc tools read the prose. Write parameter descriptions inline.\\n- **Prose over tags:** Describe behavior, edge cases, and usage in full sentences.\\n\\n*Source: [Effective Dart](https://dart.dev/effective-dart)*\"\n }\n ],\n \"languages\": [\n \"dart\"\n ],\n \"frameworks\": [],\n \"file_patterns\": [],\n \"applies_to\": [\n \"planning\",\n \"implementation\",\n \"review\",\n \"tests\"\n ],\n \"rules\": [\n {\n \"id\": \"dart-rule-1\",\n \"severity\": \"guidance\",\n \"summary\": \"**`dart format`:** All Dart code **must** be formatted with `dart format` (formerly `dartfmt`). Non-negotiable.\"\n },\n {\n \"id\": \"dart-rule-2\",\n \"severity\": \"guidance\",\n \"summary\": \"**Indentation:** 2 spaces. No tabs.\"\n },\n {\n \"id\": \"dart-rule-3\",\n \"severity\": \"guidance\",\n \"summary\": \"**Line Length:** 80 characters maximum.\"\n },\n {\n \"id\": \"dart-rule-4\",\n \"severity\": \"guidance\",\n \"summary\": \"**Trailing commas:** Add a trailing comma after the last item in multi-line argument/parameter lists to keep `dart format` from collapsing them to one line.\"\n },\n {\n \"id\": \"dart-rule-5\",\n \"severity\": \"guidance\",\n \"summary\": \"**`UpperCamelCase`:** For classes, enums, typedefs, and type parameters.\"\n },\n {\n \"id\": \"dart-rule-6\",\n \"severity\": \"guidance\",\n \"summary\": \"**`lowerCamelCase`:** For variables, parameters, named parameters, functions, methods, and constant variables.\"\n },\n {\n \"id\": \"dart-rule-7\",\n \"severity\": \"guidance\",\n \"summary\": \"**`lowercase_with_underscores`:** For libraries, packages, directories, and source files.\"\n },\n {\n \"id\": \"dart-rule-8\",\n \"severity\": \"guidance\",\n \"summary\": \"**`_lowerCamelCase`:** For private identifiers (prefix with `_`).\"\n },\n {\n \"id\": \"dart-rule-9\",\n \"severity\": \"guidance\",\n \"summary\": \"**Acronyms:** Capitalize only the first letter — `Http`, `Url`, `Json`, not `HTTP`, `URL`, `JSON` (exception: well-known two-letter acronyms like `IO`).\"\n },\n {\n \"id\": \"dart-rule-10\",\n \"severity\": \"guidance\",\n \"summary\": \"**Boolean naming:** Name boolean variables and getters as affirmative phrases: `isEmpty`, `hasChildren`, `canClose`. Avoid `isNotEmpty` as a variable name.\"\n },\n {\n \"id\": \"dart-rule-11\",\n \"severity\": \"guidance\",\n \"summary\": \"**Prefer type inference:** Let Dart infer types for local variables (`var x = ...`). Annotate when the type is not obvious or when required for API clarity.\"\n },\n {\n \"id\": \"dart-rule-12\",\n \"severity\": \"guidance\",\n \"summary\": \"**`dynamic`:** Avoid `dynamic`. Use it only when genuinely dynamic behavior is needed. Prefer `Object?` for unknown values.\"\n },\n {\n \"id\": \"dart-rule-13\",\n \"severity\": \"guidance\",\n \"summary\": \"**`Object` vs `dynamic`:** Prefer `Object?` for a type that accepts any value — it still participates in type checking; `dynamic` opts out entirely.\"\n },\n {\n \"id\": \"dart-rule-14\",\n \"severity\": \"guidance\",\n \"summary\": \"**`var` vs explicit type:** Use `var` for local variables. Use explicit types for top-level and class-level declarations.\"\n },\n {\n \"id\": \"dart-rule-15\",\n \"severity\": \"guidance\",\n \"summary\": \"**Nullable vs non-nullable:** With null safety, prefer non-nullable types. Only add `?` when `null` is a genuinely valid value.\"\n },\n {\n \"id\": \"dart-rule-16\",\n \"severity\": \"guidance\",\n \"summary\": \"**Late variables:** Use `late` only when initialization is deferred but guaranteed before use. Prefer passing values in constructors.\"\n },\n {\n \"id\": \"dart-rule-17\",\n \"severity\": \"guidance\",\n \"summary\": \"**Named parameters:** Prefer named parameters for functions with more than two parameters or when parameter meaning is not obvious from the call site.\"\n },\n {\n \"id\": \"dart-rule-18\",\n \"severity\": \"guidance\",\n \"summary\": \"**Required named parameters:** Mark mandatory named parameters `required`. Do not simulate with assertions on nullable params.\"\n },\n {\n \"id\": \"dart-rule-19\",\n \"severity\": \"guidance\",\n \"summary\": \"**Arrow functions:** Use `=>` for simple single-expression functions and getters.\"\n },\n {\n \"id\": \"dart-rule-20\",\n \"severity\": \"guidance\",\n \"summary\": \"**`async`/`await`:** Prefer `async`/`await` over raw `Future` chaining (`.then`, `.catchError`). Never mix them in the same function body.\"\n },\n {\n \"id\": \"dart-rule-21\",\n \"severity\": \"guidance\",\n \"summary\": \"**Avoid `async` without `await`:** Do not mark a function `async` if it does not contain `await`.\"\n },\n {\n \"id\": \"dart-rule-22\",\n \"severity\": \"guidance\",\n \"summary\": \"**`Stream`:** Return `Stream` for multiple asynchronous values. Use `async*` with `yield` to create streams.\"\n },\n {\n \"id\": \"dart-rule-23\",\n \"severity\": \"guidance\",\n \"summary\": \"**`final` by default:** Prefer `final` for variables that are not reassigned. Use `const` for compile-time constants.\"\n },\n {\n \"id\": \"dart-rule-24\",\n \"severity\": \"guidance\",\n \"summary\": \"**`const` constructors:** Define `const` constructors for immutable classes. Use `const` at call sites for constant objects.\"\n },\n {\n \"id\": \"dart-rule-25\",\n \"severity\": \"guidance\",\n \"summary\": \"**`??` and `?.`:** Use the null-aware operators instead of explicit null checks. Use `??=` for lazy initialization.\"\n },\n {\n \"id\": \"dart-rule-26\",\n \"severity\": \"guidance\",\n \"summary\": \"**Cascade (`..`):** Use cascades to perform a sequence of operations on the same object. Do not cascade when the receiver is a temporary.\"\n },\n {\n \"id\": \"dart-rule-27\",\n \"severity\": \"guidance\",\n \"summary\": \"**`is` over `as`:** Prefer `if (obj is Foo)` over `(obj as Foo)` to avoid runtime cast errors.\"\n },\n {\n \"id\": \"dart-rule-28\",\n \"severity\": \"guidance\",\n \"summary\": \"**Avoid `late final` + nullable:** Pick one. Either the variable is `late` and always initialized, or it is nullable.\"\n },\n {\n \"id\": \"dart-rule-29\",\n \"severity\": \"guidance\",\n \"summary\": \"**Collection literals:** Use `[]`, `{}`, `<K,V>{}` over `List()`, `Set()`, `Map()` constructors.\"\n },\n {\n \"id\": \"dart-rule-30\",\n \"severity\": \"guidance\",\n \"summary\": \"**Collection-if and collection-for:** Use these inside literals instead of building collections with `add`/`addAll` in a loop.\"\n },\n {\n \"id\": \"dart-rule-31\",\n \"severity\": \"guidance\",\n \"summary\": \"**Spreads (`...`):** Use the spread operator to combine collections. Prefer over `addAll`.\"\n },\n {\n \"id\": \"dart-rule-32\",\n \"severity\": \"guidance\",\n \"summary\": \"**`where`, `map`, `toList()`:** Chain iterable methods for transformations. Call `toList()` at the end to materialize only once.\"\n },\n {\n \"id\": \"dart-rule-33\",\n \"severity\": \"guidance\",\n \"summary\": \"**Avoid `length` for emptiness:** Use `isEmpty`/`isNotEmpty` instead of `list.length == 0`.\"\n },\n {\n \"id\": \"dart-rule-34\",\n \"severity\": \"guidance\",\n \"summary\": \"**Initializer lists:** Initialize fields in the initializer list, not the constructor body.\"\n },\n {\n \"id\": \"dart-rule-35\",\n \"severity\": \"guidance\",\n \"summary\": \"**Shorthand field initialization:** Use `this.field` constructor parameters to initialize fields directly.\"\n },\n {\n \"id\": \"dart-rule-36\",\n \"severity\": \"guidance\",\n \"summary\": \"**Factory constructors:** Use `factory` for constructors that return a cached or subtype instance.\"\n },\n {\n \"id\": \"dart-rule-37\",\n \"severity\": \"guidance\",\n \"summary\": \"**`@immutable`:** Annotate classes with `@immutable` when all fields are `final`.\"\n },\n {\n \"id\": \"dart-rule-38\",\n \"severity\": \"guidance\",\n \"summary\": \"**No public `late` fields:** Avoid public `late` fields. Prefer constructor initialization.\"\n },\n {\n \"id\": \"dart-rule-39\",\n \"severity\": \"guidance\",\n \"summary\": \"**Extension methods:** Use extensions to add methods to existing types without subclassing.\"\n },\n {\n \"id\": \"dart-rule-40\",\n \"severity\": \"guidance\",\n \"summary\": \"**Exceptions for programming errors:** Throw `Error` subtypes (e.g., `ArgumentError`, `StateError`) for programming mistakes.\"\n },\n {\n \"id\": \"dart-rule-41\",\n \"severity\": \"guidance\",\n \"summary\": \"**Exceptions for runtime failures:** Throw `Exception` subtypes for runtime failures the caller can recover from.\"\n },\n {\n \"id\": \"dart-rule-42\",\n \"severity\": \"guidance\",\n \"summary\": \"**Avoid catching `Error`:** Catch specific exception types. Catching `Object` or `Error` is a sign of poor error modeling.\"\n },\n {\n \"id\": \"dart-rule-43\",\n \"severity\": \"guidance\",\n \"summary\": \"**`on` before `catch`:** Use `on ExceptionType catch (e)` to restrict what you catch. Never use a bare `catch` without `on`.\"\n },\n {\n \"id\": \"dart-rule-44\",\n \"severity\": \"guidance\",\n \"summary\": \"**`///` doc comments:** Use `///` (not `/** */`) for documentation on all public APIs.\"\n },\n {\n \"id\": \"dart-rule-45\",\n \"severity\": \"guidance\",\n \"summary\": \"**Single-sentence summary:** Start every doc comment with a one-sentence summary that ends with a period.\"\n },\n {\n \"id\": \"dart-rule-46\",\n \"severity\": \"guidance\",\n \"summary\": \"**Markdown:** Doc comments support Markdown. Use code blocks (`` ` ``) for inline code references.\"\n },\n {\n \"id\": \"dart-rule-47\",\n \"severity\": \"guidance\",\n \"summary\": \"**`@param`, `@returns`:** Do not use these tags — Dart doc tools read the prose. Write parameter descriptions inline.\"\n },\n {\n \"id\": \"dart-rule-48\",\n \"severity\": \"guidance\",\n \"summary\": \"**Prose over tags:** Describe behavior, edge cases, and usage in full sentences.\"\n }\n ],\n \"source\": \"bundled_template\"\n}\n","styleguides/flutter.json":"{\n \"version\": 1,\n \"schema\": \"cadre.styleguide.v1\",\n \"kind\": \"styleguide\",\n \"id\": \"flutter\",\n \"title\": \"Effective Flutter Style Guide Summary\",\n \"summary\": \"This document summarizes key rules and best practices for writing idiomatic Flutter code, building on Effective Dart with Flutter-specific widget, state, and performance conventions.\",\n \"sections\": [\n {\n \"heading\": \"1. Formatting and Tooling\",\n \"body\": \"- **`dart format`:** All Flutter code must be formatted with `dart format`. Run via `flutter format .`.\\n- **`flutter analyze`:** Treat all analyzer warnings as errors. Enforce in CI.\\n- **Trailing commas:** Always add trailing commas after the last argument in multi-line widget trees — this keeps `dart format` from collapsing widget hierarchies to one line.\\n- **Import ordering:** `dart:` → `package:flutter/` → other `package:` → relative imports.\"\n },\n {\n \"heading\": \"2. Widget Design\",\n \"body\": \"- **`StatelessWidget` by default:** Reach for `StatelessWidget` first. Only use `StatefulWidget` when local mutable state is genuinely needed.\\n- **Small, composable widgets:** Prefer extracting reusable pieces into their own widgets over large `build` methods. A build method over ~50 lines is a sign it should be split.\\n- **`const` constructors everywhere:** Define `const` constructors on all widgets. Use `const` at call sites to skip unnecessary rebuilds.\\n- **`Key` usage:** Pass `Key` to the parent `Widget` constructor, not to child widgets inside `build`. Use `ValueKey`, `ObjectKey`, or `UniqueKey` — not `GlobalKey` unless absolutely required (e.g., form validation, imperative scroll).\\n- **`Widget` over helper methods:** Extract sub-trees into separate `Widget` classes rather than private `_buildXxx()` methods. Widget classes participate in the element tree and optimize rebuilds; helper methods do not.\"\n },\n {\n \"heading\": \"3. State Management\",\n \"body\": \"- **Lift state up:** Keep state as low in the tree as needed and no lower. Share state by lifting to a common ancestor.\\n- **`setState` scope:** Call `setState` with the minimum code needed. Only pass the mutation, not the full rebuild computation.\\n- **Avoid storing `BuildContext` across async gaps:** After an `await`, check `mounted` before using `context`. Never store `context` in a field for later use.\\n- **Inherited widgets / providers:** Use `InheritedWidget`, `Provider`, `Riverpod`, or `Bloc` for state that many widgets need. Do not prop-drill through 3+ layers.\\n- **`initState` / `dispose`:** Always pair resource acquisition (`initState`, `addListener`) with release (`dispose`, `removeListener`). Never call `setState` in `initState`.\\n- **`didChangeDependencies`:** Use for operations that depend on `InheritedWidget` values, not `initState`.\"\n },\n {\n \"heading\": \"4. Performance\",\n \"body\": \"- **`const` widgets:** Mark widgets and their constructors `const` whenever possible — this is the single highest-ROI optimization in Flutter.\\n- **`ListView.builder`:** Use `ListView.builder` (or `GridView.builder`, `CustomScrollView`) for lists of unknown or large length. Never use `ListView(children: items.map(...).toList())` for long lists.\\n- **`RepaintBoundary`:** Wrap expensive, independently-animating subtrees in `RepaintBoundary` to isolate repaints.\\n- **Avoid rebuilding with `AnimatedBuilder`:** Pass only the widget that changes as the `child` parameter — it is cached and not rebuilt on animation ticks.\\n- **`ImageCache` and `precacheImage`:** Precache images likely to be shown soon. Prefer `AssetImage`/`NetworkImage` with proper caching over `Image.memory` for large images.\\n- **Avoid work in `build`:** Never compute values, parse data, or make network calls inside `build()`. Compute in `initState`, `didUpdateWidget`, or a state management layer.\"\n },\n {\n \"heading\": \"5. Layout\",\n \"body\": \"- **Prefer `Column`/`Row` over `Stack` where possible:** `Stack` is for overlay scenarios; prefer linear layouts for sequential content.\\n- **`Expanded` and `Flexible`:** Use `Expanded` to fill remaining space. Use `Flexible` when you want to allow shrinking. Never use `SizedBox.expand()` inside `Column`/`Row` — use `Expanded`.\\n- **`SizedBox` for spacing:** Prefer `SizedBox(height: 8)` over `Padding(padding: EdgeInsets.only(top: 8))` for simple fixed spacing.\\n- **`MediaQuery` and `LayoutBuilder`:** Use `LayoutBuilder` for widget-local responsive constraints. Use `MediaQuery.of(context)` sparingly — changes trigger full rebuilds.\\n- **Avoid unbounded height/width:** `Column` inside a `ListView` without a bounded height will throw. Use `shrinkWrap: true` or wrap in `SizedBox` with an explicit dimension when nesting scrollables.\"\n },\n {\n \"heading\": \"6. Navigation and Routing\",\n \"body\": \"- **Named routes or `go_router`:** Prefer declarative routing (`go_router`, `auto_route`) over imperative `Navigator.push` for deep linking and complex flows.\\n- **`WillPopScope` / `PopScope`:** Handle back navigation explicitly when there is unsaved state or a multi-step flow.\\n- **Pass data via constructor, not `arguments`:** Prefer typed constructor injection over `ModalRoute.of(context)!.settings.arguments`. Use route parameters with `go_router`.\"\n },\n {\n \"heading\": \"7. Theming and Styling\",\n \"body\": \"- **Use `Theme.of(context)`:** Never hardcode colors or text styles. Always derive from the active `ThemeData`.\\n- **`TextTheme`:** Use `Theme.of(context).textTheme.bodyLarge` etc. — do not define ad-hoc `TextStyle` objects everywhere.\\n- **`ColorScheme`:** Use Material 3's `ColorScheme` roles (`primary`, `surface`, `onPrimary`) rather than direct `Color` values.\\n- **`ThemeExtension`:** Define custom theme data in a `ThemeExtension<T>` instead of global constants.\"\n },\n {\n \"heading\": \"8. Testing\",\n \"body\": \"- **Widget tests over unit tests for UI:** Test widget behavior with `flutter_test`'s `WidgetTester`. Avoid screenshot testing as the primary regression tool.\\n- **`find.byType`, `find.byKey`:** Prefer `find.byKey(ValueKey('submit'))` for interactive elements. Use `find.byType` for presence checks.\\n- **`pumpAndSettle`:** Use after triggering async operations. Use `pump(Duration)` for animations you control explicitly.\\n- **Golden tests:** Use sparingly — they are brittle across platforms. Gate on a single reference platform in CI.\"\n },\n {\n \"heading\": \"9. Naming and File Structure\",\n \"body\": \"- **One widget per file:** Each top-level `Widget` subclass lives in its own file.\\n- **File names match class names:** `UserProfileCard` → `user_profile_card.dart`.\\n- **Feature-first folder structure:** Group by feature (`lib/features/auth/`, `lib/features/home/`), not by type (`lib/widgets/`, `lib/models/`).\\n- **`_` prefix for private widgets:** Private helper widgets within a file are prefixed with `_`.\\n\\n*Sources: [Flutter Docs](https://docs.flutter.dev) · [Effective Dart](https://dart.dev/effective-dart) · [Flutter Performance Best Practices](https://docs.flutter.dev/perf/best-practices)*\"\n }\n ],\n \"languages\": [\n \"flutter\"\n ],\n \"frameworks\": [],\n \"file_patterns\": [],\n \"applies_to\": [\n \"planning\",\n \"implementation\",\n \"review\",\n \"tests\"\n ],\n \"rules\": [\n {\n \"id\": \"flutter-rule-1\",\n \"severity\": \"guidance\",\n \"summary\": \"**`dart format`:** All Flutter code must be formatted with `dart format`. Run via `flutter format .`.\"\n },\n {\n \"id\": \"flutter-rule-2\",\n \"severity\": \"guidance\",\n \"summary\": \"**`flutter analyze`:** Treat all analyzer warnings as errors. Enforce in CI.\"\n },\n {\n \"id\": \"flutter-rule-3\",\n \"severity\": \"guidance\",\n \"summary\": \"**Trailing commas:** Always add trailing commas after the last argument in multi-line widget trees — this keeps `dart format` from collapsing widget hierarchies to one line.\"\n },\n {\n \"id\": \"flutter-rule-4\",\n \"severity\": \"guidance\",\n \"summary\": \"**Import ordering:** `dart:` → `package:flutter/` → other `package:` → relative imports.\"\n },\n {\n \"id\": \"flutter-rule-5\",\n \"severity\": \"guidance\",\n \"summary\": \"**`StatelessWidget` by default:** Reach for `StatelessWidget` first. Only use `StatefulWidget` when local mutable state is genuinely needed.\"\n },\n {\n \"id\": \"flutter-rule-6\",\n \"severity\": \"guidance\",\n \"summary\": \"**Small, composable widgets:** Prefer extracting reusable pieces into their own widgets over large `build` methods. A build method over ~50 lines is a sign it should be split.\"\n },\n {\n \"id\": \"flutter-rule-7\",\n \"severity\": \"guidance\",\n \"summary\": \"**`const` constructors everywhere:** Define `const` constructors on all widgets. Use `const` at call sites to skip unnecessary rebuilds.\"\n },\n {\n \"id\": \"flutter-rule-8\",\n \"severity\": \"guidance\",\n \"summary\": \"**`Key` usage:** Pass `Key` to the parent `Widget` constructor, not to child widgets inside `build`. Use `ValueKey`, `ObjectKey`, or `UniqueKey` — not `GlobalKey` unless absolutely required (e.g., form validation, imperative scroll).\"\n },\n {\n \"id\": \"flutter-rule-9\",\n \"severity\": \"guidance\",\n \"summary\": \"**`Widget` over helper methods:** Extract sub-trees into separate `Widget` classes rather than private `_buildXxx()` methods. Widget classes participate in the element tree and optimize rebuilds; helper methods do not.\"\n },\n {\n \"id\": \"flutter-rule-10\",\n \"severity\": \"guidance\",\n \"summary\": \"**Lift state up:** Keep state as low in the tree as needed and no lower. Share state by lifting to a common ancestor.\"\n },\n {\n \"id\": \"flutter-rule-11\",\n \"severity\": \"guidance\",\n \"summary\": \"**`setState` scope:** Call `setState` with the minimum code needed. Only pass the mutation, not the full rebuild computation.\"\n },\n {\n \"id\": \"flutter-rule-12\",\n \"severity\": \"guidance\",\n \"summary\": \"**Avoid storing `BuildContext` across async gaps:** After an `await`, check `mounted` before using `context`. Never store `context` in a field for later use.\"\n },\n {\n \"id\": \"flutter-rule-13\",\n \"severity\": \"guidance\",\n \"summary\": \"**Inherited widgets / providers:** Use `InheritedWidget`, `Provider`, `Riverpod`, or `Bloc` for state that many widgets need. Do not prop-drill through 3+ layers.\"\n },\n {\n \"id\": \"flutter-rule-14\",\n \"severity\": \"guidance\",\n \"summary\": \"**`initState` / `dispose`:** Always pair resource acquisition (`initState`, `addListener`) with release (`dispose`, `removeListener`). Never call `setState` in `initState`.\"\n },\n {\n \"id\": \"flutter-rule-15\",\n \"severity\": \"guidance\",\n \"summary\": \"**`didChangeDependencies`:** Use for operations that depend on `InheritedWidget` values, not `initState`.\"\n },\n {\n \"id\": \"flutter-rule-16\",\n \"severity\": \"guidance\",\n \"summary\": \"**`const` widgets:** Mark widgets and their constructors `const` whenever possible — this is the single highest-ROI optimization in Flutter.\"\n },\n {\n \"id\": \"flutter-rule-17\",\n \"severity\": \"guidance\",\n \"summary\": \"**`ListView.builder`:** Use `ListView.builder` (or `GridView.builder`, `CustomScrollView`) for lists of unknown or large length. Never use `ListView(children: items.map(...).toList())` for long lists.\"\n },\n {\n \"id\": \"flutter-rule-18\",\n \"severity\": \"guidance\",\n \"summary\": \"**`RepaintBoundary`:** Wrap expensive, independently-animating subtrees in `RepaintBoundary` to isolate repaints.\"\n },\n {\n \"id\": \"flutter-rule-19\",\n \"severity\": \"guidance\",\n \"summary\": \"**Avoid rebuilding with `AnimatedBuilder`:** Pass only the widget that changes as the `child` parameter — it is cached and not rebuilt on animation ticks.\"\n },\n {\n \"id\": \"flutter-rule-20\",\n \"severity\": \"guidance\",\n \"summary\": \"**`ImageCache` and `precacheImage`:** Precache images likely to be shown soon. Prefer `AssetImage`/`NetworkImage` with proper caching over `Image.memory` for large images.\"\n },\n {\n \"id\": \"flutter-rule-21\",\n \"severity\": \"guidance\",\n \"summary\": \"**Avoid work in `build`:** Never compute values, parse data, or make network calls inside `build()`. Compute in `initState`, `didUpdateWidget`, or a state management layer.\"\n },\n {\n \"id\": \"flutter-rule-22\",\n \"severity\": \"guidance\",\n \"summary\": \"**Prefer `Column`/`Row` over `Stack` where possible:** `Stack` is for overlay scenarios; prefer linear layouts for sequential content.\"\n },\n {\n \"id\": \"flutter-rule-23\",\n \"severity\": \"guidance\",\n \"summary\": \"**`Expanded` and `Flexible`:** Use `Expanded` to fill remaining space. Use `Flexible` when you want to allow shrinking. Never use `SizedBox.expand()` inside `Column`/`Row` — use `Expanded`.\"\n },\n {\n \"id\": \"flutter-rule-24\",\n \"severity\": \"guidance\",\n \"summary\": \"**`SizedBox` for spacing:** Prefer `SizedBox(height: 8)` over `Padding(padding: EdgeInsets.only(top: 8))` for simple fixed spacing.\"\n },\n {\n \"id\": \"flutter-rule-25\",\n \"severity\": \"guidance\",\n \"summary\": \"**`MediaQuery` and `LayoutBuilder`:** Use `LayoutBuilder` for widget-local responsive constraints. Use `MediaQuery.of(context)` sparingly — changes trigger full rebuilds.\"\n },\n {\n \"id\": \"flutter-rule-26\",\n \"severity\": \"guidance\",\n \"summary\": \"**Avoid unbounded height/width:** `Column` inside a `ListView` without a bounded height will throw. Use `shrinkWrap: true` or wrap in `SizedBox` with an explicit dimension when nesting scrollables.\"\n },\n {\n \"id\": \"flutter-rule-27\",\n \"severity\": \"guidance\",\n \"summary\": \"**Named routes or `go_router`:** Prefer declarative routing (`go_router`, `auto_route`) over imperative `Navigator.push` for deep linking and complex flows.\"\n },\n {\n \"id\": \"flutter-rule-28\",\n \"severity\": \"guidance\",\n \"summary\": \"**`WillPopScope` / `PopScope`:** Handle back navigation explicitly when there is unsaved state or a multi-step flow.\"\n },\n {\n \"id\": \"flutter-rule-29\",\n \"severity\": \"guidance\",\n \"summary\": \"**Pass data via constructor, not `arguments`:** Prefer typed constructor injection over `ModalRoute.of(context)!.settings.arguments`. Use route parameters with `go_router`.\"\n },\n {\n \"id\": \"flutter-rule-30\",\n \"severity\": \"guidance\",\n \"summary\": \"**Use `Theme.of(context)`:** Never hardcode colors or text styles. Always derive from the active `ThemeData`.\"\n },\n {\n \"id\": \"flutter-rule-31\",\n \"severity\": \"guidance\",\n \"summary\": \"**`TextTheme`:** Use `Theme.of(context).textTheme.bodyLarge` etc. — do not define ad-hoc `TextStyle` objects everywhere.\"\n },\n {\n \"id\": \"flutter-rule-32\",\n \"severity\": \"guidance\",\n \"summary\": \"**`ColorScheme`:** Use Material 3's `ColorScheme` roles (`primary`, `surface`, `onPrimary`) rather than direct `Color` values.\"\n },\n {\n \"id\": \"flutter-rule-33\",\n \"severity\": \"guidance\",\n \"summary\": \"**`ThemeExtension`:** Define custom theme data in a `ThemeExtension<T>` instead of global constants.\"\n },\n {\n \"id\": \"flutter-rule-34\",\n \"severity\": \"guidance\",\n \"summary\": \"**Widget tests over unit tests for UI:** Test widget behavior with `flutter_test`'s `WidgetTester`. Avoid screenshot testing as the primary regression tool.\"\n },\n {\n \"id\": \"flutter-rule-35\",\n \"severity\": \"guidance\",\n \"summary\": \"**`find.byType`, `find.byKey`:** Prefer `find.byKey(ValueKey('submit'))` for interactive elements. Use `find.byType` for presence checks.\"\n },\n {\n \"id\": \"flutter-rule-36\",\n \"severity\": \"guidance\",\n \"summary\": \"**`pumpAndSettle`:** Use after triggering async operations. Use `pump(Duration)` for animations you control explicitly.\"\n },\n {\n \"id\": \"flutter-rule-37\",\n \"severity\": \"guidance\",\n \"summary\": \"**Golden tests:** Use sparingly — they are brittle across platforms. Gate on a single reference platform in CI.\"\n },\n {\n \"id\": \"flutter-rule-38\",\n \"severity\": \"guidance\",\n \"summary\": \"**One widget per file:** Each top-level `Widget` subclass lives in its own file.\"\n },\n {\n \"id\": \"flutter-rule-39\",\n \"severity\": \"guidance\",\n \"summary\": \"**File names match class names:** `UserProfileCard` → `user_profile_card.dart`.\"\n },\n {\n \"id\": \"flutter-rule-40\",\n \"severity\": \"guidance\",\n \"summary\": \"**Feature-first folder structure:** Group by feature (`lib/features/auth/`, `lib/features/home/`), not by type (`lib/widgets/`, `lib/models/`).\"\n },\n {\n \"id\": \"flutter-rule-41\",\n \"severity\": \"guidance\",\n \"summary\": \"**`_` prefix for private widgets:** Private helper widgets within a file are prefixed with `_`.\"\n }\n ],\n \"source\": \"bundled_template\"\n}\n","styleguides/general.json":"{\n \"version\": 1,\n \"schema\": \"cadre.styleguide.v1\",\n \"kind\": \"styleguide\",\n \"id\": \"general\",\n \"title\": \"General Code Style Principles\",\n \"summary\": \"This document outlines general coding principles that apply across all languages and frameworks used in this project.\",\n \"sections\": [\n {\n \"heading\": \"Readability\",\n \"body\": \"- Code should be easy to read and understand by humans.\\n- Avoid overly clever or obscure constructs.\"\n },\n {\n \"heading\": \"Consistency\",\n \"body\": \"- Follow existing patterns in the codebase.\\n- Maintain consistent formatting, naming, and structure.\"\n },\n {\n \"heading\": \"Simplicity\",\n \"body\": \"- Prefer simple solutions over complex ones.\\n- Break down complex problems into smaller, manageable parts.\"\n },\n {\n \"heading\": \"Maintainability\",\n \"body\": \"- Write code that is easy to modify and extend.\\n- Minimize dependencies and coupling.\"\n },\n {\n \"heading\": \"Documentation\",\n \"body\": \"- Document *why* something is done, not just *what*.\\n- Keep documentation up-to-date with code changes.\"\n }\n ],\n \"languages\": [],\n \"frameworks\": [],\n \"file_patterns\": [],\n \"applies_to\": [\n \"planning\",\n \"implementation\",\n \"review\",\n \"tests\"\n ],\n \"rules\": [\n {\n \"id\": \"general-rule-1\",\n \"severity\": \"guidance\",\n \"summary\": \"Code should be easy to read and understand by humans.\"\n },\n {\n \"id\": \"general-rule-2\",\n \"severity\": \"guidance\",\n \"summary\": \"Avoid overly clever or obscure constructs.\"\n },\n {\n \"id\": \"general-rule-3\",\n \"severity\": \"guidance\",\n \"summary\": \"Follow existing patterns in the codebase.\"\n },\n {\n \"id\": \"general-rule-4\",\n \"severity\": \"guidance\",\n \"summary\": \"Maintain consistent formatting, naming, and structure.\"\n },\n {\n \"id\": \"general-rule-5\",\n \"severity\": \"guidance\",\n \"summary\": \"Prefer simple solutions over complex ones.\"\n },\n {\n \"id\": \"general-rule-6\",\n \"severity\": \"guidance\",\n \"summary\": \"Break down complex problems into smaller, manageable parts.\"\n },\n {\n \"id\": \"general-rule-7\",\n \"severity\": \"guidance\",\n \"summary\": \"Write code that is easy to modify and extend.\"\n },\n {\n \"id\": \"general-rule-8\",\n \"severity\": \"guidance\",\n \"summary\": \"Minimize dependencies and coupling.\"\n },\n {\n \"id\": \"general-rule-9\",\n \"severity\": \"guidance\",\n \"summary\": \"Document *why* something is done, not just *what*.\"\n },\n {\n \"id\": \"general-rule-10\",\n \"severity\": \"guidance\",\n \"summary\": \"Keep documentation up-to-date with code changes.\"\n }\n ],\n \"source\": \"bundled_template\"\n}\n","styleguides/go.json":"{\n \"version\": 1,\n \"schema\": \"cadre.styleguide.v1\",\n \"kind\": \"styleguide\",\n \"id\": \"go\",\n \"title\": \"Effective Go Style Guide Summary\",\n \"summary\": \"This document summarizes key rules and best practices from the official \\\"Effective Go\\\" guide for writing idiomatic Go code.\",\n \"sections\": [\n {\n \"heading\": \"1. Formatting\",\n \"body\": \"- **`gofmt`:** All Go code **must** be formatted with `gofmt` (or `go fmt`). This is a non-negotiable, automated standard.\\n- **Indentation:** Use tabs for indentation (`gofmt` handles this).\\n- **Line Length:** Go has no strict line length limit. Let `gofmt` handle line wrapping.\"\n },\n {\n \"heading\": \"2. Naming\",\n \"body\": \"- **`MixedCaps`:** Use `MixedCaps` or `mixedCaps` for multi-word names. Do not use underscores.\\n- **Exported vs. Unexported:** Names starting with an uppercase letter are exported (public). Names starting with a lowercase letter are not exported (private).\\n- **Package Names:** Short, concise, single-word, lowercase names.\\n- **Getters:** Do not name getters with a `Get` prefix. A getter for a field named `owner` should be named `Owner()`.\\n- **Interface Names:** One-method interfaces are named by the method name plus an `-er` suffix (e.g., `Reader`, `Writer`).\"\n },\n {\n \"heading\": \"3. Control Structures\",\n \"body\": \"- **`if`:** No parentheses around the condition. Braces are mandatory. Can include an initialization statement (e.g., `if err := file.Chmod(0664); err != nil`).\\n- **`for`:** Go's only looping construct. Unifies `for` and `while`. Use `for...range` to iterate over slices, maps, strings, and channels.\\n- **`switch`:** More general than in C. Cases do not fall through by default (use `fallthrough` explicitly). Can be used without an expression to function as a cleaner `if-else-if` chain.\"\n },\n {\n \"heading\": \"4. Functions\",\n \"body\": \"- **Multiple Returns:** Functions can return multiple values. This is the standard way to return a result and an error (e.g., `value, err`).\\n- **Named Result Parameters:** Return parameters can be named. This can make code clearer and more concise.\\n- **`defer`:** Schedules a function call to be run immediately before the function executing `defer` returns. Use it for cleanup tasks like closing files.\"\n },\n {\n \"heading\": \"5. Data\",\n \"body\": \"- **`new` vs. `make`:**\\n - `new(T)`: Allocates memory for a new item of type `T`, zeroes it, and returns a pointer (`*T`).\\n - `make(T, ...)`: Creates and initializes slices, maps, and channels only. Returns an initialized value of type `T` (not a pointer).\\n- **Slices:** The preferred way to work with sequences. They are more flexible than arrays.\\n- **Maps:** Use the \\\"comma ok\\\" idiom to check for the existence of a key: `value, ok := myMap[key]`.\"\n },\n {\n \"heading\": \"6. Interfaces\",\n \"body\": \"- **Implicit Implementation:** A type implements an interface by implementing its methods. No `implements` keyword is needed.\\n- **Small Interfaces:** Prefer many small interfaces over one large one. The standard library is full of single-method interfaces (e.g., `io.Reader`).\"\n },\n {\n \"heading\": \"7. Concurrency\",\n \"body\": \"- **Share Memory By Communicating:** This is the core philosophy. Do not communicate by sharing memory; instead, share memory by communicating.\\n- **Goroutines:** Lightweight, concurrently executing functions. Start one with the `go` keyword.\\n- **Channels:** Typed conduits for communication between goroutines. Use `make` to create them.\"\n },\n {\n \"heading\": \"8. Errors\",\n \"body\": \"- **`error` type:** The built-in `error` interface is the standard way to handle errors.\\n- **Explicit Error Handling:** Do not discard errors with the blank identifier (`_`). Check for errors explicitly.\\n- **`panic`:** Reserved for truly exceptional, unrecoverable situations. Generally, libraries should not panic.\\n\\n*Source: [Effective Go](https://go.dev/doc/effective_go)*\"\n }\n ],\n \"languages\": [\n \"go\"\n ],\n \"frameworks\": [],\n \"file_patterns\": [],\n \"applies_to\": [\n \"planning\",\n \"implementation\",\n \"review\",\n \"tests\"\n ],\n \"rules\": [\n {\n \"id\": \"go-rule-1\",\n \"severity\": \"guidance\",\n \"summary\": \"**`gofmt`:** All Go code **must** be formatted with `gofmt` (or `go fmt`). This is a non-negotiable, automated standard.\"\n },\n {\n \"id\": \"go-rule-2\",\n \"severity\": \"guidance\",\n \"summary\": \"**Indentation:** Use tabs for indentation (`gofmt` handles this).\"\n },\n {\n \"id\": \"go-rule-3\",\n \"severity\": \"guidance\",\n \"summary\": \"**Line Length:** Go has no strict line length limit. Let `gofmt` handle line wrapping.\"\n },\n {\n \"id\": \"go-rule-4\",\n \"severity\": \"guidance\",\n \"summary\": \"**`MixedCaps`:** Use `MixedCaps` or `mixedCaps` for multi-word names. Do not use underscores.\"\n },\n {\n \"id\": \"go-rule-5\",\n \"severity\": \"guidance\",\n \"summary\": \"**Exported vs. Unexported:** Names starting with an uppercase letter are exported (public). Names starting with a lowercase letter are not exported (private).\"\n },\n {\n \"id\": \"go-rule-6\",\n \"severity\": \"guidance\",\n \"summary\": \"**Package Names:** Short, concise, single-word, lowercase names.\"\n },\n {\n \"id\": \"go-rule-7\",\n \"severity\": \"guidance\",\n \"summary\": \"**Getters:** Do not name getters with a `Get` prefix. A getter for a field named `owner` should be named `Owner()`.\"\n },\n {\n \"id\": \"go-rule-8\",\n \"severity\": \"guidance\",\n \"summary\": \"**Interface Names:** One-method interfaces are named by the method name plus an `-er` suffix (e.g., `Reader`, `Writer`).\"\n },\n {\n \"id\": \"go-rule-9\",\n \"severity\": \"guidance\",\n \"summary\": \"**`if`:** No parentheses around the condition. Braces are mandatory. Can include an initialization statement (e.g., `if err := file.Chmod(0664); err != nil`).\"\n },\n {\n \"id\": \"go-rule-10\",\n \"severity\": \"guidance\",\n \"summary\": \"**`for`:** Go's only looping construct. Unifies `for` and `while`. Use `for...range` to iterate over slices, maps, strings, and channels.\"\n },\n {\n \"id\": \"go-rule-11\",\n \"severity\": \"guidance\",\n \"summary\": \"**`switch`:** More general than in C. Cases do not fall through by default (use `fallthrough` explicitly). Can be used without an expression to function as a cleaner `if-else-if` chain.\"\n },\n {\n \"id\": \"go-rule-12\",\n \"severity\": \"guidance\",\n \"summary\": \"**Multiple Returns:** Functions can return multiple values. This is the standard way to return a result and an error (e.g., `value, err`).\"\n },\n {\n \"id\": \"go-rule-13\",\n \"severity\": \"guidance\",\n \"summary\": \"**Named Result Parameters:** Return parameters can be named. This can make code clearer and more concise.\"\n },\n {\n \"id\": \"go-rule-14\",\n \"severity\": \"guidance\",\n \"summary\": \"**`defer`:** Schedules a function call to be run immediately before the function executing `defer` returns. Use it for cleanup tasks like closing files.\"\n },\n {\n \"id\": \"go-rule-15\",\n \"severity\": \"guidance\",\n \"summary\": \"**`new` vs. `make`:**\"\n },\n {\n \"id\": \"go-rule-16\",\n \"severity\": \"guidance\",\n \"summary\": \"`new(T)`: Allocates memory for a new item of type `T`, zeroes it, and returns a pointer (`*T`).\"\n },\n {\n \"id\": \"go-rule-17\",\n \"severity\": \"guidance\",\n \"summary\": \"`make(T, ...)`: Creates and initializes slices, maps, and channels only. Returns an initialized value of type `T` (not a pointer).\"\n },\n {\n \"id\": \"go-rule-18\",\n \"severity\": \"guidance\",\n \"summary\": \"**Slices:** The preferred way to work with sequences. They are more flexible than arrays.\"\n },\n {\n \"id\": \"go-rule-19\",\n \"severity\": \"guidance\",\n \"summary\": \"**Maps:** Use the \\\"comma ok\\\" idiom to check for the existence of a key: `value, ok := myMap[key]`.\"\n },\n {\n \"id\": \"go-rule-20\",\n \"severity\": \"guidance\",\n \"summary\": \"**Implicit Implementation:** A type implements an interface by implementing its methods. No `implements` keyword is needed.\"\n },\n {\n \"id\": \"go-rule-21\",\n \"severity\": \"guidance\",\n \"summary\": \"**Small Interfaces:** Prefer many small interfaces over one large one. The standard library is full of single-method interfaces (e.g., `io.Reader`).\"\n },\n {\n \"id\": \"go-rule-22\",\n \"severity\": \"guidance\",\n \"summary\": \"**Share Memory By Communicating:** This is the core philosophy. Do not communicate by sharing memory; instead, share memory by communicating.\"\n },\n {\n \"id\": \"go-rule-23\",\n \"severity\": \"guidance\",\n \"summary\": \"**Goroutines:** Lightweight, concurrently executing functions. Start one with the `go` keyword.\"\n },\n {\n \"id\": \"go-rule-24\",\n \"severity\": \"guidance\",\n \"summary\": \"**Channels:** Typed conduits for communication between goroutines. Use `make` to create them.\"\n },\n {\n \"id\": \"go-rule-25\",\n \"severity\": \"guidance\",\n \"summary\": \"**`error` type:** The built-in `error` interface is the standard way to handle errors.\"\n },\n {\n \"id\": \"go-rule-26\",\n \"severity\": \"guidance\",\n \"summary\": \"**Explicit Error Handling:** Do not discard errors with the blank identifier (`_`). Check for errors explicitly.\"\n },\n {\n \"id\": \"go-rule-27\",\n \"severity\": \"guidance\",\n \"summary\": \"**`panic`:** Reserved for truly exceptional, unrecoverable situations. Generally, libraries should not panic.\"\n }\n ],\n \"source\": \"bundled_template\"\n}\n","styleguides/html-css.json":"{\n \"version\": 1,\n \"schema\": \"cadre.styleguide.v1\",\n \"kind\": \"styleguide\",\n \"id\": \"html-css\",\n \"title\": \"Google HTML/CSS Style Guide Summary\",\n \"summary\": \"This document summarizes key rules and best practices from the Google HTML/CSS Style Guide.\",\n \"sections\": [\n {\n \"heading\": \"1. General Rules\",\n \"body\": \"- **Protocol:** Use HTTPS for all embedded resources.\\n- **Indentation:** Indent by 2 spaces. Do not use tabs.\\n- **Capitalization:** Use only lowercase for all code (element names, attributes, selectors, properties).\\n- **Trailing Whitespace:** Remove all trailing whitespace.\\n- **Encoding:** Use UTF-8 (without a BOM). Specify `<meta charset=\\\"utf-8\\\">` in HTML.\"\n },\n {\n \"heading\": \"2. HTML Style Rules\",\n \"body\": \"- **Document Type:** Use `<!doctype html>`.\\n- **HTML Validity:** Use valid HTML.\\n- **Semantics:** Use HTML elements according to their intended purpose (e.g., use `<p>` for paragraphs, not for spacing).\\n- **Multimedia Fallback:** Provide `alt` text for images and transcripts/captions for audio/video.\\n- **Separation of Concerns:** Strictly separate structure (HTML), presentation (CSS), and behavior (JavaScript). Link to CSS and JS from external files.\\n- **`type` Attributes:** Omit `type` attributes for stylesheets (`<link>`) and scripts (`<script>`).\"\n },\n {\n \"heading\": \"3. HTML Formatting Rules\",\n \"body\": \"- **General:** Use a new line for every block, list, or table element, and indent its children.\\n- **Quotation Marks:** Use double quotation marks (`\\\"\\\"`) for attribute values.\"\n },\n {\n \"heading\": \"4. CSS Style Rules\",\n \"body\": \"- **CSS Validity:** Use valid CSS.\\n- **Class Naming:** Use meaningful, generic names. Separate words with a hyphen (`-`).\\n - **Good:** `.video-player`, `.site-navigation`\\n - **Bad:** `.vid`, `.red-text`\\n- **ID Selectors:** Avoid using ID selectors for styling. Prefer class selectors.\\n- **Shorthand Properties:** Use shorthand properties where possible (e.g., `padding`, `font`).\\n- **`0` and Units:** Omit units for `0` values (e.g., `margin: 0;`).\\n- **Leading `0`s:** Always include leading `0`s for decimal values (e.g., `font-size: 0.8em;`).\\n- **Hexadecimal Notation:** Use 3-character hex notation where possible (e.g., `#fff`).\\n- **`!important`:** Avoid using `!important`.\"\n },\n {\n \"heading\": \"5. CSS Formatting Rules\",\n \"body\": \"- **Declaration Order:** Alphabetize declarations within a rule.\\n- **Indentation:** Indent all block content.\\n- **Semicolons:** Use a semicolon after every declaration.\\n- **Spacing:**\\n - Use a space after a property name's colon (`font-weight: bold;`).\\n - Use a space between the last selector and the opening brace (`.foo {`).\\n - Start a new line for each selector and declaration.\\n- **Rule Separation:** Separate rules with a new line.\\n- **Quotation Marks:** Use single quotes (`''`) for attribute selectors and property values (e.g., `[type='text']`).\\n\\n**BE CONSISTENT.** When editing code, match the existing style.\\n\\n*Source: [Google HTML/CSS Style Guide](https://google.github.io/styleguide/htmlcssguide.html)*\"\n }\n ],\n \"languages\": [\n \"html-css\"\n ],\n \"frameworks\": [],\n \"file_patterns\": [],\n \"applies_to\": [\n \"planning\",\n \"implementation\",\n \"review\",\n \"tests\"\n ],\n \"rules\": [\n {\n \"id\": \"html-css-rule-1\",\n \"severity\": \"guidance\",\n \"summary\": \"**Protocol:** Use HTTPS for all embedded resources.\"\n },\n {\n \"id\": \"html-css-rule-2\",\n \"severity\": \"guidance\",\n \"summary\": \"**Indentation:** Indent by 2 spaces. Do not use tabs.\"\n },\n {\n \"id\": \"html-css-rule-3\",\n \"severity\": \"guidance\",\n \"summary\": \"**Capitalization:** Use only lowercase for all code (element names, attributes, selectors, properties).\"\n },\n {\n \"id\": \"html-css-rule-4\",\n \"severity\": \"guidance\",\n \"summary\": \"**Trailing Whitespace:** Remove all trailing whitespace.\"\n },\n {\n \"id\": \"html-css-rule-5\",\n \"severity\": \"guidance\",\n \"summary\": \"**Encoding:** Use UTF-8 (without a BOM). Specify `<meta charset=\\\"utf-8\\\">` in HTML.\"\n },\n {\n \"id\": \"html-css-rule-6\",\n \"severity\": \"guidance\",\n \"summary\": \"**Document Type:** Use `<!doctype html>`.\"\n },\n {\n \"id\": \"html-css-rule-7\",\n \"severity\": \"guidance\",\n \"summary\": \"**HTML Validity:** Use valid HTML.\"\n },\n {\n \"id\": \"html-css-rule-8\",\n \"severity\": \"guidance\",\n \"summary\": \"**Semantics:** Use HTML elements according to their intended purpose (e.g., use `<p>` for paragraphs, not for spacing).\"\n },\n {\n \"id\": \"html-css-rule-9\",\n \"severity\": \"guidance\",\n \"summary\": \"**Multimedia Fallback:** Provide `alt` text for images and transcripts/captions for audio/video.\"\n },\n {\n \"id\": \"html-css-rule-10\",\n \"severity\": \"guidance\",\n \"summary\": \"**Separation of Concerns:** Strictly separate structure (HTML), presentation (CSS), and behavior (JavaScript). Link to CSS and JS from external files.\"\n },\n {\n \"id\": \"html-css-rule-11\",\n \"severity\": \"guidance\",\n \"summary\": \"**`type` Attributes:** Omit `type` attributes for stylesheets (`<link>`) and scripts (`<script>`).\"\n },\n {\n \"id\": \"html-css-rule-12\",\n \"severity\": \"guidance\",\n \"summary\": \"**General:** Use a new line for every block, list, or table element, and indent its children.\"\n },\n {\n \"id\": \"html-css-rule-13\",\n \"severity\": \"guidance\",\n \"summary\": \"**Quotation Marks:** Use double quotation marks (`\\\"\\\"`) for attribute values.\"\n },\n {\n \"id\": \"html-css-rule-14\",\n \"severity\": \"guidance\",\n \"summary\": \"**CSS Validity:** Use valid CSS.\"\n },\n {\n \"id\": \"html-css-rule-15\",\n \"severity\": \"guidance\",\n \"summary\": \"**Class Naming:** Use meaningful, generic names. Separate words with a hyphen (`-`).\"\n },\n {\n \"id\": \"html-css-rule-16\",\n \"severity\": \"guidance\",\n \"summary\": \"**Good:** `.video-player`, `.site-navigation`\"\n },\n {\n \"id\": \"html-css-rule-17\",\n \"severity\": \"guidance\",\n \"summary\": \"**Bad:** `.vid`, `.red-text`\"\n },\n {\n \"id\": \"html-css-rule-18\",\n \"severity\": \"guidance\",\n \"summary\": \"**ID Selectors:** Avoid using ID selectors for styling. Prefer class selectors.\"\n },\n {\n \"id\": \"html-css-rule-19\",\n \"severity\": \"guidance\",\n \"summary\": \"**Shorthand Properties:** Use shorthand properties where possible (e.g., `padding`, `font`).\"\n },\n {\n \"id\": \"html-css-rule-20\",\n \"severity\": \"guidance\",\n \"summary\": \"**`0` and Units:** Omit units for `0` values (e.g., `margin: 0;`).\"\n },\n {\n \"id\": \"html-css-rule-21\",\n \"severity\": \"guidance\",\n \"summary\": \"**Leading `0`s:** Always include leading `0`s for decimal values (e.g., `font-size: 0.8em;`).\"\n },\n {\n \"id\": \"html-css-rule-22\",\n \"severity\": \"guidance\",\n \"summary\": \"**Hexadecimal Notation:** Use 3-character hex notation where possible (e.g., `#fff`).\"\n },\n {\n \"id\": \"html-css-rule-23\",\n \"severity\": \"guidance\",\n \"summary\": \"**`!important`:** Avoid using `!important`.\"\n },\n {\n \"id\": \"html-css-rule-24\",\n \"severity\": \"guidance\",\n \"summary\": \"**Declaration Order:** Alphabetize declarations within a rule.\"\n },\n {\n \"id\": \"html-css-rule-25\",\n \"severity\": \"guidance\",\n \"summary\": \"**Indentation:** Indent all block content.\"\n },\n {\n \"id\": \"html-css-rule-26\",\n \"severity\": \"guidance\",\n \"summary\": \"**Semicolons:** Use a semicolon after every declaration.\"\n },\n {\n \"id\": \"html-css-rule-27\",\n \"severity\": \"guidance\",\n \"summary\": \"**Spacing:**\"\n },\n {\n \"id\": \"html-css-rule-28\",\n \"severity\": \"guidance\",\n \"summary\": \"Use a space after a property name's colon (`font-weight: bold;`).\"\n },\n {\n \"id\": \"html-css-rule-29\",\n \"severity\": \"guidance\",\n \"summary\": \"Use a space between the last selector and the opening brace (`.foo {`).\"\n },\n {\n \"id\": \"html-css-rule-30\",\n \"severity\": \"guidance\",\n \"summary\": \"Start a new line for each selector and declaration.\"\n },\n {\n \"id\": \"html-css-rule-31\",\n \"severity\": \"guidance\",\n \"summary\": \"**Rule Separation:** Separate rules with a new line.\"\n },\n {\n \"id\": \"html-css-rule-32\",\n \"severity\": \"guidance\",\n \"summary\": \"**Quotation Marks:** Use single quotes (`''`) for attribute selectors and property values (e.g., `[type='text']`).\"\n }\n ],\n \"source\": \"bundled_template\"\n}\n","styleguides/javascript.json":"{\n \"version\": 1,\n \"schema\": \"cadre.styleguide.v1\",\n \"kind\": \"styleguide\",\n \"id\": \"javascript\",\n \"title\": \"Google JavaScript Style Guide Summary\",\n \"summary\": \"This document summarizes key rules and best practices from the Google JavaScript Style Guide.\",\n \"sections\": [\n {\n \"heading\": \"1. Source File Basics\",\n \"body\": \"- **File Naming:** All lowercase, with underscores (`_`) or dashes (`-`). Extension must be `.js`.\\n- **File Encoding:** UTF-8.\\n- **Whitespace:** Use only ASCII horizontal spaces (0x20). Tabs are forbidden for indentation.\"\n },\n {\n \"heading\": \"2. Source File Structure\",\n \"body\": \"- New files should be ES modules (`import`/`export`).\\n- **Exports:** Use named exports (`export {MyClass};`). **Do not use default exports.**\\n- **Imports:** Do not use line-wrapped imports. The `.js` extension in import paths is mandatory.\"\n },\n {\n \"heading\": \"3. Formatting\",\n \"body\": \"- **Braces:** Required for all control structures (`if`, `for`, `while`, etc.), even single-line blocks. Use K&R style (\\\"Egyptian brackets\\\").\\n- **Indentation:** +2 spaces for each new block.\\n- **Semicolons:** Every statement must be terminated with a semicolon.\\n- **Column Limit:** 80 characters.\\n- **Line-wrapping:** Indent continuation lines at least +4 spaces.\\n- **Whitespace:** Use single blank lines between methods. No trailing whitespace.\"\n },\n {\n \"heading\": \"4. Language Features\",\n \"body\": \"- **Variable Declarations:** Use `const` by default, `let` if reassignment is needed. **`var` is forbidden.**\\n- **Array Literals:** Use trailing commas. Do not use the `Array` constructor.\\n- **Object Literals:** Use trailing commas and shorthand properties. Do not use the `Object` constructor.\\n- **Classes:** Do not use JavaScript getter/setter properties (`get name()`). Provide ordinary methods instead.\\n- **Functions:** Prefer arrow functions for nested functions to preserve `this` context.\\n- **String Literals:** Use single quotes (`'`). Use template literals (`` ` ``) for multi-line strings or complex interpolation.\\n- **Control Structures:** Prefer `for-of` loops. `for-in` loops should only be used on dict-style objects.\\n- **`this`:** Only use `this` in class constructors, methods, or in arrow functions defined within them.\\n- **Equality Checks:** Always use identity operators (`===` / `!==`).\"\n },\n {\n \"heading\": \"5. Disallowed Features\",\n \"body\": \"- `with` keyword.\\n- `eval()` or `Function(...string)`.\\n- Automatic Semicolon Insertion.\\n- Modifying builtin objects (`Array.prototype.foo = ...`).\"\n },\n {\n \"heading\": \"6. Naming\",\n \"body\": \"- **Classes:** `UpperCamelCase`.\\n- **Methods & Functions:** `lowerCamelCase`.\\n- **Constants:** `CONSTANT_CASE` (all uppercase with underscores).\\n- **Non-constant Fields & Variables:** `lowerCamelCase`.\"\n },\n {\n \"heading\": \"7. JSDoc\",\n \"body\": \"- JSDoc is used on all classes, fields, and methods.\\n- Use `@param`, `@return`, `@override`, `@deprecated`.\\n- Type annotations are enclosed in braces (e.g., `/** @param {string} userName */`).\\n\\n*Source: [Google JavaScript Style Guide](https://google.github.io/styleguide/jsguide.html)*\"\n }\n ],\n \"languages\": [\n \"javascript\"\n ],\n \"frameworks\": [],\n \"file_patterns\": [],\n \"applies_to\": [\n \"planning\",\n \"implementation\",\n \"review\",\n \"tests\"\n ],\n \"rules\": [\n {\n \"id\": \"javascript-rule-1\",\n \"severity\": \"guidance\",\n \"summary\": \"**File Naming:** All lowercase, with underscores (`_`) or dashes (`-`). Extension must be `.js`.\"\n },\n {\n \"id\": \"javascript-rule-2\",\n \"severity\": \"guidance\",\n \"summary\": \"**File Encoding:** UTF-8.\"\n },\n {\n \"id\": \"javascript-rule-3\",\n \"severity\": \"guidance\",\n \"summary\": \"**Whitespace:** Use only ASCII horizontal spaces (0x20). Tabs are forbidden for indentation.\"\n },\n {\n \"id\": \"javascript-rule-4\",\n \"severity\": \"guidance\",\n \"summary\": \"New files should be ES modules (`import`/`export`).\"\n },\n {\n \"id\": \"javascript-rule-5\",\n \"severity\": \"guidance\",\n \"summary\": \"**Exports:** Use named exports (`export {MyClass};`). **Do not use default exports.**\"\n },\n {\n \"id\": \"javascript-rule-6\",\n \"severity\": \"guidance\",\n \"summary\": \"**Imports:** Do not use line-wrapped imports. The `.js` extension in import paths is mandatory.\"\n },\n {\n \"id\": \"javascript-rule-7\",\n \"severity\": \"guidance\",\n \"summary\": \"**Braces:** Required for all control structures (`if`, `for`, `while`, etc.), even single-line blocks. Use K&R style (\\\"Egyptian brackets\\\").\"\n },\n {\n \"id\": \"javascript-rule-8\",\n \"severity\": \"guidance\",\n \"summary\": \"**Indentation:** +2 spaces for each new block.\"\n },\n {\n \"id\": \"javascript-rule-9\",\n \"severity\": \"guidance\",\n \"summary\": \"**Semicolons:** Every statement must be terminated with a semicolon.\"\n },\n {\n \"id\": \"javascript-rule-10\",\n \"severity\": \"guidance\",\n \"summary\": \"**Column Limit:** 80 characters.\"\n },\n {\n \"id\": \"javascript-rule-11\",\n \"severity\": \"guidance\",\n \"summary\": \"**Line-wrapping:** Indent continuation lines at least +4 spaces.\"\n },\n {\n \"id\": \"javascript-rule-12\",\n \"severity\": \"guidance\",\n \"summary\": \"**Whitespace:** Use single blank lines between methods. No trailing whitespace.\"\n },\n {\n \"id\": \"javascript-rule-13\",\n \"severity\": \"guidance\",\n \"summary\": \"**Variable Declarations:** Use `const` by default, `let` if reassignment is needed. **`var` is forbidden.**\"\n },\n {\n \"id\": \"javascript-rule-14\",\n \"severity\": \"guidance\",\n \"summary\": \"**Array Literals:** Use trailing commas. Do not use the `Array` constructor.\"\n },\n {\n \"id\": \"javascript-rule-15\",\n \"severity\": \"guidance\",\n \"summary\": \"**Object Literals:** Use trailing commas and shorthand properties. Do not use the `Object` constructor.\"\n },\n {\n \"id\": \"javascript-rule-16\",\n \"severity\": \"guidance\",\n \"summary\": \"**Classes:** Do not use JavaScript getter/setter properties (`get name()`). Provide ordinary methods instead.\"\n },\n {\n \"id\": \"javascript-rule-17\",\n \"severity\": \"guidance\",\n \"summary\": \"**Functions:** Prefer arrow functions for nested functions to preserve `this` context.\"\n },\n {\n \"id\": \"javascript-rule-18\",\n \"severity\": \"guidance\",\n \"summary\": \"**String Literals:** Use single quotes (`'`). Use template literals (`` ` ``) for multi-line strings or complex interpolation.\"\n },\n {\n \"id\": \"javascript-rule-19\",\n \"severity\": \"guidance\",\n \"summary\": \"**Control Structures:** Prefer `for-of` loops. `for-in` loops should only be used on dict-style objects.\"\n },\n {\n \"id\": \"javascript-rule-20\",\n \"severity\": \"guidance\",\n \"summary\": \"**`this`:** Only use `this` in class constructors, methods, or in arrow functions defined within them.\"\n },\n {\n \"id\": \"javascript-rule-21\",\n \"severity\": \"guidance\",\n \"summary\": \"**Equality Checks:** Always use identity operators (`===` / `!==`).\"\n },\n {\n \"id\": \"javascript-rule-22\",\n \"severity\": \"guidance\",\n \"summary\": \"`with` keyword.\"\n },\n {\n \"id\": \"javascript-rule-23\",\n \"severity\": \"guidance\",\n \"summary\": \"`eval()` or `Function(...string)`.\"\n },\n {\n \"id\": \"javascript-rule-24\",\n \"severity\": \"guidance\",\n \"summary\": \"Automatic Semicolon Insertion.\"\n },\n {\n \"id\": \"javascript-rule-25\",\n \"severity\": \"guidance\",\n \"summary\": \"Modifying builtin objects (`Array.prototype.foo = ...`).\"\n },\n {\n \"id\": \"javascript-rule-26\",\n \"severity\": \"guidance\",\n \"summary\": \"**Classes:** `UpperCamelCase`.\"\n },\n {\n \"id\": \"javascript-rule-27\",\n \"severity\": \"guidance\",\n \"summary\": \"**Methods & Functions:** `lowerCamelCase`.\"\n },\n {\n \"id\": \"javascript-rule-28\",\n \"severity\": \"guidance\",\n \"summary\": \"**Constants:** `CONSTANT_CASE` (all uppercase with underscores).\"\n },\n {\n \"id\": \"javascript-rule-29\",\n \"severity\": \"guidance\",\n \"summary\": \"**Non-constant Fields & Variables:** `lowerCamelCase`.\"\n },\n {\n \"id\": \"javascript-rule-30\",\n \"severity\": \"guidance\",\n \"summary\": \"JSDoc is used on all classes, fields, and methods.\"\n },\n {\n \"id\": \"javascript-rule-31\",\n \"severity\": \"guidance\",\n \"summary\": \"Use `@param`, `@return`, `@override`, `@deprecated`.\"\n },\n {\n \"id\": \"javascript-rule-32\",\n \"severity\": \"guidance\",\n \"summary\": \"Type annotations are enclosed in braces (e.g., `/** @param {string} userName */`).\"\n }\n ],\n \"source\": \"bundled_template\"\n}\n","styleguides/kotlin.json":"{\n \"version\": 1,\n \"schema\": \"cadre.styleguide.v1\",\n \"kind\": \"styleguide\",\n \"id\": \"kotlin\",\n \"title\": \"Kotlin Coding Conventions Style Guide Summary\",\n \"summary\": \"This document summarizes key rules and best practices from the official Kotlin Coding Conventions and JetBrains style guide for writing idiomatic, concise, and safe Kotlin code.\",\n \"sections\": [\n {\n \"heading\": \"1. Formatting\",\n \"body\": \"- **ktlint / detekt:** Format with `ktlint` and lint with `detekt`. Enforce both in CI.\\n- **Indentation:** 4 spaces. No tabs. Continuation lines: 4 spaces (not 8).\\n- **Line Length:** 120 characters maximum (Kotlin convention; some projects use 100).\\n- **Trailing lambdas:** When the last parameter is a lambda, move it outside the parentheses. Omit the parentheses entirely if the lambda is the only parameter.\"\n },\n {\n \"heading\": \"2. Naming\",\n \"body\": \"- **`UpperCamelCase`:** For classes, objects, interfaces, and enum entries.\\n- **`lowerCamelCase`:** For functions, properties, local variables, and parameters.\\n- **`SCREAMING_SNAKE_CASE`:** For `const val` top-level and companion object constants only.\\n- **`_` prefix:** Do not use. Kotlin backing properties use `_name` as a convention for private backing fields exposed via a public property — this is the single accepted use.\\n- **Acronyms:** Use `UpperCamelCase` even for acronyms: `XmlParser`, `HttpClient`, not `XMLParser`.\\n- **Boolean properties:** Name as `isEnabled`, `hasError`, `canClose`. Prefix with `is`, `has`, or `can`.\\n- **Test functions:** Use backtick names for test readability: `` `should throw when user is null`() ``.\"\n },\n {\n \"heading\": \"3. Null Safety\",\n \"body\": \"- **Non-nullable by default:** Prefer non-nullable types. Add `?` only when `null` is a genuinely valid value.\\n- **Avoid `!!`:** The `!!` operator is a code smell. It bypasses null safety and throws `NullPointerException`. Use `?.`, `?:`, `let`, `also`, or explicit null checks instead.\\n- **`?.let { }`:** Use for null-conditional execution. Prefer `if (x != null)` when the block is long and `x` is used multiple times (smart cast).\\n- **Elvis operator `?:`:** Use for default values: `val name = user?.name ?: \\\"Anonymous\\\"`.\\n- **`requireNotNull` / `checkNotNull`:** Use to assert non-nullability at runtime with a clear message: `requireNotNull(user) { \\\"User must not be null\\\" }`.\"\n },\n {\n \"heading\": \"4. Classes and Objects\",\n \"body\": \"- **`data class`:** Use for classes that hold data. They get `equals`, `hashCode`, `toString`, `copy`, and `componentN` for free.\\n- **`sealed class`:** Use for closed type hierarchies (discriminated unions). Prefer `sealed class` over `enum class` when variants carry different data.\\n- **`object`:** Use for singletons and companion objects. Do not use a class with a private constructor + static `getInstance()`.\\n- **`companion object`:** Use for factory methods and constants logically associated with a class. Name the companion only if it will be referenced by name.\\n- **`val` over `var`:** Prefer immutable `val` properties. Use `var` only when mutation is necessary.\\n- **`init` blocks:** Minimize logic in `init` blocks. Prefer constructor parameter defaults and `lazy` properties.\\n- **`lazy`:** Use `by lazy { }` for properties that are expensive to compute and not always needed.\"\n },\n {\n \"heading\": \"5. Functions\",\n \"body\": \"- **Expression bodies:** Use `= expression` for single-expression functions. Omit braces and `return`.\\n- **Default parameter values:** Use default values instead of overloaded functions.\\n- **Named arguments:** Use named arguments when calling functions with many parameters or when the parameter type is a primitive and meaning is unclear.\\n- **Extension functions:** Use extension functions to add behavior to existing types without subclassing. Place extensions in a file named `TypeExtensions.kt`.\\n- **Scope functions (`let`, `run`, `with`, `apply`, `also`):**\\n - `apply`: Configure an object — use when returning the object. (`builder.apply { ... }`)\\n - `also`: Perform side effects — use when returning the object. (`list.also { log(it) }`)\\n - `let`: Transform a value, especially with nullability. (`str?.let { process(it) }`)\\n - `run`/`with`: Group a block of operations on an object. Prefer `run` for nullable receivers, `with` for non-null.\\n - **Do not nest scope functions more than 2 levels deep.**\\n- **`operator fun`:** Only implement operator overloads when the semantics are universally clear (e.g., `+` for numeric types, `get`/`set` for collections).\"\n },\n {\n \"heading\": \"6. Collections\",\n \"body\": \"- **Immutable collections:** Prefer `listOf`, `mapOf`, `setOf`. Use `mutableListOf` etc. only when mutation is needed.\\n- **`Sequence` for lazy pipelines:** Use `asSequence()` for long transformation chains on large collections to avoid creating intermediate lists.\\n- **Avoid `null` in collections:** Prefer `emptyList()` over `null` for absent collections. Use `filterNotNull()` to clean mixed lists.\\n- **`associate`, `groupBy`, `partition`:** Use the stdlib collection transforms instead of manual loops.\\n- **Destructuring:** Use destructuring declarations in `for` loops and `map` operations: `for ((key, value) in map)`.\"\n },\n {\n \"heading\": \"7. Coroutines\",\n \"body\": \"- **`suspend` functions:** Mark any function that calls another `suspend` function or performs async I/O as `suspend`. Do not block inside `suspend` functions — use `withContext(Dispatchers.IO)`.\\n- **Structured concurrency:** Always launch coroutines in a `CoroutineScope`. Never use `GlobalScope` in application code.\\n- **`Dispatchers.Main` / `.IO` / `.Default`:** Use the correct dispatcher — `Main` for UI, `IO` for blocking I/O, `Default` for CPU work.\\n- **`Flow`:** Use `Flow<T>` for streams of values. Use `StateFlow`/`SharedFlow` for hot streams. Call `.collect {}` in a lifecycle-aware scope.\\n- **Error handling:** Use `try/catch` inside coroutines. Use `CoroutineExceptionHandler` for unhandled exceptions in `launch`. `async`/`await` propagates exceptions at the `await` site.\\n- **`viewModelScope` / `lifecycleScope`:** Use these scopes in Android (see Android guide) to tie coroutine lifetime to the component.\"\n },\n {\n \"heading\": \"8. Error Handling\",\n \"body\": \"- **Exceptions for exceptional cases:** Do not use exceptions for normal control flow. Return `Result<T>`, `sealed class`, or nullable values for expected failure paths.\\n- **`runCatching`:** Use `runCatching { }` for concise try-catch with `Result<T>` return.\\n- **Avoid catching `Throwable`:** Catch specific exception types. Catching `Throwable` also catches `Error` (e.g., `OutOfMemoryError`).\"\n },\n {\n \"heading\": \"9. Documentation\",\n \"body\": \"- **KDoc (`/** */`):** Use KDoc for all public API documentation.\\n- **`@param`, `@return`, `@throws`:** Include these tags for public functions with non-obvious parameters or return values.\\n- **`@since`:** Mark API additions with `@since <version>`.\\n- **Avoid redundant comments:** Do not restate the function name in the doc. Add information about behavior, edge cases, or constraints.\\n\\n*Source: [Kotlin Coding Conventions](https://kotlinlang.org/docs/coding-conventions.html)*\"\n }\n ],\n \"languages\": [\n \"kotlin\"\n ],\n \"frameworks\": [],\n \"file_patterns\": [],\n \"applies_to\": [\n \"planning\",\n \"implementation\",\n \"review\",\n \"tests\"\n ],\n \"rules\": [\n {\n \"id\": \"kotlin-rule-1\",\n \"severity\": \"guidance\",\n \"summary\": \"**ktlint / detekt:** Format with `ktlint` and lint with `detekt`. Enforce both in CI.\"\n },\n {\n \"id\": \"kotlin-rule-2\",\n \"severity\": \"guidance\",\n \"summary\": \"**Indentation:** 4 spaces. No tabs. Continuation lines: 4 spaces (not 8).\"\n },\n {\n \"id\": \"kotlin-rule-3\",\n \"severity\": \"guidance\",\n \"summary\": \"**Line Length:** 120 characters maximum (Kotlin convention; some projects use 100).\"\n },\n {\n \"id\": \"kotlin-rule-4\",\n \"severity\": \"guidance\",\n \"summary\": \"**Trailing lambdas:** When the last parameter is a lambda, move it outside the parentheses. Omit the parentheses entirely if the lambda is the only parameter.\"\n },\n {\n \"id\": \"kotlin-rule-5\",\n \"severity\": \"guidance\",\n \"summary\": \"**`UpperCamelCase`:** For classes, objects, interfaces, and enum entries.\"\n },\n {\n \"id\": \"kotlin-rule-6\",\n \"severity\": \"guidance\",\n \"summary\": \"**`lowerCamelCase`:** For functions, properties, local variables, and parameters.\"\n },\n {\n \"id\": \"kotlin-rule-7\",\n \"severity\": \"guidance\",\n \"summary\": \"**`SCREAMING_SNAKE_CASE`:** For `const val` top-level and companion object constants only.\"\n },\n {\n \"id\": \"kotlin-rule-8\",\n \"severity\": \"guidance\",\n \"summary\": \"**`_` prefix:** Do not use. Kotlin backing properties use `_name` as a convention for private backing fields exposed via a public property — this is the single accepted use.\"\n },\n {\n \"id\": \"kotlin-rule-9\",\n \"severity\": \"guidance\",\n \"summary\": \"**Acronyms:** Use `UpperCamelCase` even for acronyms: `XmlParser`, `HttpClient`, not `XMLParser`.\"\n },\n {\n \"id\": \"kotlin-rule-10\",\n \"severity\": \"guidance\",\n \"summary\": \"**Boolean properties:** Name as `isEnabled`, `hasError`, `canClose`. Prefix with `is`, `has`, or `can`.\"\n },\n {\n \"id\": \"kotlin-rule-11\",\n \"severity\": \"guidance\",\n \"summary\": \"**Test functions:** Use backtick names for test readability: `` `should throw when user is null`() ``.\"\n },\n {\n \"id\": \"kotlin-rule-12\",\n \"severity\": \"guidance\",\n \"summary\": \"**Non-nullable by default:** Prefer non-nullable types. Add `?` only when `null` is a genuinely valid value.\"\n },\n {\n \"id\": \"kotlin-rule-13\",\n \"severity\": \"guidance\",\n \"summary\": \"**Avoid `!!`:** The `!!` operator is a code smell. It bypasses null safety and throws `NullPointerException`. Use `?.`, `?:`, `let`, `also`, or explicit null checks instead.\"\n },\n {\n \"id\": \"kotlin-rule-14\",\n \"severity\": \"guidance\",\n \"summary\": \"**`?.let { }`:** Use for null-conditional execution. Prefer `if (x != null)` when the block is long and `x` is used multiple times (smart cast).\"\n },\n {\n \"id\": \"kotlin-rule-15\",\n \"severity\": \"guidance\",\n \"summary\": \"**Elvis operator `?:`:** Use for default values: `val name = user?.name ?: \\\"Anonymous\\\"`.\"\n },\n {\n \"id\": \"kotlin-rule-16\",\n \"severity\": \"guidance\",\n \"summary\": \"**`requireNotNull` / `checkNotNull`:** Use to assert non-nullability at runtime with a clear message: `requireNotNull(user) { \\\"User must not be null\\\" }`.\"\n },\n {\n \"id\": \"kotlin-rule-17\",\n \"severity\": \"guidance\",\n \"summary\": \"**`data class`:** Use for classes that hold data. They get `equals`, `hashCode`, `toString`, `copy`, and `componentN` for free.\"\n },\n {\n \"id\": \"kotlin-rule-18\",\n \"severity\": \"guidance\",\n \"summary\": \"**`sealed class`:** Use for closed type hierarchies (discriminated unions). Prefer `sealed class` over `enum class` when variants carry different data.\"\n },\n {\n \"id\": \"kotlin-rule-19\",\n \"severity\": \"guidance\",\n \"summary\": \"**`object`:** Use for singletons and companion objects. Do not use a class with a private constructor + static `getInstance()`.\"\n },\n {\n \"id\": \"kotlin-rule-20\",\n \"severity\": \"guidance\",\n \"summary\": \"**`companion object`:** Use for factory methods and constants logically associated with a class. Name the companion only if it will be referenced by name.\"\n },\n {\n \"id\": \"kotlin-rule-21\",\n \"severity\": \"guidance\",\n \"summary\": \"**`val` over `var`:** Prefer immutable `val` properties. Use `var` only when mutation is necessary.\"\n },\n {\n \"id\": \"kotlin-rule-22\",\n \"severity\": \"guidance\",\n \"summary\": \"**`init` blocks:** Minimize logic in `init` blocks. Prefer constructor parameter defaults and `lazy` properties.\"\n },\n {\n \"id\": \"kotlin-rule-23\",\n \"severity\": \"guidance\",\n \"summary\": \"**`lazy`:** Use `by lazy { }` for properties that are expensive to compute and not always needed.\"\n },\n {\n \"id\": \"kotlin-rule-24\",\n \"severity\": \"guidance\",\n \"summary\": \"**Expression bodies:** Use `= expression` for single-expression functions. Omit braces and `return`.\"\n },\n {\n \"id\": \"kotlin-rule-25\",\n \"severity\": \"guidance\",\n \"summary\": \"**Default parameter values:** Use default values instead of overloaded functions.\"\n },\n {\n \"id\": \"kotlin-rule-26\",\n \"severity\": \"guidance\",\n \"summary\": \"**Named arguments:** Use named arguments when calling functions with many parameters or when the parameter type is a primitive and meaning is unclear.\"\n },\n {\n \"id\": \"kotlin-rule-27\",\n \"severity\": \"guidance\",\n \"summary\": \"**Extension functions:** Use extension functions to add behavior to existing types without subclassing. Place extensions in a file named `TypeExtensions.kt`.\"\n },\n {\n \"id\": \"kotlin-rule-28\",\n \"severity\": \"guidance\",\n \"summary\": \"**Scope functions (`let`, `run`, `with`, `apply`, `also`):**\"\n },\n {\n \"id\": \"kotlin-rule-29\",\n \"severity\": \"guidance\",\n \"summary\": \"`apply`: Configure an object — use when returning the object. (`builder.apply { ... }`)\"\n },\n {\n \"id\": \"kotlin-rule-30\",\n \"severity\": \"guidance\",\n \"summary\": \"`also`: Perform side effects — use when returning the object. (`list.also { log(it) }`)\"\n },\n {\n \"id\": \"kotlin-rule-31\",\n \"severity\": \"guidance\",\n \"summary\": \"`let`: Transform a value, especially with nullability. (`str?.let { process(it) }`)\"\n },\n {\n \"id\": \"kotlin-rule-32\",\n \"severity\": \"guidance\",\n \"summary\": \"`run`/`with`: Group a block of operations on an object. Prefer `run` for nullable receivers, `with` for non-null.\"\n },\n {\n \"id\": \"kotlin-rule-33\",\n \"severity\": \"guidance\",\n \"summary\": \"**Do not nest scope functions more than 2 levels deep.**\"\n },\n {\n \"id\": \"kotlin-rule-34\",\n \"severity\": \"guidance\",\n \"summary\": \"**`operator fun`:** Only implement operator overloads when the semantics are universally clear (e.g., `+` for numeric types, `get`/`set` for collections).\"\n },\n {\n \"id\": \"kotlin-rule-35\",\n \"severity\": \"guidance\",\n \"summary\": \"**Immutable collections:** Prefer `listOf`, `mapOf`, `setOf`. Use `mutableListOf` etc. only when mutation is needed.\"\n },\n {\n \"id\": \"kotlin-rule-36\",\n \"severity\": \"guidance\",\n \"summary\": \"**`Sequence` for lazy pipelines:** Use `asSequence()` for long transformation chains on large collections to avoid creating intermediate lists.\"\n },\n {\n \"id\": \"kotlin-rule-37\",\n \"severity\": \"guidance\",\n \"summary\": \"**Avoid `null` in collections:** Prefer `emptyList()` over `null` for absent collections. Use `filterNotNull()` to clean mixed lists.\"\n },\n {\n \"id\": \"kotlin-rule-38\",\n \"severity\": \"guidance\",\n \"summary\": \"**`associate`, `groupBy`, `partition`:** Use the stdlib collection transforms instead of manual loops.\"\n },\n {\n \"id\": \"kotlin-rule-39\",\n \"severity\": \"guidance\",\n \"summary\": \"**Destructuring:** Use destructuring declarations in `for` loops and `map` operations: `for ((key, value) in map)`.\"\n },\n {\n \"id\": \"kotlin-rule-40\",\n \"severity\": \"guidance\",\n \"summary\": \"**`suspend` functions:** Mark any function that calls another `suspend` function or performs async I/O as `suspend`. Do not block inside `suspend` functions — use `withContext(Dispatchers.IO)`.\"\n },\n {\n \"id\": \"kotlin-rule-41\",\n \"severity\": \"guidance\",\n \"summary\": \"**Structured concurrency:** Always launch coroutines in a `CoroutineScope`. Never use `GlobalScope` in application code.\"\n },\n {\n \"id\": \"kotlin-rule-42\",\n \"severity\": \"guidance\",\n \"summary\": \"**`Dispatchers.Main` / `.IO` / `.Default`:** Use the correct dispatcher — `Main` for UI, `IO` for blocking I/O, `Default` for CPU work.\"\n },\n {\n \"id\": \"kotlin-rule-43\",\n \"severity\": \"guidance\",\n \"summary\": \"**`Flow`:** Use `Flow<T>` for streams of values. Use `StateFlow`/`SharedFlow` for hot streams. Call `.collect {}` in a lifecycle-aware scope.\"\n },\n {\n \"id\": \"kotlin-rule-44\",\n \"severity\": \"guidance\",\n \"summary\": \"**Error handling:** Use `try/catch` inside coroutines. Use `CoroutineExceptionHandler` for unhandled exceptions in `launch`. `async`/`await` propagates exceptions at the `await` site.\"\n },\n {\n \"id\": \"kotlin-rule-45\",\n \"severity\": \"guidance\",\n \"summary\": \"**`viewModelScope` / `lifecycleScope`:** Use these scopes in Android (see Android guide) to tie coroutine lifetime to the component.\"\n },\n {\n \"id\": \"kotlin-rule-46\",\n \"severity\": \"guidance\",\n \"summary\": \"**Exceptions for exceptional cases:** Do not use exceptions for normal control flow. Return `Result<T>`, `sealed class`, or nullable values for expected failure paths.\"\n },\n {\n \"id\": \"kotlin-rule-47\",\n \"severity\": \"guidance\",\n \"summary\": \"**`runCatching`:** Use `runCatching { }` for concise try-catch with `Result<T>` return.\"\n },\n {\n \"id\": \"kotlin-rule-48\",\n \"severity\": \"guidance\",\n \"summary\": \"**Avoid catching `Throwable`:** Catch specific exception types. Catching `Throwable` also catches `Error` (e.g., `OutOfMemoryError`).\"\n },\n {\n \"id\": \"kotlin-rule-49\",\n \"severity\": \"guidance\",\n \"summary\": \"**KDoc (`/** */`):** Use KDoc for all public API documentation.\"\n },\n {\n \"id\": \"kotlin-rule-50\",\n \"severity\": \"guidance\",\n \"summary\": \"**`@param`, `@return`, `@throws`:** Include these tags for public functions with non-obvious parameters or return values.\"\n },\n {\n \"id\": \"kotlin-rule-51\",\n \"severity\": \"guidance\",\n \"summary\": \"**`@since`:** Mark API additions with `@since <version>`.\"\n },\n {\n \"id\": \"kotlin-rule-52\",\n \"severity\": \"guidance\",\n \"summary\": \"**Avoid redundant comments:** Do not restate the function name in the doc. Add information about behavior, edge cases, or constraints.\"\n }\n ],\n \"source\": \"bundled_template\"\n}\n","styleguides/python.json":"{\n \"version\": 1,\n \"schema\": \"cadre.styleguide.v1\",\n \"kind\": \"styleguide\",\n \"id\": \"python\",\n \"title\": \"Google Python Style Guide Summary\",\n \"summary\": \"This document summarizes key rules and best practices from the Google Python Style Guide.\",\n \"sections\": [\n {\n \"heading\": \"1. Python Language Rules\",\n \"body\": \"- **Linting:** Run `pylint` on your code to catch bugs and style issues.\\n- **Imports:** Use `import x` for packages/modules. Use `from x import y` only when `y` is a submodule.\\n- **Exceptions:** Use built-in exception classes. Do not use bare `except:` clauses.\\n- **Global State:** Avoid mutable global state. Module-level constants are okay and should be `ALL_CAPS_WITH_UNDERSCORES`.\\n- **Comprehensions:** Use for simple cases. Avoid for complex logic where a full loop is more readable.\\n- **Default Argument Values:** Do not use mutable objects (like `[]` or `{}`) as default values.\\n- **True/False Evaluations:** Use implicit false (e.g., `if not my_list:`). Use `if foo is None:` to check for `None`.\\n- **Type Annotations:** Strongly encouraged for all public APIs.\"\n },\n {\n \"heading\": \"2. Python Style Rules\",\n \"body\": \"- **Line Length:** Maximum 80 characters.\\n- **Indentation:** 4 spaces per indentation level. Never use tabs.\\n- **Blank Lines:** Two blank lines between top-level definitions (classes, functions). One blank line between method definitions.\\n- **Whitespace:** Avoid extraneous whitespace. Surround binary operators with single spaces.\\n- **Docstrings:** Use `\\\"\\\"\\\"triple double quotes\\\"\\\"\\\"`. Every public module, function, class, and method must have a docstring.\\n - **Format:** Start with a one-line summary. Include `Args:`, `Returns:`, and `Raises:` sections.\\n- **Strings:** Use f-strings for formatting. Be consistent with single (`'`) or double (`\\\"`) quotes.\\n- **`TODO` Comments:** Use `TODO(username): Fix this.` format.\\n- **Imports Formatting:** Imports should be on separate lines and grouped: standard library, third-party, and your own application's imports.\"\n },\n {\n \"heading\": \"3. Naming\",\n \"body\": \"- **General:** `snake_case` for modules, functions, methods, and variables.\\n- **Classes:** `PascalCase`.\\n- **Constants:** `ALL_CAPS_WITH_UNDERSCORES`.\\n- **Internal Use:** Use a single leading underscore (`_internal_variable`) for internal module/class members.\"\n },\n {\n \"heading\": \"4. Main\",\n \"body\": \"- All executable files should have a `main()` function that contains the main logic, called from a `if __name__ == '__main__':` block.\\n\\n**BE CONSISTENT.** When editing code, match the existing style.\\n\\n*Source: [Google Python Style Guide](https://google.github.io/styleguide/pyguide.html)*\"\n }\n ],\n \"languages\": [\n \"python\"\n ],\n \"frameworks\": [],\n \"file_patterns\": [],\n \"applies_to\": [\n \"planning\",\n \"implementation\",\n \"review\",\n \"tests\"\n ],\n \"rules\": [\n {\n \"id\": \"python-rule-1\",\n \"severity\": \"guidance\",\n \"summary\": \"**Linting:** Run `pylint` on your code to catch bugs and style issues.\"\n },\n {\n \"id\": \"python-rule-2\",\n \"severity\": \"guidance\",\n \"summary\": \"**Imports:** Use `import x` for packages/modules. Use `from x import y` only when `y` is a submodule.\"\n },\n {\n \"id\": \"python-rule-3\",\n \"severity\": \"guidance\",\n \"summary\": \"**Exceptions:** Use built-in exception classes. Do not use bare `except:` clauses.\"\n },\n {\n \"id\": \"python-rule-4\",\n \"severity\": \"guidance\",\n \"summary\": \"**Global State:** Avoid mutable global state. Module-level constants are okay and should be `ALL_CAPS_WITH_UNDERSCORES`.\"\n },\n {\n \"id\": \"python-rule-5\",\n \"severity\": \"guidance\",\n \"summary\": \"**Comprehensions:** Use for simple cases. Avoid for complex logic where a full loop is more readable.\"\n },\n {\n \"id\": \"python-rule-6\",\n \"severity\": \"guidance\",\n \"summary\": \"**Default Argument Values:** Do not use mutable objects (like `[]` or `{}`) as default values.\"\n },\n {\n \"id\": \"python-rule-7\",\n \"severity\": \"guidance\",\n \"summary\": \"**True/False Evaluations:** Use implicit false (e.g., `if not my_list:`). Use `if foo is None:` to check for `None`.\"\n },\n {\n \"id\": \"python-rule-8\",\n \"severity\": \"guidance\",\n \"summary\": \"**Type Annotations:** Strongly encouraged for all public APIs.\"\n },\n {\n \"id\": \"python-rule-9\",\n \"severity\": \"guidance\",\n \"summary\": \"**Line Length:** Maximum 80 characters.\"\n },\n {\n \"id\": \"python-rule-10\",\n \"severity\": \"guidance\",\n \"summary\": \"**Indentation:** 4 spaces per indentation level. Never use tabs.\"\n },\n {\n \"id\": \"python-rule-11\",\n \"severity\": \"guidance\",\n \"summary\": \"**Blank Lines:** Two blank lines between top-level definitions (classes, functions). One blank line between method definitions.\"\n },\n {\n \"id\": \"python-rule-12\",\n \"severity\": \"guidance\",\n \"summary\": \"**Whitespace:** Avoid extraneous whitespace. Surround binary operators with single spaces.\"\n },\n {\n \"id\": \"python-rule-13\",\n \"severity\": \"guidance\",\n \"summary\": \"**Docstrings:** Use `\\\"\\\"\\\"triple double quotes\\\"\\\"\\\"`. Every public module, function, class, and method must have a docstring.\"\n },\n {\n \"id\": \"python-rule-14\",\n \"severity\": \"guidance\",\n \"summary\": \"**Format:** Start with a one-line summary. Include `Args:`, `Returns:`, and `Raises:` sections.\"\n },\n {\n \"id\": \"python-rule-15\",\n \"severity\": \"guidance\",\n \"summary\": \"**Strings:** Use f-strings for formatting. Be consistent with single (`'`) or double (`\\\"`) quotes.\"\n },\n {\n \"id\": \"python-rule-16\",\n \"severity\": \"guidance\",\n \"summary\": \"**`TODO` Comments:** Use `TODO(username): Fix this.` format.\"\n },\n {\n \"id\": \"python-rule-17\",\n \"severity\": \"guidance\",\n \"summary\": \"**Imports Formatting:** Imports should be on separate lines and grouped: standard library, third-party, and your own application's imports.\"\n },\n {\n \"id\": \"python-rule-18\",\n \"severity\": \"guidance\",\n \"summary\": \"**General:** `snake_case` for modules, functions, methods, and variables.\"\n },\n {\n \"id\": \"python-rule-19\",\n \"severity\": \"guidance\",\n \"summary\": \"**Classes:** `PascalCase`.\"\n },\n {\n \"id\": \"python-rule-20\",\n \"severity\": \"guidance\",\n \"summary\": \"**Constants:** `ALL_CAPS_WITH_UNDERSCORES`.\"\n },\n {\n \"id\": \"python-rule-21\",\n \"severity\": \"guidance\",\n \"summary\": \"**Internal Use:** Use a single leading underscore (`_internal_variable`) for internal module/class members.\"\n },\n {\n \"id\": \"python-rule-22\",\n \"severity\": \"guidance\",\n \"summary\": \"All executable files should have a `main()` function that contains the main logic, called from a `if __name__ == '__main__':` block.\"\n }\n ],\n \"source\": \"bundled_template\"\n}\n","styleguides/rust.json":"{\n \"version\": 1,\n \"schema\": \"cadre.styleguide.v1\",\n \"kind\": \"styleguide\",\n \"id\": \"rust\",\n \"title\": \"Effective Rust Style Guide Summary\",\n \"summary\": \"This document summarizes key rules and best practices from the official Rust API Guidelines, Rust Style Guide, and idiomatic Rust conventions for writing safe, performant, and maintainable Rust code.\",\n \"sections\": [\n {\n \"heading\": \"1. Formatting\",\n \"body\": \"- **`rustfmt`:** All Rust code **must** be formatted with `rustfmt`. This is non-negotiable. Run via `cargo fmt`.\\n- **`clippy`:** Run `cargo clippy` and fix all warnings before review. Treat lints as errors in CI: `RUSTFLAGS=\\\"-D warnings\\\"`.\\n- **Indentation:** 4 spaces. No tabs.\\n- **Line Length:** 100 characters maximum (rustfmt default).\"\n },\n {\n \"heading\": \"2. Naming\",\n \"body\": \"- **`snake_case`:** For functions, methods, variables, modules, and crates.\\n- **`UpperCamelCase`:** For types, traits, enums, and struct names.\\n- **`SCREAMING_SNAKE_CASE`:** For constants and statics.\\n- **`snake_case`:** For crate names (hyphens in `Cargo.toml` map to underscores in code).\\n- **Acronyms:** Treat acronyms as words — `HttpClient`, not `HTTPClient`; `JsonParser`, not `JSONParser`.\\n- **Getters:** Do not prefix with `get_`. A getter for `name` is `name()`, not `get_name()`.\\n- **Setters:** Use `set_name()`.\\n- **Builders:** Use the `Builder` suffix and return `Self` or `Result<T>` from `build()`.\\n- **Iterator adaptors:** Name the struct for its iterator, e.g., `Lines` for a `lines()` method.\"\n },\n {\n \"heading\": \"3. Ownership and Borrowing\",\n \"body\": \"- **Prefer borrowing over cloning:** Pass `&T` or `&mut T` unless ownership transfer is required.\\n- **Prefer `&str` over `&String`:** Accept `&str` in function arguments; callers with `String` can deref. Same for `&[T]` over `&Vec<T>` and `&Path` over `&PathBuf`.\\n- **Minimize `clone()`:** A `clone()` call is a code smell if it can be avoided with a borrow.\\n- **Avoid `unwrap()` in library code:** Use `?` to propagate errors. Reserve `unwrap()` for prototypes, tests, or genuinely infallible paths (document why).\\n- **Use `expect()` over `unwrap()`** when a panic is intended: `expect(\\\"config file must exist\\\")` produces better diagnostics.\"\n },\n {\n \"heading\": \"4. Error Handling\",\n \"body\": \"- **`Result<T, E>` is the standard:** Use it for all fallible functions. Never silently discard errors.\\n- **`?` operator:** Use `?` to propagate errors up the call stack. Do not write `match` blocks for simple propagation.\\n- **Error types:** In libraries, define a custom error type implementing `std::error::Error`. Use `thiserror` crate. In applications, use `anyhow` for ergonomic error context.\\n- **`panic!`:** Reserved for unrecoverable programming errors (invariant violations). Libraries must not panic in normal operation.\\n- **`unwrap_or_else`, `map`, `and_then`:** Chain `Result`/`Option` combinators for concise, readable error paths.\"\n },\n {\n \"heading\": \"5. Types and Traits\",\n \"body\": \"- **Newtype pattern:** Wrap primitive types in newtypes to enforce invariants: `struct Meters(f64);`.\\n- **Derive common traits:** Derive `Debug`, `Clone`, `PartialEq`, `Eq`, `Hash`, `Default` where appropriate. Always derive `Debug`.\\n- **`Default` trait:** Implement `Default` for types that have a sensible zero/empty value. Use `#[derive(Default)]` when possible.\\n- **Trait objects vs. generics:** Prefer generics (`fn foo<T: Trait>(x: T)`) for performance. Use `dyn Trait` only when type erasure is needed (heterogeneous collections, dynamic dispatch).\\n- **`impl Trait` in return position:** Use for simple cases to hide concrete return types without boxing.\\n- **Sealed traits:** Use the sealed-trait pattern to prevent external implementations of traits not designed for extension.\\n- **Iterator:** Implement `Iterator` for custom collections. Return `impl Iterator` from methods rather than concrete types.\"\n },\n {\n \"heading\": \"6. Enums and Pattern Matching\",\n \"body\": \"- **Enums over booleans:** Prefer `enum Direction { Left, Right }` over `bool` for clarity.\\n- **`match` is exhaustive:** Always handle all variants. Prefer explicit arms over `_ =>` wildcards when variants may be added.\\n- **`if let` / `while let`:** Use for single-pattern matching instead of a full `match` block.\\n- **`Option` instead of null:** Never model absence with sentinel values. Use `Option<T>`.\\n- **Avoid nested `match`:** Flatten with combinators (`map`, `and_then`, `unwrap_or`) or `?`.\"\n },\n {\n \"heading\": \"7. Concurrency\",\n \"body\": \"- **Fearless concurrency:** Let the compiler enforce thread safety via `Send` and `Sync` bounds.\\n- **Prefer channels over shared state:** Use `std::sync::mpsc` or `tokio::sync` channels.\\n- **`Arc<Mutex<T>>`:** Standard pattern for shared mutable state. Lock for the minimum scope needed.\\n- **`async`/`await`:** Use for I/O-bound concurrency. Use `tokio` or `async-std` as the runtime. Do not block inside async functions — use `tokio::task::spawn_blocking` for CPU-bound work.\\n- **`rayon`:** Use for data-parallel CPU-bound work instead of manual threading.\"\n },\n {\n \"heading\": \"8. Modules and Visibility\",\n \"body\": \"- **`pub` is an API contract:** Only `pub` what is intended to be part of the public API. Default to private.\\n- **`pub(crate)`:** Use for items shared within a crate but not externally.\\n- **`mod.rs` vs. inline modules:** Prefer `module/mod.rs` for multi-file modules. Prefer inline `mod` for small, single-file submodules.\\n- **`use` declarations:** Group imports: std → external crates → local. Use `rustfmt` to sort.\\n- **Re-exports:** Re-export public types at the crate root to flatten the API surface.\"\n },\n {\n \"heading\": \"9. Performance\",\n \"body\": \"- **Zero-cost abstractions:** Trust iterators, closures, and generics — they compile to the same code as manual loops.\\n- **Avoid unnecessary allocation:** Prefer stack types and slices. Profile before switching to `Box`, `Vec`, or `Arc`.\\n- **`Cow<str>` / `Cow<[T]>`:** Use when a function sometimes needs to allocate and sometimes doesn't.\\n- **Inline:** Use `#[inline]` on small hot functions. Use `#[inline(always)]` sparingly.\"\n },\n {\n \"heading\": \"10. Documentation\",\n \"body\": \"- **`///` doc comments:** All public items **must** have doc comments. Include an example in `# Examples` for non-trivial functions.\\n- **`//!` module docs:** Add module-level documentation explaining purpose and usage.\\n- **`# Panics` / `# Errors` / `# Safety`:** Document these sections on any function that panics, returns `Result`, or is `unsafe`.\\n- **`cargo doc --open`:** Verify documentation renders correctly before publishing.\\n- **`unsafe` blocks:** Every `unsafe` block **must** have a `// SAFETY:` comment explaining why the invariants are upheld.\\n\\n*Sources: [Rust API Guidelines](https://rust-lang.github.io/api-guidelines/) · [Rust Style Guide](https://doc.rust-lang.org/nightly/style-guide/) · [The Rust Book](https://doc.rust-lang.org/book/)*\"\n }\n ],\n \"languages\": [\n \"rust\"\n ],\n \"frameworks\": [],\n \"file_patterns\": [],\n \"applies_to\": [\n \"planning\",\n \"implementation\",\n \"review\",\n \"tests\"\n ],\n \"rules\": [\n {\n \"id\": \"rust-rule-1\",\n \"severity\": \"guidance\",\n \"summary\": \"**`rustfmt`:** All Rust code **must** be formatted with `rustfmt`. This is non-negotiable. Run via `cargo fmt`.\"\n },\n {\n \"id\": \"rust-rule-2\",\n \"severity\": \"guidance\",\n \"summary\": \"**`clippy`:** Run `cargo clippy` and fix all warnings before review. Treat lints as errors in CI: `RUSTFLAGS=\\\"-D warnings\\\"`.\"\n },\n {\n \"id\": \"rust-rule-3\",\n \"severity\": \"guidance\",\n \"summary\": \"**Indentation:** 4 spaces. No tabs.\"\n },\n {\n \"id\": \"rust-rule-4\",\n \"severity\": \"guidance\",\n \"summary\": \"**Line Length:** 100 characters maximum (rustfmt default).\"\n },\n {\n \"id\": \"rust-rule-5\",\n \"severity\": \"guidance\",\n \"summary\": \"**`snake_case`:** For functions, methods, variables, modules, and crates.\"\n },\n {\n \"id\": \"rust-rule-6\",\n \"severity\": \"guidance\",\n \"summary\": \"**`UpperCamelCase`:** For types, traits, enums, and struct names.\"\n },\n {\n \"id\": \"rust-rule-7\",\n \"severity\": \"guidance\",\n \"summary\": \"**`SCREAMING_SNAKE_CASE`:** For constants and statics.\"\n },\n {\n \"id\": \"rust-rule-8\",\n \"severity\": \"guidance\",\n \"summary\": \"**`snake_case`:** For crate names (hyphens in `Cargo.toml` map to underscores in code).\"\n },\n {\n \"id\": \"rust-rule-9\",\n \"severity\": \"guidance\",\n \"summary\": \"**Acronyms:** Treat acronyms as words — `HttpClient`, not `HTTPClient`; `JsonParser`, not `JSONParser`.\"\n },\n {\n \"id\": \"rust-rule-10\",\n \"severity\": \"guidance\",\n \"summary\": \"**Getters:** Do not prefix with `get_`. A getter for `name` is `name()`, not `get_name()`.\"\n },\n {\n \"id\": \"rust-rule-11\",\n \"severity\": \"guidance\",\n \"summary\": \"**Setters:** Use `set_name()`.\"\n },\n {\n \"id\": \"rust-rule-12\",\n \"severity\": \"guidance\",\n \"summary\": \"**Builders:** Use the `Builder` suffix and return `Self` or `Result<T>` from `build()`.\"\n },\n {\n \"id\": \"rust-rule-13\",\n \"severity\": \"guidance\",\n \"summary\": \"**Iterator adaptors:** Name the struct for its iterator, e.g., `Lines` for a `lines()` method.\"\n },\n {\n \"id\": \"rust-rule-14\",\n \"severity\": \"guidance\",\n \"summary\": \"**Prefer borrowing over cloning:** Pass `&T` or `&mut T` unless ownership transfer is required.\"\n },\n {\n \"id\": \"rust-rule-15\",\n \"severity\": \"guidance\",\n \"summary\": \"**Prefer `&str` over `&String`:** Accept `&str` in function arguments; callers with `String` can deref. Same for `&[T]` over `&Vec<T>` and `&Path` over `&PathBuf`.\"\n },\n {\n \"id\": \"rust-rule-16\",\n \"severity\": \"guidance\",\n \"summary\": \"**Minimize `clone()`:** A `clone()` call is a code smell if it can be avoided with a borrow.\"\n },\n {\n \"id\": \"rust-rule-17\",\n \"severity\": \"guidance\",\n \"summary\": \"**Avoid `unwrap()` in library code:** Use `?` to propagate errors. Reserve `unwrap()` for prototypes, tests, or genuinely infallible paths (document why).\"\n },\n {\n \"id\": \"rust-rule-18\",\n \"severity\": \"guidance\",\n \"summary\": \"**Use `expect()` over `unwrap()`** when a panic is intended: `expect(\\\"config file must exist\\\")` produces better diagnostics.\"\n },\n {\n \"id\": \"rust-rule-19\",\n \"severity\": \"guidance\",\n \"summary\": \"**`Result<T, E>` is the standard:** Use it for all fallible functions. Never silently discard errors.\"\n },\n {\n \"id\": \"rust-rule-20\",\n \"severity\": \"guidance\",\n \"summary\": \"**`?` operator:** Use `?` to propagate errors up the call stack. Do not write `match` blocks for simple propagation.\"\n },\n {\n \"id\": \"rust-rule-21\",\n \"severity\": \"guidance\",\n \"summary\": \"**Error types:** In libraries, define a custom error type implementing `std::error::Error`. Use `thiserror` crate. In applications, use `anyhow` for ergonomic error context.\"\n },\n {\n \"id\": \"rust-rule-22\",\n \"severity\": \"guidance\",\n \"summary\": \"**`panic!`:** Reserved for unrecoverable programming errors (invariant violations). Libraries must not panic in normal operation.\"\n },\n {\n \"id\": \"rust-rule-23\",\n \"severity\": \"guidance\",\n \"summary\": \"**`unwrap_or_else`, `map`, `and_then`:** Chain `Result`/`Option` combinators for concise, readable error paths.\"\n },\n {\n \"id\": \"rust-rule-24\",\n \"severity\": \"guidance\",\n \"summary\": \"**Newtype pattern:** Wrap primitive types in newtypes to enforce invariants: `struct Meters(f64);`.\"\n },\n {\n \"id\": \"rust-rule-25\",\n \"severity\": \"guidance\",\n \"summary\": \"**Derive common traits:** Derive `Debug`, `Clone`, `PartialEq`, `Eq`, `Hash`, `Default` where appropriate. Always derive `Debug`.\"\n },\n {\n \"id\": \"rust-rule-26\",\n \"severity\": \"guidance\",\n \"summary\": \"**`Default` trait:** Implement `Default` for types that have a sensible zero/empty value. Use `#[derive(Default)]` when possible.\"\n },\n {\n \"id\": \"rust-rule-27\",\n \"severity\": \"guidance\",\n \"summary\": \"**Trait objects vs. generics:** Prefer generics (`fn foo<T: Trait>(x: T)`) for performance. Use `dyn Trait` only when type erasure is needed (heterogeneous collections, dynamic dispatch).\"\n },\n {\n \"id\": \"rust-rule-28\",\n \"severity\": \"guidance\",\n \"summary\": \"**`impl Trait` in return position:** Use for simple cases to hide concrete return types without boxing.\"\n },\n {\n \"id\": \"rust-rule-29\",\n \"severity\": \"guidance\",\n \"summary\": \"**Sealed traits:** Use the sealed-trait pattern to prevent external implementations of traits not designed for extension.\"\n },\n {\n \"id\": \"rust-rule-30\",\n \"severity\": \"guidance\",\n \"summary\": \"**Iterator:** Implement `Iterator` for custom collections. Return `impl Iterator` from methods rather than concrete types.\"\n },\n {\n \"id\": \"rust-rule-31\",\n \"severity\": \"guidance\",\n \"summary\": \"**Enums over booleans:** Prefer `enum Direction { Left, Right }` over `bool` for clarity.\"\n },\n {\n \"id\": \"rust-rule-32\",\n \"severity\": \"guidance\",\n \"summary\": \"**`match` is exhaustive:** Always handle all variants. Prefer explicit arms over `_ =>` wildcards when variants may be added.\"\n },\n {\n \"id\": \"rust-rule-33\",\n \"severity\": \"guidance\",\n \"summary\": \"**`if let` / `while let`:** Use for single-pattern matching instead of a full `match` block.\"\n },\n {\n \"id\": \"rust-rule-34\",\n \"severity\": \"guidance\",\n \"summary\": \"**`Option` instead of null:** Never model absence with sentinel values. Use `Option<T>`.\"\n },\n {\n \"id\": \"rust-rule-35\",\n \"severity\": \"guidance\",\n \"summary\": \"**Avoid nested `match`:** Flatten with combinators (`map`, `and_then`, `unwrap_or`) or `?`.\"\n },\n {\n \"id\": \"rust-rule-36\",\n \"severity\": \"guidance\",\n \"summary\": \"**Fearless concurrency:** Let the compiler enforce thread safety via `Send` and `Sync` bounds.\"\n },\n {\n \"id\": \"rust-rule-37\",\n \"severity\": \"guidance\",\n \"summary\": \"**Prefer channels over shared state:** Use `std::sync::mpsc` or `tokio::sync` channels.\"\n },\n {\n \"id\": \"rust-rule-38\",\n \"severity\": \"guidance\",\n \"summary\": \"**`Arc<Mutex<T>>`:** Standard pattern for shared mutable state. Lock for the minimum scope needed.\"\n },\n {\n \"id\": \"rust-rule-39\",\n \"severity\": \"guidance\",\n \"summary\": \"**`async`/`await`:** Use for I/O-bound concurrency. Use `tokio` or `async-std` as the runtime. Do not block inside async functions — use `tokio::task::spawn_blocking` for CPU-bound work.\"\n },\n {\n \"id\": \"rust-rule-40\",\n \"severity\": \"guidance\",\n \"summary\": \"**`rayon`:** Use for data-parallel CPU-bound work instead of manual threading.\"\n },\n {\n \"id\": \"rust-rule-41\",\n \"severity\": \"guidance\",\n \"summary\": \"**`pub` is an API contract:** Only `pub` what is intended to be part of the public API. Default to private.\"\n },\n {\n \"id\": \"rust-rule-42\",\n \"severity\": \"guidance\",\n \"summary\": \"**`pub(crate)`:** Use for items shared within a crate but not externally.\"\n },\n {\n \"id\": \"rust-rule-43\",\n \"severity\": \"guidance\",\n \"summary\": \"**`mod.rs` vs. inline modules:** Prefer `module/mod.rs` for multi-file modules. Prefer inline `mod` for small, single-file submodules.\"\n },\n {\n \"id\": \"rust-rule-44\",\n \"severity\": \"guidance\",\n \"summary\": \"**`use` declarations:** Group imports: std → external crates → local. Use `rustfmt` to sort.\"\n },\n {\n \"id\": \"rust-rule-45\",\n \"severity\": \"guidance\",\n \"summary\": \"**Re-exports:** Re-export public types at the crate root to flatten the API surface.\"\n },\n {\n \"id\": \"rust-rule-46\",\n \"severity\": \"guidance\",\n \"summary\": \"**Zero-cost abstractions:** Trust iterators, closures, and generics — they compile to the same code as manual loops.\"\n },\n {\n \"id\": \"rust-rule-47\",\n \"severity\": \"guidance\",\n \"summary\": \"**Avoid unnecessary allocation:** Prefer stack types and slices. Profile before switching to `Box`, `Vec`, or `Arc`.\"\n },\n {\n \"id\": \"rust-rule-48\",\n \"severity\": \"guidance\",\n \"summary\": \"**`Cow<str>` / `Cow<[T]>`:** Use when a function sometimes needs to allocate and sometimes doesn't.\"\n },\n {\n \"id\": \"rust-rule-49\",\n \"severity\": \"guidance\",\n \"summary\": \"**Inline:** Use `#[inline]` on small hot functions. Use `#[inline(always)]` sparingly.\"\n },\n {\n \"id\": \"rust-rule-50\",\n \"severity\": \"guidance\",\n \"summary\": \"**`///` doc comments:** All public items **must** have doc comments. Include an example in `# Examples` for non-trivial functions.\"\n },\n {\n \"id\": \"rust-rule-51\",\n \"severity\": \"guidance\",\n \"summary\": \"**`//!` module docs:** Add module-level documentation explaining purpose and usage.\"\n },\n {\n \"id\": \"rust-rule-52\",\n \"severity\": \"guidance\",\n \"summary\": \"**`# Panics` / `# Errors` / `# Safety`:** Document these sections on any function that panics, returns `Result`, or is `unsafe`.\"\n },\n {\n \"id\": \"rust-rule-53\",\n \"severity\": \"guidance\",\n \"summary\": \"**`cargo doc --open`:** Verify documentation renders correctly before publishing.\"\n },\n {\n \"id\": \"rust-rule-54\",\n \"severity\": \"guidance\",\n \"summary\": \"**`unsafe` blocks:** Every `unsafe` block **must** have a `// SAFETY:` comment explaining why the invariants are upheld.\"\n }\n ],\n \"source\": \"bundled_template\"\n}\n","styleguides/swift.json":"{\n \"version\": 1,\n \"schema\": \"cadre.styleguide.v1\",\n \"kind\": \"styleguide\",\n \"id\": \"swift\",\n \"title\": \"Swift API Design Guidelines Style Guide Summary\",\n \"summary\": \"This document summarizes key rules and best practices from the Swift API Design Guidelines and Swift.org style conventions for writing idiomatic, safe, and expressive Swift code.\",\n \"sections\": [\n {\n \"heading\": \"1. Formatting\",\n \"body\": \"- **SwiftFormat / SwiftLint:** Format with `swiftformat` and lint with `swiftlint`. Enforce both in CI. Include `.swiftlint.yml` in the repository root.\\n- **Indentation:** 4 spaces. No tabs.\\n- **Line Length:** 120 characters maximum (SwiftLint default; adjust to team preference).\\n- **Blank lines:** One blank line between declarations. Two blank lines between major sections (e.g., before `// MARK:` sections).\"\n },\n {\n \"heading\": \"2. Naming\",\n \"body\": \"- **`UpperCamelCase`:** For types (class, struct, enum, protocol, typealias) and enum cases.\\n- **`lowerCamelCase`:** For functions, methods, properties, parameters, and local variables.\\n- **Clarity at the call site:** Name things so usage reads like prose: `list.insert(element, at: index)`, not `list.insert(element, position: index)`.\\n- **Omit needless words:** Do not repeat the type in the name. `backgroundColor`, not `backgroundColorOfView`. `users.remove(at: index)`, not `users.removeElement(at: index)`.\\n- **Boolean properties:** Start with `is`, `has`, `can`, or `should`: `isEnabled`, `hasChildren`, `canClose`.\\n- **Protocol naming:**\\n - Protocols describing what something *is*: noun (`Collection`, `Sequence`).\\n - Protocols describing a *capability*: `-able`, `-ible`, `-ing` suffix (`Hashable`, `Codable`, `Equatable`).\\n- **Avoid abbreviations:** Use full words. `destinationURL` not `destURL`, `error` not `err`, `index` not `idx`. Well-known abbreviations (`URL`, `ID`, `JSON`) are fine.\\n- **First argument label:** Omit when it is obviously part of the function name: `x.addSubview(y)` not `x.addSubview(view: y)`. Include when it adds clarity: `a.move(from: b, to: c)`.\"\n },\n {\n \"heading\": \"3. Types\",\n \"body\": \"- **`struct` by default:** Prefer value types (`struct`, `enum`) over reference types (`class`). Use `class` only when identity semantics, inheritance, or reference sharing is required.\\n- **`final` by default:** Mark classes `final` unless designed for subclassing. Subclassable classes are a design decision, not a default.\\n- **`enum` for closed sets:** Use `enum` for a fixed set of related values. Use `CaseIterable` when you need to enumerate cases.\\n- **Associated values:** Use `enum` with associated values as discriminated unions: `enum Result<T> { case success(T); case failure(Error) }`.\\n- **`typealias`:** Use to clarify the role of complex types: `typealias Completion = (Result<User, Error>) -> Void`.\\n- **`extension` over subclass:** Prefer extending a type to add behavior over subclassing. Extensions cannot store state — use composition for that.\"\n },\n {\n \"heading\": \"4. Optionals\",\n \"body\": \"- **Avoid `!` force-unwrap:** Force-unwrap is a crash waiting to happen. Use `guard let`, `if let`, or `??` instead.\\n- **`guard let` for early exit:** Use `guard let` to unwrap optionals at the top of a function when `nil` means \\\"cannot proceed\\\". This reduces nesting.\\n- **`if let` for optional use:** Use `if let` when the `nil` case is a legitimate alternate path.\\n- **Optional chaining (`?.`):** Use for accessing properties/methods on optionals where `nil` propagation is correct.\\n- **`??` for defaults:** Use the nil-coalescing operator for fallback values: `let name = user?.name ?? \\\"Unknown\\\"`.\\n- **Implicit optionals (`!` type):** Use `@IBOutlet weak var button: UIButton!` and similarly initialized-before-use patterns — keep to `@IBOutlet` and injection patterns only. Never use `!` types for general logic.\"\n },\n {\n \"heading\": \"5. Functions and Closures\",\n \"body\": \"- **Single responsibility:** Each function does one thing. Break down large functions.\\n- **`@discardableResult`:** Add only when ignoring the result is a common and correct pattern. Do not add it to silence warnings mechanically.\\n- **Trailing closure syntax:** Use trailing closure syntax when the closure is the last parameter and its role is clear: `UIView.animate(withDuration: 0.3) { ... }`.\\n- **`@escaping`:** Mark closures `@escaping` when they outlive the function call. Document the lifecycle implications.\\n- **`inout`:** Use `inout` sparingly. Prefer returning a new value over mutating in place unless performance is critical.\\n- **`throws` / `async throws`:** Use `throws` for functions that can fail with typed errors. Use `async` for asynchronous work. Combine as `async throws` for async-fallible functions.\"\n },\n {\n \"heading\": \"6. Error Handling\",\n \"body\": \"- **`throws` + `try`:** Use Swift's typed error handling for recoverable errors. Functions that can fail return via `throw`, not via optional or sentinel values.\\n- **`do / catch`:** Handle errors at the appropriate layer. Do not `try!` unless a failure is genuinely impossible and you can prove it.\\n- **`Result<T, Error>`:** Use `Result` for asynchronous completions that predate `async/await`, or when you need to store a result for later.\\n- **Custom error types:** Define `enum MyError: Error, LocalizedError` with associated values for structured error information. Implement `errorDescription` for user-facing messages.\\n- **`try?`:** Use when `nil` on failure is acceptable and the error is irrelevant to the caller.\"\n },\n {\n \"heading\": \"7. Concurrency (Swift Concurrency)\",\n \"body\": \"- **`async`/`await`:** Prefer Swift Concurrency over completion handlers, Combine, or DispatchQueue-based async code for new code.\\n- **`Task { }`:** Use to bridge from synchronous to async context. Use `Task.detached` only when the task must not inherit actor context.\\n- **`@MainActor`:** Annotate types or functions that must run on the main thread. Use `@MainActor` on ViewModels/Controllers rather than `DispatchQueue.main.async`.\\n- **`actor`:** Use `actor` types for shared mutable state. Actors serialize access and eliminate data races.\\n- **`Sendable`:** Mark types crossing actor boundaries as `Sendable`. Do not suppress `Sendable` warnings with `@unchecked Sendable` without justification.\\n- **`async let`:** Use `async let` for independent concurrent work within a function: `async let user = fetchUser(); async let feed = fetchFeed(); let (u, f) = try await (user, feed)`.\"\n },\n {\n \"heading\": \"8. Memory Management\",\n \"body\": \"- **ARC is automatic:** Do not call `retain`/`release`. ARC handles memory.\\n- **`weak` for delegates and callbacks:** Mark delegate properties `weak var` to avoid retain cycles. Capture `[weak self]` in closures that outlive the object.\\n- **`unowned` only when guaranteed:** Use `unowned` instead of `weak` only when the referenced object is guaranteed to outlive the closure/property. Incorrect `unowned` crashes; incorrect `weak` just produces `nil`.\\n- **`[weak self]` + guard:** Pattern: `{ [weak self] in guard let self = self else { return } ... }` (or `[weak self] in self?.doWork()`).\"\n },\n {\n \"heading\": \"9. Collections and Functional Patterns\",\n \"body\": \"- **`map`, `filter`, `compactMap`, `reduce`:** Use functional transforms over `for` loops for collection transformations.\\n- **`compactMap`:** Use to filter `nil` from a sequence of optionals: `names.compactMap { user(id: $0)?.name }`.\\n- **`flatMap` on sequences:** Use to flatten sequences: `[[1,2],[3,4]].flatMap { $0 }` → `[1,2,3,4]`.\\n- **`lazy`:** Use `collection.lazy.filter { }.map { }` to avoid allocating intermediate arrays for long pipelines.\"\n },\n {\n \"heading\": \"10. Documentation\",\n \"body\": \"- **`///` doc comments:** Use triple-slash comments for all public API. Xcode renders these in Quick Help.\\n- **Summary + discussion:** First line is the summary. Add a blank line then the discussion for longer explanations.\\n- **`- Parameter`, `- Returns`, `- Throws`:** Document parameters, return values, and thrown errors using these list items.\\n- **`- Note:`, `- Important:`, `- Warning:`:** Use callout keywords for additional reader guidance.\\n- **Code examples:** Include brief usage examples in doc comments for complex APIs using fenced code blocks.\\n\\n*Sources: [Swift API Design Guidelines](https://swift.org/documentation/api-design-guidelines/) · [Swift.org Style Guide](https://google.github.io/swift/) · [Swift Concurrency](https://docs.swift.org/swift-book/documentation/the-swift-programming-language/concurrency/)*\"\n }\n ],\n \"languages\": [\n \"swift\"\n ],\n \"frameworks\": [],\n \"file_patterns\": [],\n \"applies_to\": [\n \"planning\",\n \"implementation\",\n \"review\",\n \"tests\"\n ],\n \"rules\": [\n {\n \"id\": \"swift-rule-1\",\n \"severity\": \"guidance\",\n \"summary\": \"**SwiftFormat / SwiftLint:** Format with `swiftformat` and lint with `swiftlint`. Enforce both in CI. Include `.swiftlint.yml` in the repository root.\"\n },\n {\n \"id\": \"swift-rule-2\",\n \"severity\": \"guidance\",\n \"summary\": \"**Indentation:** 4 spaces. No tabs.\"\n },\n {\n \"id\": \"swift-rule-3\",\n \"severity\": \"guidance\",\n \"summary\": \"**Line Length:** 120 characters maximum (SwiftLint default; adjust to team preference).\"\n },\n {\n \"id\": \"swift-rule-4\",\n \"severity\": \"guidance\",\n \"summary\": \"**Blank lines:** One blank line between declarations. Two blank lines between major sections (e.g., before `// MARK:` sections).\"\n },\n {\n \"id\": \"swift-rule-5\",\n \"severity\": \"guidance\",\n \"summary\": \"**`UpperCamelCase`:** For types (class, struct, enum, protocol, typealias) and enum cases.\"\n },\n {\n \"id\": \"swift-rule-6\",\n \"severity\": \"guidance\",\n \"summary\": \"**`lowerCamelCase`:** For functions, methods, properties, parameters, and local variables.\"\n },\n {\n \"id\": \"swift-rule-7\",\n \"severity\": \"guidance\",\n \"summary\": \"**Clarity at the call site:** Name things so usage reads like prose: `list.insert(element, at: index)`, not `list.insert(element, position: index)`.\"\n },\n {\n \"id\": \"swift-rule-8\",\n \"severity\": \"guidance\",\n \"summary\": \"**Omit needless words:** Do not repeat the type in the name. `backgroundColor`, not `backgroundColorOfView`. `users.remove(at: index)`, not `users.removeElement(at: index)`.\"\n },\n {\n \"id\": \"swift-rule-9\",\n \"severity\": \"guidance\",\n \"summary\": \"**Boolean properties:** Start with `is`, `has`, `can`, or `should`: `isEnabled`, `hasChildren`, `canClose`.\"\n },\n {\n \"id\": \"swift-rule-10\",\n \"severity\": \"guidance\",\n \"summary\": \"**Protocol naming:**\"\n },\n {\n \"id\": \"swift-rule-11\",\n \"severity\": \"guidance\",\n \"summary\": \"Protocols describing what something *is*: noun (`Collection`, `Sequence`).\"\n },\n {\n \"id\": \"swift-rule-12\",\n \"severity\": \"guidance\",\n \"summary\": \"Protocols describing a *capability*: `-able`, `-ible`, `-ing` suffix (`Hashable`, `Codable`, `Equatable`).\"\n },\n {\n \"id\": \"swift-rule-13\",\n \"severity\": \"guidance\",\n \"summary\": \"**Avoid abbreviations:** Use full words. `destinationURL` not `destURL`, `error` not `err`, `index` not `idx`. Well-known abbreviations (`URL`, `ID`, `JSON`) are fine.\"\n },\n {\n \"id\": \"swift-rule-14\",\n \"severity\": \"guidance\",\n \"summary\": \"**First argument label:** Omit when it is obviously part of the function name: `x.addSubview(y)` not `x.addSubview(view: y)`. Include when it adds clarity: `a.move(from: b, to: c)`.\"\n },\n {\n \"id\": \"swift-rule-15\",\n \"severity\": \"guidance\",\n \"summary\": \"**`struct` by default:** Prefer value types (`struct`, `enum`) over reference types (`class`). Use `class` only when identity semantics, inheritance, or reference sharing is required.\"\n },\n {\n \"id\": \"swift-rule-16\",\n \"severity\": \"guidance\",\n \"summary\": \"**`final` by default:** Mark classes `final` unless designed for subclassing. Subclassable classes are a design decision, not a default.\"\n },\n {\n \"id\": \"swift-rule-17\",\n \"severity\": \"guidance\",\n \"summary\": \"**`enum` for closed sets:** Use `enum` for a fixed set of related values. Use `CaseIterable` when you need to enumerate cases.\"\n },\n {\n \"id\": \"swift-rule-18\",\n \"severity\": \"guidance\",\n \"summary\": \"**Associated values:** Use `enum` with associated values as discriminated unions: `enum Result<T> { case success(T); case failure(Error) }`.\"\n },\n {\n \"id\": \"swift-rule-19\",\n \"severity\": \"guidance\",\n \"summary\": \"**`typealias`:** Use to clarify the role of complex types: `typealias Completion = (Result<User, Error>) -> Void`.\"\n },\n {\n \"id\": \"swift-rule-20\",\n \"severity\": \"guidance\",\n \"summary\": \"**`extension` over subclass:** Prefer extending a type to add behavior over subclassing. Extensions cannot store state — use composition for that.\"\n },\n {\n \"id\": \"swift-rule-21\",\n \"severity\": \"guidance\",\n \"summary\": \"**Avoid `!` force-unwrap:** Force-unwrap is a crash waiting to happen. Use `guard let`, `if let`, or `??` instead.\"\n },\n {\n \"id\": \"swift-rule-22\",\n \"severity\": \"guidance\",\n \"summary\": \"**`guard let` for early exit:** Use `guard let` to unwrap optionals at the top of a function when `nil` means \\\"cannot proceed\\\". This reduces nesting.\"\n },\n {\n \"id\": \"swift-rule-23\",\n \"severity\": \"guidance\",\n \"summary\": \"**`if let` for optional use:** Use `if let` when the `nil` case is a legitimate alternate path.\"\n },\n {\n \"id\": \"swift-rule-24\",\n \"severity\": \"guidance\",\n \"summary\": \"**Optional chaining (`?.`):** Use for accessing properties/methods on optionals where `nil` propagation is correct.\"\n },\n {\n \"id\": \"swift-rule-25\",\n \"severity\": \"guidance\",\n \"summary\": \"**`??` for defaults:** Use the nil-coalescing operator for fallback values: `let name = user?.name ?? \\\"Unknown\\\"`.\"\n },\n {\n \"id\": \"swift-rule-26\",\n \"severity\": \"guidance\",\n \"summary\": \"**Implicit optionals (`!` type):** Use `@IBOutlet weak var button: UIButton!` and similarly initialized-before-use patterns — keep to `@IBOutlet` and injection patterns only. Never use `!` types for general logic.\"\n },\n {\n \"id\": \"swift-rule-27\",\n \"severity\": \"guidance\",\n \"summary\": \"**Single responsibility:** Each function does one thing. Break down large functions.\"\n },\n {\n \"id\": \"swift-rule-28\",\n \"severity\": \"guidance\",\n \"summary\": \"**`@discardableResult`:** Add only when ignoring the result is a common and correct pattern. Do not add it to silence warnings mechanically.\"\n },\n {\n \"id\": \"swift-rule-29\",\n \"severity\": \"guidance\",\n \"summary\": \"**Trailing closure syntax:** Use trailing closure syntax when the closure is the last parameter and its role is clear: `UIView.animate(withDuration: 0.3) { ... }`.\"\n },\n {\n \"id\": \"swift-rule-30\",\n \"severity\": \"guidance\",\n \"summary\": \"**`@escaping`:** Mark closures `@escaping` when they outlive the function call. Document the lifecycle implications.\"\n },\n {\n \"id\": \"swift-rule-31\",\n \"severity\": \"guidance\",\n \"summary\": \"**`inout`:** Use `inout` sparingly. Prefer returning a new value over mutating in place unless performance is critical.\"\n },\n {\n \"id\": \"swift-rule-32\",\n \"severity\": \"guidance\",\n \"summary\": \"**`throws` / `async throws`:** Use `throws` for functions that can fail with typed errors. Use `async` for asynchronous work. Combine as `async throws` for async-fallible functions.\"\n },\n {\n \"id\": \"swift-rule-33\",\n \"severity\": \"guidance\",\n \"summary\": \"**`throws` + `try`:** Use Swift's typed error handling for recoverable errors. Functions that can fail return via `throw`, not via optional or sentinel values.\"\n },\n {\n \"id\": \"swift-rule-34\",\n \"severity\": \"guidance\",\n \"summary\": \"**`do / catch`:** Handle errors at the appropriate layer. Do not `try!` unless a failure is genuinely impossible and you can prove it.\"\n },\n {\n \"id\": \"swift-rule-35\",\n \"severity\": \"guidance\",\n \"summary\": \"**`Result<T, Error>`:** Use `Result` for asynchronous completions that predate `async/await`, or when you need to store a result for later.\"\n },\n {\n \"id\": \"swift-rule-36\",\n \"severity\": \"guidance\",\n \"summary\": \"**Custom error types:** Define `enum MyError: Error, LocalizedError` with associated values for structured error information. Implement `errorDescription` for user-facing messages.\"\n },\n {\n \"id\": \"swift-rule-37\",\n \"severity\": \"guidance\",\n \"summary\": \"**`try?`:** Use when `nil` on failure is acceptable and the error is irrelevant to the caller.\"\n },\n {\n \"id\": \"swift-rule-38\",\n \"severity\": \"guidance\",\n \"summary\": \"**`async`/`await`:** Prefer Swift Concurrency over completion handlers, Combine, or DispatchQueue-based async code for new code.\"\n },\n {\n \"id\": \"swift-rule-39\",\n \"severity\": \"guidance\",\n \"summary\": \"**`Task { }`:** Use to bridge from synchronous to async context. Use `Task.detached` only when the task must not inherit actor context.\"\n },\n {\n \"id\": \"swift-rule-40\",\n \"severity\": \"guidance\",\n \"summary\": \"**`@MainActor`:** Annotate types or functions that must run on the main thread. Use `@MainActor` on ViewModels/Controllers rather than `DispatchQueue.main.async`.\"\n },\n {\n \"id\": \"swift-rule-41\",\n \"severity\": \"guidance\",\n \"summary\": \"**`actor`:** Use `actor` types for shared mutable state. Actors serialize access and eliminate data races.\"\n },\n {\n \"id\": \"swift-rule-42\",\n \"severity\": \"guidance\",\n \"summary\": \"**`Sendable`:** Mark types crossing actor boundaries as `Sendable`. Do not suppress `Sendable` warnings with `@unchecked Sendable` without justification.\"\n },\n {\n \"id\": \"swift-rule-43\",\n \"severity\": \"guidance\",\n \"summary\": \"**`async let`:** Use `async let` for independent concurrent work within a function: `async let user = fetchUser(); async let feed = fetchFeed(); let (u, f) = try await (user, feed)`.\"\n },\n {\n \"id\": \"swift-rule-44\",\n \"severity\": \"guidance\",\n \"summary\": \"**ARC is automatic:** Do not call `retain`/`release`. ARC handles memory.\"\n },\n {\n \"id\": \"swift-rule-45\",\n \"severity\": \"guidance\",\n \"summary\": \"**`weak` for delegates and callbacks:** Mark delegate properties `weak var` to avoid retain cycles. Capture `[weak self]` in closures that outlive the object.\"\n },\n {\n \"id\": \"swift-rule-46\",\n \"severity\": \"guidance\",\n \"summary\": \"**`unowned` only when guaranteed:** Use `unowned` instead of `weak` only when the referenced object is guaranteed to outlive the closure/property. Incorrect `unowned` crashes; incorrect `weak` just produces `nil`.\"\n },\n {\n \"id\": \"swift-rule-47\",\n \"severity\": \"guidance\",\n \"summary\": \"**`[weak self]` + guard:** Pattern: `{ [weak self] in guard let self = self else { return } ... }` (or `[weak self] in self?.doWork()`).\"\n },\n {\n \"id\": \"swift-rule-48\",\n \"severity\": \"guidance\",\n \"summary\": \"**`map`, `filter`, `compactMap`, `reduce`:** Use functional transforms over `for` loops for collection transformations.\"\n },\n {\n \"id\": \"swift-rule-49\",\n \"severity\": \"guidance\",\n \"summary\": \"**`compactMap`:** Use to filter `nil` from a sequence of optionals: `names.compactMap { user(id: $0)?.name }`.\"\n },\n {\n \"id\": \"swift-rule-50\",\n \"severity\": \"guidance\",\n \"summary\": \"**`flatMap` on sequences:** Use to flatten sequences: `[[1,2],[3,4]].flatMap { $0 }` → `[1,2,3,4]`.\"\n },\n {\n \"id\": \"swift-rule-51\",\n \"severity\": \"guidance\",\n \"summary\": \"**`lazy`:** Use `collection.lazy.filter { }.map { }` to avoid allocating intermediate arrays for long pipelines.\"\n },\n {\n \"id\": \"swift-rule-52\",\n \"severity\": \"guidance\",\n \"summary\": \"**`///` doc comments:** Use triple-slash comments for all public API. Xcode renders these in Quick Help.\"\n },\n {\n \"id\": \"swift-rule-53\",\n \"severity\": \"guidance\",\n \"summary\": \"**Summary + discussion:** First line is the summary. Add a blank line then the discussion for longer explanations.\"\n },\n {\n \"id\": \"swift-rule-54\",\n \"severity\": \"guidance\",\n \"summary\": \"**`- Parameter`, `- Returns`, `- Throws`:** Document parameters, return values, and thrown errors using these list items.\"\n },\n {\n \"id\": \"swift-rule-55\",\n \"severity\": \"guidance\",\n \"summary\": \"**`- Note:`, `- Important:`, `- Warning:`:** Use callout keywords for additional reader guidance.\"\n },\n {\n \"id\": \"swift-rule-56\",\n \"severity\": \"guidance\",\n \"summary\": \"**Code examples:** Include brief usage examples in doc comments for complex APIs using fenced code blocks.\"\n }\n ],\n \"source\": \"bundled_template\"\n}\n","styleguides/swiftui.json":"{\n \"version\": 1,\n \"schema\": \"cadre.styleguide.v1\",\n \"kind\": \"styleguide\",\n \"id\": \"swiftui\",\n \"title\": \"Effective SwiftUI Style Guide Summary\",\n \"summary\": \"This document summarizes key rules and best practices for writing idiomatic SwiftUI code, building on Swift API Design Guidelines with SwiftUI-specific view, state, and composition conventions.\",\n \"sections\": [\n {\n \"heading\": \"1. Formatting and Tooling\",\n \"body\": \"- **SwiftFormat:** Format all SwiftUI code with `swiftformat`. Add `.swiftformat` config to the repo.\\n- **SwiftLint:** Enforce with `.swiftlint.yml`. Treat all errors as CI failures.\\n- **Trailing closures and `ViewBuilder`:** Use trailing closure syntax for all `ViewBuilder` content parameters — this is the SwiftUI idiom.\\n- **`// MARK:` sections:** Organize view files with `// MARK: - Body`, `// MARK: - Subviews`, `// MARK: - View Model` sections for long files.\"\n },\n {\n \"heading\": \"2. View Design\",\n \"body\": \"- **Small, composable views:** Decompose complex `body` implementations into private child views or separate `View` structs. A `body` over ~30 lines should be split.\\n- **`some View` return type:** Always use `some View` as the return type of `body`. Do not erase to `AnyView` without a concrete reason.\\n- **`AnyView` avoidance:** `AnyView` disables SwiftUI's diff engine. Use conditional views, `Group`, or `@ViewBuilder` functions instead. If `AnyView` is unavoidable, contain it to a single call site.\\n- **`@ViewBuilder` functions:** Extract reusable sub-trees into `@ViewBuilder` private methods or standalone `View` structs. Prefer structs for views reused across files.\\n- **Previews:** Every view **must** have a `#Preview` (or `PreviewProvider`). Include multiple preview variants: light/dark, different data states (empty, loaded, error), and different device sizes.\"\n },\n {\n \"heading\": \"3. State Management\",\n \"body\": \"- **Choose the right property wrapper:**\\n - `@State`: Local, view-owned, value-type state. Keep it minimal and view-specific.\\n - `@Binding`: Pass mutable state down from a parent. Never derive a `@Binding` from a computed property.\\n - `@StateObject`: Own a reference-type observable object for the lifetime of this view subtree.\\n - `@ObservedObject`: Receive an observable object from a parent. The parent owns its lifetime.\\n - `@EnvironmentObject`: Inject a shared object through the view hierarchy. Use for app-wide state (user session, theme, router).\\n - `@Environment`: Read system values (`\\\\.colorScheme`, `\\\\.dismiss`, `\\\\.locale`) and custom environment keys.\\n- **Observation (`@Observable`):** In iOS 17+, prefer `@Observable` macro over `ObservableObject`/`@Published` — it is more efficient (only the accessed properties trigger redraws).\\n- **Minimize `@State`:** Lift state up to the smallest common ancestor that needs it. Do not put everything in the root view.\\n- **No logic in `body`:** Move business logic, data transformations, and side effects into the ViewModel or a computed property. `body` should be pure view construction.\"\n },\n {\n \"heading\": \"4. ViewModel Pattern\",\n \"body\": \"- **`@Observable` / `ObservableObject` ViewModel:** Each screen has a ViewModel that is `@Observable` (iOS 17+) or `ObservableObject`. The view is a thin rendering layer.\\n- **`@StateObject` for injection:** Create the ViewModel in the view that owns it with `@StateObject var vm = MyViewModel()`. Pass to children via `@ObservedObject` or `@EnvironmentObject`.\\n- **`@MainActor` on ViewModels:** Annotate the ViewModel class with `@MainActor` to ensure all published property updates occur on the main thread.\\n- **Async tasks via `Task`:** Trigger async operations from `.task { }` modifier (cancelled automatically on view disappearance) or `Task { }` in response to user actions.\\n- **`.onAppear` vs `.task`:** Prefer `.task { }` for async work (auto-cancels). Use `.onAppear` only for synchronous side effects.\"\n },\n {\n \"heading\": \"5. Layout and Composition\",\n \"body\": \"- **Use modifiers in the right order:** Modifier order matters in SwiftUI. Background and border go before padding; padding before frame.\\n ```swift\\n Text(\\\"Hello\\\")\\n .background(Color.blue) // applies to text bounds\\n .padding() // then pads\\n .border(Color.red) // border around padded area\\n ```\\n- **`Group` for applying modifiers to multiple views:** Use `Group { }` to apply the same modifier to several views without a container.\\n- **`ViewThatFits`:** Use for adaptive layouts that switch between compact and expanded presentations.\\n- **`LazyVStack` / `LazyHStack` / `LazyVGrid`:** Use lazy containers for long or dynamically-loaded lists. Use eager `VStack`/`HStack` only for short, fixed-count content.\\n- **`GeometryReader` sparingly:** `GeometryReader` takes all available space and can break layouts. Prefer `containerRelativeFrame` (iOS 17+), `frame(maxWidth: .infinity)`, or `Layout` protocol instead.\\n- **`Spacer()` vs fixed spacing:** Use `Spacer()` to push views apart in a stack. Use `.padding()` or `.frame(height: 8)` for fixed spacing.\"\n },\n {\n \"heading\": \"6. Navigation\",\n \"body\": \"- **`NavigationStack`:** Use `NavigationStack` (iOS 16+) over `NavigationView`. Use path-based navigation for programmatic control: `NavigationStack(path: $path)`.\\n- **`navigationDestination(for:)`:** Register destinations with `.navigationDestination(for: MyType.self)` and drive navigation by appending to the path.\\n- **`NavigationPath`:** Use for heterogeneous navigation stacks. Use typed `[MyRoute]` arrays when all destinations are the same type.\\n- **`.sheet`, `.fullScreenCover`, `.popover`:** Control presentation with `@State var isPresented = false` and `item:`-based variants for associated data.\\n- **Avoid `NavigationLink(isActive:)`:** Deprecated in iOS 16+. Use path-based navigation instead.\"\n },\n {\n \"heading\": \"7. Animation\",\n \"body\": \"- **`withAnimation { }`:** Wrap state changes that should animate in `withAnimation`. Prefer this over `.animation(_:value:)` on views.\\n- **`.animation(_:value:)`:** Use on a view when only that view should animate in response to a specific state value changing.\\n- **Explicit animations over implicit:** Prefer `withAnimation(.spring())` triggered by state changes over `.animation(.spring())` on views — explicit animations are more predictable.\\n- **`matchedGeometryEffect`:** Use for hero animations between views. Always pair with a shared `@Namespace`.\\n- **`Animatable` and `AnimatableModifier`:** Implement for custom animations on non-standard properties.\"\n },\n {\n \"heading\": \"8. Performance\",\n \"body\": \"- **`Equatable` views:** Make views `Equatable` and use `.equatable()` to skip redraws when input is unchanged.\\n- **Stable identities in `ForEach`:** Pass stable `Identifiable` models or explicit `id:` parameters. Avoid `ForEach(items, id: \\\\.self)` for complex objects — use a proper `id` property.\\n- **Avoid heavy computation in `body`:** Any expensive computation in `body` runs on every redraw. Move to a stored property or the ViewModel.\\n- **`@Observable` over `ObservableObject`:** `@Observable` tracks property access precisely — only views that read a changed property redraw. `@Published` triggers redraws for all observers of any property change.\\n- **`task(id:)`:** Use `task(id: someValue) { }` to restart async work when a value changes, instead of `onChange(of:) { Task { ... } }`.\"\n },\n {\n \"heading\": \"9. Accessibility\",\n \"body\": \"- **`.accessibilityLabel`:** Every interactive element and image must have an accessibility label.\\n- **`.accessibilityHint`:** Add hints for non-obvious actions: `.accessibilityHint(\\\"Double-tap to expand details\\\")`.\\n- **`.accessibilityElement(children: .combine)`:** Group visually related elements into a single accessible element.\\n- **Dynamic Type:** Use semantic text styles (`.font(.headline)`) not fixed sizes. Test with the largest and smallest Dynamic Type sizes.\\n- **Color contrast:** Do not convey information with color alone. Use labels, icons, or patterns as secondary indicators.\"\n },\n {\n \"heading\": \"10. File and Code Organization\",\n \"body\": \"- **One view per file:** Each top-level `View` struct lives in its own file.\\n- **File naming:** File name matches the type name: `UserProfileView.swift`.\\n- **Extension for subviews:** Place private subviews in an `extension` at the bottom of the same file:\\n ```swift\\n // MARK: - Subviews\\n private extension UserProfileView {\\n var headerSection: some View { ... }\\n }\\n ```\\n- **Feature folder structure:** `Features/Auth/`, `Features/Home/` — group screens, ViewModels, and models by feature.\\n- **Shared components:** Place reusable design-system components in `Components/` or a dedicated Swift package.\\n\\n*Sources: [SwiftUI Documentation](https://developer.apple.com/documentation/swiftui) · [Swift API Design Guidelines](https://swift.org/documentation/api-design-guidelines/) · [Observation framework](https://developer.apple.com/documentation/observation)*\"\n }\n ],\n \"languages\": [\n \"swiftui\"\n ],\n \"frameworks\": [],\n \"file_patterns\": [],\n \"applies_to\": [\n \"planning\",\n \"implementation\",\n \"review\",\n \"tests\"\n ],\n \"rules\": [\n {\n \"id\": \"swiftui-rule-1\",\n \"severity\": \"guidance\",\n \"summary\": \"**SwiftFormat:** Format all SwiftUI code with `swiftformat`. Add `.swiftformat` config to the repo.\"\n },\n {\n \"id\": \"swiftui-rule-2\",\n \"severity\": \"guidance\",\n \"summary\": \"**SwiftLint:** Enforce with `.swiftlint.yml`. Treat all errors as CI failures.\"\n },\n {\n \"id\": \"swiftui-rule-3\",\n \"severity\": \"guidance\",\n \"summary\": \"**Trailing closures and `ViewBuilder`:** Use trailing closure syntax for all `ViewBuilder` content parameters — this is the SwiftUI idiom.\"\n },\n {\n \"id\": \"swiftui-rule-4\",\n \"severity\": \"guidance\",\n \"summary\": \"**`// MARK:` sections:** Organize view files with `// MARK: - Body`, `// MARK: - Subviews`, `// MARK: - View Model` sections for long files.\"\n },\n {\n \"id\": \"swiftui-rule-5\",\n \"severity\": \"guidance\",\n \"summary\": \"**Small, composable views:** Decompose complex `body` implementations into private child views or separate `View` structs. A `body` over ~30 lines should be split.\"\n },\n {\n \"id\": \"swiftui-rule-6\",\n \"severity\": \"guidance\",\n \"summary\": \"**`some View` return type:** Always use `some View` as the return type of `body`. Do not erase to `AnyView` without a concrete reason.\"\n },\n {\n \"id\": \"swiftui-rule-7\",\n \"severity\": \"guidance\",\n \"summary\": \"**`AnyView` avoidance:** `AnyView` disables SwiftUI's diff engine. Use conditional views, `Group`, or `@ViewBuilder` functions instead. If `AnyView` is unavoidable, contain it to a single call site.\"\n },\n {\n \"id\": \"swiftui-rule-8\",\n \"severity\": \"guidance\",\n \"summary\": \"**`@ViewBuilder` functions:** Extract reusable sub-trees into `@ViewBuilder` private methods or standalone `View` structs. Prefer structs for views reused across files.\"\n },\n {\n \"id\": \"swiftui-rule-9\",\n \"severity\": \"guidance\",\n \"summary\": \"**Previews:** Every view **must** have a `#Preview` (or `PreviewProvider`). Include multiple preview variants: light/dark, different data states (empty, loaded, error), and different device sizes.\"\n },\n {\n \"id\": \"swiftui-rule-10\",\n \"severity\": \"guidance\",\n \"summary\": \"**Choose the right property wrapper:**\"\n },\n {\n \"id\": \"swiftui-rule-11\",\n \"severity\": \"guidance\",\n \"summary\": \"`@State`: Local, view-owned, value-type state. Keep it minimal and view-specific.\"\n },\n {\n \"id\": \"swiftui-rule-12\",\n \"severity\": \"guidance\",\n \"summary\": \"`@Binding`: Pass mutable state down from a parent. Never derive a `@Binding` from a computed property.\"\n },\n {\n \"id\": \"swiftui-rule-13\",\n \"severity\": \"guidance\",\n \"summary\": \"`@StateObject`: Own a reference-type observable object for the lifetime of this view subtree.\"\n },\n {\n \"id\": \"swiftui-rule-14\",\n \"severity\": \"guidance\",\n \"summary\": \"`@ObservedObject`: Receive an observable object from a parent. The parent owns its lifetime.\"\n },\n {\n \"id\": \"swiftui-rule-15\",\n \"severity\": \"guidance\",\n \"summary\": \"`@EnvironmentObject`: Inject a shared object through the view hierarchy. Use for app-wide state (user session, theme, router).\"\n },\n {\n \"id\": \"swiftui-rule-16\",\n \"severity\": \"guidance\",\n \"summary\": \"`@Environment`: Read system values (`\\\\.colorScheme`, `\\\\.dismiss`, `\\\\.locale`) and custom environment keys.\"\n },\n {\n \"id\": \"swiftui-rule-17\",\n \"severity\": \"guidance\",\n \"summary\": \"**Observation (`@Observable`):** In iOS 17+, prefer `@Observable` macro over `ObservableObject`/`@Published` — it is more efficient (only the accessed properties trigger redraws).\"\n },\n {\n \"id\": \"swiftui-rule-18\",\n \"severity\": \"guidance\",\n \"summary\": \"**Minimize `@State`:** Lift state up to the smallest common ancestor that needs it. Do not put everything in the root view.\"\n },\n {\n \"id\": \"swiftui-rule-19\",\n \"severity\": \"guidance\",\n \"summary\": \"**No logic in `body`:** Move business logic, data transformations, and side effects into the ViewModel or a computed property. `body` should be pure view construction.\"\n },\n {\n \"id\": \"swiftui-rule-20\",\n \"severity\": \"guidance\",\n \"summary\": \"**`@Observable` / `ObservableObject` ViewModel:** Each screen has a ViewModel that is `@Observable` (iOS 17+) or `ObservableObject`. The view is a thin rendering layer.\"\n },\n {\n \"id\": \"swiftui-rule-21\",\n \"severity\": \"guidance\",\n \"summary\": \"**`@StateObject` for injection:** Create the ViewModel in the view that owns it with `@StateObject var vm = MyViewModel()`. Pass to children via `@ObservedObject` or `@EnvironmentObject`.\"\n },\n {\n \"id\": \"swiftui-rule-22\",\n \"severity\": \"guidance\",\n \"summary\": \"**`@MainActor` on ViewModels:** Annotate the ViewModel class with `@MainActor` to ensure all published property updates occur on the main thread.\"\n },\n {\n \"id\": \"swiftui-rule-23\",\n \"severity\": \"guidance\",\n \"summary\": \"**Async tasks via `Task`:** Trigger async operations from `.task { }` modifier (cancelled automatically on view disappearance) or `Task { }` in response to user actions.\"\n },\n {\n \"id\": \"swiftui-rule-24\",\n \"severity\": \"guidance\",\n \"summary\": \"**`.onAppear` vs `.task`:** Prefer `.task { }` for async work (auto-cancels). Use `.onAppear` only for synchronous side effects.\"\n },\n {\n \"id\": \"swiftui-rule-25\",\n \"severity\": \"guidance\",\n \"summary\": \"**Use modifiers in the right order:** Modifier order matters in SwiftUI. Background and border go before padding; padding before frame.\"\n },\n {\n \"id\": \"swiftui-rule-26\",\n \"severity\": \"guidance\",\n \"summary\": \"**`Group` for applying modifiers to multiple views:** Use `Group { }` to apply the same modifier to several views without a container.\"\n },\n {\n \"id\": \"swiftui-rule-27\",\n \"severity\": \"guidance\",\n \"summary\": \"**`ViewThatFits`:** Use for adaptive layouts that switch between compact and expanded presentations.\"\n },\n {\n \"id\": \"swiftui-rule-28\",\n \"severity\": \"guidance\",\n \"summary\": \"**`LazyVStack` / `LazyHStack` / `LazyVGrid`:** Use lazy containers for long or dynamically-loaded lists. Use eager `VStack`/`HStack` only for short, fixed-count content.\"\n },\n {\n \"id\": \"swiftui-rule-29\",\n \"severity\": \"guidance\",\n \"summary\": \"**`GeometryReader` sparingly:** `GeometryReader` takes all available space and can break layouts. Prefer `containerRelativeFrame` (iOS 17+), `frame(maxWidth: .infinity)`, or `Layout` protocol instead.\"\n },\n {\n \"id\": \"swiftui-rule-30\",\n \"severity\": \"guidance\",\n \"summary\": \"**`Spacer()` vs fixed spacing:** Use `Spacer()` to push views apart in a stack. Use `.padding()` or `.frame(height: 8)` for fixed spacing.\"\n },\n {\n \"id\": \"swiftui-rule-31\",\n \"severity\": \"guidance\",\n \"summary\": \"**`NavigationStack`:** Use `NavigationStack` (iOS 16+) over `NavigationView`. Use path-based navigation for programmatic control: `NavigationStack(path: $path)`.\"\n },\n {\n \"id\": \"swiftui-rule-32\",\n \"severity\": \"guidance\",\n \"summary\": \"**`navigationDestination(for:)`:** Register destinations with `.navigationDestination(for: MyType.self)` and drive navigation by appending to the path.\"\n },\n {\n \"id\": \"swiftui-rule-33\",\n \"severity\": \"guidance\",\n \"summary\": \"**`NavigationPath`:** Use for heterogeneous navigation stacks. Use typed `[MyRoute]` arrays when all destinations are the same type.\"\n },\n {\n \"id\": \"swiftui-rule-34\",\n \"severity\": \"guidance\",\n \"summary\": \"**`.sheet`, `.fullScreenCover`, `.popover`:** Control presentation with `@State var isPresented = false` and `item:`-based variants for associated data.\"\n },\n {\n \"id\": \"swiftui-rule-35\",\n \"severity\": \"guidance\",\n \"summary\": \"**Avoid `NavigationLink(isActive:)`:** Deprecated in iOS 16+. Use path-based navigation instead.\"\n },\n {\n \"id\": \"swiftui-rule-36\",\n \"severity\": \"guidance\",\n \"summary\": \"**`withAnimation { }`:** Wrap state changes that should animate in `withAnimation`. Prefer this over `.animation(_:value:)` on views.\"\n },\n {\n \"id\": \"swiftui-rule-37\",\n \"severity\": \"guidance\",\n \"summary\": \"**`.animation(_:value:)`:** Use on a view when only that view should animate in response to a specific state value changing.\"\n },\n {\n \"id\": \"swiftui-rule-38\",\n \"severity\": \"guidance\",\n \"summary\": \"**Explicit animations over implicit:** Prefer `withAnimation(.spring())` triggered by state changes over `.animation(.spring())` on views — explicit animations are more predictable.\"\n },\n {\n \"id\": \"swiftui-rule-39\",\n \"severity\": \"guidance\",\n \"summary\": \"**`matchedGeometryEffect`:** Use for hero animations between views. Always pair with a shared `@Namespace`.\"\n },\n {\n \"id\": \"swiftui-rule-40\",\n \"severity\": \"guidance\",\n \"summary\": \"**`Animatable` and `AnimatableModifier`:** Implement for custom animations on non-standard properties.\"\n },\n {\n \"id\": \"swiftui-rule-41\",\n \"severity\": \"guidance\",\n \"summary\": \"**`Equatable` views:** Make views `Equatable` and use `.equatable()` to skip redraws when input is unchanged.\"\n },\n {\n \"id\": \"swiftui-rule-42\",\n \"severity\": \"guidance\",\n \"summary\": \"**Stable identities in `ForEach`:** Pass stable `Identifiable` models or explicit `id:` parameters. Avoid `ForEach(items, id: \\\\.self)` for complex objects — use a proper `id` property.\"\n },\n {\n \"id\": \"swiftui-rule-43\",\n \"severity\": \"guidance\",\n \"summary\": \"**Avoid heavy computation in `body`:** Any expensive computation in `body` runs on every redraw. Move to a stored property or the ViewModel.\"\n },\n {\n \"id\": \"swiftui-rule-44\",\n \"severity\": \"guidance\",\n \"summary\": \"**`@Observable` over `ObservableObject`:** `@Observable` tracks property access precisely — only views that read a changed property redraw. `@Published` triggers redraws for all observers of any property change.\"\n },\n {\n \"id\": \"swiftui-rule-45\",\n \"severity\": \"guidance\",\n \"summary\": \"**`task(id:)`:** Use `task(id: someValue) { }` to restart async work when a value changes, instead of `onChange(of:) { Task { ... } }`.\"\n },\n {\n \"id\": \"swiftui-rule-46\",\n \"severity\": \"guidance\",\n \"summary\": \"**`.accessibilityLabel`:** Every interactive element and image must have an accessibility label.\"\n },\n {\n \"id\": \"swiftui-rule-47\",\n \"severity\": \"guidance\",\n \"summary\": \"**`.accessibilityHint`:** Add hints for non-obvious actions: `.accessibilityHint(\\\"Double-tap to expand details\\\")`.\"\n },\n {\n \"id\": \"swiftui-rule-48\",\n \"severity\": \"guidance\",\n \"summary\": \"**`.accessibilityElement(children: .combine)`:** Group visually related elements into a single accessible element.\"\n },\n {\n \"id\": \"swiftui-rule-49\",\n \"severity\": \"guidance\",\n \"summary\": \"**Dynamic Type:** Use semantic text styles (`.font(.headline)`) not fixed sizes. Test with the largest and smallest Dynamic Type sizes.\"\n },\n {\n \"id\": \"swiftui-rule-50\",\n \"severity\": \"guidance\",\n \"summary\": \"**Color contrast:** Do not convey information with color alone. Use labels, icons, or patterns as secondary indicators.\"\n },\n {\n \"id\": \"swiftui-rule-51\",\n \"severity\": \"guidance\",\n \"summary\": \"**One view per file:** Each top-level `View` struct lives in its own file.\"\n },\n {\n \"id\": \"swiftui-rule-52\",\n \"severity\": \"guidance\",\n \"summary\": \"**File naming:** File name matches the type name: `UserProfileView.swift`.\"\n },\n {\n \"id\": \"swiftui-rule-53\",\n \"severity\": \"guidance\",\n \"summary\": \"**Extension for subviews:** Place private subviews in an `extension` at the bottom of the same file:\"\n },\n {\n \"id\": \"swiftui-rule-54\",\n \"severity\": \"guidance\",\n \"summary\": \"**Feature folder structure:** `Features/Auth/`, `Features/Home/` — group screens, ViewModels, and models by feature.\"\n },\n {\n \"id\": \"swiftui-rule-55\",\n \"severity\": \"guidance\",\n \"summary\": \"**Shared components:** Place reusable design-system components in `Components/` or a dedicated Swift package.\"\n }\n ],\n \"source\": \"bundled_template\"\n}\n","styleguides/typescript.json":"{\n \"version\": 1,\n \"schema\": \"cadre.styleguide.v1\",\n \"kind\": \"styleguide\",\n \"id\": \"typescript\",\n \"title\": \"Google TypeScript Style Guide Summary\",\n \"summary\": \"This document summarizes key rules and best practices from the Google TypeScript Style Guide, which is enforced by the `gts` tool.\",\n \"sections\": [\n {\n \"heading\": \"1. Language Features\",\n \"body\": \"- **Variable Declarations:** Always use `const` or `let`. **`var` is forbidden.** Use `const` by default.\\n- **Modules:** Use ES6 modules (`import`/`export`). **Do not use `namespace`.**\\n- **Exports:** Use named exports (`export {MyClass};`). **Do not use default exports.**\\n- **Classes:**\\n - **Do not use `#private` fields.** Use TypeScript's `private` visibility modifier.\\n - Mark properties never reassigned outside the constructor with `readonly`.\\n - **Never use the `public` modifier** (it's the default). Restrict visibility with `private` or `protected` where possible.\\n- **Functions:** Prefer function declarations for named functions. Use arrow functions for anonymous functions/callbacks.\\n- **String Literals:** Use single quotes (`'`). Use template literals (`` ` ``) for interpolation and multi-line strings.\\n- **Equality Checks:** Always use triple equals (`===`) and not equals (`!==`).\\n- **Type Assertions:** **Avoid type assertions (`x as SomeType`) and non-nullability assertions (`y!`)**. If you must use them, provide a clear justification.\"\n },\n {\n \"heading\": \"2. Disallowed Features\",\n \"body\": \"- **`any` Type:** **Avoid `any`**. Prefer `unknown` or a more specific type.\\n- **Wrapper Objects:** Do not instantiate `String`, `Boolean`, or `Number` wrapper classes.\\n- **Automatic Semicolon Insertion (ASI):** Do not rely on it. **Explicitly end all statements with a semicolon.**\\n- **`const enum`:** Do not use `const enum`. Use plain `enum` instead.\\n- **`eval()` and `Function(...string)`:** Forbidden.\"\n },\n {\n \"heading\": \"3. Naming\",\n \"body\": \"- **`UpperCamelCase`:** For classes, interfaces, types, enums, and decorators.\\n- **`lowerCamelCase`:** For variables, parameters, functions, methods, and properties.\\n- **`CONSTANT_CASE`:** For global constant values, including enum values.\\n- **`_` Prefix/Suffix:** **Do not use `_` as a prefix or suffix** for identifiers, including for private properties.\"\n },\n {\n \"heading\": \"4. Type System\",\n \"body\": \"- **Type Inference:** Rely on type inference for simple, obvious types. Be explicit for complex types.\\n- **`undefined` and `null`:** Both are supported. Be consistent within your project.\\n- **Optional vs. `|undefined`:** Prefer optional parameters and fields (`?`) over adding `|undefined` to the type.\\n- **`Array<T>` Type:** Use `T[]` for simple types. Use `Array<T>` for more complex union types (e.g., `Array<string | number>`).\\n- **`{}` Type:** **Do not use `{}`**. Prefer `unknown`, `Record<string, unknown>`, or `object`.\"\n },\n {\n \"heading\": \"5. Comments and Documentation\",\n \"body\": \"- **JSDoc:** Use `/** JSDoc */` for documentation, `//` for implementation comments.\\n- **Redundancy:** **Do not declare types in `@param` or `@return` blocks** (e.g., `/** @param {string} user */`). This is redundant in TypeScript.\\n- **Add Information:** Comments must add information, not just restate the code.\\n\\n*Source: [Google TypeScript Style Guide](https://google.github.io/styleguide/tsguide.html)*\"\n }\n ],\n \"languages\": [\n \"typescript\"\n ],\n \"frameworks\": [],\n \"file_patterns\": [],\n \"applies_to\": [\n \"planning\",\n \"implementation\",\n \"review\",\n \"tests\"\n ],\n \"rules\": [\n {\n \"id\": \"typescript-rule-1\",\n \"severity\": \"guidance\",\n \"summary\": \"**Variable Declarations:** Always use `const` or `let`. **`var` is forbidden.** Use `const` by default.\"\n },\n {\n \"id\": \"typescript-rule-2\",\n \"severity\": \"guidance\",\n \"summary\": \"**Modules:** Use ES6 modules (`import`/`export`). **Do not use `namespace`.**\"\n },\n {\n \"id\": \"typescript-rule-3\",\n \"severity\": \"guidance\",\n \"summary\": \"**Exports:** Use named exports (`export {MyClass};`). **Do not use default exports.**\"\n },\n {\n \"id\": \"typescript-rule-4\",\n \"severity\": \"guidance\",\n \"summary\": \"**Classes:**\"\n },\n {\n \"id\": \"typescript-rule-5\",\n \"severity\": \"guidance\",\n \"summary\": \"**Do not use `#private` fields.** Use TypeScript's `private` visibility modifier.\"\n },\n {\n \"id\": \"typescript-rule-6\",\n \"severity\": \"guidance\",\n \"summary\": \"Mark properties never reassigned outside the constructor with `readonly`.\"\n },\n {\n \"id\": \"typescript-rule-7\",\n \"severity\": \"guidance\",\n \"summary\": \"**Never use the `public` modifier** (it's the default). Restrict visibility with `private` or `protected` where possible.\"\n },\n {\n \"id\": \"typescript-rule-8\",\n \"severity\": \"guidance\",\n \"summary\": \"**Functions:** Prefer function declarations for named functions. Use arrow functions for anonymous functions/callbacks.\"\n },\n {\n \"id\": \"typescript-rule-9\",\n \"severity\": \"guidance\",\n \"summary\": \"**String Literals:** Use single quotes (`'`). Use template literals (`` ` ``) for interpolation and multi-line strings.\"\n },\n {\n \"id\": \"typescript-rule-10\",\n \"severity\": \"guidance\",\n \"summary\": \"**Equality Checks:** Always use triple equals (`===`) and not equals (`!==`).\"\n },\n {\n \"id\": \"typescript-rule-11\",\n \"severity\": \"guidance\",\n \"summary\": \"**Type Assertions:** **Avoid type assertions (`x as SomeType`) and non-nullability assertions (`y!`)**. If you must use them, provide a clear justification.\"\n },\n {\n \"id\": \"typescript-rule-12\",\n \"severity\": \"guidance\",\n \"summary\": \"**`any` Type:** **Avoid `any`**. Prefer `unknown` or a more specific type.\"\n },\n {\n \"id\": \"typescript-rule-13\",\n \"severity\": \"guidance\",\n \"summary\": \"**Wrapper Objects:** Do not instantiate `String`, `Boolean`, or `Number` wrapper classes.\"\n },\n {\n \"id\": \"typescript-rule-14\",\n \"severity\": \"guidance\",\n \"summary\": \"**Automatic Semicolon Insertion (ASI):** Do not rely on it. **Explicitly end all statements with a semicolon.**\"\n },\n {\n \"id\": \"typescript-rule-15\",\n \"severity\": \"guidance\",\n \"summary\": \"**`const enum`:** Do not use `const enum`. Use plain `enum` instead.\"\n },\n {\n \"id\": \"typescript-rule-16\",\n \"severity\": \"guidance\",\n \"summary\": \"**`eval()` and `Function(...string)`:** Forbidden.\"\n },\n {\n \"id\": \"typescript-rule-17\",\n \"severity\": \"guidance\",\n \"summary\": \"**`UpperCamelCase`:** For classes, interfaces, types, enums, and decorators.\"\n },\n {\n \"id\": \"typescript-rule-18\",\n \"severity\": \"guidance\",\n \"summary\": \"**`lowerCamelCase`:** For variables, parameters, functions, methods, and properties.\"\n },\n {\n \"id\": \"typescript-rule-19\",\n \"severity\": \"guidance\",\n \"summary\": \"**`CONSTANT_CASE`:** For global constant values, including enum values.\"\n },\n {\n \"id\": \"typescript-rule-20\",\n \"severity\": \"guidance\",\n \"summary\": \"**`_` Prefix/Suffix:** **Do not use `_` as a prefix or suffix** for identifiers, including for private properties.\"\n },\n {\n \"id\": \"typescript-rule-21\",\n \"severity\": \"guidance\",\n \"summary\": \"**Type Inference:** Rely on type inference for simple, obvious types. Be explicit for complex types.\"\n },\n {\n \"id\": \"typescript-rule-22\",\n \"severity\": \"guidance\",\n \"summary\": \"**`undefined` and `null`:** Both are supported. Be consistent within your project.\"\n },\n {\n \"id\": \"typescript-rule-23\",\n \"severity\": \"guidance\",\n \"summary\": \"**Optional vs. `|undefined`:** Prefer optional parameters and fields (`?`) over adding `|undefined` to the type.\"\n },\n {\n \"id\": \"typescript-rule-24\",\n \"severity\": \"guidance\",\n \"summary\": \"**`Array<T>` Type:** Use `T[]` for simple types. Use `Array<T>` for more complex union types (e.g., `Array<string | number>`).\"\n },\n {\n \"id\": \"typescript-rule-25\",\n \"severity\": \"guidance\",\n \"summary\": \"**`{}` Type:** **Do not use `{}`**. Prefer `unknown`, `Record<string, unknown>`, or `object`.\"\n },\n {\n \"id\": \"typescript-rule-26\",\n \"severity\": \"guidance\",\n \"summary\": \"**JSDoc:** Use `/** JSDoc */` for documentation, `//` for implementation comments.\"\n },\n {\n \"id\": \"typescript-rule-27\",\n \"severity\": \"guidance\",\n \"summary\": \"**Redundancy:** **Do not declare types in `@param` or `@return` blocks** (e.g., `/** @param {string} user */`). This is redundant in TypeScript.\"\n },\n {\n \"id\": \"typescript-rule-28\",\n \"severity\": \"guidance\",\n \"summary\": \"**Add Information:** Comments must add information, not just restate the code.\"\n }\n ],\n \"source\": \"bundled_template\"\n}\n","workflow.json":"{\n \"version\": 1,\n \"schema\": \"cadre.workflow.v1\",\n \"kind\": \"workflow\",\n \"title\": \"Project Workflow\",\n \"summary\": \"\",\n \"sections\": [\n {\n \"heading\": \"Guiding Principles\",\n \"body\": \"1. **Cadre State Is Packet-Owned:** Cadre records progress through MCP\\n task-completion, mutation, workflow, review, native event/message, and validation packets.\\n2. **The JSON Plan Is Authoritative:** `plan.json` describes the work. `plan.md`\\n is generated for human review only and must not drive runtime behavior.\\n3. **The Tech Stack Is Deliberate:** Changes to the tech stack must be reflected\\n in Cadre context through the appropriate packet before implementation relies on\\n them.\\n4. **Test-Driven Development:** Write tests before implementing behavior whenever\\n the task is testable.\\n5. **High Code Coverage:** Aim for more than 80 percent coverage for new or\\n changed modules unless the packet records an approved exception.\\n6. **User Experience First:** Product decisions should prioritize the user's\\n workflow, clarity, and failure recovery.\\n7. **Non-Interactive and CI-Aware:** Prefer one-shot project commands for tests,\\n builds, linters, and formatters.\"\n },\n {\n \"heading\": \"Task Lifecycle\",\n \"body\": \"All Cadre orchestration uses MCP packets. If a required packet returns `ok:false`,\\nhalt and report the packet error instead of recreating Cadre state logic outside\\nMCP.\\n\\n1. **Select Work:** Use Cadre status or implementation-prep packets to select the\\n next available track, phase, or task.\\n2. **Claim Work:** Use the implementation workflow packet or mutation packet to\\n claim ownership before product edits begin.\\n3. **Red Phase:** Add or update product tests that express the expected behavior.\\n Run the relevant project test command and confirm the new test fails for the\\n intended reason when practical.\\n4. **Green Phase:** Implement the smallest product change that satisfies the test\\n and acceptance criteria.\\n5. **Refactor:** Improve clarity, duplication, performance, and accessibility\\n while preserving behavior.\\n6. **Verify:** Run targeted tests first, then broader project checks according to\\n risk. Include coverage when the project has coverage tooling.\\n7. **Commit Product Work:** Make clear product commits for the completed unit of\\n work according to the team's normal commit policy.\\n8. **Record Completion:** Call the Cadre task-completion packet with test,\\n coverage, commit, and summary evidence. The packet updates plan state, metadata,\\n journals, events, and indexes.\"\n },\n {\n \"heading\": \"Commit Discipline\",\n \"body\": \"- Cadre uses Conventional Commit subjects for traceable work: product commits\\n use `feat(scope): subject`, control-plane commits use `cadre(workflow):\\n subject`, and automation commits use `cadre(train): subject`.\\n- Prefer one product commit per completed task or coherent implementation\\n checkpoint. When `cadre_complete_task` is called without a commit SHA, Cadre\\n stages the task-owned product files and creates the task commit automatically.\\n- Durable Cadre state changes are committed by the packet that writes them. Setup,\\n track creation, revision, refresh, completion records, review evidence,\\n publication ledgers, archive, release, handoff, artifact sync, status flags,\\n and squashed wisps all receive control-plane commits.\\n- Cadre writes structured commit trace notes to `refs/notes/cadre` using the\\n `cadre.commit_trace.v1` schema. Notes link commits back to track, task, repo,\\n workflow, tests, coverage, provider evidence, and event ids.\\n- Do not mark a task complete until its product commit, verification summary,\\n Cadre control-plane commit, and trace note have been recorded or the packet\\n explicitly reports a local/transient classification.\"\n },\n {\n \"heading\": \"Polyrepo Notes\",\n \"body\": \"In polyrepo mode, Cadre packets identify the repo, branch, worktree, task, and\\ncommit evidence for each product repository. Product commands run in the\\nappropriate repo worktree. Cadre control-plane synchronization, cross-repo review\\nlinks, fleet status, and merge-train metadata are packet-owned.\\n\\nIn monorepo mode, the same packet lifecycle applies with a single product repo.\"\n },\n {\n \"heading\": \"Quality Gates\",\n \"body\": \"Before marking any task complete through Cadre packets, verify:\\n\\n- Tests for the changed behavior pass.\\n- Coverage meets the project's threshold or the packet records an approved reason.\\n- Code follows the relevant style guide in `styleguides/*.json`; Markdown under\\n `code_styleguides/` is generated for human readability only.\\n- Public APIs are documented when the project convention requires it.\\n- Type checks, lint checks, and static analysis pass when configured.\\n- User-facing changes have appropriate accessibility and responsive checks.\\n- Documentation is updated when behavior, setup, or operations changed.\\n- Security-sensitive changes receive explicit review evidence.\"\n },\n {\n \"heading\": \"Phase Completion\",\n \"body\": \"When a task completes a phase, use Cadre workflow and completion packets to gather\\nphase evidence, validate coverage, record the checkpoint, and refresh indexes.\\nManual verification plans may be summarized for the user, but Cadre checkpoint\\nstate is recorded only through packets.\"\n },\n {\n \"heading\": \"Development Commands\",\n \"body\": \"Project setup, tests, builds, linters, formatters, local servers, and product\\ncommits remain normal product work. Use the commands configured by the project and\\nkeep them non-interactive. These commands must not mutate Cadre control-plane,\\nprovider, index, review, archive, handoff, event, message, or validation state directly.\"\n }\n ]\n}\n"}};
|
|
5
5
|
"use strict";
|
|
6
6
|
var __create = Object.create;
|
|
7
7
|
var __defProp = Object.defineProperty;
|