@openora/create 0.4.1-canary.397 → 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 (27) hide show
  1. package/dist/.tsbuildinfo +1 -1
  2. package/dist/generated/versions.js +1 -1
  3. package/package.json +2 -2
  4. package/template/__dot__claude/settings.json.tpl +8 -0
  5. package/template/__dot__gitignore +0 -5
  6. package/template/__dot__rulesync/hooks/_shared.mjs +12 -34
  7. package/template/__dot__rulesync/hooks/guard-core.mjs.tpl +39 -17
  8. package/template/__dot__rulesync/hooks/guard-generated.mjs +1 -4
  9. package/template/__dot__rulesync/hooks/guard-mr.mjs +78 -16
  10. package/template/__dot__rulesync/hooks/guard-review.mjs +280 -0
  11. package/template/__dot__rulesync/hooks/guard-stack.mjs +35 -0
  12. package/template/__dot__rulesync/hooks/post-edit.mjs.tpl +1 -1
  13. package/template/__dot__rulesync/hooks.json +10 -0
  14. package/template/__dot__rulesync/rules/overview.md +1 -1
  15. package/template/__dot__rulesync/skills/agent-retro/SKILL.md.tpl +81 -0
  16. package/template/__dot__rulesync/skills/agent-retro/scan.mjs +420 -0
  17. package/template/__dot__rulesync/skills/create-pr/SKILL.md.tpl +1 -1
  18. package/template/__dot__rulesync/skills/review/SKILL.md.tpl +3 -3
  19. package/template/__dot__rulesync/skills/ship/SKILL.md.tpl +6 -6
  20. package/template/__dot__rulesync/skills/ship/watch-pr.mjs +24 -7
  21. package/template/docs/agents/cross-repo.md.tpl +0 -1
  22. package/template/docs/agents/forge.md.tpl +4 -2
  23. package/template/docs/standards/git-delivery.md +13 -0
  24. package/template/docs/standards/module-structure.md +8 -8
  25. package/template/package.json.tpl +1 -1
  26. package/template/rulesync.jsonc +1 -2
  27. package/template/tools/sync-agents.mjs +23 -7
@@ -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
+ }
@@ -16,7 +16,7 @@ description: Commit, push, and open a pull request on this repo's forge, targeti
16
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
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
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** using the command in `docs/agents/forge.md` (only after the push is confirmed and done). Reuse an open request for the same source -> target instead of creating a duplicate, and never delete a long-lived branch on merge.
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
20
  8. **Report** the pull-request URL back to the user, and the OSS PR URL when paired.
21
21
 
22
22
  ## Pull-request description
@@ -28,7 +28,7 @@ Checklist - tick as you go:
28
28
  - `--agents N` - parallel reviewers (2-4); default 2 (§5).
29
29
  - `--base <ref>` - diff base; default `{{mrTarget}}`.
30
30
  - `--full` - ignore the previous review (§2a) and review the whole change.
31
- - `<number>` - a pull request: read its patch and intent with the commands in `docs/agents/forge.md`.
31
+ - `<number>` - a pull request: read its patch and intent with the commands in `docs/agents/forge.md`. Only your own: a pull request whose author is not the forge user you are logged in as is refused (say so and stop); a person reviews it, with the `pr-manual-review` skill when the repo has one. `--ci` (the forge bot) is exempt. So `--post` only ever posts on your own pull request.
32
32
  - paths - restrict review to those files/dirs.
33
33
  - `--fix` - apply BLOCK/WARN fixes after the review; default report-only.
34
34
  - `--post` - publish findings to the pull request as inline diff-line comments + a one-line summary verdict (§8). Requires a pull-request number. Draft-and-confirm by default.
@@ -129,7 +129,7 @@ Applies to every change that crosses a layer: an oRPC route, a service, a Drizzl
129
129
  3. Service - open every callee; typed failures return, unexpected errors do not leak to the client.
130
130
  4. Query - every read and write filters by owner/tenant; a write and its ledger/audit row share one transaction.
131
131
  5. Table - the invariant lives in a constraint, index, or FK per `docs/standards/database.md`, not only in code; a migration exists for every schema change.
132
- 6. Side effects - an event, job, or outbox message fires after commit and its handler is safe to run twice.
132
+ 6. Side effects - an informational event or job fires after commit; a money, compliance or RG event is written in the transaction via `emitInTransaction` (outbox). Every handler is safe to run twice.
133
133
  7. Response - output matches the contract schema and leaks no extra field; each error path returns the code the client expects.
