@wildshard/sdk 0.3.1 → 0.3.3

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 (79) hide show
  1. package/GUIDE.md +19 -6
  2. package/bin/wildshard.mjs +4 -0
  3. package/docs/api/EXPORT-TIERS.md +3 -2
  4. package/lint/export-tiers.json +1 -0
  5. package/lint/sdk-plugin.d.mts +2 -0
  6. package/lint/sdk-plugin.mjs +39 -1
  7. package/package.json +10 -9
  8. package/scripts/capture-hero.mjs +48 -18
  9. package/scripts/ci21-sdk-tail-lint.mjs +95 -0
  10. package/scripts/keep-copy.mjs +172 -0
  11. package/scripts/land.mjs +34 -4
  12. package/scripts/lane-live.mjs +136 -0
  13. package/scripts/leftovers-report.mjs +47 -0
  14. package/scripts/lint-dispatch.mjs +5 -0
  15. package/scripts/music/export-midi.mjs +3 -2
  16. package/scripts/prepare-product.mjs +3 -2
  17. package/scripts/scratch-dir.d.mts +3 -0
  18. package/scripts/scratch-dir.mjs +33 -14
  19. package/scripts/scratch-sweep.mjs +15 -23
  20. package/scripts/typecheck.mjs +15 -0
  21. package/scripts/worktree-reap.mjs +46 -104
  22. package/scripts/worktree.mjs +35 -13
  23. package/skills/wildshard/SKILL.md +3 -1
  24. package/src/cli/content-command.ts +44 -0
  25. package/src/cli/content.ts +287 -0
  26. package/src/cli/help.ts +7 -2
  27. package/src/cli/hero/hero.ts +51 -3
  28. package/src/cli/hero/scene-card.ts +46 -0
  29. package/src/cli/hero/stamp.ts +5 -3
  30. package/src/sharddev/authorManifest.ts +20 -2
  31. package/src/sharddev/cli.ts +1 -1
  32. package/src/sharddev/dev.ts +23 -4
  33. package/src/sharddev/newProject.ts +27 -8
  34. package/src/sharddev/project.ts +2 -2
  35. package/src/sharddev/refusals.ts +1 -0
  36. package/src/sharddev/scene/author.ts +22 -1
  37. package/src/sharddev/scene/budget.ts +87 -0
  38. package/src/sharddev/scene/creature.ts +171 -0
  39. package/src/sharddev/scene/description.ts +41 -0
  40. package/src/sharddev/scene/lower.ts +127 -3
  41. package/src/sharddev/scene/shardfile.ts +222 -20
  42. package/src/sharddev/shardSource.ts +2 -2
  43. package/src/sharddev/test/diskScriptScenario.ts +4 -2
  44. package/src/sharddev/test/ownedScratch.ts +14 -0
  45. package/src/sharddev/test/scriptScenario.ts +18 -13
  46. package/src/sharddev/tsconfig.json +3 -0
  47. package/src/sharddev/watch/pageEntry.ts +1 -19
  48. package/src/sharddev/watch/parity-baseline.json +8 -8
  49. package/src/sharddev/watch/parity.mjs +24 -0
  50. package/src/sharddev/watch/watch.ts +10 -2
  51. package/src/shards/_template/behaviour/boss.as +13 -4
  52. package/src/shards/_template/behaviour/door.as +8 -3
  53. package/src/shards/_template/behaviour/hooks.json +35 -0
  54. package/src/shards/_template/card/landscape.jpg +0 -0
  55. package/src/shards/_template/card/portrait.jpg +0 -0
  56. package/src/shards/_template/card/thumb.jpg +0 -0
  57. package/src/shards/_template/data/bossDecision.json +11 -1
  58. package/src/shards/_template/data/card.json +49 -1
  59. package/src/shards/_template/data/clientScripts.json +411 -0
  60. package/src/shards/_template/data/creatures.json +280 -2
  61. package/src/shards/_template/data/items.json +1 -1
  62. package/src/shards/_template/data/layout.json +32 -1
  63. package/src/shards/_template/data/ledger.json +45 -0
  64. package/src/shards/_template/data/npcs/hermit.json +72 -0
  65. package/src/shards/_template/data/quests.json +297 -11
  66. package/src/shards/_template/data/rows.json +154 -0
  67. package/src/shards/_template/data/skins.json +14 -0
  68. package/src/shards/_template/data/targets.json +47 -0
  69. package/src/shards/_template/data/text.json +4 -1
  70. package/src/shards/_template/generators/lift.ts +71 -0
  71. package/src/shards/_template/generators/product.ts +19 -5
  72. package/src/shards/_template/generators/templatePropsSource.ts +5 -4
  73. package/src/shards/_template/generators/terrain.ts +10 -2
  74. package/src/shards/_template/generators/world.ts +42 -7
  75. package/src/shards/_template/hero.json +6 -6
  76. package/src/shards/_template/manifest.json +49 -1
  77. package/src/shards/authoring-slice/generators/shard.ts +2 -1
  78. package/src/shards/authoring-slice/generators/world.ts +8 -1
  79. package/tsconfig.author.json +24 -0
@@ -1,8 +1,8 @@
1
1
  #!/usr/bin/env node
2
- // repo-kit's 3-day scratch sweep (meta REPO-DISK-PLAN DK6, was TEMP-HYGIENE T7). One copy lives in repo-kit; every org
2
+ // repo-kit's report-only scratch sweep (meta REPO-DISK-PLAN J358, was TEMP-HYGIENE T7). One copy lives in repo-kit; every org
3
3
  // repo carries a byte-identical copy at scripts/scratch-sweep.mjs, beside scratch-dir.mjs (DK3) and vite-tmp.mjs.
4
4
  //
