opencastle 0.32.4 → 0.32.6

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 (108) hide show
  1. package/README.md +13 -3
  2. package/bin/cli.mjs +2 -0
  3. package/dist/cli/bootstrap.js +1 -1
  4. package/dist/cli/bootstrap.js.map +1 -1
  5. package/dist/cli/bootstrap.test.js +16 -0
  6. package/dist/cli/bootstrap.test.js.map +1 -1
  7. package/dist/cli/init.test.js +38 -0
  8. package/dist/cli/init.test.js.map +1 -1
  9. package/dist/cli/stack-config-update.test.js +18 -0
  10. package/dist/cli/stack-config-update.test.js.map +1 -1
  11. package/dist/cli/stack-config.d.ts.map +1 -1
  12. package/dist/cli/stack-config.js +1 -0
  13. package/dist/cli/stack-config.js.map +1 -1
  14. package/dist/cli/types.d.ts +1 -1
  15. package/dist/cli/types.d.ts.map +1 -1
  16. package/dist/orchestrator/plugins/index.d.ts.map +1 -1
  17. package/dist/orchestrator/plugins/index.js +4 -0
  18. package/dist/orchestrator/plugins/index.js.map +1 -1
  19. package/dist/orchestrator/plugins/notion/config.d.ts +3 -0
  20. package/dist/orchestrator/plugins/notion/config.d.ts.map +1 -0
  21. package/dist/orchestrator/plugins/notion/config.js +46 -0
  22. package/dist/orchestrator/plugins/notion/config.js.map +1 -0
  23. package/dist/orchestrator/plugins/trello/config.d.ts +3 -0
  24. package/dist/orchestrator/plugins/trello/config.d.ts.map +1 -0
  25. package/dist/orchestrator/plugins/trello/config.js +43 -0
  26. package/dist/orchestrator/plugins/trello/config.js.map +1 -0
  27. package/dist/orchestrator/plugins/types.d.ts +1 -1
  28. package/dist/orchestrator/plugins/types.d.ts.map +1 -1
  29. package/package.json +1 -1
  30. package/src/cli/bootstrap.test.ts +21 -0
  31. package/src/cli/bootstrap.ts +1 -1
  32. package/src/cli/init.test.ts +46 -0
  33. package/src/cli/stack-config-update.test.ts +20 -0
  34. package/src/cli/stack-config.ts +1 -0
  35. package/src/cli/types.ts +1 -1
  36. package/src/dashboard/node_modules/.vite/deps/_metadata.json +6 -6
  37. package/src/orchestrator/agents/api-designer.agent.md +25 -34
  38. package/src/orchestrator/agents/architect.agent.md +40 -84
  39. package/src/orchestrator/agents/content-engineer.agent.md +29 -31
  40. package/src/orchestrator/agents/copywriter.agent.md +35 -60
  41. package/src/orchestrator/agents/data-expert.agent.md +24 -30
  42. package/src/orchestrator/agents/database-engineer.agent.md +26 -31
  43. package/src/orchestrator/agents/developer.agent.md +32 -34
  44. package/src/orchestrator/agents/devops-expert.agent.md +31 -26
  45. package/src/orchestrator/agents/documentation-writer.agent.md +29 -29
  46. package/src/orchestrator/agents/performance-expert.agent.md +36 -33
  47. package/src/orchestrator/agents/release-manager.agent.md +25 -34
  48. package/src/orchestrator/agents/researcher.agent.md +41 -95
  49. package/src/orchestrator/agents/reviewer.agent.md +24 -34
  50. package/src/orchestrator/agents/security-expert.agent.md +35 -39
  51. package/src/orchestrator/agents/seo-specialist.agent.md +25 -32
  52. package/src/orchestrator/agents/session-guard.agent.md +20 -79
  53. package/src/orchestrator/agents/team-lead.agent.md +50 -254
  54. package/src/orchestrator/agents/testing-expert.agent.md +37 -49
  55. package/src/orchestrator/agents/ui-ux-expert.agent.md +33 -39
  56. package/src/orchestrator/customizations/KNOWN-ISSUES.md +0 -1
  57. package/src/orchestrator/customizations/agents/skill-matrix.json +20 -4
  58. package/src/orchestrator/customizations/agents/skill-matrix.md +20 -0
  59. package/src/orchestrator/instructions/general.instructions.md +24 -84
  60. package/src/orchestrator/plugins/astro/SKILL.md +23 -179
  61. package/src/orchestrator/plugins/convex/SKILL.md +38 -12
  62. package/src/orchestrator/plugins/index.ts +4 -0
  63. package/src/orchestrator/plugins/netlify/SKILL.md +17 -13
  64. package/src/orchestrator/plugins/nextjs/SKILL.md +55 -261
  65. package/src/orchestrator/plugins/notion/SKILL.md +205 -0
  66. package/src/orchestrator/plugins/notion/config.ts +47 -0
  67. package/src/orchestrator/plugins/nx/SKILL.md +20 -72
  68. package/src/orchestrator/plugins/playwright/SKILL.md +5 -17
  69. package/src/orchestrator/plugins/slack/SKILL.md +28 -190
  70. package/src/orchestrator/plugins/teams/SKILL.md +10 -140
  71. package/src/orchestrator/plugins/trello/SKILL.md +151 -0
  72. package/src/orchestrator/plugins/trello/config.ts +44 -0
  73. package/src/orchestrator/plugins/types.ts +1 -1
  74. package/src/orchestrator/plugins/vitest/SKILL.md +2 -2
  75. package/src/orchestrator/prompts/bug-fix.prompt.md +25 -63
  76. package/src/orchestrator/prompts/implement-feature.prompt.md +29 -66
  77. package/src/orchestrator/prompts/quick-refinement.prompt.md +31 -66
  78. package/src/orchestrator/skills/accessibility-standards/SKILL.md +50 -105
  79. package/src/orchestrator/skills/agent-hooks/SKILL.md +60 -110
  80. package/src/orchestrator/skills/agent-memory/SKILL.md +44 -93
  81. package/src/orchestrator/skills/api-patterns/SKILL.md +20 -68
  82. package/src/orchestrator/skills/code-commenting/SKILL.md +49 -101
  83. package/src/orchestrator/skills/context-map/SKILL.md +47 -88
  84. package/src/orchestrator/skills/data-engineering/SKILL.md +27 -74
  85. package/src/orchestrator/skills/decomposition/SKILL.md +50 -98
  86. package/src/orchestrator/skills/deployment-infrastructure/SKILL.md +44 -107
  87. package/src/orchestrator/skills/documentation-standards/SKILL.md +28 -89
  88. package/src/orchestrator/skills/fast-review/SKILL.md +51 -276
  89. package/src/orchestrator/skills/frontend-design/SKILL.md +53 -163
  90. package/src/orchestrator/skills/git-workflow/SKILL.md +18 -54
  91. package/src/orchestrator/skills/memory-merger/SKILL.md +51 -88
  92. package/src/orchestrator/skills/observability-logging/SKILL.md +29 -75
  93. package/src/orchestrator/skills/orchestration-protocols/SKILL.md +58 -117
  94. package/src/orchestrator/skills/panel-majority-vote/SKILL.md +65 -140
  95. package/src/orchestrator/skills/performance-optimization/SKILL.md +21 -85
  96. package/src/orchestrator/skills/project-consistency/SKILL.md +62 -281
  97. package/src/orchestrator/skills/react-development/SKILL.md +38 -86
  98. package/src/orchestrator/skills/security-hardening/SKILL.md +40 -84
  99. package/src/orchestrator/skills/self-improvement/SKILL.md +26 -60
  100. package/src/orchestrator/skills/seo-patterns/SKILL.md +40 -105
  101. package/src/orchestrator/skills/session-checkpoints/SKILL.md +26 -68
  102. package/src/orchestrator/skills/team-lead-reference/SKILL.md +66 -206
  103. package/src/orchestrator/skills/testing-workflow/SKILL.md +42 -112
  104. package/src/orchestrator/skills/validation-gates/SKILL.md +39 -170
  105. package/src/orchestrator/snippets/base-output-contract.md +14 -0
  106. package/src/orchestrator/snippets/discovered-issues-policy.md +15 -0
  107. package/src/orchestrator/snippets/logging-mandatory.md +11 -0
  108. package/src/orchestrator/snippets/never-expose-secrets.md +22 -0
