@krtclcdy/tersio 2.25.5 → 2.25.7

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 (231) hide show
  1. package/README.md +42 -38
  2. package/dashboard/dist/index.html +15 -15
  3. package/dist/bench/code-out/pfull-0/debounce.js +13 -0
  4. package/dist/bench/code-out/pfull-0/deepClone.js +18 -0
  5. package/dist/bench/code-out/pfull-0/groupBy.js +15 -0
  6. package/dist/bench/code-out/pfull-1/debounce.js +13 -0
  7. package/dist/bench/code-out/pfull-1/deepClone.js +17 -0
  8. package/dist/bench/code-out/pfull-1/groupBy.js +14 -0
  9. package/dist/bench/code-out/pfull-2/debounce.js +13 -0
  10. package/dist/bench/code-out/pfull-2/deepClone.js +18 -0
  11. package/dist/bench/code-out/pfull-2/groupBy.js +15 -0
  12. package/dist/bench/code-out/pfull-3/debounce.js +12 -0
  13. package/dist/bench/code-out/pfull-3/deepClone.js +17 -0
  14. package/dist/bench/code-out/pfull-3/groupBy.js +7 -0
  15. package/dist/bench/code-out/pfull-4/debounce.js +10 -0
  16. package/dist/bench/code-out/pfull-4/deepClone.js +17 -0
  17. package/dist/bench/code-out/pfull-4/groupBy.js +14 -0
  18. package/dist/bench/code-out/plite-0/debounce.js +13 -0
  19. package/dist/bench/code-out/plite-0/deepClone.js +18 -0
  20. package/dist/bench/code-out/plite-0/groupBy.js +15 -0
  21. package/dist/bench/code-out/plite-1/debounce.js +13 -0
  22. package/dist/bench/code-out/plite-1/deepClone.js +17 -0
  23. package/dist/bench/code-out/plite-1/groupBy.js +11 -0
  24. package/dist/bench/code-out/plite-2/debounce.js +12 -0
  25. package/dist/bench/code-out/plite-2/deepClone.js +17 -0
  26. package/dist/bench/code-out/plite-2/groupBy.js +14 -0
  27. package/dist/bench/code-out/plite-3/debounce.js +12 -0
  28. package/dist/bench/code-out/plite-3/deepClone.js +17 -0
  29. package/dist/bench/code-out/plite-3/groupBy.js +14 -0
  30. package/dist/bench/code-out/plite-4/debounce.js +12 -0
  31. package/dist/bench/code-out/plite-4/deepClone.js +17 -0
  32. package/dist/bench/code-out/plite-4/groupBy.js +14 -0
  33. package/dist/bench/code-out/pultra-0/debounce.js +12 -0
  34. package/dist/bench/code-out/pultra-0/deepClone.js +20 -0
  35. package/dist/bench/code-out/pultra-0/groupBy.js +14 -0
  36. package/dist/bench/code-out/pultra-1/debounce.js +10 -0
  37. package/dist/bench/code-out/pultra-1/deepClone.js +17 -0
  38. package/dist/bench/code-out/pultra-1/groupBy.js +7 -0
  39. package/dist/bench/code-out/pultra-2/debounce.js +13 -0
  40. package/dist/bench/code-out/pultra-2/deepClone.js +18 -0
  41. package/dist/bench/code-out/pultra-2/groupBy.js +15 -0
  42. package/dist/bench/code-out/pultra-3/debounce.js +13 -0
  43. package/dist/bench/code-out/pultra-3/deepClone.js +18 -0
  44. package/dist/bench/code-out/pultra-3/groupBy.js +15 -0
  45. package/dist/bench/code-out/pultra-4/debounce.js +13 -0
  46. package/dist/bench/code-out/pultra-4/deepClone.js +18 -0
  47. package/dist/bench/code-out/pultra-4/groupBy.js +15 -0
  48. package/dist/bench/code-out/run-0/debounce.js +12 -0
  49. package/dist/bench/code-out/run-0/deepClone.js +17 -0
  50. package/dist/bench/code-out/run-0/groupBy.js +14 -0
  51. package/dist/bench/code-out/run-1/debounce.js +13 -0
  52. package/dist/bench/code-out/run-1/deepClone.js +15 -0
  53. package/dist/bench/code-out/run-1/groupBy.js +13 -0
  54. package/dist/bench/code-out/run-2/debounce.js +12 -0
  55. package/dist/bench/code-out/run-2/deepClone.js +18 -0
  56. package/dist/bench/code-out/run-2/groupBy.js +13 -0
  57. package/dist/bench/code-out/run-3/debounce.js +12 -0
  58. package/dist/bench/code-out/run-3/deepClone.js +18 -0
  59. package/dist/bench/code-out/run-3/groupBy.js +14 -0
  60. package/dist/bench/code-out/run-4/debounce.js +12 -0
  61. package/dist/bench/code-out/run-4/deepClone.js +16 -0
  62. package/dist/bench/code-out/run-4/groupBy.js +13 -0
  63. package/dist/cli/backups.js +7 -14
  64. package/dist/cli/banner.js +3 -3
  65. package/dist/cli/common.js +29 -13
  66. package/dist/cli/currency.js +1 -1
  67. package/dist/cli/dashboard.js +66 -35
  68. package/dist/cli/doctor-fix.js +204 -19
  69. package/dist/cli/doctor.js +263 -40
  70. package/dist/cli/hosts.js +25 -6
  71. package/dist/cli/install.js +150 -49
  72. package/dist/cli/interactive.js +3 -3
  73. package/dist/cli/manifest.js +109 -9
  74. package/dist/cli/profile.js +13 -8
  75. package/dist/cli/rtk-wiring.js +1 -1
  76. package/dist/cli/settings.js +20 -5
  77. package/dist/cli/uninstall.js +4 -4
  78. package/dist/cli/update.js +6 -7
  79. package/dist/cli/usage.js +6 -9
  80. package/dist/extensions/caveman/index.js +10 -4
  81. package/dist/extensions/caveman/rule-lite.md +77 -0
  82. package/dist/extensions/caveman/rule-megacave-lite.md +59 -0
  83. package/dist/extensions/caveman/rule-megacave-ultra.md +59 -0
  84. package/dist/extensions/caveman/rule-megacave.md +5 -3
  85. package/dist/extensions/caveman/rule-ultra.md +4 -4
  86. package/dist/extensions/caveman/rule.md +55 -45
  87. package/dist/extensions/combo/index.js +85 -25
  88. package/dist/extensions/commands/index.js +1 -1
  89. package/dist/extensions/pstack/index.js +121 -0
  90. package/dist/extensions/pstack/rule.md +141 -0
  91. package/dist/extensions/rtk/filter.js +0 -1
  92. package/dist/extensions/rtk/session.js +20 -12
  93. package/dist/extensions/server.js +90 -6
  94. package/dist/extensions/shared/agent-stats.js +214 -278
  95. package/dist/extensions/shared/brand-marks.js +33 -34
  96. package/dist/extensions/shared/carbon.js +1 -1
  97. package/dist/extensions/shared/plugin-settings.js +11 -6
  98. package/dist/extensions/shared/pricing.js +8 -16
  99. package/dist/extensions/shared/rtk-eligible.js +84 -0
  100. package/dist/extensions/shared/rtk-gain.js +5 -10
  101. package/dist/extensions/shared/session-state.js +15 -10
  102. package/dist/extensions/shared/sqlite.js +162 -0
  103. package/dist/extensions/shared/status.js +8 -9
  104. package/dist/extensions/shared/types.js +1 -1
  105. package/dist/extensions/shared/usage-ledger.js +155 -61
  106. package/dist/extensions/shared/usage-store.js +111 -52
  107. package/dist/extensions/shared/utils.js +5 -5
  108. package/dist/extensions/timing/index.js +31 -0
  109. package/dist/extensions/updater/index.js +3 -6
  110. package/dist/tersio.js +8 -3
  111. package/extensions/caveman/index.ts +10 -4
  112. package/extensions/caveman/rule-lite.md +77 -0
  113. package/extensions/caveman/rule-megacave-lite.md +59 -0
  114. package/extensions/caveman/rule-megacave-ultra.md +59 -0
  115. package/extensions/caveman/rule-megacave.md +5 -3
  116. package/extensions/caveman/rule-ultra.md +4 -4
  117. package/extensions/caveman/rule.md +55 -45
  118. package/extensions/combo/index.ts +86 -23
  119. package/extensions/commands/index.ts +1 -1
  120. package/extensions/pstack/index.ts +130 -0
  121. package/extensions/pstack/playbooks/authoring-a-skill.md +12 -0
  122. package/extensions/pstack/playbooks/autonomous-run.md +13 -0
  123. package/extensions/pstack/playbooks/autopilot-full.md +13 -0
  124. package/extensions/pstack/playbooks/autopilot-stack.md +16 -0
  125. package/extensions/pstack/playbooks/babysit.md +23 -0
  126. package/extensions/pstack/playbooks/bug-fix.md +15 -0
  127. package/extensions/pstack/playbooks/eval.md +25 -0
  128. package/extensions/pstack/playbooks/feature.md +21 -0
  129. package/extensions/pstack/playbooks/hillclimb.md +21 -0
  130. package/extensions/pstack/playbooks/investigation.md +14 -0
  131. package/extensions/pstack/playbooks/multi-phase-plan.md +155 -0
  132. package/extensions/pstack/playbooks/opening-a-pr.md +34 -0
  133. package/extensions/pstack/playbooks/orchestrate.md +111 -0
  134. package/extensions/pstack/playbooks/pause-safely.md +10 -0
  135. package/extensions/pstack/playbooks/perf-issue.md +25 -0
  136. package/extensions/pstack/playbooks/prototype.md +14 -0
  137. package/extensions/pstack/playbooks/refactoring.md +16 -0
  138. package/extensions/pstack/playbooks/runtime-forensics.md +11 -0
  139. package/extensions/pstack/playbooks/session-pickup.md +11 -0
  140. package/extensions/pstack/playbooks/shipping.md +17 -0
  141. package/extensions/pstack/playbooks/trace-forensics.md +14 -0
  142. package/extensions/pstack/playbooks/visual-parity.md +11 -0
  143. package/extensions/pstack/playbooks/worktree-cleanup.md +12 -0
  144. package/extensions/pstack/principles/attack-the-premise.md +22 -0
  145. package/extensions/pstack/principles/boundary-discipline.md +33 -0
  146. package/extensions/pstack/principles/build-the-lever.md +22 -0
  147. package/extensions/pstack/principles/encode-lessons-in-structure.md +10 -0
  148. package/extensions/pstack/principles/exhaust-the-design-space.md +8 -0
  149. package/extensions/pstack/principles/experience-first.md +18 -0
  150. package/extensions/pstack/principles/explain-the-number.md +16 -0
  151. package/extensions/pstack/principles/fix-root-causes.md +23 -0
  152. package/extensions/pstack/principles/foundational-thinking.md +20 -0
  153. package/extensions/pstack/principles/guard-the-context-window.md +11 -0
  154. package/extensions/pstack/principles/laziness-protocol.md +9 -0
  155. package/extensions/pstack/principles/make-operations-idempotent.md +23 -0
  156. package/extensions/pstack/principles/migrate-callers-then-delete-legacy-apis.md +21 -0
  157. package/extensions/pstack/principles/minimize-reader-load.md +17 -0
  158. package/extensions/pstack/principles/model-the-domain.md +23 -0
  159. package/extensions/pstack/principles/never-block-on-the-human.md +14 -0
  160. package/extensions/pstack/principles/outcome-oriented-execution.md +20 -0
  161. package/extensions/pstack/principles/prove-it-works.md +21 -0
  162. package/extensions/pstack/principles/redesign-from-first-principles.md +15 -0
  163. package/extensions/pstack/principles/separate-before-serializing-shared-state.md +15 -0
  164. package/extensions/pstack/principles/sequence-verifiable-units.md +16 -0
  165. package/extensions/pstack/principles/subtract-before-you-add.md +17 -0
  166. package/extensions/pstack/principles/test-behavior-not-implementation.md +20 -0
  167. package/extensions/pstack/principles/type-system-discipline.md +17 -0
  168. package/extensions/pstack/references/bugbot-triage.md +142 -0
  169. package/extensions/pstack/rule.md +141 -0
  170. package/extensions/pstack/skills/architect/SKILL.md +78 -0
  171. package/extensions/pstack/skills/architect/references/design-red-flags.md +57 -0
  172. package/extensions/pstack/skills/architect/references/rationale-template.md +35 -0
  173. package/extensions/pstack/skills/architect/references/runner-prompt.md +20 -0
  174. package/extensions/pstack/skills/arena/SKILL.md +47 -0
  175. package/extensions/pstack/skills/benchmark-checklist/SKILL.md +38 -0
  176. package/extensions/pstack/skills/blast-radius/SKILL.md +49 -0
  177. package/extensions/pstack/skills/bro/SKILL.md +6 -0
  178. package/extensions/pstack/skills/correct/SKILL.md +31 -0
  179. package/extensions/pstack/skills/figure-it-out/SKILL.md +51 -0
  180. package/extensions/pstack/skills/how/SKILL.md +35 -0
  181. package/extensions/pstack/skills/how/references/explainer-prompt.md +55 -0
  182. package/extensions/pstack/skills/how/references/explorer-prompt.md +35 -0
  183. package/extensions/pstack/skills/interrogate/SKILL.md +73 -0
  184. package/extensions/pstack/skills/interrogate/references/code-quality-review.md +47 -0
  185. package/extensions/pstack/skills/interrogate/references/lead-judgment.md +58 -0
  186. package/extensions/pstack/skills/interrogate/references/reviewer-prompt.md +62 -0
  187. package/extensions/pstack/skills/interrogate/references/rubric.md +77 -0
  188. package/extensions/pstack/skills/no-comments/SKILL.md +23 -0
  189. package/extensions/pstack/skills/reflect/SKILL.md +66 -0
  190. package/extensions/pstack/skills/reflect/references/divergent-reviewer.md +38 -0
  191. package/extensions/pstack/skills/reflect/references/judgment-reviewer.md +37 -0
  192. package/extensions/pstack/skills/reflect/references/synthesizer.md +56 -0
  193. package/extensions/pstack/skills/reflect/references/tooling-reviewer.md +48 -0
  194. package/extensions/pstack/skills/show-me-your-work/SKILL.md +81 -0
  195. package/extensions/pstack/skills/swarm/SKILL.md +45 -0
  196. package/extensions/pstack/skills/tdd/SKILL.md +41 -0
  197. package/extensions/pstack/skills/technical-writing/SKILL.md +105 -0
  198. package/extensions/pstack/skills/unslop/SKILL.md +61 -0
  199. package/extensions/pstack/skills/why/SKILL.md +97 -0
  200. package/extensions/pstack/skills/why/references/epistemics.md +71 -0
  201. package/extensions/pstack/skills/why/references/investigator-prompt.md +84 -0
  202. package/extensions/pstack/skills/why/references/source-playbook.md +17 -0
  203. package/extensions/pstack/skills/why/references/sources/code-archaeology.md +51 -0
  204. package/extensions/pstack/skills/why/references/sources/databricks.md +70 -0
  205. package/extensions/pstack/skills/why/references/sources/datadog.md +97 -0
  206. package/extensions/pstack/skills/why/references/sources/incident-postmortem.md +5 -0
  207. package/extensions/pstack/skills/why/references/sources/linear.md +48 -0
  208. package/extensions/pstack/skills/why/references/sources/notion.md +55 -0
  209. package/extensions/pstack/skills/why/references/sources/sentry.md +66 -0
  210. package/extensions/pstack/skills/why/references/sources/slack.md +17 -0
  211. package/extensions/pstack/skills/why/references/synthesizer-prompt.md +129 -0
  212. package/extensions/rtk/filter.ts +0 -1
  213. package/extensions/rtk/session.ts +19 -11
  214. package/extensions/server.ts +72 -7
  215. package/extensions/shared/agent-stats.ts +226 -278
  216. package/extensions/shared/brand-marks.ts +34 -34
  217. package/extensions/shared/carbon.ts +1 -1
  218. package/extensions/shared/plugin-settings.ts +12 -6
  219. package/extensions/shared/pricing.ts +10 -26
  220. package/extensions/shared/rtk-eligible.ts +83 -0
  221. package/extensions/shared/rtk-gain.ts +5 -10
  222. package/extensions/shared/session-state.ts +18 -13
  223. package/extensions/shared/sqlite.ts +162 -0
  224. package/extensions/shared/status.ts +9 -9
  225. package/extensions/shared/types.ts +2 -1
  226. package/extensions/shared/usage-ledger.ts +157 -66
  227. package/extensions/shared/usage-store.ts +120 -52
  228. package/extensions/shared/utils.ts +5 -5
  229. package/extensions/timing/index.ts +44 -0
  230. package/extensions/updater/index.ts +3 -8
  231. package/package.json +21 -9
