@wildshard/sdk 0.2.10 → 0.2.11

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wildshard/sdk",
3
- "version": "0.2.10",
3
+ "version": "0.2.11",
4
4
  "description": "The author's toolbox: the `wildshard` CLI that bakes shard source into a shardfile, the author SDK, the local dev server (engine client against engine server), the explorers, arena and drafts tool.",
5
5
  "license": "UNLICENSED",
6
6
  "repository": {
@@ -48,20 +48,20 @@
48
48
  "drafts:test": "tsc -p drafts/tsconfig.json && tsc -p drafts/tools/tsconfig.json && vitest run drafts/test && node drafts/tools/atlas.ts --check",
49
49
  "typecheck": "pnpm typecheck:kit && pnpm typecheck:author",
50
50
  "lint": "node scripts/lint-dispatch.mjs --ignore-pattern 'scripts/chromium-keychain*' --ignore-pattern 'test/tooling/chrome-keychain.test.mjs'",
51
- "lint:kit": "oxlint -c src/.oxlintrc.json --type-aware --deny-warnings --ignore-pattern '.githooks/**' --ignore-pattern '.agents/**' --ignore-pattern 'tmp/**' --ignore-pattern 'vitest.config.ts' --ignore-pattern 'src/sharddev/**' --ignore-pattern 'src/commons/**' --ignore-pattern 'src/shards/**' --ignore-pattern 'public/**' --ignore-pattern 'scripts/**' --ignore-pattern 'test/**' --ignore-pattern 'drafts/**' --ignore-pattern 'lint/**' --ignore-pattern 'vite/**' --ignore-pattern 'bin/**' --no-error-on-unmatched-pattern",
52
- "lint:fix": "oxlint -c src/.oxlintrc.json --type-aware --fix --ignore-pattern '.githooks/**' --ignore-pattern '.agents/**' --ignore-pattern 'scripts/agent-parity.mjs' --ignore-pattern 'scripts/agent-sync.mjs' --ignore-pattern 'tmp/**' --ignore-pattern 'vitest.config.ts' --ignore-pattern 'src/sharddev/**' --ignore-pattern 'src/commons/**' --ignore-pattern 'src/shards/**' --ignore-pattern 'public/**' --ignore-pattern 'scripts/**' --ignore-pattern 'test/**' --ignore-pattern 'drafts/**' --ignore-pattern 'lint/**' --ignore-pattern 'vite/**' --ignore-pattern 'bin/**'",
53
- "format": "oxfmt -c src/.oxfmtrc.json src",
54
- "format:check": "oxfmt -c src/.oxfmtrc.json --check src",
51
+ "lint:kit": "node kit/scripts/lint.mjs --type-aware --deny-warnings --ignore-pattern '.githooks/**' --ignore-pattern '.agents/**' --ignore-pattern 'tmp/**' --ignore-pattern 'vitest.config.ts' --ignore-pattern 'src/sharddev/**' --ignore-pattern 'src/commons/**' --ignore-pattern 'src/shards/**' --ignore-pattern 'public/**' --ignore-pattern 'scripts/**' --ignore-pattern 'test/**' --ignore-pattern 'drafts/**' --ignore-pattern 'lint/**' --ignore-pattern 'vite/**' --ignore-pattern 'bin/**' --no-error-on-unmatched-pattern",
52
+ "lint:fix": "node kit/scripts/lint.mjs --type-aware --fix --ignore-pattern '.githooks/**' --ignore-pattern '.agents/**' --ignore-pattern 'scripts/agent-parity.mjs' --ignore-pattern 'scripts/agent-sync.mjs' --ignore-pattern 'tmp/**' --ignore-pattern 'vitest.config.ts' --ignore-pattern 'src/sharddev/**' --ignore-pattern 'src/commons/**' --ignore-pattern 'src/shards/**' --ignore-pattern 'public/**' --ignore-pattern 'scripts/**' --ignore-pattern 'test/**' --ignore-pattern 'drafts/**' --ignore-pattern 'lint/**' --ignore-pattern 'vite/**' --ignore-pattern 'bin/**'",
53
+ "format": "oxfmt -c kit/.oxfmtrc.json kit src",
54
+ "format:check": "oxfmt -c kit/.oxfmtrc.json --check kit src",
55
55
  "test": "pnpm test:kit && pnpm test:author",
56
56
  "test:ci": "node --test 'src/ci/**/*.test.ts'",
57
57
  "test:e2e": "playwright test --config src/e2e/playwright.config.ts",
58
- "check:asks": "node src/scripts/asks.mjs check",
58
+ "check:asks": "node kit/scripts/asks.mjs check",
59
59
  "check:agents": "node .githooks/agents-md.mjs lint",
60
60
  "check:parity": "node scripts/agent-parity.mjs --strict",
61
61
  "check:agent-sync": "node scripts/agent-sync.mjs --check",
62
62
  "test:agent-hooks": "node --test '.agents/hooks/test/*.test.mjs'",
63
63
  "agents:sync": "node scripts/agent-sync.mjs",
64
- "md:wrap": "node src/scripts/md-wrap.mjs",
64
+ "md:wrap": "node kit/scripts/md-wrap.mjs",
65
65
  "test:hooks": "node --test '.githooks/*.test.mjs'",
66
66
  "check": "pnpm typecheck && pnpm lint && pnpm format:check && pnpm test && pnpm check:asks && pnpm check:agents && pnpm check:agent-sync && pnpm test:agent-hooks && pnpm check:parity && node --check scripts/chromium-keychain-check.mjs && node --test test/tooling/chrome-keychain.test.mjs test/tooling/worktree-guard.test.mjs",
67
67
  "typecheck:kit": "tsc -p src/tsconfig.json && tsc -p src/web/tsconfig.json",
@@ -83,7 +83,7 @@
83
83
  "@types/three": "0.186.0",
84
84
  "@typescript/typescript6": "6.0.2",
85
85
  "@valibot/to-json-schema": "1.8.0",
86
- "@wildshard/engine": "0.1.17",
86
+ "@wildshard/engine": "0.1.18",
87
87
  "@wildshard/format": "npm:@wildshard/shard-format@0.4.9",
88
88
  "ajv": "6.15.0",
89
89
  "assemblyscript": "0.28.20",
@@ -35,6 +35,7 @@
35
35
  // every replaced byte, and nothing outside these paths is touched.
36
36
  // Exit 0 ok, 1 stale, invalid or refused, 2 usage.
37
37
  import { spawnSync } from 'node:child_process';
38
+ import { createHash } from 'node:crypto';
38
39
  import { chmodSync, existsSync, lstatSync, mkdirSync, readFileSync, readdirSync, readlinkSync, realpathSync, renameSync, rmSync, rmdirSync, statSync, symlinkSync, unlinkSync, writeFileSync } from 'node:fs';
39
40
  import { dirname, isAbsolute, join, relative, resolve } from 'node:path';
40
41
  import { pathToFileURL } from 'node:url';
@@ -283,6 +284,18 @@ export function kitFiles(kit) {
283
284
  export const kitSkills = (kit) => (isRealDir(join(kit, SKILLS)) ? readdirSync(join(kit, SKILLS)).filter((name) => isRealDir(join(kit, SKILLS, name))).sort() : []);
284
285
 
285
286
  const gitOut = (root, args) => spawnSync('git', ['-C', root, ...args], { encoding: 'utf8' });
287
+ /** A file's git blob id, as `git hash-object` gives it. */
288
+ const blobId = (bytes) => createHash('sha1').update(`blob ${bytes.length}\0`).update(bytes).digest('hex');
289
+ /**
290
+ * MA10 (e): every blob the kit's history held at any of `paths` (its current path and, for a moved file, the
291
+ * repo's old path), so a copy the stamp replaces reads as an older kit copy, not a local edit. Empty when the
292
+ * kit is not a git checkout.
293
+ */
294
+ function kitBlobs(kit, paths) {
295
+ const log = gitOut(kit, ['--literal-pathspecs', 'log', '--format=', '--raw', '--no-abbrev', '--no-renames', 'HEAD', '--', ...paths]);
296
+ if (log.status !== 0) return new Set();
297
+ return new Set(log.stdout.split('\n').flatMap((line) => line.startsWith(':') ? line.split(' ').slice(2, 4) : []).filter((id) => !/^0+$/u.test(id)));
298
+ }
286
299
 
287
300
  /** The first symlink at or above `rel` inside root, component by component, or null. */
288
301
  function linkOnPath(root, rel) {
@@ -362,7 +375,7 @@ const realOr = (path) => {
362
375
  * Stamp the kit's agent layout into a repo. Everything is checked before anything is written: the kit,
363
376
  * the repo's specs and manifests, every registration the new manifests would drop, symlinks on every
364
377
  * path it writes or removes, and uncommitted, untracked or ignored files under those paths.
365
- * @returns {{ changed: string[], replaced: string[], problems: string[] }}
378
+ * @returns {{ changed: string[], replaced: string[], older?: string[], problems: string[] }}
366
379
  */
367
380
  export function stamp(kitDir, rootDir) {
368
381
  const kit = resolve(kitDir);
@@ -428,11 +441,16 @@ export function stamp(kitDir, rootDir) {
428
441
  if (problems.length) return refuse(problems);
429
442
 
430
443
  const changed = new Set();
431
- // Copies the stamp replaces whose bytes differ from the kit's: git keeps the old bytes; the caller reviews them.
444
+ // Copies the stamp replaces whose bytes differ from the kit's: git keeps the old bytes. One the kit's history
445
+ // held is an older kit copy (`older`); any other is a local edit the caller reviews (`replaced`).
432
446
  const replaced = [];
447
+ const older = [];
448
+ const differs = (path, kitPath) => {
449
+ (kitBlobs(kit, [...new Set([kitPath, path])]).has(blobId(readFileSync(join(root, path)))) ? older : replaced).push(path);
450
+ };
433
451
  for (const path of legacy) {
434
452
  const want = join(kit, '.agents/hooks', path.slice('.claude/hooks/'.length));
435
- if (!existsSync(want) || !readFileSync(join(root, path)).equals(readFileSync(want))) replaced.push(path);
453
+ if (!existsSync(want) || !readFileSync(join(root, path)).equals(readFileSync(want))) differs(path, `.agents/hooks/${path.slice('.claude/hooks/'.length)}`);
436
454
  rmSync(join(root, path));
437
455
  changed.add(path);
438
456
  }
@@ -440,7 +458,7 @@ export function stamp(kitDir, rootDir) {
440
458
  for (const name of oldKitSkills) {
441
459
  const path = `${CLAUDE_SKILLS}/${name}`;
442
460
  for (const file of entriesUnder(root, path)) {
443
- if (!readFileSync(join(root, file)).equals(readFileSync(join(kit, SKILLS, name, relative(path, file))))) replaced.push(file);
461
+ if (!readFileSync(join(root, file)).equals(readFileSync(join(kit, SKILLS, name, relative(path, file))))) differs(file, `${SKILLS}/${name}/${relative(path, file)}`);
444
462
  changed.add(file);
445
463
  }
446
464
  rmSync(join(root, path), { recursive: true });
@@ -460,7 +478,7 @@ export function stamp(kitDir, rootDir) {
460
478
  const mode = statSync(from).mode & 0o777;
461
479
  const same = existsSync(to) && readFileSync(to).equals(bytes);
462
480
  if (!same || (statSync(to).mode & 0o777) !== mode) {
463
- if (existsSync(to) && !same) replaced.push(path);
481
+ if (existsSync(to) && !same) differs(path, path);
464
482
  mkdirSync(dirname(to), { recursive: true });
465
483
  writeFileSync(to, bytes);
466
484
  chmodSync(to, mode);
@@ -468,10 +486,10 @@ export function stamp(kitDir, rootDir) {
468
486
  }
469
487
  }
470
488
  const next = plan(root);
471
- if (next.problems.length) return { changed: [...changed].sort(), replaced, problems: next.problems };
489
+ if (next.problems.length) return { changed: [...changed].sort(), replaced, older, problems: next.problems };
472
490
  apply(root, next.actions);
473
491
  for (const action of next.actions) changed.add(action.path);
474
- return { changed: [...changed].sort(), replaced: [...new Set(replaced)].sort(), problems: [] };
492
+ return { changed: [...changed].sort(), replaced: [...new Set(replaced)].sort(), older: [...new Set(older)].sort(), problems: [] };
475
493
  }
476
494
 
477
495
  // ---------------------------------------------------------------- main
@@ -497,8 +515,9 @@ function main(argv) {
497
515
  }
498
516
  root = resolve(root);
499
517
  if (from) {
500
- const { changed, replaced, problems } = stamp(resolve(from), root);
518
+ const { changed, replaced, older = [], problems } = stamp(resolve(from), root);
501
519
  for (const path of changed) process.stdout.write(`stamped ${path}\n`);
520
+ for (const path of older) process.stdout.write(`updated ${path}: it was an older kit copy (its blob is in the kit's history)\n`);
502
521
  for (const path of replaced) process.stdout.write(`replaced ${path}: its bytes differed from the kit's; check git diff for a local edit\n`);
503
522
  for (const problem of problems) process.stderr.write(`agent-sync: ${problem}\n`);
504
523
  return problems.length ? 1 : 0;
@@ -1 +1 @@
1
- export const KEYCHAIN_ARGS: readonly ['--use-mock-keychain', '--password-store=basic'];
1
+ export const KEYCHAIN_ARGS: readonly ['--use-mock-keychain', '--password-store=basic', '--mute-audio'];
@@ -12,3 +12,5 @@ export function land(argv: string[], cwd?: string, env?: NodeJS.ProcessEnv): Pro
12
12
  export function flakyFiles(directory: string, jobNames: readonly string[]): string[] | null;
13
13
  export function strikePlans(book: string, file: string, now: number): string[];
14
14
  export function quarantineFile(path: string, file: string, owner: string, reason: string, now: number): boolean;
15
+ export const REF_LOCK: RegExp;
16
+ export function tryGitLocked(cwd: string, args: string[], env: NodeJS.ProcessEnv, onRetry?: (why: string) => void): import('node:child_process').SpawnSyncReturns<string>;
package/scripts/land.mjs CHANGED
@@ -89,6 +89,22 @@ export function loadLandConfig(root){
89
89
  const git=(cwd,args,env=process.env)=>execFileSync('git',args,{cwd,env,encoding:'utf8',stdio:['ignore','pipe','pipe'],maxBuffer:64<<20}).trim();
90
90
  /** @param {string} cwd @param {string[]} args @param {NodeJS.ProcessEnv} [env] */
91
91
  const tryGit=(cwd,args,env=process.env)=>spawnSync('git',args,{cwd,env,encoding:'utf8',maxBuffer:64<<20});
92
+ /** A ref lock another git process holds or just moved: worktrees share refs, so two lands fetching main at once race
93
+ * for refs/remotes/origin/main ("cannot lock ref ...: is at X but expected Y", engine run 43332891983), and any git
94
+ * may hold packed-refs.lock for a moment. Only these are retried; every other git failure stops as before. */
95
+ export const REF_LOCK=/cannot lock ref|Unable to create '[^']*\.lock': File exists/u;
96
+ const LOCK_WAITS_MS=[200,400,800,1600];
97
+ /** tryGit, tried again after a short backoff while git's only complaint is a ref lock (REF_LOCK). Only for git
98
+ * commands safe to repeat: a fetch or a ref update, never a push.
99
+ * @param {string} cwd @param {string[]} args @param {NodeJS.ProcessEnv} env @param {(why:string)=>void} [onRetry] */
100
+ export function tryGitLocked(cwd,args,env,onRetry){
101
+ for(let attempt=0;;attempt++){
102
+ const result=tryGit(cwd,args,env),wait=LOCK_WAITS_MS[attempt];
103
+ if(result.status===0||wait===undefined||!REF_LOCK.test(String(result.stderr)))return result;
104
+ onRetry?.(`git ${args[0]??''} lost a ref lock (${String(result.stderr).trim().split('\n')[0]??''}); retrying in ${String(wait)} ms`);
105
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,wait+Math.floor(Math.random()*wait/2));
106
+ }
107
+ }
92
108
  /** @param {string} cwd @param {string} ancestor @param {string} descendant */
93
109
  const isAncestor=(cwd,ancestor,descendant)=>tryGit(cwd,['merge-base','--is-ancestor',ancestor,descendant]).status===0;
94
110
  /** @param {string} cwd @param {string} from @param {string} to */
@@ -295,6 +311,9 @@ class Landing{
295
311
  /** @type {string|null} */this.landedSha=null;
296
312
  }
297
313
 
314
+ /** @type {(why:string)=>void} */
315
+ retry=why=>{this.say('retry',why);};
316
+
298
317
  /** @param {string} state @param {string} detail */
299
318
  say(state,detail){process.stdout.write(`land ${new Date().toISOString().slice(11,19)} ${state.padEnd(9)} ${detail}\n`);}
300
319
 
@@ -345,7 +364,7 @@ class Landing{
345
364
  head(){return git(this.root,['rev-parse','HEAD']);}
346
365
 
347
366
  fetchMain(){
348
- const fetched=tryGit(this.root,['fetch','--quiet','origin','+refs/heads/main:refs/remotes/origin/main']);
367
+ const fetched=tryGitLocked(this.root,['fetch','--quiet','origin','+refs/heads/main:refs/remotes/origin/main'],process.env,this.retry);
349
368
  if(fetched.status!==0)throw new StopError(`git fetch origin main failed: ${fetched.stderr.trim()}`);
350
369
  return git(this.root,['rev-parse','refs/remotes/origin/main']);
351
370
  }
@@ -449,7 +468,13 @@ class Landing{
449
468
  pushPlan(sha){
450
469
  const ref=`refs/heads/${this.branch}`,tracking=`refs/remotes/origin/${this.branch}`;
451
470
  if(git(this.root,['rev-parse',ref])!==sha)throw new StopError(`${this.branch} is not at ${short(sha)}; run land again`);
452
- if(tryGit(this.root,['fetch','--quiet','origin',`+${ref}:${tracking}`]).status!==0)tryGit(this.root,['update-ref','-d',tracking]);
471
+ const fetched=tryGitLocked(this.root,['fetch','--quiet','origin',`+${ref}:${tracking}`],process.env,this.retry);
472
+ if(fetched.status!==0){
473
+ // Only a branch origin lacks clears the tracking ref (a lease on "absent"); any other failure, the network or a
474
+ // lock still held after the retries, stops here instead of passing for someone else's push.
475
+ if(!/couldn't find remote ref/u.test(fetched.stderr))throw new StopError(`git fetch origin ${this.branch} failed: ${fetched.stderr.trim()}`);
476
+ tryGitLocked(this.root,['update-ref','-d',tracking],process.env,this.retry);
477
+ }
453
478
  const tip=tryGit(this.root,['rev-parse','--verify','--quiet',`${tracking}^{commit}`]).stdout.trim()||null;
454
479
  if(tip===sha){this.say('pushed',`${this.branch} already at ${short(sha)}`);this.planTip=sha;return;}
455
480
  const rewrite=tip!==null&&!isAncestor(this.root,tip,sha);
@@ -702,7 +727,8 @@ class Landing{
702
727
  let canonical='',outcome='';
703
728
  try{
704
729
  canonical=canonicalRoot(this.root);
705
- git(canonical,['fetch','--quiet','origin','main']);
730
+ const fetched=tryGitLocked(canonical,['fetch','--quiet','origin','main'],process.env,this.retry);
731
+ if(fetched.status!==0)throw new Error(`git fetch origin main failed: ${fetched.stderr.trim()}`);
706
732
  outcome=followMain(canonical,git(canonical,['rev-parse','origin/main']).trim());
707
733
  }catch(error){outcome=`could not check it (${error instanceof Error?error.message.split('\n')[0]:String(error)})`;}
708
734
  if(/fast-forwarded|current$/u.test(outcome)){this.say('canonical',outcome);return;}
@@ -756,7 +782,7 @@ class Landing{
756
782
  if(stopped.length>0)parts.push(`stopped ${String(stopped.length)} process(es) still running there (pid ${stopped.join(', ')})`);
757
783
  const removed=tryGit(canonical,['worktree','remove',this.root]);
758
784
  if(removed.status===0){
759
- tryGit(canonical,['update-ref','-d',`refs/heads/${this.branch}`,head]);
785
+ tryGitLocked(canonical,['update-ref','-d',`refs/heads/${this.branch}`,head],process.env,this.retry);
760
786
  parts.push(`worktree and ${this.branch} removed; continue from ${canonical}`);
761
787
  }else parts.push(`worktree kept (${removed.stderr.trim().split('\n').at(-1)??'git worktree remove refused'})`);
762
788
  }
@@ -1,173 +1,12 @@
1
1
  {
2
- "$schema": "./node_modules/oxlint/configuration_schema.json",
3
- "plugins": [
4
- "typescript",
5
- "unicorn",
6
- "oxc",
7
- "import",
8
- "promise",
9
- "node",
10
- "react",
11
- "react-perf",
12
- "jsx-a11y"
13
- ],
14
- // Strictest of greenroom (every category denied) and wildshard-singleplayer
15
- // (these options, and import/no-nodejs-modules outside Node-side folders).
16
- "options": {
17
- "typeAware": true,
18
- "denyWarnings": true,
19
- "reportUnusedDisableDirectives": "error"
20
- },
21
- "categories": {
22
- "correctness": "deny",
23
- "suspicious": "deny",
24
- "pedantic": "deny",
25
- "perf": "deny",
26
- "style": "deny",
27
- "restriction": "deny",
28
- "nursery": "deny"
29
- },
2
+ "$schema": "../node_modules/oxlint/configuration_schema.json",
3
+ "extends": ["../kit/.oxlintrc.json"],
4
+ // oxlint does not inherit ignorePatterns through extends (K11, J329).
30
5
  "ignorePatterns": [
31
- // Plain-JS repo scripts, outside the TS project; covered by
32
- // `pnpm test:hooks` instead. (.githooks/ sits outside src/.)
33
6
  "scripts/**",
34
7
  "dist/**",
35
- "node_modules/**",
8
+ "test/fixtures/**",
36
9
  "test-results/**",
37
- "playwright-report/**",
38
- "test/fixtures/**"
39
- ],
40
- "rules": {
41
- "typescript/explicit-function-return-type": [
42
- "deny",
43
- {
44
- "allowExpressions": false,
45
- "allowTypedFunctionExpressions": false,
46
- "allowHigherOrderFunctions": false,
47
- "allowDirectConstAssertionInArrowFunctions": false,
48
- "allowConciseArrowFunctionExpressionsStartingWithVoid": false,
49
- "allowFunctionsWithoutTypeParameters": false,
50
- "allowIIFEs": false
51
- }
52
- ],
53
- "typescript/explicit-module-boundary-types": [
54
- "deny",
55
- {
56
- "allowArgumentsExplicitlyTypedAsAny": false,
57
- "allowDirectConstAssertionInArrowFunctions": false,
58
- "allowHigherOrderFunctions": false,
59
- "allowTypedFunctionExpressions": false
60
- }
61
- ],
62
- "typescript/no-floating-promises": [
63
- "deny",
64
- {
65
- "allowForKnownSafeCalls": [
66
- {
67
- "from": "package",
68
- "package": "node:test",
69
- "name": ["describe", "it", "suite", "test"]
70
- }
71
- ]
72
- }
73
- ],
74
- "typescript/prefer-readonly-parameter-types": [
75
- "deny",
76
- {
77
- "treatMethodsAsReadonly": true,
78
- // Framework objects that are mutable by design and only ever passed in.
79
- "allow": [
80
- { "from": "package", "package": "hono", "name": "Context" },
81
- { "from": "package", "package": "node:test", "name": "TestContext" },
82
- {
83
- "from": "package",
84
- "package": "http",
85
- "name": ["IncomingMessage", "ServerResponse"]
86
- },
87
- {
88
- "from": "package",
89
- "package": "playwright",
90
- "name": [
91
- "PlaywrightTestArgs",
92
- "PlaywrightTestOptions",
93
- "PlaywrightWorkerArgs",
94
- "PlaywrightWorkerOptions"
95
- ]
96
- }
97
- ]
98
- }
99
- ],
100
- "eslint/func-style": [
101
- "deny",
102
- "declaration",
103
- { "allowArrowFunctions": true }
104
- ],
105
- "eslint/no-duplicate-imports": [
106
- "deny",
107
- { "allowSeparateTypeImports": true }
108
- ],
109
- // `return await` everywhere keeps stack traces and squares require-await with promise-function-async.
110
- "typescript/return-await": ["deny", "always"],
111
- // `void promise` is the marker no-floating-promises asks for.
112
- "eslint/no-void": ["deny", { "allowAsStatement": true }],
113
- // Continuation lines of a multi-line comment start mid-sentence.
114
- "eslint/capitalized-comments": [
115
- "deny",
116
- "always",
117
- { "ignoreConsecutiveComments": true }
118
- ],
119
- "react/jsx-filename-extension": ["deny", { "extensions": [".tsx"] }],
120
-
121
- // Disabled: each contradicts another rule or fights the stack.
122
- "eslint/sort-imports": "off", // oxfmt's sortImports owns import order; two sorters fight
123
- "eslint/sort-keys": "off", // key order carries meaning (schemas, options); not autofixable
124
- "eslint/one-var": "off", // one binding per declaration is how oxfmt lays code out
125
- "eslint/no-undef": "off", // tsc reports undefined names; this misreads type-only globals
126
- "eslint/no-undefined": "off", // contradicts unicorn/no-null; undefined is the absent value
127
- "eslint/no-ternary": "off", // JSX conditional rendering needs it; no-nested-ternary stays on
128
- "import/no-named-export": "off", // contradicts import/no-default-export; named exports win
129
- "import/prefer-default-export": "off", // contradicts import/no-default-export
130
- "import/no-relative-parent-imports": "off", // #subpath imports break the tsc build's extension rewrite
131
- "node/no-top-level-await": "off", // contradicts unicorn/prefer-top-level-await; ESM-only, never require()d
132
- "oxc/no-async-await": "off", // contradicts typescript/promise-function-async and require-await
133
- "oxc/no-optional-chaining": "off", // contradicts typescript/prefer-optional-chain
134
- "oxc/no-rest-spread-properties": "off", // ES5-compat ban; target is es2024
135
- "react/react-in-jsx-scope": "off", // contradicts the react-jsx automatic runtime
136
- "react/jsx-no-literals": "off" // i18n-only rule; no translations yet
137
- },
138
- "overrides": [
139
- {
140
- // Node programs may import node: modules; everything else (shared, client,
141
- // web code) may not, as in wildshard-singleplayer.
142
- "files": [
143
- "cli/**",
144
- "server/**",
145
- "tools/**",
146
- "test/**",
147
- "e2e/**",
148
- "cook/**",
149
- "**/*.test.ts",
150
- "*.config.ts",
151
- "**/*.config.ts"
152
- ],
153
- "rules": {
154
- "import/no-nodejs-modules": "off"
155
- }
156
- },
157
- {
158
- "files": ["*.config.ts", "**/*.config.ts"],
159
- "rules": {
160
- "import/no-default-export": "off", // playwright loads the default export
161
- "node/no-process-env": "off" // config reads CI from the environment
162
- }
163
- },
164
- {
165
- "files": ["**/*.test.ts", "test/**", "e2e/**"],
166
- "rules": {
167
- "eslint/no-magic-numbers": "off", // assertions compare against literal expected values
168
- "node/no-sync": "off", // test fixtures set up git repos synchronously
169
- "node/no-process-env": "off" // the git helper isolates git from the developer's env
170
- }
171
- }
10
+ "playwright-report/**"
172
11
  ]
173
12
  }
package/src/tsconfig.json CHANGED
@@ -1,30 +1,4 @@
1
1
  {
2
- "compilerOptions": {
3
- "target": "es2024",
4
- "strict": true,
5
- "noUncheckedIndexedAccess": true,
6
- "exactOptionalPropertyTypes": true,
7
- "noImplicitOverride": true,
8
- "noImplicitReturns": true,
9
- "noFallthroughCasesInSwitch": true,
10
- "noPropertyAccessFromIndexSignature": true,
11
- "noUnusedLocals": true,
12
- "noUnusedParameters": true,
13
- "allowUnreachableCode": false,
14
- "allowUnusedLabels": false,
15
- "useUnknownInCatchVariables": true,
16
- "verbatimModuleSyntax": true,
17
- "erasableSyntaxOnly": true,
18
- "isolatedModules": true,
19
- "allowImportingTsExtensions": true,
20
- "resolveJsonModule": true,
21
- "forceConsistentCasingInFileNames": true,
22
- "skipLibCheck": true,
23
- "module": "nodenext",
24
- "moduleResolution": "nodenext",
25
- "lib": ["es2024", "webworker"],
26
- "types": ["node"],
27
- "noEmit": true
28
- },
2
+ "extends": "../kit/tsconfig.json",
29
3
  "include": ["ci", "cli", "test", "server", "shared", "tools", "e2e"]
30
4
  }
package/src/.oxfmtrc.json DELETED
@@ -1,50 +0,0 @@
1
- {
2
- "$schema": "./node_modules/oxfmt/configuration_schema.json",
3
- "printWidth": 80,
4
- "tabWidth": 2,
5
- "useTabs": false,
6
- "semi": false,
7
- "singleQuote": true,
8
- "jsxSingleQuote": true,
9
- "trailingComma": "all",
10
- "arrowParens": "avoid",
11
- "endOfLine": "lf",
12
- "insertFinalNewline": true,
13
- "bracketSpacing": true,
14
- "sortPackageJson": false,
15
- "sortImports": {
16
- "groups": [
17
- "builtin",
18
- "external",
19
- "internal",
20
- ["parent", "sibling", "index"],
21
- [
22
- "type-external",
23
- "type-internal",
24
- "type-parent",
25
- "type-sibling",
26
- "type-index"
27
- ]
28
- ],
29
- "newlinesBetween": true
30
- },
31
- "ignorePatterns": [
32
- // Plain-JS repo scripts, outside the TS project; covered by
33
- // `pnpm test:hooks` instead. (.githooks/ sits outside src/.)
34
- "scripts/**",
35
- "dist/**",
36
- "node_modules/**",
37
- "test-results/**",
38
- "playwright-report/**",
39
- "pnpm-lock.yaml",
40
- // A real built product: its JSON is canonical, byte for byte.
41
- "test/fixtures/**",
42
- "**/*.md"
43
- ],
44
- "overrides": [
45
- {
46
- "files": ["*.json", "*.jsonc"],
47
- "options": { "trailingComma": "none" }
48
- }
49
- ]
50
- }
@@ -1,29 +0,0 @@
1
- #!/usr/bin/env bash
2
- # ask-new.sh — claim the next ask id and create docs/tasks/asks/<ID>.md
3
- # (one file per request for work from Jake; rules in
4
- # docs/tasks/asks/README.md). Ported from project-wildshard-singleplayer.
5
- #
6
- # src/scripts/ask-new.sh "<Jake's words>" [series letter, default A]
7
- #
8
- # The file IS the claim: it is created with noclobber (O_EXCL), so two
9
- # agents asking at the same moment get two different ids. Prints the new
10
- # file's path. Fill in the rest with Edit, then commit it by pathspec.
11
- set -uo pipefail
12
- cd "$(git rev-parse --show-toplevel)" || exit 1
13
- ask="${1:?usage: src/scripts/ask-new.sh \"<the request, in Jake words>\" [series letter]}"
14
- series="${2:-A}"
15
- dir=docs/tasks/asks
16
- mkdir -p "$dir"
17
- max="$(ls "$dir" 2>/dev/null | grep -oE "^${series}[0-9]+\.md$" | grep -oE '[0-9]+' | sort -n | tail -1)"
18
- n=$(( ${max:-0} + 1 ))
19
- set -o noclobber
20
- for _ in $(seq 1 50); do
21
- f="$dir/${series}${n}.md"
22
- if { printf '# %s%s\n\n**Status:** open (%s)\n**Ask:** %s\n' "$series" "$n" "$(date +%F)" "$ask" > "$f"; } 2>/dev/null; then
23
- echo "$f"
24
- exit 0
25
- fi
26
- n=$(( n + 1 ))
27
- done
28
- echo "ask-new: could not claim an id in series $series" >&2
29
- exit 1
@@ -1,141 +0,0 @@
1
- // asks.mjs — the ask rules (docs/tasks/asks/README.md), one parser for
2
- // the session brief and the pre-commit hook. Ported from
3
- // project-wildshard-singleplayer's scripts/asks.mjs.
4
- //
5
- // node src/scripts/asks.mjs brief asks still open: expired claims, picks for Jake
6
- // node src/scripts/asks.mjs check pre-commit: every staged ask file follows the rules
7
- //
8
- // An ask is a receipt of Jake's words. Follow-up work is a plan row.
9
- import { spawnSync } from 'node:child_process'
10
- import { existsSync, readdirSync, readFileSync } from 'node:fs'
11
- import { basename, resolve } from 'node:path'
12
- import { pathToFileURL } from 'node:url'
13
-
14
- const ROOT = resolve(import.meta.dirname, '..', '..')
15
- const ASKS = 'docs/tasks/asks'
16
- const PLANS = 'docs/plans'
17
- const LEASE_HOURS = 71 // a claim with no commit touching it for 71 h has expired
18
-
19
- /** The Status vocabulary. `folded into` / `superseded by` name the ask or plan that carries the work. */
20
- export const STATES = ['open', 'in flight', 'needs pick', 'done', 'dropped', 'folded into', 'superseded by']
21
- const CLOSED = new Set(['done', 'dropped', 'folded into', 'superseded by'])
22
-
23
- /** @param {string[]} args */
24
- const git = (...args) => {
25
- const r = spawnSync('git', args, { cwd: ROOT, encoding: 'utf8', maxBuffer: 64 * 1024 * 1024 })
26
- return r.status === 0 ? r.stdout : ''
27
- }
28
-
29
- /** @param {string} text */
30
- export function parseAsk(text) {
31
- const status = /^\*\*Status:\*\* *(.*)$/mu.exec(text)?.[1]?.trim() ?? ''
32
- const lower = status.toLowerCase()
33
- const state = STATES.find(s => lower.startsWith(s)) ?? null
34
- const date = /(\d{4}-\d{2}-\d{2})/u.exec(status)?.[1] ?? null
35
- const target =
36
- state === 'folded into' || state === 'superseded by'
37
- ? (/^(?:folded into|superseded by) +([A-Za-z][A-Za-z0-9_-]*)/iu.exec(status)?.[1] ?? null)
38
- : null
39
- return {
40
- title: /^# (\S+)/u.exec(text)?.[1] ?? null,
41
- status,
42
- state,
43
- closed: state !== null && CLOSED.has(state),
44
- date,
45
- target,
46
- ask: /^\*\*Ask:\*\* *(.*)$/mu.exec(text)?.[1]?.trim() ?? '',
47
- }
48
- }
49
-
50
- /** A target exists: an ask, a live plan, or a plan archived as project/archive/<date>-<name>.md. */
51
- /** @param {string} target */
52
- export function targetExists(target, root = ROOT) {
53
- if (existsSync(resolve(root, ASKS, `${target}.md`))) return true
54
- if (existsSync(resolve(root, PLANS, `${target}.md`))) return true
55
- const archive = resolve(root, 'project/archive')
56
- if (!existsSync(archive)) return false
57
- const name = target.toLowerCase()
58
- return readdirSync(archive).some(f => f.toLowerCase().endsWith(`-${name}.md`) || f.toLowerCase() === `${name}.md`)
59
- }
60
-
61
- /**
62
- * Every rule an ask file must pass.
63
- * @param {string} id
64
- * @param {string} text
65
- * @returns {string[]} problems; empty when it passes
66
- */
67
- export function checkAsk(id, text, exists = targetExists) {
68
- const a = parseAsk(text)
69
- const out = []
70
- if (a.title !== id) out.push(`first line must be "# ${id}" (create asks with src/scripts/ask-new.sh)`)
71
- if (!a.status) out.push('no **Status:** line')
72
- if (!a.ask) out.push("no **Ask:** line (Jake's words)")
73
- if (a.status && a.state === null) {
74
- out.push(`Status "${a.status.slice(0, 40)}" is not one of: ${STATES.join(' / ')}`)
75
- }
76
- if (a.state === 'in flight' && !/^in flight \(\d{4}-\d{2}-\d{2}, *[^)]+\)/u.test(a.status)) {
77
- out.push('in flight needs its claim: "in flight (YYYY-MM-DD, <owner>)"')
78
- }
79
- if ((a.state === 'open' || a.state === 'needs pick' || a.state === 'done') && !a.date) {
80
- out.push(`${a.state} needs its date: "${a.state} (YYYY-MM-DD)"`)
81
- }
82
- if ((a.state === 'folded into' || a.state === 'superseded by') && (a.target === null || !exists(a.target))) {
83
- out.push(`"${a.state}" must name an existing ask (A12) or plan (a-plan-slug)`)
84
- }
85
- return out
86
- }
87
-
88
- function check() {
89
- const staged = git('diff', '--cached', '--name-only', '--diff-filter=AM', '-z')
90
- .split('\0')
91
- .filter(p => p.startsWith(`${ASKS}/`) && p.endsWith('.md') && !p.endsWith('/README.md'))
92
- let bad = 0
93
- for (const p of staged) {
94
- const problems = checkAsk(basename(p, '.md'), git('show', `:${p}`))
95
- for (const m of problems) console.error(` ${p}: ${m}`)
96
- bad += problems.length
97
- }
98
- if (bad > 0) {
99
- console.error('\n X commit blocked: ask file breaks the rules in docs/tasks/asks/README.md.\n')
100
- process.exitCode = 1
101
- }
102
- }
103
-
104
- /** @param {string} from */
105
- const days = (from, to = Date.now()) => (to - Date.parse(`${from}T00:00:00Z`)) / 86_400_000
106
-
107
- function brief() {
108
- const dir = resolve(ROOT, ASKS)
109
- const files = existsSync(dir) ? readdirSync(dir).filter(n => /^[A-Z]+\d+\.md$/u.test(n)) : []
110
- const now = Date.now()
111
- const rows = []
112
- for (const f of files.sort((x, y) => x.localeCompare(y, 'en', { numeric: true }))) {
113
- const a = parseAsk(readFileSync(resolve(dir, f), 'utf8'))
114
- if (a.closed) continue
115
- let flag = ''
116
- if (a.state === 'in flight') {
117
- const committed = Number(git('log', '-1', '--format=%ct', '--', `${ASKS}/${f}`).trim()) * 1000
118
- const last = Math.max(a.date ? Date.parse(`${a.date}T23:59:59Z`) : 0, committed)
119
- if ((now - last) / 3_600_000 > LEASE_HOURS) {
120
- flag = ` !! CLAIM EXPIRED (no commit in ${LEASE_HOURS} h): anyone may take it`
121
- }
122
- }
123
- if (a.state === 'needs pick') {
124
- const open = a.date ? ` (open ${Math.floor(days(a.date, now))} d)` : ''
125
- flag = ` !! ASK JAKE with the question tool${open}: a pick never expires`
126
- }
127
- if (a.state === null) flag = ' !! Status outside the vocabulary (docs/tasks/asks/README.md)'
128
- rows.push(` ${basename(f, '.md')} | ${a.status.slice(0, 80)}${flag} | ${a.ask.slice(0, 100)}`)
129
- }
130
- console.log(rows.length > 0 ? rows.join('\n') : ' (none)')
131
- }
132
-
133
- if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) {
134
- const [mode] = process.argv.slice(2)
135
- if (mode === 'check') check()
136
- else if (mode === 'brief') brief()
137
- else {
138
- console.error('usage: node src/scripts/asks.mjs brief | check')
139
- process.exitCode = 2
140
- }
141
- }
@@ -1,34 +0,0 @@
1
- #!/usr/bin/env bash
2
- # herdr-prompt.sh: a herdr write, sent only when its target is clear.
3
- #
4
- # herdr-prompt.sh <agent> <message> [options] herdr agent prompt
5
- # herdr-prompt.sh agent prompt|send-keys <target> ...
6
- # herdr-prompt.sh pane send-text|send-keys|run <pane> ...
7
- #
8
- # It asks herdr-question-open.sh (beside it) first and writes only on its
9
- # "clear" answer. A blocked or unavailable target, an unresolved one, or
10
- # a missing or non-executable helper refuses with exit 3, so the message
11
- # never answers Jake's question. Codex lanes call this; Claude lanes get
12
- # the same check from the PreToolUse guard guard-herdr-prompt.sh, which
13
- # asks the same helper. Exit 2 is usage.
14
- set -uo pipefail
15
-
16
- usage() { echo "usage: herdr-prompt.sh <agent> <message> | agent prompt|send-keys <target> ... | pane send-text|send-keys|run <pane> ..." >&2; exit 2; }
17
- case "${1:-} ${2:-}" in
18
- "agent prompt" | "agent send-keys" | "pane send-text" | "pane send-keys" | "pane run")
19
- group="$1" verb="$2"; shift 2 ;;
20
- *) group=agent verb=prompt ;;
21
- esac
22
- target="${1:-}"
23
- [ -n "$target" ] && [ $# -ge 2 ] || usage
24
- shift
25
-
26
- check="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/herdr-question-open.sh"
27
- refuse() { echo "herdr-prompt: not sent: $1. Put it in STATE.md or a commit message instead, or retry later." >&2; exit 3; }
28
- [ -f "$check" ] && [ -x "$check" ] || refuse "$check is missing or not executable, so $target cannot be checked"
29
- why="$("$check" "$target" 2>&1)" && rc=0 || rc=$?
30
- case "$rc:$why" in
31
- 1:clear*) ;;
32
- *) refuse "${why:-herdr-question-open.sh exited $rc}" ;;
33
- esac
34
- exec herdr "$group" "$verb" "$target" "$@"
@@ -1,67 +0,0 @@
1
- #!/usr/bin/env bash
2
- # herdr-question-open.sh <agent|pane>: may a herdr write go to that target now?
3
- #
4
- # A herdr paste into a pane that has a question open (Claude's
5
- # AskUserQuestion, a Codex question, an approval prompt) lands in the
6
- # answer field and picks for Jake (Jake, 2026-10-12, G232/G233). Read
7
- # before write: the PreToolUse guard (guard-herdr-prompt.sh) and the
8
- # wrapper (herdr-prompt.sh) both ask this script before any herdr
9
- # write, so both refuse the same targets.
10
- #
11
- # It prints one line and exits:
12
- # 1 "clear: ..." the target resolves, its status and screen
13
- # were read, and no question is open. Exit 1
14
- # with "clear" is the only answer that permits
15
- # a write.
16
- # 0 "blocked: ..." a question or approval prompt is open.
17
- # 3 "unavailable: ..." the target does not resolve to an agent or
18
- # pane, or herdr, jq, its status or its screen
19
- # could not be read. Not knowing is not clear.
20
- # 2 usage.
21
- # Exit 0 keeps the old "a question is open" meaning for `if` callers.
22
- set -uo pipefail
23
-
24
- target="${1:-}"
25
- [ -n "$target" ] && [ $# -eq 1 ] || { echo "usage: herdr-question-open.sh <agent|pane>" >&2; exit 2; }
26
-
27
- say() { printf '%s\n' "$2"; exit "$1"; }
28
- unavailable() { say 3 "unavailable: $target $1"; }
29
-
30
- command -v herdr >/dev/null 2>&1 || unavailable "cannot be inspected: herdr is not on PATH"
31
- command -v jq >/dev/null 2>&1 || unavailable "cannot be inspected: jq is not on PATH"
32
-
33
- # Resolve: an agent name or pane id through `agent get`, then a plain
34
- # pane through `pane get`. Only *_not_found from both means unresolved.
35
- info="" codes=""
36
- for kind in agent pane; do
37
- out="$(herdr "$kind" get "$target" 2>/dev/null)" && rc=0 || rc=$?
38
- if [ "$rc" -eq 0 ]; then
39
- info="$(printf '%s' "$out" | jq -ce ".result.$kind | objects" 2>/dev/null)" || info=""
40
- [ -n "$info" ] && break
41
- unavailable "could not be read: herdr $kind get gave no $kind status"
42
- else
43
- # herdr prints its error JSON on stderr; read it again with both streams.
44
- code="$(herdr "$kind" get "$target" 2>&1 | jq -r '.error.code // empty' 2>/dev/null | head -n 1)"
45
- codes="$codes $kind:${code:-exit-$rc}"
46
- fi
47
- done
48
- if [ -z "$info" ]; then
49
- case "$codes" in
50
- " agent:agent_not_found pane:pane_not_found") unavailable "does not resolve to a herdr agent or pane" ;;
51
- *) unavailable "could not be read (herdr:$codes)" ;;
52
- esac
53
- fi
54
-
55
- pane="$(printf '%s' "$info" | jq -r '.pane_id // empty')"
56
- [ -n "$pane" ] || unavailable "resolved without a pane id"
57
- # A pane running an agent must report its status; a plain shell pane has none.
58
- has_agent="$(printf '%s' "$info" | jq -r 'if (.agent // null) == null then "no" else "yes" end')"
59
- status="$(printf '%s' "$info" | jq -r '.agent_status // empty')"
60
- [ "$has_agent" = no ] || [ -n "$status" ] || unavailable "($pane) has an agent but no readable status"
61
- [ "$status" = blocked ] && say 0 "blocked: $target ($pane) is blocked (herdr sees a question or approval prompt open)"
62
-
63
- screen="$(herdr pane read "$pane" --source visible 2>/dev/null)" || unavailable "($pane): its screen could not be read"
64
- if printf '%s' "$screen" | grep -qE 'Enter to select|to navigate|Skip for now|Type something\.|\? [0-9]+ questions?|Do you want to proceed\?'; then
65
- say 0 "blocked: $target ($pane) is showing a question on screen"
66
- fi
67
- say 1 "clear: $target ($pane) is ${status:-a plain pane} with no question on screen"
@@ -1,229 +0,0 @@
1
- // md-wrap.mjs — markdown prose wraps at 72 characters (Jake's norm;
2
- // ported from kami-kakushi's md-wrap, written fresh for greenroom).
3
- //
4
- // node src/scripts/md-wrap.mjs <file...> reflow long prose in place
5
- // node src/scripts/md-wrap.mjs --check [--new-only] <file...> list long prose lines (exit 1)
6
- //
7
- // --new-only reports only lines added vs HEAD (an untracked file counts
8
- // whole), so touching one line of an old doc doesn't flag its history.
9
- // Exempt everywhere: front matter, code fences, tables, headings, HTML,
10
- // block quotes, and lines whose overflow can't be broken (one long token
11
- // such as a URL, or an `inline code` span, which is never split). Reflow rewraps only paragraphs and list items that
12
- // hold a long line, keeping list markers and indentation.
13
- import { spawnSync } from 'node:child_process'
14
- import { existsSync, readFileSync, writeFileSync } from 'node:fs'
15
- import { pathToFileURL } from 'node:url'
16
- import { resolve } from 'node:path'
17
-
18
- export const WIDTH = 72
19
- const segmenter = new Intl.Segmenter('en', { granularity: 'grapheme' })
20
- /** @param {string} text */
21
- export const width = text => Array.from(segmenter.segment(text)).length
22
-
23
- const FENCE = /^\s*(```|~~~)/u
24
- const ITEM = /^(\s*)([-*+]|\d+[.)])(\s+)(\[[ xX]\]\s+)?/u
25
-
26
- /**
27
- * Classify every line: 'prose' lines may wrap; everything else is left alone.
28
- * @param {string[]} lines
29
- * @returns {('prose' | 'item' | 'skip' | 'blank')[]}
30
- */
31
- export function classify(lines) {
32
- const kinds = []
33
- let fence = false
34
- let front = lines[0] === '---'
35
- for (const [i, line] of lines.entries()) {
36
- if (front) {
37
- kinds.push('skip')
38
- if (i > 0 && line === '---') front = false
39
- continue
40
- }
41
- if (FENCE.test(line)) {
42
- fence = !fence
43
- kinds.push('skip')
44
- continue
45
- }
46
- const trimmed = line.trim()
47
- if (fence) kinds.push('skip')
48
- else if (trimmed === '') kinds.push('blank')
49
- else if (/^(#|\||<|>|---+$|\*\*\*+$|\[[^\]]+\]:)/u.test(trimmed)) kinds.push('skip')
50
- else if (/^ {4,}\S/u.test(line) && kinds.at(-1) === 'blank' && !isInsideList(kinds, lines)) kinds.push('skip')
51
- else if (ITEM.test(line)) kinds.push('item')
52
- else kinds.push('prose')
53
- }
54
- return kinds
55
- }
56
-
57
- /** An indented block right after a blank line is code unless we are inside a list. */
58
- function isInsideList(kinds, lines) {
59
- for (let i = kinds.length - 1; i >= 0; i--) {
60
- if (kinds[i] === 'item') return true
61
- if (kinds[i] === 'blank' || /^\s/u.test(lines[i])) continue
62
- return false
63
- }
64
- return false
65
- }
66
-
67
- /** The text a line starts with that must stay put (indent, list marker, checkbox). */
68
- function prefixOf(line) {
69
- const item = ITEM.exec(line)
70
- if (item) return item[0]
71
- return /^\s*/u.exec(line)?.[0] ?? ''
72
- }
73
-
74
- /**
75
- * Split prose into words on spaces, keeping each `inline code` span whole
76
- * (a command split across lines can't be copied).
77
- * @param {string} body
78
- */
79
- export function tokens(body) {
80
- const out = []
81
- let current = ''
82
- let code = false
83
- for (const char of body) {
84
- if (char === '`') code = !code
85
- if (char === ' ' && !code) {
86
- if (current) out.push(current)
87
- current = ''
88
- } else {
89
- current += char
90
- }
91
- }
92
- if (current) out.push(current)
93
- return out
94
- }
95
-
96
- /** A long line can be wrapped only if its first word (after the prefix) fits and another follows. */
97
- export function breakable(line) {
98
- const prefix = prefixOf(line)
99
- const words = tokens(line.slice(prefix.length))
100
- return words.length > 1 && width(prefix) + width(words[0]) <= WIDTH
101
- }
102
-
103
- /**
104
- * Long prose lines, 1-based.
105
- * @param {string} text
106
- * @param {Set<number> | null} only line numbers to report (null = all)
107
- */
108
- export function findLong(text, only = null) {
109
- const lines = text.split('\n')
110
- const kinds = classify(lines)
111
- const found = []
112
- for (const [i, line] of lines.entries()) {
113
- if (only && !only.has(i + 1)) continue
114
- if ((kinds[i] === 'prose' || kinds[i] === 'item') && width(line) > WIDTH && breakable(line)) {
115
- found.push({ line: i + 1, width: width(line) })
116
- }
117
- }
118
- return found
119
- }
120
-
121
- /** Greedy wrap of words under a first-line prefix and a continuation indent. */
122
- function wrap(words, first, rest) {
123
- const out = []
124
- let current = first
125
- let empty = true
126
- for (const word of words) {
127
- const candidate = empty ? current + word : `${current} ${word}`
128
- if (!empty && width(candidate) > WIDTH) {
129
- out.push(current)
130
- current = rest + word
131
- } else {
132
- current = candidate
133
- }
134
- empty = false
135
- }
136
- out.push(current)
137
- return out
138
- }
139
-
140
- /** Rewrap paragraphs and list items that contain a long, breakable line. */
141
- export function reflow(text) {
142
- const lines = text.split('\n')
143
- const kinds = classify(lines)
144
- const out = []
145
- let i = 0
146
- while (i < lines.length) {
147
- if (kinds[i] !== 'prose' && kinds[i] !== 'item') {
148
- out.push(lines[i])
149
- i += 1
150
- continue
151
- }
152
- // A block: this line plus continuation prose lines (not a new item,
153
- // not after a hard break). Items continue only with indented lines.
154
- const start = i
155
- const first = prefixOf(lines[i])
156
- const indent = kinds[i] === 'item' ? ' '.repeat(width(first)) : first
157
- let end = i + 1
158
- while (
159
- end < lines.length &&
160
- kinds[end] === 'prose' &&
161
- !/( {2}|\\)$/u.test(lines[end - 1]) &&
162
- (kinds[start] !== 'item' || /^\s/u.test(lines[end]))
163
- ) {
164
- end += 1
165
- }
166
- const block = lines.slice(start, end)
167
- const needs = block.some(line => width(line) > WIDTH && breakable(line))
168
- if (!needs) {
169
- out.push(...block)
170
- } else {
171
- const hardBreak = /( {2}|\\)$/u.exec(block.at(-1))?.[0] ?? ''
172
- const joined = block
173
- .map((line, n) => (n === 0 ? line.slice(first.length) : line.trim()))
174
- .join(' ')
175
- .trim()
176
- const words = tokens(joined)
177
- const wrapped = wrap(words, first, indent)
178
- if (hardBreak) wrapped[wrapped.length - 1] += hardBreak
179
- out.push(...wrapped)
180
- }
181
- i = end
182
- }
183
- return out.join('\n')
184
- }
185
-
186
- /** Line numbers added vs HEAD; null = the whole file is new. */
187
- function addedLines(file) {
188
- const tracked = spawnSync('git', ['ls-files', '--error-unmatch', '--', file], { encoding: 'utf8' })
189
- if (tracked.status !== 0) return null
190
- const diff = spawnSync('git', ['diff', '-U0', 'HEAD', '--', file], { encoding: 'utf8' }).stdout ?? ''
191
- const added = new Set()
192
- for (const match of diff.matchAll(/^@@ -\S+ \+(\d+)(?:,(\d+))? @@/gmu)) {
193
- const from = Number(match[1])
194
- const count = match[2] === undefined ? 1 : Number(match[2])
195
- for (let n = from; n < from + count; n++) added.add(n)
196
- }
197
- return added
198
- }
199
-
200
- function main(argv) {
201
- const check = argv.includes('--check')
202
- const newOnly = argv.includes('--new-only')
203
- const files = argv.filter(arg => !arg.startsWith('--'))
204
- if (!files.length) {
205
- console.error('usage: node src/scripts/md-wrap.mjs [--check [--new-only]] <file.md...>')
206
- return 2
207
- }
208
- let status = 0
209
- for (const file of files) {
210
- if (!existsSync(file)) continue
211
- const text = readFileSync(file, 'utf8')
212
- if (check) {
213
- const long = findLong(text, newOnly ? addedLines(file) : null)
214
- for (const { line, width: w } of long) console.log(` ${file}:${line}: ${w} chars (> ${WIDTH})`)
215
- if (long.length) status = 1
216
- } else {
217
- const next = reflow(text)
218
- if (next !== text) {
219
- writeFileSync(file, next)
220
- console.log(`rewrapped ${file}`)
221
- }
222
- }
223
- }
224
- return status
225
- }
226
-
227
- if (process.argv[1] && import.meta.url === pathToFileURL(resolve(process.argv[1])).href) {
228
- process.exitCode = main(process.argv.slice(2))
229
- }