@@ -3,150 +3,100 @@ name: agent-hooks
3
3
  description: "Lifecycle hooks for AI agent sessions — reusable actions that run at specific points (session start, session end, pre-delegation, post-delegation). Defines what to do at each lifecycle event so agents behave consistently."
4
4
  ---
5
5
 
6
- <!-- ⚠️ This file is managed by OpenCastle. Edits will be overwritten on update. Customize in the .opencastle/ directory instead. -->
7
-
8
6
  # Agent Lifecycle Hooks
9
7
 
10
- Hooks are **standardized actions** that agents execute at specific points during their lifecycle. They enforce consistency across sessions and prevent common oversights (missing lessons, forgotten checkpoints, untracked issues).
11
-
12
- ## Hook Execution Model
13
-
14
- Hooks are **conventions, not automated triggers**. Agents must explicitly follow them. The Team Lead includes hook reminders in delegation prompts; specialist agents include them in their own workflow.
8
+ Conventions (not auto-triggers) agents execute at specific lifecycle points. Team Lead includes hook reminders in delegation prompts; specialists follow them in their own workflow.
15
9
 
16
10
  ```
17
- Session Lifecycle:
18
- on-session-start → [work loop] → on-session-end
19
- ↓ ↑
20
- on-pre-delegate → on-post-delegate
11
+ on-session-start → [work loop] → on-session-end
12
+ ↓ ↑
13
+ on-pre-delegate → on-post-delegate
21
14
  ```
22
15
 
23
16
  ---
24
17
 