@@ -0,0 +1,97 @@
1
+ # Datadog Telemetry
2
+
3
+ ## What this source contains
4
+
5
+ Datadog holds the runtime record, what actually happened in production, as opposed to what was planned or discussed.
6
+
7
+ - **Metrics.** Counters, gauges, histograms instrumented by the team. A metric's *presence* is itself evidence that someone thought the number worth watching.
8
+ - **Monitors & alerts.** Conditions the team decided warranted waking someone up. A monitor firing on `rate_limit_hit > 10/min` is direct evidence the team worried about that threshold.
9
+ - **Dashboards.** Curated views of what the team considers important for a subsystem.
10
+ - **APM traces & spans.** Request-level runtime data, for "why is this slow" / "why is there a timeout here" questions.
11
+ - **Logs.** High-volume event records, often holding the error conditions that motivated defensive code.
12
+ - **Incidents.** Formal incident records with timelines and linked postmortems.
13
+ - **Notebooks.** The team's exploratory investigations, often with hypotheses and analyses.
14
+
15
+ ## How to search it
16
+
17
+ Use the Datadog MCP. Start broad, then narrow.
18
+
19
+ 1. **Identify the owning service(s).**
20
+
21
+ ```
22
+ search_datadog_services (filter by name or team)
23
+ search_datadog_service_dependencies (see upstream/downstream)
24
+ ```
25
+
26
+ 2. **Dashboards and monitors first.**
27
+
28
+ ```
29
+ search_datadog_dashboards (query: feature name, service name, symbol)
30
+ search_datadog_monitors (same queries)
31
+ ```
32
+
33
+ When a dashboard or monitor covers the target, note its queries and watched thresholds. The threshold is frequently the answer to "why is this clamped at N?"
34
+
35
+ 3. **Metrics around the target.**
36
+
37
+ ```
38
+ search_datadog_metrics (by name pattern, e.g., the feature or symbol)
39
+ get_datadog_metric_context (metadata: description, units, tags)
40
+ get_datadog_metric (timeseries; "was there a spike around the PR date?")
41
+ ```
42
+
43
+ Correlating a metric's trajectory with the target's add/change date is strong supporting evidence: "the `payment_timeout` metric spiked 2023-11-03, and the retry logic merged 2023-11-06."
44
+
45
+ 4. **Logs. Narrow, don't dump.**
46
+
47
+ ```
48
+ search_datadog_logs (raw log patterns near the target, set use_log_patterns=true)
49
+ analyze_datadog_logs (SQL-style aggregations, only when you need counts)
50
+ ```
51
+
52
+ Search with symbols, error strings, or feature names. **Strongly prefer time-bounded queries** (e.g., 30 days before/after the change).
53
+
54
+ 5. **APM spans and traces.**
55
+
56
+ ```
57
+ aggregate_spans (stats: "how often does this endpoint fail?")
58
+ search_datadog_spans (inspect individual spans)
59
+ get_datadog_trace (a specific trace ID)
60
+ ```
61
+
62
+ Useful for timeouts, retries, slow paths, and cross-service behavior.
63
+
64
+ 6. **Incidents.**
65
+
66
+ ```
67
+ search_datadog_incidents (by title, team, date range)
68
+ get_datadog_incident (full detail for a specific incident)
69
+ ```
70
+
71
+ If the target looks defensive, search for incidents around the time it was added. An incident whose timeline includes "added defensive check for X" is near-direct evidence.
72
+
73
+ ## What good evidence looks like here
74
+
75
+ - A monitor whose query and threshold match the constraint the code enforces (code clamps to 100, monitor alerts when requests exceed 100/min)
76
+ - A dashboard created by the target's author, with widgets that correspond to what the code measures or guards against
77
+ - A metric showing a production spike immediately before the code was merged, and stable values after
78
+ - An incident record referencing the target code, the same symbols, or the same error strings
79
+ - Logs showing a specific error pattern the defensive code would prevent, timestamped in the window before the change
80
+
81
+ ## Common pitfalls
82
+
83
+ - **Correlation is not causation.** A spike before a PR and stabilization after is suggestive, not definitive, since other changes may have landed in the same window. Check neighboring PRs.
84
+ - **Overfitting to the chart you found.** A chart reflects its maker's framing. A chart named "retry success rate" is evidence the team cared about retry success, not that it's why a specific line of code exists.
85
+ - **Vanished telemetry.** Metrics can be renamed, deleted, or have short retention. If you can't find data from the relevant window, that's a gap, not a null result.
86
+ - **Noise at scale.** Narrow log searches by service, tag, and time window aggressively. Use `analyze_datadog_logs` to aggregate rather than dumping raw logs.
87
+ - **Instrumented != caused.** A metric shows someone cared enough to measure something, not that the code was added *because* of it. Cross-reference with commit/PR dates.
88
+
89
+ ## What to return
90
+
91
+ For each relevant item:
92
+ - Type (dashboard / monitor / metric / log pattern / trace / incident / notebook)
93
+ - Title or name
94
+ - Link or identifier (dashboard ID, monitor ID, metric name, incident ID)
95
+ - Owner/author and created/modified date
96
+ - The specific condition, query, or quote that bears on the question (verbatim where possible)
97
+ - Relevance: what this suggests about the target code, and how strong the connection is
@@ -0,0 +1,5 @@
1
+ # Incident & Postmortem Context
2
+
3
+ - **Linear**: look for tickets labeled `incident`, `sev-*`, `postmortem-action-item`, `reliability`
4
+ - **Slack**: search `#sev-*` and `#incident-*` channels around the dates the target code was added
5
+ - **Git**: commits with messages like "fix for incident", "add defensive check", "revert" followed by "re-apply with..." are strong signals
@@ -0,0 +1,48 @@
1
+ # Linear Tickets
2
+
3
+ ## What this source contains
4
+
5
+ - Issues describing features, bugs, and their motivation
6
+ - Project docs attached to issues (often PRDs or specs)
7
+ - Parent/sub-issue relationships (broader initiative → specific tickets)
8
+ - Comments on issues (clarifications, scope changes, "why we're doing this" rationale)
9
+ - Labels (e.g., `compliance`, `customer-request`, `perf`) that signal the type of motivation
10
+ - Status updates that explain scope changes
11
+ - Attachments and linked GitHub PRs
12
+
13
+ Linear is where the product/business context often lives: the "we're doing this because customer X asked" or "this is for the Q3 compliance initiative" layer.
14
+
15
+ ## How to search it
16
+
17
+ Use the Linear MCP.
18
+
19
+ 1. **Start with linked tickets.** If the seed commits or PRs reference ticket IDs (e.g., `ENG-1234`, `[BUG-567]`), fetch those first with `get_issue`. Read the full issue including comments.
20
+ 2. **List related issues by keyword.** Use `list_issues` with text search for the feature name, key symbol, or business term. Try multiple phrasings.
21
+ 3. **Walk the issue tree.** If you land on a sub-issue, fetch its parent. Sub-issues are tactical. Parents often carry the "why."
22
+ 4. **Read project docs.** If the issue belongs to a project, use `get_project` and check attached docs. Project-level documents are where specs and rationale are most often captured.
23
+ 5. **Check labels and milestones.** Labels hint at the category of motivation (customer-request, incident-followup, compliance). Milestones tie work to deadlines, which often reveal motivation.
24
+
25
+ ## What good evidence looks like here
26
+
27
+ - An issue description stating the business problem: "Customer Acme needs X because of their SOC2 audit"
28
+ - A comment recording a decision: "We decided to go with approach B because approach A would require touching the billing service"
29
+ - A parent issue titled like an initiative: "Q3 Enterprise Readiness" or "Reduce Payment Failures"
30
+ - An attached PRD or spec
31
+ - Labels like `customer:acme`, `incident-followup`, `compliance`, `perf-regression`
32
+
33
+ ## Common pitfalls
34
+
35
+ - **Scope drift.** The ticket the PR references may have been closed and reopened with a different scope. Read the whole history.
36
+ - **Mechanical templates.** Some teams require "Why" sections but fill them with boilerplate. Generic text ("improve user experience") is probably not a real answer.
37
+ - **Stale tickets.** Old tickets often reflect a version of the plan that changed. Check dates and cross-reference with the code's ship date.
38
+ - **Closed-as-duplicate chains.** Follow the duplicate-of relationships back to the canonical ticket.
39
+ - **Private workspace content.** If you can't access an issue, note that as a gap rather than guessing.
40
+
41
+ ## What to return
42
+
43
+ For each relevant ticket:
44
+ - Ticket ID and title
45
+ - The problem/motivation quoted from the description or comments (not paraphrased. The synthesizer needs the exact text to cite)
46
+ - Labels, parent issue, project
47
+ - Author, created date, closed date
48
+ - Link to the ticket if available
@@ -0,0 +1,55 @@
1
+ # Notion Docs
2
+
3
+ ## What this source contains
4
+
5
+ - PRDs (product requirement documents)
6
+ - Technical specs and RFCs
7
+ - Architectural decision records (ADRs)
8
+ - Meeting notes from design reviews
9
+ - Team pages with domain context
10
+ - Postmortems from incidents
11
+ - Runbooks that may explain defensive code
12
+ - Strategy documents that set priorities
13
+
14
+ Notion is where "why" often lives in long-form before it becomes code. A significant feature usually has a doc.
15
+
16
+ ## How to search it
17
+
18
+ Use the Notion MCP.
19
+
20
+ 1. **Keyword searches with `notion-search`.** Try:
21
+ - The feature name
22
+ - Key symbols / class names from the target code
23
+ - Author handles (design docs are often authored before the code lands)
24
+ - Error strings or user-visible terms
25
+ - Time-bounded queries if you know when the code shipped
26
+ 2. **Fetch candidate pages with `notion-fetch`.** Read the full content, not the preview. Rationale is often buried mid-document.
27
+ 3. **Follow backlinks and child pages.** Design docs often have sub-pages for alternatives considered, appendices, or implementation notes.
28
+ 4. **Check related databases.** `notion-query-data-sources` and `notion-query-meeting-notes` can surface meeting notes that discussed the decision.
29
+ 5. **Search author-specific spaces.** If the PR author has a personal notebook (common at some companies), it may hold exploratory thinking that preceded the code.
30
+
31
+ ## What good evidence looks like here
32
+
33
+ - A PRD with a "Problem statement" or "Motivation" section that matches the target code's purpose
34
+ - An "Alternatives considered" or "Rejected approaches" section
35
+ - A postmortem that names the target code as the fix for a specific incident
36
+ - Meeting notes that record "we decided X because Y" and tie to the same author/date range as the PR
37
+ - An ADR template filled out non-trivially (status, context, decision, consequences)
38
+
39
+ ## Common pitfalls
40
+
41
+ - **Outdated docs.** Specs are often written before implementation and not updated. The doc may describe a plan that changed. Cross-check against the actual PR.
42
+ - **Doc vs. reality drift.** A spec may say "we'll do X" but the code actually does Y. Flag the divergence. The synthesizer will surface the contradiction.
43
+ - **Boilerplate templates.** Some orgs require a "Why" section that gets filled with fluff. Look for specificity.
44
+ - **Unlinked docs.** The most relevant doc may not be linked from anywhere. Broad keyword searches help.
45
+ - **Multiple drafts.** If a topic has multiple docs, find the one that was finalized or most recently updated. Check dates.
46
+ - **Access-restricted pages.** If you can't access a page, note it as a gap.
47
+
48
+ ## What to return
49
+
50
+ For each relevant doc:
51
+ - Title and URL
52
+ - Authors and last-updated date
53
+ - The motivation text (verbatim quote), with page/section location
54
+ - Relevant linked pages (so the synthesizer can cite them)
55
+ - Whether the doc was finalized or draft
@@ -0,0 +1,66 @@
1
+ # Sentry Error History
2
+
3
+ ## How to search it
4
+
5
+ Use the Sentry MCP.
6
+
7
+ 1. **Orient.** If you don't know the project slug and organization:
8
+
9
+ ```
10
+ find_organizations
11
+ find_projects
12
+ ```
13
+
14
+ 2. **Search for issues related to the target.**
15
+
16
+ ```
17
+ search_issues (natural language, e.g., "errors in PaymentService timeout", "unhandled exceptions in uploadFile")
18
+ ```
19
+
20
+ Build queries from the exception class names the target handles, its function or class name, the error message strings it checks for, and its file path.
21
+
22
+ 3. **Narrow by release and time window.**
23
+
24
+ ```
25
+ search_issue_events (filter by release, time, environment, trace ID, tags)
26
+ get_issue_tag_values (for an issue, see distribution across versions, users, environments)
27
+ ```
28
+
29
+ For a suspected issue, check **first seen** and **last seen** (does the stop line up with the target's ship date?), the **affected releases** (which saw it, and which was the fix?), and the **frequency trajectory** (did it spike, then get resolved?).
30
+
31
+ 4. **Pull the full event for context.**
32
+
33
+ ```
34
+ get_sentry_resource (pass a Sentry URL or type+ID)
35
+ ```
36
+
37
+ Does the stack trace pass through the target code? Do the tags and breadcrumbs match the conditions the target defends against?
38
+
39
+ 5. **Check releases that landed near the target.**
40
+
41
+ ```
42
+ find_releases (around the commit date of the target)
43
+ ```
44
+
45
+ Cross-reference release version with the PR's merge date.
46
+
47
+ 6. **Use Seer sparingly.**
48
+
49
+ ```
50
+ analyze_issue_with_seer
51
+ ```
52
+
53
+ Seer's AI root-cause analyses are a hypothesis generator. Treat them as inference, not authoritative. The actual events and stack traces are the primary evidence.
54
+
55
+ ## What to return
56
+
57
+ For each relevant issue:
58
+ - Issue ID and title
59
+ - Project and organization
60
+ - First seen / last seen timestamps
61
+ - Event count (and sampling rate if known)
62
+ - Affected releases
63
+ - A representative stack trace snippet showing relevance to the target (verbatim excerpt, not summary)
64
+ - First/last-seen correlation with the target's ship date
65
+ - Link to the issue
66
+ - Any author comments or resolution notes
@@ -0,0 +1,17 @@
1
+ # Slack Conversations
2
+
3
+ ## How to search it
4
+
5
+ Slack MCP tools vary. Check which Slack MCP is available and inspect its tool schema first. It may require `mcp_auth`. If authentication fails, stop and report the gap.
6
+
7
+ 1. **Author-bounded search.** Messages from the PR author around the PR merge date. Limits scope dramatically and often hits gold.
8
+ 3. **PR URL search.** Slack often links PRs when they're reviewed or discussed. Search for the PR URL (or just `/pull/<number>`).
9
+ 4. **Error string search.** If the code handles a specific error, search for the error string. Incident threads often surface.
10
+
11
+ ## Common pitfalls
12
+
13
+ - **Channel archaeology limits.** Very old messages may be gone due to retention policies. If you can't find anything before a certain date, note the retention cliff.
14
+ - **Unsearched DMs.** Many decisions happen in DMs that aren't searchable. You'll miss them. That's a known limitation.
15
+ - **Speculative jokes as "decisions."** Slack is casual. "Lol just do the thing" isn't a decision, even if it preceded the commit. Look for considered discussion.
16
+ - **Context collapse in single messages.** Without the thread, a single message often reads differently than in context. Always fetch threads.
17
+ - **Auth failures.** If the MCP isn't authenticated, stop. Don't make up findings. Report that Slack wasn't searchable.
@@ -0,0 +1,129 @@
1
+ # Synthesizer Prompt Template
2
+
3
+ Fill in the placeholders.
4
+
5
+ ---
6
+
7
+ You are answering a "why" question about a piece of code by synthesizing findings from investigators who searched different historical sources (source control, issue / ticket tracker, long-form documents, real-time team chat, infrastructure observability, error / exception tracking, product analytics warehouse, and code comments). Produce a confidence-weighted, evidence-cited narrative that says honestly what the evidence supports, and just as honestly what it doesn't.
8
+
9
+ ## The Question
10
+
11
+ > {QUESTION}
12
+
13
+ ## The Code Anchor
14
+
15
+ **Target files:** {FILES_WITH_LINE_RANGES}
16
+
17
+ **Key symbols:** {SYMBOLS}
18
+
19
+ ## Investigator Findings
20
+
21
+ {ALL_INVESTIGATOR_FINDINGS}
22
+
23
+ ## Sources That Weren't Searched
24
+
25
+ {SKIPPED_SOURCES_WITH_REASONS}
26
+
27
+ ## Epistemics Framework
28
+
29
+ You MUST follow `references/epistemics.md`. Read it in full before writing. The key rules:
30
+
31
+ 1. Every claim must sit in one tier: **Direct**, **Supported**, **Inferred**, **Speculative**, **Unknown**. The tier sets its section and its phrasing.
32
+ 2. Every Direct/Supported claim must have a citation (PR #, ticket ID, doc URL, chat permalink, commit hash, or file:line).
33
+ 3. Inferred and Speculative claims must use hedged language ("appears to", "likely", "suggests", "one possibility is").
34
+ 4. Never cite code as evidence for its own intent.
35
+ 5. Document gaps. Don't fill them with plausible-sounding guesses.
36
+ 6. Treat a hypothesis embedded in the user's question as a candidate, not a conclusion. Check it independently.
37
+
38
+ ## Instructions
39
+
40
+ 1. **Read all investigator findings** and weigh the evidence yourself. Investigators gathered raw evidence, not conclusions.
41
+ 2. **Merge overlaps.** When several investigators cite the same PR, ticket, or doc, give it one authoritative reference.
42
+ 3. **Surface contradictions.** When two items disagree, show both. Don't pick one.
43
+ 4. **Calibrate each claim.** Find its evidence and tier. Direct: cite it and state it plainly. Inferred: hedge it and show the inference. Speculative: mark it. No evidence: put it in the gaps.
44
+ 5. **Verify citations by spot-checking.** If you're uncertain a cited item exists or says what the investigator claims, check it by reading the codebase or calling MCP tools. Don't propagate errors. Do not write files, commit, or modify external state.
45
+ 6. **Don't overreach.** The user will act on this. Leave an open question open rather than fill it with a confident guess.
46
+
47
+ ## Output Format
48
+
49
+ Write for the user, in this exact structure:
50
+
51
+ ---
52
+
53
+ ### The Question
54
+
55
+ Restate the user's question in one or two sentences.
56
+
57
+ ### The Code in Question
58
+
59
+ File paths, line ranges, key symbols. Two or three lines to orient a cold reader.
60
+
61
+ ### What We Found
62
+
63
+ Claims with textual evidence, each quoted or paraphrased and cited precisely:
64
+
65
+ - **[Direct]** {Claim}. Source: [PR #123](url) / ticket ID / file:line. {Brief quote or paraphrase.}
66
+ - **[Supported]** {Claim}. Evidence: {list of items and what each contributes}.
67
+
68
+ `[Direct]` is single-source, explicit evidence. `[Supported]` is multiple indirect items converging on a conclusion.
69
+
70
+ ### What We Can Reasonably Infer
71
+
72
+ Claims stated nowhere but well-supported by indirect evidence. Each bullet must make the inference chain visible ("Given A and B, it's likely that C") and must use hedged language ("appears to", "likely", "suggests", "is consistent with"):
73
+
74
+ - **[Inferred]** {Hedged claim}. Reasoning: {the specific evidence and the inference step}.
75
+
76
+ Skip this section if there's nothing to infer.
77
+
78
+ ### Competing Hypotheses
79
+
80
+ If the evidence fits multiple stories, present each. Don't force a winner the record doesn't support. For each hypothesis:
81
+
82
+ - **Hypothesis:** {one-sentence statement}
83
+ - **Evidence for:** {specific items}
84
+ - **Evidence against or missing:** {what would need to be true but isn't, or what counter-signals exist}
85
+
86
+ Skip this section if there's a single clear answer.
87
+
88
+ ### What We Don't Know
89
+
90
+ Specific gaps: "We searched the issue tracker for [query1], [query2], [query3] and found no issue discussing the rate-limit threshold", not "We don't know why." Include:
91
+
92
+ - Questions that went unanswered
93
+ - Searches that returned nothing
94
+ - Sources that were unavailable, and why (such as a missing real-time team chat MCP)
95
+ - People who would likely know but whom you can't ask
96
+
97
+ ### Sources Consulted
98
+
99
+ What was actually searched, so the user can judge coverage and redirect:
100
+
101
+ - **Source control history**: {file paths}, {number of commits reviewed}, PRs #{numbers}, and code comments searched. Or "Not searched. This should not happen because git and `gh` are always expected."
102
+ - **Issue / ticket tracker**: {ticket IDs and keyword searches}. Or "Not searched. No matching MCP available in this environment."
103
+ - **Long-form documents**: {page titles and search queries}. Or "Not searched. No matching MCP available in this environment."
104
+ - **Real-time team chat**: {channels searched, date ranges, queries}. Or "Not searched. No matching MCP available in this environment."
105
+ - **Infrastructure observability**: {dashboards, monitors, metrics, logs, traces, or incidents searched}. Or "Not searched. No matching MCP available in this environment."
106
+ - **Error / exception tracking**: {issues, events, or releases searched}. Or "Not searched. No matching MCP available in this environment."
107
+ - **Product analytics warehouse**: {fully-qualified tables queried, the time windows, and the numeric summaries (counts, percentiles, first/last-seen timestamps) that bore on the question}. Or "Not searched. No matching MCP available in this environment."
108
+
109
+ ### Confidence Summary
110
+
111
+ One or two sentences on overall confidence, e.g.:
112
+
113
+ > "The core rationale (A) is well-supported by direct PR and ticket evidence. The specific threshold value (100) is inferred from the surrounding context but not explicitly documented. The question of whether this was driven by a customer request could not be answered. No relevant issue tracker or long-form doc content surfaced, and real-time team chat search was unavailable."
114
+
115
+ ---
116
+
117
+ ## Quality Check Before Returning
118
+
119
+ Revise if any item fails:
120
+
121
+ 1. Does every claim in "What We Found" have a citation? If not, add one or move it to "Inferred" or "Hypotheses."
122
+ 2. Is the phrasing tier-appropriate? (Direct claims can use "because". Inferred claims cannot.)
123
+ 3. Did you surface every contradiction you noticed, or quietly pick one?
124
+ 4. Does "What We Don't Know" name specific gaps? If it's empty or missing, be suspicious. Historical investigations almost always have gaps.
125
+ 5. Did you check any hypothesis embedded in the question against the evidence rather than rubber-stamp it?
126
+ 6. Did you cite code as evidence for its own intent? Remove it. Code is mechanics, not motivation.
127
+ 7. Is the tone calibrated? A confident-sounding answer on weak evidence is the exact failure this skill exists to prevent.
128
+
129
+ The value of this output is its honesty, not its authority. A reader who takes it to the original author, an engineering lead, or a product manager should know what's known, what's inferred, and what's missing, so they can ask the right follow-up questions. Optimize for being useful, not for looking decisive.
@@ -43,7 +43,6 @@ export function rtkActive(entries: SessionEntry[] | null | undefined): boolean {
43
43
  /** The text in a result's content parts, or null when the parts are not plain text. */
44
44
  export function filterableText(parts: unknown): string | null {
45
45
  if (!Array.isArray(parts) || parts.length === 0) return null;
46
- // An image or a mixed result is not text to filter.
47
46
  if (parts.some((part) => (part as { type?: unknown } | null)?.type !== 'text')) return null;
48
47
  return parts.map((part) => (part as { text?: unknown } | null)?.text ?? '').join('\n');
49
48
  }
@@ -23,8 +23,11 @@ function setRtkProcessEnabled(enabled: boolean): void {
23
23
  else process.env.RTK_DISABLED = '1';
24
24
  }
25
25
 
26
- // rtk's awareness contract: state the output contract, never tell the model to type `rtk`.
27
- const RTK_PROMPT = `RTK guidance active. Bash output, and large grep and glob results, are condensed to save tokens: every signal kept, costly noise dropped. Treat a condensed result as complete. Re-run something unfiltered only when its result is empty, garbled, or contradicts its exit code.`;
26
+ // rtk's contract: name the rewritten surface first and the binary second — a hand-typed `rtk` in front of a
27
+ // rewritten command fights the rewrite, and the direct calls cover only what the rewrite cannot express.
28
+ const RTK_PROMPT = `RTK guidance active. What you run is condensed automatically, in the host's own rewritten form: searches (grep, rg, ast-grep), listings (ls, find, tree), reads (cat), package and test runs (bun, npm, pnpm, npx, cargo, go, pytest, vitest, jest, ctest, tsc), version control and forges (git, gh, glab), containers and clusters (docker, kubectl), cloud and platform CLIs (aws, oc, dotnet), PHP tooling (phpunit, pest, phpstan, pint, ecs), lint and format (eslint, ruff, mypy, prettier, sqlfluff, playwright, prisma, next), and data tools (jq, curl, wget, psql, wc, make, tail, docker logs). The runner's own subcommand, such as \`rtk bun run test\`, keeps the failing test name, the assertion, and the file and line. Every signal kept, costly noise dropped. Treat a condensed result as complete. Re-run something unfiltered only when its result is empty, garbled, or contradicts its exit code.
29
+
30
+ Call rtk directly for what the rewrite cannot express: \`rtk read <file> --level aggressive\` for an overview, \`--max-lines N\` for a preview, \`rtk smart <file>\` for a two-line summary, \`rtk summary <cmd>\` for a heuristic one, \`rtk err <cmd>\` for errors only, \`rtk log <file>\` to dedupe logs, \`rtk json <file>\` with \`--keys-only\` for shape, plus \`rtk deps\`, \`rtk diff\`, \`rtk env\`, \`rtk ast-grep\`, and \`rtk test <cmd>\` for a runner without its own form. A command with no condensed form passes through unchanged, so wrap it: \`rtk err node build.js\`, and \`rtk find -name '*.ts'\` in place of fd. Never type \`rtk\` in front of a command listed above.`;
28
31
 
29
32
  export default function rtkSessionExtension(pi: ExtensionApi): void {
30
33
  let enabled = DEFAULT_ENABLED;
@@ -44,7 +47,7 @@ export default function rtkSessionExtension(pi: ExtensionApi): void {
44
47
 
45
48
  setExtensionLabel(pi, 'RTK session toggle');
46
49
 
47
- // Live mirror: a /tersio or /combo switch publishes shared state — adopt it at once so the next turn and the rtk_run gate see it, no reload.
50
+ // Live mirror: a /tersio or /combo switch publishes shared state — adopt it once so the next turn and rtk_run see it.
48
51
  function syncFromShared(state: { rtk: string }): void {
49
52
  enabled = state.rtk === 'on';
50
53
  setRtkProcessEnabled(enabled);
@@ -73,27 +76,32 @@ export default function rtkSessionExtension(pi: ExtensionApi): void {
73
76
  pi.registerTool?.({
74
77
  name: 'rtk_run',
75
78
  label: 'RTK Run',
76
- description: 'Run the installed `rtk` binary for compact command output when RTK mode is enabled.',
79
+ description: 'Run a shell command through the installed `rtk` binary when RTK mode is on, and run it plainly when RTK mode is off.',
77
80
  parameters: stringArrayToolParams(pi, 'args', {
78
81
  minItems: 1,
79
82
  description: "Arguments passed to rtk, e.g. ['git','status'] or ['read','src/index.ts']",
80
83
  }),
81
84
  async execute(_toolCallId, params, signal, onUpdate, ctx) {
82
85
  // A subagent's own flag sits at its start-up default, so honour shared state too.
83
- if (!(enabled || getSharedComboState().rtk === 'on')) return fail('RTK mode is off. Run /rtk on for this session, or use bash explicitly.');
86
+ const rtkOn = enabled || getSharedComboState().rtk === 'on';
84
87
  if (typeof pi.exec !== 'function') return fail('This host cannot run rtk.');
85
- onUpdate?.({ content: [{ type: 'text', text: `rtk ${params.args.join(' ')}` }], details: { phase: 'start' } });
88
+ // RTK off: run the command as given rather than answering "mode is off". The tool is the only one left under --no-tools, and a refusal there made the model spend turns re-calling it. rtk is the condenser, never the command.
89
+ const cwd = ctx?.cwd || pi.cwd;
90
+ const bin = rtkOn ? resolveRtkBinary() : null;
91
+ if (rtkOn && bin === null) return fail('RTK mode is on but the rtk binary is not installed. Run: tersio update');
92
+ const argv = params.args;
93
+ onUpdate?.({ content: [{ type: 'text', text: `${bin === null ? '' : 'rtk '}${argv.join(' ')}` }], details: { phase: 'start' } });
86
94
  try {
87
95
  // A GUI-launched host may lack ~/.bun/bin on PATH, so prefer the resolved path.
88
- const result = await pi.exec(resolveRtkBinary() ?? 'rtk', params.args, { signal, cwd: ctx?.cwd || pi.cwd });
96
+ const result = await pi.exec(bin ?? argv[0], argv, { signal, cwd });
89
97
  const text = [result.stdout, result.stderr].filter(Boolean).join('\n');
90
98
  return {
91
99
  isError: result.code !== 0,
92
- content: [{ type: 'text', text: text || `rtk exited ${result.code}` }],
93
- details: { code: result.code, killed: result.killed, enabled },
100
+ content: [{ type: 'text', text: text || `exited ${result.code}` }],
101
+ details: { code: result.code, killed: result.killed, enabled, condensed: bin !== null },
94
102
  };
95
103
  } catch (e) {
96
- return fail(`rtk could not run: ${e instanceof Error ? e.message : String(e)}`);
104
+ return fail(`${bin === null ? argv[0] : 'rtk'} could not run: ${e instanceof Error ? e.message : String(e)}`);
97
105
  }
98
106
  },
99
107
  });
@@ -102,7 +110,7 @@ export default function rtkSessionExtension(pi: ExtensionApi): void {
102
110
  const entries = sessionEntries(ctx);
103
111
  // A subagent's branch has no Tersio entries; reconciling it would wipe shared state.
104
112
  if (hasModeState(entries)) reconcileSharedComboEntries(entries);
105
- // Persisted session state wins; a fresh session falls back to the installer/user-configured default (off unless configured).
113
+ // Persisted session state wins; a fresh session falls back to the installer/user default (off unless configured).
106
114
  const persisted = resolveEnabled(entries);
107
115
  enabled = typeof persisted === 'boolean' ? persisted : enabled || readRtkDefault();
108
116
  setRtkProcessEnabled(enabled);
@@ -1,7 +1,11 @@
1
1
  // OpenCode plugin entry: maps its plugin API onto the shared ExtensionApi the mode extensions consume.
2
2
  import { execFile } from 'node:child_process';
3
+ import { readFileSync, readdirSync } from 'node:fs';
4
+ import { basename, dirname, join } from 'node:path';
5
+ import { fileURLToPath } from 'node:url';
3
6
  import type { Plugin } from '@opencode/plugin';
4
7
  import cavemanSessionExtension from './caveman/index.ts';
8
+ import pstackSessionExtension from './pstack/index.ts';
5
9
  import rtkSessionExtension from './rtk/session.ts';
6
10
  import rtkFilterExtension, { FILTER_BY_TOOL, MIN_FILTER_BYTES, filterThroughRtk, filterableText, rtkActive } from './rtk/filter.ts';
7
11
  import comboToggleExtension from './combo/index.ts';
@@ -40,8 +44,7 @@ const plugin: Plugin.Plugin = {
40
44
  const loadEntries = async (sid: string): Promise<SessionEntry[]> => {
41
45
  const own = ((await ctx.storage.get(`entries:${sid}`)) as SessionEntry[] | undefined) ?? [];
42
46
  if (own.length) return own;
43
- // Pre-scoped installs kept one global list; adopt it once, then diverge.
44
- // Clear it after adoption so it can never shadow saved defaults later.
47
+ // Pre-scoped installs kept one global list; adopt it once and clear it so it cannot shadow saved defaults later.
45
48
  const legacy = ((await ctx.storage.get('entries')) as SessionEntry[] | undefined) ?? [];
46
49
  if (legacy.length) void ctx.storage.set('entries', []).catch(() => {});
47
50
  return [...legacy];
@@ -122,7 +125,7 @@ const plugin: Plugin.Plugin = {
122
125
  },
123
126
  };
124
127
 
125
- for (const extension of [cavemanSessionExtension, rtkSessionExtension, rtkFilterExtension, comboToggleExtension, tersioCommandsExtension]) extension(host);
128
+ for (const extension of [cavemanSessionExtension, pstackSessionExtension, rtkSessionExtension, rtkFilterExtension, comboToggleExtension, tersioCommandsExtension]) extension(host);
126
129
 
127
130
  // The first hook of an unseen session runs its session_start handlers.
128
131
  const sidOf = (value: unknown): string | undefined =>
@@ -138,8 +141,7 @@ const plugin: Plugin.Plugin = {
138
141
  if (sid) await ensureSession(sid);
139
142
  const text = typeof input.prompt?.text === 'string' ? input.prompt.text : '';
140
143
  const args = text.includes(' ') ? text.slice(text.indexOf(' ') + 1).trim() : '';
141
- // The shared handlers report through ui.notify, which has no OpenCode
142
- // surface. Collect it and send it back so a command never answers blank.
144
+ // Shared handlers notify via ui.notify, which OpenCode lacks; echo it back so a command does not answer blank.
143
145
  const notes: string[] = [];
144
146
  const cmdCtx: ExtensionCtx = {
145
147
  ...stubCtx(sid),
@@ -175,6 +177,15 @@ const plugin: Plugin.Plugin = {
175
177
  }
176
178
  });
177
179
 
180
+ // The tree ships the ruleset beside the extensions, and OpenCode reads no node_modules from a plugin dir.
181
+ try {
182
+ await ctx.skill.transform((editor) => {
183
+ for (const skill of bundledSkills()) editor.add(skill as never);
184
+ });
185
+ } catch {
186
+ // Hosts without the skill transform keep the ruleset in the prompt alone.
187
+ }
188
+
178
189
  await ctx.session.hook('context', async (event) => {
179
190
  const sid = sidOf((event as { sessionID?: unknown }).sessionID);
180
191
  if (sid) await ensureSession(sid);
@@ -205,6 +216,10 @@ const plugin: Plugin.Plugin = {
205
216
  if (tool !== 'bash' && tool !== 'shell') return;
206
217
  const input = event.input as { command?: unknown } | null | undefined;
207
218
  if (typeof input?.command !== 'string' || !input.command) return;
219
+ // /rtk off must stop the rewrite too, or the mode switch only silences the prompt block.
220
+ const sid = typeof (event as { sessionID?: unknown }).sessionID === 'string' ? (event as { sessionID: string }).sessionID : activeSid;
221
+ if (sid !== undefined) await ensureSession(sid);
222
+ if (!rtkActive(sid === undefined ? undefined : sessionEntriesOf(sid))) return;
208
223
  const rewritten = await rewriteCommand(input.command);
209
224
  if (rewritten) input.command = rewritten;
210
225
  });
@@ -246,16 +261,66 @@ function execRtk(cmd: string, args: string[], opts?: { signal?: AbortSignal; tim
246
261
  });
247
262
  }
248
263
 
264
+ /** `rtk rewrite` exit codes: 0 rewrite found, 1 no equivalent, 3 advisory; the code is the contract. */
265
+ const RTK_REWRITE_FOUND = 0;
266
+ const RTK_REWRITE_ADVISORY = 3;
267
+
268
+ /** The bundled ruleset's skill dirs, beside the plugin entry: OpenCode reads no node_modules from a plugin. */
269
+ const PONYTAIL_BUNDLE_SKILLS = join(dirname(fileURLToPath(import.meta.url)), 'ponytail-bundle', 'skills');
270
+
271
+ /** Frontmatter a SKILL.md carries: flat keys only, the shape every bundled skill uses. */
272
+ function parseSkillFile(file: string): { id: string; name: string; description: string; path: string; content: string } | null {
273
+ let raw: string;
274
+ try { raw = readFileSync(file, 'utf8'); } catch { return null; }
275
+ const match = raw.match(/^---\r?\n([\s\S]*?)\r?\n---[^\S\n]*\r?\n?([\s\S]*)$/);
276
+ if (!match) return null;
277
+ const field = (key: string): string | undefined => {
278
+ const lines = match[1].split(/\r?\n/);
279
+ const at = lines.findIndex((line) => line.startsWith(`${key}:`));
280
+ if (at === -1) return undefined;
281
+ const value = lines[at].slice(key.length + 1).trim();
282
+ if (value[0] !== '>' && value[0] !== '|') return value;
283
+ // Folded (`>`) joins the indented lines; the next unindented key ends the block.
284
+ const block: string[] = [];
285
+ for (const line of lines.slice(at + 1)) {
286
+ if (line.trim() !== '' && !/^\s/.test(line)) break;
287
+ block.push(line.trim());
288
+ }
289
+ while (block.length > 0 && block[block.length - 1] === '') block.pop();
290
+ return block.join(value[0] === '|' ? '\n' : ' ');
291
+ };
292
+ const id = field('name') ?? basename(dirname(file));
293
+ return { id, name: id, description: field('description') ?? '', path: file, content: match[2] };
294
+ }
295
+
296
+ /** Every bundled skill, or an empty list when the installer has not bundled them. */
297
+ function bundledSkills(): ReturnType<typeof parseSkillFile>[] {
298
+ let entries;
299
+ try { entries = readdirSync(PONYTAIL_BUNDLE_SKILLS, { withFileTypes: true }); } catch { return []; }
300
+ const out: ReturnType<typeof parseSkillFile>[] = [];
301
+ for (const entry of entries.sort((a, b) => a.name.localeCompare(b.name))) {
302
+ if (!entry.isDirectory()) continue;
303
+ const skill = parseSkillFile(join(PONYTAIL_BUNDLE_SKILLS, entry.name, 'SKILL.md'));
304
+ if (skill) out.push(skill);
305
+ }
306
+ return out;
307
+ }
308
+
249
309
  function rewriteCommand(command: string): Promise<string | null> {
250
310
  const bin = resolveRtkBinary();
251
311
  if (!bin) return Promise.resolve(null);
252
312
  return new Promise((resolve) => {
253
313
  execFile(bin, ['rewrite', command], { timeout: 5000 }, (error, stdout) => {
254
314
  // A kill or timeout means untrustworthy output; pass the command through.
255
- const err = error as { killed?: boolean; signal?: unknown } | null;
315
+ const err = error as { killed?: boolean; signal?: unknown; code?: unknown } | null;
256
316
  if (err && (err.killed || err.signal)) return resolve(null);
317
+ const code = typeof err?.code === 'number' ? err.code : RTK_REWRITE_FOUND;
318
+ // Exit 1 is the only "no equivalent" answer, so anything else with output rewrites.
319
+ if (code === 1) return resolve(null);
257
320
  const out = String(stdout).trim();
258
- resolve(out && out !== command ? out : null);
321
+ if (!out || out === command) return resolve(null);
322
+ if (code !== RTK_REWRITE_FOUND && code !== RTK_REWRITE_ADVISORY) return resolve(null);
323
+ resolve(out);
259
324
  });
260
325
  });
261
326
  }