@wildshard/sdk 0.3.2 → 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 +6 -1
  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 +196 -14
  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 +6 -6
  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
@@ -0,0 +1,172 @@
1
+ #!/usr/bin/env node
2
+ // REPO-DISK DK18a/J358: preserve a worktree before a human removes it. This
3
+ // helper only writes a copy; it has no delete operation.
4
+ import { spawnSync } from 'node:child_process';
5
+ import { createHash, randomUUID } from 'node:crypto';
6
+ import { existsSync, lstatSync, mkdirSync, readdirSync, readFileSync, readlinkSync, realpathSync, writeFileSync } from 'node:fs';
7
+ import { homedir } from 'node:os';
8
+ import { basename, dirname, join, resolve, sep } from 'node:path';
9
+ import { pathToFileURL } from 'node:url';
10
+
11
+ const MAX_UNTRACKED_BYTES = 50 * 1024 * 1024;
12
+ const DEFAULT_KEEP_ROOT = join(homedir(), '.cache/wildshard/session-keep');
13
+ const RETENTION_DAYS = 14;
14
+ const RAW_PATCH = ['--binary', '--no-color', '--no-ext-diff', '--no-textconv', '--src-prefix=a/', '--dst-prefix=b/'];
15
+ // Declared build/install outputs are regenerable. Other ignored files, including
16
+ // tmp captures and owner metadata, must be copied or make removal fail closed.
17
+ const REGENERABLE = /^(?:(?:node_modules|dist(?:-[^/]+)?|out|build|coverage|\.bin-deps|\.tsc-layers|\.cache|\.vite|test-results|playwright-report|blob-report)\/|public\/(?:assets\/(?:packs|physics|gpu)|basis|shardfiles)\/)|(?:^|\/)[^/]+\.(?:tsbuildinfo|generated\.ts)$/u;
18
+
19
+ /** @param {string} cwd @param {string[]} args */
20
+ const run = (cwd, args) => spawnSync('git', ['-C', cwd, ...args], { encoding: 'utf8', maxBuffer: 64 * 1024 * 1024 });
21
+ /** @param {string} cwd @param {string[]} args */
22
+ const text = (cwd, args) => {
23
+ const result = run(cwd, args);
24
+ if (result.status !== 0) throw new Error(`keep-copy: git ${args.join(' ')} failed: ${result.stderr.trim()}`);
25
+ return result.stdout;
26
+ };
27
+
28
+ /** A patch is a byte stream: text diffs may contain non-UTF-8 source bytes.
29
+ * @param {string} root @param {boolean} [cached] */
30
+ function rawPatch(root, cached = false) {
31
+ const args = ['-C', root, 'diff', ...(cached ? ['--cached'] : []), ...RAW_PATCH, 'HEAD'];
32
+ const result = spawnSync('git', args, { maxBuffer: 64 * 1024 * 1024 });
33
+ if (result.status !== 0) throw new Error(`keep-copy: raw patch failed: ${result.stderr?.toString('utf8')}`);
34
+ return result.stdout;
35
+ }
36
+
37
+ /** @param {string} path @param {string} root @param {Date} now */
38
+ function destination(path, root, now) {
39
+ const day = now.toISOString().slice(0, 10);
40
+ const stamp = now.toISOString().slice(11, 19).replaceAll(':', '-');
41
+ return join(root, day, `${basename(path)}__${process.pid}-${stamp}-${randomUUID()}`);
42
+ }
43
+
44
+ /** Resolve existing symlink ancestors before any destination directory is made.
45
+ * @param {string} path */
46
+ function physicalPath(path) {
47
+ let ancestor = resolve(path);
48
+ const tail = [];
49
+ while (!existsSync(ancestor)) {
50
+ tail.unshift(basename(ancestor));
51
+ ancestor = dirname(ancestor);
52
+ }
53
+ return resolve(realpathSync(ancestor), ...tail);
54
+ }
55
+
56
+ /** @param {string} source @param {string} target */
57
+ function requireExternalCopy(source, target) {
58
+ if (target === source || target.startsWith(source + sep))
59
+ throw new Error('keep-copy: destination must stay outside the source removal tree');
60
+ }
61
+
62
+ /** @param {string} path @param {string[]} files */
63
+ function bytes(path, files) {
64
+ return files.reduce((total, file) => total + lstatSync(join(path, file)).size, 0);
65
+ }
66
+
67
+ /** Include ignored evidence without walking known generated outputs or symlinks.
68
+ * @param {string} root */
69
+ function recoverableFiles(root) {
70
+ const files = new Set(text(root, ['ls-files', '--others', '--exclude-standard', '-z']).split('\0').filter(Boolean));
71
+ const visit = (/** @type {string} */ file) => {
72
+ const info = lstatSync(join(root, file));
73
+ if (info.isDirectory()) {
74
+ for (const name of readdirSync(join(root, file))) visit(join(file, name));
75
+ } else if (info.isFile() || info.isSymbolicLink()) files.add(file);
76
+ else throw new Error(`keep-copy: cannot preserve ${file}; source must be kept`);
77
+ };
78
+ for (const file of text(root, ['ls-files', '--others', '--ignored', '--exclude-standard', '--directory', '--no-empty-directory', '-z']).split('\0').filter(Boolean))
79
+ if (!REGENERABLE.test(file)) visit(file.replace(/\/$/u, ''));
80
+ const list = [...files].sort();
81
+ if (bytes(root, list) > MAX_UNTRACKED_BYTES) throw new Error('keep-copy: recoverable files exceed 50 MiB; source must be kept');
82
+ return list;
83
+ }
84
+
85
+ /** Snapshot every recoverable byte before copying and again after stopping
86
+ * writers. Status alone misses edits within an existing untracked folder.
87
+ * @param {string} root */
88
+ export function worktreeState(root) {
89
+ const hash = createHash('sha256');
90
+ for (const file of recoverableFiles(root)) {
91
+ const path = join(root, file), info = lstatSync(path);
92
+ if (!info.isFile() && !info.isSymbolicLink()) throw new Error(`cannot snapshot ${file}`);
93
+ hash.update(JSON.stringify([file, info.mode, info.size]));
94
+ hash.update(info.isSymbolicLink() ? readlinkSync(path) : readFileSync(path));
95
+ }
96
+ return JSON.stringify([
97
+ text(root, ['rev-parse', 'HEAD']), text(root, ['symbolic-ref', '--quiet', 'HEAD']),
98
+ text(root, ['status', '--porcelain', '--untracked-files=all']),
99
+ createHash('sha256').update(rawPatch(root)).digest('hex'), createHash('sha256').update(rawPatch(root, true)).digest('hex'),
100
+ hash.digest('hex'),
101
+ ]);
102
+ }
103
+
104
+ /** Copy recoverable Git worktree state. It never deletes or mutates `path`.
105
+ * @param {string} path @param {{keepRoot?: string, now?: Date}} [options] */
106
+ export function keepCopy(path, { keepRoot = DEFAULT_KEEP_ROOT, now = new Date() } = {}) {
107
+ const root = resolve(path);
108
+ if (!existsSync(root)) throw new Error(`keep-copy: ${root} does not exist`);
109
+ const repo = text(root, ['rev-parse', '--show-toplevel']).trim();
110
+ const source = realpathSync(root);
111
+ requireExternalCopy(source, physicalPath(keepRoot));
112
+ const files = recoverableFiles(root);
113
+ const dir = destination(root, resolve(keepRoot), now);
114
+ mkdirSync(dir, { recursive: true });
115
+ requireExternalCopy(source, realpathSync(dir));
116
+ /** @type {{source:string,repository:string,created:string,bundle:boolean,patch:boolean,untracked:string|{files:number,bytes:number}}} */
117
+ const manifest = { source: root, repository: repo, created: now.toISOString(), bundle: false, patch: false, untracked: 'none' };
118
+ const unpublished = run(root, ['log', 'HEAD', '--branches', '--tags', '--not', '--remotes', '--format=%H']);
119
+ if (unpublished.status !== 0) throw new Error(`keep-copy: cannot inspect unpublished commits: ${unpublished.stderr.trim()}`);
120
+ if (unpublished.stdout.trim() !== '') {
121
+ text(root, ['bundle', 'create', join(dir, 'unpublished.bundle'), 'HEAD', '--branches', '--tags', '--not', '--remotes']);
122
+ manifest.bundle = true;
123
+ }
124
+ const patch = rawPatch(root);
125
+ const indexPatch = rawPatch(root, true);
126
+ if (indexPatch.length > 0) writeFileSync(join(dir, 'index.patch'), indexPatch);
127
+ if (patch.length > 0) {
128
+ writeFileSync(join(dir, 'tracked.patch'), patch);
129
+ manifest.patch = true;
130
+ }
131
+ if (files.length > 0) {
132
+ const total = bytes(root, files);
133
+ if (total <= MAX_UNTRACKED_BYTES) {
134
+ const archive = spawnSync('tar', ['-czf', join(dir, 'untracked.tgz'), '--null', '-T', '-'], { cwd: root, input: `${files.join('\0')}\0`, encoding: 'utf8' });
135
+ if (archive.status !== 0) throw new Error(`keep-copy: tar failed: ${archive.stderr.trim()}`);
136
+ manifest.untracked = { files: files.length, bytes: total };
137
+ } else throw new Error('keep-copy: untracked files exceed 50 MiB; source must be kept');
138
+ }
139
+ writeFileSync(join(dir, 'MANIFEST.json'), `${JSON.stringify(manifest, null, 2)}\n`);
140
+ return { dir, manifest };
141
+ }
142
+
143
+ /** List retention candidates for a human audit. This never removes a copy.
144
+ * @param {{keepRoot?: string, now?: Date}} [options] */
145
+ export function oldKeepCopies({ keepRoot = DEFAULT_KEEP_ROOT, now = new Date() } = {}) {
146
+ if (!existsSync(keepRoot)) return [];
147
+ const rows = [];
148
+ for (const day of readdirSync(keepRoot, { withFileTypes: true }).filter(entry => entry.isDirectory())) {
149
+ const parent = join(keepRoot, day.name);
150
+ for (const child of readdirSync(parent, { withFileTypes: true }).filter(entry => entry.isDirectory())) {
151
+ const manifest = join(parent, child.name, 'MANIFEST.json');
152
+ try {
153
+ const created = new Date(JSON.parse(readFileSync(manifest, 'utf8')).created);
154
+ const age = Math.floor((now.getTime() - created.getTime()) / 86_400_000);
155
+ if (Number.isFinite(age) && age >= RETENTION_DAYS) rows.push({ path: join(parent, child.name), age });
156
+ } catch {/* Unreadable evidence is skipped. */}
157
+ }
158
+ }
159
+ return rows.sort((left, right) => right.age - left.age || left.path.localeCompare(right.path));
160
+ }
161
+
162
+ if (import.meta.url === pathToFileURL(process.argv[1] ?? '').href) {
163
+ try {
164
+ const [path] = process.argv.slice(2);
165
+ if (!path || process.argv.length !== 3) throw new Error('usage: node scripts/keep-copy.mjs <worktree>');
166
+ const result = keepCopy(path, { keepRoot: process.env.WS_SESSION_KEEP_ROOT ?? DEFAULT_KEEP_ROOT });
167
+ process.stdout.write(`${result.dir}\n`);
168
+ } catch (error) {
169
+ process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
170
+ process.exitCode = 1;
171
+ }
172
+ }
package/scripts/land.mjs CHANGED
@@ -24,6 +24,7 @@
24
24
  // {quarantine, artifacts, packedStep, owner}: the J200 quarantine file, the artifact pattern holding
