azcodr 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (89) hide show
  1. package/.agents/skills/agentic-architect/SKILL.md +118 -0
  2. package/.agents/skills/agentic-architect/references/agents_md_template.md +59 -0
  3. package/.agents/skills/agentic-architect/references/refinement_workflow.md +32 -0
  4. package/.agents/skills/agentic-architect/references/skill_architecture_inquiry.md +63 -0
  5. package/.agents/skills/agentic-architect/references/skill_template.md +55 -0
  6. package/.agents/skills/agentic-architect/scripts/validate_agentic_configs.sh +163 -0
  7. package/.agents/skills/clean-code-refactor/SKILL.md +91 -0
  8. package/.agents/skills/clean-code-refactor/references/clean_code_smells.md +27 -0
  9. package/.agents/skills/clean-code-refactor/references/design_patterns_ts.md +65 -0
  10. package/.agents/skills/compliance-audit/SKILL.md +120 -0
  11. package/.agents/skills/compliance-audit/references/owasp_top10_controls.md +16 -0
  12. package/.agents/skills/compliance-audit/references/soc2_iso_controls.md +28 -0
  13. package/.agents/skills/lets-build/SKILL.md +164 -0
  14. package/.agents/skills/lets-build/references/architecture_interview_matrix.md +188 -0
  15. package/.agents/skills/lets-build/references/hexagonal_bootstrap_scaffolds.md +113 -0
  16. package/.agents/skills/lets-build/references/project_readme_template.md +79 -0
  17. package/.agents/skills/lets-build/scripts/bootstrap_workspace.sh +68 -0
  18. package/.agents/skills/merge-ai/SKILL.md +90 -0
  19. package/.agents/skills/merge-ai/scripts/audit_divergence.sh +108 -0
  20. package/.agents/skills/merge-ai/scripts/resolve_repo.sh +177 -0
  21. package/.agents/skills/product-analyst/SKILL.md +143 -0
  22. package/.agents/skills/product-analyst/references/backlog_ordering_techniques.md +107 -0
  23. package/.agents/skills/product-analyst/references/gherkin_patterns.md +46 -0
  24. package/.agents/skills/product-analyst/references/invest_checklist.md +38 -0
  25. package/.agents/skills/product-analyst/references/okr_alignment_guide.md +76 -0
  26. package/.agents/skills/product-analyst/references/smart_tasks.md +59 -0
  27. package/.agents/skills/relentless-questioner/SKILL.md +120 -0
  28. package/.agents/skills/relentless-questioner/references/adaptive_question_trees.md +84 -0
  29. package/.gitignore +20 -0
  30. package/AGENTS.md +119 -0
  31. package/LICENSE +21 -0
  32. package/README.md +184 -0
  33. package/bin/azcodr.js +151 -0
  34. package/docs/knowledge/dos_and_donts.md +540 -0
  35. package/docs/knowledge/issue_log.md +25 -0
  36. package/docs/knowledge/knowledge_graph.md +188 -0
  37. package/docs/knowledge/lessons_learned.md +107 -0
  38. package/docs/knowledge/ubiquitous_language.md +23 -0
  39. package/docs/rules/accessibility.md +31 -0
  40. package/docs/rules/advanced_api_patterns.md +104 -0
  41. package/docs/rules/agentic_configuration.md +168 -0
  42. package/docs/rules/api_versioning.md +128 -0
  43. package/docs/rules/application_security.md +23 -0
  44. package/docs/rules/architecture_decision_records.md +42 -0
  45. package/docs/rules/authentication.md +76 -0
  46. package/docs/rules/authorization.md +75 -0
  47. package/docs/rules/caching.md +52 -0
  48. package/docs/rules/clean_code.md +25 -0
  49. package/docs/rules/cloud_native.md +43 -0
  50. package/docs/rules/compliance.md +25 -0
  51. package/docs/rules/container_infrastructure.md +32 -0
  52. package/docs/rules/continuous_deployment.md +24 -0
  53. package/docs/rules/continuous_integration.md +20 -0
  54. package/docs/rules/continuous_learning.md +29 -0
  55. package/docs/rules/database_integrity.md +88 -0
  56. package/docs/rules/database_migrations.md +41 -0
  57. package/docs/rules/database_operations.md +27 -0
  58. package/docs/rules/database_performance.md +44 -0
  59. package/docs/rules/database_transactions.md +81 -0
  60. package/docs/rules/design_patterns.md +40 -0
  61. package/docs/rules/devsecops.md +33 -0
  62. package/docs/rules/domain_driven_design.md +84 -0
  63. package/docs/rules/domain_expertise.md +42 -0
  64. package/docs/rules/error_handling.md +39 -0
  65. package/docs/rules/feature_flags.md +42 -0
  66. package/docs/rules/gof_design_patterns_reference.md +70 -0
  67. package/docs/rules/multitenancy_isolation.md +86 -0
  68. package/docs/rules/product_ownership.md +150 -0
  69. package/docs/rules/project_management.md +66 -0
  70. package/docs/rules/react.md +88 -0
  71. package/docs/rules/relentless_questioning.md +48 -0
  72. package/docs/rules/requirements_engineering.md +113 -0
  73. package/docs/rules/rest_api_conventions.md +62 -0
  74. package/docs/rules/server_driven_ui.md +71 -0
  75. package/docs/rules/tenant_dynamic_schemas.md +88 -0
  76. package/docs/rules/tenant_pluggable_logic.md +59 -0
  77. package/docs/rules/test_driven_development.md +106 -0
  78. package/docs/rules/test_isolation.md +26 -0
  79. package/docs/rules/transactional_email.md +20 -0
  80. package/docs/rules/typescript.md +55 -0
  81. package/docs/rules/ui_navigation.md +20 -0
  82. package/docs/rules/ui_ux_architecture.md +168 -0
  83. package/docs/rules/upstream_synchronization.md +66 -0
  84. package/docs/rules/workflow_state_machines.md +118 -0
  85. package/docs/rules/workspace_isolation.md +25 -0
  86. package/lib/index.js +5 -0
  87. package/lib/scaffold.js +177 -0
  88. package/memory.md +262 -0
  89. package/package.json +49 -0