134
134
 
135
135
  **Check the blast radius.** The change must not break a part it does not name. Build the caller list with `git grep -w -- <symbol> -- '*.ts' '*.tsx' '*.sql'` for each changed export, table symbol, and SQL table name, then confirm each use still holds:
@@ -208,7 +208,7 @@ Dedup by `file:line`, order BLOCK -> WARN -> INFO.
208
208
 
209
209
  **Prior findings.** One `PRIOR:` line each: `fixed`, `still open`, or `obsolete` from the reviewer that re-verified it, `carried` for the rest. `still open` and `carried` findings count toward the verdict like new ones.
210
210
 
211
- **Save the state** after every review, `--ci` included: write `.claude/reviews/<pr or branch>.json` in the main checkout with the reviewed HEAD SHA, base, verdict, every open finding (new, `still open`, `carried`), and the `DIMENSION:` lines.
211
+ **Save the state** after every review, `--ci` included: write `.claude/reviews/<pr or branch>.json` in the main checkout (for an OSS branch: in its `{{ossDir}}/.worktrees/<branch, / as +>/`, since the OSS main checkout is read-only here and `guard-review` reads the worktree too) with `sha` (the full `git rev-parse HEAD` reviewed), `base`, `verdict` (the bare `APPROVED` or `CHANGES REQUESTED`; the `guard-review` hook reads it before every push and new MR/PR), every open finding (new, `still open`, `carried`), and the `DIMENSION:` lines.
212
212
 
213
213
  Default and `--post`: a human-readable report - one line per finding `[SEV] file:line - finding - evidence - rule cited - fix`, one `TRACE:` line per traced entry point (format below), one status line per AC bullet, the `PRIOR:` lines, the `SKIPPED:` count, the seven `DIMENSION:` lines, and **APPROVED** / **CHANGES REQUESTED** with the most critical finding last. `--post` rewrites those findings into the §8 comments.
214
214
 
@@ -31,7 +31,7 @@ The orchestrator: one ticket key in, a green MR in Code Review out. You own the
31
31
  - Git: commits on the ticket branch `<type>/{{trackerKey}}-XXX/<slug>` and pushing it. Never a push to `{{mrTarget}}`, `stage`, `prod` or any shared branch.
32
32
  - Force-push: only `git push --force-with-lease` on the ticket branch, and only while every commit on the remote branch past `{{mrTarget}}` is your own (`git log --format=%ae origin/{{mrTarget}}..origin/<branch>` shows only your `git config user.email`). Someone else's commit there: merge, never push over it. Never a plain `--force`.
33
33
  - Merging: into a feature branch only (`{{mrTarget}}` merged into the ticket branch to clear conflicts, a stacked MR into its parent ticket branch). Never into `{{mrTarget}}`, `dev`, `develop`, `stage`, `staging`, `prod`, `production`, `main` or `master`.
34
- - The forge: opening the MR for that branch and replying on its review threads. Every comment you leave starts with `Agent:`, so `watch-pr.mjs` and other tools never take it for one to answer.
34
+ - The forge: opening the MR for that branch and reacting on its review threads (`eyes` picked up, `thumbsup` fixed, `question` needs an answer). Never a reply, review or comment on the MR: the developer writes MR text by hand. Your `thumbsup` or `question` on a thread's last comment is what tells `watch-pr.mjs` it is handled; `eyes` alone stays pending.
35
35
  - Slack: nothing. Announcing the MR is the forge integration's job, so ship never drafts a notice.
36
36
 
37
37
  ## Do what the work needs, inside the worktree
@@ -73,7 +73,7 @@ Every run starts here, so a run that died midway resumes where it stopped. Read
73
73
  | Plan, no branch | 2. Build |
74
74
  | Branch, no MR | 3. Test, 4. Review, 4b. Evidence, 5. Open the MR |
75
75
  | MR open, CI red or conflicts | 6. `fix-pipeline` skill |
76
- | MR open, review threads with no reply | 6. `fix-review-comments` skill |
76
+ | MR open, review threads with no reaction | 6. `fix-review-comments` skill |
77
77
  | MR open, CI running, or green and answered | 7. Ready for review |
78
78
  | MR merged or closed | Report it, do nothing |
79
79
 
