@nurix/etna 0.1.3 → 0.2.1

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 (30) hide show
  1. package/README.md +35 -26
  2. package/bin/etna.js +82 -56
  3. package/data/harness-index.json +0 -7
  4. package/data/harnesses/code/agents/change-review.md +80 -0
  5. package/data/harnesses/code/agents/contract-monitor.md +65 -0
  6. package/data/harnesses/code/agents/dep-health.md +148 -0
  7. package/data/harnesses/code/agents/git-history.md +201 -0
  8. package/data/harnesses/code/agents/maintenance.md +112 -0
  9. package/data/harnesses/code/agents/review.md +109 -0
  10. package/data/harnesses/code/agents/spec-mode.md +56 -0
  11. package/data/harnesses/code/rules/general.md +96 -0
  12. package/data/harnesses/code/rules/nomenclature.md +34 -0
  13. package/data/harnesses/code/scripts/build-ownership-index.sh +138 -0
  14. package/data/harnesses/code/scripts/check-doc-drift.sh +125 -0
  15. package/data/harnesses/code/skills/documentation/SKILL.md +238 -0
  16. package/data/harnesses/code/skills/documentation/references/examples.md +193 -0
  17. package/data/harnesses/code/skills/documentation/references/style-guide.md +288 -0
  18. package/data/harnesses/code/skills/documentation/references/templates.md +901 -0
  19. package/data/harnesses/code/skills/introspect/SKILL.md +135 -0
  20. package/data/harnesses/code/skills/workflow-mapper/SKILL.md +430 -0
  21. package/data/harnesses/code/skills/workflow-mapper/references/patterns.md +214 -0
  22. package/data/harnesses/kb-agi/agents/kb-agi-init.md +276 -0
  23. package/data/harnesses/kb-agi/agents/kb-catch-stale.md +22 -0
  24. package/data/harnesses/kb-agi/agents/kb-find-gaps.md +27 -0
  25. package/data/harnesses/kb-agi/agents/kb-fix-links.md +22 -0
  26. package/data/harnesses/kb-agi/agents/kb-refresh-frontdoor.md +22 -0
  27. package/data/harnesses/kb-agi/agents/kb-refresh-summaries.md +22 -0
  28. package/data/harnesses/kb-agi/agents/kb-sync-metadata.md +25 -0
  29. package/data/harnesses/kb-agi/rules/kb.md +13 -0
  30. package/package.json +1 -1