5
- // node scripts/scratch-sweep.mjs [--live] [--root <repo>] [--days <n>]
5
+ // node scripts/scratch-sweep.mjs [--root <repo>] [--days <n>]
6
6
  //
7
7
  // It looks at each folder directly under <repo>/tmp/ and would remove one in which nothing (the folder or anything in
8
8
  // it) changed for <n> days (3 by default), with or without a DK3 `.owner`. It keeps:
@@ -11,12 +11,13 @@
11
11
  // - a folder that is, or holds, some process's cwd (lsof -d cwd; /proc on Linux); an unreadable table keeps all;
12
12
  // - a folder holding a Git root with dirty files or commits no remote has (DS14's list: the reason names the root);
13
13
  // - dot folders, symlinks, and `tmp/vitest` (vite-tmp.mjs's own).
14
- // Dry run is the default until Jake's yes (REPO-DISK decision 1) and a week of dry-run log; `--live` removes. Every
15
- // decision is appended to tmp/.sweep.log, one line each, and a summary line goes to stdout.
14
+ // J358 cancelled the 11-20 go-live: this script never removes files. Every decision is appended to
15
+ // tmp/.sweep.log, one line each, and a summary line goes to stdout for a human daily audit.
16
16
  import { spawnSync } from 'node:child_process';
17
- import { appendFileSync, lstatSync, readdirSync, readFileSync, readlinkSync, realpathSync, rmSync } from 'node:fs';
17
+ import { appendFileSync, lstatSync, readdirSync, readFileSync, readlinkSync, realpathSync } from 'node:fs';
18
18
  import { join, resolve, sep } from 'node:path';
19
19
  import { pathToFileURL } from 'node:url';
20
+ import { laneLive } from './lane-live.mjs';
20
21
 
21
22
  const DEFAULT_DAYS = 3;
22
23
  const MINUTES_A_DAY = 1440;
@@ -138,23 +139,14 @@ export function plan({ root, days = DEFAULT_DAYS, cwds = processCwds() }) {
138
139
  return rows;
139
140
  }
140
141
 