@@ -121,7 +121,7 @@ The code is final now, so the videos are recorded once, here, never in an earlie
121
121
 
122
122
  ### 5. Open the MR
123
123
 
124
- `--ask`: report the SHA and stop for "yes push". Then run **create-pr** with the tester's AC table and the 4b videos. Comment the MR link on the ticket and move it to Code Review in the same turn. Then 7.
124
+ The pushed HEAD is the commit step 4 approved: anything committed after it, 4b specs included, goes back to 4 first (`guard-review` blocks the push otherwise). That round counts against the budget of three, and 4b is not repeated unless app code changed. `--ask`: report the SHA and stop for "yes push". Then run **create-pr** (it opens the MR as a draft) with the tester's AC table and the 4b videos. Comment the MR link on the ticket and move it to Code Review in the same turn. Then 7.
125
125
 
126
126
  ### 6. Red CI and review comments
127
127
 
@@ -130,7 +130,7 @@ Run the repo's `fix-pipeline` skill on a red pipeline or conflicts, `fix-review-
130
130
  - Each thread is checked against the code on this branch first: correct | already handled | wrong on this branch | out of scope. Only a correct one changes code; the rest get an answer.
131
131
  - A red job is reproduced locally first; `builder` fixes its cause. Never skip or loosen a test.
132
132
  - Every fix goes to `builder`. Then `tester` re-runs the cases the fix touches and leaves a test that fails without it, and 4 runs on the new commits. Then 4b records again only the ACs the fix touched, and their clips replace the old ones in the MR description. Nothing is pushed untested.
133
- - Push the ticket branch without asking (a force-push only as above). Reply per thread, in the thread itself, with what changed and the test that proves it, or why nothing changed. Resolve only a thread the fix addressed; a question or a disagreement stays open for the reviewer.
133
+ - Push the ticket branch without asking (a force-push only as above). React per thread instead of replying: `thumbsup` and resolve when the fix addressed it, `question` when it needs an answer or you disagree; that thread stays open and its question goes in the ticket's questions comment, the single place for open questions.
134
134
 
135
135
  Then 7.
136
136
 
@@ -138,9 +138,9 @@ Then 7.
138
138
 
139
139
  Start `node <this skill's folder>/watch-pr.mjs <branch> --until-green` as a background command, never a sleep loop in the session. It prints one line and exits when there is work:
140
140
 
141
- - `failed` or `conflicts` -> 6, then watch again. Still red after three fixes -> blocker comment, report, stop.
141
+ - `failed` or `conflicts` -> 6, then watch again. Still red after three fixes -> blocker comment, report, stop. Ten fix rounds in total after the push (pipeline and threads together) and the MR still is not ready -> blocker comment, report, stop: a person takes it from there.
142
142
  - `threads <ids>` (unanswered for two checks in a row, from a person or a bot) -> 6 for those, then watch again. A thread the forge's AI review opens is a blocker it found on this head: it counts like a person's.
143
- - `green` -> check the MR is ready (below), report "Ready for review:" and the MR URL, then watch again without `--until-green`.
143
+ - `green` -> check the MR is ready (below). Ready: mark the draft ready for review (`docs/agents/forge.md`), report "Ready for review:" and the MR URL, then watch again without `--until-green`. Not ready: it stays a draft. Fix what is yours (the description, an unanswered thread) and watch again with `--until-green`; what only a person can supply (an UNCHECKED row) -> report "Draft, missing:" and the list, stop.
144
144
  - `merged` or `closed` -> report it, drop the worktree's database and Redis db, stop. `error ...` -> report it, stop.
145
145
 
146
146
  Ready means: the pipeline on the last commit is green, no conflicts with `{{mrTarget}}`, every thread has an answer, no money, KYC, responsible-gambling or authz case or mutation row is UNCHECKED or SURVIVED, and the description holds the AC table, the screenshots and the UNCHECKED rows.
@@ -1,8 +1,8 @@
1
1
  #!/usr/bin/env node
2
2
  // Watches the MR or PR of a branch and prints one line, then exits, when ship has work on it:
3
3
  // failed | conflicts | threads <ids> | green (only with --until-green) | merged | closed | error <message>
