rvlib-shipkit 0.26.0 → 0.28.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/CHANGELOG.md CHANGED
@@ -1,5 +1,20 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.28.0
4
+
5
+ - **The `.claude/` policy files are OPT-IN.** 0.27.0 wrote a pre-approved shell allowlist (`curl *`, `git push*`, `./deploy.sh`) and an attribution silencer into every started repo, gitignored and therefore invisible to review. Those are decisions about what an agent can do in a repo and what its git history says, so they now require the caller to declare a house (`claudePolicy`, which `start` enables when it seeds CLAUDE.md include lines), and the grant prints once by name when it lands. The verify skill still lands for everyone.
6
+ - **The scaffolded verify skill points at `shipkit ci`.** It shipped a gate of `bunx tsc && bun test && bun run build`: scripts a started repo does not have, contradicting the coding page written beside it.
7
+ - **The `.gitignore` baseline is appended line by line, by ONE writer.** It was written only when the file was absent, so a dir arriving with any `.gitignore` at all (a downloaded template, one stray line) skipped it: the install then wrote `node_modules/` and the first commit refused over thousands of staged files. A `.env` in a started dir is now ignored rather than blocking the commit outright, so the secret stays out AND the work gets backed up.
8
+ - **A scaffold write error no longer aborts the start.** It is wrapped like every other step, warns, and the chain still commits and pushes.
9
+ - **Smaller repairs**: an unparseable `package.json` warns instead of silently skipping the scripts · files the scaffold SKIPPED are reported, because on a half-built dir the skipped one is the interesting one · delivered templates get their "copy me somewhere" comment blocks stripped, true on the page they twin and nonsense in the repo they land in · the hub port in `tasks.json` derives from the package name, matching what `init` writes into `repo.config.ts`.
10
+
11
+ ## 0.27.0
12
+
13
+ - **`shipkit start` writes the whole day-one shape, not just a repo.** A started dir was a repo you still had to furnish: no tsconfig, no editor tasks, no agent wiki behind CLAUDE.md's own include, no verify skill, no attribution silencer, and two baseline scripts the rules then warned about. One scaffold pass now writes all of it (`src/scaffold/project-scaffold.ts`), installs the toolchain, and the result passes its OWN `shipkit ci` with nothing left but the identity assets a human has to choose. Every file is CREATE-ONLY, so running it over a half-built dir never destroys work.
14
+ - **The scaffolded tsconfig drops the root `*.ts` glob.** That glob picks up `repo.config.ts`, whose `rvlib-shipkit` import is raw TypeScript, so `tsc --noEmit` walked into the dependency and typechecked the entire library (`skipLibCheck` covers `.d.ts` only). A fresh repo's typecheck failed on someone else's code, which no user can fix. List a root config file by name when one earns checking, the way a vite repo lists `vite.config.ts`.
15
+ - **The baseline `.gitignore` is written before anything else can create one.** The scaffold's own ignore lines landed first, so the `node_modules/` baseline was skipped and the first commit refused on 7700 staged dependency files.
16
+ - **`start` says how to land in the dir it made.** A child process cannot cd its parent shell, so the path goes to stdout for a sourced wrapper and, when none is in play, the last line names the `cd`. `SHIPKIT_CD=1` silences it for a wrapper that does the move.
17
+
3
18
  ## 0.26.0
4
19
 
5
20
  - **start means START: the full bootstrap runs on any dir with no commit history.** 0.25.0 widened the scaffold to empty dirs and commitless husks, and the very next field run hit the remaining wall: a folder holding one stray readme was still refused. The gate is now commit history alone: no commits means the dir is startable, and loose files simply ride in the first commit as the repo's first backup. What start still refuses is structural: a repo with real history is never scaffolded or pushed over, a subdirectory of another work tree gets nothing, a temp dir never mints a github repo, and the risky-file refusal still blocks a first commit carrying a `.env` or `node_modules` anywhere in the tree.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "rvlib-shipkit",