25
- ## Hook: on-session-start
26
-
27
- **When:** First action in any agent session (Team Lead or specialist).
28
-
29
- ### Actions
30
-
31
- 1. **Read lessons learned** — Scan `.opencastle/LESSONS-LEARNED.md` for entries relevant to the current task domain. Apply proactively.
32
- 2. **Check for checkpoint** — If `.opencastle/SESSION-CHECKPOINT.md` exists, read it. Resume from last known state instead of re-analyzing.
33
- 3. **Check pending approvals** — If the checkpoint has a `## Pending Approvals` section, check for replies using the configured messaging provider's MCP tools (e.g., `conversations_replies` for Slack). Read `.opencastle.json` → `stack.teamTools` to determine the provider. If no messaging is configured, skip this step.
34
- 4. **Check dead letter queue** — Scan `.opencastle/AGENT-FAILURES.md` for pending failures related to the current scope.
35
- 5. **Validate skill-matrix bindings** — Open `.opencastle/agents/skill-matrix.json` and check whether the `bindings` object has any slots with non-empty `entries` arrays. If all entries are empty, **warn the user** that the bootstrap hasn't been run and capability slots will not resolve. Suggest running the *"Bootstrap Customizations"* prompt first. Do NOT silently continue with empty bindings.
36
- 6. **Check project context** — If `.opencastle/project.instructions.md` has only empty template rows (`| | | |`), warn the user that bootstrap hasn't populated project context.
37
- 7. **Load domain skills** — Based on the task description, load the appropriate skills before writing code. Don't start coding without the relevant skill loaded.
38
-
39
- ### Template for Delegation Prompts
18
+ ## on-session-start — First action in any session
40
19
 
41
- Include this reminder in every delegation:
20
+ | # | Action | Detail |
21
+ |---|--------|--------|
22
+ | 1 | Read lessons | Scan `.opencastle/LESSONS-LEARNED.md` for task-relevant entries. |
23
+ | 2 | Check checkpoint | If `.opencastle/SESSION-CHECKPOINT.md` exists, resume from it. |
24
+ | 3 | Check pending approvals | If checkpoint has `## Pending Approvals`, check replies via messaging provider (`stack.teamTools` in `.opencastle.json`). Skip if no messaging configured. |
25
+ | 4 | Check DLQ | Scan `.opencastle/AGENT-FAILURES.md` for failures in current scope. |
26
+ | 5 | Validate skill-matrix | Open `.opencastle/agents/skill-matrix.json` — if all `bindings` entries are empty, **warn** user to run *"Bootstrap Customizations"* prompt first. |
27
+ | 6 | Check project context | If `.opencastle/project.instructions.md` has only empty template rows, warn bootstrap hasn't run. |
28
+ | 7 | Load domain skills | Load appropriate skills before writing code. |
42
29
 
30
+ **Delegation reminder:**
43
31
  ```
44
- **Session Start:** Read `.opencastle/LESSONS-LEARNED.md` before starting.
45
- Check `.opencastle/SESSION-CHECKPOINT.md` for prior state and pending approvals.
46
- If pending approvals exist, check for replies via the messaging provider.
47
- Validate `.opencastle/agents/skill-matrix.json` — warn if skill bindings are empty (bootstrap not run).
48
- Load relevant skills before writing code.
32
+ Session Start: Read `.opencastle/LESSONS-LEARNED.md`. Check `.opencastle/SESSION-CHECKPOINT.md` for prior state and pending approvals. Validate `.opencastle/agents/skill-matrix.json` — warn if bindings empty. Load relevant skills before coding.
49
33
  ```
50
34
 
51
35
  ---
52
36
 
53
- ## Hook: on-session-end
37
+ ## on-session-end — Before yielding control, every time unconditionally
54
38
 
55
- **When:** Before the agent yields control back to the user every time, unconditionally.
39
+ > **⛔ HARD GATE** See [logging-mandatory](../../snippets/logging-mandatory.md). Run the Pre-Response Quality Gate from the **observability-logging** skill.
56
40
 
57
- > **⛔ HARD GATE Run the Pre-Response Quality Gate checklist from the **observability-logging** skill before responding.**
58
- > A session without log records is a failed session. A session without lessons captured after retries is a failed session.
59
-
60
- ### Actions
61
-
62
- 1. **Call Session Guard** (Team Lead only) Delegate to the **Session Guard** agent with a session summary (delegations, retries, discoveries, files changed). Execute any fix commands it returns. This replaces the manual Pre-Response Quality Gate checklist — the guard runs it automatically with a fresh context window.
63
- 2. **For specialist agents** (not Team Lead) Run the Pre-Response Quality Gate checklist from the **observability-logging** skill manually. Specialist agents don't have access to the Session Guard.
64
- 3. **Save checkpoint** (Team Lead only) — If work is incomplete, write `.opencastle/SESSION-CHECKPOINT.md` with current state so the next session can resume. Load **session-checkpoints** skill for format.
65
- 4. **Memory merge check** — If `LESSONS-LEARNED.md` has grown significantly (5+ new entries this session), flag for memory merge consideration.
66
- 5. **Clean up** — Remove any temporary files created during the session (e.g., test fixtures, debug outputs).
67
-
68
- ### Template for Delegation Prompts
41
+ | # | Action | Who |
42
+ |---|--------|-----|
43
+ | 1 | Call Session Guard with session summary; execute fix commands it returns | Team Lead only |
44
+ | 2 | Run Pre-Response Quality Gate checklist from **observability-logging** skill | Specialists only |
45
+ | 3 | Write `.opencastle/SESSION-CHECKPOINT.md` if work is incomplete (load **session-checkpoints** skill) | Team Lead only |
46
+ | 4 | Flag for memory merge if 5+ new lessons this session | All |
47
+ | 5 | Remove temp files created during session | All |
69
48
 