4
- // A thread waits for an answer until its last comment is an "Agent:" reply from the account this runs as
5
- // (anyone can type the prefix); it is reported once it stayed the same for two checks, so a review with
4
+ // A thread waits for an answer until the account this runs as left a final reaction on its last comment (thumbsup
5
+ // or question; eyes only means picked up and stays pending: the agent never writes on the MR) or that comment is its legacy "Agent:" reply; it is reported once it stayed the same for two checks, so a review with
6
6
  // ten comments is one line. Run it in the background:
7
7
  // node watch-pr.mjs <branch> [--until-green] WATCH_DEBUG=1 prints every check to stderr
8
8
  // --once checks one time, for a caller that polls on its own (a scheduler): threads are reported at
@@ -39,7 +39,9 @@ const json = (cmd, args) => JSON.parse(run(cmd, args));
39
39
  const unansweredIds = (lastComments, me) =>
40
40
  lastComments
41
41
  .filter(
42
- (comment) => !(comment.author === me && comment.body.trimStart().startsWith(AGENT_REPLY)),
42
+ (comment) =>
43
+ !(comment.author === me && comment.body.trimStart().startsWith(AGENT_REPLY)) &&
44
+ !comment.reactors.includes(me),
43
45
  )
44
46
  .map((comment) => String(comment.id))
45
47
  .sort();
@@ -48,10 +50,10 @@ const THREADS = `query($owner: String!, $name: String!, $number: Int!, $endCurso
48
50
  viewer { login }
49
51
  repository(owner: $owner, name: $name) { pullRequest(number: $number) {
50
52
  reviewThreads(first: 100, after: $endCursor) {
51
- nodes { isResolved comments(last: 1) { nodes { id body author { login } } } }
53
+ nodes { isResolved comments(last: 1) { nodes { id body author { login } reactions(first: 50) { nodes { content user { login } } } } } }
52
54
  pageInfo { hasNextPage endCursor }
53
55
  }
54
- comments(last: 1) { nodes { id body author { login } } }
56
+ comments(last: 1) { nodes { id body author { login } reactions(first: 50) { nodes { content user { login } } } } }
55
57
  } }
56
58
  }`;
57
59
 
@@ -84,7 +86,13 @@ function github() {
84
86
  .filter((thread) => !thread.isResolved)
85
87
  .flatMap((thread) => thread.comments.nodes)
86
88
  .concat(pages[0].repository.pullRequest.comments.nodes)
87
- .map((comment) => ({ ...comment, author: comment.author?.login }));
89
+ .map((comment) => ({
90
+ ...comment,
91
+ author: comment.author?.login,
92
+ reactors: comment.reactions.nodes
93
+ .filter((reaction) => reaction.content !== 'EYES')
94
+ .map((reaction) => reaction.user?.login),
95
+ }));
88
96
  const checks = pr.statusCheckRollup ?? [];
89
97
  const ci = !checks.length
90
98
  ? null
@@ -128,7 +136,16 @@ function gitlab() {
128
136
  ),
129
137
  )
130
138
  .map((notes) => notes.at(-1))
131
- .map((note) => ({ ...note, author: note.author?.username }));
139
+ .map((note) => ({
140
+ ...note,
141
+ author: note.author?.username,
142
+ reactors: json('glab', [
143
+ 'api',
144
+ `projects/${mr.project_id}/merge_requests/${mr.iid}/notes/${note.id}/award_emoji`,
145
+ ])
146
+ .filter((award) => award.name !== 'eyes')
147
+ .map((award) => award.user?.username),
148
+ }));
132
149
  const pipeline = mr.head_pipeline?.sha === mr.sha ? mr.head_pipeline.status : null;
133
150
  const ci = !pipeline
134
151
  ? null
@@ -31,7 +31,6 @@ Grant the whole `{{ossDir}}`, not only `.worktrees/`: a worktree keeps its git m
31
31
 
32
32
  - **Claude Code**: `permissions.additionalDirectories: ["{{ossDir}}"]` in `.claude/settings.json`, checked in. Takes effect once the workspace is trusted. That grants file access only; `claude --add-dir {{ossDir}}` (or `/add-dir {{ossDir}}`) also loads the OSS repo's skills and agents, and with `CLAUDE_CODE_ADDITIONAL_DIRECTORIES_CLAUDE_MD=1` in the `env` block of `.claude/settings.json`, checked in, its `CLAUDE.md` and `.claude/rules/`.
