kiro-10x-better 1.0.4 → 1.1.0

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.
package/README.md CHANGED
@@ -50,7 +50,11 @@ npx kiro-10x-better --global
50
50
  - `security-guard.json` + `scripts/guard.cjs` (`PreToolUse`): Hard-blocks destructive commands (`rm -rf`, `git push --force`, `git reset --hard`, `DROP TABLE`) and writes to `.env` or private key files.
51
51
  - `auto-lint.json` (`PostFileSave`): Auto-detects `pnpm`/`yarn`/`npm` and `biome`/`eslint`/`prettier` from your project (or disables itself if none are found).
52
52
  - `verify-after-task.json` (`PostTaskExec` + `SubagentStop`): Runs `tsc --noEmit` when `tsconfig.json` is present and prompts subagents for fresh verification output.
53
- - **Permissions (`~/.kiro/settings/permissions.yaml`):** Safe read/test/lint allowlist, confirmation prompts for pushes/installs, and hard-denies for destructive commands and secret files.
53
+ - `turn-checkpoint.json` + `scripts/checkpoint.cjs` (`UserPromptSubmit`): Silently snapshots the working tree via shadow Git refs (`refs/kiro/checkpoints/*`, keeping `.git/index` and `git status` untouched) and resets `.loop-state.json`. Run `node .kiro/hooks/scripts/checkpoint.cjs list | diff | restore [turn-id]` anytime to inspect or rewind edits.
54
+ - `stop-verify-loop.json` + `scripts/verify-loop.cjs` (`Stop`): Runs fast targeted verification (`kiro:verify`, local `tsc --noEmit`, `node --check`, `py_compile`, or `go vet`) only when code files changed this turn, blocking completion up to 2 retries (`KIRO_LOOP_MAX_RETRIES`) so any model self-heals errors without infinite credit burn.
55
+ - `stack-skill-sync.json` + `scripts/sync-stack-skills.cjs`: Watches `package.json` (`mtimeMs`-cached) to auto-install Web App or Better Auth skills when added later.
56
+ - **Model-Agnostic Loop (`AGENTS.md` / `~/.kiro/steering/AGENTS.md`):** Non-destructively injects a marker-bounded 5-state loop (`SKILL GATE → FAST ORIENT → SURGICAL EDIT → TARGETED VERIFY → EXIT GATE & REWIND`) that preserves existing project instructions.
57
+ - **Permissions (`~/.kiro/settings/permissions.yaml`):** Safe read/test/lint/checkpoint-inspect allowlist, confirmation prompts for pushes/installs/rewinds, and hard-denies for destructive commands and secret files.
54
58
  - **Project Ignores (project mode):** Adds `.kiro/` to `.gitignore` and creates `.kiroignore` blocking `.env*`, `*.pem`, `*.key`, `node_modules/`, `dist/`, and `.next/`.
55
59
 
56
60
  ## Recommended Kiro CLI V3 Settings
package/bin/cli.mjs CHANGED
@@ -305,6 +305,46 @@ function appendAllowRules(homeKiroDir, commands, tracker) {
305
305
  console.log(` update ~/.kiro/settings/permissions.yaml (added ${missing.join(", ")})`);
306
306
  }
307
307
 