@@ -0,0 +1,135 @@
1
+ ---
2
+ name: introspect
3
+ description: Pre-implementation impact analyzer. Reads a plan in docs/history/plans/ and checks every Proposed Change against docs/operations/guardrails.md to surface cascading risks before coding starts. Produces a severity-ranked violation report with suggested plan additions. Read-only. Triggers on "introspect", "check this plan", "impact analysis", "/introspect", "what could break", "guardrail check before I start".
4
+ ---
5
+
6
+ # Introspect Skill
7
+
8
+ Pre-implementation impact analysis. Reads a plan, intersects every proposed change with documented guardrails, and surfaces cascading risk _before_ implementation. The complement to `contract-monitor`, which scans the live codebase _after_ changes land.
9
+
10
+ The skill is read-only. It does not edit the plan, modify code, or write to memory. Output is a report the user reviews and acts on.
11
+
12
+ ---
13
+
14
+ ## When to Use
15
+
16
+ Trigger this skill when:
17
+
18
+ - The user types `/introspect`, "introspect", "check this plan", "impact analysis", "what could break"
19
+ - A plan exists in `docs/history/plans/` and the user is about to start implementation
20
+ - A plan was recently revised and the user wants to re-check guardrail impact
21
+
22
+ Do not run it when:
23
+
24
+ - No `docs/operations/guardrails.md` exists — tell the user to create guardrails first via the documentation skill (`add guardrail`)
25
+ - No plan exists — tell the user to write a plan first (documentation skill, `create plan`)
26
+ - The user wants post-implementation auditing — that's the `contract-monitor` agent
27
+
28
+ ---
29
+
30
+ ## Inputs
31
+
32
+ - **Plan path**: user-provided. If unspecified, use the most recent file in `docs/history/plans/` (sorted by filename date).
33
+ - **Guardrails**: `docs/operations/guardrails.md` is mandatory. Stop if missing.
34
+ - **Source files**: read on demand to verify intersections — never guess from plan text alone.
35
+
36
+ ---
37
+
38
+ ## Workflow
39
+
40
+ ### Phase 1: Load
41
+
42
+ 1. Resolve the plan path. If the user named a feature, glob `docs/history/plans/*{feature}*.md` and pick the newest.
43
+ 2. Read the plan in full.
44
+ 3. Confirm it has a `Status:` field. If `Complete` or `Abandoned`, ask the user whether they want to introspect a frozen plan anyway — it's usually a mistake.
45
+ 4. Read `docs/operations/guardrails.md`. Parse each guardrail section into: name, canonical source location, consumer paths, violation description.
46
+
47
+ ### Phase 2: Parse Proposed Changes
48
+
49
+ The plan template's **Proposed Changes** subsections are load-bearing — introspect relies on their exact structure. Extract content from each:
50
+
51
+ | Subsection | What introspect uses it for |
52
+ |------------|------------------------------|
53
+ | **New Files** | New paths to check against ownership and guardrail consumer paths |
54
+ | **Modified Files** | Existing paths to check against guardrails referencing them |
55
+ | **New Entities / State** | Entity strings, state slices, schema additions — checked against entity-type and schema-mismatch guardrails |
56
+ | **API Changes** | New or modified routes, contracts, request/response shapes — checked against documented contracts |
57
+ | **Cross-Module Contracts Affected** | The plan author's own admission of contracts touched — start here, then verify |
58
+
59
+ If a subsection is missing or empty, note it in the report (the plan may be incomplete) but continue with what's there.
60
+
61
+ ### Phase 3: Analyze
62
+
63
+ For each guardrail × proposed change pair, check intersection:
64
+
65
+ 1. **Path overlap** — does the change touch any file in the guardrail's consumer-paths set?
66
+ 2. **Pattern overlap** — does the change introduce code shapes the guardrail prohibits (raw string literal where a shared constant is required, new entity type not in the canonical array, persisted field without selector fallback)?
67
+ 3. **Contract overlap** — does the change modify the canonical source of a guardrail (the `ENTITY_TYPES` array, the shared constants file, the persistence schema)?
68
+
69
+ Whenever an intersection is plausible from plan text, **read the actual source files** to verify. Never guess from plan text alone.
70
+
71
+ Assign severity:
72
+
73
+ - **Critical** — silent data loss, corrupted persistence, broken cross-entity references
74
+ - **High** — stale state, broken lookups, schema selectors without fallbacks
75
+ - **Medium** — potential mismatch, string-coupling that's likely to drift
76
+ - **Low** — unlikely issue, code smell, easily caught in review
77
+
78
+ ### Phase 4: Report
79
+
80
+ Produce a markdown report:
81
+
82
+ ```
83
+ # Introspect — {plan filename}
84
+
85
+ Plan: {path}
86
+ Guardrails: {N} sections evaluated
87
+ Intersections found: {N} ({critical}/{high}/{medium}/{low})
88
+
89
+ ## Violations
90
+
91
+ | # | Guardrail | Risk | Severity | Plan step |
92
+ |---|-----------|------|----------|-----------|
93
+
94
+ ## Suggested Plan Additions
95
+
96
+ For each violation, a specific recommendation:
97
+
98
+ - **Violation #1**: Add step X to Implementation Steps — {one-line action}
99
+ - **Violation #2**: Add to Done Criteria — {one-line check}
100
+ - **Violation #3**: Update Cross-Module Contracts Affected — {missing entry}
101
+
102
+ ## Missing Subsections
103
+
104
+ {If any Proposed Changes subsection was empty or absent, list it here}
105
+
106
+ ## New Cross-Module Contracts Detected
107
+
108
+ {If the plan introduces a contract not yet in guardrails.md, show a diff-style proposed addition. Ask the user to approve adding it via the documentation skill — never write directly.}
109
+ ```
110
+
111
+ The severity-ranked table is the load-bearing output. Suggestions are advisory — the user decides which to fold back into the plan.
112
+
113
+ ### Phase 5: Hand Off
114
+
115
+ After producing the report:
116
+
117
+ - If the user accepts a suggested plan addition, they edit the plan themselves (or invoke the documentation skill to do it). Introspect never edits plans.
118
+ - If new contracts are detected, suggest invoking the documentation skill with `add guardrail` to formalize them — do not append to `guardrails.md` from this skill.
119
+
120
+ ---
121
+
122
+ ## Rules
123
+
124
+ - **Read-only**. Never edit the plan, source code, guardrails, or memory.
125
+ - **Verify against source**. Never report a violation purely from plan text — read the files the plan claims it will touch.
126
+ - **Plan structure is load-bearing**. If a plan was not written using the documentation skill's plan template, the Proposed Changes subsections may be missing. Note this clearly rather than fabricating intersections.
127
+ - **A clean report is valid**. Plans with no intersections produce an empty violations table — say so, don't pad.
128
+ - **Be specific**. Cite file paths, plan-step numbers, guardrail names, and the exact code shape that breaks the contract.
129
+ - **Don't replicate contract-monitor**. Introspect checks intent (plan text). Contract-monitor checks reality (code). If the user wants to scan live code, route them to contract-monitor.
130
+
131
+ ---
132
+
133
+ ## Output Location
134
+
135
+ The report is returned in the chat — not written to disk. The user reviews it and folds insights back into the plan manually (or via the documentation skill).
@@ -0,0 +1,430 @@
1
+ ---
2
+ name: workflow-mapper
3
+ description: Discover and document all major workflows in a codebase by tracing call chains from user action to database/external system. Produces mermaid sequence diagrams and markdown documentation. Use when the user asks to map workflows, trace flows, document sequences, understand how features work end-to-end, or generate architecture diagrams. Triggers on "map workflows", "trace workflows", "workflow diagram", "sequence diagram", "how does X work end-to-end", "document flows", "codebase workflows", "how does this feature work", "trace the request flow", "show me the call chain", "what happens when a user does X", "end-to-end flow".
4
+ ---
5
+
6
+ # Workflow Mapper Skill
7
+
8
+ Identify and document every major workflow in a codebase by tracing execution paths from trigger to terminal effect. Output is a single markdown file with mermaid sequence diagrams.
9
+
10
+ ---
11
+
12
+ ## Decision Tree
13
+
14
+ ```
15
+ User request
16
+ │
17
+ ├─ "Map all workflows" ────────────▶ Full Discovery (all phases)
18
+ │
19
+ ├─ "Map workflow for {feature}" ───▶ Targeted Discovery (skip Phase 1 broad scan)
20
+ │
21
+ ├─ "Update workflow map" ──────────▶ Incremental (diff against existing map)
22
+ │
23
+ └─ "How does X work end-to-end" ──▶ Single Workflow Trace (Phase 2-4 only)
24
+ ```
25
+
26
+ ---
27
+
28
+ ## Phase 1: Entry Point Discovery
29
+
30
+ Find all places where a multi-step process begins. Use parallel sub-agents — one per technique.
31
+
32
+ ### Technique 1: Route Harvesting
33
+
34
+ Scan all API route definitions. These are the primary entry points for backend workflows.
35
+
36
+ ```
37
+ Search patterns (adapt to framework):
38
+ Express: router.(get|post|put|patch|delete)\(
39
+ Fastify: fastify.(get|post|put|patch|delete)\(
40
+ Next.js: export (async )?function (GET|POST|PUT|PATCH|DELETE)
41
+ Hono: app.(get|post|put|patch|delete)\(
42
+ tRPC: .query\(|.mutation\(
43
+ ```
44
+
45
+ For each route, record: `{ method, path, handler_function, file }`.
46
+
47
+ Filter out trivial CRUD (single DB call + response). Keep routes that:
48
+ - Call `startWorkflow`, `addJob`, `enqueue`, `emit`, `publish` (async dispatch)
49
+ - Call 2+ service functions sequentially
50
+ - Have transaction blocks (`$transaction`, `BEGIN`, `withTransaction`)
51
+ - Return a job/workflow ID for polling
52
+ - Trigger WebSocket/SSE events
53
+
54
+ ### Technique 2: Background Job Discovery
55
+
56
+ Find all registered background jobs, workflows, and queues.
57
+
58
+ ```
59
+ Search patterns:
60
+ Temporal: export async function .*Workflow|workflowModules|startChild\(
61
+ BullMQ: new Queue\(|new Worker\(|.add\(|.process\(
62
+ Celery: @app.task|@shared_task
63
+ Inngest: createFunction\(|inngest.send\(
64
+ Cron: cron.schedule\(|@Cron\(|node-cron
65
+ EventEmitter: .on\(|.emit\(|EventEmitter
66
+ ```
67
+
68
+ For Temporal specifically, also check:
69
+ - `temporal/config/workflowModules.js` — workflow registry with queues and dependencies
70
+ - `temporal/config/activityModules.js` — activity aggregation
71
+
72
+ ### Technique 3: Frontend Action Tracing
73
+
74
+ Find UI-initiated multi-step flows.
75
+
76
+ ```
77
+ Search patterns:
78
+ Redux thunks: createAsyncThunk\(|dispatch\(
79
+ API calls: api\.(post|put|patch|delete)\(|axios\.(post|put|patch|delete)\(|fetch\(
80
+ Form submits: onSubmit|handleSubmit
81
+ Custom hooks: use[A-Z].*\(\) that contain API calls
82
+ ```
83
+
84
+ Focus on actions that:
85
+ - POST/PUT/PATCH/DELETE to backend (not just GETs)
86
+ - Dispatch multiple Redux actions in sequence
87
+ - Start polling loops (`setInterval`, recursive `setTimeout`, retry patterns)
88
+ - Open WebSocket connections or listen for server-sent events
89
+
90
+ ### Technique 4: Event & Message Tracing
91
+
92
+ Find event-driven workflows (WebSocket, pub/sub, SSE).
93
+
94
+ ```
95
+ Search patterns:
96
+ WebSocket: socket.on\(|io.on\(|ws.on\(
97
+ SSE: EventSource|text/event-stream
98
+ Redis pub: .publish\(|.subscribe\(
99
+ Message: .sendMessage\(|.postMessage\(
100
+ ```
101
+
102
+ ### Technique 5: Scheduled & Lifecycle Workflows
103
+
104
+ ```
105
+ Search patterns:
106
+ App startup: app.listen|bootstrap|onModuleInit|main\(\)
107
+ Shutdown: SIGTERM|SIGINT|gracefulShutdown|onModuleDestroy
108
+ Migrations: migrate|seed|up\(\)|down\(\)
109
+ Health checks: /health|/ping|/ready|/live
110
+ ```
111
+
112
+ ---
113
+
114
+ ## Phase 2: Call Chain Tracing
115
+
116
+ For each discovered entry point, trace the full execution path. Use one sub-agent per workflow for parallelism.
117
+
118
+ ### Tracing Algorithm
119
+
120
+ ```
121
+ 1. Start at the entry point function
122
+ 2. Read the function body
123
+ 3. For each function call or await:
124
+ a. Is it a DB operation? → Record as "Database" participant action
125
+ b. Is it an external API call? → Record as "{ServiceName}" participant action
126
+ c. Is it a queue/workflow dispatch? → Record as "{QueueSystem}" participant, then recurse into the dispatched handler
127
+ d. Is it a Redux dispatch? → Record as "Redux" participant action
128
+ e. Is it an internal function in the same service? → Recurse (but cap depth at 4)
129
+ f. Is it a WebSocket emit? → Record as "WebSocket" participant action
130
+ 4. Record branching (if/else, try/catch, switch) as alt/opt blocks
131
+ 5. Record loops (polling, retry, pagination) as loop blocks
132
+ 6. Stop when you hit: a return to the caller, a terminal DB write, or an external system response
133
+ 7. If a workflow trace exceeds the configured depth cap, stop tracing and note the overflow point with a comment like "→ [continues deeper, capped at depth N]". Do not silently truncate.
134
+ ```
135
+
136
+ ### Participant Identification
137
+
138
+ Map code actors to diagram participants using this hierarchy:
139
+
140
+ | Code Pattern | Participant Name |
141
+ |---|---|
142
+ | React component, hook, event handler | `User` + `Frontend` |
143
+ | Express/API route handler | `API` |
144
+ | Temporal workflow | `Temporal` |
145
+ | BullMQ worker/processor | `Queue` |
146
+ | Prisma/Sequelize/Knex call | `Database` |
147
+ | External HTTP call (axios, fetch to external URL) | `{ServiceName}` (derive from URL or config) |
148
+ | Redis operation | `Cache` |
149
+ | WebSocket emit/broadcast | `WebSocket` |
150
+ | File system / S3 / storage | `Storage` |
151
+ | Git API calls | `Git` |
152
+ | Email/SMS send | `Notifications` |
153
+ | Auth provider (Keycloak, Better Auth, Auth0) | `Auth` |
154
+
155
+ ### Branching Detection
156
+
157
+ Look for conditional logic that represents meaningful workflow forks:
158
+
159
+ ```
160
+ - Version conflicts (optimistic locking) → alt block
161
+ - Permission/auth checks → opt block
162
+ - Feature flags → opt block
163
+ - Error handling with different outcomes → alt block
164
+ - Retry with backoff → loop block
165
+ - Polling for completion → loop block
166
+ - Batch processing → loop block
167
+ ```
168
+
169
+ ---
170
+
171
+ ## Phase 3: Classification & Filtering
172
+
173
+ Not every API route is a "workflow". Classify and filter.
174
+
175
+ ### Workflow Categories
176
+
177
+ | Category | Criteria | Include? |
178
+ |---|---|---|
179
+ | **Orchestration** | Multi-step, multi-service, async handoffs (save, publish, deploy) | Always |
180
+ | **Auth & Session** | Login, logout, token refresh, SSO flows | Always |
181
+ | **Real-time** | WebSocket connections, live updates, presence | Always |
182
+ | **Event-driven** | Pub/sub chains, webhook handlers, event sourcing | Always |
183
+ | **Scheduled** | Cron jobs, recurring workflows, cleanup tasks | Always |
184
+ | **Data Pipeline** | ETL, import/export, migration, sync between systems | Always |
185
+ | **Simple CRUD** | Single DB call + response, no branching | Skip |
186
+ | **Static Serving** | File serving, asset delivery | Skip |
187
+ | **Health/Config** | Health checks, config endpoints | Skip |
188
+
189
+ ### Complexity Scoring
190
+
191
+ Score each workflow to determine diagram detail level:
192
+
193
+ - **Steps**: Count distinct operations (DB calls, API calls, dispatches). 1-2 = simple, 3-5 = moderate, 6+ = complex
194
+ - **Participants**: Count distinct systems involved. 2 = simple, 3-4 = moderate, 5+ = complex
195
+ - **Branching**: Count alt/opt blocks. 0 = linear, 1-2 = moderate, 3+ = complex
196
+ - **Async**: Has polling, callbacks, child workflows? +1 complexity level
197
+
198
+ Simple workflows get a compact diagram. Complex workflows get full detail with alt/opt/loop blocks.
199
+
200
+ ---
201
+
202
+ ## Phase 4: Mermaid Diagram Generation
203
+
204
+ ### Diagram Template
205
+
206
+ ````markdown
207
+ ### {Workflow Name}
208
+
209
+ **Trigger:** {What initiates this — button click, API call, cron schedule, event}
210
+ **Participants:** {List of systems involved}
211
+ **Key files:** {3-5 most important files in the chain}
212
+
213
+ ```mermaid
214
+ sequenceDiagram
215
+ participant User
216
+ participant Frontend
217
+ participant API
218
+ participant Database
219
+
220
+ User->>Frontend: {User action}
221
+ Frontend->>API: {HTTP method} {path}
222
+ API->>Database: {Operation}
223
+ Database-->>API: {Result}
224
+ API-->>Frontend: {Response}
225
+ Frontend-->>User: {UI update}
226
+ ```
227
+
228
+ **Notes:**
229
+ - {Important implementation detail not visible in diagram}
230
+ - {Performance consideration, timeout, retry policy}
231
+ - {Known edge cases or failure modes}
232
+ ````
233
+
234
+ ### Diagram Rules
235
+
236
+ 1. **Arrow types**: Solid (`->>`) for calls/requests, dashed (`-->>`) for returns/responses
237
+ 2. **Activation bars**: Use `activate`/`deactivate` only for long-running operations (Temporal workflows, polling loops)
238
+ 3. **Alt blocks**: Use for real workflow branching (conflict vs success), not for error handling
239
+ 4. **Loop blocks**: Use for polling, retry, batch processing — include the condition
240
+ 5. **Opt blocks**: Use for conditional steps (feature flags, optional integrations)
241
+ 6. **Notes**: Use `Note over` for context that doesn't fit in arrow labels
242
+ 7. **Participant order**: Left-to-right follows the data flow direction (User → Frontend → API → Backend → Database)
243
+ 8. **Label brevity**: Arrow labels should be ≤8 words. Use the action, not the implementation detail
244
+ 9. **Max participants**: 7 per diagram. If more, split into sub-diagrams or collapse internal services
245
+ 10. **Max steps**: 15 visible interactions per diagram. For longer workflows, group related steps or use `rect` blocks
246
+
247
+ ### Grouping Related Steps
248
+
249
+ For workflows with many sequential same-type operations, collapse them:
250
+
251
+ ```mermaid
252
+ sequenceDiagram
253
+ rect rgb(240, 240, 240)
254
+ Note over Temporal,Database: Save all entities (10 types)
255
+ Temporal->>Database: Upsert objects, attributes, pages...
256
+ Database-->>Temporal: Saved
257
+ end
258
+ ```
259
+
260
+ ---
261
+
262
+ ## Phase 5: Output Assembly
263
+
264
+ ### Output File Structure
265
+
266
+ Write to the user-specified path, or default to `docs/architecture/workflows.md`. Before writing output files, ensure the target directory exists. Create it with `mkdir -p` if needed.
267
+
268
+ ````markdown
269
+ ---
270
+ generated: {YYYY-MM-DD}
271
+ scope: {full | feature-name}
272
+ workflows_found: {count}
273
+ ---
274
+
275
+ # Codebase Workflows
276
+
277
+ Auto-generated workflow map. Traces execution paths from user action to terminal effect.
278
+
279
+ ## Table of Contents
280
+
281
+ | Workflow | Category | Trigger | Participants | Complexity |
282
+ |---|---|---|---|---|
283
+ | [{Name}](#{anchor}) | {Category} | {Trigger} | {Count} | {Simple/Moderate/Complex} |
284
+
285
+ ---
286
+
287
+ ## Orchestration Workflows
288
+
289
+ ### {Workflow Name}
290
+ {Diagram + metadata as defined in Phase 4}
291
+
292
+ ---
293
+
294
+ ## Authentication & Session Workflows
295
+
296
+ ### {Workflow Name}
297
+ {...}
298
+
299
+ ---
300
+
301
+ ## Real-time Workflows
302
+
303
+ ### {Workflow Name}
304
+ {...}
305
+
306
+ ---
307
+
308
+ ## Event-driven Workflows
309
+
310
+ ### {Workflow Name}
311
+ {...}
312
+
313
+ ---
314
+
315
+ ## Scheduled Workflows
316
+
317
+ ### {Workflow Name}
318
+ {...}
319
+
320
+ ---
321
+
322
+ ## Data Pipeline Workflows
323
+
324
+ ### {Workflow Name}
325
+ {...}
326
+ ````
327
+
328
+ ### Section Ordering
329
+
330
+ 1. Orchestration (the core business logic — save, publish, deploy)
331
+ 2. Authentication & Session
332
+ 3. Real-time (WebSocket, SSE)
333
+ 4. Event-driven (pub/sub, webhooks)
334
+ 5. Scheduled (cron, recurring)
335
+ 6. Data Pipeline (import/export, sync, migration)
336
+
337
+ Skip empty sections.
338
+
339
+ ---
340
+
341
+ ## Execution Strategy
342
+
343
+ ### Full Discovery (default)
344
+
345
+ Launch 5 parallel sub-agents for Phase 1 (one per technique). Collect results, deduplicate entry points, then launch parallel sub-agents for Phase 2 (one per workflow, max 8 concurrent). Run Phase 3-5 sequentially in the main agent.
346
+
347
+ ### Targeted Discovery
348
+
349
+ User specifies a feature name. Skip broad Phase 1 scan. Instead:
350
+ 1. Find the feature's directory/files (grep for feature name in routes, components, workflows)
351
+ 2. Trace from those entry points only
352
+ 3. Output a single-feature workflow document
353
+
354
+ ### Incremental Update
355
+
356
+ Read the existing workflow map file. For each workflow listed, check if the key files have changed (git diff). Re-trace only changed workflows. Preserve unchanged sections.
357
+
358
+ ---
359
+
360
+ ## Advanced Techniques
361
+
362
+ ### Payload Storage Detection
363
+
364
+ Look for patterns where large payloads are stored separately and referenced by ID:
365
+ ```
366
+ storePayload|savePayload|workflow_payload|jobData
367
+ → then: retrievePayload|fetchPayload|getPayload (in the worker/activity)
368
+ ```
369
+ Note this in the diagram as a "Store payload → reference by ID" pattern.
370
+
371
+ ### Optimistic Locking Detection
372
+
373
+ Look for version comparison patterns:
374
+ ```
375
+ version.*!==|version.*conflict|StaleObjectError|OptimisticLock
376
+ if.*serverVersion.*localVersion|if.*version.*mismatch
377
+ ```
378
+ These indicate conflict branching that should appear as `alt` blocks.
379
+
380
+ ### Polling Loop Detection
381
+
382
+ Look for patterns where the frontend waits for async completion:
383
+ ```
384
+ setInterval|setTimeout.*recursive|poll|retry.*status
385
+ GET.*status\?.*workflowId|GET.*status\?.*jobId
386
+ ```
387
+ Note the polling interval and timeout in the diagram.
388
+
389
+ ### Child Workflow / Sub-job Detection
390
+
391
+ Look for spawned sub-processes:
392
+ ```
393
+ startChild\(|spawnChild|fork\(|.add\(.*queue
394
+ Promise\.all.*map.*startWorkflow
395
+ ```
396
+ These should appear as nested sequences or separate linked diagrams.
397
+
398
+ ### Transaction Boundary Detection
399
+
400
+ Look for explicit transaction markers:
401
+ ```
402
+ \$transaction|\$executeRaw|BEGIN|COMMIT|ROLLBACK
403
+ withTransaction|runInTransaction|atomic
404
+ ```
405
+ Group operations within a transaction using `rect` blocks in the diagram.
406
+
407
+ ### Rate Limiting & Middleware Detection
408
+
409
+ Look for middleware applied to route groups:
410
+ ```
411
+ rateLimit|rateLimiter|throttle
412
+ authenticate|authorize|requireAuth|requireRole
413
+ validate|validateBody|validateParams
414
+ ```
415
+ Note these as guards in the diagram using `opt` blocks or notes.
416
+
417
+ ---
418
+
419
+ ## Quality Checks
420
+
421
+ Before outputting, verify:
422
+
423
+ - [ ] Every diagram has ≥3 participants (otherwise it's probably too simple to document)
424
+ - [ ] Every diagram has both request and response arrows (no dangling calls)
425
+ - [ ] Participant names are consistent across all diagrams (same DB = same name everywhere)
426
+ - [ ] Alt/opt/loop blocks have clear conditions written in the block label
427
+ - [ ] Key files listed actually exist in the codebase (verify with glob)
428
+ - [ ] No workflow is documented twice under different names
429
+ - [ ] Mermaid syntax is valid (no unclosed blocks, balanced activate/deactivate)
430
+ - [ ] Table of contents anchors match actual heading anchors