49
+ **Delegation reminder (specialists):**
70
50
  ```
71
- **Session End:** Run the Pre-Response Quality Gate from the **observability-logging** skill:
72
- - Log your session using the observability-logging skill's session record command (Constitution rule #6)
73
- - If you retried anything with a different approach that worked, use the **self-improvement** skill to add a lesson
74
- - Track any discovered issues in KNOWN-ISSUES.md or a tracker ticket
75
- - Clean up temp files
51
+ Session End: Log session via observability-logging skill (Constitution rule #6). Add lesson via self-improvement if retried. Track discovered issues in KNOWN-ISSUES.md or tracker. Clean up temp files.
76
52
  ```
77
53
 
78
- > **Note for Team Lead:** You do NOT use this template yourself. Instead, call the **Session Guard** agent (step 10 in your role). This template is only for specialist agents you delegate to.
79
-
80
- ---
81
-
82
- ## Hook: on-pre-delegate
83
-
84
- **When:** Team Lead only — before every delegation (sub-agent or background agent).
85
-
86
- Run the 5-point Pre-Delegation Checks from the Team Lead agent file: (1) Tracker issue exists, (2) File partition clean, (3) Dependencies verified Done, (4) Prompt has file paths + acceptance criteria, (5) Self-improvement reminder included. For complex tasks (5+ files), also generate a context map.
87
-
88
54
  ---
89
55
 
90
- ## Hook: on-post-delegate
91
-
92
- **When:** Team Lead only — after receiving results from a delegated agent.
56
+ ## on-pre-delegate — Team Lead only, before every delegation
93
57
 
94
- ### Actions
58
+ Run the 5-point Pre-Delegation Checks from the Team Lead agent file: (1) Tracker issue exists, (2) File partition clean, (3) Dependencies verified Done, (4) Prompt has file paths + acceptance criteria, (5) Self-improvement reminder included. For 5+ files, generate a context map.
95
59
 
96
- 0. **Log the delegation (⛔ hard gate)** Use the **observability-logging** skill's delegation record command. Do NOT proceed to review or any other action until the delegation is logged and verified.
97
- 1. **Fast review (mandatory)** — Run the `fast-review` skill against the agent's output. This is a **non-skippable gate**. See the fast-review skill for the full procedure (single reviewer sub-agent, automatic retry, escalation). **Log the review (⛔ hard gate)** using the **observability-logging** skill's review record command immediately after — do NOT proceed until logged. Only after both the fast review passes and the review is logged do you proceed to the remaining post-delegate actions below.
98
- 2. **Verify output** — Read changed files. Check that changes stay within the agent's file partition.
99
- 2. **Run verification** — Execute appropriate checks: lint, type-check, tests, or visual inspection.
100
- 3. **Check acceptance criteria** — Compare output against the tracker issue's acceptance criteria. Each criterion must be independently verified.
101
- 4. **Discovered issues tracked** — Verify the agent followed the Discovered Issues Policy. If they found issues, check that they're in KNOWN-ISSUES.md or a new tracker ticket.
102
- 5. **Lessons captured** — If the agent retried anything, verify a lesson was added via the **self-improvement** skill.
103
- 6. **Update tracker** — Move the issue to Done (if passing) or add failure notes and re-delegate (if failing). On 3rd failure → log to `.opencastle/AGENT-FAILURES.md` (DLQ format in file header).
104
- 7. **Update agent expertise** — In `.opencastle/AGENT-EXPERTISE.md`: first-attempt success → add strong area; 2+ retries → add weak area. Update file familiarity with touched files.
105
- 8. **Append knowledge graph** — Add file-to-file relationships the agent touched to `.opencastle/KNOWLEDGE-GRAPH.md` (one row per dependency discovered).
60
+ ## on-post-delegateTeam Lead only, after receiving delegation results
106
61
 
107
- ### Quick Checklist
62
+ | # | Action |
63
+ |---|--------|
64
+ | 0 | **⛔ Log delegation** via observability-logging skill — BLOCKING |
65
+ | 1 | **Fast review (mandatory)** — run `fast-review` skill; **⛔ log review** — BLOCKING. Escalate to panel if needed; **⛔ log panel** — BLOCKING |
66
+ | 2 | Read changed files; verify within file partition |
67
+ | 3 | Run lint, type-check, tests |
68
+ | 4 | Verify each acceptance criterion against tracker issue |
69
+ | 5 | Confirm Discovered Issues Policy followed (KNOWN-ISSUES.md or tracker ticket) |
70
+ | 6 | If agent retried, verify lesson added via **self-improvement** skill |
71
+ | 7 | Move issue to Done or re-delegate; on 3rd failure → log to `.opencastle/AGENT-FAILURES.md` |
72
+ | 8 | Update `.opencastle/AGENT-EXPERTISE.md` (strong/weak area + file familiarity) |
73
+ | 9 | Append file relationships to `.opencastle/KNOWLEDGE-GRAPH.md` |
108
74
 