308
+ function upsertAgentsMd(targetPath, blockContent, { label, tracker }) {
309
+ const START_MARKER = "<!-- kiro-10x-better:start -->";
310
+ const END_MARKER = "<!-- kiro-10x-better:end -->";
311
+ const trimmedBlock = blockContent.trim();
312
+
313
+ if (!fs.existsSync(targetPath)) {
314
+ fs.mkdirSync(path.dirname(targetPath), { recursive: true });
315
+ fs.writeFileSync(targetPath, `${trimmedBlock}\n`, "utf8");
316
+ tracker.created.push(label);
317
+ console.log(` write ${label}`);
318
+ return;
319
+ }
320
+
321
+ const content = fs.readFileSync(targetPath, "utf8");
322
+ const startIdx = content.indexOf(START_MARKER);
323
+ const endIdx = content.indexOf(END_MARKER);
324
+
325
+ let updated;
326
+ if (startIdx !== -1 && endIdx !== -1 && endIdx >= startIdx) {
327
+ const before = content.slice(0, startIdx);
328
+ const after = content.slice(endIdx + END_MARKER.length);
329
+ updated = `${before}${trimmedBlock}${after}`;
330
+ if (!updated.endsWith("\n")) {
331
+ updated += "\n";
332
+ }
333
+ if (updated === content) {
334
+ tracker.skipped.push(`${label} (already up to date)`);
335
+ console.log(` skip ${label} (already up to date)`);
336
+ return;
337
+ }
338
+ } else {
339
+ const base = content.replace(/\s+$/, "");
340
+ updated = base ? `${base}\n\n${trimmedBlock}\n` : `${trimmedBlock}\n`;
341
+ }
342
+
343
+ fs.writeFileSync(targetPath, updated, "utf8");
344
+ tracker.created.push(label);
345
+ console.log(` update ${label}`);
346
+ }
347
+
308
348
  async function promptYesNo(question, defaultYes = true) {
309
349
  const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
310
350
  try {
@@ -385,7 +425,7 @@ async function main() {
385
425
 
386
426
  console.log(`\nSetting up Kiro CLI V3 in ${targetKiroDir}\n`);
387
427
 
388
- // Step 1: Fast Core Setup (steering, bundled skills, core + watcher hooks, ignores, permissions)
428
+ // Step 1: Fast Core Setup (steering, bundled skills, core + watcher + checkpoint/verify hooks, AGENTS.md, ignores, permissions)
389
429
  copyTemplateFile(
390
430
  path.join("steering", "core-rules.md"),
391
431
  path.join(targetKiroDir, "steering", "core-rules.md"),
@@ -397,16 +437,23 @@ async function main() {
397
437
  `${prefixLabel}/skills`,
398
438
  { force: flags.force, tracker }
399
439
  );
400
- copyTemplateFile(
401
- path.join("hooks", "scripts", "guard.cjs"),
402
- path.join(targetKiroDir, "hooks", "scripts", "guard.cjs"),
403
- { force: flags.force, label: `${prefixLabel}/hooks/scripts/guard.cjs`, tracker }
404
- );
405
- copyTemplateFile(
406
- path.join("hooks", "scripts", "sync-stack-skills.cjs"),
407
- path.join(targetKiroDir, "hooks", "scripts", "sync-stack-skills.cjs"),
408
- { force: flags.force, label: `${prefixLabel}/hooks/scripts/sync-stack-skills.cjs`, tracker }
409
- );
440
+
441
+ const staticHookFiles = [
442
+ ["scripts", "guard.cjs"],
443
+ ["scripts", "sync-stack-skills.cjs"],
444
+ ["scripts", "checkpoint.cjs"],
445
+ ["scripts", "verify-loop.cjs"],
446
+ ["stack-skill-sync.json"],
447
+ ["turn-checkpoint.json"],
448
+ ["stop-verify-loop.json"]
449
+ ];
450
+ for (const parts of staticHookFiles) {
451
+ copyTemplateFile(
452
+ path.join("hooks", ...parts),
453
+ path.join(targetKiroDir, "hooks", ...parts),
454
+ { force: flags.force, label: `${prefixLabel}/hooks/${parts.join("/")}`, tracker }
455
+ );
456
+ }
410
457
 
411
458
  writeTargetFile(
412
459
  path.join(targetKiroDir, "hooks", "security-guard.json"),
@@ -423,11 +470,13 @@ async function main() {
423
470
  buildVerifyConfig(stack),
424
471
  { force: flags.force, label: `${prefixLabel}/hooks/verify-after-task.json`, tracker }
425
472
  );
426
- copyTemplateFile(
427
- path.join("hooks", "stack-skill-sync.json"),
428
- path.join(targetKiroDir, "hooks", "stack-skill-sync.json"),
429
- { force: flags.force, label: `${prefixLabel}/hooks/stack-skill-sync.json`, tracker }
430
- );
473
+
474
+ const agentsBlock = fs.readFileSync(path.join(TEMPLATES_DIR, "agents-block.md"), "utf8");
475
+ const agentsPath = flags.global
476
+ ? path.join(homeKiroDir, "steering", "AGENTS.md")
477
+ : path.join(cwd, "AGENTS.md");
478
+ const agentsLabel = flags.global ? "~/.kiro/steering/AGENTS.md" : "AGENTS.md";
479
+ upsertAgentsMd(agentsPath, agentsBlock, { label: agentsLabel, tracker });
431
480
 
432
481
  if (!flags.global) {
433
482
  updateGitignore(cwd, tracker);
@@ -448,6 +497,14 @@ async function main() {
448
497
  { force: flags.force, label: "~/.kiro/settings/permissions.yaml", tracker }
449
498
  );
450
499
  configureMediumEffort(homeKiroDir, tracker);
500
+ appendAllowRules(
501
+ homeKiroDir,
502
+ [
503
+ "node .kiro/hooks/scripts/checkpoint.cjs list*",
504
+ "node .kiro/hooks/scripts/checkpoint.cjs diff*"
505
+ ],
506
+ tracker
507
+ );
451
508
  }
452
509
 
453
510
  if (flags.withSkills && !flags.coreOnly) {
@@ -552,6 +609,10 @@ async function main() {
552
609
  "\nWeb tip: Run \"npm install -g agent-browser && agent-browser install\" once if you haven't installed the browser binary yet."
553
610
  );
554
611
  }
612
+ console.log("\nHarness Features Enabled:");
613
+ console.log(" - Per-turn snapshots: node .kiro/hooks/scripts/checkpoint.cjs list | diff | restore");
614
+ console.log(" - Stop auto-verify: credit-safe self-heal loop (max 2 retries; override via KIRO_LOOP_MAX_RETRIES)");
615
+ console.log(" - Model-agnostic: 5-state engineering loop injected into AGENTS.md");
555
616
  console.log("\nNext steps in Kiro CLI V3:");
556
617
  console.log(" 1. Enable \"Approve for me\" and Workflows (chat.enableWorkflows) in Kiro settings.");
557
618
  console.log(" 2. Set /effort medium for daily work (or high for complex debugging) and start a fresh kiro-cli session.");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "kiro-10x-better",
3
- "version": "1.0.4",
3
+ "version": "1.1.0",
4
4
  "description": "Instant, zero-dependency CLI to set up a high-discipline Kiro CLI V3 environment with hooks, steering rules, skills, and permissions.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -0,0 +1,35 @@
1
+ <!-- kiro-10x-better:start -->
2
+ # Universal Engineering Loop (`kiro-10x-better`)
3
+
4
+ Follow this strict 5-state execution loop on EVERY coding task regardless of which model is active (Claude, GPT, Grok, Gemini, or open-weight). Never skip states.
5
+
6
+ ## State 1 — SKILL GATE (Check Skills First)
7
+ - Before writing code or running complex commands, check `.kiro/skills/` and load the single best matching skill for the task:
8
+ - Multi-step features, debugging, or subagents → `/pro-workflow`
9
+ - Architecture, new modules, or design interviews → `/codebase-design`
10
+ - PR/diff audits, cleanup, or simplification → `/code-review`
11
+ - Security audits / auth checks → `/security-audit`, `/security-review`, or `/better-auth-security-best-practices`
12
+ - Web UI verification / Core Web Vitals → `/agent-browser` or `/modern-web-guidance`
13
+ - Follow the active skill's workflow strictly; do not wing complex tasks from scratch.
14
+
15
+ ## State 2 — FAST ORIENT (Minimal Context)
16
+ - Locate targets with `rg -n` (or `grep`) before opening files.
17
+ - Read ONLY the relevant functions or line ranges—never dump entire large files into context.
18
+ - State key assumptions or ambiguities upfront in 1–2 concise lines before editing.
19
+
20
+ ## State 3 — SURGICAL EDIT (One Hypothesis at a Time)
21
+ - Make the smallest clean diff required to solve the exact task.
22
+ - Match existing code conventions; do NOT reformat unrelated lines, add speculative abstractions, or modify untouched files.
23
+
24
+ ## State 4 — TARGETED VERIFY & SELF-HEAL LOOP
25
+ - After editing code, immediately run the fastest targeted verification for changed files (typecheck, syntax check, or single test file).
26
+ - If verification fails—or if the `Stop` auto-verify hook blocks completion with errors—fix the **root cause** and re-verify. NEVER silence failures with `any`, `@ts-ignore`, disabled lint rules, or weakened assertions.
27
+
28
+ ## State 5 — EXIT GATE & FILE REWIND
29
+ - Never claim "done" or "fixed" without fresh passing verification output from the current turn.
30
+ - If the same issue fails **3 attempts**, STOP editing, summarize what was tried and what failed, and ask the user for direction.
31
+ - **Per-Turn File Snapshots & Rewind:** Every user prompt automatically saves a zero-pollution Git shadow snapshot. When the user asks to inspect or rewind/undo recent file edits:
32
+ - List snapshots: `node .kiro/hooks/scripts/checkpoint.cjs list`
33
+ - Preview changes: `node .kiro/hooks/scripts/checkpoint.cjs diff [turn-id]`
34
+ - Rewind files (only when explicitly requested by the user): `node .kiro/hooks/scripts/checkpoint.cjs restore [turn-id]`
35
+ <!-- kiro-10x-better:end -->
@@ -0,0 +1,323 @@
1
+ const fs = require("node:fs");
2
+ const path = require("node:path");
3
+ const os = require("node:os");
4
+ const crypto = require("node:crypto");
5
+ const { execFileSync } = require("node:child_process");
6
+
7
+ const SUBCOMMANDS = new Set(["capture", "list", "diff", "restore"]);
8
+ const MAX_CHECKPOINTS = 30;
9
+
10
+ function parseSubcommand() {
11
+ const args = process.argv.slice(1);
12
+ const idx = args.findIndex((a) => SUBCOMMANDS.has(a));
13
+ if (idx === -1) {
14
+ return { cmd: "list", targetId: undefined };
15
+ }
16
+ return { cmd: args[idx], targetId: args[idx + 1] };
17
+ }
18
+
19
+ function isGitRepo(cwd) {
20
+ try {
21
+ const out = execFileSync("git", ["rev-parse", "--is-inside-work-tree"], {
22
+ cwd,
23
+ stdio: "pipe",
24
+ encoding: "utf8"
25
+ });
26
+ return out.trim() === "true";
27
+ } catch {
28
+ return false;
29
+ }
30
+ }
31
+
32
+ function makeTempIndexPath() {
33
+ const name = `kiro-idx-${process.pid}-${Date.now()}-${crypto.randomBytes(4).toString("hex")}`;
34
+ return path.join(os.tmpdir(), name);
35
+ }
36
+
37
+ function captureWorkingTree(cwd) {
38
+ const tmpIndex = makeTempIndexPath();
39
+ const env = { ...process.env, GIT_INDEX_FILE: tmpIndex };
40
+ try {
41
+ execFileSync("git", ["add", "-A"], { cwd, env, stdio: "pipe" });
42
+ return execFileSync("git", ["write-tree"], {
43
+ cwd,
44
+ env,
45
+ stdio: "pipe",
46
+ encoding: "utf8"
47
+ }).trim();
48
+ } finally {
49
+ fs.rmSync(tmpIndex, { force: true });
50
+ }
51
+ }
52
+
53
+ function loadCheckpoints(checkpointsPath) {
54
+ if (!fs.existsSync(checkpointsPath)) {
55
+ return [];
56
+ }
57
+ try {
58
+ const parsed = JSON.parse(fs.readFileSync(checkpointsPath, "utf8"));
59
+ return Array.isArray(parsed) ? parsed : [];
60
+ } catch {
61
+ return [];
62
+ }
63
+ }
64
+
65
+ function saveAndPruneCheckpoints(cwd, checkpointsPath, checkpoints) {
66
+ while (checkpoints.length > MAX_CHECKPOINTS) {
67
+ const evicted = checkpoints.shift();
68
+ if (evicted && evicted.ref) {
69
+ try {
70
+ execFileSync("git", ["update-ref", "-d", evicted.ref], { cwd, stdio: "pipe" });
71
+ } catch {
72
+ // Ignore missing ref on prune
73
+ }
74
+ }
75
+ }
76
+ fs.mkdirSync(path.dirname(checkpointsPath), { recursive: true });
77
+ fs.writeFileSync(checkpointsPath, `${JSON.stringify(checkpoints, null, 2)}\n`, "utf8");
78
+ }
79
+
80
+ function writeLoopState(kiroDir, turnId, preTurnTreeHash) {
81
+ if (!fs.existsSync(kiroDir)) {
82
+ return;
83
+ }
84
+ const statePath = path.join(kiroDir, ".loop-state.json");
85
+ const state = {
86
+ turnId,
87
+ preTurnTreeHash,
88
+ retries: 0,
89
+ maxRetries: 2,
90
+ updatedAt: Date.now()
91
+ };
92
+ fs.writeFileSync(statePath, `${JSON.stringify(state, null, 2)}\n`, "utf8");
93
+ }
94
+
95
+ function readPromptLabelBrief() {
96
+ if (process.stdin.isTTY) {
97
+ return Promise.resolve("");
98
+ }
99
+ return new Promise((resolve) => {
100
+ let raw = "";
101
+ let settled = false;
102
+ const done = (text) => {
103
+ if (settled) return;
104
+ settled = true;
105
+ clearTimeout(timer);
106
+ process.stdin.removeAllListeners();
107
+ if (typeof process.stdin.pause === "function") {
108
+ process.stdin.pause();
109
+ }
110
+ try {
111
+ const parsed = JSON.parse(text.trim());
112
+ const prompt = String(parsed.prompt ?? parsed.message ?? "").replace(/\s+/g, " ").trim();
113
+ resolve(prompt.slice(0, 60));
114
+ } catch {
115
+ resolve("");
116
+ }
117
+ };
118
+
119
+ const timer = setTimeout(() => {
120
+ try {
121
+ process.stdin.destroy();
122
+ } catch {}
123
+ done(raw);
124
+ }, 25);
125
+
126
+ process.stdin.setEncoding("utf8");
127
+ process.stdin.on("data", (chunk) => {
128
+ raw += chunk;
129
+ if (raw.length > 4096) {
130
+ done(raw);
131
+ }
132
+ });
133
+ process.stdin.on("end", () => done(raw));
134
+ process.stdin.on("error", () => done(""));
135
+ process.stdin.resume();
136
+ });
137
+ }
138
+
139
+ function nextTurnId(checkpoints) {
140
+ let maxNum = 0;
141
+ for (const cp of checkpoints) {
142
+ const match = /^turn-(\d+)$/.exec(String(cp.id || ""));
143
+ if (match) {
144
+ maxNum = Math.max(maxNum, Number(match[1]));
145
+ }
146
+ }
147
+ return `turn-${String(maxNum + 1).padStart(4, "0")}`;
148
+ }
149
+
150
+ function resolveCheckpoint(checkpoints, targetId) {
151
+ if (checkpoints.length === 0) {
152
+ return null;
153
+ }
154
+ if (!targetId) {
155
+ return checkpoints[checkpoints.length - 1];
156
+ }
157
+ return checkpoints.find((cp) => cp.id === targetId) || null;
158
+ }
159
+
160
+ async function handleCapture(cwd, kiroDir, checkpointsPath) {
161
+ try {
162
+ if (!isGitRepo(cwd)) {
163
+ writeLoopState(kiroDir, null, null);
164
+ process.exit(0);
165
+ }
166
+
167
+ const label = await readPromptLabelBrief();
168
+ const treeHash = captureWorkingTree(cwd);
169
+ const checkpoints = loadCheckpoints(checkpointsPath);
170
+ const latest = checkpoints[checkpoints.length - 1];
171
+
172
+ let turnId;
173
+ if (latest && latest.treeHash === treeHash) {
174
+ turnId = latest.id;
175
+ } else {
176
+ turnId = nextTurnId(checkpoints);
177
+ const ref = `refs/kiro/checkpoints/${turnId}`;
178
+ execFileSync("git", ["update-ref", ref, treeHash], { cwd, stdio: "pipe" });
179
+ checkpoints.push({
180
+ id: turnId,
181
+ ref,
182
+ treeHash,
183
+ timestamp: new Date().toISOString(),
184
+ label
185
+ });
186
+ saveAndPruneCheckpoints(cwd, checkpointsPath, checkpoints);
187
+ }
188
+
189
+ writeLoopState(kiroDir, turnId, treeHash);
190
+ } catch {
191
+ // Never fail or write stdout during UserPromptSubmit
192
+ }
193
+ process.exit(0);
194
+ }
195
+
196
+ function handleList(cwd, checkpointsPath) {
197
+ if (!isGitRepo(cwd)) {
198
+ console.log("Not inside a git repository. Git is required for turn checkpoints.");
199
+ return;
200
+ }
201
+ const checkpoints = loadCheckpoints(checkpointsPath);
202
+ if (checkpoints.length === 0) {
203
+ console.log("No checkpoints recorded yet.");
204
+ return;
205
+ }
206
+ for (let i = checkpoints.length - 1; i >= 0; i -= 1) {
207
+ const cp = checkpoints[i];
208
+ const ts = String(cp.timestamp || "").replace("T", " ").slice(0, 19);
209
+ const shortHash = String(cp.treeHash || "").slice(0, 7);
210
+ const label = cp.label || "(prompt)";
211
+ console.log(`${cp.id} | ${ts} | ${shortHash} | ${label}`);
212
+ }
213
+ }
214
+
215
+ function handleDiff(cwd, checkpointsPath, targetId) {
216
+ if (!isGitRepo(cwd)) {
217
+ console.log("Not inside a git repository. Git is required for turn checkpoints.");
218
+ return;
219
+ }
220
+ const checkpoints = loadCheckpoints(checkpointsPath);
221
+ const target = resolveCheckpoint(checkpoints, targetId);
222
+ if (!target) {
223
+ console.log(targetId ? `Checkpoint not found: ${targetId}` : "No checkpoints recorded yet.");
224
+ return;
225
+ }
226
+ const currentTree = captureWorkingTree(cwd);
227
+ const diffStat = execFileSync("git", ["diff", "--stat", target.treeHash, currentTree], {
228
+ cwd,
229
+ stdio: "pipe",
230
+ encoding: "utf8"
231
+ }).trim();
232
+ console.log(diffStat || `No changes since ${target.id} (${target.treeHash.slice(0, 7)}).`);
233
+ }
234
+
235
+ function isProtectedPath(relPath) {
236
+ const norm = relPath.replace(/\\/g, "/");
237
+ if (norm === ".git" || norm.startsWith(".git/") || norm === ".kiro" || norm.startsWith(".kiro/")) {
238
+ return true;
239
+ }
240
+ const base = path.posix.basename(norm);
241
+ return base === ".env" || base.startsWith(".env.");
242
+ }
243
+
244
+ function handleRestore(cwd, checkpointsPath, targetId) {
245
+ if (!isGitRepo(cwd)) {
246
+ console.log("Not inside a git repository. Git is required for turn checkpoints.");
247
+ return;
248
+ }
249
+ const checkpoints = loadCheckpoints(checkpointsPath);
250
+ const target = resolveCheckpoint(checkpoints, targetId);
251
+ if (!target) {
252
+ console.log(targetId ? `Checkpoint not found: ${targetId}` : "No checkpoints recorded yet.");
253
+ return;
254
+ }
255
+
256
+ // Step 1: Pre-restore safety backup
257
+ const preRestoreHash = captureWorkingTree(cwd);
258
+ const backupId = `pre-restore-${Date.now()}`;
259
+ const backupRef = `refs/kiro/checkpoints/${backupId}`;
260
+ execFileSync("git", ["update-ref", backupRef, preRestoreHash], { cwd, stdio: "pipe" });
261
+ checkpoints.push({
262
+ id: backupId,
263
+ ref: backupRef,
264
+ treeHash: preRestoreHash,
265
+ timestamp: new Date().toISOString(),
266
+ label: `backup before restoring ${target.id}`
267
+ });
268
+ saveAndPruneCheckpoints(cwd, checkpointsPath, checkpoints);
269
+
270
+ // Step 2: Remove newly created unignored files not in target snapshot
271
+ const targetOut = execFileSync("git", ["ls-tree", "-r", "--name-only", "-z", target.treeHash], {
272
+ cwd,
273
+ stdio: "pipe",
274
+ encoding: "utf8"
275
+ });
276
+ const targetFiles = new Set(targetOut.split("\0").filter(Boolean));
277
+
278
+ const currentOut = execFileSync(
279
+ "git",
280
+ ["ls-files", "--cached", "--others", "--exclude-standard", "-z"],
281
+ { cwd, stdio: "pipe", encoding: "utf8" }
282
+ );
283
+ const currentFiles = currentOut.split("\0").filter(Boolean);
284
+
285
+ for (const relPath of currentFiles) {
286
+ if (!targetFiles.has(relPath) && !isProtectedPath(relPath)) {
287
+ fs.rmSync(path.join(cwd, relPath), { force: true });
288
+ }
289
+ }
290
+
291
+ // Step 3: Restore snapshot using isolated temporary GIT_INDEX_FILE
292
+ const tmpIndex = makeTempIndexPath();
293
+ const env = { ...process.env, GIT_INDEX_FILE: tmpIndex };
294
+ try {
295
+ execFileSync("git", ["read-tree", target.treeHash], { cwd, env, stdio: "pipe" });
296
+ execFileSync("git", ["checkout-index", "-a", "-f"], { cwd, env, stdio: "pipe" });
297
+ } finally {
298
+ fs.rmSync(tmpIndex, { force: true });
299
+ }
300
+
301
+ console.log(
302
+ `Restored ${target.id} (${target.treeHash.slice(0, 7)}). Backup saved as ${backupId}.`
303
+ );
304
+ }
305
+
306
+ async function main() {
307
+ const { cmd, targetId } = parseSubcommand();
308
+ const cwd = process.cwd();
309
+ const kiroDir = path.join(cwd, ".kiro");
310
+ const checkpointsPath = path.join(kiroDir, ".checkpoints.json");
311
+
312
+ if (cmd === "capture") {
313
+ await handleCapture(cwd, kiroDir, checkpointsPath);
314
+ } else if (cmd === "list") {
315
+ handleList(cwd, checkpointsPath);
316
+ } else if (cmd === "diff") {
317
+ handleDiff(cwd, checkpointsPath, targetId);
318
+ } else if (cmd === "restore") {
319
+ handleRestore(cwd, checkpointsPath, targetId);
320
+ }
321
+ }
322
+
323
+ main().catch(() => process.exit(0));
@@ -0,0 +1,228 @@
1
+ const fs = require("node:fs");
2
+ const path = require("node:path");
3
+ const os = require("node:os");
4
+ const crypto = require("node:crypto");
5
+ const { execFileSync, spawnSync } = require("node:child_process");
6
+
7
+ const CODE_EXTENSIONS = new Set([
8
+ ".ts",
9
+ ".tsx",
10
+ ".mts",
11
+ ".cts",
12
+ ".js",
13
+ ".jsx",
14
+ ".mjs",
15
+ ".cjs",
16
+ ".py",
17
+ ".go",
18
+ ".rs",
19
+ ".json"
20
+ ]);
21
+
22
+ const LOCKFILES = new Set([
23
+ "package-lock.json",
24
+ "pnpm-lock.yaml",
25
+ "yarn.lock",
26
+ "bun.lockb",
27
+ "cargo.lock",
28
+ "composer.lock"
29
+ ]);
30
+
31
+ function isGitRepo(cwd) {
32
+ try {
33
+ const out = execFileSync("git", ["rev-parse", "--is-inside-work-tree"], {
34
+ cwd,
35
+ stdio: "pipe",
36
+ encoding: "utf8"
37
+ });
38
+ return out.trim() === "true";
39
+ } catch {
40
+ return false;
41
+ }
42
+ }
43
+
44
+ function captureWorkingTree(cwd) {
45
+ const tmpIndex = path.join(
46
+ os.tmpdir(),
47
+ `kiro-verify-idx-${process.pid}-${Date.now()}-${crypto.randomBytes(4).toString("hex")}`
48
+ );
49
+ const env = { ...process.env, GIT_INDEX_FILE: tmpIndex };
50
+ try {
51
+ execFileSync("git", ["add", "-A"], { cwd, env, stdio: "pipe" });
52
+ return execFileSync("git", ["write-tree"], {
53
+ cwd,
54
+ env,
55
+ stdio: "pipe",
56
+ encoding: "utf8"
57
+ }).trim();
58
+ } finally {
59
+ fs.rmSync(tmpIndex, { force: true });
60
+ }
61
+ }
62
+
63
+ function isCodeFile(relPath) {
64
+ const base = path.basename(relPath).toLowerCase();
65
+ if (LOCKFILES.has(base) || base.endsWith(".lock") || base.endsWith("-lock.json")) {
66
+ return false;
67
+ }
68
+ return CODE_EXTENSIONS.has(path.extname(base));
69
+ }
70
+
71
+ function detectPackageManager(cwd) {
72
+ if (fs.existsSync(path.join(cwd, "pnpm-lock.yaml"))) return "pnpm";
73
+ if (fs.existsSync(path.join(cwd, "yarn.lock"))) return "yarn";
74
+ return "npm";
75
+ }
76
+
77
+ function readPackageJson(cwd) {
78
+ const pkgPath = path.join(cwd, "package.json");
79
+ if (!fs.existsSync(pkgPath)) return null;
80
+ try {
81
+ return JSON.parse(fs.readFileSync(pkgPath, "utf8").replace(/^\uFEFF/, ""));
82
+ } catch {
83
+ return null;
84
+ }
85
+ }
86
+
87
+ function runCommand(cmd, args, cwd, useShell = false) {
88
+ return spawnSync(cmd, args, {
89
+ cwd,
90
+ encoding: "utf8",
91
+ stdio: "pipe",
92
+ shell: useShell,
93
+ timeout: 40000
94
+ });
95
+ }
96
+
97
+ function runTargetedVerification(cwd, changedFiles) {
98
+ // Priority 1: Custom package.json script "kiro:verify"
99
+ const pkg = readPackageJson(cwd);
100
+ if (pkg && pkg.scripts && pkg.scripts["kiro:verify"]) {
101
+ const pm = detectPackageManager(cwd);
102
+ return runCommand(pm, ["run", "kiro:verify"], cwd, process.platform === "win32");
103
+ }
104
+
105
+ // Priority 2: Local TypeScript compiler when tsconfig.json + changed TS files exist
106
+ const hasTsChanges = changedFiles.some((f) => /\.(ts|tsx|mts|cts)$/i.test(f));
107
+ const localTsc = path.join(
108
+ cwd,
109
+ "node_modules",
110
+ ".bin",
111
+ process.platform === "win32" ? "tsc.cmd" : "tsc"
112
+ );
113
+ if (hasTsChanges && fs.existsSync(path.join(cwd, "tsconfig.json")) && fs.existsSync(localTsc)) {
114
+ return runCommand(localTsc, ["--noEmit"], cwd, process.platform === "win32");
115
+ }
116
+
117
+ // Priority 3: Node syntax check on changed JS files
118
+ const jsFiles = changedFiles.filter(
119
+ (f) => /\.(js|mjs|cjs)$/i.test(f) && fs.existsSync(path.join(cwd, f))
120
+ );
121
+ if (jsFiles.length > 0) {
122
+ for (const file of jsFiles) {
123
+ const res = runCommand(process.execPath, ["--check", file], cwd, false);
124
+ if (res.status !== 0 || res.error) {
125
+ return res;
126
+ }
127
+ }
128
+ return { status: 0, stdout: "", stderr: "" };
129
+ }
130
+
131
+ // Priority 4: Python syntax check on changed .py files
132
+ const pyFiles = changedFiles.filter(
133
+ (f) => /\.py$/i.test(f) && fs.existsSync(path.join(cwd, f))
134
+ );
135
+ if (pyFiles.length > 0) {
136
+ let res = runCommand("python3", ["-m", "py_compile", ...pyFiles], cwd, false);
137
+ if (res.error && res.error.code === "ENOENT") {
138
+ res = runCommand("python", ["-m", "py_compile", ...pyFiles], cwd, false);
139
+ }
140
+ if (res.error && res.error.code === "ENOENT") {
141
+ return null;
142
+ }
143
+ return res;
144
+ }
145
+
146
+ // Priority 5: Go vet when go.mod + changed .go files exist
147
+ const hasGoChanges = changedFiles.some((f) => /\.go$/i.test(f));
148
+ if (hasGoChanges && fs.existsSync(path.join(cwd, "go.mod"))) {
149
+ const res = runCommand("go", ["vet", "./..."], cwd, false);
150
+ if (res.error && res.error.code === "ENOENT") {
151
+ return null;
152
+ }
153
+ return res;
154
+ }
155
+
156
+ return null;
157
+ }
158
+
159
+ function stripAnsiAndTrim(text) {
160
+ const clean = text.replace(
161
+ /[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><~]/g,
162
+ ""
163
+ ).trim();
164
+ if (clean.length <= 1800) {
165
+ return clean;
166
+ }
167
+ return `${clean.slice(0, 1800)}\n... [truncated]`;
168
+ }
169
+
170
+ function main() {
171
+ const cwd = process.cwd();
172
+ const statePath = path.join(cwd, ".kiro", ".loop-state.json");
173
+ if (!fs.existsSync(statePath)) {
174
+ process.exit(0);
175
+ }
176
+
177
+ const state = JSON.parse(fs.readFileSync(statePath, "utf8"));
178
+ const maxRetries = Number(process.env.KIRO_LOOP_MAX_RETRIES) || state.maxRetries || 2;
179
+ const retries = state.retries || 0;
180
+ if (retries >= maxRetries) {
181
+ process.exit(0);
182
+ }
183
+
184
+ if (!state.preTurnTreeHash || !isGitRepo(cwd)) {
185
+ process.exit(0);
186
+ }
187
+
188
+ const currentTreeHash = captureWorkingTree(cwd);
189
+ if (currentTreeHash === state.preTurnTreeHash) {
190
+ process.exit(0);
191
+ }
192
+
193
+ const diffOut = execFileSync(
194
+ "git",
195
+ ["diff", "--name-only", "-z", state.preTurnTreeHash, currentTreeHash],
196
+ { cwd, stdio: "pipe", encoding: "utf8" }
197
+ );
198
+ const changedFiles = diffOut.split("\0").filter(Boolean);
199
+ const codeFiles = changedFiles.filter(isCodeFile);
200
+ if (codeFiles.length === 0) {
201
+ process.exit(0);
202
+ }
203
+
204
+ const result = runTargetedVerification(cwd, codeFiles);
205
+ if (!result || (result.status === 0 && !result.error)) {
206
+ process.exit(0);
207
+ }
208
+
209
+ const nextRetry = retries + 1;
210
+ state.retries = nextRetry;
211
+ state.updatedAt = Date.now();
212
+ fs.writeFileSync(statePath, `${JSON.stringify(state, null, 2)}\n`, "utf8");
213
+
214
+ const combined = [result.stderr, result.stdout, result.error && result.error.message]
215
+ .filter(Boolean)
216
+ .join("\n");
217
+ const trimmed = stripAnsiAndTrim(combined || "Verification command failed with non-zero exit.");
218
+ const reason = `[kiro-10x-better auto-verify retry ${nextRetry}/${maxRetries}] Verification failed after your edits. Fix the exact root cause below before finishing:\n\n${trimmed}`;
219
+
220
+ process.stdout.write(`${JSON.stringify({ decision: "block", reason })}\n`);
221
+ }
222
+
223
+ try {
224
+ main();
225
+ } catch {
226
+ // Never block or crash Kiro CLI on unexpected internal hook errors
227
+ }
228
+ process.exit(0);
@@ -0,0 +1,16 @@
1
+ {
2
+ "version": "v1",
3
+ "hooks": [
4
+ {
5
+ "name": "auto-verify-stop-loop",
6
+ "description": "Runs fast targeted verification when code files changed and blocks Stop (up to 2 retries) so any model self-heals errors",
7
+ "trigger": "Stop",
8
+ "action": {
9
+ "type": "command",
10
+ "command": "node -e \"const fs=require('fs'),p=require('path'),os=require('os'),loc=p.join('.kiro','hooks','scripts','verify-loop.cjs'),glob=p.join(os.homedir(),'.kiro','hooks','scripts','verify-loop.cjs');require(fs.existsSync(loc)?p.resolve(loc):glob)\""
11
+ },
12
+ "timeout": 45,
13
+ "enabled": true
14
+ }
15
+ ]
16
+ }
@@ -0,0 +1,16 @@
1
+ {
2
+ "version": "v1",
3
+ "hooks": [
4
+ {
5
+ "name": "snapshot-on-prompt-submit",
6
+ "description": "Silently snapshots working tree via shadow git ref and resets auto-verify loop state before every user prompt",
7
+ "trigger": "UserPromptSubmit",
8
+ "action": {
9
+ "type": "command",
10
+ "command": "node -e \"const fs=require('fs'),p=require('path'),os=require('os'),loc=p.join('.kiro','hooks','scripts','checkpoint.cjs'),glob=p.join(os.homedir(),'.kiro','hooks','scripts','checkpoint.cjs');process.argv.splice(1,0,'capture');require(fs.existsSync(loc)?p.resolve(loc):glob)\""
11
+ },
12
+ "timeout": 15,
13
+ "enabled": true
14
+ }
15
+ ]
16
+ }