@openora/create 0.4.1-canary.40 → 0.4.1-canary.403

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 (104) hide show
  1. package/dist/.tsbuildinfo +1 -1
  2. package/dist/generated/versions.d.ts +11 -0
  3. package/dist/generated/versions.d.ts.map +1 -0
  4. package/dist/generated/versions.js +11 -0
  5. package/dist/generated/versions.js.map +1 -0
  6. package/dist/index.js +48 -93
  7. package/dist/index.js.map +1 -1
  8. package/dist/render.d.ts +15 -0
  9. package/dist/render.d.ts.map +1 -0
  10. package/dist/render.js +125 -0
  11. package/dist/render.js.map +1 -0
  12. package/package.json +8 -6
  13. package/template/README.md.tpl +12 -7
  14. package/template/__dot__claude/settings.json.tpl +30 -12
  15. package/template/__dot__env.example +16 -0
  16. package/template/__dot__gitignore +5 -5
  17. package/template/__dot__rulesync/commands/check.md +11 -10
  18. package/template/__dot__rulesync/commands/doctor.md.tpl +17 -0
  19. package/template/__dot__rulesync/commands/scaffold-module.md +3 -2
  20. package/template/__dot__rulesync/commands/scaffold-plugin.md +23 -4
  21. package/template/__dot__rulesync/commands/scaffold-route.md +1 -0
  22. package/template/__dot__rulesync/commands/start.md +2 -2
  23. package/template/__dot__rulesync/hooks/_shared.mjs +25 -34
  24. package/template/__dot__rulesync/hooks/guard-core.mjs.tpl +98 -28
  25. package/template/__dot__rulesync/hooks/guard-generated.mjs +15 -16
  26. package/template/__dot__rulesync/hooks/guard-mr.mjs +143 -0
  27. package/template/__dot__rulesync/hooks/guard-review.mjs +280 -0
  28. package/template/__dot__rulesync/hooks/guard-stack.mjs +35 -0
  29. package/template/__dot__rulesync/hooks/guard-subagent.mjs +22 -6
  30. package/template/__dot__rulesync/hooks/post-edit.mjs.tpl +116 -0
  31. package/template/__dot__rulesync/hooks.json +37 -4
  32. package/template/__dot__rulesync/rules/conventions.md +99 -119
  33. package/template/__dot__rulesync/rules/db-conventions.md +6 -72
  34. package/template/__dot__rulesync/rules/e2e-conventions.md +33 -7
  35. package/template/__dot__rulesync/rules/frontend-conventions.md.tpl +35 -0
  36. package/template/__dot__rulesync/rules/oss-boundaries.md.tpl +78 -0
  37. package/template/__dot__rulesync/rules/overview.md +19 -82
  38. package/template/__dot__rulesync/skills/agent-retro/SKILL.md.tpl +81 -0
  39. package/template/__dot__rulesync/skills/agent-retro/scan.mjs +420 -0
  40. package/template/__dot__rulesync/skills/create-plugin/{SKILL.md → SKILL.md.tpl} +12 -23
  41. package/template/__dot__rulesync/skills/create-pr/SKILL.md.tpl +37 -0
  42. package/template/__dot__rulesync/skills/create-task/SKILL.md.tpl +96 -0
  43. package/template/__dot__rulesync/skills/create-ui-module/{SKILL.md → SKILL.md.tpl} +12 -10
  44. package/template/__dot__rulesync/skills/enhance-prompt/{SKILL.md → SKILL.md.tpl} +4 -4
  45. package/template/__dot__rulesync/skills/handoff/SKILL.md +4 -3
  46. package/template/__dot__rulesync/skills/review/SKILL.md.tpl +278 -0
  47. package/template/__dot__rulesync/skills/ship/SKILL.md.tpl +157 -0
  48. package/template/__dot__rulesync/skills/ship/handoff.md.tpl +48 -0
  49. package/template/__dot__rulesync/skills/ship/watch-pr.mjs +189 -0
  50. package/template/__dot__rulesync/skills/ui-verify/SKILL.md.tpl +120 -0
  51. package/template/__dot__rulesync/skills/ui-verify/layout-check.check.sh +58 -0
  52. package/template/__dot__rulesync/skills/ui-verify/layout-check.js +163 -0
  53. package/template/__dot__rulesync/subagents/builder.md.tpl +116 -0
  54. package/template/__dot__rulesync/subagents/compliance-reviewer.md +79 -0
  55. package/template/__dot__rulesync/subagents/debugger.md.tpl +89 -0
  56. package/template/__dot__rulesync/subagents/deployer.md.tpl +55 -0
  57. package/template/__dot__rulesync/subagents/expert.md +29 -34
  58. package/template/__dot__rulesync/subagents/planner.md.tpl +40 -0
  59. package/template/__dot__rulesync/subagents/quality-reviewer.md.tpl +113 -0
  60. package/template/__dot__rulesync/subagents/security-reviewer.md.tpl +86 -0
  61. package/template/__dot__rulesync/subagents/tester.md.tpl +103 -0
  62. package/template/__dot__rulesync/sync.json.tpl +26 -0
  63. package/template/apps/api/package.json.tpl +2 -2
  64. package/template/apps/api/src/extensions.config.ts.tpl +12 -0
  65. package/template/apps/api/src/main.ts.tpl +1 -4
  66. package/template/apps/api/src/seed.ts.tpl +24 -17
  67. package/template/docker-compose.yml +13 -0
  68. package/template/docs/agents/cross-repo.md.tpl +36 -0
  69. package/template/docs/agents/forge.md.tpl +56 -0
  70. package/template/docs/agents/issue-tracker.md.tpl +42 -0
  71. package/template/docs/standards/comments.md +16 -0
  72. package/template/docs/standards/database.md +77 -0
  73. package/template/docs/standards/enforcement.md +12 -0
  74. package/template/docs/standards/errors.md +30 -0
  75. package/template/docs/standards/frontend.md +60 -0
  76. package/template/docs/standards/functions.md +38 -0
  77. package/template/docs/standards/git-delivery.md +33 -0
  78. package/template/docs/standards/module-structure.md +37 -0
  79. package/template/docs/standards/testing.md +91 -0
  80. package/template/docs/standards/types.md +31 -0
  81. package/template/package.json.tpl +16 -10
  82. package/template/pnpm-workspace.yaml.tpl +6 -0
  83. package/template/rulesync.jsonc +4 -5
  84. package/template/tools/oss-worktree.mjs.tpl +105 -0
  85. package/template/tools/review-precheck.mjs +575 -0
  86. package/template/tools/sync-agents.mjs +273 -0
  87. package/dist/generated/core-version.d.ts +0 -2
  88. package/dist/generated/core-version.d.ts.map +0 -1
  89. package/dist/generated/core-version.js +0 -2
  90. package/dist/generated/core-version.js.map +0 -1
  91. package/template/__dot__rulesync/commands/doctor.md +0 -16
  92. package/template/__dot__rulesync/hooks/post-edit.mjs +0 -57
  93. package/template/__dot__rulesync/rules/oss-boundaries.md +0 -31
  94. package/template/__dot__rulesync/skills/add-feature/SKILL.md +0 -113
  95. package/template/__dot__rulesync/skills/add-feature/handoff.md +0 -58
  96. package/template/__dot__rulesync/skills/create-pr/SKILL.md +0 -55
  97. package/template/__dot__rulesync/skills/create-task/SKILL.md +0 -77
  98. package/template/__dot__rulesync/skills/review/SKILL.md +0 -110
  99. package/template/__dot__rulesync/subagents/builder.md +0 -93
  100. package/template/__dot__rulesync/subagents/debugger.md +0 -82
  101. package/template/__dot__rulesync/subagents/deployer.md +0 -66
  102. package/template/__dot__rulesync/subagents/qa.md +0 -88
  103. package/template/__dot__rulesync/subagents/quality-reviewer.md +0 -67
  104. package/template/__dot__rulesync/subagents/security-reviewer.md +0 -54