75
+ **Quick checklist:**
109
76
  ```
110
- Post-Delegate:
111
- Delegation logged (observability-logging skill — verify with tail -1) — BLOCKING
112
- ☐ Changed files reviewed
113
- ☐ Files within partition
77
+ ☐ ⛔ Delegation logged (verify: tail -1 events.ndjson) — BLOCKING
78
+ Changed files reviewed; within partition
114
79
  ☐ Lint/test/build passes
115
- ☐ Fast review PASS (mandatory load fast-review skill)
116
- ☐ ⛔ Review logged (observability-logging skillverify with tail -1) — BLOCKING
117
- ☐ ⛔ Panel logged if escalated (observability-logging skill — verify with tail -1) — BLOCKING
80
+ ☐ Fast review PASS; Review logged BLOCKING
81
+ ☐ ⛔ Panel logged if escalated — BLOCKING
118
82
  ☐ Acceptance criteria met
119
- ☐ Discovered issues tracked (not ignored)
120
- ☐ Lessons captured (if retries occurred)
83
+ ☐ Discovered issues tracked
84
+ ☐ Lessons captured (if retries)
121
85
  ☐ Issue updated
122
- Agent expertise updated (AGENT-EXPERTISE.md — strong/weak area + file familiarity)
123
- Knowledge graph appended (KNOWLEDGE-GRAPH.md — file relationships)
86
+ ☐ AGENT-EXPERTISE.md updated
87
+ ☐ KNOWLEDGE-GRAPH.md appended
124
88
  ```
125
89
 
126
90
  ---
127
91
 
128
- ## Hook Integration
129
-
130
- ### For Team Lead
131
-
132
- The on-pre-delegate and on-post-delegate hooks are already encoded in the Team Lead's orchestration workflow. Reference this skill to ensure consistency.
133
-
134
- ### For Specialist Agents
135
-
136
- Include on-session-start and on-session-end actions in every delegation prompt. Use the templates above.
137
-
138
- ### For Workflow Templates
139
-
140
- Each workflow's **Delivery phase** naturally serves as the on-session-end hook for that workflow type. The Delivery phase steps should include session logging, lesson verification, and memory merge checks.
141
-
142
- ---
143
-
144
92
  ## Anti-Patterns
145
93
 
146
- - **Skipping on-session-start** Leads to repeated mistakes already documented in lessons learned
147
- - **Forgetting session logging** — Makes the observability dashboard empty and performance tracking impossible. This is the #1 most common failure.
148
- - **Treating logging as optional** Every session gets logged. No threshold, no exceptions.
149
- - **Batch-logging retrospectively** Log each task as it completes, not all at once at the end of a long conversation.
150
- - **Partial post-delegate checks** "It compiled, ship it" without checking acceptance criteria
151
- - **No cleanup** Temp files accumulate and confuse future sessions
152
- - **Hooks as blockers** Hooks should add ~2 minutes overhead, not 20. If a hook takes too long, skip the optional parts
94
+ | Anti-pattern | Why it matters |
95
+ |---|---|
96
+ | Skipping on-session-start | Repeated mistakes already in lessons learned |
97
+ | Forgetting session logging | Observability dashboard empty; #1 most common failure |
98
+ | Treating logging as optional | Every session logged no threshold, no exceptions |
99
+ | Batch-logging retrospectively | Log each task as it completes, not all at end |
100
+ | Partial post-delegate checks | Must verify acceptance criteria, not just "it compiled" |
101
+ | No cleanup | Temp files accumulate and confuse future sessions |
102
+ | Hooks as blockers | Hooks add ~2 min overhead — skip optional parts if needed |
@@ -3,19 +3,11 @@ name: agent-memory
3
3
  description: "Agent expertise tracking and cross-session knowledge graph. Use when delegating tasks to track agent strengths/weaknesses, or when building context about file relationships and patterns."
4
4
  ---
5
5
 
6
- <!-- ⚠️ This file is managed by OpenCastle. Edits will be overwritten on update. Customize in the .opencastle/ directory instead. -->
7
-
8
6
  # Agent Memory Protocol
9
7
 
10
- ## Purpose
11
-
12
- Track which agents have expertise with which files, patterns, and tools across sessions. This information helps the Team Lead make better delegation decisions by matching tasks to agents with proven track records.
13
-
14
8
  ## Expertise File
15
9
 
16
- Location: `.opencastle/AGENT-EXPERTISE.md` — a structured record of agent performance per domain.
17
-
18
- Template structure:
10
+ **Location:** `.opencastle/AGENT-EXPERTISE.md`
19
11
 