141
- /** Plans, logs every row to tmp/.sweep.log, and removes the planned folders when live.
142
- * @param {{ root: string, live?: boolean, days?: number, cwds?: readonly string[] | null, now?: Date }} options */
143
- export function sweep({ root, live = false, days = DEFAULT_DAYS, cwds, now = new Date() }) {
142
+ /** Plans and logs every row to tmp/.sweep.log. J358: humans, not this script, remove leftovers.
143
+ * @param {{ root: string, days?: number, cwds?: readonly string[] | null, now?: Date }} options */
144
+ export function sweep({ root, days = DEFAULT_DAYS, cwds, now = new Date() }) {
144
145
  const rows = plan({ root, days, ...(cwds === undefined ? {} : { cwds }) });
145
146
  const stamp = now.toISOString(), lines = [];
146
- let removed = 0;
147
147
  for (const row of rows) {
148
- let verb = row.action === 'keep' ? `keep (${row.reason})` : 'would remove';
149
- if (row.action === 'remove' && live) {
150
- try {
151
- rmSync(join(root, 'tmp', row.name), { recursive: true, force: true });
152
- verb = 'removed';
153
- removed += 1;
154
- } catch (error) {
155
- verb = `remove failed (${error instanceof Error ? error.message : String(error)})`;
156
- }
157
- }
148
+ const liveness = laneLive(join(root, 'tmp', row.name));
149
+ const verb = row.action === 'keep' ? `keep (${row.reason}; ${liveness.state}: ${liveness.reason})` : `leftover (manual audit; ${liveness.state}: ${liveness.reason})`;
158
150
  lines.push(`${stamp} ${verb} tmp/${row.name}${row.action === 'remove' ? ` (${row.reason})` : ''}\n`);
159
151
  }
160
152
  if (lines.length > 0) {
@@ -163,7 +155,7 @@ export function sweep({ root, live = false, days = DEFAULT_DAYS, cwds, now = new
163
155
  } catch {}
164
156
  }
165
157
  const planned = rows.filter(row => row.action === 'remove').length;
166
- return { rows, planned, removed };
158
+ return { rows, planned };
167
159
  }
168
160
 
169
161
  if (process.argv[1] !== undefined && import.meta.url === pathToFileURL(process.argv[1]).href) {
@@ -175,8 +167,8 @@ if (process.argv[1] !== undefined && import.meta.url === pathToFileURL(process.a
175
167
  const days = Number(flag('--days') ?? DEFAULT_DAYS);
176
168
  if (!Number.isInteger(days) || days < 1) throw new Error('--days takes a whole number of days, 1 or more');
177
169
  const root = resolve(flag('--root') ?? resolve(import.meta.dirname, '..'));
178
- const live = args.includes('--live');
179
- const { rows, planned, removed } = sweep({ root, live, days });
170
+ if (args.includes('--live')) throw new Error('--live was removed by REPO-DISK J358: this command only reports leftovers');
171
+ const { rows, planned } = sweep({ root, days });
180
172
  const keptRows = rows.filter(row => row.action === 'keep');
181
- process.stdout.write(`scratch-sweep ${live ? 'live' : '(dry run)'} ${root}/tmp: ${live ? `removed ${String(removed)} of ${String(planned)}` : `would remove ${String(planned)}`}, kept ${String(keptRows.length)}; log tmp/.sweep.log\n`);
173
+ process.stdout.write(`scratch-sweep report ${root}/tmp: ${String(planned)} leftover(s) for manual audit, kept ${String(keptRows.length)}; log tmp/.sweep.log\n`);
182
174
  }
@@ -0,0 +1,15 @@
1
+ #!/usr/bin/env node
2
+ // Run every existing TypeScript project without serial pnpm startup.
3
+ // All projects must finish successfully; stdout/stderr stay attached.
4
+ import { spawn } from 'node:child_process';
5
+ import { resolve } from 'node:path';
6
+
7
+ const root = resolve(import.meta.dirname, '..');
8
+ const compiler = resolve(root, 'node_modules/.bin/tsc');
9
+ const projects = ['src/tsconfig.json', 'src/web/tsconfig.json', 'tsconfig.author.json'];
10
+ const results = await Promise.all(projects.map(project => new Promise(done => {
11
+ const child = spawn(compiler, ['-p', project], { cwd: root, stdio: 'inherit' });
12
+ child.on('error', error => { process.stderr.write([project, ': ', error.message, '\n'].join('')); done(1); });
13
+ child.on('close', code => done(code ?? 1));
14
+ })));
15
+ process.exitCode = results.some(code => code !== 0) ? 1 : 0;
@@ -1,35 +1,22 @@
1
- // DEV-SPEED DS13: `node scripts/worktree.mjs reap [--dry-run] [--grace=HOURS] [--no-remote]` removes the plan
2
- // worktrees whose work is on main, and nothing else. Safe to run any time, from any checkout of the repo.
3
- //
4
- // A worktree at <canonical>/.worktrees/<slug> on plan/<slug> is reaped only when all of these hold:
5
- // - landed: the branch tip is on origin/main itself (`merge-base --is-ancestor`; land fast-forwards), after a fetch;
6
- // - clean: `git status --porcelain` is empty (tracked edits and untracked files; ignored build output doesn't count);
7
- // - idle: no process has its working directory inside it (orphans reparented to pid 1 are stopped first, FL30), no `land` holds its lock, no `worktree new` is running,
8
- // and nothing in it (index, HEAD, reflog, tip commit) changed for --grace hours (default 24: a lane between
9
- // landings keeps its worktree). The reaper then holds the worktree's land lock and checks HEAD, the tree, the
10
- // processes and setup again before it removes anything; a worktree whose folder resolves outside
11
- // <canonical>/.worktrees/ is skipped.
12
- // Then: `git worktree remove` (never --force), the local branch deleted only while it still points at the checked
13
- // commit, and `origin plan/<slug>` deleted (`git push --delete`, which the pre-push lets through without a gate)
14
- // only if the remote branch is landed too, under a lease on the SHA it had. A worktree that fails any check is kept
15
- // and named with the reason; an unlanded branch, local or remote, is never touched. Every run appends one receipt.
1
+ // REPO-DISK J358: report plan-worktree liveness for a human audit.
2
+ // This command never removes worktrees or branches and never stops processes.
16
3
  import {execFileSync,spawnSync} from 'node:child_process';
17
- import {appendFileSync,existsSync,mkdirSync,readdirSync,readlinkSync,realpathSync,statSync} from 'node:fs';
18
- import {homedir} from 'node:os';
19
- import {basename,dirname,join,resolve,sep} from 'node:path';
20
- import {pidLock} from './pid-lock.mjs';
4
+ import {existsSync,readdirSync,readlinkSync,statSync,statfsSync} from 'node:fs';
5
+ import {basename,join,resolve,sep} from 'node:path';
6
+ import {laneLive} from './lane-live.mjs';
21
7
  import {WORKTREES} from './worktree-ignore.mjs';
22
8
 
23
- const REAP_USAGE='usage: node scripts/worktree.mjs reap [--dry-run] [--grace=HOURS] [--no-remote]';
9
+ const REAP_USAGE='usage: node scripts/worktree.mjs reap [--dry-run] [--grace=HOURS] [--stale=HOURS] [--no-remote]';
24
10
 
25
- /** @param {string[]} argv the arguments after `reap` @returns {{dryRun:boolean,graceHours:number,remote:boolean}} */
11
+ /** @param {string[]} argv the arguments after `reap` @returns {{dryRun:boolean,graceHours:number,staleHours:number,remote:boolean}} */
26
12
  export function parseReapArgs(argv){
27
- const options={dryRun:false,graceHours:24,remote:true};
13
+ const options={dryRun:false,graceHours:24,staleHours:72,remote:true};
28
14
  for(const arg of argv){
29
15
  const [name,value]=arg.split('=',2);
30
16
  if(arg==='--dry-run')options.dryRun=true;
31
17
  else if(arg==='--no-remote')options.remote=false;
32
18
  else if(name==='--grace'&&value!==undefined&&/^\d+(?:\.\d+)?$/u.test(value))options.graceHours=Number(value);
19
+ else if(name==='--stale'&&value!==undefined&&/^\d+(?:\.\d+)?$/u.test(value))options.staleHours=Number(value);
33
20
  else throw new Error(`unknown option ${arg}\n${REAP_USAGE}`);
34
21
  }
35
22
  return options;
@@ -54,7 +41,7 @@ export function processDirectories(){
54
41
  }
55
42
  // From /, so lsof itself never shows up in the folder being checked.
56
43
  const listed=spawnSync('lsof',['-a','-d','cwd','-F','pn'],{cwd:'/',encoding:'utf8',maxBuffer:64<<20});
57
- if(listed.error!==undefined||listed.stdout==='')return undefined;
44
+ if(listed.error!==undefined||listed.status!==0||listed.stdout==='')return undefined;
58
45
  let pid=0;
59
46
  for(const line of listed.stdout.split('\n')){
60
47
  if(line.startsWith('p'))pid=Number(line.slice(1));
@@ -63,13 +50,14 @@ export function processDirectories(){
63
50
  return found;
64
51
  }
65
52
 
66
- /** pid -> parent pid and command line, from `ps`. @returns {Map<number,{ppid:number,command:string}>} */
53
+ /** pid -> parent pid and command line, from `ps`. @returns {Map<number,{ppid:number,state:string,command:string}>} */
67
54
  function processTable(){
68
- /** @type {Map<number,{ppid:number,command:string}>} */const table=new Map();
69
- const listed=spawnSync('ps',['-Ao','pid=,ppid=,command='],{encoding:'utf8',maxBuffer:64<<20});
55
+ /** @type {Map<number,{ppid:number,state:string,command:string}>} */const table=new Map();
56
+ const listed=spawnSync('ps',['-Ao','pid=,ppid=,stat=,command='],{encoding:'utf8',maxBuffer:64<<20});
57
+ if(listed.error!==undefined||listed.status!==0)throw new Error('process table unreadable');
70
58
  for(const line of (listed.stdout??'').split('\n')){
71
- const match=/^\s*(\d+)\s+(\d+)\s(.*)$/u.exec(line);
72
- if(match!==null)table.set(Number(match[1]),{ppid:Number(match[2]),command:match[3]??''});
59
+ const match=/^\s*(\d+)\s+(\d+)\s+(\S+)\s(.*)$/u.exec(line);
60
+ if(match!==null)table.set(Number(match[1]),{ppid:Number(match[2]),state:match[3]??'',command:match[4]??''});
73
61
  }
74
62
  return table;
75
63
  }
@@ -84,10 +72,10 @@ function processTable(){
84
72
  * @returns {number[]} */
85
73
  export function stopWorktreeProcesses(tree,options={}){
86
74
  const directories=processDirectories();
87
- if(directories===undefined)return [];
75
+ if(directories===undefined)throw new Error('process directories unreadable');
88
76
  const table=processTable(),spared=new Set();
89
- // Without the table nothing tells land's own parents apart (J206 review): stop nothing.
90
- if(!table.has(process.pid))return [];
77
+ // Without the table nothing tells land's own parents apart: retain the tree.
78
+ if(!table.has(process.pid))throw new Error('process ancestry unreadable');
91
79
  for(let pid=process.pid;pid>1&&!spared.has(pid);pid=table.get(pid)?.ppid??0)spared.add(pid);
92
80
  const shell=(/** @type {string} */ command)=>/^-?(?:\S*\/)?(?:ba|z|da|fi|k|tc|c)?sh$/u.test(command.trim());
93
81
  // Only processes whose own working directory is inside: a daemon's children elsewhere are not this worktree's.
@@ -99,6 +87,17 @@ export function stopWorktreeProcesses(tree,options={}){
99
87
  const until=Date.now()+3000,nap=new Int32Array(new SharedArrayBuffer(4));
100
88
  while(Date.now()<until&&pids.some(pid=>signal(pid,0)))Atomics.wait(nap,0,0,50);
101
89
  for(const pid of pids)signal(pid,'SIGKILL');
90
+ const killedUntil=Date.now()+1000;
91
+ let remaining=pids;
92
+ do{
93
+ const current=processTable();
94
+ // Exited children may remain zombies until their blocked parent reaps them.
95
+ // They cannot write; a live or uninspectable process still retains the tree.
96
+ remaining=pids.filter(pid=>current.get(pid)?.state.startsWith('Z')===false);
97
+ if(remaining.length===0)break;
98
+ Atomics.wait(nap,0,0,25);
99
+ }while(Date.now()<killedUntil);
100
+ if(remaining.length>0)throw new Error('a worktree process is still alive');
102
101
  return pids;
103
102
  }
104
103
 
@@ -109,10 +108,14 @@ export function lastActivity(tree,gitDir){
109
108
  return newest;
110
109
  }
111
110
 
111
+ /** Free bytes on the volume holding `path` (what `df` shows as available). @param {string} path */
112
+ export function freeBytes(path){
113
+ const volume=statfsSync(path);
114
+ return volume.bavail*volume.bsize;
115
+ }
116
+
112
117
  /** Is `sha` on origin/main itself? @param {string} canonical @param {string} sha */
113
118
  export const onMain=(canonical,sha)=>sha!==''&&tryGit(canonical,['merge-base','--is-ancestor',sha,'origin/main']).status===0;
114
- /** Commits of `sha` that origin/main lacks. @param {string} canonical @param {string} sha */
115
- const aheadOfMain=(canonical,sha)=>Number(tryGit(canonical,['rev-list','--count',`origin/main..${sha}`]).stdout.trim()||'0');
116
119
 
117
120
  /** @typedef {{path:string,head:string,branch:string}} Worktree */
118
121
 
@@ -136,79 +139,18 @@ export function linkedWorktrees(canonical){
136
139
  * @param {NodeJS.ProcessEnv} env @param {(line:string)=>void} say
137
140
  */
138
141
  export function reap(canonical,options,env,say){
139
- const common=join(canonical,'.git');
140
- if(existsSync(join(common,'wildshard-worktree-setup.lock'))){say('reap STOP a worktree setup is running; retry when it finishes');return 1;}
141
- const fetched=tryGit(canonical,['fetch','--quiet','origin','+refs/heads/main:refs/remotes/origin/main']);
142
- if(fetched.status!==0){say(`reap STOP cannot fetch origin main: ${fetched.stderr.trim()}`);return 1;}
142
+ // J358: this command is an inventory for a human audit. Land alone removes
143
+ // its own just-landed worktree, after a successful keep-copy.
143
144
  const directories=processDirectories();
144
- const realRoot=realpathSync(canonical),now=Date.now();
145
- /** @type {string[]} */const reaped=[];
146
- /** @type {string[]} */const kept=[];
147
- /** @type {string[]} */const remotes=[];
145
+ const cwds=directories===undefined?null:[...directories.values()];
148
146
  for(const tree of linkedWorktrees(canonical)){
149
- const slug=basename(tree.path),branch=`refs/heads/plan/${slug}`;
150
- const keep=(/** @type {string} */ why)=>{kept.push(`${slug} (${why})`);say(`kept ${slug}: ${why}`);};
151
- if(resolve(tree.path)!==join(canonical,WORKTREES,slug)&&resolve(tree.path)!==join(realRoot,WORKTREES,slug)){say(`skipped ${tree.path}: not a plan worktree of this checkout`);continue;}
152
- // Physically too: a linked .worktrees/ or worktree folder may point anywhere.
153
- let physical='';
154
- try{physical=realpathSync(tree.path);}catch{/* Gone: kept below. */}
155
- if(physical!==''&&(physical!==join(realRoot,WORKTREES,slug)||realpathSync(join(canonical,WORKTREES))!==join(realRoot,WORKTREES))){say(`skipped ${tree.path}: resolves to ${physical}, outside ${join(realRoot,WORKTREES)}`);continue;}
156
- if(tree.branch!==branch){keep(`on ${tree.branch===''?'a detached HEAD':tree.branch}, not plan/${slug}`);continue;}
157
- if(!existsSync(tree.path)){keep('its folder is gone; `git worktree prune` clears it');continue;}
158
- // Landed means the tip is on main itself (land fast-forwards): \`git cherry\` would miss a merge's own changes.
159
- if(!onMain(canonical,tree.head)){keep(`${String(aheadOfMain(canonical,tree.head))} commit(s) not on main`);continue;}
160
- const dirty=git(tree.path,['--no-optional-locks','status','--porcelain','--untracked-files=all']).split('\n').filter(Boolean);
161
- if(dirty.length>0){keep(`${String(dirty.length)} uncommitted path(s), first ${dirty[0]?.slice(3)}`);continue;}
162
- const gitDir=git(tree.path,['rev-parse','--absolute-git-dir']).trim();
163
- const busy=(/** @type {Map<number,string>|undefined} */ seen)=>seen===undefined?'cannot list process working directories'
164
- :[...seen].filter(([,path])=>path===physical||path.startsWith(`${physical}${sep}`)).map(([pid])=>String(pid)).join(', ');
165
- // FL30: orphans (reparented to pid 1) in a landed, clean worktree are nobody's; they don't make it busy, and they
166
- // are stopped only once it passed the grace, under its land lock (J206 review).
167
- const orphans=new Set(stopWorktreeProcesses(physical,{orphansOnly:true,dryRun:true}));
168
- const using=busy(directories===undefined?undefined:new Map([...directories].filter(([pid])=>!orphans.has(pid))));
169
- if(using!==''){keep(directories===undefined?using:`in use by pid ${using}`);continue;}
170
- const idleHours=Math.max(0,(now-lastActivity(tree.path,gitDir))/3_600_000);
171
- if(options.graceHours>0&&idleHours<options.graceHours){keep(`active ${idleHours.toFixed(1)} h ago, under the ${String(options.graceHours)} h grace`);continue;}
172
- // Hold the worktree's land lock (land can't start under it; a running land holds it already), then check again
173
- // what could have changed since: HEAD, a commit, an edit, a new process inside, a worktree setup.
174
- /** @type {(() => void)|undefined} */let release;
175
- try{release=pidLock(join(gitDir,'wildshard-land.lock'));}catch(error){keep(error instanceof Error?error.message:String(error));continue;}
176
- if(release===undefined){keep('land is running there');continue;}
177
- try{
178
- if(orphans.size>0){
179
- const stopped=stopWorktreeProcesses(physical,{orphansOnly:true,dryRun:options.dryRun});
180
- if(stopped.length>0)say(`${options.dryRun?'would stop':'stopped '} ${slug}: orphaned pid ${stopped.join(', ')}`);
181
- }
182
- const head=tryGit(tree.path,['rev-parse','HEAD']).stdout.trim();
183
- const now2=git(tree.path,['--no-optional-locks','status','--porcelain','--untracked-files=all']).trim();
184
- const seen2=processDirectories();
185
- const using2=busy(seen2===undefined||!options.dryRun?seen2:new Map([...seen2].filter(([pid])=>!orphans.has(pid))));
186
- const why=head!==tree.head?`HEAD moved to ${head.slice(0,10)} during the check`:now2!==''?'edited during the check':using2!==''?`in use during the check (${using2})`
187
- :existsSync(join(common,'wildshard-worktree-setup.lock'))?'a worktree setup started during the check':!onMain(canonical,head)?'not on main during the check':'';
188
- if(why!==''){keep(why);continue;}
189
- if(options.dryRun){say(`would reap ${slug}: landed, clean, idle ${idleHours.toFixed(1)} h`);reaped.push(slug);continue;}
190
- const removed=tryGit(canonical,['worktree','remove',tree.path]);
191
- if(removed.status!==0){keep(`git worktree remove refused: ${removed.stderr.trim()}`);continue;}
192
- }finally{release();}
193
- // Only while the branch is still the commit checked above; anything newer is somebody's work.
194
- const deleted=tryGit(canonical,['update-ref','-d',branch,tree.head]);
195
- say(`reaped ${slug}: worktree removed${deleted.status===0?', branch deleted':`, branch kept (${deleted.stderr.trim()})`}`);
196
- reaped.push(slug);
197
- if(!options.remote)continue;
198
- const listed=tryGit(canonical,['ls-remote','--heads','origin',branch]);
199
- const sha=listed.status===0?listed.stdout.trim().split(/\s+/u)[0]??'':'';
200
- if(sha===''){if(listed.status!==0)say(` ${slug}: origin not reachable; its remote branch is left`);continue;}
201
- // The remote branch goes only if it is landed too: its commit must be here and add nothing main lacks.
202
- if(tryGit(canonical,['cat-file','-e',`${sha}^{commit}`]).status!==0){remotes.push(`${slug} kept (origin has ${sha.slice(0,10)}, unknown here)`);say(` ${slug}: origin plan/${slug} is ${sha.slice(0,10)}, not fetched here; left`);continue;}
203
- if(!onMain(canonical,sha)){remotes.push(`${slug} kept (origin has unlanded commits)`);say(` ${slug}: origin plan/${slug} holds commits not on main; left`);continue;}
204
- const pushed=tryGit(canonical,['push','--quiet',`--force-with-lease=${branch}:${sha}`,'origin','--delete',branch]);
205
- if(pushed.status===0){remotes.push(`${slug} deleted`);say(` ${slug}: origin plan/${slug} deleted`);}
206
- else{remotes.push(`${slug} delete failed`);say(` ${slug}: origin plan/${slug} not deleted: ${pushed.stderr.trim()}`);}
147
+ const slug=basename(tree.path);
148
+ if(resolve(tree.path)!==join(canonical,WORKTREES,slug)){
149
+ say(`skipped ${tree.path}: outside plan worktrees`);continue;
150
+ }
151
+ const state=laneLive(tree.path,{receipts:env.WS_LANE_RECEIPTS,cwds,activeLog:env.WS_ACTIVE_HOURS_LOG});
152
+ const landed=onMain(canonical,tree.head);
153
+ say(`${state.state} ${slug}: ${state.reason}; ${landed?'on origin/main':'not on origin/main'}; manual audit, copy before removal`);
207
154
  }
208
- if(!options.dryRun)tryGit(canonical,['worktree','prune']);
209
- const lane=/^[a-z][a-z0-9_-]*$/u.test(env.WS_LANE_NAME??'')?String(env.WS_LANE_NAME):'reaper';
210
- const line=`${new Date().toISOString().slice(11,16)} UTC ${lane} worktree reap ${basename(canonical)}${options.dryRun?' (dry run)':''}: ${reaped.length===0?'none':`${options.dryRun?'would reap':'reaped'} ${reaped.join(', ')}`}; kept ${kept.length===0?'none':kept.join(', ')}${remotes.length===0?'':`; origin ${remotes.join(', ')}`}`;
211
- const file=resolve(env.WS_LANE_RECEIPTS??join(homedir(),'.cache/wildshard/lane-receipts.log'));
212
- try{mkdirSync(dirname(file),{recursive:true});appendFileSync(file,`${line}\n`);}catch(error){say(`reap receipt unavailable: ${String(error)}`);}
213
155
  return 0;
214
156
  }
@@ -16,7 +16,9 @@
16
16
  //
17
17
  // Never copied: .env*, tmp/, .review/, .cache/, browser profiles, leases, ports, push proofs; the worktree gets
18
18
  // only tracked files and its own install. Each step's seconds go to <worktree>/tmp/worktree-setup.json and, with
19
- // WS_LANE_NAME set, one line in ~/.cache/wildshard/lane-receipts.log. Removal is DS13's reaper: `reap`
19
+ // WS_LANE_NAME set, one line in ~/.cache/wildshard/lane-receipts.log. REPO-DISK DK10: the record and the receipt also
20
+ // carry the volume's `df` free bytes before and after and the worktree's `du`: build output inside a worktree costs
21
+ // nothing until written (clones), so `df` shows the real cost and `du` the apparent one. Removal is DS13's reaper: `reap`
20
22
  // (scripts/worktree-reap.mjs) removes landed, clean, idle worktrees with their branches, local and on origin.
21
23
  import {execFileSync,spawn,spawnSync} from 'node:child_process';
22
24
  import {randomBytes} from 'node:crypto';
@@ -25,7 +27,7 @@ import {homedir} from 'node:os';
25
27
  import {basename,dirname,join,resolve} from 'node:path';
26
28
  import {pathToFileURL} from 'node:url';
27
29
  import {WORKTREES} from './worktree-ignore.mjs';
28
- import {lastActivity,linkedWorktrees,onMain,parseReapArgs,reap} from './worktree-reap.mjs';
30
+ import {freeBytes,lastActivity,linkedWorktrees,onMain,parseReapArgs,reap} from './worktree-reap.mjs';
29
31
 
30
32
  export const SLUG=/^[a-z0-9][a-z0-9._-]{0,63}$/u;
31
33
  const REGULAR=/^100(?:644|755)$/u;
@@ -51,7 +53,7 @@ for source, target in zip(parts[0::2], parts[1::2]):
51
53
  sys.exit(f'{target.decode()}: {os.strerror(ctypes.get_errno())}')
52
54
  finally:
53
55
  os.close(fd)`;
54
- const USAGE='usage: node scripts/worktree.mjs new <slug> [--no-install] [--no-pins] [--no-herdr] [--no-clone]\n node scripts/worktree.mjs reap [--dry-run] [--grace=HOURS] [--no-remote]';
56
+ const USAGE='usage: node scripts/worktree.mjs new <slug> [--row=PLAN-ROW] [--no-install] [--no-pins] [--no-herdr] [--no-clone]\n node scripts/worktree.mjs reap [--dry-run] [--grace=HOURS] [--no-remote]';
55
57
 
56
58
  class StopError extends Error{name='StopError';}
57
59
 
@@ -97,7 +99,7 @@ export function freeGib(path,env){
97
99
  return value;
98
100
  }
99
101
  const volume=statfsSync(path);
100
- return Number(volume.bavail)*Number(volume.bsize)/2**30;
102
+ return volume.bavail*volume.bsize/2**30;
101
103
  }
102
104
 
103
105
  /**
@@ -139,9 +141,11 @@ export function parseArgs(argv){
139
141
  if(command!=='new'||slug===undefined)throw new StopError(USAGE);
140
142
  if(!SLUG.test(slug))throw new StopError(`slug "${slug}" must match ${SLUG.source}`);
141
143
  const flags=new Set(['--no-install','--no-pins','--no-herdr','--no-clone']);
142
- const unknown=rest.filter(arg=>!flags.has(arg));
144
+ const row=rest.find(arg=>arg.startsWith('--row='));
145
+ const unknown=rest.filter(arg=>!flags.has(arg)&&arg!==row);
143
146
  if(unknown.length>0)throw new StopError(`unknown option ${unknown.join(' ')}\n${USAGE}`);
144
- return {slug,install:!rest.includes('--no-install'),pins:!rest.includes('--no-pins'),herdr:!rest.includes('--no-herdr'),clone:!rest.includes('--no-clone')};
147
+ if(row!==undefined&&!/^--row=[A-Z][A-Z0-9-]*\d+[a-z]?$/u.test(row))throw new StopError(`invalid plan row ${row}\n${USAGE}`);
148
+ return {slug,row:row?.slice('--row='.length)??null,install:!rest.includes('--no-install'),pins:!rest.includes('--no-pins'),herdr:!rest.includes('--no-herdr'),clone:!rest.includes('--no-clone')};
145
149
  }
146
150
 
147
151
  /** The canonical checkout of the repo `cwd` is in: the main worktree, never a linked one. @param {string} cwd */
@@ -181,7 +185,7 @@ function convertedPaths(tree,paths){
181
185
  /** Clone into `tree` each tracked file the canonical checkout holds clean with the same blob and mode, then keep only
182
186
  * clones whose raw bytes hash to their blob and whose mode matches. @param {string} canonical @param {string} tree
183
187
  * @returns {number} files kept */
184
- function cloneTrackedFiles(canonical,tree){
188
+ export function cloneTrackedFiles(canonical,tree){
185
189
  const source=stagedBlobs(canonical),target=stagedBlobs(tree);
186
190
  // Hidden edits count as dirty: modified, deleted, staged, assume-unchanged (lowercase tag) or skip-worktree (S).
187
191
  const dirty=new Set(nul(git(canonical,['ls-files','-z','--modified','--deleted'])));
@@ -300,12 +304,22 @@ function run(cwd,command,args,env){
300
304
  if(result.status!==0)throw new StopError(`${command} ${args.join(' ')} exited ${String(result.status)}`);
301
305
  }
302
306
 
307
+ /** DK10: what the new worktree cost the volume (`df` free before minus after; other writers move it too) and what
308
+ * `du` counts in it (clones in full). @param {string} tree @param {number} freeBefore free bytes before setup */
309
+ export function diskCost(tree,freeBefore){
310
+ const freeAfter=freeBytes(tree),listed=spawnSync('du',['-sk',tree],{encoding:'utf8',timeout:120_000});
311
+ const kib=Number((listed.stdout??'').split('\t')[0]),duKib=listed.status===0&&Number.isFinite(kib)?kib:undefined;
312
+ const cost=freeBefore-freeAfter,costMib=Math.round(cost/1_048_576);
313
+ const text=`df ${costMib<0?'gained':'cost'} ${Math.abs(costMib).toLocaleString('en-US')} MiB, du ${duKib===undefined?'unknown':`${(duKib/1_048_576).toFixed(2)} GiB`}, free ${(freeAfter/2**30).toFixed(1)} GiB`;
314
+ return {freeBefore,freeAfter,dfCostBytes:cost,duKib,text};
315
+ }
316
+
303
317
  /** @param {string[]} argv @param {string} [cwd] @param {NodeJS.ProcessEnv} [env] @returns {number} */
304
318
  export function worktreeNew(argv,cwd=process.cwd(),env=process.env){
305
319
  const options=parseArgs(argv),canonical=canonicalRoot(cwd),common=join(canonical,'.git');
306
320
  const relative=`${WORKTREES}/${options.slug}`,tree=join(canonical,relative),branch=`plan/${options.slug}`;
307
321
  /** @type {{step:string,seconds:number,detail?:string}[]} */const steps=[];
308
- const began=performance.now();
322
+ const began=performance.now(),freeBefore=freeBytes(canonical);
309
323
  /** @param {string} step @param {() => (string|void)} work */
310
324
  const timed=(step,work)=>{
311
325
  const started=performance.now(),detail=work();
@@ -364,16 +378,24 @@ export function worktreeNew(argv,cwd=process.cwd(),env=process.env){
364
378
  catch(error){process.stderr.write(`worktree: timings refresh not started (${error instanceof Error?error.message:String(error)})\n`);}
365
379
  }
366
380
  const total=Number(((performance.now()-began)/1000).toFixed(2));
367
- const record={slug:options.slug,branch,base,tree,total,steps,finished:new Date().toISOString()};
381
+ const disk=diskCost(tree,freeBefore);
382
+ process.stdout.write(`worktree disk ${disk.text}\n`);
383
+ const created=new Date().toISOString();
384
+ const lane=/^[a-z][a-z0-9_-]*$/u.test(env.WS_LANE_NAME??'')?String(env.WS_LANE_NAME):null;
385
+ const record={slug:options.slug,branch,base,tree,total,steps,disk,finished:created};
386
+ let receiptOffset=null;
387
+ try{receiptOffset=statSync(env.WS_LANE_RECEIPTS??join(homedir(),'.cache/wildshard/lane-receipts.log')).size;}
388
+ catch(error){if(error instanceof Error&&'code'in error&&error.code==='ENOENT')receiptOffset=0;}
389
+ const owner={lane,session:env.CODEX_THREAD_ID||env.CLAUDE_SESSION_ID||env.CLAUDE_CODE_SESSION_ID||lane,agent:env.CODEX_THREAD_ID?'codex':env.CLAUDE_SESSION_ID||env.CLAUDE_CODE_SESSION_ID?'claude':lane?'codex':'unknown',row:options.row??env.WS_PLAN_ROW??null,created,activeHours:null,receiptOffset};
390
+ writeFileSync(join(tree,'.owner'),`${JSON.stringify(owner,null,2)}\n`,{flag:'wx'});
368
391
  mkdirSync(join(tree,'tmp'),{recursive:true});
369
392
  writeFileSync(join(tree,'tmp/worktree-setup.json'),`${JSON.stringify(record,null,2)}\n`);
370
- const lane=/^[a-z][a-z0-9_-]*$/u.test(env.WS_LANE_NAME??'')?String(env.WS_LANE_NAME):'';
371
- if(lane!==''){
393
+ if(lane!==null){
372
394
  const file=resolve(env.WS_LANE_RECEIPTS??join(homedir(),'.cache/wildshard/lane-receipts.log'));
373
- try{mkdirSync(dirname(file),{recursive:true});appendFileSync(file,`${new Date().toISOString().slice(11,16)} UTC ${lane} worktree new ${basename(canonical)}/${relative} on ${branch} from ${base.slice(0,10)} in ${total.toFixed(1)} s (${steps.map(row=>`${row.step} ${row.seconds.toFixed(1)}`).join(', ')})\n`);}
395
+ try{mkdirSync(dirname(file),{recursive:true});appendFileSync(file,`${new Date().toISOString().slice(11,16)} UTC ${lane} worktree new ${basename(canonical)}/${relative} on ${branch} from ${base.slice(0,10)} in ${total.toFixed(1)} s (${steps.map(row=>`${row.step} ${row.seconds.toFixed(1)}`).join(', ')}); ${disk.text}\n`);}
374
396
  catch(error){process.stderr.write(`worktree receipt unavailable: ${String(error)}\n`);}
375
397
  }
376
- const name=lane===''?'<lane>':lane;
398
+ const name=lane??'<lane>';
377
399
  process.stdout.write(`\nworktree ready in ${total.toFixed(1)} s: ${tree} on ${branch}\n\nLand (J240):\n cd ${tree}\n # commit by pathspec as usual; the hooks allow commits here on ${branch}\n WS_LANE_NAME=${name} node scripts/land.mjs\n # it pushes ${branch}, waits for its hosted CI (land.config.json workflows), rebases and fast-forwards main;\n # check its receipt in ~/.cache/wildshard/lane-receipts.log. Force only your own plan/* branch\n # after a rebase (--force-with-lease), never main.\n`);
378
400
  return 0;
379
401
  }
@@ -21,7 +21,9 @@ instead where a step is not built yet.
21
21
 
22
22
  1. **new**: `wildshard new <dir>` started this repo. `GUIDE.md#1-the-loop`; every flag in `GUIDE.md#every-verb`.
23
23
  2. **dev**: `wildshard dev .` serves the shard on localhost; open the URL it prints. `GUIDE.md#walking-your-shard`,
24
- and what reloads on save in `GUIDE.md#4-what-reloads-under-dev`. Done when you have walked it.
24
+ and what reloads on save in `GUIDE.md#4-what-reloads-under-dev`. Done when you have walked it. A shard written as
25
+ a three.js scene (`src/generators/world.ts`, from `new --template scene`): `pnpm watch` (`wildshard watch .`)
26
+ swaps each saved edit into the running page with no reload; `GUIDE.md#every-verb`.
25
27
  3. **check**: `wildshard check .` after every change. `GUIDE.md#1-the-loop`; what it measures in
26
28
  `GUIDE.md#3-budgets`. Done when the last line reads `check pass`.
27
29
  4. **hero**: capture a new hero after your last change to the world. `GUIDE.md#the-hero`, then step 1 of
@@ -0,0 +1,44 @@
1
+ /* eslint-disable no-magic-numbers */
2
+ import { formatContent, readContent } from './content.ts'
3
+
4
+ const EXIT_OK = 0
5
+ const EXIT_USAGE = 1
6
+ const EXIT_ERROR = 2
7
+ const EXIT_FAILED = 3
8
+ const [dir, ...options] = process.argv.slice(2)
9
+ const flags: { bar?: string; unknown?: string } = {}
10
+ for (let index = 0; index < options.length; index += 1) {
11
+ const option = options[index]
12
+ if (option === '--bar') {
13
+ index += 1
14
+ flags.bar = options[index] ?? ''
15
+ } else if (option?.startsWith('--bar=') === true) {
16
+ flags.bar = option.slice('--bar='.length)
17
+ } else {
18
+ flags.unknown = option ?? ''
19
+ }
20
+ }
21
+
22
+ const { bar, unknown } = flags
23
+
24
+ if (dir === undefined) {
25
+ process.stderr.write('wildshard: content needs a built shard directory\n')
26
+ process.exitCode = EXIT_USAGE
27
+ } else if (
28
+ unknown !== undefined ||
29
+ (bar !== undefined && bar !== 'templates')
30
+ ) {
31
+ process.stderr.write(
32
+ `wildshard: content does not know ${unknown ?? `--bar=${bar}`}\n`,
33
+ )
34
+ process.exitCode = EXIT_USAGE
35
+ } else {
36
+ try {
37
+ const report = readContent(dir, bar)
38
+ process.stdout.write(formatContent(report, bar))
39
+ process.exitCode = report.short.length === 0 ? EXIT_OK : EXIT_FAILED
40
+ } catch (error: unknown) {
41
+ process.stderr.write(`wildshard: content failed: ${String(error)}\n`)
42
+ process.exitCode = EXIT_ERROR
43
+ }
44
+ }