@wildshard/engine 0.1.22 → 0.1.24
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 +15 -0
- package/index.html +17 -4
- package/lint/engine-sides.json +9 -0
- package/lint/sim-players.json +2 -13
- package/package.json +36 -3
- package/scripts/apfs-clone.mjs +5 -2
- package/scripts/app-build/catalogue.ts +39 -8
- package/scripts/app-build/serviceWorker.ts +4 -1
- package/scripts/app-build/splitOutput.mjs +33 -11
- package/scripts/app-build/titlePreloads.mjs +8 -5
- package/scripts/bake-road-surfaces.entry.ts +18 -0
- package/scripts/bake-road-surfaces.mjs +44 -0
- package/scripts/changelog.mjs +2 -1
- package/scripts/ci-pack.mjs +3 -3
- package/scripts/engine-ci-shard.mjs +11 -0
- package/scripts/fight-page-census.mjs +131 -0
- package/scripts/goldens/board.py +44 -11
- package/scripts/goldens/capture.mjs +18 -6
- package/scripts/goldens/native-residency.d.mts +2 -0
- package/scripts/goldens/native-residency.mjs +31 -4
- package/scripts/grid-road-lag.mjs +209 -0
- package/scripts/keep-copy.mjs +172 -0
- package/scripts/land.d.mts +4 -1
- package/scripts/land.mjs +121 -9
- package/scripts/lane-live.mjs +136 -0
- package/scripts/leftovers-report.mjs +47 -0
- package/scripts/loading-card-proof.mjs +42 -9
- package/scripts/loading-flow/benchmax.mjs +59 -7
- package/scripts/loading-flow/stalls.d.mts +2 -0
- package/scripts/loading-flow/stalls.mjs +13 -0
- package/scripts/map-hash.mjs +1 -1
- package/scripts/mmo-bots.mjs +5 -3
- package/scripts/mmo-grid-proof.mjs +74 -0
- package/scripts/mmo-seat-proof.mjs +43 -0
- package/scripts/nightly-heads.ts +13 -13
- package/scripts/nightly-model.ts +26 -12
- package/scripts/nightly-tag.mjs +2 -4
- package/scripts/nightly.proof.ts +18 -5
- package/scripts/nightly.ts +13 -8
- package/scripts/no-astc-boot.mjs +77 -0
- package/scripts/page-release/content.mjs +19 -10
- package/scripts/page-release/flow.d.mts +3 -2
- package/scripts/page-release/flow.mjs +31 -21
- package/scripts/page-release/packs.d.mts +5 -0
- package/scripts/page-release/packs.mjs +13 -3
- package/scripts/page-release/preview.d.mts +2 -0
- package/scripts/page-release/preview.mjs +74 -0
- package/scripts/page-release.mjs +13 -5
- package/scripts/physics-route.json +6 -6
- package/scripts/pins-reuse.mjs +1 -0
- package/scripts/pins-staging.ts +54 -0
- package/scripts/pins.ts +5 -0
- package/scripts/ring3.proof.ts +71 -0
- package/scripts/ring3.ts +100 -0
- package/scripts/road-drive-proof.mjs +269 -0
- package/scripts/road-memory-probe.mjs +129 -0
- package/scripts/scratch-dir.mjs +33 -14
- package/scripts/scratch-sweep.mjs +15 -23
- package/scripts/server-release/github.mjs +59 -26
- package/scripts/server-release/items.d.mts +7 -0
- package/scripts/server-release/items.mjs +28 -0
- package/scripts/server-release/publish.mjs +24 -2
- package/scripts/server-release/sign.mjs +8 -4
- package/scripts/side-parity.mjs +1 -1
- package/scripts/test-products.json +1 -0
- package/scripts/test_prebuilt_output.py +3 -1
- package/scripts/tsconfig.json +2 -0
- package/scripts/turn-in-shots.mjs +83 -0
- package/scripts/vitest-bench-observe-proof.py +168 -0
- package/scripts/vitest-bench.py +122 -77
- package/scripts/vitest-ci-files.ts +5 -1
- package/scripts/vps/rebuild.sh +3 -1
- package/scripts/vps/wildshard-config +106 -1
- package/scripts/warm-native-chrome.mjs +9 -3
- package/scripts/worker-client-fights.mjs +9 -3
- package/scripts/worktree-reap.mjs +36 -140
- package/scripts/worktree.mjs +92 -12
- package/scripts/zone-gate-proof.mjs +93 -0
- package/src/client/engine/audio/audioLog.ts +7 -2
- package/src/client/engine/boot/diagnostics.ts +69 -1
- package/src/client/engine/boot/sw.ts +3 -1
- package/src/client/engine/core/ktx2.ts +33 -10
- package/src/client/engine/core/ktx2Zstd.ts +2 -1
- package/src/client/engine/models/place.ts +7 -5
- package/src/client/engine/pwa/sw.js +83 -10
- package/src/client/engine/render/dataLook.ts +14 -7
- package/src/client/engine/render/lookLight.ts +64 -20
- package/src/client/engine/render/precompile.ts +6 -0
- package/src/client/engine/render/tiers.ts +9 -0
- package/src/client/engine/ui/Loading.ts +6 -8
- package/src/client/engine/ui/lookLightOption.ts +1 -1
- package/src/client/engine/ui/playerReload.ts +5 -5
- package/src/client/game/audio/cueDirector.ts +2 -1
- package/src/client/game/boot/bytes.generated.ts +4 -1
- package/src/client/game/boot/versions.generated.ts +8 -5
- package/src/client/game/boss/arenaRoom.ts +4 -3
- package/src/client/game/boss/roamingProjection.ts +1 -1
- package/src/client/game/devScene/hook.ts +1 -1
- package/src/client/game/devScene/liveLook.ts +1 -1
- package/src/client/game/grid/cellClip.ts +70 -6
- package/src/client/game/grid/dataCellKit.ts +9 -1
- package/src/client/game/grid/gateCard.css +9 -0
- package/src/client/game/grid/gateCard.ts +67 -0
- package/src/client/game/grid/live.ts +17 -3
- package/src/client/game/grid/liveSession.ts +15 -5
- package/src/client/game/grid/neighbourLife.ts +10 -1
- package/src/client/game/grid/neighbourPanels.ts +29 -2
- package/src/client/game/grid/pageEntry.ts +21 -0
- package/src/client/game/grid/products.ts +21 -7
- package/src/client/game/grid/regionalWorld.ts +5 -0
- package/src/client/game/grid/roadCompressedSurfaces.ts +69 -0
- package/src/client/game/grid/roadLook.ts +5 -73
- package/src/client/game/grid/roadLookPlatform.ts +11 -6
- package/src/client/game/grid/roadSurfaceMaps.ts +80 -0
- package/src/client/game/grid/roadTilePool.ts +4 -0
- package/src/client/game/grid/session.ts +58 -16
- package/src/client/game/grid/softWallLook.ts +6 -1
- package/src/client/game/plugin/ui.ts +3 -0
- package/src/client/game/population/signals.ts +1 -1
- package/src/client/game/quest/chapterDirector.ts +1 -0
- package/src/client/game/session/play.ts +3 -0
- package/src/client/game/shardfile/clientBossTelegraph.ts +4 -3
- package/src/client/game/shardfile/clientSource.ts +5 -2
- package/src/client/game/shardfile/clientWorker.ts +25 -8
- package/src/client/game/shardfile/look.ts +1 -1
- package/src/client/game/shardfile/runtimeProduct.ts +9 -5
- package/src/client/game/shardfile/slabLibrary.ts +37 -0
- package/src/client/game/shardfile/slabRanges.ts +145 -0
- package/src/client/game/shardfile/wirePage.ts +5 -2
- package/src/client/game/shardfile/worldSceneTextures.ts +15 -9
- package/src/client/host/online/shell.ts +2 -2
- package/src/client/host/standalone/shell.ts +4 -1
- package/src/cook/game/cookWorker.ts +8 -5
- package/src/cook/game/tierTextures.ts +5 -3
- package/src/server/engine/net/simWorld.ts +3 -4
- package/src/server/game/grid/cellHome.ts +58 -0
- package/src/server/game/grid/simulation.ts +32 -8
- package/src/server/game/plugin/mover.ts +18 -14
- package/src/server/game/plugin/simulation.ts +2 -0
- package/src/server/game/shardfile/dataRespawn.ts +47 -0
- package/src/server/game/shardfile/declaredKitItems.ts +31 -7
- package/src/server/host/bake/headlessWorker.ts +3 -3
- package/src/server/host/dedicated/cellWorker.ts +4 -2
- package/src/server/host/dedicated/main.ts +7 -4
- package/src/server/host/dedicated/packReader.ts +15 -2
- package/src/server/host/dedicated/playerStore.ts +1 -1
- package/src/server/host/headlessRuntime.ts +11 -6
- package/src/server/host/standalone/cellWorld.ts +20 -6
- package/src/server/host/standalone/gridServer.ts +20 -6
- package/src/server/host/standalone/roadWorld.ts +36 -0
- package/src/server/host/standalone/serverHost.ts +2 -2
- package/src/shared/engine/entities/AnimalSim.ts +10 -0
- package/src/shared/engine/physics/gridBorders.ts +15 -1
- package/src/shared/engine/physics/transferWalls.ts +9 -4
- package/src/shared/engine/sim/snapshot.ts +5 -5
- package/src/shared/game/grid/allocator.ts +8 -1
- package/src/shared/game/grid/gateCount.ts +27 -0
- package/src/shared/game/grid/zoneWalls.ts +64 -0
- package/src/shared/game/ledger.ts +13 -4
- package/src/shared/game/loot/platformCatalogue.ts +14 -0
- package/src/shared/game/quest/ledger.ts +3 -3
- package/src/shared/game/shardfile/items.ts +9 -1
- package/src/shared/game/strings.ts +2 -0
- package/src/shared/host/headlessJourney.ts +3 -3
- package/src/shared/host/headlessTape.ts +7 -6
- package/src/shared/host/releaseRows.ts +4 -1
- package/src/shared/host/standalone/harnessPlace.ts +4 -0
- package/src/test/engine/simState.ts +134 -0
- package/src/test/game/builtProduct.ts +6 -0
- package/src/test/game/headless/admittedProductCache.ts +61 -0
- package/src/test/game/headless/checkedReplayPipeline.ts +21 -0
- package/src/test/game/headless/nativeBounds.ts +27 -0
- package/src/test/game/headless/processUsage.ts +22 -0
- package/src/test/game/headless/productSession.ts +39 -0
- package/src/test/game/headless/ropeBodies.ts +60 -0
- package/src/test/game/headless/worker.ts +34 -0
- package/src/test/game/headlessNative.ts +114 -0
- package/src/test/game/headlessWorker.ts +43 -0
- package/src/test/tsconfig.game.json +3 -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.d.mts
CHANGED
|
@@ -2,7 +2,10 @@ import type { SpawnSyncReturns } from 'node:child_process';
|
|
|
2
2
|
|
|
3
3
|
export const LAND_WORKFLOWS: readonly string[];
|
|
4
4
|
export function githubSlug(remote: string): string | null;
|
|
5
|
-
export function parseArgs(argv: string[]): { pollSeconds: number; timeoutMinutes: number; appearMinutes: number; rounds: number;
|
|
5
|
+
export function parseArgs(argv: string[]): { pollSeconds: number; timeoutMinutes: number; appearMinutes: number; rounds: number; keep: boolean; preflight: boolean };
|
|
6
|
+
export function preflightSteps(files: string[]): [string, string[]][];
|
|
7
|
+
export const CHECK_CSS: string;
|
|
8
|
+
export const PINS_LEDGER: string;
|
|
6
9
|
export function classifyRebase(cwd: string, range: { tested: string; base: string; head: string; main: string }): { rule: 'carried' | 'rerun'; reason: string; stamp?: boolean };
|
|
7
10
|
export function shaVerdict(data: unknown, sha: string): { state: 'pending' | 'green' | 'red'; runs: Record<string, { id: number; status: string; conclusion: string | null; branch: string; url: string; attempt: number }>; summary: string };
|
|
8
11
|
export function failedJobs(data: unknown): { blocking: string[]; nonblocking: string[] };
|
package/scripts/land.mjs
CHANGED
|
@@ -13,8 +13,13 @@
|
|
|
13
13
|
// 6. Fast-forward the canonical checkout when it is on main and clean (J247, WL7).
|
|
14
14
|
// 7. A `landed` receipt; main-watch follows main's own `ci` and reports it (LS5).
|
|
15
15
|
// 8. Delete origin's plan branch and remove this worktree (--keep skips it).
|
|
16
|
+
// Before gen:inputs, a worktree that never ran `pnpm pins` runs it. Before step 2's push, a preflight runs lint:game,
|
|
17
|
+
// check-css, typecheck and the Vitest files related to the branch's changed code,
|
|
18
|
+
// here, and stops on the first red with its log (BUILD-MAX 2026-11-15: 14 of 22 stopped lands failed a check that runs
|
|
19
|
+
// locally, each after a push and a wait). --no-preflight skips it.
|
|
16
20
|
// Main's CI runs after every landing; if it goes red, the lane that landed last fixes it forward or reverts it.
|
|
17
21
|
import {execFileSync,spawn,spawnSync} from 'node:child_process';
|
|
22
|
+
import {keepCopy,worktreeState} from './keep-copy.mjs';
|
|
18
23
|
import {appendFileSync,existsSync,linkSync,lstatSync,mkdirSync,mkdtempSync,readFileSync,readdirSync,realpathSync,renameSync,rmSync,writeFileSync} from 'node:fs';
|
|
19
24
|
import {homedir} from 'node:os';
|
|
20
25
|
import {dirname,join,resolve} from 'node:path';
|
|
@@ -87,6 +92,24 @@ function gitTee(cwd,args,env){
|
|
|
87
92
|
const git=(cwd,args,env=process.env)=>execFileSync('git',args,{cwd,env,encoding:'utf8',stdio:['ignore','pipe','pipe'],maxBuffer:64<<20}).trim();
|
|
88
93
|
/** @param {string} cwd @param {string[]} args @param {NodeJS.ProcessEnv} [env] */
|
|
89
94
|
const tryGit=(cwd,args,env=process.env)=>spawnSync('git',args,{cwd,env,encoding:'utf8',maxBuffer:64<<20});
|
|
95
|
+
|
|
96
|
+
/** WL12: a recent small branch merits a mode reminder, never a refusal.
|
|
97
|
+
* Reflog selectors carry branch-event time; commit time can predate branch creation.
|
|
98
|
+
* Missing/expired local reflogs cannot establish age and produce no warning.
|
|
99
|
+
* @param {string} root @param {string} branch @param {number} [now] @returns {string|null} */
|
|
100
|
+
export function smallPlanWarning(root,branch,now=Date.now()){
|
|
101
|
+
if(!PLAN_BRANCH.test(branch))return null;
|
|
102
|
+
const count=tryGit(root,['rev-list','--count',`origin/main..${branch}`]);
|
|
103
|
+
if(count.status!==0)return null;
|
|
104
|
+
const commits=Number(count.stdout.trim());
|
|
105
|
+
if(!Number.isSafeInteger(commits)||commits<1||commits>3)return null;
|
|
106
|
+
const history=tryGit(root,['reflog','show','--date=unix','--format=%gD%x09%gs',`refs/heads/${branch}`]);
|
|
107
|
+
if(history.status!==0)return null;
|
|
108
|
+
const first=history.stdout.trim().split('\n').at(-1)??'';
|
|
109
|
+
const created=Number(/@\{(\d+)\}\tbranch: Created from .+$/u.exec(first)?.[1])*1000,age=now-created;
|
|
110
|
+
if(!Number.isFinite(created)||!Number.isFinite(age)||age<0||age>=3*60*60*1000)return null;
|
|
111
|
+
return `WARNING one-row land (J290): commit on main next time (${commits} commit${commits===1?'':'s'}, ${Math.floor(age/60_000)} min old; J336: land a whole plan once)`;
|
|
112
|
+
}
|
|
90
113
|
/** A ref lock another git process holds or just moved: worktrees share refs, so two lands fetching main at once race
|
|
91
114
|
* for refs/remotes/origin/main ("cannot lock ref ...: is at X but expected Y", engine run 43332891983), and any git
|
|
92
115
|
* may hold packed-refs.lock for a moment. Only these are retried; every other git failure stops as before. */
|
|
@@ -108,6 +131,22 @@ const isAncestor=(cwd,ancestor,descendant)=>tryGit(cwd,['merge-base','--is-ances
|
|
|
108
131
|
/** @param {string} cwd @param {string} from @param {string} to */
|
|
109
132
|
const short=(/** @type {string} */ sha)=>sha.slice(0,10);
|
|
110
133
|
|
|
134
|
+
/** CI's `check css` (scripts/ci-static.sh). A tree without it (a fixture, another repo's land) skips the step. */
|
|
135
|
+
export const CHECK_CSS='scripts/check-css.mjs';
|
|
136
|
+
/** What `pnpm pins` leaves (scripts/pins.ts LEDGER). Without it gen.mjs --inputs-only fails, so land runs pins first. */
|
|
137
|
+
export const PINS_LEDGER='out/.pins.json';
|
|
138
|
+
|
|
139
|
+
/** The preflight's checks, in order, as [name, argv], for a branch whose diff from main is `files` (BUILD-MAX 2026-11-15).
|
|
140
|
+
* check-css is a check CI's static job runs and the pre-push does not (it cost opus-gcm11 a 27-minute re-run). Vitest
|
|
141
|
+
* runs only when code changed, on the tests related to that code (`vitest related`, which includes a changed test itself).
|
|
142
|
+
* @param {string[]} files @returns {[string,string[]][]} */
|
|
143
|
+
export function preflightSteps(files){
|
|
144
|
+
const code=files.filter(file=>/^(?:src|test|scripts)\/.+\.[cm]?[jt]sx?$/u.test(file));
|
|
145
|
+
/** @type {[string,string[]][]} */const steps=[['lint:game',['pnpm','lint:game']],['check-css',['node',CHECK_CSS]],['typecheck',['pnpm','typecheck']]];
|
|
146
|
+
if(code.length>0)steps.push(['vitest',['pnpm','exec','vitest','related','--run','--passWithNoTests',...code]]);
|
|
147
|
+
return steps;
|
|
148
|
+
}
|
|
149
|
+
|
|
111
150
|
/** `owner/name` of a GitHub remote URL, or null.
|
|
112
151
|
* @param {string} remote */
|
|
113
152
|
export function githubSlug(remote){
|
|
@@ -118,7 +157,7 @@ export function githubSlug(remote){
|
|
|
118
157
|
/** Refuse anything but the known options. Any spelling of force is refused by name.
|
|
119
158
|
* @param {string[]} argv */
|
|
120
159
|
export function parseArgs(argv){
|
|
121
|
-
const options={pollSeconds:30,timeoutMinutes:60,appearMinutes:5,rounds:5,keep:false};
|
|
160
|
+
const options={pollSeconds:30,timeoutMinutes:60,appearMinutes:5,rounds:5,keep:false,preflight:true};
|
|
122
161
|
for(const arg of argv){
|
|
123
162
|
if(/^-f$|force/iu.test(arg))throw new StopError(`refused ${arg}: land never force-pushes main (J240: fast-forward only). If main moved, land rebases and retries by itself`);
|
|
124
163
|
const [name,value]=arg.split('=',2);
|
|
@@ -126,11 +165,12 @@ export function parseArgs(argv){
|
|
|
126
165
|
// --no-watch-main is accepted for old callers: land never watches main now (LS8).
|
|
127
166
|
if(name==='--no-watch-main'&&value===undefined)continue;
|
|
128
167
|
if(name==='--keep'&&value===undefined)options.keep=true;
|
|
168
|
+
else if(name==='--no-preflight'&&value===undefined)options.preflight=false;
|
|
129
169
|
else if(value!==undefined&&Number.isFinite(number)&&number>0&&name==='--poll')options.pollSeconds=number;
|
|
130
170
|
else if(value!==undefined&&Number.isFinite(number)&&number>0&&name==='--timeout')options.timeoutMinutes=number;
|
|
131
171
|
else if(value!==undefined&&Number.isFinite(number)&&number>0&&name==='--appear')options.appearMinutes=number;
|
|
132
172
|
else if(value!==undefined&&Number.isSafeInteger(number)&&number>0&&name==='--rounds')options.rounds=number;
|
|
133
|
-
else throw new StopError(`unknown option ${arg}; usage: node scripts/land.mjs [--poll=SECONDS] [--timeout=MINUTES] [--appear=MINUTES] [--rounds=N] [--keep]`);
|
|
173
|
+
else throw new StopError(`unknown option ${arg}; usage: node scripts/land.mjs [--poll=SECONDS] [--timeout=MINUTES] [--appear=MINUTES] [--rounds=N] [--keep] [--no-preflight]`);
|
|
134
174
|
}
|
|
135
175
|
return options;
|
|
136
176
|
}
|
|
@@ -159,8 +199,8 @@ function ghApi(repo,path){
|
|
|
159
199
|
}
|
|
160
200
|
|
|
161
201
|
/** J193/J200: `quarantine (n)` jobs run quarantined files with their ordinary exit code and are continue-on-error;
|
|
162
|
-
* they are red by design until rewritten and never block a landing.
|
|
163
|
-
const NONBLOCKING_JOB=/^
|
|
202
|
+
* they are red by design until rewritten and never block a landing. Boundaries blocks after TS15's green soak. */
|
|
203
|
+
const NONBLOCKING_JOB=/^quarantine(?: \(\d+\))?$/u;
|
|
164
204
|
const FAILED=new Set(['failure','timed_out','cancelled','startup_failure']);
|
|
165
205
|
|
|
166
206
|
/** A run's failed jobs, split into the blocking ones and the non-blocking quarantine ones.
|
|
@@ -309,6 +349,7 @@ class Landing{
|
|
|
309
349
|
/** @type {string|null} */this.planTip=null;
|
|
310
350
|
this.expected='';
|
|
311
351
|
/** @type {string|null} */this.landedSha=null;
|
|
352
|
+
/** @type {string|null} */this.sizeWarning=null;
|
|
312
353
|
}
|
|
313
354
|
|
|
314
355
|
/** @type {(why:string)=>void} */
|
|
@@ -714,12 +755,52 @@ class Landing{
|
|
|
714
755
|
throw new StopError(`main push of ${short(head)} failed and main did not move: ${result.stdout.trim()}\nA red pre-push names its failing check above; fix forward and run land again.`);
|
|
715
756
|
}
|
|
716
757
|
|
|
758
|
+
/** lint:game, typecheck and the related Vitest files, here, before anything is pushed; the first red stops land with
|
|
759
|
+
* its log. The logs live in this worktree's git dir, so they never dirty the tree and go when the worktree does.
|
|
760
|
+
* @param {string} main */
|
|
761
|
+
localChecks(main){
|
|
762
|
+
if(!this.options.preflight){this.say('preflight','skipped (--no-preflight)');return;}
|
|
763
|
+
const head=this.head(),files=git(this.root,['diff','--name-only','--no-renames',`${main}...${head}`]).split('\n').filter(Boolean);
|
|
764
|
+
const dir=resolve(this.root,git(this.root,['rev-parse','--git-path','land-preflight']));
|
|
765
|
+
mkdirSync(dir,{recursive:true});
|
|
766
|
+
for(const [name,[command,...args]] of preflightSteps(files)){
|
|
767
|
+
if(command==='node'&&!existsSync(join(this.root,args[0]??''))){this.say('preflight',`${name} skipped: no ${args[0]} here`);continue;}
|
|
768
|
+
const log=join(dir,`${short(head)}-${name.replace(':','-')}.log`),began=Date.now();
|
|
769
|
+
this.say('preflight',`${name} on ${short(head)}`);
|
|
770
|
+
const ran=spawnSync(command==='node'?process.execPath:command??'pnpm',args,{cwd:this.root,env:this.env,encoding:'utf8',stdio:['ignore','pipe','pipe'],maxBuffer:256<<20});
|
|
771
|
+
writeFileSync(log,`$ ${command} ${args.join(' ')}\n${ran.stdout??''}${ran.stderr??''}${ran.error===undefined?'':`\n${String(ran.error)}\n`}`);
|
|
772
|
+
if(ran.status!==0){
|
|
773
|
+
this.receipt(`STOP preflight ${name} red on ${short(head)}, nothing pushed: ${log}`);
|
|
774
|
+
throw new StopError(`preflight ${name} is red on ${short(head)}; nothing was pushed. Log: ${log}\nFix it on ${this.branch} and run land again (--no-preflight skips the preflight).`);
|
|
775
|
+
}
|
|
776
|
+
this.say('preflight',`${name} green in ${String(Math.round((Date.now()-began)/1000))} s`);
|
|
777
|
+
}
|
|
778
|
+
}
|
|
779
|
+
|
|
780
|
+
/** A worktree that never ran `pnpm pins` has no PINS_LEDGER, and gen:inputs fails on it (opus-gcm11, 2026-11-15). Run it
|
|
781
|
+
* once, before gen:inputs; with or without --no-preflight, since gen:inputs needs it either way. */
|
|
782
|
+
pinsOnce(){
|
|
783
|
+
/** @type {{pins?:string}} */let scripts={};
|
|
784
|
+
try{scripts=JSON.parse(readFileSync(join(this.root,'package.json'),'utf8')).scripts??{};}catch{return;}
|
|
785
|
+
if(scripts.pins===undefined||existsSync(join(this.root,PINS_LEDGER)))return;
|
|
786
|
+
this.say('pins',`no ${PINS_LEDGER}: this worktree never ran pnpm pins; running it before gen:inputs`);
|
|
787
|
+
const ran=spawnSync('pnpm',['--silent','pins'],{cwd:this.root,env:this.env,encoding:'utf8',stdio:['ignore','pipe','pipe'],maxBuffer:256<<20});
|
|
788
|
+
if(ran.status!==0){
|
|
789
|
+
const why=`${ran.stderr??''}${ran.stdout??''}`.trim().split('\n').slice(-3).join(' | ')||String(ran.error??`exit ${String(ran.status)}`);
|
|
790
|
+
this.receipt(`STOP pnpm pins failed before gen:inputs: ${why}`);
|
|
791
|
+
throw new StopError(`pnpm pins failed in ${this.root} (gen:inputs needs its outputs); nothing was pushed: ${why}`);
|
|
792
|
+
}
|
|
793
|
+
this.say('pins',`pnpm pins done; ${PINS_LEDGER} written`);
|
|
794
|
+
}
|
|
795
|
+
|
|
717
796
|
async run(){
|
|
718
797
|
const stamps=this.clean();
|
|
719
798
|
const start=this.head();this.expected=start;
|
|
720
799
|
let main=this.fetchMain();
|
|
721
800
|
if(start===main||isAncestor(this.root,start,main)){this.say('nothing',`${this.branch} ${short(start)} has nothing main lacks`);return 0;}
|
|
722
801
|
this.say('start',`${this.branch} ${short(start)} -> main ${short(main)} (repo ${this.repo})`);
|
|
802
|
+
this.sizeWarning=smallPlanWarning(this.root,this.branch);
|
|
803
|
+
if(this.sizeWarning!==null){this.say('warning',this.sizeWarning);this.receipt(`small-plan warning: ${this.sizeWarning}`);}
|
|
723
804
|
// An install a stopped land owed (its rebase had already moved HEAD) runs before anything else (J206 review).
|
|
724
805
|
if(existsSync(this.installMarker()))this.install(['an earlier land\'s rebase']);
|
|
725
806
|
// DS22: gen:inputs rewrites the stamps from the tree after the rebase, so their stale bytes never block it.
|
|
@@ -732,7 +813,9 @@ class Landing{
|
|
|
732
813
|
this.rebase(main);
|
|
733
814
|
if(this.head()===main){this.say('nothing',`every commit on ${this.branch} is already on main`);return 0;}
|
|
734
815
|
}
|
|
816
|
+
this.pinsOnce();
|
|
735
817
|
this.regenerate();
|
|
818
|
+
this.localChecks(main);
|
|
736
819
|
/** @type {{sha:string,base:string}|null} */let tested=null;
|
|
737
820
|
let needHosted=true,rule='exact',why='main had not moved since the hosted run';
|
|
738
821
|
for(let round=1;round<=this.options.rounds;round++){
|
|
@@ -825,16 +908,45 @@ class Landing{
|
|
|
825
908
|
const deleted=tryGit(this.root,['push','--quiet',`--force-with-lease=refs/heads/${this.branch}:${this.planTip}`,'origin','--delete',this.branch]);
|
|
826
909
|
parts.push(deleted.status===0?`origin ${this.branch} deleted`:`origin ${this.branch} kept (${deleted.stderr.trim().split('\n').at(-1)??'push refused'})`);
|
|
827
910
|
}
|
|
828
|
-
const
|
|
911
|
+
const dirtyResult=tryGit(this.root,['status','--porcelain','--untracked-files=all']);
|
|
912
|
+
const dirty=dirtyResult.stdout.trimEnd();
|
|
913
|
+
const generatedOnly=dirty!==''&&dirty.split('\n').every(line=>/^[ MAD?]{2} (?:[^"\n]+\.generated\.ts|public\/assets\/gpu\/[^"\n]+)$/u.test(line));
|
|
914
|
+
const patchBefore=tryGit(this.root,['diff','--binary','HEAD']);
|
|
829
915
|
const now=tryGit(this.root,['symbolic-ref','--quiet','HEAD']).stdout.trim(),at=tryGit(this.root,['rev-parse','HEAD']).stdout.trim();
|
|
830
916
|
if(now!==`refs/heads/${this.branch}`||at!==head)parts.push(`worktree kept: HEAD moved off ${this.branch} ${short(head)} after landing`);
|
|
831
|
-
else if(
|
|
917
|
+
else if(dirtyResult.status!==0||patchBefore.status!==0)parts.push('worktree kept: status unreadable');
|
|
918
|
+
else if(dirty!==''&&!generatedOnly)parts.push(`worktree kept: ${dirty.split('\n').length} uncommitted or untracked path(s)`);
|
|
832
919
|
else{
|
|
920
|
+
// J358's sole removal exception: this land owns this just-landed worktree.
|
|
921
|
+
// Copy first; any failure retains the source and its local branch.
|
|
922
|
+
let before;
|
|
923
|
+
try{
|
|
924
|
+
before=worktreeState(this.root);
|
|
925
|
+
const saved=keepCopy(this.root,{keepRoot:this.env.WS_SESSION_KEEP_ROOT});
|
|
926
|
+
this.say('copied',`recoverable worktree state saved at ${saved.dir}`);
|
|
927
|
+
}catch(error){
|
|
928
|
+
const line=parts.concat(`worktree kept: copy failed (${error instanceof Error?error.message:String(error)})`).join('; ');
|
|
929
|
+
this.say('cleaned',line);
|
|
930
|
+
return line;
|
|
931
|
+
}
|
|
932
|
+
const unchanged=()=>{try{return worktreeState(this.root)===before;}catch{return false;}};
|
|
933
|
+
if(!unchanged()){
|
|
934
|
+
const line=parts.concat('worktree kept: changed during copy').join('; ');
|
|
935
|
+
this.say('cleaned',line);return line;
|
|
936
|
+
}
|
|
833
937
|
// TEST-SPEED FL30: nothing started here may outlive the folder (an orphaned Vitest held the CPU slots).
|
|
834
938
|
let stopped=[];
|
|
835
|
-
try{stopped=stopWorktreeProcesses(realpathSync(this.root));}catch{
|
|
939
|
+
try{stopped=stopWorktreeProcesses(realpathSync(this.root));}catch{
|
|
940
|
+
const line=parts.concat('worktree kept: process cleanup failed').join('; ');
|
|
941
|
+
this.say('cleaned',line);return line;
|
|
942
|
+
}
|
|
836
943
|
if(stopped.length>0)parts.push(`stopped ${String(stopped.length)} process(es) still running there (pid ${stopped.join(', ')})`);
|
|
837
|
-
|
|
944
|
+
// Shutdown handlers may write after the copy. Protect their last writes.
|
|
945
|
+
if(!unchanged()){
|
|
946
|
+
const line=parts.concat('worktree kept: changed during process cleanup').join('; ');
|
|
947
|
+
this.say('cleaned',line);return line;
|
|
948
|
+
}
|
|
949
|
+
const removed=tryGit(canonical,['worktree','remove',...(generatedOnly?['--force']:[]),this.root]);
|
|
838
950
|
if(removed.status===0){
|
|
839
951
|
tryGitLocked(canonical,['update-ref','-d',`refs/heads/${this.branch}`,head],process.env,this.retry);
|
|
840
952
|
parts.push(`worktree and ${this.branch} removed; continue from ${canonical}`);
|
|
@@ -854,7 +966,7 @@ class Landing{
|
|
|
854
966
|
this.startWatcher(head);
|
|
855
967
|
this.say('rule',`main's own CI runs on ${short(head)} now. If it goes red, the lane that landed last fixes it forward or reverts it, at once (J249)`);
|
|
856
968
|
const seconds=Math.round((Date.now()-this.started)/1000);
|
|
857
|
-
this.receipt(`landed ${short(head)} on main (${short(before)}..${short(head)}); ${rule}; rounds ${round}; branch ci ${this.runs.join(', ')||'none'}; main ci ${rule==='carried'?'followed by main-watch':'reuses the branch run'}; ${seconds} s`);
|
|
969
|
+
this.receipt(`landed ${short(head)} on main (${short(before)}..${short(head)}); ${rule}; rounds ${round}; branch ci ${this.runs.join(', ')||'none'}; main ci ${rule==='carried'?'followed by main-watch':'reuses the branch run'}${this.sizeWarning===null?'':'; one-row'}; ${seconds} s`);
|
|
858
970
|
return 0;
|
|
859
971
|
}
|
|
860
972
|
}
|
|
@@ -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
|
+
}
|