20
12
  ```markdown
21
13
  # Agent Expertise Registry
@@ -24,123 +16,82 @@ Template structure:
24
16
  ### Strong Areas
25
17
  | Area | Evidence | Last Updated |
26
18
  |------|----------|-------------|
27
- | Feature implementation | Successfully built 5 pages (TAS-XX, TAS-YY) | YYYY-MM-DD |
28
- | Server-side logic | Fixed auth flow (TAS-ZZ) | YYYY-MM-DD |
19
+ | Feature implementation | Built 5 pages (TAS-XX, TAS-YY) | YYYY-MM-DD |
29
20
 
30
21
  ### Weak Areas
31
22
  | Area | Evidence | Last Updated |
32
23
  |------|----------|-------------|
33
- | Styling approach | Required 2 retries on styling task (TAS-AA) | YYYY-MM-DD |
24
+ | Styling | 2 retries on TAS-AA | YYYY-MM-DD |
34
25
 
35
26
  ### File Familiarity
36
- - `apps/web-app/places/` — 3 tasks completed
37
- - `libs/queries/src/lib/` — 2 tasks completed
27
+ - `apps/web-app/places/` — 3 tasks
38
28
  ```
39
29
 
40
- ## Memory Update Triggers
30
+ ## Update Triggers
41
31
 
42
32
  | Trigger | Action |
43
33
  |---------|--------|
44
- | Agent completes task successfully on first attempt | Add/update Strong Area entry |
45
- | Agent requires 2+ retries | Add/update Weak Area entry |
46
- | Agent modifies a file | Update File Familiarity count |
47
- | Agent fails a task entirely (DLQ) | Add Weak Area with failure reference |
48
- | >3 months since last update in an area | Mark as "stale" — needs re-evaluation |
49
-
50
- ## Memory Retrieval Protocol
51
-
52
- 1. Before delegating, check `.opencastle/AGENT-EXPERTISE.md` for the candidate agent
53
- 2. If the task matches a Strong Area, include in the prompt: *"You have prior experience with [area] from [TAS-XX]. Apply the same patterns."*
54
- 3. If the task matches a Weak Area, either: (a) add extra context to the prompt to compensate, or (b) consider a different agent
55
- 4. If the file has high familiarity, mention it: *"You've worked on [file] before in [TAS-XX]."*
56
-
57
- ## Memory Pruning Rules
58
-
59
- - Remove entries older than 6 months without recent updates
60
- - Consolidate similar entries (e.g., 5 "App Router pages" entries → 1 entry with count)
61
- - Remove File Familiarity entries for files that no longer exist
62
- - The Team Lead should prune at the start of major feature work (not every session)
34
+ | First-attempt success | Add/update Strong Area |
35
+ | 2+ retries | Add/update Weak Area |
36
+ | File modified | Increment File Familiarity |
37
+ | DLQ failure | Add Weak Area with ref |
38
+ | >3 months stale | Mark as "stale" |
63
39
 
64
- ## Integration with Delegation
40
+ ## Retrieval & Delegation
65
41
 
66
- Add relevant expertise context to delegation prompts. Example addition:
42
+ Check `.opencastle/AGENT-EXPERTISE.md` before delegating. Add to prompt:
67
43
 
68
44
  ```
69
- ### Agent Context (from expertise registry)
70
- - Strong: Server Components, CMS queries (3 successful tasks)
71
- - Weak: Component styling (1 retry on TAS-AA)
72
- - Familiar files: libs/queries/src/lib/search/ (2 tasks)
45
+ ### Agent Context
46
+ - Strong: Server Components, CMS queries (3 tasks) → "Prior experience from TAS-XX."
47
+ - Weak: Component styling (retry TAS-AA) → add context or reassign
48
+ - Familiar: libs/queries/src/lib/search/ (2 tasks) → "You've worked on [file] in TAS-XX."
73
49
  ```
74
50
 
75
- ## Cross-Session Knowledge Graph
51
+ ## Pruning
76
52
 
77
- ### Purpose
53
+ - Remove entries >6 months old; consolidate repetitive entries; remove familiarity for deleted files
54
+ - Prune at start of major feature work
78
55
 
79
- Capture structured relationships between concepts, files, agents, and decisions. Goes beyond flat lesson lists to show how pieces of the system connect.
56
+ ## Knowledge Graph
80
57
 
81
- ### Entity Types
58
+ **Location:** `.opencastle/KNOWLEDGE-GRAPH.md` (append-only)
82
59
 
83
- | Entity Type | Examples | Notation |
84
- |-------------|----------|----------|
85
- | `File` | `libs/queries/src/lib/search/searchModule.ts` | `F:path` |
86
- | `Agent` | Developer, Security Expert | `A:name` |
87
- | `Pattern` | Server Component data fetching, RLS policy structure | `P:name` |
88
- | `Decision` | "Use Jotai over Redux" (from DECISIONS.md) | `D:name` |
89
- | `Bug` | Known issue KI-XXX | `B:id` |
90
- | `Lesson` | LES-XXX from LESSONS-LEARNED.md | `L:id` |
60
+ ### Entities & Relationships
91
61
 
92
- ### Relationship Types
62
+ | Entity | Notation | Relationships |
63
+ |--------|----------|--------------|
64
+ | File | `F:path` | `depends-on`, `blocks` |
65
+ | Agent | `A:name` | `expert-in` |
66
+ | Pattern/Decision | `P:name` / `D:name` | `related-to`, `obsoletes` |
67
+ | Bug/Lesson | `B:id` / `L:id` | `caused-by`, `related-to` |
93
68
 
