kiro-10x-better 1.0.3 → 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 +11 -6
- package/bin/cli.mjs +98 -26
- package/package.json +1 -1
- package/templates/agents-block.md +35 -0
- package/templates/hooks/scripts/checkpoint.cjs +323 -0
- package/templates/hooks/scripts/sync-stack-skills.cjs +73 -17
- package/templates/hooks/scripts/verify-loop.cjs +228 -0
- package/templates/hooks/stack-skill-sync.json +18 -6
- package/templates/hooks/stop-verify-loop.json +16 -0
- package/templates/hooks/turn-checkpoint.json +16 -0
package/README.md
CHANGED
|
@@ -26,17 +26,18 @@ npx kiro-10x-better --global
|
|
|
26
26
|
| :--- | :--- |
|
|
27
27
|
| `-g`, `--global` | Install into `~/.kiro/` instead of `./.kiro/` |
|
|
28
28
|
| `-f`, `--force` | Overwrite existing `.kiro` files (default: skip existing) |
|
|
29
|
-
| `-y`, `--yes` | Skip interactive prompts
|
|
29
|
+
| `-y`, `--yes` | Skip interactive prompts (installs security + detected web skills) |
|
|
30
|
+
| `--core-only` | Skip external `npx skills add` calls (keeps local stack watcher hook) |
|
|
30
31
|
| `--with-skills` | Also install core `obra/superpowers` skills via `npx skills` |
|
|
31
32
|
| `--web` | Install Web App skills (`agent-browser` + `modern-web-guidance`) without prompting |
|
|
32
|
-
| `--security` | Install Security Audit skills
|
|
33
|
+
| `--security` | Install Security Audit skills without prompting |
|
|
33
34
|
| `-h`, `--help` | Show usage help and exit |
|
|
34
35
|
|
|
35
36
|
## Progressive Setup Flow
|
|
36
37
|
|
|
37
|
-
1. **
|
|
38
|
-
2. **Web App
|
|
39
|
-
3. **Security Audit
|
|
38
|
+
1. **Core Setup (Always Runs):** Installs steering rules, the 3 bundled skills, core safety/lint/verify hooks, the always-on `stack-skill-sync.json` watcher hook (`SessionStart`, `PostFileSave` on `package.json`, `PostToolUse` on `shell`), ignores, and global `permissions.yaml`.
|
|
39
|
+
2. **Web App Skills (`--web` / Auto-Detect):** Detects web frameworks (`next`, `react`, `vite`, `vue`, `svelte`, `astro`, `nuxt`, `remix`, `@tanstack/react-start`) in `package.json`. Under `--yes`, installs `agent-browser` + `modern-web-guidance` automatically when a web framework is detected (otherwise the always-on watcher installs them automatically as soon as one is added later).
|
|
40
|
+
3. **Security Audit Skills (`--security` / Smart `--yes`):** Enabled by default under `--yes` and `(Y/n)` interactively—installs `security-audit` (Cloudflare) + `security-review` (Sentry), appends `pnpm audit*` / `npm audit*` to `permissions.yaml`, and installs `better-auth-security-best-practices` immediately if `better-auth` is in `package.json` (or via the watcher hook whenever added later).
|
|
40
41
|
|
|
41
42
|
## What Gets Installed
|
|
42
43
|
|
|
@@ -49,7 +50,11 @@ npx kiro-10x-better --global
|
|
|
49
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.
|
|
50
51
|
- `auto-lint.json` (`PostFileSave`): Auto-detects `pnpm`/`yarn`/`npm` and `biome`/`eslint`/`prettier` from your project (or disables itself if none are found).
|
|
51
52
|
- `verify-after-task.json` (`PostTaskExec` + `SubagentStop`): Runs `tsc --noEmit` when `tsconfig.json` is present and prompts subagents for fresh verification output.
|
|
52
|
-
-
|
|
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.
|
|
53
58
|
- **Project Ignores (project mode):** Adds `.kiro/` to `.gitignore` and creates `.kiroignore` blocking `.env*`, `*.pem`, `*.key`, `node_modules/`, `dist/`, and `.next/`.
|
|
54
59
|
|
|
55
60
|
## Recommended Kiro CLI V3 Settings
|
package/bin/cli.mjs
CHANGED
|
@@ -30,10 +30,11 @@ Usage:
|
|
|
30
30
|
Options:
|
|
31
31
|
-g, --global Install into ~/.kiro/ instead of ./.kiro/
|
|
32
32
|
-f, --force Overwrite existing files (default: skip existing)
|
|
33
|
-
-y, --yes Skip
|
|
33
|
+
-y, --yes Skip prompts (auto-installs security + detected web skills)
|
|
34
|
+
--core-only Skip external npx skills installs (keeps local watcher hook)
|
|
34
35
|
--with-skills Install core obra/superpowers skills via npx skills
|
|
35
36
|
--web Install Web App skills (agent-browser + modern-web-guidance)
|
|
36
|
-
--security Install Security Audit skills
|
|
37
|
+
--security Install Security Audit skills without prompting
|
|
37
38
|
-h, --help Show this help message and exit
|
|
38
39
|
`);
|
|
39
40
|
}
|
|
@@ -43,6 +44,7 @@ function parseArgs(argv) {
|
|
|
43
44
|
global: false,
|
|
44
45
|
force: false,
|
|
45
46
|
yes: false,
|
|
47
|
+
coreOnly: false,
|
|
46
48
|
withSkills: false,
|
|
47
49
|
web: false,
|
|
48
50
|
security: false,
|
|
@@ -63,6 +65,9 @@ function parseArgs(argv) {
|
|
|
63
65
|
case "-y":
|
|
64
66
|
flags.yes = true;
|
|
65
67
|
break;
|
|
68
|
+
case "--core-only":
|
|
69
|
+
flags.coreOnly = true;
|
|
70
|
+
break;
|
|
66
71
|
case "--with-skills":
|
|
67
72
|
flags.withSkills = true;
|
|
68
73
|
break;
|
|
@@ -300,6 +305,46 @@ function appendAllowRules(homeKiroDir, commands, tracker) {
|
|
|
300
305
|
console.log(` update ~/.kiro/settings/permissions.yaml (added ${missing.join(", ")})`);
|
|
301
306
|
}
|
|
302
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
|
+
|
|
303
348
|
async function promptYesNo(question, defaultYes = true) {
|
|
304
349
|
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
|
|
305
350
|
try {
|
|
@@ -380,7 +425,7 @@ async function main() {
|
|
|
380
425
|
|
|
381
426
|
console.log(`\nSetting up Kiro CLI V3 in ${targetKiroDir}\n`);
|
|
382
427
|
|
|
383
|
-
// Step 1: Fast Core Setup (steering, bundled skills, core hooks, ignores,
|
|
428
|
+
// Step 1: Fast Core Setup (steering, bundled skills, core + watcher + checkpoint/verify hooks, AGENTS.md, ignores, permissions)
|
|
384
429
|
copyTemplateFile(
|
|
385
430
|
path.join("steering", "core-rules.md"),
|
|
386
431
|
path.join(targetKiroDir, "steering", "core-rules.md"),
|
|
@@ -392,11 +437,23 @@ async function main() {
|
|
|
392
437
|
`${prefixLabel}/skills`,
|
|
393
438
|
{ force: flags.force, tracker }
|
|
394
439
|
);
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
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
|
+
}
|
|
400
457
|
|
|
401
458
|
writeTargetFile(
|
|
402
459
|
path.join(targetKiroDir, "hooks", "security-guard.json"),
|
|
@@ -414,6 +471,13 @@ async function main() {
|
|
|
414
471
|
{ force: flags.force, label: `${prefixLabel}/hooks/verify-after-task.json`, tracker }
|
|
415
472
|
);
|
|
416
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 });
|
|
480
|
+
|
|
417
481
|
if (!flags.global) {
|
|
418
482
|
updateGitignore(cwd, tracker);
|
|
419
483
|
copyTemplateFile("kiroignore", path.join(cwd, ".kiroignore"), {
|
|
@@ -433,18 +497,30 @@ async function main() {
|
|
|
433
497
|
{ force: flags.force, label: "~/.kiro/settings/permissions.yaml", tracker }
|
|
434
498
|
);
|
|
435
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
|
+
);
|
|
436
508
|
}
|
|
437
509
|
|
|
438
|
-
if (flags.withSkills) {
|
|
510
|
+
if (flags.withSkills && !flags.coreOnly) {
|
|
439
511
|
runSkillsInstall(flags.global);
|
|
440
512
|
}
|
|
441
513
|
|
|
442
|
-
// Step 2: Web App
|
|
514
|
+
// Step 2: Web App Skills (--web / Auto-Detect)
|
|
443
515
|
const hasWebFramework = !flags.global && WEB_FRAMEWORKS.some((fw) => fw in pkgDeps);
|
|
444
516
|
let installWeb = false;
|
|
445
|
-
if (flags.
|
|
517
|
+
if (flags.coreOnly) {
|
|
518
|
+
installWeb = false;
|
|
519
|
+
} else if (flags.web) {
|
|
446
520
|
installWeb = true;
|
|
447
|
-
} else if (
|
|
521
|
+
} else if (flags.yes) {
|
|
522
|
+
installWeb = hasWebFramework;
|
|
523
|
+
} else {
|
|
448
524
|
const webPrompt = hasWebFramework
|
|
449
525
|
? "\nIs this a web app? Installs agent-browser + modern-web-guidance (Y/n): "
|
|
450
526
|
: "\nIs this a web app? Installs agent-browser + modern-web-guidance (y/N): ";
|
|
@@ -470,12 +546,14 @@ async function main() {
|
|
|
470
546
|
appendAllowRules(homeKiroDir, ["agent-browser *", "npx modern-web-guidance*"], tracker);
|
|
471
547
|
}
|
|
472
548
|
|
|
473
|
-
// Step 3: Security Audit
|
|
549
|
+
// Step 3: Security Audit Skills (--security / Smart --yes)
|
|
474
550
|
let installSecurity = false;
|
|
475
|
-
if (flags.
|
|
551
|
+
if (flags.coreOnly) {
|
|
552
|
+
installSecurity = false;
|
|
553
|
+
} else if (flags.security || flags.yes) {
|
|
476
554
|
installSecurity = true;
|
|
477
|
-
} else
|
|
478
|
-
installSecurity = await promptYesNo("\nAdd code security-audit skills? (
|
|
555
|
+
} else {
|
|
556
|
+
installSecurity = await promptYesNo("\nAdd code security-audit skills? (Y/n): ", true);
|
|
479
557
|
}
|
|
480
558
|
|
|
481
559
|
if (installSecurity) {
|
|
@@ -487,16 +565,6 @@ async function main() {
|
|
|
487
565
|
["skills", "add", "getsentry/skills", "--skill", "security-review", "-a", "kiro-cli", "-y"],
|
|
488
566
|
flags.global
|
|
489
567
|
);
|
|
490
|
-
copyTemplateFile(
|
|
491
|
-
path.join("hooks", "stack-skill-sync.json"),
|
|
492
|
-
path.join(targetKiroDir, "hooks", "stack-skill-sync.json"),
|
|
493
|
-
{ force: flags.force, label: `${prefixLabel}/hooks/stack-skill-sync.json`, tracker }
|
|
494
|
-
);
|
|
495
|
-
copyTemplateFile(
|
|
496
|
-
path.join("hooks", "scripts", "sync-stack-skills.cjs"),
|
|
497
|
-
path.join(targetKiroDir, "hooks", "scripts", "sync-stack-skills.cjs"),
|
|
498
|
-
{ force: flags.force, label: `${prefixLabel}/hooks/scripts/sync-stack-skills.cjs`, tracker }
|
|
499
|
-
);
|
|
500
568
|
|
|
501
569
|
if ("better-auth" in pkgDeps) {
|
|
502
570
|
runNpxSkills(
|
|
@@ -541,6 +609,10 @@ async function main() {
|
|
|
541
609
|
"\nWeb tip: Run \"npm install -g agent-browser && agent-browser install\" once if you haven't installed the browser binary yet."
|
|
542
610
|
);
|
|
543
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");
|
|
544
616
|
console.log("\nNext steps in Kiro CLI V3:");
|
|
545
617
|
console.log(" 1. Enable \"Approve for me\" and Workflows (chat.enableWorkflows) in Kiro settings.");
|
|
546
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
|
@@ -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));
|
|
@@ -3,30 +3,86 @@ const path = require("node:path");
|
|
|
3
3
|
const os = require("node:os");
|
|
4
4
|
const { execFileSync } = require("node:child_process");
|
|
5
5
|
|
|
6
|
+
const WEB_FRAMEWORKS = new Set([
|
|
7
|
+
"next",
|
|
8
|
+
"react",
|
|
9
|
+
"vite",
|
|
10
|
+
"vue",
|
|
11
|
+
"svelte",
|
|
12
|
+
"astro",
|
|
13
|
+
"nuxt",
|
|
14
|
+
"remix",
|
|
15
|
+
"@tanstack/react-start"
|
|
16
|
+
]);
|
|
17
|
+
|
|
18
|
+
function isSkillInstalled(skillName) {
|
|
19
|
+
const localSkill = path.join(process.cwd(), ".kiro", "skills", skillName, "SKILL.md");
|
|
20
|
+
const globalSkill = path.join(os.homedir(), ".kiro", "skills", skillName, "SKILL.md");
|
|
21
|
+
return fs.existsSync(localSkill) || fs.existsSync(globalSkill);
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function ensureWebPermissions() {
|
|
25
|
+
const permPath = path.join(os.homedir(), ".kiro", "settings", "permissions.yaml");
|
|
26
|
+
if (!fs.existsSync(permPath)) return;
|
|
27
|
+
let content = fs.readFileSync(permPath, "utf8");
|
|
28
|
+
const rulesToAdd = [];
|
|
29
|
+
if (!content.includes('"agent-browser *"')) {
|
|
30
|
+
rulesToAdd.push(' - tool: shell\n command: "agent-browser *"');
|
|
31
|
+
}
|
|
32
|
+
if (!content.includes('"npx modern-web-guidance*"')) {
|
|
33
|
+
rulesToAdd.push(' - tool: shell\n command: "npx modern-web-guidance*"');
|
|
34
|
+
}
|
|
35
|
+
if (rulesToAdd.length > 0 && content.includes("allow:\n")) {
|
|
36
|
+
content = content.replace("allow:\n", `allow:\n${rulesToAdd.join("\n")}\n`);
|
|
37
|
+
fs.writeFileSync(permPath, content, "utf8");
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
6
41
|
try {
|
|
7
42
|
const pkgPath = path.join(process.cwd(), "package.json");
|
|
8
43
|
if (!fs.existsSync(pkgPath)) process.exit(0);
|
|
9
44
|
|
|
45
|
+
// Fast exit (<1ms) if package.json mtime hasn't changed since last check
|
|
46
|
+
const stat = fs.statSync(pkgPath);
|
|
47
|
+
const kiroDir = path.join(process.cwd(), ".kiro");
|
|
48
|
+
const statePath = path.join(kiroDir, ".stack-sync-state.json");
|
|
49
|
+
if (fs.existsSync(statePath)) {
|
|
50
|
+
try {
|
|
51
|
+
const prev = JSON.parse(fs.readFileSync(statePath, "utf8"));
|
|
52
|
+
if (prev.mtimeMs === stat.mtimeMs) process.exit(0);
|
|
53
|
+
} catch {}
|
|
54
|
+
}
|
|
55
|
+
|
|
10
56
|
const pkg = JSON.parse(fs.readFileSync(pkgPath, "utf8"));
|
|
11
57
|
const deps = { ...(pkg.dependencies || {}), ...(pkg.devDependencies || {}) };
|
|
12
|
-
|
|
58
|
+
const depNames = Object.keys(deps);
|
|
13
59
|
|
|
14
|
-
|
|
15
|
-
const
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
60
|
+
// 1. Auto-sync Web App skills when Next.js / React / Vite etc. is installed
|
|
61
|
+
const hasWeb = depNames.some((d) => WEB_FRAMEWORKS.has(d));
|
|
62
|
+
if (hasWeb && (!isSkillInstalled("agent-browser") || !isSkillInstalled("modern-web-guidance"))) {
|
|
63
|
+
console.log("[kiro-10x-better] Detected web framework in package.json — installing agent-browser + modern-web-guidance...");
|
|
64
|
+
execFileSync(
|
|
65
|
+
"npx",
|
|
66
|
+
["skills", "add", "vercel-labs/agent-browser", "--skill", "agent-browser", "--skill", "modern-web-guidance", "-a", "kiro-cli", "-y"],
|
|
67
|
+
{ stdio: "inherit", shell: process.platform === "win32", timeout: 50000 }
|
|
68
|
+
);
|
|
69
|
+
ensureWebPermissions();
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// 2. Auto-sync Better Auth security skill when better-auth is installed
|
|
73
|
+
if (deps["better-auth"] && !isSkillInstalled("better-auth-security-best-practices")) {
|
|
74
|
+
console.log("[kiro-10x-better] Detected better-auth in package.json — installing better-auth-security-best-practices...");
|
|
75
|
+
execFileSync(
|
|
76
|
+
"npx",
|
|
77
|
+
["skills", "add", "better-auth/skills", "--skill", "better-auth-security-best-practices", "-a", "kiro-cli", "-y"],
|
|
78
|
+
{ stdio: "inherit", shell: process.platform === "win32", timeout: 50000 }
|
|
79
|
+
);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
if (fs.existsSync(kiroDir)) {
|
|
83
|
+
fs.writeFileSync(statePath, JSON.stringify({ mtimeMs: stat.mtimeMs }), "utf8");
|
|
84
|
+
}
|
|
29
85
|
} catch {
|
|
30
|
-
// Never block Kiro CLI
|
|
86
|
+
// Never block Kiro CLI if offline or npx is unavailable
|
|
31
87
|
process.exit(0);
|
|
32
88
|
}
|
|
@@ -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);
|
|
@@ -2,26 +2,38 @@
|
|
|
2
2
|
"version": "v1",
|
|
3
3
|
"hooks": [
|
|
4
4
|
{
|
|
5
|
-
"name": "sync-
|
|
6
|
-
"description": "Auto-installs
|
|
5
|
+
"name": "sync-stack-skills-on-start",
|
|
6
|
+
"description": "Auto-installs Web and Better Auth skills when matching packages appear in package.json",
|
|
7
7
|
"trigger": "SessionStart",
|
|
8
8
|
"action": {
|
|
9
9
|
"type": "command",
|
|
10
10
|
"command": "node -e \"const fs=require('fs'),p=require('path'),os=require('os'),loc=p.join('.kiro','hooks','scripts','sync-stack-skills.cjs'),glob=p.join(os.homedir(),'.kiro','hooks','scripts','sync-stack-skills.cjs');require(fs.existsSync(loc)?p.resolve(loc):glob)\""
|
|
11
11
|
},
|
|
12
|
-
"timeout":
|
|
12
|
+
"timeout": 60,
|
|
13
13
|
"enabled": true
|
|
14
14
|
},
|
|
15
15
|
{
|
|
16
|
-
"name": "sync-
|
|
17
|
-
"description": "Auto-installs
|
|
16
|
+
"name": "sync-stack-skills-on-pkg-save",
|
|
17
|
+
"description": "Auto-installs Web and Better Auth skills when package.json is saved",
|
|
18
18
|
"trigger": "PostFileSave",
|
|
19
19
|
"matcher": "package\\.json$",
|
|
20
20
|
"action": {
|
|
21
21
|
"type": "command",
|
|
22
22
|
"command": "node -e \"const fs=require('fs'),p=require('path'),os=require('os'),loc=p.join('.kiro','hooks','scripts','sync-stack-skills.cjs'),glob=p.join(os.homedir(),'.kiro','hooks','scripts','sync-stack-skills.cjs');require(fs.existsSync(loc)?p.resolve(loc):glob)\""
|
|
23
23
|
},
|
|
24
|
-
"timeout":
|
|
24
|
+
"timeout": 60,
|
|
25
|
+
"enabled": true
|
|
26
|
+
},
|
|
27
|
+
{
|
|
28
|
+
"name": "sync-stack-skills-on-shell",
|
|
29
|
+
"description": "Checks package.json mtime after shell installs (e.g. create-next-app or pnpm add)",
|
|
30
|
+
"trigger": "PostToolUse",
|
|
31
|
+
"matcher": "shell",
|
|
32
|
+
"action": {
|
|
33
|
+
"type": "command",
|
|
34
|
+
"command": "node -e \"const fs=require('fs'),p=require('path'),os=require('os'),loc=p.join('.kiro','hooks','scripts','sync-stack-skills.cjs'),glob=p.join(os.homedir(),'.kiro','hooks','scripts','sync-stack-skills.cjs');require(fs.existsSync(loc)?p.resolve(loc):glob)\""
|
|
35
|
+
},
|
|
36
|
+
"timeout": 60,
|
|
25
37
|
"enabled": true
|
|
26
38
|
}
|
|
27
39
|
]
|
|
@@ -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
|
+
}
|