3
- "version": "0.26.0",
3
+ "version": "0.28.0",
4
4
  "description": "All-in-one repo companion: ci gate (task DAG), auto-discovered health checks, release-contract fulfillness, asks queue, md-wiki tools, asset atelier, live tui",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -9,7 +9,7 @@ export class StartCommand extends Command {
9
9
 
10
10
  static override usage = Command.Usage({
11
11
  category: 'Setup',
12
- description: 'create (or enter) ~/dev/<name> from ANY cwd, READY to work in: ensures the dir, seeds CLAUDE.md include lines, scaffolds a minimal package.json + src/index.ts + the rvlib-shipkit dev dep on any dir with no commit history (loose files ride in the first commit), wires shipkit (repo.config.ts via init), then runs the whole bootstrap chain: git init, first commit, PRIVATE github repo, push. Only a repo with real history is left as it is. Prints the dir on stdout so a shell alias can cd there. cwd-only sibling: `shipkit init`',
12
+ description: 'create (or enter) ~/dev/<name> from ANY cwd, READY to work in. On any dir with no commit history it writes the day-one shape (package.json + src/index.ts + lint/fmt/typecheck, tsconfig, .vscode tasks + settings, the verify skill, an agent/ wiki, .rv-reflections), installs the toolchain, wires shipkit (repo.config.ts via init), and runs the whole bootstrap chain: git init, first commit, PRIVATE github repo, push. Loose files ride in that first commit, and only a repo with real history is left as it is. Writes are create-only for files, additive for package.json scripts and .gitignore. Seeding CLAUDE.md include lines also opts the repo into the .claude/ policy files (a pre-approved shell allowlist + the attribution silencer). Prints the dir on stdout so a shell alias can cd there. cwd-only sibling: `shipkit init`',
13
13
  examples: [
14
14
  ['create or enter ~/dev/pong: dir, package.json, shipkit wiring, git, first commit, private github repo, push', 'shipkit start pong'],
15
15
  ['seed CLAUDE.md includes', "shipkit start pong --include '@~/wiki/index.md' --include '@./agent/index.md'"],
@@ -14,7 +14,7 @@
14
14
  // identity), it never touches a history that already has commits, and every
15
15
  // unverifiable path (no gh, not authenticated, offline) is a WARN that
16
16
  // leaves the local repo wired and names the next move.
17
- import { existsSync, realpathSync } from 'fs'
17
+ import { existsSync, readFileSync, realpathSync, writeFileSync } from 'fs'
18
18
  import { tmpdir } from 'os'
19
19
  import { basename, join } from 'path'
20
20
  import { spawnWithTimeout } from './core/spawn-timeout.ts'
@@ -261,13 +261,15 @@ async function firstCommit(root: string, git: Run, p: (line: string) => void): P
261
261
  p('skip: first commit — nothing in this dir yet')
262
262
  return false
263
263
  }
264
- // a repo with no .gitignore at all gets the baseline: the very first
265
- // commit is the one nobody reviews, and it is the one that ships a .env
266
- // to github. A repo that HAS one keeps its own answer, whatever it says.
267
- // rule SK004 stays the only writer of its managed block, with the repo's
268
- // real config: rewriting it from a synthetic one here DELETED the lines
269
- // repo.config.ts contributed, seconds before staging what they covered
270
- if (!existsSync(join(root, '.gitignore'))) await Bun.write(join(root, '.gitignore'), `${IGNORE_BASELINE.join('\n')}\n`)
264
+ // the baseline lands before the very first commit, the one nobody
265
+ // reviews and the one that ships a .env to github. Every MISSING line is
266
+ // appended, because a repo that arrived with a one-line .gitignore is
267
+ // exactly as exposed as one with none. Repo-owned lines are never
268
+ // touched, and rule SK004 stays the only writer of its managed block,
269
+ // with the repo's real config: rewriting it from a synthetic one here
270
+ // DELETED the lines repo.config.ts contributed, seconds before staging
271
+ // what they covered
272
+ ensureIgnoreBaseline(root)
271
273
  const status = await git(['status', '--porcelain', '-uall'])
272
274
  if (status.code !== 0) {
273
275
  p(`WARN no first commit: ${firstGhLine(status.out)}`)
@@ -300,6 +302,19 @@ async function firstCommit(root: string, git: Run, p: (line: string) => void): P
300
302
  return true
301
303
  }
302
304
 
305
+ /** append whichever baseline lines this repo's .gitignore does not already
306
+ * carry. ONE writer of this fact, called by the first commit and by the
307
+ * start scaffold (which runs before the dep install, so node_modules can
308
+ * never reach the staging area) */
309
+ export function ensureIgnoreBaseline(root: string): void {
310
+ const path = join(root, '.gitignore')
311
+ const cur = existsSync(path) ? readFileSync(path, 'utf8') : ''
312
+ const have = new Set(cur.split('\n').map((l) => l.trim()))
313
+ const missing = IGNORE_BASELINE.filter((l) => !have.has(l))
314
+ if (missing.length === 0) return
315
+ writeFileSync(path, `${cur}${cur === '' || cur.endsWith('\n') ? '' : '\n'}${missing.join('\n')}\n`)
316
+ }
317
+
303
318
  /** never in a first commit, wherever it sits in the tree. `.env.example` and
304
319
  * friends are documentation and belong in the repo */
305
320
  function isRisky(f: string): boolean {
@@ -0,0 +1,9 @@
1
+ # Changelog
2
+
3
+ Newest first. Each entry narrates WHAT changed and WHY, for the next
4
+ session that arrives with no context.
5
+
6
+ ## {{DATE}}
7
+
8
+ - Repo scaffolded: package.json, tsconfig, vscode tasks, agent/ wiki,
9
+ shipkit wiring, first commit.
@@ -0,0 +1,35 @@
1
+ # Coding standards — {{NAME}}
2
+
3
+ The always-loaded page. Keep it to hard gates plus a screen of standards.
4
+ Once it grows past that, split the gates into `process.md`, make that the
5
+ always-loaded one, and route the rest by surface.
6
+
7
+ ## Gates
8
+
9
+ - **Spec-first**: the `agent/` page changes BEFORE the code it describes.
10
+ - **`shipkit ci` is the verification.** Run it, not the linter, the
11
+ typechecker and the tests one at a time.
12
+ - **Repro before fix**: write the failing test, then fix, then re-run it.
13
+ - One code path per concern. Delete the redundant mechanism rather than
14
+ keeping two.
15
+
16
+ ## TypeScript
17
+
18
+ - `strict`, `noUncheckedIndexedAccess`, `noUnusedLocals`,
19
+ `noUnusedParameters`, `noFallthroughCasesInSwitch`: all on, always.
20
+ - No `as any`, no `@ts-ignore`. A cast that survives review is listed here
21
+ with the reason it is safe.
22
+ - Imports are absolute (`src/...`), never `../..` chains.
23
+
24
+ ## Comments
25
+
26
+ - The default is NO comment. Write one only for what the code cannot say:
27
+ a constraint, an invariant, a performance reason, a workaround.
28
+ - Never narrate the edit, the date, or who asked for it. That is what git
29
+ and the changelog are for.
30
+ - Lowercase, no dash punctuation, matching the density of the file.
31
+
32
+ ## Layout
33
+
34
+ - A file past ~600 lines is a smell; carve it at ~800.
35
+ - Anti-patterns: <fill as the project teaches them>.
@@ -0,0 +1,25 @@
1
+ # {{NAME}}
2
+
3
+ <One paragraph: what this project is, who it is for, and the stack.>
4
+
5
+ ## Quick start
6
+
7
+ - `bun run hub` → the repo toolbox at http://localhost:{{PORT}}
8
+ - `shipkit ci` → THE gate: run it to check your work, never the parts
9
+
10
+ This folder is the project's internal wiki and its SPEC. Update the page
11
+ BEFORE the change it describes.
12
+
13
+ **Always loaded every session:**
14
+
15
+ @coding.md
16
+
17
+ Read the matching page before touching a surface:
18
+
19
+ | read when touching… | page |
20
+ |---|---|
21
+ | any source file | `agent/coding.md` |
22
+ | recent changes and why | `agent/changelog.md` |
23
+
24
+ Grow this table: a subsystem, a service, a runbook each earn their own page,
25
+ cross-linked from here.
@@ -0,0 +1,23 @@
1
+ {
2
+ "permissions": {
3
+ "allow": [
4
+ "Bash(shipkit *)",
5
+ "Bash(bun run *)",
6
+ "Bash(bun test*)",
7
+ "Bash(bun install*)",
8
+ "Bash(bun add *)",
9
+ "Bash(bunx tsc*)",
10
+ "Bash(bunx wrangler*)",
11
+ "Bash(git status*)",
12
+ "Bash(git diff*)",
13
+ "Bash(git log*)",
14
+ "Bash(git add *)",
15
+ "Bash(git commit*)",
16
+ "Bash(git push*)",
17
+ "Bash(curl *)",
18
+ "Bash(oxlint*)",
19
+ "Bash(./deploy.sh)"
20
+ ],
21
+ "deny": []
22
+ }
23
+ }
@@ -0,0 +1,6 @@
1
+ {
2
+ "attribution": {
3
+ "commit": "",
4
+ "pr": ""
5
+ }
6
+ }
@@ -0,0 +1,48 @@
1
+ {
2
+ // ONE tsconfig at the repo root — copy as-is (replaces whatever
3
+ // `bun init` generated), adjust include/paths to the repo's dirs.
4
+ "compilerOptions": {
5
+ // real node resolution, no bundler hand-waving — what tsc resolves is
6
+ // what bun resolves at runtime (bun follows tsconfig paths)
7
+ "module": "nodenext",
8
+ "moduleResolution": "nodenext",
9
+
10
+ // the pair that legalizes `from 'src/foo/Bar.ts'` — extensions are part
11
+ // of the exact-path search key; tsc only typechecks, bun/vite emit
12
+ "allowImportingTsExtensions": true,
13
+ "noEmit": true,
14
+
15
+ // THE mapping that makes 'src/...' specifiers resolve. No baseUrl —
16
+ // explicit paths only, so bare specifiers can't collide with packages.
17
+ // paths doubles as an escape hatch for deps with broken "exports"
18
+ // (map the submodule) — but bun follows these at RUNTIME too, so
19
+ // runtime-loaded packages need "exports" patches instead, or bun
20
+ // resolves a .d.ts where it needs a .js.
21
+ "paths": {
22
+ "src/*": ["./src/*"],
23
+ "scripts/*": ["./scripts/*"]
24
+ },
25
+
26
+ // every file is a module even with no import/export (standalone scripts)
27
+ "moduleDetection": "force",
28
+
29
+ // the house TS standard is all five, always on (meta/rv-conventions):
30
+ // strict alone leaves dead locals and fallthrough bugs in the codebase
31
+ "strict": true,
32
+ "noUncheckedIndexedAccess": true,
33
+ "noUnusedLocals": true,
34
+ "noUnusedParameters": true,
35
+ "noFallthroughCasesInSwitch": true,
36
+ "isolatedModules": true,
37
+ "skipLibCheck": true,
38
+ "incremental": true,
39
+ "tsBuildInfoFile": "node_modules/.cache/tsbuildinfo.json"
40
+ },
41
+ // NO root `*.ts` glob: it picks up a config file like repo.config.ts,
42
+ // and a dependency imported from there whose package points at raw .ts
43
+ // (rvlib-shipkit does) gets walked and typechecked in full, since
44
+ // skipLibCheck covers .d.ts only. The repo then fails on code its owner
45
+ // cannot edit. List a root file BY NAME when it earns checking, the way
46
+ // a vite repo lists vite.config.ts
47
+ "include": ["src", "scripts"]
48
+ }
@@ -0,0 +1,32 @@
1
+ ---
2
+ name: verify
3
+ description: Prove a change in THIS project actually works — drive the real flow end to end, never trust green checks or self-reports. Use before committing any nontrivial change.
4
+ ---
5
+
6
+ # verify — how to PROVE a change works here
7
+
8
+ <!-- Template: copy to .claude/skills/verify/SKILL.md at project start, fill the
9
+ placeholders, then GROW it — every gotcha discovered in this repo gets
10
+ encoded here the same day. -->
11
+
12
+ ## The rules (house-wide)
13
+ - Failing repro test BEFORE the fix. Green checks ≠ verification.
14
+ - Logic → fast headless `bun test` (tiny ~10-line test files reusing fixtures).
15
+ - Look & feel → NEVER screenshot-self-verify; the repo owner playtests it.
16
+ - Verify as the end user would: drive the real flow, observe the real signal.
17
+
18
+ ## This project
19
+ - Full gate: `shipkit ci` — THE command, never the linter, the typechecker
20
+ and the tests one at a time.
21
+ - TODO, fill these in once the stack exists: the dev server command and its
22
+ port (check it is not already running: `curl -s localhost:PORT >/dev/null
23
+ && echo up`), and the live URL after deploy (curl 200 + drive the flow).
24
+
25
+ ## Browser verification (only when a browser is truly needed)
26
+ Playwright with explicit `executablePath`, `deviceScaleFactor: 2`, localStorage
27
+ reset between runs, `page.evaluate` probes for state, collect `pageerror`
28
+ ("none" is evidence). Screenshots are for LOOKS, never for "does it fit".
29
+
30
+ ## Gotchas discovered in this repo
31
+ <!-- append as found — this list is the reason this file exists -->
32
+ - (none yet)
@@ -0,0 +1,40 @@
1
+ // merge into .vscode/settings.json — the convention only sticks if the editor
2
+ // produces it by default. Load-bearing keys for the absolute-import style.
3
+ // NOTE: `js/ts.*` is the unified prefix (recent VSCode); on older builds
4
+ // expand each to its `typescript.*` + `javascript.*` twins
5
+ // (e.g. typescript.preferences.importModuleSpecifier, typescript.tsdk).
6
+ {
7
+ // THE key pair: auto-import inserts 'src/...' absolute specifiers, never
8
+ // './relative'. Modern tsserver respects this reliably.
9
+ // the ONE key that makes auto-import write `src/foo/Bar.ts`, not
10
+ // `../foo/Bar`. It is the only real id in that family (`…Ending` aside);
11
+ // vscode ignores unknown keys in silence, so an invented name looks like
12
+ // it works
13
+ "js/ts.preferences.importModuleSpecifier": "non-relative",
14
+
15
+ // use the workspace typescript (native ts7 compiler), not vscode's bundled one
16
+ "js/ts.tsdk.path": "node_modules/typescript/lib",
17
+
18
+ // auto-imports emit `import type` — saves don't fight the lint's
19
+ // consistent-type-imports rule
20
+ "js/ts.preferences.preferTypeOnlyAutoImports": true,
21
+
22
+ // kill junk suggestions: only tsserver speaks, no word-soup completions
23
+ "editor.suggest.showWords": false,
24
+ "editor.wordBasedSuggestions": "off",
25
+ "js/ts.preferences.includePackageJsonAutoImports": "off",
26
+
27
+ // rename the real symbol, not an import alias; rename both jsx tags
28
+ "js/ts.preferences.useAliasesForRenames": false,
29
+ "js/ts.preferences.renameMatchingJsxTags": true,
30
+
31
+ // big-repo hygiene: more tsserver memory, no npm probing, no auto type acquisition
32
+ "js/ts.tsserver.maxMemory": 6144,
33
+ "js/ts.tsserver.automaticTypeAcquisition.enabled": false,
34
+ "js/ts.tsserver.checkNpmIsInstalled": false,
35
+
36
+ // oxc lints in-editor; eslint off; formatter owns formatting, not tsserver
37
+ "oxc.enable": true,
38
+ "eslint.enable": false,
39
+ "js/ts.format.enabled": false
40
+ }
@@ -0,0 +1,45 @@
1
+ {
2
+ // one master task with runOn folderOpen, every dev process as a subtask.
3
+ // Opening the folder in vscode starts them all. Add a subtask per
4
+ // long-running watcher the stack earns (dev server, css, tests), never
5
+ // for a one-off script.
6
+ "version": "2.0.0",
7
+ "tasks": [
8
+ {
9
+ "label": "starts everything",
10
+ "dependsOn": ["👁 TSC", "🚀 shipkit"],
11
+ "group": { "kind": "build", "isDefault": true },
12
+ "runOptions": { "runOn": "folderOpen", "instanceLimit": 1 },
13
+ "problemMatcher": []
14
+ },
15
+ {
16
+ "label": "👁 TSC",
17
+ "detail": "Get all typescript errors in problems pane",
18
+ "type": "process",
19
+ "command": "${workspaceFolder}/node_modules/.bin/tsc",
20
+ "args": ["--noEmit", "--incremental", "--watch", "--project", "tsconfig.json"],
21
+ "options": {
22
+ "cwd": "${workspaceFolder}",
23
+ "env": { "NODE_OPTIONS": "--max-old-space-size=8192" }
24
+ },
25
+ "isBackground": true,
26
+ "presentation": { "reveal": "never", "clear": true },
27
+ "group": "build",
28
+ "runOptions": { "instanceLimit": 1 },
29
+ "problemMatcher": []
30
+ },
31
+ {
32
+ "label": "🚀 shipkit",
33
+ "detail": "The shipkit hub at http://localhost:{{PORT}} — clickable URLs: the page, /graph/wiki, /graph/agent",
34
+ "type": "process",
35
+ "command": "bun",
36
+ "args": ["run", "hub"],
37
+ "options": { "cwd": "${workspaceFolder}" },
38
+ "isBackground": true,
39
+ "presentation": { "reveal": "always", "close": false },
40
+ "group": "build",
41
+ "runOptions": { "instanceLimit": 1 },
42
+ "problemMatcher": []
43
+ }
44
+ ]
45
+ }
@@ -0,0 +1,202 @@
1
+ // the day-one shape of a repo, written by `shipkit start` for a dir with no
2
+ // commit history. The bar: opening the folder in vscode starts the watchers,
3
+ // an agent lands on a wiki that routes it, and `shipkit ci` is green with no
4
+ // warning a machine could have cleared.
5
+ //
6
+ // Writes are CREATE-ONLY for files (a path that exists is left exactly as it
7
+ // is) and ADDITIVE for package.json scripts and .gitignore (a free key or a
8
+ // missing line is filled, an existing one is never touched), so the scaffold
9
+ // can run over a half-built dir without ever destroying work. Note that the
10
+ // package.json rewrite reformats the file it edits.
11
+ // Templates live beside this file in files/ and ship in the npm tarball, so
12
+ // none of them may name a machine-local tool or a private path.
13
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'fs'
14
+ import { dirname, join } from 'path'
15
+ import { defaultHubPort } from '../serve/run-serve.ts'
16
+
17
+ const FILES = join(import.meta.dir, 'files')
18
+
19
+ export type ScaffoldOpts = {
20
+ /** repo name, substituted into the templates */
21
+ name: string
22
+ /** report sink */
23
+ print?: (line: string) => void
24
+ /** the changelog's first dated entry — injected so callers stay testable */
25
+ today?: string
26
+ /** write the .claude/ POLICY files: a pre-approved permission list and an
27
+ * attribution silencer. Both are decisions about what agents may do in
28
+ * someone's repo and what its git history says, so they are opt-in: only
29
+ * a caller that declares a house (start seeds include lines) turns them
30
+ * on, and the grant is printed the one time it lands */
31
+ claudePolicy?: boolean
32
+ }
33
+
34
+ /** every dep the house toolchain needs for the scripts below to run */
35
+ export const TOOLCHAIN = ['typescript', 'oxlint', 'oxfmt', '@types/bun'] as const
36
+
37
+ /** script bodies for a fresh repo whose only source dir is src/. A stack
38
+ * scaffold (vite, hono) adds dev/build on top; these three are the floor
39
+ * rule SK001 asks every repo for */
40
+ const SCRIPTS: Record<string, string> = {
41
+ lint: 'oxlint src/',
42
+ fmt: 'oxfmt src/',
43
+ typecheck: 'tsc --noEmit',
44
+ }
45
+
46
+ /** repo-owned ignore lines, written OUTSIDE rule SK004's managed block so its
47
+ * fixer never rewrites them */
48
+ const IGNORE_EXTRA = ['backups/', '.claude/settings.local.json']
49
+
50
+ /** a line telling a READER to copy this file somewhere. True in the wiki page
51
+ * the template is a twin of, nonsense in the repo it just landed in */
52
+ const COPY_INSTRUCTION = /copy (?:as-is|to|this)|merge into|^\s*<!-- Template:/i
53
+
54
+ const template = (file: string, vars: Record<string, string>): string => {
55
+ let out = readFileSync(join(FILES, file), 'utf8')
56
+ for (const [k, v] of Object.entries(vars)) out = out.replaceAll(`{{${k}}}`, v)
57
+ return stripCopyInstructions(out)
58
+ }
59
+
60
+ /** drop whole COMMENT BLOCKS that address a copier, never a structural line:
61
+ * a template's own "copy me somewhere" line is true on the wiki page it
62
+ * twins and nonsense in the repo it just landed in. Comments explaining the
63
+ * CONTENT are the point of these files and stay */
64
+ export function stripCopyInstructions(body: string): string {
65
+ const lines = body.split('\n')
66
+ const drop = new Set<number>()
67
+ const blockSpeaksToACopier = (from: number, to: number): boolean => COPY_INSTRUCTION.test(lines.slice(from, to + 1).join('\n'))
68
+ for (let i = 0; i < lines.length; i++) {
69
+ if (drop.has(i)) continue
70
+ const line = lines[i]!
71
+ // an html comment block, possibly spanning lines
72
+ if (/^\s*<!--/.test(line)) {
73
+ let end = i
74
+ while (end < lines.length && !/-->/.test(lines[end]!)) end++
75
+ if (end < lines.length && blockSpeaksToACopier(i, end)) for (let k = i; k <= end; k++) drop.add(k)
76
+ i = end
77
+ continue
78
+ }
79
+ // a run of consecutive // lines is one block
80
+ if (/^\s*\/\//.test(line)) {
81
+ let end = i
82
+ while (end + 1 < lines.length && /^\s*\/\//.test(lines[end + 1]!)) end++
83
+ if (blockSpeaksToACopier(i, end)) for (let k = i; k <= end; k++) drop.add(k)
84
+ i = end
85
+ }
86
+ }
87
+ if (drop.size === 0) return body
88
+ const kept = lines.filter((_, i) => !drop.has(i))
89
+ while (kept.length > 0 && kept[0]!.trim() === '') kept.shift()
90
+ return kept.join('\n')
91
+ }
92
+
93
+ /** write only when the path is free. Returns whether it wrote */
94
+ function put(root: string, rel: string, body: string): boolean {
95
+ const path = join(root, rel)
96
+ if (existsSync(path)) return false
97
+ mkdirSync(dirname(path), { recursive: true })
98
+ writeFileSync(path, body)
99
+ return true
100
+ }
101
+
102
+ export function scaffoldProject(root: string, opts: ScaffoldOpts): string[] {
103
+ const p = opts.print ?? console.log
104
+ // the hub resolves its port from the CONFIG name, which init takes from
105
+ // package.json — a dir whose folder name differs would otherwise get a
106
+ // tasks.json advertising a port nothing listens on
107
+ const configName = packageName(root) ?? opts.name
108
+ const vars = {
109
+ NAME: opts.name,
110
+ PORT: String(defaultHubPort(configName)),
111
+ DATE: opts.today ?? new Date().toISOString().slice(0, 10),
112
+ }
113
+ const written: string[] = []
114
+ const skipped: string[] = []
115
+ const write = (rel: string, body: string): void => { (put(root, rel, body) ? written : skipped).push(rel) }
116
+
117
+ write('src/index.ts', 'export {}\n')
118
+ write('tsconfig.json', template('tsconfig.json', vars))
119
+ write('.vscode/settings.json', template('vscode-settings.json', vars))
120
+ write('.vscode/tasks.json', template('vscode-tasks.json', vars))
121
+ write('.claude/skills/verify/SKILL.md', template('verify-skill.md', vars))
122
+ // a permission grant and a git-history policy are decisions about someone
123
+ // else's repo, so they land only for a caller that declared a house, and
124
+ // the grant is named out loud the one time it is written
125
+ if (opts.claudePolicy === true) {
126
+ write('.claude/settings.json', template('claude-settings.json', vars))
127
+ write('.claude/settings.local.json', template('claude-settings-local.json', vars))
128
+ if (written.includes('.claude/settings.local.json')) p(`ok: .claude/ policy written — agents are pre-approved for ${grantSummary()} in this repo, and the harness writes no attribution trailer`)
129
+ }
130
+ // the project's own docs wiki. A repo whose CLAUDE.md routes at
131
+ // agent/index.md (rule SK003) needs the file to exist, and a repo with no
132
+ // CLAUDE.md at all still gets a place for its docs to live
133
+ write('agent/index.md', template('agent-index.md', vars))
134
+ write('agent/coding.md', template('agent-coding.md', vars))
135
+ write('agent/changelog.md', template('agent-changelog.md', vars))
136
+ // gitignored by policy, so it never ships: it exists so an agent hitting
137
+ // friction with the toolchain finds the place to write it down
138
+ write('.rv-reflections/README.md', REFLECTIONS_README)
139
+
140
+ addScripts(root, written, p)
141
+ addIgnoreLines(root, written)
142
+
143
+ if (written.length > 0) p(`ok: scaffolded ${written.length} file(s): ${written.slice(0, 6).join(', ')}${written.length > 6 ? `, +${written.length - 6} more` : ''}`)
144
+ // the skips are the interesting half on a half-built dir: a pre-existing
145
+ // .claude/settings.json means no attribution silencer, and that one only
146
+ // counts from the first commit on
147
+ if (skipped.length > 0) p(`skip: ${skipped.length} file(s) already present, left untouched: ${skipped.join(', ')}`)
148
+ return written
149
+ }
150
+
151
+ /** what the pre-approved permission list actually allows, in one phrase */
152
+ function grantSummary(): string {
153
+ try {
154
+ const s = JSON.parse(readFileSync(join(FILES, 'claude-settings-local.json'), 'utf8')) as { permissions?: { allow?: string[] } }
155
+ const allow = s.permissions?.allow ?? []
156
+ return `${allow.length} shell patterns incl. ${allow.filter((a) => /curl|push|deploy/.test(a)).join(', ') || 'none network-facing'}`
157
+ } catch {
158
+ return 'a shell allowlist'
159
+ }
160
+ }
161
+
162
+ const REFLECTIONS_README = `# .rv-reflections
163
+
164
+ One file per friction with the shared toolchain: \`YYYYMMDD-<slug>.md\`.
165
+ What broke, which page or lib, what you expected. Gitignored on purpose,
166
+ transient by design: it is harvested, then deleted.
167
+ `
168
+
169
+ /** the three baseline scripts, added only where the key is free */
170
+ function addScripts(root: string, written: string[], p: (line: string) => void): void {
171
+ const path = join(root, 'package.json')
172
+ if (!existsSync(path)) return void p('WARN no package.json here — the lint/fmt/typecheck scripts were not written')
173
+ const raw = readFileSync(path, 'utf8')
174
+ let pkg: { scripts?: Record<string, string> }
175
+ try { pkg = JSON.parse(raw) as { scripts?: Record<string, string> } }
176
+ catch (e) { return void p(`WARN package.json is unparseable (${String(e).slice(0, 80)}) — the lint/fmt/typecheck scripts were not written, repair it then re-run`) }
177
+ pkg.scripts ??= {}
178
+ let added = 0
179
+ for (const [k, v] of Object.entries(SCRIPTS)) if (pkg.scripts[k] == null) { pkg.scripts[k] = v; added++ }
180
+ if (added === 0) return
181
+ const indent = raw.match(/^(\s+)"/m)?.[1] ?? ' '
182
+ writeFileSync(path, JSON.stringify(pkg, null, indent) + '\n')
183
+ written.push(`package.json (${added} script(s))`)
184
+ }
185
+
186
+ function packageName(root: string): string | null {
187
+ try {
188
+ return (JSON.parse(readFileSync(join(root, 'package.json'), 'utf8')) as { name?: string }).name ?? null
189
+ } catch {
190
+ return null
191
+ }
192
+ }
193
+
194
+ function addIgnoreLines(root: string, written: string[]): void {
195
+ const path = join(root, '.gitignore')
196
+ const cur = existsSync(path) ? readFileSync(path, 'utf8') : ''
197
+ const have = new Set(cur.split('\n').map((l) => l.trim()))
198
+ const missing = IGNORE_EXTRA.filter((l) => !have.has(l))
199
+ if (missing.length === 0) return
200
+ writeFileSync(path, `${cur}${cur === '' || cur.endsWith('\n') ? '' : '\n'}${missing.join('\n')}\n`)
201
+ written.push('.gitignore')
202
+ }
package/src/start-repo.ts CHANGED
@@ -7,8 +7,9 @@
7
7
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'fs'
8
8
  import { homedir } from 'os'
9
9
  import { join } from 'path'
10
- import { ensureGitRepo, firstGhLine, IGNORE_BASELINE, isScratch, publishRepo, runner, type Run } from './git-bootstrap.ts'
10
+ import { ensureGitRepo, ensureIgnoreBaseline, firstGhLine, isScratch, publishRepo, runner, type Run } from './git-bootstrap.ts'
11
11
  import { initRepo } from './init-repo.ts'
12
+ import { scaffoldProject, TOOLCHAIN } from './scaffold/project-scaffold.ts'
12
13
 
13
14
  export type StartOpts = {
14
15
  /** parent dir for repos — default ~/dev */
@@ -94,33 +95,44 @@ export async function startRepo(name: string, opts: StartOpts = {}): Promise<num
94
95
  // and the risky-file commit refusal downstream still guards .env and
95
96
  // node_modules
96
97
  const startable = wired && (await runner('git', dir, 120_000)(['rev-parse', '--verify', 'HEAD'])).code !== 0
97
- if (startable && !existsSync(join(dir, 'package.json')) && !existsSync(join(dir, 'repo.config.ts'))) {
98
- const pkg = { name, version: '0.0.0', private: true, type: 'module', scripts: {} }
99
- writeFileSync(join(dir, 'package.json'), JSON.stringify(pkg, null, 4) + '\n')
100
- // the first source file, so the ci gate is green from commit one:
101
- // an imports gate over zero files fails loud on purpose
102
- mkdirSync(join(dir, 'src'), { recursive: true })
103
- writeFileSync(join(dir, 'src', 'index.ts'), 'export {}\n')
104
- console.error('ok: package.json + src/index.ts scaffolded (private, type module)')
105
- // the install below creates node_modules/ BEFORE the first
106
- // commit, so the baseline ignore must exist first (SK004's block,
107
- // written by init, does not carry node_modules)
108
- if (!existsSync(join(dir, '.gitignore'))) writeFileSync(join(dir, '.gitignore'), `${IGNORE_BASELINE.join('\n')}\n`)
109
- // the scripts init wires call node_modules/rvlib-shipkit — a
110
- // scaffold whose scripts exit 127 is not a started repo. Skips
111
- // mirror the github half's guards: an injected runner wins, the
112
- // env switch turns it off machine-wide, a temp dir is a rehearsal
113
- // that must not pull the network. init owns the fix line for
114
- // every not-installed outcome
98
+ if (startable && !existsSync(join(dir, 'repo.config.ts'))) {
99
+ if (!existsSync(join(dir, 'package.json'))) {
100
+ const pkg = { name, version: '0.0.0', private: true, type: 'module', scripts: {} }
101
+ writeFileSync(join(dir, 'package.json'), JSON.stringify(pkg, null, 4) + '\n')
102
+ console.error('ok: package.json created (private, type module)')
103
+ }
104
+ // the baseline ignore goes FIRST, before anything else creates a
105
+ // .gitignore, and every MISSING line is appended rather than the
106
+ // file being written only when absent: the install below writes
107
+ // node_modules/, neither SK004's block nor the scaffold's own
108
+ // lines carry it, and a dir that arrived with any .gitignore at
109
+ // all (a downloaded template, one stray line) otherwise skipped
110
+ // the baseline and refused the first commit over 7000 dep files
111
+ ensureIgnoreBaseline(dir)
112
+ // the day-one shape: tsconfig, vscode tasks, the agent wiki, the
113
+ // verify skill. Create-only, so a dir that already holds any of
114
+ // them keeps its own. The .claude/ policy files ride on the
115
+ // include lines: a caller that declares a house gets the house
116
+ // defaults, a bare `shipkit start` never has its agent
117
+ // permissions widened by a scaffold
118
+ try { scaffoldProject(dir, { name, print, claudePolicy: (opts.include ?? []).length > 0 }) }
119
+ catch (e) { console.error(`WARN scaffold incomplete in ${dir}: ${e instanceof Error ? e.message : String(e)} — the dir is still yours`) }
120
+ // the wired scripts call node_modules binaries, so a scaffold
121
+ // whose scripts exit 127 is not a started repo. Skips mirror the
122
+ // github half's guards: an injected runner wins, the env switch
123
+ // turns it off machine-wide, a temp dir is a rehearsal that must
124
+ // not pull the network. init owns the fix line for every
125
+ // not-installed outcome
115
126
  let bun: Run | null
116
127
  if (opts.bun !== undefined) bun = opts.bun
117
- else if ((process.env.SHIPKIT_NO_INSTALL ?? '') !== '') { console.error('skip: rvlib-shipkit install — SHIPKIT_NO_INSTALL is set'); bun = null }
118
- else if (isScratch(dir)) { console.error(`skip: rvlib-shipkit install — ${dir} is a temp dir`); bun = null }
119
- else bun = Bun.which('bun') == null ? null : runner('bun', dir, 180_000)
128
+ else if ((process.env.SHIPKIT_NO_INSTALL ?? '') !== '') { console.error('skip: dependency install — SHIPKIT_NO_INSTALL is set'); bun = null }
129
+ else if (isScratch(dir)) { console.error(`skip: dependency install — ${dir} is a temp dir`); bun = null }
130
+ else bun = Bun.which('bun') == null ? null : runner('bun', dir, 300_000)
120
131
  if (bun != null) {
121
- const r = await bun(['add', '-d', 'rvlib-shipkit'])
122
- if (r.code === 0) console.error('ok: rvlib-shipkit installed (dev dep)')
123
- else console.error(`WARN rvlib-shipkit install failed: ${firstGhLine(r.out)}`)
132
+ const deps = ['rvlib-shipkit', ...TOOLCHAIN]
133
+ const r = await bun(['add', '-d', ...deps])
134
+ if (r.code === 0) console.error(`ok: installed ${deps.join(', ')}`)
135
+ else console.error(`WARN dependency install failed: ${firstGhLine(r.out)}`)
124
136
  }
125
137
  }
126
138
  let unscaffolded = false
@@ -137,6 +149,11 @@ export async function startRepo(name: string, opts: StartOpts = {}): Promise<num
137
149
  // last line, so what to do next is the last thing read
138
150
  if (unscaffolded) console.error(`next: scaffold the app in ${dir} (package.json), then \`shipkit init\` inside it — the commit gates arm on the first ci run`)
139
151
  }
152
+ // a child process cannot cd its parent shell, so the dir goes to stdout
153
+ // and a sourced wrapper does the move. Without one, say the move out
154
+ // loud: a verb that lands you nowhere reads as a verb that did nothing.
155
+ // A wrapper sets SHIPKIT_CD to silence this
156
+ if ((process.env.SHIPKIT_CD ?? '') === '') console.error(`next: cd ${dir} (a sourced shell function running \`cd "$(shipkit start <name>)"\` does this for you)`)
140
157
  console.log(dir)
141
158
  return 0
142
159
  }