@@ -0,0 +1,188 @@
1
+ # System Knowledge Graph & Architectural Topology
2
+
3
+ > **Core Purpose:** High-density, token-efficient knowledge representation of the workspace architecture, data topologies, and subsystem boundaries, eliminating repetitive discovery prompts.
4
+
5
+ ---
6
+
7
+ ## 1. Universal Hexagonal Architectural Subsystems
8
+
9
+ ```mermaid
10
+ flowchart TD
11
+ subgraph Ingress["Client & Primary Ingress Adapters"]
12
+ UI["Multi-Platform Client (Web / Mobile / Desktop SDUI)"]
13
+ Gateway["Ingress Gateway / Envoy (REST / gRPC / SSE)"]
14
+ BrokerIn["Message Consumer (Kafka / NATS / RabbitMQ)"]
15
+ end
16
+
17
+ subgraph Core["Pure Invariant Domain Core (Hexagonal Ports)"]
18
+ direction TB
19
+ TenantContext["Multi-Tenant Context Resolver Port"]
20
+ AuthPort["Authentication & Identity Port"]
21
+ AuthzPort["Authorization & Policy Port"]
22
+ DomainServices["Domain Services & Aggregate Roots"]
23
+ RulePort["Dynamic Rule Engine Port (CEL / Wasm)"]
24
+ WorkflowPort["Workflow Orchestration Port (Temporal / BPMN)"]
25
+ OutboxPort["Transactional Outbox Port"]
26
+ CachePort["Cache & Distributed Lock Port"]
27
+ RepoPort["Universal Repository Port"]
28
+ end
29
+
30
+ subgraph Egress["Secondary / Egress Polyglot Adapters"]
31
+ Storage["Relational & NoSQL Storage (Postgres / MySQL / Cockroach / Mongo)"]
32
+ CacheStore["In-Memory Store (Redis / Valkey / Dragonfly / Memcached)"]
33
+ BrokerOut["Event Streaming (Kafka / NATS / RabbitMQ / CloudEvents)"]
34
+ AuthEngines["Policy-as-Code (OPA Rego / OpenFGA ReBAC / Cerbos)"]
35
+ SMTP["Transactional Email Gateway (SMTP / Providers)"]
36
+ end
37
+
38
+ UI --> Gateway
39
+ Gateway --> TenantContext
40
+ BrokerIn --> DomainServices
41
+ TenantContext --> AuthPort
42
+ AuthPort --> AuthzPort
43
+ AuthzPort --> DomainServices
44
+ DomainServices --> RulePort
45
+ DomainServices --> WorkflowPort
46
+ DomainServices --> OutboxPort
47
+ DomainServices --> CachePort
48
+ DomainServices --> RepoPort
49
+
50
+ RepoPort --> Storage
51
+ OutboxPort --> Storage
52
+ OutboxPort --> BrokerOut
53
+ CachePort --> CacheStore
54
+ AuthzPort --> AuthEngines
55
+ DomainServices --> SMTP
56
+ ```
57
+
58
+ ---
59
+
60
+ ## 2. Multi-Tenant Data Isolation & Schema Graph
61
+
62
+ ```mermaid
63
+ erDiagram
64
+ TENANT ||--o{ USER : "owns"
65
+ TENANT ||--o{ ROLE : "defines"
66
+ TENANT ||--o{ TENANT_SCHEMA : "configures"
67
+ TENANT ||--o{ TENANT_ENTITY : "defines"
68
+ TENANT_ENTITY ||--o{ TENANT_RECORD : "stores"
69
+ TENANT ||--o{ OUTBOX_EVENT : "emits"
70
+ TENANT ||--o{ AUDIT_LOG : "records"
71
+
72
+ TENANT {
73
+ uuid id PK
74
+ string slug UK
75
+ string name
76
+ string subscription_tier
77
+ string status
78
+ json theme_tokens
79
+ timestamptz created_at
80
+ }
81
+
82
+ USER {
83
+ uuid id PK
84
+ uuid tenant_id FK
85
+ string email UK
86
+ string password_hash
87
+ boolean mfa_enabled
88
+ timestamptz created_at
89
+ }
90
+
91
+ TENANT_SCHEMA {
92
+ uuid id PK
93
+ uuid tenant_id FK
94
+ string entity_name
95
+ json json_schema
96
+ int version
97
+ }
98
+
99
+ OUTBOX_EVENT {
100
+ uuid id PK
101
+ uuid tenant_id FK
102
+ string aggregate_type
103
+ string aggregate_id
104
+ string event_type
105
+ json payload
106
+ string status
107
+ timestamptz created_at
108
+ }
109
+ ```
110
+
111
+ ---
112
+
113
+ ## 3. Subsystem Fast Lookup Index
114
+
115
+ | Capability | Invariant Contract / Open Standard | Swappable Polyglot Adapters | Governing Rule |
116
+ |---|---|---|---|
117
+ | **Runtime & Language** | Hexagonal Core (Zero Deps) | Polyglot (Go, Rust, Python, Java, TypeScript) | [`clean_code.md`](../rules/clean_code.md) |
118
+ | **Type Safety** | Sound static types & branded primitives | Rust, TypeScript, Go, Python (type hints) | [`typescript.md`](../rules/typescript.md) |
119
+ | **Persistence / DAL** | Abstract Repository & Unit of Work | Atlas / Flyway migrations; SQL & NoSQL drivers | [`database_transactions.md`](../rules/database_transactions.md) |
120
+ | **Tenant Isolation** | 4 Models (AST Interceptor, Schema, DB, Proxy) | SQL AST parser, RLS, multi-pool router, Envoy | [`multitenancy_isolation.md`](../rules/multitenancy_isolation.md) |
121
+ | **Dynamic Schemas** | JSON Schema Draft 2020-12 | Polyglot validators (`valico`, `gojsonschema`, `ajv`) | [`tenant_dynamic_schemas.md`](../rules/tenant_dynamic_schemas.md) |
122
+ | **Authentication** | OIDC, OAuth 2.1, Passkeys (WebAuthn) | PASETO, JWT with JWKS, SPIFFE/SPIRE mTLS | [`authentication.md`](../rules/authentication.md) |
123
+ | **Authorization** | Policy-as-Code & ReBAC | OPA (Rego/Wasm), OpenFGA (Zanzibar), Cerbos | [`authorization.md`](../rules/authorization.md) |
124
+ | **Pluggable Logic** | Common Expression Language (CEL) / Wasm | `cel-go`, `cel-rust`, Extism (Wasm plugins) | [`tenant_pluggable_logic.md`](../rules/tenant_pluggable_logic.md) |
125
+ | **Workflows** | Durable Orchestration & Statecharts | Temporal.io SDKs, Camunda/Zeebe (BPMN 2.0) | [`tenant_pluggable_logic.md`](../rules/tenant_pluggable_logic.md) |
126
+ | **Caching** | Abstract Cache Port with XFetch | Redis, Valkey, Dragonfly, Memcached, Local LRU | [`caching.md`](../rules/caching.md) |
127
+ | **Feature Flags** | OpenFeature Standard | Flipt, Unleash, LaunchDarkly, GoFeatureFlag | [`feature_flags.md`](../rules/feature_flags.md) |
128
+ | **Testing** | Outside-In TDD, BDD & Consumer Contracts | Cucumber/Gherkin, Pact, Schemathesis | [`test_driven_development.md`](../rules/test_driven_development.md) |
129
+ | **Presentation / SDUI** | Declarative JSON SDUI + DTCG Tokens | Web (React/Vue/Svelte), Mobile (Flutter/Native) | [`server_driven_ui.md`](../rules/server_driven_ui.md) |
130
+ | **Transactional Email** | Declarative Email Specs / MJML | SMTP Gateway, Mailpit (Local), SES/Sendgrid | [`transactional_email.md`](../rules/transactional_email.md) |
131
+ | **Event Streaming** | CNCF CloudEvents v1.0.2 | Kafka, NATS JetStream, RabbitMQ, SQS | [`database_transactions.md`](../rules/database_transactions.md) |
132
+ | **Observability** | OpenTelemetry OTLP standard | OTel Collector, Jaeger, Prometheus, OpenSearch | [`cloud_native.md`](../rules/cloud_native.md) |
133
+
134
+ ---
135
+
136
+ ## 4. Agentic Skill Topology & Composability Matrix
137
+
138
+ ```mermaid
139
+ flowchart TD
140
+ subgraph Inputs["Inception & Intent"]
141
+ Req["Stakeholder Feature Request / Mutation"]
142
+ end
143
+
144
+ subgraph Pattern1["Pattern 1: Sequential Pipeline Chaining (Workflows)"]
145
+ direction TB
146
+ SkillRQ["relentless-questioner"]
147
+ SkillPA["product-analyst"]
148
+ SkillTDD["test_driven_development"]
149
+ SkillRefactor["clean-code-refactor"]
150
+
151
+ SkillRQ -->|"Feature Alignment Spec (FAS)"| SkillPA
152
+ SkillPA -->|"INVEST Stories & Gherkin AC"| SkillTDD
153
+ SkillTDD -->|"Working Green Code"| SkillRefactor
154
+ end
155
+
156
+ subgraph Pattern2["Pattern 2: Dynamic Skill Stacking (Contextual Composition)"]
157
+ AgentCore["Primary Agent Session"]
158
+ SkillSec["compliance-audit"]
159
+ SkillArch["agentic-architect"]
160
+
161
+ AgentCore -.->|"Dynamic Load"| SkillSec
162
+ AgentCore -.->|"Dynamic Load"| SkillArch
163
+ end
164
+
165
+ subgraph Pattern3["Pattern 3: Multi-Agent Subagent Delegation (Division of Labor)"]
166
+ Coord["Coordinator Agent"]
167
+ SubA["Subagent A: Compliance Auditor"]
168
+ SubB["Subagent B: Code Refactorer"]
169
+
170
+ Coord -->|"Invoke Task"| SubA
171
+ Coord -->|"Invoke Task"| SubB
172
+ SubA -->|"Audit Findings"| Coord
173
+ SubB -->|"Refactored Units"| Coord
174
+ end
175
+
176
+ Req --> SkillRQ
177
+ ```
178
+
179
+ ### Many-to-Many Skill Cross-Matrix
180
+
181
+ | Skill Name | Functional Specialty | Applicable Lifecycle Stages | Target Artifacts Produced |
182
+ |---|---|---|---|
183
+ | `relentless-questioner` | Context-aware ambiguity interrogation | Pre-Discovery, Pre-Planning | Feature Alignment Spec (FAS), Invariant List |
184
+ | `product-analyst` | Requirements decomposition & Gherkin | Phase 1: Requirements | INVEST User Stories, Gherkin Scenarios |
185
+ | `lets-build` | Technical infrastructure scaffolding | Initial Bootstrapping only | Package manifests, build configs, `/healthz` |
186
+ | `clean-code-refactor` | Code smell eradication, GoF patterns | Phase 4: TDD Inner Loop | Decoupled classes, small functions (< 30 lines) |
187
+ | `compliance-audit` | Security & compliance verification | Phase 1, Phase 5: DoD | Gitleaks, Semgrep, Trivy, OWASP audit logs |
188
+ | `agentic-architect` | Agent configuration & skill governance | Continuous meta-refinement | Atomic `SKILL.md`, `AGENTS.md`, ADR records |
@@ -0,0 +1,107 @@
1
+ # Institutional Lessons Learned & Engineering Insights
2
+
3
+ > **Core Purpose:** Capture high-level strategic takeaways, trade-off analyses, and architecture lessons to continuously elevate team velocity and agentic precision.
4
+
5
+ ---
6
+
7
+ ## 1. Agentic Architecture & Token Optimization
8
+ - **Progressive Disclosure is Non-Negotiable:** Injecting 500 lines of documentation on every prompt degrades LLM reasoning. A lean root file (under 120 lines) acting as an indexed directory to modular rules preserves token budget and drastically improves model precision.
9
+ - **Conjunctions Betray Anti-Patterns:** Rules named `x_and_y.md` almost always signal that two distinct concepts have been artificially bundled. Decomposing into pure single-responsibility files prevents documentation rot and makes rules truly composable.
10
+ - **Relentless Questioning Prevents Hallucination:** Asking the 7 Core Inquiry Branches before authoring skills prevents speculative features, unused scripts, and ungrounded assumptions.
11
+
12
+ ---
13
+
14
+ ## 2. Multi-Tenancy & Data Isolation
15
+ - **Defense in Depth Over Developer Memory:** Never assume every developer or agent will remember to write `where: { tenantId }`. Hard database constraints (PostgreSQL RLS) must enforce isolation as a physical barrier.
16
+ - **Metadata Over Code Sprawl:** Enterprise tenants always require custom attributes, diverging workflows, and custom branding. Solving this through code branches (`if (tenant === 'acme')`) leads to exponential debt. Solving this through declarative schemas, JSON rule engines, and Server-Driven UI (SDUI) keeps the codebase tenant-agnostic.
17
+
18
+ ---
19
+
20
+ ## 3. Database Atomicity & Concurrency
21
+ - **The Dual-Write Problem is Everywhere:** As soon as an application updates a database and publishes to a broker or sends an email sequentially, it risks data divergence. The Transactional Outbox pattern is the gold standard for reliable event-driven state propagation.
22
+ - **DDL Locks Starve Production:** DDL queries queue up and block all subsequent reads and writes. Setting defensive `lock_timeout` and using non-blocking operations (`CREATE INDEX CONCURRENTLY`, two-phase constraint validation) is essential for zero-downtime operations.
23
+
24
+ ---
25
+
26
+ ## 4. Full-Stack Boundary & Monorepo Test Integrity
27
+ - **The In-Memory Supertest Illusion:** In-memory integration testing (`supertest(app)`) operates entirely within Node.js process memory. It validates route mapping and status codes, but completely masks network binding failures, reverse proxy omissions (Vite dev server / NGINX), and frontend client JSON serialization mismatches.
28
+ - **Coverage Percentages Do Not Equal System Integrity:** 100.00% statement and branch coverage in an isolated backend package gives zero guarantees about whether the frontend client or reverse proxy works. Monorepo test suites must mandate outer-loop smoke verification (`scripts/smoke_test.sh`) before declaring a full-stack system functional.
29
+
30
+ ---
31
+
32
+ ## 5. Process Integrity: Decoupling Bootstrapping from Domain Discovery
33
+ - **The Bootstrapping Scope Trap:** AI agents naturally gravitate toward rapidly generating complete functional applications. When invoked with `/lets-build`, an eager agent tends to generate entire domain entities, database tables, and mock UIs on sheer assumptions. This skips the most crucial phase of software engineering: deep, relentless stakeholder domain analysis.
34
+ - **Strict Phase Gating:** Project bootstrapping (`lets-build`) must be strictly confined to technical plumbing (toolchain, package manifests, build scripts, linter, Docker/Compose, and a minimal `/healthz` probe). Once the technical foundation is verified, the agent must stop and hand off to Domain Analysis (`product-analyst`, `relentless-questioner`). Real domain models must emerge exclusively from stakeholder interviews and Ubiquitous Language discovery.
35
+
36
+ ---
37
+
38
+ ## 6. UX Integrity: Decoupling Developer Personas from Production Auth & Design Triage
39
+ - **The "Toy Prototype" Anti-Pattern:** A major failure mode in rapid prototyping is embedding test personas ("Admin Alice", "Operator Bob", "Member Charlie") directly inside end-user sign-in forms or modals. This destroys product credibility, confuses real users, and masks broken authentication and onboarding flows.
40
+ - **Strict Separation of Concerns:** Developer testing personas must be 100% decoupled from production authentication. They belong exclusively in a dedicated development toolbar (`import.meta.env.DEV`), completely invisible in production builds. Production authentication must be a clean, dedicated, professional experience with validation, session persistence, and role-based post-login redirection.
41
+ - **The Untriaged Design Architecture Trap:** Building user interfaces without upfront Design Architecture Triage (roles, information architecture, navigation shell, URL state synchronization, and page flows) inevitably produces fractured, toy-like prototypes. Every UI increment must pass the 7-Pillar Design Architecture Triage Gate before writing a line of view code.
42
+
43
+ ---
44
+
45
+ ## 7. Server State Synchronization vs. Mock React Context
46
+ - **The Local Mock Store Debt:** Maintaining temporary in-memory React contexts (`MockResourceContext.tsx`) or mock data arrays alongside a real backend REST API creates phantom state, breaks multi-tab consistency, and causes state divergence.
47
+ - **Server-Authoritative State via TanStack Query:** Migrating to server-authoritative state via TanStack Query (`useQuery`, `useMutation`, and cache invalidation) with declarative RBAC guards (`<Can permission="...">`) grounds the entire web application in persistent backend data, eliminating client-side mocks and guaranteeing multi-tenant consistency.
48
+
49
+ ---
50
+
51
+ ## 8. Zero-Dependency SMTP Sockets & Deterministic Email Testing
52
+ - **Third-Party Mailer Bloat vs. Native Sockets:** Standard local development and containerized mail catchers (e.g. Mailpit) accept RFC 5321 commands over TCP sockets. Relying on heavy external mailer packages introduces unneeded transitive dependencies and supply chain risks. Implementing a clean socket-based SMTP adapter with standard library sockets provides zero-dependency, fully audited delivery with multipart/alternative MIME formatting and graceful offline fallback.
53
+ - **Strict HTML Escaping & Injection Neutralization:** Transactional notifications interpolate user inputs (names, action titles, payment references). Centralizing sanitization through a strict escaping utility neutralizing `&`, `<`, `>`, `"`, and `'` guarantees zero HTML injection or XSS risks.
54
+ - **Double-Loop Decoupling with Background Job Queue:** Decoupling notification delivery from HTTP request-response cycles via an asynchronous job queue ensures API responsiveness. Testing event dispatchers against in-memory notification sinks allows 100.00% branch and statement coverage without network flakes.
55
+
56
+ ---
57
+
58
+ ## 9. Digital Contract Execution, Schema Evolution & Signature Auditing
59
+ - **Non-Destructive Schema Evolution with Declarative JSON:** Expanding database models to support variable contractual covenants, conditions, and digital signature records without table bloat is achieved cleanly through semi-structured JSON fields (`termsJson`, `signatureJson`). Running declarative synchronization preserves database integrity and avoids premature migration schema lock-in during rapid domain evolution.
60
+ - **Cryptographic Execution Audit Trails:** Digital signatures require more than a boolean `isSigned` flag. A legally defensible electronic execution record must record: (1) Typed signer legal name, (2) ISO 8601 UTC timestamp, (3) Authenticated user actor ID, (4) Client IP address, (5) Client User-Agent string, and (6) A deterministic cryptographic checksum or execution reference hash.
61
+ - **Outside-In Event Notification Synchronization:** Executing an agreement is a domain transition that must trigger notification side effects. Emitting domain events on an asynchronous queue allows event notification dispatchers to compose transactional confirmation messages with executed terms and receipt summaries without blocking the HTTP response.
62
+
63
+ ---
64
+
65
+ ## 10. Design Token Completeness & Application-Wide Theme Architecture
66
+ - **The Partial Dark Mode Token Pitfall:** Automated component CLI generators inject component-scoped CSS variables into `.dark` (e.g. `--sidebar-*`), but do not populate omitted foundational design tokens (`--background`, `--foreground`, `--card`, `--border`, `--popover`). If root `.dark` is missing foundational tokens, applying the `dark` class leaves background colors white and text illegible. Always maintain symmetric, complete design tokens across `:root` and `.dark`.
67
+ - **System Preference Detection & Reactive Synchronization:** A robust `ThemeProvider` must listen to `window.matchMedia('(prefers-color-scheme: dark)')` with dynamic event listeners so OS appearance toggles seamlessly propagate in real-time. Synchronizing `document.documentElement.style.colorScheme = resolvedTheme` ensures native browser elements (scrollbars, datetime pickers) match the selected theme.
68
+
69
+ ---
70
+
71
+ ## 11. Dependency Injection Hygiene vs. Split-Brain In-Memory Traps
72
+ - **The Split-Brain Instantiation Anti-Pattern:** When application factories (`createApp(deps)`) provide default fallback instances for domain repositories, passing some repositories while omitting others creates two disconnected sets of state. For instance, if `index.ts` creates a `userRepo` and seeds admin credentials, but `createApp` defaults to a newly constructed `userRepo`, API requests hit the empty fallback instance.
73
+ - **Strict Inversion of Control:** Factories must accept a fully instantiated `AppDependencies` composite or explicit container. Server entrypoints must assemble the complete dependency graph and inject all collaborators explicitly.
74
+
75
+ ---
76
+
77
+ ## 12. Domain Invariant Synchronization & Resource Concurrency
78
+ - **Aggregate Isolation Requires Domain Coordination:** An agreement or reservation is a separate aggregate from a constrained inventory resource. However, activating an agreement without validating resource availability permits double-allocation race conditions. Hexagonal use cases must coordinate aggregate transitions atomically: validating resource availability before agreement signing, transitioning the resource status to `ALLOCATED` upon execution, and restoring `AVAILABLE` upon termination.
79
+ - **Fail-Closed Multi-Tenancy:** Never trust client-supplied tenant headers (`x-tenant-id`) without cryptographically verifying the authenticated actor's tenant organization memberships. Mismatched tenant headers must immediately fail closed with HTTP 403 `FORBIDDEN_TENANT_ACCESS`.
80
+
81
+ ---
82
+
83
+ ## 13. Client-Side Resilience & Multi-Tab Reactive Synchronization
84
+ - **Error Boundaries Prevent Catastrophic Shell Crashes:** Heavy visual components (such as charts with dynamic SVG/canvas rendering) or dynamic sub-routes can throw runtime exceptions on unexpected data. Wrapping page outlets and complex widgets in accessible `<ErrorBoundary>` components preserves the shell and navigation while offering modular retry.
85
+ - **Cross-Tab Synchronization via Storage Events:** Modern multi-tab workflows mean users open links, resource lists, or self-service portals in separate tabs. Listening to the browser's native `storage` event ensures that login, logout, and active tenant switches are immediately synchronized across all open tabs without desynchronization.
86
+
87
+ ---
88
+
89
+ ## 14. Decoupling Developer Diagnostics from Production Shell & Centralizing UI Copy
90
+ - **The Telemetry Bleed Anti-Pattern:** Placing internal architectural metrics ("ACID ledger", "Hexagonal ports", "API Connected" pulsing pills, "Role: OPERATOR" badges) into user-facing wayfinding breadcrumbs, headers, or footers creates confusion for end users (consumers and enterprise operators alike). These technical indicators belong strictly within development tools conditionally mounted under `import.meta.env.DEV`, ensuring production builds are clean and focused on user tasks.
91
+ - **Centralized Single Source of Truth for Copy:** Distributing strings across JSX templates causes text divergence, typos, and high refactoring overhead. Consolidating all copy, error messages, empty states, breadcrumbs, and action text into a single configuration module (`UI_STRINGS` in `app-constants.ts`) simplifies internationalization readiness, branding updates, and unit test verification.
92
+
93
+ ---
94
+
95
+ ## 15. Monorepo-Wide Module Path Aliasing (`@/*`) & Deep Relative Traversal Elimination
96
+ - **Fragility of Deep Relative Imports:** Using deep relative traversals (`../../../..`, `../../..`, `../..`) across modular hexagonal architectures creates fragile couplings. Minor file restructuring breaks dozens of imports, and deep relative paths obscure which architectural boundary (domain core, primary ports, secondary adapters) is being invoked.
97
+ - **Unified Path Aliasing Standard:** Standardizing on `@/*` mapped to `./src/*` across TypeScript compiler configs (`tsconfig.json`), test runners (Vitest), and bundlers (Vite) enforces consistent, unambiguous imports across the entire monorepo.
98
+ - **Node.js ESM Build Resolution via `tsc-alias`:** TypeScript's `tsc` compiler does not rewrite path aliases in emitted JavaScript by default. In Node.js ESM environments, running `tsc-alias` post-compilation (`tsc && tsc-alias`) transforms `@/*` aliases into valid relative paths directly in `dist/`, enabling 100% native Node.js ESM execution with zero runtime loader overhead.
99
+
100
+ ---
101
+
102
+ ## 16. Canonical Domain Error Hierarchy & Zero-`any` Type Safety
103
+ - **The Monkey-Patching Anti-Pattern:** Adding status codes to arbitrary error objects at catch sites (e.g. `(err as any).statusCode = 404`) bypasses TypeScript strict mode, prevents compile-time exhaustiveness checking, and risks dropping contextual problem details.
104
+ - **Structured Domain Error Model:** Modeling operational domain errors via an explicit `DomainError` base class with canonical subclasses (`ValidationError`, `UnauthorizedError`, `ForbiddenError`, `NotFoundError`, `ConflictError`, `ExpiredError`) allows clean `instanceof` type narrowing in HTTP error middleware, guaranteeing RFC 7807 compliance without type assertion escape hatches.
105
+
106
+
107
+
@@ -0,0 +1,23 @@
1
+ # Living Ubiquitous Language Glossary Template
2
+
3
+ > **Source of Truth:** Authoritative terminology dictionary binding domain concepts, business definitions, and exact code identifiers. Customize this glossary per project.
4
+
5
+ ---
6
+
7
+ ## Canonical Domain Vocabulary Matrix
8
+
9
+ | Canonical Term | Business Definition | Bounded Context | Forbidden Synonyms | Code & Database Identifiers |
10
+ |---|---|---|---|---|
11
+ | **Organization** | The top-level administrative and multi-tenant isolation container. | Multi-Tenancy & Identity | Account, Company, Workspace, TenantGroup | `Organization`, `organizationId`, `organizations` table |
12
+ | **User** | A human actor authenticated with verified credentials across the platform. | Identity & Access | Member (when unauthenticated), Account, Login | `User`, `userId`, `users` table |
13
+ | **Membership** | The formal association connecting a User to an Organization with assigned roles. | Authorization & RBAC | UserOrg, Seat, PermissionAssignment | `Membership`, `membershipId`, `memberships` table |
14
+ | **Role** | A named set of granular `<entity>:<action>` permissions within an organization. | Authorization | Group, Profile, Level | `Role`, `roleId`, `roles` table |
15
+ | **Resource** | The primary business entity managed within the domain core. | Core Domain | Item, Object, Record, Entity | `Resource`, `resourceId`, `resources` table |
16
+ | **Ledger Entry** | An immutable audit record detailing a financial or transactional state change. | Finance & Accounting | TransactionRow, MoneyLog, BillEntry | `LedgerEntry`, `ledgerEntryId`, `ledger_entries` table |
17
+
18
+ ---
19
+
20
+ ## Linguistic Invariants & Rules
21
+ 1. **The Single Name Rule:** Every domain concept has exactly one authoritative name. Synonyms are strictly forbidden across code, schemas, and UI.
22
+ 2. **Contextual Boundaries:** If a word has multiple meanings across business departments, isolate the terms within dedicated Bounded Contexts.
23
+ 3. **Continuous Updating:** When domain experts establish or rename a term, update this glossary immediately, record an ADR in `memory.md`, and refactor all occurrences.
@@ -0,0 +1,31 @@
1
+ # Accessibility (A11y) & WCAG 2.2 Standards
2
+
3
+ > **Core Mandate:** Enforce WCAG 2.2 Level AA compliance, accessible Radix UI primitives, keyboard focus management, visible focus rings, and ARIA live regions across all user interfaces.
4
+
5
+ ---
6
+
7
+ ## 1. Accessible UI Primitives & Radix UI
8
+
9
+ - **Prohibited Native Alerts**: Strictly prohibit browser-native `window.confirm()` or `window.alert()`. Use accessible Radix UI dialogs (`@radix-ui/react-dialog`, `@radix-ui/react-alert-dialog`).
10
+ - **Focus Management & Trapping**:
11
+ - Modal dialogs must trap keyboard focus within the dialog container while open.
12
+ - Closing a dialog must return keyboard focus deterministically to the triggering element.
13
+ - **Visible Focus Indicators**: Never remove default outline rings (`outline: none`) without providing an explicit, high-contrast replacement (`focus-visible:ring-2 focus-visible:ring-offset-2`).
14
+
15
+ ---
16
+
17
+ ## 2. Form & Feedback Accessibility
18
+
19
+ - **Form Input Wiring**:
20
+ - Every form input must have an associated `<label>` using `htmlFor` or nested wrapping.
21
+ - Validation errors must be programmatically linked to their inputs via `aria-invalid="true"` and `aria-describedby="<error-message-id>"`.
22
+ - **Dynamic Content & Status Feedback (ARIA Live Regions)**:
23
+ - Asynchronous notifications, toast alerts, and status updates must use `role="status"` or `aria-live="polite"` so screen readers announce changes without interrupting the user.
24
+ - Critical error alerts must use `role="alert"` or `aria-live="assertive"`.
25
+
26
+ ---
27
+
28
+ ## 3. Visual & Contrast Baselines
29
+
30
+ - **Color Contrast**: Maintain a minimum contrast ratio of 4.5:1 for normal text and 3:1 for large text / UI controls against their background.
31
+ - **Semantic Landmark Markup**: Use semantic landmark elements (`<main>`, `<nav>`, `<aside>`, `<header>`, `<footer>`, `<section>`) rather than unsemantic `<div>` structures.
@@ -0,0 +1,104 @@
1
+ # Advanced REST API Patterns & Capability Architecture
2
+
3
+ > **Core Mandate:** Enrich API responses with capability metadata (Allowed Actions), ensure safe mutations via idempotency keys, enforce cursor pagination, and prevent race conditions with optimistic concurrency.
4
+
5
+ ---
6
+
7
+ ## 1. Allowed Actions & Capability Metadata (HATEOAS-Lite)
8
+
9
+ Clients must not duplicate server-side business and authorization rules to decide whether an action (edit, delete, approve, cancel) is permitted. **The server is the authoritative source of truth.**
10
+
11
+ ### Pattern: `_actions` and `_links` Envelope
12
+ Every resource response must embed an `_actions` boolean map and optional `_links` hypermedia block indicating what the requesting caller is permitted to do based on their role, tenant boundaries, and the entity's current state:
13
+
14
+ ```json
15
+ {
16
+ "id": "ord_9876",
17
+ "status": "SHIPPED",
18
+ "totalAmount": 149.99,
19
+ "currency": "USD",
20
+ "_actions": {
21
+ "canEdit": false,
22
+ "canCancel": false,
23
+ "canTrack": true,
24
+ "canRequestRefund": true
25
+ },
26
+ "_links": {
27
+ "self": { "href": "/api/v1/orders/ord_9876", "method": "GET" },
28
+ "track": { "href": "/api/v1/orders/ord_9876/tracking", "method": "GET" },
29
+ "refund": { "href": "/api/v1/orders/ord_9876/refunds", "method": "POST" }
30
+ }
31
+ }
32
+ ```
33
+
34
+ ### UI Benefits
35
+ - Frontend buttons and menus simply bind to `resource._actions.canDelete`.
36
+ - When business logic evolves (e.g. orders over $1,000 require manager approval), only the backend logic changes—zero frontend redeployment required.
37
+
38
+ ---
39
+
40
+ ## 2. Safe Mutations via Idempotency Keys (IETF Draft)
41
+
42
+ To prevent duplicate processing (double charging, duplicate resource creation) caused by network retries:
43
+
44
+ ### Protocol
45
+ - Clients generating mutating requests (`POST`, `PATCH`) must supply a unique `Idempotency-Key: <uuid-v4>` header.
46
+ - **Server Lifecycle**:
47
+ 1. Check distributed idempotency store for key `idemp:<tenantId>:<idempotencyKey>`.
48
+ 2. If found with status `IN_FLIGHT`: return `409 Conflict` (`IDEMPOTENT_OPERATION_IN_PROGRESS`).
49
+ 3. If found with status `COMPLETED`: return the cached status code, headers, and response payload without re-executing.
50
+ 4. If not found: Acquire distributed lock, process mutation atomically, cache response with a 24-hour TTL, and release lock.
51
+
52
+ ---
53
+
54
+ ## 3. High-Scale Keyset / Cursor-Based Pagination
55
+
56
+ Never use offset pagination (`OFFSET 10000 LIMIT 20`) on large tables. Offsets degrade linearly (`O(N)`) and suffer from page-drift anomalies.
57
+
58
+ ### Specification
59
+ - Query Parameters: `?cursor=<opaque_base64>&limit=20` (default limit 20, max 100).
60
+ - Response Envelope:
61
+ ```json
62
+ {
63
+ "data": [...],
64
+ "pagination": {
65
+ "nextCursor": "ZXlKaWRI...==",
66
+ "hasMore": true,
67
+ "limit": 20
68
+ }
69
+ }
70
+ ```
71
+ - **Agnostic Keyset Query Pattern**:
72
+ ```sql
73
+ SELECT * FROM orders
74
+ WHERE tenant_id = :tenantId
75
+ AND (created_at, id) < (:cursorCreatedAt, :cursorId)
76
+ ORDER BY created_at DESC, id DESC
77
+ LIMIT :limit + 1;
78
+ ```
79
+ If `results.length > limit`, slice the extra item and encode its cursor token for `nextCursor`.
80
+
81
+ ---
82
+
83
+ ## 4. Optimistic Concurrency Control (OCC)
84
+
85
+ Prevent lost-update anomalies during concurrent edits without pessimistic database row locking:
86
+
87
+ ### Protocol
88
+ - Every mutable entity contains an incrementing integer `version` column.
89
+ - Server returns the current version in the `ETag` response header: `ETag: W/"v4"`.
90
+ - Clients submitting updates (`PUT`, `PATCH`) must include `If-Match: W/"v4"`.
91
+ - **Conflict Handling**:
92
+ - Atomic update: `UPDATE table SET ..., version = version + 1 WHERE id = :id AND version = :expectedVersion`.
93
+ - If 0 rows updated: Return **`409 Conflict`** with error code `CONCURRENCY_CONFLICT` and the latest entity representation.
94
+
95
+ ---
96
+
97
+ ## 5. Asynchronous Processing (`202 Accepted`)
98
+
99
+ For tasks taking > 1.5 seconds (video rendering, large PDF export, batch imports):
100
+ - Do NOT block synchronous client requests.
101
+ - Dispatch task to an asynchronous worker queue or workflow engine.
102
+ - Return **`202 Accepted`** immediately with:
103
+ - Header: `Location: /api/v1/tasks/:taskId`
104
+ - Body: `{ "taskId": "tsk_123", "status": "QUEUED", "pollIntervalMs": 2000 }`
@@ -0,0 +1,168 @@
1
+ # Agentic Configuration, Skills & Harness Standards
2
+
3
+ > **Core Mandate:** Maintain lean agent entrypoints via progressive disclosure, modular documentation, strict skill front matter standards, harness symlink parity, and relentless questioning during skill architecture.
4
+
5
+ ---
6
+
7
+ ## 1. The Root AGENTS.md Standard
8
+
9
+ Root configuration files (`AGENTS.md`) are injected into the agent context on **every single prompt**. To prevent context pollution and token degradation:
10
+
11
+ ### Required Contents (Keep under 100–120 lines)
12
+ - **Identity & Mission:** 1–2 sentences defining workspace purpose and core domain.
13
+ - **Runtime Environment:** Declared package manager, runtime version, and non-standard scripts.
14
+ - **Core Operating Framework:** Foundational principles (Rule Zero, Zero-Assumption, Relentless Questioning, 5-stage lifecycle, action boundaries).
15
+ - **Open-Source Mandate:** Strict requirement to standardize on 100% open-source packages and tools.
16
+ - **High-Level Layout:** High-level architectural boundaries only (packages, apps).
17
+ - **Progressive Disclosure Table:** Clean index linking to specialized domain rules in `docs/rules/*.md`.
18
+
19
+ ### Explicit Prohibitions (What NOT to Include)
20
+ - **No Developer Onboarding / Getting Started Guides:** Do not include steps for cloning, environment setup, or basic onboarding meant for human engineers.
21
+ - **No Granular File Trees:** Never enumerate individual file paths that change frequently (causes rapid documentation rot).
22
+ - **No Monolithic Domain Tutorials:** Never embed full CSS conventions, database migration steps, API specs, or PR delivery checklists directly in the root file.
23
+ - **No Preemptive Speculation:** Never add rules for errors the AI has not actually made. Ground rules in verified project mistakes or requirements.
24
+
25
+ ---
26
+
27
+ ## 2. Monorepo & Nested AGENTS.md Files
28
+
29
+ - In multi-package workspaces or monorepos (e.g. `apps/backend/`, `apps/frontend/`), place package-specific instructions in a nested `AGENTS.md` within that package folder.
30
+ - The root `AGENTS.md` remains high-level; the nested `AGENTS.md` provides scoped context only when the agent operates within that subdirectory.
31
+
32
+ ---
33
+
34
+ ## 3. Harness Parity & Symlinks
35
+
36
+ Different AI agents and IDE harnesses look for different configuration filenames:
37
+ - Standard: `AGENTS.md`
38
+ - Lowercase: `agents.md`
39
+ - Anthropic Claude Code: `CLAUDE.md`
40
+
41
+ **Standard:** Maintain identical configuration across all harnesses by establishing filesystem symbolic links:
42
+ ```bash
43
+ ln -sf AGENTS.md agents.md
44
+ ln -sf AGENTS.md CLAUDE.md
45
+ ```
46
+ Never duplicate content into separate files.
47
+
48
+ ---
49
+
50
+ ## 4. Skills Architecture (`.agents/skills/<skill-name>/`)
51
+
52
+ Skills provide on-demand capabilities for **specialized, complex, or multi-step workflows** that should not pollute the global context.
53
+
54
+ ### Front Matter Specification (`SKILL.md`)
55
+ ```yaml
56
+ ---
57
+ name: <skill-name>
58
+ description: <Imperative trigger description under 1024 characters. MUST start with 'Use when...'>
59
+ ---
60
+ ```
61
+ - **Description Requirements:**
62
+ - Focus strictly on **user intent**, not just technology descriptions.
63
+ - Explicitly state when to use: `Use when the user wants to...`
64
+ - Explicitly state when NOT to use: `Do not use for...`
65
+ - Never write generic summaries like `"A library for managing state"`.
66
+
67
+ ### Body Guidelines
68
+ - Keep under **500 lines**.
69
+ - Ground instructions in real codebase experience, not generic documentation the LLM already knows.
70
+ - **Mandatory "Gotchas & What NOT to Do" section:** Explicitly list known AI anti-patterns and pitfalls.
71
+ - Include structured response templates and self-validation checklists for deterministic output.
72
+
73
+ ### Progressive Disclosure Subdirectories
74
+ - `references/`: Detailed sub-domain markdown files loaded on demand by the skill.
75
+ - `scripts/`: Deterministic executable scripts (bash, node, python) for tasks where LLMs produce non-deterministic drift.
76
+ - `assets/`: Static data, lookup tables, schemas, or boilerplate templates.
77
+
78
+ ---
79
+
80
+ ## 5. The Architectural Atomicity Mandate for Rules & Skills
81
+
82
+ Every rule, skill, workflow, and configuration component must adhere to the **Single Responsibility Principle (SRP)**: indivisible, self-contained, orthogonal, and composable.
83
+
84
+ ### Rule Atomicity
85
+ - **One Domain Per Rule:** Each rule file in `docs/rules/` must govern exactly one architectural or engineering subdomain.
86
+ - **Completeness Without Stubs:** A rule must never be a shallow stub or placeholder; it must codify production-grade invariants, anti-patterns, and concrete code patterns.
87
+ - **Zero Cross-Leakage:** Rules must be mutually orthogonal—never duplicate or contradict directives across files.
88
+
89
+ ### Skill Atomicity
90
+ - **One Capability Per Skill:** Each skill in `.agents/skills/` must encapsulate one discrete, multi-step workflow.
91
+ - **Bounded Negative Triggers:** Must define both what it does (`Use when...`) and explicitly what it does not do (`Do not use for...`).
92
+ - **Encapsulated Artifacts:** Scripts, assets, and reference docs must live within the skill's isolated directory tree.
93
+ - **Idempotent Execution:** Re-executing a skill against the same inputs must produce identical, deterministic results.
94
+
95
+ ### Many-to-Many Skill Composability Models
96
+ Coding tasks and agentic skills exhibit an explicit **Many-to-Many ($M:N$) Relationship**:
97
+ 1. **Multiple Skills per Coding Task:** Implementing a complex domain feature frequently requires composing several orthogonal skills:
98
+ - `relentless-questioner` (resolves ambiguous invariants and failure edge cases).
99
+ - `product-analyst` (decomposes into INVEST user stories and executable Gherkin criteria).
100
+ - `compliance-audit` (verifies OWASP, SOC 2, and data isolation controls).
101
+ - `clean-code-refactor` (applies GoF patterns, CQS, SLAP, and eliminates code smells during the TDD inner loop).
102
+ 2. **Single Skill in Multiple Scenarios:** An atomic skill functions as a reusable capability across completely different business problems (e.g. `clean-code-refactor` applies equally to financial ledgers, order lifecycle state machines, and authentication middleware).
103
+
104
+ #### The 3 Composition Patterns:
105
+ - **Pattern 1: Sequential Pipeline Chaining (Workflow Composition):** Skill $A$ produces a structured artifact (e.g. Feature Alignment Spec) that serves as the direct input contract for Skill $B$ (e.g. Gherkin test suite generation).
106
+ - **Pattern 2: Dynamic Skill Stacking (Contextual Composition):** An agent activates multiple orthogonal skills simultaneously in its execution context, adhering to Progressive Disclosure without polluting global prompts.
107
+ - **Pattern 3: Multi-Agent Subagent Delegation (Division of Labor):** A coordinator agent delegates isolated sub-tasks to specialized subagents equipped with specific skills, synthesizing their outputs into a single atomic change.
108
+
109
+ #### Invariants for Valid Skill Composition:
110
+ - **Standardized Output Contracts:** Skills must emit predictable, structured markdown or JSON envelopes (e.g. FAS, Gherkin blocks, ADR templates).
111
+ - **Zero Cross-Contamination:** No skill may write code or modify files outside its declared functional boundary.
112
+ - **Pure Function Semantics:** Analysis skills must remain read-only and side-effect free.
113
+
114
+ ---
115
+
116
+ ## 6. The Relentless Skill Architecture Inquiry
117
+
118
+ Never architect or modify a skill based on assumptions. Before authoring any `SKILL.md`, run the **7 Core Skill Inquiry Branches**:
119
+
120
+ ```
121
+ [New Skill / Rule Request]
122
+ │
123
+ ▼
124
+ [Branch 1: Placement] ────────── Should this be AGENTS.md, a Rule, or a Skill?
125
+ │
126
+ ▼
127
+ [Branch 2: Trigger Boundaries] ── Exact 'Use when...' and explicit 'Do NOT use for...'?
128
+ │
129
+ ▼
130
+ [Branch 3: Domain Ground Truth] ─ Have generic textbook tutorials been purged?
131
+ │
132
+ ▼
133
+ [Branch 4: Gotchas & Anti-Patterns] What specific AI mistakes MUST be forbidden?
134
+ │
135
+ ▼
136
+ [Branch 5: Determinism vs LLM] ── Should deterministic steps be scripts in scripts/?
137
+ │
138
+ ▼
139
+ [Branch 6: Progressive Bloat] ─── Is SKILL.md < 500 lines with sub-docs in references/?
140
+ │
141
+ ▼
142
+ [Branch 7: Verification Loop] ─── Are there output templates and self-checklists?
143
+ │
144
+ ▼
145
+ [Ready to Author / Update Skill]
146
+ ```
147
+
148
+ ### The 7 Core Inquiry Branches
149
+
150
+ | # | Inquiry Branch | What to Interrogate | If Unanswered |
151
+ |---|---|---|---|
152
+ | **1** | **Placement & Scope** | Does this apply to all prompts (Root `AGENTS.md`), one package (Nested `AGENTS.md`), a continuous coding domain (`docs/rules/`), or an on-demand task (`.agents/skills/`)? | Stop and categorize correctly. Never bloat root configs. |
153
+ | **2** | **Trigger Intent** | What explicit user intent wakes this skill? What are the negative conditions? | Interrogate the user on exact workflow boundaries. |
154
+ | **3** | **Domain Truth** | Is this grounded in this project's architecture, or generic fluff the LLM already knows? | Purge generic definitions (e.g. "What is a PDF/REST API"). |
155
+ | **4** | **Gotchas & Anti-Patterns** | What exact mistakes has the AI repeatedly made in this task? | Formulate 3–5 explicit negative "DO NOT" rules. |
156
+ | **5** | **Determinism** | Are there brittle CLI sequences that need a bash/Node script instead of stochastic LLM generation? | Create helper scripts in `scripts/`. |
157
+ | **6** | **Progressive Bloat** | Does `SKILL.md` exceed 500 lines? | Extract sub-topic guides into `references/`. |
158
+ | **7** | **Verification Loop** | How will the agent and user prove the skill succeeded? | Provide structured response templates & validation checklists. |
159
+
160
+ ---
161
+
162
+ ## 7. The Continuous Refinement Loop
163
+
164
+ When an AI produces suboptimal code or documentation:
165
+ 1. Preserve the original AI output draft.
166
+ 2. Make manual corrections to produce the desired gold-standard output.
167
+ 3. Diff the original draft against the corrected version to identify specific gaps.
168
+ 4. Update the relevant skill's "What NOT to do" or guideline section to prevent repeating that mistake.