94
- | Relationship | Meaning | Example |
95
- |-------------|---------|---------|
96
- | `depends-on` | X requires Y to function | `F:places/page.tsx depends-on F:searchModule.ts` |
97
- | `caused-by` | X was caused by Y | `B:KI-042 caused-by D:use-server-components` |
98
- | `expert-in` | Agent X has expertise in Y | `A:Content Engineer expert-in P:CMS-queries` |
99
- | `related-to` | Loose conceptual connection | `L:LES-15 related-to P:RLS-policies` |
100
- | `obsoletes` | X replaces/supersedes Y | `D:use-app-router obsoletes D:use-pages-router` |
101
- | `blocks` | X prevents Y from working | `B:KI-099 blocks F:auth/middleware.ts` |
102
-
103
- ### Knowledge Graph File
104
-
105
- Location: `.opencastle/KNOWLEDGE-GRAPH.md` — an append-only relationship log.
106
-
107
- Template structure:
69
+ ### Graph Template
108
70
 
109
71
  ```markdown
110
72
  # Knowledge Graph
111
-
112
73
  ## Relationships
113
-
114
74
  | Source | Relationship | Target | Added | Context |
115
75
  |--------|-------------|--------|-------|---------|
116
- | A:Content Engineer | expert-in | P:CMS-queries | 2026-02-23 | Completed 3 CMS query tasks |
117
- | F:searchModule.ts | depends-on | F:cms-client.ts | 2026-02-23 | Search uses CMS client |
118
- | L:LES-15 | related-to | P:cookie-sessions | 2026-02-23 | Lesson about auth token format |
76
+ | A:Content Engineer | expert-in | P:CMS-queries | 2026-02-23 | 3 tasks |
77
+ | F:searchModule.ts | depends-on | F:cms-client.ts | 2026-02-23 | |
119
78
  ```
120
79
 
121
- ### When to Add Relationships
122
-
123
- | Trigger | What to Record |
124
- |---------|---------------|
125
- | Agent completes a task touching multiple files | `depends-on` between the files |
126
- | A lesson is added that relates to a pattern | `related-to` between lesson and pattern |
127
- | An agent demonstrates expertise | `expert-in` between agent and domain |
128
- | A decision causes a known issue | `caused-by` between bug and decision |
129
- | A new pattern supersedes an old approach | `obsoletes` between decisions/patterns |
80
+ ### Add Relationships When
130
81
 
131
- ### Query Patterns
82
+ | Trigger | Record |
83
+ |---------|--------|
84
+ | Task touches multiple files | `depends-on` |
85
+ | Lesson relates to a pattern | `related-to` |
86
+ | Agent demonstrates expertise | `expert-in` |
87
+ | Decision causes known issue | `caused-by` |
88
+ | Pattern supersedes old approach | `obsoletes` |
132
89
 
133
- When gathering context for a delegation:
90
+ ### Pre-Delegation Queries
134
91
 
135
- 1. Find the target file(s) in the graph
136
- 2. Follow `depends-on` edges to identify related files the agent might need to read
137
- 3. Follow `expert-in` edges to confirm the right agent is assigned
138
- 4. Follow `related-to` edges from relevant lessons to discover applicable patterns
139
- 5. Check for `blocks` edges that might indicate known issues affecting the task
92
+ Follow `depends-on` for related reads, `expert-in` to confirm agent, `related-to` for patterns, `blocks` for known issues.
140
93
 
141
- ### Maintenance Rules
94
+ ### Maintenance
142
95
 
143
- - Add relationships as you discover them — don't batch
144
- - Review and prune at the start of major features (remove obsolete relationships)
145
- - Keep the graph focused — max ~100 active relationships. Archive old ones quarterly
146
- - Relationships are append-only during a session; pruning happens between sessions
96
+ - Add as discovered; prune between sessions
97
+ - Max ~100 active relationships; archive quarterly
@@ -3,19 +3,17 @@ name: api-patterns
3
3
  description: "API design patterns for route handlers, Server Actions, Zod validation, and external API integration. Use when creating API routes, Server Actions, or integrating external services."
4
4
  ---
5
5
 
6
- <!-- ⚠️ This file is managed by OpenCastle. Edits will be overwritten on update. Customize in the .opencastle/ directory instead. -->
7
-
8
6
  # API Patterns
9
7
 
10
- Generic API design patterns for server-rendered framework projects. For project-specific endpoints, actions, and external API inventory, see [api-config.md](../../.opencastle/stack/api-config.md).
8
+ Project-specific config: [api-config.md](../../.opencastle/stack/api-config.md).
11
9
 
12
10
  ## Architecture
13
11
 
14
- This project uses **App Router** API patterns (resolve the specific framework via the **framework** capability slot in the skill matrix):
15
-
16
- - **Server Actions** (preferred for mutations) form submissions, data writes, auth operations
17
- - **Route Handlers** (`route.ts`) analytics endpoints, autocomplete, external integrations
18
- - **Proxy layer** IP rate limiting, fingerprinting, bot detection
12
+ | Layer | Use for |
13
+ |-------|---------|
14
+ | **Server Actions** (preferred) | mutations, form submissions, data writes, auth |
15
+ | **Route Handlers** (`route.ts`) | analytics, autocomplete, external integrations |
16
+ | **Proxy layer** | IP rate limiting, fingerprinting, bot detection |
19
17
 