33
33
  - **Codex CLI**: `codex --add-dir {{ossDir}}`. `.codex/config.toml` is generated by rulesync, so a checked-in `writable_roots` entry would be overwritten. A personal alternative is `[sandbox_workspace_write] writable_roots` in `~/.codex/config.toml` with an absolute path.
34
- - **GitHub Copilot CLI**: `copilot --add-dir {{ossDir}}`, or `/add-dir {{ossDir}}` in the session. No project-level key exists.
35
34
  - **Gemini CLI**: `gemini --include-directories {{ossDir}}`, or `/directory add {{ossDir}}`. `.gemini/settings.json` is generated by rulesync.
36
35
 
37
36
  Each tool reads only this repo's instruction files at start. The rules therefore tell every agent to read the OSS repo's `AGENTS.md`, `.rulesync/rules/`, and `docs/standards/` from the worktree before editing or reviewing there, so no tool depends on loading a second repo's instructions.
@@ -2,7 +2,7 @@
2
2
 
3
3
  Code review for `{{gitRemotePath}}` happens on GitHub pull requests, driven by the [`gh`](https://cli.github.com) CLI. Every skill that opens, reads, or comments on a pull request reads this file instead of hardcoding commands, so a repo on a different forge rewrites this one file and the skills keep working.
4
4
 
5
- Swapping forge: keep the headings below and replace the commands. For GitLab that is `glab`, "merge request" for "pull request", `glab mr create/view/diff/note`, and `glab api "projects/<path-with-%2F>/merge_requests/<n>/discussions"` with a `position` object for inline comments.
5
+ Swapping forge: keep the headings below and replace the commands. For GitLab that is `glab`, "merge request" for "pull request", `glab mr create --draft`, `glab mr update <n> --ready`, `glab mr view/diff/note`, and `glab api "projects/<path-with-%2F>/merge_requests/<n>/discussions"` with a `position` object for inline comments.
6
6
 
7
7
  ## Coordinates
8
8
 
@@ -18,9 +18,11 @@ Swapping forge: keep the headings below and replace the commands. For GitLab tha
18
18
  ## Open a pull request
19
19
 
20
20
  ```
21
- gh pr create --base <target> --head <current> --title "<type>: <summary>" --body "<body>"
21
+ gh pr create --draft --base <target> --head <current> --title "<type>: <summary>" --body "<body>"
22
22
  ```
23
23
 
24
+ A new pull request opens as a draft. Once its pipeline on the last commit is green, mark it ready for review: `gh pr ready <n>`. A red one stays a draft until it is fixed.
25
+
24
26
  Reuse an open PR for the same head -> base instead of opening a duplicate: `gh pr list --head <current> --base <target>`. Never delete a long-lived branch on merge.
25
27
 
26
28
  ## Read a pull request
@@ -10,6 +10,19 @@ Read this before a commit, PR, or branch operation.
10
10
  the tree.
11
11
  - Green before review: `pnpm verify` on the committed tree. It is the full gate and records the
12
12
  verified commit; the `guard-mr` hook blocks opening the PR/MR without it.
13
+ - Reviewed before it leaves the machine: an agent runs `ship`, or the `review` skill until
14
+ APPROVED, before every push, including a branch already in review and a push after a rebase or
15
+ a pipeline fix. The `guard-review` hook blocks a push or a new PR/MR until a review approved
16
+ that exact HEAD; a promotion from a shared branch, a branch delete, and a tag push pass.
17
+ - On GitHub, a PR that builds on another feature branch goes up as a native stacked PR with
18
+ `gh stack` (`init`, `add`, `submit`, `sync`); the `guard-stack` hook blocks a plain PR based on
19
+ a feature branch. Each layer is reviewed on its own.
20
+ - A PR/MR opens as a draft and is marked ready for review once its pipeline on the last commit
21
+ is green; a red one stays a draft. For a stack that means `gh stack submit --auto` (new layers
22
+ open as drafts; never `--open`), then `gh pr ready <n>` per layer as its pipeline goes green.
23
+ - The merge bot merges. `guard-review` denies an agent's `gh pr merge`, `gh stack merge`,
24
+ `glab mr merge` and any push to a shared branch; a person who has to do one runs it from their
25
+ own terminal.
13
26
  - Branch off `dev`; never commit directly to a shared branch; never push without an explicit
14
27
  per-action "yes push", except the ticket branch `/ship` opens its MR from.
15
28
  - PR description carries intent: what / why / acceptance criteria / ticket link. No secrets,