joycraft 0.7.12 → 0.7.14

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 (54) hide show
  1. package/README.md +30 -16
  2. package/dist/chunk-7BPB2IKY.js +255 -0
  3. package/dist/chunk-7BPB2IKY.js.map +1 -0
  4. package/dist/chunk-B73DPYYC.js +377 -0
  5. package/dist/chunk-B73DPYYC.js.map +1 -0
  6. package/dist/{chunk-DSVGHVYM.js → chunk-JYPBXPGD.js} +117 -90
  7. package/dist/chunk-JYPBXPGD.js.map +1 -0
  8. package/dist/{chunk-OAC5CVHJ.js → chunk-K4AI6FKB.js} +12 -2
  9. package/dist/chunk-K4AI6FKB.js.map +1 -0
  10. package/dist/{chunk-PBOICMDE.js → chunk-KKDKC4FM.js} +11 -73
  11. package/dist/chunk-KKDKC4FM.js.map +1 -0
  12. package/dist/chunk-OMFGDJW4.js +97 -0
  13. package/dist/chunk-OMFGDJW4.js.map +1 -0
  14. package/dist/chunk-PR4QDKPL.js +3755 -0
  15. package/dist/chunk-PR4QDKPL.js.map +1 -0
  16. package/dist/chunk-Z5JFEGWG.js +563 -0
  17. package/dist/chunk-Z5JFEGWG.js.map +1 -0
  18. package/dist/cli.js +389 -56
  19. package/dist/cli.js.map +1 -1
  20. package/dist/index.d.ts +235 -1
  21. package/dist/index.js +691 -1
  22. package/dist/index.js.map +1 -1
  23. package/dist/init-S5JU5BHL.js +60 -0
  24. package/dist/init-S5JU5BHL.js.map +1 -0
  25. package/dist/{init-autofix-YCSDK5ZR.js → init-autofix-WSKUT2HN.js} +4 -3
  26. package/dist/{init-autofix-YCSDK5ZR.js.map → init-autofix-WSKUT2HN.js.map} +1 -1
  27. package/dist/install-manifest-EQHT4474.js +37 -0
  28. package/dist/joycraft-release.json +8 -0
  29. package/dist/release-artifact-4TL5L2ZY.js +14 -0
  30. package/dist/release-resolver-P2H46QTU.js +293 -0
  31. package/dist/release-resolver-P2H46QTU.js.map +1 -0
  32. package/dist/{telemetry-store-X7K5NYWD.js → telemetry-store-IBO5GRTA.js} +2 -2
  33. package/dist/telemetry-store-IBO5GRTA.js.map +1 -0
  34. package/dist/update-HNTXCEKB.js +19 -0
  35. package/dist/update-HNTXCEKB.js.map +1 -0
  36. package/dist/update-check-YT765NE7.js +36 -0
  37. package/dist/update-check-YT765NE7.js.map +1 -0
  38. package/dist/upgrade-LZOND7OZ.js +28 -0
  39. package/dist/upgrade-LZOND7OZ.js.map +1 -0
  40. package/package.json +5 -2
  41. package/dist/chunk-BZW5DR3O.js +0 -91
  42. package/dist/chunk-BZW5DR3O.js.map +0 -1
  43. package/dist/chunk-DSVGHVYM.js.map +0 -1
  44. package/dist/chunk-OAC5CVHJ.js.map +0 -1
  45. package/dist/chunk-PBOICMDE.js.map +0 -1
  46. package/dist/chunk-Q2ZQ6RGD.js +0 -243
  47. package/dist/chunk-Q2ZQ6RGD.js.map +0 -1
  48. package/dist/init-J5Q6RX3K.js +0 -1307
  49. package/dist/init-J5Q6RX3K.js.map +0 -1
  50. package/dist/upgrade-AHUSQZEQ.js +0 -643
  51. package/dist/upgrade-AHUSQZEQ.js.map +0 -1
  52. package/dist/version-B2CCAEMC.js +0 -28
  53. /package/dist/{telemetry-store-X7K5NYWD.js.map → install-manifest-EQHT4474.js.map} +0 -0
  54. /package/dist/{version-B2CCAEMC.js.map → release-artifact-4TL5L2ZY.js.map} +0 -0