25
25
  // the shard reports, the packed step a flaky failure must be limited to, and the quarantine's owner.
26
26
  import {execFileSync,spawn,spawnSync} from 'node:child_process';
27
+ import {keepCopy,worktreeState} from './keep-copy.mjs';
27
28
  import {appendFileSync,existsSync,linkSync,lstatSync,mkdirSync,mkdtempSync,readFileSync,readdirSync,realpathSync,renameSync,rmSync,writeFileSync} from 'node:fs';
28
29
  import {homedir} from 'node:os';
29
30
  import {dirname,join,resolve} from 'node:path';
@@ -771,16 +772,45 @@ class Landing{
771
772
  const deleted=tryGit(this.root,['push','--quiet',`--force-with-lease=refs/heads/${this.branch}:${this.planTip}`,'origin','--delete',this.branch]);
772
773
  parts.push(deleted.status===0?`origin ${this.branch} deleted`:`origin ${this.branch} kept (${deleted.stderr.trim().split('\n').at(-1)??'push refused'})`);
773
774
  }
774
- const dirty=tryGit(this.root,['status','--porcelain']).stdout.trim();
775
+ const dirtyResult=tryGit(this.root,['status','--porcelain','--untracked-files=all']);
776
+ const dirty=dirtyResult.stdout.trimEnd();
777
+ const generatedOnly=dirty!==''&&dirty.split('\n').every(line=>/^[ MAD?]{2} (?:[^"\n]+\.generated\.ts|public\/assets\/gpu\/[^"\n]+)$/u.test(line));
778
+ const patchBefore=tryGit(this.root,['diff','--binary','HEAD']);
775
779
  const now=tryGit(this.root,['symbolic-ref','--quiet','HEAD']).stdout.trim(),at=tryGit(this.root,['rev-parse','HEAD']).stdout.trim();