@@ -0,0 +1,420 @@
1
+ #!/usr/bin/env node
2
+ // Deterministic signal extractor over Claude Code transcripts. No LLM, no deps.
3
+ // Usage: node scan.mjs [--days 7] [--match '<this repo>|openora'] [--root ~/.claude/projects] [--top 25] [--save false]
4
+ import {
5
+ createReadStream,
6
+ readdirSync,
7
+ statSync,
8
+ existsSync,
9
+ mkdirSync,
10
+ writeFileSync,
11
+ } from 'node:fs';
12
+ import { createInterface } from 'node:readline';
13
+ import { execFileSync } from 'node:child_process';
14
+ import { basename, dirname, join } from 'node:path';
15
+ import { homedir } from 'node:os';
16
+
17
+ const args = Object.fromEntries(
18
+ process.argv
19
+ .slice(2)
20
+ .reduce(
21
+ (acc, a, i, all) => (a.startsWith('--') ? [...acc, [a.slice(2), all[i + 1]]] : acc),
22
+ [],
23
+ ),
24
+ );
25
+ const positiveInt = (name, fallback) => {
26
+ const value = Number(args[name] ?? fallback);
27
+ if (!Number.isInteger(value) || value <= 0) {
28
+ throw new Error(`--${name} must be a positive integer, got ${args[name]}`);
29
+ }
30
+ return value;
31
+ };
32
+ const days = positiveInt('days', 7);
33
+ const top = positiveInt('top', 25);
34
+ // The main checkout, also from a worktree: its name picks the transcripts, its .claude/reviews/ keeps the reports.
35
+ const mainCheckout = () => {
36
+ try {
37
+ return dirname(
38
+ execFileSync('git', ['rev-parse', '--path-format=absolute', '--git-common-dir'], {
39
+ encoding: 'utf8',
40
+ stdio: ['ignore', 'pipe', 'ignore'],
41
+ }).trim(),
42
+ );
43
+ } catch {
44
+ throw new Error('run inside a git checkout, or pass --match and --save false');
45
+ }
46
+ };
47
+ const repoNames = args.match ? [] : [...new Set([basename(mainCheckout()), 'openora'])];
48
+ // Claude Code names a project dir after its path with every non-alphanumeric turned into '-',
49
+ // so match whole '-'-separated segments: a repo named "api" must not pick up "~/apix" (but "~/x/api/y" and "~/x-api-y" look the same).
50
+ const match = new RegExp(
51
+ args.match ??
52
+ `(?:^|-)(?:${repoNames.map((name) => name.replace(/[^a-zA-Z0-9]/g, '-')).join('|')})(?:-|$)`,
53
+ 'i',
54
+ );
55
+ const root = args.root ?? join(homedir(), '.claude/projects');
56
+ const since = Date.now() - days * 86_400_000;
57
+
58
+ // `\b` is ASCII-only in JS, so Polish words ending in a diacritic sit outside the `\b` groups.
59
+ const CORRECTION =
60
+ /\b(instead|actually|nope|i told you|you should have|still (not|broken|failing)|nadal|wciaz)\b|wciąż|^(no\b|nie\b|stop\b|wrong|źle|zle\b|not that|don'?t\b|nie rób|nie rob|why did you|dlaczego|i said|mówiłem|mowilem|again\b|znowu|you forgot|zapomniałeś|zapomniales|revert|cofnij|that'?s not)/i;
61
+
62
+ // The digest is shared at the team sync: credentials, emails and home paths are masked.
63
+ const SECRET_NAME =
64
+ /(["']?)([\w-]*(?:password|passwd|pwd|secret|token|api[_-]?key|access[_-]?key|private[_-]?key|credential)[\w-]*)\1(\s*[:=]\s*)(?:"[^"]*"|'[^']*'|[^\s",}]+)/gi;
65
+ // Capped: the name patterns backtrack quadratically on long word runs.
66
+ const redact = (text) =>
67
+ String(text)
68
+ .slice(0, 4000)
69
+ .replace(
70
+ /-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?(?:-----END [A-Z ]*PRIVATE KEY-----|$)/g,
71
+ '<private-key>',
72
+ )
73
+ .replace(/\/(?:Users|home)\/[^/\s'"]+\//g, '~/')
74
+ .replace(/-(?:Users|home)-[^-\s]+-/g, '-~-')
75
+ .replace(/:\/\/[^\s/:@]+:[^\s/?#]+@/g, '://<user>:<redacted>@')
76
+ .replace(
77
+ /\b(Authorization|PRIVATE-TOKEN|x-api-key)(["']?\s*[:=]\s*)(?:(?:Bearer|Basic|token)\s+)?[^\s"']+/gi,
78
+ '$1$2<redacted>',
79
+ )
80
+ // A cookie header holds a whole `a=1; b=2` list, so it is masked to the closing quote or line end.
81
+ .replace(/\b(Cookie|Set-Cookie)(["']?\s*[:=]\s*)[^"'\r\n]+/gi, '$1$2<redacted>')
82
+ .replace(/\b(curl\s(?:.*?\s)?(?:-b|--cookie)(?:=|\s+))(?:"[^"]*"|'[^']*'|\S+)/g, '$1<redacted>')
83
+ .replace(/\b(Bearer|Basic)\s+[\w.~+/=-]{8,}/g, '$1 <redacted>')
84
+ .replace(SECRET_NAME, '$1$2$1$3<redacted>')
85
+ .replace(/(--password[= ]|docker login\s.*?-p\s+|curl\s.*?-u\s+[^:\s]+:)\S+/g, '$1<redacted>')
86
+ .replace(
87
+ /\b(glpat-|glptt-|ghp_|gho_|ghs_|github_pat_|npm_|sk-|sk_live_|rk_live_|whsec_|xox[bp]-)[\w-]+/g,
88
+ '$1<redacted>',
89
+ )
90
+ .replace(/\b(?:AKIA|ASIA)[0-9A-Z]{16}\b/g, '<aws-key-id>')
91
+ .replace(/\beyJ[\w-]+\.[\w-]+\.[\w-]+/g, '<jwt>')
92
+ .replace(/[\w.+-]+@[\w-]+\.[\w.-]+/g, '<email>');
93
+
94
+ const counter = () => new Map();
95
+ // Redact before truncating, so a cut never splits a secret out of its pattern's reach.
96
+ const bump = (map, key, example, incident) => {
97
+ const safeKey = redact(key);
98
+ const entry = map.get(safeKey) ?? {
99
+ n: 0,
100
+ sessions: new Set(),
101
+ example: redact(example.slice(0, 2000)).slice(0, 300),
102
+ };
103
+ entry.n += 1;
104
+ entry.sessions.add(incident);
105
+ map.set(safeKey, entry);
106
+ };
107
+
108
+ const toolErrors = counter();
109
+ const hookBlocks = counter();
110
+ const guardTotals = counter();
111
+ const commandFamilies = counter();
112
+ const failedCommandFamilies = counter();
113
+ const corrections = [];
114
+ const interrupts = counter();
115
+ const skills = counter();
116
+ const subagents = counter();
117
+ const fileReads = counter();
118
+ const sessionStats = [];
119
+
120
+ // Collapse volatile parts so identical failures group together.
121
+ // Redact first: placeholders below would break the secret patterns and leave token tails.
122
+ const normalize = (text) =>
123
+ redact(text)
124
+ .replace(/(?:\/(?:Users|home)\/|~\/)[^\s'"]+/g, '<path>')
125
+ .replace(/\/(private\/)?tmp\/[^\s'"]+/g, '<tmp>')
126
+ .replace(/\b[0-9a-f]{7,40}\b/g, '<sha>')
127
+ .replace(/\d+/g, '<n>')
128
+ .replace(/\s+/g, ' ')
129
+ .trim()
130
+ .slice(0, 140);
131
+
132
+ // A file path relative to its checkout, so the same file in two worktrees is one row.
133
+ const WORKTREE =
134
+ /^.*\/(?:\.t3\/worktrees\/[^/]+\/[^/]+|\.claude\/worktrees\/[^/]+|\.worktrees\/[^/]+)\//;
135
+ const escapeRegExp = (text) => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
136
+ const CHECKOUT = repoNames.length
137
+ ? new RegExp(`^.*?/(?:${repoNames.map(escapeRegExp).join('|')})/`)
138
+ : /^$/;
139
+ const checkoutRelative = (path) =>
140
+ WORKTREE.test(path)
141
+ ? path.replace(WORKTREE, '')
142
+ : path.replace(CHECKOUT, '').replace(/^\/(?:Users|home)\/[^/]+\//, '~/');
143
+
144
+ // First meaningful tokens of a shell command: "pnpm --filter api typecheck", "glab mr view".
145
+ const commandFamily = (command) => {
146
+ const first = command
147
+ .replace(/^\s*cd\s+\S+\s*(&&|;)\s*/, '')
148
+ .split(/&&|\|\||;|\|/)[0]
149
+ .trim();
150
+ const tokens = first.split(/\s+/).filter((t) => !t.startsWith('$') && !t.includes('='));
151
+ return tokens
152
+ .slice(
153
+ 0,
154
+ tokens[0] && /^(pnpm|npm|npx|glab|gh|git|docker|node|bun|turbo)$/.test(tokens[0]) ? 3 : 2,
155
+ )
156
+ .join(' ');
157
+ };
158
+
159
+ const textOf = (content) =>
160
+ typeof content === 'string'
161
+ ? content
162
+ : Array.isArray(content)
163
+ ? content.map((c) => (typeof c === 'string' ? c : (c.text ?? ''))).join('\n')
164
+ : '';
165
+
166
+ async function scanFile(file, project, isSubagent) {
167
+ const session = basename(file, '.jsonl');
168
+ // A subagent's events belong to the main session that spawned it: one incident, not six.
169
+ const incident = isSubagent ? file.split('/').at(-3) : session;
170
+ const pendingTools = new Map(); // tool_use_id -> { name, family }
171
+ const countedMessages = new Set(); // every content block repeats its message's usage
172
+ const stats = {
173
+ project,
174
+ session,
175
+ isSubagent,
176
+ turns: 0,
177
+ toolCalls: 0,
178
+ errors: 0,
179
+ compactions: 0,
180
+ costUSD: 0,
181
+ tokens: 0,
182
+ corrections: 0,
183
+ };
184
+ const lines = createInterface({ input: createReadStream(file), crlfDelay: Infinity });
185
+ for await (const line of lines) {
186
+ let entry;
187
+ try {
188
+ entry = JSON.parse(line);
189
+ } catch {
190
+ continue;
191
+ }
192
+ const content = entry.message?.content;
193
+ const toolUses =
194
+ entry.type === 'assistant' && Array.isArray(content)
195
+ ? content.filter((block) => block.type === 'tool_use')
196
+ : [];
197
+ for (const block of toolUses) {
198
+ const input = block.input ?? {};
199
+ const family =
200
+ block.name === 'Bash' && typeof input.command === 'string'
201
+ ? commandFamily(input.command)
202
+ : undefined;
203
+ pendingTools.set(block.id, { name: block.name, family });
204
+ }
205
+ // Long sessions span weeks: count only what happened inside the window.
206
+ if (entry.timestamp && Date.parse(entry.timestamp) < since) {
207
+ continue;
208
+ }
209
+ const usage = entry.type === 'assistant' ? entry.message?.usage : undefined;
210
+ if (usage && !countedMessages.has(entry.message.id)) {
211
+ countedMessages.add(entry.message.id);
212
+ stats.tokens +=
213
+ (usage.input_tokens ?? 0) +
214
+ (usage.cache_creation_input_tokens ?? 0) +
215
+ (usage.cache_read_input_tokens ?? 0) +
216
+ (usage.output_tokens ?? 0);
217
+ }
218
+ if (entry.type === 'cost-state') {
219
+ stats.costUSD = Math.max(stats.costUSD, entry.totalCostUSD ?? 0);
220
+ }
221
+ if (entry.type === 'system' && entry.subtype === 'compact_boundary') {
222
+ stats.compactions += 1;
223
+ }
224
+ if (entry.type === 'attachment' && entry.attachment?.type === 'hook_blocking_error') {
225
+ const message = String(
226
+ entry.attachment.blockingError?.blockingError ??
227
+ entry.attachment.content ??
228
+ JSON.stringify(entry.attachment),
229
+ );
230
+ const hook = message.match(/hooks\/([\w-]+\.\w+)/)?.[1] ?? 'hook';
231
+ const reason =
232
+ message.match(/eslint\([^)]+\)|oss-[\w-]+|Typecheck failed for \S+|error TS\d+/)?.[0] ??
233
+ normalize(message).slice(0, 80);
234
+ bump(hookBlocks, `${hook} :: ${reason}`, message, incident);
235
+ bump(guardTotals, `${entry.attachment.hookEvent ?? 'hook'} ${hook}`, '', incident);
236
+ }
237
+ for (const block of toolUses) {
238
+ stats.toolCalls += 1;
239
+ const input = block.input ?? {};
240
+ const { family } = pendingTools.get(block.id);
241
+ if (family) {
242
+ bump(commandFamilies, family, input.command, incident);
243
+ }
244
+ if (block.name === 'Skill') {
245
+ bump(skills, String(input.skill), '', incident);
246
+ }
247
+ if (block.name === 'Agent' || block.name === 'Task') {
248
+ bump(subagents, String(input.subagent_type ?? 'general-purpose'), '', incident);
249
+ }
250
+ if (block.name === 'Read' && typeof input.file_path === 'string') {
251
+ bump(fileReads, checkoutRelative(input.file_path), '', incident);
252
+ }
253
+ }
254
+ if (entry.type === 'user' && !entry.isMeta) {
255
+ if (Array.isArray(content) && content.some((c) => c.type === 'tool_result')) {
256
+ for (const result of content) {
257
+ if (result.type !== 'tool_result' || result.is_error !== true) {
258
+ continue;
259
+ }
260
+ stats.errors += 1;
261
+ const tool = pendingTools.get(result.tool_use_id) ?? { name: '?' };
262
+ const text = textOf(result.content);
263
+ const signature = normalize(text.replace(/^Exit code \d+\s*/, ''));
264
+ bump(toolErrors, `${tool.name} :: ${signature}`, text, incident);
265
+ if (text.startsWith('PreToolUse:')) {
266
+ const guard =
267
+ text.match(/hooks\/([\w.-]+)/)?.[1] ??
268
+ `unnamed: ${normalize(text.replace(/^PreToolUse:\S+ hook error:\s*/, '')).slice(0, 50)}`;
269
+ bump(guardTotals, `PreToolUse ${guard}`, '', incident);
270
+ }
271
+ // Hook blocks have their own table; here only commands that ran and failed.
272
+ if (tool.family && !text.startsWith('PreToolUse:')) {
273
+ bump(failedCommandFamilies, tool.family, text, incident);
274
+ }
275
+ }
276
+ } else {
277
+ const text = textOf(content).trim();
278
+ // Compaction summaries, status-file restores and pasted skill bodies arrive as user turns.
279
+ if (
280
+ !text ||
281
+ entry.isCompactSummary ||
282
+ entry.isVisibleInTranscriptOnly ||
283
+ /^(<|Caveat:|Task status from|Delegated task|\(Re-invocation)/.test(text)
284
+ ) {
285
+ continue;
286
+ }
287
+ if (text.startsWith('[Request interrupted')) {
288
+ bump(interrupts, 'interrupt', '', incident);
289
+ continue;
290
+ }
291
+ stats.turns += 1;
292
+ if (!isSubagent && text.length < 600 && CORRECTION.test(text)) {
293
+ stats.corrections += 1;
294
+ corrections.push({
295
+ project,
296
+ session,
297
+ at: entry.timestamp ?? '',
298
+ text: redact(text).replace(/\s+/g, ' ').slice(0, 220),
299
+ });
300
+ }
301
+ }
302
+ }
303
+ }
304
+ sessionStats.push(stats);
305
+ }
306
+
307
+ const files = [];
308
+ for (const dir of readdirSync(root)) {
309
+ const projectDir = join(root, dir);
310
+ if (!match.test(dir) || !statSync(projectDir).isDirectory()) {
311
+ continue;
312
+ }
313
+ for (const name of readdirSync(projectDir)) {
314
+ const path = join(projectDir, name);
315
+ if (name.endsWith('.jsonl')) {
316
+ if (statSync(path).mtimeMs >= since) {
317
+ files.push([path, dir, false]);
318
+ }
319
+ continue;
320
+ }
321
+ const subDir = join(path, 'subagents');
322
+ if (!existsSync(subDir)) {
323
+ continue;
324
+ }
325
+ for (const sub of readdirSync(subDir)) {
326
+ const subPath = join(subDir, sub);
327
+ if (sub.endsWith('.jsonl') && statSync(subPath).mtimeMs >= since) {
328
+ files.push([subPath, dir, true]);
329
+ }
330
+ }
331
+ }
332
+ }
333
+
334
+ for (const [file, project, isSubagent] of files) {
335
+ await scanFile(file, project, isSubagent);
336
+ }
337
+
338
+ const ranked = (map, limit = top) =>
339
+ [...map.entries()]
340
+ .sort((a, b) => b[1].sessions.size - a[1].sessions.size || b[1].n - a[1].n)
341
+ .slice(0, limit);
342
+ const table = (title, map, { withExample = true, limit } = {}) => {
343
+ const rows = ranked(map, limit);
344
+ if (!rows.length) {
345
+ return `## ${title}\n\n(none)\n`;
346
+ }
347
+ const head = withExample
348
+ ? '| n | sessions | key | example |\n|---|---|---|---|'
349
+ : '| n | sessions | key |\n|---|---|---|';
350
+ const cell = (s) => String(s).replace(/\|/g, '\\|').replace(/\n/g, ' ↵ ');
351
+ return `## ${title}\n\n${head}\n${rows
352
+ .map(
353
+ ([key, v]) =>
354
+ `| ${v.n} | ${v.sessions.size} | ${cell(key)} |${withExample ? ` ${cell(v.example).slice(0, 200)} |` : ''}`,
355
+ )
356
+ .join('\n')}\n`;
357
+ };
358
+
359
+ const mains = sessionStats.filter((s) => !s.isSubagent && (s.toolCalls > 0 || s.turns > 0));
360
+ const sum = (list, key) => list.reduce((acc, s) => acc + s[key], 0);
361
+ const failureRate = new Map(
362
+ [...failedCommandFamilies.entries()]
363
+ .map(([family, v]) => [family, { ...v, total: commandFamilies.get(family)?.n ?? v.n }])
364
+ .filter(([, v]) => v.n >= 3)
365
+ .map(([family, v]) => [`${family} (${Math.round((100 * v.n) / v.total)}% of ${v.total})`, v]),
366
+ );
367
+
368
+ const mtok = (n) => `${(n / 1e6).toFixed(1)}M`;
369
+ const out = [
370
+ `# Agent session digest: last ${days}d, /${match.source}/`,
371
+ '',
372
+ `Main sessions: ${mains.length}, subagent transcripts: ${sessionStats.length - mains.length}, tool calls: ${sum(sessionStats, 'toolCalls')}, tool errors: ${sum(sessionStats, 'errors')}, user corrections: ${corrections.length}, interrupts: ${interrupts.get('interrupt')?.n ?? 0}, compactions: ${sum(mains, 'compactions')}, tokens in window: ${mtok(sum(sessionStats, 'tokens'))}`,
373
+ '',
374
+ 'Ranked by distinct main sessions (a subagent counts as its parent), then count. `<n>`/`<path>`/`<sha>` are normalized placeholders, `<redacted>`/`<email>`/`<jwt>` masked values.',
375
+ '',
376
+ table('Recurring tool errors', toolErrors, { limit: top * 2 }),
377
+ table('Blocks per guard (totals: quote these, never add rows up yourself)', guardTotals, {
378
+ withExample: false,
379
+ }),
380
+ table('Post-edit hook blocks by reason', hookBlocks),
381
+ table('Shell command families that fail often (>=3 failures)', failureRate),
382
+ table('Most-run shell command families (script/allowlist candidates)', commandFamilies),
383
+ table('Most-read files (precompute / rule candidates)', fileReads, { withExample: false }),
384
+ table('Skills invoked', skills, { withExample: false }),
385
+ table('Subagents spawned', subagents, { withExample: false }),
386
+ '## Possible user corrections (main sessions, regex-matched, verify each; newest last)',
387
+ '',
388
+ ...corrections
389
+ .sort((a, b) => a.at.localeCompare(b.at))
390
+ .slice(-60)
391
+ .map(
392
+ (c) =>
393
+ `- [${c.project.replace(/^-(?:Users|home)-[^-]+-/, '')} ${c.session.slice(0, 8)}] ${c.text}`,
394
+ ),
395
+ '',
396
+ '## Costliest main sessions (by tokens in the window; $ is the whole session, window or not)',
397
+ '',
398
+ '| tokens | $ | turns | tool calls | errors | corrections | compactions | project | session |\n|---|---|---|---|---|---|---|---|---|',
399
+ ...mains
400
+ .sort((a, b) => b.tokens - a.tokens)
401
+ .slice(0, 15)
402
+ .map(
403
+ (s) =>
404
+ `| ${mtok(s.tokens)} | ${s.costUSD.toFixed(1)} | ${s.turns} | ${s.toolCalls} | ${s.errors} | ${s.corrections} | ${s.compactions} | ${s.project.replace(/^-(?:Users|home)-[^-]+-/, '')} | ${s.session} |`,
405
+ ),
406
+ '',
407
+ ];
408
+ // Transcripts carry control bytes (NUL in tool output) that make the digest read as binary.
409
+ // eslint-disable-next-line no-control-regex
410
+ const digest = out.join('\n').replace(/[\u0000-\u0008\u000b-\u001f]/g, '');
411
+ process.stdout.write(digest);
412
+
413
+ // Saved in the main checkout's gitignored .claude/reviews/: a worktree is gone by next week.
414
+ if (args.save !== 'false') {
415
+ const dir = join(mainCheckout(), '.claude/reviews');
416
+ mkdirSync(dir, { recursive: true });
417
+ const file = join(dir, `agent-retro-digest-${new Date().toISOString().slice(0, 10)}.md`);
418
+ writeFileSync(file, digest);
419
+ process.stderr.write(`\nsaved ${file}\nreports dir: ${dir}\n`);
420
+ }
@@ -1,19 +1,17 @@
1
1
  ---
2
2
  name: create-plugin
3
-
3
+ targets: ['*']
4
4
  description: >
5
- Guided creation of an extension - the right way to add behavior or swap a vendor without
5
+ Guided creation of a {{name}} extension - the right way to add behavior or swap a vendor without
6
6
  touching `@openora/*` core. Interviews for intent, classifies the seam (plugin / adapter /
7
7
  page / route), runs the matching scaffold command, wires extensions.config.ts, and enforces
8
8
  boundaries + audit + db rules. Use on "create plugin", "add an extension", "swap KYC/PSP",
9
9
  "mount a page", "/create-plugin <name>".
10
10
  ---
11
11
 
12
- # create-plugin
12
+ # create-plugin ({{name}})
13
13
 
14
- The platform is extended from the **outside only** (overlay plugin / adapter rebind / UI page /
15
- config) - never by editing `@openora/*`. This skill picks the correct seam and scaffolds it.
16
- Domain questions go to `expert` first; review the result with `review`.
14
+ The platform is extended from the **outside only** (overlay plugin / adapter rebind / UI page / config) - never by editing `@openora/*`. This skill picks the correct seam and scaffolds it. Domain questions go to `expert` first; review the result with `review`.
17
15
 
18
16
  ## 1. Classify the seam (ask if unclear)
19
17
 
@@ -24,23 +22,17 @@ Domain questions go to `expert` first; review the result with `review`.
24
22
  | Mount a react-sdk page on a route | page | `pnpm gen page <route>` |
25
23
  | Add one route to an existing add-on/overlay | route | `/scaffold-route <add-on> <METHOD> <path>` |
26
24
 
27
- If the behavior genuinely cannot be expressed from the outside, STOP - it's an OSS-core change.
28
- Hand off via the `add-feature` skill's `handoff.md`. Do not patch the linked OSS checkout.
25
+ If the behavior genuinely cannot be expressed from the outside, STOP - it's an OSS-core change. Hand off via the `ship` skill's `handoff.md`. Never patch `{{ossDir}}`.
29
26
 
30
27
  ## 2. Ground first
31
28
 
32
- - Read `.claude/rules/overview.md` (what you may and may not touch) and
33
- `.claude/rules/db-conventions.md` (if the extension owns tables).
34
- - Inspect what already exists with the `oss` MCP: `catalog-overview`, `list-adapters` (token +
35
- default binding to swap), `list-routes` (collision check), `list-slots`, `list-events`.
36
- - For a domain rule you can't safely assume (a limit, a KYC threshold, a jurisdiction behavior),
37
- spawn `expert` before scaffolding.
29
+ - Read `CLAUDE.md` / `AGENTS.md` (the rendered `overview` rule: what you may and may not touch), `.claude/rules/oss-boundaries.md`, and `.claude/rules/db-conventions.md` + `docs/standards/database.md` (if the extension owns tables).
30
+ - Inspect what already exists with the `oss` MCP: `catalog-overview`, `list-adapters` (token + default binding to swap), `list-routes` (collision check), `list-slots`, `list-events`.
31
+ - For a domain rule you can't safely assume (a limit, a KYC threshold, a jurisdiction behavior), spawn `expert` before scaffolding.
38
32
 
39
33
  ## 3. Scaffold + wire
40
34
 
41
- Run the command from step 1, then fill the `// AGENT: implement here` regions. Register the plugin
42
- in `apps/api/src/extensions.config.ts`. **Order matters for adapters** - last registration of a DI
43
- token wins, so list a swap AFTER the module that owns the default binding.
35
+ Run the command from step 1, then fill the `// AGENT: implement here` regions. Register the plugin in `apps/api/src/extensions.config.ts`. **Order matters for adapters** - last registration of a DI token wins, so list a swap AFTER the module that owns the default binding.
44
36
 
45
37
  ```ts
46
38
  // good - swap binds after the owning module, so it replaces the default
@@ -52,12 +44,9 @@ plugins: [myCustomPspAdapter, walletModule];
52
44
 
53
45
  ## 4. Non-negotiables
54
46
 
55
- - **Boundaries**: import only package entrypoints (`@openora/core`, not `.../src` or `.../dist`).
56
- No imports between extensions; cross-extension data goes through the oRPC client or a schema subpath.
57
- - **Tables**: live in the overlay's own `src/schema/index.ts`; follow `db-conventions` (snake_case,
58
- `timestamp({ withTimezone: true })`). Run `pnpm db:migrate` after.
59
- - **Audit every mutation**: each state-changing action emits a domain event the `audit` add-on
60
- subscribes to, or resolves `AUDIT_WRITER` and calls `record(...)`. A mutation with no audit is not done.
47
+ - **Boundaries**: import only package entrypoints (`@openora/core`, not `.../src` or `.../dist`). No imports between extensions; cross-extension data goes through the oRPC client or a schema subpath.
48
+ - **Tables**: live in the overlay's own `src/schema/index.ts`; follow `docs/standards/database.md` (snake_case, `timestamp({ withTimezone: true })`). Run `pnpm db:migrate` after.
49
+ - **Audit every mutation**: each state-changing action emits a domain event the `audit` add-on subscribes to, or resolves `AUDIT_WRITER` and calls `record(...)`. A mutation with no audit is not done.
61
50
  - **Validate at the edge**: Zod schemas for every route input/output; no inline `fetch`/SQL in handlers.
62
51
 
63
52
  ## 5. Verify
@@ -0,0 +1,37 @@
1
+ ---
2
+ name: create-pr
3
+ targets: ['*']
4
+ description: Commit, push, and open a pull request on this repo's forge, targeting the branch `docs/agents/forge.md` names. Use on "create pr", "create mr", "open a pr/mr", "/create-pr", or "promote <branch>".
5
+ ---
6
+
7
+ # create-pr ({{name}})
8
+
9
+ `docs/agents/forge.md` is the source of truth for this repo's forge: which CLI to use, how to open and read a pull request, and where a change lands. Read it first - the steps below never hardcode a forge command.
10
+
11
+ ## Steps
12
+
13
+ 1. **Determine source + target.** `git branch --show-current`, then take the target from the "Where a change lands" section of `docs/agents/forge.md`.
14
+ 2. **Land the paired OSS change first, if there is one.** It is paired when `{{ossDir}}/.worktrees/<branch, / as +>` exists or `git -C {{ossDir}} branch --list <branch>` matches. First finish step 3 of "Changing OSS core" in the `oss-boundaries` rule (verify, OSS review, no open BLOCK). Then run steps 3-7 inside that worktree under the OSS repo's own delivery rules (`<worktree>/docs/standards/skills/delivery.md`: `gh`, its PR template, `pnpm verify`, public-record rules), with its own explicit push confirmation. Reuse an open OSS PR (`gh pr list --head <branch>` in the worktree).
15
+ 3. **Scope the commit.** `git status -s`. Commit ONLY changes that belong to this unit of work. If unrelated/pre-existing edits are present, do NOT bundle them - stage your files explicitly and tell the user what you left out. Never `git add -A` blindly when foreign changes are in the tree.
16
+ 4. **Commit.** Conventional-commit message (`feat:`, `fix:`, `docs:`, `refactor:`, `chore:`); the scope is a commitlint-enum package or app, never the ticket key; for ticket work the key goes at the END of the subject (e.g. `feat(web): add deposit limits ({{trackerKey}}-123)`). No "Co-Authored-By" / "Generated with" trailers.
17
+ 5. **Verify the commit.** Run `pnpm verify` on the committed, clean tree: it is the pre-MR gate and records the verified commit. The `guard-mr` hook refuses to open the pull request until that record matches HEAD. Don't push a red tree.
18
+ 6. **Push** the current branch - but STOP and get an explicit per-action "yes push" from the user FIRST. The one exception: run by `ship` without `--ask`, the `/ship` invocation is that yes for its ticket branch only. Report the commit SHA, then ask. Invoking this skill is NOT push authorization. Pushing to a shared/env branch (`{{mrTarget}}`, `stage`, `prod`) without that explicit yes is forbidden. Only after the yes: `git push -u origin <current>`.
19
+ 7. **Open the pull request as a draft** using the command in `docs/agents/forge.md` (only after the push is confirmed and done). Run by `ship`: stop here, its step 7 marks the request ready. Otherwise start `node .rulesync/skills/ship/watch-pr.mjs <branch> --until-green` as a background command, never a sleep loop; at `green` mark the request ready for review (`docs/agents/forge.md`). Red stays a draft: fix it first. Reuse an open request for the same source -> target instead of creating a duplicate, and never delete a long-lived branch on merge.
20
+ 8. **Report** the pull-request URL back to the user, and the OSS PR URL when paired.
21
+
22
+ ## Pull-request description
23
+
24
+ - State the user-facing change and its reason briefly.
25
+ - Add short, reproducible local test steps for the changed behavior (for example, `pnpm dev` then the relevant URLs or user flow).
26
+ - Close the ticket by key at the end: `Closes <KEY>-n` if this PR finishes it, else `Refs <KEY>-n` (see `docs/agents/issue-tracker.md`).
27
+ - Do not include a generic verification-command list: CI already reports those checks.
28
+ - **Attach the manual-verification evidence.** The videos are what a reviewer reads as proof of a user-visible change: one short clip per acceptance criterion, embedded under that criterion, the before/after pair on a fix. A screenshot only where a clip adds nothing, such as a second theme. Upload each file to the forge and embed the markdown it returns - `docs/agents/forge.md` says how (its "Attach evidence" section). A local path under `apps/e2e/test-results/` shows a reviewer nothing; never put one in a description. An API-only change attaches the request/response trace instead. Paste the `tester` pass's verdict table next to it. Skip this only when nothing user-visible changed.
29
+ - **Diagram the flow.** A change that adds or changes a flow across components (a request path through gates and a vendor, a state machine, an async job or webhook, a new module or overlay) embeds a fenced `mermaid` block (`flowchart` or `sequenceDiagram`), right after the summary - GitHub and GitLab both render it. Name nodes as the code does, keep it under ~15 nodes, include the refusal and failure branches. No flow (copy, styling, deps, a one-file fix): no diagram.
30
+ - A paired change links neither way: the shared branch name pairs the two requests. The OSS repo is public, so its PR never names this repo or the operator; this request may be read by people outside the team, so it never names or links the OSS repo.
31
+
32
+ ## Rules
33
+
34
+ - NEVER push without an explicit per-action "yes push" from the user (or `/ship` on its ticket branch, see step 6). Invoking this skill does NOT authorize a push. Report the commit SHA, ask, then push only on yes.
35
+ - `pnpm verify` must pass on the commit you push.
36
+ - Keep the pull request scoped to one concern; split unrelated changes into separate ones.
37
+ - No AI-attribution trailers anywhere - not in the commit, not in the pull-request title or description. No "Generated with", no "Co-Authored-By: Claude", no robot-emoji footer.
@@ -0,0 +1,96 @@
1
+ ---
2
+ name: create-task
3
+ targets: ['*']
4
+ description: Create or rewrite this operator's Jira tickets in a lean, bulleted, easy-to-scan format, from a wiki spec page, a design prototype, or plain notes. Use on "create task", "new ticket", "rewrite ticket", "turn this into Jira issues", "break this feature down in Jira", "/create-task", or any {{trackerKey}}-XXX description work.
5
+ ---
6
+
7
+ # create-task ({{name}})
8
+
9
+ Template and clean up Jira tickets for this operator's project so they are short, scannable, and free of filler. Use for new tasks, for breaking a spec or design into issues, and for rewriting bloated ones.
10
+
11
+ ## Jira coordinates
12
+
13
+ - Tool: the **Atlassian** MCP - read the issue, create/edit the issue.
14
+ - `cloudId`: `{{jiraCloudId}}` (`{{jiraSite}}`)
15
+ - Project key: `{{trackerKey}}` (ticket keys look like `{{trackerKey}}-XXX`)
16
+ - Always pass `contentFormat: "markdown"` and `responseContentFormat: "markdown"`, except for checkable acceptance criteria (see gotchas).
17
+ - Epic link: the standard `parent` field (`parent: { key: "<EPIC-KEY>" }`), not the deprecated Epic Link custom field.
18
+
19
+ ## Issue type
20
+
21
+ | Type | When |
22
+ | --- | --- |
23
+ | Epic | One per module spec page. Description empty. Confirm with the user before creating one. |
24
+ | Story | One per sub-feature, or per distinct flow or command inside it. The common case. |
25
+ | Task | Small freestanding work: bugfix, config change, provider swap, spike. Also a shipped feature that drifted from its design. |
26
+
27
+ No sub-tasks, sprints, or test links: other processes own those. Leave assignee unset and priority at the project default unless the user says otherwise.
28
+
29
+ ## Source rules
30
+
31
+ - **Wiki page** (`{{wikiSpace}}` space): read it whole per `docs/agents/issue-tracker.md`, images and comments included. Pull scenarios, rules, limits, and role names from the page; never invent them. Link the page.
32
+ - **Design prototype** (URL or screenshot): acceptance criteria cover only what is visible - layout, states, copy, controls. Rules the design cannot show (limits, validation, rate caps) go to **Open questions**, not criteria.
33
+ - **Plain notes**: feature-sized -> full template, ask for what you would normally read from a spec. Small -> Task with **Goal** + **Tasks** only.
34
+ - Anything you filled in from judgement is listed under **Open questions** in chat, never asserted as a criterion.
35
+ - Unsure whether it is a Task or a Story: ask. The wrong one buries a feature in a one-liner or pads a bugfix with empty sections.
36
+
37
+ ## Writing rules
38
+
39
+ - Lead with **Goal** (1-2 lines). Reader should get the point in 5 seconds.
40
+ - Everything else is **bullets**. No long prose paragraphs.
41
+ - Cut: progress logs, "we decided to instead", history, anything not actionable. State the current decision, not how we got there.
42
+ - Short dashes `-` only, never long dashes. ASCII only.
43
+ - Use `->` for flows, `x3` for counts, backticks for commands/env vars/paths.
44
+ - Acceptance criteria are flat statements with real values: "Player can send a message (max 500 characters)", not "should be able to".
45
+ - Name the owner-confirmed decisions inline with date + who (e.g. "confirmed with <owner> 2026-06-15") so they are not relitigated.
46
+ - Scope tightly. Push anything bigger into a separate ticket and say so in **Out of scope**, citing the real key. Sibling not filed yet: say so in chat, never invent a key.
47
+
48
+ ## Jira gotchas
49
+
50
+ - **Markdown checkboxes break.** `- [ ]` renders as literal `\[ \]`. Default to plain `-` bullets. Only when the user asks for checkable criteria: build the whole description as ADF (`heading`, `bulletList`, `taskList` nodes) and send `contentFormat: "adf"`. Each `taskItem` has `state: "TODO"` and every `localId` is a real UUID (`uuidgen`): a short id like `ac-1` saves fine and renders no checkbox. Fetch back with `responseContentFormat: "adf"` and confirm the `taskList` survived.
51
+ - The summary is plain text: `&amp;` or `&mdash;` arrive literally.
52
+ - Markdown `##` headings and `**bold**` convert cleanly; tables convert too. Markdown writes need no re-read.
53
+
54
+ ## Section template (drop unused sections)
55
+
56
+ ```markdown
57
+ ## Goal
58
+
59
+ <1-2 lines: what ships and for whom>
60
+
61
+ ## Decisions
62
+
63
+ - <key tech/approach choice, with confirmer + date if relevant>
64
+
65
+ ## Scope / What to build
66
+
67
+ - <bulleted, concrete>
68
+
69
+ ## Tasks
70
+
71
+ - <ordered, each a discrete unit of work>
72
+
73
+ ## Links
74
+
75
+ - <spec page, design, vendor docs>
76
+
77
+ ## Out of scope
78
+
79
+ <comma list, point to follow-up tickets>
80
+
81
+ ## Acceptance criteria
82
+
83
+ - <observable, testable outcomes>
84
+ ```
85
+
86
+ Infra/DevOps tickets: swap **Scope** for **Provision** (services as bullets) + a **One-time bootstrap** section. Cross-cutting infra a module depends on: swap **Out of scope** for **Key assumptions**. Link a prior infra ticket as a worked example if one exists.
87
+
88
+ Spikes (research with no code output): **Context** (what and why) + **Links** + criteria as deliverables ("Compare cost, coverage, integration effort", "Written recommendation", "Client confirms the decision" when sign-off is the end point). Compliance-sensitive spikes (payments, KYC/AML, data handling) name the licence jurisdiction that constrains them.
89
+
90
+ ## Flow
91
+
92
+ 1. If rewriting: read the issue whole per `docs/agents/issue-tracker.md` (`atlassian-read`; comments and images included) - a rewrite that drops a decision buried in a comment or a screenshot is a regression.
93
+ 2. Read the source per **Source rules**, plus any context it references (Slack decision, sibling ticket).
94
+ 3. Find the epic: `project = {{trackerKey}} AND issuetype = Epic AND summary ~ "<module>"`. Then list its children (`parent = <EPIC-KEY>`) to see what is already covered and which keys to cross-reference.
95
+ 4. Source covers several flows: propose the split (one line per issue) and get a yes before drafting.
96
+ 5. Draft in chat with **Open questions** listed separately. Create or edit only after the user confirms. Report the ticket key + URL.