@@ -1,1307 +0,0 @@
1
- #!/usr/bin/env node
2
- import {
3
- applyGitattributes,
4
- getPackageVersion,
5
- renderExecutionProfileSection,
6
- renderFolderMap,
7
- resolveExecutionProfile
8
- } from "./chunk-Q2ZQ6RGD.js";
9
- import {
10
- PRIVATE_DIRS_DISPLAY,
11
- PRIVATE_UNTRACK_COMMAND,
12
- applyGitignoreProfile,
13
- resolveGitignoreProfile
14
- } from "./chunk-BZW5DR3O.js";
15
- import "./chunk-OAC5CVHJ.js";
16
- import {
17
- CODEX_SKILLS,
18
- COPILOT_SKILLS,
19
- PI_AGENTS,
20
- PI_EXTENSIONS,
21
- PI_SCRIPTS,
22
- PI_SKILLS,
23
- SKILLS,
24
- TEMPLATES
25
- } from "./chunk-DSVGHVYM.js";
26
- import {
27
- DEFAULT_GITIGNORE_PROFILE,
28
- STATE_PATH,
29
- hashContent,
30
- readVersion,
31
- resolveHarnesses,
32
- writeVersion
33
- } from "./chunk-PBOICMDE.js";
34
-
35
- // src/init.ts
36
- import { mkdirSync as mkdirSync2, existsSync as existsSync5, writeFileSync as writeFileSync3, readFileSync as readFileSync4, readdirSync as readdirSync2, statSync, chmodSync } from "fs";
37
- import { join as join5, basename, resolve, dirname } from "path";
38
-
39
- // src/detect.ts
40
- import { readFileSync, existsSync, readdirSync } from "fs";
41
- import { join } from "path";
42
- var WEB_FRAMEWORKS = /* @__PURE__ */ new Set(["Next.js", "Nuxt", "Remix", "React", "Vue", "Svelte"]);
43
- var API_FRAMEWORKS = /* @__PURE__ */ new Set(["Express", "Fastify", "FastAPI", "Django", "Flask", "Gin", "Fiber", "Echo", "Actix", "Axum", "Rocket"]);
44
- function buildTestingStrategy(backbone) {
45
- switch (backbone) {
46
- case "playwright":
47
- return { backbone, testFormat: ".spec.ts", layers: ["ui", "api", "logic", "static"] };
48
- case "maestro":
49
- return { backbone, testFormat: ".yaml", layers: ["ui", "api", "logic", "static"] };
50
- case "api":
51
- return { backbone, testFormat: ".test.ts", layers: ["api", "logic", "static"] };
52
- case "native":
53
- return { backbone, testFormat: ".test.ts", layers: ["logic", "static"] };
54
- }
55
- }
56
- function readFile(path) {
57
- try {
58
- return readFileSync(path, "utf-8");
59
- } catch {
60
- return null;
61
- }
62
- }
63
- function detectNodeFramework(pkg) {
64
- const allDeps = { ...pkg.dependencies, ...pkg.devDependencies };
65
- if (allDeps["next"]) return "Next.js";
66
- if (allDeps["nuxt"]) return "Nuxt";
67
- if (allDeps["@remix-run/node"] || allDeps["@remix-run/react"]) return "Remix";
68
- if (allDeps["express"]) return "Express";
69
- if (allDeps["fastify"]) return "Fastify";
70
- if (allDeps["react"]) return "React";
71
- if (allDeps["vue"]) return "Vue";
72
- if (allDeps["svelte"]) return "Svelte";
73
- return void 0;
74
- }
75
- function detectNodeTestFramework(pkg) {
76
- const allDeps = { ...pkg.dependencies, ...pkg.devDependencies };
77
- if (allDeps["vitest"]) return "vitest";
78
- if (allDeps["jest"]) return "jest";
79
- if (allDeps["mocha"]) return "mocha";
80
- return void 0;
81
- }
82
- function detectNodePackageManager(dir) {
83
- if (existsSync(join(dir, "pnpm-lock.yaml"))) return "pnpm";
84
- if (existsSync(join(dir, "yarn.lock"))) return "yarn";
85
- if (existsSync(join(dir, "bun.lockb")) || existsSync(join(dir, "bun.lock"))) return "bun";
86
- return "npm";
87
- }
88
- function detectNode(dir) {
89
- const raw = readFile(join(dir, "package.json"));
90
- if (raw === null) return null;
91
- let pkg;
92
- try {
93
- pkg = JSON.parse(raw);
94
- } catch {
95
- return null;
96
- }
97
- const pm = detectNodePackageManager(dir);
98
- const run = pm === "npm" ? "npm run" : pm;
99
- const scripts = pkg.scripts ?? {};
100
- const framework = detectNodeFramework(pkg);
101
- const testFramework = detectNodeTestFramework(pkg);
102
- const commands = {};
103
- if (scripts.build) commands.build = `${run} build`;
104
- else commands.build = `${run} build`;
105
- if (scripts.test) commands.test = `${run} test`;
106
- else if (testFramework) commands.test = `${run} test`;
107
- else commands.test = `${pm === "npm" ? "npm" : pm} test`;
108
- if (scripts.lint) commands.lint = `${run} lint`;
109
- if (scripts.typecheck) commands.typecheck = `${run} typecheck`;
110
- else if (pkg.devDependencies?.["typescript"]) {
111
- commands.typecheck = "tsc --noEmit";
112
- }
113
- const allDeps = { ...pkg.dependencies, ...pkg.devDependencies };
114
- let testingStrategy;
115
- if (allDeps["react-native"]) {
116
- testingStrategy = buildTestingStrategy("maestro");
117
- } else if (framework && WEB_FRAMEWORKS.has(framework)) {
118
- testingStrategy = buildTestingStrategy("playwright");
119
- } else if (framework && API_FRAMEWORKS.has(framework)) {
120
- testingStrategy = buildTestingStrategy("api");
121
- } else {
122
- testingStrategy = buildTestingStrategy("native");
123
- }
124
- return {
125
- language: "node",
126
- packageManager: pm,
127
- commands,
128
- framework,
129
- testingStrategy
130
- };
131
- }
132
- function detectPythonFramework(content) {
133
- if (/fastapi/i.test(content)) return "FastAPI";
134
- if (/django/i.test(content)) return "Django";
135
- if (/flask/i.test(content)) return "Flask";
136
- return void 0;
137
- }
138
- function detectPython(dir) {
139
- const pyproject = readFile(join(dir, "pyproject.toml"));
140
- if (pyproject !== null) {
141
- const isPoetry = /\[tool\.poetry\]/.test(pyproject);
142
- const isUv = existsSync(join(dir, "uv.lock"));
143
- let pm;
144
- let run;
145
- if (isUv) {
146
- pm = "uv";
147
- run = "uv run";
148
- } else if (isPoetry) {
149
- pm = "poetry";
150
- run = "poetry run";
151
- } else {
152
- pm = "pip";
153
- run = "python -m";
154
- }
155
- const framework = detectPythonFramework(pyproject);
156
- const hasPytest = /pytest/i.test(pyproject);
157
- const testingStrategy = framework && API_FRAMEWORKS.has(framework) ? buildTestingStrategy("api") : buildTestingStrategy("native");
158
- return {
159
- language: "python",
160
- packageManager: pm,
161
- commands: {
162
- build: `${pm === "poetry" ? "poetry" : pm} build`,
163
- test: hasPytest ? `${run} pytest` : `${run} pytest`,
164
- lint: `${run} ruff check .`
165
- },
166
- framework,
167
- testingStrategy
168
- };
169
- }
170
- const requirements = readFile(join(dir, "requirements.txt"));
171
- if (requirements !== null) {
172
- const framework = detectPythonFramework(requirements);
173
- const testingStrategy = framework && API_FRAMEWORKS.has(framework) ? buildTestingStrategy("api") : buildTestingStrategy("native");
174
- return {
175
- language: "python",
176
- packageManager: "pip",
177
- commands: {
178
- build: "pip install -e .",
179
- test: "python -m pytest",
180
- lint: "python -m ruff check ."
181
- },
182
- framework,
183
- testingStrategy
184
- };
185
- }
186
- return null;
187
- }
188
- function detectRust(dir) {
189
- const cargo = readFile(join(dir, "Cargo.toml"));
190
- if (cargo === null) return null;
191
- let framework;
192
- if (/actix-web/.test(cargo)) framework = "Actix";
193
- else if (/axum/.test(cargo)) framework = "Axum";
194
- else if (/rocket/.test(cargo)) framework = "Rocket";
195
- const testingStrategy = framework && API_FRAMEWORKS.has(framework) ? buildTestingStrategy("api") : buildTestingStrategy("native");
196
- return {
197
- language: "rust",
198
- packageManager: "cargo",
199
- commands: {
200
- build: "cargo build",
201
- test: "cargo test",
202
- lint: "cargo clippy"
203
- },
204
- framework,
205
- testingStrategy
206
- };
207
- }
208
- function detectGo(dir) {
209
- const gomod = readFile(join(dir, "go.mod"));
210
- if (gomod === null) return null;
211
- let framework;
212
- if (/github\.com\/gin-gonic\/gin/.test(gomod)) framework = "Gin";
213
- else if (/github\.com\/gofiber\/fiber/.test(gomod)) framework = "Fiber";
214
- else if (/github\.com\/labstack\/echo/.test(gomod)) framework = "Echo";
215
- const testingStrategy = framework && API_FRAMEWORKS.has(framework) ? buildTestingStrategy("api") : buildTestingStrategy("native");
216
- return {
217
- language: "go",
218
- packageManager: "go",
219
- commands: {
220
- build: "go build ./...",
221
- test: "go test ./...",
222
- lint: "golangci-lint run"
223
- },
224
- framework,
225
- testingStrategy
226
- };
227
- }
228
- function detectSwift(dir) {
229
- const pkg = readFile(join(dir, "Package.swift"));
230
- if (pkg === null) return null;
231
- return {
232
- language: "swift",
233
- packageManager: "swift",
234
- commands: {
235
- build: "swift build",
236
- test: "swift test"
237
- },
238
- testingStrategy: buildTestingStrategy("native")
239
- };
240
- }
241
- function detectFlutter(dir) {
242
- const pubspec = readFile(join(dir, "pubspec.yaml"));
243
- if (pubspec === null) return null;
244
- if (!/flutter/i.test(pubspec)) return null;
245
- return {
246
- language: "dart",
247
- packageManager: "flutter",
248
- commands: {
249
- build: "flutter build",
250
- test: "flutter test",
251
- lint: "flutter analyze"
252
- },
253
- framework: "Flutter",
254
- testingStrategy: buildTestingStrategy("maestro")
255
- };
256
- }
257
- function detectXcode(dir) {
258
- try {
259
- const entries = readdirSync(dir);
260
- const hasXcode = entries.some((e) => e.endsWith(".xcodeproj") || e.endsWith(".xcworkspace"));
261
- if (!hasXcode) return null;
262
- } catch {
263
- return null;
264
- }
265
- return {
266
- language: "swift",
267
- packageManager: "xcode",
268
- commands: {
269
- build: "xcodebuild build",
270
- test: "xcodebuild test"
271
- },
272
- testingStrategy: buildTestingStrategy("maestro")
273
- };
274
- }
275
- function detectMakefile(dir) {
276
- const makefile = readFile(join(dir, "Makefile"));
277
- if (makefile === null) return null;
278
- const commands = {};
279
- commands.build = "make build";
280
- if (/^test:/m.test(makefile)) commands.test = "make test";
281
- if (/^lint:/m.test(makefile)) commands.lint = "make lint";
282
- return {
283
- language: "unknown",
284
- packageManager: "make",
285
- commands
286
- };
287
- }
288
- function detectDockerfile(dir) {
289
- if (!existsSync(join(dir, "Dockerfile"))) return null;
290
- return {
291
- language: "unknown",
292
- packageManager: "docker",
293
- commands: {
294
- build: "docker build ."
295
- }
296
- };
297
- }
298
- async function detectStack(dir) {
299
- const detectors = [
300
- detectNode,
301
- detectPython,
302
- detectRust,
303
- detectGo,
304
- detectFlutter,
305
- detectSwift,
306
- detectXcode,
307
- detectMakefile,
308
- detectDockerfile
309
- ];
310
- for (const detect of detectors) {
311
- const result = detect(dir);
312
- if (result) return result;
313
- }
314
- return { language: "unknown", packageManager: "", commands: {} };
315
- }
316
-
317
- // src/improve-claude-md.ts
318
- import { existsSync as existsSync2 } from "fs";
319
- import { join as join2 } from "path";
320
- function nonEmptyLines(items) {
321
- return (items ?? []).map((s) => s.trim()).filter((s) => s.length > 0);
322
- }
323
- function glossaryEntries(glossary) {
324
- return Object.entries(glossary ?? []).map(([term, def]) => [term.trim(), def.trim()]).filter(([term, def]) => term.length > 0 && def.length > 0);
325
- }
326
- function generateProductIdentitySection(identity) {
327
- if (!identity) return null;
328
- const values = nonEmptyLines(identity.values);
329
- const taste = nonEmptyLines(identity.taste);
330
- const glossary = glossaryEntries(identity.glossary);
331
- if (values.length === 0 && taste.length === 0 && glossary.length === 0) return null;
332
- const today = (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
333
- const parts = ["## Product Identity", "", `_Added ${today} \u2014 review at next optimize run_`];
334
- if (values.length > 0) {
335
- parts.push("", "### Values", "", ...values.map((v) => `- ${v}`));
336
- }
337
- if (glossary.length > 0) {
338
- parts.push("", "### Glossary", "", ...glossary.map(([term, def]) => `- **${term}** \u2014 ${def}`));
339
- }
340
- if (taste.length > 0) {
341
- parts.push("", "### Taste", "", ...taste.map((t) => `- ${t}`));
342
- }
343
- return parts.join("\n");
344
- }
345
- var PRIVATE_SETUP_NOTE_MARKER = "After cloning, run";
346
- function generatePrivateSetupNote() {
347
- return `> **Private setup:** The harness dirs (\`.claude/\`, \`.agents/\`, \`.pi/\`) are gitignored in this repo, so they aren't committed. ${PRIVATE_SETUP_NOTE_MARKER} \`npx joycraft init\` to regenerate the skill files locally \u2014 it only creates missing files and leaves your committed \`CLAUDE.md\`, \`AGENTS.md\`, and \`docs/\` untouched (use \`--force\` only if you deliberately want to regenerate them).`;
348
- }
349
- function generateCommandsBlock(stack) {
350
- const lines = ["```bash"];
351
- if (stack.commands.build) lines.push(`# Build
352
- ${stack.commands.build}`);
353
- if (stack.commands.test) lines.push(`# Test
354
- ${stack.commands.test}`);
355
- if (stack.commands.lint) lines.push(`# Lint
356
- ${stack.commands.lint}`);
357
- if (stack.commands.typecheck) lines.push(`# Type check
358
- ${stack.commands.typecheck}`);
359
- if (stack.commands.deploy) lines.push(`# Deploy
360
- ${stack.commands.deploy}`);
361
- lines.push("```");
362
- return lines.join("\n");
363
- }
364
- function generateExternalApiSafetySection() {
365
- return "### External API Safety\n- Read official docs and type definitions before writing code against a third-party SDK\n- Add third-party SDKs as devDependencies so typecheck runs against real types, not stubs\n- Critical integration paths should have a smoke test that validates against the real runtime";
366
- }
367
- function generateClaudeMdPointer() {
368
- return `@AGENTS.md
369
-
370
- ## Claude Code
371
-
372
- _Shared project instructions \u2014 boundaries, workflow, architecture \u2014 live in \`AGENTS.md\`, imported above so every AI tool reads the same source. Add Claude Code\u2013specific instructions in this section only._
373
- `;
374
- }
375
- function generateBoundariesSection() {
376
- return `## Behavioral Boundaries
377
-
378
- ### ALWAYS
379
- - Run tests and type-check before committing
380
- - Run tests before implementing new features -- confirm they fail first, then implement until they pass
381
- - Use \`verb: concise message\` format for commits
382
- - Commit after completing each discrete task (atomic commits)
383
- - Stage specific files by name (not \`git add -A\` or \`git add .\`)
384
- - Read \`docs/context/\` before making infrastructure or config changes
385
- - Follow existing code patterns and style
386
-
387
- ### ASK FIRST
388
- - Pushing to remote
389
- - Creating or merging pull requests
390
- - Adding new dependencies
391
- - Modifying database schema or data models
392
- - Changing authentication or authorization flows
393
- - Any destructive git operation (force-push, reset --hard, branch deletion)
394
-
395
- ### NEVER
396
- - Push directly to main/master without approval
397
- - Commit .env files, secrets, or credentials
398
- - Use --no-verify to skip hooks
399
- - Amend commits that have been pushed
400
- - Skip type-checking or linting
401
- - Commit code that doesn't build`;
402
- }
403
- function generateWorkflowSection(stack) {
404
- return `## Development Workflow
405
-
406
- ${generateCommandsBlock(stack)}
407
-
408
- **Default execution mode:** batch
409
-
410
- _How \`/joycraft-implement\` wraps up after each spec. \`joycraft-decompose\` reads this line (absent \u21D2 \`batch\`) and recommends a per-spec mode you approve. Modes: \`batch\` (implement a cluster, wrap once at the end), \`checkpoint\` (commit + status bump after each spec), \`isolated\` (fresh context per spec \u2014 on Pi, the \`joycraft-implement-loop\` driver). Change the value above to set your project default._
411
-
412
- **Deferred work \u2192 \`docs/backlog/\`.** Ideas and follow-ups you surface mid-sprint but can't take on now go to \`docs/backlog/\` (one file per item) so the current spec stays focused without losing the thread. Promote an entry to a Feature Brief under \`docs/features/<slug>/\` when you're ready to build it.`;
413
- }
414
- function generateArchitectureSection(projectDir) {
415
- if (projectDir) {
416
- return `## Architecture
417
-
418
- ${renderFolderMap(projectDir)}`;
419
- }
420
- return `## Architecture
421
-
422
- _TODO: Add a brief description of your project's architecture and key directories._`;
423
- }
424
- function generateKeyFilesSection() {
425
- return `## Key Files
426
-
427
- | File | Purpose |
428
- |------|---------|
429
- | _TODO_ | _Add key files and their purposes_ |`;
430
- }
431
- function generateGotchasSection() {
432
- return `## Common Gotchas
433
-
434
- _TODO: Add any gotchas, quirks, or non-obvious behaviors that developers should know about._`;
435
- }
436
- function generateGettingStartedSection(multiTool = false) {
437
- const invocationNote = multiTool ? "\n\nSkill names are shared across tools; only the invocation prefix differs: `/joycraft-*` (Claude Code), `$joycraft-*` (Codex), `/skill:joycraft-*` (Pi)." : "";
438
- return `## Getting Started with Joycraft
439
-
440
- This project uses [Joycraft](https://github.com/maksutovic/joycraft) for AI development workflow. Available skills:
441
-
442
- | Skill | Purpose |
443
- |-------|---------|
444
- | \`/joycraft-setup\` | Start here \u2014 the first-run door; sets up and assesses your project |
445
- | \`/joycraft-tune\` | Assess your harness, apply upgrades, see your maturity roadmap |
446
- | \`/joycraft-new-feature\` | Interview -> Feature Brief -> Atomic Specs |
447
- | \`/joycraft-interview\` | Lightweight brainstorm \u2014 yap about ideas, get a structured summary |
448
- | \`/joycraft-decompose\` | Break a brief into small, testable specs |
449
- | \`/joycraft-session-end\` | Capture discoveries, verify, commit |
450
- | \`/joycraft-implement-level5\` | Experimental \u2014 Level 5 autofix loop, holdout scenarios, scenario evolution |
451
-
452
- Run \`/joycraft-tune\` to see where your project stands and what to improve next.${invocationNote}`;
453
- }
454
- function generateContextMapSection() {
455
- return `## Context Map
456
-
457
- Keep this file lean \u2014 link out, don't inline. Long-form reference docs live in \`docs/context/reference/\`; this table points to what to read on demand.
458
-
459
- | Document | Read it when\u2026 |
460
- |----------|---------------|`;
461
- }
462
- function generateAreasSection() {
463
- return `## Areas
464
-
465
- This project organizes some work by area. When working on a specific area, read its README first; check for area-specific boundaries.
466
-
467
- - For each area: see \`docs/areas/<area-name>/README.md\`
468
- - Area-level boundaries (when present): \`docs/areas/<area-name>/boundaries.md\``;
469
- }
470
- function projectHasAreas(opts) {
471
- if (!opts?.projectDir) return false;
472
- return existsSync2(join2(opts.projectDir, "docs", "areas"));
473
- }
474
- function generateProjectToolsSection(existingSkills) {
475
- const MAX_LISTED = 10;
476
- let skillList;
477
- if (existingSkills.length <= MAX_LISTED) {
478
- skillList = existingSkills.join(", ");
479
- } else {
480
- skillList = existingSkills.slice(0, MAX_LISTED).join(", ") + `, and ${existingSkills.length - MAX_LISTED} more \u2014 see .claude/skills/`;
481
- }
482
- return `## Project Tools
483
-
484
- This project has additional tools beyond Joycraft. Always check \`.claude/skills/\` for available skills: ${skillList}`;
485
- }
486
- function generateCLAUDEMd(projectName, stack, existingSkills = [], opts) {
487
- const frameworkNote = stack.framework ? ` (${stack.framework})` : "";
488
- const langLabel = stack.language === "unknown" ? "" : ` | **Stack:** ${stack.language}${frameworkNote}`;
489
- const lines = [
490
- `# ${projectName}`,
491
- "",
492
- `**Component:** _TODO: describe what this project is_${langLabel}`,
493
- "",
494
- "---",
495
- "",
496
- generateBoundariesSection(),
497
- ""
498
- ];
499
- if (opts?.multiTool) {
500
- lines.push(generateExternalApiSafetySection(), "");
501
- }
502
- lines.push(
503
- generateWorkflowSection(stack),
504
- "",
505
- generateArchitectureSection(opts?.projectDir),
506
- "",
507
- generateKeyFilesSection(),
508
- "",
509
- generateGotchasSection(),
510
- "",
511
- generateContextMapSection(),
512
- "",
513
- generateGettingStartedSection(opts?.multiTool ?? false),
514
- ""
515
- );
516
- const identitySection = generateProductIdentitySection(opts?.identity);
517
- if (identitySection) {
518
- lines.push(identitySection, "");
519
- }
520
- if (opts?.executionProfile) {
521
- lines.push(renderExecutionProfileSection(opts.executionProfile), "");
522
- }
523
- if (opts?.privateProfile) {
524
- lines.push(generatePrivateSetupNote(), "");
525
- }
526
- if (existingSkills.length > 0) {
527
- lines.push(generateProjectToolsSection(existingSkills), "");
528
- }
529
- if (projectHasAreas(opts)) {
530
- lines.push(generateAreasSection(), "");
531
- }
532
- return lines.join("\n");
533
- }
534
-
535
- // src/agents-md.ts
536
- function generateCommandsBlock2(stack) {
537
- const lines = ["```bash"];
538
- if (stack.commands.build) lines.push(stack.commands.build);
539
- if (stack.commands.test) lines.push(stack.commands.test);
540
- if (stack.commands.lint) lines.push(stack.commands.lint);
541
- if (stack.commands.typecheck) lines.push(stack.commands.typecheck);
542
- if (stack.commands.deploy) lines.push(stack.commands.deploy);
543
- lines.push("```");
544
- return lines.join("\n");
545
- }
546
- function generateDevelopmentSection(stack) {
547
- return `## Development
548
-
549
- ${generateCommandsBlock2(stack)}
550
-
551
- **Deferred work \u2192 \`docs/backlog/\`.** Ideas and follow-ups surfaced mid-sprint that can't be taken on now go to \`docs/backlog/\` (one file per item) so the current spec stays focused. Promote an entry to a Feature Brief under \`docs/features/<slug>/\` when ready to build it.`;
552
- }
553
- function generateArchitectureSection2(projectDir) {
554
- if (projectDir) {
555
- return `## Architecture
556
-
557
- ${renderFolderMap(projectDir)}`;
558
- }
559
- return `## Architecture
560
-
561
- _TODO: Add a compact directory tree and one-paragraph summary._`;
562
- }
563
- function generateKeyFilesSection2() {
564
- return `## Key Files
565
-
566
- | File | Purpose |
567
- |------|---------|
568
- | _TODO_ | _Add key files_ |`;
569
- }
570
- function generateAgentsMd(projectName, stack, privateProfile = false, executionProfile, identity, projectDir) {
571
- const frameworkNote = stack.framework ? ` (${stack.framework})` : "";
572
- const langLabel = stack.language === "unknown" ? "" : ` | **Stack:** ${stack.language}${frameworkNote}`;
573
- const lines = [
574
- `# ${projectName}`,
575
- "",
576
- `**Component:** _TODO: describe what this project is_${langLabel}`,
577
- "",
578
- "> Auto-generated by Joycraft.",
579
- "",
580
- "---",
581
- "",
582
- generateBoundariesSection(),
583
- generateExternalApiSafetySection(),
584
- "",
585
- generateArchitectureSection2(projectDir),
586
- "",
587
- generateKeyFilesSection2(),
588
- "",
589
- generateDevelopmentSection(stack),
590
- ""
591
- ];
592
- const identitySection = generateProductIdentitySection(identity);
593
- if (identitySection) {
594
- lines.push(identitySection, "");
595
- }
596
- if (executionProfile) {
597
- lines.push(renderExecutionProfileSection(executionProfile), "");
598
- }
599
- if (privateProfile) {
600
- lines.push(generatePrivateSetupNote(), "");
601
- }
602
- return lines.join("\n");
603
- }
604
-
605
- // src/permissions.ts
606
- function generatePermissions(stack) {
607
- const deny = [
608
- "Bash(rm -rf *)",
609
- "Bash(git push --force *)",
610
- "Bash(git push -f *)",
611
- "Bash(git reset --hard *)",
612
- "Edit(//.env*)",
613
- "Edit(//*.pem)",
614
- "Edit(//*.key)",
615
- "Edit(//.git/**)"
616
- ];
617
- const allow = [
618
- "Bash(git status)",
619
- "Bash(git diff *)",
620
- "Bash(git log *)",
621
- "Bash(git add *)",
622
- "Bash(git commit *)",
623
- "Bash(git checkout *)",
624
- "Bash(git branch *)"
625
- ];
626
- if (stack.language === "node") {
627
- allow.push(`Bash(${stack.packageManager} *)`);
628
- if (stack.packageManager !== "npm") deny.push("Bash(npm install *)");
629
- if (stack.packageManager !== "yarn") deny.push("Bash(yarn add *)");
630
- if (stack.packageManager !== "pnpm") deny.push("Bash(pnpm add *)");
631
- if (stack.packageManager !== "bun") deny.push("Bash(bun add *)");
632
- if (stack.commands.test) allow.push(`Bash(${stack.commands.test})`);
633
- if (stack.commands.build) allow.push(`Bash(${stack.commands.build})`);
634
- if (stack.commands.lint) allow.push(`Bash(${stack.commands.lint})`);
635
- if (stack.commands.typecheck) allow.push(`Bash(${stack.commands.typecheck})`);
636
- }
637
- if (stack.language === "python") {
638
- allow.push(`Bash(${stack.packageManager} *)`);
639
- if (stack.commands.test) allow.push(`Bash(${stack.commands.test})`);
640
- if (stack.commands.lint) allow.push(`Bash(${stack.commands.lint})`);
641
- if (stack.commands.build) allow.push(`Bash(${stack.commands.build})`);
642
- }
643
- if (stack.language === "rust") {
644
- allow.push("Bash(cargo *)");
645
- }
646
- if (stack.language === "go") {
647
- allow.push("Bash(go *)");
648
- }
649
- if (stack.language === "swift") {
650
- allow.push("Bash(swift *)");
651
- allow.push("Bash(xcodebuild *)");
652
- }
653
- return { allow, deny };
654
- }
655
-
656
- // src/safeguard.ts
657
- import { existsSync as existsSync3, readFileSync as readFileSync2, writeFileSync, mkdirSync } from "fs";
658
- import { join as join3 } from "path";
659
- function generateHookScript() {
660
- return `#!/bin/bash
661
- # Joycraft Safeguard \u2014 PreToolUse hook
662
- # Blocks dangerous Bash commands. Exit 2 = block the action.
663
- # Edit deny-patterns.txt to customize what's blocked.
664
-
665
- TOOL_NAME="$1"
666
- # Read the full tool input from stdin
667
- INPUT=$(cat)
668
-
669
- # Only check Bash commands
670
- if [ "$TOOL_NAME" != "Bash" ]; then
671
- exit 0
672
- fi
673
-
674
- # Extract the command from the JSON input
675
- COMMAND=$(echo "$INPUT" | grep -o '"command":"[^"]*"' | head -1 | sed 's/"command":"//;s/"$//')
676
-
677
- if [ -z "$COMMAND" ]; then
678
- exit 0
679
- fi
680
-
681
- PATTERNS_FILE="$(dirname "$0")/deny-patterns.txt"
682
-
683
- if [ ! -f "$PATTERNS_FILE" ]; then
684
- exit 0
685
- fi
686
-
687
- while IFS= read -r pattern || [ -n "$pattern" ]; do
688
- # Skip empty lines and comments
689
- [ -z "$pattern" ] && continue
690
- [[ "$pattern" == \\#* ]] && continue
691
-
692
- if echo "$COMMAND" | grep -qEi "$pattern"; then
693
- echo "Blocked by Joycraft Safeguard: command matches deny pattern '$pattern'"
694
- echo "Edit .claude/hooks/joycraft/deny-patterns.txt to modify blocked patterns."
695
- exit 2
696
- fi
697
- done < "$PATTERNS_FILE"
698
-
699
- exit 0
700
- `;
701
- }
702
- function generateDenyPatternsFile(customPatterns = []) {
703
- const lines = [
704
- "# Joycraft Safeguard \u2014 Deny Patterns",
705
- "# One regex pattern per line. Lines starting with # are comments.",
706
- "# Commands matching any pattern will be blocked (exit 2).",
707
- "# Edit this file to customize what's blocked.",
708
- "",
709
- "# Destructive file operations",
710
- "rm\\s+-rf\\s+/",
711
- "rm\\s+-rf\\s+\\.",
712
- "",
713
- "# Dangerous git operations",
714
- "git\\s+push\\s+--force",
715
- "git\\s+push\\s+-f\\b",
716
- "git\\s+reset\\s+--hard",
717
- "",
718
- "# SQL destruction",
719
- "DROP\\s+TABLE",
720
- "DROP\\s+DATABASE",
721
- "TRUNCATE",
722
- "",
723
- "# System security",
724
- "chmod\\s+777",
725
- "curl.*\\|.*sh",
726
- "wget.*\\|.*sh"
727
- ];
728
- if (customPatterns.length > 0) {
729
- lines.push("");
730
- lines.push("# Project-specific patterns (from risk interview)");
731
- for (const p of customPatterns) {
732
- lines.push(p);
733
- }
734
- }
735
- return lines.join("\n") + "\n";
736
- }
737
- function installSafeguardHooks(targetDir, customPatterns = [], force = false, skipSettingsMerge = false) {
738
- const result = { created: [], skipped: [] };
739
- const hooksDir = join3(targetDir, ".claude", "hooks", "joycraft");
740
- if (!existsSync3(hooksDir)) {
741
- mkdirSync(hooksDir, { recursive: true });
742
- }
743
- const hookPath = join3(hooksDir, "block-dangerous.sh");
744
- if (!existsSync3(hookPath) || force) {
745
- writeFileSync(hookPath, generateHookScript(), { mode: 493 });
746
- result.created.push(hookPath);
747
- } else {
748
- result.skipped.push(hookPath);
749
- }
750
- const patternsPath = join3(hooksDir, "deny-patterns.txt");
751
- if (!existsSync3(patternsPath) || force) {
752
- writeFileSync(patternsPath, generateDenyPatternsFile(customPatterns));
753
- result.created.push(patternsPath);
754
- } else {
755
- result.skipped.push(patternsPath);
756
- }
757
- if (!skipSettingsMerge) {
758
- const settingsPath = join3(targetDir, ".claude", "settings.json");
759
- let settings = {};
760
- if (existsSync3(settingsPath)) {
761
- try {
762
- settings = JSON.parse(readFileSync2(settingsPath, "utf-8"));
763
- } catch {
764
- return result;
765
- }
766
- }
767
- if (!settings.hooks) settings.hooks = {};
768
- const hooks = settings.hooks;
769
- if (!hooks.PreToolUse) hooks.PreToolUse = [];
770
- const preToolUse = hooks.PreToolUse;
771
- const hasJoycraftHook = preToolUse.some((h) => {
772
- const innerHooks = h.hooks;
773
- return innerHooks?.some((ih) => typeof ih.command === "string" && ih.command.includes("joycraft"));
774
- });
775
- if (!hasJoycraftHook) {
776
- preToolUse.push({
777
- matcher: "Bash",
778
- hooks: [{
779
- type: "command",
780
- command: ".claude/hooks/joycraft/block-dangerous.sh"
781
- }]
782
- });
783
- writeFileSync(settingsPath, JSON.stringify(settings, null, 2) + "\n", "utf-8");
784
- }
785
- }
786
- return result;
787
- }
788
-
789
- // src/tsconfig.ts
790
- import { existsSync as existsSync4, readFileSync as readFileSync3, writeFileSync as writeFileSync2 } from "fs";
791
- import { join as join4 } from "path";
792
- var PI_EXCLUDE = ".pi";
793
- function stripJsonComments(text) {
794
- return text.replace(/\/\*[\s\S]*?\*\//g, "").replace(/(^|[^:])\/\/.*$/gm, "$1");
795
- }
796
- function alreadyExcludesPi(rawText) {
797
- try {
798
- const parsed = JSON.parse(stripJsonComments(rawText));
799
- if (!Array.isArray(parsed.exclude)) return false;
800
- return parsed.exclude.some(
801
- (e) => typeof e === "string" && (e === PI_EXCLUDE || e === "./.pi" || e === ".pi/**")
802
- );
803
- } catch {
804
- return false;
805
- }
806
- }
807
- function insertPiExclude(rawText) {
808
- const excludeArrayRe = /("exclude"\s*:\s*\[)(\s*)/;
809
- if (excludeArrayRe.test(rawText)) {
810
- return rawText.replace(excludeArrayRe, (_m, open, ws) => {
811
- const sep = ws.includes("\n") ? ws : " ";
812
- return `${open}${sep}"${PI_EXCLUDE}",${ws.includes("\n") ? "" : " "}`;
813
- });
814
- }
815
- const includeArrayRe = /("include"\s*:\s*\[[^\]]*\])/;
816
- if (includeArrayRe.test(rawText)) {
817
- return rawText.replace(includeArrayRe, (m) => `${m},
818
- "exclude": ["${PI_EXCLUDE}"]`);
819
- }
820
- const lastBrace = rawText.lastIndexOf("}");
821
- if (lastBrace > 0 && rawText.slice(0, lastBrace).includes(":")) {
822
- const before = rawText.slice(0, lastBrace).replace(/\s*$/, "");
823
- const after = rawText.slice(lastBrace);
824
- const needsComma = !before.endsWith(",") && !before.endsWith("{");
825
- return `${before}${needsComma ? "," : ""}
826
- "exclude": ["${PI_EXCLUDE}"]
827
- ${after}`;
828
- }
829
- return null;
830
- }
831
- function ensurePiExcludedFromTsconfig(targetDir) {
832
- const path = join4(targetDir, "tsconfig.json");
833
- if (!existsSync4(path)) return { status: "no-tsconfig" };
834
- let rawText;
835
- try {
836
- rawText = readFileSync3(path, "utf-8");
837
- } catch {
838
- return { status: "skipped", reason: "tsconfig.json could not be read" };
839
- }
840
- if (alreadyExcludesPi(rawText)) {
841
- return { status: "already-present", path };
842
- }
843
- const updated = insertPiExclude(rawText);
844
- if (updated === null || updated === rawText) {
845
- return {
846
- status: "skipped",
847
- reason: 'could not safely edit tsconfig.json \u2014 add ".pi" to its "exclude" array manually so the Pi extension stays out of your TypeScript build'
848
- };
849
- }
850
- if (!alreadyExcludesPi(updated)) {
851
- return {
852
- status: "skipped",
853
- reason: 'tsconfig.json edit could not be verified \u2014 add ".pi" to its "exclude" array manually'
854
- };
855
- }
856
- try {
857
- writeFileSync2(path, updated, "utf-8");
858
- } catch {
859
- return { status: "skipped", reason: "tsconfig.json could not be written" };
860
- }
861
- return { status: "added", path };
862
- }
863
-
864
- // src/auto-memory.ts
865
- import { createInterface } from "readline";
866
- var AUTO_MEMORY_KEY = "autoMemoryEnabled";
867
- function parseAutoMemoryAnswer(answer) {
868
- const normalized = answer.trim().toLowerCase();
869
- if (normalized === "") return false;
870
- if (normalized === "y" || normalized === "yes") return true;
871
- if (normalized === "n" || normalized === "no") return false;
872
- return null;
873
- }
874
- function promptAutoMemory() {
875
- console.log("\nJoycraft keeps project facts in one home: your repo.");
876
- console.log(
877
- " Claude Code auto-memory is a second, per-machine home for the same facts."
878
- );
879
- console.log(
880
- ` Disabling it for this project writes "${AUTO_MEMORY_KEY}": false to .claude/settings.json.`
881
- );
882
- console.log(" Your other projects are unaffected.");
883
- const input = process.stdin;
884
- if (input.readableEnded === true || input.destroyed === true) {
885
- return Promise.resolve(false);
886
- }
887
- return new Promise((resolve2) => {
888
- const rl = createInterface({ input, output: process.stdout });
889
- let settled = false;
890
- const done = (value) => {
891
- if (settled) return;
892
- settled = true;
893
- rl.close();
894
- resolve2(value);
895
- };
896
- rl.once("close", () => done(false));
897
- const ask = (attempt) => {
898
- rl.question("Disable auto-memory for this project? [y/N]: ", (answer) => {
899
- const parsed = parseAutoMemoryAnswer(answer);
900
- if (parsed !== null) {
901
- done(parsed);
902
- return;
903
- }
904
- if (attempt >= 4) {
905
- done(false);
906
- return;
907
- }
908
- console.log(`Unrecognized answer '${answer.trim()}' \u2014 type 'y' or 'n', or press Enter for no change.`);
909
- ask(attempt + 1);
910
- });
911
- };
912
- ask(0);
913
- });
914
- }
915
- async function resolveAutoMemoryOffer(interactive) {
916
- if (!interactive) return false;
917
- return promptAutoMemory();
918
- }
919
-
920
- // src/init.ts
921
- var BACKLOG_README = `# Backlog
922
-
923
- Deferred work lives here \u2014 ideas and follow-ups you surface mid-sprint but
924
- can't take on in the current feature. Capturing them keeps the current spec
925
- focused without losing the thread.
926
-
927
- - One file per item: \`docs/backlog/YYYY-MM-DD-<short-name>.md\`.
928
- - Joycraft skills (\`/joycraft-interview\`, \`/joycraft-new-feature\`,
929
- \`/joycraft-design\`) offer to write entries here \u2014 always with your
930
- confirmation, never automatically.
931
- - Promote an item by turning it into a Feature Brief under
932
- \`docs/features/<slug>/\` when you're ready to build it.
933
- `;
934
- function ensureDir(dir) {
935
- if (!existsSync5(dir)) {
936
- mkdirSync2(dir, { recursive: true });
937
- }
938
- }
939
- function writeFile(path, content, force, result) {
940
- if (existsSync5(path) && !force) {
941
- result.skipped.push(path);
942
- return;
943
- }
944
- writeFileSync3(path, content, "utf-8");
945
- result.created.push(path);
946
- }
947
- async function init(dir, opts) {
948
- const targetDir = resolve(dir);
949
- const result = { created: [], skipped: [], modified: [], warnings: [] };
950
- const stack = await detectStack(targetDir);
951
- const isPi = existsSync5(join5(targetDir, ".pi"));
952
- const harnesses = await resolveHarnesses(process.stdin.isTTY === true);
953
- const wants = (h) => harnesses.includes(h);
954
- if (harnesses.length === 0) {
955
- console.log(
956
- "\nNo harness selected \u2014 Joycraft will not install any skills.\nPlease run init again and select at least one harness (claude, codex, pi, copilot)."
957
- );
958
- return;
959
- }
960
- const executionProfile = await resolveExecutionProfile(harnesses, process.stdin.isTTY === true);
961
- const { profile: gitignoreProfile } = await resolveGitignoreProfile({
962
- flag: opts.gitignore,
963
- persisted: readVersion(targetDir)?.gitignoreProfile,
964
- interactive: process.stdin.isTTY === true,
965
- promptIntro: "\nHow should Joycraft files be tracked in git?"
966
- });
967
- const disableAutoMemory = wants("claude") ? await resolveAutoMemoryOffer(process.stdin.isTTY === true) : false;
968
- ensureDir(join5(targetDir, "docs", "context"));
969
- ensureDir(join5(targetDir, "docs", "backlog"));
970
- writeFile(join5(targetDir, "docs", "backlog", "README.md"), BACKLOG_README, opts.force, result);
971
- const skillsDir = join5(targetDir, ".claude", "skills");
972
- let existingSkills = [];
973
- if (wants("claude") && existsSync5(skillsDir)) {
974
- existingSkills = readdirSync2(skillsDir).filter((name) => {
975
- if (name.startsWith("joycraft-")) return false;
976
- if (name.startsWith(".")) return false;
977
- const fullPath = join5(skillsDir, name);
978
- try {
979
- return statSync(fullPath).isDirectory();
980
- } catch {
981
- return false;
982
- }
983
- });
984
- }
985
- if (wants("claude")) {
986
- for (const [filename, content] of Object.entries(SKILLS)) {
987
- const skillName = filename.replace(/\.md$/, "");
988
- const skillDir = join5(skillsDir, skillName);
989
- ensureDir(skillDir);
990
- writeFile(join5(skillDir, "SKILL.md"), content, opts.force, result);
991
- }
992
- }
993
- if (wants("codex")) {
994
- const codexSkillsDir = join5(targetDir, ".agents", "skills");
995
- for (const [filename, content] of Object.entries(CODEX_SKILLS)) {
996
- const skillName = filename.replace(/\.md$/, "");
997
- const skillDir = join5(codexSkillsDir, skillName);
998
- ensureDir(skillDir);
999
- writeFile(join5(skillDir, "SKILL.md"), content, opts.force, result);
1000
- }
1001
- }
1002
- if (wants("pi")) {
1003
- const piSkillsDir = join5(targetDir, ".pi", "skills");
1004
- for (const [filename, content] of Object.entries(PI_SKILLS)) {
1005
- const skillName = filename.replace(/\.md$/, "");
1006
- const skillDir = join5(piSkillsDir, skillName);
1007
- ensureDir(skillDir);
1008
- writeFile(join5(skillDir, "SKILL.md"), content, opts.force, result);
1009
- }
1010
- const piScriptsDir = join5(targetDir, ".pi", "scripts", "joycraft");
1011
- ensureDir(piScriptsDir);
1012
- for (const [name, content] of Object.entries(PI_SCRIPTS)) {
1013
- const scriptPath = join5(piScriptsDir, name);
1014
- writeFile(scriptPath, content, opts.force, result);
1015
- if (name !== "README.md") {
1016
- try {
1017
- chmodSync(scriptPath, 493);
1018
- } catch {
1019
- }
1020
- }
1021
- }
1022
- const piExtDir = join5(targetDir, ".pi", "extensions");
1023
- ensureDir(piExtDir);
1024
- for (const [name, content] of Object.entries(PI_EXTENSIONS)) {
1025
- writeFile(join5(piExtDir, name), content, opts.force, result);
1026
- }
1027
- const piAgentsDir = join5(targetDir, ".pi", "agents");
1028
- ensureDir(piAgentsDir);
1029
- for (const [name, content] of Object.entries(PI_AGENTS)) {
1030
- writeFile(join5(piAgentsDir, name), content, opts.force, result);
1031
- }
1032
- }
1033
- if (wants("copilot")) {
1034
- const githubDir = join5(targetDir, ".github");
1035
- ensureDir(githubDir);
1036
- const copilotSkillsDir = join5(githubDir, "skills");
1037
- ensureDir(copilotSkillsDir);
1038
- for (const [filename, content] of Object.entries(COPILOT_SKILLS)) {
1039
- const skillName = filename.replace(/\.md$/, "");
1040
- const skillDir = join5(copilotSkillsDir, skillName);
1041
- ensureDir(skillDir);
1042
- writeFile(join5(skillDir, "SKILL.md"), content, opts.force, result);
1043
- }
1044
- }
1045
- const templatesDir = join5(targetDir, "docs", "templates");
1046
- ensureDir(templatesDir);
1047
- for (const [filename, content] of Object.entries(TEMPLATES)) {
1048
- ensureDir(dirname(join5(templatesDir, filename)));
1049
- writeFile(join5(templatesDir, filename), content, opts.force, result);
1050
- }
1051
- const multiTool = wants("codex") || wants("pi") || wants("copilot");
1052
- const claudeMdPath = join5(targetDir, "CLAUDE.md");
1053
- if (existsSync5(claudeMdPath) && !opts.force) {
1054
- result.skipped.push(claudeMdPath);
1055
- } else {
1056
- const projectName = basename(targetDir);
1057
- const content = multiTool ? generateClaudeMdPointer() : generateCLAUDEMd(projectName, stack, existingSkills, {
1058
- privateProfile: gitignoreProfile === "private",
1059
- projectDir: targetDir
1060
- });
1061
- writeFileSync3(claudeMdPath, content, "utf-8");
1062
- result.created.push(claudeMdPath);
1063
- }
1064
- const agentsMdPath = join5(targetDir, "AGENTS.md");
1065
- if (existsSync5(agentsMdPath) && !opts.force) {
1066
- result.skipped.push(agentsMdPath);
1067
- } else {
1068
- const projectName = basename(targetDir);
1069
- const content = multiTool ? generateCLAUDEMd(projectName, stack, existingSkills, {
1070
- privateProfile: gitignoreProfile === "private",
1071
- multiTool: true,
1072
- executionProfile,
1073
- projectDir: targetDir
1074
- }) : generateAgentsMd(projectName, stack, gitignoreProfile === "private", executionProfile, void 0, targetDir);
1075
- writeFileSync3(agentsMdPath, content, "utf-8");
1076
- result.created.push(agentsMdPath);
1077
- }
1078
- const fileHashes = {};
1079
- if (wants("claude")) {
1080
- for (const [filename, content] of Object.entries(SKILLS)) {
1081
- const skillName = filename.replace(/\.md$/, "");
1082
- fileHashes[join5(".claude", "skills", skillName, "SKILL.md")] = hashContent(content);
1083
- }
1084
- }
1085
- if (wants("codex")) {
1086
- for (const [filename, content] of Object.entries(CODEX_SKILLS)) {
1087
- const skillName = filename.replace(/\.md$/, "");
1088
- fileHashes[join5(".agents", "skills", skillName, "SKILL.md")] = hashContent(content);
1089
- }
1090
- }
1091
- for (const [filename, content] of Object.entries(TEMPLATES)) {
1092
- fileHashes[join5("docs", "templates", filename)] = hashContent(content);
1093
- }
1094
- if (wants("pi")) {
1095
- for (const [filename, content] of Object.entries(PI_SKILLS)) {
1096
- const skillName = filename.replace(/\.md$/, "");
1097
- fileHashes[join5(".pi", "skills", skillName, "SKILL.md")] = hashContent(content);
1098
- }
1099
- for (const [name, content] of Object.entries(PI_SCRIPTS)) {
1100
- fileHashes[join5(".pi", "scripts", "joycraft", name)] = hashContent(content);
1101
- }
1102
- for (const [name, content] of Object.entries(PI_EXTENSIONS)) {
1103
- fileHashes[join5(".pi", "extensions", name)] = hashContent(content);
1104
- }
1105
- for (const [name, content] of Object.entries(PI_AGENTS)) {
1106
- fileHashes[join5(".pi", "agents", name)] = hashContent(content);
1107
- }
1108
- }
1109
- if (wants("copilot")) {
1110
- for (const [filename, content] of Object.entries(COPILOT_SKILLS)) {
1111
- const skillName = filename.replace(/\.md$/, "");
1112
- fileHashes[join5(".github", "skills", skillName, "SKILL.md")] = hashContent(content);
1113
- }
1114
- }
1115
- writeVersion(targetDir, getPackageVersion(), fileHashes, gitignoreProfile, harnesses);
1116
- applyGitignoreProfile(targetDir, gitignoreProfile);
1117
- applyGitattributes(targetDir);
1118
- if (wants("pi")) {
1119
- const outcome = ensurePiExcludedFromTsconfig(targetDir);
1120
- if (outcome.status === "added") {
1121
- result.modified.push(outcome.path);
1122
- result.warnings.push(
1123
- 'Added ".pi" to tsconfig.json "exclude" so the Pi extension stays out of your TypeScript build.'
1124
- );
1125
- } else if (outcome.status === "skipped") {
1126
- result.warnings.push(outcome.reason);
1127
- }
1128
- }
1129
- if (wants("claude")) {
1130
- const hooksDir = join5(targetDir, ".claude", "hooks");
1131
- ensureDir(hooksDir);
1132
- const hookScript = `// Joycraft version check \u2014 runs on Claude Code session start
1133
- import { readFileSync } from 'node:fs';
1134
- import { join } from 'node:path';
1135
- try {
1136
- const data = JSON.parse(readFileSync(join(process.cwd(), '${STATE_PATH.split(/[\\/]/).join("', '")}'), 'utf-8'));
1137
- const res = await fetch('https://registry.npmjs.org/joycraft/latest', { signal: AbortSignal.timeout(3000) });
1138
- if (res.ok) {
1139
- const latest = (await res.json()).version;
1140
- if (data.version !== latest) console.log('Joycraft ' + latest + ' available (you have ' + data.version + '). Run: npx joycraft@latest upgrade');
1141
- }
1142
- } catch {}
1143
- `;
1144
- writeFile(join5(hooksDir, "joycraft-version-check.mjs"), hookScript, opts.force, result);
1145
- const settingsPath = join5(targetDir, ".claude", "settings.json");
1146
- let settings = {};
1147
- let settingsMalformed = false;
1148
- if (existsSync5(settingsPath)) {
1149
- try {
1150
- settings = JSON.parse(readFileSync4(settingsPath, "utf-8"));
1151
- } catch {
1152
- settingsMalformed = true;
1153
- result.warnings.push(
1154
- "settings.json exists but is malformed \u2014 skipping settings merge to protect your config.\n Fix the JSON in .claude/settings.json and re-run init."
1155
- );
1156
- }
1157
- }
1158
- if (!settingsMalformed) {
1159
- if (!settings.hooks) settings.hooks = {};
1160
- const hooksConfig = settings.hooks;
1161
- if (!hooksConfig.SessionStart) hooksConfig.SessionStart = [];
1162
- const sessionStartHooks = hooksConfig.SessionStart;
1163
- const hasJoycraftHook = sessionStartHooks.some((h) => {
1164
- const innerHooks = h.hooks;
1165
- return innerHooks?.some((ih) => typeof ih.command === "string" && ih.command.includes("joycraft"));
1166
- });
1167
- if (!settings.env) settings.env = {};
1168
- const env = settings.env;
1169
- const envMissing = !("CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS" in env);
1170
- if (envMissing) {
1171
- env.CLAUDE_CODE_EXPERIMENTAL_AGENT_TEAMS = "1";
1172
- }
1173
- const autoMemoryMissing = !(AUTO_MEMORY_KEY in settings);
1174
- const writeAutoMemory = disableAutoMemory && autoMemoryMissing;
1175
- if (writeAutoMemory) {
1176
- settings[AUTO_MEMORY_KEY] = false;
1177
- }
1178
- if (!hasJoycraftHook) {
1179
- sessionStartHooks.push({
1180
- matcher: "",
1181
- hooks: [{
1182
- type: "command",
1183
- command: "node .claude/hooks/joycraft-version-check.mjs"
1184
- }]
1185
- });
1186
- }
1187
- if (!hasJoycraftHook || envMissing || writeAutoMemory) {
1188
- writeFileSync3(settingsPath, JSON.stringify(settings, null, 2) + "\n", "utf-8");
1189
- if (!result.created.includes(settingsPath)) result.created.push(settingsPath);
1190
- }
1191
- const permissions = generatePermissions(stack);
1192
- if (existsSync5(settingsPath)) {
1193
- try {
1194
- settings = JSON.parse(readFileSync4(settingsPath, "utf-8"));
1195
- } catch {
1196
- result.warnings.push(
1197
- "settings.json became unreadable after hook merge \u2014 skipping permissions merge.\n Fix the JSON in .claude/settings.json and re-run init."
1198
- );
1199
- settingsMalformed = true;
1200
- }
1201
- }
1202
- if (!settingsMalformed) {
1203
- if (!settings.permissions) settings.permissions = {};
1204
- const perms = settings.permissions;
1205
- if (!perms.allow) perms.allow = [];
1206
- if (!perms.deny) perms.deny = [];
1207
- for (const rule of permissions.allow) {
1208
- if (!perms.allow.includes(rule)) perms.allow.push(rule);
1209
- }
1210
- for (const rule of permissions.deny) {
1211
- if (!perms.deny.includes(rule)) perms.deny.push(rule);
1212
- }
1213
- writeFileSync3(settingsPath, JSON.stringify(settings, null, 2) + "\n", "utf-8");
1214
- }
1215
- }
1216
- const hookResult = installSafeguardHooks(targetDir, [], opts.force, settingsMalformed);
1217
- result.created.push(...hookResult.created);
1218
- result.skipped.push(...hookResult.skipped);
1219
- }
1220
- if (gitignoreProfile === "shared" && wants("claude")) {
1221
- const gitignorePath = join5(targetDir, ".gitignore");
1222
- if (existsSync5(gitignorePath)) {
1223
- const gitignore = readFileSync4(gitignorePath, "utf-8");
1224
- if (/^\.claude\/?$/m.test(gitignore) || /^\.claude\/\*$/m.test(gitignore)) {
1225
- result.warnings.push(
1226
- ".claude/ is in your .gitignore \u2014 teammates won't get Joycraft skills.\n Add this line to .gitignore to fix: !.claude/skills/"
1227
- );
1228
- }
1229
- }
1230
- }
1231
- printSummary(result, stack, existingSkills, isPi, gitignoreProfile, harnesses);
1232
- }
1233
- function printSummary(result, stack, existingSkills = [], isPi = false, gitignoreProfile = DEFAULT_GITIGNORE_PROFILE, harnesses = []) {
1234
- console.log("\nJoycraft initialized!\n");
1235
- if (harnesses.length > 0) {
1236
- console.log(` Installed harnesses: ${harnesses.join(", ")}`);
1237
- }
1238
- if (stack.language !== "unknown") {
1239
- const fw = stack.framework ? ` + ${stack.framework}` : "";
1240
- console.log(` Detected stack: ${stack.language}${fw} (${stack.packageManager})`);
1241
- } else {
1242
- console.log(" Detected stack: unknown (no recognized manifest found)");
1243
- }
1244
- if (isPi) {
1245
- console.log(" Detected agent: Pi");
1246
- }
1247
- if (gitignoreProfile === "private") {
1248
- console.log(` Gitignore profile: private (${PRIVATE_DIRS_DISPLAY} are gitignored \u2014 only CLAUDE.md, AGENTS.md, docs/ are tracked)`);
1249
- } else {
1250
- console.log(" Gitignore profile: shared (skills and docs are tracked for your team)");
1251
- }
1252
- if (result.created.length > 0) {
1253
- console.log(`
1254
- Created ${result.created.length} file(s):`);
1255
- for (const f of result.created) {
1256
- console.log(` + ${f}`);
1257
- }
1258
- }
1259
- if (result.modified.length > 0) {
1260
- console.log(`
1261
- Modified ${result.modified.length} file(s):`);
1262
- for (const f of result.modified) {
1263
- console.log(` ~ ${f}`);
1264
- }
1265
- }
1266
- if (result.skipped.length > 0) {
1267
- console.log(`
1268
- Skipped ${result.skipped.length} file(s) (already exist, use --force to overwrite):`);
1269
- for (const f of result.skipped) {
1270
- console.log(` - ${f}`);
1271
- }
1272
- }
1273
- if (result.warnings.length > 0) {
1274
- console.log("\n Warnings:");
1275
- for (const w of result.warnings) {
1276
- console.log(` \u26A0 ${w}`);
1277
- }
1278
- }
1279
- if (existingSkills.length > 0) {
1280
- console.log(`
1281
- Found existing skills: ${existingSkills.join(", ")}. These are preserved \u2014 Joycraft is additive.`);
1282
- }
1283
- const hasExistingClaude = result.skipped.some((f) => f.endsWith("CLAUDE.md"));
1284
- console.log("\n Next steps:");
1285
- console.log(" 1. Run Claude Code and try /joycraft-setup \u2014 the first-run door that sets up and assesses your project");
1286
- if (hasExistingClaude) {
1287
- console.log(" (it routes to /joycraft-tune to assess and improve your existing CLAUDE.md)");
1288
- } else {
1289
- console.log(" (then review and customize the generated CLAUDE.md for your project)");
1290
- }
1291
- console.log(" 2. Try /joycraft-new-feature to start building with the spec-driven workflow");
1292
- console.log(" (feature artifacts are written to docs/features/<slug>/ as you go)");
1293
- if (gitignoreProfile === "private") {
1294
- console.log(` 3. Commit CLAUDE.md, AGENTS.md, and docs/ \u2014 ${PRIVATE_DIRS_DISPLAY} stay local (gitignored)`);
1295
- console.log(` (if any harness files were already committed, run: ${PRIVATE_UNTRACK_COMMAND})`);
1296
- } else {
1297
- console.log(" 3. Commit .claude/skills/ and docs/ so your team gets the same workflow");
1298
- }
1299
- if (!isPi) {
1300
- console.log(" Pi: Skills installed to .pi/skills/. Use /skill:joycraft-* to invoke.");
1301
- }
1302
- console.log("");
1303
- }
1304
- export {
1305
- init
1306
- };
1307
- //# sourceMappingURL=init-J5Q6RX3K.js.map