20
18
  ## Code Patterns
21
19
 
@@ -25,16 +23,11 @@ This project uses **App Router** API patterns (resolve the specific framework vi
25
23
  // app/api/example/route.ts
26
24
  import { NextRequest, NextResponse } from 'next/server';
27
25
  import { z } from 'zod';
28
-
29
26
  const schema = z.object({ query: z.string().min(1).max(200) });
30
27
 
31
28
  export async function GET(request: NextRequest) {
32
- const params = Object.fromEntries(request.nextUrl.searchParams);
33
- const result = schema.safeParse(params);
34
- if (!result.success) {
35
- return NextResponse.json({ error: 'Invalid input' }, { status: 400 });
36
- }
37
- // ... process
29
+ const result = schema.safeParse(Object.fromEntries(request.nextUrl.searchParams));
30
+ if (!result.success) return NextResponse.json({ error: 'Invalid input' }, { status: 400 });
38
31
  return NextResponse.json(data);
39
32
  }
40
33
  ```
@@ -47,62 +40,21 @@ import { createServerClient } from '@libs/auth';
47
40
  import { revalidatePath } from 'next/cache';
48
41
 
49
42
  export async function submitAction(formData: FormData) {
50
- const client = await createServerClient();
51
- const { data: { user } } = await client.auth.getUser();
43
+ const { data: { user } } = await (await createServerClient()).auth.getUser();
52
44
  if (!user) return { error: 'Unauthorized' };
53
- // ... validate and process
54
45
  revalidatePath('/places');
55
46
  return { success: true };
56
47
  }
57
48
  ```
58
49
 
59
- ## Design Principles
60
-
61
- - Prefer Server Actions for mutations over API routes
62
- - Always validate input with Zod schemas on the server side
63
- - Return appropriate HTTP status codes and error messages
64
- - Protect sensitive routes with middleware or role checks
65
- - Rate limit public endpoints to prevent abuse
66
- - Use Web `Request`/`Response` APIs with `NextRequest`/`NextResponse`
67
- - Use CDN caching headers for public, cacheable responses
68
- - Document new API endpoints in project documentation
69
-
70
- ## API Design Principles
71
-
72
- ### Route Architecture
73
- - RESTful resource naming: `/api/v1/places`, `/api/v1/places/:slug`
74
- - Use HTTP methods correctly: `GET` (read), `POST` (create), `PATCH` (partial update), `DELETE` (remove)
75
- - Group related endpoints under a common prefix
76
- - Keep URLs noun-based, not verb-based (`/api/places` not `/api/getPlaces`)
77
-
78
- ### Request/Response Schemas
79
- - Define Zod schemas for all request bodies, query params, and responses
80
- - Use consistent envelope format for responses:
81
- ```json
82
- { "data": ..., "meta": { "total": 42, "page": 1 } }
83
- ```
84
- - Error responses follow a standard shape:
85
- ```json
86
- { "error": { "code": "VALIDATION_ERROR", "message": "...", "details": [...] } }
87
- ```
88
-
89
- ### Error Handling
90
- - Use appropriate HTTP status codes (400, 401, 403, 404, 422, 429, 500)
91
- - Return machine-readable error codes alongside human-readable messages
92
- - Never leak internal errors — sanitize stack traces in production
93
- - Provide actionable error messages when possible
94
-
95
- ### Pagination & Filtering
96
- - Cursor-based pagination for large datasets (offset-based as fallback)
97
- - Consistent query parameter names: `limit`, `cursor`, `sort`, `order`
98
- - Filter parameters match field names: `?type=brewery&city=prague`
99
-
100
- ### Versioning
101
- - URL-based versioning: `/api/v1/...`
102
- - Never break existing contracts — add fields, never remove or rename
103
- - Deprecation notices in response headers before removal
104
-
105
- ### Rate Limiting & Caching
106
- - Define rate limits per endpoint sensitivity
107
- - Set `Cache-Control` headers appropriate to content freshness
108
- - Use `ETag` / `If-None-Match` for conditional requests where applicable
50
+ ## Design Rules
51
+
52
+ - Server Actions for mutations; Route Handlers for external/public endpoints
53
+ - Validate all input with Zod on the server
54
+ - RESTful nouns: `/api/v1/places/:slug`; HTTP methods: `GET` read, `POST` create, `PATCH` update, `DELETE` remove
55
+ - Response envelope: `{ "data": ..., "meta": { "total": 42, "page": 1 } }`
56
+ - Error shape: `{ "error": { "code": "VALIDATION_ERROR", "message": "...", "details": [...] } }`
57
+ - Status codes: 400, 401, 403, 404, 422, 429, 500 — never leak stack traces
58
+ - Pagination: cursor-based preferred; params: `limit`, `cursor`, `sort`, `order`
59
+ - Versioning: `/api/v1/...`; add fields only, never remove/rename; deprecation headers before removal
60
+ - Rate-limit public endpoints; set `Cache-Control` and `ETag`/`If-None-Match` headers