776
780
  if(now!==`refs/heads/${this.branch}`||at!==head)parts.push(`worktree kept: HEAD moved off ${this.branch} ${short(head)} after landing`);
777
- else if(dirty!=='')parts.push(`worktree kept: ${dirty.split('\n').length} uncommitted or untracked path(s)`);
781
+ else if(dirtyResult.status!==0||patchBefore.status!==0)parts.push('worktree kept: status unreadable');
782
+ else if(dirty!==''&&!generatedOnly)parts.push(`worktree kept: ${dirty.split('\n').length} uncommitted or untracked path(s)`);
778
783
  else{
784
+ // J358's sole removal exception: this land owns this just-landed worktree.
785
+ // Copy first; any failure retains the source and its local branch.
786
+ let before;
787
+ try{
788
+ before=worktreeState(this.root);
789
+ const saved=keepCopy(this.root,{keepRoot:this.env.WS_SESSION_KEEP_ROOT});
790
+ this.say('copied',`recoverable worktree state saved at ${saved.dir}`);
791
+ }catch(error){
792
+ const line=parts.concat(`worktree kept: copy failed (${error instanceof Error?error.message:String(error)})`).join('; ');
793
+ this.say('cleaned',line);
794
+ return line;
795
+ }
796
+ const unchanged=()=>{try{return worktreeState(this.root)===before;}catch{return false;}};
797
+ if(!unchanged()){
798
+ const line=parts.concat('worktree kept: changed during copy').join('; ');
799
+ this.say('cleaned',line);return line;
800
+ }
779
801
  // TEST-SPEED FL30: nothing started here may outlive the folder (an orphaned Vitest held the CPU slots).
780
802
  let stopped=[];
781
- try{stopped=stopWorktreeProcesses(realpathSync(this.root));}catch{/* Listing failed: remove as before. */}
803
+ try{stopped=stopWorktreeProcesses(realpathSync(this.root));}catch{
804
+ const line=parts.concat('worktree kept: process cleanup failed').join('; ');
805
+ this.say('cleaned',line);return line;
806
+ }
782
807
  if(stopped.length>0)parts.push(`stopped ${String(stopped.length)} process(es) still running there (pid ${stopped.join(', ')})`);
783
- const removed=tryGit(canonical,['worktree','remove',this.root]);
808
+ // Shutdown handlers may write after the copy. Protect their last writes.
809
+ if(!unchanged()){
810
+ const line=parts.concat('worktree kept: changed during process cleanup').join('; ');
811
+ this.say('cleaned',line);return line;
812
+ }
813
+ const removed=tryGit(canonical,['worktree','remove',...(generatedOnly?['--force']:[]),this.root]);
784
814
  if(removed.status===0){
785
815
  tryGitLocked(canonical,['update-ref','-d',`refs/heads/${this.branch}`,head],process.env,this.retry);
786
816
  parts.push(`worktree and ${this.branch} removed; continue from ${canonical}`);
@@ -0,0 +1,136 @@
1
+ #!/usr/bin/env node
2
+ // REPO-DISK DK16/J358: read liveness without changing the lane.
3
+ import { spawnSync } from 'node:child_process';
4
+ import { existsSync, lstatSync, readFileSync, readdirSync, readlinkSync, realpathSync, statSync } from 'node:fs';
5
+ import { homedir } from 'node:os';
6
+ import { join, sep } from 'node:path';
7
+ import { pathToFileURL } from 'node:url';
8
+ import { activeHoursSince } from '../.agents/hooks/active-hours.mjs';
9
+
10
+ const RECEIPTS = join(homedir(), '.cache/wildshard/lane-receipts.log');
11
+ /** @param {string} path @param {string} root */
12
+ const under = (path, root) => path === root || path.startsWith(root + sep);
13
+ /** @param {string} path */
14
+ const readOwner = path => {
15
+ try {
16
+ const marker = join(path, '.owner'), info = lstatSync(marker);
17
+ if (!info.isFile() || info.isSymbolicLink() || info.size > 65536) return undefined;
18
+ const value = JSON.parse(readFileSync(marker, 'utf8'));
19
+ return value && typeof value === 'object' && !Array.isArray(value) ? value : undefined;
20
+ } catch { return undefined; }
21
+ };
22
+
23
+ /** null means process evidence could not be read; callers protect the folder. */
24
+ export function processCwds() {
25
+ if (existsSync('/proc/self/cwd')) {
26
+ try {
27
+ return readdirSync('/proc').filter(pid => /^\d+$/u.test(pid)).flatMap(pid => {
28
+ try { return [readlinkSync(`/proc/${ pid }/cwd`)]; } catch { return []; }
29
+ });
30
+ } catch { return null; }
31
+ }
32
+ const found = spawnSync('lsof', ['-nP', '-w', '-d', 'cwd', '-Fn'], {
33
+ cwd: '/', encoding: 'utf8', timeout: 2000, maxBuffer: 64 * 1024 * 1024,
34
+ });
35
+ if (found.error || found.signal || found.status !== 0) return null;
36
+ return found.stdout.split('\n').filter(line => line.startsWith('n')).map(line => line.slice(1));
37
+ }
38
+
39
+ /** @param {unknown} lane @param {string} path @param {unknown} offset */
40
+ function receipt(lane, path, offset) {
41
+ if (typeof lane !== 'string' || !/^[\w.-]+$/u.test(lane)) return undefined;
42
+ // Undated receipts cannot end a folder created later. Legacy owners have
43
+ // no cursor, so they must use process/session evidence and active hours.
44
+ if (typeof offset !== 'number' || !Number.isSafeInteger(offset) || offset < 0) return undefined;
45
+ try {
46
+ const log = readFileSync(path);
47
+ if (offset > log.length) return undefined;
48
+ let last;
49
+ for (const line of log.subarray(offset).toString('utf8').split('\n').slice(0, -1))
50
+ if (line.includes(` ${lane} `) && /\s(?:DONE|ENDED|PAUSED):/u.test(line)) last = line;
51
+ return last;
52
+ } catch { return undefined; }
53
+ }
54
+
55
+ /** @param {string} root @param {number} depth */
56
+ function pidfileLive(root, depth = 0) {
57
+ for (const name of ['.pid', 'pid', 'pidfile', 'server.pid', 'dev.pid']) {
58
+ try {
59
+ const pid = Number(readFileSync(join(root, name), 'utf8').trim());
60
+ if (!Number.isSafeInteger(pid) || pid < 1) continue;
61
+ try { process.kill(pid, 0); return true; } catch (error) { if (error instanceof Error && 'code' in error && error.code === 'EPERM') return true; }
62
+ } catch {/* Unreadable evidence is skipped. */}
63
+ }
64
+ if (depth < 2) {
65
+ try {
66
+ for (const entry of readdirSync(root, { withFileTypes: true })) {
67
+ if (entry.isDirectory() && !entry.isSymbolicLink() && entry.name.startsWith('dev-') &&
68
+ pidfileLive(join(root, entry.name), depth + 1)) return true;
69
+ }
70
+ } catch {/* No readable dev-process children. */}
71
+ }
72
+ return false;
73
+ }
74
+
75
+ /** @param {unknown} session @param {string|undefined} activeLog
76
+ * @returns {{live?:boolean,latest?:number}} */
77
+ function sessionEvidence(session, activeLog) {
78
+ if (typeof session !== 'string' || !/^[\w.@:-]+$/u.test(session)) return {};
79
+ // A transcript's existence is not liveness: use its most recent write.
80
+ let latest = 0;
81
+ for (const root of [join(homedir(), '.claude/projects'), join(homedir(), '.codex/sessions')]) {
82
+ try {
83
+ for (const row of readdirSync(root, { recursive: true })) {
84
+ if (!String(row).includes(session)) continue;
85
+ const info = statSync(join(root, String(row)));
86
+ if (info.isFile()) latest = Math.max(latest, info.mtimeMs);
87
+ }
88
+ } catch {/* Unreadable evidence is skipped. */}
89
+ }
90
+ const listed = spawnSync('herdr', ['agent', 'list'], { encoding: 'utf8', timeout: 2000, maxBuffer: 8 * 1024 * 1024 });
91
+ if (listed.status === 0) {
92
+ try {
93
+ /** @type {{agent_session?:{value?:string}}[]} */
94
+ const agents = JSON.parse(listed.stdout)?.result?.agents ?? [];
95
+ if (agents.some(agent => agent.agent_session?.value === session)) return { live: true };
96
+ } catch {/* Unreadable evidence is skipped. */}
97
+ }
98
+ return { live: latest > 0 && activeHoursSince(new Date(latest), { log: activeLog }) < 24, latest };
99
+ }
100
+
101
+ /** Read-only classification. Unreadable process evidence always protects a folder.
102
+ * @param {string} path
103
+ * @param {{receipts?:string,activeHours?:number,cwdLive?:boolean,cwds?:string[]|null,sessionLive?:boolean,activeLog?:string}} [options] */
104
+ export function laneLive(path, { receipts = RECEIPTS, activeHours, cwdLive, cwds,
105
+ sessionLive, activeLog = process.env.WS_ACTIVE_HOURS_LOG } = {}) {
106
+ let root;
107
+ try { root = realpathSync(path); } catch { return { state: 'unknown', reason: 'folder unreadable' }; }
108
+ const directories = cwds === undefined && cwdLive === undefined ? processCwds() : cwds;
109
+ if (cwdLive === true || directories?.some(cwd => under(cwd, root)) || pidfileLive(root))
110
+ return { state: 'live', reason: 'a process cwd or pidfile is live' };
111
+ if (cwdLive === undefined && directories === null) return { state: 'live', reason: 'process evidence unreadable' };
112
+ const record = readOwner(root);
113
+ if (!record) {
114
+ const hours = activeHours ?? activeHoursSince(lstatSync(root).mtime, { log: activeLog });
115
+ return { state: 'unknown', reason: hours >= 72 ? 'no readable .owner; at least 72 active hours, investigate' : 'no readable .owner' };
116
+ }
117
+ const evidence = sessionLive === undefined ? sessionEvidence(record.session, activeLog) : { live: sessionLive, latest: 0 };
118
+ if (evidence.live) return { state: 'live', reason: 'owner session is present' };
119
+ const line = receipt(record.lane, receipts, record.receiptOffset);
120
+ if (line && /\s(?:DONE|ENDED):/u.test(line)) return { state: 'ended', reason: 'ending receipt' };
121
+ const since = evidence.latest !== undefined && evidence.latest > 0 ? evidence.latest : Date.parse(record.started ?? record.created ?? '');
122
+ const elapsed = activeHours ?? (Number.isFinite(since) ? activeHoursSince(new Date(since), { log: activeLog }) : 0);
123
+ if (elapsed >= 24) return { state: 'ended', reason: 'owner gone and silent for 24 active hours' };
124
+ return { state: 'live', reason: line ? 'non-ending receipt' : 'no ending receipt' };
125
+ }
126
+
127
+ if (import.meta.url === pathToFileURL(process.argv[1] ?? '').href) {
128
+ const [path] = process.argv.slice(2);
129
+ if (!path || process.argv.length !== 3) {
130
+ process.stderr.write('usage: node scripts/lane-live.mjs <lane-root>\n');
131
+ process.exitCode = 2;
132
+ } else {
133
+ const result = laneLive(path, { receipts: process.env.WS_LANE_RECEIPTS ?? RECEIPTS });
134
+ process.stdout.write(`${result.state }: ${ result.reason }\n`);
135
+ }
136
+ }
@@ -0,0 +1,47 @@
1
+ #!/usr/bin/env node
2
+ // REPO-DISK J358: a read-only, compact leftovers list for the session brief and
3
+ // daily human audit. It deliberately has no delete operation.
4
+ import { execFileSync } from 'node:child_process';
5
+ import { lstatSync, readdirSync } from 'node:fs';
6
+ import { homedir } from 'node:os';
7
+ import { join, resolve } from 'node:path';
8
+ import { pathToFileURL } from 'node:url';
9
+ import { laneLive } from './lane-live.mjs';
10
+
11
+ const ROOT = resolve(import.meta.dirname, '..');
12
+ const RECEIPTS = join(homedir(), '.cache/wildshard/lane-receipts.log');
13
+
14
+ /** @param {string} path */
15
+ function size(path) {
16
+ try { return Number.parseInt(execFileSync('du', ['-sk', path], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim().split(/\s+/u)[0] ?? '0', 10); } catch { return 0; }
17
+ }
18
+
19
+ /** Read each direct tmp folder without mutating it.
20
+ * @param {{root?: string, receipts?: string}} [options] */
21
+ export function leftovers({ root = ROOT, receipts = RECEIPTS } = {}) {
22
+ const tmp = join(resolve(root), 'tmp');
23
+ let names = [];
24
+ try { names = readdirSync(tmp).sort(); } catch { return []; }
25
+ return names.flatMap(name => {
26
+ const path = join(tmp, name);
27
+ try { if (!lstatSync(path).isDirectory() || name.startsWith('.')) return []; } catch { return []; }
28
+ const liveness = laneLive(path, { receipts });
29
+ return [{ name, path, state: liveness.state, reason: liveness.reason, kib: size(path) }];
30
+ });
31
+ }
32
+
33
+ /** At most four brief lines. @param {ReturnType<typeof leftovers>} rows */
34
+ export function brief(rows) {
35
+ if (rows.length === 0) return [' leftovers: none'];
36
+ return [...rows].sort((a, b) => {
37
+ const state = a.state.localeCompare(b.state), byteOrder = b.kib - a.kib;
38
+ return state !== 0 ? state : byteOrder !== 0 ? byteOrder : a.name.localeCompare(b.name);
39
+ }).slice(0, 4)
40
+ .map(row => ` ${row.state}: tmp/${row.name} (${(row.kib / 1024 / 1024).toFixed(1)} GiB; ${row.reason})`);
41
+ }
42
+
43
+ if (import.meta.url === pathToFileURL(process.argv[1] ?? '').href) {
44
+ const rootAt = process.argv.indexOf('--root');
45
+ const root = rootAt === -1 ? ROOT : resolve(process.argv[rootAt + 1] ?? '');
46
+ process.stdout.write(`${brief(leftovers({ root, receipts: process.env.WS_LANE_RECEIPTS ?? RECEIPTS })).join('\n')}\n`);
47
+ }
@@ -2,11 +2,16 @@
2
2
  // Keep staged CLI/CI paths in the scaffold lane. pnpm appends arguments to
3
3
  // the last command of an && script, which incorrectly sent them to author lint.
4
4
  import {spawnSync} from 'node:child_process';
5
+ import {readFileSync} from 'node:fs';
5
6
 
6
7
  const files=process.argv.slice(2).filter(file=>file!=='--');
8
+ const manifest=JSON.parse(readFileSync(new URL('../test/ci21-sdk-tail.json',import.meta.url),'utf8'));
9
+ const ports=[...manifest.files.map(file=>file.targetPath),...manifest.supportPaths];
7
10
  const author=file=>/^src\/(?:sharddev|commons|shards)\//u.test(file);
8
11
  const jobs=files.length===0?[['lint:kit',[]],['lint:author',[]]]:
9
12
  [['lint:kit',files.filter(file=>!author(file))],['lint:author',files.filter(author)]].filter(([,paths])=>paths.length>0);
13
+ if(files.length===0)jobs.push(['lint:ci21',[]]);
14
+ else {const selected=files.filter(file=>ports.includes(file));if(selected.length>0)jobs.push(['lint:ci21',selected]);}
10
15
  for(const [name,paths] of jobs){
11
16
  const run=spawnSync('pnpm',['run',name,...paths],{stdio:'inherit'});
12
17
  if(run.error!==undefined)throw run.error;
@@ -5,13 +5,14 @@
5
5
  // loop (D → B) is written once, followed by the ring-out.
6
6
  import { writeFileSync } from 'node:fs';
7
7
  import { resolve } from 'node:path';
8
- import { ARRANGEMENTS, CHORDS } from '@wildshard/engine/game/audio/theme';
8
+ import '@wildshard/engine/scripts/format-hook.mjs';
9
+ const { ARRANGEMENTS, CHORDS } = await import('@wildshard/engine/game/audio/theme');
9
10
 
10
11
  const here = import.meta.dirname;
11
12
  const name = process.argv[2] ?? 'theme';
12
13
  const out = resolve(process.argv[3] ?? `${here}/wildshard-${name}.mid`);
13
14
 
14
- // The defining score is pure author data; Node 24 strips its type-only declarations.
15
+ // The defining score is installed TypeScript; the shared hook strips its type-only declarations.
15
16
  const arr = Object.entries(ARRANGEMENTS).find(([key]) => key === name)?.[1];
16
17
  if (!arr) throw new Error(`no arrangement ${name}`);
17
18
 
@@ -4,7 +4,6 @@
4
4
  import {createHash} from 'node:crypto';
5
5
  import {spawn} from 'node:child_process';
6
6
  import {readFileSync,writeFileSync,mkdirSync,mkdtempSync,rmSync,readdirSync,statSync,lstatSync} from 'node:fs';
7
- import {tmpdir} from 'node:os';
8
7
  import {join,resolve,dirname} from 'node:path';
9
8
  import {fileURLToPath} from 'node:url';
10
9
  import '@wildshard/format/formatHook';
@@ -95,7 +94,9 @@ export async function prepareProduct(dir,base,inline=false){
95
94
  try{return await prepareProduct(dir,preview.url,true);}finally{await preview.close();}
96
95
  }
97
96
  const header=readFileSync(join(dir,'shard.json')),index=parseOutputIndex(JSON.parse(header));
98
- const scratch=mkdtempSync(join(tmpdir(),'wildshard-prepare-'));
97
+ // SA17: the recording lands under the project's own tmp/ (git-ignored by `new`), never the system temp dir.
98
+ const parent=join(process.cwd(),'tmp');mkdirSync(parent,{recursive:true});
99
+ const scratch=mkdtempSync(join(parent,'wildshard-prepare-'));
99
100
  try{
100
101
  const out=join(scratch,'recording.json');
101
102
  const script=fileURLToPath(new URL('./bake-entry-programs.mjs',import.meta.url));
@@ -0,0 +1,3 @@
1
+ export function scratchDir(task: string, purpose: string, options?: {
2
+ root?: string; env?: NodeJS.ProcessEnv; now?: Date; row?: string | null;
3
+ }): string;
@@ -2,17 +2,18 @@
2
2
  // repo-kit's scratch folder maker (meta docs/plans/REPO-DISK-PLAN.md row DK3). One copy lives in repo-kit; every org
3
3
  // repo and singleplayer carries a byte-identical copy at scripts/scratch-dir.mjs (DK8 checks the copies).
4
4
  //
5
- // node scripts/scratch-dir.mjs <task> "<purpose>"
5
+ // node scripts/scratch-dir.mjs <task> "<purpose>" [--row <plan-row>]
6
6
  //
7
7
  // creates <repo>/tmp/<task>/ and tmp/<task>/.owner, then prints the folder's absolute path. .owner is JSON: the session
8
- // id ($CLAUDE_SESSION_ID, else $CLAUDE_CODE_SESSION_ID, else the Codex lane name in $WS_LANE_NAME), the lane name, the
8
+ // id ($CODEX_THREAD_ID, else $CLAUDE_SESSION_ID, else $CLAUDE_CODE_SESSION_ID, else $WS_LANE_NAME), the lane name, the
9
9
  // herdr pane ($HERDR_PANE_ID), the start time and the purpose. DK4's SessionEnd hook removes the folders whose .owner
10
- // names the ending session; a .keep file in the folder (one line: why to keep it) stops that and DK6's 3-day sweep.
10
+ // names the ending session. J358 makes cleanup report-only; a human audits and copies before removal.
11
11
  //
12
12
  // <task> is one plain folder name: letters, digits, '.', '_' and '-', not starting with '.', never containing '/' or
13
13
  // '..'. The helper deletes nothing. It refuses a folder that already exists unless that folder's .owner names this
14
14
  // same session (then it prints the path again), so it never takes over another lane's or an ownerless folder.
15
- import { mkdirSync, readFileSync, rmdirSync, writeFileSync } from 'node:fs';
15
+ import { mkdirSync, readFileSync, renameSync, rmdirSync, statSync, writeFileSync } from 'node:fs';
16
+ import { homedir } from 'node:os';
16
17
  import { join, resolve } from 'node:path';
17
18
  import { pathToFileURL } from 'node:url';
18
19
 
@@ -31,14 +32,21 @@ export function refuseTask(task) {
31
32
  }
32
33
 
33
34
  /** The .owner record for a new folder.
34
- * @param {string} task @param {string} purpose @param {NodeJS.ProcessEnv} env @param {Date} now */
35
- export function ownerRecord(task, purpose, env, now) {
35
+ * @param {string} task @param {string} purpose @param {NodeJS.ProcessEnv} env @param {Date} now
36
+ * @param {string | null} row */
37
+ export function ownerRecord(task, purpose, env, now, row = null) {
36
38
  const lane = env.WS_LANE_NAME || null;
39
+ let receiptOffset = null;
40
+ try { receiptOffset = statSync(env.WS_LANE_RECEIPTS ?? join(homedir(), '.cache/wildshard/lane-receipts.log')).size; }
41
+ catch (error) { if (error instanceof Error && 'code' in error && error.code === 'ENOENT') receiptOffset = 0; }
37
42
  return {
38
43
  task,
39
- session: env.CLAUDE_SESSION_ID || env.CLAUDE_CODE_SESSION_ID || lane,
44
+ session: env.CODEX_THREAD_ID || env.CLAUDE_SESSION_ID || env.CLAUDE_CODE_SESSION_ID || lane,
40
45
  lane,
41
46
  pane: env.HERDR_PANE_ID || null,
47
+ agent: env.CODEX_THREAD_ID ? 'codex' : env.CLAUDE_SESSION_ID || env.CLAUDE_CODE_SESSION_ID ? 'claude' : lane ? 'codex' : 'unknown',
48
+ row,
49
+ receiptOffset,
42
50
  started: now.toISOString(),
43
51
  purpose,
44
52
  };
@@ -52,21 +60,29 @@ function readOwner(path) {
52
60
  /** Make <root>/tmp/<task>/ and its .owner; returns the folder's absolute path. Throws on a refused name, an empty
53
61
  * purpose, or a folder that exists and is not this session's.
54
62
  * @param {string} task @param {string} purpose
55
- * @param {{root?: string, env?: NodeJS.ProcessEnv, now?: Date}} [options] */
56
- export function scratchDir(task, purpose, { root = ROOT, env = process.env, now = new Date() } = {}) {
63
+ * @param {{root?: string, env?: NodeJS.ProcessEnv, now?: Date, row?: string | null}} [options] */
64
+ export function scratchDir(task, purpose, { root = ROOT, env = process.env, now = new Date(), row = null } = {}) {
57
65
  const refusal = refuseTask(task);
58
66
  if (refusal) throw new Error(refusal);
59
67
  if (typeof purpose !== 'string' || purpose.trim() === '') throw new Error('a purpose is required');
60
68
  const tmp = join(resolve(root), 'tmp');
61
69
  const dir = join(tmp, task);
62
- const owner = ownerRecord(task, purpose.trim(), env, now);
70
+ if (row !== null && !/^[A-Z][A-Z0-9-]*\d+[a-z]?$/u.test(row)) throw new Error(`row "${row}" is not a plan row`);
71
+ const owner = ownerRecord(task, purpose.trim(), env, now, row);
63
72
  mkdirSync(tmp, { recursive: true });
64
73
  try {
65
74
  mkdirSync(dir);
66
75
  } catch (error) {
67
76
  if (!(error instanceof Error && 'code' in error && error.code === 'EEXIST')) throw error;
68
77
  const existing = readOwner(join(dir, '.owner'));
69
- if (existing && owner.session && existing.session === owner.session) return dir;
78
+ if (existing && owner.session && existing.session === owner.session) {
79
+ // A lane name can outlive a task. Advance its cursor when it resumes,
80
+ // without ever exposing a half-written ownership record.
81
+ const next = join(dir, `.owner-${process.pid}`);
82
+ writeFileSync(next, `${JSON.stringify(owner, null, 2)}\n`, { flag: 'wx' });
83
+ renameSync(next, join(dir, '.owner'));
84
+ return dir;
85
+ }
70
86
  throw new Error(existing
71
87
  ? `${dir} already belongs to session ${String(existing.session)}; pick another task name`
72
88
  : `${dir} already exists with no .owner; pick another task name`);
@@ -82,12 +98,15 @@ export function scratchDir(task, purpose, { root = ROOT, env = process.env, now
82
98
 
83
99
  if (import.meta.url === pathToFileURL(process.argv[1] ?? '').href) {
84
100
  const [task = '', purpose = '', ...rest] = process.argv.slice(2);
85
- if (rest.length > 0 || task === '--help' || task === '-h') {
86
- console.error('usage: node scripts/scratch-dir.mjs <task> "<purpose>"');
101
+ const rowAt = rest.indexOf('--row');
102
+ const row = rowAt === -1 ? null : rest[rowAt + 1] ?? null;
103
+ const other = rowAt === -1 ? rest : rest.filter((_, index) => index !== rowAt && index !== rowAt + 1);
104
+ if (other.length > 0 || task === '--help' || task === '-h' || rowAt !== -1 && row === null) {
105
+ console.error('usage: node scripts/scratch-dir.mjs <task> "<purpose>" [--row <plan-row>]');
87
106
  process.exit(2);
88
107
  }
89
108
  try {
90
- console.log(scratchDir(task, purpose));
109
+ console.log(scratchDir(task, purpose, { row }));
91
110
  } catch (error) {
92
111
  console.error(`scratch-dir: ${error instanceof Error ? error.message : String(error)}`);
93
112
  process.exit(1);